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: ignore stale workspace request results (#57)
LILAC13222e32271b
diff --git a/server/src/__tests__/workspace-context-epoch.test.ts b/server/src/__tests__/workspace-context-epoch.test.tsnew file mode 100644index 0000000..57e8b15--- /dev/null+++ b/server/src/__tests__/workspace-context-epoch.test.ts@@ -0,0 +1,38 @@+import { test } from 'node:test'+import assert from 'node:assert/strict'+import { commitIfEpochCurrent } from '../../../src/stores/contextEpoch'++interface Deferred<T> {+ promise: Promise<T>+ resolve: (value: T) => void+}++function deferred<T>(): Deferred<T> {+ let resolve!: (value: T) => void+ const promise = new Promise<T>((done) => { resolve = done })+ return { promise, resolve }+}++test('a late request from the previous workspace cannot overwrite the current workspace', async () => {+ const requestA = deferred<string>()+ const requestB = deferred<string>()+ let contextEpoch = 0+ let stored = ''+ const commitIfCurrent = (request: () => Promise<string>) => commitIfEpochCurrent(+ () => contextEpoch,+ request,+ (value) => { stored = value },+ )++ const loadA = commitIfCurrent(() => requestA.promise)+ contextEpoch += 1+ const loadB = commitIfCurrent(() => requestB.promise)++ requestB.resolve('workspace-b data')+ assert.equal(await loadB, true)+ assert.equal(stored, 'workspace-b data')++ requestA.resolve('workspace-a data')+ assert.equal(await loadA, false)+ assert.equal(stored, 'workspace-b data')+})diff --git a/src/stores/auth.ts b/src/stores/auth.tsindex 16fe2e7..19e6ed4 100644--- a/src/stores/auth.ts+++ b/src/stores/auth.ts@@ -5,6 +5,7 @@*/import { create } from 'zustand'import type { ServerCapabilities } from '@/api/client'+import { commitIfEpochCurrent } from './contextEpoch'export interface AuthCompany {id: string@@ -30,6 +31,9 @@ interface AuthState {user: AuthUser | nullcompanies: AuthCompany[]activeCompanyId: string | null+ /** Monotonic identity/workspace generation used to reject async results+ * that were started before the current auth context was selected. */+ contextEpoch: numberready: boolean // false until the initial /auth/me probe finishes/** Server-driven feature flags. Null until the first /auth/me probe* populates them; consumers should treat null as "don't know yet" and@@ -52,12 +56,13 @@ export const useAuth = create<AuthState>((set) => ({user: null,companies: [],activeCompanyId: localStorage.getItem(COMPANY_KEY),+ contextEpoch: 0,ready: false,serverCapabilities: null,setSession(token, user, companyId) {localStorage.setItem(TOKEN_KEY, token)if (companyId) localStorage.setItem(COMPANY_KEY, companyId)- set({ token, user, activeCompanyId: companyId, ready: true })+ set((s) => ({ token, user, activeCompanyId: companyId, ready: true, contextEpoch: s.contextEpoch + 1 }))// Fresh auth → rebind the WS connection so it carries the new// session's ticket instead of staying on whatever it had before.void import('@/api/client').then(({ ws }) => ws.reconnect())@@ -72,7 +77,14 @@ export const useAuth = create<AuthState>((set) => ({? stored: (activeCompanyId && memberIds.has(activeCompanyId) ? activeCompanyId : (companies[0]?.id ?? null))if (resolved) localStorage.setItem(COMPANY_KEY, resolved)- set({ user, companies, activeCompanyId: resolved })+ set((s) => ({+ user,+ companies,+ activeCompanyId: resolved,+ contextEpoch: s.user?.id !== user.id || s.activeCompanyId !== resolved+ ? s.contextEpoch + 1+ : s.contextEpoch,+ }))},setServerCapabilities(caps) {set({ serverCapabilities: caps })@@ -80,7 +92,7 @@ export const useAuth = create<AuthState>((set) => ({setActiveCompany(id) {if (useAuth.getState().activeCompanyId === id) returnlocalStorage.setItem(COMPANY_KEY, id)- set({ activeCompanyId: id })+ set((s) => ({ activeCompanyId: id, contextEpoch: s.contextEpoch + 1 }))// Force the WS connection to re-handshake. The bridge filters events// by company-membership which is the same regardless of "active"// company, but logging in / switching identities should still rebind@@ -101,7 +113,11 @@ export const useAuth = create<AuthState>((set) => ({/** Append a freshly-created company to the user's set and switch to it. */addCompany(c) {const prevId = useAuth.getState().activeCompanyId- set((s) => ({ companies: [...s.companies, c], activeCompanyId: c.id }))+ set((s) => ({+ companies: [...s.companies, c],+ activeCompanyId: c.id,+ contextEpoch: s.activeCompanyId === c.id ? s.contextEpoch : s.contextEpoch + 1,+ }))localStorage.setItem(COMPANY_KEY, c.id)// If this is a SWITCH (we already had a company), wipe library// stores too so the new workspace doesn't render the previous@@ -118,7 +134,15 @@ export const useAuth = create<AuthState>((set) => ({clear() {localStorage.removeItem(TOKEN_KEY)localStorage.removeItem(COMPANY_KEY)- set({ token: null, user: null, companies: [], activeCompanyId: null, ready: true, serverCapabilities: null })+ set((s) => ({+ token: null,+ user: null,+ companies: [],+ activeCompanyId: null,+ ready: true,+ serverCapabilities: null,+ contextEpoch: s.contextEpoch + 1,+ }))// Stale object-URLs from the previous user's avatars would otherwise// linger; clear them so the next sign-in doesn't briefly render a// dead URL.createObjectURL pointing at a freed blob.@@ -163,3 +187,16 @@ export function useMe(): string | null {export function getActiveCompanyId(): string | null {return useAuth.getState().activeCompanyId}++/** Run a request against the current auth/workspace context and commit its+ * result only if that context is still active when the request completes. */+export async function commitIfContextCurrent<T>(+ request: () => Promise<T>,+ commit: (value: T) => void,+): Promise<boolean> {+ return commitIfEpochCurrent(+ () => useAuth.getState().contextEpoch,+ request,+ commit,+ )+}diff --git a/src/stores/computers.ts b/src/stores/computers.tsindex e957adb..0166f4b 100644--- a/src/stores/computers.ts+++ b/src/stores/computers.ts@@ -1,6 +1,7 @@import { create } from 'zustand'import { api, ws, type ApiComputer } from '@/api/client'import type { Computer, ComputerStatus } from '@/types'+import { commitIfContextCurrent } from '@/stores/auth'interface ComputersState {byId: Record<string, Computer>@@ -31,10 +32,11 @@ function fromApi(c: ApiComputer): Computer {async function fetchInto(set: (partial: Partial<ComputersState>) => void): Promise<void> {try {- const list = await api.getComputers()- const byId: Record<string, Computer> = {}- for (const c of list) byId[c.id] = fromApi(c)- set({ byId, loaded: true })+ await commitIfContextCurrent(() => api.getComputers(), (list) => {+ const byId: Record<string, Computer> = {}+ for (const c of list) byId[c.id] = fromApi(c)+ set({ byId, loaded: true })+ })} catch (err) {console.warn('[computers] fetch failed', err)}diff --git a/src/stores/contextEpoch.ts b/src/stores/contextEpoch.tsnew file mode 100644index 0000000..3600e71--- /dev/null+++ b/src/stores/contextEpoch.ts@@ -0,0 +1,12 @@+/** Commit an async result only while the context that started it is current. */+export async function commitIfEpochCurrent<T>(+ getEpoch: () => number,+ request: () => Promise<T>,+ commit: (value: T) => void,+): Promise<boolean> {+ const epoch = getEpoch()+ const value = await request()+ if (getEpoch() !== epoch) return false+ commit(value)+ return true+}diff --git a/src/stores/conversations.ts b/src/stores/conversations.tsindex b1cc225..8aa3fb9 100644--- a/src/stores/conversations.ts+++ b/src/stores/conversations.ts@@ -2,7 +2,7 @@ import { create } from 'zustand'import { api, ws, type ApiConversation } from '@/api/client'import type { Conversation } from '@/types'import { useApp } from '@/stores/app'-import { useAuth } from '@/stores/auth'+import { commitIfContextCurrent, useAuth } from '@/stores/auth'import { useMessages } from '@/stores/messages'import { useParticipants } from '@/stores/participants'@@ -185,20 +185,22 @@ export const useConversations = create<ConversationsState>((set) => ({// previous tenant's conversations during the loading window.set({ list: [], loaded: false })try {- const list = await api.getConversations()- const conversations = list.map(fromApi)- set({ list: conversations, loaded: true })- refreshActiveMessagesIfSidebarMoved(conversations)+ await commitIfContextCurrent(() => api.getConversations(), (list) => {+ const conversations = list.map(fromApi)+ set({ list: conversations, loaded: true })+ refreshActiveMessagesIfSidebarMoved(conversations)+ })} catch (err) {console.warn('[conversations] load failed', err)}},async reload() {try {- const list = await api.getConversations()- const conversations = list.map(fromApi)- set({ list: conversations })- refreshActiveMessagesIfSidebarMoved(conversations)+ await commitIfContextCurrent(() => api.getConversations(), (list) => {+ const conversations = list.map(fromApi)+ set({ list: conversations })+ refreshActiveMessagesIfSidebarMoved(conversations)+ })} catch (err) {console.warn('[conversations] reload failed', err)}diff --git a/src/stores/participants.ts b/src/stores/participants.tsindex 7ef0df3..14ce6eb 100644--- a/src/stores/participants.ts+++ b/src/stores/participants.ts@@ -2,6 +2,7 @@ import { create } from 'zustand'import { api, ws, type ApiParticipant } from '@/api/client'import type { Participant, Status } from '@/types'import { invalidateAvatar, clearAvatarCache } from '@/lib/avatarCache'+import { commitIfContextCurrent } from '@/stores/auth'interface ParticipantsState {byId: Record<string, Participant>@@ -40,10 +41,11 @@ function normalizeStatus(status: Status, updatedAt?: string): Status {* difference is whether they pre-clear state. */async function fetchInto(set: (partial: Partial<ParticipantsState>) => void): Promise<void> {try {- const list = await api.getParticipants()- const byId: Record<string, Participant> = {}- for (const p of list) byId[p.id] = fromApi(p)- set({ byId, loaded: true })+ await commitIfContextCurrent(() => api.getParticipants(), (list) => {+ const byId: Record<string, Participant> = {}+ for (const p of list) byId[p.id] = fromApi(p)+ set({ byId, loaded: true })+ })} catch (err) {console.warn('[participants] fetch failed', err)}diff --git a/src/stores/whispers.ts b/src/stores/whispers.tsindex 084a633..65b05b0 100644--- a/src/stores/whispers.ts+++ b/src/stores/whispers.ts@@ -11,6 +11,7 @@*/import { create } from 'zustand'import { api, ws, type ApiWhisper, type ApiWhisperMessage } from '@/api/client'+import { commitIfContextCurrent } from '@/stores/auth'export interface WhispersState {list: ApiWhisper[]@@ -41,8 +42,10 @@ export const useWhispers = create<WhispersState>((set) => ({// tenant's peek list + per-pair message cache before fetching fresh.set({ list: [], byId: {}, streaming: {}, loaded: false })try {- const list = await api.getWhispers()- set({ list, loaded: true })+ await commitIfContextCurrent(+ () => api.getWhispers(),+ (list) => set({ list, loaded: true }),+ )} catch (err) {console.warn('[whispers] loadList failed', err)}@@ -53,8 +56,10 @@ export const useWhispers = create<WhispersState>((set) => ({// handlers call this so the per-conversation `byId` cache doesn't// get wiped (which would flash the open thread empty).try {- const list = await api.getWhispers()- set({ list, loaded: true })+ await commitIfContextCurrent(+ () => api.getWhispers(),+ (list) => set({ list, loaded: true }),+ )} catch (err) {console.warn('[whispers] refreshList failed', err)}@@ -62,8 +67,10 @@ export const useWhispers = create<WhispersState>((set) => ({async loadMessages(id) {try {- const msgs = await api.getWhisperMessages(id)- set((s) => ({ byId: { ...s.byId, [id]: msgs } }))+ await commitIfContextCurrent(+ () => api.getWhisperMessages(id),+ (msgs) => set((s) => ({ byId: { ...s.byId, [id]: msgs } })),+ )} catch (err) {console.warn('[whispers] loadMessages failed', err)}