Skip to content

Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure

TypeScript

feat(desktop-app): sync session rename over RPC with a pending-rename queue (spec 15 Phase B)

Diego Zacariasabfaad6b6e92
diff --git a/desktop-app/src/__tests__/appService.renameSession.test.ts b/desktop-app/src/__tests__/appService.renameSession.test.ts
new file mode 100644
index 000000000..45a32a5ae
--- /dev/null
+++ b/desktop-app/src/__tests__/appService.renameSession.test.ts
@@ -0,0 +1,86 @@
+import { describe, expect, it, vi } from 'vitest'
+import { AppService } from '../appService.js'
+import { ApiError } from '../httpClient.js'
+
+vi.mock('../chatStoreBinding.js', () => ({
+ bindChatStoreForUser: vi.fn(),
+ getChatStore: vi.fn(),
+ unbindChatStore: vi.fn(),
+}))
+
+function renameService() {
+ const issueRpcTokenForHostRefs = vi
+ .fn()
+ .mockResolvedValue({ token: 'rpc-token', scopes: [], hostRefs: [] })
+ const rpcClient = { renameSession: vi.fn() }
+ const service = new AppService() as unknown as {
+ issueRpcTokenForHostRefs: typeof issueRpcTokenForHostRefs
+ rpcClient: typeof rpcClient
+ rpcTokenManager: { clear: () => void }
+ renameSession: AppService['renameSession']
+ }
+ service.issueRpcTokenForHostRefs = issueRpcTokenForHostRefs
+ service.rpcClient = rpcClient
+ service.rpcTokenManager = { clear: vi.fn() }
+ return { service, issueRpcTokenForHostRefs, rpcClient }
+}
+
+describe('AppService.renameSession (spec 15 Fase B)', () => {
+ it('issues a host:session:write token — NOT wake-eligible — and forwards the rename', async () => {
+ const { service, issueRpcTokenForHostRefs, rpcClient } = renameService()
+ rpcClient.renameSession.mockResolvedValue({ title: 'New name' })
+
+ const result = await service.renameSession('chatllm', 'chatllm', 'chat-1', 'New name')
+
+ expect(result).toEqual({ title: 'New name' })
+ // The dedicated write scope, and DELIBERATELY without host:wake:write: a
+ // rename must not be a cheap "wake my pod" primitive (spec 15 §5).
+ expect(issueRpcTokenForHostRefs).toHaveBeenCalledWith(['host:session:write'], ['chatllm'])
+ expect(issueRpcTokenForHostRefs.mock.calls[0]?.[0]).not.toContain('host:wake:write')
+ expect(rpcClient.renameSession).toHaveBeenCalledWith(
+ 'rpc-token',
+ 'chatllm',
+ 'chatllm',
+ 'chat-1',
+ 'New name'
+ )
+ })
+
+ it('does not accept a renderer hostRefs fleet — token is scoped to the single host', async () => {
+ const { service, issueRpcTokenForHostRefs, rpcClient } = renameService()
+ rpcClient.renameSession.mockResolvedValue({ title: 'x' })
+ // The method signature carries an optional hostRefs, but the ipc handler never
+ // forwards one; default is [hostRef].
+ await service.renameSession('chatllm', 'chatllm', 'chat-1', 'x')
+ expect(issueRpcTokenForHostRefs).toHaveBeenCalledWith(['host:session:write'], ['chatllm'])
+ })
+
+ it('re-mints the token and retries once on a 401 token lapse', async () => {
+ const { service, issueRpcTokenForHostRefs, rpcClient } = renameService()
+ rpcClient.renameSession
+ .mockRejectedValueOnce(new ApiError('Rename session failed (401)', 401, ''))
+ .mockResolvedValueOnce({ title: 'ok' })
+
+ const result = await service.renameSession('chatllm', 'chatllm', 'chat-1', 'ok')
+
+ expect(result).toEqual({ title: 'ok' })
+ expect(rpcClient.renameSession).toHaveBeenCalledTimes(2)
+ expect(issueRpcTokenForHostRefs).toHaveBeenCalledTimes(2)
+ })
+
+ it('does NOT retry a 404 (that is a real "not found" for the queue to handle)', async () => {
+ const { service, rpcClient } = renameService()
+ rpcClient.renameSession.mockRejectedValue(new ApiError('Rename session failed (404)', 404, ''))
+ await expect(service.renameSession('chatllm', 'chatllm', 'chat-1', 'x')).rejects.toThrow(
+ '(404)'
+ )
+ expect(rpcClient.renameSession).toHaveBeenCalledTimes(1)
+ })
+
+ it('requires hostRef, agent, and chatId', async () => {
+ const { service } = renameService()
+ await expect(service.renameSession('', 'chatllm', 'chat-1', 'x')).rejects.toThrow()
+ await expect(service.renameSession('chatllm', '', 'chat-1', 'x')).rejects.toThrow()
+ await expect(service.renameSession('chatllm', 'chatllm', '', 'x')).rejects.toThrow()
+ })
+})
diff --git a/desktop-app/src/appService.ts b/desktop-app/src/appService.ts
index 2d0030825..ffd444deb 100644
--- a/desktop-app/src/appService.ts
+++ b/desktop-app/src/appService.ts
@@ -210,6 +210,15 @@ const HOST_STATUS_SCOPES: RpcScope[] = HOST_OBSERVABILITY_SCOPES.status
const HOST_ACTIVITY_SCOPES: RpcScope[] = HOST_OBSERVABILITY_SCOPES.activity
const HOST_SESSION_SCOPES: RpcScope[] = HOST_FINITE_OPERATION_SCOPES.session
const HOST_MODEL_SCOPES: RpcScope[] = HOST_FINITE_OPERATION_SCOPES.model
+// Spec 15 Fase B — explicit user rename. A dedicated WRITE scope, distinct from
+// `host:session:read` (so a read/navigation token can never rename), and
+// DELIBERATELY NOT wake-eligible: it carries no HOST_WAKE_SCOPE. Rename is
+// optimistic local-first and reconciles on the next listSessions poll, and
+// rpc-proxy's PATCH route is non-wake too — granting wake here would turn a
+// rename into a cheap "wake my pod" primitive. Kept OUT of
+// HOST_FINITE_OPERATION_SCOPES (whose every entry carries wake, asserted by
+// appService.wakeScopeMatrix.issue791.test.ts) for exactly that reason.
+const HOST_SESSION_TITLE_SCOPES: RpcScope[] = ['host:session:write']
const HOST_ARTIFACT_SCOPES: RpcScope[] = HOST_FINITE_OPERATION_SCOPES.artifact
const HOST_APPROVAL_SCOPES: RpcScope[] = HOST_FINITE_OPERATION_SCOPES.approval
const MCP_SERVERS_LIST_SCOPES: RpcScope[] = ['mcp:servers:list']
@@ -4401,6 +4410,56 @@ export class AppService {
return this.rpcClient.setHostModel(rpc.token, targetHostRef, chatId, targetModel)
}
+ /**
+ * Spec 15 Fase B — propagates an explicit user rename to the server. Mints a
+ * token carrying the dedicated, NON-wake `host:session:write` scope (see
+ * {@link HOST_SESSION_TITLE_SCOPES}). The raw title is never logged. Errors
+ * (404 missing/foreign/channel, 400 invalid, 403 access) throw so the renderer
+ * can drive the pending-rename queue (§2.5); a bounded refresh-retry mirrors
+ * {@link getDesktopStatus} for the 401/403-missing-scope token-lapse case.
+ */
+ async renameSession(
+ hostRef: string,
+ agent: string,
+ chatId: string,
+ title: string,
+ hostRefs?: string[]
+ ): Promise<{ title: string }> {
+ const targetHostRef = String(hostRef || '').trim()
+ const targetAgent = String(agent || '').trim()
+ const targetChatId = String(chatId || '').trim()
+ if (!targetHostRef || !targetAgent || !targetChatId) {
+ throw new Error('hostRef, agent, and chatId are required')
+ }
+ const effectiveHostRefs = hostRefs && hostRefs.length > 0 ? hostRefs : [targetHostRef]
+ const rpc = await this.issueRpcTokenForHostRefs(HOST_SESSION_TITLE_SCOPES, effectiveHostRefs)
+ try {
+ return await this.rpcClient.renameSession(
+ rpc.token,
+ targetHostRef,
+ targetAgent,
+ targetChatId,
+ title
+ )
+ } catch (error) {
+ if (AppService.shouldRefreshRpcToken(error)) {
+ this.rpcTokenManager.clear()
+ const retried = await this.issueRpcTokenForHostRefs(
+ HOST_SESSION_TITLE_SCOPES,
+ effectiveHostRefs
+ )
+ return this.rpcClient.renameSession(
+ retried.token,
+ targetHostRef,
+ targetAgent,
+ targetChatId,
+ title
+ )
+ }
+ throw error
+ }
+ }
+
getTokenMetadata(): TokenMetadata {
const meta = this.rpcTokenManager.getMetadata()
return {
diff --git a/desktop-app/src/ipc.ts b/desktop-app/src/ipc.ts
index 6d51f1fc9..cf07a5768 100644
--- a/desktop-app/src/ipc.ts
+++ b/desktop-app/src/ipc.ts
@@ -12,6 +12,7 @@ import { promises as fs } from 'node:fs'
import path from 'node:path'
import { AppService } from './appService.js'
import { requireChatStore } from './chatStoreBinding.js'
+import { assertSafeRouteSegment } from './pathSafety.js'
import {
PLUGIN_SDK_CAPABILITIES_CHANNEL,
PLUGIN_SDK_CONSENT_RESOLVE_CHANNEL,
@@ -1308,6 +1309,32 @@ export function registerIpcHandlers(service: AppService): void {
}
)
+ // Spec 15 Fase B — propagate an explicit user rename to the server.
+ ipcMain.handle(
+ 'rpc:renameSession',
+ async (event, payload: { hostRef: string; agent: string; chatId: string; title: string }) => {
+ assertTrustedSender(event)
+ const hostRef = sanitizeString(payload?.hostRef)
+ const agent = sanitizeString(payload?.agent)
+ const chatId = sanitizeString(payload?.chatId)
+ // `sanitizeString` is only trim(); the authoritative title contract (NFC +
+ // strip \p{C} + collapse + cap 120cp/512B) is enforced server-side by
+ // mcp-host (spec 15 §5). A cheap trim + non-empty reject here just avoids a
+ // round-trip for an obviously empty rename; content validity is the server.
+ const title = sanitizeString(payload?.title)
+ if (!hostRef || !agent || !chatId) {
+ throw new Error('hostRef, agent, and chatId are required')
+ }
+ if (!title) throw new Error('title is required')
+ // Never trust route segments minted by the renderer, and never accept a
+ // `hostRefs` fleet list from it (the token is scoped to this single host).
+ assertSafeRouteSegment('hostRef', hostRef)
+ assertSafeRouteSegment('agent', agent, { maxLength: 200, allowColon: false })
+ assertSafeRouteSegment('chatId', chatId)
+ return service.renameSession(hostRef, agent, chatId, title)
+ }
+ )
+
ipcMain.handle('rpc:getTokenMetadata', async event => {
assertTrustedSender(event)
return service.getTokenMetadata()
diff --git a/desktop-app/src/preload.ts b/desktop-app/src/preload.ts
index e32d85431..d57e13944 100644
--- a/desktop-app/src/preload.ts
+++ b/desktop-app/src/preload.ts
@@ -457,6 +457,10 @@ const clerum = Object.freeze({
ipcRenderer.invoke('rpc:getHostModels', { hostRef, chatId, hostRefs }),
setHostModel: (hostRef: string, chatId: string, model: string, hostRefs?: string[]) =>
ipcRenderer.invoke('rpc:setHostModel', { hostRef, chatId, model, hostRefs }),
+ // Spec 15 Fase B — explicit user rename. No `hostRefs` fleet arg: the main
+ // process scopes the write token to this single host.
+ renameSession: (hostRef: string, agent: string, chatId: string, title: string) =>
+ ipcRenderer.invoke('rpc:renameSession', { hostRef, agent, chatId, title }),
getTokenMetadata: () => ipcRenderer.invoke('rpc:getTokenMetadata'),
// U5 (mcp-oauth reactive consent): "Connect <server>" — open the provider
// authorize-URL for a task that suspended with `connect_required`. Host-bound
diff --git a/desktop-app/src/renderer.d.ts b/desktop-app/src/renderer.d.ts
index 30faf8e77..af75ee4d0 100644
--- a/desktop-app/src/renderer.d.ts
+++ b/desktop-app/src/renderer.d.ts
@@ -576,6 +576,17 @@ declare global {
model: string,
hostRefs?: string[]
) => Promise<SetHostModelResult>
+ /**
+ * Spec 15 Fase B — explicit user rename, propagated to the server. Rejects
+ * with an error whose message carries the HTTP status `(NNN)` so the
+ * renderer's pending-rename queue can branch on 404 / 400·403 / 5xx.
+ */
+ renameSession: (
+ hostRef: string,
+ agent: string,
+ chatId: string,
+ title: string
+ ) => Promise<{ title: string }>
getTokenMetadata: () => Promise<TokenMetadata>
// U5 (mcp-oauth reactive consent): "Connect <server>" for a task
// suspended with `connect_required`. Host-bound to that conversation.
diff --git a/desktop-app/src/rpcProxyClient.ts b/desktop-app/src/rpcProxyClient.ts
index c3da8446e..059cd7fff 100644
--- a/desktop-app/src/rpcProxyClient.ts
+++ b/desktop-app/src/rpcProxyClient.ts
@@ -1165,6 +1165,50 @@ export class RpcProxyClient {
return response.json() as Promise<SetHostModelResult>
}
+ /**
+ * Spec 15 Fase B — renames a session (explicit user rename) via
+ * `PATCH …/hosts/:hostRef/sessions/:agent/:chatId/name`. Keyed by
+ * `(agent, chatId)` like {@link loadSessionMessages}; the server derives the
+ * owning `userSub` from the verified token and validates/sanitizes the title.
+ *
+ * The status is preserved in the thrown {@link ApiError} message (the caller's
+ * pending-rename queue keys off it: 404 = not materialized server-side yet →
+ * keep pending; 400/403 = real rejection → rollback; 5xx/network → offline
+ * retry). The raw title is NEVER put in the error message (user content, §5).
+ */
+ async renameSession(
+ rpcToken: string,
+ hostRef: string,
+ agent: string,
+ chatId: string,
+ title: string
+ ): Promise<{ title: string }> {
+ assertSafeRouteSegment('hostRef', hostRef)
+ assertSafeRouteSegment('agent', agent, { maxLength: 200, allowColon: false })
+ assertSafeRouteSegment('chatId', chatId)
+ const response = await fetch(
+ url(
+ `/api/v1/rpc/hosts/${encodeURIComponent(hostRef)}/sessions/${encodeURIComponent(agent)}/${encodeURIComponent(chatId)}/name`
+ ),
+ {
+ method: 'PATCH',
+ headers: { authorization: `Bearer ${rpcToken}`, 'content-type': 'application/json' },
+ body: JSON.stringify({ title }),
+ signal: withTimeout(),
+ }
+ )
+ if (!response.ok) {
+ // Body may echo the invalid title; read it for the ApiError payload but
+ // keep the raw title out of the human-facing message.
+ const body = await readErrorBody(response)
+ throw new ApiError(`Rename session failed (${response.status})`, response.status, body)
+ }
+ const parsed = (await response.json().catch(() => ({}))) as { title?: unknown }
+ // Re-sanitize the server's echoed title on read (defense in depth, A14 rule).
+ const sanitized = typeof parsed.title === 'string' ? sanitizeWireTitle(parsed.title) : undefined
+ return { title: sanitized ?? title }
+ }
+
async getDesktopStatus(
rpcAccessToken: string,
hostRef: string
diff --git a/desktop-app/src/types.ts b/desktop-app/src/types.ts
index 489ac52ae..e4d83c1dd 100644
--- a/desktop-app/src/types.ts
+++ b/desktop-app/src/types.ts
@@ -10,6 +10,7 @@ export type RpcScope =
| 'host:task:read'
| 'host:approval:write'
| 'host:session:read'
+ | 'host:session:write'
| 'host:model:write'
| 'desktop:view'
| 'sandbox:ui:view'
diff --git a/desktop-app/test/ipc.test.ts b/desktop-app/test/ipc.test.ts
index 22e73d928..7802f9f10 100644
--- a/desktop-app/test/ipc.test.ts
+++ b/desktop-app/test/ipc.test.ts
@@ -105,6 +105,7 @@ describe('ipc host status stream handlers', () => {
downloadArtifact: vi.fn(),
listSessions: vi.fn(),
loadSessionMessages: vi.fn(),
+ renameSession: vi.fn(),
listWorkflowRuns: vi.fn(),
listWorkflowRunArtifacts: vi.fn(),
downloadWorkflowRunArtifact: vi.fn(),
@@ -151,6 +152,75 @@ describe('ipc host status stream handlers', () => {
).rejects.toThrow('Untrusted IPC sender')
})
+ // ─── rpc:renameSession (spec 15 Fase B) ───
+
+ it('rejects an untrusted sender for rpc:renameSession', async () => {
+ const handler = testState.handlers.get('rpc:renameSession')
+ expect(handler).toBeDefined()
+ await expect(
+ Promise.resolve(
+ handler?.(
+ {
+ senderFrame: { url: 'https://evil.example.com' },
+ sender: { id: 1, send: vi.fn(), once: vi.fn() },
+ },
+ { hostRef: 'chatllm', agent: 'chatllm', chatId: 'c1', title: 'x' }
+ )
+ )
+ ).rejects.toThrow('Untrusted IPC sender')
+ expect(service.renameSession).not.toHaveBeenCalled()
+ })
+
+ it('forwards a valid rpc:renameSession to the service', async () => {
+ const { event } = makeTrustedEvent()
+ const handler = testState.handlers.get('rpc:renameSession')
+ service.renameSession.mockResolvedValue({ title: 'New name' })
+ await handler?.(event, {
+ hostRef: 'chatllm',
+ agent: 'chatllm',
+ chatId: 'c1',
+ title: 'New name',
+ })
+ expect(service.renameSession).toHaveBeenCalledWith('chatllm', 'chatllm', 'c1', 'New name')
+ })
+
+ it('rejects an unsafe chatId segment for rpc:renameSession before calling the service', async () => {
+ const { event } = makeTrustedEvent()
+ const handler = testState.handlers.get('rpc:renameSession')
+ await expect(
+ Promise.resolve(
+ handler?.(event, { hostRef: 'chatllm', agent: 'chatllm', chatId: '../evil', title: 'x' })
+ )
+ ).rejects.toThrow(/unsafe path segment/)
+ expect(service.renameSession).not.toHaveBeenCalled()
+ })
+
+ it('rejects an empty title for rpc:renameSession', async () => {
+ const { event } = makeTrustedEvent()
+ const handler = testState.handlers.get('rpc:renameSession')
+ await expect(
+ Promise.resolve(
+ handler?.(event, { hostRef: 'chatllm', agent: 'chatllm', chatId: 'c1', title: ' ' })
+ )
+ ).rejects.toThrow('title is required')
+ expect(service.renameSession).not.toHaveBeenCalled()
+ })
+
+ it('ignores a renderer-supplied hostRefs fleet for rpc:renameSession', async () => {
+ const { event } = makeTrustedEvent()
+ const handler = testState.handlers.get('rpc:renameSession')
+ service.renameSession.mockResolvedValue({ title: 'x' })
+ await handler?.(event, {
+ hostRef: 'chatllm',
+ agent: 'chatllm',
+ chatId: 'c1',
+ title: 'x',
+ hostRefs: ['chatllm', 'other'],
+ } as never)
+ // The handler passes only the four positional args; no hostRefs fleet leaks.
+ expect(service.renameSession).toHaveBeenCalledWith('chatllm', 'chatllm', 'c1', 'x')
+ })
+
it('forwards sandbox UI visibility changes from the trusted renderer', async () => {
const { event } = makeTrustedEvent()
const handler = testState.handlers.get('sandboxUi:setVisible')
diff --git a/desktop-app/test/rpcProxyClient.test.ts b/desktop-app/test/rpcProxyClient.test.ts
index 632a1ff4d..0a3bfa387 100644
--- a/desktop-app/test/rpcProxyClient.test.ts
+++ b/desktop-app/test/rpcProxyClient.test.ts
@@ -206,6 +206,81 @@ describe('RpcProxyClient — openTaskProgressStream()', () => {
})
})
+describe('RpcProxyClient — renameSession() (spec 15 Fase B)', () => {
+ it('PATCHes the name route with the title and returns the (re-sanitized) server title', async () => {
+ const fetchMock = vi
+ .fn()
+ .mockResolvedValue(
+ new Response(JSON.stringify({ ok: true, title: 'Clean name' }), { status: 200 })
+ )
+ vi.stubGlobal('fetch', fetchMock)
+
+ const client = new RpcProxyClient()
+ const result = await client.renameSession(
+ 'rpc-token',
+ 'chatllm',
+ 'chatllm',
+ 'chat-1',
+ 'Clean name'
+ )
+
+ expect(result).toEqual({ title: 'Clean name' })
+ const [requestUrl, init] = fetchMock.mock.calls[0] as [URL, RequestInit]
+ expect(String(requestUrl)).toContain('/hosts/chatllm/sessions/chatllm/chat-1/name')
+ expect(init.method).toBe('PATCH')
+ expect(JSON.parse(String(init.body))).toEqual({ title: 'Clean name' })
+ })
+
+ it('re-sanitizes a hostile echoed title on read (bidi override stripped)', async () => {
+ vi.stubGlobal(
+ 'fetch',
+ vi
+ .fn()
+ .mockResolvedValue(
+ new Response(JSON.stringify({ ok: true, title: 'Safe‮name' }), { status: 200 })
+ )
+ )
+ const client = new RpcProxyClient()
+ const result = await client.renameSession(
+ 'rpc-token',
+ 'chatllm',
+ 'chatllm',
+ 'chat-1',
+ 'Safe name'
+ )
+ expect(result.title).toBe('Safename')
+ expect(result.title).not.toContain('‮')
+ })
+
+ it('preserves the HTTP status in the thrown error message (404 / 400 / 403 / 5xx)', async () => {
+ const client = new RpcProxyClient()
+ for (const status of [404, 400, 403, 502]) {
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response('nope', { status })))
+ await expect(
+ client.renameSession('rpc-token', 'chatllm', 'chatllm', 'chat-1', 'x')
+ ).rejects.toThrow(`(${status})`)
+ }
+ })
+
+ it('never puts the raw title in the error message', async () => {
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response('bad', { status: 400 })))
+ const client = new RpcProxyClient()
+ await expect(
+ client.renameSession('rpc-token', 'chatllm', 'chatllm', 'chat-1', 'super-secret-title')
+ ).rejects.toThrow(/^Rename session failed \(400\)$/)
+ })
+
+ it('rejects an unsafe chatId segment before any fetch', async () => {
+ const fetchMock = vi.fn()
+ vi.stubGlobal('fetch', fetchMock)
+ const client = new RpcProxyClient()
+ await expect(
+ client.renameSession('rpc-token', 'chatllm', 'chatllm', '../evil', 'x')
+ ).rejects.toThrow(/unsafe path segment/)
+ expect(fetchMock).not.toHaveBeenCalled()
+ })
+})
+
describe('parseSessionsListResult — title parse + sanitize on read (spec 15 §2.2/A14)', () => {
const baseItem = {
agent: 'chatllm',
diff --git a/desktop-app/ui/src/hooks/domain/__tests__/__fixtures__/mockClerum.ts b/desktop-app/ui/src/hooks/domain/__tests__/__fixtures__/mockClerum.ts
index 2134a7d71..2bd0f3e49 100644
--- a/desktop-app/ui/src/hooks/domain/__tests__/__fixtures__/mockClerum.ts
+++ b/desktop-app/ui/src/hooks/domain/__tests__/__fixtures__/mockClerum.ts
@@ -35,6 +35,7 @@ interface RpcMock {
getTaskResult: Fn
listSessions: Fn
loadSessionMessages: Fn
+ renameSession: Fn
getContextBreakdown: Fn
cancelTask: Fn
subscribeHostActivity: Fn
@@ -94,6 +95,11 @@ export function installMockClerum(): MockClerum {
getTaskResult: vi.fn(async () => ({ response: 'ok' })),
listSessions: vi.fn(async () => ({ items: [] })),
loadSessionMessages: vi.fn(async () => ({ agent: '', chatId: '', turns: [] })),
+ renameSession: vi.fn(
+ async (_hostRef: string, _agent: string, _chatId: string, title: string) => ({
+ title,
+ })
+ ),
getContextBreakdown: vi.fn(async () => ({ breakdown: null })),
cancelTask: vi.fn(async () => undefined),
subscribeHostActivity: vi.fn(
diff --git a/desktop-app/ui/src/hooks/domain/__tests__/renameSessionQueue.test.tsx b/desktop-app/ui/src/hooks/domain/__tests__/renameSessionQueue.test.tsx
new file mode 100644
index 000000000..77c72932c
--- /dev/null
+++ b/desktop-app/ui/src/hooks/domain/__tests__/renameSessionQueue.test.tsx
@@ -0,0 +1,426 @@
+// @vitest-environment jsdom
+/**
+ * spec 15 Fase B §2.5 — the pending-rename queue, asserted through the observable
+ * sidebar title (pr-discipline T4) and the RPC call count. Covers: 200 confirms,
+ * 404 keeps the optimistic title without rollback (retried after the session is
+ * reported), a genuine 4xx rolls back + toasts, a network failure queues offline,
+ * a pending rename WINS over a server title (case E — protects case C), and the
+ * auto-title path (applyLocalTitleOnly) never fires the rename RPC.
+ *
+ * T3: these fail against the parent commit (no queue, no renameSession — the RPC
+ * is never called and there is no rollback/pending behavior to assert).
+ */
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { act, waitFor } from '@testing-library/react'
+import type { ChatIndex } from '../../../../../src/types'
+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
+
+let clerum: MockClerum
+
+beforeEach(() => {
+ clerum = installMockClerum()
+})
+
+afterEach(() => {
+ vi.restoreAllMocks()
+ uninstallMockClerum()
+})
+
+const NOW = '2026-09-12T00:00:00.000Z'
+
+function localIndex(chats: Array<{ id: string; title: string }>): ChatIndex {
+ return {
+ version: 1,
+ lastActiveChatId: null,
+ onboardingDismissed: false,
+ chats: chats.map(c => ({
+ id: c.id,
+ title: c.title,
+ createdAt: NOW,
+ updatedAt: NOW,
+ messageCount: 0,
+ })),
+ }
+}
+
+function titleInList(current: { chatList: Array<{ id: string; title: string }> }, id: string) {
+ return current.chatList.find(c => c.id === id)?.title
+}
+
+function titleInLatest(
+ current: { latestChatSessions: Array<{ id: string; title: string }> },
+ id: string
+) {
+ return current.latestChatSessions.find(c => c.id === id)?.title
+}
+
+interface Deferred<T> {
+ promise: Promise<T>
+ resolve: (value: T) => void
+ reject: (reason?: unknown) => void
+}
+
+function deferred<T>(): Deferred<T> {
+ let resolve!: (value: T) => void
+ let reject!: (reason?: unknown) => void
+ const promise = new Promise<T>((res, rej) => {
+ resolve = res
+ reject = rej
+ })
+ return { promise, resolve, reject }
+}
+
+async function flushMicrotasks(): Promise<void> {
+ for (let i = 0; i < 8; i += 1) await Promise.resolve()
+}
+
+/**
+ * Wire getIndex/renameChat as a stateful in-memory index so renameChat writes are
+ * visible to a later getIndex — exactly like the real chatStore. A static getIndex
+ * mock would hide the very bugs FIX 2 addresses (a re-rename reading back an
+ * unconfirmed optimistic title, and the catalog loader resetting the optimistic
+ * title from the persisted index on the next poll).
+ */
+function wireStatefulIndex(c: MockClerum, chats: Array<{ id: string; title: string }>) {
+ const idx = localIndex(chats)
+ c.chat.getIndex.mockImplementation(async () => ({
+ ...idx,
+ chats: idx.chats.map(ch => ({ ...ch })),
+ }))
+ c.chat.rename.mockImplementation(async (_agentRef: string, id: string, title: string) => {
+ const found = idx.chats.find(x => x.id === id)
+ if (found) found.title = title
+ })
+}
+
+function reportedSessions(chats: Array<{ chatId: string; title?: string }>) {
+ return {
+ items: chats.map(c => ({
+ agent: 'agent-x',
+ chatId: c.chatId,
+ turnCount: 1,
+ lastActivityAt: NOW,
+ ...(c.title !== undefined ? { title: c.title } : {}),
+ })),
+ }
+}
+
+describe('rename pending queue (spec 15 §2.5)', () => {
+ it('200: optimistic local title + RPC sync (hostRef===agent===agentRef), no toast', async () => {
+ clerum.chat.getIndex.mockResolvedValue(localIndex([{ id: 'c1', title: 'old' }]))
+ clerum.rpc.renameSession.mockResolvedValue({ title: 'renamed' })
+
+ const { result, spies } = renderController({
+ selectedAgent: 'agent-x',
+ agentNames: ['agent-x'],
+ })
+ await waitFor(() => expect(titleInList(result.current, 'c1')).toBe('old'))
+
+ await act(async () => {
+ await result.current.handleRenameChatForAgent('agent-x', 'c1', 'renamed')
+ })
+
+ expect(clerum.rpc.renameSession).toHaveBeenCalledWith('agent-x', 'agent-x', 'c1', 'renamed')
+ expect(titleInList(result.current, 'c1')).toBe('renamed')
+ expect(spies.pushToast).not.toHaveBeenCalledWith(expect.anything(), 'error')
+ })
+
+ it('4xx: rolls the optimistic title back to the previous value and toasts an error', async () => {
+ clerum.chat.getIndex.mockResolvedValue(localIndex([{ id: 'c1', title: 'old' }]))
+ clerum.rpc.renameSession.mockRejectedValue(new Error('Rename session failed (400)'))
+
+ const { result, spies } = renderController({
+ selectedAgent: 'agent-x',
+ agentNames: ['agent-x'],
+ })
+ await waitFor(() => expect(titleInList(result.current, 'c1')).toBe('old'))
+
+ await act(async () => {
+ await result.current.handleRenameChatForAgent('agent-x', 'c1', 'renamed')
+ })
+
+ expect(clerum.rpc.renameSession).toHaveBeenCalledTimes(1)
+ await waitFor(() => expect(titleInList(result.current, 'c1')).toBe('old'))
+ expect(spies.pushToast).toHaveBeenCalledWith(expect.any(String), 'error')
+ })
+
+ it('404: keeps the optimistic title without rollback or toast (pending)', async () => {
+ clerum.chat.getIndex.mockResolvedValue(localIndex([{ id: 'c1', title: 'old' }]))
+ clerum.rpc.renameSession.mockRejectedValue(new Error('Rename session failed (404)'))
+
+ const { result, spies } = renderController({
+ selectedAgent: 'agent-x',
+ agentNames: ['agent-x'],
+ })
+ await waitFor(() => expect(titleInList(result.current, 'c1')).toBe('old'))
+
+ await act(async () => {
+ await result.current.handleRenameChatForAgent('agent-x', 'c1', 'renamed')
+ })
+
+ // NOT an error: optimistic title stays, no rollback, no toast.
+ expect(titleInList(result.current, 'c1')).toBe('renamed')
+ expect(spies.pushToast).not.toHaveBeenCalledWith(expect.anything(), 'error')
+ })
+
+ it('network failure: keeps the optimistic title, queues offline, no toast', async () => {
+ clerum.chat.getIndex.mockResolvedValue(localIndex([{ id: 'c1', title: 'old' }]))
+ clerum.rpc.renameSession.mockRejectedValue(new Error('fetch failed'))
+
+ const { result, spies } = renderController({
+ selectedAgent: 'agent-x',
+ agentNames: ['agent-x'],
+ })
+ await waitFor(() => expect(titleInList(result.current, 'c1')).toBe('old'))
+
+ await act(async () => {
+ await result.current.handleRenameChatForAgent('agent-x', 'c1', 'renamed')
+ })
+
+ expect(titleInList(result.current, 'c1')).toBe('renamed')
+ expect(spies.pushToast).not.toHaveBeenCalledWith(expect.anything(), 'error')
+ })
+
+ it('T5: a pending (404) rename WINS over a server title on the next poll (case E protects C)', async () => {
+ clerum.chat.getIndex.mockResolvedValue(localIndex([{ id: 'c1', title: 'old' }]))
+ // The server reports a DIFFERENT title for the same session.
+ clerum.rpc.listSessions.mockResolvedValue({
+ items: [
+ { agent: 'agent-x', chatId: 'c1', turnCount: 1, lastActivityAt: NOW, title: 'server' },
+ ],
+ })
+ // First rename 404s (session not materialized yet), retry succeeds.
+ clerum.rpc.renameSession
+ .mockRejectedValueOnce(new Error('Rename session failed (404)'))
+ .mockResolvedValue({ title: 'renamed' })
+
+ const { result, rerender } = renderController({
+ selectedAgent: 'agent-x',
+ agentNames: ['agent-x'],
+ })
+ await waitFor(() => expect(titleInList(result.current, 'c1')).toBe('server'))
+
+ await act(async () => {
+ await result.current.handleRenameChatForAgent('agent-x', 'c1', 'renamed')
+ })
+
+ // Even though the server keeps sending 'server', the pending local rename wins.
+ expect(titleInList(result.current, 'c1')).toBe('renamed')
+ expect(clerum.rpc.renameSession).toHaveBeenCalledTimes(1)
+
+ // Next poll reports c1 → the queue retries the 404'd rename.
+ await act(async () => {
+ rerender({ agentNames: ['agent-x'] })
+ })
+ await waitFor(() => expect(clerum.rpc.renameSession).toHaveBeenCalledTimes(2))
+ // Still shows the rename (never clobbered by the server title).
+ expect(titleInList(result.current, 'c1')).toBe('renamed')
+ })
+
+ it('applyLocalTitleOnly updates the sidebar but never fires the rename RPC', async () => {
+ clerum.chat.getIndex.mockResolvedValue(localIndex([{ id: 'c1', title: 'old' }]))
+
+ const { result } = renderController({ selectedAgent: 'agent-x', agentNames: ['agent-x'] })
+ await waitFor(() => expect(titleInList(result.current, 'c1')).toBe('old'))
+
+ await act(async () => {
+ await result.current.applyLocalTitleOnly('agent-x', 'c1', 'local-auto-title')
+ })
+
+ expect(titleInList(result.current, 'c1')).toBe('local-auto-title')
+ expect(clerum.rpc.renameSession).not.toHaveBeenCalled()
+ })
+
+ it('T5: a rename in device A is seen by a fresh client B with no cache (server-authoritative)', async () => {
+ // Fresh client: empty local cache. The server reports the renamed title.
+ clerum.chat.getIndex.mockResolvedValue(localIndex([]))
+ clerum.rpc.listSessions.mockResolvedValue({
+ items: [
+ {
+ agent: 'agent-x',
+ chatId: 'c1',
+ turnCount: 1,
+ lastActivityAt: NOW,
+ title: 'renamed on A',
+ },
+ ],
+ })
+
+ const { result } = renderController({ selectedAgent: 'agent-x', agentNames: ['agent-x'] })
+
+ await waitFor(() => expect(titleInList(result.current, 'c1')).toBe('renamed on A'))
+ })
+})
+
+describe('rename pending queue — concurrency (spec 15 §2.5)', () => {
+ // FIX 1: a flush (catalog poll) landing while a PATCH is in flight must NOT
+ // fire a second renameSession for the same key.
+ it('does not fire a duplicate PATCH when a poll lands during an in-flight rename', async () => {
+ const inFlight = deferred<{ title: string }>()
+ clerum.chat.getIndex.mockResolvedValue(localIndex([{ id: 'c1', title: 'old' }]))
+ clerum.rpc.listSessions.mockResolvedValue(reportedSessions([{ chatId: 'c1' }]))
+ clerum.rpc.renameSession.mockReturnValue(inFlight.promise)
+
+ const { result, rerender } = renderController({
+ selectedAgent: 'agent-x',
+ agentNames: ['agent-x'],
+ })
+ await waitFor(() => expect(titleInList(result.current, 'c1')).toBe('old'))
+
+ let pending: Promise<void> | undefined
+ await act(async () => {
+ pending = result.current.handleRenameChatForAgent('agent-x', 'c1', 'renamed')
+ await flushMicrotasks()
+ })
+ await waitFor(() => expect(clerum.rpc.renameSession).toHaveBeenCalledTimes(1))
+
+ // A catalog poll lands while the PATCH is still in flight. (The same rerender
+ // trick drives a retry in the 404 case — see the T5 test — so it does invoke
+ // flushPendingRenames; here the in-flight guard must make it a no-op.)
+ await act(async () => {
+ rerender({ agentNames: ['agent-x'] })
+ await flushMicrotasks()
+ })
+ await act(async () => {
+ rerender({ agentNames: ['agent-x'] })
+ await flushMicrotasks()
+ })
+
+ // The poll must NOT have spawned a second PATCH.
+ expect(clerum.rpc.renameSession).toHaveBeenCalledTimes(1)
+
+ await act(async () => {
+ inFlight.resolve({ title: 'renamed' })
+ await pending
+ })
+ })
+
+ // FIX 2: renaming the same chat twice before the first PATCH resolves. The
+ // second rename's pending marker must survive the first (stale) 200, so the
+ // newer optimistic title keeps its case-E protection and is not clobbered.
+ it('a stale 200 from the first rename does not drop the second rename’s protection', async () => {
+ const first = deferred<{ title: string }>()
+ const second = deferred<{ title: string }>()
+ wireStatefulIndex(clerum, [{ id: 'c1', title: 'old' }])
+ // The server keeps reporting a DIFFERENT title — it must never win while a
+ // rename is pending.
+ clerum.rpc.listSessions.mockResolvedValue(reportedSessions([{ chatId: 'c1', title: 'server' }]))
+ clerum.rpc.renameSession
+ .mockImplementationOnce(() => first.promise)
+ .mockImplementationOnce(() => second.promise)
+
+ const { result, rerender } = renderController({
+ selectedAgent: 'agent-x',
+ agentNames: ['agent-x'],
+ })
+ await waitFor(() => expect(titleInList(result.current, 'c1')).toBe('server'))
+
+ let p1: Promise<void> | undefined
+ let p2: Promise<void> | undefined
+ await act(async () => {
+ p1 = result.current.handleRenameChatForAgent('agent-x', 'c1', 'A')
+ await flushMicrotasks()
+ })
+ await act(async () => {
+ p2 = result.current.handleRenameChatForAgent('agent-x', 'c1', 'B')
+ await flushMicrotasks()
+ })
+ await waitFor(() => expect(clerum.rpc.renameSession).toHaveBeenCalledTimes(2))
+ // Assert the CROSS-agent "Latest sessions" title: that list is what a poll
+ // (agentNames rerender) actually re-merges, so it exercises the precedence
+ // merge that a dropped marker would let the server clobber.
+ await waitFor(() => expect(titleInLatest(result.current, 'c1')).toBe('B'))
+
+ // The FIRST rename resolves 200 (stale — a newer rename replaced it).
+ await act(async () => {
+ first.resolve({ title: 'A' })
+ await p1
+ await flushMicrotasks()
+ })
+
+ // A poll lands: the second rename is still pending, so its local title wins
+ // over the server title. If the stale 200 had dropped the marker, the merge
+ // would clobber it back to 'server'.
+ await act(async () => {
+ rerender({ agentNames: ['agent-x'] })
+ await flushMicrotasks()
+ })
+ expect(titleInLatest(result.current, 'c1')).toBe('B')
+
+ await act(async () => {
+ second.resolve({ title: 'B' })
+ await p2
+ })
+ })
+
+ // FIX 2 (rollback target): the second rename's rollback restores the title from
+ // BEFORE the pending chain ('old'), never the first rename's unconfirmed 'A'.
+ it('rolls a re-renamed chat back to the pre-pending title, not the prior optimistic one', async () => {
+ const first = deferred<{ title: string }>()
+ const second = deferred<{ title: string }>()
+ wireStatefulIndex(clerum, [{ id: 'c1', title: 'old' }])
+ clerum.rpc.renameSession
+ .mockImplementationOnce(() => first.promise)
+ .mockImplementationOnce(() => second.promise)
+
+ const { result, spies } = renderController({
+ selectedAgent: 'agent-x',
+ agentNames: ['agent-x'],
+ })
+ await waitFor(() => expect(titleInList(result.current, 'c1')).toBe('old'))
+
+ let p1: Promise<void> | undefined
+ let p2: Promise<void> | undefined
+ await act(async () => {
+ p1 = result.current.handleRenameChatForAgent('agent-x', 'c1', 'A')
+ await flushMicrotasks()
+ })
+ await act(async () => {
+ p2 = result.current.handleRenameChatForAgent('agent-x', 'c1', 'B')
+ await flushMicrotasks()
+ })
+
+ // The second rename is rejected with a genuine 4xx → rollback.
+ await act(async () => {
+ second.reject(new Error('Rename session failed (400)'))
+ await p2
+ await flushMicrotasks()
+ })
+
+ // Rolled back to the pre-pending title 'old', NOT the first rename's 'A'.
+ await waitFor(() => expect(titleInList(result.current, 'c1')).toBe('old'))
+ expect(spies.pushToast).toHaveBeenCalledWith(expect.any(String), 'error')
+
+ // Clean up the still-in-flight first attempt (it is now stale → no-op).
+ await act(async () => {
+ first.resolve({ title: 'A' })
+ await p1
+ })
+ })
+
+ // FIX 3: a 4xx on a chat with no local cache entry (previousTitle === '') must
+ // NOT blank the sidebar — no rollback to an empty title.
+ it('does not roll back to a blank title when there was no cached previous title', async () => {
+ clerum.chat.getIndex.mockResolvedValue(localIndex([]))
+ // Server reports the chat so it lands in the list as a server-only entry.
+ clerum.rpc.listSessions.mockResolvedValue(reportedSessions([{ chatId: 'c1', title: 'server' }]))
+ clerum.rpc.renameSession.mockRejectedValue(new Error('Rename session failed (400)'))
+
+ const { result, spies } = renderController({
+ selectedAgent: 'agent-x',
+ agentNames: ['agent-x'],
+ })
+ await waitFor(() => expect(titleInList(result.current, 'c1')).toBe('server'))
+
+ await act(async () => {
+ await result.current.handleRenameChatForAgent('agent-x', 'c1', 'renamed')
+ })
+
+ // The optimistic title was applied; on the 4xx we must NOT blank it.
+ expect(titleInList(result.current, 'c1')).not.toBe('')
+ expect(spies.pushToast).toHaveBeenCalledWith(expect.any(String), 'error')
+ })
+})
diff --git a/desktop-app/ui/src/hooks/domain/useAgentChatController.ts b/desktop-app/ui/src/hooks/domain/useAgentChatController.ts
index 6312b41ef..cd92b70b0 100644
--- a/desktop-app/ui/src/hooks/domain/useAgentChatController.ts
+++ b/desktop-app/ui/src/hooks/domain/useAgentChatController.ts
@@ -933,6 +933,7 @@ export function useAgentChatController({
handleCreateChat,
handleRenameChat,
handleRenameChatForAgent,
+ applyLocalTitleOnly,
handleDeleteChat,
handleDeleteChatForAgent,
} = chatListCtl
@@ -948,6 +949,7 @@ export function useAgentChatController({
autoSelectedChatIdRef.current = chatId
},
shouldAutoSelectLatest: () => navItem === DESKTOP_ROUTES.chat,
+ pushToast,
}
})
@@ -2503,7 +2505,11 @@ export function useAgentChatController({
: '')
const autoTitle = truncateTitle(autoTitleSeed)
if (autoTitle) {
- void handleRenameChat(sendChatId, autoTitle)
+ // spec 15 §2.5/B19: the client-derived auto-title stays LOCAL only —
+ // it must not be pushed by RPC (un-redacted, and it would race the
+ // server's own COALESCE auto-title). Only an explicit user rename
+ // syncs. The server materializes the authoritative title on turn 1.
+ void applyLocalTitleOnly(selectedAgent, sendChatId, autoTitle)
}
}
}
@@ -2738,7 +2744,7 @@ export function useAgentChatController({
chatStore,
clearComposerAfterSend,
fsm,
- handleRenameChat,
+ applyLocalTitleOnly,
pushToast,
tracker,
ensureAgentActivityStream,
@@ -2952,6 +2958,7 @@ export function useAgentChatController({
handleCreateChat,
handleRenameChat,
handleRenameChatForAgent,
+ applyLocalTitleOnly,
handleDeleteChat,
handleDeleteChatForAgent,
handleSelectChat,
diff --git a/desktop-app/ui/src/hooks/domain/useChatListController.ts b/desktop-app/ui/src/hooks/domain/useChatListController.ts
index 6337a57c7..d17b76a41 100644
--- a/desktop-app/ui/src/hooks/domain/useChatListController.ts
+++ b/desktop-app/ui/src/hooks/domain/useChatListController.ts
@@ -1,7 +1,7 @@
import { type MutableRefObject, useCallback, useEffect, useRef, useState } from 'react'
import { makeTaskKey } from '@contexts/AgentTaskTrackerContext'
import { agentChatPlaceholder, remotePlaceholder } from '@lib/chatTitle'
-import { resolveSessionTitle } from '@lib/resolveSessionTitle'
+import { type PendingRename, resolveSessionTitle } from '@lib/resolveSessionTitle'
import type { ChatIndex, ChatMetadata, SessionsListResult } from '../../../../src/types'
import { scheduleAfterFirstPaint } from '../scheduleAfterFirstPaint'
import type { useChatStore } from '../useChatStore'
@@ -62,6 +62,12 @@ export interface ChatListControllerHost {
getAutoSelectedChatId: () => string | null
markAutoSelectedChat: (chatId: string | null) => void
shouldAutoSelectLatest: () => boolean
+ /**
+ * Transient feedback for a rename that genuinely failed (spec 15 §2.5). The
+ * parent owns the toast stack; the controller reaches it through this ref
+ * rather than taking `pushToast` as a param (its callers don't have it).
+ */
+ pushToast: (message: string, tone: 'success' | 'error' | 'info') => void
}
interface UseChatListControllerParams {
@@ -91,6 +97,26 @@ function isRecoverableCatalogCursorError(error: unknown): boolean {
return /\b4\d\d\b/.test(message) || message.toLowerCase().includes('invalid')
}
+/**
+ * Classify a failed rename RPC for the pending-rename queue (spec 15 §2.5). The
+ * HTTP status rides the error message as `(NNN)` (see rpcProxyClient.renameSession
+ * — the raw title is never in the message). A missing status (a bare transport
+ * error) is treated as a network failure.
+ * - 'not-found' (404): session not materialized server-side yet → keep pending,
+ * retry once it appears in listSessions. NOT an error; no rollback.
+ * - 'client-error' (other 4xx: 400 invalid title, 401/403 access): a genuine
+ * rejection → roll the optimistic title back and toast.
+ * - 'network' (5xx / no status): transient → queue offline, retry on reconnect.
+ */
+function classifyRenameError(error: unknown): 'not-found' | 'client-error' | 'network' {
+ const message = error instanceof Error ? error.message : String(error)
+ const match = message.match(/\((\d{3})\)/)
+ const status = match ? Number(match[1]) : null
+ if (status === 404) return 'not-found'
+ if (status !== null && status >= 400 && status < 500) return 'client-error'
+ return 'network'
+}
+
function dedupeSidebarChats<T extends SidebarChatEntry>(chats: T[]): T[] {
const seen = new Set<string>()
return chats.filter(chat => {
@@ -132,6 +158,44 @@ export function useChatListController({
const chatListLoadingMoreByAgentRef = useRef<Set<string>>(new Set())
const requestGenerationRef = useRef(0)
+ // Spec 15 §2.5 (B21) — pending-rename queue. A user rename is optimistic-local
+ // first, then synced by RPC; while unconfirmed the local title wins over the
+ // server (§2.2 cases E/F). Kept in a ref (NOT on the persisted ChatMetadata):
+ // it must live in memory only and survive list rebuilds + retries. Keyed by
+ // `${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
+ }
+ >
+ >(new Map())
+
+ const pendingRenameKey = (agentRef: string, chatId: string): string => `${agentRef}:${chatId}`
+
+ const pendingRenameStateFor = useCallback((agentRef: string, chatId: string): PendingRename => {
+ return pendingRenamesRef.current.get(pendingRenameKey(agentRef, chatId))?.state ?? 'none'
+ }, [])
+
+ // Indirection so the catalog loaders (defined above the queue) can trigger a
+ // retry of pending renames after a listSessions poll without depending on the
+ // queue's identity. Wired in an effect once the queue is defined.
+ const flushPendingRenamesRef = useRef<(serverChatKeys?: Set<string>) => void>(() => {})
+
useEffect(() => {
requestGenerationRef.current += 1
}, [isAuthenticated, scopeKey])
@@ -235,9 +299,9 @@ export function useChatListController({
const dedupedPrevious = dedupeSidebarChats(previous)
const serverById = new Map(serverSessions.map(s => [s.chatId, s]))
const knownIds = new Set(dedupedPrevious.map(c => c.id))
- // Cases C/D (§2.2): the server is authoritative for a cached chat's
- // title when it reports one; otherwise the cached local title stays.
- // Fase A has no pending renames, so pendingRename is always 'none'.
+ // Cases C/D/E/F (§2.2): the server is authoritative for a cached chat's
+ // title when it reports one AND no local rename is pending; a pending
+ // rename (in-flight / offline) keeps the local title until it lands.
const reconciled = dedupedPrevious.map(chat => {
const server = serverById.get(chat.id)
if (!server) return chat
@@ -245,7 +309,7 @@ export function useChatListController({
inCache: true,
localTitle: chat.title,
serverTitle: server.title,
- pendingRename: 'none',
+ pendingRename: pendingRenameStateFor(agentRef, chat.id),
placeholder: agentChatPlaceholder(chat.id),
})
return title === chat.title ? chat : { ...chat, title }
@@ -259,7 +323,7 @@ export function useChatListController({
title: resolveSessionTitle({
inCache: false,
serverTitle: s.title,
- pendingRename: 'none',
+ pendingRename: pendingRenameStateFor(agentRef, s.chatId),
placeholder: agentChatPlaceholder(s.chatId),
}).title,
createdAt: s.lastActivityAt,
@@ -273,6 +337,10 @@ export function useChatListController({
return [...reconciled, ...fromServerOnly].sort(byUpdatedDesc)
})
+ // §2.5: a rename that 404'd (session not yet server-side) retries now that
+ // the poll reports which sessions exist.
+ flushPendingRenamesRef.current(new Set(serverSessions.map(s => `${agentRef}:${s.chatId}`)))
+
const latestServerSession = serverSessions[0]
// A mode:none request suppresses this one deferred catalog result. Consume
// it here, after the post-paint continuation reaches the auto-select gate,
@@ -369,8 +437,8 @@ export function useChatListController({
const dedupedPrevious = dedupeSidebarChats(previous)
const serverById = new Map(serverSessions.map(s => [s.chatId, s]))
const knownIds = new Set(dedupedPrevious.map(c => c.id))
- // Cases C/D (§2.2): reconcile the title of any cached chat this page
- // also reports; server wins when it has a title, else keep local.
+ // Cases C/D/E/F (§2.2): reconcile the title of any cached chat this page
+ // also reports; server wins when it has a title and no rename is pending.
const reconciled = dedupedPrevious.map(chat => {
const server = serverById.get(chat.id)
if (!server) return chat
@@ -378,7 +446,7 @@ export function useChatListController({
inCache: true,
localTitle: chat.title,
serverTitle: server.title,
- pendingRename: 'none',
+ pendingRename: pendingRenameStateFor(agentRef, chat.id),
placeholder: agentChatPlaceholder(chat.id),
})
return title === chat.title ? chat : { ...chat, title }
@@ -391,7 +459,7 @@ export function useChatListController({
title: resolveSessionTitle({
inCache: false,
serverTitle: s.title,
- pendingRename: 'none',
+ pendingRename: pendingRenameStateFor(agentRef, s.chatId),
placeholder: agentChatPlaceholder(s.chatId),
}).title,
createdAt: s.lastActivityAt,
@@ -619,7 +687,14 @@ export function useChatListController({
host.current?.scrollChatToBottom()
}, [chatStore, appendNewEntry, host])
- const handleRenameChatForAgent = useCallback(
+ /**
+ * Optimistic LOCAL-only title update (spec 15 §2.5 / B19). Persists to the
+ * local index and both sidebar lists WITHOUT firing the rename RPC. Used by
+ * the first-turn auto-title path (which must NOT sync an un-redacted client
+ * title that would race the server's COALESCE) and, internally, by the
+ * user-rename handler before it syncs.
+ */
+ const applyLocalTitleOnly = useCallback(
async (agentRef: string, chatId: string, newTitle: string) => {
if (!agentRef) return
const requestGeneration = requestGenerationRef.current
@@ -644,6 +719,128 @@ export function useChatListController({
[chatStore]
)
+ /**
+ * Sync one pending rename to the server (spec 15 §2.5). 200 confirms and clears
+ * the marker; a 404 (session not materialized yet) or a network/5xx failure
+ * keeps it pending — 'in-flight' (retried when the session appears in
+ * listSessions) or 'offline' (retried on reconnect) — so the local title keeps
+ * winning over the server (§2.2 E/F) until it lands. A genuine 4xx rejection
+ * 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
+ }) => {
+ 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
+ // FIX 2: only act on the entry that is STILL the current pending entry for
+ // this key — a newer rename may have replaced it, and that newer attempt
+ // owns the key from here on. Both guards use object identity.
+ if (entry.sending) return
+ if (pendingRenamesRef.current.get(key) !== entry) return
+ entry.sending = true
+ try {
+ 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)
+ }
+ } catch (error) {
+ // A newer rename superseded this one: leave the key entirely to it — no
+ // rollback, no re-mark (FIX 2).
+ if (pendingRenamesRef.current.get(key) !== entry) return
+ const kind = classifyRenameError(error)
+ if (kind === 'client-error') {
+ pendingRenamesRef.current.delete(key)
+ // 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.
+ if (entry.previousTitle) {
+ await applyLocalTitleOnly(entry.agentRef, entry.chatId, entry.previousTitle)
+ }
+ host.current?.pushToast(
+ 'Could not rename the chat. Please try a different name.',
+ 'error'
+ )
+ return
+ }
+ // 404 → keep 'in-flight' (retry once the session exists server-side);
+ // network / 5xx → 'offline' (retry on reconnect). Never rolled back.
+ entry.state = kind === 'network' ? 'offline' : 'in-flight'
+ } finally {
+ // Clearing on the entry object is safe even if it was deleted from the
+ // Map (a superseding rename owns a different object).
+ entry.sending = false
+ }
+ },
+ [chatStore, applyLocalTitleOnly, host]
+ )
+
+ /**
+ * Retry pending renames (spec 15 §2.5). With `serverChatKeys` (a listSessions
+ * poll), retry an 'in-flight' entry only once its session actually appears
+ * server-side (the 404 → turn-1 case); 'offline' entries retry unconditionally
+ * (the reconnect case). Without keys (a `window 'online'` event) retry all.
+ */
+ const flushPendingRenames = useCallback(
+ async (serverChatKeys?: Set<string>) => {
+ for (const entry of [...pendingRenamesRef.current.values()]) {
+ // FIX 1: skip a key with a PATCH already in flight (attemptRenameRpc
+ // guards this too, but skipping avoids spawning a no-op).
+ if (entry.sending) continue
+ const key = pendingRenameKey(entry.agentRef, entry.chatId)
+ if (entry.state === 'in-flight' && serverChatKeys && !serverChatKeys.has(key)) continue
+ await attemptRenameRpc(entry)
+ }
+ },
+ [attemptRenameRpc]
+ )
+
+ /**
+ * Explicit user rename (spec 15 §2.5 / B19): optimistic local first, then sync
+ * to the server via the pending-rename queue. This is the ONLY rename path that
+ * fires RPC (the auto-title path uses `applyLocalTitleOnly`).
+ */
+ const handleRenameChatForAgent = useCallback(
+ async (agentRef: string, chatId: string, newTitle: string) => {
+ if (!agentRef) return
+ const key = pendingRenameKey(agentRef, chatId)
+ // FIX 2: the rollback target is the title BEFORE the pending chain began.
+ // If a rename is already pending for this key, preserve its `previousTitle`
+ // (the last non-pending value) rather than re-reading the index — which now
+ // holds the earlier rename's UNCONFIRMED optimistic title.
+ const existing = pendingRenamesRef.current.get(key)
+ let previousTitle: string
+ if (existing) {
+ previousTitle = existing.previousTitle
+ } else {
+ const index = await chatStore.getIndex(agentRef)
+ previousTitle = index.chats.find(c => c.id === chatId)?.title ?? ''
+ }
+ await applyLocalTitleOnly(agentRef, chatId, newTitle)
+ // 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 = {
+ agentRef,
+ chatId,
+ title: newTitle,
+ previousTitle,
+ state: 'in-flight' as PendingRename,
+ sending: false,
+ }
+ pendingRenamesRef.current.set(key, entry)
+ await attemptRenameRpc(entry)
+ },
+ [chatStore, applyLocalTitleOnly, attemptRenameRpc]
+ )
+
const handleRenameChat = useCallback(
async (chatId: string, newTitle: string) => {
const agentRef = selectedAgentRef.current
@@ -653,6 +850,22 @@ export function useChatListController({
[handleRenameChatForAgent]
)
+ // Retry offline (and best-effort in-flight) pending renames when connectivity
+ // returns (spec 15 §2.5 case F).
+ useEffect(() => {
+ const handleOnline = () => {
+ void flushPendingRenames()
+ }
+ window.addEventListener('online', handleOnline)
+ return () => window.removeEventListener('online', handleOnline)
+ }, [flushPendingRenames])
+
+ useEffect(() => {
+ flushPendingRenamesRef.current = (serverChatKeys?: Set<string>) => {
+ void flushPendingRenames(serverChatKeys)
+ }
+ }, [flushPendingRenames])
+
const handleDeleteChatForAgent = useCallback(
async (agentRef: string, chatId: string) => {
if (!agentRef) return
@@ -768,7 +981,8 @@ export function useChatListController({
serverByKey.set(`${group.agentRef}:${session.chatId}`, session)
}
}
- // Cases C/D (§2.2): server-authoritative title for cached entries.
+ // Cases C/D/E/F (§2.2): server-authoritative title for cached entries,
+ // unless a local rename is pending for that (agentRef, chatId).
const reconciled = previous.map(item => {
const server = serverByKey.get(`${item.agentRef}:${item.id}`)
if (!server) return item
@@ -776,7 +990,7 @@ export function useChatListController({
inCache: true,
localTitle: item.title,
serverTitle: server.title,
- pendingRename: 'none',
+ pendingRename: pendingRenameStateFor(item.agentRef, item.id),
placeholder: remotePlaceholder(item.id),
})
return title === item.title ? item : { ...item, title }
@@ -794,7 +1008,7 @@ export function useChatListController({
title: resolveSessionTitle({
inCache: false,
serverTitle: session.title,
- pendingRename: 'none',
+ pendingRename: pendingRenameStateFor(group.agentRef, session.chatId),
placeholder: remotePlaceholder(session.chatId),
}).title,
createdAt: session.lastActivityAt,
@@ -807,6 +1021,16 @@ export function useChatListController({
}
return [...reconciled, ...remoteOnly].sort(byUpdatedDesc)
})
+
+ // §2.5: retry any rename that 404'd, now that this cross-agent poll
+ // reports which sessions exist server-side.
+ flushPendingRenamesRef.current(
+ new Set(
+ sessionGroups.flatMap(group =>
+ group.sessions.map(session => `${group.agentRef}:${session.chatId}`)
+ )
+ )
+ )
} finally {
if (!cancelled) {
setLatestChatSessionsLoading(false)
@@ -839,6 +1063,7 @@ export function useChatListController({
handleCreateChat,
handleRenameChat,
handleRenameChatForAgent,
+ applyLocalTitleOnly,
handleDeleteChat,
handleDeleteChatForAgent,
// Loader + list-loading control (parent agent-selection effect).
diff --git a/desktop-app/ui/src/hooks/useChatStore.ts b/desktop-app/ui/src/hooks/useChatStore.ts
index cd2aa91a0..cc6771514 100644
--- a/desktop-app/ui/src/hooks/useChatStore.ts
+++ b/desktop-app/ui/src/hooks/useChatStore.ts
@@ -221,6 +221,14 @@ export function useChatStore() {
hostModelRequests.delete(hostModelKey(hostRef, chatId))
return result
}, [])
+ // Spec 15 Fase B — propagate an explicit user rename to the server. In this app
+ // hostRef === agent === agentRef (same key used by listSessions). Rejections
+ // propagate so the pending-rename queue can branch on the HTTP status.
+ const renameSession = useCallback(
+ (agentRef: string, chatId: string, title: string) =>
+ window.clerum.rpc.renameSession(agentRef, agentRef, chatId, title),
+ []
+ )
const clearCachedRemoteData = useCallback(() => {
sessionCatalogRequests.clear()
hostModelRequests.clear()
@@ -295,6 +303,7 @@ export function useChatStore() {
getContextBreakdown,
getHostModels,
setHostModel,
+ renameSession,
clearCachedRemoteData,
setRemoteCacheScope,
setPendingModel,