A chat for analytics users
AnalyticsChat is a chat for people who work with data. The conversation is always there; everything else appears only when you pass its prop:
sessions: saved conversations, listed in a Conversations panel to search, filter, sort and group, and each conversation saved as it goes.attachFiles: a+button, and files dropped or pasted on the box. Any file is offered (acceptnarrows the picker); your function says which became data (aDataRef), which is a picture to show as a thumbnail (attachment), which it handled itself (taken) and why the others did not.browse: an "Add data" button and a Data panel with tables (ObjectBrowser) and files (FileBrowser). Names go to the agent, never values.agents: a Model menu, and one Agent setup menu whose sections (Agent, Skills, Connectors) open in place, filled fromDescribeAgents. Short lists are menus in the composer; each ends in "View all…" or "Manage…", which opens its panel on the rail to the right.speech: a microphone that dictates, and a Talk button for a spoken conversation that sends after a pause, reads the reply and listens again. It stops when a reply needs a decision.
Send is a round arrow. With none of these props it is a plain conversation with no workspace.
The agent says what a person may choose. offer on toolCallingAgent lists the models, skills (text added to the system prompt while on) and connectors (sets of tools, on or off). The backend refuses anything it did not list:
agent.ts:
import { type AgentBackend, type DescribesAgents, type ModelChunk, type ToolCallingAgentOptions, dataTools, toolCallingAgent } from "@surfaces-ui/agent";
import type { DataSource } from "@surfaces-ui/data";
/**
* What a person may choose for this agent: two models, two skills and one
* connector. The backend checks every turn against it; the client is never
* trusted to turn on something not listed.
*/
export function analystAgent(dataSource: DataSource, complete: ToolCallingAgentOptions["complete"]): AgentBackend & DescribesAgents {
const tools = dataTools(dataSource);
return toolCallingAgent({
system: "You answer questions about the person's data.",
tools,
complete,
offer: {
id: "analyst",
name: "Analyst",
models: [
{ id: "claude-sonnet-5-5", label: "Claude Sonnet 5.5" },
{ id: "claude-opus-5-5", label: "Claude Opus 5.5" },
],
defaultModel: "claude-sonnet-5-5",
skills: [
{ id: "charts", name: "Chart standards", text: "Bars start at zero. One y scale.", defaultOn: true },
{ id: "terse", name: "Short answers", text: "Answer in two sentences at most.", defaultOn: false },
],
// Tools no connector names are always on; these are on only while the connector is.
connectors: [{ id: "catalog", name: "Data catalog", description: "List and describe tables", tools: tools.map((t) => t.name) }],
},
});
}
/** A stand-in for a model, for the test: it says which model it was asked to be. */
export async function* echoModel({ model }: { model?: string }): AsyncIterable<ModelChunk> {
yield { type: "text", delta: `Answered by ${model}.` };
yield { type: "done", model: model ?? "" };
}The page asks the agent what it offers and keeps conversations in a surface library, so they also show in a Library as saved surfaces of kind conversation. With your server, connectAgent({ baseUrl }) from @surfaces-ui/client-connect has both send and describeAgents:
App.tsx:
import { AnalyticsChat, type AttachResult, browserSpeech, librarySessions } from "@surfaces-ui/chat";
import type { AgentBackend, DescribesAgents } from "@surfaces-ui/agent";
import { DataSourceProvider } from "@surfaces-ui/components";
import { type DataSource, type SurfaceLibrary } from "@surfaces-ui/data";
import type { AgentInfo } from "@surfaces-ui/proto";
import { useEffect, useMemo, useState } from "react";
export interface AnalyticsChatPageProps {
/** `connectAgent({ baseUrl })` in a real app; anything with `send` and `describeAgents`. */
agent: AgentBackend & DescribesAgents;
dataSource: DataSource;
/** Where conversations are kept: `memorySurfaceLibrary({ storage: browserStorage() })`, or your server's library. */
library: SurfaceLibrary;
sourceId: string;
/** Turn on voice only when the person chose it: the browser's speech service may send audio away. */
voice?: boolean;
}
export function AnalyticsChatPage({ agent, dataSource, library, sourceId, voice }: AnalyticsChatPageProps) {
const [agents, setAgents] = useState<AgentInfo[]>([]);
useEffect(() => {
void agent.describeAgents().then((r) => setAgents(r.agents));
}, [agent]);
const sessions = useMemo(() => librarySessions(library), [library]);
const speech = useMemo(() => (voice ? browserSpeech() : undefined), [voice]);
// Your own rule for files: here every file is named and refused, since this server reads only its own tables.
const attachFiles = async (files: File[]): Promise<AttachResult[]> => files.map((file) => ({ file, error: "This server reads only its own tables." }));
return (
<DataSourceProvider dataSource={dataSource}>
<AnalyticsChat
agent={agent}
agents={agents}
sessions={sessions}
attachFiles={attachFiles}
browse={{ sourceId }}
speech={speech}
starters={["What tables are there?"]}
height={640}
/>
</DataSourceProvider>
);
}Voice listens only once the person agrees: pass speechConsent and the microphone's first press asks, saying where audio goes; or pass speech only after they turned it on. browserSpeech() uses the browser's own speech service; in Chrome that sends audio to Google, and its label says so. Pass your own SpeechAdapter to use another service.
The test picks a model from the menu, sends a question, sees that the turn ran on that model, and finds the conversation in the library:
analytics-chat.test.tsx:
// @vitest-environment jsdom
import { memoryDataSource, memorySurfaceLibrary } from "@surfaces-ui/data";
import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { afterEach, describe, expect, it } from "vitest";
import { AnalyticsChatPage } from "./App.js";
import { analystAgent, echoModel } from "./agent.js";
afterEach(cleanup);
describe("analytics chat recipe", () => {
it("offers the agent's models and skills, runs a turn on the chosen model, and keeps the conversation", async () => {
const dataSource = memoryDataSource({ sourceId: "shop", tables: { orders: [{ order_id: 1, amount: 10 }] } });
const library = memorySurfaceLibrary();
render(<AnalyticsChatPage agent={analystAgent(dataSource, echoModel)} dataSource={dataSource} library={library} sourceId="shop" />);
fireEvent.click(await screen.findByRole("button", { name: "Model: Claude Sonnet 5.5" }));
fireEvent.click(screen.getByRole("radio", { name: /Claude Opus 5.5/ }));
fireEvent.change(screen.getByLabelText("Message"), { target: { value: "How many orders?" } });
fireEvent.click(screen.getByRole("button", { name: "Send" }));
expect(await screen.findByText("Answered by claude-opus-5-5.")).toBeTruthy();
// Saved to the library as a conversation, titled from the question.
await waitFor(async () => expect((await library.listSurfaces({})).surfaces.map((s) => s.title)).toEqual(["How many orders?"]));
});
});Not verified here: speech in a real browser (the chat package tests the loop with a fake adapter), and a live model.
Source and test: apps/recipes/src/analytics-chat