Skip to content

Commit 72bbe6f

Browse files
committed
fix(ui): validate session catalog agent
1 parent a2eceb9 commit 72bbe6f

10 files changed

Lines changed: 508 additions & 32 deletions

File tree

‎ui/src/app/agent-selection.test.ts‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,30 @@ describe("agent selection", () => {
9898
expect(selection.state).toEqual({ selectedId: "ops", scopeId: "ops" });
9999
});
100100

101+
it("adopts the hello default published by the same gateway client", () => {
102+
const gateway = createGateway(null);
103+
const selection = createAgentSelectionCapability(gateway.gateway, createRoster().roster);
104+
const client = { request() {} } as unknown as GatewayBrowserClient;
105+
106+
gateway.publish({ client, assistantAgentId: null });
107+
expect(selection.state).toEqual({ selectedId: null, scopeId: null });
108+
109+
gateway.publish({ client, assistantAgentId: "Roboclaw" });
110+
expect(selection.state).toEqual({ selectedId: "roboclaw", scopeId: "roboclaw" });
111+
});
112+
113+
it("does not replace an explicit pre-hello selection", () => {
114+
const gateway = createGateway(null);
115+
const selection = createAgentSelectionCapability(gateway.gateway, createRoster().roster);
116+
const client = { request() {} } as unknown as GatewayBrowserClient;
117+
118+
gateway.publish({ client, assistantAgentId: null });
119+
selection.set("Research");
120+
gateway.publish({ client, assistantAgentId: "Roboclaw" });
121+
122+
expect(selection.state).toEqual({ selectedId: "research", scopeId: "research" });
123+
});
124+
101125
it("self-heals an unknown cold-load selection to the roster default", () => {
102126
const gateway = createGateway("Main");
103127
const roster = createRoster();

‎ui/src/app/agent-selection.ts‎

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,7 @@ export function createAgentSelectionCapability(
6161
scopeId: resolveScopeId(initialSelectedId),
6262
};
6363
let client = gateway.snapshot.client;
64+
let assistantAgentId = initialId;
6465
const listeners = new Set<(next: AgentSelectionState) => void>();
6566

6667
const publish = (next: AgentSelectionState) => {
@@ -79,10 +80,16 @@ export function createAgentSelectionCapability(
7980
};
8081

8182
gateway.subscribe((next) => {
82-
if (next.client !== client) {
83-
client = next.client;
84-
const selectedId = next.assistantAgentId ? normalizeAgentId(next.assistantAgentId) : null;
85-
publish({ selectedId, scopeId: selectedId });
83+
const nextAssistantAgentId = next.assistantAgentId
84+
? normalizeAgentId(next.assistantAgentId)
85+
: null;
86+
const clientChanged = next.client !== client;
87+
const assistantChanged = nextAssistantAgentId !== assistantAgentId;
88+
const followedPreviousDefault = state.selectedId === assistantAgentId;
89+
client = next.client;
90+
assistantAgentId = nextAssistantAgentId;
91+
if (clientChanged || (assistantChanged && (!state.selectedId || followedPreviousDefault))) {
92+
publish({ selectedId: nextAssistantAgentId, scopeId: nextAssistantAgentId });
8693
}
8794
});
8895
roster.subscribe(() => publish(state));

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

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -135,6 +135,8 @@ describe("createApplicationGateway connection phase", () => {
135135
snapshot: { sessionDefaults: { defaultAgentId: "roboclaw" } },
136136
});
137137
expect(gateway.snapshot.assistantAgentId).toBe("roboclaw");
138+
gateway.stop();
139+
expect(gateway.snapshot.assistantAgentId).toBeNull();
138140
});
139141

140142
it("publishes the hello canvas URL synchronously and clears it on disconnect", () => {

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

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -333,7 +333,8 @@ export function createApplicationGateway(
333333
phase: "connected",
334334
hello,
335335
canvasPluginSurfaceUrl,
336-
assistantAgentId: sessionDefaults?.defaultAgentId ?? null,
336+
// Trim guards a whitespace-only defaultId from becoming a truthy selection.
337+
assistantAgentId: sessionDefaults?.defaultAgentId?.trim() || null,
337338
sessionKey,
338339
lastError: null,
339340
lastErrorCode: null,
@@ -399,6 +400,7 @@ export function createApplicationGateway(
399400
phase: everConnected ? "reconnecting" : "connecting",
400401
hello: null,
401402
canvasPluginSurfaceUrl: null,
403+
assistantAgentId: null,
402404
selfUser: null,
403405
sessionKey: nextSessionKey,
404406
lastError: null,
@@ -446,6 +448,7 @@ export function createApplicationGateway(
446448
offlineStable: false,
447449
hello: null,
448450
canvasPluginSurfaceUrl: null,
451+
assistantAgentId: null,
449452
selfUser: null,
450453
lastError: null,
451454
lastErrorCode: null,

‎ui/src/components/session-data-controller-catalog.ts‎

Lines changed: 55 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import type {
55
import type { GatewayBrowserClient } from "../api/gateway.ts";
66
import type { RouteId } from "../app-route-paths.ts";
77
import type { ApplicationContext } from "../app/context.ts";
8+
import { normalizeAgentId } from "../lib/sessions/session-key.ts";
89
import {
910
refreshSessionCatalogsLive,
1011
SESSION_CATALOG_CHANGED_REFRESH_MS,
@@ -66,12 +67,13 @@ export function visibleSessionCatalogClient(
6667

6768
export function synchronizeSessionCatalogAgent(
6869
owner: SessionCatalogDataOwner,
69-
agentId: string,
70+
agentId: string | null,
7071
): void {
71-
if (agentId === owner.sessionCatalogAgentId) {
72+
const nextAgentId = resolveSessionCatalogAgentId(owner, agentId);
73+
if (nextAgentId === owner.sessionCatalogAgentId) {
7274
return;
7375
}
74-
owner.sessionCatalogAgentId = agentId;
76+
owner.sessionCatalogAgentId = nextAgentId;
7577
owner.sessionCatalogGeneration += 1;
7678
owner.sessionCatalogRevision += 1;
7779
owner.sessionCatalogLive.clear();
@@ -86,12 +88,52 @@ export function synchronizeSessionCatalogAgent(
8688
owner.requestSessionDataUpdate();
8789
}
8890

91+
function resolveSessionCatalogAgentId(
92+
owner: SessionCatalogDataOwner,
93+
candidateAgentId: string | null | undefined = owner.expandedAgentId(),
94+
): string | null {
95+
const context = owner.context;
96+
const gateway = context?.gateway.snapshot;
97+
const agentsState = context?.agents.state;
98+
const agentsList =
99+
gateway?.phase === "connected" &&
100+
gateway.client &&
101+
agentsState?.connected &&
102+
agentsState.client === gateway.client
103+
? agentsState.agentsList
104+
: null;
105+
if (agentsList) {
106+
const rawSelectedId = context ? context.agentSelection.state.selectedId : candidateAgentId;
107+
const selectedId = rawSelectedId?.trim() ? normalizeAgentId(rawSelectedId) : null;
108+
if (
109+
selectedId &&
110+
agentsList.agents.some((agent) => normalizeAgentId(agent.id) === selectedId)
111+
) {
112+
return selectedId;
113+
}
114+
const defaultId = normalizeAgentId(agentsList.defaultId);
115+
return agentsList.agents.some((agent) => normalizeAgentId(agent.id) === defaultId)
116+
? defaultId
117+
: null;
118+
}
119+
if (gateway?.phase !== "connected" || !gateway.hello || !gateway.assistantAgentId) {
120+
return null;
121+
}
122+
const helloDefault = normalizeAgentId(gateway.assistantAgentId);
123+
const rawSelected = context?.agentSelection.state.selectedId;
124+
const selected = rawSelected?.trim() ? normalizeAgentId(rawSelected) : null;
125+
// An explicit pre-roster selection may target an agent hello knows nothing about;
126+
// defer until the roster can validate it instead of fetching the default's catalog.
127+
return selected && selected !== helloDefault ? null : helloDefault;
128+
}
129+
89130
export function requestSessionCatalogRefresh(owner: SessionCatalogDataOwner): void {
90131
const snapshot = owner.context?.gateway.snapshot;
91132
owner.sessionCatalogLive.requestRefresh({
92133
visible: document.visibilityState !== "hidden",
93134
connected:
94135
owner.isSessionDataHostConnected &&
136+
owner.sessionCatalogAgentId !== null &&
95137
Boolean(sessionCatalogListClient(snapshot, owner.sessionDataHostConnected)),
96138
generation: owner.sessionCatalogGeneration,
97139
refresh: () => void owner.refreshSessionCatalogs(),
@@ -128,13 +170,14 @@ export function applySessionCatalogHostEvent(
128170
export async function refreshSessionCatalogs(owner: SessionCatalogDataOwner): Promise<void> {
129171
// Hidden pages resume through the coalesced activation handler. Starting
130172
// here without a timer makes catalog state updates poll at request latency.
173+
const agentId = resolveSessionCatalogAgentId(owner);
174+
synchronizeSessionCatalogAgent(owner, agentId);
131175
const client = visibleSessionCatalogClient(owner);
132-
if (!client) {
176+
if (!client || !agentId) {
133177
return;
134178
}
135179
const generation = owner.sessionCatalogGeneration;
136180
const revision = owner.sessionCatalogRevision;
137-
const agentId = owner.sessionCatalogAgentId ?? owner.expandedAgentId();
138181
await refreshSessionCatalogsLive({
139182
live: owner.sessionCatalogLive,
140183
client,
@@ -187,11 +230,16 @@ export async function loadMoreSessionCatalog(
187230
return;
188231
}
189232
const client = owner.context?.gateway.snapshot.client;
190-
if (!client || !owner.sessionDataHostConnected) {
233+
const agentId = resolveSessionCatalogAgentId(owner);
234+
if (
235+
!client ||
236+
!owner.sessionDataHostConnected ||
237+
!agentId ||
238+
agentId !== owner.sessionCatalogAgentId
239+
) {
191240
return;
192241
}
193242
const generation = owner.sessionCatalogGeneration;
194-
const agentId = owner.sessionCatalogAgentId ?? owner.expandedAgentId();
195243
const revision = owner.sessionCatalogRevisions.get(catalogId) ?? 0;
196244
owner.loadingMoreSessionCatalogIds = new Set([...owner.loadingMoreSessionCatalogIds, catalogId]);
197245
owner.requestSessionDataUpdate();

‎ui/src/pages/new-session/catalog-target.test.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,4 +65,11 @@ describe("new-session catalog target", () => {
6565
expect(resolveAgentId({ ...target, agentId: "retired" }, agents, "main")).toBe("main");
6666
expect(resolveAgentId({ ...target, agentId: "" }, agents, "research")).toBe("research");
6767
});
68+
69+
it("reconciles a provisional new-thread picker value after the roster loads", () => {
70+
const location = { agentId: "main", catalogId: "" };
71+
72+
expect(resolveAgentId(location, [], "main")).toBe("main");
73+
expect(resolveAgentId(location, [{ id: "roboclaw" }], "roboclaw")).toBe("roboclaw");
74+
});
6875
});
Lines changed: 147 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,147 @@
1+
import { describe, expect, it, vi } from "vitest";
2+
import type { GatewayBrowserClient } from "../../api/gateway.ts";
3+
import type { ApplicationContext, ApplicationGatewaySnapshot } from "../../app/context.ts";
4+
import type { NewSessionRouteData } from "./location.ts";
5+
import { page } from "./route.ts";
6+
7+
// The loader is exercised through the page contract so route.ts keeps its
8+
// internals unexported; new-session routes never resolve to RouteNotFound.
9+
const loadNewSessionData = (context: ApplicationContext, search: string) =>
10+
page.loader?.(context, { location: { search } } as never) as Promise<NewSessionRouteData>;
11+
12+
function createContext(params: {
13+
assistantAgentId: string | null;
14+
agentsList: ApplicationContext["agents"]["state"]["agentsList"];
15+
staleRosterClient?: boolean;
16+
}) {
17+
const request = vi.fn(async (method: string) => {
18+
if (method !== "sessions.catalog.list") {
19+
throw new Error(`unexpected request: ${method}`);
20+
}
21+
return { catalogs: [] };
22+
});
23+
const client = { request } as unknown as GatewayBrowserClient;
24+
const snapshot: ApplicationGatewaySnapshot = {
25+
client,
26+
phase: "connected",
27+
offlineStable: false,
28+
canvasPluginSurfaceUrl: null,
29+
hello: {
30+
type: "hello-ok",
31+
protocol: 1,
32+
auth: { role: "operator", scopes: [] },
33+
features: { methods: ["sessions.catalog.list"] },
34+
},
35+
assistantAgentId: params.assistantAgentId,
36+
sessionKey: "main",
37+
lastError: null,
38+
lastErrorCode: null,
39+
};
40+
const ensureList = vi.fn(async () => params.agentsList);
41+
const agentsState = {
42+
client: params.staleRosterClient
43+
? ({ request: vi.fn() } as unknown as GatewayBrowserClient)
44+
: client,
45+
connected: true,
46+
agentsList: params.agentsList,
47+
};
48+
const context = {
49+
gateway: { snapshot },
50+
agents: {
51+
state: agentsState,
52+
ensureList,
53+
},
54+
} as unknown as ApplicationContext;
55+
return { agentsState, client, context, ensureList, request };
56+
}
57+
58+
describe("new-session route catalog target", () => {
59+
it("defers an unvalidated route agent before roster hydration", async () => {
60+
const { context, request } = createContext({
61+
assistantAgentId: "roboclaw",
62+
agentsList: null,
63+
});
64+
65+
const data = await loadNewSessionData(context, "?agent=main&catalog=claude");
66+
67+
expect(data.agentId).toBe("");
68+
expect(request).not.toHaveBeenCalled();
69+
});
70+
71+
it("reconciles a retired route agent against the loaded roster", async () => {
72+
const { context, request } = createContext({
73+
assistantAgentId: "main",
74+
agentsList: {
75+
defaultId: "roboclaw",
76+
mainKey: "main",
77+
scope: "agent",
78+
agents: [{ id: "roboclaw" }],
79+
},
80+
});
81+
82+
const data = await loadNewSessionData(context, "?agent=main&catalog=claude");
83+
84+
expect(data.agentId).toBe("roboclaw");
85+
expect(request).toHaveBeenCalledWith("sessions.catalog.list", {
86+
agentId: "roboclaw",
87+
catalogId: "claude",
88+
limitPerHost: 1,
89+
});
90+
});
91+
92+
it("defers catalog retries when neither roster nor hello supplies an agent", async () => {
93+
const { context, request } = createContext({ assistantAgentId: null, agentsList: null });
94+
95+
const data = await loadNewSessionData(context, "?agent=main&catalog=claude");
96+
97+
expect(data.agentId).toBe("");
98+
expect(request).not.toHaveBeenCalled();
99+
});
100+
101+
it("waits for the replacement client's roster before preserving a valid route agent", async () => {
102+
const { agentsState, client, context, request } = createContext({
103+
assistantAgentId: "roboclaw",
104+
agentsList: {
105+
defaultId: "main",
106+
mainKey: "main",
107+
scope: "agent",
108+
agents: [{ id: "main" }],
109+
},
110+
staleRosterClient: true,
111+
});
112+
113+
const pending = await loadNewSessionData(context, "?agent=research&catalog=claude");
114+
115+
expect(pending.agentId).toBe("");
116+
expect(request).not.toHaveBeenCalled();
117+
118+
agentsState.client = client;
119+
agentsState.agentsList = {
120+
defaultId: "roboclaw",
121+
mainKey: "main",
122+
scope: "agent",
123+
agents: [{ id: "roboclaw" }, { id: "research" }],
124+
};
125+
const data = await loadNewSessionData(context, "?agent=research&catalog=claude");
126+
127+
expect(data.agentId).toBe("research");
128+
expect(request).toHaveBeenCalledWith("sessions.catalog.list", {
129+
agentId: "research",
130+
catalogId: "claude",
131+
limitPerHost: 1,
132+
});
133+
});
134+
135+
it("reuses the current gateway client across route retries", async () => {
136+
const { client, context, request } = createContext({
137+
assistantAgentId: "roboclaw",
138+
agentsList: null,
139+
});
140+
141+
await loadNewSessionData(context, "?catalog=claude");
142+
await loadNewSessionData(context, "?catalog=claude");
143+
144+
expect(context.gateway.snapshot.client).toBe(client);
145+
expect(request).toHaveBeenCalledTimes(2);
146+
});
147+
});

0 commit comments

Comments
 (0)