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

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
}