Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 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
59 changes: 59 additions & 0 deletions src/lib/actions/sandbox/policy-channel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,7 @@ export async function addSandboxPolicy(
}

policies.applyPreset(sandboxName, answer);
syncSessionPolicyPresetsWithRegistry(sandboxName, answer, "add");
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

/**
Expand Down Expand Up @@ -210,6 +211,11 @@ async function applyExternalPreset(
const result = policies.applyPresetContent(sandboxName, loaded.presetName, loaded.content, {
custom: { sourcePath: path.resolve(filePath) },
});
if (result !== false) {
// Custom presets share the registry slot with built-ins (customPolicies
// in policy/index.ts:684), so they need the same session-sync.
syncSessionPolicyPresetsWithRegistry(sandboxName, loaded.presetName, "add");
}
return result !== false;
} catch (err: unknown) {
const message = err instanceof Error ? err.message : String(err);
Expand Down Expand Up @@ -721,6 +727,7 @@ function applyChannelPresetIfAvailable(sandboxName: string, channelName: string)
);
return false;
}
syncSessionPolicyPresetsWithRegistry(sandboxName, channelName, "add");
return true;
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
Expand All @@ -732,6 +739,55 @@ function applyChannelPresetIfAvailable(sandboxName: string, channelName: string)
}
}

// Mirror a registry-side preset add/remove into `session.policyPresets`.
// Without this, a later `rebuild` re-enters onboard resume, reads the
// stale session, and narrows the preset back away — see #3437 follow-up.
// Best-effort: registry has already succeeded; failure paths log and
// swallow so the caller's flow is never broken by a session I/O error.
function syncSessionPolicyPresetsWithRegistry(
sandboxName: string,
presetName: string,
action: "add" | "remove",
): void {
let session: ReturnType<typeof onboardSession.loadSession>;
try {
session = onboardSession.loadSession();
} catch {
return;
}
// No session = nothing to sync. Foreign sandbox = leave its intent alone.
if (!session) return;
if (session.sandboxName !== sandboxName) return;

const current = Array.isArray(session.policyPresets) ? session.policyPresets : [];
const has = current.includes(presetName);
// Skip the file write when the desired state already holds.
if (action === "add" && has) return;
if (action === "remove" && !has) return;

try {
onboardSession.updateSession((s) => {
const arr = Array.isArray(s.policyPresets) ? [...s.policyPresets] : [];
if (action === "add") {
if (!arr.includes(presetName)) arr.push(presetName);
} else {
const idx = arr.indexOf(presetName);
if (idx >= 0) arr.splice(idx, 1);
}
s.policyPresets = arr;
return s;
});
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
console.error(
` ${YW}⚠${R} Could not record '${presetName}' preset ${action} in onboard session: ${msg}`,
);
console.error(
` Registry is consistent; rerun '${CLI_NAME} ${sandboxName} policy-${action === "add" ? "add" : "remove"} ${presetName}' after rebuild if needed.`,
);
}
}

// Mirror of applyChannelPresetIfAvailable. When the channel-named built-in
// preset is currently applied to the sandbox, un-apply it so `policy-list`
// no longer reports it active and the L7 proxy stops allow-listing the
Expand All @@ -756,6 +812,8 @@ function removeChannelPresetIfPresent(sandboxName: string, channelName: string):
console.error(
` Run manually after rebuild with: ${CLI_NAME} ${sandboxName} policy-remove ${channelName}`,
);
} else {
syncSessionPolicyPresetsWithRegistry(sandboxName, channelName, "remove");
}
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
Expand Down Expand Up @@ -944,4 +1002,5 @@ export async function removeSandboxPolicy(
if (!policies.removePreset(sandboxName, answer)) {
process.exit(1);
}
syncSessionPolicyPresetsWithRegistry(sandboxName, answer, "remove");
}
214 changes: 213 additions & 1 deletion test/channels-add-preset.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,10 +49,20 @@ function buildPreamble({
presetNamesAvailable = ["telegram", "slack", "discord", "npm", "github"],
applyPresetResult = true,
sandboxAgent = "openclaw",
sessionSandboxName = "test-sb",
sessionPolicyPresets = ["npm", "pypi", "huggingface", "brew"] as string[] | null,
sessionLoadThrows = false,
sessionUpdateThrows = false,
sessionMissing = false,
}: {
presetNamesAvailable?: string[];
applyPresetResult?: boolean;
sandboxAgent?: string;
sessionSandboxName?: string | null;
sessionPolicyPresets?: string[] | null;
sessionLoadThrows?: boolean;
sessionUpdateThrows?: boolean;
sessionMissing?: boolean;
} = {}): string {
const j = (p: string) => JSON.stringify(path.join(repoRoot, "dist", "lib", p));
return String.raw`
Expand Down Expand Up @@ -102,8 +112,48 @@ policies.applyPreset = (sandboxName, presetName) => {
callOrder.push("applyPreset:" + presetName);
return ${JSON.stringify(applyPresetResult)};
};
policies.removePreset = (sandboxName, presetName) => {
callOrder.push("removePreset:" + presetName);
return true;
};
policies.getAppliedPresets = () => [];

// Stub onboardSession so the new policyPresets-sync helper has something
// to read/write. The test asserts on sessionUpdates to verify the
// helper kept session.policyPresets aligned with the registry.
const onboardSession = require(${j("state/onboard-session.js")});
const sessionUpdates = [];
const sessionLoadConfig = ${JSON.stringify({
sessionSandboxName,
sessionPolicyPresets,
sessionLoadThrows,
sessionMissing,
})};
const sessionUpdateThrows = ${JSON.stringify(sessionUpdateThrows)};
let sessionState = sessionLoadConfig.sessionMissing
? null
: {
sandboxName: sessionLoadConfig.sessionSandboxName,
policyPresets: Array.isArray(sessionLoadConfig.sessionPolicyPresets)
? [...sessionLoadConfig.sessionPolicyPresets]
: sessionLoadConfig.sessionPolicyPresets,
};
onboardSession.loadSession = () => {
if (sessionLoadConfig.sessionLoadThrows) throw new Error("simulated load failure");
return sessionState;
};
onboardSession.updateSession = (mutator) => {
if (sessionUpdateThrows) throw new Error("simulated save failure");
// Mirror the real updateSession contract: load → mutate → save.
if (!sessionState) sessionState = { sandboxName: null, policyPresets: null };
const next = mutator(sessionState) || sessionState;
sessionState = next;
sessionUpdates.push({
policyPresets: Array.isArray(next.policyPresets) ? [...next.policyPresets] : next.policyPresets,
});
return next;
};

// Tag the rebuild-prompt branch via stdout so we can compare ordering.
// In NEMOCLAW_NON_INTERACTIVE mode, promptAndRebuild logs "Change queued."
// and returns immediately without invoking rebuildSandbox.
Expand All @@ -116,7 +166,7 @@ console.log = (...args) => {

const channelModule = require(${j("actions/sandbox/policy-channel.js")});

module.exports = { channelModule, appliedCalls, callOrder, providerCalls, registryUpdates };
module.exports = { channelModule, appliedCalls, callOrder, providerCalls, registryUpdates, sessionUpdates, getSessionState: () => sessionState };
`;
}

Expand Down Expand Up @@ -316,3 +366,165 @@ const ctx = module.exports;
);
});
});

// Regression: `channels add` was updating the registry but NOT
// session.policyPresets. A later `rebuild` re-entered onboard in resume
// mode, read the stale session, and the policy-selection step narrowed
// the channel's preset back away. The new sandbox booted with the
// channel auto-launched but no matching network policy active, so the
// bridge's Slack/Telegram/Discord WebClient hit 403s and stayed wedged
// even after Step 5.5 of rebuild reapplied the preset from the backup
// manifest.
//
// These tests pin down the invariant: after a successful preset apply
// via channels-add, session.policyPresets must contain the channel
// name; after a successful preset remove via channels-remove, it must
// not. Edge cases (no session, foreign sandbox, save failure) must not
// abort the operation.
describe("channels add/remove keeps session.policyPresets in sync with registry", () => {
it("appends the channel preset to session.policyPresets after a successful add", () => {
const script = `${buildPreamble({
sessionSandboxName: "test-sb",
sessionPolicyPresets: ["npm", "pypi", "huggingface", "brew"],
})}
const ctx = module.exports;
(async () => {
try {
await ctx.channelModule.addSandboxChannel("test-sb", { channel: "slack" });
process.stdout.write("\\n__RESULT__" + JSON.stringify({
sessionUpdates: ctx.sessionUpdates,
finalSession: ctx.getSessionState(),
}) + "\\n");
} catch (err) {
process.stdout.write("\\n__RESULT__" + JSON.stringify({ error: err.message, stack: err.stack }) + "\\n");
}
})();
`;
const result = runScript(script);
assert.equal(result.status, 0, `script failed: ${result.stderr}\n${result.stdout}`);
const marker = result.stdout.lastIndexOf("__RESULT__");
const payload = JSON.parse(result.stdout.slice(marker + "__RESULT__".length).trim());
assert.ok(!payload.error, `unexpected error: ${payload.error}\n${payload.stack || ""}`);

// Exactly one update — the helper short-circuits when the desired
// membership already holds, so duplicate writes would be a bug.
assert.equal(
payload.sessionUpdates.length,
1,
`expected exactly one session update; got ${JSON.stringify(payload.sessionUpdates)}`,
);
assert.deepEqual(payload.sessionUpdates[0].policyPresets, [
"npm",
"pypi",
"huggingface",
"brew",
"slack",
]);
assert.deepEqual(payload.finalSession.policyPresets, [
"npm",
"pypi",
"huggingface",
"brew",
"slack",
]);
});

it("does not touch the session when it tracks a different sandbox", () => {
const script = `${buildPreamble({
sessionSandboxName: "other-sb",
sessionPolicyPresets: ["npm", "github"],
})}
const ctx = module.exports;
(async () => {
try {
await ctx.channelModule.addSandboxChannel("test-sb", { channel: "slack" });
process.stdout.write("\\n__RESULT__" + JSON.stringify({
sessionUpdates: ctx.sessionUpdates,
finalSession: ctx.getSessionState(),
appliedCalls: ctx.appliedCalls,
}) + "\\n");
} catch (err) {
process.stdout.write("\\n__RESULT__" + JSON.stringify({ error: err.message, stack: err.stack }) + "\\n");
}
})();
`;
const result = runScript(script);
assert.equal(result.status, 0, `script failed: ${result.stderr}\n${result.stdout}`);
const marker = result.stdout.lastIndexOf("__RESULT__");
const payload = JSON.parse(result.stdout.slice(marker + "__RESULT__".length).trim());
assert.ok(!payload.error, `unexpected error: ${payload.error}\n${payload.stack || ""}`);

// applyPreset still runs against the registry — the preset is the
// channel's egress contract and lives in registry, not session.
assert.deepEqual(payload.appliedCalls, [{ sandboxName: "test-sb", presetName: "slack" }]);
// But the foreign session's policyPresets must be left untouched —
// otherwise we corrupt the other sandbox's resume state.
assert.deepEqual(
payload.sessionUpdates,
[],
`session belonging to a different sandbox must not be mutated; got ${JSON.stringify(payload.sessionUpdates)}`,
);
assert.deepEqual(payload.finalSession.policyPresets, ["npm", "github"]);
});

it("succeeds even when no onboard session file exists", () => {
const script = `${buildPreamble({ sessionMissing: true })}
const ctx = module.exports;
(async () => {
try {
await ctx.channelModule.addSandboxChannel("test-sb", { channel: "slack" });
process.stdout.write("\\n__RESULT__" + JSON.stringify({
sessionUpdates: ctx.sessionUpdates,
appliedCalls: ctx.appliedCalls,
callOrder: ctx.callOrder,
}) + "\\n");
} catch (err) {
process.stdout.write("\\n__RESULT__" + JSON.stringify({ error: err.message, stack: err.stack }) + "\\n");
}
})();
`;
const result = runScript(script);
assert.equal(result.status, 0, `script failed: ${result.stderr}\n${result.stdout}`);
const marker = result.stdout.lastIndexOf("__RESULT__");
const payload = JSON.parse(result.stdout.slice(marker + "__RESULT__".length).trim());
assert.ok(!payload.error, `unexpected error: ${payload.error}\n${payload.stack || ""}`);

// Registry mutation still happens; only the session-sync side-effect
// is skipped (there is no intent record to keep aligned).
assert.deepEqual(payload.appliedCalls, [{ sandboxName: "test-sb", presetName: "slack" }]);
assert.deepEqual(payload.sessionUpdates, []);
assert.ok(payload.callOrder.includes("promptAndRebuild"));
});

it("does not abort channels-add when session save fails", () => {
const script = `${buildPreamble({
sessionSandboxName: "test-sb",
sessionPolicyPresets: ["npm", "pypi", "huggingface", "brew"],
sessionUpdateThrows: true,
})}
const ctx = module.exports;
(async () => {
try {
await ctx.channelModule.addSandboxChannel("test-sb", { channel: "slack" });
process.stdout.write("\\n__RESULT__" + JSON.stringify({
appliedCalls: ctx.appliedCalls,
callOrder: ctx.callOrder,
}) + "\\n");
} catch (err) {
process.stdout.write("\\n__RESULT__" + JSON.stringify({ error: err.message, stack: err.stack }) + "\\n");
}
})();
`;
const result = runScript(script);
assert.equal(result.status, 0, `script failed: ${result.stderr}\n${result.stdout}`);
const marker = result.stdout.lastIndexOf("__RESULT__");
const payload = JSON.parse(result.stdout.slice(marker + "__RESULT__".length).trim());
assert.ok(!payload.error, `unexpected error: ${payload.error}\n${payload.stack || ""}`);

// Even though session.updateSession threw, the channel add flow
// still completed: preset applied to registry, rebuild prompted.
// Session-sync is best-effort.
assert.deepEqual(payload.appliedCalls, [{ sandboxName: "test-sb", presetName: "slack" }]);
assert.ok(payload.callOrder.includes("promptAndRebuild"));
});
});
Loading
Loading