// The chat store, ported from a Golem15 SPA's Pinia setup store as a // composable over useState keys prefixed chat: (no Pinia). The SPA's one // group conversation became the host's list of channels: `channels`, // `activeId` (the open conversation) and `kind` ('channel' or 'dm'). // // One store per Nuxt app; every component that calls useChat() shares it. // It runs in the browser only (start() does nothing on the server). // // Realtime: user:{me} for the whole member session (messages from others in // any conversation, read marks, mention changes; every other event goes to // onUserEvent handlers), and the open conversation's channel while it is // open (created, typing, reactions, edits, deletions, presence). Without // realtime the open conversation is polled every 15 s and the counts every // 60 s. // // On top of the ported store: threads (replies, thread mute), channel pins, // reactions, attachments, edits, deletes (a moderator also deletes other // people's messages in channels) and slash commands (golem15.chatbots: a // message starting with / is dispatched, never posted; an ephemeral answer // is a local row only the sender sees). import { computed, reactive, ref, shallowRef } from 'vue' import { ChatApiError, userIdFromToken } from '../lib/client' import { checkFiles, type FileCheckMessages } from '../lib/attachments' import { applyChatMessage, applyReaction, needsFetch, parsePublication, type ChatEvent } from '../lib/chatEvents' import { setFormatLocale } from '../lib/format' import { disconnect as disconnectRealtime, dispatchUserEvent, hasRealtimeAuth, onConnection, onUnavailable, presence as fetchPresence, setRealtimeAuth, subscribe, type ChannelHandle, type ConnectionState, type PresenceClient, } from '../lib/realtime' import type { ChatAttachment, ChatChannel, ChatCommand, ChatConversationRow, ChatLimits, ChatMember, ChatMessage, ChatSendBody } from '../lib/types' export interface ChatDraft { text: string /** The send error line (an i18n key under chat.), cleared on the next input or send. */ error: string /** A server message shown with the error (a 422 field error), or ''. */ detail: string sending: boolean /** Staged attachments, uploaded as soon as they are picked. */ files: StagedFile[] } /** An attachment chip: uploading with progress, done with its pending id, or failed. */ export interface StagedFile { localId: number name: string size: number /** 0 to 100. */ progress: number state: 'uploading' | 'done' | 'failed' /** The pending attachment id once uploaded. */ id: number | null } /** A slash command's answer shown to the sender only, under the conversation. */ export interface ChatEphemeral { id: number input: string /** The answer text (rendered escaped), or '' for an error row. */ text: string /** The refusal (an unknown command, for example), or ''. */ error: string } /** The open thread. */ export interface ChatThread { rootId: number conversationId: number } /** Where a list was scrolled: restored when the list mounts again. */ export interface ChatAnchor { atBottom: boolean /** The first visible message. */ messageId: number | null /** Its top relative to the list's scrollTop. */ offset: number } /** The open conversation's kind. */ export type ChatKind = 'channel' | 'dm' /** * The chat's realtime link: connecting (first connect), connected, * reconnecting (SDK backoff), unavailable (token refused for good, or no * realtime at all: the chat polls). idle before a member session starts it. */ export type ChatConnection = 'idle' | 'connecting' | 'connected' | 'reconnecting' | 'unavailable' /** Without realtime the open conversation is polled every 15 s and the counts every 60 s. */ export const POLL_ACTIVE_MS = 15_000 export const POLL_COUNTS_MS = 60_000 /** One read POST per conversation within this window. */ export const READ_DEBOUNCE_MS = 500 export const MESSAGE_PAGE = 50 /** The composer emits typing at most once every 3 s per conversation. */ export const TYPING_THROTTLE_MS = 3_000 /** A typing entry expires 6 s after that person's last typing event. */ export const TYPING_EXPIRY_MS = 6_000 const EMPTY_DRAFT: Readonly = Object.freeze({ text: '', error: '', detail: '', sending: false, files: Object.freeze([]) as unknown as StagedFile[], }) /** The fallback limits before the bootstrap answers (golem15.chat MaxAttachments, 5 MiB). */ const DEFAULT_FILE_LIMITS = { max_files: 5, max_bytes: 5 * 1024 * 1024 } /** The send-error key (chat.error.*) for a failed POST. */ export function sendErrorKey(e: unknown): string { const status = e instanceof ChatApiError ? e.status : -1 if (status === 0) return 'error.offline' if (status === 429) return 'error.tooFast' if (status === 403 || status === 404) return 'error.noAccess' if (status === 400 || status === 422) return 'error.refused' return 'error.send' } /** The DM-start error key (the chat-dm bucket allows 10 a minute). */ export function dmErrorKey(e: unknown): string { if (e instanceof ChatApiError && e.status === 429) return 'error.tooManyDms' if (e instanceof ChatApiError && e.status === 0) return 'error.offline' return 'error.dm' } /** The message as shown once deleted: no text, reactions, attachments or metadata. */ export function markDeleted(m: ChatMessage) { m.deleted_at = m.deleted_at ?? new Date().toISOString() m.content = null m.reactions = [] m.attachments = [] m.metadata = undefined } /** * Marks deleted the loaded messages a fresh latest page leaves out although * it covers them: up to lastBefore (the newest id loaded when the page was * requested) and from the page's first id, or from the start when the page * is short. The list API leaves deleted messages out, so a missing one was * deleted. */ export function markMissingDeleted(old: ChatMessage[], page: readonly ChatMessage[], lastBefore: number) { const present = new Set(page.map((m) => m.id)) const from = page.length < MESSAGE_PAGE ? 0 : (page[0]?.id ?? Infinity) for (const m of old) { if (m.deleted_at || present.has(m.id) || m.id < from || m.id > lastBefore) continue markDeleted(m) } } const conversationChannel = (id: number) => `chat:conversation:${id}` /** The window has focus; true outside a browser. */ function pageFocused(): boolean { return typeof document === 'undefined' || typeof document.hasFocus !== 'function' || document.hasFocus() } /** Inserts a message in id order unless it is already there. */ function insertMessage(list: ChatMessage[], m: ChatMessage): boolean { if (list.some((x) => x.id === m.id)) return false let i = list.length while (i > 0 && list[i - 1].id > m.id) i-- list.splice(i, 0, m) return true } function createChatStore() { const api = useChatApi() const auth = useChatAuth() const config = useChatConfig() const notice = useChatNotice() const userId = useState('chat:userId', () => null) /** undefined: not known yet (bootstrap in flight). */ const member = useState('chat:member', () => undefined) const moderator = useState('chat:moderator', () => false) const context = useState<{ type: string; id: number } | null>('chat:context', () => null) const channels = useState('chat:channels', () => []) const conversations = useState('chat:conversations', () => []) const limits = useState('chat:limits', () => null) /** The open conversation id. */ const activeId = useState('chat:activeId', () => null) const kind = useState('chat:kind', () => null) const dmError = useState('chat:dmError', () => '') /** Messages per conversation id, oldest first; absent until loaded. */ const messages = useState>('chat:messages', () => ({})) const loading = useState>('chat:loading', () => ({})) const errors = useState>('chat:errors', () => ({})) const drafts = useState>('chat:drafts', () => ({})) const anchors = useState>('chat:anchors', () => ({})) /** Members by id (the others; the caller is not listed). */ const memberRows = useState>('chat:members', () => ({})) const membersState = useState<'idle' | 'loading' | 'ready' | 'error'>('chat:membersState', () => 'idle') const bootstrapState = useState<'idle' | 'loading' | 'ready' | 'error'>('chat:bootstrapState', () => 'idle') const connection = useState('chat:connection', () => 'idle') /** A chat view is on screen (set by ChatPanel and the floating panel). */ const panelVisible = useState('chat:panelVisible', () => false) const reachedStart = useState>('chat:reachedStart', () => ({})) const olderLoading = useState>('chat:olderLoading', () => ({})) const olderError = useState>('chat:olderError', () => ({})) /** Who is typing, per conversation (others only). */ const typing = useState>('chat:typing', () => ({})) /** The allowed reaction keys from the server; null until loaded. */ const allowedReactions = useState('chat:reactions', () => null) const thread = useState('chat:thread', () => null) /** Replies per thread root id, oldest first; absent until loaded. */ const replies = useState>('chat:replies', () => ({})) const repliesError = useState>('chat:repliesError', () => ({})) const threadDrafts = useState>('chat:threadDrafts', () => ({})) /** Thread mute per root id, as set in this session. */ const threadMuted = useState>('chat:threadMuted', () => ({})) /** Pinned message ids per channel id; absent until loaded. */ const pinIds = useState>('chat:pinIds', () => ({})) const pinMessages = useState>('chat:pinMessages', () => ({})) const pinsError = useState>('chat:pinsError', () => ({})) /** False after the host refused a pin: the action is hidden for the session. */ const pinAllowed = useState('chat:pinAllowed', () => true) const commands = useState('chat:commands', () => null) const ephemeral = useState>('chat:ephemeral', () => ({})) /** Presence of the open channel: Centrifugo client id to user id. */ const presenceClients = shallowRef>(new Map()) const presenceAvailable = ref(false) /** Bumped by reset(): answers of an older session are dropped. */ let generation = 0 let bootstrapping: Promise | null = null let membersLoading: Promise | null = null let reactionsLoading: Promise | null = null let commandsLoading: Promise | null = null /** The latest reaction toggle per message: only its answer replaces the chips. */ const reactionSeq = new Map() // Attachments: the picked File per chip (kept for a retry) and the aborts of uploads in flight. let fileSeq = 0 const fileBlobs = new Map() const fileAborts = new Map() /** Replies already counted on their root's thread summary in this session. */ const countedReplies = new Set() let ephemeralSeq = 0 /** Channels whose conversation route ran this session (it makes the caller a participant). */ const joinedConversations = new Set() // Realtime: user:{me} for the whole session, the open conversation while open. let realtimeStarted = false let userHandle: ChannelHandle | null = null let openHandle: ChannelHandle | null = null let openChannelId: number | null = null let openSeq = 0 let unlisten: Array<() => void> = [] let activePoll: ReturnType | null = null let countsPoll: ReturnType | null = null const fetchingIds = new Set() const refreshing = new Map>() // Read marking: the newest message id already marked, the debounce timers, POSTs in flight. const readUpTo = new Map() const readTimers = new Map>() const readInFlight = new Set() let onVisibility: (() => void) | null = null const typingTimers = new Map>() const typingSentAt = new Map() const members = computed(() => new Map(Object.values(memberRows.value).map((m) => [m.id, m]))) /** Members by handle, for mentions in message bodies. */ const membersByHandle = computed(() => { const out = new Map() for (const m of members.value.values()) if (m.handle) out.set(m.handle, m) return out }) /** The user's own handle when the host lists the caller among the members. */ const myHandle = computed(() => (userId.value !== null ? (members.value.get(userId.value)?.handle ?? null) : null)) const joinedChannels = computed(() => channels.value.filter((c) => c.joined)) const activeChannel = computed(() => (kind.value === 'channel' ? (channels.value.find((c) => c.conversation_id === activeId.value) ?? null) : null)) const activeDm = computed(() => (kind.value === 'dm' ? (conversations.value.find((c) => c.id === activeId.value) ?? null) : null)) function channelOf(conversationId: number): ChatChannel | undefined { return channels.value.find((c) => c.conversation_id === conversationId) } function isChannel(conversationId: number): boolean { return !!channelOf(conversationId) } /** Unread messages in one conversation. */ function unreadOf(conversationId: number): number { const ch = channelOf(conversationId) if (ch) return ch.unread return conversations.value.find((c) => c.id === conversationId)?.unread ?? 0 } /** Unread mentions of the user (channels only: DMs have none). */ function mentionsOf(conversationId: number): number { return channelOf(conversationId)?.mentions ?? 0 } /** The sum over DMs. */ const dmUnread = computed(() => conversations.value.reduce((n, c) => n + (c.unread > 0 ? c.unread : 0), 0)) /** Unread messages in joined channels. */ const channelUnread = computed(() => joinedChannels.value.reduce((n, c) => n + (c.unread > 0 ? c.unread : 0), 0)) const totalMentions = computed(() => (member.value ? channels.value.reduce((n, c) => n + (c.mentions > 0 ? c.mentions : 0), 0) : 0)) /** DMs plus channel mentions: the floating panel's badge. */ const attention = computed(() => (member.value ? dmUnread.value + totalMentions.value : 0)) /** Other members online in the open channel, by id. */ const othersOnline = computed(() => [...new Set(presenceClients.value.values())].filter((id) => id !== userId.value).sort((a, b) => a - b)) /** Everyone online in the open channel, you included. */ const onlineCount = computed(() => othersOnline.value.length + 1) /** A member's online dot, while the open channel's presence is known. */ function isOnline(id: number): boolean { return presenceAvailable.value && othersOnline.value.includes(id) } /** The people typing in a conversation; none without realtime. */ function typingIn(conversationId: number): number[] { if (connection.value === 'unavailable') return [] return typing.value[conversationId] ?? [] } /** The user's DMs, last message newest first; DMs without messages last. */ const dmRows = computed(() => [...conversations.value].sort((a, b) => { const ta = a.last_message ? Date.parse(a.last_message.created_at) : -Infinity const tb = b.last_message ? Date.parse(b.last_message.created_at) : -Infinity return tb - ta || b.id - a.id }), ) function applyBootstrap(b: Awaited>) { if (!b.member) { stopRealtime() member.value = false moderator.value = false context.value = null channels.value = [] conversations.value = [] limits.value = null activeId.value = null kind.value = null messages.value = {} return } member.value = true moderator.value = !!b.moderator context.value = b.context channels.value = (b.channels ?? []).map((c) => ({ ...c })) conversations.value = (b.conversations ?? []).map((c) => ({ ...c })) limits.value = b.limits // A read still on its way must not bring the old count back. for (const id of [...readTimers.keys(), ...readInFlight]) zeroLocal(id) if (activeId.value !== null && !isChannel(activeId.value) && !conversations.value.some((c) => c.id === activeId.value)) { activeId.value = null kind.value = null } } /** Re-checks membership and refreshes channels, DMs and counts. */ function bootstrap(): Promise { if (bootstrapping) return bootstrapping const gen = generation // A refetch (counts, gap fill, polling) keeps the last values on failure, silently. const refetch = bootstrapState.value === 'ready' if (!refetch) bootstrapState.value = 'loading' bootstrapping = (async () => { try { const b = await api.bootstrap() if (gen !== generation) return applyBootstrap(b) bootstrapState.value = 'ready' } catch { if (gen === generation && !refetch) bootstrapState.value = 'error' } finally { if (gen === generation) bootstrapping = null } })() return bootstrapping } function currentUserId(): number | null { try { const own = auth.userId?.() if (typeof own === 'number' && own > 0) return own } catch { /* fall back to the token */ } return userIdFromToken(auth.token()) } /** * Starts the chat for the signed-in user: the bootstrap, the member list * and realtime. Membership is revalidated on every call; a different user * resets the store first. Without public.chat.hostApiBase it logs an error * and does nothing. */ async function start(locale?: string): Promise { if (import.meta.server) return if (locale) setFormatLocale(locale, Intl.DateTimeFormat().resolvedOptions().timeZone) if (!config.hostApiBase) { console.error('vue-chat-layer: runtimeConfig.public.chat.hostApiBase is not set; the chat does not start') return } const id = currentUserId() if (id === null) { // Signed out in this tab: forget the last session. if (userId.value !== null) reset() return } if (userId.value !== id) { reset() userId.value = id } if (!hasRealtimeAuth()) setRealtimeAuth(() => auth.token(), auth.refresh ? () => auth.refresh!() : undefined) const gen = generation await bootstrap() if (gen !== generation || !member.value) return void loadMembers() void loadReactions() watchVisibility() void startRealtime() } /** Loads the latest page of a conversation. */ async function loadLatest(conversationId: number) { const gen = generation loading.value[conversationId] = true errors.value[conversationId] = '' try { const page = await api.messages(conversationId, { limit: MESSAGE_PAGE }) if (gen !== generation) return messages.value[conversationId] = page reachedStart.value[conversationId] = page.length < MESSAGE_PAGE // Nothing unread: what loaded is already read, so opening it sends no read. if (unreadOf(conversationId) === 0 && mentionsOf(conversationId) === 0) readUpTo.set(conversationId, page.at(-1)?.id ?? 0) } catch { if (gen === generation) errors.value[conversationId] = 'error.load' } finally { if (gen === generation) loading.value[conversationId] = false } } /** Makes a conversation active and loads its latest page once. */ async function open(conversationId: number, as: ChatKind) { if (thread.value && thread.value.conversationId !== conversationId) thread.value = null activeId.value = conversationId kind.value = as void syncOpenChannel() if (messages.value[conversationId] === undefined && !loading.value[conversationId]) await loadLatest(conversationId) } /** * Opens a channel: a channel the user left is joined again, and the * conversation route runs once a session (it makes the caller a * participant of the channel's conversation). */ async function openChannel(channel: ChatChannel): Promise { const ctx = context.value const gen = generation try { if (!channel.joined && ctx) { await api.joinChannel(ctx, channel.id) if (gen !== generation) return false const row = channels.value.find((c) => c.id === channel.id) if (row) row.joined = true } if (!joinedConversations.has(channel.id)) { await api.openConversation('channel', channel.id) if (gen !== generation) return false joinedConversations.add(channel.id) } } catch { if (gen === generation) notice.show('error.openChannel') return false } await open(channel.conversation_id, 'channel') return true } /** Leaves a channel; it stays listed with joined false. */ async function leaveChannel(channel: ChatChannel): Promise { const ctx = context.value if (!ctx) return false try { await api.leaveChannel(ctx, channel.id) } catch { notice.show('error.leaveChannel') return false } const row = channels.value.find((c) => c.id === channel.id) if (row) row.joined = false if (activeId.value === channel.conversation_id) { activeId.value = null kind.value = null void syncOpenChannel() } void bootstrap() return true } /** Joins a channel without opening it. */ async function joinChannel(channel: ChatChannel): Promise { const ctx = context.value if (!ctx) return false try { await api.joinChannel(ctx, channel.id) } catch { notice.show('error.joinChannel') return false } const row = channels.value.find((c) => c.id === channel.id) if (row) row.joined = true void bootstrap() return true } /** Closes the open conversation (the floating panel's back button). */ function close() { activeId.value = null kind.value = null void syncOpenChannel() } /** * Refetches the latest page and merges it (gap fill after a reconnect, * polling without realtime). A page that no longer overlaps what is * loaded replaces it, so the list never shows a hole. A loaded message * the page should hold but no longer does was deleted while no event * reached this client: it is shown as deleted, without its text. */ function refreshLatest(conversationId: number): Promise { const running = refreshing.get(conversationId) if (running) return running const gen = generation const job = (async () => { try { const lastBefore = messages.value[conversationId]?.at(-1)?.id ?? 0 const page = await api.messages(conversationId, { limit: MESSAGE_PAGE }) if (gen !== generation) return const old = messages.value[conversationId] const lastOld = old?.at(-1)?.id ?? 0 if (!old || (page.length >= MESSAGE_PAGE && page[0].id > lastOld)) { messages.value[conversationId] = page errors.value[conversationId] = '' reachedStart.value[conversationId] = page.length < MESSAGE_PAGE return } markMissingDeleted(old, page, lastBefore) const byId = new Map(old.map((m) => [m.id, m])) for (const m of page) byId.set(m.id, m) messages.value[conversationId] = [...byId.values()].sort((a, b) => a.id - b.id) } catch { /* the next event or poll tries again */ } finally { if (gen === generation) refreshing.delete(conversationId) } })() refreshing.set(conversationId, job) return job } /** The previous page before the oldest loaded message. */ async function loadOlder(conversationId: number) { const list = messages.value[conversationId] if (!list?.length || olderLoading.value[conversationId] || reachedStart.value[conversationId]) return const gen = generation olderLoading.value[conversationId] = true olderError.value[conversationId] = '' try { const page = await api.messages(conversationId, { limit: MESSAGE_PAGE, before: list[0].id }) if (gen !== generation) return const current = messages.value[conversationId] ?? [] const known = new Set(current.map((m) => m.id)) messages.value[conversationId] = [...page.filter((m) => !known.has(m.id)), ...current] reachedStart.value[conversationId] = page.length < MESSAGE_PAGE } catch { if (gen === generation) olderError.value[conversationId] = 'error.older' } finally { if (gen === generation) olderLoading.value[conversationId] = false } } function zeroLocal(conversationId: number) { const ch = channelOf(conversationId) if (ch) { ch.unread = 0 ch.mentions = 0 return } const row = conversations.value.find((c) => c.id === conversationId) if (row) row.unread = 0 } /** * Called when the conversation is seen (the message list checks the rule). * The badges drop at once; the POST goes out once per 500 ms window, and * only when something is unread or newer than the last read. */ function markRead(conversationId: number) { const last = messages.value[conversationId]?.at(-1)?.id ?? 0 const pending = unreadOf(conversationId) > 0 || mentionsOf(conversationId) > 0 || last > (readUpTo.get(conversationId) ?? 0) if (!pending) return zeroLocal(conversationId) readUpTo.set(conversationId, last) if (readTimers.has(conversationId)) return const gen = generation readTimers.set( conversationId, setTimeout(() => { readTimers.delete(conversationId) if (gen !== generation) return readInFlight.add(conversationId) api .markRead(conversationId) .catch(() => { /* the next bootstrap corrects the count */ }) .finally(() => { if (gen === generation) readInFlight.delete(conversationId) }) }, READ_DEBOUNCE_MS), ) } /** Counts are refetched whenever the page becomes visible again (other tabs and devices read too). */ function watchVisibility() { if (onVisibility || typeof document === 'undefined') return onVisibility = () => { if (document.visibilityState === 'visible' && member.value) void refetchCounts() } document.addEventListener('visibilitychange', onVisibility) } /** The user is looking at the conversation: active, on screen, window focused. */ function seen(conversationId: number): boolean { return activeId.value === conversationId && panelVisible.value && pageFocused() } function appendMessage(m: ChatMessage) { if (m.root_id) { addReply(m) return } const list = messages.value[m.conversation_id] if (list) insertMessage(list, m) const row = conversations.value.find((c) => c.id === m.conversation_id) if (row && (!row.last_message || Date.parse(m.created_at) >= Date.parse(row.last_message.created_at))) { row.last_message = { id: m.id, sender_id: m.sender_id, content: m.content ?? '', created_at: m.created_at } } } /** Opens one DM. */ async function openDm(conversationId: number) { dmError.value = '' await open(conversationId, 'dm') } /** The DM row with a member, if the user already has one. */ function dmWith(otherUserId: number): ChatConversationRow | undefined { return conversations.value.find((c) => c.other_user_id === otherUserId) } /** * Opens the DM with a member, creating it through golem15.chat when it is * new. Returns the conversation id, or null with dmError set. */ async function startDm(otherUserId: number): Promise { dmError.value = '' const existing = dmWith(otherUserId) if (existing) { await openDm(existing.id) return existing.id } const ctx = context.value if (!ctx) return null const gen = generation try { const conv = await api.startDm(ctx, otherUserId) if (gen !== generation) return null if (!conversations.value.some((c) => c.id === conv.id)) { conversations.value.unshift({ id: conv.id, type: conv.type || 'dm', other_user_id: otherUserId, unread: 0, last_message: null }) } await openDm(conv.id) return conv.id } catch (e) { if (gen === generation) dmError.value = dmErrorKey(e) return null } } function draft(conversationId: number | null): Readonly { return (conversationId !== null && drafts.value[conversationId]) || EMPTY_DRAFT } function ensureDraft(conversationId: number): ChatDraft { if (!drafts.value[conversationId]) drafts.value[conversationId] = { text: '', error: '', detail: '', sending: false, files: [] } return drafts.value[conversationId] } /** True while any attachment of the draft is uploading (the send waits). */ function uploading(conversationId: number | null): boolean { return draft(conversationId).files.some((f) => f.state === 'uploading') } /** Text or an uploaded file, nothing uploading and no send in flight. */ function canSend(conversationId: number | null): boolean { const d = draft(conversationId) if (d.sending || uploading(conversationId)) return false return d.text.trim() !== '' || d.files.some((f) => f.state === 'done') } function startUpload(conversationId: number, localId: number) { const file = fileBlobs.get(localId) const chip = drafts.value[conversationId]?.files.find((f) => f.localId === localId) if (!file || !chip) return chip.state = 'uploading' chip.progress = 0 chip.id = null const abort = new AbortController() fileAborts.set(localId, abort) const gen = generation // The reactive copy: progress and results land on what the view renders. const live = () => drafts.value[conversationId]?.files.find((f) => f.localId === localId) api .upload( file, (n) => { const c = live() if (gen === generation && c && c.state === 'uploading') c.progress = n }, abort.signal, ) .then((answer) => { const c = live() if (gen !== generation || !c || abort.signal.aborted) return c.state = 'done' c.progress = 100 c.id = answer.id }) .catch((e: unknown) => { const c = live() if (gen !== generation || !c || abort.signal.aborted) return c.state = 'failed' const d = drafts.value[conversationId] if (d) { d.error = 'error.upload' d.detail = e instanceof ChatApiError ? e.field('file') : '' } }) .finally(() => { if (fileAborts.get(localId) === abort) fileAborts.delete(localId) }) } /** * Stages picked files: refused ones (too many, SVG/HTML/XML, over * limits.max_bytes alone or together with the staged chips) never upload * and answer their error lines, which also become the draft's error * detail; the rest upload at once with progress. */ function uploadFiles(conversationId: number, files: readonly File[], messages?: FileCheckMessages): string[] { const d = ensureDraft(conversationId) const stagedBytes = d.files.reduce((sum, f) => sum + f.size, 0) const { accepted, errors } = checkFiles(files, limits.value ?? DEFAULT_FILE_LIMITS, d.files.length, stagedBytes, messages) d.error = errors.length ? 'error.files' : '' d.detail = errors.join(' ') for (const file of accepted) { const localId = ++fileSeq fileBlobs.set(localId, file) d.files.push({ localId, name: file.name, size: file.size, progress: 0, state: 'uploading', id: null }) startUpload(conversationId, localId) } return errors } /** Uploads a failed chip again. */ function retryUpload(conversationId: number, localId: number) { const chip = drafts.value[conversationId]?.files.find((f) => f.localId === localId) if (!chip || chip.state !== 'failed') return const d = drafts.value[conversationId] if (d) { d.error = '' d.detail = '' } startUpload(conversationId, localId) } /** Drops a chip, aborting its upload if it is still running. */ function removeFile(conversationId: number, localId: number) { fileAborts.get(localId)?.abort() fileAborts.delete(localId) fileBlobs.delete(localId) const d = drafts.value[conversationId] if (d) d.files = d.files.filter((f) => f.localId !== localId) } function setDraftText(conversationId: number, text: string) { const d = ensureDraft(conversationId) d.text = text d.error = '' d.detail = '' } /** * Sends the draft of a conversation (the open one by default). No * optimistic row: the message appears once the API answers. On failure * the draft is kept and the error line set. */ async function send(conversationId: number | null = activeId.value): Promise { if (conversationId === null) return false const d = ensureDraft(conversationId) const content = d.text.trim() const sent = d.files.filter((f) => f.state === 'done' && f.id !== null) if ((!content && !sent.length) || d.sending || uploading(conversationId)) return false // A slash command is dispatched to golem15.chatbots, never posted. if (content.startsWith('/') && !sent.length) { const ok = await runCommand(conversationId, content) if (ok) d.text = '' return ok } const body: ChatSendBody = { content } if (sent.length) body.attachment_ids = sent.map((f) => f.id as number) d.sending = true d.error = '' d.detail = '' const gen = generation try { const m = await api.send(conversationId, body) if (gen !== generation) return false appendMessage(m) d.text = '' // Failed chips stay, so a file that did not upload is never dropped silently. const gone = new Set(sent.map((f) => f.localId)) for (const id of gone) fileBlobs.delete(id) d.files = d.files.filter((f) => !gone.has(f.localId)) return true } catch (e) { if (gen !== generation) return false d.error = sendErrorKey(e) if (e instanceof ChatApiError) d.detail = e.field('content') if (e instanceof ChatApiError && (e.status === 403 || e.status === 404)) void bootstrap() return false } finally { d.sending = false } } function saveAnchor(conversationId: number, anchor: ChatAnchor) { anchors.value[conversationId] = { ...anchor } } function anchorFor(conversationId: number): ChatAnchor | null { return anchors.value[conversationId] ?? null } /** The member list, once per session. */ function loadMembers(force = false): Promise { if (membersLoading) return membersLoading if (membersState.value === 'ready' && !force) return Promise.resolve() const gen = generation membersState.value = 'loading' membersLoading = (async () => { try { const list = await api.members() if (gen !== generation) return memberRows.value = Object.fromEntries(list.map((m) => [m.id, m])) membersState.value = 'ready' } catch { if (gen === generation) membersState.value = 'error' } finally { if (gen === generation) membersLoading = null } })() return membersLoading } /** The loaded copy of a message (a thread reply too), if any. */ function findMessage(conversationId: number, id: number): ChatMessage | undefined { const hit = messages.value[conversationId]?.find((m) => m.id === id) if (hit) return hit for (const list of Object.values(replies.value)) { const r = list.find((m) => m.id === id && m.conversation_id === conversationId) if (r) return r } return undefined } /** The reaction list, once per session; a failure leaves it null so the add button stays disabled. */ function loadReactions(): Promise { if (allowedReactions.value !== null) return Promise.resolve() if (reactionsLoading) return reactionsLoading const gen = generation reactionsLoading = (async () => { try { const keys = await api.reactions() if (gen === generation) allowedReactions.value = Array.isArray(keys) ? keys.filter((k) => typeof k === 'string' && k !== '') : [] } catch { /* the add button stays disabled; the next session tries again */ } finally { if (gen === generation) reactionsLoading = null } })() return reactionsLoading } /** * Toggles the user's reaction: the chip changes at once, the answer * replaces the message's reactions, and an error undoes the change with a * notice. Realtime events patch the same list idempotently. */ async function toggleReaction(message: Pick, key: string) { const me = userId.value const m = findMessage(message.conversation_id, message.id) if (me === null || !m || m.deleted_at) return const add = !(m.reactions ?? []).some((r) => r.key === key && r.user_ids.includes(me)) m.reactions = applyReaction(m.reactions, key, me, add, allowedReactions.value ?? []) const seq = (reactionSeq.get(m.id) ?? 0) + 1 reactionSeq.set(m.id, seq) const gen = generation try { const answer = add ? await api.addReaction(m.id, key) : await api.removeReaction(m.id, key) if (gen !== generation || reactionSeq.get(m.id) !== seq) return const current = findMessage(message.conversation_id, message.id) if (current && !current.deleted_at) current.reactions = answer.reactions ?? [] } catch { if (gen !== generation) return const current = findMessage(message.conversation_id, message.id) if (current) current.reactions = applyReaction(current.reactions, key, me, !add, allowedReactions.value ?? []) notice.show(add ? 'error.reactionAdd' : 'error.reactionRemove') } finally { if (gen === generation && reactionSeq.get(m.id) === seq) reactionSeq.delete(m.id) } } /** Only your own, live text messages can be edited (golem15.chat edits text only). */ function canEdit(m: ChatMessage): boolean { return userId.value !== null && m.sender_id === userId.value && !m.deleted_at && m.type === 'text' } /** * Your own messages; someone else's only for a moderator and only in a * channel, never in a DM. The server enforces the same rule. */ function canDelete(m: ChatMessage): boolean { if (userId.value === null || m.deleted_at) return false if (m.sender_id === userId.value) return true return moderator.value && isChannel(m.conversation_id) } /** Saves an edit. null when saved (or unchanged); the error key otherwise. */ async function edit(message: ChatMessage, text: string): Promise { const content = text.trim() if (content === (message.content ?? '').trim()) return null if (!content) return 'error.edit' const gen = generation try { const next = await api.edit(message.id, content) if (gen === generation) replaceMessage(next) return null } catch (e) { return e instanceof ChatApiError && e.status === 422 ? 'error.refused' : 'error.edit' } } /** Deletes a message. null when deleted; the error key otherwise. */ async function remove(message: ChatMessage): Promise { const gen = generation try { await api.remove(message.id) if (gen === generation) deleteLocal(message.conversation_id, message.id) return null } catch (e) { // Already gone on the server: show it as deleted. if (e instanceof ChatApiError && e.status === 404) { if (gen === generation) deleteLocal(message.conversation_id, message.id) return null } return 'error.delete' } } /** * Saves a message attachment: a bearer fetch to a blob, saved through a * temporary anchor with the download attribute. The blob is typed as * octet-stream, so the browser never renders it. */ async function download(message: ChatMessage, a: ChatAttachment): Promise { try { const data = await api.download(message.id, a.id) const url = URL.createObjectURL(new Blob([data], { type: 'application/octet-stream' })) const link = document.createElement('a') link.href = url link.download = a.filename || 'file' link.rel = 'noopener' link.style.display = 'none' document.body.appendChild(link) link.click() link.remove() setTimeout(() => URL.revokeObjectURL(url), 30_000) return true } catch { notice.show('error.download') return false } } /** Inserts a reply in its loaded thread and counts it on the root once. */ function addReply(m: ChatMessage) { const root = m.root_id if (!root) return const list = replies.value[root] if (list) insertMessage(list, m) if (countedReplies.has(m.id)) return countedReplies.add(m.id) const r = messages.value[m.conversation_id]?.find((x) => x.id === root) if (!r) return const s = r.thread_summary ?? { root_id: root, reply_count: 0, participant_ids: [] } const ids = s.participant_ids.includes(m.sender_id) ? s.participant_ids : [...s.participant_ids, m.sender_id] r.thread_summary = { ...s, reply_count: s.reply_count + 1, last_reply_at: m.created_at, participant_ids: ids } } /** Loads a thread's replies; the counted set learns them, so their events do not count twice. */ async function loadReplies(rootId: number) { const gen = generation repliesError.value[rootId] = false try { const list = await api.replies(rootId) if (gen !== generation) return for (const m of list) countedReplies.add(m.id) replies.value[rootId] = list } catch { if (gen === generation) repliesError.value[rootId] = true } } /** Opens a thread pane on a root message. */ async function openThread(root: ChatMessage) { thread.value = { rootId: root.id, conversationId: root.conversation_id } await loadReplies(root.id) } function closeThread() { thread.value = null } function threadDraft(rootId: number | null): Readonly { return (rootId !== null && threadDrafts.value[rootId]) || EMPTY_DRAFT } function setThreadDraftText(rootId: number, text: string) { if (!threadDrafts.value[rootId]) threadDrafts.value[rootId] = { text: '', error: '', detail: '', sending: false, files: [] } const d = threadDrafts.value[rootId] d.text = text d.error = '' d.detail = '' } /** Posts a reply in the open thread. */ async function sendReply(rootId: number): Promise { const d = threadDrafts.value[rootId] const content = d?.text.trim() ?? '' if (!d || !content || d.sending) return false d.sending = true d.error = '' d.detail = '' const gen = generation try { const m = await api.reply(rootId, { content }) if (gen !== generation) return false addReply(m) d.text = '' return true } catch (e) { if (gen !== generation) return false d.error = sendErrorKey(e) if (e instanceof ChatApiError) d.detail = e.field('content') return false } finally { d.sending = false } } /** Mutes or unmutes a thread for the user. */ async function setThreadMute(rootId: number, muted: boolean): Promise { try { const answer = await api.muteThread(rootId, muted) threadMuted.value[rootId] = answer?.is_muted ?? muted return true } catch { notice.show('error.threadMute') return false } } /** Loads a channel's pins: the ids, then each message. */ async function loadPins(channel: ChatChannel) { const ctx = context.value if (!ctx) return const gen = generation pinsError.value[channel.id] = false try { const ids = await api.pins(ctx, channel.id) if (gen !== generation) return pinIds.value[channel.id] = ids const got = await Promise.all(ids.slice(0, 50).map((id) => api.message(id).catch(() => null))) if (gen !== generation) return pinMessages.value[channel.id] = got.filter((m): m is ChatMessage => !!m && !m.deleted_at) } catch { if (gen === generation) pinsError.value[channel.id] = true } } function isPinned(m: ChatMessage): boolean { const ch = channelOf(m.conversation_id) return !!ch && (pinIds.value[ch.id] ?? []).includes(m.id) } /** Pins or unpins a channel message. A refusal hides the action for the session. */ async function togglePin(m: ChatMessage): Promise { const ch = channelOf(m.conversation_id) const ctx = context.value if (!ch || !ctx) return false const pinned = isPinned(m) try { if (pinned) await api.unpin(ctx, ch.id, m.id) else await api.pin(ctx, ch.id, m.id) } catch (e) { if (e instanceof ChatApiError && e.status !== 0 && e.status !== 429 && e.status < 500) { pinAllowed.value = false notice.show('error.pinRefused') } else { notice.show('error.pin') } return false } await loadPins(ch) return true } /** The slash commands, once per session. */ function loadCommands(): Promise { if (commands.value !== null) return Promise.resolve() if (commandsLoading) return commandsLoading const gen = generation commandsLoading = (async () => { try { const list = await api.commands() if (gen === generation) commands.value = list.filter((c) => typeof c?.trigger === 'string' && c.trigger !== '') } catch { if (gen === generation) commands.value = [] } finally { if (gen === generation) commandsLoading = null } })() return commandsLoading } /** The text of a command's payload: its content (or text, or message), or a string payload. */ function payloadText(payload: unknown): string { if (typeof payload === 'string') return payload if (payload && typeof payload === 'object') { const p = payload as Record for (const k of ['content', 'text', 'message']) if (typeof p[k] === 'string') return p[k] as string } return '' } /** * Dispatches a slash command for a conversation. The answer is shown to * the sender only, as a local row; a refusal (an unknown command, 422) * becomes an error row. Nothing is posted to the conversation. */ async function runCommand(conversationId: number, input: string): Promise { const d = ensureDraft(conversationId) if (d.sending) return false d.sending = true d.error = '' d.detail = '' const gen = generation const rows = () => (ephemeral.value[conversationId] ??= []) try { const answer = await api.dispatch(input) if (gen !== generation) return false rows().push({ id: ++ephemeralSeq, input, text: payloadText(answer?.payload), error: '' }) return true } catch (e) { if (gen !== generation) return false if (e instanceof ChatApiError && e.status === 422) { rows().push({ id: ++ephemeralSeq, input, text: '', error: e.field('input') || e.message }) return true } d.error = sendErrorKey(e) return false } finally { d.sending = false } } function dismissEphemeral(conversationId: number, id: number) { const list = ephemeral.value[conversationId] if (list) ephemeral.value[conversationId] = list.filter((r) => r.id !== id) } /** A newer copy of a message (an edit), also in the DM row preview. */ function replaceMessage(next: ChatMessage) { const list = next.root_id ? replies.value[next.root_id] : messages.value[next.conversation_id] const i = list ? list.findIndex((m) => m.id === next.id) : -1 if (list && i >= 0) list[i] = next const row = conversations.value.find((c) => c.id === next.conversation_id) if (row?.last_message?.id === next.id) row.last_message = { ...row.last_message, content: next.content ?? '' } } /** Marks a loaded message deleted and blanks its DM preview. */ function deleteLocal(conversationId: number, id: number) { const m = findMessage(conversationId, id) if (m) markDeleted(m) const row = conversations.value.find((c) => c.id === conversationId) if (row?.last_message?.id === id) row.last_message = { ...row.last_message, content: '' } } /** updated.chat.message: refetch a loaded message (events carry ids only). */ async function refetchMessage(conversationId: number, id: number) { if (!findMessage(conversationId, id)) return const gen = generation try { const m = await api.message(id) if (gen !== generation) return if (m.deleted_at) deleteLocal(conversationId, id) else replaceMessage(m) } catch { /* the next gap fill brings it */ } } /** Refetches the bootstrap counts; a failure keeps the last values. */ function refetchCounts(): Promise { return bootstrap() } /** A content-free created event: fetch the message over REST, once per id. */ async function fetchMessage(id: number) { if (fetchingIds.has(id)) return fetchingIds.add(id) const gen = generation try { const m = await api.message(id) if (gen === generation) appendMessage(m) } catch { /* the next gap fill or poll brings it */ } finally { if (gen === generation) fetchingIds.delete(id) } } /** A message from someone else on user:{me}: counts, preview, order and new DM rows. */ function receiveMessage(m: ChatMessage) { const conv = m.conversation_id stopTyping(conv, m.sender_id) const isSeen = seen(conv) if (m.root_id) addReply(m) else { const list = messages.value[conv] if (list) insertMessage(list, m) } const ch = channelOf(conv) if (ch) { if (!isSeen) ch.unread += 1 return } conversations.value = applyChatMessage(conversations.value, m, { seen: isSeen }) } function handleEvent(ev: ChatEvent) { switch (ev.kind) { case 'created': stopTyping(ev.conversationId, ev.senderId) if (ev.rootId) { // A reply: fetched only when its thread or its root is on screen. const rootId = ev.rootId if (!countedReplies.has(ev.id) && (replies.value[rootId] || findMessage(ev.conversationId, rootId))) void fetchMessage(ev.id) } else if (needsFetch(ev, messages.value)) void fetchMessage(ev.id) return case 'typing': onTyping(ev.conversationId, ev.userId) return case 'chatMessage': receiveMessage(ev.message) return case 'mentions': void refetchCounts() return case 'updated': void refetchMessage(ev.conversationId, ev.id) return case 'deleted': deleteLocal(ev.conversationId, ev.id) return case 'reacted': { const m = findMessage(ev.conversationId, ev.id) if (m && !m.deleted_at) m.reactions = applyReaction(m.reactions, ev.key, ev.userId, ev.added, allowedReactions.value ?? []) return } default: return } } function onPublication(data: unknown) { const ev = parsePublication(data) if (ev) handleEvent(ev) } /** user:{me}: the chat's own events, everything else to onUserEvent handlers. */ function onUserPublication(data: unknown) { const ev = parsePublication(data) if (ev) handleEvent(ev) else dispatchUserEvent(data) } /** * History and recovery are off, so every (re)subscribe refetches the open * conversation's latest page and the counts. */ function gapFill() { const id = activeId.value if (id !== null && messages.value[id] !== undefined) void refreshLatest(id) void refetchCounts() } function onConnectionState(s: ConnectionState) { if (connection.value === 'idle' || connection.value === 'unavailable') return if (s === 'connected') { connection.value = 'connected' return } // Presence and typing come back with the next subscribe. presenceAvailable.value = false clearTyping() connection.value = connection.value === 'connected' || connection.value === 'reconnecting' ? 'reconnecting' : 'connecting' } function startPolling() { stopPolling() activePoll = setInterval(() => { const id = activeId.value if (id !== null) void refreshLatest(id) }, POLL_ACTIVE_MS) countsPoll = setInterval(() => void refetchCounts(), POLL_COUNTS_MS) } function stopPolling() { if (activePoll) clearInterval(activePoll) if (countsPoll) clearInterval(countsPoll) activePoll = null countsPoll = null } /** No live updates for this session: say so and poll. */ function goUnavailable() { if (!realtimeStarted || connection.value === 'unavailable') return connection.value = 'unavailable' presenceAvailable.value = false clearTyping() startPolling() } function onTyping(conversationId: number, user: number) { if (user === userId.value || connection.value === 'unavailable') return const current = typing.value[conversationId] ?? [] if (!current.includes(user)) typing.value[conversationId] = [...current, user] const key = `${conversationId}:${user}` const old = typingTimers.get(key) if (old) clearTimeout(old) typingTimers.set( key, setTimeout(() => stopTyping(conversationId, user), TYPING_EXPIRY_MS), ) } function stopTyping(conversationId: number, user: number) { const key = `${conversationId}:${user}` const t = typingTimers.get(key) if (t) clearTimeout(t) typingTimers.delete(key) const current = typing.value[conversationId] if (current?.includes(user)) typing.value[conversationId] = current.filter((x) => x !== user) } function clearTyping() { for (const t of typingTimers.values()) clearTimeout(t) typingTimers.clear() typing.value = {} } /** The composer tells the others, at most once every 3 s, never for blank text. */ function emitTyping(conversationId: number, text: string) { if (!text.trim() || connection.value === 'idle' || connection.value === 'unavailable') return const now = Date.now() const last = typingSentAt.get(conversationId) if (last !== undefined && now - last < TYPING_THROTTLE_MS) return typingSentAt.set(conversationId, now) api.typing(conversationId).catch(() => { /* typing is best effort */ }) } /** The open channel's presence after every subscribe; null from the client means hidden. */ async function loadPresence(channel: string) { const gen = generation const got = await fetchPresence(channel) if (gen !== generation || connection.value === 'unavailable') return if (got === null) { presenceAvailable.value = false return } presenceClients.value = new Map(got.map((p) => [p.client, p.user])) presenceAvailable.value = true } function onJoin(who: PresenceClient) { const next = new Map(presenceClients.value) next.set(who.client, who.user) presenceClients.value = next } function onLeave(who: PresenceClient) { if (!presenceClients.value.has(who.client)) return const next = new Map(presenceClients.value) next.delete(who.client) presenceClients.value = next } /** Connects once per member session: user:{me} on the shared client, then the open conversation. */ async function startRealtime() { if (realtimeStarted || userId.value === null) return realtimeStarted = true const gen = generation const me = userId.value connection.value = 'connecting' unlisten.push(onConnection(onConnectionState), onUnavailable(goUnavailable)) try { const u = await subscribe(`user:${me}`, { onPublication: onUserPublication, onSubscribed: gapFill }) if (gen !== generation) return u.close() userHandle = u await syncOpenChannel() } catch { // The client chunk did not load: the chat still works over REST. if (gen === generation) goUnavailable() } } /** Subscribes the open conversation's channel and leaves the previous one. */ async function syncOpenChannel() { if (!realtimeStarted) return const want = activeId.value if (want === openChannelId) return const seq = ++openSeq openHandle?.close() openHandle = null openChannelId = want presenceAvailable.value = false presenceClients.value = new Map() if (want === null) return const gen = generation const name = conversationChannel(want) const withPresence = kind.value === 'channel' try { const h = await subscribe(name, { onPublication, onSubscribed: () => { gapFill() if (withPresence) void loadPresence(name) }, onJoin: withPresence ? onJoin : undefined, onLeave: withPresence ? onLeave : undefined, }) if (gen !== generation || seq !== openSeq) return h.close() openHandle = h } catch { /* goUnavailable already ran for the client */ } } /** Closes the chat's handles and listeners; returns whether realtime had started. */ function stopRealtime(): boolean { for (const off of unlisten) off() unlisten = [] userHandle?.close() openHandle?.close() userHandle = openHandle = null openChannelId = null openSeq++ stopPolling() const was = realtimeStarted realtimeStarted = false connection.value = 'idle' presenceAvailable.value = false presenceClients.value = new Map() clearTyping() typingSentAt.clear() return was } /** Forgets everything: on logout a second account never sees the first one's chat. */ function reset() { // The socket carries this user's token: drop it, the next login gets a fresh one. if (stopRealtime() || userId.value !== null) disconnectRealtime() fetchingIds.clear() refreshing.clear() for (const t of readTimers.values()) clearTimeout(t) readTimers.clear() readInFlight.clear() readUpTo.clear() joinedConversations.clear() if (onVisibility && typeof document !== 'undefined') document.removeEventListener('visibilitychange', onVisibility) onVisibility = null generation++ bootstrapping = null membersLoading = null reactionsLoading = null commandsLoading = null reactionSeq.clear() for (const a of fileAborts.values()) a.abort() fileAborts.clear() fileBlobs.clear() countedReplies.clear() allowedReactions.value = null thread.value = null replies.value = {} repliesError.value = {} threadDrafts.value = {} threadMuted.value = {} pinIds.value = {} pinMessages.value = {} pinsError.value = {} pinAllowed.value = true commands.value = null ephemeral.value = {} userId.value = null member.value = undefined moderator.value = false context.value = null channels.value = [] conversations.value = [] limits.value = null activeId.value = null kind.value = null dmError.value = '' messages.value = {} loading.value = {} errors.value = {} drafts.value = {} anchors.value = {} reachedStart.value = {} olderLoading.value = {} olderError.value = {} memberRows.value = {} membersState.value = 'idle' bootstrapState.value = 'idle' } return reactive({ userId, member, moderator, context, channels, joinedChannels, activeChannel, activeDm, conversations, limits, activeId, kind, dmError, dmRows, messages, loading, errors, drafts, anchors, members, membersByHandle, myHandle, membersState, bootstrapState, connection, panelVisible, reachedStart, olderLoading, olderError, dmUnread, channelUnread, totalMentions, attention, unreadOf, mentionsOf, isChannel, markRead, loadOlder, presenceAvailable, othersOnline, onlineCount, isOnline, typing, typingIn, emitTyping, start, bootstrap, open, openChannel, joinChannel, leaveChannel, close, openDm, dmWith, startDm, loadLatest, refreshLatest, refetchCounts, draft, setDraftText, canSend, send, saveAnchor, anchorFor, loadMembers, findMessage, replaceMessage, deleteLocal, uploading, uploadFiles, retryUpload, removeFile, download, allowedReactions, loadReactions, toggleReaction, canEdit, canDelete, edit, remove, thread, replies, repliesError, threadMuted, openThread, closeThread, loadReplies, threadDraft, setThreadDraftText, sendReply, setThreadMute, pinIds, pinMessages, pinsError, pinAllowed, loadPins, isPinned, togglePin, commands, loadCommands, runCommand, ephemeral, dismissEphemeral, reset, }) } export type ChatStore = ReturnType /** The app's chat store (one per Nuxt app). */ export function useChat(): ChatStore { const nuxtApp = useNuxtApp() as unknown as { _chatStore?: ChatStore } if (!nuxtApp._chatStore) nuxtApp._chatStore = createChatStore() return nuxtApp._chatStore }