@base44-preview/platform 0.2.0-pr.315.69f7032 → 0.2.0-pr.315.9332712
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 +6 -8
- package/dist/client/modules/builder-socket.d.ts +0 -1
- package/dist/client/modules/builder-socket.js +5 -19
- package/dist/client/modules/builder.types.d.ts +0 -6
- package/dist/react/chat-items.d.ts +9 -4
- package/dist/react/chat-items.js +30 -12
- package/dist/react/chat.types.d.ts +29 -12
- package/dist/react/useBase44Chat.d.ts +2 -4
- package/dist/react/useBase44Chat.js +56 -39
- package/package.json +1 -1
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
|
|
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,9 @@ 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`, `
|
|
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
|
|
198
|
-
|
|
199
|
-
actions its kind allows
|
|
200
|
-
declined for you. Every shape has JSDoc in `src/react/chat.types.ts
|
|
201
|
-
[`examples/react-chat/`](examples/react-chat) shows Tiny Sunny's chat built on it, with its `backend`.
|
|
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`.
|
|
@@ -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
|
|
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
|
|
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")
|
|
110
|
-
|
|
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.
|
|
18
|
-
*
|
|
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
|
|
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
|
|
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;
|
package/dist/react/chat-items.js
CHANGED
|
@@ -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
|
|
22
|
-
|
|
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) ?
|
|
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
|
|
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
|
-
|
|
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
|
|
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
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
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
|
|
@@ -34,10 +34,27 @@ export interface ToolCallAnswer {
|
|
|
34
34
|
* Base44 holds `sendMessage` and `submitToolCallInput` open for the whole turn, so resolve once
|
|
35
35
|
* the request is accepted rather than when it returns: the live session shows the rest.
|
|
36
36
|
* A rejected promise from any of them lands in {@link Base44Chat.error}.
|
|
37
|
+
*
|
|
38
|
+
* @example
|
|
39
|
+
* ```typescript
|
|
40
|
+
* // Your four calls, behind your own API routes
|
|
41
|
+
* async function post<T>(path: string, body: unknown): Promise<T> {
|
|
42
|
+
* const response = await fetch(path, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });
|
|
43
|
+
* if (!response.ok) throw new Error(`${path} failed: ${response.status}`);
|
|
44
|
+
* return response.json();
|
|
45
|
+
* }
|
|
46
|
+
*
|
|
47
|
+
* const backend: Base44ChatBackend = {
|
|
48
|
+
* createApp: (prompt) => post("/api/chat/apps", { prompt }),
|
|
49
|
+
* openLiveSession: (appId) => post("/api/chat/session", { appId }),
|
|
50
|
+
* sendMessage: (appId, content) => post("/api/chat/message", { appId, content }),
|
|
51
|
+
* submitToolCallInput: (appId, answer) => post("/api/chat/answer", { appId, answer }),
|
|
52
|
+
* };
|
|
53
|
+
* ```
|
|
37
54
|
*/
|
|
38
55
|
export interface Base44ChatBackend {
|
|
39
56
|
/** Creates an app from its first prompt. The build starts inside this call. */
|
|
40
|
-
createApp(
|
|
57
|
+
createApp(prompt: string): Promise<Base44App>;
|
|
41
58
|
/** Opens a read-only live-updates session for one app. */
|
|
42
59
|
openLiveSession(appId: string): Promise<SocketSession>;
|
|
43
60
|
/** Sends a prompt to an existing app. */
|
|
@@ -53,7 +70,8 @@ export interface ChatItem {
|
|
|
53
70
|
role: "user" | "assistant";
|
|
54
71
|
/** Raw markdown; it comes before the steps. Empty when the message is only tool activity. */
|
|
55
72
|
text: string;
|
|
56
|
-
/** When
|
|
73
|
+
/** When the message was created, as an ISO timestamp: Base44's for its messages, which carry no
|
|
74
|
+
* time zone and are UTC, and the browser's for a pending prompt. */
|
|
57
75
|
createdAt: string;
|
|
58
76
|
/** One per tool call, in order. */
|
|
59
77
|
steps: ChatStep[];
|
|
@@ -75,13 +93,15 @@ export interface ChatStep {
|
|
|
75
93
|
/** Where the call is. `waiting` waits on the user; `stopped` was declined, or the build was stopped. */
|
|
76
94
|
status: "running" | "waiting" | "done" | "stopped" | "error";
|
|
77
95
|
/** The question this step waits on, bound to the actions that answer it. Only while `status` is
|
|
78
|
-
* `waiting`, and
|
|
96
|
+
* `waiting`, and only in the last assistant message, the one that makes the chat wait. Gone once
|
|
97
|
+
* answered, and absent for a kind this release doesn't know. */
|
|
79
98
|
question?: ChatQuestion;
|
|
80
99
|
}
|
|
81
100
|
/**
|
|
82
101
|
* An open question, with the actions that answer this question and no other.
|
|
83
102
|
* 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
|
|
103
|
+
* A kind this release doesn't know is declined for you, once per tool call, when Base44 names
|
|
104
|
+
* it on the last assistant message; if that fails, `error` says so and a reconnect tries again.
|
|
85
105
|
* The actions never throw: a failure lands in {@link Base44Chat.error} and the question opens again.
|
|
86
106
|
*/
|
|
87
107
|
export type ChatQuestion = ChoiceQuestion | SecretsQuestion | ApprovalQuestion;
|
|
@@ -147,17 +167,14 @@ export interface ApprovalQuestion {
|
|
|
147
167
|
* - `submitted`: a prompt, a new app or an answer is on its way, until Base44 reports work,
|
|
148
168
|
* a reply or a queue change, or the call fails.
|
|
149
169
|
* - `ready`: everything else.
|
|
150
|
-
|
|
151
|
-
* To let the user send only when the builder can take a prompt now:
|
|
152
|
-
* `status === "ready" || status === "error"`.
|
|
170
|
+
|
|
153
171
|
*/
|
|
154
172
|
export type ChatStatus = "ready" | "submitted" | "building" | "waiting" | "error";
|
|
155
173
|
/** Whether the chat sees the builder live: `connecting` until the first snapshot, `connected`
|
|
156
|
-
* after it, `
|
|
157
|
-
* once live updates have stopped for good: the session could not open, the retries ran out, or
|
|
174
|
+
* after it, and `disconnected` once live updates have stopped for good: the session could not open, the retries ran out, or
|
|
158
175
|
* Base44 ended the session or the app's subscription. {@link Base44Chat.error} says why. Watching
|
|
159
176
|
* another app, or mounting the chat again, starts over. */
|
|
160
|
-
export type ChatConnection = "connecting" | "connected" | "
|
|
177
|
+
export type ChatConnection = "connecting" | "connected" | "disconnected";
|
|
161
178
|
/** A failure: of a call, of the live connection, or of the build itself. */
|
|
162
179
|
export interface ChatError {
|
|
163
180
|
/** What went wrong, for people. */
|
|
@@ -193,9 +210,9 @@ export interface Base44Chat {
|
|
|
193
210
|
/** Sends a prompt to the current app; Base44 queues it while the builder is busy. Resolves once
|
|
194
211
|
* the request is accepted, and the reply arrives through `items`. Needs an app: without one it
|
|
195
212
|
* sets `error`, and `create` makes the first. */
|
|
196
|
-
send(
|
|
213
|
+
send(prompt: string): Promise<void>;
|
|
197
214
|
/** Creates a new app from its first prompt and reports it through `onAppCreated`. */
|
|
198
|
-
create(
|
|
215
|
+
create(prompt: string): Promise<void>;
|
|
199
216
|
/** Clears a failed call's or the connection's {@link Base44Chat.error}. */
|
|
200
217
|
clearError(): void;
|
|
201
218
|
}
|
|
@@ -21,7 +21,7 @@ import type { Base44Chat, Base44ChatOptions } from "./chat.types.js";
|
|
|
21
21
|
*
|
|
22
22
|
* @example
|
|
23
23
|
* ```typescript
|
|
24
|
-
* //
|
|
24
|
+
* // Draw the chat and answer an approval
|
|
25
25
|
* const chat = useBase44Chat({ appId, backend, onAppCreated: selectApp });
|
|
26
26
|
* return (
|
|
27
27
|
* <>
|
|
@@ -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
|
|
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.
|
|
@@ -28,7 +28,7 @@ const creating = "creating";
|
|
|
28
28
|
*
|
|
29
29
|
* @example
|
|
30
30
|
* ```typescript
|
|
31
|
-
* //
|
|
31
|
+
* // Draw the chat and answer an approval
|
|
32
32
|
* const chat = useBase44Chat({ appId, backend, onAppCreated: selectApp });
|
|
33
33
|
* return (
|
|
34
34
|
* <>
|
|
@@ -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
|
|
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
|
-
|
|
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
|
-
|
|
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
|
|
91
|
-
//
|
|
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) =>
|
|
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
|
-
|
|
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).
|
|
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
|
-
|
|
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
|
-
|
|
216
|
+
setCallError(null);
|
|
209
217
|
setSubmitted(currentAppId);
|
|
210
218
|
setAnswered(ids => [...ids, toolCallId]);
|
|
211
|
-
return
|
|
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,
|
|
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
|
|
222
|
-
//
|
|
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((
|
|
261
|
+
const send = useCallback((prompt) => {
|
|
248
262
|
if (!currentAppId) {
|
|
249
|
-
|
|
263
|
+
setCallError({ message: "There is no app to send to yet: create one first" });
|
|
250
264
|
return Promise.resolve();
|
|
251
265
|
}
|
|
252
|
-
|
|
266
|
+
setCallError(null);
|
|
253
267
|
setSubmitted(currentAppId);
|
|
254
|
-
const
|
|
255
|
-
return
|
|
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 !==
|
|
271
|
+
setPending(all => all.filter(p => p !== shown));
|
|
258
272
|
fail(e);
|
|
259
273
|
});
|
|
260
|
-
}, [currentAppId,
|
|
261
|
-
const create = useCallback(async (
|
|
262
|
-
|
|
274
|
+
}, [currentAppId, fail, addPending]);
|
|
275
|
+
const create = useCallback(async (prompt) => {
|
|
276
|
+
setCallError(null);
|
|
263
277
|
setSubmitted(creating);
|
|
264
|
-
const
|
|
278
|
+
const shown = addPending(prompt, creating);
|
|
265
279
|
try {
|
|
266
|
-
const app = await
|
|
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 ===
|
|
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 !==
|
|
288
|
+
setPending(all => all.filter(p => p !== shown));
|
|
275
289
|
fail(e);
|
|
276
290
|
}
|
|
277
|
-
}, [
|
|
278
|
-
const clearError = useCallback(() =>
|
|
279
|
-
|
|
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