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

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,34 +1,36 @@
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, waitingIds } from "./chat-items.js";
4
+ import { isWaitingForUser, mergeMessage, mergeSnapshot, pendingPromptItems, settlePendingPrompts, sortMessages, toItems, unknownKindToolCalls, waitingToolCallIds } from "./chat-items.js";
5
5
  // Base44's public status carries no reason, so a failed build has one error.
6
- const buildFailed = { message: "The build failed", code: "build_failed" };
7
- // What `submitted` waits on while `create` runs, before the new app has an id.
8
- const creating = "creating";
6
+ const BUILD_FAILED_ERROR = { message: "The build failed", code: "build_failed" };
7
+ // The target of `submittedTo` while `create` runs, before the new app has an id.
8
+ const NEW_APP = "new-app";
9
9
  /**
10
- * Runs one app's builder chat, headless: it keeps the live connection through
11
- * the platform client, turns Base44's messages into {@link ChatItem | items}, binds
12
- * every open question to the step it belongs to. You render the items.
10
+ * Runs the AI chat for one app in your own UI.
13
11
  *
14
- * All Base44 calls go through the {@link Base44ChatBackend | backend} you pass, so no
15
- * credential reaches the browser. Actions never throw: a failure lands in
16
- * {@link Base44Chat.error}, and a question whose reply failed opens again. A question kind
17
- * this release can't show is a waiting step without a question, as in Base44's own builder.
12
+ * The hook renders nothing. It gives you the conversation and the actions, and you draw them:
13
+ * - 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 Base44Chat.status}, and the live connection in {@link Base44Chat.connection}.
16
+ * - Sends prompts, creates apps and answers questions through the {@link Base44ChatBackend | backend} you pass, so no credential reaches the browser.
18
17
  *
19
- * Requires a browser environment. One live session is opened per app and renewed through
20
- * `backend.openLiveSession` when it expires; switching apps closes the old one and starts over.
18
+ * The actions never throw. A failure sets {@link Base44Chat.error}, and a question whose answer
19
+ * failed opens again. The chat declines a question kind this release doesn't know.
21
20
  *
22
- * The chat watches `appId` when it is set. While it is `null`, the chat watches the app
23
- * {@link Base44Chat.create} just made, so passing the new id back is optional; any change to
24
- * `appId` forgets that app, so setting `appId` back to `null` starts a new chat.
21
+ * Requires a browser environment and can't be used in the backend.
25
22
  *
26
- * @param options - The app to watch, your backend's calls, and what to do with a created app.
23
+ * The chat follows `appId` when it's set. While `appId` is `null`, it follows the app
24
+ * {@link Base44Chat.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.
27
+ *
28
+ * @param options - The app to follow, your backend's calls, and what to do with a created app.
27
29
  * @returns The conversation, its status, connection and error, and the actions `send`, `create` and `clearError`.
28
30
  *
29
31
  * @example
30
32
  * ```typescript
31
- * // Render the items, answer a question
33
+ * // Draw the chat and answer an approval
32
34
  * const chat = useBase44Chat({ appId, backend, onAppCreated: selectApp });
33
35
  * return (
34
36
  * <>
@@ -53,41 +55,52 @@ const creating = "creating";
53
55
  export function useBase44Chat({ appId, backend, onAppCreated }) {
54
56
  var _a;
55
57
  const [messages, setMessages] = useState([]);
56
- const [appState, setAppState] = useState();
58
+ const [buildState, setBuildState] = useState();
59
+ const [turnId, setTurnId] = useState(null);
57
60
  const [connection, setConnection] = useState("connecting");
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);
61
- const [answered, setAnswered] = useState([]);
62
- // The app a prompt or an answer went to, or `creating`, until Base44 reacts to it.
63
- const [submitted, setSubmitted] = useState(null);
61
+ // A failed action's error, which the next action clears, and the connection's, which it doesn't.
62
+ const [actionError, setActionError] = useState(null);
63
+ const [connectionError, setConnectionError] = useState(null);
64
+ // Tool calls answered here while Base44 still reports them waiting.
65
+ const [answeredToolCallIds, setAnsweredToolCallIds] = useState([]);
66
+ // The app a prompt, a new app or an answer went to, until Base44 reacts to it.
67
+ const [submittedTo, setSubmittedTo] = useState(null);
64
68
  // Prompts sent from here, shown until Base44 has them.
65
- const [pending, setPending] = useState([]);
66
- const pendingCount = useRef(0);
69
+ const [pendingPrompts, setPendingPrompts] = useState([]);
70
+ const pendingPromptCount = useRef(0);
71
+ // Tool calls declined for the user, and those whose decline failed and may try again.
72
+ const declinedToolCalls = useRef(new Set());
73
+ const failedDeclines = useRef(new Set());
74
+ // Tool calls answered from here whose submission ends when Base44 stops reporting them waiting.
75
+ const answersAwaitingBase44 = useRef(new Set());
67
76
  // The app `create` made, shown while `appId` is null. Any change to `appId` forgets it.
68
77
  const [createdAppId, setCreatedAppId] = useState(null);
69
- const [lastAppIdProp, setLastAppIdProp] = useState(appId);
70
- const appIdChanged = lastAppIdProp !== appId;
71
- if (appIdChanged) {
72
- setLastAppIdProp(appId);
78
+ const [previousAppIdProp, setPreviousAppIdProp] = useState(appId);
79
+ const appIdPropChanged = previousAppIdProp !== appId;
80
+ if (appIdPropChanged) {
81
+ setPreviousAppIdProp(appId);
73
82
  setCreatedAppId(null);
74
83
  }
75
84
  // The app this chat shows.
76
- const currentAppId = appId !== null && appId !== void 0 ? appId : (appIdChanged ? null : createdAppId);
85
+ const currentAppId = appId !== null && appId !== void 0 ? appId : (appIdPropChanged ? null : createdAppId);
77
86
  // Switching apps starts over: the state resets in the same render that sees the new app.
78
- // A `submitted` aimed at the new app, the one `create` just made, stays.
79
- const [shownAppId, setShownAppId] = useState(currentAppId);
80
- if (shownAppId !== currentAppId) {
81
- setShownAppId(currentAppId);
87
+ // A submission aimed at the new app, the one `create` just made, stays.
88
+ const [stateAppId, setStateAppId] = useState(currentAppId);
89
+ if (stateAppId !== currentAppId) {
90
+ setStateAppId(currentAppId);
82
91
  setMessages([]);
83
- setAppState(undefined);
92
+ setBuildState(undefined);
93
+ setTurnId(null);
84
94
  setConnection("connecting");
85
- setCallError(null);
86
- setLiveError(null);
87
- setAnswered([]);
88
- if (submitted !== currentAppId && submitted !== creating)
89
- setSubmitted(null);
90
- setPending(pending.filter(p => p.appId === currentAppId || p.appId === creating));
95
+ setActionError(null);
96
+ setConnectionError(null);
97
+ setAnsweredToolCallIds([]);
98
+ if (submittedTo !== currentAppId && submittedTo !== NEW_APP)
99
+ setSubmittedTo(null);
100
+ // Only the app `create` just handed over keeps its first prompt; any other is dropped, so it
101
+ // can't reappear when that app is picked later.
102
+ const handedOver = submittedTo !== null && submittedTo === currentAppId;
103
+ setPendingPrompts(pendingPrompts.filter(prompt => prompt.appId === NEW_APP || (handedOver && prompt.appId === currentAppId)));
91
104
  }
92
105
  // The backend is read through a ref, kept current after every render, so an inline
93
106
  // `backend={{…}}` never reopens the socket or changes the actions' identity.
@@ -95,187 +108,248 @@ export function useBase44Chat({ appId, backend, onAppCreated }) {
95
108
  useEffect(() => {
96
109
  backendRef.current = backend;
97
110
  });
98
- const fail = useCallback((e) => setCallError({ message: (e === null || e === void 0 ? void 0 : e.message) || "Something went wrong", cause: e }), []);
111
+ // The app the chat follows now, so a call that finishes after a switch doesn't touch the new app.
112
+ const followedAppIdRef = useRef(currentAppId);
113
+ useEffect(() => {
114
+ followedAppIdRef.current = currentAppId;
115
+ }, [currentAppId]);
116
+ const stillFollowing = (targetAppId) => followedAppIdRef.current === targetAppId;
117
+ const reportActionError = useCallback((error) => setActionError({ message: (error === null || error === void 0 ? void 0 : error.message) || "Something went wrong", cause: error }), []);
99
118
  // Live updates: a snapshot on every connect, then events.
100
119
  useEffect(() => {
101
- const id = currentAppId;
102
- if (!id)
120
+ const followedAppId = currentAppId;
121
+ if (!followedAppId)
103
122
  return;
104
- let stopped = false;
105
- let session;
106
- const failLive = (e) => {
107
- if (!stopped)
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 });
123
+ let closed = false;
124
+ const reportConnectionError = (error) => {
125
+ if (closed)
126
+ return;
127
+ setConnectionError({ message: (error === null || error === void 0 ? void 0 : error.message) || "Live updates failed", code: error === null || error === void 0 ? void 0 : error.code, cause: error });
109
128
  };
110
129
  // A failure of the session or the subscription ends live updates: nothing retries after it.
111
- const endLive = (e) => {
112
- failLive(e);
113
- if (!stopped)
130
+ const endLiveUpdates = (error) => {
131
+ reportConnectionError(error);
132
+ if (!closed)
114
133
  setConnection("disconnected");
115
134
  };
116
- // A reply this session hasn't seen ends `submitted`. A user message it hasn't seen is the
117
- // echo of a prompt, which settles the pending one.
118
- const seen = new Set();
119
- const arrive = (list, oldestOtherwise) => {
120
- const fresh = list.filter(m => m.id && !seen.has(m.id));
121
- for (const m of list)
122
- if (m.id)
123
- seen.add(m.id);
124
- if (fresh.some(m => m.role !== "user"))
125
- setSubmitted(null);
126
- const prompts = fresh.filter(m => m.role === "user").map(m => { var _a; return (_a = m.content) !== null && _a !== void 0 ? _a : ""; });
127
- if (prompts.length)
128
- setPending(all => settlePending(all, id, prompts, oldestOtherwise));
135
+ // A new reply ends the submission. A new user message is Base44's copy of a prompt, which
136
+ // settles the pending one.
137
+ const seenMessageIds = new Set();
138
+ const handleIncomingMessages = (incomingMessages) => {
139
+ const newMessages = incomingMessages.filter(message => message.id && !seenMessageIds.has(message.id));
140
+ for (const message of incomingMessages)
141
+ if (message.id)
142
+ seenMessageIds.add(message.id);
143
+ if (newMessages.some(message => message.role !== "user"))
144
+ setSubmittedTo(null);
145
+ const arrivedPrompts = newMessages.filter(message => message.role === "user").map(message => { var _a; return (_a = message.content) !== null && _a !== void 0 ? _a : ""; });
146
+ if (arrivedPrompts.length) {
147
+ setPendingPrompts(prompts => settlePendingPrompts(prompts, followedAppId, arrivedPrompts));
148
+ }
129
149
  };
130
150
  // A snapshot replaces the conversation when it is the first, or follows a rewrite of main
131
151
  // (undo, restore, sync); after a plain rejoin the messages before its window stay.
132
- let rewritten = true;
152
+ let nextSnapshotReplaces = true;
133
153
  // Base44 can resend an earlier turn's status after the next turn has started: one older than
134
154
  // the newest seen is stale.
135
- let statusAt = "";
136
- const applyState = (status) => {
137
- var _a;
138
- const at = (_a = status === null || status === void 0 ? void 0 : status.last_updated_date) !== null && _a !== void 0 ? _a : "";
139
- if (at && at < statusAt)
155
+ let latestStatusDate = "";
156
+ // A newer status, whatever its state, means Base44 has reacted, which ends the submission.
157
+ const applyBuildStatus = (buildStatus) => {
158
+ var _a, _b;
159
+ const statusDate = (_a = buildStatus === null || buildStatus === void 0 ? void 0 : buildStatus.last_updated_date) !== null && _a !== void 0 ? _a : "";
160
+ if (statusDate && statusDate < latestStatusDate)
140
161
  return;
141
- if (at)
142
- statusAt = at;
143
- const state = status === null || status === void 0 ? void 0 : status.state;
144
- setAppState(state);
145
- if (state === "processing" || state === "error")
146
- setSubmitted(null);
162
+ const isNewer = !!statusDate && statusDate > latestStatusDate;
163
+ if (statusDate)
164
+ latestStatusDate = statusDate;
165
+ const state = buildStatus === null || buildStatus === void 0 ? void 0 : buildStatus.state;
166
+ setBuildState(state);
167
+ setTurnId((_b = buildStatus === null || buildStatus === void 0 ? void 0 : buildStatus.turn_id) !== null && _b !== void 0 ? _b : null);
168
+ if (isNewer || state === "processing" || state === "error")
169
+ setSubmittedTo(null);
147
170
  };
148
171
  // The client asks for a session on the first connect and whenever one expires, and forwards
149
172
  // no detail of a failed call, so the backend's own error is kept to report.
150
- let sessionFailure;
151
- let snapshotted = false;
152
- const builder = createPlatformClient().builder.init({
153
- getSession: () => backendRef.current.openLiveSession(id).then(session => {
154
- sessionFailure = undefined;
155
- return session;
156
- }, (e) => {
157
- sessionFailure = e;
158
- throw e;
173
+ let lastSessionError;
174
+ const builderSession = createPlatformClient().builder.init({
175
+ getSession: () => backendRef.current.openLiveSession(followedAppId).then(socketSession => {
176
+ lastSessionError = undefined;
177
+ return socketSession;
178
+ }, (error) => {
179
+ lastSessionError = error;
180
+ throw error;
159
181
  }),
160
- onError: e => {
161
- if (e.code !== "session_unavailable" || !sessionFailure)
162
- return endLive(e);
163
- if (stopped)
182
+ onError: error => {
183
+ if (error.code !== "session_unavailable" || !lastSessionError)
184
+ return endLiveUpdates(error);
185
+ if (closed)
164
186
  return;
165
- setLiveError({ message: (sessionFailure === null || sessionFailure === void 0 ? void 0 : sessionFailure.message) || e.message, code: e.code, cause: sessionFailure });
187
+ setConnectionError({ message: (lastSessionError === null || lastSessionError === void 0 ? void 0 : lastSessionError.message) || error.message, code: error.code, cause: lastSessionError });
166
188
  setConnection("disconnected");
167
189
  },
168
- // Connected means seen live: the first time after a snapshot, and again on a reconnect,
169
- // even when the rejoin's snapshot fails.
170
- onConnectionChange: state => {
171
- if (state === "reconnecting")
172
- setConnection("reconnecting");
173
- else if (snapshotted && !stopped)
174
- setConnection("connected");
175
- },
176
190
  });
177
- session = builder;
178
- builder.subscribe(id, {
191
+ builderSession.subscribe(followedAppId, {
179
192
  onSnapshot: snapshot => {
180
193
  // A snapshot holds old prompts too, so only an exact match settles one.
181
- arrive(snapshot.messages, false);
182
- const replace = rewritten;
183
- rewritten = false;
184
- setMessages(all => (replace ? snapshot.messages : mergeSnapshot(all, snapshot.messages)));
185
- applyState(snapshot.status);
186
- snapshotted = true;
194
+ handleIncomingMessages(snapshot.messages);
195
+ const replaceMessages = nextSnapshotReplaces;
196
+ nextSnapshotReplaces = false;
197
+ setMessages(heldMessages => (replaceMessages ? snapshot.messages : mergeSnapshot(heldMessages, snapshot.messages)));
198
+ applyBuildStatus(snapshot.status);
199
+ // A declined call that failed tries again on the next snapshot, after a reconnect.
200
+ for (const declineKey of failedDeclines.current)
201
+ declinedToolCalls.current.delete(declineKey);
202
+ failedDeclines.current.clear();
187
203
  setConnection("connected");
188
204
  },
189
205
  onEvent: event => {
190
206
  if (event.type === "message.updated") {
191
- arrive([event.data.message], true);
192
- setMessages(all => mergeMessage(all, event.data.message));
207
+ handleIncomingMessages([event.data.message]);
208
+ setMessages(heldMessages => mergeMessage(heldMessages, event.data.message));
209
+ }
210
+ if (event.type === "message.removed") {
211
+ setMessages(heldMessages => heldMessages.filter(message => message.id !== event.data.message_id));
193
212
  }
194
- if (event.type === "message.removed")
195
- setMessages(all => all.filter(m => m.id !== event.data.message_id));
196
213
  if (event.type === "app.status_changed")
197
- applyState(event.data.status);
214
+ applyBuildStatus(event.data.status);
198
215
  if (event.type === "conversation.changed" && event.data.branch_id == null)
199
- rewritten = true;
200
- // A prompt sent while the builder is busy waits in Base44's queue: Base44 has it, and
201
- // it stays pending until it runs.
216
+ nextSnapshotReplaces = true;
217
+ // A prompt sent while the AI is working waits in Base44's queue: Base44 has it, and it
218
+ // stays pending until it runs.
202
219
  if (event.type === "queue.updated" && event.data.branch_id == null)
203
- setSubmitted(null);
220
+ setSubmittedTo(null);
204
221
  },
205
222
  // Only snapshot_unavailable leaves the subscription running.
206
- onError: e => (e.code === "snapshot_unavailable" ? failLive(e) : endLive(e)),
223
+ onError: error => (error.code === "snapshot_unavailable" ? reportConnectionError(error) : endLiveUpdates(error)),
207
224
  });
208
225
  // A failed connect also reaches onError, which reports it.
209
- builder.connect().catch(() => { });
226
+ builderSession.connect().catch(() => { });
210
227
  return () => {
211
- stopped = true;
212
- session === null || session === void 0 ? void 0 : session.close();
228
+ closed = true;
229
+ builderSession.close();
213
230
  };
214
231
  }, [currentAppId]);
215
- // Answers one tool call. Its id leaves `answered` again if the submit fails, so the question comes back.
216
- const respond = useCallback((toolCallId, messageId, approve, extraUserInput) => {
232
+ // Answers one tool call. Its id leaves the answered list again if the submit fails, so the
233
+ // question comes back.
234
+ const submitAnswer = useCallback((toolCallId, messageId, approve, extraUserInput) => {
217
235
  if (!currentAppId)
218
236
  return Promise.resolve();
219
- setCallError(null);
220
- setSubmitted(currentAppId);
221
- setAnswered(ids => [...ids, toolCallId]);
222
- return backendRef.current.submitToolCallInput(currentAppId, { toolCallId, messageId, approve, extraUserInput }).catch((e) => {
223
- setAnswered(ids => ids.filter(id => id !== toolCallId));
224
- setSubmitted(null);
225
- fail(e);
237
+ const targetAppId = currentAppId;
238
+ setActionError(null);
239
+ setSubmittedTo(targetAppId);
240
+ setAnsweredToolCallIds(ids => [...ids, toolCallId]);
241
+ answersAwaitingBase44.current.add(toolCallId);
242
+ const answer = { toolCallId, messageId, approve, extraUserInput };
243
+ return backendRef.current.submitToolCallInput(targetAppId, answer).catch((error) => {
244
+ answersAwaitingBase44.current.delete(toolCallId);
245
+ if (!stillFollowing(targetAppId))
246
+ return;
247
+ setAnsweredToolCallIds(ids => ids.filter(answeredId => answeredId !== toolCallId));
248
+ setSubmittedTo(null);
249
+ reportActionError(error);
226
250
  });
227
- }, [currentAppId, fail]);
228
- const sorted = useMemo(() => sortMessages(messages), [messages]);
229
- const shownPending = useMemo(() => pending.filter(p => p.appId === currentAppId || (p.appId === creating && !currentAppId)), [pending, currentAppId]);
230
- const items = useMemo(() => [...toItems(sorted, answered, respond), ...pendingItems(shownPending)], [sorted, answered, respond, shownPending]);
231
- const waiting = useMemo(() => isWaiting(sorted, answered), [sorted, answered]);
251
+ }, [currentAppId, reportActionError]);
252
+ const sortedMessages = useMemo(() => sortMessages(messages), [messages]);
253
+ const pendingForCurrentApp = useMemo(() => pendingPrompts.filter(prompt => prompt.appId === currentAppId || (prompt.appId === NEW_APP && !currentAppId)), [pendingPrompts, currentAppId]);
254
+ const items = useMemo(() => [...toItems(sortedMessages, answeredToolCallIds, submitAnswer), ...pendingPromptItems(pendingForCurrentApp)], [sortedMessages, answeredToolCallIds, submitAnswer, pendingForCurrentApp]);
255
+ const waitingForUser = useMemo(() => isWaitingForUser(sortedMessages, answeredToolCallIds), [sortedMessages, answeredToolCallIds]);
256
+ // A kind this release doesn't know is declined once per tool call. If that fails, the step waits
257
+ // again, the error shows, and the next snapshot tries once more.
258
+ useEffect(() => {
259
+ const followedAppId = currentAppId;
260
+ if (!followedAppId)
261
+ return;
262
+ for (const { toolCallId, messageId } of unknownKindToolCalls(sortedMessages)) {
263
+ const declineKey = `${followedAppId}:${toolCallId}`;
264
+ if (declinedToolCalls.current.has(declineKey))
265
+ continue;
266
+ declinedToolCalls.current.add(declineKey);
267
+ setAnsweredToolCallIds(ids => [...ids, toolCallId]);
268
+ backendRef.current.submitToolCallInput(followedAppId, { toolCallId, messageId, approve: false }).catch((error) => {
269
+ failedDeclines.current.add(declineKey);
270
+ setAnsweredToolCallIds(ids => ids.filter(answeredId => answeredId !== toolCallId));
271
+ reportActionError(error);
272
+ });
273
+ }
274
+ }, [currentAppId, sortedMessages, reportActionError]);
232
275
  // An answered call stays hidden while Base44 still reports it waiting, and is forgotten once it
233
276
  // doesn't: if Base44 parks it again, its question comes back.
277
+ // An answer's submission ends there too: Base44 has taken it once the call no longer waits.
234
278
  useEffect(() => {
235
- const waiting = waitingIds(sorted);
236
- setAnswered(ids => (ids.every(id => waiting.has(id)) ? ids : ids.filter(id => waiting.has(id))));
237
- }, [sorted]);
238
- const status = appState === "error" ? "error" : waiting ? "waiting" : appState === "processing" ? "building"
239
- : (submitted === creating && !currentAppId) || (submitted !== null && submitted === currentAppId) ? "submitted" : "ready";
240
- const addPending = useCallback((content, appId) => {
241
- const prompt = { id: `pending-${++pendingCount.current}`, content, createdAt: new Date().toISOString(), appId };
242
- setPending(all => [...all, prompt]);
243
- return prompt;
279
+ const stillWaiting = waitingToolCallIds(sortedMessages);
280
+ setAnsweredToolCallIds(ids => (ids.every(answeredId => stillWaiting.has(answeredId)) ? ids : ids.filter(answeredId => stillWaiting.has(answeredId))));
281
+ let answerTaken = false;
282
+ for (const toolCallId of answersAwaitingBase44.current) {
283
+ if (stillWaiting.has(toolCallId))
284
+ continue;
285
+ answersAwaitingBase44.current.delete(toolCallId);
286
+ answerTaken = true;
287
+ }
288
+ if (answerTaken)
289
+ setSubmittedTo(target => (target === followedAppIdRef.current ? null : target));
290
+ }, [sortedMessages]);
291
+ const submissionInFlight = (submittedTo === NEW_APP && !currentAppId) || (submittedTo !== null && submittedTo === currentAppId);
292
+ let status = "ready";
293
+ if (buildState === "error")
294
+ status = "error";
295
+ else if (waitingForUser)
296
+ status = "waiting";
297
+ else if (buildState === "processing")
298
+ status = "building";
299
+ else if (submissionInFlight)
300
+ status = "submitted";
301
+ const addPendingPrompt = useCallback((content, targetAppId) => {
302
+ const pendingPrompt = { id: `pending-${++pendingPromptCount.current}`, content, createdAt: new Date().toISOString(), appId: targetAppId };
303
+ setPendingPrompts(prompts => [...prompts, pendingPrompt]);
304
+ return pendingPrompt;
244
305
  }, []);
245
- const send = useCallback((message) => {
306
+ const send = useCallback((prompt) => {
246
307
  if (!currentAppId) {
247
- setCallError({ message: "There is no app to send to yet: create one first" });
308
+ setActionError({ message: "There is no app to send to yet: create one first" });
248
309
  return Promise.resolve();
249
310
  }
250
- setCallError(null);
251
- setSubmitted(currentAppId);
252
- const prompt = addPending(message, currentAppId);
253
- return backendRef.current.sendMessage(currentAppId, message).catch((e) => {
254
- setSubmitted(null);
255
- setPending(all => all.filter(p => p !== prompt));
256
- fail(e);
311
+ const targetAppId = currentAppId;
312
+ setActionError(null);
313
+ setSubmittedTo(targetAppId);
314
+ const pendingPrompt = addPendingPrompt(prompt, targetAppId);
315
+ return backendRef.current.sendMessage(targetAppId, prompt).catch((error) => {
316
+ setPendingPrompts(prompts => prompts.filter(other => other !== pendingPrompt));
317
+ if (!stillFollowing(targetAppId))
318
+ return;
319
+ setSubmittedTo(null);
320
+ reportActionError(error);
257
321
  });
258
- }, [currentAppId, fail, addPending]);
259
- const create = useCallback(async (message) => {
260
- setCallError(null);
261
- setSubmitted(creating);
262
- const prompt = addPending(message, creating);
322
+ }, [currentAppId, reportActionError, addPendingPrompt]);
323
+ const create = useCallback(async (prompt) => {
324
+ const startedFrom = followedAppIdRef.current;
325
+ const followsSetApp = appId !== null;
326
+ setActionError(null);
327
+ setSubmittedTo(NEW_APP);
328
+ const pendingPrompt = addPendingPrompt(prompt, NEW_APP);
263
329
  try {
264
- const app = await backendRef.current.createApp(message);
330
+ const app = await backendRef.current.createApp(prompt);
265
331
  setCreatedAppId(app.id);
266
- setSubmitted(app.id);
267
- setPending(all => all.map(p => (p === prompt ? { ...p, appId: app.id } : p)));
332
+ setSubmittedTo(app.id);
333
+ // With appId set, the chat doesn't follow the new app, so its first prompt has nowhere to
334
+ // show; the new app's own snapshot holds it once someone opens it.
335
+ if (followsSetApp)
336
+ setPendingPrompts(prompts => prompts.filter(other => other !== pendingPrompt));
337
+ else
338
+ setPendingPrompts(prompts => prompts.map(other => (other === pendingPrompt ? { ...other, appId: app.id } : other)));
268
339
  onAppCreated === null || onAppCreated === void 0 ? void 0 : onAppCreated(app);
269
340
  }
270
- catch (e) {
271
- setSubmitted(null);
272
- setPending(all => all.filter(p => p !== prompt));
273
- fail(e);
341
+ catch (error) {
342
+ setPendingPrompts(prompts => prompts.filter(other => other !== pendingPrompt));
343
+ if (!stillFollowing(startedFrom))
344
+ return;
345
+ setSubmittedTo(null);
346
+ reportActionError(error);
274
347
  }
275
- }, [onAppCreated, fail, addPending]);
348
+ }, [appId, onAppCreated, reportActionError, addPendingPrompt]);
276
349
  const clearError = useCallback(() => {
277
- setCallError(null);
278
- setLiveError(null);
350
+ setActionError(null);
351
+ setConnectionError(null);
279
352
  }, []);
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 };
353
+ const error = (_a = actionError !== null && actionError !== void 0 ? actionError : connectionError) !== null && _a !== void 0 ? _a : (buildState === "error" ? BUILD_FAILED_ERROR : null);
354
+ return { items, status, connection, turnId, error, send, create, clearError };
281
355
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@base44-preview/platform",
3
- "version": "0.2.0-pr.315.ebc1eb8",
3
+ "version": "0.2.0-pr.315.f940d50",
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",