mirror of
https://github.com/wu736139669/hapi.git
synced 2026-11-24 04:47:03 +00:00
feat(opencode): show round usage and tokens per second (#1668)
This commit is contained in:
@@ -2,10 +2,14 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { MessageQueue2 } from '@/utils/MessageQueue2';
|
||||
import { MessageBuffer } from '@/ui/ink/messageBuffer';
|
||||
import type { OpencodeMode, PermissionMode } from './types';
|
||||
import { RPC_METHODS } from '@hapi/protocol/rpcMethods';
|
||||
import { getOpencodeNativeToolInstruction } from './utils/systemPrompt';
|
||||
import type { PromptContent } from '@/agent/types';
|
||||
import { ACP_INDETERMINATE_SYMBOL } from '@/agent/backends/acp/AcpStdioTransport';
|
||||
|
||||
|
||||
const harness = vi.hoisted(() => ({
|
||||
transcriptFetchImpl: null as null | (() => Promise<Response>),
|
||||
servePid: null as number | null,
|
||||
servePidCalls: [] as number[][],
|
||||
setModelArgs: [] as Array<{ sessionId: string; modelId: string; flavor?: string }>,
|
||||
@@ -291,7 +295,9 @@ vi.mock('./utils/opencodeNativeTranscript', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('./utils/opencodeNativeTranscript')>();
|
||||
return { OpencodeNativeTranscript: class extends actual.OpencodeNativeTranscript {
|
||||
constructor(options: ConstructorParameters<typeof actual.OpencodeNativeTranscript>[0]) {
|
||||
super({ ...options, fetchImpl: (async () => Response.json([])) });
|
||||
super({ ...options, fetchImpl: async () => harness.transcriptFetchImpl
|
||||
? await harness.transcriptFetchImpl()
|
||||
: Response.json([]) });
|
||||
}
|
||||
} };
|
||||
});
|
||||
@@ -380,6 +386,40 @@ vi.mock('./utils/opencodeCompactBridge', () => ({
|
||||
})
|
||||
}));
|
||||
|
||||
const roundSummaryHarness = vi.hoisted(() => ({
|
||||
snapshotCalls: [] as Array<{ baseUrl: string; sessionId: string }>,
|
||||
summaryCalls: [] as Array<{ promptText: string; durationMs: number; snapshot: { messageIds: string[] } }>,
|
||||
snapshot: { messageIds: [] } as { messageIds: string[] } | null,
|
||||
snapshotImpl: null as null | (() => Promise<unknown>),
|
||||
summary: {
|
||||
usage: { inputTokens: 10, outputTokens: 2, cacheReadInputTokens: 0, cacheCreationInputTokens: 0 },
|
||||
modelUsage: { 'openai/gpt-5.4': { inputTokens: 10, outputTokens: 2, cacheReadInputTokens: 0, cacheCreationInputTokens: 0 } },
|
||||
numTurns: 1,
|
||||
durationMs: 10
|
||||
} as unknown | null,
|
||||
summaryImpl: null as null | ((opts: { promptText: string }) => Promise<unknown>)
|
||||
}));
|
||||
|
||||
vi.mock('./utils/opencodeRoundSummary', () => ({
|
||||
captureOpencodeRoundSnapshot: vi.fn(async (opts: { baseUrl: string; sessionId: string }) => {
|
||||
roundSummaryHarness.snapshotCalls.push(opts);
|
||||
if (roundSummaryHarness.snapshotImpl) return roundSummaryHarness.snapshotImpl();
|
||||
return roundSummaryHarness.snapshot;
|
||||
}),
|
||||
fetchOpencodeRoundSummary: vi.fn(async (opts: { promptText: string; durationMs: number; snapshot: { messageIds: string[] } }) => {
|
||||
roundSummaryHarness.summaryCalls.push(opts);
|
||||
const summary = roundSummaryHarness.summaryImpl
|
||||
? await roundSummaryHarness.summaryImpl(opts)
|
||||
: harness.events.lastIndexOf('prompt:start') > harness.events.lastIndexOf('prompt:end')
|
||||
? null
|
||||
: roundSummaryHarness.summary;
|
||||
return {
|
||||
snapshot: { messageIds: [...opts.snapshot.messageIds, 'post-' + roundSummaryHarness.summaryCalls.length] },
|
||||
summary
|
||||
};
|
||||
})
|
||||
}));
|
||||
|
||||
vi.mock('@/ui/logger', () => ({
|
||||
logger: {
|
||||
debug: vi.fn(),
|
||||
@@ -440,6 +480,7 @@ function createSessionStub(
|
||||
|
||||
const sessionEvents: Array<{ type: string; [key: string]: unknown }> = [];
|
||||
const sentAgentMessages: unknown[] = [];
|
||||
const deliveryEvents: string[] = [];
|
||||
const claudeSessionMessages: unknown[] = [];
|
||||
const rpcHandlers = new Map<string, (params: unknown) => unknown>();
|
||||
const setModelReasoningEffort = vi.fn();
|
||||
@@ -477,6 +518,7 @@ function createSessionStub(
|
||||
sendUserMessage(_text: string) {},
|
||||
sendSessionEvent(event: { type: string; [key: string]: unknown }) {
|
||||
sessionEvents.push(event);
|
||||
deliveryEvents.push('ready');
|
||||
},
|
||||
emitMessagesConsumed(localIds: string[], options?: { clearQueuedThinkingGrace?: boolean; steered?: boolean }) {
|
||||
emitMessagesConsumedCalls.push({ localIds, options });
|
||||
@@ -517,6 +559,7 @@ function createSessionStub(
|
||||
},
|
||||
sendAgentMessage(message: unknown) {
|
||||
sentAgentMessages.push(message);
|
||||
deliveryEvents.push('agent');
|
||||
},
|
||||
sendSessionEvent(event: { type: string; [key: string]: unknown }) {
|
||||
client.sendSessionEvent(event);
|
||||
@@ -524,7 +567,8 @@ function createSessionStub(
|
||||
sendUserMessage(_text: string) {}
|
||||
};
|
||||
|
||||
return { session, sessionEvents, sentAgentMessages, agentMessages: sentAgentMessages, claudeSessionMessages, rpcHandlers, setModel, setModelReasoningEffort, pushKeepAlive, emitMessagesConsumedCalls, thinkingChangeCalls, steeringActiveCalls, steerIndeterminateCalls, steerStateImpl };
|
||||
return { session, sessionEvents, sentAgentMessages, deliveryEvents, agentMessages: sentAgentMessages, claudeSessionMessages, rpcHandlers, setModel, setModelReasoningEffort, pushKeepAlive, emitMessagesConsumedCalls, thinkingChangeCalls, steeringActiveCalls, steerIndeterminateCalls, steerStateImpl };
|
||||
|
||||
}
|
||||
|
||||
function createCompactMode(model?: string): OpencodeMode {
|
||||
@@ -542,79 +586,91 @@ function createClearMode(): OpencodeMode {
|
||||
};
|
||||
}
|
||||
|
||||
describe('opencodeRemoteLauncher inline model switch', () => {
|
||||
afterEach(async () => {
|
||||
harness.setModelArgs = [];
|
||||
harness.setConfigOptionArgs = [];
|
||||
harness.promptCount = 0;
|
||||
harness.promptContents = [];
|
||||
harness.refreshSessionInfoCalls = [];
|
||||
harness.bridgeOptions = null;
|
||||
harness.events = [];
|
||||
harness.cleanupEvents = [];
|
||||
harness.setModelImpl = null;
|
||||
harness.setConfigOptionImpl = null;
|
||||
harness.thoughtLevelOption = null;
|
||||
harness.thoughtLevelLookups = [];
|
||||
harness.stderrHandler = null;
|
||||
harness.servePid = null;
|
||||
harness.servePidCalls = [];
|
||||
harness.hangPrompt = false;
|
||||
harness.resolvePrompt = null;
|
||||
harness.cancelPrompt.mockClear();
|
||||
compactHarness.calls = [];
|
||||
compactHarness.v2Calls = [];
|
||||
compactHarness.v2VerifyCalls = [];
|
||||
compactHarness.v2VerifyResult = { status: 'success', text: 'v2 summary text' };
|
||||
compactHarness.triggerImpl = null;
|
||||
compactHarness.pollImpl = null;
|
||||
compactHarness.operationEvents = [];
|
||||
compactHarness.result = { ok: true };
|
||||
compactHarness.markerSnapshotCalls = [];
|
||||
compactHarness.markerSnapshot = { markerIds: ['before-this-request'] };
|
||||
compactHarness.snapshotImpl = null;
|
||||
compactHarness.resultCalls = [];
|
||||
compactHarness.compactionResult = { status: 'success', text: '## Objective\n- Did the thing' };
|
||||
compactHarness.triggerImpl = null;
|
||||
compactHarness.resultImpl = null;
|
||||
harness.promptImpl = null;
|
||||
harness.promptOnMessage = null;
|
||||
harness.sessionModelsMetadata = undefined;
|
||||
harness.cancelPromptImpl = null;
|
||||
harness.newSessionImpl = null;
|
||||
harness.disconnectImpl = null;
|
||||
harness.permissionCancelError = null;
|
||||
harness.serverStopError = null;
|
||||
harness.eventStreamOptions = [];
|
||||
harness.eventStreamCloseCount = 0;
|
||||
harness.stderrHandler = null;
|
||||
harness.softSteerCalls = [];
|
||||
harness.softSteerDispatchError = null;
|
||||
harness.deferSoftSteerDispatch = null;
|
||||
harness.deferSoftSteer = null;
|
||||
harness.softSteerThrow = null;
|
||||
harness.deferSteerState = null;
|
||||
harness.steerStateCalls = [];
|
||||
harness.steerStateResult = true;
|
||||
harness.promptGeneration = 1;
|
||||
harness.abortSoftSteersCalls = 0;
|
||||
harness.promptRequestInFlight = null;
|
||||
harness.detectedVersion = null;
|
||||
harness.loopbackListeners = [];
|
||||
harness.discoveredPort = null;
|
||||
harness.discoveredPassword = null;
|
||||
harness.backendPid = 4242;
|
||||
harness.createBackendArgs = [];
|
||||
harness.v2DiscoveryCalls = [];
|
||||
harness.v2PasswordCalls = [];
|
||||
inkHarness.lastRenderProps = null;
|
||||
const backendModule = await import('./utils/opencodeBackend');
|
||||
const backendModuleFns = backendModule as unknown as Record<string, ReturnType<typeof vi.fn>>;
|
||||
for (const name of ['createOpencodeBackend', 'detectOpencodeFlavorVersion', 'discoverOpencodeV2RestPort', 'listLoopbackListeners']) {
|
||||
backendModuleFns[name]?.mockClear();
|
||||
}
|
||||
});
|
||||
afterEach(async () => {
|
||||
harness.transcriptFetchImpl = null;
|
||||
harness.setModelArgs = [];
|
||||
harness.setConfigOptionArgs = [];
|
||||
harness.promptCount = 0;
|
||||
harness.promptContents = [];
|
||||
harness.refreshSessionInfoCalls = [];
|
||||
harness.bridgeOptions = null;
|
||||
harness.events = [];
|
||||
harness.cleanupEvents = [];
|
||||
harness.setModelImpl = null;
|
||||
harness.setConfigOptionImpl = null;
|
||||
harness.thoughtLevelOption = null;
|
||||
harness.thoughtLevelLookups = [];
|
||||
harness.stderrHandler = null;
|
||||
harness.servePid = null;
|
||||
harness.servePidCalls = [];
|
||||
harness.hangPrompt = false;
|
||||
harness.resolvePrompt = null;
|
||||
harness.cancelPrompt.mockClear();
|
||||
compactHarness.calls = [];
|
||||
compactHarness.v2Calls = [];
|
||||
compactHarness.v2VerifyCalls = [];
|
||||
compactHarness.v2VerifyResult = { status: 'success', text: 'v2 summary text' };
|
||||
compactHarness.triggerImpl = null;
|
||||
compactHarness.pollImpl = null;
|
||||
compactHarness.operationEvents = [];
|
||||
compactHarness.result = { ok: true };
|
||||
compactHarness.markerSnapshotCalls = [];
|
||||
compactHarness.markerSnapshot = { markerIds: ['before-this-request'] };
|
||||
compactHarness.snapshotImpl = null;
|
||||
compactHarness.resultCalls = [];
|
||||
compactHarness.compactionResult = { status: 'success', text: '## Objective\n- Did the thing' };
|
||||
compactHarness.triggerImpl = null;
|
||||
compactHarness.resultImpl = null;
|
||||
harness.promptImpl = null;
|
||||
harness.promptOnMessage = null;
|
||||
harness.sessionModelsMetadata = undefined;
|
||||
harness.cancelPromptImpl = null;
|
||||
harness.newSessionImpl = null;
|
||||
harness.disconnectImpl = null;
|
||||
harness.permissionCancelError = null;
|
||||
harness.serverStopError = null;
|
||||
harness.eventStreamOptions = [];
|
||||
harness.eventStreamCloseCount = 0;
|
||||
roundSummaryHarness.snapshotCalls = [];
|
||||
roundSummaryHarness.summaryCalls = [];
|
||||
roundSummaryHarness.snapshot = { messageIds: [] };
|
||||
roundSummaryHarness.snapshotImpl = null;
|
||||
roundSummaryHarness.summary = {
|
||||
usage: { inputTokens: 10, outputTokens: 2, cacheReadInputTokens: 0, cacheCreationInputTokens: 0 },
|
||||
modelUsage: { 'openai/gpt-5.4': { inputTokens: 10, outputTokens: 2, cacheReadInputTokens: 0, cacheCreationInputTokens: 0 } },
|
||||
numTurns: 1,
|
||||
durationMs: 10
|
||||
};
|
||||
roundSummaryHarness.summaryImpl = null;
|
||||
harness.softSteerCalls = [];
|
||||
harness.softSteerDispatchError = null;
|
||||
harness.deferSoftSteerDispatch = null;
|
||||
harness.deferSoftSteer = null;
|
||||
harness.softSteerThrow = null;
|
||||
harness.deferSteerState = null;
|
||||
harness.steerStateCalls = [];
|
||||
harness.steerStateResult = true;
|
||||
harness.promptGeneration = 1;
|
||||
harness.abortSoftSteersCalls = 0;
|
||||
harness.promptRequestInFlight = null;
|
||||
harness.detectedVersion = null;
|
||||
harness.loopbackListeners = [];
|
||||
harness.discoveredPort = null;
|
||||
harness.discoveredPassword = null;
|
||||
harness.backendPid = 4242;
|
||||
harness.createBackendArgs = [];
|
||||
harness.v2DiscoveryCalls = [];
|
||||
harness.v2PasswordCalls = [];
|
||||
inkHarness.lastRenderProps = null;
|
||||
const backendModule = await import('./utils/opencodeBackend');
|
||||
const backendModuleFns = backendModule as unknown as Record<string, ReturnType<typeof vi.fn>>;
|
||||
for (const name of ['createOpencodeBackend', 'detectOpencodeFlavorVersion', 'discoverOpencodeV2RestPort', 'listLoopbackListeners']) {
|
||||
backendModuleFns[name]?.mockClear();
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
describe('opencodeRemoteLauncher inline model switch', () => {
|
||||
it('reaches /clear only after the earlier prompt settles, without starting another OpenCode turn', async () => {
|
||||
let resolvePrompt: (() => void) | null = null;
|
||||
harness.promptImpl = () => new Promise<void>((resolve) => {
|
||||
@@ -2636,6 +2692,275 @@ describe('selectAbortStatusMessage', () => {
|
||||
|
||||
expect(decision).toEqual({ message: 'Turn aborted', shouldClearThinking: true });
|
||||
});
|
||||
|
||||
it('sends the round summary before ready after a prompt settles', async () => {
|
||||
const { session, sentAgentMessages, sessionEvents, deliveryEvents } = createSessionStub([{ message: 'round prompt', mode: createMode() }]);
|
||||
|
||||
await opencodeRemoteLauncher(session as never);
|
||||
|
||||
expect(roundSummaryHarness.snapshotCalls).toHaveLength(1);
|
||||
expect(roundSummaryHarness.summaryCalls).toEqual([expect.objectContaining({ promptText: expect.stringContaining('round prompt') })]);
|
||||
expect(sentAgentMessages).toEqual([expect.objectContaining({ type: 'round-summary' })]);
|
||||
expect(sessionEvents).toEqual([{ type: 'ready' }]);
|
||||
expect(deliveryEvents).toEqual(['agent', 'ready']);
|
||||
});
|
||||
|
||||
it('reuses the previous post-fetch snapshot instead of blocking a second prompt on another pre-fetch', async () => {
|
||||
roundSummaryHarness.snapshotCalls = [];
|
||||
roundSummaryHarness.summaryCalls = [];
|
||||
const { session } = createSessionStub([
|
||||
{ message: 'first round', mode: createMode() },
|
||||
{ message: 'second round', mode: createMode() }
|
||||
]);
|
||||
|
||||
await opencodeRemoteLauncher(session as never);
|
||||
|
||||
expect(roundSummaryHarness.summaryCalls.map((call) => call.snapshot.messageIds)).toEqual([[], ['post-1']]);
|
||||
expect(roundSummaryHarness.snapshotCalls).toHaveLength(1);
|
||||
expect(roundSummaryHarness.summaryCalls).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('recaptures after an explicit compact invalidates the previous post-fetch snapshot', async () => {
|
||||
roundSummaryHarness.snapshotCalls = [];
|
||||
roundSummaryHarness.summaryCalls = [];
|
||||
harness.sessionModelsMetadata = { currentModelId: 'ollama/x', availableModels: [] };
|
||||
const { session } = createSessionStub([
|
||||
{ message: 'first round', mode: createMode('ollama/x') },
|
||||
{ message: '', mode: createCompactMode('ollama/x') },
|
||||
{ message: 'second round', mode: createMode('ollama/x') }
|
||||
]);
|
||||
|
||||
await opencodeRemoteLauncher(session as never);
|
||||
|
||||
expect(compactHarness.calls).toHaveLength(1);
|
||||
expect(roundSummaryHarness.snapshotCalls).toHaveLength(2);
|
||||
expect(roundSummaryHarness.summaryCalls.map((call) => call.snapshot.messageIds)).toEqual([[], []]);
|
||||
});
|
||||
|
||||
it('keeps prompt completion and ready when post-fetch summary aggregation fails', async () => {
|
||||
roundSummaryHarness.summary = null;
|
||||
const { session, sentAgentMessages, sessionEvents } = createSessionStub([{ message: 'no summary', mode: createMode() }]);
|
||||
|
||||
await opencodeRemoteLauncher(session as never);
|
||||
|
||||
expect(sentAgentMessages).toEqual([]);
|
||||
expect(sessionEvents).toEqual([{ type: 'ready' }]);
|
||||
});
|
||||
it('keeps the dequeued prompt and ready when pre-prompt snapshot metadata throws', async () => {
|
||||
roundSummaryHarness.snapshotImpl = async () => {
|
||||
throw new TypeError('malformed optional message metadata');
|
||||
};
|
||||
const promptCountBefore = harness.promptCount;
|
||||
const { session, sentAgentMessages, sessionEvents } = createSessionStub([
|
||||
{ message: 'prompt survives malformed snapshot', mode: createMode() }
|
||||
]);
|
||||
|
||||
try {
|
||||
await opencodeRemoteLauncher(session as never);
|
||||
} finally {
|
||||
roundSummaryHarness.snapshotImpl = null;
|
||||
}
|
||||
|
||||
expect(harness.promptCount).toBe(promptCountBefore + 1);
|
||||
expect(JSON.stringify(harness.promptContents)).toContain('prompt survives malformed snapshot');
|
||||
expect(sentAgentMessages).toEqual([]);
|
||||
expect(sessionEvents).toEqual([{ type: 'ready' }]);
|
||||
});
|
||||
|
||||
it('keeps ready unblocked when a summary fetch never settles', async () => {
|
||||
roundSummaryHarness.summaryImpl = () => new Promise<unknown>(() => {});
|
||||
const { session, sentAgentMessages, sessionEvents } = createSessionStub([{ message: 'stalled summary', mode: createMode() }]);
|
||||
|
||||
await opencodeRemoteLauncher(session as never);
|
||||
|
||||
expect(sentAgentMessages).toEqual([]);
|
||||
expect(sessionEvents).toEqual([{ type: 'ready' }]);
|
||||
});
|
||||
|
||||
it('preserves queued prompts when Stop arrives during post-prompt native transcript refresh', async () => {
|
||||
const transcriptRead: { release: (() => void) | null } = { release: null };
|
||||
let readHeld = false;
|
||||
harness.transcriptFetchImpl = async () => {
|
||||
if (!readHeld && harness.events.includes('prompt:end')) {
|
||||
readHeld = true;
|
||||
return new Promise<Response>((resolve) => {
|
||||
transcriptRead.release = () => resolve(Response.json([]));
|
||||
});
|
||||
}
|
||||
return Response.json([]);
|
||||
};
|
||||
const addMessage = vi.spyOn(MessageBuffer.prototype, 'addMessage');
|
||||
const { session, rpcHandlers } = createSessionStub([
|
||||
{ message: 'first prompt before transcript read', mode: createMode() }
|
||||
], { keepOpen: true });
|
||||
const launchPromise = opencodeRemoteLauncher(session as never);
|
||||
while (!transcriptRead.release || !rpcHandlers.has(RPC_METHODS.Abort)) {
|
||||
await new Promise<void>((resolve) => setImmediate(resolve));
|
||||
}
|
||||
session.queue.push('queued after transcript read', createMode());
|
||||
await (rpcHandlers.get(RPC_METHODS.Abort) as () => Promise<void>)();
|
||||
transcriptRead.release();
|
||||
for (let attempt = 0; attempt < 50 && !JSON.stringify(harness.promptContents).includes('queued after transcript read'); attempt++) {
|
||||
await new Promise<void>((resolve) => setImmediate(resolve));
|
||||
}
|
||||
session.queue.close();
|
||||
await launchPromise;
|
||||
try {
|
||||
expect(JSON.stringify(harness.promptContents)).toContain('queued after transcript read');
|
||||
expect(harness.cancelPrompt).not.toHaveBeenCalled();
|
||||
expect(addMessage).not.toHaveBeenCalledWith('Turn aborted', 'status');
|
||||
} finally {
|
||||
addMessage.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it('excludes native transcript read latency from round prompt duration', async () => {
|
||||
let clock = 0;
|
||||
const now = vi.spyOn(performance, 'now').mockImplementation(() => clock);
|
||||
harness.promptImpl = async () => { clock = 25; };
|
||||
harness.transcriptFetchImpl = async () => {
|
||||
if (harness.events.includes('prompt:end')) clock = 5025;
|
||||
return Response.json([]);
|
||||
};
|
||||
const { session } = createSessionStub([{ message: 'duration before transcript read', mode: createMode() }]);
|
||||
try {
|
||||
await opencodeRemoteLauncher(session as never);
|
||||
expect(roundSummaryHarness.summaryCalls[0]?.durationMs).toBe(25);
|
||||
} finally {
|
||||
now.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it('plain Stop during post-prompt summary settlement preserves the queued next prompt without reporting a false abort', async () => {
|
||||
roundSummaryHarness.summaryImpl = ({ promptText }) => {
|
||||
return promptText.includes('completed first prompt')
|
||||
? new Promise<unknown>(() => {})
|
||||
: Promise.resolve(null);
|
||||
};
|
||||
const addMessage = vi.spyOn(MessageBuffer.prototype, 'addMessage');
|
||||
const { session, rpcHandlers } = createSessionStub([
|
||||
{ message: 'completed first prompt', mode: createMode() }
|
||||
], { keepOpen: true });
|
||||
|
||||
const launchPromise = opencodeRemoteLauncher(session as never);
|
||||
while (
|
||||
!rpcHandlers.has(RPC_METHODS.Abort)
|
||||
|| !roundSummaryHarness.summaryCalls.some(({ promptText }) => promptText.includes('completed first prompt'))
|
||||
) {
|
||||
await new Promise<void>((resolve) => setImmediate(resolve));
|
||||
}
|
||||
expect(harness.events).toContain('prompt:end');
|
||||
|
||||
session.queue.push('queued second prompt', createMode());
|
||||
const abortHandler = rpcHandlers.get(RPC_METHODS.Abort) as (() => Promise<void>) | undefined;
|
||||
expect(abortHandler).toBeDefined();
|
||||
await abortHandler!();
|
||||
for (let attempt = 0; attempt < 50 && !JSON.stringify(harness.promptContents).includes('queued second prompt'); attempt++) {
|
||||
await new Promise<void>((resolve) => setImmediate(resolve));
|
||||
}
|
||||
session.queue.close();
|
||||
await launchPromise;
|
||||
|
||||
expect(JSON.stringify(harness.promptContents)).toContain('queued second prompt');
|
||||
expect(harness.cancelPrompt).not.toHaveBeenCalled();
|
||||
expect(addMessage).not.toHaveBeenCalledWith('Turn aborted', 'status');
|
||||
addMessage.mockRestore();
|
||||
});
|
||||
|
||||
it('attempts and delivers a summary after a caught prompt error', async () => {
|
||||
harness.promptImpl = async () => { throw new Error('fixture prompt failure'); };
|
||||
roundSummaryHarness.summaryImpl = async () => ({
|
||||
usage: { inputTokens: 10, outputTokens: 2, cacheReadInputTokens: 0, cacheCreationInputTokens: 0 },
|
||||
modelUsage: { 'openai/gpt-5.4': { inputTokens: 10, outputTokens: 2, cacheReadInputTokens: 0, cacheCreationInputTokens: 0 } },
|
||||
numTurns: 1,
|
||||
durationMs: 10
|
||||
});
|
||||
const { session, agentMessages, sessionEvents } = createSessionStub([{ message: 'error summary', mode: createMode() }]);
|
||||
|
||||
await opencodeRemoteLauncher(session as never);
|
||||
expect(roundSummaryHarness.snapshotCalls.length).toBeGreaterThan(0);
|
||||
expect(roundSummaryHarness.summaryCalls.length).toBeGreaterThan(0);
|
||||
|
||||
expect(agentMessages).toEqual([
|
||||
expect.objectContaining({ type: 'error' }),
|
||||
expect.objectContaining({ type: 'round-summary' })
|
||||
]);
|
||||
expect(sessionEvents).toEqual([{ type: 'ready' }]);
|
||||
});
|
||||
|
||||
|
||||
it('keeps native instructions for the first actual prompt after a snapshot Abort', async () => {
|
||||
roundSummaryHarness.snapshotCalls = []
|
||||
harness.promptCount = 0
|
||||
harness.promptContents = []
|
||||
let snapshotCount = 0
|
||||
let releaseFirstSnapshot: ((value: unknown) => void) | null = null
|
||||
roundSummaryHarness.snapshotImpl = () => {
|
||||
snapshotCount += 1
|
||||
return snapshotCount === 1
|
||||
? new Promise<unknown>((resolve) => { releaseFirstSnapshot = resolve })
|
||||
: Promise.resolve({ messageIds: [] })
|
||||
}
|
||||
const { session, rpcHandlers } = createSessionStub([{ message: 'aborted before prompt', mode: createMode() }], { keepOpen: true })
|
||||
const launchPromise = opencodeRemoteLauncher(session as never)
|
||||
await new Promise<void>((resolve) => setImmediate(resolve))
|
||||
expect(roundSummaryHarness.snapshotCalls).toHaveLength(1)
|
||||
|
||||
const abortHandler = rpcHandlers.get(RPC_METHODS.Abort) as (() => Promise<void>) | undefined
|
||||
expect(abortHandler).toBeDefined()
|
||||
await abortHandler!()
|
||||
session.queue.push('actual second prompt', createMode())
|
||||
releaseFirstSnapshot!({ messageIds: [] })
|
||||
session.queue.close()
|
||||
await launchPromise
|
||||
|
||||
expect(harness.promptCount).toBe(1)
|
||||
const text = (harness.promptContents[0] as Array<{ type: string; text?: string }>)[0]?.text
|
||||
expect(text).toContain(getOpencodeNativeToolInstruction())
|
||||
expect(text).toContain('actual second prompt')
|
||||
})
|
||||
|
||||
it('does not start a backend prompt when Switch arrives during the blocking pre-prompt snapshot', async () => {
|
||||
roundSummaryHarness.snapshotCalls = []
|
||||
harness.promptCount = 0
|
||||
let releaseSnapshot: ((value: unknown) => void) | null = null
|
||||
roundSummaryHarness.snapshotImpl = () => new Promise<unknown>((resolve) => { releaseSnapshot = resolve })
|
||||
const { session, rpcHandlers, sessionEvents } = createSessionStub([{ message: 'snapshot switch', mode: createMode() }])
|
||||
const launchPromise = opencodeRemoteLauncher(session as never)
|
||||
await new Promise<void>((resolve) => setImmediate(resolve))
|
||||
expect(roundSummaryHarness.snapshotCalls).toHaveLength(1)
|
||||
|
||||
const switchHandler = rpcHandlers.get(RPC_METHODS.Switch) as (() => Promise<void>) | undefined
|
||||
expect(switchHandler).toBeDefined()
|
||||
await switchHandler!()
|
||||
releaseSnapshot!({ messageIds: [] })
|
||||
session.queue.close()
|
||||
await launchPromise
|
||||
|
||||
expect(harness.promptCount).toBe(0)
|
||||
expect(sessionEvents).toEqual([])
|
||||
})
|
||||
|
||||
it('does not start a backend prompt when Abort arrives during the blocking pre-prompt snapshot', async () => {
|
||||
roundSummaryHarness.snapshotCalls = []
|
||||
harness.promptCount = 0
|
||||
let releaseSnapshot: ((value: unknown) => void) | null = null
|
||||
roundSummaryHarness.snapshotImpl = () => new Promise<unknown>((resolve) => { releaseSnapshot = resolve })
|
||||
const { session, rpcHandlers, sessionEvents } = createSessionStub([{ message: 'snapshot abort', mode: createMode() }])
|
||||
const launchPromise = opencodeRemoteLauncher(session as never)
|
||||
await new Promise<void>((resolve) => setImmediate(resolve))
|
||||
expect(roundSummaryHarness.snapshotCalls).toHaveLength(1)
|
||||
|
||||
const abortHandler = rpcHandlers.get('abort') as (() => Promise<void>) | undefined
|
||||
expect(abortHandler).toBeDefined()
|
||||
await abortHandler!()
|
||||
releaseSnapshot!({ messageIds: [] })
|
||||
session.queue.close()
|
||||
await launchPromise
|
||||
|
||||
expect(harness.promptCount).toBe(0)
|
||||
expect(sessionEvents).toEqual([{ type: 'ready' }])
|
||||
})
|
||||
});
|
||||
|
||||
function indeterminateError(message: string): Error {
|
||||
@@ -3217,6 +3542,57 @@ describe('opencodeRemoteLauncher mid-turn steer', () => {
|
||||
}
|
||||
});
|
||||
|
||||
it('cancels and detaches a deferred steer when Stop follows foreground completion', async () => {
|
||||
let releaseSteer!: () => void;
|
||||
harness.deferSoftSteer = new Promise<void>(resolve => { releaseSteer = resolve; });
|
||||
const { stub, releasePrompt, runPromise } = await startTurn();
|
||||
try {
|
||||
stub.session.queue.push('correction', createMode(), 'steer');
|
||||
await expect(steerHandlerOf(stub)({ localId: 'steer' })).resolves.toEqual({ steered: true });
|
||||
releasePrompt();
|
||||
await vi.waitFor(() => expect(stub.steeringActiveCalls.at(-1)).toBe(false));
|
||||
expect(stub.sessionEvents.filter(event => event.type === 'ready')).toEqual([]);
|
||||
await (stub.rpcHandlers.get('abort') as () => Promise<void>)();
|
||||
expect(harness.cancelPrompt).toHaveBeenCalledWith('acp-session-1');
|
||||
expect(harness.abortSoftSteersCalls).toBe(1);
|
||||
await vi.waitFor(() => expect(stub.steerIndeterminateCalls).toContainEqual(['steer']));
|
||||
expect(stub.emitMessagesConsumedCalls).toEqual([]);
|
||||
} finally {
|
||||
releaseSteer(); harness.deferSoftSteer = null;
|
||||
stub.session.queue.close(); await runPromise;
|
||||
}
|
||||
});
|
||||
|
||||
it('reconciles a retained unknown v2 steer when Stop follows foreground completion', async () => {
|
||||
harness.detectedVersion = 'v2'; harness.discoveredPort = 48274; harness.discoveredPassword = 'test-only';
|
||||
let id = ''; let visible = false; let deleted = false; let posts = 0;
|
||||
const nativeFetch = vi.spyOn(globalThis, 'fetch').mockImplementation(async (url, init) => {
|
||||
if (init?.method === 'POST') { posts++; id = JSON.parse(String(init.body)).id; throw new Error('response lost'); }
|
||||
if (init?.method === 'DELETE') { deleted = true; return new Response(null, { status: 204 }); }
|
||||
const item = { id, sessionID: 'acp-session-1', type: 'user', delivery: 'steer', payload: { text: 'correction' } };
|
||||
return String(url).endsWith('/inbox') ? Response.json({ data: visible && !deleted ? [item] : [] }) : new Response(null, { status: 404 });
|
||||
});
|
||||
roundSummaryHarness.summaryImpl = () => new Promise<unknown>(() => {});
|
||||
const { stub, releasePrompt, runPromise } = await startTurn();
|
||||
try {
|
||||
stub.session.queue.push('correction', createMode(), 'v2-steer');
|
||||
await expect(steerHandlerOf(stub)({ localId: 'v2-steer' })).resolves.toEqual({ steered: false, error: 'Steer outcome is being reconciled' });
|
||||
expect(stub.steerIndeterminateCalls).toContainEqual(['v2-steer']);
|
||||
releasePrompt();
|
||||
await vi.waitFor(() => expect(roundSummaryHarness.summaryCalls).toHaveLength(1));
|
||||
visible = true;
|
||||
await (stub.rpcHandlers.get('abort') as () => Promise<void>)();
|
||||
expect(deleted).toBe(true);
|
||||
expect(posts).toBe(1);
|
||||
expect(stub.emitMessagesConsumedCalls).toEqual([]);
|
||||
expect(harness.steerStateCalls).not.toContainEqual({ localIds: ['v2-steer'], state: 'queued' });
|
||||
expect(stub.session.queue.peekByLocalId('v2-steer')).toBeNull();
|
||||
expect(stub.session.queue.cancelByLocalId('v2-steer')).toBe(true);
|
||||
} finally {
|
||||
nativeFetch.mockRestore(); stub.session.queue.close(); await runPromise;
|
||||
}
|
||||
});
|
||||
|
||||
it('injects a compatible queued message into the active turn without cancelling it', async () => {
|
||||
let releaseSoftSteer!: () => void;
|
||||
harness.deferSoftSteer = new Promise<void>((resolve) => { releaseSoftSteer = resolve; });
|
||||
@@ -4805,8 +5181,42 @@ function backendCreateArgsIncludePortFlags(): boolean {
|
||||
}
|
||||
|
||||
describe('opencodeRemoteLauncher v2 flavor wiring', () => {
|
||||
it('collects a v2 round through the discovered authenticated API before ready', async () => {
|
||||
harness.detectedVersion = 'v2';
|
||||
harness.discoveredPort = 41234;
|
||||
harness.discoveredPassword = 'fixture-password';
|
||||
const { session, sentAgentMessages, sessionEvents, deliveryEvents } = createSessionStub([{ message: 'v2 round', mode: createMode() }]);
|
||||
|
||||
await opencodeRemoteLauncher(session as never);
|
||||
|
||||
expect(roundSummaryHarness.snapshotCalls).toEqual([expect.objectContaining({
|
||||
baseUrl: 'http://127.0.0.1:41234', api: { version: 'v2', password: 'fixture-password' }
|
||||
})]);
|
||||
expect(roundSummaryHarness.summaryCalls).toEqual([expect.objectContaining({
|
||||
baseUrl: 'http://127.0.0.1:41234', api: { version: 'v2', password: 'fixture-password' }
|
||||
})]);
|
||||
expect(sentAgentMessages).toEqual([expect.objectContaining({ type: 'round-summary' })]);
|
||||
expect(sessionEvents).toEqual([{ type: 'ready' }]);
|
||||
expect(deliveryEvents).toEqual(['agent', 'ready']);
|
||||
});
|
||||
|
||||
it('preserves the v2 prompt and ready when API discovery fails', async () => {
|
||||
harness.detectedVersion = 'v2';
|
||||
const { session, sentAgentMessages, sessionEvents } = createSessionStub([{ message: 'v2 without discovery', mode: createMode() }]);
|
||||
|
||||
await opencodeRemoteLauncher(session as never);
|
||||
|
||||
expect(JSON.stringify(harness.promptContents)).toContain('v2 without discovery');
|
||||
expect(roundSummaryHarness.snapshotCalls).toEqual([]);
|
||||
expect(roundSummaryHarness.summaryCalls).toEqual([]);
|
||||
expect(sentAgentMessages).toEqual([]);
|
||||
expect(sessionEvents).toContainEqual({ type: 'ready' });
|
||||
});
|
||||
|
||||
|
||||
beforeEach(() => {
|
||||
harness.eventStreamOptions = [];
|
||||
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
|
||||
@@ -17,6 +17,7 @@ import type { OpencodeMode, PermissionMode } from './types';
|
||||
import type { QueueReservation } from '@/utils/MessageQueue2';
|
||||
import { admitOpencodeV2Steer, cancelOpencodeV2Steer, opencodeV2InputId, readOpencodeV2Input, steerOpencodeV2Inbox, type OpencodeSteerCancelHandler, type OpencodeSteerCancelResult } from './utils/opencodeV2Steer';
|
||||
import { RPC_METHODS } from '@hapi/protocol/rpcMethods';
|
||||
import { captureOpencodeRoundSnapshot, fetchOpencodeRoundSummary, type OpencodeRoundSnapshot } from './utils/opencodeRoundSummary';
|
||||
import {
|
||||
allocateFreePort,
|
||||
createOpencodeBackend,
|
||||
@@ -84,6 +85,29 @@ export type AbortStatusDecision = {
|
||||
};
|
||||
|
||||
type CompactOperationPhase = 'idle' | 'snapshot' | 'summarize' | 'post-summarize' | 'verification';
|
||||
type RoundSummaryPhase = 'idle' | 'snapshot' | 'prompt' | 'settle';
|
||||
|
||||
const ROUND_SUMMARY_SETTLE_TIMEOUT_MS = 1_000;
|
||||
|
||||
async function settleRoundSummary<T>(promise: Promise<T>, controller: AbortController): Promise<T | null> {
|
||||
return await new Promise<T | null>((resolve) => {
|
||||
let settled = false;
|
||||
const settle = (value: T | null) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
clearTimeout(timeout);
|
||||
controller.signal.removeEventListener('abort', onAbort);
|
||||
resolve(value);
|
||||
};
|
||||
const onAbort = () => settle(null);
|
||||
const timeout = setTimeout(() => {
|
||||
controller.abort();
|
||||
settle(null);
|
||||
}, ROUND_SUMMARY_SETTLE_TIMEOUT_MS);
|
||||
controller.signal.addEventListener('abort', onAbort, { once: true });
|
||||
void promise.then((summary) => settle(summary), () => settle(null));
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* One steer operation the launcher still tracks. Deliberately distinct from
|
||||
@@ -178,6 +202,11 @@ class OpencodeRemoteLauncher extends RemoteLauncherBase {
|
||||
// deliberately unbounded (see triggerOpencodeCompact's doc comment) and
|
||||
// the launcher stays wedged until it eventually settles on its own.
|
||||
private compactAbortController: AbortController | null = null;
|
||||
private roundSummaryAbortController: AbortController | null = null;
|
||||
/** Distinguishes an active prompt from read-only post-prompt work for Stop semantics. */
|
||||
private roundSummaryPhase: RoundSummaryPhase = 'idle';
|
||||
/** Validated ID boundary returned by the previous post-prompt fetch; explicit history mutations clear it. */
|
||||
private nextRoundSnapshot: OpencodeRoundSnapshot | null = null;
|
||||
// A plain Stop must keep waiting only while the summarize POST is
|
||||
// actually in flight. That POST can outlive a client-side abort while
|
||||
// continuing to mutate the shared OpenCode session, so advancing to a
|
||||
@@ -879,6 +908,7 @@ class OpencodeRemoteLauncher extends RemoteLauncherBase {
|
||||
continue;
|
||||
}
|
||||
|
||||
this.nextRoundSnapshot = null;
|
||||
session.onThinkingChange(true);
|
||||
try {
|
||||
await this.runCompactOperation(acpSessionId, compactAbortController, compactLocalId);
|
||||
@@ -896,17 +926,55 @@ class OpencodeRemoteLauncher extends RemoteLauncherBase {
|
||||
if (batch.mode.permissionMode === 'plan') {
|
||||
messageText = `${PLAN_MODE_INSTRUCTION}\n\n${messageText}`;
|
||||
}
|
||||
if (!this.instructionsSent) {
|
||||
messageText = `${getOpencodeNativeToolInstruction()}\n\n${messageText}`;
|
||||
this.instructionsSent = true;
|
||||
|
||||
this.stallErrorReportedForPrompt = false;
|
||||
const roundSummaryAbortController = new AbortController();
|
||||
this.roundSummaryAbortController = roundSummaryAbortController;
|
||||
this.roundSummaryPhase = 'snapshot';
|
||||
const roundApi = this.v2RestInfo
|
||||
? { baseUrl: this.v2RestInfo.baseUrl, api: { version: 'v2' as const, password: this.v2RestInfo.password } }
|
||||
: this.baseUrl ? { baseUrl: this.baseUrl } : null;
|
||||
const roundSnapshot = this.nextRoundSnapshot ?? (roundApi
|
||||
? await captureOpencodeRoundSnapshot({
|
||||
...roundApi,
|
||||
sessionId: acpSessionId,
|
||||
signal: roundSummaryAbortController.signal
|
||||
}).catch((error) => {
|
||||
logger.debug('[opencode-remote] round snapshot unavailable', error);
|
||||
return null;
|
||||
})
|
||||
: null);
|
||||
this.nextRoundSnapshot = null;
|
||||
if (
|
||||
this.roundSummaryAbortController !== roundSummaryAbortController
|
||||
|| roundSummaryAbortController.signal.aborted
|
||||
|| this.shouldExit
|
||||
) {
|
||||
if (this.roundSummaryAbortController === roundSummaryAbortController) {
|
||||
this.roundSummaryAbortController = null;
|
||||
this.roundSummaryPhase = 'idle';
|
||||
}
|
||||
session.onThinkingChange(false);
|
||||
if (session.queue.size() === 0 && !this.shouldExit) {
|
||||
sendReady();
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!this.instructionsSent) {
|
||||
messageText = `${getOpencodeNativeToolInstruction()}
|
||||
|
||||
${messageText}`;
|
||||
this.instructionsSent = true;
|
||||
}
|
||||
const promptContent: PromptContent[] = [{
|
||||
type: 'text',
|
||||
text: messageText,
|
||||
}];
|
||||
|
||||
this.stallErrorReportedForPrompt = false;
|
||||
const promptStartedAt = performance.now();
|
||||
let promptDurationMs = 0;
|
||||
this.roundSummaryPhase = 'prompt';
|
||||
session.onThinkingChange(true);
|
||||
// Only a normal prompt is steerable: /compact and /clear leave this
|
||||
// false, so a steer arriving during either is rejected rather than
|
||||
@@ -921,9 +989,14 @@ class OpencodeRemoteLauncher extends RemoteLauncherBase {
|
||||
const nativeInput = { uncertain: false };
|
||||
this.nativeInputWriters.add(nativeInput);
|
||||
try {
|
||||
await backend.prompt(acpSessionId, promptContent, (message: AgentMessage) => {
|
||||
this.handleAgentMessage(message);
|
||||
});
|
||||
try {
|
||||
await backend.prompt(acpSessionId, promptContent, (message: AgentMessage) => {
|
||||
this.handleAgentMessage(message);
|
||||
});
|
||||
} finally {
|
||||
promptDurationMs = performance.now() - promptStartedAt;
|
||||
this.roundSummaryPhase = 'settle';
|
||||
}
|
||||
this.completeNativeInput(nativeInput);
|
||||
await this.nativeTranscript?.refresh();
|
||||
void backend.refreshSessionInfo(acpSessionId, session.path);
|
||||
@@ -947,10 +1020,40 @@ class OpencodeRemoteLauncher extends RemoteLauncherBase {
|
||||
// steer that settled (or is still restoring) cannot cross the
|
||||
// turn boundary into the next prompt or a /compact.
|
||||
await this.drainSteerOperations();
|
||||
session.onThinkingChange(false);
|
||||
await this.permissionHandler?.cancelAll('Prompt finished');
|
||||
if (session.queue.size() === 0 && !this.shouldExit) {
|
||||
sendReady();
|
||||
if (
|
||||
this.roundSummaryAbortController === roundSummaryAbortController
|
||||
&& !roundSummaryAbortController.signal.aborted
|
||||
&& !this.shouldExit
|
||||
&& roundApi
|
||||
&& roundSnapshot
|
||||
) {
|
||||
const result = await settleRoundSummary(
|
||||
fetchOpencodeRoundSummary({
|
||||
...roundApi,
|
||||
sessionId: acpSessionId,
|
||||
promptText: messageText,
|
||||
snapshot: roundSnapshot,
|
||||
durationMs: promptDurationMs,
|
||||
signal: roundSummaryAbortController.signal
|
||||
}),
|
||||
roundSummaryAbortController
|
||||
);
|
||||
if (result) {
|
||||
this.nextRoundSnapshot = result.snapshot;
|
||||
if (result.summary) this.handleAgentMessage({ type: 'round_summary', summary: result.summary });
|
||||
}
|
||||
}
|
||||
if (this.roundSummaryAbortController === roundSummaryAbortController) {
|
||||
this.roundSummaryAbortController = null;
|
||||
}
|
||||
try {
|
||||
session.onThinkingChange(false);
|
||||
await this.permissionHandler?.cancelAll('Prompt finished');
|
||||
if (session.queue.size() === 0 && !this.shouldExit) {
|
||||
sendReady();
|
||||
}
|
||||
} finally {
|
||||
this.roundSummaryPhase = 'idle';
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2136,6 +2239,8 @@ class OpencodeRemoteLauncher extends RemoteLauncherBase {
|
||||
case 'turn_complete':
|
||||
this.messageBuffer.addMessage('Turn complete', 'status');
|
||||
break;
|
||||
case 'round_summary':
|
||||
break;
|
||||
default: {
|
||||
const _exhaustive: never = message;
|
||||
return _exhaustive;
|
||||
@@ -2163,6 +2268,19 @@ class OpencodeRemoteLauncher extends RemoteLauncherBase {
|
||||
* disconnects the ACP subprocess right after.
|
||||
*/
|
||||
private async handleAbort(leavingRemote = false): Promise<void> {
|
||||
this.roundSummaryAbortController?.abort();
|
||||
// Only abandon metadata when no steer or cancellation still owns work.
|
||||
if (
|
||||
!leavingRemote
|
||||
&& this.roundSummaryPhase === 'settle'
|
||||
&& this.pendingSteerOperations.size === 0
|
||||
&& this.v2Steers.size === 0
|
||||
&& !Array.from(this.backendSoftSteerOwnership).some(entry =>
|
||||
entry.backend === this.backend && entry.turnEpoch === this.steerTurnEpoch
|
||||
)
|
||||
&& !this.v2AbortInProgress
|
||||
) return;
|
||||
|
||||
if (this.majorVersion !== 'v2') return this.performAbort(leavingRemote);
|
||||
if (this.v2AbortInProgress) {
|
||||
// One overlapping Stop/switch owns queue.reset. A later reset
|
||||
|
||||
@@ -188,6 +188,18 @@ const summary = (id: string, parentID: string, overrides: Record<string, unknown
|
||||
});
|
||||
|
||||
describe('captureCompactionMarkerSnapshot', () => {
|
||||
it('fails closed when the message API array contains a null entry', async () => {
|
||||
const fetchImpl = vi.fn(async () => new Response(JSON.stringify([null]), { status: 200 }));
|
||||
|
||||
await expect(captureCompactionMarkerSnapshot({
|
||||
baseUrl: 'http://127.0.0.1:48273', sessionId: 'ses_abc', fetchImpl, signal: noSignal
|
||||
})).resolves.toBeNull();
|
||||
|
||||
await expect(fetchCompactionResult({
|
||||
baseUrl: 'http://127.0.0.1:48273', sessionId: 'ses_abc', markerIdsBefore: ['old-marker'], fetchImpl, signal: noSignal
|
||||
})).resolves.toEqual({ status: 'unverified', reason: 'Compaction result could not be verified.' });
|
||||
});
|
||||
|
||||
it('records only pre-existing manual marker IDs before POST so a later result cannot reuse them', async () => {
|
||||
const fetchImpl = vi.fn(async (url: string, init?: RequestInit) => {
|
||||
expect(url).toBe('http://127.0.0.1:48273/session/ses_abc/message');
|
||||
|
||||
@@ -492,7 +492,7 @@ async function fetchSessionMessages(opts: OpencodeCompactCallOpts & { fetchImpl?
|
||||
const response = await fetchFn(url, { method: 'GET', signal: opts.signal });
|
||||
if (!response.ok) return null;
|
||||
const data: unknown = await response.json().catch(() => null);
|
||||
return Array.isArray(data) ? data as OpencodeMessageEntry[] : null;
|
||||
return Array.isArray(data) && data.every(isObjectRecord) ? data as OpencodeMessageEntry[] : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { captureOpencodeRoundSnapshot, fetchOpencodeRoundSummary } from './opencodeRoundSummary';
|
||||
|
||||
const signal = new AbortController().signal;
|
||||
const base = { baseUrl: 'http://127.0.0.1:48273', sessionId: 'ses_abc', signal };
|
||||
|
||||
const user = (id: string, text: string) => ({ info: { id, role: 'user' }, parts: [{ type: 'text', text }] });
|
||||
const assistant = (id: string) => ({
|
||||
info: {
|
||||
id,
|
||||
role: 'assistant',
|
||||
providerID: 'openai',
|
||||
modelID: 'gpt-5.4',
|
||||
tokens: { input: 1, output: 1, reasoning: 0, cache: { read: 0, write: 0 } },
|
||||
cost: 0
|
||||
}
|
||||
});
|
||||
|
||||
describe('OpenCode round message identity boundary', () => {
|
||||
it('fails closed when the message API array contains a null entry', async () => {
|
||||
const fetchImpl = vi.fn(async () => new Response(JSON.stringify([null]), { status: 200 }));
|
||||
|
||||
await expect(captureOpencodeRoundSnapshot({
|
||||
...base,
|
||||
fetchImpl
|
||||
})).resolves.toBeNull();
|
||||
|
||||
await expect(fetchOpencodeRoundSummary({
|
||||
...base,
|
||||
promptText: 'prompt',
|
||||
snapshot: { messageIds: ['old'] },
|
||||
durationMs: 1,
|
||||
fetchImpl
|
||||
})).resolves.toBeNull();
|
||||
});
|
||||
|
||||
it('fails closed for duplicate message ids in the pre-snapshot or post-fetch response', async () => {
|
||||
await expect(captureOpencodeRoundSnapshot({
|
||||
...base,
|
||||
fetchImpl: vi.fn(async () => new Response(JSON.stringify([user('same', 'one'), user('same', 'two')]), { status: 200 }))
|
||||
})).resolves.toBeNull();
|
||||
|
||||
await expect(fetchOpencodeRoundSummary({
|
||||
...base,
|
||||
promptText: 'prompt',
|
||||
snapshot: { messageIds: ['old'] },
|
||||
durationMs: 1,
|
||||
fetchImpl: vi.fn(async () => new Response(JSON.stringify([
|
||||
user('old', 'earlier'), user('prompt-user', 'prompt'), assistant('assistant-1'), assistant('assistant-1')
|
||||
]), { status: 200 }))
|
||||
})).resolves.toBeNull();
|
||||
});
|
||||
|
||||
it('abandons a stalled message API request after its bounded timeout', async () => {
|
||||
const fetchImpl = vi.fn((_url: string, _init?: RequestInit) => new Promise<Response>(() => {}));
|
||||
|
||||
await expect(captureOpencodeRoundSnapshot({ ...base, timeoutMs: 1, fetchImpl })).resolves.toBeNull();
|
||||
expect(fetchImpl).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('bounds the whole response parse, including a response whose json never settles', async () => {
|
||||
const fetchImpl = vi.fn(async () => ({ ok: true, json: () => new Promise<unknown>(() => {}) }));
|
||||
await expect(captureOpencodeRoundSnapshot({ ...base, timeoutMs: 1, fetchImpl: fetchImpl as never })).resolves.toBeNull();
|
||||
});
|
||||
|
||||
it('checks a large snapshot identity list with a Set-backed duplicate invariant', async () => {
|
||||
const messages = Array.from({ length: 10_000 }, (_, index) => user('message-' + index, 'fixture'));
|
||||
await expect(captureOpencodeRoundSnapshot({
|
||||
...base,
|
||||
fetchImpl: vi.fn(async () => new Response(JSON.stringify(messages), { status: 200 }))
|
||||
})).resolves.toMatchObject({ messageIds: expect.arrayContaining(['message-0', 'message-9999']) });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,30 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { fetchOpencodeRoundSummary } from './opencodeRoundSummary';
|
||||
|
||||
describe('OpenCode round model key isolation', () => {
|
||||
it('aggregates hostile provider/model identifiers without touching the object prototype', async () => {
|
||||
const result = await fetchOpencodeRoundSummary({
|
||||
baseUrl: 'http://127.0.0.1:48273',
|
||||
sessionId: 'ses_abc',
|
||||
promptText: 'prompt',
|
||||
snapshot: { messageIds: ['old'] },
|
||||
durationMs: 1,
|
||||
signal: new AbortController().signal,
|
||||
fetchImpl: vi.fn(async () => new Response(JSON.stringify([
|
||||
{ info: { id: 'old', role: 'user' }, parts: [{ type: 'text', text: 'old' }] },
|
||||
{ info: { id: 'prompt', role: 'user' }, parts: [{ type: 'text', text: 'prompt' }] },
|
||||
{
|
||||
info: {
|
||||
id: 'assistant', role: 'assistant', providerID: '__proto__', modelID: '__proto__', cost: 0,
|
||||
tokens: { input: 1, output: 2, reasoning: 0, cache: { read: 0, write: 0 } }
|
||||
}
|
||||
}
|
||||
]), { status: 200 }))
|
||||
});
|
||||
|
||||
expect(result?.summary?.modelUsage).toEqual({
|
||||
'__proto__/__proto__': { inputTokens: 1, outputTokens: 2, cacheReadInputTokens: 0, cacheCreationInputTokens: 0 }
|
||||
});
|
||||
expect(Object.prototype).not.toHaveProperty('inputTokens');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,167 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { captureOpencodeRoundSnapshot, fetchOpencodeRoundSummary } from './opencodeRoundSummary';
|
||||
|
||||
const noSignal = new AbortController().signal;
|
||||
|
||||
function user(id: string, text: string) {
|
||||
return { info: { id, role: 'user' }, parts: [{ type: 'text', text }] };
|
||||
}
|
||||
|
||||
function assistant(id: string, parentID: string, overrides: Record<string, unknown> = {}) {
|
||||
return {
|
||||
info: {
|
||||
id,
|
||||
role: 'assistant',
|
||||
parentID,
|
||||
providerID: 'openai',
|
||||
modelID: 'gpt-5.4',
|
||||
tokens: { input: 10, output: 2, reasoning: 0, cache: { read: 0, write: 0 } },
|
||||
cost: 0,
|
||||
...overrides
|
||||
},
|
||||
parts: [{ type: 'step-finish' }]
|
||||
};
|
||||
}
|
||||
|
||||
function options(messages: unknown[], promptText = 'original prompt') {
|
||||
return {
|
||||
baseUrl: 'http://127.0.0.1:48273',
|
||||
sessionId: 'ses_abc',
|
||||
promptText,
|
||||
snapshot: { messageIds: ['old-user', 'old-assistant'] },
|
||||
durationMs: 1_250,
|
||||
signal: noSignal,
|
||||
fetchImpl: vi.fn(async () => new Response(JSON.stringify(messages), { status: 200 }))
|
||||
};
|
||||
}
|
||||
|
||||
describe('captureOpencodeRoundSnapshot', () => {
|
||||
it('captures only valid persisted message IDs before a prompt', async () => {
|
||||
const fetchImpl = vi.fn(async (url: string, init?: RequestInit) => {
|
||||
expect(url).toBe('http://127.0.0.1:48273/session/ses_abc/message?limit=512');
|
||||
expect(init).toMatchObject({ method: 'GET', signal: noSignal });
|
||||
return new Response(JSON.stringify([user('old-user', 'earlier'), assistant('old-assistant', 'old-user')]), { status: 200 });
|
||||
});
|
||||
|
||||
await expect(captureOpencodeRoundSnapshot({
|
||||
baseUrl: 'http://127.0.0.1:48273', sessionId: 'ses_abc', signal: noSignal, fetchImpl
|
||||
})).resolves.toEqual({ messageIds: ['old-user', 'old-assistant'] });
|
||||
});
|
||||
|
||||
it('fails closed for a non-2xx response or malformed message id', async () => {
|
||||
await expect(captureOpencodeRoundSnapshot({
|
||||
baseUrl: 'http://127.0.0.1:48273', sessionId: 'ses_abc', signal: noSignal,
|
||||
fetchImpl: vi.fn(async () => new Response('nope', { status: 404 }))
|
||||
})).resolves.toBeNull();
|
||||
await expect(captureOpencodeRoundSnapshot({
|
||||
baseUrl: 'http://127.0.0.1:48273', sessionId: 'ses_abc', signal: noSignal,
|
||||
fetchImpl: vi.fn(async () => new Response(JSON.stringify([{ info: { id: 9, role: 'user' } }]), { status: 200 }))
|
||||
})).resolves.toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('fetchOpencodeRoundSummary', () => {
|
||||
it('aggregates multi-step and multi-model assistant rows, including cache, reasoning, and positive cost', async () => {
|
||||
const messages = [
|
||||
user('old-user', 'earlier'),
|
||||
assistant('old-assistant', 'old-user'),
|
||||
user('prompt-user', 'original prompt'),
|
||||
assistant('tool-step', 'prompt-user', {
|
||||
tokens: { input: 100, output: 20, reasoning: 5, cache: { read: 50, write: 10 } }, cost: 0.01
|
||||
}),
|
||||
assistant('stop-step', 'prompt-user', {
|
||||
tokens: { input: 40, output: 7, reasoning: 3, cache: { read: 5, write: 0 } }, cost: 0.024
|
||||
}),
|
||||
assistant('other-model', 'prompt-user', {
|
||||
providerID: 'anthropic', modelID: 'claude-opus-4-1',
|
||||
tokens: { input: 80, output: 9, reasoning: 0, cache: { read: 20, write: 0 } }, cost: 0
|
||||
})
|
||||
];
|
||||
|
||||
const request = options(messages);
|
||||
const result = await fetchOpencodeRoundSummary(request);
|
||||
expect(request.fetchImpl).toHaveBeenCalledWith(
|
||||
'http://127.0.0.1:48273/session/ses_abc/message?limit=512',
|
||||
expect.objectContaining({ method: 'GET' })
|
||||
);
|
||||
expect(result?.snapshot.messageIds).toEqual([
|
||||
'old-user', 'old-assistant', 'prompt-user', 'tool-step', 'stop-step', 'other-model'
|
||||
]);
|
||||
expect(result?.summary).toEqual({
|
||||
usage: {
|
||||
inputTokens: 220,
|
||||
outputTokens: 44,
|
||||
cacheReadInputTokens: 75,
|
||||
cacheCreationInputTokens: 10
|
||||
},
|
||||
modelUsage: {
|
||||
'openai/gpt-5.4': {
|
||||
inputTokens: 140,
|
||||
outputTokens: 35,
|
||||
cacheReadInputTokens: 55,
|
||||
cacheCreationInputTokens: 10
|
||||
},
|
||||
'anthropic/claude-opus-4-1': {
|
||||
inputTokens: 80,
|
||||
outputTokens: 9,
|
||||
cacheReadInputTokens: 20,
|
||||
cacheCreationInputTokens: 0
|
||||
}
|
||||
},
|
||||
totalCostUsd: 0.034,
|
||||
numTurns: 3,
|
||||
durationMs: 1_250
|
||||
});
|
||||
});
|
||||
|
||||
it('includes tool-only, auto-compaction summary, and continuation assistants from every new parent', async () => {
|
||||
const messages = [
|
||||
user('old-user', 'earlier'),
|
||||
assistant('old-assistant', 'old-user'),
|
||||
user('prompt-user', 'original prompt'),
|
||||
assistant('tool-only', 'prompt-user'),
|
||||
user('compact-user', 'automatic compact'),
|
||||
assistant('compact-summary', 'compact-user', { summary: true, tokens: { input: 20, output: 3, reasoning: 0, cache: { read: 0, write: 0 } } }),
|
||||
user('continuation-user', 'continue'),
|
||||
assistant('continuation', 'continuation-user', { tokens: { input: 30, output: 4, reasoning: 0, cache: { read: 0, write: 0 } } })
|
||||
];
|
||||
|
||||
const result = await fetchOpencodeRoundSummary(options(messages));
|
||||
expect(result?.summary).toMatchObject({ numTurns: 3, usage: { inputTokens: 60, outputTokens: 9 } });
|
||||
});
|
||||
|
||||
it('omits zero cost while preserving a valid free round', async () => {
|
||||
const messages = [user('old-user', 'earlier'), assistant('old-assistant', 'old-user'), user('prompt-user', 'original prompt'), assistant('new', 'prompt-user')];
|
||||
const result = await fetchOpencodeRoundSummary(options(messages));
|
||||
expect(result?.summary).toMatchObject({ numTurns: 1 });
|
||||
expect(result?.summary).not.toHaveProperty('totalCostUsd');
|
||||
});
|
||||
|
||||
it('returns the validated post-fetch snapshot when malformed usage omits only the summary', async () => {
|
||||
const messages = [
|
||||
user('old-user', 'earlier'),
|
||||
assistant('old-assistant', 'old-user'),
|
||||
user('prompt-user', 'original prompt'),
|
||||
assistant('bad-model', 'prompt-user', { modelID: '' })
|
||||
];
|
||||
|
||||
await expect(fetchOpencodeRoundSummary(options(messages))).resolves.toEqual({
|
||||
snapshot: { messageIds: ['old-user', 'old-assistant', 'prompt-user', 'bad-model'] },
|
||||
summary: null
|
||||
});
|
||||
});
|
||||
|
||||
it('fails closed for missing original prompt, no assistant, malformed model/token shapes, unsafe counters, and non-finite numbers', async () => {
|
||||
const base = [user('old-user', 'earlier'), assistant('old-assistant', 'old-user')];
|
||||
expect((await fetchOpencodeRoundSummary(options([...base, assistant('new', 'unknown')])))?.summary ?? null).toBeNull();
|
||||
expect((await fetchOpencodeRoundSummary(options([...base, user('prompt-user', 'original prompt')])))?.summary ?? null).toBeNull();
|
||||
expect((await fetchOpencodeRoundSummary(options([...base, user('prompt-user', 'original prompt'), assistant('bad-model', 'prompt-user', { modelID: '' })])))?.summary ?? null).toBeNull();
|
||||
expect((await fetchOpencodeRoundSummary(options([...base, user('prompt-user', 'original prompt'), assistant('unsafe', 'prompt-user', { tokens: { input: Number.MAX_SAFE_INTEGER + 1, output: 2, reasoning: 0, cache: { read: 0, write: 0 } } })])))?.summary ?? null).toBeNull();
|
||||
expect((await fetchOpencodeRoundSummary(options([...base, user('prompt-user', 'original prompt'), assistant('infinite-cost', 'prompt-user', { cost: Infinity })])))?.summary ?? null).toBeNull();
|
||||
});
|
||||
|
||||
it('fails closed for a post-fetch API or parse failure without exposing the response body', async () => {
|
||||
await expect(fetchOpencodeRoundSummary({ ...options([]), fetchImpl: vi.fn(async () => new Response('provider secret', { status: 500 })) })).resolves.toBeNull();
|
||||
await expect(fetchOpencodeRoundSummary({ ...options([]), fetchImpl: vi.fn(async () => new Response('{', { status: 200 })) })).resolves.toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,295 @@
|
||||
import { Buffer } from 'node:buffer';
|
||||
import type { FetchLike } from './opencodeCompactBridge';
|
||||
|
||||
export type OpencodeRoundSnapshot = {
|
||||
messageIds: string[];
|
||||
};
|
||||
|
||||
export type OpencodeRoundModelUsage = {
|
||||
inputTokens: number;
|
||||
outputTokens: number;
|
||||
cacheReadInputTokens: number;
|
||||
cacheCreationInputTokens: number;
|
||||
};
|
||||
|
||||
export type OpencodeRoundSummary = {
|
||||
usage: OpencodeRoundModelUsage;
|
||||
modelUsage: Record<string, OpencodeRoundModelUsage>;
|
||||
totalCostUsd?: number;
|
||||
numTurns: number;
|
||||
durationMs: number;
|
||||
/** Assistant output + reasoning and provider-active time, excluding tools/compaction. */
|
||||
generationMs?: number;
|
||||
generationOutputTokens?: number;
|
||||
};
|
||||
|
||||
export type OpencodeRoundSummaryResult = {
|
||||
snapshot: OpencodeRoundSnapshot;
|
||||
summary: OpencodeRoundSummary | null;
|
||||
};
|
||||
|
||||
type OpencodeMessage = {
|
||||
info?: {
|
||||
id?: unknown;
|
||||
role?: unknown;
|
||||
providerID?: unknown;
|
||||
modelID?: unknown;
|
||||
tokens?: unknown;
|
||||
cost?: unknown;
|
||||
time?: unknown;
|
||||
isCompaction?: boolean;
|
||||
};
|
||||
parts?: unknown;
|
||||
};
|
||||
|
||||
type RoundFetchOptions = {
|
||||
baseUrl: string;
|
||||
sessionId: string;
|
||||
signal: AbortSignal;
|
||||
fetchImpl?: FetchLike;
|
||||
timeoutMs?: number;
|
||||
api?: { version: 'v2'; password: string };
|
||||
};
|
||||
|
||||
const ROUND_FETCH_TIMEOUT_MS = 1_000;
|
||||
const ROUND_MESSAGE_LIMIT = 512;
|
||||
// OpenCode v2's SessionMessagesQuery allows at most 200 messages per page.
|
||||
const V2_MESSAGE_PAGE_LIMIT = 200;
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function normalizeV2Messages(payload: unknown): OpencodeMessage[] | null {
|
||||
if (!isRecord(payload) || !Array.isArray(payload.data)) return null;
|
||||
const messages: OpencodeMessage[] = [];
|
||||
for (const entry of payload.data) {
|
||||
if (!isRecord(entry)) return null;
|
||||
const hasUsage = entry.type === 'assistant'
|
||||
|| (entry.type === 'compaction' && (entry.tokens !== undefined || entry.cost !== undefined));
|
||||
if (hasUsage && entry.type === 'compaction' && entry.status !== 'completed' && entry.status !== 'failed') return null;
|
||||
const model = isRecord(entry.model) ? entry.model : null;
|
||||
messages.push({
|
||||
info: {
|
||||
id: entry.id,
|
||||
role: hasUsage ? 'assistant' : entry.type === 'user' ? 'user' : undefined,
|
||||
providerID: model?.providerID,
|
||||
modelID: model?.id,
|
||||
tokens: entry.tokens,
|
||||
cost: entry.cost,
|
||||
time: entry.time,
|
||||
isCompaction: entry.type === 'compaction'
|
||||
},
|
||||
parts: entry.type === 'user' ? [{ type: 'text', text: entry.text }] : undefined
|
||||
});
|
||||
}
|
||||
return messages;
|
||||
}
|
||||
|
||||
function safeInteger(value: unknown): number | null {
|
||||
return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? value : null;
|
||||
}
|
||||
|
||||
function finiteNonNegative(value: unknown): number | null {
|
||||
return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : null;
|
||||
}
|
||||
|
||||
function messageId(message: unknown): string | null {
|
||||
if (!isRecord(message) || !isRecord(message.info)) return null;
|
||||
return typeof message.info.id === 'string' && message.info.id.length > 0 ? message.info.id : null;
|
||||
}
|
||||
|
||||
function messageText(message: OpencodeMessage): string | null {
|
||||
if (!Array.isArray(message.parts)) return null;
|
||||
const text = message.parts
|
||||
.filter(isRecord)
|
||||
.filter((part) => part.type === 'text' && typeof part.text === 'string')
|
||||
.map((part) => part.text)
|
||||
.join('');
|
||||
return text || null;
|
||||
}
|
||||
|
||||
async function fetchMessages(options: RoundFetchOptions): Promise<OpencodeMessage[] | null> {
|
||||
const fetchFn = options.fetchImpl ?? fetch;
|
||||
const controller = new AbortController();
|
||||
const abort = () => controller.abort();
|
||||
if (options.signal.aborted) return null;
|
||||
options.signal.addEventListener('abort', abort, { once: true });
|
||||
let timeout: ReturnType<typeof setTimeout> | undefined;
|
||||
const timedOut = new Promise<null>((resolve) => {
|
||||
timeout = setTimeout(() => {
|
||||
controller.abort();
|
||||
resolve(null);
|
||||
}, options.timeoutMs ?? ROUND_FETCH_TIMEOUT_MS);
|
||||
});
|
||||
try {
|
||||
const request = (async (): Promise<OpencodeMessage[] | null> => {
|
||||
const api = options.api;
|
||||
const response = await fetchFn(
|
||||
options.baseUrl + (api ? '/api/session/' : '/session/') + encodeURIComponent(options.sessionId)
|
||||
+ '/message?limit=' + (api ? V2_MESSAGE_PAGE_LIMIT : ROUND_MESSAGE_LIMIT),
|
||||
{
|
||||
method: 'GET', signal: controller.signal,
|
||||
...(api ? { headers: { authorization: 'Basic ' + Buffer.from(`opencode:${api.password}`).toString('base64') } } : {})
|
||||
}
|
||||
);
|
||||
if (!response.ok) return null;
|
||||
const parsed: unknown = await response.json();
|
||||
if (api) return normalizeV2Messages(parsed);
|
||||
return Array.isArray(parsed) ? parsed as OpencodeMessage[] : null;
|
||||
})();
|
||||
return await Promise.race([request, timedOut]);
|
||||
} catch {
|
||||
return null;
|
||||
} finally {
|
||||
if (timeout) clearTimeout(timeout);
|
||||
options.signal.removeEventListener('abort', abort);
|
||||
}
|
||||
}
|
||||
|
||||
/** Captures the persisted-message identity boundary immediately before a prompt. */
|
||||
export async function captureOpencodeRoundSnapshot(options: RoundFetchOptions): Promise<OpencodeRoundSnapshot | null> {
|
||||
const messages = await fetchMessages(options);
|
||||
if (!messages) return null;
|
||||
const messageIds: string[] = [];
|
||||
const seen = new Set<string>();
|
||||
for (const message of messages) {
|
||||
const id = messageId(message);
|
||||
if (!id || seen.has(id)) return null;
|
||||
seen.add(id);
|
||||
messageIds.push(id);
|
||||
}
|
||||
return { messageIds };
|
||||
}
|
||||
|
||||
function parseAssistantUsage(message: OpencodeMessage, allowMissingCost: boolean): { key: string; usage: OpencodeRoundModelUsage; cost: number | undefined } | null {
|
||||
if (message.info?.role !== 'assistant') return null;
|
||||
const providerID = message.info.providerID;
|
||||
const modelID = message.info.modelID;
|
||||
const tokens = message.info.tokens;
|
||||
if (typeof providerID !== 'string' || providerID.length === 0 || typeof modelID !== 'string' || modelID.length === 0 || !isRecord(tokens)) return null;
|
||||
|
||||
const cache = tokens.cache;
|
||||
if (!isRecord(cache)) return null;
|
||||
const inputTokens = safeInteger(tokens.input);
|
||||
const outputTokens = safeInteger(tokens.output);
|
||||
const reasoningTokens = safeInteger(tokens.reasoning);
|
||||
const cacheReadInputTokens = safeInteger(cache.read);
|
||||
const cacheCreationInputTokens = safeInteger(cache.write);
|
||||
const cost = allowMissingCost && message.info.cost === undefined ? undefined : finiteNonNegative(message.info.cost);
|
||||
if (inputTokens === null || outputTokens === null || reasoningTokens === null || cacheReadInputTokens === null || cacheCreationInputTokens === null || cost === null) return null;
|
||||
|
||||
const displayOutputTokens = outputTokens + reasoningTokens;
|
||||
if (!Number.isSafeInteger(displayOutputTokens)) return null;
|
||||
|
||||
return {
|
||||
key: providerID + '/' + modelID,
|
||||
usage: {
|
||||
inputTokens,
|
||||
outputTokens: displayOutputTokens,
|
||||
cacheReadInputTokens,
|
||||
cacheCreationInputTokens
|
||||
},
|
||||
cost
|
||||
};
|
||||
}
|
||||
|
||||
function addUsage(total: OpencodeRoundModelUsage, next: OpencodeRoundModelUsage): boolean {
|
||||
total.inputTokens += next.inputTokens;
|
||||
total.outputTokens += next.outputTokens;
|
||||
total.cacheReadInputTokens += next.cacheReadInputTokens;
|
||||
total.cacheCreationInputTokens += next.cacheCreationInputTokens;
|
||||
return Object.values(total).every(Number.isSafeInteger);
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads the post-prompt message list and aggregates every new assistant row.
|
||||
* The prompt text anchors the original user row; assistant parent IDs are
|
||||
* deliberately ignored because auto-compaction creates synthetic parents.
|
||||
*/
|
||||
export async function fetchOpencodeRoundSummary(options: RoundFetchOptions & {
|
||||
promptText: string;
|
||||
snapshot: OpencodeRoundSnapshot;
|
||||
durationMs: number;
|
||||
}): Promise<OpencodeRoundSummaryResult | null> {
|
||||
if (finiteNonNegative(options.durationMs) === null) return null;
|
||||
const messages = await fetchMessages(options);
|
||||
if (!messages) return null;
|
||||
|
||||
const before = new Set(options.snapshot.messageIds);
|
||||
if (before.size !== options.snapshot.messageIds.length) return null;
|
||||
const seen = new Set<string>();
|
||||
const messageIds: string[] = [];
|
||||
const delta: OpencodeMessage[] = [];
|
||||
for (const message of messages) {
|
||||
const id = messageId(message);
|
||||
if (!id || seen.has(id)) return null;
|
||||
seen.add(id);
|
||||
messageIds.push(id);
|
||||
if (!before.has(id)) delta.push(message);
|
||||
}
|
||||
|
||||
const hasOriginalPrompt = delta.some((message) => message.info?.role === 'user' && messageText(message) === options.promptText);
|
||||
if (!hasOriginalPrompt) return null;
|
||||
const snapshot = { messageIds };
|
||||
|
||||
const usage: OpencodeRoundModelUsage = {
|
||||
inputTokens: 0,
|
||||
outputTokens: 0,
|
||||
cacheReadInputTokens: 0,
|
||||
cacheCreationInputTokens: 0
|
||||
};
|
||||
const modelUsage = new Map<string, OpencodeRoundModelUsage>();
|
||||
let totalCostUsd = 0;
|
||||
let hasCompleteCost = true;
|
||||
let numTurns = 0;
|
||||
let generationMs = 0;
|
||||
let generationOutputTokens = 0;
|
||||
let hasCompleteGeneration = options.api?.version === 'v2';
|
||||
for (const message of delta) {
|
||||
if (message.info?.role !== 'assistant') continue;
|
||||
const parsed = parseAssistantUsage(message, options.api?.version === 'v2');
|
||||
if (!parsed) return { snapshot, summary: null };
|
||||
let perModel = modelUsage.get(parsed.key);
|
||||
if (!perModel) {
|
||||
perModel = {
|
||||
inputTokens: 0,
|
||||
outputTokens: 0,
|
||||
cacheReadInputTokens: 0,
|
||||
cacheCreationInputTokens: 0
|
||||
};
|
||||
modelUsage.set(parsed.key, perModel);
|
||||
}
|
||||
if (!addUsage(perModel, parsed.usage) || !addUsage(usage, parsed.usage)) return { snapshot, summary: null };
|
||||
if (parsed.cost === undefined) hasCompleteCost = false;
|
||||
else totalCostUsd += parsed.cost;
|
||||
if (!message.info.isCompaction) {
|
||||
// Match OpenCode v2 turnTokensPerSecond: assistant steps only, with
|
||||
// the provider body boundary (before tool settlement) on every step.
|
||||
const time = message.info.time;
|
||||
const created = isRecord(time) ? safeInteger(time.created) : null;
|
||||
const streamed = isRecord(time) ? safeInteger(time.streamed) : null;
|
||||
if (created === null || streamed === null || streamed <= created) hasCompleteGeneration = false;
|
||||
else generationMs += streamed - created;
|
||||
generationOutputTokens += parsed.usage.outputTokens;
|
||||
}
|
||||
numTurns++;
|
||||
}
|
||||
if (numTurns === 0 || !Number.isSafeInteger(numTurns) || !Number.isFinite(totalCostUsd)) {
|
||||
return { snapshot, summary: null };
|
||||
}
|
||||
|
||||
return {
|
||||
snapshot,
|
||||
summary: {
|
||||
usage,
|
||||
modelUsage: Object.fromEntries(modelUsage),
|
||||
...(hasCompleteCost && totalCostUsd > 0 ? { totalCostUsd } : {}),
|
||||
numTurns,
|
||||
durationMs: options.durationMs,
|
||||
...(hasCompleteGeneration && Number.isSafeInteger(generationMs) && generationMs > 0
|
||||
&& Number.isSafeInteger(generationOutputTokens) && generationOutputTokens > 0
|
||||
? { generationMs, generationOutputTokens } : {})
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { captureOpencodeRoundSnapshot, fetchOpencodeRoundSummary } from './opencodeRoundSummary';
|
||||
|
||||
const signal = new AbortController().signal;
|
||||
const api = { version: 'v2' as const, password: 'fixture-password' };
|
||||
const base = { baseUrl: 'http://127.0.0.1:48273', sessionId: 'session/id', signal, api };
|
||||
const user = { id: 'prompt', type: 'user', text: 'round prompt' };
|
||||
const assistant = (id: string, overrides: Record<string, unknown> = {}) => ({
|
||||
id, type: 'assistant', model: { providerID: 'fixture', id: 'model' },
|
||||
tokens: { input: 10, output: 2, reasoning: 1, cache: { read: 5, write: 3 } }, cost: 0,
|
||||
...overrides
|
||||
});
|
||||
function request(data: unknown) {
|
||||
return {
|
||||
...base, promptText: user.text, snapshot: { messageIds: ['old'] }, durationMs: 100,
|
||||
fetchImpl: vi.fn(async () => Response.json({ data }))
|
||||
};
|
||||
}
|
||||
|
||||
describe('OpenCode v2 round usage', () => {
|
||||
it('captures flat IDs using the authenticated v2 endpoint at its server page limit', async () => {
|
||||
const opts = request([{ id: 'old', type: 'idle' }]);
|
||||
await expect(captureOpencodeRoundSnapshot(opts)).resolves.toEqual({ messageIds: ['old'] });
|
||||
expect(opts.fetchImpl).toHaveBeenCalledWith(
|
||||
'http://127.0.0.1:48273/api/session/session%2Fid/message?limit=200',
|
||||
expect.objectContaining({ method: 'GET', headers: { authorization: 'Basic b3BlbmNvZGU6Zml4dHVyZS1wYXNzd29yZA==' } })
|
||||
);
|
||||
});
|
||||
|
||||
it('aggregates assistant and billed compaction calls while excluding native compaction and control rows', async () => {
|
||||
const opts = request([
|
||||
assistant('final', { cost: 0.03 }),
|
||||
{ id: 'synthetic', type: 'synthetic', text: 'continue' },
|
||||
assistant('compact', { type: 'compaction', status: 'completed', cost: 0.01 }),
|
||||
{ id: 'native-compact', type: 'compaction', status: 'completed', native: { messages: [] } },
|
||||
assistant('tool'), user, { id: 'old', type: 'idle' }
|
||||
]);
|
||||
const result = await fetchOpencodeRoundSummary(opts);
|
||||
expect(result?.summary).toEqual({
|
||||
usage: { inputTokens: 30, outputTokens: 9, cacheReadInputTokens: 15, cacheCreationInputTokens: 9 },
|
||||
modelUsage: { 'fixture/model': { inputTokens: 30, outputTokens: 9, cacheReadInputTokens: 15, cacheCreationInputTokens: 9 } },
|
||||
totalCostUsd: 0.04, numTurns: 3, durationMs: 100
|
||||
});
|
||||
expect(opts.fetchImpl).toHaveBeenCalledWith(
|
||||
'http://127.0.0.1:48273/api/session/session%2Fid/message?limit=200', expect.anything()
|
||||
);
|
||||
});
|
||||
|
||||
it('preserves valid tokens but omits round cost if any v2 call has no cost', async () => {
|
||||
const result = await fetchOpencodeRoundSummary(request([user, assistant('one', { cost: 0.03 }), assistant('two', { cost: undefined })]));
|
||||
expect(result?.summary).toMatchObject({ numTurns: 2, usage: { inputTokens: 20, outputTokens: 6 } });
|
||||
expect(result?.summary).not.toHaveProperty('totalCostUsd');
|
||||
});
|
||||
|
||||
it.each([
|
||||
[null], [user, { id: 'bad', type: 'assistant' }], [user, assistant('same'), assistant('same')],
|
||||
[assistant('outside-window')], [user, assistant('bad', { tokens: { input: -1 } })],
|
||||
[user, assistant('bad', { cost: null })], [user, assistant('bad', { model: [] })],
|
||||
[user, assistant('bad', { type: 'compaction', status: 'running' })]
|
||||
])('fails closed for malformed or unassociated messages %j', async (...data) => {
|
||||
const result = await fetchOpencodeRoundSummary(request(data));
|
||||
expect(result?.summary ?? null).toBeNull();
|
||||
});
|
||||
|
||||
it('rejects malformed envelope and pre-snapshot identity failures without throwing', async () => {
|
||||
for (const data of [[null], [user, user]]) {
|
||||
await expect(captureOpencodeRoundSnapshot(request(data))).resolves.toBeNull();
|
||||
}
|
||||
await expect(captureOpencodeRoundSnapshot({ ...base, fetchImpl: vi.fn(async () => Response.json([])) })).resolves.toBeNull();
|
||||
});
|
||||
|
||||
it('omits optional metadata on unauthorized, malformed, or stalled v2 responses', async () => {
|
||||
for (const response of [new Response('not authorized', { status: 401 }), new Response('{', { status: 200 })]) {
|
||||
await expect(captureOpencodeRoundSnapshot({ ...base, fetchImpl: vi.fn(async () => response) })).resolves.toBeNull();
|
||||
}
|
||||
await expect(captureOpencodeRoundSnapshot({
|
||||
...base, timeoutMs: 10,
|
||||
fetchImpl: vi.fn(async () => ({ ok: true, json: () => new Promise(() => {}) }) as Response)
|
||||
})).resolves.toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
describe('OpenCode v2 provider throughput', () => {
|
||||
const step = (id: string, time: unknown = { created: 1_000, streamed: 1_500, completed: 9_000 }) => assistant(id, { time });
|
||||
|
||||
it('weights all assistant steps including reasoning, excluding tool settlement and billed compaction', async () => {
|
||||
const result = await fetchOpencodeRoundSummary(request([
|
||||
user, step('tool'), step('final', { created: 10_000, streamed: 11_000 }),
|
||||
assistant('compact', { type: 'compaction', status: 'completed' })
|
||||
]));
|
||||
expect(result?.summary).toMatchObject({
|
||||
usage: { outputTokens: 9 }, numTurns: 3, durationMs: 100,
|
||||
generationMs: 1_500, generationOutputTokens: 6
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ interval: 'zero', time: { created: 1_000, streamed: 1_000 }, invalidFirst: true },
|
||||
{ interval: 'zero', time: { created: 1_000, streamed: 1_000 }, invalidFirst: false },
|
||||
{ interval: 'reversed', time: { created: 1_000, streamed: 999 }, invalidFirst: true },
|
||||
{ interval: 'reversed', time: { created: 1_000, streamed: 999 }, invalidFirst: false }
|
||||
])('omits both generation fields for a mixed $interval interval (invalid first: $invalidFirst)', async ({ time, invalidFirst }) => {
|
||||
const invalid = { ...step('invalid', time), cost: 0.01 };
|
||||
const valid = { ...step('valid'), cost: 0.02 };
|
||||
const result = await fetchOpencodeRoundSummary(request([user, ...(invalidFirst ? [invalid, valid] : [valid, invalid])]));
|
||||
expect(result?.summary).not.toHaveProperty('generationMs');
|
||||
expect(result?.summary).not.toHaveProperty('generationOutputTokens');
|
||||
expect(result?.summary).toEqual({
|
||||
usage: { inputTokens: 20, outputTokens: 6, cacheReadInputTokens: 10, cacheCreationInputTokens: 6 },
|
||||
modelUsage: { 'fixture/model': { inputTokens: 20, outputTokens: 6, cacheReadInputTokens: 10, cacheCreationInputTokens: 6 } },
|
||||
totalCostUsd: 0.03, numTurns: 2, durationMs: 100
|
||||
});
|
||||
});
|
||||
|
||||
it('ignores invalid compaction timing while preserving the positive assistant-only pair and billed totals', async () => {
|
||||
const result = await fetchOpencodeRoundSummary(request([
|
||||
user, { ...step('valid'), cost: 0.02 },
|
||||
assistant('compact', { type: 'compaction', status: 'completed', cost: 0.01, time: { created: 10, streamed: 9 } })
|
||||
]));
|
||||
expect(result?.summary).toEqual({
|
||||
usage: { inputTokens: 20, outputTokens: 6, cacheReadInputTokens: 10, cacheCreationInputTokens: 6 },
|
||||
modelUsage: { 'fixture/model': { inputTokens: 20, outputTokens: 6, cacheReadInputTokens: 10, cacheCreationInputTokens: 6 } },
|
||||
totalCostUsd: 0.03, numTurns: 2, durationMs: 100,
|
||||
generationMs: 500, generationOutputTokens: 3
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
undefined, null, [], {}, { streamed: 20 }, { created: 10 },
|
||||
{ created: -1, streamed: 20 }, { created: 10, streamed: Infinity },
|
||||
{ created: NaN, streamed: 20 }, { created: 1, streamed: Number.MAX_SAFE_INTEGER + 1 }, { created: '10', streamed: 20 },
|
||||
{ created: 10, streamed: 10 }, { created: 20, streamed: 10 }
|
||||
])('preserves usage while omitting throughput for incomplete or zero time %j', async (time) => {
|
||||
const result = await fetchOpencodeRoundSummary(request([user, assistant('one', { time })]));
|
||||
expect(result?.summary).toMatchObject({ usage: { outputTokens: 3 } });
|
||||
expect(result?.summary).not.toHaveProperty('generationMs');
|
||||
expect(result?.summary).not.toHaveProperty('generationOutputTokens');
|
||||
});
|
||||
|
||||
it('hides the whole rate when just one assistant boundary is missing', async () => {
|
||||
const result = await fetchOpencodeRoundSummary(request([user, step('valid'), step('missing', {})]));
|
||||
expect(result?.summary).toMatchObject({ numTurns: 2 });
|
||||
expect(result?.summary).not.toHaveProperty('generationMs');
|
||||
});
|
||||
|
||||
it('omits throughput for zero output and v1 even if timestamps are present', async () => {
|
||||
const zero = await fetchOpencodeRoundSummary(request([user, assistant('zero', {
|
||||
time: { created: 1, streamed: 100 },
|
||||
tokens: { input: 1, output: 0, reasoning: 0, cache: { read: 0, write: 0 } }
|
||||
})]));
|
||||
expect(zero?.summary).not.toHaveProperty('generationMs');
|
||||
const opts = request([]);
|
||||
const v1 = await fetchOpencodeRoundSummary({ ...opts, api: undefined, fetchImpl: async () => Response.json([
|
||||
{ info: { id: user.id, role: 'user' }, parts: [{ type: 'text', text: user.text }] },
|
||||
{ info: { ...step('one'), role: 'assistant', providerID: 'fixture', modelID: 'model' } }
|
||||
]) });
|
||||
expect(v1?.summary).toMatchObject({ numTurns: 1 });
|
||||
expect(v1?.summary).not.toHaveProperty('generationMs');
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user