Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

client-integration.md

187 lines5.8 KB

1---
2title: Showing Code Mode in the UI
3id: code-mode-client-integration
4order: 2
5description: "Show the code that the model wrote, each tool call, and the result while Code Mode runs, with onCustomEvent."
6keywords:
7 - tanstack ai
8 - code mode
9 - react ui
10 - custom events
11 - onCustomEvent
12 - streaming ui
13 - execution progress
14---
15​
16Stream Code Mode events to the client so the UI shows each sandbox step. The user then sees the run before the final answer.
17​
18Code Mode sends custom events while it runs. Catch them with `onCustomEvent` in `useChat`, and show the code, each tool call, and the result in the chat.
19​
20## Quick setup
21​
22You need the Code Mode route from the [Code Mode quick setup](./code-mode#quick-setup). Then replace your chat component with this one:
23​
24```tsx
25import { useState } from "react";
26import { parsePartialJSON } from "@tanstack/ai";
27import { useChat, fetchServerSentEvents } from "@tanstack/ai-react";
28​
29interface CodeModeEvent {
30 eventType: string;
31 data: unknown;
33​
34function isRecord(value: unknown): value is Record<string, unknown> {
35 return typeof value === "object" && value !== null;
37​
38export function CodeModeChat() {
39 const [input, setInput] = useState("");
40 const [events, setEvents] = useState<Record<string, Array<CodeModeEvent>>>(
41 {},
42 );
43​
44 const { messages, sendMessage, isLoading } = useChat({
45 connection: fetchServerSentEvents("/api/chat"),
46 threadId: "support-chat",
47 // Keep each event under the execute_typescript call that sent it.
48 onCustomEvent: (eventType, data, { toolCallId }) => {
49 if (!toolCallId) return;
50 setEvents((prev) => ({
51 ...prev,
52 [toolCallId]: [...(prev[toolCallId] ?? []), { eventType, data }],
53 }));
54 },
55 });
56​
57 return (
58 <>
59 {messages.map((message) => (
60 <div key={message.id}>
61 {message.parts.map((part, index) => {
62 if (part.type === "text") {
63 return <p key={index}>{part.content}</p>;
64 }
65 if (
66 part.type === "tool-call" &&
67 part.name === "execute_typescript"
68 ) {
69 return (
70 <CodeExecutionPanel
71 key={part.id}
72 args={part.arguments}
73 output={part.output}
74 events={events[part.id] ?? []}
75 />
76 );
77 }
78 return null;
79 })}
80 </div>
81 ))}
82 <form
83 onSubmit={(event) => {
84 event.preventDefault();
85 if (input.trim() === "") return;
86 sendMessage(input);
87 setInput("");
88 }}
89 >
90 <input value={input} onChange={(event) => setInput(event.target.value)} />
91 <button type="submit" disabled={isLoading}>
92 Send
93 </button>
94 </form>
95 </>
96 );
98​
99function CodeExecutionPanel({
100 args,
101 output,
102 events,
103}: {
104 args: string;
105 output: unknown;
106 events: Array<CodeModeEvent>;
107}) {
108 // The arguments stream in as partial JSON, so the code shows while the model writes it.
109 const parsed: unknown = parsePartialJSON(args);
110 const code =
111 isRecord(parsed) && typeof parsed.typescriptCode === "string"
112 ? parsed.typescriptCode
113 : "";
114​
115 return (
116 <div>
117 <details open>
118 <summary>TypeScript code</summary>
119 <pre>
120 <code>{code}</code>
121 </pre>
122 </details>
123 <ul>
124 {events.map((event, index) => (
125 <li key={index}>{describeEvent(event)}</li>
126 ))}
127 </ul>
128 <pre>{describeResult(output)}</pre>
129 </div>
130 );
132​
133function describeEvent({ eventType, data }: CodeModeEvent): string {
134 if (!isRecord(data)) return eventType;
135 switch (eventType) {
136 case "code_mode:execution_started":
137 return "Started";
138 case "code_mode:console":
139 return `[${String(data.level)}] ${String(data.message)}`;
140 case "code_mode:external_call":
141 return `Call ${String(data.function)}(${JSON.stringify(data.args)})`;
142 case "code_mode:external_result":
143 return `Done ${String(data.function)} in ${String(data.duration)} ms`;
144 case "code_mode:external_error":
145 return `Failed ${String(data.function)}: ${String(data.error)}`;
146 case "code_mode:execution_finished":
147 return `Finished in ${String(data.durationMs)} ms`;
148 default:
149 return eventType;
150 }
152​
153function describeResult(output: unknown): string {
154 if (output === undefined) return "Running...";
155 if (!isRecord(output)) return JSON.stringify(output, null, 2);
156 if (output.success === false) {
157 const message = isRecord(output.error) ? output.error.message : undefined;
158 return `Error: ${String(message ?? "unknown error")}`;
159 }
160 return JSON.stringify(output.result, null, 2);
162```
163​
164Send "Compare the weather in Tokyo, Paris, and New York City." The chat now shows the code that the model wrote, one line for each `external_fetchWeather` call, and the final result.
165​
166## How it works
167​
168- Code Mode sends custom events through the chat stream, next to the normal text and tool-call chunks.
169- `onCustomEvent` gets three arguments: the event type, the payload, and a context with the `toolCallId`.
170- The `toolCallId` is the `id` of the `execute_typescript` tool-call part. Use it to show each event under the right call.
171- When the execution ends, `part.output` holds the [result](./code-mode#the-result-of-execute_typescript): `success`, `result`, `logs`, and `error`.
172​
173For the full list of events and their payloads, see [Custom events](./code-mode#custom-events).
174​
175## Other frameworks
176​
177`onCustomEvent` comes from `ChatClient` in `@tanstack/ai-client`, which every framework package uses. Pass it in the same way:
178​
179- **React, Preact, Solid, Vue:** `useChat({ onCustomEvent })`.
180- **Svelte:** `createChat({ onCustomEvent })`.
181- **Angular:** `injectChat({ onCustomEvent })`.
182​
183The callback has the same signature everywhere:
184​
185```typescript ignore
186(eventType: string, data: unknown, context: { toolCallId?: string }) => void
187```