Skip to content

Commit f4beff1

Browse files
authored
fix(ui): stop per-message branch-list polling and unlatch transient branch failures (#124094)
* fix(ui): stop per-message branch-list polling and unlatch transient branch failures Four coupled defects around the chat branch dropdown, fixed at their owners: - Every persisted session.message and every sessions.changed triggered an unconditional sessions.branches.list RPC per viewing client; the gateway branch cache watermark is max(seq), so each message append made the next list a full transcript rescan. Branch topology only changes on structural mutations, and the producer already records the reason — the reload is now gated on rewind/branch-switch/fork/reset/new. - A transient listBranches failure recorded success (chatBranchesSessionKey set with branches=[]), permanently hiding the branch dropdown for that session+connection with no visible outcome. The catch no longer latches; the next history load retries naturally. - sessions.branches.list errored for upstream-linked sessions even though "no local branches" is their truthful steady state; the fresh-session sibling was already converted to {branches: []} for the same reason (spurious gateway-log failures). Only mutating siblings fail closed now. - Branch state was keyed by raw session-key spelling and strict-compared in the header and history gate, blanking the dropdown across the legacy main -> agent:main:main alias window (same class as #124020); both compares use areUiSessionKeysEquivalent. Riders per pathfinder rule: deleted the write-only chatBranchesLoading flag, a duplicate activeLeafEntryId recompute, and two provably-no-op second dropPreSessionStartAnnouncePairs passes in chat-history-pages.ts (the filter is single-pass complete and its inputs were already filtered). Production LOC +27/-34 (net -7); regression tests fail pre-fix. * refactor(ui): move branch-display ownership out of the header render check-lint-core-4 flagged chat-pane-header.ts at 702 counted lines after the equivalence gate landed there. The branches-for-display decision belongs to the state owner anyway: displayedChatSessionBranches in chat-history.ts now owns it and the header render consumes the fact.
1 parent aaa509b commit f4beff1

8 files changed

Lines changed: 86 additions & 49 deletions

File tree

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

Lines changed: 6 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -407,11 +407,9 @@ export async function readChatHistoryPage(params: {
407407
max,
408408
Math.max(readPage.messages.length, readPage.totalMessages > pageOffset ? 1 : 0),
409409
);
410-
const rawMessages = localMessages;
411-
const recencyFilteredMessages = dropPreSessionStartAnnouncePairs(
412-
rawMessages,
413-
typeof entry?.sessionStartedAt === "number" ? entry.sessionStartedAt : undefined,
414-
);
410+
// localMessages is already announce-filtered above; the filter is
411+
// single-pass complete, so no second pass is needed.
412+
const recencyFilteredMessages = localMessages;
415413
const projected = isTailPage
416414
? projectRecentChatDisplayMessages(recencyFilteredMessages, {
417415
maxChars: effectiveMaxChars,
@@ -539,15 +537,9 @@ export async function readChatHistoryPage(params: {
539537
},
540538
};
541539
}
542-
const rawMessages = cliHistory.messages;
543-
// Drop subagent_announce pairs (user inter-session announce + adjacent
544-
// assistant) whose record timestamp predates the current session's
545-
// sessionStartedAt. Run after CLI history imports too, because those
546-
// timestamped messages share the same chat.history response surface.
547-
const recencyFilteredMessages = dropPreSessionStartAnnouncePairs(
548-
rawMessages,
549-
typeof entry?.sessionStartedAt === "number" ? entry.sessionStartedAt : undefined,
550-
);
540+
// The imported case returned above, so these are the already announce-filtered
541+
// local messages; the filter is single-pass complete, so no second pass is needed.
542+
const recencyFilteredMessages = cliHistory.messages;
551543
const displayMessages = projectRecentChatDisplayMessages(recencyFilteredMessages, {
552544
maxChars: effectiveMaxChars,
553545
maxMessages: max,

‎src/gateway/server-methods/sessions-rewind.test.ts‎

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -454,21 +454,21 @@ describe("session message-cut methods", () => {
454454
);
455455
});
456456

457-
it("rejects externally owned conversations", async () => {
457+
it("rejects mutation but lists empty branches for externally owned conversations", async () => {
458458
linkToUpstreamConversation();
459459
const respond = await invoke("sessions.branches.switch", "off-path-entry");
460+
expect(respond).toHaveBeenCalledWith(
461+
false,
462+
undefined,
463+
expect.objectContaining({
464+
code: ErrorCodes.INVALID_REQUEST,
465+
message: expect.stringContaining("external agent harness"),
466+
}),
467+
);
468+
// Listing is read-only: "no local branches" is the truthful steady state,
469+
// not an error to latch into the UI.
460470
const listed = await invoke("sessions.branches.list");
461-
462-
for (const response of [respond, listed]) {
463-
expect(response).toHaveBeenCalledWith(
464-
false,
465-
undefined,
466-
expect.objectContaining({
467-
code: ErrorCodes.INVALID_REQUEST,
468-
message: expect.stringContaining("external agent harness"),
469-
}),
470-
);
471-
}
471+
expect(listed).toHaveBeenCalledWith(true, { branches: [] }, undefined);
472472
});
473473

474474
it.each(["sessions.rewind", "sessions.branches.switch"] as const)(

‎src/gateway/server-methods/sessions-rewind.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -177,7 +177,9 @@ async function listBranches(options: GatewayRequestHandlerOptions): Promise<void
177177
return;
178178
}
179179
if (readSessionUpstreamLink(current.canonicalKey, current.target.agentId)) {
180-
respond(false, undefined, errorShape(ErrorCodes.INVALID_REQUEST, EXTERNAL_CONVERSATION_ERROR));
180+
// Upstream-linked sessions truthfully have no local branches; only the
181+
// mutating siblings (rewind/switch/fork) must fail closed on them.
182+
respond(true, { branches: [] }, undefined);
181183
return;
182184
}
183185
const result = await listSessionBranches({

‎ui/src/pages/chat/chat-history.test.ts‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -416,6 +416,45 @@ describe("switchChatHistoryBranch", () => {
416416
expect(state.chatBranchesConnectionEpoch).toBe(state.connectionEpoch);
417417
});
418418

419+
it("retries the branch list on the next history load after a transient failure", async () => {
420+
const state = createState({ messages: [] }) as TestState & {
421+
sessions: { listBranches: ReturnType<typeof vi.fn> };
422+
};
423+
state.sessions = {
424+
listBranches: vi
425+
.fn()
426+
.mockRejectedValueOnce(new Error("gateway hiccup"))
427+
.mockResolvedValue([
428+
{ leafEntryId: "tip", headline: "tip", messageCount: 1, active: true },
429+
]),
430+
setModelOverride: vi.fn(),
431+
};
432+
433+
await loadChatHistory(state);
434+
// The transient failure must not latch success state; the next load retries.
435+
expect(state.chatBranchesSessionKey ?? null).toBeNull();
436+
437+
await loadChatHistory(state);
438+
expect(state.sessions.listBranches).toHaveBeenCalledTimes(2);
439+
expect(state.chatBranchesSessionKey).toBe(state.sessionKey);
440+
expect(state.chatBranches).toHaveLength(1);
441+
});
442+
443+
it("treats the legacy main alias and canonical key as the same branch owner", async () => {
444+
const state = createState({ messages: [] }) as TestState & {
445+
sessions: { listBranches: ReturnType<typeof vi.fn> };
446+
};
447+
state.sessionKey = "main";
448+
state.chatBranchesSessionKey = "agent:main:main";
449+
state.chatBranchesConnectionEpoch = state.connectionEpoch;
450+
state.sessions = { listBranches: vi.fn().mockResolvedValue([]), setModelOverride: vi.fn() };
451+
452+
await loadChatHistory(state);
453+
454+
// Equivalent spellings must not force a redundant branch reload.
455+
expect(state.sessions.listBranches).not.toHaveBeenCalled();
456+
});
457+
419458
it("starts a fresh snapshot and rejects in-flight history after a same-key branch switch", async () => {
420459
let resolvePreviousHistory!: (result: ChatHistoryResult) => void;
421460
const previousHistory = new Promise<ChatHistoryResult>((resolve) => {

‎ui/src/pages/chat/chat-history.ts‎

Lines changed: 14 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -311,7 +311,6 @@ export type ChatState = {
311311
chatBranches?: SessionBranch[];
312312
chatBranchesSessionKey?: string | null;
313313
chatBranchesConnectionEpoch?: number | null;
314-
chatBranchesLoading?: boolean;
315314
requestUpdate?: () => void;
316315
};
317316

@@ -1371,6 +1370,15 @@ export async function switchChatHistoryBranch(
13711370
}
13721371
}
13731372

1373+
/** Branches for the current pane; equivalence covers alias-canonicalization windows (#124020 class). */
1374+
export function displayedChatSessionBranches(
1375+
state: Pick<ChatState, "chatBranches" | "chatBranchesSessionKey" | "sessionKey">,
1376+
): SessionBranch[] {
1377+
return areUiSessionKeysEquivalent(state.chatBranchesSessionKey, state.sessionKey)
1378+
? (state.chatBranches ?? [])
1379+
: [];
1380+
}
1381+
13741382
export async function loadChatBranches(state: ChatState): Promise<void> {
13751383
const sessions = state.sessions;
13761384
const client = state.client;
@@ -1388,7 +1396,6 @@ export async function loadChatBranches(state: ChatState): Promise<void> {
13881396
const version = ++requests.branchVersion;
13891397
const connectionEpoch = state.connectionEpoch;
13901398
const agentParams = scopedAgentParamsForSession(state, sessionKey);
1391-
state.chatBranchesLoading = true;
13921399
try {
13931400
const branches = await sessions.listBranches(sessionKey, agentParams);
13941401
if (
@@ -1404,19 +1411,11 @@ export async function loadChatBranches(state: ChatState): Promise<void> {
14041411
state.chatBranchesSessionKey = sessionKey;
14051412
state.chatBranchesConnectionEpoch = connectionEpoch;
14061413
} catch {
1407-
if (
1408-
requests.branchVersion === version &&
1409-
state.client === client &&
1410-
state.connectionEpoch === connectionEpoch &&
1411-
visibleSessionMatches(state, sessionKey, agentParams.agentId)
1412-
) {
1413-
state.chatBranches = [];
1414-
state.chatBranchesSessionKey = sessionKey;
1415-
state.chatBranchesConnectionEpoch = connectionEpoch;
1416-
}
1414+
// Leave chatBranchesSessionKey unset so the next history load retries;
1415+
// recording success here latched transient failures into a permanently
1416+
// hidden branch dropdown with no visible outcome.
14171417
} finally {
14181418
if (requests.branchVersion === version) {
1419-
state.chatBranchesLoading = false;
14201419
state.requestUpdate?.();
14211420
}
14221421
}
@@ -1452,7 +1451,7 @@ export async function loadChatHistory(
14521451
}
14531452
if (
14541453
opts.deferBranches !== true &&
1455-
(state.chatBranchesSessionKey !== sessionKey ||
1454+
(!areUiSessionKeysEquivalent(state.chatBranchesSessionKey, sessionKey) ||
14561455
state.chatBranchesConnectionEpoch !== connectionEpoch)
14571456
) {
14581457
void loadChatBranches(state);
@@ -1662,7 +1661,7 @@ async function loadChatHistoryUncached(
16621661
},
16631662
);
16641663
if (Object.hasOwn(res.sessionInfo ?? {}, "activeLeafEntryId")) {
1665-
state.chatDisplayedLeafEntryId = res.sessionInfo?.activeLeafEntryId?.trim() || null;
1664+
state.chatDisplayedLeafEntryId = nextDisplayedLeafEntryId;
16661665
}
16671666
retirePersistedSteeredChips(state);
16681667
state.chatHistoryPagination = reconciledHistory?.pagination ?? nextPagination;

‎ui/src/pages/chat/chat-pane-header.ts‎

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ import {
2828
} from "../../lib/sessions/session-key.ts";
2929
import { isActiveTask } from "../../lib/tasks/data.ts";
3030
import { renderBoardViewSwitch } from "./board-session-surface.ts";
31+
import { displayedChatSessionBranches } from "./chat-history.ts";
3132
import { resolveChatPaneDesktopTarget, resolveChatPanePlacement } from "./chat-pane-placement.ts";
3233
import { ChatPaneSessionMenu } from "./chat-pane-session-menu.ts";
3334
import { readChatSessionActionAccess } from "./chat-session-action-access.ts";
@@ -366,10 +367,7 @@ export abstract class ChatPaneHeader extends ChatPaneSessionMenu {
366367
workspaceIcon: this.resolveWorkspaceIcon(workspace.root ? row?.key : undefined),
367368
parentSession: resolveChatPaneParentSession(row, this.state?.sessionsResult?.sessions ?? []),
368369
branch,
369-
branches:
370-
this.state && this.state.chatBranchesSessionKey === this.state.sessionKey
371-
? (this.state.chatBranches ?? [])
372-
: [],
370+
branches: this.state ? displayedChatSessionBranches(this.state) : [],
373371
branchSwitchDisabledReason,
374372
platform: this.headerPlatform,
375373
canReveal,

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

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -202,7 +202,6 @@ function handleSessionMessageEvent(state: ChatPageHost, payload: unknown) {
202202
// replaces it in place instead of appending below the newer user turn.
203203
applyLiveSessionMessage(state, payload, event.hasActiveRun ?? undefined);
204204
retirePersistedSteeredChips(state);
205-
void loadChatBranches(state);
206205
}
207206
if (matchesChat && event.archived !== null) {
208207
state.selectedChatSessionArchived = event.archived;
@@ -262,6 +261,11 @@ function replayPendingSessionMessageReload(
262261
void loadChatHistory(state).finally(() => state.requestUpdate?.());
263262
}
264263

264+
// Branch topology only changes on structural mutations; the producer records
265+
// the reason, so reload branches only for those instead of on every
266+
// sessions.changed (each cache miss rescans the full transcript on the gateway).
267+
const BRANCH_TOPOLOGY_REASONS = new Set(["rewind", "branch-switch", "fork", "reset", "new"]);
268+
265269
function handleSessionsChangedEvent(state: ChatPageHost, payload: unknown) {
266270
const runIdBeforeApply = state.chatRunId;
267271
const event = readSessionChangedEvent(payload);
@@ -280,7 +284,11 @@ function handleSessionsChangedEvent(state: ChatPageHost, payload: unknown) {
280284
// only proof that its old live and pending transcript no longer exists.
281285
reduceChatSessionProjection(state, { type: "sessionReset" }, { scope });
282286
}
283-
if (matchesChat) {
287+
if (
288+
matchesChat &&
289+
typeof source?.reason === "string" &&
290+
BRANCH_TOPOLOGY_REASONS.has(source.reason)
291+
) {
284292
void loadChatBranches(state);
285293
}
286294
if (event && matchesChat && event.archived !== null) {

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

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -170,7 +170,6 @@ export function createPageState(
170170
chatBranches: [],
171171
chatBranchesSessionKey: null,
172172
chatBranchesConnectionEpoch: null,
173-
chatBranchesLoading: false,
174173
chatToolMessages: [],
175174
chatThinkingLevel: null,
176175
chatVerboseLevel: null,

0 commit comments

Comments
 (0)