Skip to content

Commit aeee426

Browse files
authored
feat(control-ui): persistent Ask OpenClaw companion with global toggle (#125107)
* feat(control-ui): persistent Ask OpenClaw companion with global toggle The custodian surface now behaves like the persistent machine-wide agent it already is on the Gateway: the session id persists in localStorage so a reopened surface rebinds to the live engine (wizard and approval state survive close/reopen), the durable transcript is refetched when a surface opens or the gateway reconnects (idle-gated so active question/wizard cards are never clobbered), and the panel toggles from anywhere via the shared panel-toggle contract, a command-palette action, and an admin-gated lobster chrome button. One server-side line: the openclaw.chat owner-mismatch rejection now carries the existing structured session-invalidated details so persisted clients re-mint their id from a closed code instead of matching error prose. No gateway events, no protocol schema changes, no polling. Splits (session-identity/variant modules, session-lifecycle and panel-toggle test files) keep the touched files under the max-lines ratchet. * fix(control-ui): coerce custodian toggle detail without a type assertion The assertion-safety ratchet holds custodian-panel.ts at zero uncommented assertions; parse the toggle CustomEvent detail through the canonical record-coerce guard and literal narrowing instead of casting. * fix(control-ui): delete unused CustodianPanelToggleDetail export The record-coerce toggle parsing left the exported type without a production consumer; the deadcode gate rightly flags it. The palette test keeps a local shape. * test(control-ui): select the palette custodian item via keyboard Async session-search results can reflow the palette list mid-click on slow CI runners, silently dropping the positional click; keyboard selection of the asserted-active item is atomic against reflow. Also stage the reopen wait (panel section, then text) for sharper failure localization. * fix(control-ui): project live wizard state on rejoin and scope-gate the toggles Address both ClawSweeper P1 findings. The welcome-only rejoin of an existing session now routes through engine.decorateRejoinReply (the existing ChatWizardHost projection), so a reconnecting client re-renders the live wizard/question controls the session still awaits; the stale welcome question only fills in when no interaction is live. The chrome button, palette action, and deferred panel loading now use the scope-aware canCallGatewayMethod gate (operator.admin) that the session store already used, so advertised-but-read-scoped clients see nothing. * test(control-ui): fix the cloud-workers e2e flake at both roots The mocked config.get stayed frozen at the empty initial config while patch responses advanced, so a config-store reconciliation refetch could flap the snapshot to empty and saveProfile silently dropped the next save; the mock now stays consistent before each patch resolution. Also give waitForRequest an opt-in after-cursor: it is satisfied by any prior same-method request and returns the latest match, so a second wait could assert against the stale earlier request; the cloud-workers waits pin it (15x green locally, previously failing 1-in-3). * fix(ci): cover rejoin projection in sibling engine mocks; bump startup baseline The greeting-welcome and session-ownership suites' engine mocks now export decorateRejoinReply like the handler requires. The Control UI startup-JS baseline moves 337511 -> 338920 B via the documented update command: the shell chrome toggle, palette action, and scope-aware gating are genuine startup surface (~1.4 KiB gzip, within the committed ceiling). * fix(control-ui): settle interrupted structured replies and racing turns on rejoin Address both ClawSweeper reconnect P1s. A submitted question/wizard reply with an unknown outcome now triggers a full session rejoin on reconnect instead of being blocked by its own uncertainty flag: the Gateway projects whether the answer was consumed and which control is live. A restored persisted id also arms a one-shot rejoin barrier: the welcome-only request queues behind any in-flight turn on the Gateway's per-session queue, so a post-response history refresh deterministically surfaces rows a racing turn persisted after the initial fetch. The open-agent handoff moved to custodian-navigation (its owner) to keep the store under the size cap. Live-Gateway proof (isolated state dir, real gpt-5.6-luna turns): video and screenshots on the PR. * test(control-ui): reopen via the chrome toggle in the custodian e2e The palette click-through composition proved timing-flaky on loaded CI runners in three different ways while adding no coverage: the palette action's dispatch is pinned by the palette unit test and the event-opens- panel path by the chrome-toggle step. Keep the gated palette entry assertion + screenshot; reopen through the chrome path. * fix(control-ui): keep the agent-handoff path helper module-local The store now routes through performCustodianAgentHandoff, leaving the path builder without external callers; the deadcode gate rightly flags the export. * fix(control-ui): run the rejoin barrier even when a live control projects The racing-history refresh happens before the reply/control message is appended, so skipping it for projected wizard/question rejoins had no purpose and lost rows a turn persisted while the page was closed mid- wizard. Regression covers the live-step rejoin reconciling racing rows.
1 parent 44e8b6f commit aeee426

37 files changed

Lines changed: 1590 additions & 350 deletions
Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
{
2-
"startupJsGzipBytes": 339585,
3-
"reason": "Startup growth reflects session placement move controls, ownership chips, assignment menus, participant stack, cloud worker settings navigation and machine selection, plus the session permission picker (five-option menu with Default), permission chip, and guardian review notices joining the startup chat composer path.",
2+
"startupJsGzipBytes": 340994,
3+
"reason": "Ask OpenClaw companion: shell chrome toggle, palette action, scope-aware gating",
44
"updatedAt": "2026-08-17"
55
}

‎docs/web/control-ui.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -141,7 +141,7 @@ Theme, theme mode, language, and chat display preferences sync through the gatew
141141

142142
## OpenClaw system care
143143

144-
Open **Settings → Ask OpenClaw** to talk to the system setup and repair agent. The page renders a centered chat with the animated OpenClaw mascot, which switches to a thinking pose while a turn is in flight. The conversation is not trapped in Settings: the lobster button in the thread workspace rail toggles the same live session as a dockable panel (right or bottom, with placement and size persisted in the browser profile), and leaving the full page mid-conversation automatically minimizes the chat into that dock so the session follows you. The dock hides itself while the full Ask OpenClaw page is open.
144+
Open **Settings → Ask OpenClaw** to talk to the system setup and repair agent. Toggle it from anywhere with the lobster button in the shell chrome or the **Ask OpenClaw** command-palette action. The full page and dockable panel share one machine-wide conversation whose durable history lives on the Gateway. Closing the UI never cancels a turn; reopening Ask OpenClaw shows the completed conversation. The panel docks on the right or bottom, remembers its placement and size in the browser profile, and hides itself while the full page is open.
145145

146146
Each chat message carries the Control UI page you are currently viewing as an untrusted ambient hint, so requests like "configure this channel" or "why is this page empty?" resolve against the page you are looking at.
147147

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

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -179,6 +179,14 @@ type GatewaySystemAgentSession = {
179179
sensitive?: boolean;
180180
question?: SystemAgentChatQuestion;
181181
}>;
182+
decorateRejoinReply: (reply: { text: string; action: "none" }) => {
183+
text: string;
184+
action: "none" | "exit" | "open-tui" | "open-setup";
185+
sensitive?: boolean;
186+
wizardInputPending?: boolean;
187+
question?: SystemAgentChatQuestion;
188+
step?: import("../../wizard/session.js").WizardStep;
189+
};
182190
seedHistory: (turns: readonly SystemAgentHistoryTurn[]) => void;
183191
historyLength: () => number;
184192
historySince: (index: number) => SystemAgentHistoryTurn[];

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

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,42 @@ type SystemAgentChatEngineInput = Pick<
1010
"answerWizard" | "cancelWizard" | "handle"
1111
>;
1212

13+
/**
14+
* Build the welcome-only result for rejoining an existing session. A
15+
* reconnecting client must re-render the live wizard/question controls the
16+
* session still awaits; the stale welcome question only fills in when no live
17+
* interaction exists.
18+
*/
19+
export function buildSystemAgentRejoinResult(params: {
20+
sessionId: string;
21+
welcome: string;
22+
welcomeQuestion?: SystemAgentChatResult["question"];
23+
engine: {
24+
decorateRejoinReply: (reply: { text: string; action: "none" }) => {
25+
text: string;
26+
sensitive?: boolean;
27+
wizardInputPending?: boolean;
28+
question?: SystemAgentChatResult["question"];
29+
step?: SystemAgentChatResult["step"];
30+
};
31+
};
32+
}): SystemAgentChatResult {
33+
const rejoin = params.engine.decorateRejoinReply({ text: params.welcome, action: "none" });
34+
return {
35+
sessionId: params.sessionId,
36+
reply: rejoin.text || params.welcome,
37+
action: "none",
38+
...(rejoin.sensitive === true ? { sensitive: true } : {}),
39+
...(rejoin.wizardInputPending === true ? { wizardInputPending: true } : {}),
40+
...(rejoin.step ? { step: rejoin.step } : {}),
41+
...(rejoin.question
42+
? { question: rejoin.question }
43+
: params.welcomeQuestion
44+
? { question: params.welcomeQuestion }
45+
: {}),
46+
};
47+
}
48+
1349
export function getSystemAgentChatInputError(params: SystemAgentChatParams): string | undefined {
1450
if (params.message !== undefined && params.wizardAnswer !== undefined) {
1551
return "Send either message or wizardAnswer, not both.";

‎src/gateway/server-methods/system-agent-greeting-welcome.test.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,7 @@ type FakeEngine = {
5353
loadOverview: ReturnType<typeof vi.fn>;
5454
noteAssistantMessage: ReturnType<typeof vi.fn>;
5555
planGreeting: ReturnType<typeof vi.fn>;
56+
decorateRejoinReply: ReturnType<typeof vi.fn>;
5657
};
5758

5859
function makeEngine(): FakeEngine {
@@ -72,6 +73,7 @@ function makeEngine(): FakeEngine {
7273
history.push({ role: "assistant", text });
7374
}),
7475
planGreeting: vi.fn(),
76+
decorateRejoinReply: vi.fn((reply: unknown) => reply),
7577
};
7678
}
7779

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

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,7 @@ type FakeEngine = {
4747
dispose: ReturnType<typeof vi.fn>;
4848
loadOverview: ReturnType<typeof vi.fn>;
4949
noteAssistantMessage: ReturnType<typeof vi.fn>;
50+
decorateRejoinReply: ReturnType<typeof vi.fn>;
5051
};
5152

5253
function makeEngine(): FakeEngine {
@@ -66,6 +67,7 @@ function makeEngine(): FakeEngine {
6667
dispose: vi.fn(async () => undefined),
6768
loadOverview: vi.fn(async () => ({})),
6869
noteAssistantMessage: vi.fn(),
70+
decorateRejoinReply: vi.fn((reply: unknown) => reply),
6971
};
7072
}
7173

Lines changed: 277 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,277 @@
1+
// System-agent session lifecycle tests cover ownership, eviction, and reset boundaries.
2+
3+
import { expectDefined } from "@openclaw/normalization-core";
4+
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
5+
import { buildSystemAgentSessionInvalidatedErrorDetails } from "../../../packages/gateway-protocol/src/index.js";
6+
import { createDeferred } from "../../../test/helpers/promise.js";
7+
import { resetCommandQueueStateForTest } from "../../process/command-queue.test-support.js";
8+
import { systemAgentHandlers, type SystemAgentChatSession } from "./system-agent.js";
9+
import type { GatewayClient, GatewayRequestContext, RespondFn } from "./types.js";
10+
11+
const inferenceFallbackMocks = vi.hoisted(() => ({
12+
verifySystemAgentInferenceWithFallback: vi.fn(),
13+
}));
14+
const transcriptStoreMocks = vi.hoisted(() => ({
15+
appendTranscriptReset: vi.fn(),
16+
appendTranscriptTurn: vi.fn(),
17+
readTranscriptTail: vi.fn(
18+
(): Array<{ role: "user" | "assistant"; text: string; at: number }> => [],
19+
),
20+
}));
21+
22+
vi.mock("../../system-agent/inference-fallback.js", () => ({
23+
verifySystemAgentInferenceWithFallback:
24+
inferenceFallbackMocks.verifySystemAgentInferenceWithFallback,
25+
}));
26+
vi.mock("../../system-agent/transcript-store.js", () => transcriptStoreMocks);
27+
vi.mock("../../system-agent/greeting.js", () => ({
28+
acknowledgeSystemAgentGreetingDelivery: vi.fn(),
29+
buildSystemAgentGreetingQuestion: vi.fn(() => undefined),
30+
loadSystemAgentGreetingFacts: vi.fn(() => ({
31+
updateAvailable: null,
32+
channelHealth: { available: true, degraded: [] },
33+
recentExternalEdit: false,
34+
auditSequence: 0,
35+
})),
36+
resolveSystemAgentGreeting: vi.fn(async () => ({ text: "welcome text", source: "template" })),
37+
}));
38+
39+
type FakeEngine = {
40+
answerWizard: ReturnType<typeof vi.fn>;
41+
cancelWizard: ReturnType<typeof vi.fn>;
42+
decorateRejoinReply: ReturnType<typeof vi.fn>;
43+
dispose: ReturnType<typeof vi.fn>;
44+
getPendingOperatorProposal: ReturnType<typeof vi.fn>;
45+
handle: ReturnType<typeof vi.fn>;
46+
historyLength: ReturnType<typeof vi.fn>;
47+
historySince: ReturnType<typeof vi.fn>;
48+
loadOverview: ReturnType<typeof vi.fn>;
49+
noteAssistantMessage: ReturnType<typeof vi.fn>;
50+
resolveOperatorApproval: ReturnType<typeof vi.fn>;
51+
seedHistory: ReturnType<typeof vi.fn>;
52+
};
53+
54+
function makeEngine(): FakeEngine {
55+
return {
56+
answerWizard: vi.fn(),
57+
cancelWizard: vi.fn(),
58+
decorateRejoinReply: vi.fn((reply: unknown) => reply),
59+
dispose: vi.fn(async () => undefined),
60+
getPendingOperatorProposal: vi.fn(() => null),
61+
handle: vi.fn(async () => ({ text: "did the thing", action: "none" })),
62+
historyLength: vi.fn(() => 0),
63+
historySince: vi.fn(() => []),
64+
loadOverview: vi.fn(async () => ({})),
65+
noteAssistantMessage: vi.fn(),
66+
resolveOperatorApproval: vi.fn(async () => null),
67+
seedHistory: vi.fn(),
68+
};
69+
}
70+
71+
const createdEngines = vi.hoisted(() => [] as FakeEngine[]);
72+
73+
vi.mock("../../system-agent/chat-engine.js", () => {
74+
class FakeSystemAgentWizardAnswerError extends Error {}
75+
return {
76+
SystemAgentWizardAnswerError: FakeSystemAgentWizardAnswerError,
77+
SystemAgentChatEngine: function FakeSystemAgentChatEngine(this: FakeEngine) {
78+
const engine = makeEngine();
79+
createdEngines.push(engine);
80+
Object.assign(this, engine);
81+
},
82+
};
83+
});
84+
vi.mock("../../system-agent/overview.js", () => ({
85+
formatSystemAgentStartupMessage: vi.fn(() => "welcome text"),
86+
}));
87+
88+
type RespondCall = { ok: boolean; payload?: unknown; error?: unknown };
89+
90+
const defaultClient = {
91+
connId: "conn-test",
92+
connect: { device: { id: "device-test" } },
93+
} as GatewayClient;
94+
95+
function makeContext(sessions: Map<string, SystemAgentChatSession>): GatewayRequestContext {
96+
return { systemAgentSessions: sessions } as unknown as GatewayRequestContext;
97+
}
98+
99+
function seededSession(params?: {
100+
engine?: FakeEngine;
101+
lastUsedAt?: number;
102+
ownerKey?: string;
103+
}): SystemAgentChatSession {
104+
return {
105+
engine: params?.engine ?? makeEngine(),
106+
welcome: "welcome text",
107+
lastUsedAt: params?.lastUsedAt ?? 1,
108+
ownerKey: params?.ownerKey ?? "device:device-test",
109+
} as unknown as SystemAgentChatSession;
110+
}
111+
112+
async function callChat(
113+
context: GatewayRequestContext,
114+
params: Record<string, unknown>,
115+
): Promise<RespondCall> {
116+
const calls: RespondCall[] = [];
117+
const respond: RespondFn = (ok, payload, error) => calls.push({ ok, payload, error });
118+
await expectDefined(
119+
systemAgentHandlers["openclaw.chat"],
120+
'systemAgentHandlers["openclaw.chat"] test invariant',
121+
)({ params, client: defaultClient, context, respond } as never);
122+
return expectDefined(calls[0], "system-agent response");
123+
}
124+
125+
const waitOneTask = () =>
126+
new Promise<void>((resolve) => {
127+
setTimeout(resolve, 0);
128+
});
129+
130+
beforeEach(() => {
131+
createdEngines.length = 0;
132+
inferenceFallbackMocks.verifySystemAgentInferenceWithFallback.mockResolvedValue({
133+
ok: true,
134+
binding: {},
135+
});
136+
transcriptStoreMocks.appendTranscriptReset.mockReset();
137+
transcriptStoreMocks.appendTranscriptTurn.mockReset();
138+
transcriptStoreMocks.readTranscriptTail.mockReset().mockReturnValue([]);
139+
});
140+
141+
afterEach(() => {
142+
vi.clearAllMocks();
143+
resetCommandQueueStateForTest();
144+
});
145+
146+
describe("openclaw.chat session lifecycle", () => {
147+
it("rejects a foreign-owner session with structured invalidation details", async () => {
148+
const sessions = new Map<string, SystemAgentChatSession>([
149+
["s1", seededSession({ ownerKey: "device:someone-else" })],
150+
]);
151+
152+
const call = await callChat(makeContext(sessions), {
153+
sessionId: "s1",
154+
message: "Hello?",
155+
});
156+
157+
// Persisted client session ids depend on the structured details to mint a
158+
// fresh id instead of retry-looping against the foreign live session.
159+
expect(call).toEqual({
160+
ok: false,
161+
payload: undefined,
162+
error: {
163+
code: "INVALID_REQUEST",
164+
message: "OpenClaw session belongs to another caller.",
165+
details: buildSystemAgentSessionInvalidatedErrorDetails(),
166+
},
167+
});
168+
});
169+
170+
it("projects the live wizard interaction on a welcome-only rejoin", async () => {
171+
const engine = makeEngine();
172+
const liveQuestion = { id: "wizard-q", header: "Pick", options: [{ label: "A" }] };
173+
const liveStep = { id: "step-1", type: "text", message: "Enter a value" };
174+
engine.decorateRejoinReply = vi.fn((reply: Record<string, unknown>) => ({
175+
...reply,
176+
sensitive: true,
177+
wizardInputPending: true,
178+
question: liveQuestion,
179+
step: liveStep,
180+
}));
181+
const session = seededSession({ engine });
182+
(session as { welcomeQuestion?: unknown }).welcomeQuestion = {
183+
id: "welcome-q",
184+
header: "Welcome",
185+
options: [],
186+
};
187+
const sessions = new Map<string, SystemAgentChatSession>([["s1", session]]);
188+
189+
const call = await callChat(makeContext(sessions), { sessionId: "s1" });
190+
191+
// A reconnecting client must re-render the answer controls the session
192+
// still awaits; the live interaction outranks the stale welcome question.
193+
expect(call.ok).toBe(true);
194+
expect(call.payload).toMatchObject({
195+
sessionId: "s1",
196+
sensitive: true,
197+
wizardInputPending: true,
198+
question: liveQuestion,
199+
step: liveStep,
200+
});
201+
});
202+
203+
it("falls back to the welcome question when no interaction is live", async () => {
204+
const session = seededSession();
205+
(session as { welcomeQuestion?: unknown }).welcomeQuestion = {
206+
id: "welcome-q",
207+
header: "Welcome",
208+
options: [],
209+
};
210+
const sessions = new Map<string, SystemAgentChatSession>([["s1", session]]);
211+
212+
const call = await callChat(makeContext(sessions), { sessionId: "s1" });
213+
214+
expect(call.ok).toBe(true);
215+
expect(call.payload).toMatchObject({ question: { id: "welcome-q" } });
216+
expect((call.payload as { step?: unknown }).step).toBeUndefined();
217+
});
218+
219+
it("keeps the session map bounded during concurrent unique initialization", async () => {
220+
const evictionStarted = createDeferred();
221+
const releaseEviction = createDeferred();
222+
const oldest = seededSession({ lastUsedAt: 0 });
223+
oldest.engine.dispose = vi.fn(async () => {
224+
evictionStarted.resolve();
225+
await releaseEviction.promise;
226+
});
227+
const sessions = new Map<string, SystemAgentChatSession>([["oldest", oldest]]);
228+
for (let index = 1; index < 8; index += 1) {
229+
sessions.set(`existing-${index}`, seededSession({ lastUsedAt: index }));
230+
}
231+
232+
const context = makeContext(sessions);
233+
const first = callChat(context, { sessionId: "new-1" });
234+
const second = callChat(context, { sessionId: "new-2" });
235+
await evictionStarted.promise;
236+
await waitOneTask();
237+
releaseEviction.resolve();
238+
await Promise.all([first, second]);
239+
240+
expect(oldest.engine.dispose).toHaveBeenCalledOnce();
241+
expect(sessions.size).toBe(8);
242+
expect([sessions.has("new-1"), sessions.has("new-2")]).toEqual([true, true]);
243+
});
244+
245+
it("resets a session on request", async () => {
246+
const engine = makeEngine();
247+
const sessions = new Map<string, SystemAgentChatSession>([["s1", seededSession({ engine })]]);
248+
const context = makeContext(sessions);
249+
250+
const reset = await callChat(context, { sessionId: "s1", reset: true });
251+
252+
expect(engine.handle).not.toHaveBeenCalled();
253+
expect(engine.dispose).toHaveBeenCalledOnce();
254+
expect(sessions.get("s1")?.engine).not.toBe(engine);
255+
expect(reset.ok).toBe(true);
256+
expect(transcriptStoreMocks.appendTranscriptReset).toHaveBeenCalledOnce();
257+
expect(
258+
expectDefined(createdEngines[0], "replacement engine").seedHistory,
259+
).not.toHaveBeenCalled();
260+
261+
transcriptStoreMocks.readTranscriptTail.mockReturnValue([
262+
{ role: "user", text: "After reset", at: 3 },
263+
{ role: "assistant", text: "Fresh answer", at: 4 },
264+
]);
265+
const fresh = await callChat(context, { sessionId: "fresh-after-reset" });
266+
const freshEngine = expectDefined(createdEngines.at(-1), "fresh engine");
267+
268+
expect(fresh.ok).toBe(true);
269+
expect(freshEngine.seedHistory).toHaveBeenCalledWith([
270+
{ role: "user", text: "After reset" },
271+
{ role: "assistant", text: "Fresh answer" },
272+
]);
273+
expect(transcriptStoreMocks.readTranscriptTail).toHaveBeenLastCalledWith(30, {
274+
afterLastReset: true,
275+
});
276+
});
277+
});

0 commit comments

Comments
 (0)