Skip to content

Commit 05681e7

Browse files
committed
refactor(ui): unify filtered session list ownership
1 parent a1b41d5 commit 05681e7

12 files changed

Lines changed: 931 additions & 937 deletions

‎ui/src/components/app-sidebar-session-catalog-live.ts‎

Lines changed: 90 additions & 152 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { asNullableRecord } from "@openclaw/normalization-core/record-coerce";
12
import type {
23
SessionCatalog,
34
SessionsCatalogHostEvent,
@@ -17,10 +18,6 @@ import { sessionCatalogHostKey } from "./app-sidebar-session-types.ts";
1718
export const SESSION_CATALOG_CHANGED_REFRESH_MS = 5_000;
1819
const SESSION_CATALOG_STABLE_REFRESH_MS = 30_000;
1920

20-
function sessionCatalogSnapshot(catalogs: readonly SessionCatalog[]): string {
21-
return JSON.stringify(catalogs);
22-
}
23-
2421
function sessionCatalogMaterialSnapshot(catalogs: readonly SessionCatalog[]): string {
2522
// Fast follow-up polls cover catalog/host/session identity sets, labels, connectivity,
2623
// and session title/status. Ordering and recency timestamps cannot pin the 5s cadence.
@@ -65,81 +62,37 @@ export function sessionCatalogListClient(
6562
return snapshot.client;
6663
}
6764

68-
async function requestSessionCatalogList(params: {
69-
client: GatewayBrowserClient;
70-
agentId: string;
71-
progressId: string;
72-
progressive: boolean;
73-
}): Promise<{ result: SessionsCatalogListResult; progressive: boolean }> {
74-
const baseParams = { agentId: params.agentId, limitPerHost: 40 };
75-
if (!params.progressive) {
76-
return {
77-
result: await params.client.request("sessions.catalog.list", baseParams),
78-
progressive: false,
79-
};
80-
}
81-
try {
82-
return {
83-
result: await params.client.request("sessions.catalog.list", {
84-
...baseParams,
85-
progressId: params.progressId,
86-
}),
87-
progressive: true,
88-
};
89-
} catch (error) {
90-
if (!isLegacyProgressIdRejection(error)) {
91-
throw error;
92-
}
93-
// Older Gateways advertise the list method but reject the additive field.
94-
// Retry once without streaming, then keep that connection on final pages.
95-
return {
96-
result: await params.client.request("sessions.catalog.list", baseParams),
97-
progressive: false,
98-
};
99-
}
100-
}
101-
10265
function isLegacyProgressIdRejection(error: unknown): boolean {
10366
if (!(error instanceof GatewayRequestError) || error.gatewayCode !== "INVALID_REQUEST") {
10467
return false;
10568
}
10669
const message = error.message.toLowerCase();
10770
return (
10871
message.includes("progressid") &&
109-
(message.includes("unexpected property") ||
110-
message.includes("additional property") ||
111-
message.includes("additional properties") ||
112-
message.includes("unknown property") ||
113-
message.includes("unrecognized property"))
72+
/(?:unexpected|unknown|unrecognized) property|additional propert(?:y|ies)/.test(message)
11473
);
11574
}
11675

11776
function isSessionsCatalogHostEvent(value: unknown): value is SessionsCatalogHostEvent {
118-
if (!value || typeof value !== "object") {
119-
return false;
120-
}
121-
const event = value as Record<string, unknown>;
122-
const catalog = event.catalog;
123-
if (!catalog || typeof catalog !== "object") {
124-
return false;
125-
}
126-
const catalogRecord = catalog as Record<string, unknown>;
127-
const hosts = Array.isArray(catalogRecord.hosts) ? catalogRecord.hosts : [];
128-
const host = hosts[0];
129-
return (
77+
const event = asNullableRecord(value);
78+
const catalog = asNullableRecord(event?.catalog);
79+
const hosts = Array.isArray(catalog?.hosts) ? catalog.hosts : [];
80+
const host = asNullableRecord(hosts[0]);
81+
return Boolean(
82+
event &&
83+
catalog &&
84+
host &&
13085
typeof event.progressId === "string" &&
13186
event.progressId.length > 0 &&
13287
typeof event.agentId === "string" &&
13388
event.agentId.length > 0 &&
134-
typeof catalogRecord.id === "string" &&
135-
typeof catalogRecord.label === "string" &&
136-
catalogRecord.capabilities !== null &&
137-
typeof catalogRecord.capabilities === "object" &&
89+
typeof catalog.id === "string" &&
90+
typeof catalog.label === "string" &&
91+
catalog.capabilities !== null &&
92+
typeof catalog.capabilities === "object" &&
13893
hosts.length === 1 &&
139-
host !== null &&
140-
typeof host === "object" &&
141-
typeof (host as Record<string, unknown>).hostId === "string" &&
142-
Array.isArray((host as Record<string, unknown>).sessions)
94+
typeof host.hostId === "string" &&
95+
Array.isArray(host.sessions),
14396
);
14497
}
14598

@@ -158,15 +111,16 @@ export class SessionCatalogLiveState {
158111
private progressSequence = 0;
159112
private readonly progressSequences = new Map<string, number>();
160113
private readonly hostProgressSequences = new Map<string, number>();
161-
private readonly hostIdsByCatalog = new Map<string, ReadonlySet<string>>();
114+
private knownHostKeys = new Set<string>();
162115
private readonly requestChangedHostKeys = new Set<string>();
163116
private readonly warnedRequestErrors = new Set<string>();
164117
private requestOwner: symbol | null = null;
165118

166-
cancelTimer() {
167-
if (this.timer !== null) {
168-
globalThis.clearTimeout(this.timer);
169-
this.timer = null;
119+
cancelTimer(timer: "timer" | "activationTimer" = "timer") {
120+
const handle = this[timer];
121+
if (handle !== null) {
122+
globalThis.clearTimeout(handle);
123+
this[timer] = null;
170124
}
171125
}
172126

@@ -176,7 +130,7 @@ export class SessionCatalogLiveState {
176130
this.requestOwner = null;
177131
this.progressSequences.clear();
178132
this.hostProgressSequences.clear();
179-
this.hostIdsByCatalog.clear();
133+
this.knownHostKeys.clear();
180134
this.requestChangedHostKeys.clear();
181135
this.presenceSignature = null;
182136
this.sawChange = false;
@@ -185,17 +139,15 @@ export class SessionCatalogLiveState {
185139
}
186140

187141
resetConnection() {
188-
this.clear();
189-
this.connectionEpoch += 1;
190-
this.progressive = true;
142+
this.retireConnection(true);
191143
}
192144

193145
retireConnection(reset = false): void {
146+
this.clear();
194147
if (reset) {
195-
this.resetConnection();
196-
return;
148+
this.connectionEpoch += 1;
149+
this.progressive = true;
197150
}
198-
this.clear();
199151
}
200152

201153
async requestList(
@@ -204,37 +156,50 @@ export class SessionCatalogLiveState {
204156
progressId: string,
205157
): Promise<SessionsCatalogListResult> {
206158
const connectionEpoch = this.connectionEpoch;
207-
const response = await requestSessionCatalogList({
208-
client,
209-
agentId,
210-
progressId,
211-
progressive: this.progressive,
212-
});
159+
const baseParams = { agentId, limitPerHost: 40 };
160+
let progressive = this.progressive;
161+
let result: SessionsCatalogListResult;
162+
try {
163+
result = await client.request("sessions.catalog.list", {
164+
...baseParams,
165+
...(progressive ? { progressId } : {}),
166+
});
167+
} catch (error) {
168+
if (!progressive || !isLegacyProgressIdRejection(error)) {
169+
throw error;
170+
}
171+
// Older Gateways advertise the list method but reject the additive field.
172+
// Retry once without streaming, then keep that connection on final pages.
173+
result = await client.request("sessions.catalog.list", baseParams);
174+
progressive = false;
175+
}
213176
if (connectionEpoch === this.connectionEpoch) {
214-
this.progressive = response.progressive;
177+
this.progressive = progressive;
215178
}
216-
return response.result;
179+
return result;
217180
}
218181

219182
mergeFinal(catalogs: SessionCatalog[], currentCatalogs: readonly SessionCatalog[]) {
220-
const current = new Map(currentCatalogs.map((catalog) => [catalog.id, catalog]));
221-
return catalogs.map((catalog) => {
222-
const currentHosts = new Map(
223-
current.get(catalog.id)?.hosts.map((host) => [host.hostId, host]) ?? [],
224-
);
225-
return {
226-
...catalog,
227-
hosts: catalog.hosts.map((host) => {
228-
const progressiveHost = currentHosts.get(host.hostId);
229-
const changed = this.requestChangedHostKeys.has(
230-
sessionCatalogHostKey(catalog.id, host.hostId),
231-
);
232-
return host.error && changed && progressiveHost && !progressiveHost.error
233-
? progressiveHost
234-
: host;
235-
}),
236-
};
237-
});
183+
const currentHosts = new Map(
184+
currentCatalogs.flatMap((catalog) =>
185+
catalog.hosts.map(
186+
(host) => [sessionCatalogHostKey(catalog.id, host.hostId), host] as const,
187+
),
188+
),
189+
);
190+
return catalogs.map((catalog) => ({
191+
...catalog,
192+
hosts: catalog.hosts.map((host) => {
193+
const hostKey = sessionCatalogHostKey(catalog.id, host.hostId);
194+
const progressiveHost = currentHosts.get(hostKey);
195+
return host.error &&
196+
this.requestChangedHostKeys.has(hostKey) &&
197+
progressiveHost &&
198+
!progressiveHost.error
199+
? progressiveHost
200+
: host;
201+
}),
202+
}));
238203
}
239204

240205
get refetching() {
@@ -307,58 +272,39 @@ export class SessionCatalogLiveState {
307272
params.hadCatalogs &&
308273
(this.sawChange ||
309274
params.previousMaterialSnapshot !== sessionCatalogMaterialSnapshot(params.catalogs));
310-
const finalCatalogIds = new Set(params.catalogs.map((catalog) => catalog.id));
311-
for (const [catalogId, previousHostIds] of this.hostIdsByCatalog) {
312-
if (finalCatalogIds.has(catalogId)) {
313-
continue;
314-
}
315-
for (const hostId of previousHostIds) {
316-
this.hostProgressSequences.set(
317-
sessionCatalogHostKey(catalogId, hostId),
318-
params.progressSequence,
319-
);
320-
}
321-
this.hostIdsByCatalog.delete(catalogId);
322-
}
275+
const finalHostKeys = new Set<string>();
323276
for (const catalog of params.catalogs) {
324-
const previousHostIds = this.hostIdsByCatalog.get(catalog.id) ?? new Set<string>();
325-
const finalHostIds = new Set(catalog.hosts.map((host) => host.hostId));
326-
for (const hostId of previousHostIds) {
327-
if (!finalHostIds.has(hostId)) {
328-
this.hostProgressSequences.set(
329-
sessionCatalogHostKey(catalog.id, hostId),
330-
params.progressSequence,
331-
);
332-
}
333-
}
334277
for (const host of catalog.hosts) {
278+
const key = sessionCatalogHostKey(catalog.id, host.hostId);
279+
finalHostKeys.add(key);
335280
if (host.error) {
336281
continue;
337282
}
338-
const key = sessionCatalogHostKey(catalog.id, host.hostId);
339283
this.hostProgressSequences.set(
340284
key,
341285
Math.max(this.hostProgressSequences.get(key) ?? -1, params.progressSequence),
342286
);
343287
}
344-
this.hostIdsByCatalog.set(catalog.id, finalHostIds);
345288
}
289+
for (const hostKey of this.knownHostKeys) {
290+
if (!finalHostKeys.has(hostKey)) {
291+
this.hostProgressSequences.set(hostKey, params.progressSequence);
292+
}
293+
}
294+
this.knownHostKeys = finalHostKeys;
346295
}
347296

348297
observePresence(payload: unknown): boolean {
349-
const presence =
350-
payload && typeof payload === "object"
351-
? (payload as { presence?: unknown }).presence
352-
: undefined;
298+
const presence = asNullableRecord(payload)?.presence;
353299
if (!Array.isArray(presence)) {
354300
return false;
355301
}
356302
const states = new Map<string, "connected" | "offline">();
357303
for (const entry of presence) {
358-
if (!entry || typeof entry !== "object") {
304+
const record = asNullableRecord(entry);
305+
if (!record) {
359306
continue;
360307
}
361-
const record = entry as Record<string, unknown>;
362308
const rawId = typeof record.deviceId === "string" ? record.deviceId : record.instanceId;
363309
const id = typeof rawId === "string" ? rawId.trim().toLowerCase() : "";
364310
const mode = typeof record.mode === "string" ? record.mode.trim().toLowerCase() : "";
@@ -426,7 +372,7 @@ export class SessionCatalogLiveState {
426372
: catalog,
427373
);
428374
}
429-
if (sessionCatalogSnapshot(catalogs) === sessionCatalogSnapshot(params.catalogs)) {
375+
if (JSON.stringify(catalogs) === JSON.stringify(params.catalogs)) {
430376
return null;
431377
}
432378
const materialChange =
@@ -464,10 +410,7 @@ export class SessionCatalogLiveState {
464410
}
465411

466412
cancelActivation() {
467-
if (this.activationTimer !== null) {
468-
globalThis.clearTimeout(this.activationTimer);
469-
this.activationTimer = null;
470-
}
413+
this.cancelTimer("activationTimer");
471414
}
472415

473416
cancelScheduledRefreshes() {
@@ -536,11 +479,10 @@ export async function refreshSessionCatalogsLive(params: {
536479
if (!revisionIsCurrent()) {
537480
return;
538481
}
539-
const revisedCatalogIds = new Set([
540-
...params.catalogs().map((catalog) => catalog.id),
541-
...catalogs.map((catalog) => catalog.id),
542-
]);
543-
params.applyFinal(catalogs, revisedCatalogIds);
482+
params.applyFinal(
483+
catalogs,
484+
new Set([...params.catalogs(), ...catalogs].map((catalog) => catalog.id)),
485+
);
544486
live.markFinal({ catalogs, hadCatalogs, previousMaterialSnapshot, progressSequence });
545487
} catch (error) {
546488
// A transient poll failure must not collapse already visible or expanded pages.
@@ -555,17 +497,13 @@ export async function refreshSessionCatalogsLive(params: {
555497
live.requestGeneration = null;
556498
}
557499
if (ownsRequest && requestIsCurrent() && params.connected()) {
558-
const pending = live.refreshPending;
500+
const delayMs = live.refreshPending
501+
? 0
502+
: live.sawChange
503+
? SESSION_CATALOG_CHANGED_REFRESH_MS
504+
: SESSION_CATALOG_STABLE_REFRESH_MS;
559505
live.refreshPending = false;
560-
live.schedule(
561-
pending
562-
? 0
563-
: live.sawChange
564-
? SESSION_CATALOG_CHANGED_REFRESH_MS
565-
: SESSION_CATALOG_STABLE_REFRESH_MS,
566-
params.connected(),
567-
params.refresh,
568-
);
506+
live.schedule(delayMs, params.connected(), params.refresh);
569507
}
570508
}
571509
}

‎ui/src/components/app-sidebar-session-catalog-state.ts‎

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,7 @@ import type {
77
import { GatewayRequestError, type GatewayBrowserClient } from "../api/gateway.ts";
88
import { sessionCatalogHostKey } from "./app-sidebar-session-types.ts";
99

10-
type SessionCatalogError = NonNullable<SessionCatalog["error"]>;
11-
12-
export function sessionCatalogRequestError(error: unknown): SessionCatalogError {
10+
export function sessionCatalogRequestError(error: unknown): NonNullable<SessionCatalog["error"]> {
1311
return {
1412
code: error instanceof GatewayRequestError ? error.gatewayCode : "UNAVAILABLE",
1513
message: error instanceof Error ? error.message : String(error),
@@ -31,12 +29,11 @@ export function preserveExpandedCatalogHost(
3129
if (!previous) {
3230
return freshHost;
3331
}
34-
const { sessions, nextCursor, ...previousDetails } = previous;
3532
const { sessions: _freshSessions, nextCursor: _freshNextCursor, ...freshDetails } = freshHost;
33+
const { nextCursor, ...previousDetails } = previous;
3634
return {
3735
...previousDetails,
3836
...freshDetails,
39-
sessions,
4037
...(nextCursor !== undefined ? { nextCursor } : {}),
4138
};
4239
}

0 commit comments

Comments
 (0)