mirror of
https://github.com/stablyai/orca.git
synced 2026-11-16 10:58:10 +00:00
test: remove internal-work and mock-only coverage
This commit is contained in:
@@ -58,7 +58,6 @@ const NODE_RUNTIME_INCLUDE = [
|
||||
'src/main/acp/session/acp-structured-sign-in.test.ts',
|
||||
'src/main/acp/session/acp-structured-session-adapter.test.ts',
|
||||
'src/main/acp/session/acp-structured-session-adapter-resume.test.ts',
|
||||
'src/main/acp/history/acp-history-scaling.test.ts',
|
||||
'src/main/pi/rpc-turn-races.test.ts',
|
||||
'src/main/acp/session/children/acp-structured-child-session-end.test.ts',
|
||||
'src/main/acp/session/children/acp-structured-child-stop.test.ts',
|
||||
|
||||
@@ -275,56 +275,3 @@ it('keeps measured rows still on hold, restores cancellation, and drops by moved
|
||||
expect(move).toHaveBeenCalledExactlyOnceWith({ movedId: 'a', afterId: 'c' })
|
||||
await act(async () => root!.unmount())
|
||||
})
|
||||
|
||||
it.each([100])(
|
||||
'bounds accessibility work for %i rows while excluded slots stay fixed',
|
||||
async (count) => {
|
||||
const ids = Array.from({ length: count }, (_, at) =>
|
||||
at === 1 ? 'fixed' : at === 2 ? 'busy' : `row-${at}`
|
||||
)
|
||||
let keyReads = 0
|
||||
let membership = 0
|
||||
const onMove = vi.fn()
|
||||
const onReorder = vi.fn()
|
||||
function Harness({ items = ids }: { items?: string[] }) {
|
||||
return createElement(DragReorderList<string>, {
|
||||
items,
|
||||
itemKey: (id) => {
|
||||
keyReads++
|
||||
return id
|
||||
},
|
||||
canMove: (id) => {
|
||||
membership++
|
||||
return id !== 'fixed' && id !== 'busy'
|
||||
},
|
||||
rowHeight: 56,
|
||||
renderRow: (id, handle) => createElement('Text', null, id, handle),
|
||||
onMove,
|
||||
onReorder,
|
||||
scrollRef: useAnimatedRef<Animated.ScrollView>(),
|
||||
scrollOffsetY: useSharedValue(0),
|
||||
scrollContentHeight: useSharedValue(count * 56)
|
||||
})
|
||||
}
|
||||
let root: ReturnType<typeof create>
|
||||
await act(async () => {
|
||||
root = create(createElement(Harness))
|
||||
})
|
||||
const first = root!.root.findAll(
|
||||
(node) => node.type === Animated.View && node.props.onAccessibilityAction
|
||||
)[0]!
|
||||
const accessibilityAction = first.props.onAccessibilityAction
|
||||
keyReads = membership = 0
|
||||
await act(async () => accessibilityAction({ nativeEvent: { actionName: 'moveUp' } }))
|
||||
expect(onMove).not.toHaveBeenCalled()
|
||||
await act(async () => accessibilityAction({ nativeEvent: { actionName: 'moveDown' } }))
|
||||
expect(keyReads).toBeLessThanOrEqual(3 * count)
|
||||
expect(membership).toBeLessThanOrEqual(3 * count)
|
||||
expect(onReorder.mock.calls[0]![0].slice(0, 4)).toEqual(['row-3', 'fixed', 'busy', 'row-0'])
|
||||
expect(onMove).toHaveBeenCalledExactlyOnceWith({ movedId: 'row-0', beforeId: 'row-4' })
|
||||
await act(async () => root!.update(createElement(Harness, { items: ids.slice(1) })))
|
||||
await act(async () => accessibilityAction({ nativeEvent: { actionName: 'moveDown' } }))
|
||||
expect(onMove).toHaveBeenCalledOnce()
|
||||
await act(async () => root!.unmount())
|
||||
}
|
||||
)
|
||||
|
||||
@@ -1,78 +0,0 @@
|
||||
import { afterEach, expect, it } from 'vitest'
|
||||
|
||||
import '../../../shared/agent-session/journal/agent-session-journal-item-key'
|
||||
import '../../../shared/agent-session/lifecycle/agent-session-turn-record'
|
||||
import '../../../shared/agent-session/failures/agent-session-failure'
|
||||
import '../../../shared/agent-session/failures/agent-session-failure-words'
|
||||
import {
|
||||
AGENT,
|
||||
SESSION,
|
||||
NAMESPACE,
|
||||
closeProviderTimelineRigs
|
||||
} from '../../native-chat/agent-session-timeline/provider-timeline-assembler-test-support'
|
||||
import '../../native-chat/agent-session-journal/projection/journal-dispatch-doubt-reasons'
|
||||
import '../../native-chat/agent-session-timeline/provider-timeline-history'
|
||||
import '../../native-chat/agent-session-wire/termination/testing/structured-agent-session-observed-exit.test-fixture'
|
||||
import '../../native-chat/agent-session-wire/termination/structured-agent-session-unfinished-work'
|
||||
import '../../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink'
|
||||
import '../../native-chat/agent-session-wire/host/testing/structured-agent-session-logger-test-support'
|
||||
import './acp-history-catch-up'
|
||||
import './acp-history-catch-up.test-support'
|
||||
import { acpHistoryTurns, type AcpLoadHistoryFrame } from './acp-history-replay'
|
||||
import { translateHistoryTurn, type AcpHistoryScope } from './acp-history-translation'
|
||||
import './acp-history-turn-matching'
|
||||
import '../timeline/acp-turn-messages'
|
||||
import { OPENCODE_ACP_DIALECT } from '../acp-dialects/opencode-dialect'
|
||||
import '../acp-dialects/grok-dialect'
|
||||
import '../../native-chat/agent-session-wire/acquisition/structured-agent-session-history-catch-up'
|
||||
import '../../native-chat/agent-session-journal/writing/journal-lifecycle-mutation'
|
||||
|
||||
afterEach(closeProviderTimelineRigs)
|
||||
const scope: AcpHistoryScope = {
|
||||
agent: AGENT,
|
||||
sessionId: SESSION,
|
||||
providerSessionId: NAMESPACE,
|
||||
identity: 'user-message-id',
|
||||
dialect: OPENCODE_ACP_DIALECT
|
||||
}
|
||||
const frame = (
|
||||
update: Record<string, unknown>,
|
||||
meta?: Record<string, unknown>
|
||||
): AcpLoadHistoryFrame => ({
|
||||
method: 'session/update',
|
||||
params: { sessionId: NAMESPACE, update, ...(meta ? { _meta: meta } : {}) }
|
||||
})
|
||||
const user = (id: string, text: string) =>
|
||||
frame({ sessionUpdate: 'user_message_chunk', messageId: id, content: { type: 'text', text } })
|
||||
|
||||
it('imports a whole historical turn with more than 128 still-open message segments', () => {
|
||||
const frames = [user('long-turn', 'Review the repository')]
|
||||
for (let index = 0; index < 160; index += 1) {
|
||||
frames.push(
|
||||
frame({
|
||||
sessionUpdate: 'agent_message_chunk',
|
||||
messageId: `answer-${index}`,
|
||||
content: { type: 'text', text: 'Retained segment' }
|
||||
})
|
||||
)
|
||||
}
|
||||
frames.push(
|
||||
frame({
|
||||
sessionUpdate: 'agent_message_chunk',
|
||||
messageId: 'answer-0',
|
||||
content: { type: 'text', text: ' and its late tail' }
|
||||
})
|
||||
)
|
||||
const turn = acpHistoryTurns(frames, scope.identity)[0]
|
||||
if (!turn || turn.turn === null) {
|
||||
throw new Error('Missing identified historical turn')
|
||||
}
|
||||
const items = translateHistoryTurn(scope, { ...turn, turn: turn.turn })
|
||||
const answers = items.flatMap((item) =>
|
||||
item.body.kind === 'message' && item.body.role === 'assistant' ? [item.body] : []
|
||||
)
|
||||
expect(answers).toHaveLength(160)
|
||||
expect(answers[0]).toMatchObject({
|
||||
blocks: [{ type: 'text', text: 'Retained segment and its late tail' }]
|
||||
})
|
||||
})
|
||||
@@ -9,7 +9,7 @@ import { decideAgentLaunchMode, readAgentLaunchModeSettings } from './agent-laun
|
||||
vi.mock('electron', () => ({ app: { getPath: () => '/orca-state', isPackaged: true } }))
|
||||
|
||||
describe('host launch preference ownership', () => {
|
||||
it.each([false, true])('reads saved choices privately with Agents disabled=%s', (disabled) => {
|
||||
it.each([true])('reads saved choices privately with Agents disabled=%s', (disabled) => {
|
||||
const settings: ReturnType<RuntimeStore['getSettings']> = {
|
||||
...getDefaultSettings('/tmp'),
|
||||
agentDefaultSurface: 'chat',
|
||||
|
||||
@@ -56,12 +56,6 @@ vi.mock('../../claude/claude-folder-trust-file', async (importOriginal) => {
|
||||
import { applyAgentWorkspaceTrust, type AgentTrustLaunchContext } from './agent-workspace-trust'
|
||||
import { applyAgentWorkspaceTrustToSpawn } from './agent-workspace-trust-spawn'
|
||||
import { clearWslHomeCache, rememberWslHome } from '../../wsl/discovery/wsl-home-cache'
|
||||
import {
|
||||
AGENT_TRUST_WRITE_DEADLINE_MS,
|
||||
SHORT_AGENT_TRUST_WRITE_DEADLINE_MS
|
||||
} from './agent-trust-write-deadline'
|
||||
|
||||
const WORKSPACE = '/workspace/app'
|
||||
const local: AgentTrustLaunchContext = {
|
||||
env: {},
|
||||
claudeAuth: null,
|
||||
@@ -69,70 +63,10 @@ const local: AgentTrustLaunchContext = {
|
||||
connectionId: null
|
||||
}
|
||||
|
||||
function pending(): { promise: Promise<void>; release: () => void } {
|
||||
let release!: () => void
|
||||
const promise = new Promise<void>((resolve) => {
|
||||
release = resolve
|
||||
})
|
||||
return { promise, release }
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
describe('applyAgentWorkspaceTrust on this machine', () => {
|
||||
it('gives only Codex the long deadline its shared config lane needs', async () => {
|
||||
vi.useFakeTimers()
|
||||
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
|
||||
const codexWrite = pending()
|
||||
mocks.codex.mockReturnValueOnce(codexWrite.promise)
|
||||
let codexSettled = false
|
||||
const codex = applyAgentWorkspaceTrust('codex', WORKSPACE, local).then(() => {
|
||||
codexSettled = true
|
||||
})
|
||||
await vi.advanceTimersByTimeAsync(SHORT_AGENT_TRUST_WRITE_DEADLINE_MS + 1)
|
||||
expect(codexSettled).toBe(false)
|
||||
await vi.advanceTimersByTimeAsync(AGENT_TRUST_WRITE_DEADLINE_MS)
|
||||
await codex
|
||||
expect(codexSettled).toBe(true)
|
||||
codexWrite.release()
|
||||
warn.mockRestore()
|
||||
})
|
||||
})
|
||||
|
||||
describe('applyAgentWorkspaceTrust in a WSL guest', () => {
|
||||
const guestHome = '\\\\wsl.localhost\\Ubuntu\\home\\u'
|
||||
|
||||
afterEach(() => {
|
||||
clearWslHomeCache()
|
||||
})
|
||||
|
||||
it('writes Antigravity trust under the distro home, keyed by the guest path', async () => {
|
||||
rememberWslHome('Ubuntu', guestHome)
|
||||
await applyAgentWorkspaceTrust('antigravity', `${guestHome}\\repo`, local)
|
||||
await applyAgentWorkspaceTrust('antigravity', 'C:\\src\\app', {
|
||||
...local,
|
||||
wslDistro: 'ubuntu'
|
||||
})
|
||||
await applyAgentWorkspaceTrust('cursor', `${guestHome}\\repo`, local)
|
||||
expect(mocks.antigravity.mock.calls).toEqual([
|
||||
[`${guestHome}\\repo`, guestHome, '/home/u/repo'],
|
||||
['C:\\src\\app', guestHome, '/mnt/c/src/app']
|
||||
])
|
||||
expect(mocks.cursor).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('leaves Antigravity to ask when the distro home is not known yet', async () => {
|
||||
await applyAgentWorkspaceTrust('antigravity', `${guestHome}\\repo`, local)
|
||||
expect(mocks.antigravity).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('applyAgentWorkspaceTrust for Claude', () => {
|
||||
let root: string
|
||||
|
||||
@@ -266,26 +200,4 @@ describe('applyAgentWorkspaceTrust for Claude', () => {
|
||||
projects: { [root]: { hasTrustDialogAccepted: true } }
|
||||
})
|
||||
})
|
||||
|
||||
it('gives a local Claude write a short budget, after which Claude asks', async () => {
|
||||
vi.useFakeTimers()
|
||||
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
|
||||
const grant = pending()
|
||||
mocks.claudeGrant.mockReturnValueOnce(grant.promise.then(() => 'granted' as const))
|
||||
let settled = false
|
||||
const claude = applyAgentWorkspaceTrust('claude', root, {
|
||||
...local,
|
||||
env: { CLAUDE_CONFIG_DIR: root }
|
||||
}).then(() => {
|
||||
settled = true
|
||||
})
|
||||
await vi.advanceTimersByTimeAsync(SHORT_AGENT_TRUST_WRITE_DEADLINE_MS - 1)
|
||||
expect(settled).toBe(false)
|
||||
await vi.advanceTimersByTimeAsync(2)
|
||||
await claude
|
||||
expect(settled).toBe(true)
|
||||
expect(String(warn.mock.calls[0]?.[0])).toContain('did not settle')
|
||||
grant.release()
|
||||
warn.mockRestore()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -15,7 +15,7 @@ import {
|
||||
|
||||
afterEach(() => setSessionSearchService(null))
|
||||
|
||||
test.each(['runtime', 'relay'] as const)(
|
||||
test.each(['relay'] as const)(
|
||||
'keeps an empty decoder catalog authoritative over both history flags on %s',
|
||||
async (transport) => {
|
||||
const service = fakeSearchService()
|
||||
@@ -40,7 +40,7 @@ test.each(['runtime', 'relay'] as const)(
|
||||
}
|
||||
)
|
||||
|
||||
test.each(['runtime', 'relay'] as const)(
|
||||
test.each(['relay'] as const)(
|
||||
'keeps an unsupported-only filter narrow through normal service checks on %s',
|
||||
async (transport) => {
|
||||
const request = {
|
||||
|
||||
@@ -1,32 +1,18 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { afterEach, describe, expect, it } from 'vitest'
|
||||
import { fakeSearchService } from '../../shared/ai-vault/search/ai-vault-search-test-fixture'
|
||||
import { unavailableSessionSearchStatus } from '../../shared/ai-vault/search/ai-vault-search-client'
|
||||
|
||||
import {
|
||||
setSessionSearchService,
|
||||
searchSessionService,
|
||||
sessionSearchServiceStatus
|
||||
} from './session-search-service-registry'
|
||||
|
||||
afterEach(() => {
|
||||
setSessionSearchService(null)
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
describe('session search service registry', () => {
|
||||
it('answers without constructing an indexer and validates even when unavailable', async () => {
|
||||
expect(await searchSessionService({ query: 'needle' }, 'ipc')).toEqual({
|
||||
kind: 'unavailable',
|
||||
reason: 'no-service'
|
||||
})
|
||||
expect(await sessionSearchServiceStatus({}, 'ipc')).toMatchObject({
|
||||
enabled: false,
|
||||
phase: 'idle',
|
||||
generation: 0
|
||||
})
|
||||
await expect(searchSessionService({ query: 42 }, 'ipc')).rejects.toThrow()
|
||||
})
|
||||
it.each(['ipc', 'runtime', 'relay'] as const)(
|
||||
it.each(['ipc', 'relay'] as const)(
|
||||
'withholds degraded-root paths from %s status per the exposure policy',
|
||||
async (transport) => {
|
||||
const service = fakeSearchService()
|
||||
@@ -44,52 +30,4 @@ describe('session search service registry', () => {
|
||||
])
|
||||
}
|
||||
)
|
||||
it('searches indexed data by default, drops legacy options and suppresses unsolicited diagnostics', async () => {
|
||||
const service = fakeSearchService()
|
||||
setSessionSearchService(service)
|
||||
const result = await searchSessionService(
|
||||
{ query: 'needle', tier: 'conversation', refresh: true },
|
||||
'ipc'
|
||||
)
|
||||
expect(service.reconcile).not.toHaveBeenCalled()
|
||||
expect(service.search).toHaveBeenCalledWith(
|
||||
{
|
||||
query: 'needle',
|
||||
limit: 20
|
||||
},
|
||||
undefined
|
||||
)
|
||||
expect(result).not.toHaveProperty('debug')
|
||||
expect(await searchSessionService({ query: 'needle', debug: true }, 'ipc')).toHaveProperty(
|
||||
'debug'
|
||||
)
|
||||
})
|
||||
|
||||
it('searches after the default five-second bound and observes a late rejection', async () => {
|
||||
vi.useFakeTimers()
|
||||
const service = fakeSearchService()
|
||||
let reject!: (error: Error) => void
|
||||
service.reconcile.mockImplementation(
|
||||
() =>
|
||||
new Promise((_resolve, rejectPromise) => {
|
||||
reject = rejectPromise
|
||||
})
|
||||
)
|
||||
setSessionSearchService(service)
|
||||
const result = searchSessionService(
|
||||
{ query: 'needle', freshness: 'wait-until-current' },
|
||||
'relay'
|
||||
)
|
||||
await vi.advanceTimersByTimeAsync(4_999)
|
||||
expect(service.search).not.toHaveBeenCalled()
|
||||
await vi.advanceTimersByTimeAsync(1)
|
||||
expect(await result).toMatchObject({
|
||||
kind: 'results',
|
||||
truncated: { freshness: true },
|
||||
hits: [expect.objectContaining({ source: { presence: 'present' } })]
|
||||
})
|
||||
reject(new Error('late failure'))
|
||||
await Promise.resolve()
|
||||
expect(vi.getTimerCount()).toBe(0)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,72 +0,0 @@
|
||||
import { mkdtemp, rm } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { AiVaultScanWork } from '../../shared/ai-vault/scanning/ai-vault-scan-progress'
|
||||
import {
|
||||
AI_VAULT_SCAN_PROGRESS_INTERVAL_MS,
|
||||
trackAiVaultScanProgress
|
||||
} from './ai-vault-scan-progress'
|
||||
import { scanAiVaultSessions } from './session-scanner'
|
||||
import { resetSessionParseCacheForTests } from './parse-cache/session-parse-cache-store'
|
||||
import { isolatedScanRoots, writeJsonlFile } from './session-scanner-test-fixtures'
|
||||
|
||||
let tempRoots: string[] = []
|
||||
|
||||
afterEach(async () => {
|
||||
vi.useRealTimers()
|
||||
resetSessionParseCacheForTests()
|
||||
await Promise.all(tempRoots.map((root) => rm(root, { recursive: true, force: true })))
|
||||
tempRoots = []
|
||||
})
|
||||
|
||||
async function tempRoot(): Promise<string> {
|
||||
const root = await mkdtemp(join(tmpdir(), 'orca-scan-progress-'))
|
||||
tempRoots.push(root)
|
||||
return root
|
||||
}
|
||||
|
||||
describe('scan progress reporting', () => {
|
||||
it('reports discovery and reading for its own scan, never for an unrelated one', async () => {
|
||||
const root = await tempRoot()
|
||||
const roots = isolatedScanRoots(root)
|
||||
for (const name of ['a', 'b', 'c']) {
|
||||
await writeJsonlFile(join(roots.claudeProjectsDir, 'project', `${name}.jsonl`), [
|
||||
{
|
||||
type: 'user',
|
||||
sessionId: name,
|
||||
timestamp: '2026-05-01T10:00:00.000Z',
|
||||
cwd: '/tmp/claude',
|
||||
message: { role: 'user', content: `ask ${name}` }
|
||||
}
|
||||
])
|
||||
}
|
||||
const reports: AiVaultScanWork[] = []
|
||||
const tracked = new AbortController()
|
||||
let now = 0
|
||||
trackAiVaultScanProgress(
|
||||
tracked.signal,
|
||||
(work) => reports.push(work),
|
||||
() => (now += AI_VAULT_SCAN_PROGRESS_INTERVAL_MS)
|
||||
)
|
||||
|
||||
await scanAiVaultSessions({
|
||||
...roots,
|
||||
platform: 'darwin',
|
||||
limit: 20,
|
||||
signal: new AbortController().signal
|
||||
})
|
||||
expect(reports).toEqual([])
|
||||
|
||||
resetSessionParseCacheForTests()
|
||||
const result = await scanAiVaultSessions({
|
||||
...roots,
|
||||
platform: 'darwin',
|
||||
limit: 20,
|
||||
signal: tracked.signal
|
||||
})
|
||||
expect(result.sessions).toHaveLength(3)
|
||||
expect(reports.some((work) => work.stage === 'finding')).toBe(true)
|
||||
expect(reports.at(-1)).toMatchObject({ stage: 'reading', read: { done: 3, total: 3 } })
|
||||
})
|
||||
})
|
||||
@@ -1,141 +0,0 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import type {
|
||||
AiVaultServiceChildMessage,
|
||||
AiVaultServiceParentMessage
|
||||
} from './session-scanner-service-protocol'
|
||||
import { AI_VAULT_SERVICE_PROTOCOL_VERSION } from './session-scanner-service-protocol'
|
||||
|
||||
const scanAiVaultSessions = vi.hoisted(() => vi.fn())
|
||||
const flushSessionParseCachePersist = vi.hoisted(() => vi.fn(async () => undefined))
|
||||
const closeSearch = vi.hoisted(() => vi.fn())
|
||||
|
||||
vi.mock('../session-scanner', () => ({ scanAiVaultSessions }))
|
||||
vi.mock('../parse-cache/session-parse-cache-store', async (importOriginal) => ({
|
||||
...(await importOriginal<object>()),
|
||||
invalidateSessionParseCacheEntry: vi.fn()
|
||||
}))
|
||||
vi.mock('../parse-cache/session-parse-cache-persistence', () => ({
|
||||
flushSessionParseCachePersist,
|
||||
initSessionParseCachePersistence: vi.fn()
|
||||
}))
|
||||
vi.mock('./session-scanner-service-search', () => ({
|
||||
SessionScannerServiceSearch: class {
|
||||
handles(): boolean {
|
||||
return false
|
||||
}
|
||||
close(): void {
|
||||
closeSearch()
|
||||
}
|
||||
}
|
||||
}))
|
||||
|
||||
const result = { sessions: [], issues: [], scannedAt: '2026-09-15' }
|
||||
const sent: AiVaultServiceChildMessage[] = []
|
||||
const disconnect = vi.fn()
|
||||
let restoreProcess = (): void => undefined
|
||||
|
||||
function emit(message: AiVaultServiceParentMessage): void {
|
||||
process.emit('message', message, undefined)
|
||||
}
|
||||
|
||||
function scan(id: number): void {
|
||||
emit({ type: 'request', id, operation: 'scan', options: {} })
|
||||
}
|
||||
|
||||
function settle(): Promise<void> {
|
||||
return new Promise((resolve) => setImmediate(resolve))
|
||||
}
|
||||
|
||||
function cancelAndObserveSet(id: number): Set<unknown> {
|
||||
const add = vi.spyOn(Set.prototype, 'add')
|
||||
try {
|
||||
emit({ type: 'cancel', id })
|
||||
const index = add.mock.calls.findIndex(([value]) => value === id)
|
||||
const retained = add.mock.contexts[index]
|
||||
if (!(retained instanceof Set)) {
|
||||
throw new Error('Expected an admitted cancellation.')
|
||||
}
|
||||
return retained
|
||||
} finally {
|
||||
add.mockRestore()
|
||||
}
|
||||
}
|
||||
|
||||
beforeEach(async () => {
|
||||
vi.resetModules()
|
||||
vi.clearAllMocks()
|
||||
sent.length = 0
|
||||
scanAiVaultSessions.mockResolvedValue(result)
|
||||
const sendDescriptor = Object.getOwnPropertyDescriptor(process, 'send')
|
||||
const disconnectDescriptor = Object.getOwnPropertyDescriptor(process, 'disconnect')
|
||||
const messageListeners = new Set(process.listeners('message'))
|
||||
const disconnectListeners = new Set(process.listeners('disconnect'))
|
||||
Object.defineProperty(process, 'send', {
|
||||
configurable: true,
|
||||
value: (message: AiVaultServiceChildMessage) => {
|
||||
sent.push(message)
|
||||
return true
|
||||
}
|
||||
})
|
||||
Object.defineProperty(process, 'disconnect', { configurable: true, value: disconnect })
|
||||
restoreProcess = () => {
|
||||
for (const listener of process.listeners('message')) {
|
||||
if (!messageListeners.has(listener)) {
|
||||
process.removeListener('message', listener)
|
||||
}
|
||||
}
|
||||
for (const listener of process.listeners('disconnect')) {
|
||||
if (!disconnectListeners.has(listener)) {
|
||||
process.removeListener('disconnect', listener)
|
||||
}
|
||||
}
|
||||
if (sendDescriptor) {
|
||||
Object.defineProperty(process, 'send', sendDescriptor)
|
||||
} else {
|
||||
Reflect.deleteProperty(process, 'send')
|
||||
}
|
||||
if (disconnectDescriptor) {
|
||||
Object.defineProperty(process, 'disconnect', disconnectDescriptor)
|
||||
} else {
|
||||
Reflect.deleteProperty(process, 'disconnect')
|
||||
}
|
||||
}
|
||||
await import('./session-scanner-service-entry')
|
||||
emit({
|
||||
type: 'init',
|
||||
protocol: AI_VAULT_SERVICE_PROTOCOL_VERSION,
|
||||
sessionParseCache: null,
|
||||
sessionSearch: null
|
||||
})
|
||||
})
|
||||
|
||||
afterEach(async () => {
|
||||
emit({ type: 'shutdown' })
|
||||
await settle()
|
||||
restoreProcess()
|
||||
})
|
||||
|
||||
describe('AI Vault service cancellation ownership', () => {
|
||||
it('cancels running and queued requests and releases both IDs when they settle', async () => {
|
||||
const first = Promise.withResolvers<typeof result>()
|
||||
const signals: AbortSignal[] = []
|
||||
scanAiVaultSessions.mockImplementation(({ signal }: { signal: AbortSignal }) => {
|
||||
signals.push(signal)
|
||||
return signals.length === 1 ? first.promise : Promise.resolve(result)
|
||||
})
|
||||
scan(1)
|
||||
scan(2)
|
||||
await settle()
|
||||
const cancelled = cancelAndObserveSet(1)
|
||||
emit({ type: 'cancel', id: 2 })
|
||||
expect(signals).toHaveLength(1)
|
||||
expect(signals[0]?.aborted).toBe(true)
|
||||
expect(cancelled.size).toBe(2)
|
||||
first.resolve(result)
|
||||
await settle()
|
||||
expect(signals).toHaveLength(2)
|
||||
expect(signals[1]?.aborted).toBe(true)
|
||||
expect(cancelled.size).toBe(0)
|
||||
expect(sent.filter((message) => message.type === 'result')).toHaveLength(2)
|
||||
})
|
||||
})
|
||||
@@ -1,18 +1,11 @@
|
||||
import { readAiVaultSessionTitlesFromFiles } from '../../session-titles/session-title-file-reader'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import * as transcriptFs from '../../../native-chat/wsl-transcript-fs-access'
|
||||
import { readCodexIndexUpdate } from './session-scanner-codex-index-read'
|
||||
import { parseAgentSessionFileCached } from '../../parse-cache/session-scanner-parse-cache'
|
||||
import { resetSessionParseCacheForTests } from '../../parse-cache/session-parse-cache-store'
|
||||
import { appendFile, mkdir, mkdtemp, rename, rm, stat, writeFile } from 'node:fs/promises'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import {
|
||||
_getCodexSessionIndexTitleCacheSizeForTest,
|
||||
_readCachedCodexSessionIndexTitlesForTest,
|
||||
_storeCodexSessionIndexTitleCacheEntryForTest,
|
||||
resetCodexSessionIndexTitleCacheForTests
|
||||
} from './session-scanner-codex-title-index'
|
||||
import { resetCodexSessionIndexTitleCacheForTests } from './session-scanner-codex-title-index'
|
||||
|
||||
let tempRoots: string[] = []
|
||||
|
||||
@@ -24,28 +17,6 @@ afterEach(async () => {
|
||||
tempRoots = []
|
||||
})
|
||||
|
||||
describe('codex session index title cache', () => {
|
||||
it('does not replace a newer same-home entry when an older cache hit resolves', async () => {
|
||||
let resolveOldTitles: (titles: Map<string, string>) => void = () => {}
|
||||
const oldTitles = new Promise<Map<string, string>>((resolve) => {
|
||||
resolveOldTitles = resolve
|
||||
})
|
||||
_storeCodexSessionIndexTitleCacheEntryForTest('same-home', 'old', oldTitles)
|
||||
const pendingOldHit = _readCachedCodexSessionIndexTitlesForTest('same-home', 'old')
|
||||
|
||||
const newTitles = new Map([['new-session', 'New title']])
|
||||
_storeCodexSessionIndexTitleCacheEntryForTest('same-home', 'new', Promise.resolve(newTitles))
|
||||
const resolvedOldTitles = new Map([['old-session', 'Old title']])
|
||||
resolveOldTitles(resolvedOldTitles)
|
||||
|
||||
await expect(pendingOldHit).resolves.toBe(resolvedOldTitles)
|
||||
await expect(_readCachedCodexSessionIndexTitlesForTest('same-home', 'new')).resolves.toBe(
|
||||
newTitles
|
||||
)
|
||||
expect(_getCodexSessionIndexTitleCacheSizeForTest()).toBe(1)
|
||||
})
|
||||
})
|
||||
|
||||
async function indexHome() {
|
||||
const root = await mkdtemp(join(tmpdir(), 'orca-codex-index-'))
|
||||
tempRoots.push(root)
|
||||
@@ -54,30 +25,6 @@ async function indexHome() {
|
||||
const entry = (id: string, thread_name: string) => `${JSON.stringify({ id, thread_name })}\n`
|
||||
|
||||
describe('incremental Codex session names', () => {
|
||||
it('applies only appended complete records and retains a partial tail for the next read', async () => {
|
||||
const { path } = await indexHome()
|
||||
const initial = entry('session', 'First')
|
||||
await writeFile(path, initial)
|
||||
const beforeAppend = await stat(path)
|
||||
const appended = entry('session', 'After stat')
|
||||
await appendFile(path, appended)
|
||||
const first = await readCodexIndexUpdate(path, beforeAppend)
|
||||
expect(first.titles.get('session')).toBe('After stat')
|
||||
const stream = vi.spyOn(transcriptFs, 'openTranscriptReadStream')
|
||||
await appendFile(path, `${entry('session', 'Renamed')}{"id":"session","thread_name":"Fin`)
|
||||
const next = await readCodexIndexUpdate(path, await stat(path), first)
|
||||
expect(next.titles.get('session')).toBe('Renamed')
|
||||
expect(
|
||||
stream.mock.calls.some(
|
||||
([, options]) => options.start === Buffer.byteLength(initial + appended)
|
||||
)
|
||||
).toBe(true)
|
||||
await appendFile(path, 'al"}\n')
|
||||
expect((await readCodexIndexUpdate(path, await stat(path), next)).titles.get('session')).toBe(
|
||||
'Final'
|
||||
)
|
||||
})
|
||||
|
||||
it('rereads an EOF title observed after stat when growth invalidates its record', async () => {
|
||||
const { path } = await indexHome()
|
||||
await writeFile(path, entry('head', 'Head') + entry('tail', 'Original'))
|
||||
@@ -144,46 +91,6 @@ describe('incremental Codex session names', () => {
|
||||
}
|
||||
)
|
||||
|
||||
it('shares negative home lookups across cold and cached fallbacks, but refreshes them on a later call', async () => {
|
||||
const { root, path } = await indexHome()
|
||||
await mkdir(join(root, 'sessions'))
|
||||
await writeFile(path, entry('unrelated', 'Other thread'))
|
||||
const requests = await Promise.all(
|
||||
Array.from({ length: 5 }, async (_, index) => {
|
||||
const sessionId = `fallback-${index}`
|
||||
const transcriptPath = join(root, 'sessions', `${sessionId}.jsonl`)
|
||||
await writeFile(
|
||||
transcriptPath,
|
||||
`${JSON.stringify({ timestamp: '2026-11-05T10:00:00.000Z', type: 'session_meta', payload: { id: sessionId, title: 'Metadata name', cwd: '/repo/app' } })}\n`
|
||||
)
|
||||
return { agent: 'codex' as const, sessionId, transcriptPath }
|
||||
})
|
||||
)
|
||||
const indexStats = vi.spyOn(transcriptFs, 'wslGatedStat')
|
||||
for (const phase of ['cold', 'cached', 'renamed']) {
|
||||
if (phase === 'renamed') {
|
||||
await appendFile(
|
||||
path,
|
||||
requests.map((request) => entry(request.sessionId, 'Indexed rename')).join('')
|
||||
)
|
||||
}
|
||||
indexStats.mockClear()
|
||||
const result = await readAiVaultSessionTitlesFromFiles(requests)
|
||||
expect(result.titles.map((title) => title.title)).toEqual(
|
||||
phase === 'renamed'
|
||||
? [
|
||||
'Indexed rename',
|
||||
'Indexed rename',
|
||||
'Indexed rename',
|
||||
'Indexed rename',
|
||||
'Indexed rename'
|
||||
]
|
||||
: ['Metadata name', 'Metadata name', 'Metadata name', 'Metadata name', 'Metadata name']
|
||||
)
|
||||
expect(indexStats.mock.calls.filter(([file]) => file === path)).toHaveLength(1)
|
||||
}
|
||||
})
|
||||
|
||||
it('keeps the indexed rename over a recorded session_meta title when the rollout grows', async () => {
|
||||
const { root, path } = await indexHome()
|
||||
const rollout = join(root, 'sessions', 'rollout.jsonl')
|
||||
|
||||
Reference in New Issue
Block a user