feat: chat layer tracer: bootstrap, channel list, messages, composer

- createChatClient: bearer auth, one refresh-and-retry on 401, 422 field errors
- useChat over useState: host bootstrap, open a channel, send
- ChatPage, ChatChannelList, ChatMessageList, ChatComposer
- runtime config chat.apiBase, public.chat.{apiBase,channelsApiBase,botsApiBase,hostApiBase}
This commit is contained in:
Jakub Zych
2026-10-31 13:40:39 +01:00
commit fa6f9950a6
21 changed files with 9328 additions and 0 deletions

View File

@@ -0,0 +1,25 @@
<script setup lang="ts">
// The seeded channels of the community. There is no create button: members
// join and leave the channels the host has.
const { t } = useI18n()
const chat = useChat()
</script>
<template>
<nav class="chat-sidebar" :aria-label="t('chat.channels')">
<h2 class="chat-sidebar-title">{{ t('chat.channels') }}</h2>
<ul class="chat-channels">
<li v-for="c in chat.channels.value" :key="c.id">
<button
class="chat-channel"
type="button"
:data-channel-slug="c.slug"
:aria-current="chat.activeId.value === c.conversation_id ? 'true' : undefined"
@click="chat.open(c)"
>
# {{ c.name }}
</button>
</li>
</ul>
</nav>
</template>

View File

@@ -0,0 +1,28 @@
<script setup lang="ts">
// The message form: Enter sends, Shift+Enter adds a line.
const props = defineProps<{ conversationId: number }>()
const { t } = useI18n()
const chat = useChat()
const text = computed({
get: () => chat.drafts.value[props.conversationId] ?? '',
set: (v: string) => (chat.drafts.value[props.conversationId] = v),
})
async function submit() {
await chat.send(text.value)
}
function onKeydown(e: KeyboardEvent) {
if (e.isComposing || e.key !== 'Enter' || e.shiftKey) return
e.preventDefault()
void submit()
}
</script>
<template>
<form class="chat-composer" @submit.prevent="submit">
<textarea v-model="text" class="chat-composer-input" rows="2" :aria-label="t('chat.message')" :readonly="chat.sending.value" @keydown="onKeydown"></textarea>
<button class="chat-send" type="submit" :disabled="!text.trim() || chat.sending.value">{{ t('chat.send') }}</button>
</form>
</template>

View File

@@ -0,0 +1,16 @@
<script setup lang="ts">
// The messages of one conversation, oldest first, as plain text.
const props = defineProps<{ conversationId: number }>()
const { t } = useI18n()
const chat = useChat()
const list = computed(() => chat.messages.value[props.conversationId] ?? [])
</script>
<template>
<div class="chat-list" role="log" :aria-label="t('chat.messages')">
<article v-for="m in list" :key="m.id" class="chat-msg" :data-message-id="m.id">
<span class="chat-msg-name">{{ m.sender_name }}</span>
<p class="chat-msg-body">{{ m.content }}</p>
</article>
</div>
</template>

View File

@@ -0,0 +1,26 @@
<script setup lang="ts">
// The full chat: the channel sidebar and the open conversation. Render it
// inside <ClientOnly> (it uses window and the DOM).
const { t } = useI18n()
const chat = useChat()
onMounted(() => {
void chat.start()
})
const active = computed(() => chat.channels.value.find((c) => c.conversation_id === chat.activeId.value) ?? null)
</script>
<template>
<div class="chat-page">
<ChatChannelList />
<section class="chat-pane" :aria-label="active ? `# ${active.name}` : t('chat.name')">
<template v-if="chat.activeId.value !== null">
<ChatMessageList :conversation-id="chat.activeId.value" />
<ChatComposer :conversation-id="chat.activeId.value" />
</template>
<p v-else class="chat-pane-empty">{{ t('chat.pickChannel') }}</p>
<p v-if="chat.error.value" class="chat-error" role="alert">{{ t(`chat.error.${chat.error.value}`) }}</p>
</section>
</div>
</template>

