The standalone Next.js website adds a role-aware admin console and public /docs guides. These are application features, not new React/Vue/widget exports. See admin console and public documentation. Adapters still consume the same SDK and user-scoped token contract, including tokens from the server identity exchange.
The SDK owns REST authentication, error handling, IDs, ordering, subscriptions and inbox state. ChatSession keeps the inbox live: one inbox-channel subscription per identity (thread subscription stays per open thread), plus provider-channel subscriptions for team liveness — a seller follows their own provider and a service admin follows every provider in the service, so new threads and messages arrive without refresh even before joining; customers follow none — delta-merged in server order with ID dedupe, full list refresh on (re)subscription, and a default-on visible-only ~20s poller for list plus open-thread deltas when Reverb is absent. React, Vue and the DOM widget consume ChatSession; no adapter implements its own REST protocol. Source manifests are aligned at prepared version 0.1.13 (see the changelog); publication remains unverified. Reusable manifests target restricted GitHub Packages under @alzaf-it, with repository package directories and registry metadata configured. Packages remain UNLICENSED. Local builds and packed archives can be verified before publication; registry availability must be confirmed separately. Third-party dependency licenses are unaffected.
Pending actions and navigation#
Each thread opening has a generation. Late send/upload/read/join/create results from an earlier opening cannot consume the current composer or replace its messages, errors or busy indicators. This includes navigating A → B → A. The server operation can still have succeeded; reconcile history before resending. Uploads completed after leaving their opening return undefined from ChatSession.uploadAttachment and are not staged in the new opening.
ChatSession.conversationRevision is a readonly, opaque local equality token. Capture it before asynchronous composer work and compare it before clearing a draft or advancing a file batch. It changes on open (including reopening the same conversation), backToInbox and close; ordinary refresh/message/staging updates do not change it. Do not persist it, infer ordering from its value or use it as identity/authorization. Standard adapters compare it with the captured conversation ID, so A → B → A and same-thread reopen cannot resume an old batch or clear an identical new draft. send() still returns true for a confirmed server send even when its opening is obsolete.
After a confirmed send, the SDK removes only the staged card and attachment IDs captured by that send. Newly staged suggestions/files remain. Adapters clear only an unchanged draft from the original conversation, preserve edits made while waiting, serialize multi-file upload selections and stop the remainder when the conversation changes. React Enter respects IME composition and send readiness; Shift+Enter retains newline behavior.
The SDK never automatically resends. An unchanged pending manual retry retains its UUID, including reopening the same selected conversation. Changing payload, switching conversations, returning to inbox or creating a new session ends this in-memory retry boundary. Hosts must reconcile uncertain sends before retrying outside it. See SDK guide.
Exports and ownership#
@alzaf-it/chat-sdk exports ChatClient, ChatSession, ChatError, mergeMessages, createMessageId, chatStyles, the card helpers isMessageCard, cardBodyText, cardView (MessageCardView view-model: plain-text fields, HTTPS-only action), the attachment helpers messageAttachments and attachmentSizeText, the built-in EMOJI_GROUPS emoji table, and TypeScript interfaces Identity, Provider, Message, MessageCard, MessageCardView, MessagesPage, Conversation, ConversationParticipant, ChatOptions, ReverbConfig, ChatState, Attachment, AttachmentKind, AttachmentUpload, EmojiGroup. A conversation's participants omits the authenticated viewer and contains exactly one is_primary:true participant; render that participant's name and avatar_url for inbox titles, with the remaining entries as the other parties in a grouped conversation. Conversation also carries provider_id, provider_name, provider_avatar_url and has_joined: the provider/store fields identify, label and image the conversation (provider_avatar_url is the registry logo_url normalized to avatar_url semantics; a service admin's selected thread header uses provider_name with that image and the remaining participants in the description), and has_joined is the server-authoritative admin join/send gate — a missing value means "not confirmed joined". ChatSession.backToInbox() clears the selected conversation/messages without closing the session, for popover back navigation.
ChatClient construction and imports do not read browser globals or connect. subscribe requires a browser when realtime is configured. The owning host calls disconnect() on teardown. A session unsubscribes its selected conversation on selection changes and close(). Widget destroy() also clears pending read timers, removes listeners, disconnects the client, and removes its shadow host. In-flight HTTP requests may finish after cleanup, but a closed session suppresses state callbacks. Lazy realtime initialization is guarded against teardown. Do not share one client's same conversation subscription between independent sessions; channel ownership is currently per session.
React exports ChatPanel({client?,session?,title?,height?,className?}): title defaults to Messages. An explicit height sets a fixed inline height; when it is omitted the panel defaults to an h-[620px] class, so className height utilities (h-*, min-h-*, max-h-*) override or extend it via tailwind-merge (builds up to 0.1.5 applied the 620px default inline instead). The package entry imports its prebuilt stylesheet (dist/chat.css, also exported as @alzaf-it/chat-react/chat.css with a styles.css alias kept for 0.1.6–0.1.8 compatibility), so host bundlers include the panel styles automatically with zero host CSS wiring; the host provides only the standard shadcn :root/.dark tokens, and no Tailwind @source registration is required (kept as legacy for 0.1.5-era builds). Host precedence is structural: every package utility carries the ac prefix (ac:flex, ac:md:flex-row, ...), so package selectors never collide with host utilities — the package cannot override host designs and host overrides cannot break panel internals (responsive pairs like ac:flex-col/ac:md:flex-row resolve normally within the package stylesheet), and dark: utilities are class-based (.dark) per decisions 0009/0011. Plain-Node ESM/CJS runners without CSS handling need a *.css stub (see troubleshooting). Inside <ChatProvider> the panel inherits the provider's client and shared session, so neither prop is required; outside a provider pass client (a lone session also works) or it throws. Passing an explicit client or session still selects an independent or explicitly shared session as before. The React panel is built from vendored shadcn/base primitives (packages/react-chat/src/ui/: message, message-scroller, bubble, avatar, badge, button, input, input-group, textarea, item, empty, scroll-area, separator, skeleton, spinner) and uses the host's shadcn theme tokens through its prebuilt stylesheet (dist/chat.css, imported automatically by the entry); no host Tailwind scanning is required. The thread renders inside MessageScrollerProvider (autoScroll, opens at the live edge) with MessageScrollerViewport/MessageScrollerContent/MessageScrollerItem rows and a MessageScrollerButton jump-to-latest control, so history prepending, reconnect catch-up and new arrivals keep the reader's place per the official scroller behavior (backed by the @shadcn/react dependency). Consecutive messages from the same sender stack in a MessageGroup with an empty MessageAvatar on earlier rows and the avatar, name header and timestamp on the boundary rows, per the official group pattern. ### Attachments and emoji
Message.attachments is Attachment[] | null where Attachment = {id, kind: "image"|"file", name, mime, size, url}. Images render as inline previews and every other kind (currently PDF) as a named download chip with the size; both link out in a new tab. url is short-lived, so a long-open thread refreshes it by re-fetching history — URLs are not stable identifiers and name/ mime are untrusted display strings, rendered as text.
Attachments and cards are separate from bubble text. In all three adapters the message bubble holds only the body (or the card) and the attachment tiles are siblings ordered after it: React renders MessageAttachments next to the Bubble, and Vue/the widget append .attachments after .bubble. An attachment-only message therefore renders no empty bubble, and a wide image cannot stretch the sender's text bubble. React exports MessageAttachments({message, className?}) (returns null when the message has none); its root carries data-slot="message-attachments" so MessageContent aligns it with the sender side, hugs its content (w-fit) and caps the group at min(85%,22rem).
Uploads are staged in the composer: React shows an attach button with a hidden file input whose accept is built from the limits, Vue and the widget the same control, plus a staged-attachment strip (thumbnail or file icon, truncated name, remove button) and a busy state while an upload is in flight. ChatSession.uploadAttachment(file) validates type/size/count locally, asks the server how bytes should travel (presignAttachment), then either posts the file to the multipart endpoint (proxy) or PUTs it to a presigned storage URL and confirms the ticket (presigned). Models a host supplies without a presignAttachment method are proxied directly, which is the documented duck-typed-transport contract; if the direct PUT fails (missing bucket CORS, expired URL, network loss) the session retries through the proxy path, which re-validates the bytes server-side. A file rejected by policy fails again with the server's reason. Staging surfaces as state.stagedAttachments and state.uploading; removeStagedAttachment(id) / clearStagedAttachments() manage the strip, and the staged set is cleared on thread change, backToInbox() and the send that consumes it. ChatSession.attachmentLimits ({maxBytes, maxPerMessage, mimes}) is a client-side mirror for instant feedback and the composer accept list; the server config service-chat.attachments stays authoritative, and a rejected upload surfaces state.error. Override the mirror when a host configures different limits.
Emoji are built in: EMOJI_GROUPS is a curated, dependency-free table of {label, emojis: string[]} groups (EmojiGroup) exported by the SDK, consumed by the React emoji popover, the Vue picker and the widget's lazily built picker (the plain-HTML widget needs no build step or third-party picker). Picking an emoji inserts it at the composer caret rather than appending blindly.
The React composer is an InputGroup with InputGroupTextarea and a block-end InputGroupAddon send button. The host must already provide the standard shadcn :root/.dark tokens with an @theme inline mapping (the Next.js example defines them in app/globals.css with an orange primary). The panel keeps the same ChatSession behavior contract: provider selection for customers, history with manual earlier-page loading, replies gated by canReply (admins join first), manual refresh, and read-state advances. Presentation adds conversation search (matching every participant name, subject and status), unread-count badges, status badges, participant conversation titles (the primary participant's name, falling back to subject), a fixed-footprint conversation avatar cluster, sender/role headers with timestamps, loading skeletons, empty states, a responsive list/thread layout (below the md breakpoint the panel shows either the conversation list or the thread — never both — with a mobile-only back button returning to the list, the same flow as the popover), and Enter-to-send (Shift+Enter for newline). The conversation avatar uses the primary participant's avatar_url with an initials fallback, and a grouped conversation keeps that exact footprint: exactly two participants layer the second participant's avatar over the bottom-right, while three or more keep the primary avatar and place a +N badge there, so the media never grows with the participant count. The selected thread header lists the other participants (with ...) ahead of the last-activity line. Vue exports ChatPanel with the same properties, but height is a CSS string defaulting to 620px. Vue and the DOM widget keep the dependency-free chatStyles text rendering and are unchanged by the React restyle. Keep the supplied client stable. React/Next.js must render in a client component. Vue client prop must remain unchanged while mounted; remount when replacing it.
The HTML widget exports mount(options) and returns {client,destroy()}. Its conversation list displays the server-selected primary participant, so customers see the provider/store and sellers see the customer; a grouped conversation appends +N for the extra participants in its status line. The Vue adapter shows the same +N. See plain HTML.
Each shipped package (@alzaf-it/chat-sdk, @alzaf-it/chat-react, @alzaf-it/chat-vue, @alzaf-it/chat-widget) includes a versioned usage README.md at node_modules/@alzaf-it/<package>/README.md covering its exports, options, lifecycle and cleanup for the installed version. The SDK also installs the alzaf-chat bin; its init-agents command writes a marker-delimited guidance block into a host project's AGENTS.md (idempotent, --dry-run/--check, --file override; see the SDK README). The sections below remain the repository-side reference.
React popover, provider and seller hook#
@alzaf-it/chat-react additionally exports ChatProvider, useChat, useChatWithSeller, ChatPopover, MessageCardView, cardBodyText, and the shadcn Popover primitives (packages/react-chat/src/ui/popover.tsx, backed by radix-ui). ChatProvider({client,children,persistKey?,initialConversationId?,defaultOpen?,open?,onOpenChange?,cardRenderers?}) owns one ChatSession for the subtree, the popover open state and the last-conversation persistence. persistKey defaults to alzaf-chat:last-conversation; set false to disable. Only the selected conversation id is stored in localStorage (guarded for SSR/private mode); open state is not persisted. initialConversationId overrides the stored value on startup. cardRenderers maps a card type to a host renderer ((card) => ReactNode); unregistered types use the built-in MessageCardView, and the same map is inherited by ChatPanel/ChatPopover unless overridden by their own prop.
Message card rendering#
Thread bubbles render MessageCard sidecars through MessageCardView (image, title, description, one HTTPS action), or a host renderer from cardRenderers keyed by card.type. The generic card stacks a fixed-height image banner above the body on narrow widths and switches to a side-by-side row at the md breakpoint and wider, in every adapter (React, Vue and the widget share this responsive layout): the image becomes a 112px-wide thumbnail that stretches to the card height beside a body whose content is centred in the row, so a short title/description does not leave dead space beside or under the text. On a message that carries a card, React renders the sidecar without the message bubble's coloured background (a ghost bubble) so the card's own neutral bg-card/border-border surface is the only chrome and the sender's bg-primary bubble does not read as a coloured rim around the card. A custom renderer receives the raw envelope and is responsible for its own markup and trust rules. The JSON body is shown under the card unless it is blank or identical to the card title (card-only sends reuse the title), so the plaintext summary is never printed twice. Unusable payloads (missing type/title) degrade to the plaintext body, and non-HTTPS action URLs are dropped. Vue and the plain-HTML widget render the same generic card through the shared cardView view-model; a custom in-thread renderer registry is React-only for now.
useChat() returns {client,session,state,isOpen,setOpen,toggle,totalUnread,openConversation,backToInbox,openChatWithProvider}. openChatWithProvider(providerId,{subject?,context?}) loads the newest non-resolved conversation for that provider (falling back to any match) or creates one, selects it and opens the popover. useChatWithSeller(providerId,{subject?,context?,selectOnly?}) binds this to a seller button and returns {openChat,opening,error,state,totalUnread}; selectOnly selects without opening (for in-page layouts).
ChatPopover({mode?,position?,open?,defaultOpen?,onOpenChange?,title?,width?,height?,className?,style?,wrapperClassName?,wrapperStyle?,triggerClassName?,triggerStyle?,trigger?,triggerLabel?,showTrigger?,side?,align?,sideOffset?,client?,session?,persistKey?,initialConversationId?}) renders mode="floating" (default, fixed shadcn Popover with a floating action trigger and unread badge) or mode="inline" (in-page embed, no fixed positioning or trigger). variant="compact" (default) shows the narrow thread/list UI; variant="full" embeds the sidebar panel inbox (2-page list-to-thread flow below md, sidebar beside thread on larger screens) at roomier 860x620 defaults (still overridable; floating full closes via the trigger, Escape or outside click, triggerless full adds a corner close button). Floating defaults to position="bottom-right" (fixed bottom-4 right-4 z-50) and behaves the same anchored popover on mobile; override with position, wrapperClassName (merged via tailwind-merge) or wrapperStyle. Panel size defaults to 384x560 (width/height accept CSS strings or numbers) and is overridable via className/style. side/align default from the corner (top/bottom + start/end) and accept radix overrides. showTrigger={false} renders a triggerless fixed card driven only by chat.isOpen (seller buttons). Inside ChatProvider the popover shares the session; standalone, pass client (or session) for an isolated inbox. Imports and construction never touch browser globals; localStorage/scroll effects run only after mount, so SSR rendering is safe. See React/Next.js.
Configuration#
| Option | Type | Default | Location / sensitivity |
|---|---|---|---|
| apiBaseUrl | string | required | browser, public; complete API prefix, e.g. http://localhost:8000/api/chat |
| authEndpoint | string | derived from API base as /api/broadcasting/auth | browser, public; set full URL for customized routes |
| token | string or async/sync function returning string | required | authenticated user credential; use short expiry; do not log or persist in examples |
| reverb | object | absent; REST only | browser, public connection settings |
| reverb.key | string | required when configured | public app key, never Reverb secret |
| reverb.host | string | required | hostname without scheme |
| reverb.port | number | required | WebSocket port |
| reverb.scheme | http or https | required | https forces encrypted WebSocket |
| fetch | fetch-compatible function | global fetch | injectable transport/testing; also used for presigned storage PUTs, so it must not inject credentials |
| auth.signInUrl | string (relative or absolute) | absent; raw 401 error text | browser, public; Login call-to-action target shown on 401 instead of the error |
| auth.signOutUrl | string URL | absent; no sign-out call | browser, public; best-effort POST (bearer included, failures swallowed) on every 401 |
| widget.target | selector or HTMLElement | required | browser mount container |
| widget.title | string | Messages | UI branding |
| widget.height | CSS string | 620px | UI layout |
Current auth mode is bearer authorization for REST and channel auth, not cookie sessions. Origins must be allowed by host CORS and Reverb. By default channel auth URL is derived by replacing trailing /api/chat in apiBaseUrl with /api/broadcasting/auth. Set authEndpoint to a full URL when host routes use a different prefix or origin. That endpoint must authenticate the bearer token and authorize the requested channel; include its origin in your permitted CORS configuration.
Delivery and limitations#
sendMessage(id, body, clientMessageId?) makes one attempt. Reuse the same ID for retries. ChatSession.send retains its ID after failure while draft body is unchanged; successful sends clear it. Messages merge by durable ID, ascending. messagesPage(id, query) returns {messages, hasMore} from the response meta.has_more, falling back to page fullness when a host omits metadata; messages() keeps returning the bare array. ChatSession tracks state.hasEarlier from that flag on open and after each earlier page, and loadEarlier() is a no-op once exhausted, so ready-made inboxes only offer the control while older history remains. On channel subscription/reconnection, the SDK fetches pages of 100 messages after its cursor, then merges them. Realtime without Reverb is not simulated: manual Refresh updates the inbox, and reopening a chat fetches messages.
Staged message cards#
sendMessage(id, body, clientMessageId?, card?) accepts an optional `MessageCard` sidecar; body stays the required plaintext summary (card-only sends fall back to the card title). ChatSession stages a card as a removable suggestion via stageCard(card) / clearStagedCard(); state.stagedCard holds the single slot and is cleared on thread change, backToInbox(), or the send that consumes it. send(body, card?) auto-attaches the staged card, keeps it when a send fails, and treats an explicit card argument as unrelated to the staged slot. suggestCard(providerId, card, {subject?}) is the host "chat about this product" one-call flow: it opens (or creates) the provider thread and stages the card unless the same ref is already staged or present in hasRecentCard(ref) (the loaded window only). The React composer renders the staged card (thumbnail, title, description, a Send now button, a remove button and the hint "Send now, or add a message below to send it along."): Send now sends immediately with any typed draft or the card alone when the box is empty, and the main composer send button sends the card with the draft; Vue and the plain-HTML widget render the same block through their own DOM. See Message card rendering above for the in-thread card bubbles and host type-registry rules, and the message cards integrator guide for the host mapping recipe and worked demo.
The React inbox shows customer/provider/admin sender name and role, conversation search, status badges, unread-count badges, last-message preview with timestamps, and loading/empty states. Customers choose providers and create conversations. Provider/admin inboxes show authorized server results; admin Join as admin calls the backend join endpoint. The join control hides once the returned has_joined is true, and the composer stays disabled until then — an admin must join before sending. A service admin's selected thread header shows the provider/store provider_name with the provider_avatar_url image (initials fallback), and the remaining participants in the description. The thread header info button opens read-only conversation details (subject, status, provider/store, participants, last activity): a third-column sidebar beside the thread on roomy panel widths and a Details back-stack page on narrow widths and the compact popover. The details component accepts an optional future actions slot; reporting and other actions are deferred. Text messages, attachments (images and PDFs, with or without a text body), the built-in emoji picker and manual earlier-history loading are implemented. Typing indicators, automatic inbox realtime updates, resolution controls, assistance-request controls, assignment, transfer and native push notifications are deferred. The status API is exposed to custom interfaces, but ready-made panels only display status.
The widget uses a shadow root and textContent for untrusted data; components escape text through their framework. Browser import/build checks and SDK tests are distinct from live WebSocket/browser flow verification. Consult project status for actual evidence.
Source maintenance#
Keep source files UTF-8 and readable. Ready-made interface separators use ASCII | and loading placeholders use ..., avoiding encoding-dependent display defects. Build artifacts are regenerated from source; never patch bundled output.
Browser artifact dependency resolution#
The widget IIFE build explicitly uses the browser platform so Pusher resolves dist/web/pusher.js, rather than its Node entry requiring util. Its build metadata is checked by pnpm --filter @alzaf-it/chat-widget test:browser. This checks dependency selection and bundle evaluation; a live Reverb conversation remains necessary to verify end-to-end delivery.
Production authentication lifecycle#
The host supplies a user bearer token or an async getter. The getter is evaluated on every REST request and private-channel authorization, so updated credentials are used on reconnect. Token renewal through a getter must preserve the same identity and service. When switching users or services, disconnect and recreate the client/session so existing channel subscriptions and cached conversation state are removed. The SDK does not implement password login, refresh-token storage or provider-specific logout endpoints. Keep access tokens in memory; the production host owns credential renewal and revocation.
A REST or private-channel authorization HTTP 401 disconnects all subscriptions on that client and reports ChatError. The host should clear its authenticated screen and obtain a new session before remounting. A 403 is an authorization denial, not a global credential revocation. Explicit host logout must revoke its server token and then call disconnect() and unmount the panel/widget. Calling disconnect alone does not revoke a credential.
Reverb authorizes a private subscription at handshake time. An already subscribed connection does not automatically reauthorize solely because its bearer token expires or is revoked. SDK disconnection after an HTTP 401 helps cooperative clients, but cannot enforce revocation for arbitrary clients that ignore the SDK. The production host must specify and verify server-enforced active-connection/channel revocation before claiming immediate revocation security. No SDK-side periodic check is presented as a server authorization boundary.
The bundled own central host now implements and tests guarded Reverb revocation. Its local raw-WebSocket smoke verifies authorized delivery followed by logout disconnection and idle revocation. Generic embedded Laravel hosts must implement their own equivalent policy; multi-node and this actual native production deployment still require verification.
Restricted package namespace and archive verification#
All reusable browser packages use the owner scope @alzaf-it; example application names remain internal @alzaf demo projects. Manifests point to restricted GitHub Packages and record their directories in Alzaf-IT/alzaf_chat. Local workspace SDK dependencies stay workspace:* in source; pnpm pack rewrites them to the release's exact package version in archives. No compatibility alias for an earlier workspace namespace is retained. Consumers must update imports and dependency keys together.
For this rename, all four shared ESM/CJS/declaration builds, the standalone widget browser regression, 12 SDK tests, Next typecheck and Vue example build pass. node scripts/pack-distribution.mjs verifies four 0.1.0 archives under ignored .runtime/package-release/npm, with no workspace: dependency values or unexpected archive paths. This is local packing evidence; publication and installation from GitHub Packages require the separate release/consumer verification workflow.
Workspace visual system (2026-10-19)#
The website and reusable React/Vue/HTML panels follow the Alzaf Pay light the original blue palette while preserving existing page and chat layouts. The canonical visual system documents exact tokens, table density, source ownership, scope and release boundaries. Native management dialogs retain focus trapping, Escape, in-dialog save errors and credential cleanup. Tables scroll inside their wrapper on narrow screens. API permissions and payloads are unchanged. See UI verification.
The dashboard analytics layout is inspired by Able Pro cards/chart composition. It uses the existing scoped /admin/overview payload only: no extra endpoints or chart dependencies. Daily/cumulative bars, period sum/average/peak, current status shares and resolved progress derive directly from server data. Directory actions use the host navigation callback. Replaced chart/stat CSS was removed. No revenue, growth, storage usage or response-time figures are fabricated.