Skip to content

Commit 9eee618

Browse files
authored
fix(ui): serialize Control UI config writers (#116029)
1 parent b9377f6 commit 9eee618

7 files changed

Lines changed: 1172 additions & 169 deletions

File tree

‎ui/src/app/app-host.test.ts‎

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -389,20 +389,20 @@ describe("OpenClaw shell source initialization", () => {
389389
shell.routeState = { routeId: "usage" };
390390
const client = {} as GatewayBrowserClient;
391391
const snapshot = { client, phase: "connected" } as ApplicationGatewaySnapshot;
392-
const firstAgents = {
393-
state: { agentsList: null },
394-
ensureList: vi.fn(() => Promise.resolve(null)),
395-
} as unknown as ApplicationContext["agents"];
396-
const secondAgents = {
397-
state: { agentsList: null },
398-
ensureList: vi.fn(() => Promise.resolve(null)),
399-
} as unknown as ApplicationContext["agents"];
400-
const firstRuntimeConfig = {
401-
ensureLoaded: vi.fn(() => Promise.resolve()),
402-
} as unknown as ApplicationContext["runtimeConfig"];
403-
const secondRuntimeConfig = {
404-
ensureLoaded: vi.fn(() => Promise.resolve()),
405-
} as unknown as ApplicationContext["runtimeConfig"];
392+
const createAgents = () =>
393+
({
394+
state: { agentsList: null },
395+
ensureList: vi.fn(() => Promise.resolve(null)),
396+
}) as unknown as ApplicationContext["agents"];
397+
const createRuntimeConfig = () =>
398+
({
399+
state: { client, connected: true },
400+
ensureLoaded: vi.fn(() => Promise.resolve()),
401+
}) as unknown as ApplicationContext["runtimeConfig"];
402+
const firstAgents = createAgents();
403+
const secondAgents = createAgents();
404+
const firstRuntimeConfig = createRuntimeConfig();
405+
const secondRuntimeConfig = createRuntimeConfig();
406406

407407
shell.ensureAgentsList(snapshot, firstAgents);
408408
shell.ensureAgentsList(snapshot, firstAgents);

‎ui/src/app/app-host.ts‎

Lines changed: 22 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -731,6 +731,20 @@ class OpenClawShell extends OpenClawLightDomElement {
731731
});
732732
}
733733

734+
private reconcileCommittedServerUiPrefs(
735+
runtimeConfig: ApplicationContext["runtimeConfig"],
736+
needsRefresh: boolean,
737+
) {
738+
if (this.context?.runtimeConfig !== runtimeConfig) {
739+
return;
740+
}
741+
if (needsRefresh) {
742+
void runtimeConfig.refresh();
743+
return;
744+
}
745+
this.reconcileServerUiPrefs(runtimeConfig);
746+
}
747+
734748
override connectedCallback() {
735749
super.connectedCallback();
736750
if (this.outboxStoreRuntime) {
@@ -764,15 +778,11 @@ class OpenClawShell extends OpenClawLightDomElement {
764778
return;
765779
}
766780
const prefs = changedServerUiPrefs(previous, next);
767-
const snapshot = this.context?.gateway.snapshot;
768-
if (prefs && snapshot?.client) {
769-
pushServerUiPrefs(snapshot.client, prefs, {
770-
afterCommit: () => {
771-
const runtimeConfig = this.context?.runtimeConfig;
772-
if (runtimeConfig) {
773-
void runtimeConfig.refresh();
774-
}
775-
},
781+
const runtimeConfig = this.context?.runtimeConfig;
782+
if (prefs && runtimeConfig) {
783+
pushServerUiPrefs(runtimeConfig, prefs, {
784+
afterCommit: ({ needsRefresh }) =>
785+
this.reconcileCommittedServerUiPrefs(runtimeConfig, needsRefresh),
776786
});
777787
}
778788
});
@@ -1740,13 +1750,9 @@ class OpenClawShell extends OpenClawLightDomElement {
17401750
}
17411751
this.runtimeConfigClient = snapshot.client;
17421752
this.runtimeConfigSource = runtimeConfig;
1743-
flushServerUiPrefs(snapshot.client, {
1744-
afterCommit: () => {
1745-
const currentRuntimeConfig = this.context?.runtimeConfig;
1746-
if (currentRuntimeConfig) {
1747-
void currentRuntimeConfig.refresh();
1748-
}
1749-
},
1753+
flushServerUiPrefs(runtimeConfig, {
1754+
afterCommit: ({ needsRefresh }) =>
1755+
this.reconcileCommittedServerUiPrefs(runtimeConfig, needsRefresh),
17501756
});
17511757
void runtimeConfig.ensureLoaded();
17521758
}

‎ui/src/app/server-prefs.test.ts‎

Lines changed: 130 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
/* @vitest-environment jsdom */
22

33
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
4+
import type { GatewayBrowserClient } from "../api/gateway.ts";
45
import { createStorageMock } from "../test-helpers/storage.ts";
56
import {
67
applyServerUiPrefs,
@@ -26,6 +27,46 @@ function configWithPrefs(prefs: Record<string, unknown>) {
2627
return { ui: { prefs } };
2728
}
2829

30+
type RequestMock = ReturnType<typeof vi.fn<(method: string, params?: unknown) => Promise<unknown>>>;
31+
32+
function createServerPrefsWriter(
33+
request: RequestMock,
34+
gatewayUrl = "ws://gw",
35+
connected = true,
36+
refresh: { ok: true } | { ok: false; error: string } = { ok: true },
37+
): Parameters<typeof pushServerUiPrefs>[0] {
38+
const client = { request, gatewayUrl, connected } as unknown as GatewayBrowserClient;
39+
const writer = {
40+
state: { client, connected },
41+
runExternalMutation: async <T>(task: (client: GatewayBrowserClient) => Promise<T>) => {
42+
if (!writer.state.connected) {
43+
return {
44+
ok: false as const,
45+
reason: "unavailable" as const,
46+
error: "offline",
47+
};
48+
}
49+
try {
50+
return {
51+
ok: true as const,
52+
value: await task(client),
53+
refresh,
54+
};
55+
} catch (error) {
56+
const message = error instanceof Error ? error.message : String(error);
57+
return {
58+
ok: false as const,
59+
reason: message.includes("config changed since last load")
60+
? ("conflict" as const)
61+
: ("error" as const),
62+
error: message,
63+
};
64+
}
65+
},
66+
};
67+
return writer;
68+
}
69+
2970
describe("server pref extraction", () => {
3071
it("applies only valid, known pref values", () => {
3172
const onApplied = vi.fn();
@@ -93,9 +134,7 @@ describe("applyServerUiPrefs", () => {
93134
applyServerUiPrefs(oldSnapshot, { scope, onApplied });
94135
patchSettings({ themeMode: "dark" });
95136
const request = vi.fn(async () => ({}));
96-
const client = { connected: true, gatewayUrl: scope, request } as unknown as Parameters<
97-
typeof pushServerUiPrefs
98-
>[0];
137+
const client = createServerPrefsWriter(request, scope);
99138

100139
pushServerUiPrefs(client, { themeMode: "dark" });
101140
await vi.waitFor(() =>
@@ -113,9 +152,7 @@ describe("applyServerUiPrefs", () => {
113152
applyServerUiPrefs(oldSnapshot, { scope, onApplied });
114153
patchSettings({ themeMode: "dark" });
115154
const request = vi.fn(async () => ({}));
116-
const client = { connected: true, gatewayUrl: scope, request } as unknown as Parameters<
117-
typeof pushServerUiPrefs
118-
>[0];
155+
const client = createServerPrefsWriter(request, scope);
119156
pushServerUiPrefs(client, { themeMode: "dark" });
120157
await vi.waitFor(() =>
121158
expect(localStorage.getItem(`openclaw.control.serverPrefs.pending.v1:${scope}`)).toBeNull(),
@@ -272,9 +309,6 @@ describe("clearable pref removal from the server", () => {
272309
});
273310

274311
describe("pushServerUiPrefs", () => {
275-
type RequestMock = ReturnType<
276-
typeof vi.fn<(method: string, params?: unknown) => Promise<unknown>>
277-
>;
278312
const deferred = () => {
279313
let resolve!: (value: unknown) => void;
280314
let reject!: (reason?: unknown) => void;
@@ -288,8 +322,7 @@ describe("pushServerUiPrefs", () => {
288322
const lastSeenKey = (scope: string) => `openclaw.control.serverPrefs.v1:${scope}`;
289323
const readPending = (scope: string) =>
290324
JSON.parse(localStorage.getItem(pendingKey(scope)) ?? "{}") as Record<string, unknown>;
291-
const createClient = (request: RequestMock, gatewayUrl = "ws://gw", connected = true) =>
292-
({ request, gatewayUrl, connected }) as unknown as Parameters<typeof pushServerUiPrefs>[0];
325+
const createClient = createServerPrefsWriter;
293326

294327
it("sends one hash-free patch and acknowledges lastSeen plus pending", async () => {
295328
const request = vi.fn<(method: string, params?: unknown) => Promise<unknown>>(async () => ({}));
@@ -298,6 +331,7 @@ describe("pushServerUiPrefs", () => {
298331

299332
pushServerUiPrefs(client, { themeMode: "dark" }, { afterCommit });
300333
await vi.waitFor(() => expect(afterCommit).toHaveBeenCalledOnce());
334+
expect(afterCommit).toHaveBeenCalledWith({ needsRefresh: false });
301335

302336
expect(request).toHaveBeenCalledExactlyOnceWith("config.patch", {
303337
raw: JSON.stringify({ ui: { prefs: { themeMode: "dark" } } }),
@@ -401,20 +435,19 @@ describe("pushServerUiPrefs", () => {
401435
const request = vi.fn<(method: string, params?: unknown) => Promise<unknown>>(async () => {
402436
throw new Error("socket closed");
403437
});
404-
const clientState = { request, gatewayUrl: "ws://gw", connected: false };
405-
const client = clientState as unknown as Parameters<typeof pushServerUiPrefs>[0];
438+
const client = createClient(request, "ws://gw", false);
406439

407440
pushServerUiPrefs(client, { locale: "de" });
408-
await vi.waitFor(() => expect(request).toHaveBeenCalledTimes(1));
441+
expect(request).not.toHaveBeenCalled();
409442
expect(JSON.parse(localStorage.getItem(pendingKey("ws://gw")) ?? "{}")).toEqual({
410443
locale: "de",
411444
});
412445

413-
clientState.connected = true;
446+
(client.state as { connected: boolean }).connected = true;
414447
request.mockResolvedValue({});
415448
flushServerUiPrefs(client);
416-
await vi.waitFor(() => expect(request).toHaveBeenCalledTimes(2));
417-
expect(localStorage.getItem(pendingKey("ws://gw"))).toBeNull();
449+
await vi.waitFor(() => expect(request).toHaveBeenCalledOnce());
450+
await vi.waitFor(() => expect(localStorage.getItem(pendingKey("ws://gw"))).toBeNull());
418451
});
419452

420453
it("supersedes a hung prior-connection request on same-client flush", async () => {
@@ -455,18 +488,23 @@ describe("pushServerUiPrefs", () => {
455488
await vi.waitFor(() => expect(localStorage.getItem(pendingKey("ws://gw"))).toBeNull());
456489
});
457490

458-
it("keeps pending shadow active during the post-commit refresh hook", async () => {
459-
const request = vi.fn<(method: string, params?: unknown) => Promise<unknown>>(async () => ({}));
460-
const client = createClient(request);
491+
it("reconciles the refreshed snapshot again after clearing its pending shadow", async () => {
492+
const refreshedSnapshot = configWithPrefs({ themeMode: "light" });
461493
patchSettings({ themeMode: "dark" });
462494
const onApplied = vi.fn();
495+
const request = vi.fn<(method: string, params?: unknown) => Promise<unknown>>(async () => {
496+
applyServerUiPrefs(refreshedSnapshot, { scope: "ws://gw", onApplied });
497+
return {};
498+
});
499+
const client = createClient(request);
463500

464501
pushServerUiPrefs(
465502
client,
466503
{ themeMode: "dark" },
467504
{
468-
afterCommit: () => {
469-
applyServerUiPrefs(configWithPrefs({ themeMode: "light" }), {
505+
afterCommit: ({ needsRefresh }) => {
506+
expect(needsRefresh).toBe(false);
507+
applyServerUiPrefs(refreshedSnapshot, {
470508
scope: "ws://gw",
471509
onApplied,
472510
});
@@ -476,8 +514,25 @@ describe("pushServerUiPrefs", () => {
476514
await vi.waitFor(() => expect(request).toHaveBeenCalledOnce());
477515
await vi.waitFor(() => expect(localStorage.getItem(pendingKey("ws://gw"))).toBeNull());
478516

479-
expect(onApplied).not.toHaveBeenCalled();
480-
expect(loadSettings().themeMode).toBe("dark");
517+
expect(onApplied).toHaveBeenCalledWith({ themeMode: "light" });
518+
expect(loadSettings().themeMode).toBe("light");
519+
});
520+
521+
it("requests a retry refresh when the post-mutation refresh failed", async () => {
522+
const afterCommit = vi.fn();
523+
const request = vi.fn<(method: string, params?: unknown) => Promise<unknown>>(async () => ({}));
524+
const client = createClient(request, "ws://gw", true, {
525+
ok: false,
526+
error: "config.get failed",
527+
});
528+
529+
pushServerUiPrefs(client, { themeMode: "dark" }, { afterCommit });
530+
531+
await vi.waitFor(() =>
532+
expect(afterCommit).toHaveBeenCalledWith({
533+
needsRefresh: true,
534+
}),
535+
);
481536
});
482537

483538
it("lets pending local intent shadow only its own server key", async () => {
@@ -649,9 +704,9 @@ describe("pushServerUiPrefs", () => {
649704
},
650705
);
651706
pushServerUiPrefs(createClient(offlineRequest, "ws://a", false), { themeMode: "dark" });
652-
await vi.waitFor(() => expect(offlineRequest).toHaveBeenCalledTimes(1));
707+
expect(offlineRequest).not.toHaveBeenCalled();
653708
pushServerUiPrefs(createClient(offlineRequest, "ws://b", false), { locale: "de" });
654-
await vi.waitFor(() => expect(offlineRequest).toHaveBeenCalledTimes(2));
709+
expect(offlineRequest).not.toHaveBeenCalled();
655710

656711
expect(JSON.parse(localStorage.getItem(pendingKey("ws://a")) ?? "{}")).toEqual({
657712
themeMode: "dark",
@@ -671,4 +726,53 @@ describe("pushServerUiPrefs", () => {
671726
});
672727
expect(localStorage.getItem(pendingKey("ws://a"))).not.toBeNull();
673728
});
729+
730+
it("re-adopts scope when a stable writer gains or changes its gateway client", async () => {
731+
const request = vi.fn<(method: string, params?: unknown) => Promise<unknown>>(async () => ({}));
732+
const writer = createClient(request, "", false);
733+
(writer.state as { client: GatewayBrowserClient | null }).client = null;
734+
735+
pushServerUiPrefs(writer, { locale: "de" });
736+
expect(JSON.parse(localStorage.getItem(pendingKey("")) ?? "{}")).toEqual({ locale: "de" });
737+
738+
const firstClient = {
739+
request,
740+
gatewayUrl: "ws://first",
741+
connected: true,
742+
} as unknown as GatewayBrowserClient;
743+
(writer.state as { client: GatewayBrowserClient | null; connected: boolean }).client =
744+
firstClient;
745+
(writer.state as { connected: boolean }).connected = true;
746+
flushServerUiPrefs(writer);
747+
await vi.waitFor(() => expect(localStorage.getItem(pendingKey("ws://first"))).toBeNull());
748+
expect(localStorage.getItem(pendingKey(""))).toBeNull();
749+
750+
localStorage.setItem(pendingKey("ws://second"), JSON.stringify({ themeMode: "dark" }));
751+
const secondClient = {
752+
request,
753+
gatewayUrl: "ws://second",
754+
connected: true,
755+
} as unknown as GatewayBrowserClient;
756+
(writer.state as { client: GatewayBrowserClient | null }).client = secondClient;
757+
flushServerUiPrefs(writer);
758+
759+
await vi.waitFor(() => expect(request).toHaveBeenCalledTimes(2));
760+
expect(request.mock.calls[1]?.[1]).toMatchObject({
761+
raw: JSON.stringify({ ui: { prefs: { themeMode: "dark" } } }),
762+
});
763+
});
764+
765+
it("recovers persisted pre-connection intent when the first gateway is adopted", async () => {
766+
localStorage.setItem(pendingKey(""), JSON.stringify({ locale: "de" }));
767+
const request = vi.fn<(method: string, params?: unknown) => Promise<unknown>>(async () => ({}));
768+
769+
flushServerUiPrefs(createClient(request, "ws://first"));
770+
771+
await vi.waitFor(() => expect(request).toHaveBeenCalledOnce());
772+
expect(request.mock.calls[0]?.[1]).toMatchObject({
773+
raw: JSON.stringify({ ui: { prefs: { locale: "de" } } }),
774+
});
775+
await vi.waitFor(() => expect(localStorage.getItem(pendingKey("ws://first"))).toBeNull());
776+
expect(localStorage.getItem(pendingKey(""))).toBeNull();
777+
});
674778
});

0 commit comments

Comments
 (0)