@aintela/chat

中文文档
0.14.2发布于 2026/10/29TypeScriptES Module近 30 天下载 3392

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

原始使用文档
文档目录14 节
  1. Layout
  2. Develop
  3. Consuming
  4. UI-tools codegen ( aia-gen-uitools )
  5. TurnAwareButton — controls drawn inside a chat message
  6. Turns this tab did not send, and a detached run as a transc…
  7. Component names (breaking in 0.3.0)
  8. One engine, one agent (breaking in 0.3.0)
  9. Testing
  10. Releasing
  11. 1. Bump + commit + tag + push
  12. 2. Update consumers
  13. Quick smoke-test before tagging
  14. Scope

@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 @aia org 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 + config
  • dist/ — built output, gitignored; shipped in the npm tarball (built on prepack/prepare via vite 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.x0.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.ts replace the whole IWebSocketConnection. Use these when the code under test is the gateway or anything above it — they let you deliver() parsed server events directly.
  • tests/fakes/fakeRawWebSocket.ts replaces the browser WebSocket global, one layer lower. Use it when the code under test is WebSocketConnecionV2 itself (dial URL, resume cursor, reconnect loop), so all of connect() 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:coverage has produced coverage/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 @aintela org / package registers a Trusted Publisher for repo envision-tecnologia/aichat, workflow publish-aia-chat.yml. A token fallback (NPM_TOKEN secret → 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 autoCreateSession defaulting to false, 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.

版本与发布记录

@aintela/chat 共发布 104 个版本,首次发布于 2026/07/02;过去 12 个月发布了 104 个版本。

版本发布日期距今
0.14.2latest2026/10/299 天前
0.14.12026/10/299 天前
0.14.02026/10/2711 天前
0.13.22026/10/2513 天前
0.13.12026/10/2117 天前
0.13.02026/10/2118 天前

关于 @aintela/chat 的常见问题

@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

如何安装 @aintela/chat?

在项目目录运行 npm install @aintela/chat,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:axios(^1.0.0)、dayjs(^1.0.0)、react(^18.2.0)、lodash(^4.17.0)、zustand(^5.0.12)、date-fns(^4.0.0)、notistack(^3.0.0)、react-dom(^18.2.0)、typedjson(^1.8.0)、rehype-raw(^7.0.0)、remark-gfm(^4.0.0)、use-debounce(^10.0.0)、@mui/material(^7.0.0)、@emotion/react(^11.14.0)、react-markdown(^10.0.0)、@emotion/styled(^11.14.0)、react-router-dom(^7.0.0)、reflect-metadata(^0.2.2)、@mui/icons-material(^7.0.0)、@mui/x-date-pickers(^8.0.0)、react-syntax-highlighter(^16.0.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。它还提供命令行工具 aia-gen-uitools,可以用 npx aia-gen-uitools 直接运行。

@aintela/chat 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@aintela/chat 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@aintela/chat 可以商用吗?

@aintela/chat 使用 未声明 许可。package.json 没有声明许可证。没有许可证的代码默认保留全部权利,商用前请联系作者或查看仓库中的 LICENSE 文件。以上为概括,不构成法律意见,请以许可原文为准。

@aintela/chat 的下载量有多少?

根据 npm 官方下载统计,@aintela/chat 在 2026/10/05 – 2026/11/03 这 30 天内被下载 3,392 次,日均约 113 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@aintela/chat 还在维护吗?

最新版本 0.14.2 发布于 2026/10/29(9 天前);至今共发布 104 个版本,其中过去 12 个月发布了 104 个;首次发布于 2026/07/02。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。