Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 30 additions & 2 deletions bin/opencode-acp-adapter.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -232,7 +232,24 @@ async function serveJson(pathname, { method = 'GET', body } = {}) {
// ---------------------------------------------------------------------------

let nextOutgoingId = 1;
const pendingClientRequests = new Map(); // id -> { resolve, reject }
const pendingClientRequests = new Map(); // id -> { resolve, reject, timer }

// #8314: bound the wait for a client answer to a request we send.
// requestClient's only caller is handlePermissionAsked
// (session/request_permission): an approver who never answers would
// otherwise hold the pending entry — and, through it, the serve-side
// permission reply — for the process lifetime, wedging the gated
// tool call until the session is interrupted. On expiry the request
// rejects through the same failed-request path an errored answer
// takes, which posts the reject decision to the serve reply
// endpoint, and the pending entry is dropped. The default is
// generous (10 minutes: a human approver may be reading the prompt,
// and the serve has no shorter deadline of its own) but finite.
// Tests override it via OPENCODE_ACP_PERMISSION_TIMEOUT_MS.
const PERMISSION_REQUEST_TIMEOUT_MS = (() => {
const fromEnv = Number(process.env.OPENCODE_ACP_PERMISSION_TIMEOUT_MS);
return Number.isFinite(fromEnv) && fromEnv > 0 ? fromEnv : 600_000;
})();

function send(message) {
process.stdout.write(`${JSON.stringify(message)}\n`);
Expand All @@ -254,7 +271,17 @@ function requestClient(method, params) {
const id = nextOutgoingId;
nextOutgoingId += 1;
return new Promise((resolve, reject) => {
pendingClientRequests.set(id, { resolve, reject });
const timer = setTimeout(() => {
if (pendingClientRequests.delete(id)) {
reject(
new Error(
`client did not answer ${method} within ${PERMISSION_REQUEST_TIMEOUT_MS}ms (#8314)`,
),
);
}
}, PERMISSION_REQUEST_TIMEOUT_MS);
timer.unref?.();
pendingClientRequests.set(id, { resolve, reject, timer });
send({ jsonrpc: '2.0', id, method, params });
});
}
Expand Down Expand Up @@ -736,6 +763,7 @@ async function dispatch(message) {
if (isRequest && pendingClientRequests.has(id)) {
const pending = pendingClientRequests.get(id);
pendingClientRequests.delete(id);
clearTimeout(pending.timer);
if (message.error) pending.reject(new Error(message.error.message || 'client request failed'));
else pending.resolve(message.result);
}
Expand Down
51 changes: 51 additions & 0 deletions bin/opencode-acp-adapter.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -318,6 +318,57 @@ test('serve permission events round-trip through session/request_permission', as
assert.deepEqual(permCall.body, { decision: 'once' });
});

test('an unanswered permission request expires and is rejected to the serve (#8314)', async (t) => {
// Oracle: with a short OPENCODE_ACP_PERMISSION_TIMEOUT_MS, a
// session/request_permission the client never answers resolves via
// handlePermissionAsked's failed-request path — the adapter posts
// {decision: 'reject'} to the serve permission reply endpoint
// instead of waiting forever — and the pending entry is gone: a
// late answer for the same request id is ignored (no second reply)
// and the adapter keeps working.
let emitRef = null;
const script = (emit) => {
emitRef = emit;
emit({
type: 'permission.asked',
data: { id: 'perm-timeout', sessionID: SESSION_ID, action: 'bash', resources: ['ls'], metadata: {} },
});
};
const { stub, acp } = await setup(t, script, { OPENCODE_ACP_PERMISSION_TIMEOUT_MS: '200' });
await acp.request('session/new', { cwd: '/home/user/code', mcpServers: [] });
const promptPromise = acp.request('session/prompt', {
sessionId: SESSION_ID,
prompt: [{ type: 'text', text: 'list files' }],
});
const permRequest = await acp.waitFor(
() => acp.clientRequests.find((r) => r.method === 'session/request_permission'),
'session/request_permission',
);
// Never answer. The expiry must produce the reject reply on its own.
const permCall = await acp.waitFor(
() =>
stub.calls.find(
(c) => c.pathname === `/api/session/${SESSION_ID}/permission/perm-timeout/reply`,
),
'permission reject reply after expiry',
);
assert.deepEqual(permCall.body, { decision: 'reject' });

// A late answer is a no-op: the pending entry was deleted at
// expiry, so nothing resolves again and no second reply is posted.
acp.respond(permRequest.id, { outcome: { outcome: 'selected', optionId: 'allow_once' } });
await sleep(300);
assert.equal(
stub.calls.filter((c) => c.pathname.endsWith('/permission/perm-timeout/reply')).length,
1,
'late answer after expiry posted a second permission reply',
);

emitRef({ type: 'session.execution.succeeded', data: { sessionID: SESSION_ID } });
const result = await promptPromise;
assert.equal(result.stopReason, 'end_turn');
});

test('session/cancel interrupts on the serve and the prompt resolves cancelled', async (t) => {
const { stub, acp } = await setup(t, () => {
// Never completes on its own: only the interrupt (stub emits
Expand Down