Skip to content

Commit 58a3679

Browse files
authored
fix(ui): keep reconnects, browser tabs, and localized search consistent (#115221)
* fix(ui): fence stale gateway and browser lifecycles * test(ui): restore history after agent tool navigation
1 parent a8f088e commit 58a3679

8 files changed

Lines changed: 199 additions & 14 deletions

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

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -238,6 +238,15 @@ describe("settingsSearchTextMatches", () => {
238238
expect(settingsSearchTextMatches("MCP", "cp")).toBe(false);
239239
expect(settingsSearchTextMatches("外観設定", "設定")).toBe(true);
240240
});
241+
242+
it.each([
243+
["Cámara", "Ca\u0301mara"],
244+
["Ca\u0301mara", "Cámara"],
245+
["Notificación", "Notificacio\u0301n"],
246+
["Notificacio\u0301n", "Notificación"],
247+
])("matches canonically equivalent setting text %j against %j", (value, query) => {
248+
expect(settingsSearchTextMatches(value, query)).toBe(true);
249+
});
241250
});
242251

243252
describe("formatDocumentTitle", () => {

‎ui/src/app-navigation.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -161,8 +161,8 @@ function settingsSearchHasWordPrefix(value: string, query: string): boolean {
161161
}
162162

163163
export function settingsSearchTextMatches(value: string, query: string): boolean {
164-
const candidate = normalizeLowercaseStringOrEmpty(value);
165-
const normalizedQuery = normalizeLowercaseStringOrEmpty(query);
164+
const candidate = normalizeLowercaseStringOrEmpty(value).normalize("NFC");
165+
const normalizedQuery = normalizeLowercaseStringOrEmpty(query).normalize("NFC");
166166
if (!normalizedQuery) {
167167
return false;
168168
}

‎ui/src/app/gateway-store.test.ts‎

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -356,6 +356,66 @@ describe("createApplicationGateway connection phase", () => {
356356
expect(gateway.snapshot.phase).toBe("reconnecting");
357357
});
358358

359+
it("ignores presence and event-log callbacks from superseded clients", () => {
360+
const { gateway, current } = createStore();
361+
gateway.start();
362+
current().opts.onHello?.(HELLO);
363+
const stale = current();
364+
365+
gateway.connect();
366+
const active = current();
367+
active.opts.onHello?.({
368+
...HELLO,
369+
snapshot: {
370+
presence: [
371+
{
372+
instanceId: active.instanceId,
373+
user: { id: "current-user", name: "Current user" },
374+
},
375+
],
376+
},
377+
});
378+
379+
stale.opts.onEvent?.({
380+
type: "event",
381+
event: "presence",
382+
payload: {
383+
presence: [
384+
{
385+
instanceId: active.instanceId,
386+
user: { id: "stale-user", name: "Stale user" },
387+
},
388+
],
389+
},
390+
seq: 1,
391+
stateVersion: { presence: 1, health: 1 },
392+
});
393+
394+
expect(gateway.snapshot.selfUser).toEqual({ id: "current-user", name: "Current user" });
395+
expect(gateway.eventLog).toEqual([]);
396+
397+
active.opts.onEvent?.({
398+
type: "event",
399+
event: "presence",
400+
payload: {
401+
presence: [
402+
{
403+
instanceId: active.instanceId,
404+
user: { id: "current-user", name: "Updated current user" },
405+
},
406+
],
407+
},
408+
seq: 2,
409+
stateVersion: { presence: 2, health: 1 },
410+
});
411+
412+
expect(gateway.snapshot.selfUser).toEqual({
413+
id: "current-user",
414+
name: "Updated current user",
415+
});
416+
expect(gateway.eventLog).toHaveLength(1);
417+
});
418+
359419
it("projects only this browser connection's optional presence identity", () => {
360420
const { gateway, current } = createStore();
361421
gateway.start();

‎ui/src/app/gateway-store.ts‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -403,7 +403,13 @@ export function createApplicationGateway(
403403
});
404404
connect();
405405
},
406-
onEvent: recordGatewayEvent,
406+
onEvent: (event) => {
407+
// A replaced socket can still deliver queued events; never let it
408+
// project presence or history into the current gateway connection.
409+
if (client === nextClient) {
410+
recordGatewayEvent(event);
411+
}
412+
},
407413
});
408414
client = nextClient;
409415
syncClientEvents(nextClient);

‎ui/src/components/browser/browser-panel-controller-snapshot-races.test.ts‎

Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,14 +5,106 @@ import {
55
createBrowserPanelTestMetrics,
66
createBrowserPanelTestTab,
77
createDeferred,
8+
createView,
89
flushBrowserResponses,
910
setupBrowserPanelTestCleanup,
1011
stubScreenshotMedia,
12+
TestBrowserPanelHost,
1113
} from "./browser-panel-controller-test-support.ts";
14+
import { BrowserPanelController } from "./browser-panel-controller.ts";
1215

1316
setupBrowserPanelTestCleanup();
1417

1518
describe("BrowserPanelController superseded tab snapshots", () => {
19+
it.each([true, false])(
20+
"never reselects a closed active tab when refreshing the remaining tabs fails (fallback: %s)",
21+
async (hasFallback) => {
22+
stubScreenshotMedia();
23+
const activeUrl = "https://example.test/active";
24+
const fallbackUrl = "https://example.test/fallback";
25+
const { client, request } = createBrowserClient(async (envelope) => {
26+
if (envelope.method === "DELETE" && envelope.path === "/tabs/active-tab") {
27+
return { ok: true };
28+
}
29+
if (envelope.path === "/tabs") {
30+
throw new Error("Tab refresh failed after the active tab was closed");
31+
}
32+
if (envelope.path === "/screenshot" && envelope.body?.targetId === "fallback-tab") {
33+
return { path: "/fresh.png", targetId: "raw-fallback", url: fallbackUrl };
34+
}
35+
if (envelope.path === "/act") {
36+
return createBrowserPanelTestMetrics(fallbackUrl, "Fallback");
37+
}
38+
throw new Error(`Unexpected browser route: ${envelope.method} ${envelope.path}`);
39+
});
40+
const controller = createBrowserPanelTestController(client, "active-tab", activeUrl);
41+
controller.tabs = [
42+
{ id: "active-tab", targetId: "raw-active", title: "Active", url: activeUrl },
43+
...(hasFallback
44+
? [
45+
{
46+
id: "fallback-tab",
47+
targetId: "raw-fallback",
48+
title: "Fallback",
49+
url: fallbackUrl,
50+
},
51+
]
52+
: []),
53+
];
54+
55+
await controller.closeTab("active-tab");
56+
57+
expect(controller.tabs.map((tab) => tab.id)).toEqual(hasFallback ? ["fallback-tab"] : []);
58+
expect(controller.activeTargetId).toBe(hasFallback ? "fallback-tab" : null);
59+
expect(controller.view?.targetId ?? null).toBe(hasFallback ? "fallback-tab" : null);
60+
expect(controller.loading).toBe(false);
61+
expect(
62+
request.mock.calls.some(([, envelope]) => {
63+
const browserRequest = envelope as { path?: string; body?: { targetId?: string } };
64+
return (
65+
browserRequest.path === "/screenshot" && browserRequest.body?.targetId === "active-tab"
66+
);
67+
}),
68+
).toBe(false);
69+
},
70+
);
71+
72+
it("rejects old-gateway snapshots before the replacement client synchronizes", async () => {
73+
const activeUrl = "https://example.test/active";
74+
const snapshot = createDeferred<{
75+
running: boolean;
76+
tabs: ReturnType<typeof createBrowserPanelTestTab>[];
77+
}>();
78+
const old = createBrowserClient(async (envelope) => {
79+
if (envelope.path === "/tabs") {
80+
return await snapshot.promise;
81+
}
82+
throw new Error(`Unexpected old browser route: ${envelope.path}`);
83+
});
84+
const replacement = createBrowserClient(async (envelope) => {
85+
throw new Error(`Unexpected replacement browser route: ${envelope.path}`);
86+
});
87+
const host = new TestBrowserPanelHost(old.client);
88+
const controller = new BrowserPanelController(host);
89+
const originalView = createView("active-tab", activeUrl);
90+
controller.activeTargetId = "active-tab";
91+
controller.view = originalView;
92+
93+
const refresh = controller.refreshAll();
94+
await flushBrowserResponses();
95+
host.client = replacement.client;
96+
snapshot.resolve({
97+
running: true,
98+
tabs: [createBrowserPanelTestTab("active-tab", activeUrl, "Active")],
99+
});
100+
await refresh;
101+
102+
expect(controller.running).toBeNull();
103+
expect(controller.tabs).toEqual([]);
104+
expect(controller.view).toBe(originalView);
105+
expect(replacement.request).not.toHaveBeenCalled();
106+
});
107+
16108
it.each(["before", "after"] as const)(
17109
"settles loading when a superseded refresh fails %s a background-close snapshot",
18110
async (olderFailureOrder) => {

‎ui/src/components/browser/browser-panel-controller.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -435,6 +435,12 @@ export class BrowserPanelController implements ReactiveController {
435435
}
436436
return;
437437
}
438+
// DELETE already committed; a failed tab snapshot must not resurrect its
439+
// target or make the next screenshot address a tab that no longer exists.
440+
this.setState(
441+
"tabs",
442+
this.tabs.filter((tab) => tab.id !== targetId),
443+
);
438444
const snapshot = await this.refreshTabsOnly(client, () =>
439445
this.operations.isLive(epoch, client),
440446
);

‎ui/src/components/browser/browser-panel-operation-ownership.ts‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ export interface BrowserPanelControllerHost extends ReactiveControllerHost {
1818
}
1919

2020
type BrowserPanelInvocation = {
21+
readonly client: GatewayBrowserClient;
2122
epoch: number;
2223
readonly id: number;
2324
readonly mutationId: number;
@@ -88,6 +89,7 @@ export class BrowserPanelOperationOwnership {
8889
this.requestedCapture += 1;
8990
this.capturePending = false;
9091
const invocation: BrowserPanelInvocation = {
92+
client,
9193
epoch: this.lifecycleEpoch,
9294
id: ++this.requestedMutation,
9395
mutationId: this.requestedMutation,
@@ -156,6 +158,7 @@ export class BrowserPanelOperationOwnership {
156158
beginSnapshot(client: GatewayBrowserClient): BrowserPanelInvocation {
157159
const mutationId = this.requestedMutation;
158160
const invocation: BrowserPanelInvocation = {
161+
client,
159162
epoch: this.lifecycleEpoch,
160163
id: ++this.requestedSnapshot,
161164
mutationId,
@@ -173,7 +176,7 @@ export class BrowserPanelOperationOwnership {
173176
snapshotTargetId: string | null,
174177
): boolean {
175178
if (
176-
!this.isLive(invocation.epoch) ||
179+
!this.isLive(invocation.epoch, invocation.client) ||
177180
invocation.id < this.acceptedSnapshot ||
178181
(!invocation.isCurrent() && snapshotTargetId !== currentTargetId)
179182
) {
@@ -185,7 +188,10 @@ export class BrowserPanelOperationOwnership {
185188

186189
/** Older snapshots may capture the same tab unless a user mutation owns it. */
187190
canCaptureSnapshot(invocation: BrowserPanelInvocation): boolean {
188-
return this.isLive(invocation.epoch) && invocation.mutationId === this.requestedMutation;
191+
return (
192+
this.isLive(invocation.epoch, invocation.client) &&
193+
invocation.mutationId === this.requestedMutation
194+
);
189195
}
190196

191197
/** A superseded open may reconcile its created tab, but never own the selected view. */

‎ui/src/pages/agents/panels-tools-skills.browser.test.ts‎

Lines changed: 15 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -421,15 +421,21 @@ describe("agents tools panel (browser)", () => {
421421
expect(group.open).toBe(false);
422422
expect(tool.open).toBe(false);
423423

424-
chip.click();
425-
await new Promise((resolve) => {
426-
requestAnimationFrame(resolve);
427-
});
428-
429-
expect(group.open).toBe(true);
430-
expect(tool.open).toBe(true);
431-
432-
container.remove();
424+
const previousUrl = `${window.location.pathname}${window.location.search}${window.location.hash}`;
425+
try {
426+
chip.click();
427+
await new Promise((resolve) => {
428+
requestAnimationFrame(resolve);
429+
});
430+
431+
expect(group.open).toBe(true);
432+
expect(tool.open).toBe(true);
433+
} finally {
434+
// Hash links mutate shared jsdom history; restore the actual prior URL
435+
// so a later Settings route never inherits this tool-card deep link.
436+
window.history.replaceState({}, "", previousUrl);
437+
container.remove();
438+
}
433439
});
434440
});
435441

0 commit comments

Comments
 (0)