Where agent teams gather. Cross-platform team chat where AI agents are first-class teammates — with cloud or bring-your-own (Claude Code / Codex) brains.
TypeScript
fix(ui): one new message must not reload the whole sidebar (#221)
OKNOTOK5ada505632ae
diff --git a/server/src/__integration__/conversations.test.ts b/server/src/__integration__/conversations.test.tsindex b684ccc..7f9de8b 100644--- a/server/src/__integration__/conversations.test.ts+++ b/server/src/__integration__/conversations.test.ts@@ -87,3 +87,120 @@ test('[integration] GET /search uses the same perspective-specific direct title'assert.equal(direct?.title, 'Ada')})++// ── the lastMessage / unreadCount rewrite must be semantics-preserving ──────+//+// Both used to be correlated scalar subqueries, and `unreadCount` nested a+// second one (the conversation_reads lookup) inside its COUNT — so a list of+// N conversations cost 2N+ index probes. They are LATERAL joins now, with+// conversation_reads hoisted to a plain LEFT JOIN (its PK is+// (user_id, conversation_id), so it can still match at most one row). The+// shapes below are the ones where a rewrite like this typically drifts.++interface ConversationRow {+ id: string+ unreadCount: number+ lastMessage: { id: string; kind: string; body: string; email: { subject: string } | null } | null+}++async function listConversations(companyId: string): Promise<ConversationRow[]> {+ const res = await fetch(`${baseUrl}/api/conversations`, {+ headers: { 'x-company-id': companyId },+ })+ assert.equal(res.status, 200)+ return await res.json() as ConversationRow[]+}++test('[integration] lastMessage and unreadCount survive the correlated-subquery rewrite', async () => {+ const companyId = 'c-list-shape'+ await pool.query(+ `INSERT INTO companies (id, name, slug, owner_user_id)+ VALUES ($1, 'List Shape Co', 'list-shape-co', $2)`,+ [companyId, ME_USER_ID],+ )+ await seedUserMembership(ME_USER_ID, companyId, { displayName: 'Me' })+ await seedUserMembership(OTHER_USER_ID, companyId, { displayName: 'Ada' })++ const withMessages = 'g-has-messages'+ const empty = 'g-no-messages'+ const readRoom = 'g-already-read'+ for (const [id, title] of [[withMessages, 'Busy'], [empty, 'Silent'], [readRoom, 'Caught up']]) {+ await pool.query(+ `INSERT INTO conversations (id, kind, title, members, company_id)+ VALUES ($1, 'group', $2, $3::jsonb, $4)`,+ [id, title, JSON.stringify([ME_USER_ID, OTHER_USER_ID]), companyId],+ )+ }+ // Two unread from someone else, plus one of mine — my own messages never+ // count as unread.+ for (const [seq, author] of [[1, OTHER_USER_ID], [2, ME_USER_ID], [3, OTHER_USER_ID]] as const) {+ await pool.query(+ `INSERT INTO messages (id, conversation_id, author_id, kind, body, sequence, company_id)+ VALUES ($1, $2, $3, 'text', $4, $5, $6)`,+ [`m-busy-${seq}`, withMessages, author, `message ${seq}`, seq, companyId],+ )+ }+ await pool.query(+ `INSERT INTO messages (id, conversation_id, author_id, kind, body, sequence, company_id)+ VALUES ($1, $2, $3, 'text', 'old news', 1, $4)`,+ ['m-read-1', readRoom, OTHER_USER_ID, companyId],+ )+ await pool.query(+ `INSERT INTO conversation_reads (user_id, conversation_id, last_read_at)+ VALUES ($1, $2, NOW())`,+ [ME_USER_ID, readRoom],+ )++ const rows = await listConversations(companyId)+ const byId = new Map(rows.map((r) => [r.id, r]))++ const busy = byId.get(withMessages)+ assert.equal(busy?.unreadCount, 2, 'own messages must not count as unread')+ assert.equal(busy?.lastMessage?.id, 'm-busy-3', 'lastMessage is the highest sequence, not the newest row inserted')++ const silent = byId.get(empty)+ assert.equal(silent?.lastMessage, null, 'a conversation with no messages must return null, not an empty object')+ assert.equal(silent?.unreadCount, 0)++ // The read cursor is now a hoisted LEFT JOIN rather than a nested scalar —+ // this is the row that proves it is still applied per conversation.+ assert.equal(byId.get(readRoom)?.unreadCount, 0)+ assert.equal(byId.get(readRoom)?.lastMessage?.id, 'm-read-1')++ // Exactly one row per conversation: a join that fanned out would duplicate.+ assert.equal(rows.length, new Set(rows.map((r) => r.id)).size)+})++test('[integration] an email lastMessage still carries its envelope', async () => {+ const companyId = 'c-list-email'+ const conversationId = 'g-email-thread'+ await pool.query(+ `INSERT INTO companies (id, name, slug, owner_user_id)+ VALUES ($1, 'List Email Co', 'list-email-co', $2)`,+ [companyId, ME_USER_ID],+ )+ await seedUserMembership(ME_USER_ID, companyId, { displayName: 'Me' })+ await pool.query(+ `INSERT INTO conversations (id, kind, title, members, company_id)+ VALUES ($1, 'group', 'Contracts', $2::jsonb, $3)`,+ [conversationId, JSON.stringify([ME_USER_ID]), companyId],+ )+ await pool.query(+ `INSERT INTO messages (id, conversation_id, author_id, kind, body, sequence, company_id)+ VALUES ($1, $2, $3, 'email', 'body text', 1, $4)`,+ ['m-email-1', conversationId, ME_USER_ID, companyId],+ )+ await pool.query(+ `INSERT INTO email_messages+ (message_id, conversation_id, company_id, direction, transport_status,+ subject, from_addr, to_addrs)+ VALUES ($1, $2, $3, 'in', 'received', 'Re: contract draft', '[email protected]', $4::jsonb)`,+ ['m-email-1', conversationId, companyId, JSON.stringify(['[email protected]'])],+ )++ const rows = await listConversations(companyId)+ const thread = rows.find((r) => r.id === conversationId)+ // The envelope is a subquery nested inside the lateral now; the sidebar+ // renders "↓ Re: contract draft" from it instead of a raw body excerpt.+ assert.equal(thread?.lastMessage?.email?.subject, 'Re: contract draft')+})diff --git a/server/src/api/router.ts b/server/src/api/router.tsindex 870924c..c32b521 100644--- a/server/src/api/router.ts+++ b/server/src/api/router.ts@@ -3258,6 +3258,18 @@ api.post('/agents/:id/rehire', async (req, res) => {res.json({ ok: true })})+/**+ * Ceiling on one sidebar page.+ *+ * The route has no cursor, so this is a backstop rather than pagination: it+ * bounds the pathological workspace the performance review described (10,000+ * conversations returned in one response) without changing the contract for+ * the real ones, which are nowhere near it. If a workspace ever trips the log+ * line below, that is the signal that real cursor paging has become worth its+ * cost across the ~80 call sites that read this list.+ */+const CONVERSATION_LIST_LIMIT = 500+api.get('/conversations', async (req, res) => {const { userId: me, companyId: tenant } = await requireCompany(req)const { rows } = await pool.query(@@ -3274,47 +3286,15 @@ api.get('/conversations', async (req, res) => {-- "until tomorrow" silence wears off without needing a sweeper job.(mu.user_id IS NOT NULL AND (mu.muted_until IS NULL OR mu.muted_until > NOW())) AS muted,mu.muted_until AS "mutedUntil",- (- SELECT json_build_object(- 'id', m.id,- 'authorId', m.author_id,- 'kind', m.kind,- 'body', m.body,- 'tool', m.tool,- 'attachment', m.attachment,- 'createdAt', m.created_at,- -- For email messages, surface the subject + direction so the- -- sidebar preview can show "Re: contract draft" instead of a- -- raw body excerpt. NULL for non-email messages — the client- -- branches on last.kind === 'email'.- 'email', (- SELECT jsonb_build_object(- 'subject', em.subject,- 'direction', em.direction,- 'from', em.from_addr- )- FROM email_messages em- WHERE em.message_id = m.id- )- )- FROM messages m- WHERE m.conversation_id = c.id- ORDER BY m.sequence DESC- LIMIT 1- ) AS "lastMessage",- COALESCE((- SELECT COUNT(*)::int- FROM messages m- WHERE m.conversation_id = c.id- AND m.author_id <> $1- AND m.created_at > COALESCE(- (SELECT last_read_at FROM conversation_reads WHERE user_id = $1 AND conversation_id = c.id),- '1970-01-01T00:00:00Z'::timestamptz- )- ), 0) AS "unreadCount"+ last_message.payload AS "lastMessage",+ COALESCE(unread.n, 0) AS "unreadCount"FROM conversations cLEFT JOIN projects p ON p.id = c.project_idLEFT JOIN conversation_mutes mu ON mu.conversation_id = c.id AND mu.user_id = $1+ -- Hoisted out of the unread subquery. As a correlated scalar it was+ -- probed once per conversation, nested inside a COUNT that was itself+ -- probed once per conversation.+ LEFT JOIN conversation_reads cr ON cr.user_id = $1 AND cr.conversation_id = c.idLEFT JOIN LATERAL (SELECT p_other.nameFROM conversation_members member@@ -3327,6 +3307,41 @@ api.get('/conversations', async (req, res) => {ORDER BY member.ordinalLIMIT 1) other_participant ON c.kind = 'direct'+ LEFT JOIN LATERAL (+ SELECT json_build_object(+ 'id', m.id,+ 'authorId', m.author_id,+ 'kind', m.kind,+ 'body', m.body,+ 'tool', m.tool,+ 'attachment', m.attachment,+ 'createdAt', m.created_at,+ -- For email messages, surface the subject + direction so the+ -- sidebar preview can show "Re: contract draft" instead of a+ -- raw body excerpt. NULL for non-email messages — the client+ -- branches on last.kind === 'email'.+ 'email', (+ SELECT jsonb_build_object(+ 'subject', em.subject,+ 'direction', em.direction,+ 'from', em.from_addr+ )+ FROM email_messages em+ WHERE em.message_id = m.id+ )+ ) AS payload+ FROM messages m+ WHERE m.conversation_id = c.id+ ORDER BY m.sequence DESC+ LIMIT 1+ ) last_message ON true+ LEFT JOIN LATERAL (+ SELECT COUNT(*)::int AS n+ FROM messages m+ WHERE m.conversation_id = c.id+ AND m.author_id <> $1+ AND m.created_at > COALESCE(cr.last_read_at, '1970-01-01T00:00:00Z'::timestamptz)+ ) unread ON trueWHERE c.company_id = $2-- Only conversations the caller is actually in. Without this,-- agent-to-agent direct chats (members=[agentA, agentB]) leak@@ -3339,9 +3354,13 @@ api.get('/conversations', async (req, res) => {AND cm.company_id = c.company_idAND cm.participant_id = $1)- ORDER BY c.pinned DESC, c.updated_at DESC`,+ ORDER BY c.pinned DESC, c.updated_at DESC+ LIMIT ${CONVERSATION_LIST_LIMIT}`,[me, tenant],)+ if (rows.length === CONVERSATION_LIST_LIMIT) {+ console.warn(`[conversations] ${tenant} hit the ${CONVERSATION_LIST_LIMIT}-row sidebar ceiling; older rows are being withheld`)+ }res.json(rows)})diff --git a/src/App.tsx b/src/App.tsxindex 179fd9e..ecd920a 100644--- a/src/App.tsx+++ b/src/App.tsx@@ -135,10 +135,11 @@ function AuthedApp() {useEffect(() => {if (!convoId || !selectedConvoExists) returnvoid useMessages.getState().loadConversation(convoId)- void api.markRead(convoId).then(() => {- // refresh list so the badge clears- void useConversations.getState().reload()- }).catch(() => { /* swallow */ })+ // Clear the badge locally, then persist. The server response tells us+ // nothing the client doesn't already know, so refetching the whole list+ // to learn that one count went to zero is pure waste.+ useConversations.getState().markLocallyRead(convoId)+ void api.markRead(convoId).catch(() => { /* swallow */ })}, [convoId, selectedConvoExists])// Lazy-refresh whisper list when entering whispers viewdiff --git a/src/lib/conversationRow.ts b/src/lib/conversationRow.tsnew file mode 100644index 0000000..4d61be4--- /dev/null+++ b/src/lib/conversationRow.ts@@ -0,0 +1,58 @@+import type { ApiConversation, ApiMessage } from '@/api/client'+import type { Conversation } from '@/types'++/**+ * Pure helpers shared by the two paths that produce a sidebar row: the+ * `GET /conversations` fetch and the in-place patch a `message.new` WS event+ * performs.+ *+ * They live here rather than in the store because the equivalence between+ * those two paths is the whole point — a new message repaints one row instead+ * of refetching the list, which is only safe if the patch lands the row in the+ * exact state a refetch would have.+ */++/** Sidebar timestamp: clock for today, "Yest", then M/D. */+export function timeFromIso(iso?: string): string {+ if (!iso) return ''+ const d = new Date(iso)+ const now = new Date()+ if (d.toDateString() === now.toDateString()) {+ const h = String(d.getHours()).padStart(2, '0')+ const m = String(d.getMinutes()).padStart(2, '0')+ return `${h}:${m}`+ }+ if ((now.getTime() - d.getTime()) < 86400e3 * 2) return 'Yest'+ return `${d.getMonth() + 1}/${d.getDate()}`+}++/**+ * Narrow a WS `message.new` payload to the last-message shape the row renderer+ * reads. The two differ only in the timestamp field name and in the email+ * envelope, which the event carries in full — everything the preview needs is+ * already on the wire, which is why the patch does not need a refetch.+ */+export function lastMessageFromWs(m: ApiMessage): NonNullable<ApiConversation['lastMessage']> {+ return {+ id: m.id,+ authorId: m.authorId,+ kind: m.kind,+ body: m.body,+ tool: m.tool,+ attachment: m.attachment,+ createdAt: m.createdAt ?? m.at,+ email: m.email+ ? { subject: m.email.subject, direction: m.email.direction, from: m.email.from }+ : null,+ }+}++/**+ * Sidebar order, mirroring the server's `ORDER BY c.pinned DESC,+ * c.updated_at DESC`. Applied after a patch so a freshly-active row rises to+ * where a refetch would have put it.+ */+export function bySidebarOrder(a: Conversation, b: Conversation): number {+ if (a.pinned !== b.pinned) return a.pinned ? -1 : 1+ return (b.lastAtIso ?? '').localeCompare(a.lastAtIso ?? '')+}diff --git a/src/stores/conversations.ts b/src/stores/conversations.tsindex 8aa3fb9..db911c8 100644--- a/src/stores/conversations.ts+++ b/src/stores/conversations.ts@@ -1,6 +1,7 @@import { create } from 'zustand'-import { api, ws, type ApiConversation } from '@/api/client'+import { api, ws, type ApiConversation, type ApiMessage } from '@/api/client'import type { Conversation } from '@/types'+import { bySidebarOrder, lastMessageFromWs, timeFromIso } from '@/lib/conversationRow'import { useApp } from '@/stores/app'import { commitIfContextCurrent, useAuth } from '@/stores/auth'import { useMessages } from '@/stores/messages'@@ -11,19 +12,23 @@ interface ConversationsState {loaded: booleanload: () => Promise<void>reload: () => Promise<void>-}--function timeFromIso(iso?: string): string {- if (!iso) return ''- const d = new Date(iso)- const now = new Date()- if (d.toDateString() === now.toDateString()) {- const h = String(d.getHours()).padStart(2, '0')- const m = String(d.getMinutes()).padStart(2, '0')- return `${h}:${m}`- }- if ((now.getTime() - d.getTime()) < 86400e3 * 2) return 'Yest'- return `${d.getMonth() + 1}/${d.getDate()}`+ /**+ * Repaint one sidebar row from a `message.new` event.+ *+ * Every new message used to trigger a full `reload()` — a fresh+ * `GET /conversations` per online client per message, each one recomputing+ * the last message and unread count for every conversation in the+ * workspace. The event already carries the message, so the row can be+ * patched in place. Returns false when the conversation isn't in the list+ * yet and a fetch was issued instead.+ */+ applyIncomingMessage: (+ conversationId: string,+ message: ApiMessage,+ opts: { read: boolean },+ ) => boolean+ /** Clear a row's badge without waiting for the server round trip. */+ markLocallyRead: (conversationId: string) => void}/** Render a system-row JSON payload as a human-readable preview line.@@ -61,69 +66,84 @@ function renderSystemPreview(}}-function fromApi(c: ApiConversation): Conversation {- const last = c.lastMessage+/**+ * Render a conversation row's preview line from its last message.+ *+ * Shared by the list fetch and the WS patch below, which is the point: a+ * `message.new` event carries everything this needs, so a new message can+ * repaint one row without refetching the list — but only if both paths agree+ * on how a preview is spelled. Two encoders would drift the moment either+ * grows a case.+ */+function previewOf(last: ApiConversation['lastMessage']): string {// Empty string when there's no message yet — the row renderer skips the// preview line entirely so an empty conversation doesn't show a stray "—".- let preview = ''- if (last) {- // Resolve the author's DISPLAY NAME from the participants store. If the- // participant isn't loaded yet, omit the author prefix entirely — never- // fall back to the raw id (which may carry a server-side collision- // suffix like `iris-a0ab` that we shouldn't be exposing to UI).- const meId = useAuth.getState().user?.id- const byId = useParticipants.getState().byId- const resolveName = (id: string): string | null => {- if (id === meId) return 'You'- return byId[id]?.name ?? null- }- const authorName = resolveName(last.authorId)- // Rewrite raw `@<id>` mention tokens to `@<DisplayName>` so previews- // don't leak participant ids like `@u-27c9522d-3b7`. Mirror the regex- // used by parseBody() so we tokenize exactly what the chat renderer- // treats as a mention. `@all` is preserved as-is.- const humanizeMentions = (s: string): string =>- s.replace(/@[A-Za-z][\w-]*/g, (m) => {- const id = m.slice(1)- if (id === 'all') return m- const name = resolveName(id)- return name ? `@${name}` : m- })- const trimmedBody = humanizeMentions(last.body?.trim() ?? '')- if (last.kind === 'tool' && last.tool) {- const t = last.tool as { name?: string; arg?: string }- preview = authorName- ? `${authorName}: used ${t.name ?? 'tool'}`- : `used ${t.name ?? 'tool'}`- } else if (last.kind === 'email' && last.email) {- // Subject leads — that's how mailbox apps preview a thread. Body- // excerpt follows in muted text only when there's room.- const arrow = last.email.direction === 'in' ? '↓' : '↑'- const subject = last.email.subject || '(no subject)'- const snippet = trimmedBody ? ` — ${trimmedBody.slice(0, 60)}` : ''- preview = `${arrow} ${subject}${snippet}`- } else if (last.kind === 'system') {- // System rows ship as JSON bodies — translate to a short- // human-readable line ("Bram joined the group" / "Scout removed- // Iris") instead of leaking raw `{"kind":"left",...}` payloads.- preview = renderSystemPreview(last.body, resolveName) ?? '(system)'- } else if (last.attachment) {- // Attachment messages (user uploads) — the row stores attachment- // metadata in a separate jsonb column and `body` carries only the- // optional caption. Prefix with a 📎 + filename so the row reads- // as "shared a file" instead of going blank when the user uploads- // without a caption.- const a = last.attachment- const verb = a.kind === 'img' ? '📷' : '📎'- const filename = a.name ?? (a.kind === 'img' ? 'image' : 'file')- const label = trimmedBody- ? `${verb} ${filename} — ${trimmedBody.slice(0, 80)}`- : `${verb} ${filename}`- preview = authorName ? `${authorName}: ${label}` : label- } else if (trimmedBody) {- preview = authorName ? `${authorName}: ${trimmedBody.slice(0, 100)}` : trimmedBody.slice(0, 100)- }+ if (!last) return ''+ // Resolve the author's DISPLAY NAME from the participants store. If the+ // participant isn't loaded yet, omit the author prefix entirely — never+ // fall back to the raw id (which may carry a server-side collision+ // suffix like `iris-a0ab` that we shouldn't be exposing to UI).+ const meId = useAuth.getState().user?.id+ const byId = useParticipants.getState().byId+ const resolveName = (id: string): string | null => {+ if (id === meId) return 'You'+ return byId[id]?.name ?? null+ }+ const authorName = resolveName(last.authorId)+ // Rewrite raw `@<id>` mention tokens to `@<DisplayName>` so previews+ // don't leak participant ids like `@u-27c9522d-3b7`. Mirror the regex+ // used by parseBody() so we tokenize exactly what the chat renderer+ // treats as a mention. `@all` is preserved as-is.+ const humanizeMentions = (s: string): string =>+ s.replace(/@[A-Za-z][\w-]*/g, (m) => {+ const id = m.slice(1)+ if (id === 'all') return m+ const name = resolveName(id)+ return name ? `@${name}` : m+ })+ const trimmedBody = humanizeMentions(last.body?.trim() ?? '')+ if (last.kind === 'tool' && last.tool) {+ const t = last.tool as { name?: string; arg?: string }+ return authorName+ ? `${authorName}: used ${t.name ?? 'tool'}`+ : `used ${t.name ?? 'tool'}`+ }+ if (last.kind === 'email' && last.email) {+ // Subject leads — that's how mailbox apps preview a thread. Body+ // excerpt follows in muted text only when there's room.+ const arrow = last.email.direction === 'in' ? '↓' : '↑'+ const subject = last.email.subject || '(no subject)'+ const snippet = trimmedBody ? ` — ${trimmedBody.slice(0, 60)}` : ''+ return `${arrow} ${subject}${snippet}`+ }+ if (last.kind === 'system') {+ // System rows ship as JSON bodies — translate to a short+ // human-readable line ("Bram joined the group" / "Scout removed+ // Iris") instead of leaking raw `{"kind":"left",...}` payloads.+ return renderSystemPreview(last.body, resolveName) ?? '(system)'+ }+ if (last.attachment) {+ // Attachment messages (user uploads) — the row stores attachment+ // metadata in a separate jsonb column and `body` carries only the+ // optional caption. Prefix with a 📎 + filename so the row reads+ // as "shared a file" instead of going blank when the user uploads+ // without a caption.+ const a = last.attachment+ const verb = a.kind === 'img' ? '📷' : '📎'+ const filename = a.name ?? (a.kind === 'img' ? 'image' : 'file')+ const label = trimmedBody+ ? `${verb} ${filename} — ${trimmedBody.slice(0, 80)}`+ : `${verb} ${filename}`+ return authorName ? `${authorName}: ${label}` : label}+ if (trimmedBody) {+ return authorName ? `${authorName}: ${trimmedBody.slice(0, 100)}` : trimmedBody.slice(0, 100)+ }+ return ''+}++function fromApi(c: ApiConversation): Conversation {+ const last = c.lastMessagereturn {id: c.id,kind: c.kind,@@ -138,7 +158,7 @@ function fromApi(c: ApiConversation): Conversation {lastMessageId: last?.id ?? null,lastAt: timeFromIso(last?.createdAt ?? c.updatedAt),lastAtIso: last?.createdAt ?? c.updatedAt,- preview,+ preview: previewOf(last),tag: (c.tag ?? undefined) as Conversation['tag'],pulledBy: c.pulledBy ?? undefined,projectId: c.projectId,@@ -177,7 +197,7 @@ export function isMuted(c: Pick<Conversation, 'muted' | 'mutedUntil'>): booleanreturn new Date(c.mutedUntil).getTime() > Date.now()}-export const useConversations = create<ConversationsState>((set) => ({+export const useConversations = create<ConversationsState>((set, get) => ({list: [],loaded: false,async load() {@@ -205,6 +225,41 @@ export const useConversations = create<ConversationsState>((set) => ({console.warn('[conversations] reload failed', err)}},+ applyIncomingMessage(conversationId, message, opts) {+ const existing = get().list.find((c) => c.id === conversationId)+ // A conversation we've never seen — a group just created, or one we were+ // added to. There is no row to patch, so fall back to a fetch.+ if (!existing) { void get().reload(); return false }++ const last = lastMessageFromWs(message)+ // The server counts unread as `author_id <> me AND created_at > last_read`.+ // Mirror the author half here: a message this user sent from the CLI or+ // another device echoes back over WS, and counting it would show a badge+ // that the next reconcile silently takes away again.+ const mine = message.authorId === useAuth.getState().user?.id+ const unread = opts.read+ ? undefined // the user is looking at it+ : mine+ ? existing.unread // own message: no change+ : (existing.unread ?? 0) + 1+ const next: Conversation = {+ ...existing,+ lastMessageId: last.id,+ lastAt: timeFromIso(last.createdAt),+ lastAtIso: last.createdAt,+ preview: previewOf(last),+ unread,+ }+ const list = get().list.map((c) => (c.id === conversationId ? next : c)).sort(bySidebarOrder)+ set({ list })+ refreshActiveMessagesIfSidebarMoved(list)+ return true+ },+ markLocallyRead(conversationId) {+ set((s) => ({+ list: s.list.map((c) => (c.id === conversationId ? { ...c, unread: undefined } : c)),+ }))+ },}))// WS bindings are attached once for the page lifetime; data reload runs@@ -226,17 +281,27 @@ export function bootConversations() {void useConversations.getState().reload()return}- if (e.type === 'message.new' || e.type === 'group.pulled') {- // If a new message arrives for the conversation the user is currently- // viewing, treat it as already-seen — mark read on the server BEFORE we- // reload, so the badge never blinks up to 1 just to drop back to 0.+ if (e.type === 'message.new') {+ // Patch the one row this message touched. The event carries the whole+ // message, so a refetch would only re-derive what we already have —+ // for every conversation in the workspace, on every online client.const active = useApp.getState().selectedConversationId- if (e.type === 'message.new' && e.conversationId === active) {- void api.markRead(e.conversationId).then(() => useConversations.getState().reload())- return+ const isActive = e.conversationId === active+ useConversations.getState().applyIncomingMessage(e.conversationId, e.message, { read: isActive })+ // Still tell the server the user has seen it, so the badge stays gone+ // across reloads and other devices. Local state is already correct, so+ // this no longer needs to be awaited before repainting.+ if (isActive) {+ void api.markRead(e.conversationId).catch(() => { /* retried on next view */ })}+ return+ }+ if (e.type === 'group.pulled') {+ // A group that did not exist a moment ago — there is no row to patch.void useConversations.getState().reload()- } else if (e.type === 'conversation.updated') {+ return+ }+ if (e.type === 'conversation.updated') {// Surgical patch — apply patch fields to the matching conversation in// place without a full network reload.useConversations.setState((s) => ({diff --git a/tests/conversation-row.test.ts b/tests/conversation-row.test.tsnew file mode 100644index 0000000..dd00c8c--- /dev/null+++ b/tests/conversation-row.test.ts@@ -0,0 +1,134 @@+/**+ * A `message.new` event must land a sidebar row exactly where a refetch would.+ *+ * Every new message used to trigger a full `GET /conversations` — per online+ * client, per message, each one recomputing the last message and unread count+ * for every conversation in the workspace. The event already carries the+ * message, so the row is now patched in place. That is only safe if the patch+ * and the fetch agree, and these are the two places where they could drift:+ * the shape the WS payload is narrowed to, and the order the row lands in.+ */+import assert from 'node:assert/strict'+import { describe, it } from 'node:test'+import type { ApiMessage } from '../src/api/client'+import type { Conversation } from '../src/types'+import { bySidebarOrder, lastMessageFromWs, timeFromIso } from '../src/lib/conversationRow'++function wsMessage(over: Partial<ApiMessage> = {}): ApiMessage {+ return {+ id: 'm-1',+ conversationId: 'g-1',+ authorId: 'u-ada',+ kind: 'text',+ body: 'hello',+ at: '2026-03-01T10:00:00.000Z',+ sequence: 7,+ ...over,+ } as ApiMessage+}++function row(over: Partial<Conversation> = {}): Conversation {+ return {+ id: 'g-1',+ kind: 'group',+ title: 'Room',+ topic: null,+ members: [],+ pinned: false,+ muted: false,+ mutedUntil: null,+ lastMessageId: null,+ lastAt: '',+ lastAtIso: '2026-03-01T09:00:00.000Z',+ preview: '',+ projectId: null,+ projectName: null,+ projectColor: null,+ ...over,+ } as Conversation+}++describe('WS payload → last-message shape', () => {+ it('renames the timestamp field the server spells differently', () => {+ // The WS event says `at`; `GET /conversations` says `createdAt`. Getting+ // this wrong leaves every patched row stamped with the epoch.+ const last = lastMessageFromWs(wsMessage())+ assert.equal(last.createdAt, '2026-03-01T10:00:00.000Z')+ })++ it('prefers an explicit createdAt when the payload carries both', () => {+ const last = lastMessageFromWs(wsMessage({ createdAt: '2026-03-01T11:00:00.000Z' }))+ assert.equal(last.createdAt, '2026-03-01T11:00:00.000Z')+ })++ it('carries the email envelope through, so the preview reads as a subject', () => {+ const last = lastMessageFromWs(wsMessage({+ kind: 'email',+ email: {+ subject: 'Re: contract draft',+ direction: 'in',+ from: '[email protected]',+ to: [],+ cc: [],+ transportStatus: 'received',+ },+ } as Partial<ApiMessage>))+ assert.deepEqual(last.email, {+ subject: 'Re: contract draft',+ direction: 'in',+ from: '[email protected]',+ })+ })++ it('null, not undefined, when the message is not an email', () => {+ // The row renderer branches on `last.email` being present; the fetch path+ // produces SQL NULL here, so the patch must not produce `undefined`.+ assert.equal(lastMessageFromWs(wsMessage()).email, null)+ })++ it('keeps the attachment descriptor the preview renders a 📎 from', () => {+ const attachment = { name: 'contract.pdf', kind: 'pdf' as const }+ assert.deepEqual(lastMessageFromWs(wsMessage({ attachment })).attachment, attachment)+ })+})++describe('sidebar order after a patch', () => {+ it('floats the most recent conversation to the top', () => {+ const older = row({ id: 'g-old', lastAtIso: '2026-03-01T09:00:00.000Z' })+ const newer = row({ id: 'g-new', lastAtIso: '2026-03-01T10:00:00.000Z' })+ assert.deepEqual([older, newer].sort(bySidebarOrder).map((c) => c.id), ['g-new', 'g-old'])+ })++ it('keeps pinned rows above unpinned ones however recent they are', () => {+ // Mirrors the server's `ORDER BY c.pinned DESC, c.updated_at DESC` — a+ // patch that sorted by time alone would reshuffle the list on every+ // message and disagree with the next reconnect reload.+ const pinnedStale = row({ id: 'g-pin', pinned: true, lastAtIso: '2026-01-01T00:00:00.000Z' })+ const freshUnpinned = row({ id: 'g-fresh', lastAtIso: '2026-03-01T10:00:00.000Z' })+ assert.deepEqual(+ [freshUnpinned, pinnedStale].sort(bySidebarOrder).map((c) => c.id),+ ['g-pin', 'g-fresh'],+ )+ })++ it('does not throw on a row that has never had a message', () => {+ const empty = row({ id: 'g-empty', lastAtIso: undefined })+ const withMessage = row({ id: 'g-msg', lastAtIso: '2026-03-01T10:00:00.000Z' })+ assert.deepEqual([empty, withMessage].sort(bySidebarOrder).map((c) => c.id), ['g-msg', 'g-empty'])+ })+})++describe('sidebar timestamp', () => {+ it('is empty for a row with no timestamp at all', () => {+ assert.equal(timeFromIso(undefined), '')+ })++ it('shows a clock for today and a date for last week', () => {+ const today = new Date()+ today.setHours(14, 5, 0, 0)+ assert.equal(timeFromIso(today.toISOString()), '14:05')++ const lastWeek = new Date(today.getTime() - 7 * 86400e3)+ assert.equal(timeFromIso(lastWeek.toISOString()), `${lastWeek.getMonth() + 1}/${lastWeek.getDate()}`)+ })+})