Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
feat(desktop-app): read and merge server-authoritative session title (spec 15 Phase A)
Diego Zacariasbff5f7ae40c3
diff --git a/desktop-app/src/chatStore.ts b/desktop-app/src/chatStore.tsindex 10b5d50cc..563a7842f 100644--- a/desktop-app/src/chatStore.ts+++ b/desktop-app/src/chatStore.ts@@ -1758,9 +1758,10 @@ export class ChatStore {* Deliberately does NOT create entries for server-only sessions: the sidebar's* in-memory merge (`useChatListController`) already surfaces those, and a local* `deleteChat` doesn't remove the server session — eagerly re-persisting it- * would resurrect a chat the user just deleted. Titles are never touched (the- * server has none; the client derives them on open). Returns the count of- * entries reconciled.+ * would resurrect a chat the user just deleted. Titles are never touched here:+ * the server title is applied by the in-memory §2.2 catalog merge in+ * `useChatListController`, not persisted into this local index. Returns the+ * count of entries reconciled.*/async upsertServerSessions(agentRef: string,diff --git a/desktop-app/src/rpcProxyClient.ts b/desktop-app/src/rpcProxyClient.tsindex 2425e1963..c3da8446e 100644--- a/desktop-app/src/rpcProxyClient.ts+++ b/desktop-app/src/rpcProxyClient.ts@@ -52,6 +52,26 @@ function optionalWireString(value: unknown, label: string): string | undefined {return wireString(value, label)}+/**+ * Strip everything that would let a title read off the wire misrender or spoof,+ * then trim (spec 15 §2.2/§5, A14). Removes the whole Unicode "Other" category+ * `\p{C}` (control, format — bidi overrides, zero-width joiners/marks, BOM — and+ * surrogate/private-use/unassigned) plus line/paragraph separators `\p{Zl}`/+ * `\p{Zp}` (U+2028/U+2029). This aligns with the server-side writer (which+ * strips `\p{C}` and collapses whitespace) and guarantees a single-line title in+ * the sidebar and the destructive rename dialog. A session title is authored on+ * one device and read on another; a stale host or a malicious device could ship+ * a bidi-override that spoofs the dialog, so the reader never trusts the value —+ * this is defense in depth on read (ZWJ is stripped too: anti-spoofing wins over+ * emoji fidelity for a value that gates a destructive dialog). Returns+ * `undefined` when nothing legible remains, so the caller falls back to the+ * local cache or a placeholder instead of rendering a blank title.+ */+function sanitizeWireTitle(value: string): string | undefined {+ const cleaned = value.replace(/[\p{C}\p{Zl}\p{Zp}]/gu, '').trim()+ return cleaned.length > 0 ? cleaned : undefined+}+function wireSafeInteger(value: unknown,label: string,@@ -135,7 +155,9 @@ function parseToolSteps(value: unknown, label: string): MessageToolStep[] {})}-function parseSessionsListResult(value: unknown): SessionsListResult {+// Exported for tests: renderer/parser tests derive their fixtures from the real+// producer (pr-discipline T1) instead of hand-mocking the parsed shape.+export function parseSessionsListResult(value: unknown): SessionsListResult {const record = wireObject(value, 'sessions response')if (!Array.isArray(record.items)) throw new Error('Invalid sessions response.items')let firstItemError: unknown@@ -162,6 +184,16 @@ function parseSessionsListResult(value: unknown): SessionsListResult {)!,}: {}),+ ...(() => {+ // A malformed optional title must not drop a real conversation: a+ // present-but-non-string value falls to "no title" (the session+ // survives, untitled), consistent with how null/absent/empty-after-+ // sanitize are handled here. Only mandatory fields (agent, chatId,+ // lastActivityAt) throw and drop the item.+ const title =+ typeof entry.title === 'string' ? sanitizeWireTitle(entry.title) : undefined+ return title !== undefined ? { title } : {}+ })(),lastActivityAt: wireString(entry.lastActivityAt,`sessions response.items[${index}].lastActivityAt`diff --git a/desktop-app/src/types.ts b/desktop-app/src/types.tsindex e9d94dc65..489ac52ae 100644--- a/desktop-app/src/types.ts+++ b/desktop-app/src/types.ts@@ -983,6 +983,14 @@ export interface SessionsListResult {chatId: stringturnCount: numbermessageCount?: number+ /**+ * Server-authoritative session title (spec 15 §2.1). Absent when the host+ * predates the feature or the session has no materialized title yet — the+ * client then falls back to the local cache or a placeholder (§2.2 cases+ * B/D). Sanitized on read in `parseSessionsListResult` (the client never+ * trusts a title minted by another device or an older host).+ */+ title?: stringlastActivityAt: stringstate?: SessionLifecycleStateactiveTaskId?: stringdiff --git a/desktop-app/test/rpcProxyClient.test.ts b/desktop-app/test/rpcProxyClient.test.tsindex 614871e51..632a1ff4d 100644--- a/desktop-app/test/rpcProxyClient.test.ts+++ b/desktop-app/test/rpcProxyClient.test.ts@@ -1,5 +1,5 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'-import { RpcProxyClient } from '../src/rpcProxyClient.js'+import { RpcProxyClient, parseSessionsListResult } from '../src/rpcProxyClient.js'// ── Mocks ─────────────────────────────────────────────────────────────────────@@ -205,3 +205,81 @@ describe('RpcProxyClient — openTaskProgressStream()', () => {expect(events).toEqual(['open', 'heartbeat', 'done'])})})++describe('parseSessionsListResult — title parse + sanitize on read (spec 15 §2.2/A14)', () => {+ const baseItem = {+ agent: 'chatllm',+ chatId: 'c1',+ turnCount: 1,+ lastActivityAt: '2026-09-12T00:00:00.000Z',+ }++ it('parses a clean server title verbatim', () => {+ const result = parseSessionsListResult({+ items: [{ ...baseItem, title: 'Deploy the staging cluster' }],+ })+ expect(result.items[0]?.title).toBe('Deploy the staging cluster')+ })++ it('omits the title when the host does not report one', () => {+ const result = parseSessionsListResult({ items: [baseItem] })+ expect(result.items[0]).not.toHaveProperty('title')+ })++ it('strips bidi-override and zero-width characters (spoofing defense)', () => {+ // A title crafted to spoof the destructive rename dialog with an RLO+ // override + zero-width joiner. The client must not trust it.+ const hostile = 'Safeerongi name'+ const result = parseSessionsListResult({ items: [{ ...baseItem, title: hostile }] })+ expect(result.items[0]?.title).toBe('Safeerongi name')+ expect(result.items[0]?.title).not.toContain('')+ expect(result.items[0]?.title).not.toContain('')+ })++ it('strips control characters (newlines, tabs, NUL)', () => {+ const result = parseSessionsListResult({+ items: [{ ...baseItem, title: 'line1\n\tline2 ' }],+ })+ expect(result.items[0]?.title).toBe('line1line2')+ })++ it('drops a title that is empty after sanitization', () => {+ const result = parseSessionsListResult({+ items: [{ ...baseItem, title: ' ' }],+ })+ expect(result.items[0]).not.toHaveProperty('title')+ })++ it('keeps a session whose optional title is a non-string, just untitled (not dropped)', () => {+ // A malformed cosmetic field must not make a real conversation disappear.+ // T4: assert the resulting item (present, untitled), not a drop count.+ const result = parseSessionsListResult({+ items: [{ ...baseItem, chatId: 'keep', title: 123 }],+ })+ expect(result.items).toHaveLength(1)+ expect(result.items[0]?.chatId).toBe('keep')+ expect(result.items[0]).not.toHaveProperty('title')+ expect(result.droppedItemCount).toBeUndefined()+ })++ it('still drops an item whose MANDATORY field is malformed (title fix does not mask this)', () => {+ const result = parseSessionsListResult({+ items: [+ { ...baseItem, chatId: 'good', title: 'fine' },+ { ...baseItem, chatId: 'bad', lastActivityAt: 123 },+ ],+ })+ expect(result.items).toHaveLength(1)+ expect(result.items[0]?.chatId).toBe('good')+ expect(result.droppedItemCount).toBe(1)+ })++ it('strips line/paragraph separators (U+2028/U+2029) — single-line title', () => {+ const result = parseSessionsListResult({+ items: [{ ...baseItem, title: 'line1\u2028line2\u2029end' }],+ })+ expect(result.items[0]?.title).toBe('line1line2end')+ expect(result.items[0]?.title).not.toContain('\u2028')+ expect(result.items[0]?.title).not.toContain('\u2029')+ })+})diff --git a/desktop-app/ui/src/hooks/domain/__tests__/chatListTitleMerge.test.tsx b/desktop-app/ui/src/hooks/domain/__tests__/chatListTitleMerge.test.tsxnew file mode 100644index 000000000..5e824d3de--- /dev/null+++ b/desktop-app/ui/src/hooks/domain/__tests__/chatListTitleMerge.test.tsx@@ -0,0 +1,168 @@+// @vitest-environment jsdom+/**+ * spec 15 §2.2 — the session-title precedence merge, asserted through the+ * observable sidebar output (pr-discipline T4: assert the title the user sees,+ * not an intermediate effect). Covers cases A–D of the decision table for the+ * agent-scoped chat list, plus the cross-agent "Latest sessions" placeholder.+ *+ * T1: the server-side `listSessions` payloads are run through the REAL wire+ * parser (`parseSessionsListResult`) before being handed to the IPC mock, so the+ * fixtures are derived from the producer instead of hand-built parsed shapes.+ */+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { waitFor } from '@testing-library/react'+import { parseSessionsListResult } from '../../../../../src/rpcProxyClient'+import type { ChatIndex, SessionsListResult } 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'++/** Parse a raw wire payload through the real producer parser (T1). */+function serverSessions(+ items: Array<{ agent: string; chatId: string; title?: string }>+): SessionsListResult {+ return parseSessionsListResult({+ items: items.map(i => ({+ agent: i.agent,+ chatId: i.chatId,+ turnCount: 1,+ lastActivityAt: NOW,+ ...(i.title !== undefined ? { title: i.title } : {}),+ })),+ })+}++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,+ })),+ }+}++describe('chat list title merge (spec 15 §2.2, cases A–D)', () => {+ it('case A: server-only session with a title shows the server title (no placeholder)', async () => {+ clerum.chat.getIndex.mockResolvedValue(localIndex([]))+ clerum.rpc.listSessions.mockResolvedValue(+ serverSessions([{ agent: 'agent-x', chatId: 'chat-a', title: 'Deploy staging' }])+ )++ const { result } = renderController({ selectedAgent: 'agent-x', agentNames: ['agent-x'] })++ await waitFor(() =>+ expect(result.current.chatList.find(c => c.id === 'chat-a')?.title).toBe('Deploy staging')+ )+ })++ it('case B: server-only session with no title shows the "Chat <id>" placeholder', async () => {+ clerum.chat.getIndex.mockResolvedValue(localIndex([]))+ clerum.rpc.listSessions.mockResolvedValue(+ serverSessions([{ agent: 'agent-x', chatId: 'chat-bcdef012345' }])+ )++ const { result } = renderController({ selectedAgent: 'agent-x', agentNames: ['agent-x'] })++ await waitFor(() =>+ expect(result.current.chatList.find(c => c.id === 'chat-bcdef012345')?.title).toBe(+ 'Chat chat-bcd'+ )+ )+ })++ it('case C: cached session + server title -> server wins (picks up a rename from another device)', async () => {+ clerum.chat.getIndex.mockResolvedValue(localIndex([{ id: 'chat-c', title: 'old local name' }]))+ clerum.rpc.listSessions.mockResolvedValue(+ serverSessions([{ agent: 'agent-x', chatId: 'chat-c', title: 'renamed on device B' }])+ )++ const { result } = renderController({ selectedAgent: 'agent-x', agentNames: ['agent-x'] })++ await waitFor(() =>+ expect(result.current.chatList.find(c => c.id === 'chat-c')?.title).toBe(+ 'renamed on device B'+ )+ )+ })++ it('case D: cached session + server sends no title -> local fallback survives', async () => {+ clerum.chat.getIndex.mockResolvedValue(+ localIndex([{ id: 'chat-d', title: 'my local only name' }])+ )+ clerum.rpc.listSessions.mockResolvedValue(+ serverSessions([{ agent: 'agent-x', chatId: 'chat-d' }])+ )++ const { result } = renderController({ selectedAgent: 'agent-x', agentNames: ['agent-x'] })++ // Wait until the server catalog has been merged (the entry is present), then+ // confirm the local title was NOT clobbered by a placeholder.+ await waitFor(() => expect(result.current.chatList.some(c => c.id === 'chat-d')).toBe(true))+ expect(result.current.chatList.find(c => c.id === 'chat-d')?.title).toBe('my local only name')+ })+})++describe('cross-agent "Latest sessions" title merge (spec 15 §2.2)', () => {+ it('case A: server title on a cross-agent session replaces the "Remote ·" placeholder', async () => {+ clerum.chat.getIndex.mockResolvedValue(localIndex([]))+ clerum.rpc.listSessions.mockImplementation(async (agentRef: string) =>+ agentRef === 'agent-y'+ ? serverSessions([{ agent: 'agent-y', chatId: 'chat-y', title: 'Cross-device title' }])+ : serverSessions([])+ )++ const { result } = renderController({+ selectedAgent: 'agent-x',+ agentNames: ['agent-x', 'agent-y'],+ })++ await waitFor(() =>+ expect(+ result.current.latestChatSessions.find(s => s.agentRef === 'agent-y' && s.id === 'chat-y')+ ?.title+ ).toBe('Cross-device title')+ )+ })++ it('case B: no server title on a cross-agent session shows the "Remote ·" placeholder', async () => {+ clerum.chat.getIndex.mockResolvedValue(localIndex([]))+ clerum.rpc.listSessions.mockImplementation(async (agentRef: string) =>+ agentRef === 'agent-y'+ ? serverSessions([{ agent: 'agent-y', chatId: 'chat-yabcdef01' }])+ : serverSessions([])+ )++ const { result } = renderController({+ selectedAgent: 'agent-x',+ agentNames: ['agent-x', 'agent-y'],+ })++ await waitFor(() =>+ expect(+ result.current.latestChatSessions.find(+ s => s.agentRef === 'agent-y' && s.id === 'chat-yabcdef01'+ )?.title+ ).toBe('Remote · chat-yab')+ )+ })+})diff --git a/desktop-app/ui/src/hooks/domain/__tests__/useAgentChatController.test.tsx b/desktop-app/ui/src/hooks/domain/__tests__/useAgentChatController.test.tsxindex 387503f4c..5d5ff20d0 100644--- a/desktop-app/ui/src/hooks/domain/__tests__/useAgentChatController.test.tsx+++ b/desktop-app/ui/src/hooks/domain/__tests__/useAgentChatController.test.tsx@@ -127,8 +127,12 @@ describe('useAgentChatController — characterization (D.0)', () => {// Server is source of truth → replace, not append.expect(clerum.chat.replaceMessages).toHaveBeenCalled()expect(clerum.chat.appendMessages).not.toHaveBeenCalled()- // Auto-title from the first user turn.- expect(clerum.chat.rename).toHaveBeenCalledWith('agent-x', 'chat-2', 'remote question')+ // spec 15 §2.2/A19: the first-turn auto-title is shown EPHEMERALLY in the+ // sidebar (observable output, T4) but is NOT persisted via rename — the+ // server title is authoritative and a persisted client-derived title would+ // linger as a stale case-D fallback.+ expect(clerum.chat.rename).not.toHaveBeenCalled()+ expect(result.current.chatList.find(c => c.id === 'chat-2')?.title).toBe('remote question')expect(result.current.chatMessages).toHaveLength(2)expect(result.current.activeChatId).toBe('chat-2')})diff --git a/desktop-app/ui/src/hooks/domain/useAgentChatController.ts b/desktop-app/ui/src/hooks/domain/useAgentChatController.tsindex b34db491f..6312b41ef 100644--- a/desktop-app/ui/src/hooks/domain/useAgentChatController.ts+++ b/desktop-app/ui/src/hooks/domain/useAgentChatController.ts@@ -10,6 +10,7 @@ import {buildChatMessageAttachments,buildResponseFileAttachments,} from '@lib/chatMessageAttachments'+import { truncateTitle } from '@lib/chatTitle'import { buildComposerRequestContent } from '@lib/composerReferencesPrompt'import {mergeAuthoritativeServerMessages,@@ -1534,17 +1535,17 @@ export function useAgentChatController({}loadedLocalMessageCountRef.current = rendered.length// Auto-title a fresh hydration (empty cache) from the first user turn, so a- // server-only chat doesn't keep its "Chat <id>" placeholder (A.4.4 / S4).+ // server-only chat shows a meaningful name at open instead of "New Chat".+ // spec 15 §2.2/A19: this is EPHEMERAL (sidebar state only) — NOT persisted+ // via renameChat. The server title is authoritative (case C), so persisting+ // a client-derived title would only (a) diverge from the server's own+ // auto-title and (b) linger as a stale case-D fallback. On the next catalog+ // load the §2.2 merge shows the server title when the host reports one.let title = meta.titleif (localMessages.length === 0 && (resp.oldestTurnNumber ?? resp.turns[0]?.number) === 1) {const firstUserInput = resp.turns.find(t => t.user_input?.trim())?.user_input?.trim() || ''- const hydratedTitle =- firstUserInput.length > 60- ? firstUserInput.substring(0, firstUserInput.lastIndexOf(' ', 60) || 60) + '...'- : firstUserInput+ const hydratedTitle = truncateTitle(firstUserInput)if (hydratedTitle) {- await chatStore.renameChat(agentRef, chatId, hydratedTitle)- if (!stillRelevant()) return staleResult(rendered)title = hydratedTitleapplyLatestTitle(agentRef, chatId, hydratedTitle)}@@ -1559,7 +1560,6 @@ export function useAgentChatController({chatStore.loadMessages,chatStore.createChat,chatStore.replaceMessages,- chatStore.renameChat,applyLatestTitle,upsertHydratedEntry,]@@ -2501,10 +2501,7 @@ export function useAgentChatController({: effectiveReferences.length > 0? `Context: ${effectiveReferences.map(ref => ref.label).join(', ')}`: '')- const autoTitle =- autoTitleSeed.length > 60- ? autoTitleSeed.substring(0, autoTitleSeed.lastIndexOf(' ', 60) || 60) + '...'- : autoTitleSeed+ const autoTitle = truncateTitle(autoTitleSeed)if (autoTitle) {void handleRenameChat(sendChatId, autoTitle)}diff --git a/desktop-app/ui/src/hooks/domain/useChatListController.ts b/desktop-app/ui/src/hooks/domain/useChatListController.tsindex 52e5629e9..6337a57c7 100644--- a/desktop-app/ui/src/hooks/domain/useChatListController.ts+++ b/desktop-app/ui/src/hooks/domain/useChatListController.ts@@ -1,5 +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 { ChatIndex, ChatMetadata, SessionsListResult } from '../../../../src/types'import { scheduleAfterFirstPaint } from '../scheduleAfterFirstPaint'import type { useChatStore } from '../useChatStore'@@ -231,12 +233,35 @@ export function useChatListController({// hydrates them.setChatList(previous => {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'.+ const reconciled = dedupedPrevious.map(chat => {+ const server = serverById.get(chat.id)+ if (!server) return chat+ const { title } = resolveSessionTitle({+ inCache: true,+ localTitle: chat.title,+ serverTitle: server.title,+ pendingRename: 'none',+ placeholder: agentChatPlaceholder(chat.id),+ })+ return title === chat.title ? chat : { ...chat, title }+ })+ // Cases A/B (§2.2): a server-only chat shows the server title when the+ // host reports one, else the "Chat <id>" placeholder.const fromServerOnly: SidebarChatEntry[] = serverSessions.filter(s => !knownIds.has(s.chatId)).map(s => ({id: s.chatId,- title: `Chat ${s.chatId.slice(0, 8)}`,+ title: resolveSessionTitle({+ inCache: false,+ serverTitle: s.title,+ pendingRename: 'none',+ placeholder: agentChatPlaceholder(s.chatId),+ }).title,createdAt: s.lastActivityAt,updatedAt: s.lastActivityAt,// Older hosts omit messageCount. Keep that unknown value at zero@@ -245,7 +270,7 @@ export function useChatListController({messageCount: knownServerMessageCount(s),remote: true,}))- return [...dedupedPrevious, ...fromServerOnly].sort(byUpdatedDesc)+ return [...reconciled, ...fromServerOnly].sort(byUpdatedDesc)})const latestServerSession = serverSessions[0]@@ -342,18 +367,39 @@ export function useChatListController({seedSessionSnapshots(fsm, agentRef, serverSessions)setChatList(previous => {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.+ const reconciled = dedupedPrevious.map(chat => {+ const server = serverById.get(chat.id)+ if (!server) return chat+ const { title } = resolveSessionTitle({+ inCache: true,+ localTitle: chat.title,+ serverTitle: server.title,+ pendingRename: 'none',+ placeholder: agentChatPlaceholder(chat.id),+ })+ return title === chat.title ? chat : { ...chat, title }+ })+ // Cases A/B (§2.2): server-only page entries.const fromServerOnly: SidebarChatEntry[] = serverSessions.filter(s => !knownIds.has(s.chatId)).map(s => ({id: s.chatId,- title: `Chat ${s.chatId.slice(0, 8)}`,+ title: resolveSessionTitle({+ inCache: false,+ serverTitle: s.title,+ pendingRename: 'none',+ placeholder: agentChatPlaceholder(s.chatId),+ }).title,createdAt: s.lastActivityAt,updatedAt: s.lastActivityAt,messageCount: knownServerMessageCount(s),remote: true,}))- return [...dedupedPrevious, ...fromServerOnly].sort(byUpdatedDesc)+ return [...reconciled, ...fromServerOnly].sort(byUpdatedDesc)})try {@@ -716,6 +762,25 @@ export function useChatListController({seedSessionSnapshots(fsm, group.agentRef, group.sessions)}setLatestChatSessions(previous => {+ const serverByKey = new Map<string, SessionsListResult['items'][number]>()+ for (const group of sessionGroups) {+ for (const session of group.sessions) {+ serverByKey.set(`${group.agentRef}:${session.chatId}`, session)+ }+ }+ // Cases C/D (§2.2): server-authoritative title for cached entries.+ const reconciled = previous.map(item => {+ const server = serverByKey.get(`${item.agentRef}:${item.id}`)+ if (!server) return item+ const { title } = resolveSessionTitle({+ inCache: true,+ localTitle: item.title,+ serverTitle: server.title,+ pendingRename: 'none',+ placeholder: remotePlaceholder(item.id),+ })+ return title === item.title ? item : { ...item, title }+ })const knownKeys = new Set(previous.map(item => `${item.agentRef}:${item.id}`))const remoteOnly: LatestSidebarChatEntry[] = []for (const group of sessionGroups) {@@ -723,9 +788,15 @@ export function useChatListController({const key = `${group.agentRef}:${session.chatId}`if (knownKeys.has(key)) continueknownKeys.add(key)+ // Cases A/B (§2.2): server title, else "Remote · <id>" placeholder.remoteOnly.push({id: session.chatId,- title: `Remote · ${session.chatId.slice(0, 8)}`,+ title: resolveSessionTitle({+ inCache: false,+ serverTitle: session.title,+ pendingRename: 'none',+ placeholder: remotePlaceholder(session.chatId),+ }).title,createdAt: session.lastActivityAt,updatedAt: session.lastActivityAt,messageCount: knownServerMessageCount(session),@@ -734,7 +805,7 @@ export function useChatListController({})}}- return [...previous, ...remoteOnly].sort(byUpdatedDesc)+ return [...reconciled, ...remoteOnly].sort(byUpdatedDesc)})} finally {if (!cancelled) {diff --git a/desktop-app/ui/src/lib/__tests__/chatTitle.test.ts b/desktop-app/ui/src/lib/__tests__/chatTitle.test.tsnew file mode 100644index 000000000..cdd152dea--- /dev/null+++ b/desktop-app/ui/src/lib/__tests__/chatTitle.test.ts@@ -0,0 +1,64 @@+import { describe, expect, it } from 'vitest'+import {+ TITLE_ELLIPSIS,+ agentChatPlaceholder,+ remotePlaceholder,+ truncateTitle,+} from '@lib/chatTitle'++describe('truncateTitle (spec 15 §2.4)', () => {+ it('returns the input unchanged when at or under the 60 code-point budget', () => {+ expect(truncateTitle('')).toBe('')+ expect(truncateTitle('short title')).toBe('short title')+ const exactly60 = 'a'.repeat(60)+ expect(truncateTitle(exactly60)).toBe(exactly60)+ })++ it('cuts at the last space at or before the budget and appends the ellipsis', () => {+ const input = `${'a'.repeat(50)} ${'b'.repeat(50)}`+ expect(truncateTitle(input)).toBe(`${'a'.repeat(50)}${TITLE_ELLIPSIS}`)+ })++ // T3 (pr-discipline): documents the §2.4 bug this helper replaces. The old+ // inline version was `substring(0, seed.lastIndexOf(' ', 60) || 60) + '...'`.+ // With no space in the first 60 chars `lastIndexOf` returns -1, which is+ // truthy, so `substring(0, -1)` collapsed to `substring(0, 0)` === '' and the+ // title became just '...'. This assertion FAILS against that buggy logic+ // (which would yield '...'), and passes here.+ it('does NOT degrade to a bare suffix when there is no space in the first 60', () => {+ const input = 'a'.repeat(61)+ const out = truncateTitle(input)+ expect(out).toBe(`${'a'.repeat(60)}${TITLE_ELLIPSIS}`)+ expect(out).not.toBe(TITLE_ELLIPSIS)+ expect(out).not.toBe('...')+ expect(out.startsWith('a'.repeat(60))).toBe(true)+ })++ it('never splits a surrogate pair at the boundary (works on code points)', () => {+ const input = '😀'.repeat(61)+ const out = truncateTitle(input)+ const codePoints = Array.from(out)+ // 60 emoji code points + the ellipsis, no lone surrogate / replacement char.+ expect(codePoints).toHaveLength(61)+ expect(codePoints[59]).toBe('😀')+ expect(codePoints[60]).toBe(TITLE_ELLIPSIS)+ expect(out).not.toContain('�')+ })++ it('cuts hard at 60 code points when the only space is at index 0', () => {+ const input = ` ${'a'.repeat(70)}`+ const out = truncateTitle(input)+ // A leading-space cut would yield an empty prefix; fall back to a hard cut.+ expect(out).toBe(` ${'a'.repeat(59)}${TITLE_ELLIPSIS}`)+ })+})++describe('placeholders (spec 15 §2.2 case B)', () => {+ it('remotePlaceholder uses the first 8 chars of the chat id', () => {+ expect(remotePlaceholder('abcdefgh-1234-5678')).toBe('Remote · abcdefgh')+ })++ it('agentChatPlaceholder uses the first 8 chars of the chat id', () => {+ expect(agentChatPlaceholder('abcdefgh-1234-5678')).toBe('Chat abcdefgh')+ })+})diff --git a/desktop-app/ui/src/lib/__tests__/resolveSessionTitle.test.ts b/desktop-app/ui/src/lib/__tests__/resolveSessionTitle.test.tsnew file mode 100644index 000000000..cfd4407e4--- /dev/null+++ b/desktop-app/ui/src/lib/__tests__/resolveSessionTitle.test.ts@@ -0,0 +1,174 @@+import { describe, expect, it } from 'vitest'+import fc from 'fast-check'+import {+ type PendingRename,+ type ResolveSessionTitleInput,+ resolveSessionTitle,+} from '@lib/resolveSessionTitle'++const PLACEHOLDER = 'Remote · abcdefgh'++describe('resolveSessionTitle — §2.2 decision table (cases A–D)', () => {+ it('case A: server-only + server title -> server (kills the placeholder)', () => {+ expect(+ resolveSessionTitle({+ inCache: false,+ serverTitle: 'Deploy the staging cluster',+ pendingRename: 'none',+ placeholder: PLACEHOLDER,+ })+ ).toEqual({ title: 'Deploy the staging cluster', source: 'server' })+ })++ it('case B: server-only + no server title -> placeholder', () => {+ expect(+ resolveSessionTitle({+ inCache: false,+ pendingRename: 'none',+ placeholder: PLACEHOLDER,+ })+ ).toEqual({ title: PLACEHOLDER, source: 'placeholder' })+ })++ it('case C: cached + server title -> server (A picks up B’s rename)', () => {+ expect(+ resolveSessionTitle({+ inCache: true,+ localTitle: 'old local name',+ serverTitle: 'renamed on device B',+ pendingRename: 'none',+ placeholder: PLACEHOLDER,+ })+ ).toEqual({ title: 'renamed on device B', source: 'server' })+ })++ it('case D: cached + no server title -> local fallback', () => {+ expect(+ resolveSessionTitle({+ inCache: true,+ localTitle: 'my local name',+ pendingRename: 'none',+ placeholder: PLACEHOLDER,+ })+ ).toEqual({ title: 'my local name', source: 'local' })+ })++ it('treats an empty/whitespace-stripped server title as absent (falls to local)', () => {+ expect(+ resolveSessionTitle({+ inCache: true,+ localTitle: 'keep me',+ serverTitle: '',+ pendingRename: 'none',+ placeholder: PLACEHOLDER,+ })+ ).toEqual({ title: 'keep me', source: 'local' })+ })+})++describe('resolveSessionTitle — Fase B branches reachable (cases E/F)', () => {+ it('a pending local rename wins over the server (in-flight / offline)', () => {+ for (const pendingRename of ['in-flight', 'offline'] as PendingRename[]) {+ expect(+ resolveSessionTitle({+ inCache: true,+ localTitle: 'optimistic name',+ serverTitle: 'stale server name',+ pendingRename,+ placeholder: PLACEHOLDER,+ })+ ).toEqual({ title: 'optimistic name', source: 'local' })+ }+ })+})++// ── Property-based (pr-discipline T2) ────────────────────────────────────────++const nonEmpty = fc.string({ minLength: 1 }).filter(s => s.length > 0)++const arbInput: fc.Arbitrary<ResolveSessionTitleInput> = fc.record({+ inCache: fc.boolean(),+ localTitle: fc.option(fc.string(), { nil: undefined }),+ serverTitle: fc.option(fc.string(), { nil: undefined }),+ pendingRename: fc.constantFrom<PendingRename>('none', 'in-flight', 'offline'),+ placeholder: nonEmpty,+})++describe('resolveSessionTitle — properties (T2)', () => {+ it('is deterministic', () => {+ fc.assert(+ fc.property(arbInput, input => {+ expect(resolveSessionTitle(input)).toEqual(resolveSessionTitle(input))+ })+ )+ })++ it('server title (non-empty) + no pending rename => source is server', () => {+ fc.assert(+ fc.property(arbInput, nonEmpty, (input, serverTitle) => {+ const result = resolveSessionTitle({+ ...input,+ serverTitle,+ pendingRename: 'none',+ })+ expect(result).toEqual({ title: serverTitle, source: 'server' })+ })+ )+ })++ it('no server title + a non-empty local cache => never a placeholder (case D)', () => {+ fc.assert(+ fc.property(+ nonEmpty,+ nonEmpty,+ fc.constantFrom<PendingRename>('none', 'offline', 'in-flight'),+ (localTitle, placeholder, pendingRename) => {+ const result = resolveSessionTitle({+ inCache: true,+ localTitle,+ serverTitle: undefined,+ pendingRename,+ placeholder,+ })+ expect(result.source).toBe('local')+ expect(result.title).toBe(localTitle)+ }+ )+ )+ })++ it('server-only + no server title => placeholder (case B)', () => {+ fc.assert(+ fc.property(+ nonEmpty,+ fc.constantFrom<PendingRename>('none', 'offline', 'in-flight'),+ (placeholder, pendingRename) => {+ const result = resolveSessionTitle({+ inCache: false,+ serverTitle: undefined,+ pendingRename,+ placeholder,+ })+ expect(result).toEqual({ title: placeholder, source: 'placeholder' })+ }+ )+ )+ })++ it('is idempotent: feeding the resolved title back as the local cache is stable', () => {+ fc.assert(+ fc.property(arbInput, input => {+ const first = resolveSessionTitle(input)+ // Model the catalog merge applied twice: the resolved chat is now cached+ // with the resolved title, while the server input and the pending state+ // are unchanged. Re-resolving must not drift the shown title.+ const second = resolveSessionTitle({+ ...input,+ inCache: true,+ localTitle: first.title,+ })+ expect(second.title).toBe(first.title)+ })+ )+ })+})diff --git a/desktop-app/ui/src/lib/chatTitle.ts b/desktop-app/ui/src/lib/chatTitle.tsnew file mode 100644index 000000000..8b6d4d406--- /dev/null+++ b/desktop-app/ui/src/lib/chatTitle.ts@@ -0,0 +1,70 @@+/**+ * Session-title presentation helpers (spec 15 §2.4, A20).+ *+ * Centralizes the two things that used to be duplicated/inlined across the chat+ * controllers:+ * - `truncateTitle`: the auto-title truncation, previously copy-pasted in+ * `useAgentChatController` (twice) with a bug (see below);+ * - the sidebar placeholders for a server-only session with no title yet.+ */++/** Auto-title length budget, measured in Unicode code points (not UTF-16 units). */+export const TITLE_MAX_CODE_POINTS = 60++/**+ * Suffix appended to a truncated title. U+2026 (…), a single code point, chosen+ * to match the suffix mcp-host uses for the server-side auto-title so the two+ * derivations don't visibly diverge (spec 15 §2.4).+ */+export const TITLE_ELLIPSIS = '…'++/**+ * Truncate an auto-title seed to `TITLE_MAX_CODE_POINTS`, cutting at the last+ * space at or before the budget so a word isn't sliced mid-token; when there is+ * no such space, cut hard at the budget.+ *+ * Fixes the §2.4 bug in the old inline version+ * (`substring(0, seed.lastIndexOf(' ', 60) || 60) + '...'`): with no space in+ * the first 60 chars `lastIndexOf` returns -1, which is truthy, so+ * `substring(0, -1)` dropped the last char and produced garbage like `"…"`+ * alone. This version never does that.+ *+ * Operates on code points so a surrogate pair (emoji, astral characters) is+ * never split at the boundary.+ */+export function truncateTitle(input: string): string {+ const codePoints = Array.from(input)+ if (codePoints.length <= TITLE_MAX_CODE_POINTS) return input++ // Last space at code-point index <= budget. Index 0 is treated as "no usable+ // space" (a leading-space cut would yield an empty prefix), matching the old+ // `|| 60` fallback.+ let cut = -1+ const scanEnd = Math.min(TITLE_MAX_CODE_POINTS, codePoints.length - 1)+ for (let i = 1; i <= scanEnd; i++) {+ if (codePoints[i] === ' ') cut = i+ }+ const end = cut > 0 ? cut : TITLE_MAX_CODE_POINTS+ return codePoints.slice(0, end).join('') + TITLE_ELLIPSIS+}++/** Short form of a chat id used in placeholders (chat ids are ASCII UUIDs). */+function shortChatId(chatId: string): string {+ return chatId.slice(0, 8)+}++/**+ * Placeholder for a cross-agent ("Latest sessions") server-only session that has+ * no title yet (spec 15 §2.2 case B).+ */+export function remotePlaceholder(chatId: string): string {+ return `Remote · ${shortChatId(chatId)}`+}++/**+ * Placeholder for an agent-scoped server-only session that has no title yet+ * (spec 15 §2.2 case B).+ */+export function agentChatPlaceholder(chatId: string): string {+ return `Chat ${shortChatId(chatId)}`+}diff --git a/desktop-app/ui/src/lib/resolveSessionTitle.ts b/desktop-app/ui/src/lib/resolveSessionTitle.tsnew file mode 100644index 000000000..928fc5225--- /dev/null+++ b/desktop-app/ui/src/lib/resolveSessionTitle.ts@@ -0,0 +1,85 @@+/**+ * Session-title precedence resolver (spec 15 §2.2 — the D3 decision module).+ *+ * Pure function that answers a single question for one session: "which title do+ * I show, and where did it come from?", given the local cache state, the+ * server-reported title, and whether a local rename is pending.+ *+ * The invariant (§2.2): the server wins when it has a title AND there is no+ * pending local rename for that session; a pending local rename wins over the+ * server until it is confirmed or rolled back.+ *+ * Decision table:+ *+ * | Case | inCache | pendingRename | serverTitle | -> source |+ * |------|---------|---------------|-------------|---------------|+ * | A | no | none | present | server |+ * | B | no | none | absent | placeholder |+ * | C | yes | none | present | server |+ * | D | yes | none | absent | local |+ * | E | yes | in-flight | any | local |+ * | F | yes | offline | any | local |+ *+ * PHASE SCOPE: cases A–D are exercised now (Fase A / desktop). Cases E and F+ * (optimistic rename in-flight / offline queue) belong to Fase B: `pendingRename`+ * is part of the signature and the table today, but every caller passes 'none'+ * until Fase B populates the pending-rename queue. The 'in-flight'/'offline'+ * branches already return the local title, which is exactly what Fase B needs —+ * Fase B only has to feed the real pending state; it does not restructure this+ * module.+ */++/**+ * Pending-rename state for a session. 'none' in Fase A; 'in-flight' (optimistic+ * PATCH awaiting confirmation) and 'offline' (queued for reconnect) arrive in+ * Fase B.+ */+export type PendingRename = 'none' | 'in-flight' | 'offline'++export type TitleSource = 'server' | 'local' | 'placeholder'++export interface ResolveSessionTitleInput {+ /** Whether the client has this session in its local chat cache/index. */+ inCache: boolean+ /** The local cache title (only meaningful when `inCache`). */+ localTitle?: string+ /** The sanitized server title, if the host reported one. */+ serverTitle?: string+ /** Local rename state for this session. Always 'none' in Fase A. */+ pendingRename: PendingRename+ /** Placeholder to show for a server-only session with no title (case B). */+ placeholder: string+}++export interface ResolvedSessionTitle {+ title: string+ source: TitleSource+}++function hasText(value: string | undefined): value is string {+ return typeof value === 'string' && value.length > 0+}++export function resolveSessionTitle(input: ResolveSessionTitleInput): ResolvedSessionTitle {+ const hasServer = hasText(input.serverTitle)+ const hasLocal = input.inCache && hasText(input.localTitle)++ // E/F: a pending local rename wins over the server until it is confirmed.+ // (Fase B; in Fase A `pendingRename` is always 'none' so this never fires.)+ if (input.pendingRename !== 'none' && hasLocal) {+ return { title: input.localTitle as string, source: 'local' }+ }++ // A/C: server-authoritative when it has a title and nothing local is pending.+ if (hasServer) {+ return { title: input.serverTitle as string, source: 'server' }+ }++ // D: a cached local name survives as fallback when the server has none.+ if (hasLocal) {+ return { title: input.localTitle as string, source: 'local' }+ }++ // B: server-only session with no title yet.+ return { title: input.placeholder, source: 'placeholder' }+}