@base44-preview/platform 0.2.0-pr.315.69f7032 → 0.2.0-pr.315.8896ad8

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
@@ -101,8 +101,7 @@ their exceptions are isolated so they cannot interrupt another app's delivery.
101
101
 
102
102
  - `PlatformClient` (`client.types.ts`): the `builder` module.
103
103
  - `BuilderModule` (`modules/builder.types.ts`): lazy `init(options)` factory.
104
- - `BuilderInitOptions`: `getSession`, the connection-level `onError` observer, and an optional
105
- `onConnectionChange` that reports `connected` and `reconnecting`.
104
+ - `BuilderInitOptions`: `getSession` and the connection-level `onError` observer.
106
105
  - `SocketSession`: the `session_token`, `socket_url` and `socket_path` that `getSession` returns.
107
106
  - `BuilderSession`: `connect()`, `subscribe(appId, options)`, `close()`.
108
107
  - `SubscriptionOptions`: required `onSnapshot`, `onEvent` and `onError`.
@@ -192,10 +191,10 @@ chat.items.map((item) =>
192
191
  `openLiveSession`, `sendMessage` and `submitToolCallInput`, each wrapping one Base44 REST
193
192
  call with your credentials, so the browser never holds a key. The hook returns `items`, a
194
193
  `status` (`ready`, `submitted`, `building`, `waiting`, `error`), a `connection` (`connecting`,
195
- `connected`, `reconnecting`, `disconnected`), an `error`, and the actions `send`, `create` and `clearError`. `send` needs an app; `create` makes
194
+ `connected`, `disconnected`), an `error`, and the actions `send`, `create` and `clearError`. `send` needs an app; `create` makes
196
195
  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
196
+ `pending` item until Base44's own message arrives; a prompt sent mid-build waits in Base44's
197
+ queue meanwhile. A question is a union on `kind` (`choice`, `secrets`, `approval`) and carries only the
198
+ actions its kind allows, and declining is always one of them. As in Base44's builder, only the
199
+ last assistant message makes the chat wait; a kind this release doesn't know is declined for you. Every shape has JSDoc in `src/react/chat.types.ts`, and
201
200
  [`examples/react-chat/`](examples/react-chat) shows Tiny Sunny's chat built on it, with its `backend`.
