Skip to content

Commit 2ae316e

Browse files
authored
fix(ui): session titles flicker during archive transitions (#121868)
* fix(ui): preserve session titles through archive transitions * oc-ba3: fix archive title CI regressions
1 parent c8571da commit 2ae316e

19 files changed

Lines changed: 771 additions & 123 deletions

‎test/vitest-unit-fast-config.test.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -261,6 +261,8 @@ describe("unit-fast vitest lane", () => {
261261
const files = [
262262
"src/agents/auth-profiles/oauth-refresh-error.test.ts",
263263
"src/auto-reply/reply/agent-runner-execution-runtime.test.ts",
264+
"src/infra/outbound/message-action-execution.poll.test.ts",
265+
"src/infra/outbound/message-action-runner.poll.test.ts",
264266
];
265267
for (const file of files) {
266268
const analysis = unitFastAnalysis.find((entry) => entry.file === file);

‎test/vitest/vitest.unit-fast-paths.mjs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -251,7 +251,7 @@ const disqualifyingPatterns = [
251251
];
252252

253253
const statefulTestHelperImportPattern =
254-
/\bfrom\s+["']([^"']*(?:test-support|\.harness)(?:\.js|\.ts)?)["']/gu;
254+
/\bfrom\s+["']([^"']*(?:test-support|\.harness|message-action-runner\.test-helpers)(?:\.js|\.ts)?)["']/gu;
255255
const statefulTestHelperByKey = new Map();
256256

257257
function importsStatefulTestHelper(cwd, file, source) {

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

Lines changed: 63 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import type { GatewayBrowserClient } from "../api/gateway.ts";
22
import type { GatewaySessionRow, SessionsListResult } from "../api/types.ts";
33
import type { SessionCapability } from "../lib/sessions/index.ts";
4+
import { preserveRosterPresentationMetadata } from "../lib/sessions/reconcile.ts";
45
import {
56
areUiSessionKeysEquivalent,
67
resolveUiSessionNavigationParentKey,
@@ -93,26 +94,69 @@ function mergeChildSessionRows(
9394
return merged;
9495
}
9596

97+
/** Retain only the routed ancestry while a canonical refresh invalidates other child snapshots. */
98+
export function preserveActiveSessionLineageRows(
99+
sessionKey: string | null,
100+
rowsByParent: Readonly<Record<string, readonly GatewaySessionRow[]>>,
101+
): Readonly<Record<string, readonly GatewaySessionRow[]>> {
102+
const preserved: Record<string, readonly GatewaySessionRow[]> = {};
103+
let childKey = sessionKey?.trim();
104+
const visited = new Set<string>();
105+
while (childKey && !visited.has(childKey)) {
106+
visited.add(childKey);
107+
const parent = Object.entries(rowsByParent).find(([, rows]) =>
108+
rows.some((row) => areUiSessionKeysEquivalent(row.key, childKey)),
109+
);
110+
if (!parent) {
111+
break;
112+
}
113+
preserved[parent[0]] = parent[1];
114+
childKey = parent[0];
115+
}
116+
return preserved;
117+
}
118+
96119
export function publishActiveSessionLineage(
97120
owner: {
98121
activeSessionLineageRoot: GatewaySessionRow | null;
122+
activeSessionLineageSelectedRow: GatewaySessionRow | null;
99123
childSessionRowsByParent: Readonly<Record<string, readonly GatewaySessionRow[]>>;
100-
context?: { sessions: Pick<SessionCapability, "reconcile"> };
124+
context?: {
125+
gateway?: { snapshot: { sessionKey?: string | null } };
126+
sessions: Pick<SessionCapability, "reconcile">;
127+
};
101128
sessionsResult: SessionsListResult | null;
102129
},
103130
sessionKey: string,
104131
lineage: NonNullable<Awaited<ReturnType<typeof fetchSessionLineage>>>,
105132
): void {
133+
const previousRoot = owner.activeSessionLineageRoot;
134+
const previousSelectedRow = owner.activeSessionLineageSelectedRow;
135+
const preserveLineageRow = (row: GatewaySessionRow): GatewaySessionRow => {
136+
const previous = areUiSessionKeysEquivalent(row.key, sessionKey)
137+
? previousSelectedRow
138+
: previousRoot && areUiSessionKeysEquivalent(row.key, previousRoot.key)
139+
? previousRoot
140+
: null;
141+
return preserveRosterPresentationMetadata(row, previous ?? undefined);
142+
};
143+
const topmostRow = lineage.topmostRow ? preserveLineageRow(lineage.topmostRow) : null;
144+
const rowsByParent = Object.fromEntries(
145+
Object.entries(lineage.rowsByParent).map(([parentKey, rows]) => [
146+
parentKey,
147+
rows.map(preserveLineageRow),
148+
]),
149+
);
106150
owner.childSessionRowsByParent = mergeChildSessionRows(
107151
owner.childSessionRowsByParent,
108-
lineage.rowsByParent,
152+
rowsByParent,
109153
);
110-
owner.activeSessionLineageRoot = lineage.topmostRow;
154+
owner.activeSessionLineageRoot = topmostRow;
111155
// Prefer the fetched lineage on ties, but keep a newer child-list snapshot
112156
// so a delayed describe cannot regress already-settled run state.
113157
const selectedRow = [
114-
lineage.topmostRow,
115-
...Object.values(lineage.rowsByParent).flat(),
158+
topmostRow,
159+
...Object.values(rowsByParent).flat(),
116160
...collectKnownSessionRows(
117161
owner.sessionsResult?.sessions ?? [],
118162
owner.childSessionRowsByParent,
@@ -125,6 +169,8 @@ export function publishActiveSessionLineage(
125169
.reduce<GatewaySessionRow | undefined>((freshest, row) => {
126170
return !freshest || (row.updatedAt ?? 0) > (freshest.updatedAt ?? 0) ? row : freshest;
127171
}, undefined);
172+
owner.activeSessionLineageSelectedRow =
173+
selectedRow ?? (lineage.lookupFailed ? previousSelectedRow : null);
128174
if (selectedRow) {
129175
// The active list intentionally omits archived rows. Publish the routed
130176
// descriptor so the chat pane and header share the sidebar's cold-load truth.
@@ -141,9 +187,20 @@ export function evictArchivedSessionLineage(
141187
if (!sessionKey) {
142188
return;
143189
}
190+
const routedSessionKey = owner.context?.gateway?.snapshot.sessionKey?.trim();
191+
if (routedSessionKey && areUiSessionKeysEquivalent(routedSessionKey, sessionKey)) {
192+
// Sidebar lineage can momentarily retarget while the archived route remains
193+
// selected. The routed descriptor still owns pane/header presentation and
194+
// must survive until application navigation actually moves elsewhere.
195+
return;
196+
}
144197
const selectedRow =
145198
owner.sessionsResult?.sessions.find((row) => areUiSessionKeysEquivalent(row.key, sessionKey)) ??
146-
[owner.activeSessionLineageRoot, ...Object.values(owner.childSessionRowsByParent).flat()].find(
199+
[
200+
owner.activeSessionLineageSelectedRow,
201+
owner.activeSessionLineageRoot,
202+
...Object.values(owner.childSessionRowsByParent).flat(),
203+
].find(
147204
(row): row is GatewaySessionRow =>
148205
row != null && areUiSessionKeysEquivalent(row.key, sessionKey),
149206
);

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -262,6 +262,7 @@ export class AppSidebarSessionNavigationElement extends AppSidebarBase {
262262

263263
private activeLineageRow(sessionKey: string): GatewaySessionRow | undefined {
264264
return [
265+
this.sessionData.activeSessionLineageSelectedRow,
265266
this.sessionData.activeSessionLineageRoot,
266267
...Object.values(this.sessionData.childSessionRowsByParent).flat(),
267268
].find(

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

Lines changed: 43 additions & 59 deletions
Original file line numberDiff line numberDiff line change
@@ -14,22 +14,22 @@ import {
1414
type CatalogSessionContinuedDetail,
1515
} from "../lib/sessions/catalog-key.ts";
1616
import type { SessionCapability } from "../lib/sessions/index.ts";
17-
import { normalizeAgentId } from "../lib/sessions/session-key.ts";
17+
import { areUiSessionKeysEquivalent, normalizeAgentId } from "../lib/sessions/session-key.ts";
1818
import { SubscriptionsController } from "../lit/subscriptions-controller.ts";
1919
import {
2020
collectKnownSessionRows,
2121
evictArchivedSessionLineage,
2222
fetchChildSessionRows,
2323
fetchSessionLineage,
24+
preserveActiveSessionLineageRows,
2425
publishActiveSessionLineage,
2526
} from "./app-sidebar-child-session-data.ts";
2627
import { SessionCatalogLiveState } from "./app-sidebar-session-catalog-live.ts";
2728
import { bindAdoptedCatalogSession } from "./app-sidebar-session-catalogs.ts";
28-
import {
29-
resolveSidebarSessionsScrollState,
30-
type SidebarSessionMutationScope,
31-
type SidebarSessionStatusFilter,
32-
type SidebarSessionsScrollState,
29+
import type {
30+
SidebarSessionMutationScope,
31+
SidebarSessionStatusFilter,
32+
SidebarSessionsScrollState,
3333
} from "./app-sidebar-session-types.ts";
3434
import { createPanelRefreshStatus, type PanelRefreshStatus } from "./panel-refresh-status.ts";
3535
import {
@@ -49,6 +49,7 @@ import {
4949
subscribeFilteredSidebarSessions,
5050
subscribeSessionDataGatewayEvents,
5151
} from "./session-data-controller-events.ts";
52+
import { SessionDataScrollController } from "./session-data-scroll-controller.ts";
5253

5354
/** Gateway-backed session-list and external-catalog data ownership. */
5455
export class SessionDataController implements ReactiveController, SessionCatalogDataOwner {
@@ -64,7 +65,7 @@ export class SessionDataController implements ReactiveController, SessionCatalog
6465
failedChildSessionKeys: ReadonlySet<string> = new Set();
6566
loadingChildSessionKeys: ReadonlySet<string> = new Set();
6667
activeSessionLineageRoot: GatewaySessionRow | null = null;
67-
sessionsScrollState: SidebarSessionsScrollState = "none";
68+
activeSessionLineageSelectedRow: GatewaySessionRow | null = null;
6869
sessionMutationError: string | null = null;
6970
presencePayload: PresencePayload | undefined;
7071
presenceInstanceId?: string;
@@ -96,9 +97,7 @@ export class SessionDataController implements ReactiveController, SessionCatalog
9697
private gatewayConnected = false;
9798
// Bind mutation completions to one epoch so stale failures cannot cross reconnects.
9899
private sessionMutationEpoch = 0;
99-
private sessionsScrollElement: HTMLElement | null = null;
100-
private sessionsScrollResizeObserver: ResizeObserver | null = null;
101-
private sessionsScrollStateFrame: number | null = null;
100+
private readonly scroll = new SessionDataScrollController(() => this.notify());
102101
private approvalBadgeQueue: ApplicationContext<RouteId>["overlays"]["snapshot"]["approvalQueue"] =
103102
[];
104103
private approvalBadges: ApprovalBadgeSnapshot = deriveApprovalBadgeSnapshot([]);
@@ -182,7 +181,7 @@ export class SessionDataController implements ReactiveController, SessionCatalog
182181

183182
hostUpdated(): void {
184183
this.synchronizeSessionScope();
185-
this.syncSessionsScrollObserver();
184+
this.scroll.synchronize(this.host);
186185
this.updateSessionCatalogData(true);
187186
}
188187

@@ -195,13 +194,7 @@ export class SessionDataController implements ReactiveController, SessionCatalog
195194
this.gatewayClient = null;
196195
this.gatewayConnected = false;
197196
this.retireSessionCatalogData();
198-
this.sessionsScrollResizeObserver?.disconnect();
199-
this.sessionsScrollResizeObserver = null;
200-
this.sessionsScrollElement = null;
201-
if (this.sessionsScrollStateFrame !== null) {
202-
cancelAnimationFrame(this.sessionsScrollStateFrame);
203-
this.sessionsScrollStateFrame = null;
204-
}
197+
this.scroll.dispose();
205198
if (this.activeSessionLineageRetryTimer) {
206199
globalThis.clearTimeout(this.activeSessionLineageRetryTimer);
207200
this.activeSessionLineageRetryTimer = null;
@@ -357,54 +350,30 @@ export class SessionDataController implements ReactiveController, SessionCatalog
357350
return loadMoreSessionCatalogData(this, catalogId);
358351
}
359352

360-
private syncSessionsScrollObserver(): void {
361-
const element = this.host.querySelector(".sidebar-shell__body") as HTMLElement | null;
362-
if (element !== this.sessionsScrollElement) {
363-
this.sessionsScrollResizeObserver?.disconnect();
364-
this.sessionsScrollElement = element;
365-
this.sessionsScrollResizeObserver = null;
366-
if (element && typeof ResizeObserver === "function") {
367-
this.sessionsScrollResizeObserver = new ResizeObserver(() =>
368-
this.updateSessionsScrollState(element),
369-
);
370-
this.sessionsScrollResizeObserver.observe(element);
371-
}
372-
}
373-
if (element) {
374-
this.scheduleSessionsScrollStateSync();
375-
}
376-
}
377-
378-
// One rAF-coalesced scroll read rides paint layout instead of flushing every update.
379-
private scheduleSessionsScrollStateSync(): void {
380-
if (this.sessionsScrollStateFrame !== null) {
381-
return;
382-
}
383-
this.sessionsScrollStateFrame = requestAnimationFrame(() => {
384-
this.sessionsScrollStateFrame = null;
385-
const element = this.sessionsScrollElement;
386-
if (element?.isConnected) {
387-
this.updateSessionsScrollState(element);
388-
}
389-
});
353+
get sessionsScrollState(): SidebarSessionsScrollState {
354+
return this.scroll.state;
390355
}
391356

392357
updateSessionsScrollState(element: HTMLElement): void {
393-
const nextState = resolveSidebarSessionsScrollState(element);
394-
if (nextState !== this.sessionsScrollState) {
395-
this.sessionsScrollState = nextState;
396-
this.notify();
397-
}
358+
this.scroll.update(element);
398359
}
399360

400-
private resetChildSessionState(): void {
361+
private resetChildSessionState(options: { preserveActiveLineage?: boolean } = {}): void {
401362
this.childSessionGeneration += 1;
402-
this.childSessionRowsByParent = {};
363+
this.childSessionRowsByParent = options.preserveActiveLineage
364+
? preserveActiveSessionLineageRows(
365+
this.activeSessionLineageRouteKey,
366+
this.childSessionRowsByParent,
367+
)
368+
: {};
403369
this.loadedChildSessionKeys = new Set();
404370
this.failedChildSessionKeys = new Set();
405371
this.loadingChildSessionKeys = new Set();
406-
this.activeSessionLineageRoot = null;
407-
this.activeSessionLineageRouteKey = null;
372+
if (options.preserveActiveLineage !== true) {
373+
this.activeSessionLineageRoot = null;
374+
this.activeSessionLineageSelectedRow = null;
375+
this.activeSessionLineageRouteKey = null;
376+
}
408377
this.activeSessionLineageLoaded = false;
409378
this.activeSessionLineageRequestToken = null;
410379
if (this.activeSessionLineageRetryTimer) {
@@ -416,9 +385,20 @@ export class SessionDataController implements ReactiveController, SessionCatalog
416385
private readonly updateSessions = (sessions: SessionCapability) => {
417386
if (this.childSessionCanonicalListRevision !== sessions.canonicalListRevision) {
418387
this.childSessionCanonicalListRevision = sessions.canonicalListRevision;
388+
const routeKey = this.activeSessionLineageRouteKey;
389+
const routedRow = routeKey
390+
? this.sessionsResult?.sessions.find((row) => areUiSessionKeysEquivalent(row.key, routeKey))
391+
: undefined;
392+
if (routedRow) {
393+
// A canonical active-list refresh can remove the selected row before
394+
// its archived descriptor is reloaded. Keep the enriched pre-refresh
395+
// row as the routed presentation baseline so no intermediate render
396+
// falls back to the raw session key or "New session".
397+
this.activeSessionLineageSelectedRow = routedRow;
398+
}
419399
// The canonical root list advances after session events, but excludes hidden children.
420400
// Drop child snapshots so expanded parents refetch live terminal state.
421-
this.resetChildSessionState();
401+
this.resetChildSessionState({ preserveActiveLineage: true });
422402
this.notify();
423403
}
424404
const snapshot = sessions.state;
@@ -619,12 +599,16 @@ export class SessionDataController implements ReactiveController, SessionCatalog
619599

620600
async loadActiveSessionLineage(sessionKey: string): Promise<void> {
621601
const normalizedKey = sessionKey.trim();
622-
if (normalizedKey !== this.activeSessionLineageRouteKey) {
602+
if (
603+
!this.activeSessionLineageRouteKey ||
604+
!areUiSessionKeysEquivalent(normalizedKey, this.activeSessionLineageRouteKey)
605+
) {
623606
evictArchivedSessionLineage(this, this.activeSessionLineageRouteKey);
624607
this.activeSessionLineageRouteKey = normalizedKey;
625608
this.activeSessionLineageLoaded = false;
626609
this.activeSessionLineageRequestToken = null;
627610
this.activeSessionLineageRoot = null;
611+
this.activeSessionLineageSelectedRow = null;
628612
if (this.activeSessionLineageRetryTimer) {
629613
globalThis.clearTimeout(this.activeSessionLineageRetryTimer);
630614
this.activeSessionLineageRetryTimer = null;
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
import { resolveSidebarSessionsScrollState } from "./app-sidebar-session-types.ts";
2+
import type { SidebarSessionsScrollState } from "./app-sidebar-session-types.ts";
3+
4+
/** Owns sidebar scroll observation and its paint-coalesced reactive state. */
5+
export class SessionDataScrollController {
6+
state: SidebarSessionsScrollState = "none";
7+
8+
private element: HTMLElement | null = null;
9+
private resizeObserver: ResizeObserver | null = null;
10+
private frame: number | null = null;
11+
12+
/** Creates a scroll owner that notifies its reactive host on state changes. */
13+
constructor(private readonly notify: () => void) {}
14+
15+
/** Rebinds observation to the sidebar's current scroll container. */
16+
synchronize(host: Pick<HTMLElement, "querySelector">): void {
17+
const element = host.querySelector(".sidebar-shell__body") as HTMLElement | null;
18+
if (element !== this.element) {
19+
this.resizeObserver?.disconnect();
20+
this.element = element;
21+
this.resizeObserver = null;
22+
if (element && typeof ResizeObserver === "function") {
23+
this.resizeObserver = new ResizeObserver(() => this.update(element));
24+
this.resizeObserver.observe(element);
25+
}
26+
}
27+
if (element && this.frame === null) {
28+
// One rAF-coalesced read rides paint layout instead of flushing every update.
29+
this.frame = requestAnimationFrame(() => {
30+
this.frame = null;
31+
if (this.element?.isConnected) {
32+
this.update(this.element);
33+
}
34+
});
35+
}
36+
}
37+
38+
/** Publishes the scroll affordance state observed from an element. */
39+
update(element: HTMLElement): void {
40+
const nextState = resolveSidebarSessionsScrollState(element);
41+
if (nextState !== this.state) {
42+
this.state = nextState;
43+
this.notify();
44+
}
45+
}
46+
47+
/** Releases DOM observers and pending animation-frame work. */
48+
dispose(): void {
49+
this.resizeObserver?.disconnect();
50+
this.resizeObserver = null;
51+
this.element = null;
52+
if (this.frame !== null) {
53+
cancelAnimationFrame(this.frame);
54+
this.frame = null;
55+
}
56+
}
57+
}

0 commit comments

Comments
 (0)