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(realtime): a committed doc mention must not 500 on a Redis outage (#217)
OKNOTOK862fa83d77f9
diff --git a/server/src/__integration__/realtime-outbox.test.ts b/server/src/__integration__/realtime-outbox.test.tsindex 87068b2..0ada48a 100644--- a/server/src/__integration__/realtime-outbox.test.ts+++ b/server/src/__integration__/realtime-outbox.test.ts@@ -3,7 +3,8 @@ import { after, before, beforeEach, test } from 'node:test'import assert from 'node:assert/strict'import { pool } from '../db/pool.js'import { drainRealtimeOutbox, enqueueBroadcast } from '../realtime-outbox.js'-import type { BroadcastEvent } from '../redis.js'+import { CH_DOC_MENTION, type BroadcastEvent, type DocMentionEvent } from '../redis.js'+import { processDocMention } from '../ws.js'import {buildApiTestApp, ensureSchemaOnce, resetAllTables,seedUserMembership, teardownAll,@@ -155,6 +156,72 @@ test('[integration] document and calendar creates replay without duplicate rowsassert.equal(events.rows[0]?.count, 2)})+// ── a doc mention is a durable write, so its toast must ride the outbox ─────+//+// `document_mentions` is the dedup ledger: processDocMention() skips any+// (doc, mentioner, mentioned) tuple written in the last 60 seconds. Once those+// rows commit, every retry inside that window is a no-op. A post-COMMIT+// `publish()` that threw on a Redis outage therefore destroyed the notice+// permanently AND reported failure for work that had already succeeded.++test('[integration] a Redis outage delays a doc mention toast instead of losing it', async () => {+ const RECIPIENT_ID = 'u-outbox-mentioned'+ const DOCUMENT_ID = 'doc-outbox-mention'+ await seedUserMembership(RECIPIENT_ID, COMPANY_ID, { displayName: 'Mentioned Human' })+ await pool.query(+ `INSERT INTO documents (id, company_id, title, created_by)+ VALUES ($1, $2, 'Quarterly plan', $3)`,+ [DOCUMENT_ID, COMPANY_ID, USER_ID],+ )++ await processDocMention({+ documentId: DOCUMENT_ID,+ companyId: COMPANY_ID,+ mentionerId: USER_ID,+ requestedIds: [RECIPIENT_ID],+ })++ const committed = await pool.query<{ mentions: number; pending: number; channel: string }>(+ `SELECT+ (SELECT COUNT(*)::int FROM document_mentions WHERE document_id = $1) AS mentions,+ (SELECT COUNT(*)::int FROM realtime_outbox WHERE published_at IS NULL) AS pending,+ (SELECT channel FROM realtime_outbox LIMIT 1) AS channel`,+ [DOCUMENT_ID],+ )+ assert.deepEqual(committed.rows[0], {+ mentions: 1, pending: 1, channel: CH_DOC_MENTION,+ }, 'the toast must be enqueued in the same transaction as the mention row')++ const failed = await drainRealtimeOutbox({+ publishFn: async () => { throw new Error('redis unavailable') },+ })+ assert.deepEqual(failed, { claimed: 1, published: 0, failed: 1, discarded: 0 })++ // The dedup window has NOT been consumed by the failure: the durable row and+ // its undelivered event both survive, so recovery is a replay, not a re-send.+ await pool.query(`UPDATE realtime_outbox SET available_at = NOW()`)+ const delivered: BroadcastEvent[] = []+ const recovered = await drainRealtimeOutbox({+ publishFn: async (_channel, event) => { delivered.push(event) },+ })+ assert.deepEqual(recovered, { claimed: 1, published: 1, failed: 0, discarded: 0 })+ assert.equal(delivered.length, 1)+ assert.equal(delivered[0].type, 'doc.mention')+ assert.deepEqual(+ (delivered[0] as DocMentionEvent).mentionedIds, [RECIPIENT_ID],+ )++ // And the ledger still holds exactly one mention — the outage never widened+ // into a duplicate notice.+ const settled = await pool.query<{ mentions: number; pending: number }>(+ `SELECT+ (SELECT COUNT(*)::int FROM document_mentions WHERE document_id = $1) AS mentions,+ (SELECT COUNT(*)::int FROM realtime_outbox WHERE published_at IS NULL) AS pending`,+ [DOCUMENT_ID],+ )+ assert.deepEqual(settled.rows[0], { mentions: 1, pending: 0 })+})+// ── a body cut mid-emoji must not roll the transaction back ─────────────────//// The quote path truncates by UTF-16 code unit (`qr[0].body.slice(0, 240)`), sodiff --git a/server/src/api/router.ts b/server/src/api/router.tsindex 4b2b89a..e05b084 100644--- a/server/src/api/router.ts+++ b/server/src/api/router.ts@@ -3717,13 +3717,22 @@ api.post('/conversations/:id/typing', async (req, res) => {// field name is a legacy from when only agents emitted typing — the// client treats it as an opaque participant id and doesn't care// whether the typer is human or agent.+ //+ // Fail-open on a Redis outage. A typing indicator is pure ephemera+ // that the renderer expires on its own; surfacing the outage as a 500+ // would only teach a composer that fires one of these every few+ // seconds to spam the error path. Matches how the agent-side emitters+ // treat the same channel (inproc-client.ts, scheduler.ts).await publish(CH_TYPING, {type: 'typing',conversationId: id,agentId: me,done,companyId,- })+ }).catch((err) =>+ console.warn(`[typing] publish for ${id} failed — dropping`,+ err instanceof Error ? err.message : err),+ )res.json({ ok: true })} catch (e) {const status = e instanceof HttpError ? e.status : 500diff --git a/server/src/ws.ts b/server/src/ws.tsindex 9a107a2..7ea0c68 100644--- a/server/src/ws.ts+++ b/server/src/ws.ts@@ -14,6 +14,7 @@ import type { MessageNewEvent } from './redis.js'import { env } from './env.js'import { consumeWsTicket } from './auth.js'import { pool } from './db/pool.js'+import { enqueueBroadcast, nudgeRealtimeOutbox } from './realtime-outbox.js'import { setStatus } from './status.js'import {subscribe as docSubscribe,@@ -522,8 +523,12 @@ async function handleDocFrame(c: AuthedSocket, msg: Record<string, unknown>): Pr* most recent mention-row for the same (doc, mentioner, mentioned)* tuple — we don't want a noisily editing user spamming the* recipient. For mentioned AGENTS, also writes an `agent_log` row so- * the agent's history surfaces the mention. */-async function processDocMention(args: {+ * the agent's history surfaces the mention.+ *+ * Exported for the integration suite: the only production caller is the+ * `doc.mention.notify` WS frame above, and standing up a socket just to+ * assert the durable/outbox contract would test the transport instead. */+export async function processDocMention(args: {documentId: stringcompanyId: stringmentionerId: string@@ -608,7 +613,26 @@ async function processDocMention(args: {}freshRows.push(row)}+ // The toast rides the transactional outbox rather than a post-COMMIT+ // publish. `document_mentions` is the dedup ledger: once these rows+ // commit, the 60s window above swallows every retry, so a Redis outage+ // that threw here used to lose the notice permanently while the caller+ // saw a failure for work that had actually succeeded. Enqueued in-band,+ // a degraded Redis only delays it. See realtime-outbox.ts.+ if (freshRows.length > 0) {+ const event: DocMentionEvent = {+ type: 'doc.mention',+ companyId,+ documentId,+ documentTitle,+ mentionerId,+ mentionerName,+ mentionedIds: freshRows.map((row) => row.id),+ }+ await enqueueBroadcast(client, CH_DOC_MENTION, event)+ }await client.query('COMMIT')+ nudgeRealtimeOutbox()} catch (error) {await client.query('ROLLBACK').catch(() => {})throw error@@ -630,18 +654,6 @@ async function processDocMention(args: {console.warn(`[doc.mention] wake post for ${row.id} failed`, e)}}- const freshIds = freshRows.map((row) => row.id)-- const event: DocMentionEvent = {- type: 'doc.mention',- companyId,- documentId,- documentTitle,- mentionerId,- mentionerName,- mentionedIds: freshIds,- }- await publish(CH_DOC_MENTION, event)}/** Post a synthetic chat message that wakes the mentioned agent with