@base44-preview/platform 0.5.0-pr.346.138d91a → 0.5.0-pr.353.5c12c6c

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,9 +1,8 @@
1
1
  import type { PlatformEvent, PlatformSnapshot } from "./chat.events.types.js";
2
2
  import type { PlatformSocketError } from "../errors.js";
3
3
  /**
4
- * The response body of [Create socket session](/api-reference/create-socket-session), which your
5
- * `getSession()` callback returns. Pass the response through unchanged. The client reads the three
6
- * fields below.
4
+ * The three fields of a [Create socket session](/api-reference/create-socket-session) response that
5
+ * the browser needs. Keep the response's `session_id` on your server.
7
6
  */
8
7
  export interface SocketSession {
9
8
  /** Token that authenticates the socket. The client keeps it in memory and sends it only when the socket connects. */
@@ -18,13 +17,15 @@ export interface ChatInitOptions {
18
17
  /**
19
18
  * Returns a new socket session from your server.
20
19
  *
21
- * Return the response body of [Create socket session](/api-reference/create-socket-session) as a
22
- * [`SocketSession`](#socketsession), and return a new session on every call. The client calls
20
+ * Return the `session_token`, `socket_url`, and `socket_path` of a
21
+ * [Create socket session](/api-reference/create-socket-session) response as a
22
+ * [`SocketSession`](#socketsession), and keep its `session_id` on your server. Return a new
23
+ * session on every call. The client calls
23
24
  * `getSession()` on the first {@linkcode ChatSession.connect | connect()}, and again only when
24
25
  * the session expires or Base44 rejects its token. If a new session has a different `socket_url`
25
26
  * or `socket_path`, the client moves to it and rejoins every active subscription.
26
27
  *
27
- * @returns The session, as your server received it.
28
+ * @returns The session's `session_token`, `socket_url`, and `socket_path`.
28
29
  */
29
30
  getSession: () => Promise<SocketSession>;
30
31
  /**
@@ -52,8 +53,7 @@ export interface ChatModule {
52
53
  *
53
54
  * Pass a `getSession()` callback in the options. The client calls it to get a
54
55
  * [socket session](/developers/references/apps-api/sections/socket-sessions), which your server
55
- * opens with [Create socket session](/api-reference/create-socket-session) and returns as the
56
- * response body. Each session is independent and gets its own socket session.
56
+ * opens with [Create socket session](/api-reference/create-socket-session). Each session is independent and gets its own socket session.
57
57
  *
58
58
  * Call {@linkcode ChatSession.connect | connect()} on the returned session to open the socket.
59
59
  *
@@ -18,25 +18,28 @@ export interface ToolCallAnswer {
18
18
  extraUserInput?: Record<string, unknown>;
19
19
  }
20
20
  /**
21
- * The four calls your backend makes to Base44 for the chat.
21
+ * The functions you write for the `backend` option. The hook calls them when it needs Base44, and
22
+ * each one usually forwards to a route on your own server, which adds your credentials.
22
23
  *
23
- * Each call wraps one Base44 API request with your credentials, so the browser never holds a
24
- * workspace API key or an access token. Your backend can be written in any language.
24
+ * Keeping the Base44 requests on your server means the browser never holds a workspace API key or
25
+ * an access token. Your server can be written in any language.
25
26
  *
26
- * - `createApp`: [Create app](/api-reference/create-app), with the first prompt as `initial_message`.
27
- * - `openLiveSession`: [Create socket session](/api-reference/create-socket-session) with `{ app_ids: [appId] }`.
28
- * Return the response body unchanged. It holds a session token, never the workspace API key.
29
- * - `sendMessage`: [Send chat message](/api-reference/send-chat-message).
30
- * - `submitToolCallInput`: [Submit tool-call input](/api-reference/submit-tool-call-input). Send an
27
+ * Each function's route calls one Base44 endpoint:
28
+ * - [`createApp()`](#createapp): [Create app](/api-reference/create-app), with the first prompt as `initial_message`.
29
+ * - [`openLiveSession()`](#openlivesession): [Create socket session](/api-reference/create-socket-session) with `{ app_ids: [appId] }`.
30
+ * Return its `session_token`, `socket_url`, and `socket_path`, and keep `session_id` on your server.
31
+ * None of them is the workspace API key.
32
+ * - [`sendMessage()`](#sendmessage): [Send chat message](/api-reference/send-chat-message).
33
+ * - [`submitToolCallInput()`](#submittoolcallinput): [Submit tool-call input](/api-reference/submit-tool-call-input). Send an
31
34
  * `X-Request-ID` built from the tool call ID, so a retry resumes the turn only once.
32
35
  *
33
36
  * Base44 keeps the Send chat message and Submit tool-call input requests open until the AI
34
37
  * finishes the turn. Resolve your call once Base44 accepts the request, not when it returns. The
35
- * chat follows the rest live. A rejected promise from any call sets `error` on the {@link useChat | chat}.
38
+ * chat follows the rest live. A rejected promise from any call sets [`error`](#error).
36
39
  *
37
40
  * @example
38
41
  * ```typescript
39
- * // Your four calls, behind your own API routes
42
+ * // Your four functions, behind your own API routes
40
43
  * async function post<T>(path: string, body: unknown): Promise<T> {
41
44
  * const response = await fetch(path, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });
42
45
  * if (!response.ok) throw new Error(`${path} failed: ${response.status}`);
@@ -57,6 +60,22 @@ export interface ChatBackend {
57
60
  *
58
61
  * @param prompt - The first prompt, which describes the app.
59
62
  * @returns Promise resolving to the new app.
63
+ *
64
+ * @example
65
+ * ```typescript
66
+ * // Your server route for createApp(), with a personal access token
67
+ * export async function POST(request: Request) {
68
+ * const { prompt } = await request.json();
69
+ * const response = await fetch("https://app.base44.com/api/apps", {
70
+ * method: "POST",
71
+ * headers: { Authorization: `Bearer ${process.env.BASE44_ACCESS_TOKEN}`, "Content-Type": "application/json" },
72
+ * body: JSON.stringify({ initial_message: { content: prompt } }),
73
+ * });
74
+ * if (!response.ok) return new Response("Create app failed", { status: response.status });
75
+ * const app = await response.json();
76
+ * return Response.json({ id: app.id, name: app.name });
77
+ * }
78
+ * ```
60
79
  */
61
80
  createApp(prompt: string): Promise<ChatApp>;
62
81
  /**
@@ -64,12 +83,31 @@ export interface ChatBackend {
64
83
  * whenever the session expires. Sessions last one hour.
65
84
  *
66
85
  * @param appId - ID of the app to follow.
67
- * @returns Promise resolving to the Create socket session response body, unchanged.
86
+ * @returns Promise resolving to the session.
87
+ *
88
+ * @example
89
+ * ```typescript
90
+ * // Your server route for openLiveSession(), with a workspace API key
91
+ * export async function POST(request: Request) {
92
+ * const { appId } = await request.json();
93
+ * const response = await fetch("https://app.base44.com/api/v1/socket-sessions", {
94
+ * method: "POST",
95
+ * headers: { Authorization: `Bearer ${process.env.BASE44_API_KEY}`, "Content-Type": "application/json" },
96
+ * body: JSON.stringify({ app_ids: [appId] }),
97
+ * });
98
+ * if (!response.ok) return new Response("Create socket session failed", { status: response.status });
99
+ * const { session_token, socket_url, socket_path, session_id } = await response.json();
100
+ * await saveSession(appId, session_id); // Keep it on your server to change or end the session
101
+ * return Response.json({ session_token, socket_url, socket_path });
102
+ * }
103
+ * ```
68
104
  */
69
105
  openLiveSession(appId: string): Promise<SocketSession>;
70
106
  /**
71
- * Sends a prompt to an existing app. Base44 queues a prompt sent while the AI is working. When the
72
- * app has no queue, Base44 refuses it with a 409, so reject the promise.
107
+ * Sends a prompt to an existing app. Base44 queues a prompt sent while the AI is working. If Base44
108
+ * refuses the prompt, for example because the app is busy with an operation that blocks new
109
+ * messages, reject the promise. The hook then sets [`error`](#error), so your UI can show the
110
+ * failure.
73
111
  *
74
112
  * @param appId - ID of the app.
75
113
  * @param content - The prompt.
@@ -91,16 +129,21 @@ export interface ChatItem {
91
129
  id: string;
92
130
  /** Who wrote the message. */
93
131
  role: "user" | "assistant";
94
- /** The message text, as raw markdown. It comes before the steps, and is empty when the message only holds tool calls. */
132
+ /** The message text, as raw markdown. Show it before the message's steps. It's empty when the message only holds tool calls. */
95
133
  text: string;
96
- /** When the message was created, as an ISO timestamp. Base44's timestamps are UTC with no time zone. A pending prompt carries the browser's time. */
134
+ /**
135
+ * When the message was created, as an ISO 8601 timestamp in UTC. A timestamp from Base44 has no `Z`
136
+ * or offset, so add a `Z` before parsing it with `new Date()`. A pending prompt has the browser's
137
+ * time, which already ends in `Z`.
138
+ */
97
139
  createdAt: string;
98
140
  /** One step per tool call, in order. */
99
141
  steps: ChatStep[];
100
142
  /**
101
- * Whether this is a prompt sent from this chat that Base44 hasn't confirmed yet. It shows at once,
102
- * and Base44's own message replaces it. A failed send removes it. A prompt sent while the AI is
103
- * working waits in Base44's queue and stays pending until it runs.
143
+ * Whether this is a stand-in for a prompt you just sent. When you call [`send()`](#send) or
144
+ * [`create()`](#create), the prompt appears in `items` right away as a pending item, and Base44's
145
+ * copy of the message replaces it once it arrives. A failed send removes it. A prompt sent while the
146
+ * AI is working waits in Base44's queue, so it stays pending until it runs.
104
147
  */
105
148
  pending: boolean;
106
149
  }
@@ -112,20 +155,24 @@ export interface ChatStep {
112
155
  tool: string;
113
156
  /** The file paths the tool call touched. */
114
157
  files: string[];
115
- /** A line ready to show. It's Base44's description of the step when there is one, then the entity it touched, then the tool name and its files. */
158
+ /**
159
+ * A line to show for the step. It's Base44's description of the step when there is one. Otherwise
160
+ * it's the tool name followed by the entity the step touched and its record count, such as
161
+ * `create_records Task (3)`, or by the step's files.
162
+ */
116
163
  label: string;
117
164
  /**
118
- * Where the tool call is. A `waiting` step waits on the user. A `stopped` step was declined, or the
119
- * turn was stopped.
165
+ * The step's progress. A `waiting` step needs the user to answer its question. A `stopped` step was
166
+ * declined, or its turn was stopped. A status this release doesn't know counts as `done`.
120
167
  */
121
168
  status: "running" | "waiting" | "done" | "stopped" | "error";
122
169
  /**
123
- * The question this step waits on, with the actions that answer it. Present only while the step is
124
- * `waiting` in the last assistant message, which is the one that makes the chat wait. It goes away
125
- * once answered, and is absent for a question kind this release doesn't know.
170
+ * The {@link ChatQuestion | question} the step needs answered, with the actions that answer it. It's present only on a
171
+ * `waiting` step in the latest assistant reply, and goes away once answered. A `waiting` step in an
172
+ * older message has no question. It's also absent for a question kind this release doesn't know.
126
173
  */
127
174
  question?: ChatQuestion;
128
- /** What the user answered on a choice question, once answered. It stays after the question closes, so the chat's history shows it. */
175
+ /** The user's answers to a choice question, one for each question the step asked. It stays after the question closes, so you can show the answers in the chat's history. */
129
176
  answered?: ChatAnswer[];
130
177
  }
131
178
  /** One answer to a choice question, next to the question it answers. */
@@ -138,14 +185,17 @@ export interface ChatAnswer {
138
185
  text?: string;
139
186
  }
140
187
  /**
141
- * An open question, with the actions that answer this question and no other.
188
+ * An open question the AI waits on. A `waiting` step carries it as its `question`, and
189
+ * [`status`](#status) becomes `waiting`. Check `kind` to see which of the three kinds it is.
142
190
  *
143
- * Each kind carries only the actions that make sense for it, and every kind can be declined. The
144
- * actions never throw. A failure sets `error` on the {@link useChat | chat}, and the question opens again.
191
+ * Each kind has only the actions that fit it, and every kind can be declined. Calling an action
192
+ * closes the question right away and sends the answer through your
193
+ * [`submitToolCallInput()`](#submittoolcallinput). The actions never throw. A failure sets
194
+ * [`error`](#error), and the question opens again.
145
195
  *
146
- * The chat declines a question kind this release doesn't know, once per tool call, when Base44
147
- * names that kind on the last assistant message. If the decline fails, the chat's `error` says
148
- * so, and the chat tries again after it reconnects.
196
+ * The hook declines a question kind this release doesn't know, once per tool call, when Base44
197
+ * names that kind on the last assistant message. If the decline fails, [`error`](#error) says
198
+ * so, and the hook tries again after it reconnects.
149
199
  */
150
200
  export type ChatQuestion = ChoiceQuestion | SecretsQuestion | ApprovalQuestion;
151
201
  /** One of the questions in a {@link ChoiceQuestion}. */
@@ -168,28 +218,52 @@ export interface ChoiceQuestion {
168
218
  /** The questions, in order. */
169
219
  questions: ChoiceEntry[];
170
220
  /**
171
- * Answers with the picked labels, and free text where the user wrote some.
221
+ * Answers with the picked labels, and free text where the user wrote some. For a question whose
222
+ * `multi` is `false`, only the first picked label counts.
172
223
  *
173
224
  * @param picked - One list of picked labels per question, in the order of `questions`.
174
225
  * @param texts - One free-text answer per question, in the same order. Use it for a `text_input` question, or as a note beside a pick. A question with no pick and no text is skipped.
175
- * @returns Promise resolving once the answer is sent.
226
+ * @returns Promise resolving once Base44 accepts the answer, or once sending it fails and sets [`error`](#error). It never rejects.
227
+ *
228
+ * @example
229
+ * ```tsx
230
+ * // Answer a one-question choice with a button per option
231
+ * function ChoiceButtons({ question }: { question: ChoiceQuestion }) {
232
+ * const [entry] = question.questions;
233
+ * return (
234
+ * <div>
235
+ * <p>{entry.text}</p>
236
+ * {entry.options.map((label) => (
237
+ * <button key={label} onClick={() => question.answer([[label]])}>{label}</button>
238
+ * ))}
239
+ * <button onClick={question.decline}>Skip</button>
240
+ * </div>
241
+ * );
242
+ * }
243
+ * ```
176
244
  */
177
245
  answer(picked: string[][], texts?: string[]): Promise<void>;
178
246
  /**
179
247
  * Declines the question. The AI continues without the answer.
180
248
  *
181
- * @returns Promise resolving once the decline is sent.
249
+ * @returns Promise resolving once Base44 accepts the decline, or once sending it fails and sets [`error`](#error). It never rejects.
250
+ *
251
+ * @example
252
+ * ```tsx
253
+ * // Skip the question
254
+ * <button onClick={question.decline}>Skip</button>
255
+ * ```
182
256
  */
183
257
  decline(): Promise<void>;
184
258
  }
185
259
  /** A value the AI needs, such as an API key. */
186
260
  export interface SecretField {
187
- /** Name of the field, used as its key in `submit`. */
261
+ /** Name of the field, which keys its value in [`submit()`](#submit). */
188
262
  name: string;
189
263
  /** Where to get the value. */
190
264
  description?: string;
191
265
  }
192
- /** The AI needs secrets, such as API keys. The values go to Base44 and the chat keeps none of them. */
266
+ /** The AI needs secrets, such as API keys. The values go to Base44, and the hook keeps none of them. */
193
267
  export interface SecretsQuestion {
194
268
  /** Kind of question. */
195
269
  kind: "secrets";
@@ -198,14 +272,45 @@ export interface SecretsQuestion {
198
272
  /**
199
273
  * Submits the values.
200
274
  *
201
- * @param values - The values, keyed by field name.
202
- * @returns Promise resolving once the values are sent.
275
+ * @param values - The values, keyed by each field's `name`.
276
+ * @returns Promise resolving once Base44 accepts the values, or once sending it fails and sets [`error`](#error). It never rejects.
277
+ *
278
+ * @example
279
+ * ```tsx
280
+ * // Ask for each secret, then submit the values by name
281
+ * function SecretsForm({ question }: { question: SecretsQuestion }) {
282
+ * return (
283
+ * <form
284
+ * onSubmit={(event) => {
285
+ * event.preventDefault();
286
+ * const form = new FormData(event.currentTarget);
287
+ * question.submit(Object.fromEntries(question.fields.map((field) => [field.name, String(form.get(field.name) ?? "")])));
288
+ * }}
289
+ * >
290
+ * {question.fields.map((field) => (
291
+ * <label key={field.name}>
292
+ * {field.name}
293
+ * <input name={field.name} type="password" placeholder={field.description} />
294
+ * </label>
295
+ * ))}
296
+ * <button type="submit">Save</button>
297
+ * <button type="button" onClick={question.decline}>Skip</button>
298
+ * </form>
299
+ * );
300
+ * }
301
+ * ```
203
302
  */
204
303
  submit(values: Record<string, string>): Promise<void>;
205
304
  /**
206
305
  * Declines the question. The AI continues without the values.
207
306
  *
208
- * @returns Promise resolving once the decline is sent.
307
+ * @returns Promise resolving once Base44 accepts the decline, or once sending it fails and sets [`error`](#error). It never rejects.
308
+ *
309
+ * @example
310
+ * ```tsx
311
+ * // Skip without entering the secrets
312
+ * <button onClick={question.decline}>Skip</button>
313
+ * ```
209
314
  */
210
315
  decline(): Promise<void>;
211
316
  }
@@ -215,7 +320,7 @@ export interface ApprovalQuestion {
215
320
  kind: "approval";
216
321
  /** Name of the tool that wants to run. */
217
322
  action: string;
218
- /** Why the action needs approval, when Base44 gives a reason. Empty otherwise. */
323
+ /** Why the action needs approval. It's Base44's reason when there is one, otherwise the `summary` in `details`, and empty when neither is given. */
219
324
  reason: string;
220
325
  /** The check that paused the action, such as `exec_tool_send_email` or `entity_rls_guard`. */
221
326
  guard: string;
@@ -224,13 +329,34 @@ export interface ApprovalQuestion {
224
329
  /**
225
330
  * Lets the action run.
226
331
  *
227
- * @returns Promise resolving once the approval is sent.
332
+ * @returns Promise resolving once Base44 accepts the approval, or once sending it fails and sets [`error`](#error). It never rejects.
333
+ *
334
+ * @example
335
+ * ```tsx
336
+ * // Show what the action would do, then allow or decline it
337
+ * function ApprovalPrompt({ question }: { question: ApprovalQuestion }) {
338
+ * return (
339
+ * <div>
340
+ * <p>The AI wants to run {question.action}.</p>
341
+ * {question.reason && <p>{question.reason}</p>}
342
+ * <button onClick={question.approve}>Allow</button>
343
+ * <button onClick={question.decline}>Decline</button>
344
+ * </div>
345
+ * );
346
+ * }
347
+ * ```
228
348
  */
229
349
  approve(): Promise<void>;
230
350
  /**
231
351
  * Declines the action. It never runs, and the AI continues.
232
352
  *
233
- * @returns Promise resolving once the decline is sent.
353
+ * @returns Promise resolving once Base44 accepts the decline, or once sending it fails and sets [`error`](#error). It never rejects.
354
+ *
355
+ * @example
356
+ * ```tsx
357
+ * // Decline the action
358
+ * <button onClick={question.decline}>Decline</button>
359
+ * ```
234
360
  */
235
361
  decline(): Promise<void>;
236
362
  }
@@ -252,85 +378,153 @@ export interface ApprovalDetails {
252
378
  inspectionFailed?: boolean;
253
379
  }
254
380
  /**
255
- * What the AI is doing. When several hold at once, the first in this list wins.
381
+ * What the AI is doing.
382
+ *
383
+ * When several hold at once, the first in this list wins.
256
384
  *
257
385
  * - `error`: Base44 reports that the last build failed.
258
- * - `waiting`: a question waits on the user.
259
- * - `building`: the AI is working.
260
- * - `submitted`: a prompt, a new app or an answer is on its way. It lasts until Base44 reports work, a reply or a queue change, or the call fails.
261
- * - `ready`: none of the above.
386
+ * - `waiting`: A question waits for the user's answer.
387
+ * - `building`: The AI is working.
388
+ * - `submitted`: A prompt, a new app, or an answer is on its way. It lasts until Base44 reports work, a reply, or a queue change, or until the call fails.
389
+ * - `ready`: None of the above.
262
390
  */
263
391
  export type ChatStatus = "ready" | "submitted" | "building" | "waiting" | "error";
264
392
  /**
265
393
  * Whether the chat follows the app live.
266
394
  *
267
- * - `connecting`: until the first snapshot arrives.
268
- * - `connected`: after the first snapshot.
269
- * - `disconnected`: live updates stopped for good. The session couldn't open, the retries ran out,
270
- * or Base44 ended the session or the app's subscription. {@link UseChatResult.error} says why.
395
+ * - `connecting`: The chat waits for the app's first snapshot.
396
+ * - `connected`: The first snapshot arrived, and updates follow live.
397
+ * - `disconnected`: Live updates stopped for good. The session couldn't open, the retries ran out,
398
+ * or Base44 ended the session or the app's subscription. Check [`error`](#error) to see why.
271
399
  *
272
400
  * Watching another app, or mounting the chat again, starts over.
273
401
  */
274
402
  export type ChatConnection = "connecting" | "connected" | "disconnected";
275
403
  /** A failure of a call, of the live connection, or of the build. */
276
404
  export interface ChatError {
277
- /** What went wrong, for people. */
405
+ /** A readable description of what went wrong, such as `The build failed`. */
278
406
  message: string;
279
407
  /**
280
- * What went wrong, for code. A connection error carries a `PlatformSocketErrorCode`, and a failed
281
- * build carries `build_failed`. A failed call to your backend carries none.
408
+ * A value your code can check to handle the error, such as `build_failed` for a failed build. A
409
+ * connection error has one of the session or app error codes listed under the chat module's
410
+ * [Errors](/developers/references/platform-sdk/docs/interfaces/chat#errors). A failed call to
411
+ * your backend has no code.
282
412
  */
283
413
  code?: string;
284
- /** The original error, for logging. */
414
+ /** The error the failure came from, such as the one your backend threw. Log it to debug the failure. It's absent when the hook found the failure itself, such as a failed build or a send with no app. */
285
415
  cause?: unknown;
286
416
  }
287
417
  /** Options for {@link useChat}. */
288
418
  export interface ChatOptions {
289
419
  /**
290
420
  * ID of the app to follow, or `null` until an app exists. While it's `null`, the chat follows the
291
- * app {@link UseChatResult.create} made. Any change to `appId` forgets that app.
421
+ * app that [`create()`](#create) made, so you don't have to pass the new ID back.
422
+ * Changing `appId` stops following that app, so setting it back to `null` starts a new chat.
423
+ * Switching to another app closes the old session and starts over.
292
424
  */
293
425
  appId: string | null;
294
- /** The four calls your backend makes to Base44. The chat reads the latest on every action, so an inline object works. */
426
+ /**
427
+ * The functions the hook calls to reach Base44 through your backend, described in
428
+ * [Backend calls](#backend-calls). The hook uses the `backend` from the latest render, so you can
429
+ * pass an inline object without memoizing it.
430
+ */
295
431
  backend: ChatBackend;
296
432
  /**
297
- * Called with the new app after {@link UseChatResult.create} succeeds. The chat already follows it.
298
- * Pass its ID back as `appId` to keep it in your own state.
433
+ * Called with the new app after [`create()`](#create) succeeds. The chat already follows the new
434
+ * app. To keep its ID in your own state, pass it back as `appId`.
299
435
  *
300
436
  * @param app - The app that was created.
301
437
  */
302
438
  onAppCreated?: (app: ChatApp) => void;
303
439
  }
304
- /** The chat that {@link useChat} returns. */
440
+ /**
441
+ * The chat state and actions that `useChat()` returns.
442
+ *
443
+ * @groupDescription Properties
444
+ * The hook returns one object, of type `UseChatResult`. Its state is below, and its functions are
445
+ * under [Returned actions](#returned-actions).
446
+ *
447
+ * @groupDescription Methods
448
+ * Functions on the same object, which you call to act on the chat, as in `chat.send(prompt)`. They
449
+ * never throw. A failure sets [`error`](#error).
450
+ */
305
451
  export interface UseChatResult {
306
- /** The conversation, oldest first, with open questions bound to their steps. */
452
+ /** The conversation, oldest first. Each open question appears with the step that asked it. */
307
453
  items: ChatItem[];
308
454
  /** What the AI is doing. */
309
455
  status: ChatStatus;
310
456
  /** Whether the chat follows the app live. */
311
457
  connection: ChatConnection;
312
458
  /**
313
- * The last failure. It's set whenever `status` is `error`, and on any failed call or connection
314
- * error. A failed call's error clears on the next action. A connection error stays until
315
- * {@link UseChatResult.clearError}. A failed build stays while Base44 reports it.
459
+ * The failure to show, or `null`. It's set when a call fails, when the live connection fails, and
460
+ * whenever `status` is `error`. When more than one of these conditions is true, `error` holds the
461
+ * failed call first, then the connection error, then the failed build. A failed call's error
462
+ * clears on the next action, and a connection error stays until [`clearError()`](#clearerror). A
463
+ * failed build's error stays while Base44 reports it. Switching to another app clears it.
316
464
  */
317
465
  error: ChatError | null;
318
466
  /**
319
- * Sends a prompt to the current app. Base44 queues it while the AI is working. The prompt shows
320
- * at once as a pending item, and the reply arrives through `items`. Without an app, it sets
321
- * `error`. Use {@link UseChatResult.create} for the first prompt.
467
+ * Sends a prompt to the app the chat follows. The prompt appears in [`items`](#items) right away
468
+ * as a pending item, and the reply arrives there too. Base44 queues the prompt while the AI is
469
+ * working. If the chat doesn't follow an app yet, it sets [`error`](#error) instead. Use
470
+ * [`create()`](#create) for the first prompt.
322
471
  *
323
472
  * @param prompt - The prompt to send.
324
- * @returns Promise resolving once Base44 accepts the prompt. It never rejects.
473
+ * @returns Promise resolving once Base44 accepts the prompt, or once the send fails and sets [`error`](#error). It never rejects.
474
+ *
475
+ * @example
476
+ * ```tsx
477
+ * // Send the prompt from a form
478
+ * function PromptForm({ chat }: { chat: UseChatResult }) {
479
+ * const [prompt, setPrompt] = useState("");
480
+ * return (
481
+ * <form
482
+ * onSubmit={(event) => {
483
+ * event.preventDefault();
484
+ * chat.send(prompt);
485
+ * setPrompt("");
486
+ * }}
487
+ * >
488
+ * <input value={prompt} onChange={(event) => setPrompt(event.target.value)} />
489
+ * <button type="submit" disabled={!prompt.trim()}>Send</button>
490
+ * {chat.status === "building" && <small>The AI is working. New prompts wait in the queue.</small>}
491
+ * </form>
492
+ * );
493
+ * }
494
+ * ```
325
495
  */
326
496
  send(prompt: string): Promise<void>;
327
497
  /**
328
- * Creates an app from its first prompt and reports it through `onAppCreated`.
498
+ * Creates an app from its first prompt. The prompt appears in [`items`](#items) right away as a
499
+ * pending item. Once the app exists, the hook passes it to [`onAppCreated`](#onappcreated). If
500
+ * `appId` is `null`, the chat then follows the new app. Otherwise it stays on the app it follows.
329
501
  *
330
502
  * @param prompt - The first prompt, which describes the app.
331
- * @returns Promise resolving once the app exists. It never rejects.
503
+ * @returns Promise resolving once the app exists, or once creating it fails and sets [`error`](#error). It never rejects.
504
+ *
505
+ * @example
506
+ * ```tsx
507
+ * // Create the app from the first prompt, and send the next prompts to it
508
+ * const [appId, setAppId] = useState<string | null>(null);
509
+ * const chat = useChat({ appId, backend, onAppCreated: (app) => setAppId(app.id) });
510
+ *
511
+ * const submit = (prompt: string) => (appId ? chat.send(prompt) : chat.create(prompt));
512
+ * ```
332
513
  */
333
514
  create(prompt: string): Promise<void>;
334
- /** Clears {@link UseChatResult.error}. A failed build's error stays while Base44 reports it. */
515
+ /**
516
+ * Clears a failed call's or the connection's [`error`](#error). A failed build's error stays while Base44 reports it.
517
+ *
518
+ * @example
519
+ * ```tsx
520
+ * // Show the error, with a dismiss button unless the build failed
521
+ * {chat.error && (
522
+ * <div role="alert">
523
+ * {chat.error.message}
524
+ * {chat.error.code !== "build_failed" && <button onClick={chat.clearError}>Dismiss</button>}
525
+ * </div>
526
+ * )}
527
+ * ```
528
+ */
335
529
  clearError(): void;
336
530
  }
@@ -1,35 +1,32 @@
1
1
  import type { UseChatResult, ChatOptions } from "./chat.types.js";
2
2
  /**
3
- * Runs the AI chat for one app in your own UI.
3
+ * Runs an app's AI chat in your own React UI. Requires a browser environment and can't be used in
4
+ * the backend.
4
5
  *
5
- * The hook renders nothing. It gives you the conversation and the actions, and you draw them:
6
+ * The hook is headless. It gives you the conversation and the [actions](#returned-actions), and your components render them:
6
7
  * - Follows the app live, and renews its socket session when it expires.
7
- * - Turns Base44's messages into {@link ChatItem | items}, with each open question bound to the step it belongs to.
8
- * - Reports what the AI is doing in {@link UseChatResult.status}, and the live connection in {@link UseChatResult.connection}.
9
- * - Sends prompts, creates apps and answers questions through the {@link ChatBackend | backend} you pass, so no credential reaches the browser.
10
- *
11
- * The actions never throw. A failure sets {@link UseChatResult.error}, and a question whose answer
12
- * failed opens again. The chat declines a question kind this release doesn't know.
13
- *
14
- * Requires a browser environment and can't be used in the backend.
15
- *
16
- * The chat follows `appId` when it's set. While `appId` is `null`, it follows the app
17
- * {@link UseChatResult.create} made, so passing the new ID back is optional. Any change to `appId`
18
- * forgets that app, so setting it back to `null` starts a new chat. Switching apps closes the old
19
- * session and starts over.
8
+ * - Turns Base44's messages into [items](#items), and shows each open [question](#questions) with the step that asked it.
9
+ * - Reports what the AI is doing in [`status`](#status), and the live connection in [`connection`](#connection).
10
+ * - Sends prompts, creates apps, and answers questions through the {@link ChatBackend | backend} you pass, so no credential reaches the browser.
20
11
  *
21
12
  * @param options - The app to follow, your backend's calls, and what to do with a created app.
22
- * @returns The conversation, its status, connection and error, and the actions `send`, `create` and `clearError`.
13
+ * @returns The chat's state, `items`, `status`, `connection`, and `error`, and its actions `send()`, `create()`, and `clearError()`.
23
14
  *
24
15
  * @example
25
- * ```typescript
26
- * // Draw the chat and answer an approval
16
+ * ```tsx
17
+ * // Render the chat and answer an approval
18
+ * import { useChat } from "@base44/platform/react";
19
+ * import Markdown from "react-markdown";
20
+ *
21
+ * // ...
22
+ *
23
+ * // Inside your component
27
24
  * const chat = useChat({ appId, backend, onAppCreated: selectApp });
28
25
  * return (
29
26
  * <>
30
27
  * {chat.items.map((item) => (
31
28
  * <div key={item.id} className={item.role}>
32
- * {item.text && <p>{item.text}</p>}
29
+ * {item.text && <Markdown>{item.text}</Markdown>}
33
30
  * {item.steps.map((step) =>
34
31
  * step.question?.kind === "approval" ? (
35
32
  * <button key={step.id} onClick={step.question.approve}>Allow {step.question.action}</button>
@@ -7,36 +7,33 @@ const BUILD_FAILED_ERROR = { message: "The build failed", code: "build_failed" }
7
7
  // The target of `submittedTo` while `create` runs, before the new app has an id.
8
8
  const NEW_APP = "new-app";
9
9
  /**
10
- * Runs the AI chat for one app in your own UI.
10
+ * Runs an app's AI chat in your own React UI. Requires a browser environment and can't be used in
11
+ * the backend.
11
12
  *
12
- * The hook renders nothing. It gives you the conversation and the actions, and you draw them:
13
+ * The hook is headless. It gives you the conversation and the [actions](#returned-actions), and your components render them:
13
14
  * - Follows the app live, and renews its socket session when it expires.
14
- * - Turns Base44's messages into {@link ChatItem | items}, with each open question bound to the step it belongs to.
15
- * - Reports what the AI is doing in {@link UseChatResult.status}, and the live connection in {@link UseChatResult.connection}.
16
- * - Sends prompts, creates apps and answers questions through the {@link ChatBackend | backend} you pass, so no credential reaches the browser.
17
- *
18
- * The actions never throw. A failure sets {@link UseChatResult.error}, and a question whose answer
19
- * failed opens again. The chat declines a question kind this release doesn't know.
20
- *
21
- * Requires a browser environment and can't be used in the backend.
22
- *
23
- * The chat follows `appId` when it's set. While `appId` is `null`, it follows the app
24
- * {@link UseChatResult.create} made, so passing the new ID back is optional. Any change to `appId`
25
- * forgets that app, so setting it back to `null` starts a new chat. Switching apps closes the old
26
- * session and starts over.
15
+ * - Turns Base44's messages into [items](#items), and shows each open [question](#questions) with the step that asked it.
16
+ * - Reports what the AI is doing in [`status`](#status), and the live connection in [`connection`](#connection).
17
+ * - Sends prompts, creates apps, and answers questions through the {@link ChatBackend | backend} you pass, so no credential reaches the browser.
27
18
  *
28
19
  * @param options - The app to follow, your backend's calls, and what to do with a created app.
29
- * @returns The conversation, its status, connection and error, and the actions `send`, `create` and `clearError`.
20
+ * @returns The chat's state, `items`, `status`, `connection`, and `error`, and its actions `send()`, `create()`, and `clearError()`.
30
21
  *
31
22
  * @example
32
- * ```typescript
33
- * // Draw the chat and answer an approval
23
+ * ```tsx
24
+ * // Render the chat and answer an approval
25
+ * import { useChat } from "@base44/platform/react";
26
+ * import Markdown from "react-markdown";
27
+ *
28
+ * // ...
29
+ *
30
+ * // Inside your component
34
31
  * const chat = useChat({ appId, backend, onAppCreated: selectApp });
35
32
  * return (
36
33
  * <>
37
34
  * {chat.items.map((item) => (
38
35
  * <div key={item.id} className={item.role}>
39
- * {item.text && <p>{item.text}</p>}
36
+ * {item.text && <Markdown>{item.text}</Markdown>}
40
37
  * {item.steps.map((step) =>
41
38
  * step.question?.kind === "approval" ? (
42
39
  * <button key={step.id} onClick={step.question.approve}>Allow {step.question.action}</button>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@base44-preview/platform",
3
- "version": "0.5.0-pr.346.138d91a",
3
+ "version": "0.5.0-pr.353.5c12c6c",
4
4
  "description": "Base44 Platform SDK for white-label platforms: a browser client for following the AI chat and a server entrypoint for webhooks",
5
5
  "main": "dist/client/index.js",
6
6
  "types": "dist/client/index.d.ts",