Skip to content

Commit bb80e40

Browse files
committed
refactor(ui): simplify chat rendering and lifecycle state
1 parent 00b64b8 commit bb80e40

20 files changed

Lines changed: 307 additions & 593 deletions

‎config/assertion-safety-baseline.txt‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4053,7 +4053,7 @@ ui/src/pages/chat/components/chat-header-session-menu.ts 1
40534053
ui/src/pages/chat/components/chat-message-attachment-availability.ts 1
40544054
ui/src/pages/chat/components/chat-message-bubble.ts 2
40554055
ui/src/pages/chat/components/chat-message-confirmation.ts 2
4056-
ui/src/pages/chat/components/chat-message-markdown.ts 3
4056+
ui/src/pages/chat/components/chat-message-markdown.ts 2
40574057
ui/src/pages/chat/components/chat-message-media.ts 13
40584058
ui/src/pages/chat/components/chat-message-timestamp.ts 4
40594059
ui/src/pages/chat/components/chat-model-picker-options.ts 2
@@ -4068,7 +4068,7 @@ ui/src/pages/chat/components/chat-sidebar-editor-menu.ts 2
40684068
ui/src/pages/chat/components/chat-sidebar-region.runtime.ts 2
40694069
ui/src/pages/chat/components/chat-swarm-progress.ts 2
40704070
ui/src/pages/chat/components/chat-task-suggestions.ts 1
4071-
ui/src/pages/chat/components/chat-thread-interactions.ts 7
4071+
ui/src/pages/chat/components/chat-thread-interactions.ts 6
40724072
ui/src/pages/chat/components/chat-tool-cards.ts 2
40734073
ui/src/pages/chat/components/chat-voice-activity.ts 1
40744074
ui/src/pages/chat/components/session-diff-menus.ts 1

‎ui/src/pages/chat/chat-agent-run-grouping.ts‎

Lines changed: 16 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -79,32 +79,16 @@ function itemIsActive(item: AgentRunFramePart): boolean {
7979
return itemGroups(item).some((group) => group.isStreaming);
8080
}
8181

82-
function itemBoundaryId(item: AgentRunFramePart): string | undefined {
83-
return item.kind === "stream-run" ? item.boundaryId : undefined;
84-
}
85-
8682
function groupBoundaryId(group: MessageGroup): string | undefined {
8783
const firstMessage = group.messages[0]?.message;
8884
const identity = readSessionMessageIdentity(firstMessage);
89-
if (!chatItemStartsUserTurn(group)) {
90-
return undefined;
91-
}
9285
const runId = identity?.runId;
9386
if (runId) {
9487
return `send:${runId}`;
9588
}
9689
return identity?.id ? `entry:${identity.id}` : undefined;
9790
}
9891

