Developing Smarter Chat
This guide is for developers who write React code in Smarter Chat, the @smarter.sh/ui-chat npm
package, which the web console’s prompt engineering workbench imports too. It assumes you know React and TypeScript, and
explains how Smarter Chat is put together, how to run it, how to test it, and how to make the most
common kinds of change. For the conventions that it shares with the web console’s other React apps,
see Django-React Integration.
Where the Code Lives
Smarter Chat lives in the web console’s repository,
smarter-sh/smarter-console, as
packages/smarter.sh-chat,
one of the packages of its npm workspace. make install, in a smarter-console checkout, installs
its dependencies with everyone else’s:
git clone https://github.com/smarter-sh/smarter-console.git
cd smarter-console
make install
It is a workspace package like any other, with the same TypeScript, Vite, Vitest, Storybook, ESLint
and Prettier configuration as the console’s other packages. The backend that it talks to is the
Smarter repository, so a change to the chat api is two changes: the backend’s models and the
contract’s schema, which make chat-contract regenerates and commits in the Smarter repository,
then, in smarter-console, the package’s copy of the schema and its TypeScript types, which
make contracts copies and regenerates (see Using a new field of the configuration). One thing
is different:
it is a library, not a page. Its name is @smarter.sh/ui-chat, its npm package name, rather
than the @smarter/<name> of the console’s apps, and its build is its dist/. The web console’s
workbench, @smarter/workbench, imports it from there, as any React application does, so the
workspace builds it before the workbench (npm run build:deps). See
How the Web Console Hosts It.
Its npm scripts run from the package’s folder, or from smarter-console’s root with
-w @smarter.sh/ui-chat:
Script |
What it does |
|---|---|
|
Vite’s dev server, with |
|
Storybook, at http://localhost:6006. |
|
The package’s builds (see Builds), and |
|
The unit tests, and a coverage report in |
|
ESLint, and the TypeScript compiler. |
|
Generates |
|
Extracts, merges and compiles the translation catalogs. |
Running It
There are three ways to run Smarter Chat, from the fastest feedback to the most realistic.
Storybook, with the api mocked. No backend is needed. The stories’ api responses come from
MSW handlers in src/mocks/. When the Smarter dev server is running on
port 9357, the stories use the web console’s stylesheets, so they look as they do in the web
console; otherwise they use Bootstrap, which the web console’s theme is built on.
make storybook APP=smarter.sh-chat # from smarter-console's root, or
npm run storybook # from packages/smarter.sh-chat
Vite’s dev server, against your local Smarter. npm run dev, in the package, serves
index.html with hot module replacement, and proxies /api, /workbench and /static
requests to the Django dev server at http://localhost:9357. Log in to the web console first, so that
the session and CSRF cookies exist, and set smarter-llmclient-api-url in index.html’s root
element to the workbench url of one of your LLMClients, for example
http://localhost:9357/workbench/llm-clients/<hashed_id>/.
The web console itself. make build, in smarter-console, builds Smarter Chat’s library, then
the console, the workbench among its pages, into dist/. Then, in the Smarter repository,
make console-local CONSOLE_DIST=../smarter-console/dist installs that build into Django’s static
files, in place of the pinned release, and make collectstatic and make build put it in the
Docker image. Restart smarter-api, and open an LLMClient’s workbench. Alternatively,
npm run dev -w @smarter/console serves the console, with the chat, at http://localhost:5173/,
against the Smarter dev server.
Builds
npm run build runs the package’s two builds, into dist/:
The npm library |
The embed script |
|
|---|---|---|
Command |
|
|
Entry point |
|
|
Output |
ES and UMD bundles, |
|
React |
a peer dependency, not bundled |
bundled |
Mermaid |
left to the consuming page’s bundler |
its own ES module build, imported when a message first has a diagram |
KaTeX css and fonts |
left out; pages import |
in the shadow root, and the fonts beside |
Both builds strip console.debug calls, so use console.debug freely for development logging,
and never for anything a production user needs. npm run dev serves index.html, the chat
alone, for development; there is no app build.
src/index.ts is the package’s public api. Anything exported from it is a promise to the
package’s users: removing or renaming an export, or a prop, is a breaking change (see
Releases).
Architecture
Source layout
Path |
Responsibility |
|---|---|
|
The chat: state, the api calls’ orchestration, the header, the thread and the message box.
|
|
The title, with its valid and deployed icons. |
|
Displays a rendering error instead of an empty page. |
|
Every request to the Smarter api: urls, headers, the configuration, prompts, and the
prompt’s Server-Sent Events. The only module that calls |
|
The chat thread: building it from the configuration, turning api messages into displayable ones and back, and rendering markdown to sanitized html. |
|
Code blocks (highlight.js, collapsed when long), math (KaTeX, as a |
|
Messages that are data: pretty printed JSON, Smarter manifests, and CSV or TSV tables. Each detector is strict, so that prose stays markdown. |
|
SVG graphics (a |
|
Reading Django’s CSRF cookie, and the chat session and debug cookies. |
|
Message directions and sender roles. |
|
The props, and the shapes of the api’s data, as aliases of the generated contract types. |
|
The api contract: its JSON Schema, copied from the backend by |
|
Api fixtures and MSW handlers for the stories and tests, and test doubles. |
Components import from @/, an alias of src/.
What happens when the chat loads
SmarterChatbuilds its cookie descriptors (ChatCookies) and client context (ClientContext) from its props.Its first effect calls
startChat(), which callsfetchConfig(): a POST to<apiUrl>config/, with the session key from the session cookie, if there is one, andX-Smarter-Capabilities: chat-contract-v2.normalizeConfig()converts a version 1 configuration, from an older platform, to version 2.fetchConfig()saves the returnedsession_keyanddebug_modein their cookies, and returns theChatConfig.chatInit()builds the thread: the restoredhistory.chat_historyif there is one, else the system prompt, the welcome message and the example prompts.The header, placeholder and attach button are rendered from
config.llmclient, andonConfigpasses the whole configuration to the page, e.g. to the workbench’s Console.
A failure sets configError, which the thread and header display.
What happens when the user sends a message
sendMessage()adds the user’s message to the thread, and shows the typing indicator.chatMessages2RequestMessages()turns the thread into api messages: only the roles the LLM accepts (system,assistant,user,tool), each with its original fields, such as an assistant’stool_calls. Smarter’s own messages are never sent back.fetchPrompt()POSTs{session_key, messages}toconfig.llmclient.url_llmclient. WithstreamProgress, it asks for Server-Sent Events, and passes eachprogressevent toonProgress, which adds it to theprogressstate, displayed as a step in the thread.The result’s messages (
data.messagesin version 2,smarter.messagesin the completion in version 1) are added to the thread. Backend messages are hidden if the chat is in production mode. A failed prompt resolves too, with asmarter_errormessage.With
verbose,refreshConfig()fetches the configuration again, with its diagnostic parts, so that the page, e.g. the workbench’s Console, gets the session’s new tool calls.
See The Chat API Contract for the requests and responses themselves.
State
SmarterChat holds all of the chat’s state, with plain useState; there is no store.
State |
Meaning |
|---|---|
|
The |
|
Why the configuration couldn’t be loaded. |
|
The thread, as |
|
Sandbox mode ( |
|
A prompt is running, and its steps so far. |
|
Whether the configuration’s diagnostic parts are current: fetched with |
Rendering messages
Messages are displayed by chatscope’s
Message component, which takes html strings, not React elements. So message rendering is a
pipeline of strings, in messages.ts:
messageFactory()turns an api message into aChatMessage. A message from anyone that is only data goes throughdataHtml()indata.ts. Otherwise, the user’s messages go throughconvertMarkdownLinksToHTML(), which escapes them and converts only links and images, and every other role goes throughconvertMarkdownToHTML(). An assistant message that only calls tools goes throughtoolCallsHtml(), and is markedmetadata, so thattoggleMetadataMessages()displays it only in sandbox mode, as it does the backend’s own messages.convertMarkdownToHTML()parses GitHub flavored markdown withmarked, with the math extension frommath.ts, and custom renderers that escape raw html, restrict link and image urls, and render code blocks withcode.ts.The html is sanitized with DOMPurify, and only then displayed.
Because messages are html strings, their interactive parts can’t have React event handlers. The
code blocks’ Copy and Show all lines buttons, the diagrams’ and svg images’ Code buttons
and the media’s Download buttons are handled by one click listener on the chat, by event delegation
(copyCodeBlock(), toggleCodeBlock(), toggleMermaidDiagram(), toggleSvgCode() and
downloadMedia()). Mermaid renders
asynchronously, so a mermaid block is first rendered as a code block, and
renderMermaidDiagrams(), called in a layout effect whenever the messages change, replaces it in
the page with its diagram. Diagrams are cached by their source, so a re-render doesn’t redraw them.
Important
Every string that reaches a Message must come from messageFactory(), or be sanitized the
same way. Messages come from the LLM, from tools, and from users, and must never be trusted as
html.
Styling
Each component imports its own styles.css. Class names are prefixed smarter-chat-, because the
npm package’s css shares the page with its host’s. chatscope’s classes (cs-*) are overridden in
SmarterChat/styles.css.
Testing
Smarter Chat’s tests use Vitest and React Testing Library, with jsdom.
npm test # in packages/smarter.sh-chat
npm run coverage # with a coverage report in coverage/
npm run lint && npm run typecheck # ESLint and TypeScript
npx vitest run --project smarter.sh-chat # at smarter-console's root: only Smarter Chat's tests
make test # at smarter-console's root: every package, as CI does
make lint # formatting, lint and types of every package
One test module per source module, beside it:
api.test.tsforapi.ts,Component.test.tsxforComponent.tsx.Every story is also a test.
src/stories.test.tsxrenders each story in*.stories.tsx, and runs itsplayfunction, with its MSW handlers. A new visual state needs a story; a story that breaks fails the tests.The api is mocked with MSW, in tests and in Storybook alike.
src/mocks/fixtures.tsholds the api’s data, copied from real responses, andsrc/mocks/handlers.tsgroups handlers by scenario (chatHandlers,promptErrorHandlers,streamingHandlers, …). An unmocked request fails the test.jsdom has no
EventSource.installFakes()fromsrc/mocks/fakes.tsinstallsFakeEventSource, which a test drives withopen(),emit()andfail().The fixtures match the contract.
src/contract.test.tsvalidates them againstcontract/chat-contract.schema.jsonwith Ajv, in both versions of the contract, so a test can’t pass against a response that the backend never sends.jsdom can’t lay out Mermaid’s svg, so tests mock
mermaidwithsrc/mocks/mermaid.ts. Storybook’sWithDiagramstory uses the real Mermaid.
See the smarter-react-testing and smarter-chat-testing skills in smarter-console’s skills/
folder for the workspace’s shared test configuration and its pitfalls.
Common Changes
Adding a prop
Add it to
SmarterChatPropsinsrc/types.ts, optional, with a doc comment.Give it a default in
SmarterChat’s parameter list. The default must suit the npm package’s users.If the web console’s workbench sets it, pass it in the workbench’s
App.tsx(smarter-console’spackages/smarter-workbench), in the same change (see How the Web Console Hosts It).Add it to the props table of the README, and of Embedding Smarter Chat.
Test it, and add a story if it changes what the chat looks like.
Adding or changing text
Smarter Chat is translated with gettext, as the web console is (see
Translations), but its catalogs are its own, because the
npm package and the embed script run on pages that Django didn’t render. Its src/lib/i18n.tsx
has the same functions as @smarter/common: gettext, ngettext, pgettext,
npgettext, interpolate and interpolateNodes, and the same rules: a whole sentence, as a
string literal, with named %(name)s placeholders. Translate when the text is displayed, never in
a module-level constant, because SmarterChat activates its language as it renders.
Mark the text, e.g.
gettext("Start a new chat").npm run i18n, in the package.scripts/i18n.mjsextracts the messages with the TypeScript compiler intolocale/smarter-chat.pot, merges them intolocale/<language>/LC_MESSAGES/smarter-chat.po, keeping their translations, and compiles the.pofiles intosrc/catalogs.gen.ts, which the builds bundle.Translate the new
msgstrentries in every language’s.pofile (Spanish, French and Brazilian Portuguese), with the web console’s terms, and check them withmsgfmt --check -o /dev/null <file>.po.npm run i18nagain.src/catalogs.test.tsfails when a catalog is out of date, or a message isn’t translated, or its placeholders differ from the English text’s.
Using a new field of the configuration
The api’s types are not written by hand. They are generated from the contract’s JSON Schema, which the backend generates from its Pydantic models (see The Chat API Contract):
Declare the field in the backend’s model, in
smarter.apps.prompt.contract.models(for examplePromptChatApiLLMClientforllmclient.*), optional unless every supported Smarter release sends it. If the public configuration must include it, add it toPUBLIC_LLMCLIENT_FIELDStoo.Run
make chat-contract, from the Smarter repository’s root. It regenerates the backend’s schema,smarter/smarter/apps/prompt/contract/chat-contract.schema.json. Commit it together with the model.In smarter-console,
make contractscopies the schema into the package’scontract/chat-contract.schema.json, and regeneratessrc/contract.gen.ts. smarter-sh/automation’s weekly API Contract Sync proposes the same copy, as a pull request, when you don’t.Add the field to
makeConfig()insrc/mocks/fixtures.ts.src/contract.test.tschecks the fixtures against the schema, and thatsrc/contract.gen.tsis up to date.Read it, with a fallback for platforms that don’t send it yet, and for version 1 of the contract, which
normalizeConfig()insrc/lib/api.tsconverts.
Handling a new kind of progress event
Nothing is required: the chat displays any progress event’s message. To treat a type
specially, switch on event.type in SmarterChat’s onProgress, and add an example to
progressEvents in src/mocks/fixtures.ts. The types are listed in
PromptProgressEvents.
Adding a Console tab
The Console is the workbench’s (smarter-console’s packages/smarter-workbench), not Smarter Chat’s. Add the tab’s id to MenuItems in Console/enums.ts, its label to tabs()
in Console/Component.tsx, and its data to consoleData() in Console/data.ts, which reads it
from the configuration that onConfig passes. A tab that fetches its own data, as the Manifest and
Deployment tabs do, uses useTabData().
Extending markdown
Add a marked extension or renderer in messages.ts, following math.ts. Anything it emits
passes through DOMPurify; if it emits tags or attributes that DOMPurify removes, allow exactly those
in sanitize(), never more. Add a fixture with an example to src/mocks/fixtures.ts, and a
story.
Releases
@smarter.sh/ui-chat is released with the web console, and has its version (1.x; the 0.x
versions were the Smarter platform’s, when the package was published from the Smarter repository).
Commit messages follow Conventional Commits, and
semantic-release versions smarter-console from them on
each push to alpha and beta (prereleases) and main: feat is a minor release, fix
and perf are patches, and a BREAKING CHANGE: footer is a major release. Each GitHub release
that semantic-release publishes starts smarter-console’s .github/workflows/uiChatRelease.yml,
which publishes the package only when the release changed it: it checks out the release’s tag, sets
the package’s version from it (v1.2.0-alpha.1 publishes 1.2.0-alpha.1), runs the package’s
tests, builds it, checks the build with npm run check:dist, and publishes it to npm with trusted
publishing and a provenance statement. A release from main gets the npm dist-tag latest, and
a prerelease gets its channel’s, alpha or beta, so npm install @smarter.sh/ui-chat and the
embed script’s jsDelivr ranges, such as @1, only ever load latest releases; the workflow asks
jsDelivr to refresh those ranges after each one. @smarter.sh/ui-widgets is published the same
way, by uiWidgetsRelease.yml. The package’s design decisions are recorded in its own ADRs, in
packages/smarter.sh-chat/doc/adr/.
Keep two audiences in mind when you change behavior that depends on the backend:
The web console always runs the Smarter Chat that was built into the console release that the backend pins in
smarter-console-version.txt, so the two change together when the pin does.Pages that embed the npm package run whichever version they installed, against whichever Smarter platform they call. A new version of the chat must keep working with the platform releases that are in use, and the platform must keep working with the chat versions that are in use. Read the fields you depend on defensively, and say in the release notes when a feature needs a newer platform.