@@ -40,7 +40,6 @@ export declare class BuilderSocket implements BuilderSession {
40
40
  private refused;
41
41
  private retryDenied;
42
42
  private clearConnecting;
43
- private connectionChanged;
44
43
  private connectionError;
45
44
  private sessionEnded;
46
45
  private roomNotice;
@@ -11,7 +11,7 @@ export class BuilderSocket {
11
11
  this.tokenFresh = false;
12
12
  this.denialRetries = 0;
13
13
  this.authAttempt = 0;
14
- this.options = { getSession: options.getSession, onError: options.onError, onConnectionChange: options.onConnectionChange };
14
+ this.options = { getSession: options.getSession, onError: options.onError };
15
15
  }
16
16
  /** Connect with the session's token. Resolves on CONNECT, before snapshots arrive.
17
17
  * The first call fetches the session, whose address the socket opens on.
@@ -94,22 +94,15 @@ export class BuilderSocket {
94
94
  this.join(subscription);
95
95
  (_a = this.resolveConnect) === null || _a === void 0 ? void 0 : _a.call(this);
96
96
  this.clearConnecting();
97
- this.connectionChanged("connected");
98
97
  });
99
98
  socket.on("disconnect", (reason) => {
100
99
  ++this.authAttempt;
101
- if (this.closed || reason === "io client disconnect")
102
- return;
103
- if (reason !== "io server disconnect") {
104
- this.connectionChanged("reconnecting");
105
- return;
106
- } // Transport loss reconnects by itself.
100
+ if (this.closed || reason !== "io server disconnect")
101
+ return; // Transport loss reconnects by itself.
107
102
  const ending = this.ending;
108
103
  this.ending = undefined;
109
- if (ending === "session_expired") { // Renew through getSession.
110
- this.connectionChanged("reconnecting");
111
- socket.connect();
112
- }
104
+ if (ending === "session_expired")
105
+ socket.connect(); // Renew through getSession.
113
106
  else
114
107
  this.connectionError(new PlatformSocketError(ending !== null && ending !== void 0 ? ending : "connection_failed"));
115
108
  });
@@ -233,13 +226,6 @@ export class BuilderSocket {
233
226
  this.resolveConnect = undefined;
234
227
  this.rejectConnect = undefined;
235
228
  }
236
- connectionChanged(state) {
237
- var _a, _b;
238
- try {
239
- (_b = (_a = this.options).onConnectionChange) === null || _b === void 0 ? void 0 : _b.call(_a, state);
240
- }
241
- catch ( /* An observer cannot interrupt the connection. */_c) { /* An observer cannot interrupt the connection. */ }
242
- }
243
229
  connectionError(error) {
244
230
  var _a;
245
231
  (_a = this.rejectConnect) === null || _a === void 0 ? void 0 : _a.call(this, error);
@@ -34,12 +34,6 @@ export interface BuilderInitOptions {
34
34
  * [error codes](/developers/references/platform-sdk/docs/classes/PlatformSocketError#platformsocketerrorcode).
35
35
  */
36
36
  onError: (error: PlatformSocketError) => void;
37
- /**
38
- * Called when the socket connects, and when a connected socket drops and will retry.
39
- * `reconnecting` arrives on a lost connection or an expired session that renews; `connected`
40
- * on every successful connect. A retry that gives up reports through `onError` instead.
41
- */
42
- onConnectionChange?: (state: "connected" | "reconnecting") => void;
43
37
  }
44
38
  /**
45
39
  * Builder module for following the AI chat in your users' apps live.
@@ -14,18 +14,23 @@ 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 or declined here stops counting. */
23
25
  export declare function isWaiting(sorted: Message[], answered: string[]): boolean;
24
- /** @internal Waiting tool calls of a kind this release can't show, to decline. */
26
+ /** @internal Waiting calls on the last assistant message whose kind Base44 names and this release
27
+ * doesn't know, to decline. A call with no kind comes only from old messages and is left alone. */
25
28
  export declare function unknownWaiting(sorted: Message[]): {
26
29
  toolCallId: string;
27
30
  messageId: string;
28
31
  }[];
32
+ /** @internal The ids of tool calls Base44 reports waiting. */
33
+ export declare function waitingIds(sorted: Message[]): Set<string>;
29
34
  /** @internal A prompt sent from this chat that Base44 has not confirmed, for the app it went to. */
30
35
  export interface PendingPrompt {
31
36
  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,26 @@ 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 or declined here stops counting. */
59
71
  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)); });
72
+ var _a;
73
+ const last = lastActionable(sorted);
74
+ 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
75
  }
62
76
  const knownKinds = ["approval", "choice", "input"];
63
- /** @internal Waiting tool calls of a kind this release can't show, to decline. */
77
+ /** @internal Waiting calls on the last assistant message whose kind Base44 names and this release
78
+ * doesn't know, to decline. A call with no kind comes only from old messages and is left alone. */
64
79
  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
- });
80
+ var _a;
81
+ const last = lastActionable(sorted);
82
+ return ((_a = last === null || last === void 0 ? void 0 : last.tool_calls) !== null && _a !== void 0 ? _a : [])
83
+ .filter(tool => { var _a; return tool.status === "waiting_for_user_input" && ((_a = tool.waiting_on) === null || _a === void 0 ? void 0 : _a.kind) && !knownKinds.includes(tool.waiting_on.kind); })
84
+ .map(tool => ({ toolCallId: tool.id, messageId: last.id }));
85
+ }
86
+ /** @internal The ids of tool calls Base44 reports waiting. */
87
+ export function waitingIds(sorted) {
88
+ 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
89
  }
72
90
  /** @internal Prompts that arrived from Base44 as messages settle the pending ones
73
91
  * with the same text. Base44's public send carries no client id, so text is the only link. With
@@ -37,7 +37,7 @@ export interface ToolCallAnswer {
37
37
  */
