// The chat store (useChat) outside Nuxt: the auto-imported composables // (useState, useNuxtApp, useChatApi, useChatAuth, useChatConfig, // useChatNotice) are stubbed globals over a fresh state per test, the API // client is a fake and the realtime client is the layer's module with the // network parts replaced (subscribe, connection and unavailable listeners, // presence); onUserEvent and dispatchUserEvent stay real. The scenarios // follow the SPA store's tests (bm's stores/chat.test.ts) for the // multi-channel store. import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { ref } from 'vue' import { ChatApiError } from '../app/lib/client' import { dmActionsTarget } from '../app/lib/slots' import type { ChatChannel, ChatConversationRow, ChatMessage } from '../app/lib/types' const rt = vi.hoisted(() => ({ subs: new Map void; onSubscribed?: () => void; closed: boolean }>(), connection: [] as Array<(s: string) => void>, unavailable: [] as Array<() => void>, })) vi.mock('../app/lib/realtime', async (importOriginal) => { const real = await importOriginal() return { ...real, setRealtimeAuth: vi.fn(), hasRealtimeAuth: () => true, disconnect: vi.fn(), presence: vi.fn(async () => []), onConnection: (fn: (s: string) => void) => { rt.connection.push(fn) return () => {} }, onUnavailable: (fn: () => void) => { rt.unavailable.push(fn) return () => {} }, subscribe: vi.fn(async (channel: string, hooks: { onPublication?: (d: unknown) => void; onSubscribed?: () => void }) => { const entry = { ...hooks, closed: false } rt.subs.set(channel, entry) return { close: () => (entry.closed = true) } }), } }) const { useChat, POLL_ACTIVE_MS, POLL_COUNTS_MS } = await import('../app/composables/useChat') const { useChatNotice } = await import('../app/composables/useChatNotice') const { onUserEvent } = await import('../app/lib/realtime') const ME = 7 const CONTEXT = { type: 'acme', id: 1 } function channel(id: number, conv: number, over: Partial = {}): ChatChannel { return { id, slug: `c${id}`, name: `c${id}`, conversation_id: conv, joined: true, unread: 0, mentions: 0, ...over } } function dm(id: number, other: number, over: Partial = {}): ChatConversationRow { return { id, type: 'dm', other_user_id: other, unread: 0, last_message: null, ...over } } function msg(id: number, conv: number, over: Partial = {}): ChatMessage { return { id, conversation_id: conv, sender_id: 9, sender_name: 'Ada', sender_avatar: null, content: `message ${id}`, type: 'text', attachments: [], created_at: new Date(Date.UTC(2026, 10, 1, 12, 0, id)).toISOString(), created_at_human: '', edited_at: null, deleted_at: null, is_mine: false, root_id: null, reactions: [], ...over, } } function bootstrapAnswer(left: Set = new Set([2])) { return { member: true, moderator: false, context: CONTEXT, channels: [channel(1, 100), channel(2, 200), channel(3, 300, { unread: 2, mentions: 1 })].map((c) => ({ ...c, joined: !left.has(c.id) })), conversations: [dm(400, 9, { unread: 1 })], limits: { max_files: 5, max_bytes: 5242880, max_embeds: 3 }, } } /** The fake server remembers the channels the caller left (channel 2 at first). */ function fakeApi() { const left = new Set([2]) return { bootstrap: vi.fn(async () => bootstrapAnswer(left) as unknown), members: vi.fn(async () => [{ id: 9, name: 'Ada', surname: 'Hart', handle: 'ada', is_bot: false }]), reactions: vi.fn(async () => ['👍', '❤️']), messages: vi.fn(async (conv: number) => [msg(conv + 1, conv), msg(conv + 2, conv)]), openConversation: vi.fn(async (_t: string, id: number) => ({ id: id * 100, type: 'group' })), joinChannel: vi.fn(async (_ctx: unknown, id: number) => (left.delete(id), {})), leaveChannel: vi.fn(async (_ctx: unknown, id: number) => (left.add(id), {})), send: vi.fn(async (conv: number, body: { content: string }) => msg(999, conv, { sender_id: ME, content: body.content, is_mine: true })), message: vi.fn(async (id: number) => msg(id, 100)), markRead: vi.fn(async () => ({})), typing: vi.fn(async () => ({})), startDm: vi.fn(async () => ({ id: 500, type: 'dm' })), replies: vi.fn(async (root: number) => [msg(root + 50, 100, { root_id: root })]), reply: vi.fn(async (root: number, body: { content: string }) => msg(888, 100, { root_id: root, sender_id: ME, content: body.content })), muteThread: vi.fn(async (_root: number, muted: boolean) => ({ root_id: _root, is_muted: muted })), pins: vi.fn(async () => [101]), pin: vi.fn(async () => ({})), unpin: vi.fn(async () => ({})), addReaction: vi.fn(async () => ({ reactions: [{ key: '👍', count: 1, user_ids: [ME] }] })), removeReaction: vi.fn(async () => ({ reactions: [] })), commands: vi.fn(async () => [{ trigger: 'demo', description: 'What this demo shows' }]), dispatch: vi.fn(async (input: string) => ({ mode: 'ephemeral', payload: { content: `answer to ${input}` } })), edit: vi.fn(), remove: vi.fn(), upload: vi.fn(), download: vi.fn(), } } let api: ReturnType let config: { apiBase: string; channelsApiBase: string; botsApiBase: string; hostApiBase: string } beforeEach(() => { const state = new Map>() const nuxtApp = {} api = fakeApi() config = { apiBase: '/_chat/api/v1', channelsApiBase: '/_chatchannels/api/v1', botsApiBase: '/_chatbots/api/v1', hostApiBase: '/_acme/api/v1' } rt.subs.clear() rt.connection.length = 0 rt.unavailable.length = 0 vi.stubGlobal('useState', (key: string, init?: () => unknown) => { if (!state.has(key)) state.set(key, ref(init ? init() : undefined)) return state.get(key) }) vi.stubGlobal('useNuxtApp', () => nuxtApp) vi.stubGlobal('useChatApi', () => api) vi.stubGlobal('useChatAuth', () => ({ token: () => 'jwt', userId: () => ME })) vi.stubGlobal('useChatConfig', () => config) vi.stubGlobal('useChatNotice', useChatNotice) }) afterEach(() => { vi.useRealTimers() vi.unstubAllGlobals() }) /** Lets pending promise chains settle. */ async function flush() { for (let i = 0; i < 10; i++) await Promise.resolve() } async function started() { const chat = useChat() await chat.start() await flush() return chat } /** Publishes data on a subscribed channel. */ function publish(channel: string, data: unknown) { const sub = rt.subs.get(channel) if (!sub?.onPublication) throw new Error(`no subscription on ${channel}`) sub.onPublication(data) } describe('start and bootstrap', () => { it('fills channels, DMs, limits and members, and subscribes user:{me}', async () => { const chat = await started() expect(api.bootstrap).toHaveBeenCalledTimes(1) expect(chat.member).toBe(true) expect(chat.userId).toBe(ME) expect(chat.context).toEqual(CONTEXT) expect(chat.channels.map((c) => c.id)).toEqual([1, 2, 3]) expect(chat.joinedChannels.map((c) => c.id)).toEqual([1, 3]) expect(chat.conversations.map((c) => c.id)).toEqual([400]) expect(chat.limits?.max_embeds).toBe(3) expect(chat.members.get(9)?.handle).toBe('ada') expect(chat.dmUnread).toBe(1) expect(chat.channelUnread).toBe(2) expect(chat.attention).toBe(2) expect(rt.subs.has(`user:${ME}`)).toBe(true) expect(chat.connection).toBe('connecting') }) it('starts nothing without a host API base', async () => { config.hostApiBase = '' const error = vi.spyOn(console, 'error').mockImplementation(() => {}) const chat = await started() expect(api.bootstrap).not.toHaveBeenCalled() expect(rt.subs.size).toBe(0) expect(chat.member).toBeUndefined() expect(error).toHaveBeenCalledWith(expect.stringContaining('hostApiBase')) error.mockRestore() }) it('starts nothing for a non-member bootstrap', async () => { api.bootstrap.mockResolvedValueOnce({ member: false }) const chat = await started() expect(chat.member).toBe(false) expect(chat.channels).toEqual([]) expect(api.members).not.toHaveBeenCalled() expect(rt.subs.size).toBe(0) expect(chat.attention).toBe(0) }) it('starts nothing without a user', async () => { vi.stubGlobal('useChatAuth', () => ({ token: () => null })) const chat = await started() expect(api.bootstrap).not.toHaveBeenCalled() expect(chat.userId).toBeNull() }) }) describe('channels and DMs', () => { it('opening a joined channel runs its conversation route once a session and loads its page', async () => { const chat = await started() await chat.openChannel(chat.channels[0]) expect(api.joinChannel).not.toHaveBeenCalled() expect(api.openConversation).toHaveBeenCalledWith('channel', 1) expect(api.messages).toHaveBeenCalledWith(100, { limit: 50 }) expect(chat.activeId).toBe(100) expect(chat.kind).toBe('channel') expect(chat.activeChannel?.id).toBe(1) expect(chat.messages[100].map((m) => m.id)).toEqual([101, 102]) expect(rt.subs.has('chat:conversation:100')).toBe(true) await chat.openChannel(chat.channels[0]) expect(api.openConversation).toHaveBeenCalledTimes(1) expect(api.messages).toHaveBeenCalledTimes(1) }) it('opening a left channel joins it first (lazy join)', async () => { const chat = await started() await chat.openChannel(chat.channels[1]) expect(api.joinChannel).toHaveBeenCalledWith(CONTEXT, 2) expect(api.openConversation).toHaveBeenCalledWith('channel', 2) expect(chat.channels[1].joined).toBe(true) expect(chat.activeId).toBe(200) }) it('leaving the open channel closes it and keeps it listed', async () => { const chat = await started() await chat.openChannel(chat.channels[0]) await chat.leaveChannel(chat.channels[0]) await flush() expect(api.leaveChannel).toHaveBeenCalledWith(CONTEXT, 1) expect(chat.channels.map((c) => c.id)).toEqual([1, 2, 3]) expect(chat.channels[0].joined).toBe(false) expect(chat.joinedChannels.map((c) => c.id)).toEqual([3]) expect(chat.activeId).toBeNull() expect(rt.subs.get('chat:conversation:100')?.closed).toBe(true) }) it('a refused channel open shows a notice and opens nothing', async () => { api.openConversation.mockRejectedValueOnce(new ChatApiError(404, 'Not found')) const chat = await started() expect(await chat.openChannel(chat.channels[0])).toBe(false) expect(chat.activeId).toBeNull() expect(useChatNotice().current.value?.key).toBe('error.openChannel') }) it('opens an existing DM, or creates one with a member', async () => { const chat = await started() expect(await chat.startDm(9)).toBe(400) expect(api.startDm).not.toHaveBeenCalled() expect(chat.kind).toBe('dm') expect(await chat.startDm(11)).toBe(500) expect(api.startDm).toHaveBeenCalledWith(CONTEXT, 11) expect(chat.conversations[0]).toMatchObject({ id: 500, type: 'dm', other_user_id: 11 }) api.startDm.mockRejectedValueOnce(new ChatApiError(429, 'Too many')) expect(await chat.startDm(12)).toBeNull() expect(chat.dmError).toBe('error.tooManyDms') }) it('the conversation-actions slot is for DMs only', async () => { const chat = await started() await chat.openChannel(chat.channels[0]) expect(chat.activeDm).toBeNull() expect(dmActionsTarget(chat.activeDm)).toBeNull() await chat.openDm(400) expect(chat.activeChannel).toBeNull() expect(dmActionsTarget(chat.activeDm)?.id).toBe(400) expect(dmActionsTarget({ ...dm(1, 2), type: 'group' })).toBeNull() expect(dmActionsTarget(undefined)).toBeNull() }) }) describe('realtime', () => { it('a message from someone else counts as unread elsewhere and appends in the open conversation', async () => { const chat = await started() await chat.openChannel(chat.channels[0]) chat.panelVisible = true // In another channel: unread +1, nothing loaded there. publish(`user:${ME}`, { event: 'chat:message', payload: { conversation_id: 300, message: msg(301, 300) } }) expect(chat.channels[2].unread).toBe(3) // In the open, visible channel: appended, no unread. publish(`user:${ME}`, { event: 'chat:message', payload: { conversation_id: 100, message: msg(150, 100) } }) expect(chat.messages[100].map((m) => m.id)).toEqual([101, 102, 150]) expect(chat.channels[0].unread).toBe(0) // In a DM: the row's count and preview. publish(`user:${ME}`, { event: 'chat:message', payload: { conversation_id: 400, message: msg(401, 400, { content: 'hi there' }) } }) expect(chat.conversations.find((c) => c.id === 400)).toMatchObject({ unread: 2, last_message: { id: 401, content: 'hi there' } }) // The same message twice is not listed twice. publish(`user:${ME}`, { event: 'chat:message', payload: { conversation_id: 100, message: msg(150, 100) } }) expect(chat.messages[100].filter((m) => m.id === 150)).toHaveLength(1) }) it('a hidden open conversation still counts the message as unread', async () => { const chat = await started() await chat.openChannel(chat.channels[0]) publish(`user:${ME}`, { event: 'chat:message', payload: { conversation_id: 100, message: msg(160, 100) } }) expect(chat.channels[0].unread).toBe(1) expect(chat.messages[100].at(-1)?.id).toBe(160) }) it('a content-free created event fetches the message of a loaded conversation', async () => { const chat = await started() await chat.openChannel(chat.channels[0]) api.message.mockResolvedValueOnce(msg(170, 100)) publish('chat:conversation:100', { event: 'created.chat.message', payload: { id: 170, conversation_id: 100, sender_id: 9 } }) await flush() expect(api.message).toHaveBeenCalledWith(170) expect(chat.messages[100].at(-1)?.id).toBe(170) }) it('typing, reactions, edits and deletions patch the open conversation', async () => { const chat = await started() await chat.openChannel(chat.channels[0]) rt.connection.forEach((fn) => fn('connected')) publish('chat:conversation:100', { event: 'typing.chat.message', payload: { action: 'typing-start', conversation_id: 100, user_id: 9 } }) expect(chat.typingIn(100)).toEqual([9]) publish('chat:conversation:100', { event: 'reacted.chat.message', payload: { id: 101, conversation_id: 100, user_id: 9, key: '👍', action: 'added' } }) expect(chat.findMessage(100, 101)?.reactions?.[0]).toMatchObject({ key: '👍', user_ids: [9] }) publish('chat:conversation:100', { event: 'deleted.chat.message', payload: { id: 102, conversation_id: 100 } }) expect(chat.findMessage(100, 102)).toMatchObject({ content: null }) expect(chat.findMessage(100, 102)?.deleted_at).toBeTruthy() api.message.mockResolvedValueOnce(msg(101, 100, { content: 'edited', edited_at: new Date().toISOString() })) publish('chat:conversation:100', { event: 'updated.chat.message', payload: { id: 101, conversation_id: 100 } }) await flush() expect(chat.findMessage(100, 101)?.content).toBe('edited') }) it('hands events it does not handle on user:{me} to onUserEvent', async () => { const seen: unknown[] = [] const off = onUserEvent((d) => seen.push(d)) await started() const call = { event: 'video:call:incoming', payload: { session_id: 5, conversation_id: 400, caller_id: 9 } } publish(`user:${ME}`, call) publish(`user:${ME}`, { event: 'chat:message', payload: { conversation_id: 400, message: msg(402, 400) } }) off() expect(seen).toEqual([call]) }) it('polls the open conversation and the counts when realtime is unavailable', async () => { vi.useFakeTimers() const chat = useChat() await chat.start() await vi.advanceTimersByTimeAsync(0) await chat.openChannel(chat.channels[0]) expect(api.messages).toHaveBeenCalledTimes(1) rt.unavailable.forEach((fn) => fn()) expect(chat.connection).toBe('unavailable') expect(chat.typingIn(100)).toEqual([]) await vi.advanceTimersByTimeAsync(POLL_ACTIVE_MS) expect(api.messages).toHaveBeenCalledTimes(2) const boots = api.bootstrap.mock.calls.length await vi.advanceTimersByTimeAsync(POLL_COUNTS_MS - POLL_ACTIVE_MS) expect(api.bootstrap.mock.calls.length).toBeGreaterThan(boots) chat.reset() }) it('reset forgets the session and closes the subscriptions', async () => { const chat = await started() await chat.openChannel(chat.channels[0]) chat.reset() expect(chat.member).toBeUndefined() expect(chat.channels).toEqual([]) expect(chat.messages).toEqual({}) expect(rt.subs.get(`user:${ME}`)?.closed).toBe(true) expect(rt.subs.get('chat:conversation:100')?.closed).toBe(true) }) }) describe('sending', () => { it('posts the trimmed draft and appends the answer', async () => { const chat = await started() await chat.openChannel(chat.channels[0]) chat.setDraftText(100, ' hello ') expect(chat.canSend(100)).toBe(true) expect(await chat.send()).toBe(true) expect(api.send).toHaveBeenCalledWith(100, { content: 'hello' }) expect(chat.draft(100).text).toBe('') expect(chat.messages[100].at(-1)?.id).toBe(999) }) it('keeps the draft with the refusal of a 422', async () => { const chat = await started() await chat.openChannel(chat.channels[0]) api.send.mockRejectedValueOnce(new ChatApiError(422, 'Validation failed', { content: ['The text contains a word that is not allowed.'] })) chat.setDraftText(100, 'blocked') expect(await chat.send()).toBe(false) expect(chat.draft(100)).toMatchObject({ text: 'blocked', error: 'error.refused', detail: 'The text contains a word that is not allowed.' }) }) it('dispatches a slash command instead of posting it; the answer stays local', async () => { const chat = await started() await chat.openChannel(chat.channels[0]) chat.setDraftText(100, '/demo') expect(await chat.send()).toBe(true) expect(api.dispatch).toHaveBeenCalledWith('/demo') expect(api.send).not.toHaveBeenCalled() expect(chat.ephemeral[100]).toEqual([{ id: expect.any(Number), input: '/demo', text: 'answer to /demo', error: '' }]) expect(chat.draft(100).text).toBe('') expect(chat.messages[100].map((m) => m.id)).toEqual([101, 102]) chat.dismissEphemeral(100, chat.ephemeral[100][0].id) expect(chat.ephemeral[100]).toEqual([]) }) it('an unknown command becomes an error row', async () => { const chat = await started() await chat.openChannel(chat.channels[0]) api.dispatch.mockRejectedValueOnce(new ChatApiError(422, 'Validation failed', { input: ['Unknown command /nope'] })) chat.setDraftText(100, '/nope') expect(await chat.send()).toBe(true) expect(chat.ephemeral[100][0]).toMatchObject({ input: '/nope', text: '', error: 'Unknown command /nope' }) expect(api.send).not.toHaveBeenCalled() }) it('loads the command catalog once a session', async () => { const chat = await started() await Promise.all([chat.loadCommands(), chat.loadCommands()]) await chat.loadCommands() expect(api.commands).toHaveBeenCalledTimes(1) expect(chat.commands?.map((c) => c.trigger)).toEqual(['demo']) }) }) describe('threads', () => { it('loads replies, posts a reply and counts it on the root once', async () => { const chat = await started() await chat.openChannel(chat.channels[0]) const root = chat.findMessage(100, 101)! await chat.openThread(root) expect(api.replies).toHaveBeenCalledWith(101) expect(chat.thread).toEqual({ rootId: 101, conversationId: 100 }) expect(chat.replies[101].map((m) => m.id)).toEqual([151]) chat.setThreadDraftText(101, ' my reply ') expect(await chat.sendReply(101)).toBe(true) expect(api.reply).toHaveBeenCalledWith(101, { content: 'my reply' }) expect(chat.replies[101].map((m) => m.id)).toEqual([151, 888]) expect(chat.findMessage(100, 101)?.thread_summary?.reply_count).toBe(1) // The reply's own realtime echo is not counted again. publish(`user:${ME}`, { event: 'chat:message', payload: { conversation_id: 100, message: msg(888, 100, { root_id: 101, sender_id: ME }) } }) expect(chat.findMessage(100, 101)?.thread_summary?.reply_count).toBe(1) // Someone else's reply counts and lands in the open thread. publish(`user:${ME}`, { event: 'chat:message', payload: { conversation_id: 100, message: msg(889, 100, { root_id: 101 }) } }) expect(chat.findMessage(100, 101)?.thread_summary).toMatchObject({ reply_count: 2, participant_ids: [ME, 9] }) expect(chat.replies[101].map((m) => m.id)).toEqual([151, 888, 889]) // Replies stay out of the main list. expect(chat.messages[100].map((m) => m.id)).toEqual([101, 102]) chat.closeThread() expect(chat.thread).toBeNull() }) it('mutes a thread with the server answer', async () => { const chat = await started() expect(await chat.setThreadMute(101, true)).toBe(true) expect(chat.threadMuted[101]).toBe(true) api.muteThread.mockRejectedValueOnce(new ChatApiError(500, 'boom')) expect(await chat.setThreadMute(101, false)).toBe(false) expect(chat.threadMuted[101]).toBe(true) }) }) describe('pins and reactions', () => { it('loads a channel\'s pins and pins or unpins a message', async () => { const chat = await started() await chat.openChannel(chat.channels[0]) await chat.loadPins(chat.channels[0]) expect(api.pins).toHaveBeenCalledWith(CONTEXT, 1) expect(chat.pinIds[1]).toEqual([101]) expect(chat.pinMessages[1].map((m) => m.id)).toEqual([101]) expect(chat.isPinned(chat.findMessage(100, 101)!)).toBe(true) expect(chat.isPinned(chat.findMessage(100, 102)!)).toBe(false) api.pins.mockResolvedValueOnce([101, 102]) expect(await chat.togglePin(chat.findMessage(100, 102)!)).toBe(true) expect(api.pin).toHaveBeenCalledWith(CONTEXT, 1, 102) expect(chat.pinIds[1]).toEqual([101, 102]) api.pins.mockResolvedValueOnce([102]) await chat.togglePin(chat.findMessage(100, 101)!) expect(api.unpin).toHaveBeenCalledWith(CONTEXT, 1, 101) }) it('a refused pin hides the action for the session', async () => { const chat = await started() await chat.openChannel(chat.channels[0]) api.pin.mockRejectedValueOnce(new ChatApiError(403, 'Forbidden')) expect(await chat.togglePin(chat.findMessage(100, 102)!)).toBe(false) expect(chat.pinAllowed).toBe(false) }) it('toggles the user\'s reaction and takes the server\'s chips', async () => { const chat = await started() await chat.openChannel(chat.channels[0]) await chat.toggleReaction({ id: 101, conversation_id: 100 }, '👍') expect(api.addReaction).toHaveBeenCalledWith(101, '👍') expect(chat.findMessage(100, 101)?.reactions).toEqual([{ key: '👍', count: 1, user_ids: [ME] }]) await chat.toggleReaction({ id: 101, conversation_id: 100 }, '👍') expect(api.removeReaction).toHaveBeenCalledWith(101, '👍') expect(chat.findMessage(100, 101)?.reactions).toEqual([]) }) it('rolls a failed reaction back', async () => { const chat = await started() await chat.openChannel(chat.channels[0]) api.addReaction.mockRejectedValueOnce(new ChatApiError(500, 'boom')) await chat.toggleReaction({ id: 101, conversation_id: 100 }, '❤️') expect(chat.findMessage(100, 101)?.reactions ?? []).toEqual([]) expect(useChatNotice().current.value?.key).toBe('error.reactionAdd') }) })