Skip to content

Commit 215de48

Browse files
authored
perf(ui): streamline session switching and transcript rendering (#129834)
1 parent 22c1016 commit 215de48

15 files changed

Lines changed: 148 additions & 99 deletions

‎ui/src/app/app-host.document-title.test.ts‎

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
/* @vitest-environment jsdom */
22

3-
import { describe, expect, it } from "vitest";
3+
import { describe, expect, it, vi } from "vitest";
44
import type { AgentsListResult, GatewayAgentRow, GatewaySessionRow } from "../api/types.ts";
55
import type { RouteId } from "../app-routes.ts";
66
import "./app-host.ts";
@@ -74,6 +74,18 @@ describe("OpenClaw shell document title", () => {
7474
expect(document.title).toBe("Usage — OpenClaw");
7575
});
7676

77+
it("does not read stored outboxes for a connected document title", () => {
78+
const shell = createShell(createContext({}));
79+
const summarizeStoredChatOutboxes = vi.fn(() => ({ total: 3 }));
80+
shell.routeState = { routeId: "usage" };
81+
shell.outboxStoreRuntime = { summarizeStoredChatOutboxes };
82+
83+
shell.syncDocumentTitle();
84+
85+
expect(document.title).toBe("Usage — OpenClaw");
86+
expect(summarizeStoredChatOutboxes).not.toHaveBeenCalled();
87+
});
88+
7789
it("appends the configured environment to route and custodian titles", () => {
7890
const shell = createShell(createContext({ environment: { label: "edge", color: "amber" } }));
7991
shell.routeState = { routeId: "usage" };

‎ui/src/app/app-host.ts‎

Lines changed: 17 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -311,20 +311,24 @@ class OpenClawShell
311311
outboxScopeHost: StoredOutboxScopeHost,
312312
): string {
313313
const sessionKey = this.activeSessionKey;
314-
const row = context.sessions.state.result?.sessions.find(
315-
(session) => session.key === sessionKey,
316-
);
317314
// An agent's main chat is its identity, so use its roster label when available.
318315
const parsed = parseAgentSessionKey(sessionKey);
319316
const mainAgentId = isUiGlobalSessionKey(sessionKey)
320317
? resolveUiKnownSelectedGlobalAgentId(outboxScopeHost)
321318
: parsed?.rest === resolveUiConfiguredMainKey(outboxScopeHost)
322319
? normalizeAgentId(parsed.agentId)
323320
: undefined;
324-
const agent = context.agents.state.agentsList?.agents.find(
325-
(candidate) => normalizeAgentId(candidate.id) === mainAgentId,
326-
);
327-
return agent ? normalizeAgentLabel(agent) : resolveSessionDisplayName(sessionKey, row);
321+
const agent = mainAgentId
322+
? context.agents.state.agentsList?.agents.find(
323+
(candidate) => normalizeAgentId(candidate.id) === mainAgentId,
324+
)
325+
: undefined;
326+
return agent
327+
? normalizeAgentLabel(agent)
328+
: resolveSessionDisplayName(
329+
sessionKey,
330+
context.sessions.state.result?.sessions.find((session) => session.key === sessionKey),
331+
);
328332
}
329333

330334
constructor() {
@@ -638,17 +642,18 @@ class OpenClawShell
638642
return;
639643
}
640644
const outboxScopeHost = this.storedOutboxScopeHost(context);
641-
let primaryContext = titleForRoute(routeId);
645+
let primaryContext = routeId === "custodian" ? t("nav.askOpenClaw") : titleForRoute(routeId);
642646
if (isSessionRouteId(routeId) && this.activeSessionKey) {
643647
primaryContext = this.chatTitleContext(context, outboxScopeHost) || primaryContext;
644-
} else if (routeId === "custodian") {
645-
primaryContext = t("nav.askOpenClaw");
646648
}
649+
const offline = context.gateway.snapshot.phase !== "connected";
647650
let title = formatDocumentTitle({
648651
context: primaryContext,
649652
attentionCount: context.overlays.snapshot.approvalQueue.length,
650-
offline: context.gateway.snapshot.phase !== "connected",
651-
queuedCount: this.outboxStoreRuntime?.summarizeStoredChatOutboxes(outboxScopeHost).total ?? 0,
653+
offline,
654+
...(offline && {
655+
queuedCount: this.outboxStoreRuntime?.summarizeStoredChatOutboxes(outboxScopeHost).total,
656+
}),
652657
});
653658
const environment = context.config?.current.environment;
654659
if (environment) {

‎ui/src/app/bootstrap.nav-visibility.test.ts‎

Lines changed: 29 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
1-
import { describe, expect, it } from "vitest";
1+
import { describe, expect, it, vi } from "vitest";
22
import {
33
SIDEBAR_SESSION_NAV_COLLAPSE_QUERY,
44
withSidebarNavCollapseIntent,
55
} from "../app-session-route-paths.ts";
66
import { bootstrapApplication } from "./bootstrap.ts";
7-
import { loadSettings, saveSettings } from "./settings.ts";
7+
import { loadSettings, saveSettings, setSettingsChangeListener } from "./settings.ts";
88

99
const SIDEBAR_COLLAPSE_SEARCH = new URLSearchParams({
1010
[SIDEBAR_SESSION_NAV_COLLAPSE_QUERY.name]: SIDEBAR_SESSION_NAV_COLLAPSE_QUERY.value,
@@ -86,4 +86,31 @@ describe("normalizeInitialApplicationLocation", () => {
8686
saveSettings(previousSettings);
8787
}
8888
});
89+
90+
it("keeps sidebar visibility in memory without rewriting persisted settings", () => {
91+
const previousSettings = loadSettings();
92+
let runtime: ReturnType<typeof bootstrapApplication> | undefined;
93+
const onPersistedSettingsChanged = vi.fn();
94+
95+
try {
96+
runtime = bootstrapApplication({
97+
sessionPathBuilderReady: new Promise<void>(() => {}),
98+
});
99+
setSettingsChangeListener(onPersistedSettingsChanged);
100+
101+
runtime.context.navigation.update({ navCollapsed: true });
102+
103+
expect(runtime.context.navigation.snapshot.navCollapsed).toBe(true);
104+
expect(onPersistedSettingsChanged).not.toHaveBeenCalled();
105+
106+
runtime.context.navigation.update({ navWidth: previousSettings.navWidth + 1 });
107+
108+
expect(onPersistedSettingsChanged).toHaveBeenCalledOnce();
109+
expect(loadSettings().navWidth).toBe(previousSettings.navWidth + 1);
110+
} finally {
111+
runtime?.stop();
112+
setSettingsChangeListener(null);
113+
saveSettings(previousSettings);
114+
}
115+
});
89116
});

‎ui/src/app/bootstrap.ts‎

Lines changed: 13 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -209,19 +209,20 @@ function createApplicationNavigationPreferences(
209209
},
210210
update(patch) {
211211
const nextSnapshot = { ...snapshot, ...patch };
212-
if (
213-
nextSnapshot.navCollapsed === snapshot.navCollapsed &&
214-
nextSnapshot.navWidth === snapshot.navWidth &&
215-
nextSnapshot.sidebarEntries === snapshot.sidebarEntries &&
216-
nextSnapshot.pinnedAgentIds === snapshot.pinnedAgentIds
217-
) {
212+
const persistedChanged =
213+
nextSnapshot.navWidth !== snapshot.navWidth ||
214+
nextSnapshot.sidebarEntries !== snapshot.sidebarEntries ||
215+
nextSnapshot.pinnedAgentIds !== snapshot.pinnedAgentIds;
216+
if (!persistedChanged && nextSnapshot.navCollapsed === snapshot.navCollapsed) {
218217
return;
219218
}
220-
patchSettings({
221-
navWidth: nextSnapshot.navWidth,
222-
sidebarEntries: [...nextSnapshot.sidebarEntries],
223-
pinnedAgentIds: [...nextSnapshot.pinnedAgentIds],
224-
});
219+
if (persistedChanged) {
220+
patchSettings({
221+
navWidth: nextSnapshot.navWidth,
222+
sidebarEntries: [...nextSnapshot.sidebarEntries],
223+
pinnedAgentIds: [...nextSnapshot.pinnedAgentIds],
224+
});
225+
}
225226
snapshot = nextSnapshot;
226227
for (const listener of listeners) {
227228
listener(snapshot);
@@ -337,7 +338,7 @@ export function bootstrapApplication(
337338
const releasedSessionQuery =
338339
(startupRouteId === "chat" || startupRouteId === "dashboard") &&
339340
sessionRouteNamespaceFromPath(applicationLocation.pathname, basePath) === null &&
340-
new URLSearchParams(applicationLocation.search).has("session");
341+
startupSearchParams.has("session");
341342
const deferInitialLocationUntilGateway =
342343
documentMode === null &&
343344
!releasedSessionQuery &&

‎ui/src/components/app-sidebar-child-session-data.ts‎

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import type { SessionCapability } from "../lib/sessions/index.ts";
44
import { preserveRosterPresentationMetadata } from "../lib/sessions/reconcile.ts";
55
import {
66
areUiSessionKeysEquivalent,
7+
normalizeDefaultMainSessionAliasForUi,
78
resolveUiSessionNavigationParentKey,
89
} from "../lib/sessions/session-key.ts";
910
export { fetchChildSessionRows } from "../lib/sessions/child-session-data.ts";
@@ -16,13 +17,11 @@ export function collectKnownSessionRows(
1617
): Map<string, GatewaySessionRow> {
1718
const rows = new Map<string, GatewaySessionRow>();
1819
for (const row of [...Object.values(childRowsByParent).flat(), ...rootRows]) {
19-
const previous = [...rows.keys()].find((key) => areUiSessionKeysEquivalent(key, row.key));
20-
if (previous) {
21-
rows.delete(previous);
22-
}
23-
rows.set(row.key, row);
20+
const key = normalizeDefaultMainSessionAliasForUi(row.key) || row.key;
21+
rows.delete(key);
22+
rows.set(key, row);
2423
}
25-
return rows;
24+
return new Map([...rows.values()].map((row) => [row.key, row]));
2625
}
2726

2827
export async function fetchSessionLineage(params: {
@@ -45,9 +44,11 @@ export async function fetchSessionLineage(params: {
4544
// malformed cycle cannot leave direct child routes spinning forever.
4645
for (let depth = 0; depth < MAX_SESSION_LINEAGE_DEPTH && !visited.has(currentKey); depth += 1) {
4746
visited.add(currentKey);
48-
let row = [...params.knownRows.values()].find((candidate) =>
49-
areUiSessionKeysEquivalent(candidate.key, currentKey),
50-
);
47+
let row =
48+
params.knownRows.get(currentKey) ??
49+
[...params.knownRows.values()].find((candidate) =>
50+
areUiSessionKeysEquivalent(candidate.key, currentKey),
51+
);
5152
if (!row) {
5253
const described = await params.client.request<{ session?: GatewaySessionRow | null }>(
5354
"sessions.describe",

‎ui/src/components/app-sidebar-session-narration.ts‎

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -164,10 +164,9 @@ export class SidebarSessionNarrationController {
164164
const openSessionKey = input.openSessionKey.trim();
165165
const nextDesired = new Set<string>();
166166
let backgroundSubscriptions = 0;
167-
for (const row of input.rows.toSorted((left, right) => rowRecency(right) - rowRecency(left))) {
168-
if (!row.hasActiveRun) {
169-
continue;
170-
}
167+
for (const row of input.rows
168+
.filter((candidate) => candidate.hasActiveRun)
169+
.toSorted((left, right) => rowRecency(right) - rowRecency(left))) {
171170
const open = areUiSessionKeysEquivalent(row.key, openSessionKey);
172171
if (!open && backgroundSubscriptions >= SIDEBAR_NARRATION_SUBSCRIPTION_LIMIT) {
173172
continue;

‎ui/src/components/app-sidebar-session-navigation-logic.test.ts‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -286,6 +286,11 @@ describe("sidebar navigation lineage ownership", () => {
286286
{ name: "exact", rootKey: child.key, cachedKey: child.key },
287287
{ name: "equivalent", rootKey: child.key.toUpperCase(), cachedKey: child.key },
288288
{ name: "main alias", rootKey: "main", cachedKey: "agent:main:main" },
289+
{
290+
name: "case-preserving Matrix alias",
291+
rootKey: "Agent:Ops:Matrix:Channel:!Room:Example.Org",
292+
cachedKey: "agent:ops:matrix:channel:!Room:Example.Org",
293+
},
289294
])(
290295
"keeps the canonical root authoritative over an $name cached child key",
291296
async ({ rootKey, cachedKey }) => {
@@ -333,6 +338,18 @@ describe("sidebar navigation lineage ownership", () => {
333338
},
334339
);
335340

341+
it("keeps case-sensitive Matrix and Signal session identifiers distinct", () => {
342+
const keys = [
343+
"agent:ops:matrix:channel:!Room:Example.Org",
344+
"agent:ops:matrix:channel:!room:example.org",
345+
"agent:ops:signal:group:AbC123=",
346+
"agent:ops:signal:group:abc123=",
347+
];
348+
const rows = keys.map((key) => ({ ...child, key }));
349+
350+
expect([...collectKnownSessionRows(rows, {}).keys()]).toEqual(keys);
351+
});
352+
336353
it("projects a known child exactly once under its explicit navigation parent", () => {
337354
const projected = projectSessionTree({
338355
roots: [navigationParent, controlParent],

‎ui/src/components/app-sidebar-session-navigation-logic.ts‎

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -534,11 +534,12 @@ export function collectKnownSidebarSessionGroups(
534534
rows: readonly GatewaySessionRow[],
535535
): string[] {
536536
const catalogSet = new Set(catalog);
537-
const discovered = rows
538-
.map((row) => normalizeOptionalString(row.category))
539-
.filter((name): name is string => typeof name === "string" && !catalogSet.has(name))
540-
.toSorted((a, b) => a.localeCompare(b));
541-
return [...catalog, ...new Set(discovered)];
537+
const discovered = new Set(
538+
rows
539+
.map((row) => normalizeOptionalString(row.category))
540+
.filter((name): name is string => typeof name === "string" && !catalogSet.has(name)),
541+
);
542+
return [...catalog, ...[...discovered].toSorted((a, b) => a.localeCompare(b))];
542543
}
543544

544545
/** Depth-first search across a projected session tree, including descendants.

‎ui/src/components/markdown-streaming.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -294,6 +294,9 @@ const streamingRemendOptions = { katex: false, linkMode: "text-only" } satisfies
294294
export function repairStreamingMarkdownTail(tail: string, repairStart = 0): string {
295295
const repaired =
296296
tail.slice(0, repairStart) + remend(tail.slice(repairStart), streamingRemendOptions);
297+
if (!repaired.includes("<")) {
298+
return repaired;
299+
}
297300
const detailsStack: DetailsFrame[] = [];
298301
const codeSpans = findMarkdownCodeSpans(repaired);
299302
let openFence: FenceMarker | null = null;

‎ui/src/components/markdown-text.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,9 @@ export function normalizeMarkdownLineBreaks(value: string): string {
1515
}
1616

1717
export function isMarkdownBlockArtText(value: string): boolean {
18+
if (!BLOCK_ART_GLYPH_RE.test(value)) {
19+
return false;
20+
}
1821
const lines = normalizeMarkdownLineBreaks(value).split("\n");
1922
const artLines = lines.filter((line) => line.trim().length > 0);
2023
if (artLines.length < 2) {

0 commit comments

Comments
 (0)