Skip to content

Commit 20b2dac

Browse files
authored
fix(worker): preserve actionable cloud failure causes (#134200)
Freeze uploaded workspace bytes before opening the transfer request, preserve safe validation reason codes, and keep execution failures primary when reconciliation also fails. Co-authored-by: Takhoffman <[email protected]> Worked on by: - @Takhoffman Co-authored-by: roboclaw-bot <[email protected]>
1 parent 593af08 commit 20b2dac

16 files changed

Lines changed: 685 additions & 97 deletions

‎extensions/codex/src/node-exec-server.test.ts‎

Lines changed: 30 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -272,12 +272,37 @@ describe("Codex node exec-server", () => {
272272
invokeNode,
273273
} satisfies OpenClawPluginNodeInvokePolicyContext;
274274

275-
for (const decision of ["deny", "allow-always", null] as const) {
275+
for (const { decision, result } of [
276+
{
277+
decision: "deny",
278+
result: {
279+
ok: false,
280+
code: "CODEX_NODE_EXEC_APPROVAL_DENIED",
281+
message:
282+
"Codex node execution was denied. Retry the action and choose Allow once to continue.",
283+
},
284+
},
285+
{
286+
decision: "allow-always",
287+
result: {
288+
ok: false,
289+
code: "CODEX_NODE_EXEC_APPROVAL_INVALID",
290+
message:
291+
"Codex node execution cannot use permanent approval. Retry the action and choose Allow once.",
292+
},
293+
},
294+
{
295+
decision: null,
296+
result: {
297+
ok: false,
298+
code: "CODEX_NODE_EXEC_APPROVAL_EXPIRED",
299+
message:
300+
"Codex node execution approval expired before a decision. Retry the action and approve the new request.",
301+
},
302+
},
303+
] as const) {
276304
request.mockResolvedValueOnce({ decision });
277-
await expect(policy.handle(context)).resolves.toMatchObject({
278-
ok: false,
279-
code: "CODEX_NODE_EXEC_APPROVAL_DENIED",
280-
});
305+
await expect(policy.handle(context)).resolves.toEqual(result);
281306
expect(invokeNode).not.toHaveBeenCalled();
282307
}
283308
await expect(policy.handle({ ...context, approvals: undefined })).resolves.toMatchObject({

‎extensions/codex/src/node-exec-server.ts‎

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -174,10 +174,27 @@ export function createCodexNodeExecServerInvokePolicy(): OpenClawPluginNodeInvok
174174
allowedDecisions: ["allow-once"],
175175
});
176176
if (approval.decision !== "allow-once") {
177+
if (approval.decision === "deny") {
178+
return {
179+
ok: false,
180+
code: "CODEX_NODE_EXEC_APPROVAL_DENIED",
181+
message:
182+
"Codex node execution was denied. Retry the action and choose Allow once to continue.",
183+
};
184+
}
185+
if (approval.decision === "allow-always") {
186+
return {
187+
ok: false,
188+
code: "CODEX_NODE_EXEC_APPROVAL_INVALID",
189+
message:
190+
"Codex node execution cannot use permanent approval. Retry the action and choose Allow once.",
191+
};
192+
}
177193
return {
178194
ok: false,
179-
code: "CODEX_NODE_EXEC_APPROVAL_DENIED",
180-
message: "Codex node execution requires one-time approval.",
195+
code: "CODEX_NODE_EXEC_APPROVAL_EXPIRED",
196+
message:
197+
"Codex node execution approval expired before a decision. Retry the action and approve the new request.",
181198
};
182199
}
183200
return await context.invokeNode({

‎src/gateway/server-methods/chat-send-agent-dispatch.ts‎

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,17 @@ type StartChatDispatchParams = {
8787
userTurn: ReturnType<typeof createGatewayChatUserTurnController>;
8888
};
8989

90+
function formatReturnedAgentErrors(messages: string[]): string | undefined {
91+
const [primary, ...additional] = [...new Set(messages)];
92+
if (!primary || additional.length === 0) {
93+
return primary;
94+
}
95+
if (additional.length === 1) {
96+
return `${primary}\n\nAdditional error: ${additional[0]}`;
97+
}
98+
return `${primary}\n\nAdditional errors:\n${additional.map((message) => `- ${message}`).join("\n")}`;
99+
}
100+
90101
export function startChatDispatch(params: StartChatDispatchParams): void {
91102
const {
92103
admissionStartedAt,
@@ -457,10 +468,11 @@ export function startChatDispatch(params: StartChatDispatchParams): void {
457468
(agentRunStarted || !isInternalTextSlashCommandTurn);
458469
const returnedAgentErrorMessage =
459470
runtimeOutcome?.error ??
460-
(returnedAgentErrorPayloads
461-
.map((payload) => payload.text?.trim())
462-
.filter((text): text is string => Boolean(text))
463-
.join(" | ") ||
471+
(formatReturnedAgentErrors(
472+
returnedAgentErrorPayloads
473+
.map((payload) => payload.text?.trim())
474+
.filter((text): text is string => Boolean(text)),
475+
) ||
464476
(runtimeFailed ? "agent run failed" : undefined));
465477
if (
466478
!userTurnRecorder.hasPersisted() &&

‎src/gateway/server-methods/chat.directive-tags.test.ts‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4353,6 +4353,27 @@ describe("chat directive tag stripping for non-streaming final payloads", () =>
43534353
expect(finalBroadcasts).toStrictEqual([]);
43544354
});
43554355

4356+
it("labels additional returned agent errors instead of flattening them", async () => {
4357+
await createTranscriptFixture("openclaw-chat-send-multiple-agent-errors-");
4358+
mockState.triggerAgentRunStart = true;
4359+
mockState.dispatchedReplies = [
4360+
{ kind: "final", payload: { text: "Primary execution failed", isError: true } },
4361+
{ kind: "final", payload: { text: "Workspace recovery failed", isError: true } },
4362+
{ kind: "final", payload: { text: "Workspace recovery failed", isError: true } },
4363+
];
4364+
const { send } = createChatRequestFixture();
4365+
4366+
const broadcast = await send({
4367+
idempotencyKey: "idem-multiple-agent-errors",
4368+
message: "run on the worker",
4369+
});
4370+
4371+
expect(broadcast).toMatchObject({
4372+
state: "error",
4373+
errorMessage: "Primary execution failed\n\nAdditional error: Workspace recovery failed",
4374+
});
4375+
});
4376+
43564377
it.each([
43574378
["error payload after start", true, "error", undefined],
43584379
["error payload before launch", false, "error", undefined],

‎src/gateway/worker-environments/node-workspace-transfer-http.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import type {
1414
} from "./node-workspace-transfer-http-contract.js";
1515
import {
1616
isNodeWorkspaceTransferLimitError,
17+
nodeWorkspaceTransferInvalidReason,
1718
type NodeWorkspaceTransferService,
1819
} from "./node-workspace-transfer-service.js";
1920

@@ -276,9 +277,11 @@ export function createNodeWorkspaceTransferHttpCallback(
276277
return;
277278
}
278279
const limit = isNodeWorkspaceTransferLimitError(error);
280+
const reason = nodeWorkspaceTransferInvalidReason(error);
279281
const body = Buffer.from(
280282
JSON.stringify({
281283
error: limit ? "workspace_transfer_limit" : "workspace_transfer_invalid",
284+
...(reason ? { reason } : {}),
282285
}),
283286
);
284287
res.writeHead(limit ? 413 : 400, {

‎src/gateway/worker-environments/node-workspace-transfer-service.test.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -409,7 +409,9 @@ describe("node workspace transfer service", () => {
409409
"environment-1",
410410
prepared.snapshot.manifestRef,
411411
);
412-
await expect(uploadResult(failedUploadToken)).rejects.toThrow("workspace-transfer-failed");
412+
await expect(uploadResult(failedUploadToken)).rejects.toThrow(
413+
"workspace-transfer-invalid: gateway rejected workspace transfer payload (staging)",
414+
);
413415
expect(writeFaults.lastStagingRoot()).toBeDefined();
414416
await expect(fs.stat(writeFaults.lastStagingRoot()!)).rejects.toMatchObject({
415417
code: "ENOENT",

‎src/gateway/worker-environments/node-workspace-transfer-service.ts‎

Lines changed: 67 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import {
1313
import { mintNodeWorkspaceTransferToken } from "./node-workspace-transfer-token.js";
1414
import {
1515
MAX_UPLOAD_BYTES,
16+
NodeWorkspaceTransferInvalidError,
1617
NodeWorkspaceTransferLimitError,
1718
RequestByteReader,
1819
streamUploadFile,
@@ -34,7 +35,10 @@ import {
3435
} from "./workspace-reconcile.js";
3536
import { workerWorkspaceTransferPaths } from "./workspace-result-staging.js";
3637

37-
export { isNodeWorkspaceTransferLimitError } from "./node-workspace-upload-reader.js";
38+
export {
39+
isNodeWorkspaceTransferLimitError,
40+
nodeWorkspaceTransferInvalidReason,
41+
} from "./node-workspace-upload-reader.js";
3842

3943
const TRANSFER_TIMEOUT_MS = 10 * 60_000;
4044
const MANIFEST_REF_PATTERN = /^sha256:[a-f0-9]{64}$/u;
@@ -599,13 +603,30 @@ export function createNodeWorkspaceTransferService(options: {
599603
}
600604
const raw = (await reader.readExactly(bytes)).toString("utf8");
601605
const ref = expectedRef ?? `sha256:${createHash("sha256").update(raw).digest("hex")}`;
602-
return { raw, ref, manifest: parseWorkerWorkspaceManifest(raw, ref) };
606+
try {
607+
return { raw, ref, manifest: parseWorkerWorkspaceManifest(raw, ref) };
608+
} catch (error) {
609+
throw new NodeWorkspaceTransferInvalidError(
610+
"manifest",
611+
"Workspace transfer manifest is invalid",
612+
{ cause: error },
613+
);
614+
}
603615
};
604616
const base = await readManifest(operation.baseManifestRef);
605617
assertCurrent();
606618
const current = await readManifest();
607619
assertCurrent();
608-
const transferPaths = workerWorkspaceTransferPaths(current.manifest, base.manifest);
620+
let transferPaths: string[];
621+
try {
622+
transferPaths = workerWorkspaceTransferPaths(current.manifest, base.manifest);
623+
} catch (error) {
624+
throw new NodeWorkspaceTransferInvalidError(
625+
"manifest",
626+
"Workspace transfer manifests cannot be reconciled",
627+
{ cause: error },
628+
);
629+
}
609630
const transferPathSet = new Set(transferPaths);
610631
stagingRoot = await fsp.mkdtemp(path.join(authorization.context.temporaryRoot, "upload-"));
611632
const currentByPath = new Map(current.manifest.entries.map((entry) => [entry.path, entry]));
@@ -614,32 +635,57 @@ export function createNodeWorkspaceTransferService(options: {
614635
if (!entry) {
615636
continue;
616637
}
617-
const destination = entryPath(stagingRoot, relative);
618-
await fsp.mkdir(path.dirname(destination), { recursive: true, mode: 0o700 });
619-
assertCurrent();
620-
if (entry.type === "symlink") {
621-
await fsp.symlink(entry.target, destination);
638+
try {
639+
const destination = entryPath(stagingRoot, relative);
640+
await fsp.mkdir(path.dirname(destination), { recursive: true, mode: 0o700 });
622641
assertCurrent();
623-
} else {
624-
const handle = await fsp.open(destination, "wx", entry.mode);
625-
try {
626-
await streamUploadFile({ reader, handle, entry, assertCurrent });
627-
} finally {
628-
await handle.close();
642+
if (entry.type === "symlink") {
643+
await fsp.symlink(entry.target, destination);
644+
assertCurrent();
645+
} else {
646+
const handle = await fsp.open(destination, "wx", entry.mode);
647+
try {
648+
await streamUploadFile({ reader, handle, entry, assertCurrent });
649+
} finally {
650+
await handle.close();
651+
}
652+
assertCurrent();
629653
}
630-
assertCurrent();
654+
} catch (error) {
655+
if (error instanceof NodeWorkspaceTransferInvalidError) {
656+
throw error;
657+
}
658+
if (params.signal.aborted || !authorizationCurrent(authorization)) {
659+
throw error;
660+
}
661+
throw new NodeWorkspaceTransferInvalidError(
662+
"staging",
663+
"Workspace transfer payload could not be staged",
664+
{ cause: error },
665+
);
631666
}
632667
}
633668
await reader.assertEnd();
634669
assertCurrent();
635670
if (reader.bytesRead !== contentLength) {
636-
throw new Error("Workspace transfer upload length is inconsistent");
671+
throw new NodeWorkspaceTransferInvalidError(
672+
"content_length",
673+
"Workspace transfer upload length is inconsistent",
674+
);
675+
}
676+
try {
677+
await assertWorkspaceMatchesManifest({
678+
root: stagingRoot,
679+
manifest: current.manifest,
680+
entries: current.manifest.entries.filter((entry) => transferPathSet.has(entry.path)),
681+
});
682+
} catch (error) {
683+
throw new NodeWorkspaceTransferInvalidError(
684+
"staging",
685+
"Workspace transfer payload did not match its staged result",
686+
{ cause: error },
687+
);
637688
}
638-
await assertWorkspaceMatchesManifest({
639-
root: stagingRoot,
640-
manifest: current.manifest,
641-
entries: current.manifest.entries.filter((entry) => transferPathSet.has(entry.path)),
642-
});
643689
assertCurrent();
644690
operation.uploaded = {
645691
base: base.manifest,

‎src/gateway/worker-environments/node-workspace-upload-reader.test.ts‎

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,10 @@
11
import type { IncomingMessage } from "node:http";
22
import { Readable } from "node:stream";
33
import { describe, expect, it } from "vitest";
4-
import { RequestByteReader } from "./node-workspace-upload-reader.js";
4+
import {
5+
NodeWorkspaceTransferInvalidError,
6+
RequestByteReader,
7+
} from "./node-workspace-upload-reader.js";
58

69
function createReader(chunks: Buffer[]): RequestByteReader {
710
const request = Readable.from(chunks) as unknown as IncomingMessage;
@@ -44,7 +47,10 @@ describe("workspace upload byte stream", () => {
4447
it("rejects premature EOF across chunk boundaries", async () => {
4548
const reader = createReader([Buffer.from("ab"), Buffer.from("c")]);
4649

47-
await expect(reader.readExactly(4)).rejects.toThrow("ended before its declared payload");
50+
await expect(reader.readExactly(4)).rejects.toMatchObject({
51+
constructor: NodeWorkspaceTransferInvalidError,
52+
reason: "premature_eof",
53+
});
4854
});
4955

5056
it.each(["buffered", "next chunk"])("rejects trailing bytes in the %s suffix", async (suffix) => {
@@ -53,6 +59,9 @@ describe("workspace upload byte stream", () => {
5359
);
5460

5561
await expect(reader.readExactly(3)).resolves.toEqual(Buffer.from("abc"));
56-
await expect(reader.assertEnd()).rejects.toThrow("contains trailing bytes");
62+
await expect(reader.assertEnd()).rejects.toMatchObject({
63+
constructor: NodeWorkspaceTransferInvalidError,
64+
reason: "trailing_bytes",
65+
});
5766
});
5867
});

0 commit comments

Comments
 (0)