Skip to content

Commit ad760c9

Browse files
authored
fix(ui): show chat before startup metadata finishes (#128652)
* fix(ui): show chat before startup metadata finishes * test(ui): wait for config save requests * fix(ui): coalesce dashboard session queries
1 parent 295809d commit ad760c9

28 files changed

Lines changed: 559 additions & 447 deletions

‎src/gateway/server-methods/agents.ts‎

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -891,10 +891,18 @@ export const agentsHandlers: GatewayRequestHandlers = {
891891
}
892892

893893
const cfg = context.getRuntimeConfig();
894-
const modelCatalog = await readPreparedServerMethodModelCatalog(context);
894+
const modelCatalogByAgentId = new Map(
895+
await Promise.all(
896+
listAgentIds(cfg).map(
897+
async (agentId) =>
898+
[agentId, await readPreparedServerMethodModelCatalog(context, { agentId })] as const,
899+
),
900+
),
901+
);
895902
respond(
896903
true,
897-
listAgentsForGateway(cfg, modelCatalog, {
904+
listAgentsForGateway(cfg, undefined, {
905+
modelCatalogByAgentId,
898906
includeSystem: hasGatewayClientCap(client?.connect.caps, GATEWAY_CLIENT_CAPS.AGENT_KIND),
899907
}),
900908
undefined,

‎src/gateway/server-methods/chat-history-handler.ts‎

Lines changed: 27 additions & 76 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,6 @@
11
// Read-side chat handlers own history projection, startup metadata, and message lookup.
2-
import {
3-
GATEWAY_CLIENT_CAPS,
4-
hasGatewayClientCap,
5-
} from "../../../packages/gateway-protocol/src/client-info.js";
62
import {
73
ErrorCodes,
8-
type AgentsListResult,
94
errorShape,
105
validateChatHistoryParams,
116
validateChatMetadataParams,
@@ -37,7 +32,6 @@ import {
3732
getSessionDefaults,
3833
loadGatewaySessionEntryReadOnly,
3934
loadGatewaySessionRow,
40-
listAgentsForGateway,
4135
resolveSessionModelRef,
4236
} from "../session-utils.js";
4337
import { prepareSessionWorkspaceIcon } from "../workspace-icon-http.js";
@@ -56,9 +50,7 @@ import {
5650
readChatHistoryPage,
5751
readChatHistoryMessageSeq,
5852
} from "./chat-history-pages.js";
59-
import type { ChatMetadataResult } from "./chat-metadata-runtime.js";
6053
import { resolveRequestedChatAgentId, validateChatSelectedAgent } from "./chat-origin-routing.js";
61-
import type { ChatStartupProjectionResult } from "./chat-startup-projection-contract.js";
6254
import { normalizeOptionalChatText as normalizeOptionalText } from "./chat-text-normalization.js";
6355
import {
6456
loadOptionalServerMethodModelCatalogSnapshot,
@@ -165,14 +157,9 @@ async function handleChatHistoryRequest({
165157
params,
166158
respond,
167159
context,
168-
client,
169160
method,
170-
includeAgentsList,
171-
includeMetadata,
172161
}: GatewayRequestHandlerOptions & {
173162
method: ChatHistoryMethod;
174-
includeAgentsList?: boolean;
175-
includeMetadata?: boolean;
176163
}) {
177164
if (!assertValidParams(params, validateChatHistoryParams, method, respond)) {
178165
return;
@@ -314,58 +301,28 @@ async function handleChatHistoryRequest({
314301
return load;
315302
})()
316303
: Promise.resolve(undefined);
317-
const startupProjectionsPromise =
318-
method === "chat.startup"
319-
? (() => {
320-
const includeSystem = hasGatewayClientCap(
321-
client?.connect.caps,
322-
GATEWAY_CLIENT_CAPS.AGENT_KIND,
323-
);
324-
return measureDiagnosticsTimelineSpan(
325-
`gateway.${method}.startup_projections`,
326-
async () => {
327-
const projection = context.readChatStartupProjection
328-
? await context
329-
.readChatStartupProjection({
330-
agentId: sessionAgentId,
331-
sessionEntry: entry,
332-
includeSystem,
333-
})
334-
.catch((error: unknown) => {
335-
context.logGateway.debug(
336-
`chat.startup continuing without prepared startup projection: ${formatErrorMessage(error)}`,
337-
);
338-
return undefined;
339-
})
340-
: undefined;
341-
const metadata = includeMetadata
342-
? (projection?.metadata ??
343-
(await context
344-
.readChatMetadata({
345-
agentId: sessionAgentId,
346-
sessionEntry: entry,
347-
})
348-
.catch((error: unknown) => {
349-
context.logGateway.debug(
350-
`chat.startup continuing without metadata: ${formatErrorMessage(error)}`,
351-
);
352-
return undefined;
353-
})))
354-
: undefined;
355-
const agentsList = includeAgentsList
356-
? (projection?.agentsList ??
357-
listAgentsForGateway(cfg, undefined, { includeSystem }))
358-
: undefined;
359-
return { agentsList, projection, metadata };
360-
},
361-
{
362-
config: cfg,
363-
phase: method,
364-
attributes: { agentId: sessionAgentId, includeSystem },
365-
},
304+
const readStartupProjection = () =>
305+
measureDiagnosticsTimelineSpan(
306+
`gateway.${method}.startup_projection`,
307+
async () => {
308+
try {
309+
return await context.readChatStartupProjection?.({
310+
agentId: sessionAgentId,
311+
sessionEntry: entry,
312+
});
313+
} catch (error) {
314+
context.logGateway.debug(
315+
`chat.startup continuing without prepared startup projection: ${formatErrorMessage(error)}`,
366316
);
367-
})()
368-
: Promise.resolve(undefined);
317+
return undefined;
318+
}
319+
},
320+
{ config: cfg, phase: method, attributes: { agentId: sessionAgentId } },
321+
);
322+
const startupProjectionPromise =
323+
method === "chat.startup" && entry?.authProfileOverride?.trim()
324+
? readStartupProjection()
325+
: undefined;
369326
const sessionId = requestedSessionId ?? entry?.sessionId;
370327
const historyEntry =
371328
requestedSessionId && requestedSessionId !== entry?.sessionId ? undefined : entry;
@@ -466,10 +423,11 @@ async function handleChatHistoryRequest({
466423
const catalogOwnedBySessionAgent = modelCatalogSnapshot?.agentId === sessionAgentId;
467424
const modelCatalog = catalogOwnedBySessionAgent ? modelCatalogSnapshot.entries : undefined;
468425
const compatibilityOwnerAgentId = tryResolveSessionCompatibilityOwnerAgentId(cfg, sessionKey);
469-
const startupProjections = await startupProjectionsPromise;
470-
const startupProjection: ChatStartupProjectionResult | undefined = startupProjections?.projection;
471-
const startupMetadata: ChatMetadataResult | undefined = startupProjections?.metadata;
472-
const startupAgentsList: AgentsListResult | undefined = startupProjections?.agentsList;
426+
const startupProjection =
427+
method === "chat.startup"
428+
? await (startupProjectionPromise ?? readStartupProjection())
429+
: undefined;
430+
const startupMetadata = startupProjection?.metadata;
473431
const sessionModelCatalog = startupProjection?.sessionModelCatalog ?? modelCatalog;
474432
const defaultModelCatalog = startupProjection?.defaultModelCatalog ?? modelCatalog;
475433
const sessionInfo = measureDiagnosticsTimelineSpanSync(
@@ -588,7 +546,6 @@ async function handleChatHistoryRequest({
588546
messages: delta.messages,
589547
deltaCursor: delta.deltaCursor,
590548
sessionInfo,
591-
...(includeAgentsList && startupAgentsList ? { agentsList: startupAgentsList } : {}),
592549
...(startupMetadata ? { metadata: startupMetadata } : {}),
593550
});
594551
return;
@@ -612,7 +569,6 @@ async function handleChatHistoryRequest({
612569
toolOverrides: entry?.toolOverrides,
613570
verboseLevel,
614571
...(boundedInFlightRun ? { inFlightRun: boundedInFlightRun } : {}),
615-
...(includeAgentsList && startupAgentsList ? { agentsList: startupAgentsList } : {}),
616572
...(startupMetadata ? { metadata: startupMetadata } : {}),
617573
};
618574
respond(true, payload);
@@ -623,12 +579,7 @@ export const chatHistoryHandlers: GatewayRequestHandlers = {
623579
await handleChatHistoryRequest({ ...opts, method: "chat.history" });
624580
},
625581
"chat.startup": async (opts) => {
626-
await handleChatHistoryRequest({
627-
...opts,
628-
method: "chat.startup",
629-
includeAgentsList: true,
630-
includeMetadata: true,
631-
});
582+
await handleChatHistoryRequest({ ...opts, method: "chat.startup" });
632583
},
633584
"chat.metadata": handleChatMetadataRequest,
634585
};

‎src/gateway/server-methods/chat-metadata-runtime.test.ts‎

Lines changed: 38 additions & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
import fs from "node:fs/promises";
21
import { describe, expect, test, vi } from "vitest";
32
import { createDeferred } from "../../../test/helpers/promise.js";
43
import {
@@ -10,7 +9,6 @@ import type { ModelCatalogEntry } from "../../agents/model-catalog.types.js";
109
import { setPreparedModelRuntimeAuthStore } from "../../agents/prepared-model-runtime-auth.js";
1110
import type { PreparedModelRuntimeSnapshot } from "../../agents/prepared-model-runtime.js";
1211
import type { OpenClawConfig } from "../../config/types.openclaw.js";
13-
import { withOpenClawTestState } from "../../test-utils/openclaw-test-state.js";
1412
import { createGatewayChatMetadataRuntime } from "./chat-metadata-runtime.js";
1513
import type { GatewayRequestContext } from "./types.js";
1614

@@ -226,21 +224,15 @@ describe("gateway chat metadata runtime", () => {
226224
harness.getSkillsVersion.mockClear();
227225
harness.getPluginRegistryVersion.mockClear();
228226

229-
const first = await harness.runtime.readStartup({
230-
agentId: "main",
231-
includeSystem: false,
232-
});
233-
const second = await harness.runtime.readStartup({
234-
agentId: "main",
235-
includeSystem: false,
236-
});
227+
const first = await harness.runtime.readStartup({ agentId: "main" });
228+
const second = await harness.runtime.readStartup({ agentId: "main" });
237229

238-
expect(second.agentsList).toBe(first.agentsList);
239-
expect(first.sessionModelCatalog).toEqual([
230+
expect(first?.sessionModelCatalog).toEqual([
240231
expect.objectContaining({ id: "first", provider: "test" }),
241232
]);
242-
expect(first.defaultModelCatalog).toBe(first.sessionModelCatalog);
243-
expect(first.metadata.models).toEqual(first.sessionModelCatalog);
233+
expect(second).toEqual(first);
234+
expect(first?.defaultModelCatalog).toBe(first?.sessionModelCatalog);
235+
expect(first?.metadata.models).toEqual(first?.sessionModelCatalog);
244236
expect(harness.buildProjection).toHaveBeenCalledTimes(1);
245237
expect(harness.getPreparedOwner).not.toHaveBeenCalled();
246238
expect(harness.getPreparedAuthStore).not.toHaveBeenCalled();
@@ -262,16 +254,14 @@ describe("gateway chat metadata runtime", () => {
262254
});
263255
await harness.runtime.refresh();
264256

265-
const readNeutralStartup = async () =>
266-
await harness.runtime.readStartup({
267-
agentId: defaultAgentId,
268-
includeSystem: false,
269-
});
257+
const readNeutralStartup = () => harness.runtime.readStartup({ agentId: defaultAgentId });
270258
const first = await readNeutralStartup();
271259
const second = await readNeutralStartup();
272260

273-
expect(first.agentsList.agents).toHaveLength(agentIds.length);
274-
expect(second.agentsList).toBe(first.agentsList);
261+
expect(first?.sessionModelCatalog).toEqual([
262+
expect.objectContaining({ id: "first", provider: "test" }),
263+
]);
264+
expect(second).toEqual(first);
275265
expect(harness.buildProjection).toHaveBeenCalledTimes(agentIds.length);
276266

277267
await harness.runtime.readStartup({
@@ -280,14 +270,13 @@ describe("gateway chat metadata runtime", () => {
280270
authProfileOverride: "test:session",
281271
authProfileOverrideSource: "user",
282272
},
283-
includeSystem: false,
284273
});
285274
await readNeutralStartup();
286275

287276
expect(harness.buildProjection).toHaveBeenCalledTimes(agentIds.length + 1);
288277
});
289278

290-
test("caches a session auth projection separately from the neutral roster", async () => {
279+
test("caches a session auth projection separately from the neutral projection", async () => {
291280
const harness = createHarness();
292281
await harness.runtime.refresh();
293282

@@ -298,12 +287,10 @@ describe("gateway chat metadata runtime", () => {
298287
const first = await harness.runtime.readStartup({
299288
agentId: "main",
300289
sessionEntry,
301-
includeSystem: false,
302290
});
303291
const second = await harness.runtime.readStartup({
304292
agentId: "main",
305293
sessionEntry,
306-
includeSystem: false,
307294
});
308295

309296
expect(second).toEqual(first);
@@ -337,7 +324,6 @@ describe("gateway chat metadata runtime", () => {
337324
await harness.runtime.readStartup({
338325
agentId: "main",
339326
sessionEntry,
340-
includeSystem: false,
341327
});
342328

343329
const projectionParams = harness.buildProjection.mock.calls.at(-1)?.[0];
@@ -357,31 +343,6 @@ describe("gateway chat metadata runtime", () => {
357343
}
358344
});
359345

360-
test("keeps disk-only roster rows without projecting them", async () => {
361-
await withOpenClawTestState(
362-
{
363-
layout: "state-only",
364-
scenario: "minimal",
365-
agentEnv: "main",
366-
},
367-
async (state) => {
368-
await fs.mkdir(state.statePath("agents", "dormant", "agent"), { recursive: true });
369-
const harness = createHarness({});
370-
371-
await harness.runtime.refresh();
372-
harness.getPreparedOwner.mockClear();
373-
const startup = await harness.runtime.readStartup({
374-
agentId: "main",
375-
includeSystem: false,
376-
});
377-
378-
expect(startup.agentsList.agents.map((agent) => agent.id)).toEqual(["main", "dormant"]);
379-
expect(harness.getPreparedOwner).not.toHaveBeenCalled();
380-
expect(harness.buildProjection).toHaveBeenCalledTimes(1);
381-
},
382-
);
383-
});
384-
385346
test("reuses the prepared generation for an equivalent config replacement", async () => {
386347
const harness = createHarness();
387348
await harness.runtime.refresh();
@@ -570,13 +531,21 @@ describe("gateway chat metadata runtime", () => {
570531
expect(harness.buildProjection).toHaveBeenCalledTimes(4);
571532
});
572533

573-
test("waits for an invalidated generation to be replaced before serving reads", async () => {
534+
test("waits for replacement only for canonical metadata and session auth projections", async () => {
574535
const harness = createHarness();
575536
await harness.runtime.refresh();
576537

577538
harness.runtime.invalidate();
578539
const read = harness.runtime.read({ agentId: "main" });
540+
const overriddenStartup = harness.runtime.readStartup({
541+
agentId: "main",
542+
sessionEntry: {
543+
authProfileOverride: "test:session",
544+
authProfileOverrideSource: "user",
545+
},
546+
});
579547
let settled = false;
548+
let overriddenSettled = false;
580549
void read.then(
581550
() => {
582551
settled = true;
@@ -585,8 +554,18 @@ describe("gateway chat metadata runtime", () => {
585554
settled = true;
586555
},
587556
);
557+
void overriddenStartup.then(
558+
() => {
559+
overriddenSettled = true;
560+
},
561+
() => {
562+
overriddenSettled = true;
563+
},
564+
);
565+
await expect(harness.runtime.readStartup({ agentId: "main" })).resolves.toBeUndefined();
588566
await Promise.resolve();
589567
expect(settled).toBe(false);
568+
expect(overriddenSettled).toBe(false);
590569

591570
const nextConfig = {
592571
agents: { list: [{ id: "main", default: true }] },
@@ -600,6 +579,13 @@ describe("gateway chat metadata runtime", () => {
600579
models: [expect.objectContaining({ id: "replacement" })],
601580
swarmEnabled: true,
602581
});
582+
await expect(overriddenStartup).resolves.toMatchObject({
583+
metadata: {
584+
models: [expect.objectContaining({ id: "replacement" })],
585+
swarmEnabled: true,
586+
},
587+
sessionModelCatalog: [expect.objectContaining({ id: "replacement" })],
588+
});
603589
});
604590

605591
test("retries a session projection invalidated while it is awaiting", async () => {

0 commit comments

Comments
 (0)