@aintela/chat
Embeddable AI chat component built on a WebSocket agent gateway. This repo
is the standalone home for what was previously
packages/library/src/components/AiChat/ in envision-abi — extracted into a
real library (built, versioned, peer-dep'd) instead of in-tree source aliasing,
and published to the public npm registry.
Name history:
@envision/aichat→@aia/chat→@aintela/chat(the npm@aiaorg was taken). Always install and import@aintela/chat.
Layout
This repo is the published package (@aintela/chat) at its root:
src/,package.json,vite.config.ts,tsconfig.json— library source + configdist/— built output, gitignored; shipped in the npm tarball (built onprepack/prepareviavite build)examples/demo/— Vite + React SPA that exercises the library against a fake agent gateway, with an option to point at a real WSServer
Develop
npm install
cd examples/demo && npm install && npm run dev # http://localhost:5174
Previewing the phantom ghost without a server. The flat scenario passes promptGhostDebugKey="|"
(an AiChat / AiChatProvider prop, development only): typing | in the composer is swallowed and paints the
@ … ghost at the caret — location on the first press, person on the next — with mid-sentence detected from the
caret, so the mid-sentence card can be looked at by putting the caret inside a sentence. Tab accepts, Esc dismisses,
and the next keystroke's analyze clears it as it would a real one. Leave the prop unset in production.
The demo aliases the package to the root src/ during development so HMR works
across the package boundary. To validate the built bundle the way a real
consumer would:
npm run build
# then remove the alias in examples/demo/vite.config.ts (or use npm link)
Consuming
@aintela/chat is published to the public npm registry — install it like
any package and pin a normal semver range:
npm install @aintela/chat
{
"dependencies": {
"@aintela/chat": "^0.2.16"
}
}
The tarball ships the prebuilt dist/ (see the files field in package.json),
so consumers don't build anything on install.
Subpath entry points are exported for focused imports: @aintela/chat (root),
plus @aintela/chat/models, /services, /components, /hooks, /utils,
/interfaces, and the stylesheet @aintela/chat/style.css.
Every peer in peerDependencies must be installed by the consumer at a
compatible version — that's how shared singletons (React, MUI ThemeContext,
Zustand stores, reflect-metadata's patched Reflect, notistack's
SnackbarProvider) end up as exactly one instance per app instead of two.
UI-tools codegen (aia-gen-uitools)
The package ships a bin, aia-gen-uitools, that turns the server's UI-tools manifest (the JSON
written by the AgentsSdk's UiToolsManifest.PublishManifest(...)) into typed TypeScript:
uiContracts.generated.ts (the per-tool args/input/answer/result interfaces) and
aiaUiTools.generated.ts (a typed registry builder with one method per tool — ask-user AND render —
each bound to its generated interfaces). A consumer app wires ONE npm script chaining the server
manifest export and the generation:
"gen:uitools": "dotnet run --project ../path/to/Server.UiToolsManifest -- src/agent/generated/uitools.manifest.json && aia-gen-uitools src/agent/generated/uitools.manifest.json src/agent/generated"
Every C# contract becomes ONE interface, under its own name. The manifest carries each object's C#
type name as a JSON-Schema title (UiToolsManifest stamps it), and the generator lifts each titled
type into $defs and references it from every payload that embeds it — so RescheduleQuoteCardArgs
gets replacing?: RescheduleQuoteFlight[], and RescheduleQuoteFlight is declared once however many
tools carry one.
That matters because of what it replaced. JSON Schema keeps no record of the type a sub-object came
from, so a nested type could only be named after its POSITION — and the position of every array element
is the key items. Every nested list in every tool therefore emitted as one interface called Items,
and the second shape to claim the name was dropped in favour of the first with only a warning: a
reschedule-quote flight typechecked as an expense-report line, tsc accepted expenseId on a flight,
and nothing failed. Two different shapes claiming one name now stops the run and writes nothing,
naming both. A manifest published by an older server carries no titles; the generator then names a
hoisted element after its owner (RescheduleQuoteCardArgsReplacingItem) rather than after items —
correct, ugly, and a prompt to republish the manifest.
TurnAwareButton — controls drawn inside a chat message
A UI-tool component is rendered while the agent is still streaming its turn (a
present_tripstretch card appears mid-sentence), and acting on it then races the run
that is still writing to the session. Use TurnAwareButton instead of MUI's Button
for any control inside a chat-rendered component: while the turn is open it is
disabled and spinning. The spinner is the point — someone clicking a card mid-turn
has usually just not noticed the agent is still writing, so the button both refuses
the click and shows why, instead of sitting there inertly dead.
import { TurnAwareButton } from '@aintela/chat';
// Return the promise so the button keeps waiting across the gap between sending and
// the server's `open_turn` — otherwise it briefly offers itself for a second click.
<TurnAwareButton variant="contained" onClick={() => sendMessage('escolhi a opção 2')}>
selecionar ida
</TurnAwareButton>
Outside an <AiChat> provider there is no turn, so it behaves exactly like Button —
a component shared between the chat and a plain page needs no branch. The same live
flag is available on its own as useTurnOpen()
(prefer it over UiToolContext.onGoing, which is a per-surface snapshot: false
forever on a card that has settled into history, even while a later turn streams).
Turns this tab did not send, and a detached run as a transcript (AIA Issue 1548)
The server announces every turn with an InteractionStarted frame before its first delta. A
turn this tab did not send — a WhatsApp message, a platform turn after a task settled, another
tab's turn — opens with its text as the user's bubble and a small origin badge ("WhatsApp",
"Plataforma", "API"; override the words with interactionOriginLabels). It never takes the
place of a local turn that is still streaming, and neither turn unlocks the composer for the
other. History reload reads the same origin from the session (InteractionOriginContent).
DetachedRunTranscript draws one detached run as a read-only chat — the same engine and
ChatPane, fed by the run's frames stream (GET /detached-runs/{id}/frames, SSE read over
fetch because the route needs a bearer):
import { DetachedRunTranscript } from '@aintela/chat';
<DetachedRunTranscript
runId={runId}
baseUrl={agentsServerUrl}
fetchImpl={authenticatedFetch} // or getToken={() => token}; default: user.access_token
getUser={readLiveUser} // whose token reads the run's artifacts
uiTools={uiTools} // any <AiChat> presentation prop passes through
onUnauthorized={refreshToken} // on a 401: refresh, resolve true ⇒ one retry with the fresh token
onError={(e) => setStopped(e.kind)} // 'notFound' | 'forbidden' | 'unauthorized' | 'gaveUp'
resumeKey={answersSent} // change it after answering: the stream ends when the run stops
footer={<AnswerComposer runId={runId} />}
/>
DetachedRunTaskBox polls the run's record (the source of truth) and, given the same baseUrl +
fetchImpl/getToken, follows its frames while it is Pending/Running: a one-line activity ticker
and a task list that moves the moment the agent updates it. "ver detalhes" mounts the run's
DetachedRunTranscript inline (uiTools / partRenderers pass through). onSettled(run) fires
once per settle the conversation was not told about (run.announced === false); answer it with
engine.announceDetachedRun(run.id, run.settledAt), which sends the AnnounceDetachedRun socket
action — held while a turn is open in this tab, deduped per settle — and the server's announcement
arrives as an ordinary platform turn.
A host with its own <AiChat> wrapper takes the engine instead —
const { engine } = useDetachedRunTranscript({ runId, baseUrl, … }), then
<MyScopedAiChat engine={engine}><ChatPane /></MyScopedAiChat> with hidePromptInput. The
reader on its own is streamDetachedRunFrames(…) (services).
Component names (breaking in 0.3.0)
Every v2 component is exported under its plain name — AppBar, Prompt,
TaskList, RunProgressStrip — and again under its historical …V2 name as an
alias, so no existing import breaks. Prefer the plain names.
The suffix existed to separate these from a v1 layer that no longer exists: the
last four v1 components (Prompt, LastPrompts, TaskList, DetachedRunBox) were
deleted in 0.3.0 after confirming nothing consumed them, and the two
AiChatFloating implementations were merged into one. Gone with them are the
props that selected the v1 renderers — compactPrompt, showTaskList
and showDetachedRuns. The prompt is always the compact one now; the task list
and detached run trace live in the RunProgress panel.
One engine, one agent (breaking in 0.3.0)
The AgentContext — which agent answers — is owned by the engine, and by nothing
else. It is supplied exactly once, when the engine is created, and the gateway stamps
AgentId on every frame from it. Before 0.3.0 three different public inputs accepted a
context for the same conversation and only one of them decided anything, so a surface
could bind, stamp and pass expense-agent everywhere and still send every turn as the
app-default agent, with nothing failing.
// One hook per agent. The registry key is DERIVED from the agent, so "same key,
// different agent" cannot be expressed.
export const useExpenseChatEngine = () => useAgentEngine(expenseConfig()); // key: 'expense-agent'
const { engine } = useExpenseChatEngine();
await engine.openLiveSession(sessionId); // no context to pass, so none to get wrong
<AiChat engine={engine} /> // adopting: `agentContext` is a compile error here
<AiChat agentContext={ctx} … /> // building its own engine: the one place it belongs
Pass useAgentEngine(config, { scope }) for two independent conversations with the
same agent. To switch agent inside a live conversation there is
engine.forceAgentContext(ctx) — deliberately ugly, because the session already holds
another agent's history and the server stamps Session.AgentId on the first turn only,
so the conversation keeps reporting the agent it started as. Prefer a second engine.
Routine, non-identity changes have plain setters: setCustomer, setModel.
Migration from 0.2.x — every removal is a compile error at the call site, by design:
| 0.2.x | 0.3.0 |
|---|---|
useLiveSession(config, { key }) | useAgentEngine(config, { scope }) — drop the key |
<AiChat engine={e} agentContext={ctx} /> | <AiChat engine={e} /> |
engine.openLiveSession(ctx, id) | engine.openLiveSession(id) |
mgr.bindAndOpenLiveSession(ctx, id, opts) | mgr.bindAndOpenLiveSession(id, opts) |
mgr.createSession(ctx, id) / mgr.retrieveSession(ctx, id) | mgr.createSession(id) / mgr.retrieveSession(id) |
gateway.setAgentContext(ctx) / engine.setAgentContext(ctx) | forceAgentContext(ctx) — most hosts call neither |
| — | new: engine.getAgentContext(), engine.setCustomer(), engineKeyFor() |
Testing
Vitest runs the unit + integration suite. Co-located *.test.ts files
live next to the source they cover; shared fixtures + fakes live under
tests/ and are imported via the @tests/* path alias.
The default environment is node; a test that needs a DOM opts in per file with a
// @vitest-environment happy-dom pragma (see TurnAwareButton.test.tsx).
npm test # one-shot run
npm run test:watch # watch mode
npm run test:coverage # generates coverage/ (html + lcov + json-summary)
Two fakes sit at different depths, and picking the wrong one is the usual reason a test proves nothing:
tests/fakes/makeGateway.ts+fakeWebSocket.tsreplace the wholeIWebSocketConnection. Use these when the code under test is the gateway or anything above it — they let youdeliver()parsed server events directly.tests/fakes/fakeRawWebSocket.tsreplaces the browserWebSocketglobal, one layer lower. Use it when the code under test isWebSocketConnecionV2itself (dial URL, resume cursor, reconnect loop), so all ofconnect()stays real.
test:coverage enforces a ratchet (thresholds in vitest.config.ts) set
just under today's numbers. It exists to stop coverage sliding backwards, not to
describe a target — raise it when a batch of tests lands, and never lower it to
turn a red run green.
CI (.github/workflows/ci.yml) runs on every PR and every push to main:
typecheck → tests + coverage (the ratchet, so a drop fails the run) → library
build → demo typecheck. The build is included because the npm tarball ships a
prebuilt dist/, and the demo because it consumes the library through a source
alias and so catches breaking API changes the library's own typecheck cannot
see. Each run's summary page carries the coverage table and the ten biggest gaps
by uncovered statements; the full HTML report is attached as an artifact.
VS Code wiring (auto-installed via .vscode/extensions.json):
- Vitest extension surfaces pass/fail gutters next to each
it(...)and a tree view in the Test panel. - Coverage Gutters paints green/red strips on the side of source
files once
npm run test:coveragehas producedcoverage/lcov.info. Trigger with "Coverage Gutters: Display Coverage" from the command palette.
Open coverage/index.html in a browser for the drill-down report.
Releasing
Cut a release whenever you ship a behavior change (bugfix, new prop, breaking
API change). Publishing is tag-driven: pushing a v<semver> tag runs the
publish-aia-chat.yml workflow, which npm publishes to the public npm registry
via npm Trusted Publishing (OIDC — no stored token) with build provenance.
access: public comes from package.json's publishConfig.
1. Bump + commit + tag + push
From the repo root, after the change is committed on main:
# 1. bump version in package.json (semver: patch / minor / major)
npm version patch --no-git-tag-version # 0.2.16 → 0.2.17 (bugfix)
# npm version minor --no-git-tag-version # 0.2.x → 0.3.0 (new prop / feature)
# npm version major --no-git-tag-version # 0.x.y → 1.0.0 (breaking)
# 2. commit the bump
git add package.json
git commit -m "vX.Y.Z: <one-line summary of what changed>"
# 3. tag the commit + push branch and tag together
git tag -a vX.Y.Z -m "vX.Y.Z — <short release note>"
git push origin main vX.Y.Z
The pushed vX.Y.Z tag triggers CI (npm ci + npm publish --provenance). The
tag version and the package.json version must match. You can also run the
workflow manually (workflow_dispatch) to publish whatever version is currently
in package.json.
--no-git-tag-version on npm version is deliberate: it bumps package.json
without creating its own commit/tag, so you control the commit message and tag
annotation explicitly (npm's defaults are ambiguous when the bump rides alongside
the substantive change).
One-time setup (already done, noted here for recovery): on npmjs.com, the
@aintelaorg / package registers a Trusted Publisher for repoenvision-tecnologia/aichat, workflowpublish-aia-chat.yml. A token fallback (NPM_TOKENsecret →NODE_AUTH_TOKEN) is stubbed in the workflow if OIDC ever needs to be bypassed.
2. Update consumers
Each consumer bumps its semver range (or just reinstalls, if the existing range already covers the new version):
- "@aintela/chat": "^0.2.16",
+ "@aintela/chat": "^0.2.17",
npm install @aintela/chat
Quick smoke-test before tagging
v0.1.1 shipped with a part-eventType bug that the demo surfaced within seconds.
Before pushing a tag, give it a minute:
npm run build && npm run typecheck # at repo root
cd examples/demo && npm install && npm run dev
Open the Flat tab in the demo, send a prompt, watch the streamed reply render and stay rendered. Switch tabs and back. If anything renders and disappears, the fix isn't ready to tag.
Scope
v0.1 carves the chat-essential subset out of the old library:
- AiChat component + ChatPane + variants (Drawer, Floating)
- AgentGatewayWS + WebSocket connection + event bus
- Session lifecycle (SessionStateManagerService) — with
autoCreateSessiondefaulting tofalse, opposite of the old default - LlmResponseRender + EnvironmentProvider + LiveTsxConfigProvider
- Models: Interaction, InteractionPart, ChatSession, ClientMessage, etc.
- Interfaces: ISessionService, IArtifactService, IStorageService — the library ships interfaces, hosts plug in implementations
Out of scope: admin Settings UI, dashboard rendering primitives, viz library,
v2 app chrome, the Node/Mongo/Express server bundle. Those live in (or move
back to) envision-abi/packages/dashboard-app.