@base44-preview/platform 0.2.0-pr.315.69f7032 → 0.2.0-pr.315.ebc1eb8

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.
package/README.md CHANGED
@@ -194,8 +194,9 @@ call with your credentials, so the browser never holds a key. The hook returns `
194
194
  `status` (`ready`, `submitted`, `building`, `waiting`, `error`), a `connection` (`connecting`,
195
195
  `connected`, `reconnecting`, `disconnected`), an `error`, and the actions `send`, `create` and `clearError`. `send` needs an app; `create` makes
196
196
  the first, and the chat watches it while `appId` is `null`. A sent prompt shows at once as a
197
- `pending` item; to let the user send only when the builder can take it now, disable the input
198
- unless `status` is `ready` or `error`. A question is a union on `kind` (`choice`, `secrets`, `approval`) and carries only the
199
- actions its kind allows; declining is always one of them, and a kind this release doesn't know is
200
- declined for you. Every shape has JSDoc in `src/react/chat.types.ts`, and
197
+ `pending` item until Base44's own message arrives; a prompt sent mid-build waits in Base44's
198
+ queue meanwhile. A question is a union on `kind` (`choice`, `secrets`, `approval`) and carries only the
199
+ actions its kind allows, and declining is always one of them. As in Base44's builder, only the
200
+ last assistant message makes the chat wait, and a kind this release can't show is a waiting step
201
+ without a question. Every shape has JSDoc in `src/react/chat.types.ts`, and
201
202
  [`examples/react-chat/`](examples/react-chat) shows Tiny Sunny's chat built on it, with its `backend`.
@@ -14,18 +14,18 @@ export declare const SNAPSHOT_SIZE = 50;
14
14
  /** @internal A rejoin's snapshot holds only the newest messages: it is the truth for its window,
15
15
  * and the messages before its oldest one stay. A snapshot with room to spare holds them all. */
16
16
  export declare function mergeSnapshot(all: Message[], snapshot: Message[]): Message[];
17
- /** @internal Turns sorted messages into items. Every tool call that waits, is not in `answered`
18
- * and is of a kind this release knows carries its own question. */
17
+ /** @internal Turns sorted messages into items. A waiting tool call that is not in `answered` and is
18
+ * of a kind this release knows carries its own question, in the last assistant message only: the
19
+ * one that makes the chat wait. Older waiting calls keep their status but no question. */
19
20
  export declare function toItems(sorted: Message[], answered: string[], respond: Respond): ChatItem[];
20
21
  /** @internal Base44's tool call status, as a step's. */
21
22
  export declare function stepStatus(tool: ToolCall): ChatStep["status"];
22
- /** @internal Whether some tool call waits on the user and has not been answered here. */
23
+ /** @internal Whether the chat waits on the user. Like Base44's builder, only the last assistant
24
+ * message counts, and a call answered here stops counting. A kind this release can't show still
25
+ * counts: Base44 waits on it all the same. */
23
26
  export declare function isWaiting(sorted: Message[], answered: string[]): boolean;
24
- /** @internal Waiting tool calls of a kind this release can't show, to decline. */
25
- export declare function unknownWaiting(sorted: Message[]): {
26
- toolCallId: string;
27
- messageId: string;
28
- }[];
27
+ /** @internal The ids of tool calls Base44 reports waiting. */
28
+ export declare function waitingIds(sorted: Message[]): Set<string>;
29
29
  /** @internal A prompt sent from this chat that Base44 has not confirmed, for the app it went to. */
30
30
  export interface PendingPrompt {
31
31
  id: string;
@@ -18,9 +18,16 @@ export function mergeSnapshot(all, snapshot) {
18
18
  const fresh = new Set(snapshot.map(m => m.id));
19
19
  return [...all.filter(m => { var _a, _b; return !fresh.has(m.id) && ((_b = (_a = m.metadata) === null || _a === void 0 ? void 0 : _a.created_date) !== null && _b !== void 0 ? _b : "") < oldest; }), ...snapshot];
20
20
  }
21
- /** @internal Turns sorted messages into items. Every tool call that waits, is not in `answered`
22
- * and is of a kind this release knows carries its own question. */
21
+ /** @internal An assistant message that answers a turn. Base44 injects notices that expect no reply. */
22
+ function isActionable(m) {
23
+ var _a;
24
+ return (m === null || m === void 0 ? void 0 : m.role) === "assistant" && !((_a = m.additional_message_params) === null || _a === void 0 ? void 0 : _a.skip_ai_response);
25
+ }
26
+ /** @internal Turns sorted messages into items. A waiting tool call that is not in `answered` and is
27
+ * of a kind this release knows carries its own question, in the last assistant message only: the
28
+ * one that makes the chat wait. Older waiting calls keep their status but no question. */
23
29
  export function toItems(sorted, answered, respond) {
30
+ const last = lastActionable(sorted);
24
31
  return sorted.map(m => {
25
32
  var _a, _b, _c, _d;
26
33
  return ({
@@ -29,10 +36,14 @@ export function toItems(sorted, answered, respond) {
29
36
  text: (_a = m.content) !== null && _a !== void 0 ? _a : "",
30
37
  createdAt: (_c = (_b = m.metadata) === null || _b === void 0 ? void 0 : _b.created_date) !== null && _c !== void 0 ? _c : "",
31
38
  pending: false,
32
- steps: ((_d = m.tool_calls) !== null && _d !== void 0 ? _d : []).map(tool => toStep(tool, answered.includes(tool.id) ? undefined : (approve, extra) => respond(tool.id, m.id, approve, extra))),
39
+ steps: ((_d = m.tool_calls) !== null && _d !== void 0 ? _d : []).map(tool => toStep(tool, m === last && !answered.includes(tool.id) ? (approve, extra) => respond(tool.id, m.id, approve, extra) : undefined)),
33
40
  });
34
41
  });
35
42
  }
43
+ /** @internal The last assistant message that answers a turn, as Base44's builder finds it. */
44
+ function lastActionable(sorted) {
45
+ return [...sorted].reverse().find(isActionable);
46
+ }
36
47
  function toStep(tool, reply) {
37
48
  var _a, _b;
38
49
  const name = (_a = tool.name) !== null && _a !== void 0 ? _a : "";
@@ -55,19 +66,17 @@ export function stepStatus(tool) {
55
66
  return "error";
56
67
  return "done";
57
68
  }
58
- /** @internal Whether some tool call waits on the user and has not been answered here. */
69
+ /** @internal Whether the chat waits on the user. Like Base44's builder, only the last assistant
70
+ * message counts, and a call answered here stops counting. A kind this release can't show still
71
+ * counts: Base44 waits on it all the same. */
59
72
  export function isWaiting(sorted, answered) {
60
- return sorted.some(m => { var _a; return (_a = m.tool_calls) === null || _a === void 0 ? void 0 : _a.some(tool => tool.status === "waiting_for_user_input" && !answered.includes(tool.id)); });
73
+ var _a;
74
+ const last = lastActionable(sorted);
75
+ return !!((_a = last === null || last === void 0 ? void 0 : last.tool_calls) === null || _a === void 0 ? void 0 : _a.some(tool => tool.status === "waiting_for_user_input" && !answered.includes(tool.id)));
61
76
  }
62
- const knownKinds = ["approval", "choice", "input"];
63
- /** @internal Waiting tool calls of a kind this release can't show, to decline. */
64
- export function unknownWaiting(sorted) {
65
- return sorted.flatMap(m => {
66
- var _a;
67
- return ((_a = m.tool_calls) !== null && _a !== void 0 ? _a : [])
68
- .filter(tool => { var _a, _b; return tool.status === "waiting_for_user_input" && !knownKinds.includes((_b = (_a = tool.waiting_on) === null || _a === void 0 ? void 0 : _a.kind) !== null && _b !== void 0 ? _b : ""); })
69
- .map(tool => ({ toolCallId: tool.id, messageId: m.id }));
70
- });
77
+ /** @internal The ids of tool calls Base44 reports waiting. */
78
+ export function waitingIds(sorted) {
79
+ return new Set(sorted.flatMap(m => { var _a; return ((_a = m.tool_calls) !== null && _a !== void 0 ? _a : []).filter(t => t.status === "waiting_for_user_input").map(t => t.id); }));
71
80
  }
72
81
  /** @internal Prompts that arrived from Base44 as messages settle the pending ones
73
82
  * with the same text. Base44's public send carries no client id, so text is the only link. With
@@ -53,7 +53,8 @@ export interface ChatItem {
53
53
  role: "user" | "assistant";
54
54
  /** Raw markdown; it comes before the steps. Empty when the message is only tool activity. */
55
55
  text: string;
56
- /** When Base44 created the message, as an ISO timestamp. */
56
+ /** When the message was created, as an ISO timestamp: Base44's for its messages, which carry no
57
+ * time zone and are UTC, and the browser's for a pending prompt. */
57
58
  createdAt: string;
58
59
  /** One per tool call, in order. */
59
60
  steps: ChatStep[];
@@ -75,13 +76,15 @@ export interface ChatStep {
75
76
  /** Where the call is. `waiting` waits on the user; `stopped` was declined, or the build was stopped. */
76
77
  status: "running" | "waiting" | "done" | "stopped" | "error";
77
78
  /** The question this step waits on, bound to the actions that answer it. Only while `status` is
78
- * `waiting`, and gone once answered. */
79
+ * `waiting`, and only in the last assistant message, the one that makes the chat wait. Gone once
80
+ * answered, and absent for a kind this release can't show. */
79
81
  question?: ChatQuestion;
80
82
  }
81
83
  /**
82
84
  * An open question, with the actions that answer this question and no other.
83
85
  * Each kind carries only the actions that make sense for it, and every kind can be declined.
84
- * A kind this release doesn't know is declined for you and never appears.
86
+ * A waiting step of a kind this release can't show has no question, and the chat still waits on it,
87
+ * as in Base44's own builder.
85
88
  * The actions never throw: a failure lands in {@link Base44Chat.error} and the question opens again.
86
89
  */
87
90
  export type ChatQuestion = ChoiceQuestion | SecretsQuestion | ApprovalQuestion;
@@ -147,9 +150,7 @@ export interface ApprovalQuestion {
147
150
  * - `submitted`: a prompt, a new app or an answer is on its way, until Base44 reports work,
148
151
  * a reply or a queue change, or the call fails.
149
152
  * - `ready`: everything else.
150
- *
151
- * To let the user send only when the builder can take a prompt now:
152
- * `status === "ready" || status === "error"`.
153
+
153
154
  */
154
155
  export type ChatStatus = "ready" | "submitted" | "building" | "waiting" | "error";
155
156
  /** Whether the chat sees the builder live: `connecting` until the first snapshot, `connected`
@@ -7,7 +7,7 @@ import type { Base44Chat, Base44ChatOptions } from "./chat.types.js";
7
7
  * All Base44 calls go through the {@link Base44ChatBackend | backend} you pass, so no
8
8
  * credential reaches the browser. Actions never throw: a failure lands in
9
9
  * {@link Base44Chat.error}, and a question whose reply failed opens again. A question kind
10
- * this release doesn't know is declined for you.
10
+ * this release can't show is a waiting step without a question, as in Base44's own builder.
11
11
  *
12
12
  * Requires a browser environment. One live session is opened per app and renewed through
13
13
  * `backend.openLiveSession` when it expires; switching apps closes the old one and starts over.
@@ -38,9 +38,7 @@ import type { Base44Chat, Base44ChatOptions } from "./chat.types.js";
38
38
  * </div>
39
39
  * ))}
40
40
  * {chat.error && <p role="alert">{chat.error.message}</p>}
41
- * <button disabled={chat.status !== "ready" && chat.status !== "error"} onClick={() => (appId ? chat.send(prompt) : chat.create(prompt))}>
42
- * Send
43
- * </button>
41
+ * <button onClick={() => (appId ? chat.send(prompt) : chat.create(prompt))}>Send</button>
44
42
  * </>
45
43
  * );
46
44
  * ```
