Skip to content

Commit e38fe43

Browse files
hhyykkcodexloopx-agent
authored
fix(workbench): settle ACP approvals with their request lifetime (#9826)
* fix(workbench): settle ACP approvals with their request lifetime Signed-off-by: Codex <codex@openai.com> * fix(workbench): preserve known fields in ACP approval snapshots Signed-off-by: Codex <codex@openai.com> --------- Signed-off-by: Codex <codex@openai.com> Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Co-authored-by: Codex <codex@openai.com> Co-authored-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com>
1 parent 0367b0e commit e38fe43

13 files changed

Lines changed: 473 additions & 92 deletions

File tree

‎apps/workbench/README.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,8 @@ LooChat 不动 agent 本身的目录、配置和会话,装好即用。图标
8383

8484
Agy 的权限请求使用现有审批入口;已有「完全访问」默认值保留。图片通过原生 ACP 图片块传入,上下文占用使用 ACP 用量事件;`/compact` 在当前会话内执行,并显示成功、失败或取消。旧的原生会话 ID 通过 `session/resume` 恢复。登录和 `/usage` 等账号查询继续走已有原生 CLI 入口。
8585

86+
审批卡对应当前会话中的一次工具请求。等待期间,如果工具结束、请求被撤回或替换、目标或输入改变,工作台会关闭旧卡,并向 Agent 返回取消。结束当前轮次或切换权限策略也会取消待处理的审批。对话历史记录审批已取消。继续执行需要 Agent 为仍然有效的调用发起新请求。
87+
8688
下图使用隔离测试目录与假 Agent,展示实际构建页面中的模型分组和强度选择:
8789

8890
![按模型归并的目录](docs/images/antigravity-model-families.png)

‎apps/workbench/packages/daemon/src/adapters/acp.ts‎

Lines changed: 193 additions & 61 deletions
Large diffs are not rendered by default.

‎apps/workbench/packages/daemon/src/adapters/types.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,8 @@ export interface PermissionOption {
4444
}
4545

4646
export interface ApprovalRequest {
47+
/** Ends the card when the native request loses its turn or tool call. */
48+
signal?: AbortSignal;
4749
title: string;
4850
options: PermissionOption[];
4951
/** Raw tool-call payload from the agent, shown to the user as-is. */

‎apps/workbench/packages/daemon/src/threads.ts‎

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3495,6 +3495,12 @@ export class ThreadManager {
34953495
if (session) await session.cancel();
34963496
}
34973497

3498+
private approvalTurnIsCurrent(threadId: string, turnId: string): boolean {
3499+
const run = this.running.get(threadId);
3500+
const native = [...(this.nativeTurns.get(threadId)?.values() ?? [])].includes(turnId);
3501+
return this.approvalTurns.get(turnId) === threadId && !run?.cancelRequested && (run?.turnId === turnId || native);
3502+
}
3503+
34983504
/**
34993505
* Answers a pending approval. Returns false if there is none with this id.
35003506
* An option the agent did not offer is an error: agents treat unknown ids as a refusal,
@@ -3503,6 +3509,11 @@ export class ThreadManager {
35033509
resolveApproval(approvalId: string, decision: ApprovalDecision): boolean {
35043510
const p = this.approvals.get(approvalId);
35053511
if (!p) return false;
3512+
if (!('cancelled' in decision) && !this.approvalTurnIsCurrent(p.threadId, p.turnId)) {
3513+
this.approvals.delete(approvalId);
3514+
p.resolve({ cancelled: true });
3515+
return false;
3516+
}
35063517
if (!('cancelled' in decision) && !p.optionIds.includes(decision.optionId)) {
35073518
throw new HttpError(400, `not one of the offered options: ${decision.optionId}`);
35083519
}
@@ -4041,25 +4052,26 @@ export class ThreadManager {
40414052
? Promise.resolve({ cancelled: true }) : this.inputs.request(threadId, turnId, req),
40424053
cancelInput: id => this.inputs.cancel(threadId, id, true),
40434054
requestApproval: (req: ApprovalRequest) => {
4044-
const run = this.running.get(threadId);
4045-
const native = [...(this.nativeTurns.get(threadId)?.values() ?? [])].includes(turnId);
4046-
if (this.approvalTurns.get(turnId) !== threadId || run?.cancelRequested || (run?.turnId !== turnId && !native)) return Promise.resolve({ cancelled: true });
4055+
if (req.signal?.aborted || !this.approvalTurnIsCurrent(threadId, turnId)) return Promise.resolve({ cancelled: true });
40474056
// A Goal conversation never asks the person: what its sandbox does not allow is simply refused.
40484057
const refused = this.loopx?.refuse(threadId, req);
40494058
if (refused) return Promise.resolve(refused);
40504059
const approvalId = randomUUID();
40514060
return new Promise<ApprovalDecision>((resolve) => {
4061+
const cancel = () => this.resolveApproval(approvalId, { cancelled: true });
40524062
this.approvals.set(approvalId, {
40534063
threadId,
40544064
turnId,
40554065
title: req.title,
40564066
options: req.options.map((o) => ({ optionId: o.optionId, name: o.name, kind: o.kind })),
40574067
optionIds: req.options.map((o) => o.optionId),
40584068
resolve: (decision) => {
4069+
req.signal?.removeEventListener('abort', cancel);
40594070
this.emitThreadEvent(threadId, turnId, 'approval.resolved', { approvalId, decision });
40604071
resolve(decision);
40614072
},
40624073
});
4074+
req.signal?.addEventListener('abort', cancel, { once: true });
40634075
this.emitThreadEvent(threadId, turnId, 'approval.request', {
40644076
approvalId,
40654077
title: req.title,
Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
import assert from 'node:assert/strict';
2+
import { copyFileSync, mkdtempSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
3+
import { tmpdir } from 'node:os';
4+
import { join } from 'node:path';
5+
import { test } from 'node:test';
6+
import { fileURLToPath } from 'node:url';
7+
import { AgyAdapter } from '../src/adapters/agy.js';
8+
import type { ApprovalDecision, ApprovalRequest } from '../src/adapters/types.js';
9+
10+
const fixture = fileURLToPath(new URL('./fixtures/fake-agy.mjs', import.meta.url));
11+
const input = { text: 'Review fixture metadata', images: [] };
12+
const cases = [
13+
['current', 'selected'], ['progress', 'selected'], ['partial-progress', 'selected'], ['other-tool', 'selected'],
14+
['complete', 'cancelled'], ['withdraw', 'cancelled'], ['revise', 'cancelled'], ['partial-revise', 'cancelled'],
15+
['turn', 'cancelled'], ['policy', 'cancelled'],
16+
] as const;
17+
18+
for (const [event, expected] of cases) {
19+
test(`ACP approval lifecycle follows ${event}`, { timeout: 12000 }, async t => {
20+
const cwd = mkdtempSync(join(tmpdir(), 'loochat-acp-lifecycle-'));
21+
t.after(() => rmSync(cwd, { recursive: true, force: true }));
22+
const adapter = new AgyAdapter([process.execPath, fixture]);
23+
const session = await adapter.start({ cwd, permissionMode: 'ask' });
24+
const opened = Promise.withResolvers<ApprovalRequest>();
25+
const decision = Promise.withResolvers<ApprovalDecision>();
26+
const progress = Promise.withResolvers<void>();
27+
let requests = 0;
28+
const firstInput = event.startsWith('partial-') ? { ...input, text: `${input.text} (partial)` } : input;
29+
try {
30+
const first = session.prompt(firstInput, {
31+
emit(update) { if (update.type === 'tool.update' || update.type === 'tool.end') progress.resolve(); },
32+
requestApproval(request) { requests++; opened.resolve(request); return decision.promise; },
33+
});
34+
const approval = await opened.promise;
35+
assert.equal(approval.title, 'Review fixture metadata');
36+
if (event === 'turn') await session.cancel();
37+
else if (event === 'policy') await session.setPermissionMode!('auto_edit');
38+
else if (event !== 'current') {
39+
const marker = join(cwd, 'fixture-approval-step');
40+
writeFileSync(`${marker}.tmp`, event);
41+
renameSync(`${marker}.tmp`, marker);
42+
}
43+
let abortedBeforeChoosing: boolean | undefined;
44+
if (expected === 'selected') {
45+
if (event !== 'current') await progress.promise;
46+
abortedBeforeChoosing = approval.signal?.aborted;
47+
decision.resolve({ optionId: 'allow' });
48+
}
49+
assert.equal((await first).stopReason, 'end_turn');
50+
assert.equal(approval.signal?.aborted, true);
51+
assert.equal(requests, 1);
52+
decision.resolve({ optionId: 'allow' });
53+
54+
if (event === 'policy') await session.setPermissionMode!('ask');
55+
const next = await session.prompt(input, {
56+
emit() {}, requestApproval: async () => { requests++; return { optionId: 'allow' }; },
57+
});
58+
assert.equal(next.stopReason, 'end_turn');
59+
assert.equal(requests, 2);
60+
const log = join(cwd, 'fixture-approval-replies.jsonl');
61+
const evidence = process.env.LOOCHAT_ACP_LIFECYCLE_EVIDENCE;
62+
if (evidence) copyFileSync(log, join(evidence, `${event}.jsonl`));
63+
const records = readFileSync(log, 'utf8').trim().split('\n').map(line => JSON.parse(line));
64+
assert.equal(new Set(records.map(record => record.id)).size, 2);
65+
const accepted = { outcome: 'selected', optionId: 'allow' };
66+
assert.deepEqual(records.map(record => record.outcome), [expected === 'selected' ? accepted : { outcome: 'cancelled' }, accepted]);
67+
if (expected === 'selected') assert.equal(abortedBeforeChoosing, false);
68+
} finally {
69+
decision.resolve({ cancelled: true });
70+
await session.close();
71+
}
72+
});
73+
}

0 commit comments

Comments
 (0)