Skip to content

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(threads): the person who writes a reply can open the thread they started (#261)

Xialie Zhuang532420c48cd7
diff --git a/src/lib/replyCount.ts b/src/lib/replyCount.ts
new file mode 100644
index 0000000..736eb1a
--- /dev/null
+++ b/src/lib/replyCount.ts
@@ -0,0 +1,31 @@
+/**
+ * The "N replies" link under a message is driven by `replyCount`, and it is the
+ * only way into the thread drawer — `Message.tsx` gates the app's single
+ * `openThreadView` call site on `(msg.replyCount ?? 0) > 0`. So a root whose
+ * count is one short does not merely display a wrong number: at zero it hides
+ * the entrance entirely, and the person who wrote the reply cannot open the
+ * thread they just started.
+ *
+ * The count is maintained locally because the server does not publish a new one
+ * with the reply. That means every path that adds or removes a reply from the
+ * local list has to move it by exactly one — which is what this helper is for.
+ */
+import type { Message } from '@/types'
+
+/** Shift a quoted root's local reply count. No-op when the root is not in the
+ * loaded page (an old message the user has not scrolled back to) or when the
+ * message being counted is not a reply at all. Never goes below zero. */
+export function applyReplyCountDelta(
+ list: Message[],
+ rootId: string | null | undefined,
+ delta: number,
+): Message[] {
+ if (!rootId || delta === 0) return list
+ let hit = false
+ const next = list.map((m) => {
+ if (m.id !== rootId) return m
+ hit = true
+ return { ...m, replyCount: Math.max(0, (m.replyCount ?? 0) + delta) }
+ })
+ return hit ? next : list
+}
diff --git a/src/stores/messages.ts b/src/stores/messages.ts
index 5807207..ff50ee6 100644
--- a/src/stores/messages.ts
+++ b/src/stores/messages.ts
@@ -1,5 +1,6 @@
import { create } from 'zustand'
import type { Message, ReactionEntry } from '@/types'
+import { applyReplyCountDelta } from '@/lib/replyCount'
import { api, ApiError, ws, type WsEvent, type ApiMessage } from '@/api/client'
import { useApp } from '@/stores/app'
import { getMeId } from '@/stores/auth'
@@ -505,17 +506,18 @@ export const useMessages = create<MessagesState>((set, get) => ({
const sb = (b as { sequence?: number }).sequence ?? 0
return sa - sb
})
- // Live replyCount bump on the quoted-original. Server doesn't publish
- // the new count separately; without this the "N replies" link on the
- // root would only catch up on a full refetch. Only bump for fresh
- // arrivals (`prior` was absent) so a server-echo of an optimistic
- // bubble doesn't double-count.
- if (!prior && m.quotedMessageId) {
- const rootId = m.quotedMessageId
- next = next.map((x) =>
- x.id === rootId ? { ...x, replyCount: (x.replyCount ?? 0) + 1 } : x,
- )
- }
+ // Live replyCount bump on the quoted-original. The server doesn't
+ // publish the new count separately; without this the "N replies" link
+ // on the root would only catch up on a full refetch.
+ //
+ // Only for FRESH arrivals. A `prior` match means this is the server
+ // echo of our own optimistic bubble, and `sendUserMessage` already
+ // counted it at insert time — which it has to, because the author's
+ // echo ALWAYS matches `prior` (by real id once the POST resolves, or
+ // by clientId when the echo wins the race). Counting only here left
+ // the author's own root one short forever, and at zero that hides the
+ // only entrance to the thread they had just created.
+ if (!prior) next = applyReplyCountDelta(next, m.quotedMessageId, 1)
const { [m.id]: _drop, ...rest } = s.streaming
return {
streaming: rest,
@@ -690,10 +692,19 @@ export async function sendUserMessage(
// shouldn't shove our bubble up the timeline.
;(optimistic as Message & { sequence?: number }).sequence = Number.MAX_SAFE_INTEGER
+ // Count the reply against its root now, next to the bubble it belongs to.
+ // The author never gets a second chance: their server echo is always matched
+ // as a `prior` in applyEvent, so the bump there is skipped for them.
+ // `discardFailedMessage` takes it back if this send is thrown away, which is
+ // also what keeps a retry (discard, then send again) balanced at +1.
useMessages.setState((s) => ({
byConvo: {
...s.byConvo,
- [convoId]: [...(s.byConvo[convoId] ?? []), optimistic],
+ [convoId]: applyReplyCountDelta(
+ [...(s.byConvo[convoId] ?? []), optimistic],
+ quotedMessageId,
+ 1,
+ ),
},
}))
@@ -740,8 +751,15 @@ export function discardFailedMessage(convoId: string, tempId: string): void {
useMessages.setState((s) => {
const list = s.byConvo[convoId]
if (!list) return s
- const next = list.filter((m) => m.id !== tempId)
- if (next.length === list.length) return s
+ const dropped = list.find((m) => m.id === tempId)
+ if (!dropped) return s
+ // Hand back the count this reply took on insert, or the root keeps a
+ // phantom reply for the rest of the session.
+ const next = applyReplyCountDelta(
+ list.filter((m) => m.id !== tempId),
+ dropped.quotedMessageId,
+ -1,
+ )
return { byConvo: { ...s.byConvo, [convoId]: next } }
})
}
diff --git a/tests/reply-count.test.ts b/tests/reply-count.test.ts
new file mode 100644
index 0000000..6dfb623
--- /dev/null
+++ b/tests/reply-count.test.ts
@@ -0,0 +1,123 @@
+/**
+ * A reply has to move its root's count by exactly one, on every client.
+ *
+ * `applyEvent` bumped the quoted root only for arrivals with no local
+ * counterpart (`!prior`). That is never true on the client that WROTE the
+ * reply: its own server echo always matches the optimistic bubble — by real id
+ * once the POST resolves, or by clientId when the echo wins the race — and
+ * `sendUserMessage` never counted it at insert time either. So the author's
+ * copy of the root stayed one short, permanently: `loadConversation` bails on
+ * `loaded.has(id)`, so leaving and re-entering the conversation does not
+ * refetch, and only a full reload repaired it.
+ *
+ * At zero that is not a wrong number, it is a missing door. `Message.tsx` gates
+ * the app's ONLY `openThreadView` call site on `(msg.replyCount ?? 0) > 0`, so
+ * the person who wrote a thread's first reply could not open the thread they
+ * had just created. Their teammates could.
+ */
+import assert from 'node:assert/strict'
+import { readFile } from 'node:fs/promises'
+import { describe, it } from 'node:test'
+import type { Message } from '../src/types'
+import { applyReplyCountDelta } from '../src/lib/replyCount'
+
+function msg(over: Partial<Message> = {}): Message {
+ return {
+ id: 'm-root',
+ conversationId: 'g-1',
+ authorId: 'u-iris',
+ kind: 'text',
+ body: 'ship it?',
+ at: '2026-03-01T10:00:00.000Z',
+ ...over,
+ } as Message
+}
+
+describe('applyReplyCountDelta', () => {
+ it('takes a root from no-replies to one reply — the case that opens the door', () => {
+ const [root] = applyReplyCountDelta([msg()], 'm-root', 1)
+ assert.equal(root.replyCount, 1)
+ })
+
+ it('counts on top of what the server already reported', () => {
+ const [root] = applyReplyCountDelta([msg({ replyCount: 4 })], 'm-root', 1)
+ assert.equal(root.replyCount, 5)
+ })
+
+ it('gives the count back when a reply is thrown away', () => {
+ const [root] = applyReplyCountDelta([msg({ replyCount: 3 })], 'm-root', -1)
+ assert.equal(root.replyCount, 2)
+ })
+
+ it('never counts below zero', () => {
+ // A discard of a reply whose root was loaded after the fact.
+ const [root] = applyReplyCountDelta([msg({ replyCount: 0 })], 'm-root', -1)
+ assert.equal(root.replyCount, 0)
+ })
+
+ it('is a no-op for a message that is not a reply', () => {
+ const list = [msg({ replyCount: 2 })]
+ assert.equal(applyReplyCountDelta(list, null, 1), list)
+ assert.equal(applyReplyCountDelta(list, undefined, 1), list)
+ })
+
+ it('is a no-op when the root is not in the loaded page', () => {
+ // Replying to an old message the user scrolled back to and then away from.
+ const list = [msg({ replyCount: 2 })]
+ assert.equal(applyReplyCountDelta(list, 'm-somewhere-else', 1), list)
+ })
+
+ it('touches only the root, and does not mutate the array it was given', () => {
+ const list = [msg({ replyCount: 1 }), msg({ id: 'm-other', replyCount: 7 })]
+ const next = applyReplyCountDelta(list, 'm-root', 1)
+ assert.equal(next[1], list[1], 'an unrelated message was rebuilt')
+ assert.equal(list[0].replyCount, 1, 'the input list was mutated')
+ assert.equal(next[0].replyCount, 2)
+ })
+
+ it('the author\'s full sequence lands on exactly one', () => {
+ // insert the optimistic bubble (+1), then the server echo contributes 0
+ // because applyEvent skips arrivals that match a prior local copy.
+ let list = [msg()]
+ list = applyReplyCountDelta(list, 'm-root', 1) // sendUserMessage
+ // echo: prior found -> no delta
+ assert.equal(list[0].replyCount, 1, 'the author must end at exactly one, not zero and not two')
+ })
+})
+
+describe('the three places that have to agree', () => {
+ // The helper is pure: every test above passes just as well against a build
+ // where sendUserMessage never counts. The bug was never in the arithmetic —
+ // it was that only one of the three sites did any.
+
+ it('the optimistic insert counts the reply', async () => {
+ const source = await readFile(new URL('../src/stores/messages.ts', import.meta.url), 'utf8')
+ const send = source.slice(source.indexOf('export async function sendUserMessage'))
+ const body = send.slice(0, send.indexOf('\nexport '))
+ assert.match(body, /applyReplyCountDelta\([\s\S]{0,120}quotedMessageId,\s*\n?\s*1,/,
+ 'sendUserMessage no longer counts the reply it just inserted — the author\'s root will stay one short and, at zero, hide the only way into the thread')
+ })
+
+ it('the server echo does not count it a second time', async () => {
+ const source = await readFile(new URL('../src/stores/messages.ts', import.meta.url), 'utf8')
+ assert.match(source, /if \(!prior\) next = applyReplyCountDelta\(next, m\.quotedMessageId, 1\)/,
+ 'the arrival bump is no longer guarded on `!prior`, so the author would double-count their own reply')
+ })
+
+ it('discarding a failed reply gives the count back', async () => {
+ // Also what keeps a retry balanced: retryFailedMessage discards, then sends.
+ const source = await readFile(new URL('../src/stores/messages.ts', import.meta.url), 'utf8')
+ const discard = source.slice(source.indexOf('export function discardFailedMessage'))
+ const body = discard.slice(0, discard.indexOf('\nexport '))
+ assert.match(body, /applyReplyCountDelta\([\s\S]{0,160}-1,/,
+ 'a discarded reply leaves a phantom count on its root, and a retry would count twice')
+ })
+
+ it('the thread drawer is still gated on the count', async () => {
+ // If this ever stops being true the bug above stops being a missing door
+ // and becomes a wrong number — worth knowing which one we are fixing.
+ const source = await readFile(new URL('../src/components/Message.tsx', import.meta.url), 'utf8')
+ assert.match(source, /\(msg\.replyCount \?\? 0\) > 0/)
+ assert.match(source, /openThreadView\(msg\.conversationId, msg\.id\)/)
+ })
+})