View File

@@ -0,0 +1,72 @@
// The chat store: membership, channels, the open conversation, messages and
// drafts, as useState keys prefixed chat: (no Pinia). Every component that
// calls useChat() shares the same state.
import type { ChatChannel, ChatMessage } from '../lib/types'
/** The fallback page size of the message list. */
export const MESSAGE_PAGE = 50
export function useChat() {
const api = useChatApi()
const config = useChatConfig()
/** undefined: not known yet; false: outside the community. */
const member = useState<boolean | undefined>('chat:member', () => undefined)
const channels = useState<ChatChannel[]>('chat:channels', () => [])
/** The open conversation id. */
const activeId = useState<number | null>('chat:activeId', () => null)
const messages = useState<Record<number, ChatMessage[]>>('chat:messages', () => ({}))
const drafts = useState<Record<number, string>>('chat:drafts', () => ({}))
const error = useState<string>('chat:error', () => '')
const sending = useState<boolean>('chat:sending', () => false)
/** Loads the bootstrap; without public.chat.hostApiBase it logs an error and stops. */
async function start(): Promise<void> {
if (!config.hostApiBase) {
console.error('vue-chat-layer: runtimeConfig.public.chat.hostApiBase is not set; the chat does not start')
return
}
try {
const b = await api.bootstrap()
if (!b.member) {
member.value = false
channels.value = []
return
}
member.value = true
channels.value = b.channels.map((c) => ({ ...c }))
} catch {
error.value = 'bootstrap'
}
}
/** Opens a channel: the conversation route joins it, then the latest page loads. */
async function open(channel: ChatChannel): Promise<void> {
error.value = ''
await api.openConversation('channel', channel.id)
activeId.value = channel.conversation_id
messages.value[channel.conversation_id] = await api.messages(channel.conversation_id, { limit: MESSAGE_PAGE })
}
/** Sends text to the open conversation; the message appears once the API answers. */
async function send(text: string): Promise<boolean> {
const id = activeId.value
const content = text.trim()
if (id === null || !content || sending.value) return false
sending.value = true
try {
const m = await api.send(id, { content })
const list = messages.value[id] ?? (messages.value[id] = [])
if (!list.some((x) => x.id === m.id)) list.push(m)
drafts.value[id] = ''
return true
} catch {
error.value = 'send'
return false
} finally {
sending.value = false
}
}
return { member, channels, activeId, messages, drafts, error, sending, start, open, send }
}

View File

@@ -0,0 +1,56 @@
// The chat API client for the layer's components, bound to runtime config
// and the app's auth hook. One client per Nuxt app, so concurrent 401s share
// one token refresh.
//
// The auth hook: the app provides `chatAuth` from a Nuxt plugin. token()
// answers the user's frontend JWT (or null); refresh() renews it and answers
// the new one (or null); unauthorized() signs the user out locally:
//
// export default defineNuxtPlugin(() => ({
// provide: {
// chatAuth: {
// token: () => useCookie('token').value ?? null,
// refresh: async () => { ... return newToken },
// unauthorized: () => { useCookie('token').value = null },
// },
// },
// }))
//
// The token is sent as `Authorization: Bearer` (never as a cookie). The
// bases are always runtime config, never request input.
import { createChatClient, type ChatAuth, type ChatClient } from '../lib/client'
interface ChatPublicConfig {
apiBase: string
channelsApiBase: string
botsApiBase: string
hostApiBase: string
}
const NO_AUTH: ChatAuth = { token: () => null }
/** The app's $chatAuth hook, or a hook without a token. */
export function useChatAuth(): ChatAuth {
const hook = (useNuxtApp() as unknown as { $chatAuth?: Partial<ChatAuth> }).$chatAuth
if (!hook || typeof hook.token !== 'function') return NO_AUTH
return hook as ChatAuth
}
/** The public chat config (public.chat). */
export function useChatConfig(): ChatPublicConfig {
return useRuntimeConfig().public.chat as unknown as ChatPublicConfig
}
export function useChatApi(): ChatClient {
const nuxtApp = useNuxtApp() as unknown as { _chatClient?: ChatClient }
if (nuxtApp._chatClient) return nuxtApp._chatClient
const cfg = useChatConfig()
const chatBase = import.meta.server ? (useRuntimeConfig().chat as { apiBase: string }).apiBase : cfg.apiBase
const client = createChatClient({
bases: { chat: chatBase, channels: cfg.channelsApiBase, bots: cfg.botsApiBase, host: cfg.hostApiBase },
auth: useChatAuth(),
})
nuxtApp._chatClient = client
return client
}