38
38
  export interface Base44ChatBackend {
39
39
  /** Creates an app from its first prompt. The build starts inside this call. */
40
- createApp(message: string): Promise<Base44App>;
40
+ createApp(prompt: string): Promise<Base44App>;
41
41
  /** Opens a read-only live-updates session for one app. */
42
42
  openLiveSession(appId: string): Promise<SocketSession>;
43
43
  /** Sends a prompt to an existing app. */
@@ -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 doesn't know. */
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 kind this release doesn't know is declined for you, once per tool call, when Base44 names
87
+ * it on the last assistant message; if that fails, `error` says so and a reconnect tries again.
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,17 +150,14 @@ 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`
156
- * after it, `reconnecting` while the socket retries a dropped connection, and `disconnected`
157
- * once live updates have stopped for good: the session could not open, the retries ran out, or
157
+ * after it, and `disconnected` once live updates have stopped for good: the session could not open, the retries ran out, or
158
158
  * Base44 ended the session or the app's subscription. {@link Base44Chat.error} says why. Watching
159
159
  * another app, or mounting the chat again, starts over. */
160
- export type ChatConnection = "connecting" | "connected" | "reconnecting" | "disconnected";
160
+ export type ChatConnection = "connecting" | "connected" | "disconnected";
161
161
  /** A failure: of a call, of the live connection, or of the build itself. */
162
162
  export interface ChatError {
163
163
  /** What went wrong, for people. */
@@ -193,9 +193,9 @@ export interface Base44Chat {
193
193
  /** Sends a prompt to the current app; Base44 queues it while the builder is busy. Resolves once
194
194
  * the request is accepted, and the reply arrives through `items`. Needs an app: without one it
195
195
  * sets `error`, and `create` makes the first. */
196
- send(message: string): Promise<void>;
196
+ send(prompt: string): Promise<void>;
197
197
  /** Creates a new app from its first prompt and reports it through `onAppCreated`. */
198
- create(message: string): Promise<void>;
198
+ create(prompt: string): Promise<void>;
199
199
  /** Clears a failed call's or the connection's {@link Base44Chat.error}. */
200
200
  clearError(): void;
201
201
  }
@@ -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, unknownWaiting, 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.
@@ -45,24 +45,28 @@ 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);
63
64
  // Prompts sent from here, shown until Base44 has them.
64
65
  const [pending, setPending] = useState([]);
65
66
  const pendingCount = useRef(0);
67
+ // Tool calls declined for the user, and those whose decline failed and may try again.
68
+ const declined = useRef(new Set());
69
+ const failedDeclines = useRef(new Set());
66
70
  // The app `create` made, shown while `appId` is null. Any change to `appId` forgets it.
67
71
  const [createdAppId, setCreatedAppId] = useState(null);
68
72
  const [lastAppIdProp, setLastAppIdProp] = useState(appId);
@@ -81,19 +85,20 @@ export function useBase44Chat({ appId, backend, onAppCreated }) {
81
85
  setMessages([]);
82
86
  setAppState(undefined);
83
87
  setConnection("connecting");
84
- setError(null);
88
+ setCallError(null);
89
+ setLiveError(null);
85
90
  setAnswered([]);
86
91
  if (submitted !== currentAppId && submitted !== creating)
87
92
  setSubmitted(null);
88
93
  setPending(pending.filter(p => p.appId === currentAppId || p.appId === creating));
89
94
  }
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.
95
+ // The backend is read through a ref, kept current after every render, so an inline
96
+ // `backend={{…}}` never reopens the socket or changes the actions' identity.
92
97
  const backendRef = useRef(backend);
93
98
  useEffect(() => {
94
99
  backendRef.current = backend;
95
100
  });
96
- const fail = useCallback((e) => setError({ message: (e === null || e === void 0 ? void 0 : e.message) || "Something went wrong", cause: e }), []);
101
+ const fail = useCallback((e) => setCallError({ message: (e === null || e === void 0 ? void 0 : e.message) || "Something went wrong", cause: e }), []);
97
102
  // Live updates: a snapshot on every connect, then events.
98
103
  useEffect(() => {
99
104
  const id = currentAppId;
@@ -103,7 +108,7 @@ export function useBase44Chat({ appId, backend, onAppCreated }) {
103
108
  let session;
104
109
  const failLive = (e) => {
105
110
  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 });
111
+ 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
112
  };
108
113
  // A failure of the session or the subscription ends live updates: nothing retries after it.
109
114
  const endLive = (e) => {
@@ -147,7 +152,10 @@ export function useBase44Chat({ appId, backend, onAppCreated }) {
147
152
  // no detail of a failed call, so the backend's own error is kept to report.
148
153
  let sessionFailure;
149
154
  const builder = createPlatformClient().builder.init({
150
- getSession: () => backendRef.current.openLiveSession(id).catch((e) => {
155
+ getSession: () => backendRef.current.openLiveSession(id).then(session => {
156
+ sessionFailure = undefined;
157
+ return session;
158
+ }, (e) => {
151
159
  sessionFailure = e;
152
160
  throw e;
153
161
  }),
@@ -156,13 +164,9 @@ export function useBase44Chat({ appId, backend, onAppCreated }) {
156
164
  return endLive(e);
157
165
  if (stopped)
158
166
  return;
159
- setError({ message: (sessionFailure === null || sessionFailure === void 0 ? void 0 : sessionFailure.message) || e.message, code: e.code, cause: sessionFailure });
167
+ setLiveError({ message: (sessionFailure === null || sessionFailure === void 0 ? void 0 : sessionFailure.message) || e.message, code: e.code, cause: sessionFailure });
160
168
  setConnection("disconnected");
161
169
  },
162
- onConnectionChange: state => {
163
- if (state === "reconnecting")
164
- setConnection("reconnecting");
165
- },
166
170
  });
167
171
  session = builder;
168
172
  builder.subscribe(id, {
@@ -173,6 +177,10 @@ export function useBase44Chat({ appId, backend, onAppCreated }) {
173
177
  rewritten = false;
174
178
  setMessages(all => (replace ? snapshot.messages : mergeSnapshot(all, snapshot.messages)));
175
179
  applyState(snapshot.status);
180
+ // A declined call that failed tries again on the next snapshot, after a reconnect.
181
+ for (const key of failedDeclines.current)
182
+ declined.current.delete(key);
183
+ failedDeclines.current.clear();
176
184
  setConnection("connected");
177
185
  },
178
186
  onEvent: event => {
@@ -205,22 +213,21 @@ export function useBase44Chat({ appId, backend, onAppCreated }) {
205
213
  const respond = useCallback((toolCallId, messageId, approve, extraUserInput) => {
206
214
  if (!currentAppId)
207
215
  return Promise.resolve();
208
- setError(null);
216
+ setCallError(null);
209
217
  setSubmitted(currentAppId);
210
218
  setAnswered(ids => [...ids, toolCallId]);
211
- return backend.submitToolCallInput(currentAppId, { toolCallId, messageId, approve, extraUserInput }).catch((e) => {
219
+ return backendRef.current.submitToolCallInput(currentAppId, { toolCallId, messageId, approve, extraUserInput }).catch((e) => {
212
220
  setAnswered(ids => ids.filter(id => id !== toolCallId));
213
221
  setSubmitted(null);
214
222
  fail(e);
215
223
  });
216
- }, [currentAppId, backend, fail]);
224
+ }, [currentAppId, fail]);
217
225
  const sorted = useMemo(() => sortMessages(messages), [messages]);
218
226
  const shownPending = useMemo(() => pending.filter(p => p.appId === currentAppId || (p.appId === creating && !currentAppId)), [pending, currentAppId]);
219
227
  const items = useMemo(() => [...toItems(sorted, answered, respond), ...pendingItems(shownPending)], [sorted, answered, respond, shownPending]);
220
228
  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());
229
+ // A kind this release doesn't know is declined once per tool call. If that fails, the step waits
230
+ // again, the error shows, and the next snapshot tries once more.
224
231
  useEffect(() => {
225
232
  const id = currentAppId;
226
233
  if (!id)
@@ -232,11 +239,18 @@ export function useBase44Chat({ appId, backend, onAppCreated }) {
232
239
  declined.current.add(key);
233
240
  setAnswered(ids => [...ids, toolCallId]);
234
241
  backendRef.current.submitToolCallInput(id, { toolCallId, messageId, approve: false }).catch((e) => {
242
+ failedDeclines.current.add(key);
235
243
  setAnswered(ids => ids.filter(other => other !== toolCallId));
236
244
  fail(e);
237
245
  });
238
246
  }
239
247
  }, [currentAppId, sorted, fail]);
248
+ // An answered call stays hidden while Base44 still reports it waiting, and is forgotten once it
249
+ // doesn't: if Base44 parks it again, its question comes back.
250
+ useEffect(() => {
251
+ const waiting = waitingIds(sorted);
252
+ setAnswered(ids => (ids.every(id => waiting.has(id)) ? ids : ids.filter(id => waiting.has(id))));
253
+ }, [sorted]);
240
254
  const status = appState === "error" ? "error" : waiting ? "waiting" : appState === "processing" ? "building"
241
255
  : (submitted === creating && !currentAppId) || (submitted !== null && submitted === currentAppId) ? "submitted" : "ready";
242
256
  const addPending = useCallback((content, appId) => {
@@ -244,37 +258,40 @@ export function useBase44Chat({ appId, backend, onAppCreated }) {
244
258
  setPending(all => [...all, prompt]);
245
259
  return prompt;
246
260
  }, []);
247
- const send = useCallback((message) => {
261
+ const send = useCallback((prompt) => {
248
262
  if (!currentAppId) {
249
- setError({ message: "There is no app to send to yet: create one first" });
263
+ setCallError({ message: "There is no app to send to yet: create one first" });
250
264
  return Promise.resolve();
251
265
  }
252
- setError(null);
266
+ setCallError(null);
253
267
  setSubmitted(currentAppId);
254
- const prompt = addPending(message, currentAppId);
255
- return backend.sendMessage(currentAppId, message).catch((e) => {
268
+ const shown = addPending(prompt, currentAppId);
269
+ return backendRef.current.sendMessage(currentAppId, prompt).catch((e) => {
256
270
  setSubmitted(null);
257
- setPending(all => all.filter(p => p !== prompt));
271
+ setPending(all => all.filter(p => p !== shown));
258
272
  fail(e);
259
273
  });
260
- }, [currentAppId, backend, fail, addPending]);
261
- const create = useCallback(async (message) => {
262
- setError(null);
274
+ }, [currentAppId, fail, addPending]);
275
+ const create = useCallback(async (prompt) => {
276
+ setCallError(null);
263
277
  setSubmitted(creating);
264
- const prompt = addPending(message, creating);
278
+ const shown = addPending(prompt, creating);
265
279
  try {
266
- const app = await backend.createApp(message);
280
+ const app = await backendRef.current.createApp(prompt);
267
281
  setCreatedAppId(app.id);
268
282
  setSubmitted(app.id);
269
- setPending(all => all.map(p => (p === prompt ? { ...p, appId: app.id } : p)));
283
+ setPending(all => all.map(p => (p === shown ? { ...p, appId: app.id } : p)));
270
284
  onAppCreated === null || onAppCreated === void 0 ? void 0 : onAppCreated(app);
271
285
  }
272
286
  catch (e) {
273
287
  setSubmitted(null);
274
- setPending(all => all.filter(p => p !== prompt));
288
+ setPending(all => all.filter(p => p !== shown));
275
289
  fail(e);
276
290
  }
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 };
291
+ }, [onAppCreated, fail, addPending]);
292
+ const clearError = useCallback(() => {
293
+ setCallError(null);
294
+ setLiveError(null);
295
+ }, []);
296
+ 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
297
  }
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.8896ad8",
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",