@@ -1,7 +1,7 @@
1
1
  "use client";
2
2
  import { useCallback, useEffect, useMemo, useRef, useState } from "react";
3
3
  import { createPlatformClient } from "../client/client.js";
4
- import { isWaiting, mergeMessage, mergeSnapshot, pendingItems, settlePending, sortMessages, toItems, unknownWaiting } from "./chat-items.js";
4
+ import { isWaiting, mergeMessage, mergeSnapshot, pendingItems, settlePending, sortMessages, toItems, waitingIds } from "./chat-items.js";
5
5
  // Base44's public status carries no reason, so a failed build has one error.
6
6
  const buildFailed = { message: "The build failed", code: "build_failed" };
7
7
  // What `submitted` waits on while `create` runs, before the new app has an id.
@@ -14,7 +14,7 @@ const creating = "creating";
14
14
  * All Base44 calls go through the {@link Base44ChatBackend | backend} you pass, so no
15
15
  * credential reaches the browser. Actions never throw: a failure lands in
16
16
  * {@link Base44Chat.error}, and a question whose reply failed opens again. A question kind
17
- * this release doesn't know is declined for you.
17
+ * this release can't show is a waiting step without a question, as in Base44's own builder.
18
18
  *
19
19
  * Requires a browser environment. One live session is opened per app and renewed through