226
app/lib/client.ts Normal file
View File

@@ -0,0 +1,226 @@
// The chat layer's HTTP client: golem15.chat (/_chat/api/v1), the host
// bootstrap ({hostApiBase}/chat), and later chatchannels and chatbots. Pure
// and Nuxt-free, so tests drive it with a stub fetch; useChatApi binds it to
// runtime config and the app's $chatAuth hook.
//
// Every request carries `Authorization: Bearer {auth.token()}`. A 401 on a
// request that carried a token refreshes once through auth.refresh() (one
// refresh at a time; concurrent 401s share it) and retries; a second 401, or
// a refresh that yields no token, calls auth.unauthorized(). The layer never
// stores the token.
import type {
ChatBootstrap,
ChatConversation,
ChatMember,
ChatMessage,
ChatSendBody,
} from './types'
/** The app's auth hook ($chatAuth): the user's JWT, its renewal and the signed-out callback. */
export interface ChatAuth {
token(): string | null | undefined
/** Renews the token and answers the new one, or null when the session cannot be renewed. */
refresh?(): Promise<string | null | undefined>
/** Called once a request failed with 401 and the refresh did not help. */
unauthorized?(): void
}
/** The API bases: same-origin paths in the browser. */
export interface ChatBases {
/** golem15.chat, e.g. /_chat/api/v1. */
chat: string
/** golem15.chatchannels, e.g. /_chatchannels/api/v1. */
channels: string
/** golem15.chatbots, e.g. /_chatbots/api/v1. */
bots: string
/** The host's bootstrap routes ({host}/chat, {host}/chat/members). */
host: string
}
export type ChatFetch = (url: string, init: { method: string; headers: Record<string, string>; body?: string | FormData }) => Promise<Response>
export interface ChatClientOptions {
bases: ChatBases
auth: ChatAuth
fetch?: ChatFetch
}
/** A refused request: the HTTP status (0 without a connection), the message and the 422 field errors. */
export class ChatApiError extends Error {
status: number
errors: Record<string, string[]>
constructor(status: number, message: string, errors: Record<string, string[]> = {}) {
super(message)
this.name = 'ChatApiError'
this.status = status
this.errors = errors
}
/** The first error of a field, or ''. */
field(name: string): string {
return this.errors[name]?.[0] ?? ''
}
}
export interface RequestOptions {
method?: string
query?: Record<string, string | number | undefined | null>
body?: unknown
}
export interface MessagePage {
limit?: number
/** Only messages older than this id. */
before?: number
}
function joinUrl(base: string, path: string): string {
return `${base.replace(/\/+$/, '')}${path}`
}
function withQuery(url: string, query?: RequestOptions['query']): string {
if (!query) return url
const qs = new URLSearchParams()
for (const [k, v] of Object.entries(query)) {
if (v !== undefined && v !== null && v !== '') qs.set(k, String(v))
}
const s = qs.toString()
return s ? `${url}?${s}` : url
}
function errorsOf(v: unknown): Record<string, string[]> {
if (!v || typeof v !== 'object' || Array.isArray(v)) return {}
const out: Record<string, string[]> = {}
for (const [k, list] of Object.entries(v as Record<string, unknown>)) {
if (Array.isArray(list)) out[k] = list.filter((x): x is string => typeof x === 'string')
else if (typeof list === 'string') out[k] = [list]
}
return out
}
/** toError maps an error body ({"error": msg, "errors": {field: [msg]}}) to a ChatApiError. */
export function toError(status: number, json: unknown): ChatApiError {
const j = (json && typeof json === 'object' ? json : {}) as { error?: unknown; message?: unknown; errors?: unknown }
const msg = (typeof j.error === 'string' && j.error) || (typeof j.message === 'string' && j.message) || `HTTP ${status}`
return new ChatApiError(status, msg, errorsOf(j.errors))
}
/** The payload: `data` of a wrapped body, the body itself otherwise. */
function unwrap<T>(json: unknown): T {
if (json && typeof json === 'object' && !Array.isArray(json) && 'data' in json) return (json as { data: T }).data
return json as T
}
export function createChatClient(opts: ChatClientOptions) {
const { bases, auth } = opts
const doFetch: ChatFetch = opts.fetch ?? ((url, init) => fetch(url, init))
let refreshing: Promise<string | null> | null = null
function token(): string | null {
try {
return auth.token() || null
} catch {
return null
}
}
function headers(extra: Record<string, string> = {}): Record<string, string> {
const h: Record<string, string> = { Accept: 'application/json', ...extra }
const t = token()
if (t) h.Authorization = `Bearer ${t}`
return h
}
/** One refresh at a time; concurrent 401s share it. */
function refresh(): Promise<string | null> {
if (!refreshing) {
refreshing = (async () => {
try {
return (await auth.refresh?.()) || null
} catch {
return null
} finally {
// Cleared after the awaiting callers resumed.
queueMicrotask(() => {
refreshing = null
})
}
})()
}
return refreshing
}
/** send, then one refresh-and-retry on 401 for a request that carried a token. */
async function authorized(send: () => Promise<Response>): Promise<Response> {
const used = token()
let res: Response
try {
res = await send()
} catch {
throw new ChatApiError(0, 'network error')
}
if (res.status !== 401 || !used) return res
// Another request may have refreshed the token meanwhile: just retry.
const current = token()
const renewed = current && current !== used ? current : await refresh()
if (renewed) {
try {
res = await send()
} catch {
throw new ChatApiError(0, 'network error')
}
}
if (res.status === 401) auth.unauthorized?.()
return res
}
async function parse(res: Response): Promise<unknown> {
const text = await res.text()
if (!text) return null
try {
return JSON.parse(text)
} catch {
return null
}
}
/** The parsed payload of a JSON request against a full URL. */
async function request<T>(url: string, o: RequestOptions = {}): Promise<T> {
const res = await authorized(() => {
const init: Parameters<ChatFetch>[1] = { method: o.method ?? 'GET', headers: headers() }
if (o.body !== undefined) {
init.headers['Content-Type'] = 'application/json'
init.body = JSON.stringify(o.body)
}
return doFetch(withQuery(url, o.query), init)
})
const json = await parse(res)
if (!res.ok) throw toError(res.status, json)
return unwrap<T>(json)
}
const chat = (path: string) => joinUrl(bases.chat, path)
const host = (path: string) => {
if (!bases.host) throw new ChatApiError(0, 'public.chat.hostApiBase is not set')
return joinUrl(bases.host, path)
}
return {
request,
/** GET {host}/chat: membership, channels, DMs and limits. */
bootstrap: () => request<ChatBootstrap>(host('/chat')),
/** GET {host}/chat/members: the other members (pickers and mentions). */
members: () => request<{ members: ChatMember[] } | ChatMember[]>(host('/chat/members')).then((r) => (Array.isArray(r) ? r : (r?.members ?? []))),
/** The conversation of a context; opening a channel's makes the caller a participant. */
openConversation: (type: string, id: number) =>
request<ChatConversation>(chat(`/contexts/${encodeURIComponent(type)}/${id}/conversation`)),
/** A page of messages (thread roots and plain messages), oldest first. */
messages: (conversationId: number, { limit = 50, before }: MessagePage = {}) =>
request<ChatMessage[]>(chat(`/conversations/${conversationId}/messages`), { query: { limit, before } }),
/** 201 with the message itself. */
send: (conversationId: number, body: ChatSendBody) =>
request<ChatMessage>(chat(`/conversations/${conversationId}/messages`), { method: 'POST', body }),
}
}
export type ChatClient = ReturnType<typeof createChatClient>

