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(client): evict stale create idempotency keys on TTL and non-retryable errors (#215)
cicadaf2beddcb29ba
diff --git a/src/lib/create-idempotency.ts b/src/lib/create-idempotency.tsindex 351d601..53f3c11 100644--- a/src/lib/create-idempotency.ts+++ b/src/lib/create-idempotency.ts@@ -1,4 +1,11 @@-const pending = new Map<string, string>()+export const DEFAULT_IDEMPOTENCY_TTL_MS = 60_000++interface PendingEntry {+ requestId: string+ createdAt: number+}++const pending = new Map<string, PendingEntry>()function randomRequestId(): string {if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {@@ -7,21 +14,54 @@ function randomRequestId(): string {return `req-${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`}-/** Reuse the same key after an ambiguous failure; clear only after success. */-export function pendingCreateRequestId(scope: string, normalizedInput: unknown): {+/** Reuse the same key after an ambiguous failure within TTL; clear only after success or non-retryable failure. */+export function pendingCreateRequestId(+ scope: string,+ normalizedInput: unknown,+ options?: { ttlMs?: number; now?: number },+): {requestId: stringcomplete: () => void+ fail: (error?: unknown) => void} {+ const ttlMs = options?.ttlMs ?? DEFAULT_IDEMPOTENCY_TTL_MS+ const now = options?.now ?? Date.now()const key = `${scope}:${JSON.stringify(normalizedInput)}`- let requestId = pending.get(key)- if (!requestId) {- requestId = randomRequestId()- pending.set(key, requestId)++ let entry = pending.get(key)+ if (!entry || now - entry.createdAt >= ttlMs) {+ entry = { requestId: randomRequestId(), createdAt: now }+ pending.set(key, entry)}++ const currentRequestId = entry.requestId+return {- requestId,+ requestId: currentRequestId,complete: () => {- if (pending.get(key) === requestId) pending.delete(key)+ const active = pending.get(key)+ if (active && active.requestId === currentRequestId) pending.delete(key)+ },+ fail: (error?: unknown) => {+ const status =+ typeof error === 'object' && error !== null && 'status' in error+ ? Number((error as { status: unknown }).status)+ : undefined+ const isClientError = status !== undefined && status >= 400 && status < 500+ if (error === undefined || isClientError) {+ const active = pending.get(key)+ if (active && active.requestId === currentRequestId) pending.delete(key)+ }},}}++export function clearPendingCreateRequestId(scope: string, normalizedInput: unknown): void {+ const key = `${scope}:${JSON.stringify(normalizedInput)}`+ pending.delete(key)+}++export function _resetPendingCreateRequestIdsForTests(): void {+ pending.clear()+}+diff --git a/src/stores/boards.ts b/src/stores/boards.tsindex c934020..98863c5 100644--- a/src/stores/boards.ts+++ b/src/stores/boards.ts@@ -186,12 +186,17 @@ export const useBoards = create<BoardsState>((set, get) => ({createBoard: async (title, description) => {const retry = pendingCreateRequestId('board', { title, description: description ?? null })- const r = await api.createBoard({ title, description, requestId: retry.requestId })- retry.complete()- await get().loadList()- set({ selectedId: r.id })- await get().loadBoard(r.id)- return r.id+ try {+ const r = await api.createBoard({ title, description, requestId: retry.requestId })+ retry.complete()+ await get().loadList()+ set({ selectedId: r.id })+ await get().loadBoard(r.id)+ return r.id+ } catch (err) {+ retry.fail(err)+ throw err+ }},renameBoard: async (id, title) => {diff --git a/src/stores/calendar.ts b/src/stores/calendar.tsindex c27bee5..8b5c312 100644--- a/src/stores/calendar.ts+++ b/src/stores/calendar.ts@@ -92,10 +92,15 @@ export const useCalendar = create<CalendarState>((set, get) => ({async create(input) {const retry = pendingCreateRequestId('calendar-event', input)- const { event } = await api.createCalendarEvent({ ...input, requestId: retry.requestId })- retry.complete()- set((s) => ({ events: replaceOrInsert(s.events, event) }))- return event+ try {+ const { event } = await api.createCalendarEvent({ ...input, requestId: retry.requestId })+ retry.complete()+ set((s) => ({ events: replaceOrInsert(s.events, event) }))+ return event+ } catch (err) {+ retry.fail(err)+ throw err+ }},async update(id, patch) {diff --git a/src/stores/documents.ts b/src/stores/documents.tsindex 9fccf2f..106545b 100644--- a/src/stores/documents.ts+++ b/src/stores/documents.ts@@ -43,10 +43,15 @@ export const useDocuments = create<DocumentsState>((set, get) => ({title: normalized.title ?? 'Untitled',conversationId: normalized.conversationId ?? null,})- const doc = await api.createDocument({ ...normalized, requestId: retry.requestId })- retry.complete()- set((s) => ({ list: [doc, ...s.list.filter((d) => d.id !== doc.id)], selectedId: doc.id }))- return doc+ try {+ const doc = await api.createDocument({ ...normalized, requestId: retry.requestId })+ retry.complete()+ set((s) => ({ list: [doc, ...s.list.filter((d) => d.id !== doc.id)], selectedId: doc.id }))+ return doc+ } catch (err) {+ retry.fail(err)+ throw err+ }},rename: async (id, title) => {await api.renameDocument(id, title)diff --git a/tests/create-idempotency.test.ts b/tests/create-idempotency.test.tsnew file mode 100644index 0000000..2001458--- /dev/null+++ b/tests/create-idempotency.test.ts@@ -0,0 +1,75 @@+import assert from 'node:assert/strict'+import { beforeEach, describe, it } from 'node:test'+import {+ _resetPendingCreateRequestIdsForTests,+ clearPendingCreateRequestId,+ pendingCreateRequestId,+} from '../src/lib/create-idempotency'++describe('create idempotency key management', () => {+ beforeEach(() => {+ _resetPendingCreateRequestIdsForTests()+ })++ it('reuses the same requestId for ambiguous retries within TTL', () => {+ const input = { title: 'Untitled board', description: null }+ const first = pendingCreateRequestId('board', input, { now: 10_000 })+ const second = pendingCreateRequestId('board', input, { now: 15_000 })+ assert.equal(first.requestId, second.requestId)+ })++ it('generates a fresh requestId after complete() is called', () => {+ const input = { title: 'Untitled board', description: null }+ const first = pendingCreateRequestId('board', input, { now: 10_000 })+ first.complete()+ const second = pendingCreateRequestId('board', input, { now: 10_001 })+ assert.notEqual(first.requestId, second.requestId)+ })++ it('generates a fresh requestId when TTL expires', () => {+ const input = { title: 'Untitled board', description: null }+ const first = pendingCreateRequestId('board', input, { ttlMs: 1000, now: 1000 })+ const second = pendingCreateRequestId('board', input, { ttlMs: 1000, now: 2001 })+ assert.notEqual(first.requestId, second.requestId)+ })++ it('evicts pending requestId on 4xx client errors via fail()', () => {+ const input = { title: 'Bad input' }+ const first = pendingCreateRequestId('board', input)+ first.fail({ status: 400 })+ const second = pendingCreateRequestId('board', input)+ assert.notEqual(first.requestId, second.requestId)+ })++ it('preserves pending requestId on 5xx upstream errors via fail() within TTL', () => {+ const input = { title: 'Retryable board' }+ const first = pendingCreateRequestId('board', input, { now: 10_000 })+ first.fail({ status: 502 })+ const second = pendingCreateRequestId('board', input, { now: 11_000 })+ assert.equal(first.requestId, second.requestId)+ })++ it('evicts pending requestId when fail() is called with no arguments', () => {+ const input = { title: 'Aborted board' }+ const first = pendingCreateRequestId('board', input)+ first.fail()+ const second = pendingCreateRequestId('board', input)+ assert.notEqual(first.requestId, second.requestId)+ })++ it('allows explicit clearance via clearPendingCreateRequestId', () => {+ const input = { title: 'Document 1' }+ const first = pendingCreateRequestId('document', input)+ clearPendingCreateRequestId('document', input)+ const second = pendingCreateRequestId('document', input)+ assert.notEqual(first.requestId, second.requestId)+ })++ it('separates scopes and distinct inputs', () => {+ const r1 = pendingCreateRequestId('board', { title: 'A' })+ const r2 = pendingCreateRequestId('document', { title: 'A' })+ const r3 = pendingCreateRequestId('board', { title: 'B' })+ assert.notEqual(r1.requestId, r2.requestId)+ assert.notEqual(r1.requestId, r3.requestId)+ })+})