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(messages): prevent duplicates after lost delivery confirmation (#19)

Colaforniaec6976b1ff42
diff --git a/server/src/__integration__/message-delivery.test.ts b/server/src/__integration__/message-delivery.test.ts
new file mode 100644
index 0000000..2533a98
--- /dev/null
+++ b/server/src/__integration__/message-delivery.test.ts
@@ -0,0 +1,103 @@
+import { test, before, beforeEach, after } from 'node:test'
+import assert from 'node:assert/strict'
+import { createServer, type Server } from 'node:http'
+import {
+ buildApiTestApp, ensureSchemaOnce, resetAllTables, seedUserMembership, teardownAll,
+} from './_helpers.js'
+import { pool } from '../db/pool.js'
+
+const USER_ID = 'u-delivery-test'
+const COMPANY_ID = 'c-delivery-test'
+const CONVERSATION_ID = 'g-delivery-test'
+const CLIENT_ID = 'temp-delivery-test'
+let server: Server
+let baseUrl = ''
+
+before(async () => {
+ process.env.CUMORA_TEST_MESSAGE_FAULTS = '1'
+ await ensureSchemaOnce()
+ const app = await buildApiTestApp(USER_ID)
+ await new Promise<void>((resolve) => {
+ server = createServer(app).listen(0, () => {
+ const addr = server.address()
+ if (addr && typeof addr === 'object') baseUrl = `http://127.0.0.1:${addr.port}`
+ resolve()
+ })
+ })
+})
+
+beforeEach(async () => {
+ await resetAllTables()
+ await pool.query(
+ `INSERT INTO companies (id, name, slug, owner_user_id)
+ VALUES ($1, 'Delivery Test', 'delivery-test', $2)`,
+ [COMPANY_ID, USER_ID],
+ )
+ await seedUserMembership(USER_ID, COMPANY_ID)
+ await pool.query(
+ `INSERT INTO conversations (id, kind, title, members, company_id)
+ VALUES ($1, 'group', 'Delivery Test', $2::jsonb, $3)`,
+ [CONVERSATION_ID, JSON.stringify([USER_ID]), COMPANY_ID],
+ )
+})
+
+after(async () => {
+ delete process.env.CUMORA_TEST_MESSAGE_FAULTS
+ await teardownAll(server)
+})
+
+test('[integration] retrying a committed message after a lost acknowledgement returns the original', async () => {
+ await assert.rejects(fetch(`${baseUrl}/api/conversations/${CONVERSATION_ID}/messages`, {
+ method: 'POST',
+ headers: {
+ 'content-type': 'application/json',
+ 'x-company-id': COMPANY_ID,
+ 'x-cumora-test-message-fault': 'after-commit-drop-ack',
+ },
+ body: JSON.stringify({ body: 'delivery probe', clientId: CLIENT_ID }),
+ }))
+
+ const retry = await fetch(`${baseUrl}/api/conversations/${CONVERSATION_ID}/messages`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json', 'x-company-id': COMPANY_ID },
+ body: JSON.stringify({ body: 'delivery probe', clientId: CLIENT_ID }),
+ })
+ assert.equal(retry.status, 202)
+ const retried = await retry.json() as { id: string; sequence: number }
+
+ const { rows } = await pool.query<{ id: string; author_id: string; body: string; client_id: string }>(
+ `SELECT id, author_id, body, client_id FROM messages WHERE conversation_id = $1`,
+ [CONVERSATION_ID],
+ )
+ assert.deepEqual(rows, [{
+ id: retried.id,
+ author_id: USER_ID,
+ body: 'delivery probe',
+ client_id: CLIENT_ID,
+ }])
+
+ const loaded = await fetch(`${baseUrl}/api/conversations/${CONVERSATION_ID}/messages`, {
+ headers: { 'x-company-id': COMPANY_ID },
+ })
+ assert.equal(loaded.status, 200)
+ const messages = await loaded.json() as Array<{ id: string; clientId?: string }>
+ assert.equal(messages.find((message) => message.id === retried.id)?.clientId, CLIENT_ID)
+})
+
+test('[integration] concurrent requests with the same client id create one message', async () => {
+ const send = () => fetch(`${baseUrl}/api/conversations/${CONVERSATION_ID}/messages`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json', 'x-company-id': COMPANY_ID },
+ body: JSON.stringify({ body: 'concurrent delivery probe', clientId: CLIENT_ID }),
+ })
+ const responses = await Promise.all([send(), send()])
+ assert.deepEqual(responses.map((response) => response.status), [202, 202])
+ const messages = await Promise.all(responses.map((response) => response.json() as Promise<{ id: string }>))
+ assert.equal(messages[0]?.id, messages[1]?.id)
+
+ const { rows } = await pool.query<{ count: string }>(
+ `SELECT COUNT(*)::text AS count FROM messages WHERE conversation_id = $1`,
+ [CONVERSATION_ID],
+ )
+ assert.equal(rows[0]?.count, '1')
+})
diff --git a/server/src/api/router.ts b/server/src/api/router.ts
index 014b752..0b3f2ff 100644
--- a/server/src/api/router.ts
+++ b/server/src/api/router.ts
@@ -3126,6 +3126,7 @@ api.get('/conversations/:id/messages', async (req, res) => {
`SELECT
m.id, m.conversation_id AS "conversationId",
m.author_id AS "authorId", m.kind, m.body, m.sequence,
+ m.client_id AS "clientId",
m.tool, m.attachment, m.poll,
-- Per-option vote tallies for polls. Empty array for non-poll
-- rows. voterIds is sorted so the client can diff cheaply across
@@ -3320,14 +3321,41 @@ api.post('/conversations/:id/messages', async (req, res) => {
? rawQuotedId
: null
- // Optional client-supplied dedup key. Echoed back on CH_MESSAGE_NEW so the
- // renderer can recognize its own optimistic bubble when the WS event races
- // the POST response. Length-capped so a malformed client can't bloat the
- // payload — opaque to the server otherwise.
+ // Optional client-supplied idempotency key. Persisted so retries and
+ // reconnect fetches can reconcile the original optimistic bubble.
const rawClientId = req.body?.clientId
- const clientId = typeof rawClientId === 'string' && rawClientId.length > 0 && rawClientId.length <= 80
- ? rawClientId
- : null
+ if (rawClientId != null && (typeof rawClientId !== 'string' || rawClientId.length === 0 || rawClientId.length > 80)) {
+ res.status(400).json({ error: 'invalid clientId' })
+ return
+ }
+ const clientId = typeof rawClientId === 'string' ? rawClientId : null
+
+ let deliveryMessageId: string | undefined
+ let responseFinished = false
+ const logDelivery = (phase: string, extra?: Record<string, unknown>) => {
+ console.log('[message-delivery]', JSON.stringify({
+ phase,
+ conversationId: id,
+ authorId: me,
+ clientId: clientId ?? undefined,
+ messageId: deliveryMessageId,
+ ...extra,
+ }))
+ }
+ logDelivery('request.received')
+ res.once('finish', () => {
+ responseFinished = true
+ logDelivery('response.finished', { status: res.statusCode })
+ })
+ res.once('close', () => {
+ if (!responseFinished) {
+ logDelivery('response.closed', {
+ status: res.headersSent ? res.statusCode : undefined,
+ headersSent: res.headersSent,
+ writableFinished: res.writableFinished,
+ })
+ }
+ })
const { rows: convoRows } = await pool.query<{ members: string[]; kind: string }>(
`SELECT members, kind FROM conversations WHERE id = $1 AND company_id = $2`,
@@ -3413,6 +3441,8 @@ api.post('/conversations/:id/messages', async (req, res) => {
}
}
+ // Retrying a message, or sending it twice at the same time, can leave a gap
+ // in sequence numbers. They only sort messages, so gaps are safe.
const seqResult = await pool.query<{ seq: number }>(
`INSERT INTO conversation_counters (conversation_id, next_sequence)
VALUES ($1, 2)
@@ -3422,14 +3452,47 @@ api.post('/conversations/:id/messages', async (req, res) => {
)
const sequence = seqResult.rows[0]?.seq ?? 1
- const messageId = `m-${randomUUID()}`
- await pool.query(
- `INSERT INTO messages (id, conversation_id, author_id, kind, body, sequence, attachment, quoted_message_id, company_id)
- VALUES ($1,$2,$3,'text',$4,$5,$6::jsonb,$7,$8)`,
- [messageId, id, me, body, sequence, attachment ? JSON.stringify(attachment) : null, resolvedQuotedId, tenant],
+ const proposedMessageId = `m-${randomUUID()}`
+ const inserted = await pool.query<{ id: string; sequence: number }>(
+ `INSERT INTO messages
+ (id, conversation_id, author_id, kind, body, sequence, attachment, quoted_message_id, company_id, client_id)
+ VALUES ($1,$2,$3,'text',$4,$5,$6::jsonb,$7,$8,$9)
+ ON CONFLICT (conversation_id, author_id, client_id) WHERE client_id IS NOT NULL
+ DO NOTHING
+ RETURNING id, sequence`,
+ [proposedMessageId, id, me, body, sequence, attachment ? JSON.stringify(attachment) : null, resolvedQuotedId, tenant, clientId],
)
+ const persisted = inserted.rows[0] ?? (clientId
+ ? (await pool.query<{ id: string; sequence: number }>(
+ `SELECT id, sequence FROM messages
+ WHERE conversation_id = $1 AND author_id = $2 AND client_id = $3`,
+ [id, me, clientId],
+ )).rows[0]
+ : undefined)
+ if (!persisted) throw new Error('message insert returned no row')
+ const messageId = persisted.id
+ const persistedSequence = persisted.sequence
+ deliveryMessageId = messageId
+ if (!inserted.rows[0]) {
+ logDelivery('message.reused', { sequence: persistedSequence })
+ res.status(202).json({ id: messageId, sequence: persistedSequence })
+ return
+ }
+ logDelivery('message.committed', { sequence: persistedSequence })
await pool.query(`UPDATE conversations SET updated_at = NOW() WHERE id = $1`, [id])
+ // Test-only fault injection: reproduce a connection disappearing after
+ // persistence but before either HTTP or WebSocket acknowledgement.
+ if (
+ env.NODE_ENV !== 'production'
+ && process.env.CUMORA_TEST_MESSAGE_FAULTS === '1'
+ && req.get('x-cumora-test-message-fault') === 'after-commit-drop-ack'
+ ) {
+ logDelivery('fault.after_commit_drop_ack')
+ res.destroy()
+ return
+ }
+
// Drop the message into the bus. The mailbox scheduler (subscribed to
// CH_MESSAGE_NEW) wakes every agent member and lets each decide for itself
// whether to reply, react, dm, or stay silent. The companyId tag lets
@@ -3440,13 +3503,14 @@ api.post('/conversations/:id/messages', async (req, res) => {
companyId: tenant,
message: {
id: messageId, conversationId: id, authorId: me,
- kind: 'text', body, sequence, at: new Date().toISOString(),
+ kind: 'text', body, sequence: persistedSequence, at: new Date().toISOString(),
attachment: attachment ?? undefined,
quotedMessageId: resolvedQuotedId ?? undefined,
quoted: quotedSummary ?? undefined,
clientId: clientId ?? undefined,
},
})
+ logDelivery('ws.published')
// Fan out APNs to recipients who aren't currently looking at the app
// (NotificationToasts handles those). Fire-and-forget — push delivery
@@ -3484,7 +3548,7 @@ api.post('/conversations/:id/messages', async (req, res) => {
res.status(202).json({
id: messageId,
- sequence,
+ sequence: persistedSequence,
quotedMessageId: resolvedQuotedId ?? undefined,
quoted: quotedSummary ?? undefined,
})
diff --git a/server/src/db/migrate.ts b/server/src/db/migrate.ts
index 61836ba..c50cf26 100644
--- a/server/src/db/migrate.ts
+++ b/server/src/db/migrate.ts
@@ -29,11 +29,14 @@ CREATE TABLE IF NOT EXISTS messages (
reactions JSONB,
tool JSONB,
attachment JSONB,
+ client_id TEXT,
created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW()
);
CREATE INDEX IF NOT EXISTS idx_messages_convo_seq ON messages(conversation_id, sequence);
CREATE INDEX IF NOT EXISTS idx_messages_convo_created ON messages(conversation_id, created_at);
+ALTER TABLE messages ADD COLUMN IF NOT EXISTS client_id TEXT;
+
-- Reply-to / quote target. Soft self-FK (no ON DELETE CASCADE) so deleting
-- the original leaves replies as orphans rendered as "[deleted]" stubs
-- rather than wiping the reply thread. Idx supports the thread-fetch
@@ -2078,6 +2081,7 @@ export async function ensureSchema(): Promise<void> {
CREATE UNIQUE INDEX IF NOT EXISTS participants_agent_id_unique
ON participants(id) WHERE kind = 'agent'
`)
+ await ensureMessageClientIdIndex(client)
console.log('[db] schema ensured')
} catch (e) {
@@ -2158,6 +2162,13 @@ async function schemaAlreadyCurrent(client: import('pg').PoolClient): Promise<bo
AND (SELECT count(*) FROM information_schema.columns
WHERE table_name = 'participants' AND column_name = 'company_id') > 0
AND (SELECT count(*) FROM pg_class WHERE relname = 'participants_agent_id_unique') > 0
+ AND (SELECT count(*) FROM information_schema.columns
+ WHERE table_name = 'messages' AND column_name = 'client_id') > 0
+ AND EXISTS (
+ SELECT 1 FROM pg_class c
+ JOIN pg_index i ON i.indexrelid = c.oid
+ WHERE c.relname = 'uniq_messages_client_id' AND i.indisvalid
+ )
-- llm_calls is the universal sub2api ledger added in the observability
-- rollout (29155c5). Without this sentinel, a 40P01 deadlock on the big
-- DDL batch would take the "already current" shortcut and silently
@@ -2185,6 +2196,26 @@ async function schemaAlreadyCurrent(client: import('pg').PoolClient): Promise<bo
}
}
+/** Correctness index for message idempotency. Build it concurrently so adding
+ * the feature cannot block writes to the hot messages table. */
+async function ensureMessageClientIdIndex(client: import('pg').PoolClient): Promise<void> {
+ const { rows } = await client.query<{ indisvalid: boolean }>(
+ `SELECT i.indisvalid FROM pg_class c
+ JOIN pg_index i ON i.indexrelid = c.oid
+ WHERE c.relname = 'uniq_messages_client_id'`,
+ )
+ if (rows[0]?.indisvalid) return
+ await client.query("SET lock_timeout = '0'")
+ try {
+ if (rows[0]) await client.query('DROP INDEX CONCURRENTLY IF EXISTS uniq_messages_client_id')
+ await client.query(`CREATE UNIQUE INDEX CONCURRENTLY uniq_messages_client_id
+ ON messages(conversation_id, author_id, client_id)
+ WHERE client_id IS NOT NULL`)
+ } finally {
+ await client.query("SET lock_timeout = '5s'")
+ }
+}
+
/**
* Build indexes that are unsafe inside the main migration transaction.
*
diff --git a/server/src/db/schema.ts b/server/src/db/schema.ts
index 4d428c6..687b4ea 100644
--- a/server/src/db/schema.ts
+++ b/server/src/db/schema.ts
@@ -1,4 +1,5 @@
-import { pgTable, text, integer, timestamp, jsonb, boolean, index } from 'drizzle-orm/pg-core'
+import { sql } from 'drizzle-orm'
+import { pgTable, text, integer, timestamp, jsonb, boolean, index, uniqueIndex } from 'drizzle-orm/pg-core'
export const conversations = pgTable('conversations', {
id: text('id').primaryKey(),
@@ -25,6 +26,7 @@ export const messages = pgTable(
reactions: jsonb('reactions').$type<Array<{ emoji: string; count: number; mine?: boolean }> | null>(),
tool: jsonb('tool').$type<Record<string, unknown> | null>(),
attachment: jsonb('attachment').$type<Record<string, unknown> | null>(),
+ clientId: text('client_id'),
poll: jsonb('poll').$type<PollPayload | null>(),
// Reply-to / quote target: id of another message in THIS conversation that
// this message is quoting. Soft FK to messages.id with ON DELETE SET NULL
@@ -37,6 +39,9 @@ export const messages = pgTable(
convoSeqIdx: index('idx_messages_convo_seq').on(table.conversationId, table.sequence),
convoCreatedIdx: index('idx_messages_convo_created').on(table.conversationId, table.createdAt),
quotedIdx: index('idx_messages_quoted').on(table.quotedMessageId),
+ clientIdIdx: uniqueIndex('uniq_messages_client_id')
+ .on(table.conversationId, table.authorId, table.clientId)
+ .where(sql`${table.clientId} IS NOT NULL`),
}),
)
diff --git a/src/api/client.ts b/src/api/client.ts
index 65cdc9b..b6cb498 100644
--- a/src/api/client.ts
+++ b/src/api/client.ts
@@ -93,6 +93,13 @@ export function setDevModeEnabled(enabled: boolean): void {
else localStorage.removeItem(DEVTOOLS_KEY)
}
+export class ApiError extends Error {
+ constructor(message: string, readonly status: number) {
+ super(message)
+ this.name = 'ApiError'
+ }
+}
+
export async function http<T>(path: string, init?: RequestInit): Promise<T> {
const headers: Record<string, string> = { 'content-type': 'application/json' }
const token = getAuthToken()
@@ -122,7 +129,7 @@ export async function http<T>(path: string, init?: RequestInit): Promise<T> {
} catch { detail = text.slice(0, 200) }
}
} catch { /* ignore */ }
- throw new Error(detail ? `${detail} (${res.status})` : `${res.status} ${res.statusText}`)
+ throw new ApiError(detail ? `${detail} (${res.status})` : `${res.status} ${res.statusText}`, res.status)
}
return res.json() as Promise<T>
}
@@ -1022,10 +1029,9 @@ export const api = {
body: string,
attachment?: ApiAttachment | null,
quotedMessageId?: string | null,
- /** Optional client-supplied dedup key (the optimistic bubble's tempId).
- * Server echoes it on CH_MESSAGE_NEW so the renderer can match the WS
- * echo to its still-temp local bubble even when the WS event arrives
- * before this POST resolves. */
+ /** Optional client-supplied idempotency key (the optimistic bubble's
+ * tempId). The server persists it and returns the original message when
+ * the same send is retried. */
clientId?: string | null,
) =>
http<{ id: string; sequence: number }>(`/conversations/${encodeURIComponent(conversationId)}/messages`, {
diff --git a/src/components/Message.tsx b/src/components/Message.tsx
index 4d5d239..c8fbc12 100644
--- a/src/components/Message.tsx
+++ b/src/components/Message.tsx
@@ -1786,15 +1786,9 @@ function MessageRowImpl({ msg, author, delay = 0, animate = true }: MessageRowPr
)}
{msg.attachment && <AttachmentCard msg={msg} />}
- {msg.failed && (
- // Failed-to-send row: text + Retry + Dismiss buttons. The
- // bubble's id is still the optimistic tempId (the server
- // never persisted it), which is the key both store helpers
- // use. Retry re-runs sendUserMessage with the original body /
- // attachment / quote; Dismiss just drops the bubble locally
- // so it stops clogging the bottom of the conversation.
+ {(msg.failed || msg.unconfirmed) && (
<div className="mt-1 flex items-center gap-2 text-[11px] text-coral-deep">
- <span>Failed to send</span>
+ <span>{msg.unconfirmed ? 'Delivery not confirmed' : 'Failed to send'}</span>
<button
type="button"
onClick={(e) => { e.stopPropagation(); void retryFailedMessage(msg.conversationId, msg.id) }}
diff --git a/src/stores/messages.ts b/src/stores/messages.ts
index 037f65f..5807207 100644
--- a/src/stores/messages.ts
+++ b/src/stores/messages.ts
@@ -1,6 +1,6 @@
import { create } from 'zustand'
import type { Message, ReactionEntry } from '@/types'
-import { api, ws, type WsEvent, type ApiMessage } from '@/api/client'
+import { api, ApiError, ws, type WsEvent, type ApiMessage } from '@/api/client'
import { useApp } from '@/stores/app'
import { getMeId } from '@/stores/auth'
@@ -311,8 +311,7 @@ function mergeFetchedMessages(current: Message[] | undefined, incoming: Message[
const merged = incoming.map((m) => {
const prev = currentById.get(m.id)
// Keep the local optimistic key stable after a fetch returns the same
- // persisted row. The API snapshot is authoritative for message content,
- // but `clientId` is a renderer-only identity.
+ // persisted row. Older servers may omit clientId from the snapshot.
return prev?.clientId && !m.clientId ? { ...m, clientId: prev.clientId } : m
})
@@ -494,6 +493,12 @@ export const useMessages = create<MessagesState>((set, get) => ({
// list key (m.clientId ?? m.id) stays stable across the replacement
// — otherwise the row remounts and re-animates.
const merged: Message = prior?.clientId ? { ...m, clientId: prior.clientId } : m
+ if (prior?.clientId) {
+ console.info('[message-delivery]', {
+ phase: 'client.confirmed', via: 'ws', status: 'sent',
+ clientId: prior.clientId, messageId: m.id,
+ })
+ }
const without = existing.filter((x) => x !== prior && x.id !== m.id)
let next = [...without, merged].sort((a, b) => {
const sa = (a as { sequence?: number }).sequence ?? 0
@@ -612,11 +617,19 @@ function newTempId(): string {
return `temp-${rnd}`
}
+function isDefinitiveSendFailure(error: unknown): boolean {
+ return error instanceof ApiError
+ && error.status >= 400
+ && error.status < 500
+ && ![408, 425, 429].includes(error.status)
+}
+
export async function sendUserMessage(
convoId: string,
body: string,
attachment?: import('@/api/client').ApiAttachment | null,
quotedMessageId?: string | null,
+ clientId = newTempId(),
): Promise<void> {
const v = body.trim()
if (!v && !attachment) return
@@ -649,7 +662,7 @@ export async function sendUserMessage(
}
}
- const tempId = newTempId()
+ const tempId = clientId
const optimistic: Message = {
id: tempId,
clientId: tempId,
@@ -663,6 +676,7 @@ export async function sendUserMessage(
name: attachment.name,
kind: attachment.kind,
url: attachment.url,
+ key: attachment.key,
mime: attachment.mime,
size: attachment.size,
}
@@ -684,7 +698,7 @@ export async function sendUserMessage(
}))
try {
- const { id: realId } = await api.sendMessage(convoId, v, attachment ?? null, quotedMessageId ?? null, tempId)
+ const { id: realId } = await api.sendMessage(convoId, v, attachment ?? null, quotedMessageId ?? null, clientId)
// Reconcile the temp bubble with the server. Either the WS `message.new`
// already raced ahead of us (real id already in the list → drop the temp)
// or it hasn't (rename temp → real id so the eventual WS event dedupes
@@ -695,26 +709,33 @@ export async function sendUserMessage(
const next = realExists
? list.filter((m) => m.id !== tempId)
: list.map((m) =>
- m.id === tempId ? { ...m, id: realId, pending: false } : m,
+ m.id === tempId ? { ...m, id: realId, pending: false, failed: false, unconfirmed: false } : m,
)
return { byConvo: { ...s.byConvo, [convoId]: next } }
})
+ console.info('[message-delivery]', {
+ phase: 'client.confirmed', via: 'http', status: 'sent', clientId, messageId: realId,
+ })
} catch (err) {
console.warn('[messages] send failed', err)
+ const failed = isDefinitiveSendFailure(err)
useMessages.setState((s) => {
const list = s.byConvo[convoId] ?? []
const next = list.map((m) =>
- m.id === tempId ? { ...m, pending: false, failed: true } : m,
+ m.id === tempId ? { ...m, pending: false, failed, unconfirmed: !failed } : m,
)
return { byConvo: { ...s.byConvo, [convoId]: next } }
})
+ console.info('[message-delivery]', {
+ phase: failed ? 'client.failed' : 'client.unconfirmed',
+ via: 'http', status: failed ? 'failed' : 'unconfirmed',
+ clientId, httpStatus: err instanceof ApiError ? err.status : undefined,
+ })
}
}
-/** Drop a failed-to-send optimistic bubble from the local list. The
- * message never reached the server so no rollback is needed there;
- * this is purely a UI clean-up so the bubble doesn't linger forever
- * at the bottom of the conversation. */
+/** Drop a failed or unconfirmed optimistic bubble from the local list. An
+ * unconfirmed row may reappear on the next fetch if it reached the server. */
export function discardFailedMessage(convoId: string, tempId: string): void {
useMessages.setState((s) => {
const list = s.byConvo[convoId]
@@ -725,28 +746,21 @@ export function discardFailedMessage(convoId: string, tempId: string): void {
})
}
-/** Retry a failed-to-send optimistic bubble. We remove the failed
- * bubble, then resubmit the same body / attachment / quote pointer
- * via `sendUserMessage`, which paints a fresh optimistic bubble at the
- * tail of the list. If the retry also fails, that fresh bubble ends
- * up in the failed state and the user can retry again. */
+/** Retry with the original clientId so the server can return an already
+ * committed message instead of creating a duplicate. */
export async function retryFailedMessage(convoId: string, tempId: string): Promise<void> {
const list = useMessages.getState().byConvo[convoId] ?? []
const msg = list.find((m) => m.id === tempId)
if (!msg) return
const body = msg.body ?? ''
const att = msg.attachment
- // The optimistic bubble carried a denormalized attachment shape that
- // mirrors ApiAttachment minus `key` (we never stashed it on the
- // bubble). For retry that's fine — the server resolves the row by
- // url + name + mime + size, and `key` is only used as an internal
- // optimization marker.
const retryAttachment: import('@/api/client').ApiAttachment | null = att
- ? { url: att.url ?? '', name: att.name, kind: att.kind, mime: att.mime, size: att.size }
+ ? { url: att.url ?? '', name: att.name, kind: att.kind, key: att.key, mime: att.mime, size: att.size }
: null
const quotedId = msg.quotedMessageId ?? null
+ const clientId = msg.clientId ?? tempId
discardFailedMessage(convoId, tempId)
- await sendUserMessage(convoId, body, retryAttachment, quotedId)
+ await sendUserMessage(convoId, body, retryAttachment, quotedId, clientId)
}
export async function toggleReaction(messageId: string, emoji: string): Promise<void> {
diff --git a/src/types.ts b/src/types.ts
index 7685f54..d0fd963 100644
--- a/src/types.ts
+++ b/src/types.ts
@@ -213,6 +213,8 @@ export interface Message {
kind: 'img' | 'pdf' | 'file' | 'fig'
/** real assets carry a URL; mock/legacy data may not */
url?: string
+ /** Storage key used to refresh expiring signed URLs. */
+ key?: string
mime?: string
size?: number
/** legacy descriptor — fallback when no real file is present (e.g. mock data) */
@@ -248,9 +250,9 @@ export interface Message {
* the server round-trip; never returned from the API. */
pending?: boolean
failed?: boolean
- /** Stable identity that survives the temp-id → real-id rename so React
- * keeps the same DOM node (avoids re-firing the entry animation). Set on
- * optimistic insert; carried onto the server echo in `applyEvent`. */
+ /** The request may have committed, but neither HTTP nor WS confirmed it. */
+ unconfirmed?: boolean
+ /** Stable idempotency key that also survives the temp-id → real-id rename. */
clientId?: string
}