20
20
  * `backend.openLiveSession` when it expires; switching apps closes the old one and starts over.
@@ -45,18 +45,19 @@ const creating = "creating";
45
45
  * </div>
46
46
  * ))}
47
47
  * {chat.error && <p role="alert">{chat.error.message}</p>}
48
- * <button disabled={chat.status !== "ready" && chat.status !== "error"} onClick={() => (appId ? chat.send(prompt) : chat.create(prompt))}>
49
- * Send
50
- * </button>
48
+ * <button onClick={() => (appId ? chat.send(prompt) : chat.create(prompt))}>Send</button>
51
49
  * </>
52
50
  * );
53
51
  * ```
54
52
  */
55
53
  export function useBase44Chat({ appId, backend, onAppCreated }) {
54
+ var _a;
56
55
  const [messages, setMessages] = useState([]);
57
56
  const [appState, setAppState] = useState();
58
57
  const [connection, setConnection] = useState("connecting");
59
- const [error, setError] = useState(null);
58
+ // A failed call's error, which the next action clears, and the live connection's, which it doesn't.
59
+ const [callError, setCallError] = useState(null);
60
+ const [liveError, setLiveError] = useState(null);
60
61
  const [answered, setAnswered] = useState([]);
61
62
  // The app a prompt or an answer went to, or `creating`, until Base44 reacts to it.
62
63
  const [submitted, setSubmitted] = useState(null);
@@ -81,19 +82,20 @@ export function useBase44Chat({ appId, backend, onAppCreated }) {
81
82
  setMessages([]);
82
83
  setAppState(undefined);
83
84
  setConnection("connecting");
84
- setError(null);
85
+ setCallError(null);
86
+ setLiveError(null);
85
87
  setAnswered([]);
86
88
  if (submitted !== currentAppId && submitted !== creating)
87
89
  setSubmitted(null);
88
90
  setPending(pending.filter(p => p.appId === currentAppId || p.appId === creating));
89
91
  }
90
- // The live session reads the backend through a ref, kept current after every render, so an
91
- // inline `backend={{…}}` never reopens the socket. The actions below read it directly.
92
+ // The backend is read through a ref, kept current after every render, so an inline
93
+ // `backend={{…}}` never reopens the socket or changes the actions' identity.
92
94
  const backendRef = useRef(backend);
93
95
  useEffect(() => {
94
96
  backendRef.current = backend;
95
97
  });
96
- const fail = useCallback((e) => setError({ message: (e === null || e === void 0 ? void 0 : e.message) || "Something went wrong", cause: e }), []);
98
+ const fail = useCallback((e) => setCallError({ message: (e === null || e === void 0 ? void 0 : e.message) || "Something went wrong", cause: e }), []);
97
99
  // Live updates: a snapshot on every connect, then events.
98
100
  useEffect(() => {
99
101
  const id = currentAppId;
@@ -103,7 +105,7 @@ export function useBase44Chat({ appId, backend, onAppCreated }) {
103
105
  let session;
104
106
  const failLive = (e) => {
105
107
  if (!stopped)
106
- setError({ message: (e === null || e === void 0 ? void 0 : e.message) || "Live updates failed", code: e === null || e === void 0 ? void 0 : e.code, cause: e });
108
+ setLiveError({ message: (e === null || e === void 0 ? void 0 : e.message) || "Live updates failed", code: e === null || e === void 0 ? void 0 : e.code, cause: e });
107
109
  };
108
110
  // A failure of the session or the subscription ends live updates: nothing retries after it.
109
111
  const endLive = (e) => {
@@ -146,8 +148,12 @@ export function useBase44Chat({ appId, backend, onAppCreated }) {
146
148
  // The client asks for a session on the first connect and whenever one expires, and forwards
147
149
  // no detail of a failed call, so the backend's own error is kept to report.
148
150
  let sessionFailure;
151
+ let snapshotted = false;
149
152
  const builder = createPlatformClient().builder.init({
150
- getSession: () => backendRef.current.openLiveSession(id).catch((e) => {
153
+ getSession: () => backendRef.current.openLiveSession(id).then(session => {
154
+ sessionFailure = undefined;
155
+ return session;
156
+ }, (e) => {
151
157
  sessionFailure = e;
152
158
  throw e;
153
159
  }),
@@ -156,12 +162,16 @@ export function useBase44Chat({ appId, backend, onAppCreated }) {
156
162
  return endLive(e);
157
163
  if (stopped)
158
164
  return;
159
- setError({ message: (sessionFailure === null || sessionFailure === void 0 ? void 0 : sessionFailure.message) || e.message, code: e.code, cause: sessionFailure });
165
+ setLiveError({ message: (sessionFailure === null || sessionFailure === void 0 ? void 0 : sessionFailure.message) || e.message, code: e.code, cause: sessionFailure });
160
166
  setConnection("disconnected");
161
167
  },
168
+ // Connected means seen live: the first time after a snapshot, and again on a reconnect,
169
+ // even when the rejoin's snapshot fails.
162
170
  onConnectionChange: state => {
163
171
  if (state === "reconnecting")
164
172
  setConnection("reconnecting");
173
+ else if (snapshotted && !stopped)
174
+ setConnection("connected");
165
175
  },
166
176
  });
167
177
  session = builder;
@@ -173,6 +183,7 @@ export function useBase44Chat({ appId, backend, onAppCreated }) {
173
183
  rewritten = false;
174
184
  setMessages(all => (replace ? snapshot.messages : mergeSnapshot(all, snapshot.messages)));
175
185
  applyState(snapshot.status);
186
+ snapshotted = true;
176
187
  setConnection("connected");
177
188
  },
178
189
  onEvent: event => {
@@ -205,38 +216,25 @@ export function useBase44Chat({ appId, backend, onAppCreated }) {
205
216
  const respond = useCallback((toolCallId, messageId, approve, extraUserInput) => {
206
217
  if (!currentAppId)
207
218
  return Promise.resolve();
208
- setError(null);
219
+ setCallError(null);
209
220
  setSubmitted(currentAppId);
210
221
  setAnswered(ids => [...ids, toolCallId]);
211
- return backend.submitToolCallInput(currentAppId, { toolCallId, messageId, approve, extraUserInput }).catch((e) => {
222
+ return backendRef.current.submitToolCallInput(currentAppId, { toolCallId, messageId, approve, extraUserInput }).catch((e) => {
212
223
  setAnswered(ids => ids.filter(id => id !== toolCallId));
213
224
  setSubmitted(null);
214
225
  fail(e);
215
226
  });
216
- }, [currentAppId, backend, fail]);
227
+ }, [currentAppId, fail]);
217
228
  const sorted = useMemo(() => sortMessages(messages), [messages]);
218
229
  const shownPending = useMemo(() => pending.filter(p => p.appId === currentAppId || (p.appId === creating && !currentAppId)), [pending, currentAppId]);
219
230
  const items = useMemo(() => [...toItems(sorted, answered, respond), ...pendingItems(shownPending)], [sorted, answered, respond, shownPending]);
220
231
  const waiting = useMemo(() => isWaiting(sorted, answered), [sorted, answered]);
221
- // A question kind this release doesn't know is declined once per tool call; Base44 then
222
- // reports its step stopped. If the decline fails, the step waits again and the error shows.
223
- const declined = useRef(new Set());
232
+ // An answered call stays hidden while Base44 still reports it waiting, and is forgotten once it
233
+ // doesn't: if Base44 parks it again, its question comes back.
224
234
  useEffect(() => {
225
- const id = currentAppId;
226
- if (!id)
227
- return;
228
- for (const { toolCallId, messageId } of unknownWaiting(sorted)) {
229
- const key = `${id}:${toolCallId}`;
230
- if (declined.current.has(key))
231
- continue;
232
- declined.current.add(key);
233
- setAnswered(ids => [...ids, toolCallId]);
234
- backendRef.current.submitToolCallInput(id, { toolCallId, messageId, approve: false }).catch((e) => {
235
- setAnswered(ids => ids.filter(other => other !== toolCallId));
236
- fail(e);
237
- });
238
- }
239
- }, [currentAppId, sorted, fail]);
235
+ const waiting = waitingIds(sorted);
236
+ setAnswered(ids => (ids.every(id => waiting.has(id)) ? ids : ids.filter(id => waiting.has(id))));
237
+ }, [sorted]);
240
238
  const status = appState === "error" ? "error" : waiting ? "waiting" : appState === "processing" ? "building"
241
239
  : (submitted === creating && !currentAppId) || (submitted !== null && submitted === currentAppId) ? "submitted" : "ready";
242
240
  const addPending = useCallback((content, appId) => {
@@ -246,24 +244,24 @@ export function useBase44Chat({ appId, backend, onAppCreated }) {
246
244
  }, []);
247
245
  const send = useCallback((message) => {
248
246
  if (!currentAppId) {
249
- setError({ message: "There is no app to send to yet: create one first" });
247
+ setCallError({ message: "There is no app to send to yet: create one first" });
250
248
  return Promise.resolve();
251
249
  }
252
- setError(null);
250
+ setCallError(null);
253
251
  setSubmitted(currentAppId);
254
252
  const prompt = addPending(message, currentAppId);
255
- return backend.sendMessage(currentAppId, message).catch((e) => {
253
+ return backendRef.current.sendMessage(currentAppId, message).catch((e) => {
256
254
  setSubmitted(null);
257
255
  setPending(all => all.filter(p => p !== prompt));
258
256
  fail(e);
259
257
  });
260
- }, [currentAppId, backend, fail, addPending]);
258
+ }, [currentAppId, fail, addPending]);
261
259
  const create = useCallback(async (message) => {
262
- setError(null);
260
+ setCallError(null);
263
261
  setSubmitted(creating);
264
262
  const prompt = addPending(message, creating);
265
263
  try {
266
- const app = await backend.createApp(message);
264
+ const app = await backendRef.current.createApp(message);
267
265
  setCreatedAppId(app.id);
268
266
  setSubmitted(app.id);
269
267
  setPending(all => all.map(p => (p === prompt ? { ...p, appId: app.id } : p)));
@@ -274,7 +272,10 @@ export function useBase44Chat({ appId, backend, onAppCreated }) {
274
272
  setPending(all => all.filter(p => p !== prompt));
275
273
  fail(e);
276
274
  }
277
- }, [backend, onAppCreated, fail, addPending]);
278
- const clearError = useCallback(() => setError(null), []);
279
- return { items, status, connection, error: error !== null && error !== void 0 ? error : (appState === "error" ? buildFailed : null), send, create, clearError };
275
+ }, [onAppCreated, fail, addPending]);
276
+ const clearError = useCallback(() => {
277
+ setCallError(null);
278
+ setLiveError(null);
279
+ }, []);
280
+ return { items, status, connection, error: (_a = callError !== null && callError !== void 0 ? callError : liveError) !== null && _a !== void 0 ? _a : (appState === "error" ? buildFailed : null), send, create, clearError };
280
281
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@base44-preview/platform",
3
- "version": "0.2.0-pr.315.69f7032",
3
+ "version": "0.2.0-pr.315.ebc1eb8",
4
4
  "description": "Client and server SDK for building on the Base44 platform",
5
5
  "main": "dist/client/index.js",
6
6
  "types": "dist/client/index.d.ts",