perf(windows): fix 60s startup ACL walk and OpenCode streaming freeze, with benchmark harnesses (#5124)
This commit is contained in:
@@ -0,0 +1,203 @@
|
||||
/**
|
||||
* Executes the generated OpenCode plugin source (the artifact that runs inside
|
||||
* OpenCode's process) to verify streamed message.part.updated events are
|
||||
* coalesced and capped before POSTing to Orca's agent-hook server. The
|
||||
* un-throttled plugin re-posted the full accumulated reply per streamed
|
||||
* append — O(n²) bytes per turn — which saturated Orca's main + renderer
|
||||
* event loops on Windows and froze the UI mid-reply.
|
||||
*/
|
||||
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 RecordedPost = {
|
||||
url: string
|
||||
body: {
|
||||
paneKey: string
|
||||
payload: { hook_event_name: string; role?: string; text?: string }
|
||||
}
|
||||
}
|
||||
|
||||
type PluginEventHandler = (input: { event: unknown }) => Promise<void>
|
||||
|
||||
const ENV_KEYS = ['ORCA_PANE_KEY', 'ORCA_AGENT_HOOK_PORT', 'ORCA_AGENT_HOOK_TOKEN'] as const
|
||||
|
||||
describe('OpenCode plugin MessagePart throttling', () => {
|
||||
let tempDir: string
|
||||
let posts: RecordedPost[]
|
||||
let savedEnv: Record<string, string | undefined>
|
||||
let savedFetch: typeof globalThis.fetch
|
||||
|
||||
beforeEach(() => {
|
||||
tempDir = mkdtempSync(join(tmpdir(), 'orca-opencode-plugin-test-'))
|
||||
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'
|
||||
savedFetch = globalThis.fetch
|
||||
globalThis.fetch = vi.fn(async (url: RequestInfo | URL, init?: RequestInit) => {
|
||||
posts.push({ url: String(url), body: JSON.parse(String(init?.body)) })
|
||||
return new Response(null, { status: 204 })
|
||||
}) as typeof globalThis.fetch
|
||||
vi.useFakeTimers()
|
||||
})
|
||||
|
||||
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 })
|
||||
})
|
||||
|
||||
async function loadPluginEventHandler(): Promise<PluginEventHandler> {
|
||||
const pluginPath = join(tempDir, 'orca-opencode-status.mjs')
|
||||
writeFileSync(pluginPath, _internals.getOpenCodePluginSource())
|
||||
const module = (await import(pathToFileURL(pluginPath).href)) as {
|
||||
OrcaOpenCodeStatusPlugin: (ctx: unknown) => Promise<{ event: PluginEventHandler }>
|
||||
}
|
||||
const client = {
|
||||
session: {
|
||||
// No parentID → root session, events flow through.
|
||||
list: async () => ({ data: [{ id: 'session-1' }] })
|
||||
}
|
||||
}
|
||||
const hooks = await module.OrcaOpenCodeStatusPlugin({ client })
|
||||
return hooks.event
|
||||
}
|
||||
|
||||
function assistantPartEvent(text: string): { event: unknown } {
|
||||
return {
|
||||
event: {
|
||||
type: 'message.part.updated',
|
||||
properties: {
|
||||
sessionID: 'session-1',
|
||||
part: { type: 'text', text, messageID: 'msg-assistant' }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function seedAssistantRole(handler: PluginEventHandler): Promise<void> {
|
||||
await handler({
|
||||
event: {
|
||||
type: 'message.updated',
|
||||
properties: {
|
||||
sessionID: 'session-1',
|
||||
info: { id: 'msg-assistant', role: 'assistant' }
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
function messagePartPosts(): RecordedPost[] {
|
||||
return posts.filter((post) => post.body.payload.hook_event_name === 'MessagePart')
|
||||
}
|
||||
|
||||
it('coalesces a streamed reply into leading + trailing posts with capped text', async () => {
|
||||
const handler = await loadPluginEventHandler()
|
||||
await seedAssistantRole(handler)
|
||||
|
||||
// Simulate a streaming turn: 50 part updates, each carrying the full
|
||||
// accumulated text so far (how OpenCode actually publishes parts).
|
||||
let text = ''
|
||||
for (let i = 0; i < 50; i++) {
|
||||
text += 'chunk-of-streamed-reply-text-'.repeat(10)
|
||||
await handler(assistantPartEvent(text))
|
||||
}
|
||||
|
||||
// Leading edge only — everything else is pending behind the throttle.
|
||||
expect(messagePartPosts()).toHaveLength(1)
|
||||
|
||||
await vi.advanceTimersByTimeAsync(300)
|
||||
|
||||
const parts = messagePartPosts()
|
||||
expect(parts).toHaveLength(2)
|
||||
// Trailing post carries the LATEST snapshot, capped.
|
||||
const trailing = parts[1].body.payload
|
||||
expect(trailing.text!.length).toBeLessThanOrEqual(4000)
|
||||
expect(text.startsWith(trailing.text!)).toBe(true)
|
||||
})
|
||||
|
||||
it('flushes the pending reply snapshot before posting SessionIdle', async () => {
|
||||
const handler = await loadPluginEventHandler()
|
||||
await seedAssistantRole(handler)
|
||||
// Mark the session busy so the idle transition is not deduped away.
|
||||
await handler({
|
||||
event: {
|
||||
type: 'session.status',
|
||||
properties: { sessionID: 'session-1', status: { type: 'busy' } }
|
||||
}
|
||||
})
|
||||
posts.length = 0
|
||||
|
||||
await handler(assistantPartEvent('first'))
|
||||
await handler(assistantPartEvent('first final'))
|
||||
expect(messagePartPosts()).toHaveLength(1)
|
||||
|
||||
await handler({
|
||||
event: { type: 'session.idle', properties: { sessionID: 'session-1' } }
|
||||
})
|
||||
|
||||
const eventNames = posts.map((post) => post.body.payload.hook_event_name)
|
||||
expect(eventNames).toEqual(['MessagePart', 'MessagePart', 'SessionIdle'])
|
||||
expect(posts[1].body.payload.text).toBe('first final')
|
||||
})
|
||||
|
||||
it('posts user prompts immediately without consuming the assistant throttle slot', async () => {
|
||||
const handler = await loadPluginEventHandler()
|
||||
await handler({
|
||||
event: {
|
||||
type: 'message.updated',
|
||||
properties: {
|
||||
sessionID: 'session-1',
|
||||
info: { id: 'msg-user', role: 'user' }
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
await handler({
|
||||
event: {
|
||||
type: 'message.part.updated',
|
||||
properties: {
|
||||
sessionID: 'session-1',
|
||||
part: { type: 'text', text: 'u'.repeat(10_000), messageID: 'msg-user' }
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
const parts = messagePartPosts()
|
||||
expect(parts).toHaveLength(1)
|
||||
expect(parts[0].body.payload.role).toBe('user')
|
||||
expect(parts[0].body.payload.text!.length).toBe(4000)
|
||||
|
||||
// An assistant part right after the user prompt still posts immediately
|
||||
// (leading edge) because user posts do not touch the throttle clock.
|
||||
await seedAssistantRole(handler)
|
||||
await handler(assistantPartEvent('assistant reply'))
|
||||
expect(messagePartPosts()).toHaveLength(2)
|
||||
})
|
||||
})
|
||||
@@ -114,8 +114,10 @@ describe('OpenCode hook plugin source', () => {
|
||||
const source = _internals.getOpenCodePluginSource()
|
||||
|
||||
expect(source).toContain(
|
||||
'await post("MessagePart", { role, text: part.text, messageID: part.messageID, sessionID });'
|
||||
'await post("MessagePart", { role, text: capMessagePartText(part.text), messageID: part.messageID, sessionID });'
|
||||
)
|
||||
expect(source).toContain('messageID: pending.messageID,')
|
||||
expect(source).toContain('sessionID: pending.sessionID,')
|
||||
expect(source).toContain('await setStatus("busy", { sessionID });')
|
||||
expect(source.match(/await setStatus\("idle", \{ sessionID \}\);/g) ?? []).toHaveLength(2)
|
||||
})
|
||||
|
||||
@@ -160,6 +160,57 @@ function getOpenCodePluginSource(): string {
|
||||
'let lastStatus = "idle";',
|
||||
'const childSessionById = new Map();',
|
||||
'',
|
||||
'// Why: message.part.updated re-sends the FULL accumulated text of the part',
|
||||
'// after every streamed append, so posting each event forwards O(n^2) bytes',
|
||||
'// per turn through Orca (loopback HTTP -> main JSON parse -> status compare',
|
||||
'// -> IPC -> renderer store update -> React commit). On Windows that flood',
|
||||
'// saturated both event loops and froze the whole UI a few seconds into a',
|
||||
'// streaming reply. The dashboard only needs a bounded preview at a human',
|
||||
'// cadence: cap the text and trailing-edge coalesce assistant parts.',
|
||||
'const MESSAGE_PART_THROTTLE_MS = 250;',
|
||||
'const MESSAGE_PART_MAX_CHARS = 4000;',
|
||||
'let pendingAssistantPart = null;',
|
||||
'let assistantPartFlushTimer = null;',
|
||||
'let lastAssistantPartPostAt = 0;',
|
||||
'',
|
||||
'function capMessagePartText(text) {',
|
||||
' return text.length > MESSAGE_PART_MAX_CHARS ? text.slice(0, MESSAGE_PART_MAX_CHARS) : text;',
|
||||
'}',
|
||||
'',
|
||||
'async function flushPendingAssistantPart() {',
|
||||
' if (assistantPartFlushTimer) {',
|
||||
' clearTimeout(assistantPartFlushTimer);',
|
||||
' assistantPartFlushTimer = null;',
|
||||
' }',
|
||||
' const pending = pendingAssistantPart;',
|
||||
' pendingAssistantPart = null;',
|
||||
' if (!pending) return;',
|
||||
' lastAssistantPartPostAt = Date.now();',
|
||||
' await post("MessagePart", {',
|
||||
' role: pending.role,',
|
||||
' text: capMessagePartText(pending.text),',
|
||||
' messageID: pending.messageID,',
|
||||
' sessionID: pending.sessionID,',
|
||||
' });',
|
||||
'}',
|
||||
'',
|
||||
'function queueAssistantPart(part) {',
|
||||
' // Why: keep only the latest snapshot — each event already contains the',
|
||||
' // full accumulated text, so intermediate snapshots are pure waste.',
|
||||
' pendingAssistantPart = part;',
|
||||
' const sinceLastPost = Date.now() - lastAssistantPartPostAt;',
|
||||
' if (sinceLastPost >= MESSAGE_PART_THROTTLE_MS) {',
|
||||
' void flushPendingAssistantPart();',
|
||||
' return;',
|
||||
' }',
|
||||
' if (!assistantPartFlushTimer) {',
|
||||
' assistantPartFlushTimer = setTimeout(() => {',
|
||||
' void flushPendingAssistantPart();',
|
||||
' }, MESSAGE_PART_THROTTLE_MS - sinceLastPost);',
|
||||
' if (assistantPartFlushTimer.unref) assistantPartFlushTimer.unref();',
|
||||
' }',
|
||||
'}',
|
||||
'',
|
||||
'// Why: message.part.updated fires for every Part (text, tool, reasoning)',
|
||||
'// but does not include the message role — that lives on the parent',
|
||||
'// message.updated event. Cache the role per messageID so the plugin can',
|
||||
@@ -312,11 +363,21 @@ function getOpenCodePluginSource(): string {
|
||||
' if (!part || part.type !== "text" || !part.text) return;',
|
||||
' const role = messageRoleById.get(part.messageID);',
|
||||
' if (!role) return;',
|
||||
' await post("MessagePart", { role, text: part.text, messageID: part.messageID, sessionID });',
|
||||
' if (role === "user") {',
|
||||
' // Why: user prompts arrive as a single event, not a stream — post',
|
||||
' // immediately (still capped) so the throttle slot stays free for',
|
||||
' // the assistant reply that follows within the same window.',
|
||||
' await post("MessagePart", { role, text: capMessagePartText(part.text), messageID: part.messageID, sessionID });',
|
||||
' return;',
|
||||
' }',
|
||||
' queueAssistantPart({ role, text: part.text, messageID: part.messageID, sessionID });',
|
||||
' return;',
|
||||
' }',
|
||||
'',
|
||||
' if (event.type === "session.idle" || event.type === "session.error") {',
|
||||
' // Why: flush the coalesced final reply snapshot before the idle',
|
||||
' // transition so the done-state preview shows the completed message.',
|
||||
' await flushPendingAssistantPart();',
|
||||
' await setStatus("idle", { sessionID });',
|
||||
' return;',
|
||||
' }',
|
||||
|
||||
Reference in New Issue
Block a user