160
app/lib/types.ts Normal file
View File

@@ -0,0 +1,160 @@
// The JSON the chat layer reads: the host bootstrap (README, "Host bootstrap
// contract") and golem15.chat's MessageAPI, reactions and uploads. Ported
// from a Golem15 chat SPA's api/types.ts; the single group channel became a
// list of channels.
/** The composer limits: attachments per message, their total bytes and link cards per message. */
export interface ChatLimits {
max_files: number
max_bytes: number
max_embeds: number
}
/** One public channel of the community, with the caller's counts. */
export interface ChatChannel {
id: number
slug: string
name: string
/** The channel's backing golem15.chat conversation. */
conversation_id: number
/** The caller has not left it. */
joined: boolean
unread: number
mentions: number
}
export interface ChatLastMessage {
id: number
sender_id: number
content: string
created_at: string
}
/** One DM of the current user. */
export interface ChatConversationRow {
id: number
type: string
other_user_id: number
unread: number
last_message: ChatLastMessage | null
}
export interface ChatNonMember {
member: false
}
export interface ChatMemberBootstrap {
member: true
/** May delete other people's messages in channels. */
moderator: boolean
/** The chat context DMs are created in (POST /contexts/{type}/{id}/dm). */
context: { type: string; id: number }
channels: ChatChannel[]
conversations: ChatConversationRow[]
limits: ChatLimits
}
/** GET {hostApiBase}/chat: a non-member learns only that. */
export type ChatBootstrap = ChatNonMember | ChatMemberBootstrap
/** A community member (GET {hostApiBase}/chat/members); no e-mail address. */
export interface ChatMember {
id: number
name: string
surname: string
handle: string
is_bot: boolean
}
export interface ChatAttachment {
id: number
url: string
filename: string
size: number
mime_type: string
kind: string
width: number | null
height: number | null
}
export interface ChatReaction {
key: string
count: number
user_ids: number[]
}
/** The reaction routes' answer: the message's reactions after the change. */
export interface ChatReactionsAnswer {
message_id: number
reactions: ChatReaction[]
}
/** The reply sidecar of a thread root. */
export interface ChatThreadSummary {
root_id: number
reply_count: number
last_reply_at?: string
participant_ids: number[]
}
/** golem15.chat MessageAPI. sender_avatar is never rendered. */
export interface ChatMessage {
id: number
conversation_id: number
sender_id: number
sender_name: string
sender_avatar: string | null
content: string | null
type: string
attachments: ChatAttachment[]
created_at: string
created_at_human: string
edited_at: string | null
deleted_at: string | null
is_mine: boolean
root_id: number | null
thread_summary?: ChatThreadSummary | null
reactions?: ChatReaction[]
metadata?: Record<string, unknown>
}
export interface ChatSendBody {
content: string
attachment_ids?: number[]
metadata?: Record<string, unknown>
}
/** POST /attachments: the pending file. */
export interface ChatUploadAnswer {
id: number
filename: string
size: number
}
/** golem15.chat ConversationJSON (the conversation and DM answers). */
export interface ChatConversation {
id: number
type: string
name?: string | null
context_type?: string | null
context_id?: number | null
created_at?: string
}
/** PUT /threads/{rootId}/mute. */
export interface ChatThreadMute {
root_id: number
is_muted: boolean
}
/** One slash command of GET {botsApiBase}/commands. */
export interface ChatCommand {
trigger: string
description: string
}
/** POST {botsApiBase}/dispatch: ephemeral answers go to the sender only. */
export interface ChatDispatchAnswer {
mode: string
payload: unknown
}