Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(desktop): keep a local rename over catalog pages requested before it settled
Alfredo Lopezd62c072bf55b
diff --git a/desktop-app/ui/src/hooks/__tests__/useChatStore.test.tsx b/desktop-app/ui/src/hooks/__tests__/useChatStore.test.tsxindex ae1c80ac9..813c55b0c 100644--- a/desktop-app/ui/src/hooks/__tests__/useChatStore.test.tsx+++ b/desktop-app/ui/src/hooks/__tests__/useChatStore.test.tsx@@ -114,10 +114,34 @@ describe('useChatStore remote request cache', () => {await expect(stale).rejects.toThrow('host access revoked')// Witness: the fresh request is still the cached one for this key.- await expect(result.current.listSessions('host', query)).resolves.toEqual({ items: [] })+ expect(result.current.listSessions('host', query)).toBe(fresh)expect(listSessions).toHaveBeenCalledTimes(2)})+ // #1091 A21 — each page carries the sequence number taken when its request was+ // sent, so the renderer can tell a page requested before a rename settled.+ it('stamps each catalog request when it is sent and keeps the stamp on a cache hit', async () => {+ const listSessions = vi.fn(async () => ({ items: [] }))+ Object.defineProperty(window, 'clerum', {+ configurable: true,+ value: { rpc: { listSessions } },+ })+ const { result } = renderHook(() => useChatStore())+ result.current.setRemoteCacheScope('authenticated:user-seq:team-seq')+ const query = { agent: 'host', limit: 50 }++ const first = await result.current.listSessions('host', query)+ const cached = await result.current.listSessions('host', query)+ const other = await result.current.listSessions('host-b', { agent: 'host-b', limit: 50 })+ const forced = await result.current.listSessions('host', query, { force: true })++ // Witness: one upstream call per issued request; the cache hit made none.+ expect(listSessions).toHaveBeenCalledTimes(3)+ expect(cached.issueSeq).toBe(first.issueSeq)+ expect(other.issueSeq).toBeGreaterThan(first.issueSeq)+ expect(forced.issueSeq).toBeGreaterThan(other.issueSeq)+ })+// #654 M12 — the host-model catalog has exactly one cache, in// `hostModelSelectionStore`, which also owns revision ordering. A second TTL// layer here could only serve a response read BEFORE a write, which is thediff --git a/desktop-app/ui/src/hooks/domain/__tests__/chatListRenameCatalogOrder.test.tsx b/desktop-app/ui/src/hooks/domain/__tests__/chatListRenameCatalogOrder.test.tsxnew file mode 100644index 000000000..f9af97a3a--- /dev/null+++ b/desktop-app/ui/src/hooks/domain/__tests__/chatListRenameCatalogOrder.test.tsx@@ -0,0 +1,515 @@+// @vitest-environment jsdom+/**+ * #1091 A21 — a catalog page requested before a user rename settled must not+ * write the title it carries over the rename, on disk or in the sidebar.+ *+ * The index, rename and reconcile IPCs run on a real `ChatStore` in a temp dir,+ * so the per-agent `serializeIndex` queue and the index file are the+ * production ones. The "server" is one mutable title: a successful PATCH+ * updates it and `listSessions` reads it when the request is sent, so an old+ * title can only arrive through a page requested earlier (in flight or cached).+ *+ * Every test ends with a positive control: a page requested after the rename+ * settled, carrying another device's title, is written and shown.+ */+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { act, cleanup, waitFor } from '@testing-library/react'+import { mkdtempSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { ChatStore } from '../../../../../src/chatStore'+import { renderController } from './__fixtures__/controllerHarness'+import { type MockClerum, installMockClerum, uninstallMockClerum } from './__fixtures__/mockClerum'++;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true++const AGENT = 'agent-x'+const NOW = '2026-09-12T00:00:00.000Z'+const CATALOG_TTL_MS = 5_000++type ReconcileCall = { agentRef: string; titles: Record<string, string | undefined> }+type View = ReturnType<typeof renderController>++let clerum: MockClerum+let dir: string+let store: ChatStore+let serverTitle: string+let reconcileCalls: ReconcileCall[]+let reconcileWrites: Promise<unknown>[]+let renameIpcTitles: string[]+let patchTitles: string[]+let clockOffset: number+let agentListVariant: number+/** Per-title hooks into the local rename IPC: wait for a gate, then write or fail. */+let renameIpcBehaviour: Map<string, { gate?: Promise<void>; fail?: boolean }>++function deferred<T = void>() {+ let resolve!: (v: T) => void+ let reject!: (e?: unknown) => void+ const promise = new Promise<T>((res, rej) => {+ resolve = res+ reject = rej+ })+ return { promise, resolve, reject }+}++function wireStore(c: MockClerum, s: ChatStore) {+ c.chat.getIndex.mockImplementation((agentRef: string) => s.getIndex(agentRef))+ c.chat.create.mockImplementation((agentRef: string, id: string) => s.createChat(agentRef, id))+ c.chat.rename.mockImplementation(async (agentRef: string, id: string, title: string) => {+ renameIpcTitles.push(title)+ const behaviour = renameIpcBehaviour.get(title)+ if (behaviour?.fail) {+ if (behaviour.gate) await behaviour.gate+ throw new Error('local rename failed')+ }+ // Main enqueues the write at once (serializeIndex FIFO); only the reply to+ // the renderer waits, as IPC latency does.+ const write = s.renameChat(agentRef, id, title)+ if (behaviour?.gate) await behaviour.gate+ return write+ })+ c.chat.reconcileServerSessions.mockImplementation(+ (agentRef: string, sessions: Array<{ chatId: string; title?: string }>) => {+ const write = s.upsertServerSessions(agentRef, sessions)+ reconcileCalls.push({+ agentRef,+ titles: Object.fromEntries(sessions.map(x => [x.chatId, x.title])),+ })+ reconcileWrites.push(write)+ return write+ }+ )+}++function snapshotPage() {+ return {+ items: [{ agent: AGENT, chatId: 'c1', turnCount: 1, lastActivityAt: NOW, title: serverTitle }],+ }+}++/** listSessions reads the server title when called and answers when `gate` opens. */+function serveGated(gate: Promise<void>) {+ clerum.rpc.listSessions.mockImplementation(async () => {+ const page = snapshotPage()+ await gate+ return page+ })+}++function serveImmediately() {+ clerum.rpc.listSessions.mockImplementation(async () => snapshotPage())+}++/** The PATCH answers when `gate` opens; a success updates the server title. */+function gatePatch(gate: Promise<void>) {+ clerum.rpc.renameSession.mockImplementation(+ async (_h: string, _a: string, _c: string, title: string) => {+ patchTitles.push(title)+ await gate+ serverTitle = title+ return { title }+ }+ )+}++function agentCalls(fromIndex = 0): ReconcileCall[] {+ return reconcileCalls.slice(fromIndex).filter(call => call.agentRef === AGENT)+}++async function diskTitleAfterRestart(): Promise<string | undefined> {+ await Promise.all(reconcileWrites.map(write => write.catch(() => undefined)))+ // A new ChatStore on the same directory is an app restart.+ const restarted = new ChatStore(dir)+ return (await restarted.getIndex(AGENT)).chats.find(c => c.id === 'c1')?.title+}++function sidebarTitle(view: View): string | undefined {+ return view.result.current.chatList.find(c => c.id === 'c1')?.title+}++function latestTitle(view: View): string | undefined {+ return (view.result.current.latestChatSessions as Array<{ id: string; title: string }>).find(+ c => c.id === 'c1'+ )?.title+}++/** Re-runs the cross-Host publication, which requests one page per Host. */+async function pollCatalog(view: View) {+ agentListVariant += 1+ const agentNames = [AGENT, ...Array.from({ length: agentListVariant }, (_, i) => `agent-y${i}`)]+ await act(async () => {+ view.rerender({ agentNames })+ })+}++function expireCatalogCache() {+ clockOffset += CATALOG_TTL_MS + 1_000+}++/** Positive control: another device's rename, requested after settle, is accepted. */+async function expectFreshPageAccepted(view: View) {+ serverTitle = 'other-device'+ expireCatalogCache()+ serveImmediately()+ const before = reconcileCalls.length+ await pollCatalog(view)+ await waitFor(() =>+ expect(agentCalls(before).some(call => call.titles.c1 === 'other-device')).toBe(true)+ )+ await waitFor(() => expect(latestTitle(view)).toBe('other-device'))+ expect(await diskTitleAfterRestart()).toBe('other-device')+}++async function mountWithOldTitle(): Promise<View> {+ const view = renderController({ selectedAgent: AGENT, agentNames: [AGENT] })+ await waitFor(() => expect(sidebarTitle(view)).toBe('old'))+ return view+}++beforeEach(async () => {+ clerum = installMockClerum()+ dir = mkdtempSync(join(tmpdir(), 'chat-rename-catalog-order-'))+ store = new ChatStore(dir)+ await store.createChat(AGENT, 'c1')+ await store.renameChat(AGENT, 'c1', 'old')+ serverTitle = 'old'+ reconcileCalls = []+ reconcileWrites = []+ renameIpcTitles = []+ patchTitles = []+ renameIpcBehaviour = new Map()+ clockOffset = 0+ agentListVariant = 0+ const realNow = Date.now.bind(Date)+ vi.spyOn(Date, 'now').mockImplementation(() => realNow() + clockOffset)+ gatePatch(Promise.resolve())+ wireStore(clerum, store)+})++afterEach(async () => {+ cleanup()+ // A catalog read scheduled after first paint (`scheduleAfterFirstPaint`,+ // two animation frames) survives unmount. Let it reach this test's bridge+ // before the next test installs its own: otherwise it hits the next mock's+ // empty default, and the module-level catalog cache serves that empty page to+ // the next mount.+ await new Promise<void>(resolve =>+ requestAnimationFrame(() => requestAnimationFrame(() => resolve()))+ )+ vi.restoreAllMocks()+ uninstallMockClerum()+})++describe('a page requested before the rename and delivered after it settled', () => {+ async function renameWhilePageInFlight(): Promise<View> {+ const pageGate = deferred()+ let sourceCalls = 0+ clerum.rpc.listSessions.mockImplementation(async () => {+ sourceCalls += 1+ const page = snapshotPage()+ await pageGate.promise+ return page+ })+ const view = renderController({ selectedAgent: AGENT, agentNames: [AGENT] })+ await waitFor(() => expect(sourceCalls).toBeGreaterThan(0))+ await waitFor(() => expect(sidebarTitle(view)).toBe('old'))+ expect(agentCalls()).toHaveLength(0)++ await act(async () => {+ await view.result.current.handleRenameChatForAgent(AGENT, 'c1', 'new')+ })+ expect(renameIpcTitles).toEqual(['new'])+ expect(patchTitles).toEqual(['new'])+ expect(serverTitle).toBe('new')+ expect(await diskTitleAfterRestart()).toBe('new')++ await act(async () => {+ pageGate.resolve()+ })+ // Witness: the old page was processed and reached the store without a title.+ await waitFor(() => expect(agentCalls().length).toBeGreaterThan(0))+ expect(agentCalls().every(call => 'c1' in call.titles && call.titles.c1 === undefined)).toBe(+ true+ )+ return view+ }++ it('T1: keeps the renamed title on disk', async () => {+ const view = await renameWhilePageInFlight()+ expect(await diskTitleAfterRestart()).toBe('new')+ await expectFreshPageAccepted(view)+ })++ it('T7: keeps the renamed title in the sidebar and the Latest list', async () => {+ const view = await renameWhilePageInFlight()+ await waitFor(() => expect(latestTitle(view)).toBeDefined())+ expect(sidebarTitle(view)).toBe('new')+ expect(latestTitle(view)).toBe('new')+ await expectFreshPageAccepted(view)+ })+})++describe('a page served from the catalog cache after the rename', () => {+ it('T2: is not written over the rename', async () => {+ const sourceTitles: string[] = []+ clerum.rpc.listSessions.mockImplementation(async (hostRef: string) => {+ if (hostRef === AGENT) sourceTitles.push(serverTitle)+ return snapshotPage()+ })+ const view = await mountWithOldTitle()+ await waitFor(() => expect(agentCalls().some(call => call.titles.c1 === 'old')).toBe(true))++ await act(async () => {+ await view.result.current.handleRenameChatForAgent(AGENT, 'c1', 'new')+ })+ expect(serverTitle).toBe('new')+ const before = reconcileCalls.length++ await pollCatalog(view)+ // Witness: the poll was answered from the cache (no new fetch for this Host)+ // and its page reached the store without a title.+ await waitFor(() => expect(agentCalls(before).length).toBeGreaterThan(0))+ expect(sourceTitles).toEqual(['old'])+ expect(agentCalls(before).every(call => call.titles.c1 === undefined)).toBe(true)+ expect(await diskTitleAfterRestart()).toBe('new')+ expect(latestTitle(view)).toBe('new')++ await expectFreshPageAccepted(view)+ })+})++describe('a page processed while the local rename write is in flight', () => {+ async function renameDuringLocalWrite(patch: 'ok' | 'fail'): Promise<View> {+ const localReply = deferred()+ renameIpcBehaviour.set('new', { gate: localReply.promise })+ if (patch === 'fail') {+ clerum.rpc.renameSession.mockImplementation(async (_h, _a, _c, title: string) => {+ patchTitles.push(title)+ throw new Error('fetch failed')+ })+ }+ const pageGate = deferred()+ serveGated(pageGate.promise)+ const view = await mountWithOldTitle()++ let renaming: Promise<void> | undefined+ await act(async () => {+ renaming = view.result.current.handleRenameChatForAgent(AGENT, 'c1', 'new')+ })+ // Witness: the local write is queued in main and the PATCH waits for it.+ await waitFor(() => expect(renameIpcTitles).toEqual(['new']))+ expect(patchTitles).toEqual([])++ await act(async () => {+ pageGate.resolve()+ })+ await waitFor(() => expect(agentCalls().length).toBeGreaterThan(0))+ expect(agentCalls().every(call => call.titles.c1 === undefined)).toBe(true)++ await act(async () => {+ localReply.resolve()+ await renaming+ })+ expect(patchTitles).toEqual(['new'])+ return view+ }++ it('T3: PATCH succeeds — disk and sidebar keep the rename', async () => {+ const view = await renameDuringLocalWrite('ok')+ expect(serverTitle).toBe('new')+ expect(sidebarTitle(view)).toBe('new')+ expect(await diskTitleAfterRestart()).toBe('new')+ await expectFreshPageAccepted(view)+ })++ it('T4: PATCH fails — an offline restart still shows the rename', async () => {+ const view = await renameDuringLocalWrite('fail')+ expect(serverTitle).toBe('old')+ expect(sidebarTitle(view)).toBe('new')+ expect(await diskTitleAfterRestart()).toBe('new')++ view.unmount()+ cleanup()+ uninstallMockClerum()+ clerum = installMockClerum()+ reconcileCalls = []+ reconcileWrites = []+ wireStore(clerum, new ChatStore(dir))+ clerum.rpc.listSessions.mockRejectedValue(new Error('fetch failed'))+ const after = renderController({ selectedAgent: AGENT, agentNames: [AGENT] })+ await waitFor(() => expect(clerum.chat.getIndex).toHaveBeenCalled())+ await waitFor(() => expect(sidebarTitle(after)).toBeDefined())+ expect(sidebarTitle(after)).toBe('new')+ })+})++describe('a page requested while the PATCH is pending', () => {+ it.each(['before', 'after'] as const)(+ 'T5: delivered %s the 200 — not written over the rename',+ async order => {+ serveImmediately()+ const view = await mountWithOldTitle()+ await waitFor(() => expect(agentCalls().some(call => call.titles.c1 === 'old')).toBe(true))++ const patch = deferred()+ gatePatch(patch.promise)+ let renaming: Promise<void> | undefined+ await act(async () => {+ renaming = view.result.current.handleRenameChatForAgent(AGENT, 'c1', 'new')+ })+ await waitFor(() => expect(patchTitles).toEqual(['new']))++ expireCatalogCache()+ const pageGate = deferred()+ let pageRequested = false+ clerum.rpc.listSessions.mockImplementation(async (hostRef: string) => {+ const page = snapshotPage()+ if (hostRef === AGENT) pageRequested = true+ await pageGate.promise+ return page+ })+ const before = reconcileCalls.length+ await pollCatalog(view)+ // Witness: the page was requested while the PATCH was pending.+ await waitFor(() => expect(pageRequested).toBe(true))+ expect(serverTitle).toBe('old')++ const deliverPage = async () => {+ await act(async () => {+ pageGate.resolve()+ })+ await waitFor(() => expect(agentCalls(before).length).toBeGreaterThan(0))+ }+ const answerPatch = async () => {+ await act(async () => {+ patch.resolve()+ await renaming+ })+ expect(serverTitle).toBe('new')+ }+ if (order === 'before') {+ await deliverPage()+ await answerPatch()+ } else {+ await answerPatch()+ await deliverPage()+ }++ expect(agentCalls(before).every(call => call.titles.c1 === undefined)).toBe(true)+ expect(latestTitle(view)).toBe('new')+ expect(await diskTitleAfterRestart()).toBe('new')+ await expectFreshPageAccepted(view)+ }+ )+})++describe('re-renames', () => {+ it('T6a: a superseded rename never sends its PATCH', async () => {+ serveImmediately()+ const view = await mountWithOldTitle()+ const firstReply = deferred()+ renameIpcBehaviour.set('first', { gate: firstReply.promise })++ let first: Promise<void> | undefined+ await act(async () => {+ first = view.result.current.handleRenameChatForAgent(AGENT, 'c1', 'first')+ })+ await waitFor(() => expect(renameIpcTitles).toEqual(['first']))+ await act(async () => {+ await view.result.current.handleRenameChatForAgent(AGENT, 'c1', 'second')+ })+ expect(patchTitles).toEqual(['second'])++ await act(async () => {+ firstReply.resolve()+ await first+ })+ // Witness: the first rename's local write completed (FIFO order on disk).+ expect(renameIpcTitles).toEqual(['first', 'second'])+ expect(patchTitles).toEqual(['second'])+ expect(serverTitle).toBe('second')+ expect(await diskTitleAfterRestart()).toBe('second')+ await expectFreshPageAccepted(view)+ })++ it('T6b: a failed local write hands the key back to the pending rename it replaced', async () => {+ serveImmediately()+ const view = await mountWithOldTitle()+ const firstPatch = deferred()+ gatePatch(firstPatch.promise)+ let first: Promise<void> | undefined+ await act(async () => {+ first = view.result.current.handleRenameChatForAgent(AGENT, 'c1', 'first')+ })+ await waitFor(() => expect(patchTitles).toEqual(['first']))++ renameIpcBehaviour.set('second', { fail: true })+ let secondError: unknown+ await act(async () => {+ await view.result.current+ .handleRenameChatForAgent(AGENT, 'c1', 'second')+ .catch(error => (secondError = error))+ })+ expect(secondError).toBeInstanceOf(Error)+ expect(renameIpcTitles).toEqual(['first', 'second'])++ // The first PATCH is still pending: a page requested now carries the old+ // server title and must still be refused.+ expireCatalogCache()+ serveImmediately()+ const before = reconcileCalls.length+ await pollCatalog(view)+ await waitFor(() => expect(agentCalls(before).length).toBeGreaterThan(0))+ expect(serverTitle).toBe('old')+ expect(agentCalls(before).every(call => call.titles.c1 === undefined)).toBe(true)+ expect(await diskTitleAfterRestart()).toBe('first')++ await act(async () => {+ firstPatch.resolve()+ await first+ })+ expect(serverTitle).toBe('first')+ expect(patchTitles).toEqual(['first'])+ await expectFreshPageAccepted(view)+ })++ it('T6c: a failed local write after the replaced rename settled leaves no pending rename', async () => {+ serveImmediately()+ const view = await mountWithOldTitle()+ const firstPatch = deferred()+ gatePatch(firstPatch.promise)+ let first: Promise<void> | undefined+ await act(async () => {+ first = view.result.current.handleRenameChatForAgent(AGENT, 'c1', 'first')+ })+ await waitFor(() => expect(patchTitles).toEqual(['first']))++ const secondReply = deferred()+ renameIpcBehaviour.set('second', { gate: secondReply.promise, fail: true })+ let second: Promise<void> | undefined+ await act(async () => {+ second = view.result.current.handleRenameChatForAgent(AGENT, 'c1', 'second')+ })+ await waitFor(() => expect(renameIpcTitles).toEqual(['first', 'second']))++ // The first rename's 200 lands while the second waits for its local write.+ await act(async () => {+ firstPatch.resolve()+ await first+ })+ expect(serverTitle).toBe('first')++ let secondError: unknown+ await act(async () => {+ secondReply.resolve()+ await second?.catch(error => (secondError = error))+ })+ expect(secondError).toBeInstanceOf(Error)+ expect(patchTitles).toEqual(['first'])+ expect(await diskTitleAfterRestart()).toBe('first')++ // Nothing is pending any more, so a later server title is accepted.+ await expectFreshPageAccepted(view)+ })+})diff --git a/desktop-app/ui/src/hooks/domain/useChatListController.ts b/desktop-app/ui/src/hooks/domain/useChatListController.tsindex 0331beb44..7e424bb8c 100644--- a/desktop-app/ui/src/hooks/domain/useChatListController.ts+++ b/desktop-app/ui/src/hooks/domain/useChatListController.ts@@ -20,17 +20,20 @@ import {isNetworkError,} from '../../lib/format'import { scheduleAfterFirstPaint } from '../scheduleAfterFirstPaint'-import type { useChatStore } from '../useChatStore'+import { nextCatalogSequence, type useChatStore } from '../useChatStore'import { type SessionFsmEvent, type SessionFsmStore, seedSessionSnapshots } from './sessionFsm'const SESSION_CATALOG_PAGE_LIMIT = 50+/** A catalog page and the sequence number of the request that produced it. */+type IssuedCatalogPage = Awaited<ReturnType<ReturnType<typeof useChatStore>['listSessions']>>+async function readSessionCatalog(chatStore: ReturnType<typeof useChatStore>,agentRef: string,query: Parameters<ReturnType<typeof useChatStore>['listSessions']>[1],options: { force?: boolean } = {}-): Promise<SessionsListResult> {+): Promise<IssuedCatalogPage> {try {return await chatStore.listSessions(agentRef, query, options)} catch (error) {@@ -229,20 +232,48 @@ function knownServerMessageCount(session: SessionsListResult['items'][number]):/** A cross-agent catalog session tagged with the agent whose page reported it. */type LatestCatalogSession = SessionsListResult['items'][number] & { agentRef: string }+/** One user rename waiting for the server (spec 15 §2.5). */+type PendingRenameEntry = {+ agentRef: string+ chatId: string+ title: string+ // Title BEFORE the first rename of the current pending chain (the last+ // non-pending value) — the rollback target. Preserved across a re-rename+ // so a rollback never restores an unconfirmed optimistic title (FIX 2).+ previousTitle: string+ state: PendingRename+ // A PATCH for this exact entry is in flight right now (FIX 1), or the local+ // write that precedes the first PATCH has not finished. Distinct from `state`+ // (the durable 'in-flight'/'offline' pending kind): this gates re-entrancy so+ // a flush poll never fires a duplicate or early PATCH.+ sending: boolean+ // R1-M1: count of GENUINE ('offline' network / 5xx) failed sync attempts+ // for THIS entry (never reset while the entry lives). A 404 ('in-flight')+ // does NOT increment it — that is a wait for materialization, not a+ // failure. Drives the retry budget above.+ failureCount: number+ // R1-M1: budget exhausted — keep the optimistic local title but stop+ // auto-retrying on polls/online. Only 'offline' entries can reach this;+ // a fresh user rename makes a new entry.+ retriesExhausted: boolean+ // The entry has left the queue for good (confirmed, rejected or revoked),+ // whether or not it was still the current entry for its key.+ settled: boolean+}+/** The selected agent's sidebar: entries keyed by chat id, "Chat <id>" placeholder. */function mergeSelectedAgentCatalogPage(cached: SidebarChatEntry[],sessions: SessionsListResult['items'],- agentRef: string,- pendingRenameStateFor: (agentRef: string, chatId: string) => PendingRename+ renameStateFor: (chatId: string) => PendingRename): SidebarChatEntry[] {return mergeCatalogPage<SidebarChatEntry, SessionsListResult['items'][number]>({cached,sessions,entryKey: entry => entry.id,sessionKey: session => session.chatId,- entryPendingRename: entry => pendingRenameStateFor(agentRef, entry.id),- sessionPendingRename: session => pendingRenameStateFor(agentRef, session.chatId),+ entryPendingRename: entry => renameStateFor(entry.id),+ sessionPendingRename: session => renameStateFor(session.chatId),placeholderFor: agentChatPlaceholder,serverOnlyEntry: (session, title) => ({id: session.chatId,@@ -338,34 +369,11 @@ export function useChatListController({// `${agentRef}:${chatId}`. `state` maps directly to `resolveSessionTitle`'s// `pendingRename`: 'in-flight' (PATCH sent / awaiting the session to exist// server-side after a 404) or 'offline' (network failure, retry on reconnect).- const pendingRenamesRef = useRef<- Map<- string,- {- agentRef: string- chatId: string- title: string- // Title BEFORE the first rename of the current pending chain (the last- // non-pending value) — the rollback target. Preserved across a re-rename- // so a rollback never restores an unconfirmed optimistic title (FIX 2).- previousTitle: string- state: PendingRename- // A PATCH for this exact entry is in flight right now (FIX 1). Distinct- // from `state` (which is the durable 'in-flight'/'offline' pending kind):- // this gates re-entrancy so a flush poll never fires a duplicate PATCH.- sending: boolean- // R1-M1: count of GENUINE ('offline' network / 5xx) failed sync attempts- // for THIS entry (never reset while the entry lives). A 404 ('in-flight')- // does NOT increment it — that is a wait for materialization, not a- // failure. Drives the retry budget below.- failureCount: number- // R1-M1: budget exhausted — keep the optimistic local title but stop- // auto-retrying on polls/online. Only 'offline' entries can reach this;- // a fresh user rename makes a new entry.- retriesExhausted: boolean- }- >- >(new Map())+ const pendingRenamesRef = useRef<Map<string, PendingRenameEntry>>(new Map())+ // When each chat's latest rename left the queue, on the catalog clock+ // (`nextCatalogSequence`). A catalog page requested before that moment may+ // still carry the title the rename replaced (#1091 A21).+ const renameSettledSeqRef = useRef(new Map<string, number>())const pendingRenameKey = (agentRef: string, chatId: string): string => `${agentRef}:${chatId}`const authUserKeyRef = useRef(authUserKey)@@ -374,16 +382,48 @@ export function useChatListController({authUserKeyRef.current = authUserKey}, [authUserKey])- const pendingRenameStateFor = useCallback((agentRef: string, chatId: string): PendingRename => {- return pendingRenamesRef.current.get(pendingRenameKey(agentRef, chatId))?.state ?? 'none'+ /**+ * Takes `entry` out of the queue. Only the key's current entry deletes the key+ * and stamps the settle time; a superseded entry is only marked settled, and+ * the current entry's own settle stamps the key later. Returns whether `entry`+ * was current.+ */+ const settlePendingRename = useCallback((key: string, entry: PendingRenameEntry): boolean => {+ entry.settled = true+ if (pendingRenamesRef.current.get(key) !== entry) return false+ pendingRenamesRef.current.delete(key)+ renameSettledSeqRef.current.set(key, nextCatalogSequence())+ return true}, [])+ /**+ * The rename state a catalog page must respect for one chat (§2.2 E/F): a+ * pending rename's own state; 'in-flight' when the page was requested before+ * the chat's last rename settled (its title may predate the rename, so the+ * local title keeps winning); otherwise 'none'. `issueSeq` undefined means the+ * page's request time is unknown, which is treated as before the settle.+ */+ const catalogTitleRenameState = useCallback(+ (agentRef: string, chatId: string, issueSeq: number | undefined): PendingRename => {+ const key = pendingRenameKey(agentRef, chatId)+ const pending = pendingRenamesRef.current.get(key)+ if (pending) return pending.state+ const settledSeq = renameSettledSeqRef.current.get(key)+ if (settledSeq !== undefined && (issueSeq === undefined || issueSeq <= settledSeq)) {+ return 'in-flight'+ }+ return 'none'+ },+ []+ )+// Persist server freshness and titles into the local index (spec §5.3), so a// cold start paints the last server title instead of the hydration- // placeholder. A chat with a pending local rename keeps its local title (§2.2- // cases E/F). Best-effort: must never block or fail the visible render.+ // placeholder. A chat with a pending local rename, or a page requested before+ // its last rename settled, keeps its local title (§2.2 cases E/F).+ // Best-effort: must never block or fail the visible render.const persistServerSessions = useCallback(- (agentRef: string, sessions: SessionsListResult['items']) => {+ (agentRef: string, sessions: SessionsListResult['items'], issueSeq: number | undefined) => {try {void chatStore.reconcileServerSessions(@@ -391,7 +431,8 @@ export function useChatListController({sessions.map(session => ({chatId: session.chatId,lastActivityAt: session.lastActivityAt,- ...(session.title && pendingRenameStateFor(agentRef, session.chatId) === 'none'+ ...(session.title &&+ catalogTitleRenameState(agentRef, session.chatId, issueSeq) === 'none'? { title: session.title }: {}),}))@@ -401,7 +442,7 @@ export function useChatListController({// ignore — reconciliation is best-effort freshness only}},- [chatStore.reconcileServerSessions, pendingRenameStateFor]+ [chatStore.reconcileServerSessions, catalogTitleRenameState])// Indirection so the catalog loaders (defined above the queue) can trigger a@@ -443,6 +484,7 @@ export function useChatListController({// (attemptRenameRpc's `pendingRenamesRef.current.get(key) !== entry` guard).useEffect(() => {pendingRenamesRef.current.clear()+ renameSettledSeqRef.current.clear()}, [authUserKey])const reportCatalogOffline = (agentRef: string) => {@@ -571,7 +613,7 @@ export function useChatListController({const suppressionMarkerAtRequest = suppressAutoSelectionByAgentRef.current.get(agentRef)scheduleAfterFirstPaint(async () => {- let serverResult: SessionsListResult+ let serverResult: IssuedCatalogPagetry {serverResult = await readSessionCatalog(chatStore, agentRef, {agent: agentRef,@@ -643,11 +685,8 @@ export function useChatListController({chat => !deletedChatIdsByAgentRef.current.get(agentRef)?.has(chat.id))// §2.2 precedence (cases A-F) lives in `mergeCatalogPage`.- return mergeSelectedAgentCatalogPage(- dedupedPrevious,- visibleSessions,- agentRef,- pendingRenameStateFor+ return mergeSelectedAgentCatalogPage(dedupedPrevious, visibleSessions, chatId =>+ catalogTitleRenameState(agentRef, chatId, serverResult.issueSeq))})@@ -696,7 +735,7 @@ export function useChatListController({.catch(() => undefined)}- persistServerSessions(agentRef, serverSessions)+ persistServerSessions(agentRef, serverSessions, serverResult.issueSeq)})return { index, merged }@@ -711,6 +750,7 @@ export function useChatListController({onHostAccessRevoked,host,persistServerSessions,+ catalogTitleRenameState,])@@ -732,7 +772,7 @@ export function useChatListController({const hostAuthorityEpoch = getHostAuthorityEpoch(agentRef)setChatListMoreLoading(true)try {- let serverResult: SessionsListResult+ let serverResult: IssuedCatalogPagetry {serverResult = await readSessionCatalog(chatStore,@@ -818,15 +858,12 @@ export function useChatListController({chat => !deletedChatIdsByAgentRef.current.get(agentRef)?.has(chat.id))// §2.2 precedence (cases A-F) lives in `mergeCatalogPage`.- return mergeSelectedAgentCatalogPage(- dedupedPrevious,- visibleSessions,- agentRef,- pendingRenameStateFor+ return mergeSelectedAgentCatalogPage(dedupedPrevious, visibleSessions, chatId =>+ catalogTitleRenameState(agentRef, chatId, serverResult.issueSeq))})- persistServerSessions(agentRef, serverSessions)+ persistServerSessions(agentRef, serverSessions, serverResult.issueSeq)} finally {chatListLoadingMoreByAgentRef.current.delete(agentRef)if (selectedAgentRef.current === agentRef) {@@ -840,6 +877,7 @@ export function useChatListController({isHostAccessBlocked,onHostAccessRevoked,persistServerSessions,+ catalogTitleRenameState,])const loadChatList = useCallback(@@ -1170,16 +1208,7 @@ export function useChatListController({* rolls the optimistic title back and toasts. Never logs the raw title.*/const attemptRenameRpc = useCallback(- async (entry: {- agentRef: string- chatId: string- title: string- previousTitle: string- state: PendingRename- sending: boolean- failureCount: number- retriesExhausted: boolean- }) => {+ async (entry: PendingRenameEntry) => {const key = pendingRenameKey(entry.agentRef, entry.chatId)// FIX 1: never fire a duplicate PATCH for a key whose entry is already// sending (a flush poll landing during the initial/awaited attempt), and@@ -1198,9 +1227,7 @@ export function useChatListController({await chatStore.renameSession(entry.agentRef, entry.chatId, entry.title)// Only clear if this attempt still owns the key (a stale 200 must never// delete a newer rename's marker — that would drop its case-E protection).- if (pendingRenamesRef.current.get(key) === entry) {- pendingRenamesRef.current.delete(key)- }+ settlePendingRename(key, entry)} catch (error) {if (isConfirmedHostAccessRevoked(error) &&@@ -1208,9 +1235,7 @@ export function useChatListController({!isHostAccessBlocked(entry.agentRef)) {onHostAccessRevoked(entry.agentRef)- if (pendingRenamesRef.current.get(key) === entry) {- pendingRenamesRef.current.delete(key)- }+ settlePendingRename(key, entry)return}if (isAuthorizationError(error)) {@@ -1233,9 +1258,7 @@ export function useChatListController({if (!requestStillCurrent() || isHostAccessBlocked(entry.agentRef)) returnif (isConfirmedHostAccessRevoked(readError)) {onHostAccessRevoked(entry.agentRef)- if (pendingRenamesRef.current.get(key) === entry) {- pendingRenamesRef.current.delete(key)- }+ settlePendingRename(key, entry)return}}@@ -1247,11 +1270,8 @@ export function useChatListController({return}if (readSucceeded) {- if (pendingRenamesRef.current.get(key) === entry) {- pendingRenamesRef.current.delete(key)- if (entry.previousTitle) {- await applyLocalTitleOnly(entry.agentRef, entry.chatId, entry.previousTitle)- }+ if (settlePendingRename(key, entry) && entry.previousTitle) {+ await applyLocalTitleOnly(entry.agentRef, entry.chatId, entry.previousTitle)}host.current?.pushToast('You do not have permission to rename this chat.', 'error')return@@ -1274,7 +1294,7 @@ export function useChatListController({if (pendingRenamesRef.current.get(key) !== entry) returnconst kind = classifyRenameError(error)if (kind === 'client-error') {- pendingRenamesRef.current.delete(key)+ settlePendingRename(key, entry)// FIX 3: never roll back to an empty title (would blank the sidebar for// a chat that had no local cache entry). Clear the marker and let the// next poll's merge re-resolve from the server title / placeholder.@@ -1318,6 +1338,7 @@ export function useChatListController({isHostAccessBlocked,onHostAccessRevoked,onHostAuthorityUncertain,+ settlePendingRename,])@@ -1381,24 +1402,43 @@ export function useChatListController({if (authUserKeyRef.current !== authUserKeyAtRequest) returnpreviousTitle = index.chats.find(c => c.id === chatId)?.title ?? ''}- await applyLocalTitleOnly(agentRef, chatId, newTitle)- if (authUserKeyRef.current !== authUserKeyAtRequest) return// Replace any prior entry: this is now the current rename for the key. A// still-in-flight older attempt will no-op on completion (identity guard).- const entry = {+ // It is registered before the local write, so a catalog page handled while+ // the write runs cannot store the old server title over it (#1091 A21);+ // `sending` keeps flushes from sending the PATCH before the write lands.+ const entry: PendingRenameEntry = {agentRef,chatId,title: newTitle,previousTitle,- state: 'in-flight' as PendingRename,- sending: false,+ state: 'in-flight',+ sending: true,failureCount: 0,retriesExhausted: false,+ settled: false,}pendingRenamesRef.current.set(key, entry)+ try {+ await applyLocalTitleOnly(agentRef, chatId, newTitle)+ } catch (error) {+ // The local title did not change. Hand the key back to the rename this+ // one replaced while that rename is still unsettled, so its PATCH keeps+ // protecting its title; otherwise the key has no pending rename left.+ if (pendingRenamesRef.current.get(key) === entry) {+ if (existing && !existing.settled) pendingRenamesRef.current.set(key, existing)+ else settlePendingRename(key, entry)+ }+ throw error+ }+ entry.sending = false+ if (authUserKeyRef.current !== authUserKeyAtRequest) {+ settlePendingRename(key, entry)+ return+ }await attemptRenameRpc(entry)},- [authUserKey, chatStore, applyLocalTitleOnly, attemptRenameRpc]+ [authUserKey, chatStore, applyLocalTitleOnly, attemptRenameRpc, settlePendingRename])const handleRenameChat = useCallback(@@ -1674,6 +1714,8 @@ export function useChatListController({// cursors here; the selected-agent session list exposes explicit// on-demand pagination through `loadMoreChatSessions`.let serverSessions: SessionsListResult['items'] = []+ // Undefined when the read failed: no page, so no request time.+ let issueSeq: number | undefinedtry {const serverResult = await readSessionCatalog(chatStore, agentRef, {agent: agentRef,@@ -1682,6 +1724,7 @@ export function useChatListController({if (!requestStillCurrent()) returnreportCatalogOnline(agentRef, authorityScopeGeneration)serverSessions = serverResult.items+ issueSeq = serverResult.issueSeq} catch (error) {if (requestStillCurrent()) {if (isConfirmedHostAccessRevoked(error)) onHostAccessRevoked(agentRef)@@ -1720,9 +1763,10 @@ export function useChatListController({sessions: sessions.filter(session => !deleted?.has(session.chatId)),entryKey: item => `${item.agentRef}:${item.id}`,sessionKey: session => `${session.agentRef}:${session.chatId}`,- entryPendingRename: item => pendingRenameStateFor(item.agentRef, item.id),+ entryPendingRename: item =>+ catalogTitleRenameState(item.agentRef, item.id, issueSeq),sessionPendingRename: session =>- pendingRenameStateFor(session.agentRef, session.chatId),+ catalogTitleRenameState(session.agentRef, session.chatId, issueSeq),placeholderFor: remotePlaceholder,serverOnlyEntry: (session, title) => ({id: session.chatId,@@ -1743,7 +1787,7 @@ export function useChatListController({})// A Host the user never selects keeps its titles across restarts too.- if (requestStillCurrent()) persistServerSessions(agentRef, sessions)+ if (requestStillCurrent()) persistServerSessions(agentRef, sessions, issueSeq)// §2.5: retry only this Host's pending renames as its poll settles.if (requestStillCurrent()) {@@ -1784,6 +1828,7 @@ export function useChatListController({onHostAccessRevoked,latestReloadRevision,persistServerSessions,+ catalogTitleRenameState,])// Stable across renders whose inputs did not change, so consumers keyed on thediff --git a/desktop-app/ui/src/hooks/useChatStore.ts b/desktop-app/ui/src/hooks/useChatStore.tsindex c1facd01e..f262f9331 100644--- a/desktop-app/ui/src/hooks/useChatStore.ts+++ b/desktop-app/ui/src/hooks/useChatStore.ts@@ -45,10 +45,27 @@ type CachedRequest<T> = {promise: Promise<T>}-const sessionCatalogRequests = new Map<string, CachedRequest<SessionsListResult>>()+/**+ * A catalog page with the sequence number taken when its request was sent. A+ * cached page keeps the number of the request that produced it.+ */+type IssuedSessionsListResult = SessionsListResult & { issueSeq: number }++const sessionCatalogRequests = new Map<string, CachedRequest<IssuedSessionsListResult>>()let sessionCatalogSource: typeof window.clerum.rpc.listSessions | null = nulllet remoteCacheScope = 'unknown'+/**+ * One monotonic clock for catalog requests and local renames, so the renderer+ * can tell whether a catalog page was requested before or after a rename+ * settled (#1091 A21).+ */+let catalogSequence = 0+export function nextCatalogSequence(): number {+ catalogSequence += 1+ return catalogSequence+}+function pruneExpiredSessionCatalogRequests(now = Date.now()): void {for (const [key, cached] of sessionCatalogRequests) {if (cached.expiresAt <= now) {@@ -166,15 +183,19 @@ export function useChatStore() {const cached = sessionCatalogRequests.get(key)if (!options.force && cached && cached.expiresAt > Date.now()) return cached.promise- const entry: CachedRequest<SessionsListResult> = {+ const issueSeq = nextCatalogSequence()+ const entry: CachedRequest<IssuedSessionsListResult> = {expiresAt: Date.now() + SESSION_CATALOG_TTL_MS,hostRef,- promise: source(hostRef, undefined, query).catch(error => {- // An invalidation may have replaced this entry with a newer request- // under the same key; only this request's own entry is evicted.- if (sessionCatalogRequests.get(key) === entry) sessionCatalogRequests.delete(key)- throw error- }),+ promise: source(hostRef, undefined, query).then(+ result => ({ ...result, issueSeq }),+ error => {+ // An invalidation may have replaced this entry with a newer request+ // under the same key; only this request's own entry is evicted.+ if (sessionCatalogRequests.get(key) === entry) sessionCatalogRequests.delete(key)+ throw error+ }+ ),}sessionCatalogRequests.set(key, entry)return entry.promise