Skip to content

Commit af10be5

Browse files
committed
fix(approvals): stop stale approval resume loops
1 parent 2a0af67 commit af10be5

5 files changed

Lines changed: 81 additions & 14 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,8 @@ Docs: https://docs.openclaw.ai
5757

5858
### Fixes
5959

60+
- Agents/approvals: fail restart-interrupted sessions whose transcript tail is still `approval-pending` instead of replaying stale exec approval IDs into the new Gateway process after restart. Fixes #65486. Thanks @mjmai20682068-create.
61+
- CLI/Gateway: use method-specific least-privilege scopes for classified CLI Gateway calls while preserving legacy broad scopes for unclassified plugin methods, so read-only commands no longer create admin/write/pairing scope-upgrade prompts. Fixes #68634. Thanks @nightmusher.
6062
- Gateway/sessions: align `chat.history` and `sessions.list` thinking defaults with owning-agent and catalog-aware resolution so Control UI session defaults match backend runtime state. (#63418) Thanks @jpreagan.
6163
- Devices/pairing: recover array-shaped device and node pairing state files before persisting approvals, so UUID-keyed pending and paired entries no longer disappear after a malformed JSON store write. Fixes #63035. Thanks @sar618.
6264
- Gateway/auth: clear reused stale device tokens and stop reconnecting on device-token mismatch in the Control UI and Node gateway clients, avoiding rate-limit loops after scope-upgrade or token-rotation handoffs. Fixes #71609. Thanks @ricksayhi.

‎src/agents/main-session-restart-recovery.test.ts‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -123,6 +123,40 @@ describe("main-session-restart-recovery", () => {
123123
expect(store["agent:main:main"]?.abortedLastRun).toBe(false);
124124
});
125125

126+
it("fails marked sessions with stale approval-pending exec tool results", async () => {
127+
const sessionsDir = await makeSessionsDir();
128+
await writeStore(sessionsDir, {
129+
"agent:main:main": {
130+
sessionId: "main-session",
131+
updatedAt: Date.now() - 10_000,
132+
status: "running",
133+
abortedLastRun: true,
134+
},
135+
});
136+
await writeTranscript(sessionsDir, "main-session", [
137+
{ role: "user", content: "run a command that needs approval" },
138+
{ role: "assistant", content: [{ type: "toolCall", id: "call-1", name: "exec" }] },
139+
{
140+
role: "toolResult",
141+
content: "Approval required (id stale, full stale-approval-id).",
142+
details: {
143+
status: "approval-pending",
144+
approvalId: "stale-approval-id",
145+
host: "gateway",
146+
command: "echo stale",
147+
},
148+
},
149+
]);
150+
151+
const result = await recoverRestartAbortedMainSessions({ stateDir: tmpDir });
152+
153+
expect(result).toEqual({ recovered: 0, failed: 1, skipped: 0 });
154+
expect(callGateway).not.toHaveBeenCalled();
155+
const store = loadSessionStore(path.join(sessionsDir, "sessions.json"));
156+
expect(store["agent:main:main"]?.status).toBe("failed");
157+
expect(store["agent:main:main"]?.abortedLastRun).toBe(true);
158+
});
159+
126160
it("does not scan ordinary running sessions without the restart-aborted marker", async () => {
127161
const sessionsDir = await makeSessionsDir();
128162
await writeStore(sessionsDir, {

‎src/agents/main-session-restart-recovery.ts‎

Lines changed: 22 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -62,9 +62,26 @@ function isResumableTailMessage(message: unknown): boolean {
6262
return role === "user" || role === "tool" || role === "toolResult";
6363
}
6464

65-
function isMainSessionResumable(messages: unknown[]): boolean {
65+
function isApprovalPendingToolResult(message: unknown): boolean {
66+
if (!message || typeof message !== "object" || getMessageRole(message) !== "toolResult") {
67+
return false;
68+
}
69+
const details = (message as { details?: unknown }).details;
70+
if (!details || typeof details !== "object") {
71+
return false;
72+
}
73+
return (details as { status?: unknown }).status === "approval-pending";
74+
}
75+
76+
function resolveMainSessionResumeBlockReason(messages: unknown[]): string | null {
6677
const lastMeaningful = messages.toReversed().find(isMeaningfulTailMessage);
67-
return lastMeaningful ? isResumableTailMessage(lastMeaningful) : false;
78+
if (!lastMeaningful || !isResumableTailMessage(lastMeaningful)) {
79+
return "transcript tail is not resumable";
80+
}
81+
if (isApprovalPendingToolResult(lastMeaningful)) {
82+
return "transcript tail is a stale approval-pending tool result";
83+
}
84+
return null;
6885
}
6986

7087
function buildResumeMessage(): string {
@@ -216,11 +233,12 @@ async function recoverStore(params: {
216233
continue;
217234
}
218235

219-
if (!isMainSessionResumable(messages)) {
236+
const resumeBlockReason = resolveMainSessionResumeBlockReason(messages);
237+
if (resumeBlockReason) {
220238
await markSessionFailed({
221239
storePath: params.storePath,
222240
sessionKey,
223-
reason: "transcript tail is not resumable",
241+
reason: resumeBlockReason,
224242
});
225243
result.failed++;
226244
continue;

‎src/gateway/call.test.ts‎

Lines changed: 17 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -482,23 +482,31 @@ describe("callGateway url resolution", () => {
482482
expectedScopes: ["operator.read"],
483483
},
484484
{
485-
label: "keeps legacy admin scopes for explicit CLI callers",
485+
label: "uses least-privilege scopes by default for explicit CLI callers",
486486
call: () => callGatewayCli({ method: "health" }),
487-
expectedScopes: [
488-
"operator.admin",
489-
"operator.read",
490-
"operator.write",
491-
"operator.approvals",
492-
"operator.pairing",
493-
"operator.talk.secrets",
494-
],
487+
expectedScopes: ["operator.read"],
495488
},
496489
])("scope selection: $label", async ({ call, expectedScopes }) => {
497490
setLocalLoopbackGatewayConfig();
498491
await call();
499492
expect(lastClientOptions?.scopes).toEqual(expectedScopes);
500493
});
501494

495+
it("keeps legacy broad scopes for unclassified explicit CLI methods", async () => {
496+
setLocalLoopbackGatewayConfig();
497+
498+
await callGatewayCli({ method: "plugin.custom.unclassified" });
499+
500+
expect(lastClientOptions?.scopes).toEqual([
501+
"operator.admin",
502+
"operator.read",
503+
"operator.write",
504+
"operator.approvals",
505+
"operator.pairing",
506+
"operator.talk.secrets",
507+
]);
508+
});
509+
502510
it("passes explicit scopes through, including empty arrays", async () => {
503511
setLocalLoopbackGatewayConfig();
504512

‎src/gateway/call.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ import {
3535
import { canSkipGatewayConfigLoad } from "./explicit-connection-policy.js";
3636
import {
3737
CLI_DEFAULT_OPERATOR_SCOPES,
38+
isGatewayMethodClassified,
3839
resolveLeastPrivilegeOperatorScopesForMethod,
3940
type OperatorScope,
4041
} from "./method-scopes.js";
@@ -635,7 +636,11 @@ export async function callGatewayScoped<T = Record<string, unknown>>(
635636
export async function callGatewayCli<T = Record<string, unknown>>(
636637
opts: CallGatewayCliOptions,
637638
): Promise<T> {
638-
const scopes = Array.isArray(opts.scopes) ? opts.scopes : CLI_DEFAULT_OPERATOR_SCOPES;
639+
const scopes = Array.isArray(opts.scopes)
640+
? opts.scopes
641+
: isGatewayMethodClassified(opts.method)
642+
? resolveLeastPrivilegeOperatorScopesForMethod(opts.method)
643+
: CLI_DEFAULT_OPERATOR_SCOPES;
639644
return await callGatewayWithScopes(opts, scopes);
640645
}
641646

0 commit comments

Comments
 (0)