Skip to content

Commit fc8ee40

Browse files
steipeteampagent
andauthored
1 parent 45cd2ba commit fc8ee40

8 files changed

Lines changed: 168 additions & 88 deletions

File tree

‎src/commands/channels/add-wizard.ts‎

Lines changed: 20 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,12 @@ export async function runChannelsAddWizardFlow(params: ChannelsAddWizardFlowPara
9090
import("../agents.config.js"),
9191
loadOnboardChannels(),
9292
]);
93-
const postWriteHooks = onboardChannels.createChannelOnboardingPostWriteHookCollector();
93+
const channelSetup = onboardChannels.createChannelSetupTransaction({
94+
runtime,
95+
...(params.beforePersistentEffect
96+
? { beforePersistentEffect: params.beforePersistentEffect }
97+
: {}),
98+
});
9499
let selection: ChannelChoice[] = [];
95100
const accountIds: Partial<Record<ChannelChoice, string>> = {};
96101
const resolvedPlugins = new Map<ChannelChoice, ChannelSetupPlugin>();
@@ -105,9 +110,7 @@ export async function runChannelsAddWizardFlow(params: ChannelsAddWizardFlowPara
105110
? { beforePersistentEffect: params.beforePersistentEffect }
106111
: {}),
107112
...(params.deferDeviceLinkToClient ? { deferDeviceLinkToClient: true } : {}),
108-
onPostWriteHook: (hook) => {
109-
postWriteHooks.collect(hook);
110-
},
113+
onPostWriteHook: (hook) => channelSetup.onPostWriteHook(hook),
111114
promptAccountIds: true,
112115
deferStatusUntilSelection: true,
113116
skipStatusNote: true,
@@ -122,28 +125,21 @@ export async function runChannelsAddWizardFlow(params: ChannelsAddWizardFlowPara
122125
},
123126
});
124127
const commitWizardConfig = async (config: OpenClawConfig) => {
125-
await params.beforePersistentEffect?.();
126-
const committed = await commitConfigWithPendingPluginInstalls({
127-
nextConfig: config,
128-
...(baseHash !== undefined ? { baseHash } : {}),
129-
});
130-
if (committed.movedInstallRecords) {
131-
await refreshPluginRegistryAfterConfigMutation({
132-
config: committed.config,
133-
reason: "source-changed",
134-
installRecords: committed.installRecords,
135-
logger: { warn: (message) => runtime.log(message) },
128+
return await channelSetup.commit(config, async (configToCommit) => {
129+
const committed = await commitConfigWithPendingPluginInstalls({
130+
nextConfig: configToCommit,
131+
...(baseHash !== undefined ? { baseHash } : {}),
136132
});
137-
}
138-
await onboardChannels.runCollectedChannelOnboardingPostWriteHooks({
139-
hooks: postWriteHooks.drain(),
140-
cfg: committed.config,
141-
runtime,
142-
...(params.beforePersistentEffect
143-
? { beforePersistentEffect: params.beforePersistentEffect }
144-
: {}),
133+
if (committed.movedInstallRecords) {
134+
await refreshPluginRegistryAfterConfigMutation({
135+
config: committed.config,
136+
reason: "source-changed",
137+
installRecords: committed.installRecords,
138+
logger: { warn: (message) => runtime.log(message) },
139+
});
140+
}
141+
return committed.config;
145142
});
146-
return committed.config;
147143
};
148144
if (selection.length === 0) {
149145
if (nextConfig !== cfg) {

‎src/commands/onboard-channels.post-write.test.ts‎

Lines changed: 29 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,7 @@ import { describe, expect, it, vi } from "vitest";
33
import type { OpenClawConfig } from "../config/config.js";
44
import {
55
createChannelOnboardingPostWriteHook,
6-
createChannelOnboardingPostWriteHookCollector,
7-
runCollectedChannelOnboardingPostWriteHooks,
6+
createChannelSetupTransaction,
87
} from "./onboard-channels.js";
98
import { createExitThrowingRuntime } from "./test-wizard-helpers.js";
109

@@ -20,8 +19,8 @@ describe("setupChannels post-write hooks", () => {
2019
const adapter = {
2120
afterConfigWritten,
2221
};
23-
const collector = createChannelOnboardingPostWriteHookCollector();
2422
const runtime = createExitThrowingRuntime();
23+
const transaction = createChannelSetupTransaction({ runtime });
2524
const hook = createChannelOnboardingPostWriteHook({
2625
accountId: "acct-1",
2726
adapter,
@@ -32,16 +31,13 @@ describe("setupChannels post-write hooks", () => {
3231
if (!hook) {
3332
throw new Error("expected post-write hook");
3433
}
35-
collector.collect(hook);
34+
transaction.onPostWriteHook(hook);
3635

3736
expect(afterConfigWritten).not.toHaveBeenCalled();
3837

39-
await runCollectedChannelOnboardingPostWriteHooks({
40-
hooks: collector.drain(),
41-
cfg,
42-
runtime,
43-
});
38+
const committed = await transaction.commit(cfg, async () => cfg);
4439

40+
expect(committed).toBe(cfg);
4541
expect(afterConfigWritten).toHaveBeenCalledWith({
4642
previousCfg,
4743
cfg,
@@ -52,24 +48,35 @@ describe("setupChannels post-write hooks", () => {
5248

5349
it("logs onboarding post-write hook failures without aborting", async () => {
5450
const runtime = createExitThrowingRuntime();
55-
56-
await runCollectedChannelOnboardingPostWriteHooks({
57-
hooks: [
58-
{
59-
channel: "telegram",
60-
accountId: "acct-1",
61-
run: async () => {
62-
throw new Error("hook failed");
63-
},
64-
},
65-
],
66-
cfg: {} as OpenClawConfig,
67-
runtime,
51+
const transaction = createChannelSetupTransaction({ runtime });
52+
transaction.onPostWriteHook({
53+
channel: "telegram",
54+
accountId: "acct-1",
55+
run: async () => {
56+
throw new Error("hook failed");
57+
},
6858
});
6959

60+
await transaction.commit({} as OpenClawConfig, async (config) => config);
61+
7062
expect(runtime.error).toHaveBeenCalledWith(
7163
'Channel telegram post-setup warning for "acct-1": hook failed',
7264
);
7365
expect(runtime.exit).not.toHaveBeenCalled();
7466
});
67+
68+
it("does not run hooks when config persistence fails", async () => {
69+
const runtime = createExitThrowingRuntime();
70+
const hook = vi.fn();
71+
const transaction = createChannelSetupTransaction({ runtime });
72+
transaction.onPostWriteHook({ channel: "matrix", accountId: "ops", run: hook });
73+
74+
await expect(
75+
transaction.commit({} as OpenClawConfig, async () => {
76+
throw new Error("write failed");
77+
}),
78+
).rejects.toThrow("write failed");
79+
80+
expect(hook).not.toHaveBeenCalled();
81+
});
7582
});

‎src/commands/onboard-channels.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
/** Re-export seam for channel onboarding flow helpers. */
22
export {
33
createChannelOnboardingPostWriteHook,
4-
createChannelOnboardingPostWriteHookCollector,
4+
createChannelSetupTransaction,
55
runCollectedChannelOnboardingPostWriteHooks,
66
setupChannels,
77
} from "../flows/channel-setup.js";

‎src/flows/channel-setup.ts‎

Lines changed: 25 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -55,17 +55,36 @@ import {
5555
resolveQuickstartDefault,
5656
} from "./channel-setup.status.js";
5757

58-
export function createChannelOnboardingPostWriteHookCollector() {
58+
export function createChannelSetupTransaction(params: {
59+
runtime: RuntimeEnv;
60+
beforePersistentEffect?: () => Promise<void>;
61+
}) {
5962
const hooks = new Map<string, ChannelOnboardingPostWriteHook>();
63+
const runPostWriteHooks = async (cfg: OpenClawConfig) => {
64+
await runCollectedChannelOnboardingPostWriteHooks({
65+
hooks: [...hooks.values()],
66+
cfg,
67+
runtime: params.runtime,
68+
...(params.beforePersistentEffect
69+
? { beforePersistentEffect: params.beforePersistentEffect }
70+
: {}),
71+
});
72+
hooks.clear();
73+
};
6074
return {
61-
collect(hook: ChannelOnboardingPostWriteHook) {
75+
onPostWriteHook(hook: ChannelOnboardingPostWriteHook) {
6276
hooks.set(`${hook.channel}:${hook.accountId}`, hook);
6377
},
64-
drain(): ChannelOnboardingPostWriteHook[] {
65-
const next = [...hooks.values()];
66-
hooks.clear();
67-
return next;
78+
async commit(
79+
nextConfig: OpenClawConfig,
80+
write: (config: OpenClawConfig) => Promise<OpenClawConfig>,
81+
): Promise<OpenClawConfig> {
82+
await params.beforePersistentEffect?.();
83+
const committedConfig = await write(nextConfig);
84+
await runPostWriteHooks(committedConfig);
85+
return committedConfig;
6886
},
87+
runPostWriteHooks,
6988
};
7089
}
7190

‎src/system-agent/hosted-setup.runtime.test.ts‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -668,7 +668,6 @@ describe("SystemAgentChatEngine runtime", () => {
668668

669669
expect(stopped.text).toContain("Telegram setup stopped");
670670
expect(mocks.writeWizardConfigFile).toHaveBeenCalledOnce();
671-
expect(mocks.runCollectedChannelOnboardingPostWriteHooks).toHaveBeenCalledOnce();
672671
expect(hook.run).not.toHaveBeenCalled();
673672
});
674673
});
@@ -710,11 +709,12 @@ describe("hosted channel post-write hooks", () => {
710709
{ channels: { matrix: { enabled: true } } },
711710
{ allowConfigSizeDrop: false, baseHash: "hook-base-hash" },
712711
);
713-
expect(mocks.runCollectedChannelOnboardingPostWriteHooks).toHaveBeenCalledWith({
714-
hooks: [hook],
712+
expect(hook.run).toHaveBeenCalledWith({
715713
cfg: committed,
716714
runtime: expect.any(Object),
717-
beforePersistentEffect: expect.any(Function),
718715
});
716+
expect(mocks.writeWizardConfigFile.mock.invocationCallOrder[0]).toBeLessThan(
717+
hook.run.mock.invocationCallOrder[0] ?? Number.POSITIVE_INFINITY,
718+
);
719719
});
720720
});

‎src/system-agent/hosted-setup.runtime.ts‎

Lines changed: 24 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -86,38 +86,36 @@ export async function runHostedChannelSetup(
8686
beforePersistentApply: (runtime: RuntimeEnv) => Promise<void>,
8787
runtime?: RuntimeEnv,
8888
): Promise<HostedSetupCompletion> {
89-
const {
90-
createChannelOnboardingPostWriteHookCollector,
91-
runCollectedChannelOnboardingPostWriteHooks,
92-
setupChannels,
93-
} = await import("../commands/onboard-channels.js");
94-
const postWriteHooks = createChannelOnboardingPostWriteHookCollector();
89+
const { createChannelSetupTransaction, setupChannels } =
90+
await import("../commands/onboard-channels.js");
91+
let channelSetup: ReturnType<typeof createChannelSetupTransaction>;
9592
return await runHostedSetup({
9693
label: "Channel setup",
9794
runtime,
9895
beforePersistentApply,
99-
run: async ({ baseConfig, runtime: setupRuntime }) => ({
100-
nextConfig: await setupChannels(baseConfig, setupRuntime, prompter, {
101-
initialSelection: [channel],
102-
forceAllowFromChannels: [channel],
103-
allowIMessageInstall: true,
104-
allowSignalInstall: true,
105-
deferStatusUntilSelection: true,
106-
quickstartDefaults: true,
107-
skipDmPolicyPrompt: true,
108-
skipConfirm: true,
96+
run: async ({ baseConfig, runtime: setupRuntime }) => {
97+
channelSetup = createChannelSetupTransaction({
98+
runtime: setupRuntime,
10999
beforePersistentEffect: async () => await beforePersistentApply(setupRuntime),
110-
onPostWriteHook: (hook) => postWriteHooks.collect(hook),
111-
}),
112-
afterWrite: async (committedConfig) => {
113-
await runCollectedChannelOnboardingPostWriteHooks({
114-
hooks: postWriteHooks.drain(),
115-
cfg: committedConfig,
116-
runtime: setupRuntime,
100+
});
101+
return {
102+
nextConfig: await setupChannels(baseConfig, setupRuntime, prompter, {
103+
initialSelection: [channel],
104+
forceAllowFromChannels: [channel],
105+
allowIMessageInstall: true,
106+
allowSignalInstall: true,
107+
deferStatusUntilSelection: true,
108+
quickstartDefaults: true,
109+
skipDmPolicyPrompt: true,
110+
skipConfirm: true,
117111
beforePersistentEffect: async () => await beforePersistentApply(setupRuntime),
118-
});
119-
},
120-
}),
112+
onPostWriteHook: (hook) => channelSetup.onPostWriteHook(hook),
113+
}),
114+
afterWrite: async (committedConfig) => {
115+
await channelSetup.runPostWriteHooks(committedConfig);
116+
},
117+
};
118+
},
121119
});
122120
}
123121

‎src/wizard/setup.test.ts‎

Lines changed: 52 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -343,7 +343,8 @@ function expectMockCallArgNotNull(
343343
}
344344
}
345345

346-
vi.mock("../commands/onboard-channels.js", () => ({
346+
vi.mock("../commands/onboard-channels.js", async (importOriginal) => ({
347+
...(await importOriginal<typeof import("../commands/onboard-channels.js")>()),
347348
setupChannels,
348349
}));
349350

@@ -2294,6 +2295,56 @@ describe("runSetupWizard", () => {
22942295
);
22952296
});
22962297

2298+
it("persists classic channel setup before hooks and Gateway finalization", async () => {
2299+
const beforeConfig = { agents: { defaults: { workspace: "/tmp/workspace" } } };
2300+
const configured = {
2301+
...beforeConfig,
2302+
channels: { matrix: { accounts: { ops: { enabled: true } } } },
2303+
} satisfies OpenClawConfig;
2304+
const hook = vi.fn();
2305+
const isConfiguredWrite = (value: OpenClawConfig) =>
2306+
value.channels?.matrix?.accounts?.ops?.enabled === true;
2307+
setupChannels.mockImplementationOnce(async (_cfg, _runtime, _prompter, options) => {
2308+
const setupOptions = options as {
2309+
onPostWriteHook?: (value: {
2310+
channel: "matrix";
2311+
accountId: string;
2312+
run: typeof hook;
2313+
}) => void;
2314+
};
2315+
setupOptions.onPostWriteHook?.({ channel: "matrix", accountId: "ops", run: hook });
2316+
return configured;
2317+
});
2318+
readConfigFileSnapshot.mockResolvedValueOnce(configSnapshot(beforeConfig));
2319+
2320+
await runSetupWizard(
2321+
{
2322+
acceptRisk: true,
2323+
flow: "quickstart",
2324+
authChoice: "skip",
2325+
installDaemon: false,
2326+
skipSkills: true,
2327+
skipSearch: true,
2328+
skipHealth: true,
2329+
skipUi: true,
2330+
},
2331+
createRuntime(),
2332+
buildWizardPrompter({}),
2333+
);
2334+
2335+
const configuredWriteIndex = replaceConfigFile.mock.calls.findIndex(([params]) =>
2336+
isConfiguredWrite(params.nextConfig),
2337+
);
2338+
expect(configuredWriteIndex).toBeGreaterThanOrEqual(0);
2339+
expect(replaceConfigFile.mock.invocationCallOrder[configuredWriteIndex]).toBeLessThan(
2340+
hook.mock.invocationCallOrder[0] ?? Number.POSITIVE_INFINITY,
2341+
);
2342+
expect(hook).toHaveBeenCalledWith({ cfg: configured, runtime: expect.any(Object) });
2343+
expect(hook.mock.invocationCallOrder[0]).toBeLessThan(
2344+
finalizeSetupWizard.mock.invocationCallOrder[0] ?? Number.POSITIVE_INFINITY,
2345+
);
2346+
});
2347+
22972348
it("disables back navigation before side-effecting channel setup", async () => {
22982349
setupChannels.mockImplementationOnce(async (cfg, _runtime, channelPrompter) => {
22992350
if (!channelPrompter) {

‎src/wizard/setup.ts‎

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -601,7 +601,9 @@ async function runSetupWizardOnce(
601601
await prompter.note(t("wizard.setup.skipChannels"), t("wizard.setup.channelsTitle"));
602602
} else {
603603
const { listChannelPlugins } = await import("../channels/plugins/index.js");
604-
const { setupChannels } = await import("../commands/onboard-channels.js");
604+
const { createChannelSetupTransaction, setupChannels } =
605+
await import("../commands/onboard-channels.js");
606+
const channelSetup = createChannelSetupTransaction({ runtime });
605607
const quickstartAllowFromChannels =
606608
flow === "quickstart"
607609
? listChannelPlugins()
@@ -617,12 +619,19 @@ async function runSetupWizardOnce(
617619
skipConfirm: flow === "quickstart",
618620
quickstartDefaults: flow === "quickstart",
619621
secretInputMode: opts.secretInputMode,
622+
onPostWriteHook: (hook) => channelSetup.onPostWriteHook(hook),
620623
});
624+
nextConfig = await channelSetup.commit(
625+
nextConfig,
626+
async (config) => await writeSetupConfigFile(config, { allowConfigSizeDrop: false }),
627+
);
621628
}
622629

623-
nextConfig = await writeSetupConfigFile(nextConfig, {
624-
allowConfigSizeDrop: false,
625-
});
630+
if (opts.skipChannels) {
631+
nextConfig = await writeSetupConfigFile(nextConfig, {
632+
allowConfigSizeDrop: false,
633+
});
634+
}
626635
let onboardingTarget = resolveOnboardingAgentTarget(nextConfig);
627636
const { logConfigUpdated } = await loadConfigLoggingModule();
628637
logConfigUpdated(runtime);

0 commit comments

Comments
 (0)