Files
orca/src/main/opencode/hook-plugin-lifecycle-delivery.test.ts
T
OrcaWinandOrcaWin 7d6603aa17 [comment audit] Complete repository-wide comment cleanup (#33249)
* [comment audit] Align legacy failure-read counts with cached display

* [comment audit] Condense shared provider lifecycle and browser recovery comments [skip ci]

* [comment audit] Condense shared generation, path and preview comments [skip ci]

* [comment audit] Condense host, file and Git contract rationale [skip ci]

* [comment audit] Tighten Git lifecycle and provider contract comments [skip ci]

* [comment audit] Clarify shared host authority and launch isolation [skip ci]

* [comment audit] simplify local access mobile and native chat contracts [skip ci]

* [comment audit] simplify native chat presentation and state contracts [skip ci]

* [comment audit] simplify native runtime and provider contracts [skip ci]

* [comment audit] simplify migration and orchestration contracts [skip ci]

* [comment audit] simplify plugin trust and process capture rationale [skip ci]

* [comment audit] simplify terminal delivery and remote compatibility rationale [skip ci]

* [comment audit] clarify remote recovery and launch wire rationale [skip ci]

* [comment audit] shorten shared RPC compatibility and runtime evidence comments [skip ci]

* [comment audit] simplify secure storage shell startup and sidebar rationale [skip ci]

* [comment audit] clarify sidebar, skill and SSH invariants [skip ci]

* [comment audit] condense structured chat delivery and timing rationale [skip ci]

* [comment audit] condense terminal replay and telemetry invariants [skip ci]

* [comment audit] clarify launch permission and terminal delivery rationale [skip ci]

* [comment audit] clarify workspace ownership and layout contracts [skip ci]

* [comment audit] wait for fitted and painted SSH terminal links

* [comment audit] clarify layout persistence and session ownership [skip ci]

* [comment audit] clarify host routing and workspace lifecycle contracts [skip ci]

* [comment audit] clarify startup persistence and app lifetime comments [skip ci]

* [comment audit] clarify recovery and activity boundaries [skip ci]

* [comment audit] condense activity and artifact invariants [skip ci]

* [comment audit] condense automation authority contracts [skip ci]

* [comment audit] simplify automation scheduling and history contracts [skip ci]

* [comment audit] clarify browser chrome and annotation lifecycles [skip ci]

* [comment audit] clarify browser routing and retained guest ownership [skip ci]

* [comment audit] clarify browser recovery and document ownership comments [skip ci]

* [comment audit] restore hosted runners required by native IME fixtures

* [comment audit] shorten preview, palette and dashboard invariants [skip ci]

* [comment audit] clarify terminal preview, dashboard and retention comments [skip ci]

* [comment audit] clarify diff-note recovery and editor lifecycle comments [skip ci]

* [comment audit] shorten rich-text and combined-diff ownership comments [skip ci]

* [comment audit] shorten autosave, draft recovery and model ownership comments [skip ci]

* [comment audit] shorten save-queue, notebook and Markdown constraints [skip ci]

* [comment audit] shorten Monaco, PDF and rich Markdown safeguards [skip ci]

* [comment audit] clarify rich Markdown source and selection safeguards [skip ci]

* [comment audit] clarify editor loading and emulator stream lifetimes [skip ci]

* [comment audit] trim emulator and feature tour narration [skip ci]

* [comment audit] clarify floating workspace and GitHub cache ownership [skip ci]

* [comment audit] trim provider controls and Linear filter explanations [skip ci]

* [comment audit] clarify pairing and chat resume lifetimes [skip ci]

* [comment audit] clarify chat delivery and transcript lifetimes [skip ci]

* [comment audit] clarify session options and host-owned status [skip ci]

* [comment audit] clarify draft durability and live-status precedence [skip ci]

* [comment audit] Trim chat send and model ownership explanations [skip ci]

* [comment audit] Shorten transcript ownership and send recovery comments [skip ci]

* [comment audit] Simplify native chat composer and transcript hook comments [skip ci]

* [comment audit] Shorten native chat scroll and structured session explanations [skip ci]

* [comment audit] Trim workspace picker and onboarding commentary [skip ci]

* [comment audit] Simplify pet rendering, review cache and quick open comments [skip ci]

* [comment audit] Trim sidebar and session history explanations [skip ci]

* [comment audit] Condense session resume and review checks comments [skip ci]

* [comment audit] Shorten checks state and file explorer refresh comments [skip ci]

* [comment audit] Trim plugin bridge and source-control action rationale [skip ci]

* [comment audit] Trim source-control listing and review rationale [skip ci]

* [comment audit] Shorten sidebar lifecycle and explorer safeguards [skip ci]

* [comment audit] Condense Settings account and appearance rationale [skip ci]

* [comment audit] Trim pairing and repository Settings explanations [skip ci]

* [comment audit] Condense Settings search SSH and terminal safeguards [skip ci]

* [comment audit] Shorten Settings voice and provider ownership comments [skip ci]

* [comment audit] Condense Settings draft persistence and host-state rationale [skip ci]

* [comment audit] Trim Settings hooks and sidebar setup rationale [skip ci]

* [comment audit] Condense sidebar deletion and board-filter safeguards [skip ci]

* [comment audit] Condense worktree cards, host ownership and Markdown contracts [skip ci]

* [comment audit] Condense sidebar drag, folder and filtering contracts [skip ci]

* [comment audit] Condense sidebar parity, sleep and host ownership contracts [skip ci]

* [comment audit] Prune focus-read baseline after comment cleanup

* [comment audit] Clarify sidebar visibility, board drops and agent evidence [skip ci]

* [comment audit] Tighten sidebar listing, drag and reveal contracts [skip ci]

* [comment audit] Clarify viewport geometry and skill update safeguards [skip ci]

* [comment audit] Tighten skill inventory, usage and host status comments [skip ci]

* [comment audit] Clarify usage ownership and resource kill safeguards [skip ci]

* [comment audit] Tighten tab selection, rename and search contracts [skip ci]

* [comment audit] Tighten tab-strip geometry and drag ownership comments [skip ci]

* [comment audit] Tighten Tasks recovery, pagination and mutation comments [skip ci]

* [comment audit] Tighten provider loading and terminal recovery comments [skip ci]

* [comment audit] Tighten completion, cadence and PTY ownership comments [skip ci]

* [comment audit] Clarify terminal restore and parked-pane boundaries [skip ci]

* [comment audit] Tighten PTY startup and replay explanations [skip ci]

* [comment audit] Clarify PTY identity and delivery ownership [skip ci]

* [comment audit] Shorten remote reconnect and input replay rationale [skip ci]

* [comment audit] Condense terminal parking clipboard and file link comments [skip ci]

* [comment audit] Clarify IME ownership and trim trace history [skip ci]

* [comment audit] Shorten pane recovery and parked watcher explanations [skip ci]

* [comment audit] Condense snapshot replay and visibility recovery rationale [skip ci]

* [comment audit] Shorten terminal parking and keyboard ownership rationale [skip ci]

* [comment audit] Trim renderer lifecycle and menu rationale [skip ci]

* [comment audit] Condense workspace cleanup ownership and settlement notes [skip ci]

* [comment audit] Clarify renderer hook evidence and source ownership [skip ci]

* [comment audit] Tighten IPC ownership and reconnect explanations [skip ci]

* [comment audit] Trim renderer focus, paste and attention comments [skip ci]

* [comment audit] Shorten scroll, locale and agent lifecycle comments [skip ci]

* [comment audit] Trim agent launch, resume and ownership commentary [skip ci]

* [comment audit] Shorten account, browser and editor comments [skip ci]

* [comment audit] Clarify host-mirror waits, previews and input ownership [skip ci]

* [comment audit] Condense launch recovery and editor tokenization comments [skip ci]

* [comment audit] Condense workspace selection and terminal pane rationale [skip ci]

* [comment audit] Condense terminal fitting and rendering recovery comments [skip ci]

* [comment audit] Condense terminal input and host routing explanations [skip ci]

* [comment audit] Condense ownership and sleeping-session recovery rationale [skip ci]

* [comment audit] Condense structured launch and terminal link explanations [skip ci]

* [comment audit] Condense terminal ownership and workspace file routing rationale [skip ci]

* [comment audit] Condense session persistence and workspace activation rationale [skip ci]

* [comment audit] Condense workspace routing and browser ownership rationale [skip ci]

* [comment audit] Condense mirror recovery and layout authority rationale [skip ci]

* [comment audit] Condense runtime transport and file safety rationale [skip ci]

* [comment audit] Condense runtime graph and structured session rationale [skip ci]

* [comment audit] Condense browser creation and remote tab recovery rationale [skip ci]

* [comment audit] Condense snapshot authority and publisher recovery rationale [skip ci]

* [comment audit] Condense frame, startup and provider cache rationale [skip ci]

* [comment audit] Condense host twin and agent lifecycle rationale [skip ci]

* [comment audit] Condense browser authority and editor cleanup rationale [skip ci]

* [comment audit] Condense editor buffer identity and review cache rationale [skip ci]

* [comment audit] Condense provider lifetime and repository ownership rationale [skip ci]

* [comment audit] Condense reconnect, hydration and terminal retirement rationale [skip ci]

* [comment audit] Condense recovery, reconciliation and persistence rationale [skip ci]

* [comment audit] Condense cleanup ownership and listing admission rationale [skip ci]

* [comment audit] Condense teardown ordering and terminal ownership rationale [skip ci]

* [comment audit] Condense recovery ledger and web host-boundary rationale [skip ci]

* [comment audit] Condense web reconnect and credential lifecycle rationale [skip ci]

* [comment audit] Condense cloud rollout and assignment safety rationale [skip ci]

* [comment audit] Condense relay session and database recovery rationale [skip ci]

* [comment audit] Condense relay placement and protocol compatibility rationale [skip ci]

* [comment audit] Condense build and packaging constraints [skip ci]

* [comment audit] Condense CI gates and validation isolation rationale [skip ci]

* [comment audit] Condense catalog identity and browser validation rationale [skip ci]

* [comment audit] Condense mobile browser and frame-budget rationale [skip ci]

* [comment audit] Shorten mobile route and browser test explanations [skip ci]

* [comment audit] Condense editor and session seam test rationale [skip ci]

* [comment audit] Trim session and terminal closure history [skip ci]

* [comment audit] Shorten terminal browser and census explanations [skip ci]

* [comment audit] Preserve root-only E2E diagnostic baseline

* [comment audit] Condense mobile seam and HTML preview test rationale [skip ci]

* [comment audit] Condense preview instrumentation and render harness rationale [skip ci]

* [comment audit] Condense bundle contracts and native-build constraints [skip ci]

* [comment audit] Shorten native packaging and CI routing rationale [skip ci]

* [comment audit] Condense release tooling and benchmark constraints [skip ci]

* [comment audit] Condense packaging and platform gate rationale [skip ci]

* [comment audit] Shorten mobile route and history rationale [skip ci]

* [comment audit] Condense mobile browser and component rationale [skip ci]

* [comment audit] Shorten drawer and workspace-form rationale [skip ci]

* [comment audit] Trim mobile review and editor-document explanations [skip ci]

* [comment audit] Condense editor lifecycle and Markdown explanations [skip ci]

* [comment audit] Trim mobile file, diagnostics and dictation commentary [skip ci]

* [comment audit] Simplify mobile host-list and workspace-view explanations [skip ci]

* [comment audit] Clarify mobile shell lifetime and bridge delivery constraints [skip ci]

* [comment audit] Condense bridge stream, native request and audio rationale [skip ci]

* [comment audit] Reduce bridge schema and page-client commentary [skip ci]

* [comment audit] Tighten mobile page bridge contracts [skip ci]

* [comment audit] Clarify mobile cache and session constraints [skip ci]

* [comment audit] Condense mobile route and lifecycle rationale [skip ci]

* [comment audit] Tighten mobile shell hook timing rationale [skip ci]

* [comment audit] Clarify route handoff and notification compatibility [skip ci]

* [comment audit] Clarify push registration and dictation cleanup constraints [skip ci]

* [comment audit] Condense keyboard geometry and native media ownership rationale [skip ci]

* [comment audit] Tighten mobile chat scroll and composer concurrency rationale [skip ci]

* [comment audit] Condense mobile reply compatibility and upload ownership rationale [skip ci]

* [comment audit] Condense optimistic echo and scroll ownership rationale [skip ci]

* [comment audit] Tighten stream replay and queued session ownership rationale [skip ci]

* [comment audit] Condense mobile composer and reply-schema constraints [skip ci]

* [comment audit] Clarify mobile transcript recovery and session ownership [skip ci]

* [comment audit] Clarify mobile queue and source-control compatibility [skip ci]

* [comment audit] Condense storage and task launch constraints [skip ci]

* [comment audit] Clarify task schemas and terminal document ownership [skip ci]

* [comment audit] Tighten terminal input and viewport rationale [skip ci]

* [comment audit] Shorten terminal and RPC recorder contracts [skip ci]

* [comment audit] Condense recorder engine and connection contracts [skip ci]

* [comment audit] Shorten host credential and relay recovery comments [skip ci]

* [comment audit] Tighten pairing recovery and bundle transport rationale [skip ci]

* [comment audit] Clarify RPC delivery and workspace catalog boundaries [skip ci]

* [comment audit] Condense catalog and relay entry contracts [skip ci]

* [comment audit] Shorten shutdown and SSH relay delivery contracts [skip ci]

* [comment audit] Condense WSL relay and E2E regression rationale [skip ci]

* [comment audit] Shorten cross-version harness and renderer fixture explanations [skip ci]

* [comment audit] Condense paired-host and E2E lifecycle rationale [skip ci]

* [comment audit] Shorten layout oracle and regression explanations [skip ci]

* [comment audit] Condense paired recovery and ownership regression contracts [skip ci]

* [comment audit] Shorten restart, sidebar and SSH lifecycle contracts [skip ci]

* [comment audit] Condense terminal rendering and IME regression rationale [skip ci]

* [comment audit] Shorten terminal recovery and benchmark contracts [skip ci]

* [comment audit] Condense tooling and Windows lifecycle proof rationale [skip ci]

* [comment audit] Condense workflow routing and release rationale [skip ci]

* [comment audit] Condense mobile security and installer contracts [skip ci]

* [comment audit] Shorten native rationale and stylesheet workarounds [skip ci]

* [comment audit] Shorten Windows visibility probe rationale [skip ci]

* [comment audit] Condense embedded release and signing rationale [skip ci]

* [comment audit] Retain current main test behavior in final reconciliation [skip ci]

* [comment audit] Complete final comment review across current source inventory

* [comment audit] Handle consolidated audit reports before final CI

* [comment audit] Preserve credential storage census detail [skip ci]

* [comment audit] Scale broad changed E2E selections with verified timing shards

* [comment audit] Align E2E assertions with browser close and settled session metadata

* [comment audit] Match existing E2Es to current resource and windowing contracts

* [comment audit] Observe the shared server outage notice in reconnect coverage

* [comment audit] Make existing renderer probes measure settled tab and PTY work

* [comment audit] Align palette E2E selector with task search

* [comment audit] Refresh remaining palette search selectors

* [comment audit] Keep selector correction within selected audit specs

* [comment audit] Await emoji fixture settings inside renderer evaluation

* [comment audit] Cancel fixture fit retries between terminal tests

---------

Co-authored-by: OrcaWin <293788423+OrcaWin@users.noreply.github.com>
2026-10-25 04:05:46 -07:00

818 lines
28 KiB
TypeScript

import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { pathToFileURL } from 'node:url'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
const { getPathMock } = vi.hoisted(() => ({
getPathMock: vi.fn<(name: string) => string>()
}))
vi.mock('electron', () => ({
app: { getPath: getPathMock }
}))
import { _internals } from './hook-service'
type SessionFixture = { id: string; parentID?: string }
/** Fixtures cover both current two-argument and legacy single-options SDK calls. */
type SessionClientCall = (...args: never[]) => Promise<{ data: SessionFixture[] }>
type SessionClientFixture = { list: SessionClientCall; get?: SessionClientCall }
type PluginEvent = { type: string; properties?: Record<string, unknown> }
type PluginEventHandler = (input: { event: PluginEvent }) => Promise<void>
type PluginHooks = { event: PluginEventHandler; dispose?: () => Promise<void> }
type RecordedPost = {
hook_event_name: string
sessionID?: string
}
const ENV_KEYS = [
'ORCA_PANE_KEY',
'ORCA_AGENT_HOOK_PORT',
'ORCA_AGENT_HOOK_TOKEN',
'ORCA_AGENT_HOOK_ENDPOINT'
] as const
describe('OpenCode plugin lifecycle delivery', () => {
let tempDir: string
let posts: RecordedPost[]
let savedEnv: Record<string, string | undefined>
let savedFetch: typeof globalThis.fetch
beforeEach(() => {
tempDir = mkdtempSync(join(tmpdir(), 'orca-opencode-lifecycle-plugin-'))
posts = []
savedEnv = {}
for (const key of ENV_KEYS) {
savedEnv[key] = process.env[key]
}
process.env.ORCA_PANE_KEY = 'tab-1:leaf-1'
process.env.ORCA_AGENT_HOOK_PORT = '45678'
process.env.ORCA_AGENT_HOOK_TOKEN = 'test-token'
delete process.env.ORCA_AGENT_HOOK_ENDPOINT
savedFetch = globalThis.fetch
globalThis.fetch = vi.fn(async (_url: RequestInfo | URL, init?: RequestInit) => {
posts.push(readPayload(init))
return new Response(null, { status: 204 })
}) as typeof globalThis.fetch
})
afterEach(() => {
vi.useRealTimers()
globalThis.fetch = savedFetch
for (const key of ENV_KEYS) {
if (savedEnv[key] === undefined) {
delete process.env[key]
} else {
process.env[key] = savedEnv[key]
}
}
rmSync(tempDir, { recursive: true, force: true })
})
function readPayload(init?: RequestInit): RecordedPost {
return JSON.parse(String(init?.body)).payload as RecordedPost
}
async function loadHooks(
list: () => Promise<{ data: SessionFixture[] }> = async () => ({
data: [{ id: 'root' }]
})
): Promise<PluginHooks> {
return loadHooksWithSession({ list })
}
async function loadHooksWithSession(session: SessionClientFixture): Promise<PluginHooks> {
const pluginPath = join(tempDir, 'orca-opencode-status.mjs')
writeFileSync(pluginPath, _internals.getOpenCodePluginSource())
const module = (await import(pathToFileURL(pluginPath).href)) as {
OrcaOpenCodeStatusPlugin: (ctx: unknown) => Promise<PluginHooks>
}
return module.OrcaOpenCodeStatusPlugin({ client: { session } })
}
async function loadHandler(
list?: () => Promise<{ data: SessionFixture[] }>
): Promise<PluginEventHandler> {
return (await loadHooks(list)).event
}
function status(type: 'busy' | 'idle' | 'retry', sessionID = 'root'): PluginEvent {
return {
type: 'session.status',
properties: { sessionID, status: { type } }
}
}
function delta(text: string, field = 'text', sessionID = 'root'): PluginEvent {
return {
type: 'message.part.delta',
properties: {
sessionID,
messageID: 'message-assistant',
partID: 'part-assistant',
field,
delta: text
}
}
}
function names(): string[] {
return posts.map((post) => post.hook_event_name)
}
function rejectWhenAborted(signal: AbortSignal | undefined): Promise<never> {
if (!signal) {
return Promise.reject(new Error('missing abort signal'))
}
return new Promise((_resolve, reject) => {
signal.addEventListener('abort', () => reject(new Error('aborted')), { once: true })
})
}
it('maps only root session.created to SessionStart', async () => {
const handler = await loadHandler()
await handler({
event: { type: 'session.created', properties: { info: { id: 'root' } } }
})
await handler({
event: {
type: 'session.created',
properties: { info: { id: 'child', parentID: 'root' } }
}
})
expect(posts).toEqual([{ hook_event_name: 'SessionStart', sessionID: 'root' }])
})
it('falls back per coordinate when the endpoint file is partial or malformed', async () => {
const endpointPath = join(tempDir, 'endpoint.env')
writeFileSync(
endpointPath,
'not-an-assignment\nORCA_AGENT_HOOK_TOKEN=file-token\nBROKEN LINE\n'
)
process.env.ORCA_AGENT_HOOK_ENDPOINT = endpointPath
const fetchMock = vi.fn(
async (_url: RequestInfo | URL, _init?: RequestInit) => new Response(null, { status: 204 })
)
globalThis.fetch = fetchMock as typeof globalThis.fetch
const handler = await loadHandler()
await handler({ event: status('busy') })
expect(fetchMock).toHaveBeenCalledOnce()
const [url, init] = fetchMock.mock.calls[0]!
expect(String(url)).toBe('http://127.0.0.1:45678/hook/opencode')
expect(new Headers(init?.headers).get('X-Orca-Agent-Hook-Token')).toBe('file-token')
})
it('warns once for an unreadable endpoint without exposing hook credentials', async () => {
process.env.ORCA_AGENT_HOOK_ENDPOINT = tempDir
process.env.ORCA_AGENT_HOOK_TOKEN = 'fallback-secret-token'
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
try {
const handler = await loadHandler()
await handler({ event: status('busy') })
await handler({ event: delta('still working') })
expect(warn).toHaveBeenCalledOnce()
expect(warn.mock.calls.flat().join(' ')).not.toContain('fallback-secret-token')
} finally {
warn.mockRestore()
}
})
it('preserves FIFO lifecycle order while the first session lookup is delayed', async () => {
let releaseFirstLookup: (() => void) | undefined
const firstLookup = new Promise<void>((resolve) => {
releaseFirstLookup = resolve
})
let notifyFirstLookupStarted: (() => void) | undefined
const firstLookupStarted = new Promise<void>((resolve) => {
notifyFirstLookupStarted = resolve
})
let calls = 0
const list = vi.fn(async () => {
calls += 1
if (calls === 1) {
notifyFirstLookupStarted?.()
await firstLookup
}
return { data: [{ id: 'root' }] }
})
const handler = await loadHandler(list)
const busy = handler({ event: status('busy') })
await firstLookupStarted
const idle = handler({ event: status('idle') })
try {
// OpenCode does not await hooks; later idle lookup must not overtake blocked busy lookup.
expect(list).toHaveBeenCalledTimes(1)
expect(posts).toHaveLength(0)
} finally {
releaseFirstLookup?.()
}
await Promise.all([busy, idle])
expect(names()).toEqual(['SessionBusy', 'SessionIdle'])
})
it('retries an undelivered Busy transition after a non-2xx response', async () => {
vi.useFakeTimers()
let attempts = 0
globalThis.fetch = vi.fn(async (_url: RequestInfo | URL, init?: RequestInit) => {
posts.push(readPayload(init))
attempts += 1
return new Response(null, { status: attempts === 1 ? 503 : 204 })
}) as typeof globalThis.fetch
const handler = await loadHandler()
await handler({ event: status('busy') })
expect(names()).toEqual(['SessionBusy'])
await vi.advanceTimersByTimeAsync(499)
expect(names()).toEqual(['SessionBusy'])
await vi.advanceTimersByTimeAsync(1)
expect(names()).toEqual(['SessionBusy', 'SessionBusy'])
await vi.advanceTimersByTimeAsync(60_000)
expect(names()).toEqual(['SessionBusy', 'SessionBusy'])
})
it('aborts a hung Busy post before delivering the queued Idle transition', async () => {
vi.useFakeTimers()
let attempts = 0
let firstSignal: AbortSignal | undefined
let notifyFirstFetchStarted: (() => void) | undefined
const firstFetchStarted = new Promise<void>((resolve) => {
notifyFirstFetchStarted = resolve
})
globalThis.fetch = vi.fn((_url: RequestInfo | URL, init?: RequestInit) => {
posts.push(readPayload(init))
attempts += 1
if (attempts > 1) {
return Promise.resolve(new Response(null, { status: 204 }))
}
firstSignal = init?.signal ?? undefined
notifyFirstFetchStarted?.()
return new Promise<Response>((_resolve, reject) => {
init?.signal?.addEventListener('abort', () => reject(new Error('aborted')), {
once: true
})
})
}) as typeof globalThis.fetch
const handler = await loadHandler()
const busy = handler({ event: status('busy') })
const idle = handler({ event: status('idle') })
await firstFetchStarted
expect(firstSignal).toBeDefined()
await vi.advanceTimersByTimeAsync(1_999)
expect(names()).toEqual(['SessionBusy'])
await vi.advanceTimersByTimeAsync(1)
await Promise.all([busy, idle])
expect(firstSignal?.aborted).toBe(true)
expect(names()).toEqual(['SessionBusy', 'SessionIdle'])
await vi.advanceTimersByTimeAsync(60_000)
expect(names()).toEqual(['SessionBusy', 'SessionIdle'])
})
it('lets Idle supersede a pending Busy retry', async () => {
vi.useFakeTimers()
globalThis.fetch = vi.fn(async (_url: RequestInfo | URL, init?: RequestInit) => {
const payload = readPayload(init)
posts.push(payload)
return new Response(null, {
status: payload.hook_event_name === 'SessionBusy' ? 503 : 204
})
}) as typeof globalThis.fetch
const handler = await loadHandler()
await handler({ event: status('busy') })
await handler({ event: status('idle') })
expect(names()).toEqual(['SessionBusy', 'SessionIdle'])
await vi.advanceTimersByTimeAsync(60_000)
expect(names()).toEqual(['SessionBusy', 'SessionIdle'])
})
it('uses a current nonempty text delta to retry a dirty Busy transition immediately', async () => {
vi.useFakeTimers()
let attempts = 0
globalThis.fetch = vi.fn(async (_url: RequestInfo | URL, init?: RequestInit) => {
posts.push(readPayload(init))
attempts += 1
return new Response(null, { status: attempts === 1 ? 503 : 204 })
}) as typeof globalThis.fetch
const handler = await loadHandler()
await handler({ event: status('busy') })
expect(names()).toEqual(['SessionBusy'])
// Deltas after empty text-start parts must recover a lost Busy post.
await handler({ event: delta('hello') })
expect(names()).toEqual(['SessionBusy', 'SessionBusy'])
await vi.advanceTimersByTimeAsync(60_000)
expect(names()).toEqual(['SessionBusy', 'SessionBusy'])
})
it('keeps backoff across OpenCode canonical and deprecated Idle duplicates', async () => {
vi.useFakeTimers()
let idleAttempts = 0
globalThis.fetch = vi.fn(async (_url: RequestInfo | URL, init?: RequestInit) => {
const payload = readPayload(init)
posts.push(payload)
if (payload.hook_event_name === 'SessionIdle') {
idleAttempts += 1
return new Response(null, { status: idleAttempts === 1 ? 503 : 204 })
}
return new Response(null, { status: 204 })
}) as typeof globalThis.fetch
const handler = await loadHandler()
await handler({ event: status('busy') })
await handler({ event: status('idle') })
await handler({
event: { type: 'session.idle', properties: { sessionID: 'root' } }
})
expect(names()).toEqual(['SessionBusy', 'SessionIdle'])
await vi.advanceTimersByTimeAsync(499)
expect(names()).toEqual(['SessionBusy', 'SessionIdle'])
await vi.advanceTimersByTimeAsync(1)
expect(names()).toEqual(['SessionBusy', 'SessionIdle', 'SessionIdle'])
})
it('uses repeated Busy evidence to retry the same dirty state immediately', async () => {
vi.useFakeTimers()
let attempts = 0
globalThis.fetch = vi.fn(async (_url: RequestInfo | URL, init?: RequestInit) => {
posts.push(readPayload(init))
attempts += 1
return new Response(null, { status: attempts === 1 ? 503 : 204 })
}) as typeof globalThis.fetch
const handler = await loadHandler()
await handler({ event: status('busy') })
await handler({ event: status('retry') })
expect(names()).toEqual(['SessionBusy', 'SessionBusy'])
await vi.advanceTimersByTimeAsync(60_000)
expect(names()).toEqual(['SessionBusy', 'SessionBusy'])
})
it('does not turn empty or non-text deltas into immediate retry traffic', async () => {
vi.useFakeTimers()
let attempts = 0
globalThis.fetch = vi.fn(async (_url: RequestInfo | URL, init?: RequestInit) => {
posts.push(readPayload(init))
attempts += 1
return new Response(null, { status: attempts === 1 ? 503 : 204 })
}) as typeof globalThis.fetch
const handler = await loadHandler()
await handler({ event: status('busy') })
await handler({ event: delta('reasoning', 'reasoning') })
await handler({ event: delta('') })
expect(names()).toEqual(['SessionBusy'])
await vi.advanceTimersByTimeAsync(499)
expect(names()).toEqual(['SessionBusy'])
await vi.advanceTimersByTimeAsync(1)
expect(names()).toEqual(['SessionBusy', 'SessionBusy'])
})
it('backs off exponentially and caps outage retries at thirty seconds', async () => {
vi.useFakeTimers()
globalThis.fetch = vi.fn(async (_url: RequestInfo | URL, init?: RequestInit) => {
posts.push(readPayload(init))
return new Response(null, { status: 503 })
}) as typeof globalThis.fetch
const handler = await loadHandler()
await handler({ event: status('busy') })
expect(names()).toHaveLength(1)
const retryDelays = [500, 1_000, 2_000, 4_000, 8_000, 16_000, 30_000, 30_000]
for (const [index, delay] of retryDelays.entries()) {
await vi.advanceTimersByTimeAsync(delay - 1)
expect(names()).toHaveLength(index + 1)
await vi.advanceTimersByTimeAsync(1)
expect(names()).toHaveLength(index + 2)
}
})
it('fails Busy open after a hung lookup and still lets queued Idle proceed', async () => {
vi.useFakeTimers()
let releaseLookup: (() => void) | undefined
const blockedLookup = new Promise<void>((resolve) => {
releaseLookup = resolve
})
let calls = 0
const list = vi.fn(async () => {
calls += 1
if (calls === 1) {
await blockedLookup
}
return { data: [{ id: 'root' }] }
})
const handler = await loadHandler(list)
const busy = handler({ event: status('busy') })
const idle = handler({ event: status('idle') })
await vi.advanceTimersByTimeAsync(1_999)
expect(list).toHaveBeenCalledTimes(1)
expect(posts).toHaveLength(0)
await vi.advanceTimersByTimeAsync(1)
try {
expect(list).toHaveBeenCalledTimes(2)
// Child activity safely marks its root busy; idle still requires confirmed root ownership.
expect(names()).toEqual(['SessionBusy', 'SessionIdle'])
} finally {
releaseLookup?.()
}
await Promise.all([busy, idle])
})
it('aborts a hung current-SDK point lookup through its second options argument', async () => {
vi.useFakeTimers()
let capturedParameters: unknown
let capturedSignal: AbortSignal | undefined
function get(parameters: unknown, options: { signal?: AbortSignal }) {
capturedParameters = parameters
capturedSignal = options?.signal
return rejectWhenAborted(capturedSignal)
}
const hooks = await loadHooksWithSession({
get,
list: async () => ({ data: [{ id: 'root' }] })
})
const busy = hooks.event({ event: status('busy') })
await vi.advanceTimersByTimeAsync(2_000)
await busy
expect(capturedParameters).toEqual({ sessionID: 'root' })
expect(capturedSignal?.aborted).toBe(true)
expect(names()).toEqual(['SessionBusy'])
})
it('aborts a hung legacy-SDK point lookup through its one-object argument', async () => {
vi.useFakeTimers()
let capturedOptions: { path?: { id?: string }; signal?: AbortSignal } | undefined
function get(options: { path?: { id?: string }; signal?: AbortSignal }) {
capturedOptions = options
return rejectWhenAborted(options.signal)
}
const hooks = await loadHooksWithSession({
get,
list: async () => ({ data: [{ id: 'root' }] })
})
const busy = hooks.event({ event: status('busy') })
await vi.advanceTimersByTimeAsync(2_000)
await busy
expect(capturedOptions?.path).toEqual({ id: 'root' })
expect(capturedOptions?.signal?.aborted).toBe(true)
expect(names()).toEqual(['SessionBusy'])
})
it('aborts a hung current-SDK list fallback through its second options argument', async () => {
vi.useFakeTimers()
let capturedParameters: unknown
let capturedSignal: AbortSignal | undefined
function list(parameters: unknown, options: { signal?: AbortSignal }) {
capturedParameters = parameters
capturedSignal = options?.signal
return rejectWhenAborted(capturedSignal)
}
const hooks = await loadHooksWithSession({ list })
const busy = hooks.event({ event: status('busy') })
await vi.advanceTimersByTimeAsync(2_000)
await busy
expect(capturedParameters).toEqual({})
expect(capturedSignal?.aborted).toBe(true)
expect(names()).toEqual(['SessionBusy'])
})
it('aborts a hung legacy-SDK list fallback through its one-object argument', async () => {
vi.useFakeTimers()
let capturedOptions: { signal?: AbortSignal } | undefined
function list(options: { signal?: AbortSignal }) {
capturedOptions = options
return rejectWhenAborted(options.signal)
}
const hooks = await loadHooksWithSession({ list })
const busy = hooks.event({ event: status('busy') })
await vi.advanceTimersByTimeAsync(2_000)
await busy
expect(capturedOptions?.signal?.aborted).toBe(true)
expect(names()).toEqual(['SessionBusy'])
})
it('does not let a failed Busy retry overwrite delivered permission attention', async () => {
vi.useFakeTimers()
globalThis.fetch = vi.fn(async (_url: RequestInfo | URL, init?: RequestInit) => {
const payload = readPayload(init)
posts.push(payload)
const firstBusy = payload.hook_event_name === 'SessionBusy' && names().length === 1
return new Response(null, { status: firstBusy ? 503 : 204 })
}) as typeof globalThis.fetch
const handler = await loadHandler()
await handler({ event: status('busy') })
await handler({
event: { type: 'permission.asked', properties: { id: 'permission-1', sessionID: 'root' } }
})
expect(names()).toEqual(['SessionBusy', 'PermissionRequest'])
await vi.advanceTimersByTimeAsync(60_000)
expect(names()).toEqual(['SessionBusy', 'PermissionRequest'])
})
it('coalesces sustained text-delta recovery before returning to backoff', async () => {
vi.useFakeTimers()
let attempts = 0
globalThis.fetch = vi.fn(async (_url: RequestInfo | URL, init?: RequestInit) => {
posts.push(readPayload(init))
attempts += 1
return new Response(null, { status: attempts < 3 ? 503 : 204 })
}) as typeof globalThis.fetch
const handler = await loadHandler()
await handler({ event: status('busy') })
await handler({ event: delta('stream-0') })
for (let index = 1; index < 50; index += 1) {
await handler({ event: delta(`stream-${String(index)}`) })
}
expect(names()).toEqual(['SessionBusy', 'SessionBusy'])
await vi.advanceTimersByTimeAsync(999)
expect(names()).toHaveLength(2)
await vi.advanceTimersByTimeAsync(1)
expect(names()).toEqual(['SessionBusy', 'SessionBusy', 'SessionBusy'])
})
it('cancels lifecycle retries when OpenCode disposes the plugin', async () => {
vi.useFakeTimers()
globalThis.fetch = vi.fn(async (_url: RequestInfo | URL, init?: RequestInit) => {
posts.push(readPayload(init))
return new Response(null, { status: 503 })
}) as typeof globalThis.fetch
const hooks = await loadHooks()
await hooks.event({ event: status('busy') })
expect(hooks.dispose).toBeTypeOf('function')
await hooks.dispose?.()
await vi.advanceTimersByTimeAsync(60_000)
expect(names()).toEqual(['SessionBusy'])
})
it('publishes final Idle when the last busy factory is disposed', async () => {
const hooks = await loadHooks()
await hooks.event({ event: status('busy') })
await hooks.dispose?.()
expect(names()).toEqual(['SessionBusy', 'SessionIdle'])
})
it('publishes final Idle when MessagePart alone made the disposed factory Working', async () => {
const hooks = await loadHooks()
await hooks.event({
event: {
type: 'message.updated',
properties: { sessionID: 'root', info: { id: 'user-message', role: 'user' } }
}
})
await hooks.event({
event: {
type: 'message.part.updated',
properties: {
sessionID: 'root',
part: { type: 'text', text: 'prompt before busy', messageID: 'user-message' }
}
}
})
await hooks.dispose?.()
expect(names()).toEqual(['MessagePart', 'SessionIdle'])
})
it('reasserts an already-delivered Idle after a later MessagePart', async () => {
const hooks = await loadHooks()
await hooks.event({ event: status('busy') })
await hooks.event({ event: status('idle') })
await hooks.event({
event: {
type: 'message.updated',
properties: { sessionID: 'root', info: { id: 'user-message', role: 'user' } }
}
})
await hooks.event({
event: {
type: 'message.part.updated',
properties: {
sessionID: 'root',
part: { type: 'text', text: 'late prompt', messageID: 'user-message' }
}
}
})
await hooks.dispose?.()
expect(names()).toEqual(['SessionBusy', 'SessionIdle', 'MessagePart', 'SessionIdle'])
})
it('lets OpenCode duplicate Idle supersede a later-delivered MessagePart', async () => {
const hooks = await loadHooks()
await hooks.event({ event: status('busy') })
await hooks.event({ event: status('idle') })
await hooks.event({
event: {
type: 'message.updated',
properties: { sessionID: 'root', info: { id: 'user-message', role: 'user' } }
}
})
await hooks.event({
event: {
type: 'message.part.updated',
properties: {
sessionID: 'root',
part: { type: 'text', text: 'late prompt', messageID: 'user-message' }
}
}
})
await hooks.event({ event: { type: 'session.idle', properties: { sessionID: 'root' } } })
expect(names()).toEqual(['SessionBusy', 'SessionIdle', 'MessagePart', 'SessionIdle'])
})
it('does not treat a failed MessagePart attempt as delivered Working authority', async () => {
globalThis.fetch = vi.fn(async (_url: RequestInfo | URL, init?: RequestInit) => {
const payload = readPayload(init)
posts.push(payload)
return new Response(null, {
status: payload.hook_event_name === 'MessagePart' ? 503 : 204
})
}) as typeof globalThis.fetch
const hooks = await loadHooks()
await hooks.event({
event: {
type: 'message.updated',
properties: { sessionID: 'root', info: { id: 'user-message', role: 'user' } }
}
})
await hooks.event({
event: {
type: 'message.part.updated',
properties: {
sessionID: 'root',
part: { type: 'text', text: 'undelivered prompt', messageID: 'user-message' }
}
}
})
await hooks.dispose?.()
expect(names()).toEqual(['MessagePart'])
})
it('does not publish a MessagePart after its factory is disposed during lookup', async () => {
let releaseLookup: (() => void) | undefined
const blockedLookup = new Promise<void>((resolve) => {
releaseLookup = resolve
})
let calls = 0
const list = vi.fn(async () => {
calls += 1
if (calls === 2) {
await blockedLookup
}
return { data: [{ id: 'seed' }, { id: 'root' }] }
})
const hooks = await loadHooks(list)
await hooks.event({
event: {
type: 'message.updated',
properties: { sessionID: 'seed', info: { id: 'user-message', role: 'user' } }
}
})
const latePart = hooks.event({
event: {
type: 'message.part.updated',
properties: {
sessionID: 'root',
part: { type: 'text', text: 'late prompt', messageID: 'user-message' }
}
}
})
await vi.waitFor(() => expect(list).toHaveBeenCalledTimes(2))
await hooks.dispose?.()
releaseLookup?.()
await latePart
expect(names()).toEqual([])
})
it('drops a disposed factory pending preview while another factory stays active', async () => {
vi.useFakeTimers()
const first = await loadHooks()
const second = await loadHooks()
await first.event({
event: {
type: 'message.updated',
properties: {
sessionID: 'root',
info: { id: 'assistant-message', role: 'assistant' }
}
}
})
const part = (text: string): PluginEvent => ({
type: 'message.part.updated',
properties: {
sessionID: 'root',
part: { type: 'text', text, messageID: 'assistant-message' }
}
})
await first.event({ event: part('first preview') })
await first.event({ event: part('pending preview') })
await first.dispose?.()
await vi.advanceTimersByTimeAsync(1_000)
await second.dispose?.()
expect(names()).toEqual(['MessagePart', 'SessionIdle'])
})
it('keeps the pane Busy until every concurrent root session is idle', async () => {
const sessions = [{ id: 'root-a' }, { id: 'root-b' }]
const handler = await loadHandler(async () => ({ data: sessions }))
await handler({ event: status('busy', 'root-a') })
await handler({ event: status('busy', 'root-b') })
await handler({ event: status('idle', 'root-a') })
expect(names()).not.toContain('SessionIdle')
await handler({ event: status('idle', 'root-b') })
expect(names().filter((name) => name === 'SessionIdle')).toHaveLength(1)
expect(names().at(-1)).toBe('SessionIdle')
})
it('reasserts Busy through the refreshed endpoint after a live text delta', async () => {
const deliveries: { url: string; token: string | null }[] = []
globalThis.fetch = vi.fn(async (url: RequestInfo | URL, init?: RequestInit) => {
posts.push(readPayload(init))
deliveries.push({
url: String(url),
token: new Headers(init?.headers).get('X-Orca-Agent-Hook-Token')
})
return new Response(null, { status: 204 })
}) as typeof globalThis.fetch
const handler = await loadHandler()
await handler({ event: status('busy') })
process.env.ORCA_AGENT_HOOK_PORT = '56789'
process.env.ORCA_AGENT_HOOK_TOKEN = 'refreshed-token'
await handler({ event: delta('still working') })
expect(names()).toEqual(['SessionBusy', 'SessionBusy'])
expect(deliveries).toEqual([
{ url: 'http://127.0.0.1:45678/hook/opencode', token: 'test-token' },
{ url: 'http://127.0.0.1:56789/hook/opencode', token: 'refreshed-token' }
])
})
it('clears unanswered question attention on authoritative root Idle', async () => {
const handler = await loadHandler()
await handler({ event: status('busy') })
await handler({
event: { type: 'question.asked', properties: { id: 'question-1', sessionID: 'root' } }
})
expect(names().at(-1)).toBe('AskUserQuestion')
// OpenCode can finish the question tool without question.replied.
await handler({ event: status('idle') })
expect(names().at(-1)).toBe('SessionIdle')
})
})