mirror of
https://github.com/wu736139669/hapi.git
synced 2026-12-03 06:47:03 +00:00
* feat(shared): steer capability gates and live steered signal schemas - STEERING_SUPPORTED_FLAVORS / isSteeringSupportedForSession gate which agents can deliver queued messages into the active turn (pi, codex, cursor ACP; legacy stream-json cursor excluded) - AgentState.steeringActive, DecryptedMessage.steered and messages-consumed live signal (never persisted by the hub) * feat(cli): queue reservations and steered messages-consumed option - MessageQueue2 gains takeByLocalId/restoreReservation/ beginReservationDispatch/commitReservation so an async steer can reserve a queued row without racing the main loop's turn/start drain - emitMessagesConsumed accepts steered: true to mark mid-turn delivery * feat(codex): mid-turn steer via app-server turn/steer (#888) - CodexAppServerClient.steerTurn + TurnSteerParams/Response types - CodexRemoteLauncher registers the steer-queued-message RPC handler: reserves the queued row, validates it against the active turn (no control commands, matching mode hash), injects via turn/steer with an epoch guard that invalidates in-flight steers on abort/cleanup - steeringActive agent state tracks the active-turn window - hub syncEngine gate opens to codex; messages-consumed relays steered * feat(web): Steered badge and steer gating for codex sessions - HappyUserMessage shows a ↳ Steered badge fed by the live messages-consumed steered signal, preserved across server echoes and refetches (mergeMessages carries the optimistic marker) - SessionChat gates canSteer via isSteeringSupportedForSession instead of the pi-only check - clearStaleQueuedStatus normalizes a queued status on an invoked message - fix(web): drop duplicate showSessionSummaryInChat in markdown test (upstream typecheck breakage) * feat(acp): split request dispatch from completion and add soft steer - AcpStdioTransport.sendRequestWithDispatch separates stdin-accepted dispatch from the JSON-RPC response, keeping sendRequest behavior unchanged - AcpSdkBackend tracks concurrent session/prompt requests with an activePromptRequests counter (main prompt + soft steers); response completion stays pending until every concurrent prompt settles - beginSoftSteerPrompt kicks off a concurrent session/prompt (Cursor GUI Send semantics — no cancel, no handler swap) returning {dispatched, completed}; softSteerPrompt awaits the full response for direct callers * feat(cursor): mid-turn soft steer via concurrent session/prompt (#888) - CursorAcpRemoteLauncher registers the steer-queued-message RPC handler: reserves the queued row, rejects control commands and mode mismatches, then soft-injects via beginSoftSteerPrompt without canceling the in-flight turn - Acks the hub once stdin accepts the inject (not on turn completion) to stay inside the 30s RPC window; the launcher stays busy until the concurrent prompt settles so handlers are not swapped mid-inject - steeringActive agent state mirrors the active-turn window; abort and cleanup reset it and invalidate pending steers - Legacy stream-json Cursor sessions register a steer handler that reports unsupported * fix(codex,shared): address bot findings on steer gate and ambiguous turn/steer - STEERING_SUPPORTED_FLAVORS / isSteeringSupportedForSession advertise codex and pi only; cursor joins when its soft-steer handler lands (#1609) - turn/steer now splits dispatch (stdin accepted) from completion (turn finished): the hub RPC acks once dispatch succeeds — never on the concurrent turn's completion, which can exceed the 30s RPC window - queue row commits only after the turn settles; a rejected/aborted steer restores the row so the message still delivers via turn/start, and a dispatched steer is never restored (no duplicate delivery) - steer carries clientUserMessageId (echoed as userMessage.clientId) so ambiguous transport failures can reconcile the thread later - client tests cover dispatch/complete split and stdin-write failure * feat(shared): advertise cursor in the steer gate now that its handler lands Cursor ACP sessions pass the web and hub steer gates; legacy stream-json cursor sessions stay excluded. * fix(codex): reconcile dispatched steers before restoring; align error copy - A dispatched turn/steer whose completion fails (disconnect / protocol error) is now reconciled via thread/read by clientUserMessageId before the queued row is restored — the instruction is only re-delivered by turn/start when the thread never received it - Reconcile targets the pinned steer thread, not whichever turn is current when completion fails - syncEngine unsupported-flavor error now matches the capability gate (Pi and Codex only until the cursor handler lands) - launcher tests cover steer success (ack on dispatch), reconcile-accepted and reconcile-rejected outcomes * fix(codex): consume the row at dispatch; drop background reconcile - The hub RPC acks and the queue row is consumed as soon as stdin accepts turn/steer; completion is background-only logging. A dispatched steer is never restored, so the same localId cannot be re-delivered via turn/start after the caller was told the steer succeeded - Dispatch failure (stdin write error) still restores the row and reports failure - steer.completed rejection is always handled (no unhandled rejection on the dispatch-failure path) - tests updated: completion failure after dispatch keeps the row consumed; dispatch failure restores it * fix(cursor): consume the row at dispatch; keep waiters for prompt gating - The hub RPC acks and the queue row is consumed as soon as stdin accepts the concurrent session/prompt; completion is background-only. A dispatched steer is never restored (no duplicate via the next prompt) - softSteerWaiters are registered before awaiting dispatch so the main loop's finally cannot start the next prompt mid-inject; they still gate prompt handover on completion - tests updated: post-dispatch ACP rejection keeps the row consumed * fix(cursor,hub): never hang teardown on unresolved soft steer; align diagnostics - Prompt-finally waits for soft-steer completion only when not exiting; the outer finally no longer waits at all — cleanup() disconnects the ACP transport, which rejects pending requests and settles the waiters - syncEngine gate diagnostics and JSDoc name all supported flavors (Pi, Codex, Cursor ACP) - regression test: Switch with an unresolved soft-steer completion still reaches teardown * fix(codex): distinguish definite rejection from indeterminate completion - Transport-level failures (timeout, abort, disconnect, spawn, protocol) carry an indeterminate marker; explicit JSON-RPC error responses do not - After a dispatched steer, turn completion resolves → commit + consumed; a definite app-server rejection restores the row (instruction was never accepted, so turn/start cannot duplicate it); an indeterminate outcome leaves the row reserved so it can never be delivered twice - Completion handling registers before awaiting dispatch so the dispatch-failure path cannot leak an unhandled rejection - client/launcher tests cover explicit rejection (restore), indeterminate outcome (row stays reserved) and dispatch failure * fix(codex): reconcile indeterminate steers instead of a permanent reservation - After an indeterminate completion (disconnect/protocol), reconcile the thread by clientUserMessageId immediately: accepted → commit + consumed, provably rejected → restore, still unreadable → keep the reservation and retry from the main-loop top on later passes (post-reconnect) - A row never sits in dispatching forever: the hub cannot stamp it invoked while the instruction may never have been accepted - tests: indeterminate keeps reserved while thread unreadable; accepted reconciliation consumes; rejected path restores * fix(cursor): abort drops soft-steer waiters so the next prompt never blocks - Ordinary Abort (shouldExit false) now clears softSteerWaiters: the prompt finally cannot wait forever on a soft steer whose completion is unbounded; the ACP cancel rejects in-flight requests, and cleanup() settles leftovers on session end - regression test: unresolved soft-steer completion after Abort no longer blocks the next prompt * fix(codex): accept all thread item shapes; retry reconcile; ack through abort - Reconcile matcher accepts userMessage/user_message with clientId/ client_id, matching the shapes the thread parser supports — an accepted steer can no longer be misclassified as rejected - A pending reconciliation schedules a wakeLoop retry, so a temporary app-server outage cannot strand the reservation behind waitForTurnOrRecovery - The success-path ACK no longer checks the steer epoch: the hub already reported steered on dispatch, so commit + messages-consumed must reach it even when an abort resets the queue in between * fix(cursor,acp): abort force-settles soft-steer bookkeeping - AcpSdkBackend.abortSoftSteers() drops the concurrent-prompt counter and notifies response-complete so the next turn's waitForResponseComplete() cannot block on a soft steer that will never settle after abort - handleAbort calls it before clearing the waiters; the main prompt's own finishPromptRequest stays guarded by Math.max(0, ...) - unit tests cover counter release and no-op when idle * fix(codex): reinit reconnected app-server; keep reconcile retries alive - thread/read after a disconnect auto-connects a fresh app-server, which must be initialized before any request — reconcile now ensures connect + initialize (isConnected getter added to the client) - every still-unknown loop-top reconciliation schedules the next retry, so recovery without external traffic is eventually observed - launcher mock gains isConnected * test(acp): match finishPromptRequest epoch signature in whitebox test * fix(codex): timer-driven reconciliation; init tracking; abort-safe ACK - Reconciliation runs on a self-rescheduling 1s timer independent of the main loop (wakes it too), so idle loops and waitForTurnOrRecovery still observe app-server recovery; abort clears nothing implicitly — the ACK path commits and consumes even when the reservation was cancelled - Absence of a durable client id is ambiguous: unmatched reads stay 'unknown' and keep retrying instead of restoring the row - CodexAppServerClient tracks initialized state (reset on disconnect/exit) so ensureAppServerInitialized re-initializes a fresh process before thread/read; initialize failures leave the flag false for the next retry - tests: accepted reconciliation via scheduled timer, indeterminate keeps reserved, explicit rejection restores * fix(codex): bind reconciliation to the launcher lifecycle - runSteerReconciliation clears any armed retry timer on entry and never installs a second one, so loop-top and timer-driven passes cannot multiply - shuttingDown is set when the main loop ends: timers are cleared and the pending map is dropped, so an unresolved steer can never respawn an app-server after cleanup (remote-to-local switch included) * fix(cursor): abort releases an in-progress soft-steer wait - The prompt-finally wait races Promise.allSettled against the abort signal: an Abort that clears the waiters now also releases a wait that already started, so the launcher always reaches the next queued prompt * fix(codex): report steered only after app-server acceptance - The handler now awaits steer.completed (the inject-acceptance response): an explicit JSON-RPC rejection surfaces as failed and restores the row for the normal turn/start path instead of a false steered - Transport failure after dispatch reports 'Steer outcome is being reconciled' and keeps the row reserved while the timer-driven thread reconciliation runs - dispatch-failure path also swallows the paired completion rejection * fix(cursor,acp): commit on ACP acceptance; distinguish transport failures - AcpStdioTransport marks transport-level failures (timeout, closed, stdin write) as indeterminate; explicit JSON-RPC error responses are not - The steer handler commits + consumes on completion (ACP acceptance) and restores the row on an explicit rejection; an indeterminate transport failure keeps the row reserved so a delivered instruction is never re-sent, and the ACK reaches the hub even when abort reset the queue - launcher/transport tests updated for the three outcomes * fix(steer): tri-state cancel, clear-safe reservations, bounded acceptance wait - MessageQueue2.cancelByLocalId returns 'in-flight' for a dispatching steer reservation: the hub neither deletes the row nor stamps invoked_at (new CancelMessageResponse 'busy' status; web restores the optimistic row); pushIsolateAndClear and reset/close share cancelReservations so /clear-style commands cannot have a rejected steer resurrect a discarded prompt - turn/steer acceptance wait bounded at 25s (< hub 30s RPC timeout): a lost response is indeterminate and funnels into thread reconciliation instead of stranding the reservation - tests updated for the tri-state cancel contract * test(cursor): match tri-state cancel contract for dispatching steers * fix(cursor): drop duplicate promptInFlight declaration after upstream merge * fix(codex,web): busy-aware edit flow; bound reconciliation reads - QueuedMessagesBar edit flow treats a 'busy' cancel as unsuccessful: it never prefills the composer when the row is inside an async steer, so a second client cannot send a duplicate - reconcileSteerByClientId bounds thread/read with a 5s timeout so a connected-but-silent app-server cannot hold the reservation in-flight indefinitely * fix(steer): inFlight-dominated cancel acks; bounded reconciliation - hub cancel-queued-message acks check inFlight before removed: a stale duplicate socket reporting removed can no longer delete the durable row while another socket is dispatching the steer - reconciliation entries expire after 60s and mark delivered: after the rejection window, a dispatched steer that the app-server never proved (client ids dropped on restart) is committed instead of polling thread/read forever - pre-dispatch failures (abort before write included) never enter reconciliation — they restore the row and report failure * fix(cursor,acp,web): indeterminate close marks, steer gating precision - AcpStdioTransport.rejectAllPending marks close/protocol failures indeterminate, so an accepted-but-close-interrupted soft steer restores nothing (no duplicate delivery) - the abort race in the soft-steer wait removes its listener in finally (no accumulation across repeated waits) - SessionChat gates the Steer button on agentState.steeringActive for codex/cursor instead of the queued-grace thinking flag, so Steer is not exposed before the launcher can accept it - codex pre-dispatch abort never enters reconciliation (merged from #1606) * fix(steer): persist indeterminate outcomes without replay * fix(cursor): hold ambiguous steers for explicit resolution * fix(steer): make ambiguous delivery restart-safe * fix(cursor): make ambiguous delivery restart-safe * fix(steer): recover crash-held rows and preserve retry dedup * fix(steer): ack retries and bound stdin dispatch * fix(cursor): reject steers when prompt generation changes * fix(steer): reconcile indeterminate dispatches and serialize retries * fix(cursor): preserve soft-steer reservations across abort * fix(codex): classify stdin callback failures as indeterminate * fix(steer): recheck indeterminate cancels after ACK * fix(steer): close retry and abort races * fix(cursor): hold ambiguous dispatch failures * fix(steer): serialize live retries and abort admission * fix(steer): distinguish live dispatching from unknown * fix(cursor): bound ACP dispatch acknowledgements * fix(steer): keep ACK failures held and reconcile busy cancel * fix(cursor): preserve state when dispatch ACK is uncertain * fix(steer): distinguish held cancel from removal * fix(store): combine schema v24 migrations * fix(cursor): distinguish held cancel from removal * fix(store): reserve schema v25 for steer delivery state * fix(cursor): suppress late ACP updates after abort * fix(steer): keep held cancel state and notify requeue * fix(cursor): isolate late updates after abort * fix(steer): release explicitly cancelled unknown reservations * test(cursor): cover explicit held cancellation * fix(codex): reject cancelled reservations before native steer * fix(cursor): reject cancelled reservations before ACP steer * fix(codex): make reservation restore atomic with state * fix(cursor): make reservation restore atomic with state * fix(codex): terminate abandoned transport writes * fix(cursor): hard-stop abandoned writes and update native queue state * fix(steer): own abandoned app-server lifecycle and consume races * fix(cursor): isolate aborts and add native retry resolution * fix(codex): confirm dispatch and recover abandoned turns * test(codex): mock abandoned transport callback * fix(native): reconcile retry responses * fix(codex): clear visible turn state on transport loss * fix(steer): claim retries and cover native delivery state * fix(native): resync busy cancel outcomes * fix(native): preserve indeterminate state on Android hydration * fix(steer): make retry claims single-winner * fix(cursor): hold restore failures for explicit resolution * fix(steer): serialize concurrent retry claims * fix(socket): tolerate missing steer-state ACK callbacks * fix(native): serialize retry operations * docs(web): document unknown steer delivery and retry controls * fix(steer): handle retry failures and abort-before-connect * fix(cursor): drain foreground prompt after soft-steer abort * fix(steer): reinitialize after transport loss and finish iOS retry errors * fix(steer): preserve indeterminate rows across reconnect gaps * test(web): mock indeterminate queued recovery state * fix(steer): recover consumed ACK tombstones * fix(steer): expose consumed cancel tombstones * fix(cursor): drain soft steers before handler replacement * fix(cursor): preserve buffered output on abort
1786 lines
75 KiB
TypeScript
1786 lines
75 KiB
TypeScript
import { afterEach, describe, expect, it, vi } from 'vitest';
|
|
import type { AgentMessage } from '@/agent/types';
|
|
import { AcpSdkBackend } from './AcpSdkBackend';
|
|
import { AcpMessageHandler } from './AcpMessageHandler';
|
|
import { buildAcpStdioSpawnOptions } from './AcpStdioTransport';
|
|
import { ACP_SESSION_UPDATE_TYPES } from './constants';
|
|
|
|
function sleep(ms: number): Promise<void> {
|
|
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
}
|
|
|
|
type BackendStatics = {
|
|
UPDATE_QUIET_PERIOD_MS: number;
|
|
UPDATE_DRAIN_TIMEOUT_MS: number;
|
|
PRE_PROMPT_UPDATE_QUIET_PERIOD_MS: number;
|
|
PRE_PROMPT_UPDATE_DRAIN_TIMEOUT_MS: number;
|
|
LATE_FLUSH_INTERVAL_MS: number;
|
|
LATE_FLUSH_QUIET_PERIOD_MS: number;
|
|
LATE_FLUSH_WINDOW_MS: number;
|
|
};
|
|
|
|
const backendStatics = AcpSdkBackend as unknown as BackendStatics;
|
|
const originalStatics = {
|
|
updateQuietPeriodMs: backendStatics.UPDATE_QUIET_PERIOD_MS,
|
|
updateDrainTimeoutMs: backendStatics.UPDATE_DRAIN_TIMEOUT_MS,
|
|
prePromptUpdateQuietPeriodMs: backendStatics.PRE_PROMPT_UPDATE_QUIET_PERIOD_MS,
|
|
prePromptUpdateDrainTimeoutMs: backendStatics.PRE_PROMPT_UPDATE_DRAIN_TIMEOUT_MS,
|
|
lateFlushIntervalMs: backendStatics.LATE_FLUSH_INTERVAL_MS,
|
|
lateFlushQuietPeriodMs: backendStatics.LATE_FLUSH_QUIET_PERIOD_MS,
|
|
lateFlushWindowMs: backendStatics.LATE_FLUSH_WINDOW_MS
|
|
};
|
|
const originalPlatformDescriptor = Object.getOwnPropertyDescriptor(process, 'platform');
|
|
|
|
function setPlatform(value: string) {
|
|
Object.defineProperty(process, 'platform', {
|
|
value,
|
|
configurable: true
|
|
});
|
|
}
|
|
|
|
afterEach(() => {
|
|
backendStatics.UPDATE_QUIET_PERIOD_MS = originalStatics.updateQuietPeriodMs;
|
|
backendStatics.UPDATE_DRAIN_TIMEOUT_MS = originalStatics.updateDrainTimeoutMs;
|
|
backendStatics.PRE_PROMPT_UPDATE_QUIET_PERIOD_MS = originalStatics.prePromptUpdateQuietPeriodMs;
|
|
backendStatics.PRE_PROMPT_UPDATE_DRAIN_TIMEOUT_MS = originalStatics.prePromptUpdateDrainTimeoutMs;
|
|
backendStatics.LATE_FLUSH_INTERVAL_MS = originalStatics.lateFlushIntervalMs;
|
|
backendStatics.LATE_FLUSH_QUIET_PERIOD_MS = originalStatics.lateFlushQuietPeriodMs;
|
|
backendStatics.LATE_FLUSH_WINDOW_MS = originalStatics.lateFlushWindowMs;
|
|
if (originalPlatformDescriptor) {
|
|
Object.defineProperty(process, 'platform', originalPlatformDescriptor);
|
|
}
|
|
});
|
|
|
|
describe('AcpSdkBackend', () => {
|
|
it('forwards ACP session_info_update titles without requiring an active prompt', () => {
|
|
const backend = new AcpSdkBackend({ command: 'agent' });
|
|
const updates: Array<{ sessionId: string | null; title: string | null }> = [];
|
|
backend.setSessionInfoUpdateListener((update) => updates.push(update));
|
|
|
|
const backendInternal = backend as unknown as {
|
|
handleSessionUpdate: (params: unknown) => void;
|
|
};
|
|
backendInternal.handleSessionUpdate({
|
|
sessionId: 'session-1',
|
|
update: {
|
|
sessionUpdate: ACP_SESSION_UPDATE_TYPES.sessionInfoUpdate,
|
|
title: 'Native session title'
|
|
}
|
|
});
|
|
backendInternal.handleSessionUpdate({
|
|
sessionId: 'session-1',
|
|
update: {
|
|
sessionUpdate: ACP_SESSION_UPDATE_TYPES.sessionInfoUpdate,
|
|
updatedAt: '2026-07-12T00:00:00Z'
|
|
}
|
|
});
|
|
|
|
expect(updates).toEqual([{ sessionId: 'session-1', title: 'Native session title' }]);
|
|
});
|
|
|
|
it('refreshes native titles through ACP session/list', async () => {
|
|
const backend = new AcpSdkBackend({ command: 'opencode' });
|
|
const calls: Array<{ method: string; params: unknown; options: unknown }> = [];
|
|
const backendInternal = backend as unknown as {
|
|
transport: {
|
|
sendRequest: (method: string, params: unknown, options?: unknown) => Promise<unknown>;
|
|
} | null;
|
|
};
|
|
backendInternal.transport = {
|
|
sendRequest: async (method, params, options) => {
|
|
calls.push({ method, params, options });
|
|
return {
|
|
sessions: [
|
|
{ sessionId: 'other', title: 'Other title' },
|
|
{ sessionId: 'session-1', title: 'Native OpenCode title' }
|
|
]
|
|
};
|
|
}
|
|
};
|
|
const updates: Array<{ sessionId: string | null; title: string | null }> = [];
|
|
backend.setSessionInfoUpdateListener((update) => updates.push(update));
|
|
|
|
await backend.refreshSessionInfo('session-1', '/workspace');
|
|
|
|
expect(calls).toEqual([{
|
|
method: 'session/list',
|
|
params: { cwd: '/workspace' },
|
|
options: { timeoutMs: 5000 }
|
|
}]);
|
|
expect(updates).toEqual([{ sessionId: 'session-1', title: 'Native OpenCode title' }]);
|
|
});
|
|
|
|
it('retries session/list while an asynchronously generated title is still a placeholder', async () => {
|
|
vi.useFakeTimers();
|
|
try {
|
|
const backend = new AcpSdkBackend({ command: 'opencode' });
|
|
const titles = ['New session - 2026-07-12T00:00:00.000Z', 'Native OpenCode title'];
|
|
const backendInternal = backend as unknown as {
|
|
transport: { sendRequest: () => Promise<unknown> } | null;
|
|
};
|
|
backendInternal.transport = {
|
|
sendRequest: async () => ({
|
|
sessions: [{ sessionId: 'session-1', title: titles.shift() }]
|
|
})
|
|
};
|
|
const updates: Array<{ sessionId: string | null; title: string | null }> = [];
|
|
backend.setSessionInfoUpdateListener((update) => updates.push(update));
|
|
|
|
await backend.refreshSessionInfo('session-1', '/workspace');
|
|
await vi.runAllTimersAsync();
|
|
|
|
expect(updates).toEqual([
|
|
{ sessionId: 'session-1', title: 'New session - 2026-07-12T00:00:00.000Z' },
|
|
{ sessionId: 'session-1', title: 'Native OpenCode title' }
|
|
]);
|
|
} finally {
|
|
vi.useRealTimers();
|
|
}
|
|
});
|
|
|
|
it('hides the ACP stdio shell on Windows', () => {
|
|
setPlatform('win32');
|
|
|
|
expect(buildAcpStdioSpawnOptions({ TEST_ENV: '1' })).toMatchObject({
|
|
env: { TEST_ENV: '1' },
|
|
stdio: ['pipe', 'pipe', 'pipe'],
|
|
shell: true,
|
|
windowsHide: true
|
|
});
|
|
});
|
|
|
|
it('allows the permission handler to resolve requests immediately', async () => {
|
|
const backend = new AcpSdkBackend({ command: 'opencode' });
|
|
let capturedRequestId: string | null = null;
|
|
|
|
backend.onPermissionRequest((request) => {
|
|
capturedRequestId = request.id;
|
|
void backend.respondToPermission(request.sessionId, request, {
|
|
outcome: 'selected',
|
|
optionId: 'allow-once'
|
|
});
|
|
});
|
|
|
|
const backendInternal = backend as unknown as {
|
|
handlePermissionRequest: (params: unknown, requestId: string | number | null) => Promise<unknown>;
|
|
};
|
|
|
|
await expect(backendInternal.handlePermissionRequest({
|
|
sessionId: 'session-1',
|
|
toolCall: {
|
|
toolCallId: 'tool-approve',
|
|
title: 'hapi_change_title',
|
|
rawInput: { title: 'Rename chat' }
|
|
},
|
|
options: [
|
|
{
|
|
optionId: 'allow-once',
|
|
name: 'Allow once',
|
|
kind: 'allow_once'
|
|
}
|
|
]
|
|
}, null)).resolves.toEqual({
|
|
outcome: {
|
|
outcome: 'selected',
|
|
optionId: 'allow-once'
|
|
}
|
|
});
|
|
|
|
expect(capturedRequestId).toBe('tool-approve');
|
|
});
|
|
|
|
it('uses session/set_model by default (gemini flavor)', async () => {
|
|
const backend = new AcpSdkBackend({ command: 'gemini' });
|
|
const calls: Array<{ method: string; params: unknown }> = [];
|
|
const backendInternal = backend as unknown as {
|
|
transport: { sendRequest: (method: string, params: unknown) => Promise<unknown>; close: () => Promise<void> } | null;
|
|
};
|
|
backendInternal.transport = {
|
|
sendRequest: async (method, params) => {
|
|
calls.push({ method, params });
|
|
return null;
|
|
},
|
|
close: async () => {}
|
|
};
|
|
|
|
await backend.setModel('session-1', 'gemini-2.5-pro');
|
|
|
|
expect(calls).toEqual([
|
|
{ method: 'session/set_model', params: { sessionId: 'session-1', modelId: 'gemini-2.5-pro' } }
|
|
]);
|
|
});
|
|
|
|
it('uses session/set_model when flavor is opencode', async () => {
|
|
const backend = new AcpSdkBackend({ command: 'opencode' });
|
|
const calls: Array<{ method: string; params: unknown }> = [];
|
|
const backendInternal = backend as unknown as {
|
|
transport: { sendRequest: (method: string, params: unknown) => Promise<unknown>; close: () => Promise<void> } | null;
|
|
};
|
|
backendInternal.transport = {
|
|
sendRequest: async (method, params) => {
|
|
calls.push({ method, params });
|
|
// OpenCode 1.14.30's set_model response: only an opaque _meta block.
|
|
return {
|
|
_meta: { opencode: { modelId: 'ollama/exaone:4.5-33b-q8', variant: null, availableVariants: [] } }
|
|
};
|
|
},
|
|
close: async () => {}
|
|
};
|
|
|
|
await backend.setModel('session-1', 'ollama/exaone:4.5-33b-q8', { flavor: 'opencode' });
|
|
|
|
expect(calls).toEqual([
|
|
{
|
|
method: 'session/set_model',
|
|
params: {
|
|
sessionId: 'session-1',
|
|
modelId: 'ollama/exaone:4.5-33b-q8'
|
|
}
|
|
}
|
|
]);
|
|
});
|
|
|
|
it('captures availableModels and currentModelId from session/new response', async () => {
|
|
const backend = new AcpSdkBackend({ command: 'opencode' });
|
|
const backendInternal = backend as unknown as {
|
|
transport: { sendRequest: (method: string, params: unknown) => Promise<unknown>; close: () => Promise<void> } | null;
|
|
};
|
|
const fixtureModels = [
|
|
{ modelId: 'ollama/exaone:4.5-33b-q8', name: 'Ollama (SER8)/EXAONE 4.5 33B Q8' },
|
|
{ modelId: 'mlx/qwen3:0.6b', name: 'MLX/Qwen3 0.6B' }
|
|
];
|
|
backendInternal.transport = {
|
|
sendRequest: async (method) => {
|
|
if (method === 'session/new') {
|
|
return {
|
|
sessionId: 'opencode-session-7',
|
|
models: {
|
|
availableModels: fixtureModels,
|
|
currentModelId: 'ollama/exaone:4.5-33b-q8'
|
|
}
|
|
};
|
|
}
|
|
return null;
|
|
},
|
|
close: async () => {}
|
|
};
|
|
|
|
const sessionId = await backend.newSession({ cwd: '/tmp/x', mcpServers: [] });
|
|
|
|
expect(sessionId).toBe('opencode-session-7');
|
|
expect(backend.getSessionModelsMetadata(sessionId)).toEqual({
|
|
availableModels: fixtureModels,
|
|
currentModelId: 'ollama/exaone:4.5-33b-q8'
|
|
});
|
|
});
|
|
|
|
it('captures Grok reasoning efforts from x.ai session metadata and switches with set_mode', async () => {
|
|
const backend = new AcpSdkBackend({ command: 'grok' });
|
|
const calls: Array<{ method: string; params: unknown }> = [];
|
|
const backendInternal = backend as unknown as {
|
|
transport: { sendRequest: (method: string, params: unknown) => Promise<unknown>; close: () => Promise<void> } | null;
|
|
};
|
|
backendInternal.transport = {
|
|
sendRequest: async (method, params) => {
|
|
calls.push({ method, params });
|
|
if (method === 'session/new') {
|
|
return {
|
|
sessionId: 'grok-session-1',
|
|
models: {
|
|
currentModelId: 'grok-4.5',
|
|
availableModels: [{
|
|
modelId: 'grok-4.5',
|
|
name: 'Grok 4.5',
|
|
_meta: {
|
|
reasoningEfforts: [
|
|
{ value: 'high', label: 'High Effort', default: true },
|
|
{ value: 'low', label: 'Low Effort', default: false }
|
|
]
|
|
}
|
|
}]
|
|
},
|
|
_meta: {
|
|
availableCommands: [{ name: 'auto' }],
|
|
'x.ai/sessionConfig': {
|
|
options: [
|
|
{ id: 'high', category: 'mode', label: 'High Effort', selected: false },
|
|
{ id: 'low', category: 'mode', label: 'Low Effort', selected: true }
|
|
]
|
|
}
|
|
}
|
|
};
|
|
}
|
|
if (method === 'session/set_mode') return { meta: null };
|
|
return null;
|
|
},
|
|
close: async () => {}
|
|
};
|
|
|
|
const sessionId = await backend.newSession({ cwd: '/tmp/x', mcpServers: [] });
|
|
|
|
expect(backend.getSessionModelsMetadata(sessionId)).toEqual({
|
|
availableModels: [{
|
|
modelId: 'grok-4.5',
|
|
name: 'Grok 4.5',
|
|
reasoningEfforts: [
|
|
{ value: 'high', name: 'High Effort', isDefault: true },
|
|
{ value: 'low', name: 'Low Effort', isDefault: false }
|
|
]
|
|
}],
|
|
currentModelId: 'grok-4.5'
|
|
});
|
|
expect(backend.getThoughtLevelConfigOption(sessionId)).toMatchObject({
|
|
currentValue: 'low',
|
|
options: [
|
|
{ value: 'high', name: 'High Effort' },
|
|
{ value: 'low', name: 'Low Effort' }
|
|
]
|
|
});
|
|
expect(backend.hasAvailableCommand(sessionId, 'auto')).toBe(true);
|
|
|
|
await backend.setMode(sessionId, 'high');
|
|
|
|
expect(calls).toContainEqual({
|
|
method: 'session/set_mode',
|
|
params: { sessionId, modeId: 'high' }
|
|
});
|
|
expect(backend.getThoughtLevelConfigOption(sessionId)?.currentValue).toBe('high');
|
|
});
|
|
|
|
it('merges configOptions model variants into availableModels when both are present', async () => {
|
|
const backend = new AcpSdkBackend({ command: 'agent' });
|
|
const backendInternal = backend as unknown as {
|
|
transport: { sendRequest: (method: string, params: unknown) => Promise<unknown>; close: () => Promise<void> } | null;
|
|
};
|
|
backendInternal.transport = {
|
|
sendRequest: async (method) => {
|
|
if (method === 'session/new') {
|
|
return {
|
|
sessionId: 'cursor-session-variants',
|
|
models: {
|
|
availableModels: [
|
|
{ modelId: 'composer-2.5[fast=true]', name: 'composer-2.5' }
|
|
],
|
|
currentModelId: 'composer-2.5[fast=true]'
|
|
},
|
|
configOptions: [
|
|
{
|
|
id: 'model-opt',
|
|
category: 'model',
|
|
currentValue: 'composer-2.5[fast=true]',
|
|
options: [
|
|
{ value: 'composer-2.5[fast=true]', name: 'composer-2.5' },
|
|
{ value: 'composer-2.5[fast=false]', name: 'composer-2.5' }
|
|
]
|
|
}
|
|
]
|
|
};
|
|
}
|
|
return null;
|
|
},
|
|
close: async () => {}
|
|
};
|
|
|
|
const sessionId = await backend.newSession({ cwd: '/tmp/x', mcpServers: [] });
|
|
|
|
expect(backend.getSessionModelsMetadata(sessionId)?.availableModels.map((entry) => entry.modelId).sort()).toEqual([
|
|
'composer-2.5[fast=false]',
|
|
'composer-2.5[fast=true]'
|
|
]);
|
|
});
|
|
|
|
it('captures model metadata from configOptions when models block is missing', async () => {
|
|
const backend = new AcpSdkBackend({ command: 'opencode' });
|
|
const backendInternal = backend as unknown as {
|
|
transport: { sendRequest: (method: string, params: unknown) => Promise<unknown>; close: () => Promise<void> } | null;
|
|
};
|
|
backendInternal.transport = {
|
|
sendRequest: async (method) => {
|
|
if (method === 'session/new') {
|
|
return {
|
|
sessionId: 'opencode-session-config-options',
|
|
configOptions: [
|
|
{
|
|
id: 'model',
|
|
category: 'model',
|
|
currentValue: 'opencode/big-pickle',
|
|
options: [
|
|
{ value: 'opencode/big-pickle', name: 'OpenCode Zen/Big Pickle' },
|
|
{ value: 'deepseek/deepseek-chat', name: 'DeepSeek/DeepSeek Chat' }
|
|
]
|
|
}
|
|
]
|
|
};
|
|
}
|
|
return null;
|
|
},
|
|
close: async () => {}
|
|
};
|
|
|
|
const sessionId = await backend.newSession({ cwd: '/tmp/x', mcpServers: [] });
|
|
|
|
expect(backend.getSessionModelsMetadata(sessionId)).toEqual({
|
|
availableModels: [
|
|
{ modelId: 'opencode/big-pickle', name: 'OpenCode Zen/Big Pickle' },
|
|
{ modelId: 'deepseek/deepseek-chat', name: 'DeepSeek/DeepSeek Chat' }
|
|
],
|
|
currentModelId: 'opencode/big-pickle'
|
|
});
|
|
});
|
|
|
|
it('returns undefined session metadata when session/new omits models', async () => {
|
|
const backend = new AcpSdkBackend({ command: 'gemini' });
|
|
const backendInternal = backend as unknown as {
|
|
transport: { sendRequest: (method: string, params: unknown) => Promise<unknown>; close: () => Promise<void> } | null;
|
|
};
|
|
backendInternal.transport = {
|
|
sendRequest: async (method) => {
|
|
if (method === 'session/new') {
|
|
return { sessionId: 'gemini-session-3' };
|
|
}
|
|
return null;
|
|
},
|
|
close: async () => {}
|
|
};
|
|
|
|
const sessionId = await backend.newSession({ cwd: '/tmp/x', mcpServers: [] });
|
|
|
|
expect(sessionId).toBe('gemini-session-3');
|
|
expect(backend.getSessionModelsMetadata(sessionId)).toBeUndefined();
|
|
});
|
|
|
|
it('optimistically updates currentModelId after a successful opencode setModel call', async () => {
|
|
const backend = new AcpSdkBackend({ command: 'opencode' });
|
|
const backendInternal = backend as unknown as {
|
|
transport: { sendRequest: (method: string, params: unknown) => Promise<unknown>; close: () => Promise<void> } | null;
|
|
};
|
|
const fixtureModels = [
|
|
{ modelId: 'ollama/a', name: 'a' },
|
|
{ modelId: 'ollama/b', name: 'b' }
|
|
];
|
|
backendInternal.transport = {
|
|
sendRequest: async (method) => {
|
|
if (method === 'session/new') {
|
|
return {
|
|
sessionId: 's1',
|
|
models: { availableModels: fixtureModels, currentModelId: 'ollama/a' }
|
|
};
|
|
}
|
|
if (method === 'session/set_model') {
|
|
// OpenCode 1.14.30: response carries only an opaque _meta block.
|
|
return { _meta: { opencode: { modelId: 'ollama/b' } } };
|
|
}
|
|
return null;
|
|
},
|
|
close: async () => {}
|
|
};
|
|
|
|
await backend.newSession({ cwd: '/tmp/x', mcpServers: [] });
|
|
await backend.setModel('s1', 'ollama/b', { flavor: 'opencode' });
|
|
|
|
// availableModels list is preserved from session/new; currentModelId is
|
|
// optimistically updated from the requested modelId.
|
|
expect(backend.getSessionModelsMetadata('s1')).toEqual({
|
|
availableModels: fixtureModels,
|
|
currentModelId: 'ollama/b'
|
|
});
|
|
});
|
|
|
|
|
|
|
|
it('captures and sets OpenCode thought-level config option', async () => {
|
|
const backend = new AcpSdkBackend({ command: 'opencode' });
|
|
const calls: Array<{ method: string; params: unknown }> = [];
|
|
const backendInternal = backend as unknown as {
|
|
transport: { sendRequest: (method: string, params: unknown) => Promise<unknown>; close: () => Promise<void> } | null;
|
|
};
|
|
backendInternal.transport = {
|
|
sendRequest: async (method, params) => {
|
|
calls.push({ method, params });
|
|
if (method === 'session/new') {
|
|
return {
|
|
sessionId: 's1',
|
|
configOptions: [{
|
|
id: 'effort',
|
|
name: 'Effort',
|
|
category: 'thought_level',
|
|
type: 'select',
|
|
currentValue: 'low',
|
|
options: [
|
|
{ value: 'low', name: 'Low' },
|
|
{ value: 'high', name: 'High' }
|
|
]
|
|
}]
|
|
};
|
|
}
|
|
if (method === 'session/set_config_option') {
|
|
return {
|
|
configOptions: [{
|
|
id: 'effort',
|
|
category: 'thought_level',
|
|
currentValue: 'high',
|
|
options: [{ value: 'high', name: 'High' }]
|
|
}]
|
|
};
|
|
}
|
|
return null;
|
|
},
|
|
close: async () => {}
|
|
};
|
|
|
|
await backend.newSession({ cwd: '/tmp/x', mcpServers: [] });
|
|
expect(backend.getThoughtLevelConfigOption('s1')).toMatchObject({
|
|
id: 'effort',
|
|
currentValue: 'low',
|
|
options: [{ value: 'low', name: 'Low' }, { value: 'high', name: 'High' }]
|
|
});
|
|
|
|
await backend.setConfigOption('s1', 'effort', 'high');
|
|
|
|
expect(calls).toContainEqual({
|
|
method: 'session/set_config_option',
|
|
params: { sessionId: 's1', configId: 'effort', value: 'high' }
|
|
});
|
|
expect(backend.getThoughtLevelConfigOption('s1')).toMatchObject({
|
|
id: 'effort',
|
|
currentValue: 'high'
|
|
});
|
|
});
|
|
|
|
it('emits turn_complete after trailing tool updates from the same turn', async () => {
|
|
backendStatics.UPDATE_QUIET_PERIOD_MS = 25;
|
|
backendStatics.UPDATE_DRAIN_TIMEOUT_MS = 200;
|
|
backendStatics.PRE_PROMPT_UPDATE_QUIET_PERIOD_MS = 1;
|
|
backendStatics.PRE_PROMPT_UPDATE_DRAIN_TIMEOUT_MS = 50;
|
|
backendStatics.LATE_FLUSH_INTERVAL_MS = 5;
|
|
backendStatics.LATE_FLUSH_QUIET_PERIOD_MS = 10;
|
|
backendStatics.LATE_FLUSH_WINDOW_MS = 50;
|
|
|
|
const backend = new AcpSdkBackend({ command: 'opencode' });
|
|
const backendInternal = backend as unknown as {
|
|
transport: {
|
|
sendRequest: (...args: unknown[]) => Promise<unknown>;
|
|
close: () => Promise<void>;
|
|
} | null;
|
|
handleSessionUpdate: (params: unknown) => void;
|
|
};
|
|
|
|
const messages: AgentMessage[] = [];
|
|
backendInternal.transport = {
|
|
sendRequest: async () => {
|
|
setTimeout(() => {
|
|
backendInternal.handleSessionUpdate({
|
|
sessionId: 'session-1',
|
|
update: {
|
|
sessionUpdate: ACP_SESSION_UPDATE_TYPES.agentMessageChunk,
|
|
content: { type: 'text', text: 'final answer' }
|
|
}
|
|
});
|
|
}, 0);
|
|
|
|
await sleep(5);
|
|
|
|
setTimeout(() => {
|
|
backendInternal.handleSessionUpdate({
|
|
sessionId: 'session-1',
|
|
update: {
|
|
sessionUpdate: ACP_SESSION_UPDATE_TYPES.toolCall,
|
|
toolCallId: 'tool-1',
|
|
title: 'Read',
|
|
rawInput: { path: 'README.md' },
|
|
status: 'in_progress'
|
|
}
|
|
});
|
|
}, 1);
|
|
|
|
setTimeout(() => {
|
|
backendInternal.handleSessionUpdate({
|
|
sessionId: 'session-1',
|
|
update: {
|
|
sessionUpdate: ACP_SESSION_UPDATE_TYPES.toolCallUpdate,
|
|
toolCallId: 'tool-1',
|
|
status: 'completed',
|
|
rawOutput: { ok: true }
|
|
}
|
|
});
|
|
}, 2);
|
|
|
|
return { stopReason: 'end_turn' };
|
|
},
|
|
close: async () => {}
|
|
};
|
|
|
|
await backend.prompt('session-1', [{ type: 'text', text: 'hello' }], (message) => {
|
|
messages.push(message);
|
|
});
|
|
|
|
expect(messages.map((message) => message.type)).toEqual([
|
|
'text',
|
|
'tool_call',
|
|
'tool_result',
|
|
'turn_complete'
|
|
]);
|
|
});
|
|
|
|
it('combines OpenCode usage_update and prompt usage into a usage message', async () => {
|
|
backendStatics.UPDATE_QUIET_PERIOD_MS = 25;
|
|
backendStatics.UPDATE_DRAIN_TIMEOUT_MS = 200;
|
|
backendStatics.PRE_PROMPT_UPDATE_QUIET_PERIOD_MS = 1;
|
|
backendStatics.PRE_PROMPT_UPDATE_DRAIN_TIMEOUT_MS = 50;
|
|
backendStatics.LATE_FLUSH_INTERVAL_MS = 5;
|
|
backendStatics.LATE_FLUSH_QUIET_PERIOD_MS = 10;
|
|
backendStatics.LATE_FLUSH_WINDOW_MS = 50;
|
|
|
|
const backend = new AcpSdkBackend({ command: 'opencode' });
|
|
const backendInternal = backend as unknown as {
|
|
transport: {
|
|
sendRequest: (...args: unknown[]) => Promise<unknown>;
|
|
close: () => Promise<void>;
|
|
} | null;
|
|
handleSessionUpdate: (params: unknown) => void;
|
|
};
|
|
|
|
const messages: AgentMessage[] = [];
|
|
backendInternal.transport = {
|
|
sendRequest: async () => {
|
|
setTimeout(() => {
|
|
backendInternal.handleSessionUpdate({
|
|
sessionId: 'session-1',
|
|
update: {
|
|
sessionUpdate: 'usage_update',
|
|
used: 13_879,
|
|
size: 65_536,
|
|
}
|
|
});
|
|
}, 0);
|
|
|
|
await sleep(5);
|
|
|
|
return {
|
|
stopReason: 'end_turn',
|
|
usage: {
|
|
totalTokens: 13_897,
|
|
inputTokens: 8_119,
|
|
outputTokens: 2,
|
|
thoughtTokens: 11,
|
|
cachedReadTokens: 5_760,
|
|
cachedWriteTokens: 5
|
|
}
|
|
};
|
|
},
|
|
close: async () => {}
|
|
};
|
|
|
|
await backend.prompt('session-1', [{ type: 'text', text: 'hello' }], (message) => {
|
|
messages.push(message);
|
|
});
|
|
|
|
expect(messages).toContainEqual({
|
|
type: 'usage',
|
|
inputTokens: 8_119,
|
|
outputTokens: 2,
|
|
cacheReadTokens: 5_760,
|
|
cacheCreationTokens: 5,
|
|
thoughtTokens: 11,
|
|
totalTokens: 13_897,
|
|
contextTokens: 13_879,
|
|
contextWindow: 65_536
|
|
});
|
|
});
|
|
|
|
it('emits straggler chunks before turn_complete', async () => {
|
|
backendStatics.UPDATE_QUIET_PERIOD_MS = 5;
|
|
backendStatics.UPDATE_DRAIN_TIMEOUT_MS = 50;
|
|
backendStatics.PRE_PROMPT_UPDATE_QUIET_PERIOD_MS = 1;
|
|
backendStatics.PRE_PROMPT_UPDATE_DRAIN_TIMEOUT_MS = 50;
|
|
backendStatics.LATE_FLUSH_INTERVAL_MS = 5;
|
|
backendStatics.LATE_FLUSH_QUIET_PERIOD_MS = 30;
|
|
backendStatics.LATE_FLUSH_WINDOW_MS = 500;
|
|
|
|
const backend = new AcpSdkBackend({ command: 'opencode' });
|
|
const backendInternal = backend as unknown as {
|
|
transport: {
|
|
sendRequest: (...args: unknown[]) => Promise<unknown>;
|
|
close: () => Promise<void>;
|
|
} | null;
|
|
handleSessionUpdate: (params: unknown) => void;
|
|
};
|
|
|
|
const messages: AgentMessage[] = [];
|
|
backendInternal.transport = {
|
|
sendRequest: async () => {
|
|
// Schedule a late chunk to arrive *after* session/prompt returns,
|
|
// simulating a slow-tailing model that keeps emitting past the
|
|
// initial post-prompt drain.
|
|
setTimeout(() => {
|
|
backendInternal.handleSessionUpdate({
|
|
sessionId: 'session-1',
|
|
update: {
|
|
sessionUpdate: ACP_SESSION_UPDATE_TYPES.agentMessageChunk,
|
|
content: { type: 'text', text: 'late tail' }
|
|
}
|
|
});
|
|
}, 20);
|
|
return { stopReason: 'end_turn' };
|
|
},
|
|
close: async () => {}
|
|
};
|
|
|
|
await backend.prompt('session-1', [{ type: 'text', text: 'hi' }], (m) => messages.push(m));
|
|
|
|
const lateIdx = messages.findIndex((m) => m.type === 'text' && m.text === 'late tail');
|
|
const turnCompleteIdx = messages.findIndex((m) => m.type === 'turn_complete');
|
|
|
|
expect(lateIdx).toBeGreaterThanOrEqual(0);
|
|
expect(turnCompleteIdx).toBeGreaterThan(lateIdx);
|
|
});
|
|
|
|
it('attributes pre-prompt straggler chunks to the previous turn\'s onUpdate', async () => {
|
|
backendStatics.UPDATE_QUIET_PERIOD_MS = 25;
|
|
backendStatics.UPDATE_DRAIN_TIMEOUT_MS = 200;
|
|
backendStatics.PRE_PROMPT_UPDATE_QUIET_PERIOD_MS = 20;
|
|
backendStatics.PRE_PROMPT_UPDATE_DRAIN_TIMEOUT_MS = 200;
|
|
backendStatics.LATE_FLUSH_INTERVAL_MS = 5;
|
|
backendStatics.LATE_FLUSH_QUIET_PERIOD_MS = 10;
|
|
backendStatics.LATE_FLUSH_WINDOW_MS = 30;
|
|
|
|
const backend = new AcpSdkBackend({ command: 'opencode' });
|
|
const backendInternal = backend as unknown as {
|
|
transport: {
|
|
sendRequest: (...args: unknown[]) => Promise<unknown>;
|
|
close: () => Promise<void>;
|
|
} | null;
|
|
handleSessionUpdate: (params: unknown) => void;
|
|
};
|
|
|
|
const turn1: AgentMessage[] = [];
|
|
const turn2: AgentMessage[] = [];
|
|
backendInternal.transport = {
|
|
sendRequest: async () => ({ stopReason: 'end_turn' }),
|
|
close: async () => {}
|
|
};
|
|
|
|
await backend.prompt('session-1', [{ type: 'text', text: 'hi' }], (m) => turn1.push(m));
|
|
|
|
// Straggler arrives after turn 1 fully resolved but before turn 2 starts.
|
|
// Pre-prompt drain in turn 2 should route it via turn 1's handler.
|
|
backendInternal.handleSessionUpdate({
|
|
sessionId: 'session-1',
|
|
update: {
|
|
sessionUpdate: ACP_SESSION_UPDATE_TYPES.agentMessageChunk,
|
|
content: { type: 'text', text: 'straggler from turn 1' }
|
|
}
|
|
});
|
|
|
|
await backend.prompt('session-1', [{ type: 'text', text: 'again' }], (m) => turn2.push(m));
|
|
|
|
const turn1Text = turn1.filter((m): m is Extract<AgentMessage, { type: 'text' }> => m.type === 'text').map((m) => m.text);
|
|
const turn2Text = turn2.filter((m): m is Extract<AgentMessage, { type: 'text' }> => m.type === 'text').map((m) => m.text);
|
|
|
|
expect(turn1Text).toContain('straggler from turn 1');
|
|
expect(turn2Text).not.toContain('straggler from turn 1');
|
|
});
|
|
|
|
it('exits the late-flush wait once the model is quiet', async () => {
|
|
backendStatics.UPDATE_QUIET_PERIOD_MS = 5;
|
|
backendStatics.UPDATE_DRAIN_TIMEOUT_MS = 50;
|
|
backendStatics.PRE_PROMPT_UPDATE_QUIET_PERIOD_MS = 1;
|
|
backendStatics.PRE_PROMPT_UPDATE_DRAIN_TIMEOUT_MS = 50;
|
|
backendStatics.LATE_FLUSH_INTERVAL_MS = 5;
|
|
backendStatics.LATE_FLUSH_QUIET_PERIOD_MS = 20;
|
|
backendStatics.LATE_FLUSH_WINDOW_MS = 5000;
|
|
|
|
const backend = new AcpSdkBackend({ command: 'opencode' });
|
|
const backendInternal = backend as unknown as {
|
|
transport: {
|
|
sendRequest: (...args: unknown[]) => Promise<unknown>;
|
|
close: () => Promise<void>;
|
|
} | null;
|
|
};
|
|
|
|
backendInternal.transport = {
|
|
sendRequest: async () => ({ stopReason: 'end_turn' }),
|
|
close: async () => {}
|
|
};
|
|
|
|
const started = Date.now();
|
|
await backend.prompt('session-1', [{ type: 'text', text: 'hi' }], () => {});
|
|
const elapsed = Date.now() - started;
|
|
|
|
// With no late chunks arriving, drainLateBuffers should exit on the
|
|
// first quiet check well before the 5s window. Anything under ~500ms
|
|
// proves we're not blocking on the full window.
|
|
expect(elapsed).toBeLessThan(500);
|
|
});
|
|
|
|
it('catches stragglers when session/prompt paused before resolving', async () => {
|
|
// Regression: if the model emitted chunks early in the turn, paused,
|
|
// then sent stopReason, lastSessionUpdateAt is already stale when
|
|
// drainLateBuffers starts. It must anchor the quiet window to entry
|
|
// time, not just lastSessionUpdateAt, otherwise a chunk arriving just
|
|
// after session/prompt resolves is missed.
|
|
backendStatics.UPDATE_QUIET_PERIOD_MS = 5;
|
|
backendStatics.UPDATE_DRAIN_TIMEOUT_MS = 50;
|
|
backendStatics.PRE_PROMPT_UPDATE_QUIET_PERIOD_MS = 1;
|
|
backendStatics.PRE_PROMPT_UPDATE_DRAIN_TIMEOUT_MS = 50;
|
|
backendStatics.LATE_FLUSH_INTERVAL_MS = 5;
|
|
backendStatics.LATE_FLUSH_QUIET_PERIOD_MS = 50;
|
|
backendStatics.LATE_FLUSH_WINDOW_MS = 500;
|
|
|
|
const backend = new AcpSdkBackend({ command: 'opencode' });
|
|
const backendInternal = backend as unknown as {
|
|
transport: {
|
|
sendRequest: (...args: unknown[]) => Promise<unknown>;
|
|
close: () => Promise<void>;
|
|
} | null;
|
|
handleSessionUpdate: (params: unknown) => void;
|
|
};
|
|
|
|
const messages: AgentMessage[] = [];
|
|
backendInternal.transport = {
|
|
sendRequest: async () => {
|
|
// Chunk arrives early, then a long pause stales lastSessionUpdateAt.
|
|
backendInternal.handleSessionUpdate({
|
|
sessionId: 'session-1',
|
|
update: {
|
|
sessionUpdate: ACP_SESSION_UPDATE_TYPES.agentMessageChunk,
|
|
content: { type: 'text', text: 'early' }
|
|
}
|
|
});
|
|
await sleep(200);
|
|
// After sendRequest resolves, schedule a straggler.
|
|
setTimeout(() => {
|
|
backendInternal.handleSessionUpdate({
|
|
sessionId: 'session-1',
|
|
update: {
|
|
sessionUpdate: ACP_SESSION_UPDATE_TYPES.agentMessageChunk,
|
|
content: { type: 'text', text: 'post-pause straggler' }
|
|
}
|
|
});
|
|
}, 10);
|
|
return { stopReason: 'end_turn' };
|
|
},
|
|
close: async () => {}
|
|
};
|
|
|
|
await backend.prompt('session-1', [{ type: 'text', text: 'hi' }], (m) => messages.push(m));
|
|
|
|
const stragglerIdx = messages.findIndex((m) => m.type === 'text' && m.text === 'post-pause straggler');
|
|
const turnCompleteIdx = messages.findIndex((m) => m.type === 'turn_complete');
|
|
|
|
expect(stragglerIdx).toBeGreaterThanOrEqual(0);
|
|
expect(turnCompleteIdx).toBeGreaterThan(stragglerIdx);
|
|
});
|
|
|
|
it('forwards usage_update to onUpdate during an active prompt', async () => {
|
|
backendStatics.UPDATE_QUIET_PERIOD_MS = 25;
|
|
backendStatics.UPDATE_DRAIN_TIMEOUT_MS = 200;
|
|
backendStatics.PRE_PROMPT_UPDATE_QUIET_PERIOD_MS = 1;
|
|
backendStatics.PRE_PROMPT_UPDATE_DRAIN_TIMEOUT_MS = 50;
|
|
backendStatics.LATE_FLUSH_INTERVAL_MS = 5;
|
|
backendStatics.LATE_FLUSH_QUIET_PERIOD_MS = 10;
|
|
backendStatics.LATE_FLUSH_WINDOW_MS = 50;
|
|
|
|
const backend = new AcpSdkBackend({ command: 'agent' });
|
|
const backendInternal = backend as unknown as {
|
|
transport: {
|
|
sendRequest: (...args: unknown[]) => Promise<unknown>;
|
|
close: () => Promise<void>;
|
|
} | null;
|
|
handleSessionUpdate: (params: unknown) => void;
|
|
};
|
|
|
|
const messages: AgentMessage[] = [];
|
|
backendInternal.transport = {
|
|
sendRequest: async () => {
|
|
backendInternal.handleSessionUpdate({
|
|
sessionId: 'session-1',
|
|
update: { sessionUpdate: 'usage_update', used: 1_000, size: 200_000 }
|
|
});
|
|
await sleep(5);
|
|
backendInternal.handleSessionUpdate({
|
|
sessionId: 'session-1',
|
|
update: { sessionUpdate: 'usage_update', used: 2_500, size: 200_000 }
|
|
});
|
|
await sleep(5);
|
|
return { stopReason: 'end_turn' };
|
|
},
|
|
close: async () => {}
|
|
};
|
|
|
|
await backend.prompt('session-1', [{ type: 'text', text: 'hi' }], (m) => messages.push(m));
|
|
|
|
const realtimeUsage = messages.filter(
|
|
(m): m is Extract<AgentMessage, { type: 'usage' }> =>
|
|
m.type === 'usage' && m.contextTokens !== undefined
|
|
);
|
|
expect(realtimeUsage.map((m) => m.contextTokens)).toEqual([1_000, 2_500]);
|
|
});
|
|
|
|
it('forwards title changes from session_info_update', () => {
|
|
const backend = new AcpSdkBackend({ command: 'agent' });
|
|
const updates: Array<{ sessionId: string | null; title: string | null }> = [];
|
|
backend.setSessionInfoUpdateListener((update) => updates.push(update));
|
|
|
|
const backendInternal = backend as unknown as {
|
|
activeSessionId: string | null;
|
|
handleSessionUpdate: (params: unknown) => void;
|
|
};
|
|
backendInternal.activeSessionId = 'session-1';
|
|
|
|
backendInternal.handleSessionUpdate({
|
|
sessionId: 'session-1',
|
|
update: {
|
|
sessionUpdate: ACP_SESSION_UPDATE_TYPES.sessionInfoUpdate,
|
|
title: 'Native ACP title'
|
|
}
|
|
});
|
|
backendInternal.handleSessionUpdate({
|
|
sessionId: 'session-1',
|
|
update: {
|
|
sessionUpdate: ACP_SESSION_UPDATE_TYPES.sessionInfoUpdate,
|
|
title: null
|
|
}
|
|
});
|
|
backendInternal.handleSessionUpdate({
|
|
sessionId: 'session-1',
|
|
update: {
|
|
sessionUpdate: ACP_SESSION_UPDATE_TYPES.sessionInfoUpdate,
|
|
title: 123
|
|
}
|
|
});
|
|
backendInternal.handleSessionUpdate({
|
|
sessionId: 'other-session',
|
|
update: {
|
|
sessionUpdate: ACP_SESSION_UPDATE_TYPES.sessionInfoUpdate,
|
|
title: 'Wrong session'
|
|
}
|
|
});
|
|
|
|
expect(updates).toEqual([
|
|
{ sessionId: 'session-1', title: 'Native ACP title' },
|
|
{ sessionId: 'session-1', title: null }
|
|
]);
|
|
});
|
|
|
|
it('emits a context-only usage on finalize when the prompt response carries no usage', async () => {
|
|
backendStatics.UPDATE_QUIET_PERIOD_MS = 25;
|
|
backendStatics.UPDATE_DRAIN_TIMEOUT_MS = 200;
|
|
backendStatics.PRE_PROMPT_UPDATE_QUIET_PERIOD_MS = 1;
|
|
backendStatics.PRE_PROMPT_UPDATE_DRAIN_TIMEOUT_MS = 50;
|
|
backendStatics.LATE_FLUSH_INTERVAL_MS = 5;
|
|
backendStatics.LATE_FLUSH_QUIET_PERIOD_MS = 10;
|
|
backendStatics.LATE_FLUSH_WINDOW_MS = 50;
|
|
|
|
const backend = new AcpSdkBackend({ command: 'opencode' });
|
|
const backendInternal = backend as unknown as {
|
|
transport: {
|
|
sendRequest: (...args: unknown[]) => Promise<unknown>;
|
|
close: () => Promise<void>;
|
|
} | null;
|
|
handleSessionUpdate: (params: unknown) => void;
|
|
};
|
|
|
|
const messages: AgentMessage[] = [];
|
|
backendInternal.transport = {
|
|
sendRequest: async () => {
|
|
backendInternal.handleSessionUpdate({
|
|
sessionId: 'session-1',
|
|
update: { sessionUpdate: 'usage_update', used: 4_200, size: 200_000 }
|
|
});
|
|
await sleep(5);
|
|
// No `usage` field on the response: simulates slash-handled
|
|
// turns or errored turns that skip the model.
|
|
return { stopReason: 'end_turn' };
|
|
},
|
|
close: async () => {}
|
|
};
|
|
|
|
await backend.prompt('session-1', [{ type: 'text', text: 'hi' }], (m) => messages.push(m));
|
|
|
|
const usageMessages = messages.filter((m): m is Extract<AgentMessage, { type: 'usage' }> => m.type === 'usage');
|
|
expect(usageMessages.length).toBe(1);
|
|
expect(usageMessages[0]).toMatchObject({
|
|
inputTokens: 0,
|
|
outputTokens: 0,
|
|
contextTokens: 4_200,
|
|
contextWindow: 200_000
|
|
});
|
|
});
|
|
|
|
it('authenticateIfAvailable calls _client/authenticate when method is advertised', async () => {
|
|
const backend = new AcpSdkBackend({ command: 'agent' });
|
|
const calls: Array<{ method: string; params: unknown }> = [];
|
|
const backendInternal = backend as unknown as {
|
|
initializeResult: { protocolVersion: number; authMethods?: Array<{ id: string }> } | null;
|
|
transport: { sendRequest: (method: string, params: unknown) => Promise<unknown>; close: () => Promise<void> } | null;
|
|
};
|
|
backendInternal.initializeResult = {
|
|
protocolVersion: 1,
|
|
authMethods: [{ id: 'cursor_login' }]
|
|
};
|
|
backendInternal.transport = {
|
|
sendRequest: async (method, params) => {
|
|
calls.push({ method, params });
|
|
return null;
|
|
},
|
|
close: async () => {}
|
|
};
|
|
|
|
await backend.authenticateIfAvailable('cursor_login');
|
|
|
|
expect(calls).toEqual([
|
|
{ method: '_client/authenticate', params: { methodId: 'cursor_login' } }
|
|
]);
|
|
});
|
|
|
|
it('authenticateIfAvailable does not throw when _client/authenticate is unsupported', async () => {
|
|
const backend = new AcpSdkBackend({ command: 'agent' });
|
|
const backendInternal = backend as unknown as {
|
|
initializeResult: { protocolVersion: number; authMethods?: Array<{ id: string }> } | null;
|
|
transport: { sendRequest: (method: string, params: unknown) => Promise<unknown>; close: () => Promise<void> } | null;
|
|
};
|
|
backendInternal.initializeResult = {
|
|
protocolVersion: 1,
|
|
authMethods: [{ id: 'cursor_login' }]
|
|
};
|
|
backendInternal.transport = {
|
|
sendRequest: async () => {
|
|
throw new Error('"Method not found": _client/authenticate');
|
|
},
|
|
close: async () => {}
|
|
};
|
|
|
|
await expect(backend.authenticateIfAvailable('cursor_login')).resolves.toBeUndefined();
|
|
});
|
|
|
|
it('authenticateIfAvailable is a no-op when method is not advertised', async () => {
|
|
const backend = new AcpSdkBackend({ command: 'agent' });
|
|
const calls: Array<{ method: string; params: unknown }> = [];
|
|
const backendInternal = backend as unknown as {
|
|
initializeResult: { protocolVersion: number; authMethods?: Array<{ id: string }> } | null;
|
|
transport: { sendRequest: (method: string, params: unknown) => Promise<unknown>; close: () => Promise<void> } | null;
|
|
};
|
|
backendInternal.initializeResult = { protocolVersion: 1, authMethods: [] };
|
|
backendInternal.transport = {
|
|
sendRequest: async (method, params) => {
|
|
calls.push({ method, params });
|
|
return null;
|
|
},
|
|
close: async () => {}
|
|
};
|
|
|
|
await backend.authenticateIfAvailable('cursor_login');
|
|
|
|
expect(calls).toEqual([]);
|
|
});
|
|
|
|
it('supportsLoadSession reflects initialize agentCapabilities', () => {
|
|
const backend = new AcpSdkBackend({ command: 'agent' });
|
|
const backendInternal = backend as unknown as {
|
|
initializeResult: { protocolVersion: number; agentCapabilities?: { loadSession?: boolean } } | null;
|
|
};
|
|
backendInternal.initializeResult = {
|
|
protocolVersion: 1,
|
|
agentCapabilities: { loadSession: true }
|
|
};
|
|
|
|
expect(backend.supportsLoadSession()).toBe(true);
|
|
|
|
backendInternal.initializeResult = {
|
|
protocolVersion: 1,
|
|
agentCapabilities: { loadSession: false }
|
|
};
|
|
expect(backend.supportsLoadSession()).toBe(false);
|
|
});
|
|
|
|
it('setMode falls back to session/set_config_option when session/set_mode is missing', async () => {
|
|
const backend = new AcpSdkBackend({ command: 'agent' });
|
|
const calls: Array<{ method: string; params: unknown }> = [];
|
|
const backendInternal = backend as unknown as {
|
|
transport: { sendRequest: (method: string, params: unknown) => Promise<unknown>; registerRequestHandler: (method: string, handler: unknown) => void; close: () => Promise<void> } | null;
|
|
sessionConfigOptions: Map<string, Array<{ id: string; category?: string; options: Array<{ value: string }> }>>;
|
|
};
|
|
backendInternal.transport = {
|
|
sendRequest: async (method, params) => {
|
|
calls.push({ method, params });
|
|
if (method === 'session/set_mode') {
|
|
throw new Error('method not found');
|
|
}
|
|
return null;
|
|
},
|
|
registerRequestHandler: () => {},
|
|
close: async () => {}
|
|
};
|
|
backendInternal.sessionConfigOptions.set('session-1', [
|
|
{ id: 'mode-opt', category: 'mode', options: [{ value: 'agent' }, { value: 'plan' }] }
|
|
]);
|
|
|
|
await backend.setMode('session-1', 'plan');
|
|
|
|
expect(calls).toEqual([
|
|
{ method: 'session/set_mode', params: { sessionId: 'session-1', modeId: 'plan' } },
|
|
{ method: 'session/set_config_option', params: { sessionId: 'session-1', configId: 'mode-opt', value: 'plan' } }
|
|
]);
|
|
});
|
|
|
|
it('registerExtensionRequestHandler wires transport handlers', () => {
|
|
const registered = new Map<string, unknown>();
|
|
const backend = new AcpSdkBackend({ command: 'agent' });
|
|
const backendInternal = backend as unknown as {
|
|
transport: { registerRequestHandler: (method: string, handler: unknown) => void; close: () => Promise<void> } | null;
|
|
};
|
|
backendInternal.transport = {
|
|
registerRequestHandler(method, handler) {
|
|
registered.set(method, handler);
|
|
},
|
|
close: async () => {}
|
|
};
|
|
|
|
const handler = vi.fn();
|
|
backend.registerExtensionRequestHandler('cursor/ask_question', handler);
|
|
|
|
expect(registered.get('cursor/ask_question')).toBe(handler);
|
|
});
|
|
|
|
it('beginSoftSteerPrompt sends concurrent session/prompt without cancel', () => {
|
|
const backend = new AcpSdkBackend({ command: 'agent' });
|
|
const calls: Array<{ method: string; params: unknown }> = [];
|
|
const backendInternal = backend as unknown as {
|
|
transport: {
|
|
sendRequestWithDispatch: (method: string, params: unknown, options?: { timeoutMs?: number }) => { dispatched: Promise<void>; completed: Promise<unknown> };
|
|
sendNotification: (method: string, params: unknown) => void;
|
|
close: () => Promise<void>;
|
|
} | null;
|
|
isProcessingMessage: boolean;
|
|
};
|
|
backendInternal.isProcessingMessage = true;
|
|
backendInternal.transport = {
|
|
sendRequestWithDispatch: (method, params) => {
|
|
calls.push({ method, params });
|
|
return { dispatched: Promise.resolve(), completed: Promise.resolve({ stopReason: 'end_turn' }) };
|
|
},
|
|
sendNotification: () => {},
|
|
close: async () => {}
|
|
};
|
|
|
|
backend.beginSoftSteerPrompt('session-1', [{ type: 'text', text: 'pivot now' }]);
|
|
|
|
expect(calls).toEqual([{
|
|
method: 'session/prompt',
|
|
params: {
|
|
sessionId: 'session-1',
|
|
prompt: [{ type: 'text', text: 'pivot now' }]
|
|
}
|
|
}]);
|
|
});
|
|
|
|
it('beginSoftSteerPrompt drains buffered output after completion', async () => {
|
|
const backend = new AcpSdkBackend({ command: 'agent' });
|
|
const backendInternal = backend as unknown as {
|
|
transport: {
|
|
sendRequestWithDispatch: (method: string, params: unknown, options?: { timeoutMs?: number }) => { dispatched: Promise<void>; completed: Promise<unknown> };
|
|
close: () => Promise<void>;
|
|
} | null;
|
|
isProcessingMessage: boolean;
|
|
waitForSessionUpdateQuiet: (quietMs: number, timeoutMs: number) => Promise<void>;
|
|
drainLateBuffers: () => Promise<void>;
|
|
messageHandler: { drainBuffers: () => void } | null;
|
|
};
|
|
const events: string[] = [];
|
|
backendInternal.isProcessingMessage = true;
|
|
backendInternal.transport = {
|
|
sendRequestWithDispatch: () => {
|
|
events.push('request');
|
|
return { dispatched: Promise.resolve(), completed: Promise.resolve({ stopReason: 'end_turn' }) };
|
|
},
|
|
close: async () => {}
|
|
};
|
|
backendInternal.waitForSessionUpdateQuiet = async () => {
|
|
events.push('quiet');
|
|
};
|
|
backendInternal.messageHandler = {
|
|
drainBuffers: () => events.push('drain')
|
|
};
|
|
backendInternal.drainLateBuffers = async () => {
|
|
events.push('late');
|
|
};
|
|
|
|
await backend.beginSoftSteerPrompt('session-1', [{ type: 'text', text: 'pivot now' }]).completed;
|
|
|
|
expect(events).toEqual(['request', 'quiet', 'drain', 'late', 'drain']);
|
|
});
|
|
|
|
it('beginSoftSteerPrompt returns a pending promise without blocking the caller', async () => {
|
|
const backend = new AcpSdkBackend({ command: 'agent' });
|
|
let resolvePrompt: ((value: unknown) => void) | null = null;
|
|
const backendInternal = backend as unknown as {
|
|
transport: {
|
|
sendRequestWithDispatch: (method: string, params: unknown, options?: { timeoutMs?: number }) => { dispatched: Promise<void>; completed: Promise<unknown> };
|
|
sendNotification: (method: string, params: unknown) => void;
|
|
close: () => Promise<void>;
|
|
} | null;
|
|
isProcessingMessage: boolean;
|
|
};
|
|
backendInternal.isProcessingMessage = true;
|
|
backendInternal.transport = {
|
|
sendRequestWithDispatch: () => ({
|
|
dispatched: Promise.resolve(),
|
|
completed: new Promise((resolve) => { resolvePrompt = resolve; })
|
|
}),
|
|
sendNotification: () => {},
|
|
close: async () => {}
|
|
};
|
|
|
|
// Must not hang waiting for the ACP prompt response (hub RPC is 30s).
|
|
let settled = false;
|
|
const pending = backend.beginSoftSteerPrompt('session-1', [{ type: 'text', text: 'pivot now' }]).completed.then(() => {
|
|
settled = true;
|
|
});
|
|
expect(resolvePrompt).not.toBeNull();
|
|
expect(settled).toBe(false);
|
|
resolvePrompt!({ stopReason: 'end_turn' });
|
|
await pending;
|
|
expect(settled).toBe(true);
|
|
});
|
|
|
|
it('keeps response completion pending until a concurrent soft steer settles', async () => {
|
|
const backend = new AcpSdkBackend({ command: 'agent' });
|
|
let resolvePrompt: ((value: unknown) => void) | null = null;
|
|
const backendInternal = backend as unknown as {
|
|
transport: { sendRequestWithDispatch: () => { dispatched: Promise<void>; completed: Promise<unknown> }; close: () => Promise<void> } | null;
|
|
isProcessingMessage: boolean;
|
|
activePromptRequests: number;
|
|
finishPromptRequest: (epoch: number) => void;
|
|
waitForSessionUpdateQuiet: () => Promise<void>;
|
|
drainLateBuffers: () => Promise<void>;
|
|
};
|
|
backendInternal.isProcessingMessage = true;
|
|
backendInternal.activePromptRequests = 1;
|
|
backendInternal.transport = {
|
|
sendRequestWithDispatch: () => ({
|
|
dispatched: Promise.resolve(),
|
|
completed: new Promise((resolve) => { resolvePrompt = resolve; })
|
|
}),
|
|
close: async () => {}
|
|
};
|
|
backendInternal.waitForSessionUpdateQuiet = async () => {};
|
|
backendInternal.drainLateBuffers = async () => {};
|
|
|
|
const pendingSteer = backend.beginSoftSteerPrompt('session-1', [{ type: 'text', text: 'pivot now' }]);
|
|
let responseComplete = false;
|
|
const responseWait = backend.waitForResponseComplete().then(() => { responseComplete = true; });
|
|
|
|
backendInternal.finishPromptRequest(0);
|
|
await Promise.resolve();
|
|
expect(backend.processingMessage).toBe(true);
|
|
expect(responseComplete).toBe(false);
|
|
|
|
resolvePrompt!({ stopReason: 'end_turn' });
|
|
await pendingSteer.completed;
|
|
await responseWait;
|
|
expect(backend.processingMessage).toBe(false);
|
|
expect(responseComplete).toBe(true);
|
|
});
|
|
|
|
it('softSteerPrompt awaits session/prompt completion', async () => {
|
|
const backend = new AcpSdkBackend({ command: 'agent' });
|
|
let resolvePrompt: ((value: unknown) => void) | null = null;
|
|
const backendInternal = backend as unknown as {
|
|
transport: {
|
|
sendRequest: (method: string, params: unknown, options?: { timeoutMs?: number }) => Promise<unknown>;
|
|
sendNotification: (method: string, params: unknown) => void;
|
|
close: () => Promise<void>;
|
|
} | null;
|
|
isProcessingMessage: boolean;
|
|
};
|
|
backendInternal.isProcessingMessage = true;
|
|
backendInternal.transport = {
|
|
sendRequest: () => new Promise((resolve) => {
|
|
resolvePrompt = resolve;
|
|
}),
|
|
sendNotification: () => {},
|
|
close: async () => {}
|
|
};
|
|
|
|
let done = false;
|
|
const pending = backend.softSteerPrompt('session-1', [{ type: 'text', text: 'pivot now' }]).then(() => {
|
|
done = true;
|
|
});
|
|
await Promise.resolve();
|
|
expect(done).toBe(false);
|
|
resolvePrompt!({ stopReason: 'end_turn' });
|
|
await pending;
|
|
expect(done).toBe(true);
|
|
});
|
|
|
|
it('beginSoftSteerPrompt rejects when no prompt is in flight', () => {
|
|
const backend = new AcpSdkBackend({ command: 'agent' });
|
|
const backendInternal = backend as unknown as {
|
|
transport: { sendRequest: () => Promise<unknown>; close: () => Promise<void> } | null;
|
|
isProcessingMessage: boolean;
|
|
};
|
|
backendInternal.isProcessingMessage = false;
|
|
backendInternal.transport = {
|
|
sendRequest: async () => null,
|
|
close: async () => {}
|
|
};
|
|
|
|
expect(() => backend.beginSoftSteerPrompt('session-1', [{ type: 'text', text: 'x' }]))
|
|
.toThrow(/No active ACP prompt/);
|
|
});
|
|
|
|
|
|
it('suppressUpdatesDuring drops session/update notifications that would otherwise leak into the previous turn\'s onUpdate, then restores normal forwarding', async () => {
|
|
// Reproduces the real /compact duplicate-summary bug: OpenCode keeps
|
|
// streaming session/update notifications (over the same ACP
|
|
// transport) while a raw-HTTP /compact call is in flight outside
|
|
// prompt(), and handleSessionUpdate forwards them unconditionally to
|
|
// whatever messageHandler is still installed from the last prompt()
|
|
// turn — rendering the same content a second time alongside the
|
|
// compact bridge's own explicit summary message.
|
|
//
|
|
// Fast quiet-drain timing so this test doesn't pay the real
|
|
// (production) 200ms/1200ms PRE_PROMPT_* delay suppressUpdatesDuring
|
|
// now waits through before restoring the handler.
|
|
backendStatics.PRE_PROMPT_UPDATE_QUIET_PERIOD_MS = 5;
|
|
backendStatics.PRE_PROMPT_UPDATE_DRAIN_TIMEOUT_MS = 50;
|
|
|
|
const backend = new AcpSdkBackend({ command: 'opencode' });
|
|
const backendInternal = backend as unknown as {
|
|
transport: {
|
|
sendRequest: (...args: unknown[]) => Promise<unknown>;
|
|
close: () => Promise<void>;
|
|
} | null;
|
|
handleSessionUpdate: (params: unknown) => void;
|
|
messageHandler: unknown;
|
|
sessionUpdateQueue: Promise<void>;
|
|
};
|
|
backendInternal.transport = {
|
|
sendRequest: async () => ({ stopReason: 'end_turn' }),
|
|
close: async () => {}
|
|
};
|
|
|
|
const turn1: AgentMessage[] = [];
|
|
await backend.prompt('session-1', [{ type: 'text', text: 'hi' }], (m) => turn1.push(m));
|
|
|
|
const emitPlanUpdate = () => backendInternal.handleSessionUpdate({
|
|
sessionId: 'session-1',
|
|
update: {
|
|
sessionUpdate: ACP_SESSION_UPDATE_TYPES.plan,
|
|
entries: [{ content: 'leaked plan step', priority: 'medium', status: 'pending' }]
|
|
}
|
|
});
|
|
|
|
const handlerBeforeSuppression = backendInternal.messageHandler;
|
|
expect(handlerBeforeSuppression).not.toBeNull();
|
|
|
|
let handlerDuringSuppression: unknown = 'not-checked';
|
|
const result = await backend.suppressUpdatesDuring(async () => {
|
|
handlerDuringSuppression = backendInternal.messageHandler;
|
|
emitPlanUpdate();
|
|
return 'compact result';
|
|
});
|
|
|
|
expect(result).toBe('compact result');
|
|
expect(handlerDuringSuppression).toBeNull();
|
|
await backendInternal.sessionUpdateQueue;
|
|
expect(turn1.some((m) => m.type === 'plan')).toBe(false);
|
|
|
|
// The previous turn's handler must be back in place afterward so
|
|
// ordinary straggler-forwarding (covered elsewhere) is unaffected.
|
|
expect(backendInternal.messageHandler).toBe(handlerBeforeSuppression);
|
|
emitPlanUpdate();
|
|
// #958 queues message-handler work (async image registration); await
|
|
// before asserting delivery — upstream assumed sync handleUpdate.
|
|
await backendInternal.sessionUpdateQueue;
|
|
expect(turn1.some((m) => m.type === 'plan')).toBe(true);
|
|
});
|
|
|
|
it('waits for a quiet period (reusing the same drain prompt() uses before swapping handlers) before restoring the handler after suppressUpdatesDuring, so a late server-side straggler from an already-aborted operation cannot leak', async () => {
|
|
// Reproduces a hostile-review finding: aborting the client-side HTTP
|
|
// call (e.g. compactAbortController) does not mean the OpenCode
|
|
// server actually stopped the operation — session/update is a
|
|
// separate notification channel from that HTTP request's lifecycle.
|
|
// If suppressUpdatesDuring restored the handler the instant `fn`
|
|
// resolved, a straggler notification arriving moments later (while
|
|
// the server is still winding the operation down) would leak
|
|
// straight into the restored handler.
|
|
backendStatics.PRE_PROMPT_UPDATE_QUIET_PERIOD_MS = 30;
|
|
backendStatics.PRE_PROMPT_UPDATE_DRAIN_TIMEOUT_MS = 300;
|
|
|
|
const backend = new AcpSdkBackend({ command: 'opencode' });
|
|
const backendInternal = backend as unknown as {
|
|
transport: {
|
|
sendRequest: (...args: unknown[]) => Promise<unknown>;
|
|
close: () => Promise<void>;
|
|
} | null;
|
|
handleSessionUpdate: (params: unknown) => void;
|
|
messageHandler: unknown;
|
|
sessionUpdateQueue: Promise<void>;
|
|
};
|
|
backendInternal.transport = {
|
|
sendRequest: async () => ({ stopReason: 'end_turn' }),
|
|
close: async () => {}
|
|
};
|
|
|
|
const turn1: AgentMessage[] = [];
|
|
await backend.prompt('session-1', [{ type: 'text', text: 'hi' }], (m) => turn1.push(m));
|
|
|
|
const emitPlanUpdate = () => backendInternal.handleSessionUpdate({
|
|
sessionId: 'session-1',
|
|
update: {
|
|
sessionUpdate: ACP_SESSION_UPDATE_TYPES.plan,
|
|
entries: [{ content: 'late server-side straggler', priority: 'medium', status: 'pending' }]
|
|
}
|
|
});
|
|
|
|
const handlerBeforeSuppression = backendInternal.messageHandler;
|
|
|
|
const suppressPromise = backend.suppressUpdatesDuring(async () => {
|
|
// Client gives up almost immediately (mirrors compactAbortController
|
|
// firing), but the server keeps streaming for a little longer —
|
|
// one update right away, one more 15ms later.
|
|
emitPlanUpdate();
|
|
setTimeout(emitPlanUpdate, 15);
|
|
return 'aborted-early';
|
|
});
|
|
|
|
// Sampled while suppressUpdatesDuring's own returned promise is
|
|
// still pending (fn already resolved, but the quiet-drain in its
|
|
// `finally` has not) — this is what actually proves restoration is
|
|
// *deferred*, not merely eventually correct.
|
|
await sleep(20);
|
|
const handlerDuringDrainWindow = backendInternal.messageHandler;
|
|
|
|
const result = await suppressPromise;
|
|
|
|
expect(result).toBe('aborted-early');
|
|
expect(handlerDuringDrainWindow).toBeNull();
|
|
// Neither the immediate update nor the +15ms straggler leaked —
|
|
// messageHandler was null (suppressed) for both.
|
|
await backendInternal.sessionUpdateQueue;
|
|
expect(turn1.some((m) => m.type === 'plan')).toBe(false);
|
|
|
|
expect(backendInternal.messageHandler).toBe(handlerBeforeSuppression);
|
|
|
|
// Normal forwarding resumes once actually restored.
|
|
emitPlanUpdate();
|
|
await backendInternal.sessionUpdateQueue;
|
|
expect(turn1.some((m) => m.type === 'plan')).toBe(true);
|
|
});
|
|
|
|
it('drops updates enqueued while suppressed even if the queue drains after the handler is restored', async () => {
|
|
// If handleSessionUpdate looked up this.messageHandler when the queued
|
|
// microtask ran (instead of capturing it at enqueue), a compact-era
|
|
// update stuck behind earlier async image work would leak into the
|
|
// restored handler after suppressUpdatesDuring returns.
|
|
backendStatics.PRE_PROMPT_UPDATE_QUIET_PERIOD_MS = 5;
|
|
backendStatics.PRE_PROMPT_UPDATE_DRAIN_TIMEOUT_MS = 50;
|
|
|
|
const backend = new AcpSdkBackend({ command: 'opencode' });
|
|
const backendInternal = backend as unknown as {
|
|
transport: {
|
|
sendRequest: (...args: unknown[]) => Promise<unknown>;
|
|
close: () => Promise<void>;
|
|
} | null;
|
|
handleSessionUpdate: (params: unknown) => void;
|
|
messageHandler: unknown;
|
|
sessionUpdateQueue: Promise<void>;
|
|
};
|
|
backendInternal.transport = {
|
|
sendRequest: async () => ({ stopReason: 'end_turn' }),
|
|
close: async () => {}
|
|
};
|
|
|
|
const turn1: AgentMessage[] = [];
|
|
await backend.prompt('session-1', [{ type: 'text', text: 'hi' }], (m) => turn1.push(m));
|
|
|
|
let releaseBlocker!: () => void;
|
|
const blocker = new Promise<void>((resolve) => {
|
|
releaseBlocker = resolve;
|
|
});
|
|
backendInternal.sessionUpdateQueue = backendInternal.sessionUpdateQueue.then(() => blocker);
|
|
|
|
await backend.suppressUpdatesDuring(async () => {
|
|
backendInternal.handleSessionUpdate({
|
|
sessionId: 'session-1',
|
|
update: {
|
|
sessionUpdate: ACP_SESSION_UPDATE_TYPES.plan,
|
|
entries: [{ content: 'queued-during-suppress', priority: 'medium', status: 'pending' }]
|
|
}
|
|
});
|
|
return 'compact';
|
|
});
|
|
|
|
expect(backendInternal.messageHandler).not.toBeNull();
|
|
releaseBlocker();
|
|
await backendInternal.sessionUpdateQueue;
|
|
expect(turn1.some((m) => m.type === 'plan')).toBe(false);
|
|
});
|
|
|
|
it('does not let compact thought/text chunks escape through the next prompt pre-swap drain, while preserving the new prompt response', async () => {
|
|
// The reported duplicate was not emitted during /compact itself. In
|
|
// the pre-suppression implementation those chunks stayed in the old
|
|
// handler and prompt()'s next pre-swap drain emitted them as an
|
|
// ordinary assistant reply. This drives that exact backend path.
|
|
backendStatics.UPDATE_QUIET_PERIOD_MS = 1;
|
|
backendStatics.UPDATE_DRAIN_TIMEOUT_MS = 20;
|
|
backendStatics.PRE_PROMPT_UPDATE_QUIET_PERIOD_MS = 1;
|
|
backendStatics.PRE_PROMPT_UPDATE_DRAIN_TIMEOUT_MS = 20;
|
|
backendStatics.LATE_FLUSH_INTERVAL_MS = 1;
|
|
backendStatics.LATE_FLUSH_QUIET_PERIOD_MS = 1;
|
|
backendStatics.LATE_FLUSH_WINDOW_MS = 20;
|
|
|
|
const backend = new AcpSdkBackend({ command: 'opencode' });
|
|
const backendInternal = backend as unknown as {
|
|
transport: {
|
|
sendRequest: (method: string, params: unknown, options?: unknown) => Promise<unknown>;
|
|
close: () => Promise<void>;
|
|
} | null;
|
|
handleSessionUpdate: (params: unknown) => void;
|
|
sessionUpdateQueue: Promise<void>;
|
|
};
|
|
let promptRequestCount = 0;
|
|
backendInternal.transport = {
|
|
sendRequest: async (method) => {
|
|
if (method === 'session/prompt') {
|
|
promptRequestCount += 1;
|
|
if (promptRequestCount === 2) {
|
|
backendInternal.handleSessionUpdate({
|
|
sessionId: 'session-1',
|
|
update: {
|
|
sessionUpdate: ACP_SESSION_UPDATE_TYPES.agentThoughtChunk,
|
|
content: { type: 'text', text: 'new prompt thought' }
|
|
}
|
|
});
|
|
backendInternal.handleSessionUpdate({
|
|
sessionId: 'session-1',
|
|
update: {
|
|
sessionUpdate: ACP_SESSION_UPDATE_TYPES.agentMessageChunk,
|
|
content: { type: 'text', text: 'new prompt answer' }
|
|
}
|
|
});
|
|
}
|
|
return { stopReason: 'end_turn' };
|
|
}
|
|
return null;
|
|
},
|
|
close: async () => {}
|
|
};
|
|
|
|
const previousTurn: AgentMessage[] = [];
|
|
await backend.prompt('session-1', [{ type: 'text', text: 'before compact' }], (message) => previousTurn.push(message));
|
|
|
|
await backend.suppressUpdatesDuring(async () => {
|
|
backendInternal.handleSessionUpdate({
|
|
sessionId: 'session-1',
|
|
update: {
|
|
sessionUpdate: ACP_SESSION_UPDATE_TYPES.agentThoughtChunk,
|
|
content: { type: 'text', text: 'compact-only thought' }
|
|
}
|
|
});
|
|
backendInternal.handleSessionUpdate({
|
|
sessionId: 'session-1',
|
|
update: {
|
|
sessionUpdate: ACP_SESSION_UPDATE_TYPES.agentMessageChunk,
|
|
content: { type: 'text', text: 'compact-only summary' }
|
|
}
|
|
});
|
|
});
|
|
|
|
const nextTurn: AgentMessage[] = [];
|
|
await backend.prompt('session-1', [{ type: 'text', text: 'after compact' }], (message) => nextTurn.push(message));
|
|
|
|
expect(previousTurn).toEqual([
|
|
{ type: 'turn_complete', stopReason: 'end_turn' }
|
|
]);
|
|
expect(nextTurn).toEqual([
|
|
{ type: 'reasoning', text: 'new prompt thought' },
|
|
{ type: 'text', text: 'new prompt answer' },
|
|
{ type: 'turn_complete', stopReason: 'end_turn' }
|
|
]);
|
|
});
|
|
|
|
it('notifies agent-activity listener for sustained running + idle, not content/usage noise (#1470/#1502)', () => {
|
|
vi.useFakeTimers();
|
|
const backend = new AcpSdkBackend({ command: 'agent' });
|
|
const activity: boolean[] = [];
|
|
backend.setAgentActivityListener((thinking) => {
|
|
activity.push(thinking);
|
|
});
|
|
|
|
const backendInternal = backend as unknown as {
|
|
handleSessionUpdate: (params: unknown) => void;
|
|
};
|
|
|
|
backendInternal.handleSessionUpdate({
|
|
sessionId: 'session-1',
|
|
update: {
|
|
sessionUpdate: ACP_SESSION_UPDATE_TYPES.agentMessageChunk,
|
|
content: { type: 'text', text: 'resumed' }
|
|
}
|
|
});
|
|
backendInternal.handleSessionUpdate({
|
|
sessionId: 'session-1',
|
|
update: {
|
|
sessionUpdate: ACP_SESSION_UPDATE_TYPES.toolCallUpdate,
|
|
toolCallId: 'tc-bg',
|
|
status: 'in_progress'
|
|
}
|
|
});
|
|
backendInternal.handleSessionUpdate({
|
|
sessionId: 'session-1',
|
|
update: { sessionUpdate: 'usage_update', used: 1_000, size: 200_000 }
|
|
});
|
|
backendInternal.handleSessionUpdate({
|
|
sessionId: 'session-1',
|
|
update: {
|
|
sessionUpdate: ACP_SESSION_UPDATE_TYPES.sessionInfoUpdate,
|
|
title: 'noise'
|
|
}
|
|
});
|
|
// Chatter: running then idle before debounce → no true bump (idle may clear)
|
|
backendInternal.handleSessionUpdate({
|
|
sessionId: 'session-1',
|
|
update: { sessionUpdate: 'state_update', state: 'running' }
|
|
});
|
|
vi.advanceTimersByTime(200);
|
|
backendInternal.handleSessionUpdate({
|
|
sessionId: 'session-1',
|
|
update: { sessionUpdate: 'state_update', state: 'idle' }
|
|
});
|
|
expect(activity.filter((v) => v === true)).toEqual([]);
|
|
|
|
// Sustained running commits after debounce
|
|
backendInternal.handleSessionUpdate({
|
|
sessionId: 'session-1',
|
|
update: { sessionUpdate: 'state_update', state: 'running' }
|
|
});
|
|
vi.advanceTimersByTime(750);
|
|
expect(activity.filter((v) => v === true)).toEqual([true]);
|
|
backendInternal.handleSessionUpdate({
|
|
sessionId: 'session-1',
|
|
update: { sessionUpdate: 'state_update', state: 'idle' }
|
|
});
|
|
expect(activity.at(-1)).toBe(false);
|
|
vi.useRealTimers();
|
|
});
|
|
|
|
it('ignores idle clears while a HAPI prompt turn is still draining', () => {
|
|
const backend = new AcpSdkBackend({ command: 'agent' });
|
|
const activity: boolean[] = [];
|
|
backend.setAgentActivityListener((thinking) => {
|
|
activity.push(thinking);
|
|
});
|
|
const backendInternal = backend as unknown as {
|
|
handleSessionUpdate: (params: unknown) => void;
|
|
isProcessingMessage: boolean;
|
|
};
|
|
backendInternal.isProcessingMessage = true;
|
|
backendInternal.handleSessionUpdate({
|
|
sessionId: 'session-1',
|
|
update: { sessionUpdate: 'state_update', state: 'idle' }
|
|
});
|
|
expect(activity).toEqual([]);
|
|
backendInternal.isProcessingMessage = false;
|
|
backendInternal.handleSessionUpdate({
|
|
sessionId: 'session-1',
|
|
update: { sessionUpdate: 'state_update', state: 'idle' }
|
|
});
|
|
expect(activity).toEqual([false]);
|
|
});
|
|
|
|
it('notifies agent-activity listener when a permission request arrives (#1470)', async () => {
|
|
const backend = new AcpSdkBackend({ command: 'agent' });
|
|
const activity: boolean[] = [];
|
|
backend.setAgentActivityListener((thinking) => {
|
|
activity.push(thinking);
|
|
});
|
|
backend.onPermissionRequest(() => {
|
|
// leave pending; we only care that activity fired first
|
|
});
|
|
|
|
const backendInternal = backend as unknown as {
|
|
handlePermissionRequest: (params: unknown, requestId: string) => Promise<unknown>;
|
|
};
|
|
|
|
const pending = backendInternal.handlePermissionRequest({
|
|
sessionId: 'session-1',
|
|
toolCall: {
|
|
toolCallId: 'tc-1',
|
|
title: 'Shell',
|
|
kind: 'execute',
|
|
status: 'pending'
|
|
},
|
|
options: [{ optionId: 'allow-once', name: 'Allow once', kind: 'allow_once' }]
|
|
}, 'req-1');
|
|
|
|
expect(activity).toEqual([true]);
|
|
// Cancel so the promise does not hang the suite.
|
|
await backend.respondToPermission('session-1', {
|
|
id: 'tc-1',
|
|
sessionId: 'session-1',
|
|
toolCallId: 'tc-1',
|
|
title: 'Shell',
|
|
kind: 'execute',
|
|
options: []
|
|
}, { outcome: 'cancelled' });
|
|
await pending;
|
|
});
|
|
});
|
|
|
|
describe('AcpSdkBackend abortSoftSteers', () => {
|
|
it('drains buffered foreground output before suppressing late updates', async () => {
|
|
const backend = new AcpSdkBackend({ command: 'agent' });
|
|
const updates: AgentMessage[] = [];
|
|
const handler = new AcpMessageHandler((message) => updates.push(message));
|
|
const backendInternal = backend as unknown as {
|
|
messageHandler: AcpMessageHandler | null;
|
|
};
|
|
|
|
await handler.handleUpdate({
|
|
sessionUpdate: ACP_SESSION_UPDATE_TYPES.agentMessageChunk,
|
|
content: { type: 'text', text: 'partial answer' }
|
|
});
|
|
await handler.handleUpdate({
|
|
sessionUpdate: ACP_SESSION_UPDATE_TYPES.agentThoughtChunk,
|
|
content: { type: 'text', text: 'partial thought' }
|
|
});
|
|
backendInternal.messageHandler = handler;
|
|
|
|
backend.abortSoftSteers();
|
|
|
|
expect(updates).toEqual([
|
|
{ type: 'reasoning', text: 'partial thought' },
|
|
{ type: 'text', text: 'partial answer' }
|
|
]);
|
|
});
|
|
|
|
it('releases processingMessage without waiting for the concurrent prompt', () => {
|
|
const backend = new AcpSdkBackend({ command: 'agent' });
|
|
const backendInternal = backend as unknown as {
|
|
isProcessingMessage: boolean;
|
|
activePromptRequests: number;
|
|
};
|
|
backendInternal.isProcessingMessage = true;
|
|
backendInternal.activePromptRequests = 2;
|
|
|
|
backend.abortSoftSteers();
|
|
|
|
expect(backend.processingMessage).toBe(false);
|
|
expect(backendInternal.activePromptRequests).toBe(0);
|
|
});
|
|
|
|
it('is a no-op when nothing is in flight', () => {
|
|
const backend = new AcpSdkBackend({ command: 'agent' });
|
|
const backendInternal = backend as unknown as {
|
|
activePromptRequests: number;
|
|
};
|
|
backendInternal.activePromptRequests = 0;
|
|
|
|
expect(() => backend.abortSoftSteers()).not.toThrow();
|
|
expect(backend.processingMessage).toBe(false);
|
|
});
|
|
});
|