99-
function isExternalBoundary(group: MessageGroup): boolean {
100-
return group.role === "user" || assistantGroupIsForwardedBoundary(group);
101-
}
102-
103-
function itemBoundaryGroup(item: AgentRunFramePart): MessageGroup | undefined {
104-
const first = itemGroups(item)[0];
105-
return first && chatItemStartsUserTurn(first) ? first : undefined;
106-
}
107-
10892
function frameKey(runId: string, boundaryId: string, segmentId: string | undefined): string {
10993
return `agent-run:${JSON.stringify(segmentId ? [runId, boundaryId, segmentId] : [runId, boundaryId])}`;
11094
}
@@ -233,48 +217,46 @@ export function coalesceAgentRunFrames(
233217
segmentId = boundaryId ? undefined : item.key;
234218
continue;
235219
}
236-
const candidate = item;
237-
const boundaryGroup = itemBoundaryGroup(candidate);
238-
if (boundaryGroup) {
220+
const boundaryGroup = itemGroups(item)[0];
221+
if (boundaryGroup && chatItemStartsUserTurn(boundaryGroup)) {
239222
flush();
240223
segmentId = undefined;
241224
const nextBoundaryId = groupBoundaryId(boundaryGroup);
242-
if (isExternalBoundary(boundaryGroup) || !nextBoundaryId) {
225+
if (
226+
boundaryGroup.role === "user" ||
227+
assistantGroupIsForwardedBoundary(boundaryGroup) ||
228+
!nextBoundaryId
229+
) {
243230
result.push(item);
244231
boundaryId = nextBoundaryId;
245232
continue;
246233
}
247234
boundaryId = nextBoundaryId;
248235
}
249-
const candidateBoundaryId = itemBoundaryId(candidate);
236+
const candidateBoundaryId = item.kind === "stream-run" ? item.boundaryId : undefined;
250237
if (candidateBoundaryId && candidateBoundaryId !== boundaryId) {
251238
flush();
252239
boundaryId = candidateBoundaryId;
253240
}
254-
const candidateRunId = itemRunId(candidate);
255-
if (boundaryId && candidateRunId && itemFailsFrame(candidate)) {
256-
if (runId && runId !== candidateRunId) {
257-
flush();
258-
}
259-
runId = candidateRunId;
260-
parts.push(candidate);
261-
flush(true);
262-
boundaryId = undefined;
263-
segmentId = item.key;
264-
continue;
265-
}
241+
const candidateRunId = itemRunId(item);
266242
if (!boundaryId || !candidateRunId) {
267243
flush();
268244
result.push(item);
269245
boundaryId = undefined;
270246
segmentId = item.key;
271247
continue;
272248
}
249+
const failed = itemFailsFrame(item);
273250
if (runId && runId !== candidateRunId) {
274251
flush();
275252
}
276253
runId = candidateRunId;
277-
parts.push(candidate);
254+
parts.push(item);
255+
if (failed) {
256+
flush(true);
257+
boundaryId = undefined;
258+
segmentId = item.key;
259+
}
278260
}
279261
flush();
280262
return result;

‎ui/src/pages/chat/chat-outbox-drain.ts‎

Lines changed: 6 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -94,23 +94,15 @@ type StoredChatOutboxDrainLane = {
9494
rerun: boolean;
9595
};
9696

97-
type StoredChatOutboxClientState = {
98-
lanes: Map<string, StoredChatOutboxDrainLane>;
99-
};
10097
export const UNCONFIRMED_CHAT_SEND_ERROR =
10198
"Reconnected before delivery was confirmed. Check the conversation — retry only if your message didn't arrive.";
10299
const UNCERTAIN_CLEAR_SUCCESSOR_ERROR =
103100
"A preceding /clear may have completed. Review the current conversation before retrying.";
104101

105-
const storedChatOutboxClients = new WeakMap<GatewayBrowserClient, StoredChatOutboxClientState>();
106-
107-
function getStoredChatOutboxClientState(client: GatewayBrowserClient): StoredChatOutboxClientState {
108-
const state = storedChatOutboxClients.get(client) ?? {
109-
lanes: new Map(),
110-
};
111-
storedChatOutboxClients.set(client, state);
112-
return state;
113-
}
102+
const storedChatOutboxLanes = new WeakMap<
103+
GatewayBrowserClient,
104+
Map<string, StoredChatOutboxDrainLane>
105+
>();
114106

115107
export function scheduleStoredChatOutboxRetry(
116108
host: ChatHost,
@@ -630,7 +622,8 @@ export async function scheduleStoredChatOutboxDrain(
630622
return undefined;
631623
}
632624
const key = storedChatOutboxScopeKey(scope);
633-
const { lanes } = getStoredChatOutboxClientState(client);
625+
const lanes = storedChatOutboxLanes.get(client) ?? new Map<string, StoredChatOutboxDrainLane>();
626+
storedChatOutboxLanes.set(client, lanes);
634627
const candidateOwnsScope = visibleSessionMatches(host, scope.sessionKey, scope.agentId);
635628
if (consumeChatOutboxRetry(host, key, candidateOwnsScope, itemId)) {
636629
return undefined;

‎ui/src/pages/chat/chat-pane-attachment-handoff.ts‎

Lines changed: 6 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import type { ApplicationContext } from "../../app/context.ts";
22
import type { ChatAttachment } from "../../lib/chat/chat-types.ts";
33
import {
4-
releaseChatAttachmentPayload,
4+
releaseChatAttachmentPayloads,
55
releaseDisplacedChatAttachmentPayloads,
66
} from "./attachment-payload-store.ts";
77
import type { ChatPageHost } from "./chat-state-host.ts";
@@ -19,20 +19,6 @@ function handoffKey(paneId: string, state: ChatPageHost, owner: ChatAttachmentGa
1919
};
2020
}
2121

22-
function releaseAttachments(
23-
attachments: readonly ChatAttachment[],
24-
retainedIds = new Set<string>(),
25-
releasedIds = new Set<string>(),
26-
): void {
27-
for (const attachment of attachments) {
28-
if (retainedIds.has(attachment.id) || releasedIds.has(attachment.id)) {
29-
continue;
30-
}
31-
releasedIds.add(attachment.id);
32-
releaseChatAttachmentPayload(attachment.id);
33-
}
34-
}
35-
3622
export function restorePaneStagedAttachments(
3723
context: ApplicationContext,
3824
paneId: string,
@@ -79,10 +65,9 @@ export function discardStateStagedAttachments(state: ChatPageHost | undefined):
7965
if (!state) {
8066
return;
8167
}
82-
const releasedIds = new Set<string>();
83-
releaseAttachments(state.chatAttachments, new Set(), releasedIds);
68+
releaseChatAttachmentPayloads(state.chatAttachments);
8469
for (const fallback of Object.values(state.chatComposerFallbackByScope)) {
85-
releaseAttachments(fallback.attachments, new Set(), releasedIds);
70+
releaseChatAttachmentPayloads(fallback.attachments);
8671
fallback.attachments = [];
8772
}
8873
state.chatAttachments = [];
@@ -103,7 +88,9 @@ export function replacePaneStagedAttachmentGatewayOwner(
10388
// reconnect or plugin-install rotation must not silently discard them.
10489
if (state) {
10590
const dropAnnotations = (attachments: readonly ChatAttachment[]) => {
106-
releaseAttachments(attachments.filter((attachment) => attachment.browserAnnotation));
91+
releaseChatAttachmentPayloads(
92+
attachments.filter((attachment) => attachment.browserAnnotation),
93+
);
10794
return attachments.filter((attachment) => !attachment.browserAnnotation);
10895
};
10996
state.chatAttachments = dropAnnotations(state.chatAttachments);

‎ui/src/pages/chat/chat-settings-patches.ts‎

Lines changed: 7 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -24,9 +24,7 @@ type ChatCommandSettingsContext = {
2424
defaultAgentId?: string;
2525
agentId?: string;
2626
};
27-
type PendingPatchStore = WeakMap<SessionCapability, Map<string, Promise<boolean>>>;
28-
29-
const pendingChatPickerPatches: PendingPatchStore = new WeakMap();
27+
const pendingChatPickerPatches = new WeakMap<SessionCapability, Map<string, Promise<boolean>>>();
3028

3129
function resolveChatPickerPatchKey(
3230
host: ChatPickerPatchHost,
@@ -64,25 +62,24 @@ function resolveChatPickerPatchKey(
6462
return `agent:${normalizeAgentId(resolvedAgentId)}:${settingsKey}`;
6563
}
6664

67-
function getPendingPatch(
68-
store: PendingPatchStore,
65+
export function getPendingChatPickerPatch(
6966
host: ChatPickerPatchHost,
7067
sessionKey: string,
7168
agentId?: string,
7269
): Promise<boolean> | undefined {
7370
const patchKey = resolveChatPickerPatchKey(host, sessionKey, agentId);
74-
return store.get(host.sessions)?.get(patchKey);
71+
return pendingChatPickerPatches.get(host.sessions)?.get(patchKey);
7572
}
7673

77-
function trackLatestPatch(
78-
store: PendingPatchStore,
74+
function trackPendingChatSettingsPatch(
7975
host: ChatPickerPatchHost,
8076
sessionKey: string,
8177
patchPromise: Promise<boolean>,
8278
agentId?: string,
8379
): void {
84-
const pendingBySession = store.get(host.sessions) ?? new Map<string, Promise<boolean>>();
85-
store.set(host.sessions, pendingBySession);
80+
const pendingBySession =
81+
pendingChatPickerPatches.get(host.sessions) ?? new Map<string, Promise<boolean>>();
82+
pendingChatPickerPatches.set(host.sessions, pendingBySession);
8683
const patchKey = resolveChatPickerPatchKey(host, sessionKey, agentId);
8784
pendingBySession.set(patchKey, patchPromise);
8885
void patchPromise.finally(() => {
@@ -92,23 +89,6 @@ function trackLatestPatch(
9289
});
9390
}
9491

95-
export function getPendingChatPickerPatch(
96-
host: ChatPickerPatchHost,
97-
sessionKey: string,
98-
agentId?: string,
99-
): Promise<boolean> | undefined {
100-
return getPendingPatch(pendingChatPickerPatches, host, sessionKey, agentId);
101-
}
102-
103-
function trackPendingChatSettingsPatch(
104-
host: ChatPickerPatchHost,
105-
sessionKey: string,
106-
patchPromise: Promise<boolean>,
107-
agentId?: string,
108-
): void {
109-
trackLatestPatch(pendingChatPickerPatches, host, sessionKey, patchPromise, agentId);
110-
}
111-
11292
export function patchChatSessionSettings(
11393
host: ChatPickerPatchHost,
11494
sessionKey: string,

‎ui/src/pages/chat/chat-state-controller.ts‎

Lines changed: 1 addition & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,6 @@ import type { AfterCommitEffect, RenderLifecycle } from "./render-lifecycle.ts";
1717
import { cancelChatScroll, scheduleCommittedChatScroll } from "./scroll.ts";
1818

1919
type ChatRenderLifecycleScope = {
20-
connectionEpoch: number;
2120
cancellations: Set<() => void>;
2221
};
2322

@@ -36,7 +35,6 @@ export class ChatStateController<TState extends ChatPageHost> implements Reactiv
3635
private forceScrollAfterUpdate = false;
3736
private readonly cleanups: Array<() => void> = [];
3837
private renderLifecycleConnected = false;
39-
private renderLifecycleConnectionEpoch = 0;
4038
private renderLifecycleScope: ChatRenderLifecycleScope | undefined;
4139

4240
constructor(private readonly host: ReactiveControllerHost) {
@@ -54,7 +52,6 @@ export class ChatStateController<TState extends ChatPageHost> implements Reactiv
5452
createRenderLifecycle(): RenderLifecycle {
5553
this.cancelRenderLifecycleScope();
5654
const scope: ChatRenderLifecycleScope = {
57-
connectionEpoch: this.renderLifecycleConnectionEpoch,
5855
cancellations: new Set(),
5956
};
6057
this.renderLifecycleScope = scope;
@@ -119,11 +116,7 @@ export class ChatStateController<TState extends ChatPageHost> implements Reactiv
119116
}
120117

121118
private isRenderLifecycleScopeActive(scope: ChatRenderLifecycleScope): boolean {
122-
return (
123-
this.renderLifecycleConnected &&
124-
this.renderLifecycleScope === scope &&
125-
scope.connectionEpoch === this.renderLifecycleConnectionEpoch
126-
);
119+
return this.renderLifecycleConnected && this.renderLifecycleScope === scope;
127120
}
128121

129122
private requestUpdateForScope(scope: ChatRenderLifecycleScope): boolean {
@@ -252,7 +245,6 @@ export class ChatStateController<TState extends ChatPageHost> implements Reactiv
252245
}
253246

254247
hostConnected() {
255-
this.renderLifecycleConnectionEpoch += 1;
256248
this.renderLifecycleConnected = true;
257249
// A lifecycle created while detached must never become active on reconnect.
258250
this.cancelRenderLifecycleScope();

0 commit comments

Comments
 (0)