Skip to content

Commit 890a4b0

Browse files
committed
Control UI: add direct Custodian wizard cancel
1 parent ca4dc1b commit 890a4b0

17 files changed

Lines changed: 376 additions & 7 deletions

File tree

‎apps/shared/OpenClawKit/Sources/OpenClawProtocol/GatewayModels.swift‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9934,6 +9934,7 @@ public struct SystemAgentChatParams: Codable, Sendable {
99349934
public let sessionid: String
99359935
public let message: String?
99369936
public let wizardanswer: [String: AnyCodable]?
9937+
public let wizardcancel: [String: AnyCodable]?
99379938
public let welcomevariant: AnyCodable?
99389939
public let reset: Bool?
99399940
public let context: [String: AnyCodable]?
@@ -9943,6 +9944,7 @@ public struct SystemAgentChatParams: Codable, Sendable {
99439944
sessionid: String,
99449945
message: String? = nil,
99459946
wizardanswer: [String: AnyCodable]? = nil,
9947+
wizardcancel: [String: AnyCodable]? = nil,
99469948
welcomevariant: AnyCodable? = nil,
99479949
reset: Bool? = nil,
99489950
context: [String: AnyCodable]? = nil,
@@ -9951,6 +9953,7 @@ public struct SystemAgentChatParams: Codable, Sendable {
99519953
self.sessionid = sessionid
99529954
self.message = message
99539955
self.wizardanswer = wizardanswer
9956+
self.wizardcancel = wizardcancel
99549957
self.welcomevariant = welcomevariant
99559958
self.reset = reset
99569959
self.context = context
@@ -9961,6 +9964,7 @@ public struct SystemAgentChatParams: Codable, Sendable {
99619964
case sessionid = "sessionId"
99629965
case message
99639966
case wizardanswer = "wizardAnswer"
9967+
case wizardcancel = "wizardCancel"
99649968
case welcomevariant = "welcomeVariant"
99659969
case reset
99669970
case context

‎packages/gateway-protocol/src/schema/openclaw.test.ts‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,21 @@ describe("OpenClaw chat params protocol", () => {
3838
).toBe(false);
3939
});
4040

41+
it("accepts a typed wizard cancel and rejects unknown cancel fields", () => {
42+
expect(
43+
validateSystemAgentChatParams({
44+
sessionId: "session-1",
45+
wizardCancel: { stepId: "channel" },
46+
}),
47+
).toBe(true);
48+
expect(
49+
validateSystemAgentChatParams({
50+
sessionId: "session-1",
51+
wizardCancel: { stepId: "channel", reason: "user" },
52+
}),
53+
).toBe(false);
54+
});
55+
4156
it("rejects unsafe page ids and unknown context fields", () => {
4257
expect(validateSystemAgentChatParams({ ...base, context: { page: "channels?tab=all" } })).toBe(
4358
false,

‎packages/gateway-protocol/src/schema/openclaw.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,11 @@ import { closedObject } from "./closed-object.js";
55
import { NonEmptyString } from "./primitives.js";
66
import { WizardAnswerSchema, WizardStartResultSchema, WizardStepSchema } from "./wizard.js";
77

8+
export const SystemAgentWizardCancelSchema = closedObject({
9+
/** The visible step this action belongs to; stale controls must not affect a newer step. */
10+
stepId: NonEmptyString,
11+
});
12+
813
/**
914
* OpenClaw chat lets clients (macOS app onboarding, future UIs) hold the
1015
* setup/repair conversation over the gateway. The gateway live-tests the
@@ -17,6 +22,8 @@ export const SystemAgentChatParamsSchema = closedObject({
1722
message: Type.Optional(Type.String()),
1823
/** Typed answer from a client rendering the current `WizardStep`. */
1924
wizardAnswer: Type.Optional(WizardAnswerSchema),
25+
/** Direct client control for cancelling the currently rendered hosted wizard. */
26+
wizardCancel: Type.Optional(SystemAgentWizardCancelSchema),
2027
/** Seeds a purpose-specific first greeting for a fresh conversation. */
2128
welcomeVariant: Type.Optional(
2229
Type.Union([Type.Literal("onboarding"), Type.Literal("new-agent")]),
@@ -360,6 +367,7 @@ export const SystemAgentSetupAuthStartResultSchema = WizardStartResultSchema;
360367
// Wire types derive directly from local schema consts so public d.ts graphs never
361368
// pull in the ProtocolSchemas registry.
362369
export type SystemAgentChatParams = Static<typeof SystemAgentChatParamsSchema>;
370+
export type SystemAgentWizardCancel = Static<typeof SystemAgentWizardCancelSchema>;
363371
export type SystemAgentChatQuestion = Static<typeof SystemAgentChatQuestionSchema>;
364372
export type SystemAgentChatResult = Static<typeof SystemAgentChatResultSchema>;
365373
export type SystemAgentChatHistoryParams = Static<typeof SystemAgentChatHistoryParamsSchema>;

‎src/gateway/server-methods/shared-types.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import type {
22
SessionApprovalReplay,
33
SystemAgentChatQuestion,
4+
SystemAgentWizardCancel,
45
WizardAnswer,
56
} from "../../../packages/gateway-protocol/src/index.js";
67
// Shared server-method types define the client, context, response, and handler
@@ -155,6 +156,12 @@ type GatewaySystemAgentSession = {
155156
sensitive?: boolean;
156157
question?: SystemAgentChatQuestion;
157158
}>;
159+
cancelWizard: (cancel: SystemAgentWizardCancel) => Promise<{
160+
text: string;
161+
action: "none" | "exit" | "open-tui" | "open-setup";
162+
sensitive?: boolean;
163+
question?: SystemAgentChatQuestion;
164+
}>;
158165
seedHistory: (turns: readonly SystemAgentHistoryTurn[]) => void;
159166
historyLength: () => number;
160167
historySince: (index: number) => SystemAgentHistoryTurn[];

‎src/gateway/server-methods/system-agent-chat-turn.test.ts‎

Lines changed: 54 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,10 +8,12 @@ import {
88
function makeEngine() {
99
const handle = vi.fn();
1010
const answerWizard = vi.fn();
11+
const cancelWizard = vi.fn();
1112
return {
1213
answerWizard,
14+
cancelWizard,
1315
handle,
14-
engine: { answerWizard, handle },
16+
engine: { answerWizard, cancelWizard, handle },
1517
};
1618
}
1719

@@ -41,6 +43,38 @@ describe("system-agent chat input", () => {
4143
},
4244
error: "A wizard answer cannot reset its OpenClaw chat session.",
4345
},
46+
{
47+
input: {
48+
sessionId: "s1",
49+
message: "cancel",
50+
wizardCancel: { stepId: "channel" },
51+
},
52+
error: "Send wizardCancel without a message or wizardAnswer.",
53+
},
54+
{
55+
input: {
56+
sessionId: "s1",
57+
wizardAnswer: { stepId: "channel", value: "twitch" },
58+
wizardCancel: { stepId: "channel" },
59+
},
60+
error: "Send wizardCancel without a message or wizardAnswer.",
61+
},
62+
{
63+
input: {
64+
sessionId: "s1",
65+
wizardCancel: { stepId: "channel" },
66+
delegation: { agentId: "main", sessionKey: "agent:main:main" },
67+
},
68+
error: "Delegated OpenClaw sessions cannot cancel hosted wizards.",
69+
},
70+
{
71+
input: {
72+
sessionId: "s1",
73+
wizardCancel: { stepId: "channel" },
74+
reset: true,
75+
},
76+
error: "A wizard cancel cannot reset its OpenClaw chat session.",
77+
},
4478
])("rejects invalid mixed input: $error", ({ input, error }) => {
4579
expect(getSystemAgentChatInputError(input)).toBe(error);
4680
});
@@ -63,6 +97,25 @@ describe("system-agent chat input", () => {
6397
expect(handle).not.toHaveBeenCalled();
6498
});
6599

100+
it("routes a structured wizard cancel through the typed engine seam", async () => {
101+
const { engine, answerWizard, cancelWizard, handle } = makeEngine();
102+
cancelWizard.mockResolvedValue({ text: "Setup cancelled.", action: "none" });
103+
104+
await expect(
105+
runSystemAgentChatInput({
106+
engine,
107+
input: {
108+
sessionId: "s1",
109+
wizardCancel: { stepId: "channel" },
110+
},
111+
}),
112+
).resolves.toEqual({ text: "Setup cancelled.", action: "none" });
113+
114+
expect(cancelWizard).toHaveBeenCalledWith({ stepId: "channel" });
115+
expect(answerWizard).not.toHaveBeenCalled();
116+
expect(handle).not.toHaveBeenCalled();
117+
});
118+
66119
it("preserves the enriched wizard step in the gateway result", () => {
67120
expect(
68121
buildSystemAgentChatResult({

‎src/gateway/server-methods/system-agent-chat-turn.ts‎

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,10 @@ import type {
55
import type { SystemAgentChatEngine } from "../../system-agent/chat-engine.js";
66

77
type SystemAgentChatReply = Awaited<ReturnType<SystemAgentChatEngine["handle"]>>;
8-
type SystemAgentChatEngineInput = Pick<SystemAgentChatEngine, "answerWizard" | "handle">;
8+
type SystemAgentChatEngineInput = Pick<
9+
SystemAgentChatEngine,
10+
"answerWizard" | "cancelWizard" | "handle"
11+
>;
912

1013
export function getSystemAgentChatInputError(params: SystemAgentChatParams): string | undefined {
1114
if (params.message !== undefined && params.wizardAnswer !== undefined) {
@@ -17,6 +20,18 @@ export function getSystemAgentChatInputError(params: SystemAgentChatParams): str
1720
if (params.wizardAnswer !== undefined && params.reset === true) {
1821
return "A wizard answer cannot reset its OpenClaw chat session.";
1922
}
23+
if (
24+
params.wizardCancel !== undefined &&
25+
(params.message !== undefined || params.wizardAnswer !== undefined)
26+
) {
27+
return "Send wizardCancel without a message or wizardAnswer.";
28+
}
29+
if (params.wizardCancel !== undefined && params.delegation !== undefined) {
30+
return "Delegated OpenClaw sessions cannot cancel hosted wizards.";
31+
}
32+
if (params.wizardCancel !== undefined && params.reset === true) {
33+
return "A wizard cancel cannot reset its OpenClaw chat session.";
34+
}
2035
return undefined;
2136
}
2237

@@ -27,6 +42,9 @@ export async function runSystemAgentChatInput(params: {
2742
if (params.input.wizardAnswer !== undefined) {
2843
return await params.engine.answerWizard(params.input.wizardAnswer);
2944
}
45+
if (params.input.wizardCancel !== undefined) {
46+
return await params.engine.cancelWizard(params.input.wizardCancel);
47+
}
3048
if (params.input.message === undefined) {
3149
return undefined;
3250
}

‎src/gateway/server-methods/system-agent-session-ownership.test.ts‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ vi.mock("../../system-agent/greeting.js", () => ({
3737

3838
type FakeEngine = {
3939
answerWizard: ReturnType<typeof vi.fn>;
40+
cancelWizard: ReturnType<typeof vi.fn>;
4041
handle: ReturnType<typeof vi.fn>;
4142
seedHistory: ReturnType<typeof vi.fn>;
4243
historyLength: ReturnType<typeof vi.fn>;
@@ -53,6 +54,9 @@ function makeEngine(): FakeEngine {
5354
answerWizard: vi.fn(async () => {
5455
throw new SystemAgentWizardAnswerError("No hosted wizard is awaiting an answer.");
5556
}),
57+
cancelWizard: vi.fn(async () => {
58+
throw new SystemAgentWizardAnswerError("No hosted wizard is awaiting cancellation.");
59+
}),
5660
handle: vi.fn(async () => ({ text: "did the thing", action: "none" })),
5761
seedHistory: vi.fn(),
5862
historyLength: vi.fn(() => 0),
@@ -181,6 +185,11 @@ describe("openclaw.chat session ownership", () => {
181185
attacker,
182186
);
183187
const reset = await callChat(context, { sessionId: "owned-session", reset: true }, attacker);
188+
const cancel = await callChat(
189+
context,
190+
{ sessionId: "owned-session", wizardCancel: { stepId: "channel" } },
191+
attacker,
192+
);
184193

185194
expect(turn).toMatchObject({
186195
ok: false,
@@ -197,7 +206,15 @@ describe("openclaw.chat session ownership", () => {
197206
payload: undefined,
198207
error: { code: "INVALID_REQUEST" },
199208
});
209+
expect(cancel).toMatchObject({
210+
ok: false,
211+
payload: undefined,
212+
error: { code: "INVALID_REQUEST" },
213+
});
200214
expect(handle).not.toHaveBeenCalled();
215+
expect(
216+
expectDefined(createdEngines[0], "created system-agent engine").cancelWizard,
217+
).not.toHaveBeenCalled();
201218
expect(
202219
expectDefined(createdEngines[0], "created system-agent engine").dispose,
203220
).not.toHaveBeenCalled();
@@ -370,6 +387,36 @@ describe("openclaw.chat session responses", () => {
370387
expect(inferenceFallbackMocks.verifySystemAgentInferenceWithFallback).not.toHaveBeenCalled();
371388
});
372389

390+
it("rejects a structured cancel without an active chat session", async () => {
391+
const call = await callChat(makeContext(new Map()), {
392+
sessionId: "missing",
393+
wizardCancel: { stepId: "channel" },
394+
});
395+
396+
expect(call).toMatchObject({
397+
ok: false,
398+
error: {
399+
code: "INVALID_REQUEST",
400+
details: { code: "system_agent_session_invalidated" },
401+
},
402+
});
403+
expect(setupInferenceMocks.verifySetupInference).not.toHaveBeenCalled();
404+
});
405+
406+
it("routes a structured cancel through its bound session", async () => {
407+
const engine = makeEngine();
408+
engine.cancelWizard.mockResolvedValue({ text: "Setup cancelled.", action: "none" });
409+
const sessions = new Map<string, SystemAgentChatSession>([["s1", seededSession({ engine })]]);
410+
411+
const call = await callChat(makeContext(sessions), {
412+
sessionId: "s1",
413+
wizardCancel: { stepId: "channel" },
414+
});
415+
416+
expect(engine.cancelWizard).toHaveBeenCalledWith({ stepId: "channel" });
417+
expect(call.payload).toMatchObject({ reply: "Setup cancelled.", action: "none" });
418+
});
419+
373420
it("rejects a structured answer when the active session has no hosted wizard", async () => {
374421
const engine = makeEngine();
375422
const sessions = new Map<string, SystemAgentChatSession>([["s1", seededSession({ engine })]]);

‎src/gateway/server-methods/system-agent.ts‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -547,13 +547,15 @@ export const systemAgentHandlers: GatewayRequestHandlers = {
547547
await existing?.engine.dispose();
548548
}
549549
let session = sessions.get(sessionId);
550-
if (params.wizardAnswer !== undefined && !session) {
550+
if ((params.wizardAnswer !== undefined || params.wizardCancel !== undefined) && !session) {
551551
respond(
552552
false,
553553
undefined,
554554
errorShape(
555555
ErrorCodes.INVALID_REQUEST,
556-
"No active OpenClaw chat session is awaiting that wizard answer.",
556+
params.wizardCancel !== undefined
557+
? "No active OpenClaw chat session is awaiting that wizard cancel."
558+
: "No active OpenClaw chat session is awaiting that wizard answer.",
557559
{ details: buildSystemAgentSessionInvalidatedErrorDetails() },
558560
),
559561
);
@@ -562,6 +564,7 @@ export const systemAgentHandlers: GatewayRequestHandlers = {
562564
let greetingAuditSequence: number | undefined;
563565
const welcomeOnly =
564566
params.wizardAnswer === undefined &&
567+
params.wizardCancel === undefined &&
565568
(params.message === undefined || !params.message.trim());
566569
if (!session) {
567570
const { verifySystemAgentInferenceWithFallback } =
@@ -665,6 +668,7 @@ export const systemAgentHandlers: GatewayRequestHandlers = {
665668
// Inline check (not `welcomeOnly`) so TS narrows params.message below.
666669
if (
667670
params.wizardAnswer === undefined &&
671+
params.wizardCancel === undefined &&
668672
(params.message === undefined || !params.message.trim())
669673
) {
670674
respond(

‎src/system-agent/chat-engine.test.ts‎

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3492,6 +3492,50 @@ describe("OpenClaw chat wizard step payload", () => {
34923492
expect(engine.historySince(0)).toContainEqual({ role: "user", text: "Beta" });
34933493
});
34943494

3495+
it("cancels the current hosted wizard through a typed direct action", async () => {
3496+
useTempStateDir();
3497+
const engine = new SystemAgentChatEngine({
3498+
surface: "gateway",
3499+
runAgentTurn: async () => null,
3500+
planWithAssistant: async () => null,
3501+
deps: { loadOverview: fakeOverviewLoader() },
3502+
runChannelSetupWizard: async (_channel: string, prompter: WizardPrompter) => {
3503+
await prompter.text({ message: "Bot token" });
3504+
},
3505+
});
3506+
3507+
const prompt = await engine.handle("connect telegram");
3508+
const stepId = expectDefined(prompt.step?.id, "expected an active wizard step");
3509+
const cancelled = await engine.cancelWizard({ stepId });
3510+
3511+
expect(cancelled.text).toContain("cancelled");
3512+
expect(cancelled.step).toBeUndefined();
3513+
expect(cancelled.wizardInputPending).toBeUndefined();
3514+
expect(engine.historySince(0)).toContainEqual({ role: "user", text: "Cancel" });
3515+
});
3516+
3517+
it("rejects a stale typed cancel without changing the active step", async () => {
3518+
useTempStateDir();
3519+
const engine = new SystemAgentChatEngine({
3520+
surface: "gateway",
3521+
runAgentTurn: async () => null,
3522+
planWithAssistant: async () => null,
3523+
deps: { loadOverview: fakeOverviewLoader() },
3524+
runChannelSetupWizard: async (_channel: string, prompter: WizardPrompter) => {
3525+
await prompter.text({ message: "Bot token" });
3526+
},
3527+
});
3528+
3529+
const prompt = await engine.handle("connect telegram");
3530+
const stepId = expectDefined(prompt.step?.id, "expected an active wizard step");
3531+
await expect(engine.cancelWizard({ stepId: "stale-step" })).rejects.toBeInstanceOf(
3532+
SystemAgentWizardAnswerError,
3533+
);
3534+
const cancelled = await engine.cancelWizard({ stepId });
3535+
3536+
expect(cancelled.text).toContain("cancelled");
3537+
});
3538+
34953539
it("rejects a stale structured answer without changing the active step", async () => {
34963540
useTempStateDir();
34973541
const engine = new SystemAgentChatEngine({

0 commit comments

Comments
 (0)