Skip to content

Commit 9aceb16

Browse files
authored
fix(system-agent): emit the wizard cancel hint once per message (#113731)
* fix(system-agent): emit the wizard cancel hint once per message * refactor(wizard): own input wait semantics * refactor(wizard): declare step input requirements * refactor(wizard): infer input requirement by step type * docs: note wizard cancel hint fix * chore: follow release-owned changelog policy
1 parent 586e1fe commit 9aceb16

5 files changed

Lines changed: 127 additions & 50 deletions

File tree

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

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -326,6 +326,9 @@ afterEach(() => {
326326
}
327327
});
328328

329+
const CANCEL_HINT = "Say `cancel` to stop this setup.";
330+
const countCancelHints = (text: string) => text.split(CANCEL_HINT).length - 1;
331+
329332
describe("SystemAgentChatEngine", () => {
330333
it("lets only an operator arm delegated persistent writes", async () => {
331334
useTempStateDir();
@@ -2048,10 +2051,61 @@ describe("SystemAgentChatEngine", () => {
20482051
const invalid = await engine.handle("banana");
20492052
expect(invalid.text).toContain("Enter port 18789");
20502053
expect(invalid.text).toContain("Port");
2054+
expect(countCancelHints(invalid.text)).toBe(1);
2055+
expect(invalid.text.endsWith(CANCEL_HINT)).toBe(true);
20512056
const done = await engine.handle("18789");
20522057
expect(done.text).toContain("telegram is configured");
20532058
});
20542059

2060+
it("hints cancel once per message, only while a step awaits an answer", async () => {
2061+
useTempStateDir();
2062+
const engine = new SystemAgentChatEngine({
2063+
runAgentTurn: async () => null,
2064+
planWithAssistant: async () => null,
2065+
deps: { loadOverview: fakeOverviewLoader() },
2066+
runChannelSetupWizard: async (_channel: string, prompter: WizardPrompter) => {
2067+
await prompter.note("Open the linked-devices screen.", "Step 1");
2068+
await prompter.note("Scan the code shown next.", "Step 2");
2069+
await prompter.note("Keep the phone online.", "Step 3");
2070+
await prompter.text({ message: "Phone number" });
2071+
await prompter.note("Linked.", "Step 4");
2072+
},
2073+
});
2074+
2075+
// Three auto-answered notes concatenate into the prompt's message; the hint
2076+
// is the message's, not each step's.
2077+
const prompt = await engine.handle("connect telegram");
2078+
expect(prompt.text).toContain("Step 3");
2079+
expect(prompt.text).toContain("Phone number");
2080+
expect(countCancelHints(prompt.text)).toBe(1);
2081+
expect(prompt.text.endsWith(CANCEL_HINT)).toBe(true);
2082+
expect(engine.historySince(0).at(-1)).toEqual({ role: "assistant", text: prompt.text });
2083+
2084+
const done = await engine.handle("+15551230000");
2085+
expect(done.text).toContain("Step 4");
2086+
expect(done.text).toContain("telegram is configured");
2087+
expect(countCancelHints(done.text)).toBe(0);
2088+
});
2089+
2090+
it("drops the cancel hint from the cancellation message", async () => {
2091+
useTempStateDir();
2092+
const engine = new SystemAgentChatEngine({
2093+
runAgentTurn: async () => null,
2094+
planWithAssistant: async () => null,
2095+
deps: { loadOverview: fakeOverviewLoader() },
2096+
runChannelSetupWizard: async (_channel: string, prompter: WizardPrompter) => {
2097+
await prompter.text({ message: "Bot token" });
2098+
},
2099+
});
2100+
2101+
const prompt = await engine.handle("connect discord");
2102+
expect(countCancelHints(prompt.text)).toBe(1);
2103+
2104+
const cancelled = await engine.handle("cancel");
2105+
expect(cancelled.text).toContain("cancelled");
2106+
expect(countCancelHints(cancelled.text)).toBe(0);
2107+
});
2108+
20552109
it("cancels a hosted wizard mid-flight", async () => {
20562110
useTempStateDir();
20572111
const engine = new SystemAgentChatEngine({

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

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ import { isSensitiveConfigPath } from "../config/sensitive-paths.js";
44
import { formatErrorMessage } from "../infra/errors.js";
55
import { createSubsystemLogger } from "../logging/subsystem.js";
66
import type { RuntimeEnv } from "../runtime.js";
7-
import { WizardSession, type WizardStep } from "../wizard/session.js";
7+
import { WizardSession, wizardStepAwaitsInput, type WizardStep } from "../wizard/session.js";
88
import type {
99
MemoryImportProviderOutcome,
1010
SetupMemoryImportOutcome,
@@ -535,10 +535,11 @@ function renderWizardStep(step: WizardStep): string {
535535
default:
536536
break;
537537
}
538-
lines.push("Say `cancel` to stop this setup.");
539538
return lines.filter(Boolean).join("\n");
540539
}
541540

541+
const WIZARD_CANCEL_HINT = "Say `cancel` to stop this setup.";
542+
542543
/** Map a chat reply to a wizard step answer; null means "could not parse". */
543544
function parseWizardAnswer(step: WizardStep, text: string): { value: unknown } | null {
544545
const trimmed = text.trim();
@@ -743,7 +744,15 @@ export class SystemAgentChatEngine {
743744
// Snapshot before resolving: wizard answers to sensitive steps (tokens,
744745
// passwords) must never enter the AI-visible history.
745746
const sensitiveTurn = this.wizardBridge?.step?.sensitive === true;
746-
const reply = await this.resolveTurn(text, options);
747+
const resolved = await this.resolveTurn(text, options);
748+
// The hint belongs to the outgoing message, not to each rendered step: one
749+
// turn can concatenate several auto-answered notes, and a wizard that just
750+
// ended must not offer a cancel that can no longer happen.
751+
const awaitedStep = this.wizardBridge?.step;
752+
const reply: SystemAgentChatReply =
753+
resolved.text && awaitedStep && wizardStepAwaitsInput(awaitedStep)
754+
? { ...resolved, text: `${resolved.text}\n${WIZARD_CANCEL_HINT}` }
755+
: resolved;
747756
this.history.push({
748757
role: "user",
749758
text: sensitiveTurn ? "<redacted secret>" : redactSensitiveCommandText(text),

‎src/wizard/session.test.ts‎

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
// Wizard session tests cover session creation and state transitions.
2+
23
import { describe, expect, test, vi } from "vitest";
3-
import { WizardSession } from "./session.js";
4+
import { WizardSession, wizardStepAwaitsInput, type WizardStep } from "./session.js";
45

56
function noteRunner() {
67
return new WizardSession(async (prompter) => {
@@ -11,6 +12,21 @@ function noteRunner() {
1112
}
1213

1314
describe("WizardSession", () => {
15+
test.each([
16+
["select", undefined, true],
17+
["multiselect", undefined, true],
18+
["text", undefined, true],
19+
["confirm", undefined, true],
20+
["action", "client", true],
21+
["action", "gateway", false],
22+
["note", undefined, false],
23+
["progress", undefined, false],
24+
] as const satisfies ReadonlyArray<
25+
readonly [WizardStep["type"], WizardStep["executor"], boolean]
26+
>)("classifies whether %s/%s awaits user input", (type, executor, expected) => {
27+
expect(wizardStepAwaitsInput({ id: "step", type, executor })).toBe(expected);
28+
});
29+
1430
test("steps progress in order", async () => {
1531
const session = noteRunner();
1632

‎src/wizard/session.ts‎

Lines changed: 41 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,34 +1,39 @@
11
// Wizard session helpers track onboarding session ids and state.
22
import { randomUUID } from "node:crypto";
3+
import type { WizardStep as ProtocolWizardStep } from "../../packages/gateway-protocol/src/index.js";
34
import { createDeferred, type Deferred } from "../shared/deferred.js";
45
import { WizardCancelledError, type WizardProgress, type WizardPrompter } from "./prompts.js";
56

67
// WizardSession exposes interactive setup as a step/answer protocol for remote
78
// clients while reusing the same WizardPrompter contract as the local CLI.
8-
type WizardStepOption = {
9-
value: unknown;
10-
label: string;
11-
hint?: string;
12-
};
13-
14-
export type WizardStep = {
15-
id: string;
16-
type: "note" | "select" | "text" | "confirm" | "multiselect" | "progress" | "action";
17-
title?: string;
18-
message?: string;
19-
format?: "plain";
20-
options?: WizardStepOption[];
21-
initialValue?: unknown;
22-
placeholder?: string;
23-
sensitive?: boolean;
24-
executor?: "gateway" | "client";
25-
externalUrl?: string;
26-
deviceCode?: {
27-
code: string;
28-
expiresInMinutes?: number;
29-
message?: string;
30-
};
31-
};
9+
export type WizardStep = ProtocolWizardStep;
10+
11+
type WizardStepInputRequirement = "always" | "never" | "client-executor";
12+
13+
const WIZARD_STEP_INPUT_REQUIREMENT_BY_TYPE = {
14+
note: "never",
15+
select: "always",
16+
text: "always",
17+
confirm: "always",
18+
multiselect: "always",
19+
progress: "never",
20+
action: "client-executor",
21+
} as const satisfies Record<WizardStep["type"], WizardStepInputRequirement>;
22+
23+
/** Whether a step needs a user answer instead of client or gateway acknowledgement. */
24+
export function wizardStepAwaitsInput(step: WizardStep): boolean {
25+
const requirement = WIZARD_STEP_INPUT_REQUIREMENT_BY_TYPE[step.type];
26+
switch (requirement) {
27+
case "always":
28+
return true;
29+
case "never":
30+
return false;
31+
case "client-executor":
32+
return step.executor === "client";
33+
}
34+
const unhandledRequirement: never = requirement;
35+
return unhandledRequirement;
36+
}
3237

3338
type WizardSessionStatus = "running" | "done" | "cancelled" | "error";
3439

@@ -76,7 +81,12 @@ class WizardSessionPrompter implements WizardPrompter {
7681
}
7782

7883
async note(message: string, title?: string): Promise<void> {
79-
await this.prompt({ type: "note", title, message, executor: "client" });
84+
await this.prompt({
85+
type: "note",
86+
title,
87+
message,
88+
executor: "client",
89+
});
8090
}
8191

8292
async deviceCode(params: {
@@ -106,7 +116,12 @@ class WizardSessionPrompter implements WizardPrompter {
106116
}
107117

108118
async plain(message: string): Promise<void> {
109-
await this.prompt({ type: "note", message, format: "plain", executor: "client" });
119+
await this.prompt({
120+
type: "note",
121+
message,
122+
format: "plain",
123+
executor: "client",
124+
});
110125
}
111126

112127
async select<T>(params: {

‎ui/src/pages/channels/wizard-controller.ts‎

Lines changed: 3 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
// Drives a gateway channel-setup wizard session (wizard.start flow "channels")
22
// as a step/answer state machine for the Control UI wizard modal.
3+
import type { WizardStep } from "../../api/types.ts";
34
import { isWizardNotFoundError } from "../../lib/gateway-errors.ts";
45

56
type WizardGatewayClient = {
@@ -37,26 +38,8 @@ async function requestWithTimeout<T>(
3738
}
3839
}
3940

40-
export type ChannelWizardStepOption = {
41-
value: unknown;
42-
label: string;
43-
hint?: string;
44-
};
45-
46-
export type ChannelWizardStep = {
47-
id: string;
48-
type: "note" | "select" | "text" | "confirm" | "multiselect" | "progress" | "action";
49-
title?: string;
50-
message?: string;
51-
format?: "plain";
52-
options?: ChannelWizardStepOption[];
53-
initialValue?: unknown;
54-
placeholder?: string;
55-
sensitive?: boolean;
56-
executor?: "gateway" | "client";
57-
externalUrl?: string;
58-
deviceCode?: { code: string; expiresInMinutes?: number; message?: string };
59-
};
41+
export type ChannelWizardStepOption = NonNullable<WizardStep["options"]>[number];
42+
export type ChannelWizardStep = WizardStep;
6043

6144
type WizardNextResult = {
6245
sessionId?: string;

0 commit comments

Comments
 (0)