Skip to content

Commit 59cd041

Browse files
authored
refactor(ui): centralize gateway page lifecycle (#118243)
* refactor(ui): centralize gateway page lifecycle * fix(ui): align gateway controller state types * fix(ui): satisfy lifecycle lint boundaries * fix(ui): keep usage refresh reason private * test(ui): cover usage refresh policy surface
1 parent a613ec3 commit 59cd041

21 files changed

Lines changed: 1241 additions & 1161 deletions

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

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ import {
2525
} from "./tools-effective.ts";
2626

2727
export type { AgentsPanel } from "./panels.ts";
28+
export { watchAgentScope } from "./watch-agent-scope.ts";
2829

2930
export type AgentsState = {
3031
client: GatewayBrowserClient | null;
@@ -50,6 +51,8 @@ export type AgentsState = {
5051
agentsPanel?: AgentsPanel;
5152
};
5253

54+
type AgentToolsState = Omit<AgentsState, "agentsLoading" | "agentsError">;
55+
5356
type AgentsConfigCapability = {
5457
readonly state: { configFormDirty: boolean };
5558
save: () => Promise<boolean>;
@@ -99,7 +102,7 @@ async function loadAgentFilesList(
99102
return client.request<AgentsFilesListResult | null>("agents.files.list", { agentId });
100103
}
101104

102-
function hasSelectedAgentMismatch(state: AgentsState, agentId: string): boolean {
105+
function hasSelectedAgentMismatch(state: AgentToolsState, agentId: string): boolean {
103106
return Boolean(state.agentsSelectedId && state.agentsSelectedId !== agentId);
104107
}
105108

@@ -112,7 +115,7 @@ function resolveToolsErrorMessage(
112115
: String(err);
113116
}
114117

115-
export async function loadToolsCatalog(state: AgentsState, agentId: string) {
118+
export async function loadToolsCatalog(state: AgentToolsState, agentId: string) {
116119
const resolvedAgentId = agentId.trim();
117120
const client = state.client;
118121
if (
@@ -166,7 +169,7 @@ export {
166169
};
167170

168171
export async function loadToolsEffective(
169-
state: AgentsState,
172+
state: AgentToolsState,
170173
params: { agentId: string; sessionKey: string },
171174
) {
172175
const client = state.client;
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
import { describe, expect, it, vi } from "vitest";
2+
import { watchAgentScope } from "./watch-agent-scope.ts";
3+
4+
function selection(scopeId: string | null) {
5+
const listeners = new Set<(state: { scopeId: string | null }) => void>();
6+
const state = { scopeId };
7+
return {
8+
source: {
9+
state,
10+
subscribe(listener: (next: { scopeId: string | null }) => void) {
11+
listeners.add(listener);
12+
return () => listeners.delete(listener);
13+
},
14+
},
15+
publish(nextScopeId: string | null) {
16+
state.scopeId = nextScopeId;
17+
for (const listener of listeners) {
18+
listener(state);
19+
}
20+
},
21+
};
22+
}
23+
24+
describe("watchAgentScope", () => {
25+
it("suppresses the initial scope and duplicate publications", () => {
26+
const current = selection("main");
27+
const onChange = vi.fn();
28+
const watch = watchAgentScope(onChange);
29+
const cleanup = watch(current.source);
30+
31+
current.publish("main");
32+
current.publish("writer");
33+
34+
expect(onChange).toHaveBeenCalledOnce();
35+
expect(onChange).toHaveBeenCalledWith("writer", "main");
36+
cleanup();
37+
});
38+
39+
it("keeps the observed scope across source replacement", () => {
40+
const first = selection("main");
41+
const replacement = selection("writer");
42+
const onChange = vi.fn();
43+
const watch = watchAgentScope(onChange);
44+
watch(first.source)();
45+
46+
watch(replacement.source)();
47+
48+
expect(onChange).toHaveBeenCalledWith("writer", "main");
49+
});
50+
});
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
type AgentScopeSelection = {
2+
readonly state: { scopeId: string | null };
3+
subscribe: (listener: (state: { scopeId: string | null }) => void) => () => void;
4+
};
5+
6+
/** Watches semantic scope changes across selection-source replacements. */
7+
export function watchAgentScope(
8+
onChange: (scopeId: string | null, previousScopeId: string | null) => void,
9+
): (selection: AgentScopeSelection) => () => void {
10+
let observedScopeId: string | null | undefined;
11+
return (selection) => {
12+
const sync = () => {
13+
const nextScopeId = selection.state.scopeId;
14+
if (observedScopeId === undefined) {
15+
observedScopeId = nextScopeId;
16+
return;
17+
}
18+
if (nextScopeId === observedScopeId) {
19+
return;
20+
}
21+
const previousScopeId = observedScopeId;
22+
observedScopeId = nextScopeId;
23+
onChange(nextScopeId, previousScopeId);
24+
};
25+
sync();
26+
return selection.subscribe(sync);
27+
};
28+
}
Lines changed: 176 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,176 @@
1+
import type { ReactiveController, ReactiveControllerHost } from "lit";
2+
import { describe, expect, it, vi } from "vitest";
3+
import type { GatewayBrowserClient } from "../api/gateway.ts";
4+
import type { ApplicationGateway, ApplicationGatewaySnapshot } from "../app/context.ts";
5+
import { GatewayPageController } from "./gateway-page-controller.ts";
6+
7+
function snapshot(
8+
client: GatewayBrowserClient | null,
9+
phase: ApplicationGatewaySnapshot["phase"],
10+
): ApplicationGatewaySnapshot {
11+
return {
12+
client,
13+
phase,
14+
offlineStable: false,
15+
hello: null,
16+
canvasPluginSurfaceUrl: null,
17+
assistantAgentId: null,
18+
sessionKey: "agent:main:main",
19+
lastError: null,
20+
lastErrorCode: null,
21+
};
22+
}
23+
24+
function createGateway(initial: ApplicationGatewaySnapshot) {
25+
let current = initial;
26+
const listeners = new Set<(value: ApplicationGatewaySnapshot) => void>();
27+
const gateway = {
28+
get snapshot() {
29+
return current;
30+
},
31+
subscribe(listener: (value: ApplicationGatewaySnapshot) => void) {
32+
listeners.add(listener);
33+
return () => listeners.delete(listener);
34+
},
35+
} as unknown as ApplicationGateway;
36+
return {
37+
gateway,
38+
publish(next: ApplicationGatewaySnapshot) {
39+
current = next;
40+
for (const listener of listeners) {
41+
listener(next);
42+
}
43+
},
44+
};
45+
}
46+
47+
function createHost() {
48+
const controllers: ReactiveController[] = [];
49+
const requestUpdate = vi.fn();
50+
const host = {
51+
addController(controller: ReactiveController) {
52+
controllers.push(controller);
53+
},
54+
removeController() {},
55+
requestUpdate,
56+
updateComplete: Promise.resolve(true),
57+
} satisfies ReactiveControllerHost;
58+
return {
59+
host,
60+
requestUpdate,
61+
connect() {
62+
for (const controller of controllers) {
63+
controller.hostConnected?.();
64+
}
65+
},
66+
update() {
67+
for (const controller of controllers) {
68+
controller.hostUpdate?.();
69+
}
70+
},
71+
disconnect() {
72+
for (const controller of controllers) {
73+
controller.hostDisconnected?.();
74+
}
75+
},
76+
};
77+
}
78+
79+
describe("GatewayPageController", () => {
80+
it("binds the current source and retires work across same-client reconnects", () => {
81+
const client = {} as GatewayBrowserClient;
82+
const source = createGateway(snapshot(client, "connected"));
83+
const host = createHost();
84+
const identityChanges = vi.fn();
85+
const invalidations = vi.fn();
86+
const ensureInitialData = vi.fn();
87+
const controller = new GatewayPageController(host.host, {
88+
getGateway: () => source.gateway,
89+
onIdentityChange: identityChanges,
90+
invalidateRequests: invalidations,
91+
ensureInitialData,
92+
});
93+
94+
host.connect();
95+
const first = controller.capture();
96+
expect(controller.client).toBe(client);
97+
expect(controller.connected).toBe(true);
98+
expect(first).not.toBeNull();
99+
100+
source.publish(snapshot(client, "reconnecting"));
101+
expect(first && controller.isCurrent(first)).toBe(false);
102+
expect(controller.capture()).toBeNull();
103+
104+
source.publish(snapshot(client, "connected"));
105+
expect(controller.capture()).not.toBeNull();
106+
expect(identityChanges).not.toHaveBeenCalled();
107+
expect(invalidations).toHaveBeenCalledTimes(2);
108+
expect(ensureInitialData).toHaveBeenCalledTimes(2);
109+
});
110+
111+
it("treats an equivalent replacement source as a new identity", () => {
112+
const client = {} as GatewayBrowserClient;
113+
const first = createGateway(snapshot(client, "connected"));
114+
const second = createGateway(snapshot(client, "connected"));
115+
let gateway = first.gateway;
116+
const host = createHost();
117+
const identityChanges = vi.fn();
118+
const controller = new GatewayPageController(host.host, {
119+
getGateway: () => gateway,
120+
onIdentityChange: identityChanges,
121+
});
122+
host.connect();
123+
const scope = controller.capture();
124+
125+
gateway = second.gateway;
126+
host.update();
127+
128+
expect(scope && controller.isCurrent(scope)).toBe(false);
129+
expect(identityChanges).toHaveBeenLastCalledWith(
130+
expect.objectContaining({ sourceChanged: true, identityChanged: true }),
131+
);
132+
});
133+
134+
it("checks route data by exact source and snapshot identity", () => {
135+
const current = createGateway(snapshot({} as GatewayBrowserClient, "connected"));
136+
const host = createHost();
137+
const controller = new GatewayPageController(host.host, {
138+
getGateway: () => current.gateway,
139+
});
140+
host.connect();
141+
142+
expect(
143+
controller.isRouteDataCurrent({
144+
gateway: current.gateway,
145+
gatewaySnapshot: current.gateway.snapshot,
146+
}),
147+
).toBe(true);
148+
expect(
149+
controller.isRouteDataCurrent({
150+
gateway: current.gateway,
151+
gatewaySnapshot: { ...current.gateway.snapshot },
152+
}),
153+
).toBe(false);
154+
});
155+
156+
it("can reconnect after the host detaches", () => {
157+
const current = createGateway(snapshot({} as GatewayBrowserClient, "connected"));
158+
const host = createHost();
159+
const identityChanges = vi.fn();
160+
const controller = new GatewayPageController(host.host, {
161+
getGateway: () => current.gateway,
162+
onIdentityChange: identityChanges,
163+
});
164+
host.connect();
165+
const stale = controller.capture();
166+
167+
host.disconnect();
168+
expect(stale && controller.isCurrent(stale)).toBe(false);
169+
expect(controller.capture()).toBeNull();
170+
expect(identityChanges).not.toHaveBeenCalled();
171+
172+
host.connect();
173+
expect(controller.capture()).not.toBeNull();
174+
expect(identityChanges).toHaveBeenCalledTimes(1);
175+
});
176+
});

0 commit comments

Comments
 (0)