Skip to content

Commit b7f745c

Browse files
authored
fix(ui): preserve selected session ownership in the composer (#133085)
* fix(ui): preserve selected session ownership in the composer * fix(ui): preserve roster intent when operator identity arrives
1 parent 7fa0bd1 commit b7f745c

11 files changed

Lines changed: 330 additions & 237 deletions

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,7 @@ Docs: https://docs.openclaw.ai
7070

7171
### Fixes
7272

73+
- **Control UI global sessions:** preserve the selected agent's session in the composer so usage, goals, progress, and thinking options survive agent switches without reusing another agent's stale row.
7374
- **Image analysis startup:** prepare selected model providers and keep configuration reads independent of full runtime loading, avoiding unrelated discovery and redundant model resolution while preserving credentials and runtime cleanup.
7475
- **Browser extension relay:** route Runtime binding callbacks only to registered clients and preserve shared bindings during client cleanup, preventing raw callback payloads from reaching unrelated Playwright sessions.
7576
- **Control UI media playback:** restore inline audio and video rendition loading so readiness checks reach the Gateway instead of silently falling back to download cards. (#132832)

‎docs/web/control-ui.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -618,7 +618,7 @@ Chat error banners, including cloud runner failures, keep a compact preview. Ope
618618
- The chat model picker requests the Gateway's configured model view. If `agents.defaults.modelPolicy.allow` is non-empty, that policy drives the picker, including `provider/*` entries that keep provider-scoped catalogs dynamic. Otherwise the picker shows configured entries plus providers with usable auth; aliases and settings under `agents.defaults.models` do not restrict it. The full catalog stays available through the debug `models.list` RPC with `view: "all"`.
619619
- Chat and New Session block sending when the Gateway reports missing provider credentials or a confirmed authentication failure. Missing credentials point to **Model Setup**; authentication failures ask you to review the credential or sign-in. Temporary credential cooldowns and unknown model availability do not block sending or show an authentication banner; run errors remain visible in the transcript. Unavailable model choices stay disabled in the picker.
620620
- After a config change or a published credential update, connected Chat and New Session views re-read model readiness automatically; no page reload or picker action is needed. Chat also re-reads its session projection after a model or auth-profile selection changes. An existing missing-credential or authentication-failure block stays in place while that read is pending or fails, until replacement metadata changes it. Existing chats keep their session's selected auth profile; New Session uses the agent's default credential selection. This refresh is event-driven, not a timed polling guarantee.
621-
- When fresh Gateway session usage reports include current context tokens, the chat composer toolbar shows a small context usage ring with the used percentage. Open the ring for the current context window, latest-run token counts and estimated total cost, provider/model identity, and the latest provider response's input/output/cache cost breakdown when reported. The ring switches to warning styling at high context pressure. Stale token snapshots are hidden until the Gateway reports fresh usage again.
621+
- The chat composer usage ring follows the selected session and agent, including global sessions. Open it for the current context window, latest-run token counts, and the current provider's account, plan, and quota when reported. Subscription quota replaces dollar estimates; other sessions can show estimated total cost and the latest provider response's input/output/cache cost breakdown. Fresh usage switches to warning styling at high context pressure; stale token snapshots remain visible as approximate usage without that warning. During an agent switch, the previous agent's session row is not reused for the ring.
622622

623623
</Accordion>
624624
<Accordion title="Talk mode (browser realtime)">

‎ui/src/e2e/chat-quota-pill-93041.e2e.test.ts‎

Lines changed: 46 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import {
88
controlUiE2eWaitTimeoutMs,
99
controlUiSessionUrl,
1010
installMockGateway,
11+
type MockGatewayControls,
1112
} from "../test-helpers/control-ui-e2e.ts";
1213
import { createControlUiE2eSuite } from "./control-ui-e2e-suite.test-support.ts";
1314

@@ -123,6 +124,7 @@ const selectedGlobalSessions = {
123124
...gatewayInjectedSessions.sessions[0],
124125
displayName: "Selected global",
125126
key: "global",
127+
kind: "global",
126128
label: "Selected global",
127129
modelProvider: "openai",
128130
},
@@ -220,13 +222,36 @@ async function closeChat(fixture: { context: BrowserContext; page: Page }): Prom
220222
await fixture.context.close().catch(() => {});
221223
}
222224

223-
async function setSelectedAgent(page: Page, agentId: string): Promise<void> {
224-
await page.evaluate((nextAgentId) => {
225-
const app = document.querySelector("openclaw-app") as HTMLElement & {
226-
runtime?: { context: { agentSelection: { set: (value: string) => void } } };
227-
};
228-
app.runtime?.context.agentSelection.set(nextAgentId);
229-
}, agentId);
225+
async function setSelectedAgent(page: Page, name: string): Promise<void> {
226+
const sidebar = page.locator("openclaw-app-sidebar");
227+
await sidebar.getByRole("button", { name: /Switch agent/ }).click();
228+
await sidebar.getByRole("menuitemradio", { name, exact: true }).click();
229+
}
230+
231+
async function replyToAgentMetadata(gateway: MockGatewayControls, agentId: "main" | "work") {
232+
for (const method of ["models.authStatus", "agent.identity.get"]) {
233+
const requests = (await gateway.getRequests(method)).filter((request) => {
234+
const params = request.params;
235+
return (
236+
typeof params === "object" &&
237+
params !== null &&
238+
"agentId" in params &&
239+
params.agentId === agentId
240+
);
241+
});
242+
expect(requests.length).toBeGreaterThan(0);
243+
for (const request of requests) {
244+
await gateway.deliverLatest({
245+
type: "res",
246+
id: request.id,
247+
ok: true,
248+
payload:
249+
method === "models.authStatus"
250+
? agentAuthStatus(agentId)
251+
: { agentId, name: `${agentId === "main" ? "Stale Main" : "Work"} Agent` },
252+
});
253+
}
254+
}
230255
}
231256

232257
async function visibleAuthState(page: Page) {
@@ -447,7 +472,7 @@ suite.define(() => {
447472
const gateway = await installMockGateway(page, {
448473
assistantAgentId: "main",
449474
defaultAgentId: "main",
450-
deferredMethods: ["models.authStatus", "models.authStatus", "agent.identity.get"],
475+
heldMethods: ["models.authStatus", "agent.identity.get"],
451476
// The selected agent's session metrics may not have arrived; its transcript
452477
// still identifies which provider's quota belongs in the popover.
453478
historyMessages: [
@@ -474,6 +499,7 @@ suite.define(() => {
474499
"sessions.list": selectedGlobalSessions,
475500
},
476501
sessionKey: "global",
502+
sessionScope: "global",
477503
});
478504
await page.goto(controlUiSessionUrl(suite.server.baseUrl, "global"));
479505
const connectRequest = await gateway.waitForRequest("connect");
@@ -512,10 +538,7 @@ suite.define(() => {
512538
pane.state.requestUpdate?.();
513539
}
514540
});
515-
await gateway.deferNext("models.authStatus", { agentId: "work" });
516-
await gateway.deferNext("models.authStatus", { agentId: "work" });
517-
await gateway.deferNext("agent.identity.get", { agentId: "work" });
518-
await setSelectedAgent(page, "work");
541+
await setSelectedAgent(page, "Work");
519542
await expect.poll(async () => (await visibleAuthState(page)).agentId).toBe("work");
520543
await expect
521544
.poll(async () => (await gateway.getRequests("models.authStatus")).length)
@@ -551,8 +574,7 @@ suite.define(() => {
551574
};
552575
}),
553576
)
554-
.toEqual({ name: "", avatar: null, renderedAvatar: null });
555-
await gateway.deferNext("models.authStatus", { agentId: "work" });
577+
.toEqual({ name: "OpenClaw", avatar: null, renderedAvatar: null });
556578
await gateway.emitGatewayEvent("presence", {
557579
presence: [
558580
{
@@ -582,12 +604,7 @@ suite.define(() => {
582604
});
583605
}
584606

585-
await gateway.resolveDeferred("models.authStatus");
586-
await gateway.resolveDeferred("models.authStatus");
587-
await gateway.resolveDeferred("agent.identity.get", {
588-
agentId: "main",
589-
name: "Stale Main Agent",
590-
});
607+
await replyToAgentMetadata(gateway, "main");
591608
await page.waitForTimeout(100);
592609
const delayedMainState = await visibleAuthState(page);
593610
expect(delayedMainState).toEqual({
@@ -640,13 +657,7 @@ suite.define(() => {
640657
),
641658
).not.toHaveLength(0);
642659

643-
for (let pending = workAuthRequests.length; pending > 0; pending -= 1) {
644-
await gateway.resolveDeferred("models.authStatus");
645-
}
646-
await gateway.resolveDeferred("agent.identity.get", {
647-
agentId: "work",
648-
name: "Work Agent",
649-
});
660+
await replyToAgentMetadata(gateway, "work");
650661
await expect
651662
.poll(() => visibleAuthState(page))
652663
.toEqual({
@@ -657,6 +668,14 @@ suite.define(() => {
657668
plan: "Work Team",
658669
ts: baseTime + 2,
659670
});
671+
await setOwnershipProofCue(page, "Selected agent: Work | Work account and plan loaded");
672+
if (captureOwnershipProof) {
673+
await page.screenshot({
674+
animations: "disabled",
675+
fullPage: true,
676+
path: path.join(ownershipProofDir, "03-work-settled.png"),
677+
});
678+
}
660679
popover = await openVisibleQuotaPopover(page);
661680
await expect.poll(async () => popover.textContent()).toContain("Work Team");
662681
const settledText = (await popover.textContent()) ?? "";

‎ui/src/lib/sessions/connection-hydration.test.ts‎

Lines changed: 92 additions & 67 deletions
Original file line numberDiff line numberDiff line change
@@ -189,6 +189,8 @@ describe("session connection hydration", () => {
189189
expect(request.mock.calls.filter(([method]) => method === "sessions.list")).toHaveLength(0);
190190
expect(sessions.state.result).toBeNull();
191191
const queuedRefresh = sessions.refresh({ agentId: "other", search: "queued", force: true });
192+
snapshot = { ...snapshot, selfUser: { id: "collaborator", name: "Collaborator" } };
193+
gatewayListener?.(snapshot);
192194

193195
bootstrap.resolve({ subscribed: true, list: roster });
194196
await waitForFast(() =>
@@ -260,77 +262,100 @@ describe("session connection hydration", () => {
260262
sessions.dispose();
261263
});
262264

263-
it("rehydrates owner sessions when identity arrives on the same connection", async () => {
264-
let resolveList: (result: SessionsListResult) => void = () => undefined;
265-
const pendingList = new Promise<SessionsListResult>((resolve) => {
266-
resolveList = resolve;
267-
});
268-
let listCalls = 0;
269-
const result: SessionsListResult = {
270-
ts: 1,
271-
path: "(multiple)",
272-
count: 0,
273-
defaults: { modelProvider: null, model: null, contextTokens: null },
274-
sessions: [],
275-
};
276-
const request = vi.fn(async (method: string, _params?: Record<string, unknown>) => {
277-
if (method === "sessions.subscribe") {
278-
return { subscribed: true };
279-
}
280-
if (method === "sessions.list") {
281-
listCalls += 1;
282-
return listCalls === 1 ? await pendingList : result;
283-
}
284-
throw new Error(`Unexpected request: ${method}`);
285-
});
286-
const client = { request } as unknown as GatewayBrowserClient;
287-
let snapshot = {
288-
client: null as GatewayBrowserClient | null,
289-
phase: "reconnecting" as "connected" | "reconnecting",
290-
sessionKey: "agent:main:main",
291-
assistantAgentId: "main" as string | null,
292-
hello: null as GatewayHelloOk | null,
293-
canvasPluginSurfaceUrl: null as string | null,
294-
selfUser: null as { id: string; name?: string } | null,
295-
};
296-
let gatewayListener: ((next: typeof snapshot) => void) | undefined;
297-
const sessions = createSessionCapability({
298-
get snapshot() {
299-
return snapshot;
300-
},
301-
subscribe(listener) {
302-
gatewayListener = listener;
303-
return () => undefined;
304-
},
305-
subscribeEvents: () => () => undefined,
306-
});
265+
it.each(["main", "work"])(
266+
"rehydrates the current %s roster when identity arrives on the same connection",
267+
async (agentId) => {
268+
let resolveList: (result: SessionsListResult) => void = () => undefined;
269+
const pendingList = new Promise<SessionsListResult>((resolve) => {
270+
resolveList = resolve;
271+
});
272+
let listCalls = 0;
273+
const result: SessionsListResult = {
274+
ts: 1,
275+
path: "(multiple)",
276+
count: 0,
277+
defaults: { modelProvider: null, model: null, contextTokens: null },
278+
sessions: [],
279+
};
280+
const request = vi.fn(async (method: string, _params?: Record<string, unknown>) => {
281+
if (method === "sessions.subscribe") {
282+
return { subscribed: true };
283+
}
284+
if (method === "sessions.list") {
285+
listCalls += 1;
286+
return listCalls === 1 ? await pendingList : result;
287+
}
288+
throw new Error(`Unexpected request: ${method}`);
289+
});
290+
const client = { request } as unknown as GatewayBrowserClient;
291+
let snapshot = {
292+
client: null as GatewayBrowserClient | null,
293+
phase: "reconnecting" as "connected" | "reconnecting",
294+
sessionKey: "agent:main:main",
295+
assistantAgentId: "main" as string | null,
296+
hello: null as GatewayHelloOk | null,
297+
canvasPluginSurfaceUrl: null as string | null,
298+
selfUser: null as { id: string; name?: string } | null,
299+
};
300+
let gatewayListener: ((next: typeof snapshot) => void) | undefined;
301+
const sessions = createSessionCapability({
302+
get snapshot() {
303+
return snapshot;
304+
},
305+
subscribe(listener) {
306+
gatewayListener = listener;
307+
return () => undefined;
308+
},
309+
subscribeEvents: () => () => undefined,
310+
});
307311

308-
snapshot = { ...snapshot, client, phase: "connected" };
309-
gatewayListener?.(snapshot);
310-
await waitForFast(() => expect(listCalls).toBe(1));
312+
snapshot = { ...snapshot, client, phase: "connected" };
313+
gatewayListener?.(snapshot);
314+
await waitForFast(() => expect(listCalls).toBe(1));
311315

312-
snapshot = { ...snapshot, canvasPluginSurfaceUrl: "https://gateway.example.test/canvas" };
313-
gatewayListener?.(snapshot);
314-
await Promise.resolve();
315-
expect(listCalls).toBe(1);
316+
snapshot = { ...snapshot, canvasPluginSurfaceUrl: "https://gateway.example.test/canvas" };
317+
gatewayListener?.(snapshot);
318+
await Promise.resolve();
319+
expect(listCalls).toBe(1);
320+
321+
if (agentId === "work") {
322+
resolveList(result);
323+
await waitForFast(() => expect(sessions.state.result).toBe(result));
324+
// The global route remains unchanged while the picker selects another roster.
325+
snapshot = { ...snapshot, sessionKey: "global" };
326+
await sessions.refresh({ agentId, search: "selected", force: true });
327+
expect(sessions.state.agentId).toBe(agentId);
328+
}
329+
snapshot = { ...snapshot, selfUser: { id: "operator", name: "Operator" } };
330+
gatewayListener?.(snapshot);
331+
resolveList(result);
332+
await waitForFast(() => expect(listCalls).toBe(agentId === "work" ? 3 : 2));
316333

317-
snapshot = { ...snapshot, selfUser: { id: "operator", name: "Operator" } };
318-
gatewayListener?.(snapshot);
319-
resolveList(result);
320-
await waitForFast(() => expect(listCalls).toBe(2));
334+
expect(
335+
request.mock.calls
336+
.filter(([method]) => method === "sessions.list")
337+
.map(([, params]) => params),
338+
).toEqual([
339+
expect.not.objectContaining({ ownerFirst: expect.anything() }),
340+
...(agentId === "work" ? [expect.objectContaining({ agentId, search: "selected" })] : []),
341+
expect.objectContaining({
342+
agentId,
343+
limit: SIDEBAR_SESSION_ROSTER_LIMIT,
344+
...(agentId === "work" ? { search: "selected" } : { ownerFirst: true }),
345+
}),
346+
]);
347+
await waitForFast(() => expect(sessions.state.agentId).toBe(agentId));
348+
expect(sessions.state.result?.sessions).toEqual([]);
321349

322-
expect(
323-
request.mock.calls
324-
.filter(([method]) => method === "sessions.list")
325-
.map(([, params]) => params),
326-
).toEqual([
327-
expect.not.objectContaining({ ownerFirst: expect.anything() }),
328-
expect.objectContaining({ ownerFirst: true, limit: SIDEBAR_SESSION_ROSTER_LIMIT }),
329-
]);
330-
expect(sessions.state.result?.sessions).toEqual([]);
331-
expect(sessions.state.agentId).toBe("main");
332-
sessions.dispose();
333-
});
350+
// A new connection still derives scope from the current gateway route.
351+
snapshot = { ...snapshot, phase: "reconnecting" };
352+
gatewayListener?.(snapshot);
353+
snapshot = { ...snapshot, phase: "connected", sessionKey: "agent:main:main" };
354+
gatewayListener?.(snapshot);
355+
await waitForFast(() => expect(sessions.state.agentId).toBe("main"));
356+
sessions.dispose();
357+
},
358+
);
334359

335360
it("hydrates again after the current client reconnects", async () => {
336361
let listCalls = 0;

‎ui/src/lib/sessions/index.ts‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -486,13 +486,19 @@ export function createSessionCapability(gateway: SessionGateway): SessionCapabil
486486
});
487487
return;
488488
}
489-
if (hydratedClient !== next.client || hydratedSelfUserId !== selfUserId) {
489+
const hydrateConnection = hydratedClient !== next.client;
490+
if (hydrateConnection || hydratedSelfUserId !== selfUserId) {
490491
const scope = connection.capture();
491492
if (!scope) {
492493
return;
493494
}
494495
hydratedClient = scope.client;
495496
hydratedSelfUserId = selfUserId;
497+
if (!hydrateConnection) {
498+
// Identity updates refresh the current roster without displacing queued picker intent.
499+
roster.scheduleEvent();
500+
return;
501+
}
496502
void (async () => {
497503
if (connection.isCurrent(scope)) {
498504
const sessionKey = gateway.snapshot.sessionKey?.trim();

0 commit comments

Comments
 (0)