@raybase/agent-ui 0.0.2 → 0.3.3
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/LICENSE +21 -0
- package/dist/index.d.ts +403 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +3088 -0
- package/dist/index.js.map +1 -0
- package/dist/latex-prose.d.ts +26 -0
- package/dist/latex-prose.d.ts.map +1 -0
- package/dist/latex-prose.js +333 -0
- package/dist/latex-prose.js.map +1 -0
- package/dist/voice-recorder.d.ts +19 -0
- package/dist/voice-recorder.d.ts.map +1 -0
- package/dist/voice-recorder.js +121 -0
- package/dist/voice-recorder.js.map +1 -0
- package/package.json +43 -8
- package/README.md +0 -3
package/dist/index.js
ADDED
|
@@ -0,0 +1,3088 @@
|
|
|
1
|
+
import { createContext, createElement, Fragment, memo, useContext, useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
|
|
2
|
+
import { AssistantRuntimeProvider, ComposerPrimitive, MessagePartPrimitive, MessagePrimitive, ThreadPrimitive, useAssistantState, useExternalStoreRuntime } from "@assistant-ui/react";
|
|
3
|
+
import { agentFilePlaceholder, raybaseAgentDataPartTypes, raybaseAgentTurnError } from "@raybase/core";
|
|
4
|
+
import { History, LifeBuoy, MessageCircle, Mic, Pin, Plus, RotateCw, Search, Send, Square, Trash2, X } from "lucide-react";
|
|
5
|
+
import ReactMarkdown from "react-markdown";
|
|
6
|
+
import remarkGfm from "remark-gfm";
|
|
7
|
+
import { remarkRaybaseLatexProse } from "./latex-prose.js";
|
|
8
|
+
import { createVoiceRecorder, defaultVoiceNoteMaxSeconds, isVoiceRecordingSupported } from "./voice-recorder.js";
|
|
9
|
+
/** True only after the server has committed an assistant message to this turn. */
|
|
10
|
+
export function raybaseAgentHasCommittedResponse(snapshot) {
|
|
11
|
+
const activeRun = [...snapshot.runs].reverse().find((run) => run.status === "running");
|
|
12
|
+
return snapshot.isRunning
|
|
13
|
+
&& activeRun !== undefined
|
|
14
|
+
&& snapshot.committedResponseRunId === activeRun.id;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* A Raybase agent request that did not land. `status` is the HTTP status the
|
|
18
|
+
* server answered with, or 0 when the request never reached a response at all
|
|
19
|
+
* (offline, aborted transport, a fetch that threw).
|
|
20
|
+
*/
|
|
21
|
+
export class RaybaseAgentRequestError extends Error {
|
|
22
|
+
status;
|
|
23
|
+
constructor(message, status, options) {
|
|
24
|
+
super(message, options);
|
|
25
|
+
this.status = status;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
export function createRaybaseAgentChat(options) {
|
|
29
|
+
const listeners = new Set();
|
|
30
|
+
const fetcher = options.fetch ?? fetch;
|
|
31
|
+
const agentBasePath = options.agentBasePath ?? "/api/raybase/agents";
|
|
32
|
+
const initialConversationTitle = options.initialConversationTitle ?? options.title;
|
|
33
|
+
const persistConversation = options.persistConversation !== false;
|
|
34
|
+
const storageKey = options.storageKey ?? defaultConversationStorageKey(options);
|
|
35
|
+
let conversationId = options.conversationId ?? (persistConversation ? readStoredConversationId(storageKey) : null);
|
|
36
|
+
let basePath = null;
|
|
37
|
+
let conversationToken = null;
|
|
38
|
+
let webSocketToken = null;
|
|
39
|
+
let conversationKind = null;
|
|
40
|
+
let currentUserId = null;
|
|
41
|
+
let roomSocket = null;
|
|
42
|
+
let roomReconnectTimer = null;
|
|
43
|
+
let socketOpening = null;
|
|
44
|
+
let roomReconnectBlocked = false;
|
|
45
|
+
let roomLocalStreamingMessageId = null;
|
|
46
|
+
let lastSeq = 0;
|
|
47
|
+
let subscribeRef = 0;
|
|
48
|
+
const deltaMessageIds = new Map();
|
|
49
|
+
const pendingMessageIds = new Map();
|
|
50
|
+
const requests = new Map();
|
|
51
|
+
const outputMessageIdsByRun = new Map();
|
|
52
|
+
const outputOwnedRunIds = new Set();
|
|
53
|
+
let conversationGeneration = 0;
|
|
54
|
+
let conversationBootstrap = null;
|
|
55
|
+
let voicePipeline = null;
|
|
56
|
+
let closed = false;
|
|
57
|
+
/** Opaque server cursor for the next-older archived page; null = fully paged. */
|
|
58
|
+
let olderCursor = null;
|
|
59
|
+
const roomMemberNames = new Map();
|
|
60
|
+
const uploadedVoiceNotes = new WeakMap();
|
|
61
|
+
let snapshot = {
|
|
62
|
+
agentName: options.agentName,
|
|
63
|
+
conversationId,
|
|
64
|
+
conversations: [],
|
|
65
|
+
messages: [],
|
|
66
|
+
runs: [],
|
|
67
|
+
currentUserId: null,
|
|
68
|
+
presence: [],
|
|
69
|
+
roomMembers: [],
|
|
70
|
+
voiceNotes: disabledVoiceNotesCapability(),
|
|
71
|
+
attachments: disabledAttachmentsCapability(),
|
|
72
|
+
voiceNotePending: false,
|
|
73
|
+
status: "idle",
|
|
74
|
+
isLoading: false,
|
|
75
|
+
isRunning: false,
|
|
76
|
+
committedResponseRunId: null,
|
|
77
|
+
hasLoaded: false,
|
|
78
|
+
error: null,
|
|
79
|
+
hasOlder: false,
|
|
80
|
+
loadingOlder: false,
|
|
81
|
+
markers: [],
|
|
82
|
+
olderError: null
|
|
83
|
+
};
|
|
84
|
+
const emit = () => {
|
|
85
|
+
for (const listener of listeners)
|
|
86
|
+
listener();
|
|
87
|
+
};
|
|
88
|
+
const setSnapshot = (update) => {
|
|
89
|
+
snapshot = { ...snapshot, ...update };
|
|
90
|
+
emit();
|
|
91
|
+
return snapshot;
|
|
92
|
+
};
|
|
93
|
+
const isLiveRunStatus = (status) => status === "queued" || status === "running";
|
|
94
|
+
const isTerminalRunStatus = (status) => !isLiveRunStatus(status);
|
|
95
|
+
const mergeRunStatus = (current, incoming) => {
|
|
96
|
+
if (!current)
|
|
97
|
+
return incoming;
|
|
98
|
+
if (isTerminalRunStatus(current))
|
|
99
|
+
return current;
|
|
100
|
+
if (isTerminalRunStatus(incoming))
|
|
101
|
+
return incoming;
|
|
102
|
+
if (current === "running" && incoming === "queued")
|
|
103
|
+
return current;
|
|
104
|
+
return incoming;
|
|
105
|
+
};
|
|
106
|
+
const projectRun = (runId, status, replaceRunId) => {
|
|
107
|
+
const existing = snapshot.runs.find((run) => run.id === runId);
|
|
108
|
+
const mergedStatus = mergeRunStatus(existing?.status, status);
|
|
109
|
+
const insertionCandidates = [
|
|
110
|
+
snapshot.runs.findIndex((run) => run.id === replaceRunId),
|
|
111
|
+
snapshot.runs.findIndex((run) => run.id === runId)
|
|
112
|
+
].filter((index) => index >= 0);
|
|
113
|
+
const insertionIndex = insertionCandidates.length
|
|
114
|
+
? Math.min(...insertionCandidates)
|
|
115
|
+
: snapshot.runs.length;
|
|
116
|
+
const runs = snapshot.runs.filter((run) => run.id !== runId && (!replaceRunId || run.id !== replaceRunId));
|
|
117
|
+
runs.splice(Math.min(insertionIndex, runs.length), 0, { id: runId, status: mergedStatus });
|
|
118
|
+
return runs;
|
|
119
|
+
};
|
|
120
|
+
const publishActivity = (update = {}) => {
|
|
121
|
+
const next = { ...snapshot, ...update };
|
|
122
|
+
const isRunning = requests.size > 0 || next.runs.some((run) => isLiveRunStatus(run.status));
|
|
123
|
+
const status = next.isLoading
|
|
124
|
+
? "loading"
|
|
125
|
+
: isRunning
|
|
126
|
+
? "running"
|
|
127
|
+
: next.error
|
|
128
|
+
? "error"
|
|
129
|
+
: "ready";
|
|
130
|
+
return setSnapshot({ ...update, status, isRunning });
|
|
131
|
+
};
|
|
132
|
+
const isCurrentRequest = (record) => !closed
|
|
133
|
+
&& record.generation === conversationGeneration
|
|
134
|
+
&& requests.get(record.requestKey) === record;
|
|
135
|
+
const registerRequest = (input) => {
|
|
136
|
+
const record = {
|
|
137
|
+
requestKey: input.requestKey,
|
|
138
|
+
clientRunId: input.clientRunId,
|
|
139
|
+
controller: new AbortController(),
|
|
140
|
+
generation: conversationGeneration,
|
|
141
|
+
...(input.optimisticMessageId ? { optimisticMessageId: input.optimisticMessageId } : {}),
|
|
142
|
+
accepted: false,
|
|
143
|
+
disposition: null,
|
|
144
|
+
serverRunId: null,
|
|
145
|
+
deadlineRunId: null,
|
|
146
|
+
runningDeadline: null
|
|
147
|
+
};
|
|
148
|
+
requests.set(record.requestKey, record);
|
|
149
|
+
if (record.optimisticMessageId)
|
|
150
|
+
pendingMessageIds.set(record.requestKey, record.optimisticMessageId);
|
|
151
|
+
return record;
|
|
152
|
+
};
|
|
153
|
+
const removeRequest = (record) => {
|
|
154
|
+
if (requests.get(record.requestKey) !== record)
|
|
155
|
+
return false;
|
|
156
|
+
requests.delete(record.requestKey);
|
|
157
|
+
pendingMessageIds.delete(record.requestKey);
|
|
158
|
+
return true;
|
|
159
|
+
};
|
|
160
|
+
const invalidateAsyncWork = () => {
|
|
161
|
+
conversationGeneration += 1;
|
|
162
|
+
conversationBootstrap = null;
|
|
163
|
+
for (const record of requests.values())
|
|
164
|
+
record.controller.abort();
|
|
165
|
+
requests.clear();
|
|
166
|
+
pendingMessageIds.clear();
|
|
167
|
+
if (voicePipeline)
|
|
168
|
+
voicePipeline.controller.abort();
|
|
169
|
+
voicePipeline = null;
|
|
170
|
+
outputOwnedRunIds.clear();
|
|
171
|
+
};
|
|
172
|
+
const bindRequestToRun = (record, disposition, runId, status) => {
|
|
173
|
+
if (record.serverRunId !== runId) {
|
|
174
|
+
record.serverRunId = runId;
|
|
175
|
+
record.deadlineRunId = null;
|
|
176
|
+
record.runningDeadline = null;
|
|
177
|
+
}
|
|
178
|
+
record.disposition = disposition;
|
|
179
|
+
if (disposition === "run")
|
|
180
|
+
outputOwnedRunIds.add(runId);
|
|
181
|
+
return projectRun(runId, status, record.clientRunId);
|
|
182
|
+
};
|
|
183
|
+
const settleRequest = (record) => {
|
|
184
|
+
if (removeRequest(record) && !record.controller.signal.aborted)
|
|
185
|
+
record.controller.abort();
|
|
186
|
+
};
|
|
187
|
+
const settleRequestsForRun = (runId) => {
|
|
188
|
+
for (const record of [...requests.values()]) {
|
|
189
|
+
if (record.serverRunId === runId)
|
|
190
|
+
settleRequest(record);
|
|
191
|
+
}
|
|
192
|
+
};
|
|
193
|
+
const rejectRequest = (record, error, input = { accepted: record.accepted }) => {
|
|
194
|
+
if (!isCurrentRequest(record))
|
|
195
|
+
return snapshot;
|
|
196
|
+
const cancelled = input.cancelled === true;
|
|
197
|
+
const siblingOnRun = record.serverRunId
|
|
198
|
+
? [...requests.values()].some((candidate) => candidate !== record && candidate.serverRunId === record.serverRunId)
|
|
199
|
+
: false;
|
|
200
|
+
settleRequest(record);
|
|
201
|
+
let runs = snapshot.runs;
|
|
202
|
+
if (!input.accepted) {
|
|
203
|
+
runs = runs.filter((run) => run.id !== record.clientRunId);
|
|
204
|
+
}
|
|
205
|
+
else if (record.serverRunId && !siblingOnRun) {
|
|
206
|
+
runs = projectRun(record.serverRunId, cancelled ? "cancelled" : "failed", record.clientRunId);
|
|
207
|
+
}
|
|
208
|
+
else if (!record.serverRunId) {
|
|
209
|
+
runs = projectRun(record.clientRunId, cancelled ? "cancelled" : "failed");
|
|
210
|
+
}
|
|
211
|
+
const settledRunId = record.serverRunId && !siblingOnRun
|
|
212
|
+
? record.serverRunId
|
|
213
|
+
: !record.serverRunId
|
|
214
|
+
? record.clientRunId
|
|
215
|
+
: null;
|
|
216
|
+
return publishActivity({
|
|
217
|
+
messages: !input.accepted && record.optimisticMessageId
|
|
218
|
+
? snapshot.messages.filter((message) => message.id !== record.optimisticMessageId)
|
|
219
|
+
: snapshot.messages,
|
|
220
|
+
runs,
|
|
221
|
+
isLoading: false,
|
|
222
|
+
...(settledRunId && snapshot.committedResponseRunId === settledRunId ? { committedResponseRunId: null } : {}),
|
|
223
|
+
hasLoaded: true,
|
|
224
|
+
...(cancelled ? {} : { error })
|
|
225
|
+
});
|
|
226
|
+
};
|
|
227
|
+
const rememberConversation = () => {
|
|
228
|
+
if (!persistConversation || !conversationId)
|
|
229
|
+
return;
|
|
230
|
+
writeStoredConversationId(storageKey, conversationId, "session");
|
|
231
|
+
writeStoredConversationId(storageKey, conversationId, "local");
|
|
232
|
+
};
|
|
233
|
+
const forgetConversation = () => {
|
|
234
|
+
if (!persistConversation)
|
|
235
|
+
return;
|
|
236
|
+
removeStoredConversationId(storageKey, "session");
|
|
237
|
+
removeStoredConversationId(storageKey, "local");
|
|
238
|
+
};
|
|
239
|
+
const closeRoomSocket = () => {
|
|
240
|
+
if (roomReconnectTimer) {
|
|
241
|
+
clearTimeout(roomReconnectTimer);
|
|
242
|
+
roomReconnectTimer = null;
|
|
243
|
+
}
|
|
244
|
+
const socket = roomSocket;
|
|
245
|
+
roomSocket = null;
|
|
246
|
+
if (!socket)
|
|
247
|
+
return;
|
|
248
|
+
socket.onclose = null;
|
|
249
|
+
socket.close(1000, "Raybase Agent conversation changed");
|
|
250
|
+
};
|
|
251
|
+
const resetRoomState = (publish = true) => {
|
|
252
|
+
invalidateAsyncWork();
|
|
253
|
+
closeRoomSocket();
|
|
254
|
+
webSocketToken = null;
|
|
255
|
+
conversationKind = null;
|
|
256
|
+
currentUserId = null;
|
|
257
|
+
roomReconnectBlocked = false;
|
|
258
|
+
roomLocalStreamingMessageId = null;
|
|
259
|
+
lastSeq = 0;
|
|
260
|
+
olderCursor = null;
|
|
261
|
+
deltaMessageIds.clear();
|
|
262
|
+
outputMessageIdsByRun.clear();
|
|
263
|
+
outputOwnedRunIds.clear();
|
|
264
|
+
roomMemberNames.clear();
|
|
265
|
+
if (publish) {
|
|
266
|
+
setSnapshot({
|
|
267
|
+
currentUserId: null,
|
|
268
|
+
presence: [],
|
|
269
|
+
roomMembers: [],
|
|
270
|
+
voiceNotePending: false,
|
|
271
|
+
committedResponseRunId: null,
|
|
272
|
+
hasOlder: false,
|
|
273
|
+
loadingOlder: false,
|
|
274
|
+
markers: [],
|
|
275
|
+
olderError: null
|
|
276
|
+
});
|
|
277
|
+
}
|
|
278
|
+
};
|
|
279
|
+
async function ensureConversation() {
|
|
280
|
+
if (conversationId && basePath && conversationToken)
|
|
281
|
+
return;
|
|
282
|
+
if (conversationBootstrap)
|
|
283
|
+
return conversationBootstrap;
|
|
284
|
+
const generation = conversationGeneration;
|
|
285
|
+
publishActivity({ isLoading: requests.size === 0, error: null });
|
|
286
|
+
conversationBootstrap = (async () => {
|
|
287
|
+
const body = await bootstrapConversation(conversationId ?? undefined);
|
|
288
|
+
if (closed || generation !== conversationGeneration) {
|
|
289
|
+
throw new DOMException("Conversation changed", "AbortError");
|
|
290
|
+
}
|
|
291
|
+
conversationId = body.conversationId;
|
|
292
|
+
basePath = body.basePath;
|
|
293
|
+
conversationToken = body.conversationToken;
|
|
294
|
+
webSocketToken = null;
|
|
295
|
+
conversationKind = body.kind ?? null;
|
|
296
|
+
currentUserId = body.userId ?? null;
|
|
297
|
+
roomReconnectBlocked = false;
|
|
298
|
+
rememberConversation();
|
|
299
|
+
// Publish the resolved id but stay in the caller's in-flight state: an
|
|
300
|
+
// open is not ready until its messages have loaded (the caller settles
|
|
301
|
+
// the snapshot), and a submit/retry stays running.
|
|
302
|
+
publishActivity({
|
|
303
|
+
conversationId,
|
|
304
|
+
currentUserId,
|
|
305
|
+
voiceNotes: normalizeVoiceNotesCapability(body.voiceNotes),
|
|
306
|
+
attachments: normalizeAttachmentsCapability(body.attachments, body.voiceNotes)
|
|
307
|
+
});
|
|
308
|
+
if (conversationKind === "room")
|
|
309
|
+
await refreshRoomMembers().catch(() => { });
|
|
310
|
+
})().finally(() => {
|
|
311
|
+
if (generation === conversationGeneration)
|
|
312
|
+
conversationBootstrap = null;
|
|
313
|
+
});
|
|
314
|
+
return conversationBootstrap;
|
|
315
|
+
}
|
|
316
|
+
async function bootstrapConversation(id) {
|
|
317
|
+
const response = await fetcher(urlFor(options.baseUrl, `${agentBasePath}/${encodeURIComponent(options.agentName)}/conversations`), {
|
|
318
|
+
method: "POST",
|
|
319
|
+
credentials: "same-origin",
|
|
320
|
+
headers: raybaseAgentHeaders(options),
|
|
321
|
+
body: JSON.stringify({
|
|
322
|
+
conversationId: id,
|
|
323
|
+
// Resumes omit title entirely: absent means "keep the stored title".
|
|
324
|
+
...(id === undefined && initialConversationTitle ? { title: initialConversationTitle } : {}),
|
|
325
|
+
route: options.route,
|
|
326
|
+
surface: options.surface
|
|
327
|
+
})
|
|
328
|
+
});
|
|
329
|
+
const body = await readAgentResponseBody(response);
|
|
330
|
+
if (!response.ok || !body.conversationId || !body.basePath || !body.conversationToken) {
|
|
331
|
+
throw new RaybaseAgentRequestError(body.error ?? `Raybase agent bootstrap failed with ${response.status}`, response.status);
|
|
332
|
+
}
|
|
333
|
+
return body;
|
|
334
|
+
}
|
|
335
|
+
async function openRoomSocket() {
|
|
336
|
+
if (closed || roomReconnectBlocked || !conversationId || !basePath || !conversationToken || roomSocket)
|
|
337
|
+
return;
|
|
338
|
+
if (socketOpening)
|
|
339
|
+
return socketOpening;
|
|
340
|
+
socketOpening = (async () => {
|
|
341
|
+
const WebSocketConstructor = options.webSocket ?? globalThis.WebSocket;
|
|
342
|
+
if (typeof WebSocketConstructor !== "function")
|
|
343
|
+
return;
|
|
344
|
+
const minted = await mintSubscriptionCredentials();
|
|
345
|
+
if (closed || roomSocket || !basePath)
|
|
346
|
+
return;
|
|
347
|
+
webSocketToken = minted.webSocketToken;
|
|
348
|
+
if (minted.conversationToken)
|
|
349
|
+
conversationToken = minted.conversationToken;
|
|
350
|
+
const socket = new WebSocketConstructor(roomWebSocketUrl(options.baseUrl, basePath, webSocketToken));
|
|
351
|
+
roomSocket = socket;
|
|
352
|
+
socket.onopen = () => {
|
|
353
|
+
if (roomSocket === socket)
|
|
354
|
+
subscribeRoomSocket(socket);
|
|
355
|
+
};
|
|
356
|
+
socket.onmessage = (event) => {
|
|
357
|
+
if (roomSocket !== socket || typeof event.data !== "string")
|
|
358
|
+
return;
|
|
359
|
+
handleRoomSocketMessage(event.data);
|
|
360
|
+
};
|
|
361
|
+
socket.onclose = (event) => {
|
|
362
|
+
if (roomSocket === socket)
|
|
363
|
+
roomSocket = null;
|
|
364
|
+
webSocketToken = null;
|
|
365
|
+
if (event.code === 1008) {
|
|
366
|
+
roomReconnectBlocked = true;
|
|
367
|
+
return;
|
|
368
|
+
}
|
|
369
|
+
if (closed || roomReconnectBlocked || !conversationId)
|
|
370
|
+
return;
|
|
371
|
+
roomReconnectTimer = setTimeout(() => {
|
|
372
|
+
roomReconnectTimer = null;
|
|
373
|
+
void refreshRoomSocketCredentials();
|
|
374
|
+
}, 250);
|
|
375
|
+
};
|
|
376
|
+
if (socket.readyState === WebSocketConstructor.OPEN)
|
|
377
|
+
subscribeRoomSocket(socket);
|
|
378
|
+
})().finally(() => {
|
|
379
|
+
socketOpening = null;
|
|
380
|
+
});
|
|
381
|
+
return socketOpening;
|
|
382
|
+
}
|
|
383
|
+
function subscribeRoomSocket(socket = roomSocket) {
|
|
384
|
+
if (!socket || socket.readyState !== 1)
|
|
385
|
+
return;
|
|
386
|
+
socket.send(JSON.stringify({
|
|
387
|
+
v: 1,
|
|
388
|
+
ref: `agent-ui-${++subscribeRef}`,
|
|
389
|
+
type: "subscribe",
|
|
390
|
+
lastSeq
|
|
391
|
+
}));
|
|
392
|
+
}
|
|
393
|
+
async function mintSubscriptionCredentials(retry = true) {
|
|
394
|
+
const response = await fetcher(urlFor(options.baseUrl, `${agentBasePath}/${encodeURIComponent(options.agentName)}/conversations/${encodeURIComponent(conversationId)}/ws-token`), {
|
|
395
|
+
method: "POST",
|
|
396
|
+
credentials: "same-origin",
|
|
397
|
+
headers: {
|
|
398
|
+
...raybaseAgentHeaders(options),
|
|
399
|
+
authorization: `Bearer ${conversationToken}`
|
|
400
|
+
}
|
|
401
|
+
});
|
|
402
|
+
const body = await readResponseBody(response);
|
|
403
|
+
if (!response.ok || !body.webSocketToken) {
|
|
404
|
+
if (retry && response.status === 401 && conversationId) {
|
|
405
|
+
const refreshed = await bootstrapConversation(conversationId);
|
|
406
|
+
basePath = refreshed.basePath;
|
|
407
|
+
conversationToken = refreshed.conversationToken;
|
|
408
|
+
currentUserId = refreshed.userId ?? null;
|
|
409
|
+
setSnapshot({ currentUserId });
|
|
410
|
+
return mintSubscriptionCredentials(false);
|
|
411
|
+
}
|
|
412
|
+
throw new RaybaseAgentRequestError(body.error ?? `Raybase agent socket-token mint failed with ${response.status}`, response.status);
|
|
413
|
+
}
|
|
414
|
+
return { webSocketToken: body.webSocketToken, conversationToken: body.conversationToken };
|
|
415
|
+
}
|
|
416
|
+
async function refreshRoomSocketCredentials() {
|
|
417
|
+
if (closed || roomReconnectBlocked || !conversationId)
|
|
418
|
+
return;
|
|
419
|
+
try {
|
|
420
|
+
await openRoomSocket();
|
|
421
|
+
}
|
|
422
|
+
catch (error) {
|
|
423
|
+
if (error instanceof RaybaseAgentRequestError && (error.status === 403 || error.status === 404 || error.status === 410)) {
|
|
424
|
+
roomReconnectBlocked = true;
|
|
425
|
+
return;
|
|
426
|
+
}
|
|
427
|
+
if (!closed && !roomReconnectBlocked) {
|
|
428
|
+
roomReconnectTimer = setTimeout(() => {
|
|
429
|
+
roomReconnectTimer = null;
|
|
430
|
+
void refreshRoomSocketCredentials();
|
|
431
|
+
}, 1_000);
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
function handleRoomSocketMessage(data) {
|
|
436
|
+
let frame;
|
|
437
|
+
try {
|
|
438
|
+
const parsed = JSON.parse(data);
|
|
439
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
|
|
440
|
+
return;
|
|
441
|
+
frame = parsed;
|
|
442
|
+
}
|
|
443
|
+
catch {
|
|
444
|
+
return;
|
|
445
|
+
}
|
|
446
|
+
if (frame.type === "presence") {
|
|
447
|
+
const members = normalizeRoomPresenceMembers(frame.members);
|
|
448
|
+
const event = frame.event;
|
|
449
|
+
const byConnection = new Map(snapshot.presence.map((member) => [member.connectionId, member]));
|
|
450
|
+
if (event === "sync")
|
|
451
|
+
byConnection.clear();
|
|
452
|
+
for (const member of members) {
|
|
453
|
+
if (event === "leave")
|
|
454
|
+
byConnection.delete(member.connectionId);
|
|
455
|
+
else
|
|
456
|
+
byConnection.set(member.connectionId, member);
|
|
457
|
+
if (member.name)
|
|
458
|
+
roomMemberNames.set(member.userId, member.name);
|
|
459
|
+
}
|
|
460
|
+
setSnapshot({ presence: [...byConnection.values()] });
|
|
461
|
+
return;
|
|
462
|
+
}
|
|
463
|
+
if (frame.type === "subscribed") {
|
|
464
|
+
const cursor = Number(frame.lastSeq);
|
|
465
|
+
if (Number.isInteger(cursor) && cursor >= lastSeq)
|
|
466
|
+
lastSeq = cursor;
|
|
467
|
+
adoptActiveRuns(frame.activeRuns);
|
|
468
|
+
return;
|
|
469
|
+
}
|
|
470
|
+
if (frame.type === "resync") {
|
|
471
|
+
void resyncConversationSnapshot();
|
|
472
|
+
return;
|
|
473
|
+
}
|
|
474
|
+
if (frame.type === "delta" && typeof frame.runId === "string" && typeof frame.delta === "string") {
|
|
475
|
+
applyAgentDelta(frame.runId, frame.delta);
|
|
476
|
+
return;
|
|
477
|
+
}
|
|
478
|
+
if (frame.type === "event") {
|
|
479
|
+
const seq = Number(frame.seq);
|
|
480
|
+
if (!Number.isInteger(seq) || seq <= lastSeq)
|
|
481
|
+
return;
|
|
482
|
+
if (seq !== lastSeq + 1) {
|
|
483
|
+
subscribeRoomSocket();
|
|
484
|
+
return;
|
|
485
|
+
}
|
|
486
|
+
lastSeq = seq;
|
|
487
|
+
applyConversationEvent(frame.event && typeof frame.event === "object" && !Array.isArray(frame.event)
|
|
488
|
+
? frame.event
|
|
489
|
+
: {}, typeof frame.createdAt === "string" ? frame.createdAt : new Date().toISOString());
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
async function refreshRoomMembers() {
|
|
493
|
+
const requestedConversationId = conversationId;
|
|
494
|
+
if (conversationKind !== "room" || !requestedConversationId || !conversationToken) {
|
|
495
|
+
if (conversationKind !== "room")
|
|
496
|
+
setSnapshot({ roomMembers: [] });
|
|
497
|
+
return;
|
|
498
|
+
}
|
|
499
|
+
const response = await fetcher(urlFor(options.baseUrl, `${agentBasePath}/${encodeURIComponent(options.agentName)}/conversations/${encodeURIComponent(requestedConversationId)}/members`), {
|
|
500
|
+
method: "GET",
|
|
501
|
+
credentials: "same-origin",
|
|
502
|
+
headers: {
|
|
503
|
+
...raybaseAgentHeaders(options),
|
|
504
|
+
authorization: `Bearer ${conversationToken}`
|
|
505
|
+
}
|
|
506
|
+
});
|
|
507
|
+
const body = await readResponseBody(response);
|
|
508
|
+
if (!response.ok) {
|
|
509
|
+
throw new RaybaseAgentRequestError(body.error ?? `Raybase agent room-member sync failed with ${response.status}`, response.status);
|
|
510
|
+
}
|
|
511
|
+
if (conversationId !== requestedConversationId)
|
|
512
|
+
return;
|
|
513
|
+
const roomMembers = normalizeRoomMembers(body.members);
|
|
514
|
+
for (const member of roomMembers)
|
|
515
|
+
roomMemberNames.set(member.userId, member.name);
|
|
516
|
+
setSnapshot({ roomMembers });
|
|
517
|
+
}
|
|
518
|
+
async function resyncConversationSnapshot() {
|
|
519
|
+
const generation = conversationGeneration;
|
|
520
|
+
const requestedConversationId = conversationId;
|
|
521
|
+
try {
|
|
522
|
+
if (conversationKind === "room")
|
|
523
|
+
await refreshRoomMembers().catch(() => { });
|
|
524
|
+
const loaded = await loadConversationMessages();
|
|
525
|
+
if (closed || generation !== conversationGeneration || requestedConversationId !== conversationId)
|
|
526
|
+
return;
|
|
527
|
+
lastSeq = loaded.seq;
|
|
528
|
+
deltaMessageIds.clear();
|
|
529
|
+
roomLocalStreamingMessageId = null;
|
|
530
|
+
outputMessageIdsByRun.clear();
|
|
531
|
+
for (const [messageId, runId] of loaded.messageRunIds) {
|
|
532
|
+
outputMessageIdsByRun.set(runId, messageId);
|
|
533
|
+
}
|
|
534
|
+
// A resync rebuilds from the fresh hot snapshot: previously paged-in
|
|
535
|
+
// older messages and markers are dropped and can be re-paged.
|
|
536
|
+
olderCursor = loaded.nextCursor;
|
|
537
|
+
setSnapshot({
|
|
538
|
+
messages: loaded.messages,
|
|
539
|
+
hasLoaded: true,
|
|
540
|
+
hasOlder: loaded.hasOlder,
|
|
541
|
+
loadingOlder: false,
|
|
542
|
+
markers: [],
|
|
543
|
+
olderError: null
|
|
544
|
+
});
|
|
545
|
+
subscribeRoomSocket();
|
|
546
|
+
}
|
|
547
|
+
catch (error) {
|
|
548
|
+
if (closed || generation !== conversationGeneration || requestedConversationId !== conversationId)
|
|
549
|
+
return;
|
|
550
|
+
publishActivity({ isLoading: false, error: asError(error) });
|
|
551
|
+
}
|
|
552
|
+
}
|
|
553
|
+
function applyAgentDelta(runId, delta) {
|
|
554
|
+
if (!delta)
|
|
555
|
+
return;
|
|
556
|
+
let messageId = deltaMessageIds.get(runId);
|
|
557
|
+
if (!messageId) {
|
|
558
|
+
messageId = randomClientId("agent_delta");
|
|
559
|
+
deltaMessageIds.set(runId, messageId);
|
|
560
|
+
roomLocalStreamingMessageId = messageId;
|
|
561
|
+
const message = messageSnapshot("assistant", [{ type: "text", text: delta }]);
|
|
562
|
+
message.id = messageId;
|
|
563
|
+
setSnapshot({ messages: [...snapshot.messages, message] });
|
|
564
|
+
return;
|
|
565
|
+
}
|
|
566
|
+
setSnapshot({
|
|
567
|
+
messages: snapshot.messages.map((message) => message.id === messageId
|
|
568
|
+
? {
|
|
569
|
+
...message,
|
|
570
|
+
parts: [{ type: "text", text: `${message.parts.find((part) => part.type === "text")?.text ?? ""}${delta}` }]
|
|
571
|
+
}
|
|
572
|
+
: message)
|
|
573
|
+
});
|
|
574
|
+
}
|
|
575
|
+
function applyConversationEvent(event, createdAt) {
|
|
576
|
+
if (event.type === "membership") {
|
|
577
|
+
void refreshRoomMembers().catch(() => { });
|
|
578
|
+
return;
|
|
579
|
+
}
|
|
580
|
+
if (event.type === "conversation.rewound") {
|
|
581
|
+
const lastMessageId = typeof event.lastMessageId === "string" ? event.lastMessageId : null;
|
|
582
|
+
const retainedIndex = lastMessageId
|
|
583
|
+
? snapshot.messages.findIndex((message) => message.id === lastMessageId)
|
|
584
|
+
: -1;
|
|
585
|
+
deltaMessageIds.clear();
|
|
586
|
+
invalidateAsyncWork();
|
|
587
|
+
outputMessageIdsByRun.clear();
|
|
588
|
+
roomLocalStreamingMessageId = null;
|
|
589
|
+
setSnapshot({
|
|
590
|
+
messages: lastMessageId && retainedIndex >= 0
|
|
591
|
+
? snapshot.messages.slice(0, retainedIndex + 1)
|
|
592
|
+
: [],
|
|
593
|
+
runs: [],
|
|
594
|
+
status: "ready",
|
|
595
|
+
isLoading: false,
|
|
596
|
+
isRunning: false,
|
|
597
|
+
voiceNotePending: false,
|
|
598
|
+
committedResponseRunId: null,
|
|
599
|
+
hasLoaded: true,
|
|
600
|
+
error: null
|
|
601
|
+
});
|
|
602
|
+
if (lastMessageId && retainedIndex < 0)
|
|
603
|
+
void resyncConversationSnapshot();
|
|
604
|
+
return;
|
|
605
|
+
}
|
|
606
|
+
if (event.type === "message" && event.message && typeof event.message === "object" && !Array.isArray(event.message)) {
|
|
607
|
+
const incoming = normalizeSnapshotMessages([{ ...event.message, createdAt }], roomMemberNames)[0];
|
|
608
|
+
if (!incoming)
|
|
609
|
+
return;
|
|
610
|
+
let messages = snapshot.messages.filter((message) => message.id !== incoming.id);
|
|
611
|
+
if (incoming.role === "assistant") {
|
|
612
|
+
const ephemeralIds = new Set(deltaMessageIds.values());
|
|
613
|
+
messages = messages.filter((message) => !ephemeralIds.has(message.id));
|
|
614
|
+
deltaMessageIds.clear();
|
|
615
|
+
roomLocalStreamingMessageId = null;
|
|
616
|
+
notifyDataChangedParts(options, conversationId, incoming.parts, new Set());
|
|
617
|
+
applyConversationTitleParts(incoming.parts);
|
|
618
|
+
}
|
|
619
|
+
else {
|
|
620
|
+
const matchingPending = [...pendingMessageIds.values()].find((id) => {
|
|
621
|
+
const pending = messages.find((message) => message.id === id);
|
|
622
|
+
return pending && agentMessageText(pending) === agentMessageText(incoming);
|
|
623
|
+
});
|
|
624
|
+
if (matchingPending)
|
|
625
|
+
messages = messages.filter((message) => message.id !== matchingPending);
|
|
626
|
+
}
|
|
627
|
+
const runningRuns = snapshot.isRunning
|
|
628
|
+
? snapshot.runs.filter((run) => run.status === "running")
|
|
629
|
+
: [];
|
|
630
|
+
const activeRun = runningRuns.length === 1 ? runningRuns[0] : undefined;
|
|
631
|
+
if (incoming.role === "assistant" && activeRun) {
|
|
632
|
+
outputMessageIdsByRun.set(activeRun.id, incoming.id);
|
|
633
|
+
}
|
|
634
|
+
setSnapshot({
|
|
635
|
+
messages: [...messages, incoming],
|
|
636
|
+
hasLoaded: true,
|
|
637
|
+
...(incoming.role === "assistant" && activeRun
|
|
638
|
+
? { committedResponseRunId: activeRun.id }
|
|
639
|
+
: {})
|
|
640
|
+
});
|
|
641
|
+
return;
|
|
642
|
+
}
|
|
643
|
+
if ((event.type === "message.updated" || event.type === "message.removed")
|
|
644
|
+
&& event.message
|
|
645
|
+
&& typeof event.message === "object"
|
|
646
|
+
&& !Array.isArray(event.message)) {
|
|
647
|
+
const incoming = normalizeSnapshotMessages([
|
|
648
|
+
{ ...event.message, createdAt }
|
|
649
|
+
], roomMemberNames)[0];
|
|
650
|
+
if (!incoming)
|
|
651
|
+
return;
|
|
652
|
+
const original = snapshot.messages.find((message) => message.id === incoming.id);
|
|
653
|
+
setSnapshot({
|
|
654
|
+
messages: snapshot.messages.map((message) => message.id === incoming.id
|
|
655
|
+
? { ...incoming, createdAt: original?.createdAt ?? incoming.createdAt }
|
|
656
|
+
: message)
|
|
657
|
+
});
|
|
658
|
+
return;
|
|
659
|
+
}
|
|
660
|
+
if (event.type === "reaction" && typeof event.messageId === "string" && typeof event.userId === "string") {
|
|
661
|
+
setSnapshot({
|
|
662
|
+
messages: snapshot.messages.map((message) => {
|
|
663
|
+
if (message.id !== event.messageId)
|
|
664
|
+
return message;
|
|
665
|
+
const reactions = { ...message.reactions };
|
|
666
|
+
if (event.emoji === null)
|
|
667
|
+
delete reactions[event.userId];
|
|
668
|
+
else if (typeof event.emoji === "string")
|
|
669
|
+
reactions[event.userId] = event.emoji;
|
|
670
|
+
return { ...message, reactions };
|
|
671
|
+
})
|
|
672
|
+
});
|
|
673
|
+
return;
|
|
674
|
+
}
|
|
675
|
+
if (event.type === "run" && typeof event.status === "string") {
|
|
676
|
+
applyRunEvent(event);
|
|
677
|
+
return;
|
|
678
|
+
}
|
|
679
|
+
if (event.type === "title") {
|
|
680
|
+
const title = typeof event.title === "string" ? event.title : null;
|
|
681
|
+
setSnapshot({
|
|
682
|
+
conversations: snapshot.conversations.map((conversation) => conversation.conversationId === conversationId ? { ...conversation, title } : conversation)
|
|
683
|
+
});
|
|
684
|
+
}
|
|
685
|
+
}
|
|
686
|
+
/**
|
|
687
|
+
* Turns the in-flight runs reported by the subscribe handshake into the same
|
|
688
|
+
* running state a live `run.started` event produces. A subscriber that joins
|
|
689
|
+
* mid-run — the ordinary open, which subscribes from the head and so replays
|
|
690
|
+
* nothing — otherwise sees nothing at all for a turn it did not submit: the
|
|
691
|
+
* Agent's own composed turn, or another room member's.
|
|
692
|
+
*
|
|
693
|
+
* Purely additive. A local turn already in flight keeps its own run and its
|
|
694
|
+
* own reconciliation (a foreign run must never be mistaken for it), and runs
|
|
695
|
+
* adopted here are settled by their durable `run.finished` event, whatever
|
|
696
|
+
* its verdict, exactly as live-observed foreign runs are.
|
|
697
|
+
*/
|
|
698
|
+
function adoptActiveRuns(value) {
|
|
699
|
+
if (!Array.isArray(value))
|
|
700
|
+
return;
|
|
701
|
+
const adopted = value.filter((runId) => typeof runId === "string"
|
|
702
|
+
&& runId.length > 0
|
|
703
|
+
&& !snapshot.runs.some((run) => run.id === runId));
|
|
704
|
+
if (!adopted.length)
|
|
705
|
+
return;
|
|
706
|
+
if (snapshot.runs.some((run) => run.status === "queued" || run.status === "running"))
|
|
707
|
+
return;
|
|
708
|
+
setSnapshot({
|
|
709
|
+
runs: [...snapshot.runs, ...adopted.map((id) => ({ id, status: "running" }))],
|
|
710
|
+
status: "running",
|
|
711
|
+
isRunning: true,
|
|
712
|
+
committedResponseRunId: null,
|
|
713
|
+
error: null
|
|
714
|
+
});
|
|
715
|
+
}
|
|
716
|
+
function applyRunEvent(event) {
|
|
717
|
+
const runId = typeof event.runId === "string" ? event.runId : null;
|
|
718
|
+
if (event.status === "started" && runId) {
|
|
719
|
+
publishActivity({ runs: projectRun(runId, "running"), isLoading: false });
|
|
720
|
+
return;
|
|
721
|
+
}
|
|
722
|
+
if (event.status === "ignored" && typeof event.requestKey === "string") {
|
|
723
|
+
const record = requests.get(event.requestKey);
|
|
724
|
+
if (!record)
|
|
725
|
+
return;
|
|
726
|
+
settleRequest(record);
|
|
727
|
+
publishActivity({
|
|
728
|
+
runs: snapshot.runs.filter((run) => run.id !== record.clientRunId),
|
|
729
|
+
isLoading: false,
|
|
730
|
+
hasLoaded: true
|
|
731
|
+
});
|
|
732
|
+
return;
|
|
733
|
+
}
|
|
734
|
+
if (event.status !== "finished" || !runId)
|
|
735
|
+
return;
|
|
736
|
+
const verdict = event.verdict;
|
|
737
|
+
const terminal = verdict === "cancelled"
|
|
738
|
+
? "cancelled"
|
|
739
|
+
: verdict === "failed"
|
|
740
|
+
? "failed"
|
|
741
|
+
: "completed";
|
|
742
|
+
settleRun(terminal, runId, typeof event.error === "string" ? event.error : undefined);
|
|
743
|
+
}
|
|
744
|
+
function settleRun(status, runId, error) {
|
|
745
|
+
settleRequestsForRun(runId);
|
|
746
|
+
publishActivity({
|
|
747
|
+
runs: projectRun(runId, status),
|
|
748
|
+
isLoading: false,
|
|
749
|
+
...(snapshot.committedResponseRunId === runId ? { committedResponseRunId: null } : {}),
|
|
750
|
+
hasLoaded: true,
|
|
751
|
+
...(status === "failed" ? { error: new Error(error || "Raybase agent turn failed") } : {})
|
|
752
|
+
});
|
|
753
|
+
void refreshConversations().catch(() => { });
|
|
754
|
+
}
|
|
755
|
+
async function markCurrentConversationRead() {
|
|
756
|
+
if (!conversationId)
|
|
757
|
+
return snapshot;
|
|
758
|
+
try {
|
|
759
|
+
const response = await fetcher(urlFor(options.baseUrl, `${agentBasePath}/${encodeURIComponent(options.agentName)}/conversations/${encodeURIComponent(conversationId)}/read`), {
|
|
760
|
+
method: "POST",
|
|
761
|
+
credentials: "same-origin",
|
|
762
|
+
headers: raybaseAgentHeaders(options)
|
|
763
|
+
});
|
|
764
|
+
const body = await readResponseBody(response);
|
|
765
|
+
if (!response.ok || typeof body.lastReadAt !== "string") {
|
|
766
|
+
throw new RaybaseAgentRequestError(body.error ?? `Raybase agent mark-read failed with ${response.status}`, response.status);
|
|
767
|
+
}
|
|
768
|
+
return setSnapshot({
|
|
769
|
+
conversations: snapshot.conversations.map((conversation) => conversation.conversationId === conversationId ? { ...conversation, lastReadAt: body.lastReadAt ?? null } : conversation),
|
|
770
|
+
roomMembers: snapshot.roomMembers.map((member) => member.userId === currentUserId ? { ...member, lastReadAt: body.lastReadAt ?? null } : member)
|
|
771
|
+
});
|
|
772
|
+
}
|
|
773
|
+
catch {
|
|
774
|
+
return snapshot;
|
|
775
|
+
}
|
|
776
|
+
}
|
|
777
|
+
/**
|
|
778
|
+
* The transport behind `editMessage`, `removeMessage` and `setReaction`.
|
|
779
|
+
*
|
|
780
|
+
* A failure is thrown to the caller, never parked on the snapshot. A message
|
|
781
|
+
* change that did not land is the caller's to handle — an optimistic chip to
|
|
782
|
+
* take back, a small line to say beside the message — and it is emphatically
|
|
783
|
+
* not the conversation's turn failing, which is what `status: "error"` means
|
|
784
|
+
* to every panel built on this client. Rejects with
|
|
785
|
+
* `RaybaseAgentRequestError`; `status` stays wherever the run left it.
|
|
786
|
+
*
|
|
787
|
+
* Landing does not touch the run either. This used to clear `error`, which
|
|
788
|
+
* read as generosity and was the same trespass the other way round: since
|
|
789
|
+
* `status` is derived from `error` only where activity is published, a
|
|
790
|
+
* reaction to an older message wiped a failed turn's message while leaving
|
|
791
|
+
* `status: "error"` behind it — a dead composer with nothing on screen
|
|
792
|
+
* explaining why, and the "try again" affordance gone with it. Clearing a
|
|
793
|
+
* failed turn belongs to the next turn (`submit`, `retry`), not to an emoji.
|
|
794
|
+
*/
|
|
795
|
+
async function mutateCurrentMessage(messageId, input) {
|
|
796
|
+
if (!conversationId)
|
|
797
|
+
return snapshot;
|
|
798
|
+
let response;
|
|
799
|
+
try {
|
|
800
|
+
response = await fetcher(urlFor(options.baseUrl, `${agentBasePath}/${encodeURIComponent(options.agentName)}/conversations/${encodeURIComponent(conversationId)}/messages/${encodeURIComponent(messageId)}${input.suffix ?? ""}`), {
|
|
801
|
+
method: input.method,
|
|
802
|
+
credentials: "same-origin",
|
|
803
|
+
headers: {
|
|
804
|
+
...raybaseAgentHeaders(options),
|
|
805
|
+
...(input.body ? { "content-type": "application/json" } : {})
|
|
806
|
+
},
|
|
807
|
+
...(input.body ? { body: JSON.stringify(input.body) } : {})
|
|
808
|
+
});
|
|
809
|
+
}
|
|
810
|
+
catch (error) {
|
|
811
|
+
throw new RaybaseAgentRequestError(asError(error).message, 0, { cause: error });
|
|
812
|
+
}
|
|
813
|
+
const body = await readResponseBody(response);
|
|
814
|
+
if (!response.ok) {
|
|
815
|
+
throw new RaybaseAgentRequestError(body.error ?? `Raybase agent message change failed with ${response.status}`, response.status);
|
|
816
|
+
}
|
|
817
|
+
const incoming = body.message
|
|
818
|
+
? normalizeSnapshotMessages([{ ...body.message, createdAt: snapshot.messages.find((message) => message.id === messageId)?.createdAt }])[0]
|
|
819
|
+
: null;
|
|
820
|
+
return setSnapshot({
|
|
821
|
+
messages: snapshot.messages.map((message) => {
|
|
822
|
+
if (message.id !== messageId)
|
|
823
|
+
return message;
|
|
824
|
+
if (incoming)
|
|
825
|
+
return incoming;
|
|
826
|
+
if (body.reactions)
|
|
827
|
+
return { ...message, reactions: body.reactions };
|
|
828
|
+
return message;
|
|
829
|
+
})
|
|
830
|
+
});
|
|
831
|
+
}
|
|
832
|
+
async function fetchConversations(query) {
|
|
833
|
+
const params = new URLSearchParams();
|
|
834
|
+
if (query?.trim())
|
|
835
|
+
params.set("q", query.trim());
|
|
836
|
+
const suffix = params.size ? `?${params}` : "";
|
|
837
|
+
const response = await fetcher(urlFor(options.baseUrl, `${agentBasePath}/${encodeURIComponent(options.agentName)}/conversations${suffix}`), {
|
|
838
|
+
method: "GET",
|
|
839
|
+
credentials: "same-origin",
|
|
840
|
+
headers: {
|
|
841
|
+
...raybaseAgentHeaders(options),
|
|
842
|
+
"x-raybase-agent-include-archived": "true"
|
|
843
|
+
}
|
|
844
|
+
});
|
|
845
|
+
const body = await readResponseBody(response);
|
|
846
|
+
if (!response.ok) {
|
|
847
|
+
throw new RaybaseAgentRequestError(body.error ?? `Raybase agent conversations failed with ${response.status}`, response.status);
|
|
848
|
+
}
|
|
849
|
+
if (body.voiceNotes || body.attachments) {
|
|
850
|
+
setSnapshot({
|
|
851
|
+
voiceNotes: normalizeVoiceNotesCapability(body.voiceNotes),
|
|
852
|
+
attachments: normalizeAttachmentsCapability(body.attachments, body.voiceNotes)
|
|
853
|
+
});
|
|
854
|
+
}
|
|
855
|
+
return Array.isArray(body.conversations) ? body.conversations : [];
|
|
856
|
+
}
|
|
857
|
+
async function loadConversationMessages() {
|
|
858
|
+
if (!conversationId)
|
|
859
|
+
return { messages: [], messageRunIds: new Map(), seq: 0, hasOlder: false, nextCursor: null };
|
|
860
|
+
const response = await fetcher(urlFor(options.baseUrl, `${agentBasePath}/${encodeURIComponent(options.agentName)}/conversations/${encodeURIComponent(conversationId)}/messages`), {
|
|
861
|
+
method: "GET",
|
|
862
|
+
credentials: "same-origin",
|
|
863
|
+
headers: raybaseAgentHeaders(options)
|
|
864
|
+
});
|
|
865
|
+
const body = await readResponseBody(response);
|
|
866
|
+
if (!response.ok) {
|
|
867
|
+
throw new RaybaseAgentRequestError(body.error ?? `Raybase agent messages failed with ${response.status}`, response.status);
|
|
868
|
+
}
|
|
869
|
+
const messageRunIds = new Map();
|
|
870
|
+
const nextCursor = typeof body.nextCursor === "string" && body.nextCursor ? body.nextCursor : null;
|
|
871
|
+
return {
|
|
872
|
+
messages: normalizeSnapshotMessages(body.messages, roomMemberNames, messageRunIds),
|
|
873
|
+
messageRunIds,
|
|
874
|
+
seq: Number.isInteger(body.seq) && Number(body.seq) >= 0 ? Number(body.seq) : 0,
|
|
875
|
+
hasOlder: body.hasOlder === true && nextCursor !== null,
|
|
876
|
+
nextCursor
|
|
877
|
+
};
|
|
878
|
+
}
|
|
879
|
+
async function loadOlderMessages() {
|
|
880
|
+
if (closed || snapshot.loadingOlder)
|
|
881
|
+
return;
|
|
882
|
+
const cursor = olderCursor;
|
|
883
|
+
const requestedConversationId = conversationId;
|
|
884
|
+
if (!cursor || !requestedConversationId)
|
|
885
|
+
return;
|
|
886
|
+
const generation = conversationGeneration;
|
|
887
|
+
setSnapshot({ loadingOlder: true });
|
|
888
|
+
try {
|
|
889
|
+
const response = await fetcher(urlFor(options.baseUrl, `${agentBasePath}/${encodeURIComponent(options.agentName)}/conversations/${encodeURIComponent(requestedConversationId)}/messages?cursor=${encodeURIComponent(cursor)}`), {
|
|
890
|
+
method: "GET",
|
|
891
|
+
credentials: "same-origin",
|
|
892
|
+
headers: raybaseAgentHeaders(options)
|
|
893
|
+
});
|
|
894
|
+
const body = await readResponseBody(response);
|
|
895
|
+
if (!response.ok) {
|
|
896
|
+
throw new RaybaseAgentRequestError(body.error ?? `Raybase agent older messages failed with ${response.status}`, response.status);
|
|
897
|
+
}
|
|
898
|
+
if (closed || generation !== conversationGeneration || requestedConversationId !== conversationId)
|
|
899
|
+
return;
|
|
900
|
+
// The newest archived chapter can overlap the live hot tail, and a
|
|
901
|
+
// repeated page can overlap earlier paging: identity settles it here.
|
|
902
|
+
const presentIds = new Set(snapshot.messages.map((message) => message.id));
|
|
903
|
+
const older = normalizeSnapshotMessages(body.messages, roomMemberNames)
|
|
904
|
+
.filter((message) => !presentIds.has(message.id));
|
|
905
|
+
olderCursor = typeof body.nextCursor === "string" && body.nextCursor ? body.nextCursor : null;
|
|
906
|
+
setSnapshot({
|
|
907
|
+
messages: [...older, ...snapshot.messages],
|
|
908
|
+
markers: mergeChapterMarkers(snapshot.markers, normalizeChapterMarkers(body.markers)),
|
|
909
|
+
hasOlder: body.hasOlder === true && olderCursor !== null,
|
|
910
|
+
loadingOlder: false,
|
|
911
|
+
olderError: null
|
|
912
|
+
});
|
|
913
|
+
}
|
|
914
|
+
catch (error) {
|
|
915
|
+
if (closed || generation !== conversationGeneration || requestedConversationId !== conversationId)
|
|
916
|
+
return;
|
|
917
|
+
// The cursor is kept: the next loadOlder() retries the same page.
|
|
918
|
+
setSnapshot({ loadingOlder: false, olderError: asError(error).message });
|
|
919
|
+
}
|
|
920
|
+
}
|
|
921
|
+
async function refreshConversations(query) {
|
|
922
|
+
const conversations = await fetchConversations(query);
|
|
923
|
+
setSnapshot({ conversations });
|
|
924
|
+
return conversations;
|
|
925
|
+
}
|
|
926
|
+
// Applies data-raybase-conversation-title parts (emitted when the runtime
|
|
927
|
+
// auto-titles a conversation) to the conversation list, so open UIs show
|
|
928
|
+
// the new title without waiting for a refetch.
|
|
929
|
+
function applyConversationTitleParts(parts) {
|
|
930
|
+
for (const part of parts) {
|
|
931
|
+
if (part.type !== raybaseAgentDataPartTypes.conversationTitle || !part.data || typeof part.data !== "object")
|
|
932
|
+
continue;
|
|
933
|
+
const data = part.data;
|
|
934
|
+
if (typeof data.conversationId !== "string" || typeof data.title !== "string" || !data.title)
|
|
935
|
+
continue;
|
|
936
|
+
if (!snapshot.conversations.some((conversation) => conversation.conversationId === data.conversationId))
|
|
937
|
+
continue;
|
|
938
|
+
const title = data.title;
|
|
939
|
+
setSnapshot({
|
|
940
|
+
conversations: snapshot.conversations.map((conversation) => conversation.conversationId === data.conversationId ? { ...conversation, title } : conversation)
|
|
941
|
+
});
|
|
942
|
+
}
|
|
943
|
+
}
|
|
944
|
+
async function executeTurn(record, input) {
|
|
945
|
+
try {
|
|
946
|
+
await openRoomSocket().catch(() => { });
|
|
947
|
+
if (!isCurrentRequest(record))
|
|
948
|
+
return snapshot;
|
|
949
|
+
const response = await fetcher(urlFor(options.baseUrl, `${agentBasePath}/${encodeURIComponent(options.agentName)}/conversations/${encodeURIComponent(conversationId)}/messages`), {
|
|
950
|
+
method: "POST",
|
|
951
|
+
credentials: "same-origin",
|
|
952
|
+
signal: record.controller.signal,
|
|
953
|
+
headers: {
|
|
954
|
+
...raybaseAgentHeaders(options),
|
|
955
|
+
authorization: `Bearer ${conversationToken}`
|
|
956
|
+
},
|
|
957
|
+
body: JSON.stringify({
|
|
958
|
+
requestKey: record.requestKey,
|
|
959
|
+
...(input.retry
|
|
960
|
+
? { retry: true }
|
|
961
|
+
: input.parts ? { parts: input.parts } : { message: input.message })
|
|
962
|
+
})
|
|
963
|
+
});
|
|
964
|
+
const ack = await readResponseBody(response);
|
|
965
|
+
if (response.status !== 202
|
|
966
|
+
|| ack.requestKey !== record.requestKey
|
|
967
|
+
|| typeof ack.messageId !== "string"
|
|
968
|
+
|| !Number.isInteger(ack.seq)) {
|
|
969
|
+
throw new RaybaseAgentRequestError(ack.error ?? `Raybase agent send failed with ${response.status}`, response.status);
|
|
970
|
+
}
|
|
971
|
+
if (!isCurrentRequest(record))
|
|
972
|
+
return snapshot;
|
|
973
|
+
if (record.optimisticMessageId && !snapshot.messages.some((message) => message.id === ack.messageId)) {
|
|
974
|
+
setSnapshot({
|
|
975
|
+
messages: snapshot.messages.map((message) => message.id === record.optimisticMessageId ? { ...message, id: ack.messageId } : message)
|
|
976
|
+
});
|
|
977
|
+
}
|
|
978
|
+
pendingMessageIds.delete(record.requestKey);
|
|
979
|
+
record.accepted = true;
|
|
980
|
+
input.onAccepted?.();
|
|
981
|
+
rememberConversation();
|
|
982
|
+
await pollAgentRequest(record);
|
|
983
|
+
}
|
|
984
|
+
catch (error) {
|
|
985
|
+
if (!isCurrentRequest(record))
|
|
986
|
+
return snapshot;
|
|
987
|
+
const nextError = asError(error);
|
|
988
|
+
const wasCancelled = isAbortError(error);
|
|
989
|
+
rejectRequest(record, nextError, { accepted: record.accepted, cancelled: wasCancelled });
|
|
990
|
+
if (!record.accepted && input.onAcceptanceError) {
|
|
991
|
+
input.onAcceptanceError(nextError);
|
|
992
|
+
}
|
|
993
|
+
}
|
|
994
|
+
return snapshot;
|
|
995
|
+
}
|
|
996
|
+
async function pollAgentRequest(record) {
|
|
997
|
+
let delayMs = 250;
|
|
998
|
+
for (;;) {
|
|
999
|
+
if (!isCurrentRequest(record))
|
|
1000
|
+
return;
|
|
1001
|
+
const signal = record.controller.signal;
|
|
1002
|
+
if (signal.aborted)
|
|
1003
|
+
throw signal.reason ?? new DOMException("Aborted", "AbortError");
|
|
1004
|
+
const response = await fetcher(urlFor(options.baseUrl, `${agentBasePath}/${encodeURIComponent(options.agentName)}/conversations/${encodeURIComponent(conversationId)}/requests/${encodeURIComponent(record.requestKey)}`), {
|
|
1005
|
+
method: "GET",
|
|
1006
|
+
credentials: "same-origin",
|
|
1007
|
+
signal,
|
|
1008
|
+
headers: {
|
|
1009
|
+
...raybaseAgentHeaders(options),
|
|
1010
|
+
authorization: `Bearer ${conversationToken}`
|
|
1011
|
+
}
|
|
1012
|
+
});
|
|
1013
|
+
const body = await readResponseBody(response);
|
|
1014
|
+
if (!response.ok) {
|
|
1015
|
+
throw new RaybaseAgentRequestError(body.error ?? `Raybase agent status failed with ${response.status}`, response.status);
|
|
1016
|
+
}
|
|
1017
|
+
if (!isCurrentRequest(record))
|
|
1018
|
+
return;
|
|
1019
|
+
const run = body.run;
|
|
1020
|
+
if (!run) {
|
|
1021
|
+
if (body.disposition === "ignored") {
|
|
1022
|
+
record.disposition = "ignored";
|
|
1023
|
+
settleRequest(record);
|
|
1024
|
+
publishActivity({
|
|
1025
|
+
runs: snapshot.runs.filter((candidate) => candidate.id !== record.clientRunId),
|
|
1026
|
+
isLoading: false,
|
|
1027
|
+
hasLoaded: true
|
|
1028
|
+
});
|
|
1029
|
+
return;
|
|
1030
|
+
}
|
|
1031
|
+
}
|
|
1032
|
+
else if (run.status === "queued" || run.status === "running") {
|
|
1033
|
+
const runs = bindRequestToRun(record, body.disposition ?? record.disposition, run.runId, run.status);
|
|
1034
|
+
if (record.deadlineRunId !== run.runId) {
|
|
1035
|
+
record.deadlineRunId = run.runId;
|
|
1036
|
+
record.runningDeadline = null;
|
|
1037
|
+
}
|
|
1038
|
+
if (run.status === "running" && record.runningDeadline === null) {
|
|
1039
|
+
record.runningDeadline = Date.now() + 120_000;
|
|
1040
|
+
}
|
|
1041
|
+
publishActivity({ runs, isLoading: false });
|
|
1042
|
+
}
|
|
1043
|
+
else {
|
|
1044
|
+
if (run.status === "failed") {
|
|
1045
|
+
const runs = bindRequestToRun(record, body.disposition ?? record.disposition, run.runId, run.status);
|
|
1046
|
+
publishActivity({ runs, isLoading: false });
|
|
1047
|
+
settleRun("failed", run.runId, run.error);
|
|
1048
|
+
return;
|
|
1049
|
+
}
|
|
1050
|
+
const dropped = run.status === "completed" && run.delivery?.verdict === "drop";
|
|
1051
|
+
const parts = dropped ? [] : normalizeMessageParts(run.parts, run.text);
|
|
1052
|
+
const disposition = body.disposition ?? record.disposition;
|
|
1053
|
+
const hasBoundOutputOwner = disposition === "run" || outputOwnedRunIds.has(run.runId) || [...requests.values()].some((candidate) => candidate !== record
|
|
1054
|
+
&& candidate.serverRunId === run.runId
|
|
1055
|
+
&& candidate.disposition === "run");
|
|
1056
|
+
const outputAlreadyPresent = typeof run.outputMessageId === "string"
|
|
1057
|
+
? snapshot.messages.some((message) => message.id === run.outputMessageId)
|
|
1058
|
+
: outputMessageIdsByRun.has(run.runId);
|
|
1059
|
+
const materializeOutput = parts.length > 0 && hasBoundOutputOwner && !outputAlreadyPresent;
|
|
1060
|
+
const runs = bindRequestToRun(record, disposition, run.runId, materializeOutput ? "running" : run.status);
|
|
1061
|
+
publishActivity({ runs, isLoading: false });
|
|
1062
|
+
if (materializeOutput) {
|
|
1063
|
+
const ephemeralIds = new Set(deltaMessageIds.values());
|
|
1064
|
+
deltaMessageIds.clear();
|
|
1065
|
+
roomLocalStreamingMessageId = null;
|
|
1066
|
+
notifyDataChangedParts(options, conversationId, parts, new Set());
|
|
1067
|
+
applyConversationTitleParts(parts);
|
|
1068
|
+
const message = messageSnapshot("assistant", parts);
|
|
1069
|
+
if (run.outputMessageId)
|
|
1070
|
+
message.id = run.outputMessageId;
|
|
1071
|
+
outputMessageIdsByRun.set(run.runId, message.id);
|
|
1072
|
+
setSnapshot({
|
|
1073
|
+
messages: [
|
|
1074
|
+
...snapshot.messages.filter((message) => !ephemeralIds.has(message.id)),
|
|
1075
|
+
message
|
|
1076
|
+
],
|
|
1077
|
+
committedResponseRunId: run.runId
|
|
1078
|
+
});
|
|
1079
|
+
}
|
|
1080
|
+
settleRun(run.status, run.runId);
|
|
1081
|
+
return;
|
|
1082
|
+
}
|
|
1083
|
+
if (record.runningDeadline !== null && Date.now() >= record.runningDeadline) {
|
|
1084
|
+
throw new Error("Raybase agent turn timed out");
|
|
1085
|
+
}
|
|
1086
|
+
await abortableAgentDelay(delayMs, signal);
|
|
1087
|
+
delayMs = Math.min(delayMs * 2, 2_000);
|
|
1088
|
+
}
|
|
1089
|
+
}
|
|
1090
|
+
async function openConversationInternal(id, input = {}) {
|
|
1091
|
+
resetRoomState(false);
|
|
1092
|
+
const generation = conversationGeneration;
|
|
1093
|
+
conversationId = id;
|
|
1094
|
+
basePath = null;
|
|
1095
|
+
conversationToken = null;
|
|
1096
|
+
setSnapshot({
|
|
1097
|
+
conversationId,
|
|
1098
|
+
currentUserId: null,
|
|
1099
|
+
presence: [],
|
|
1100
|
+
roomMembers: [],
|
|
1101
|
+
runs: [],
|
|
1102
|
+
status: "loading",
|
|
1103
|
+
isLoading: true,
|
|
1104
|
+
isRunning: false,
|
|
1105
|
+
voiceNotePending: false,
|
|
1106
|
+
committedResponseRunId: null,
|
|
1107
|
+
error: null,
|
|
1108
|
+
hasOlder: false,
|
|
1109
|
+
loadingOlder: false,
|
|
1110
|
+
markers: [],
|
|
1111
|
+
olderError: null
|
|
1112
|
+
});
|
|
1113
|
+
try {
|
|
1114
|
+
await ensureConversation();
|
|
1115
|
+
if (closed || generation !== conversationGeneration)
|
|
1116
|
+
return snapshot;
|
|
1117
|
+
const loaded = await loadConversationMessages();
|
|
1118
|
+
if (closed || generation !== conversationGeneration)
|
|
1119
|
+
return snapshot;
|
|
1120
|
+
lastSeq = loaded.seq;
|
|
1121
|
+
outputMessageIdsByRun.clear();
|
|
1122
|
+
for (const [messageId, runId] of loaded.messageRunIds) {
|
|
1123
|
+
outputMessageIdsByRun.set(runId, messageId);
|
|
1124
|
+
}
|
|
1125
|
+
rememberConversation();
|
|
1126
|
+
olderCursor = loaded.nextCursor;
|
|
1127
|
+
const settled = setSnapshot({
|
|
1128
|
+
conversationId,
|
|
1129
|
+
messages: loaded.messages,
|
|
1130
|
+
runs: [],
|
|
1131
|
+
status: "ready",
|
|
1132
|
+
isLoading: false,
|
|
1133
|
+
isRunning: false,
|
|
1134
|
+
voiceNotePending: false,
|
|
1135
|
+
committedResponseRunId: null,
|
|
1136
|
+
hasLoaded: true,
|
|
1137
|
+
error: null,
|
|
1138
|
+
hasOlder: loaded.hasOlder,
|
|
1139
|
+
loadingOlder: false,
|
|
1140
|
+
markers: [],
|
|
1141
|
+
olderError: null
|
|
1142
|
+
});
|
|
1143
|
+
// A conversation whose whole hot tail was archived would otherwise
|
|
1144
|
+
// reopen onto a blank screen: page in the newest archived span once.
|
|
1145
|
+
if (settled.messages.length === 0 && settled.hasOlder)
|
|
1146
|
+
await loadOlderMessages();
|
|
1147
|
+
await openRoomSocket().catch(() => { });
|
|
1148
|
+
return snapshot;
|
|
1149
|
+
}
|
|
1150
|
+
catch (error) {
|
|
1151
|
+
if (closed || generation !== conversationGeneration)
|
|
1152
|
+
return snapshot;
|
|
1153
|
+
if (input.fromStorage && isRecoverableConversationError(error)) {
|
|
1154
|
+
forgetConversation();
|
|
1155
|
+
conversationId = null;
|
|
1156
|
+
basePath = null;
|
|
1157
|
+
conversationToken = null;
|
|
1158
|
+
resetRoomState();
|
|
1159
|
+
// Only load() opens fromStorage, and it keeps going after this
|
|
1160
|
+
// recovery (conversation list, then settle) — stay loading so the
|
|
1161
|
+
// cleared snapshot doesn't read as "settled empty" mid-load.
|
|
1162
|
+
setSnapshot({
|
|
1163
|
+
conversationId: null,
|
|
1164
|
+
messages: [],
|
|
1165
|
+
status: "loading",
|
|
1166
|
+
isLoading: true,
|
|
1167
|
+
isRunning: false,
|
|
1168
|
+
committedResponseRunId: null,
|
|
1169
|
+
error: null
|
|
1170
|
+
});
|
|
1171
|
+
}
|
|
1172
|
+
throw error;
|
|
1173
|
+
}
|
|
1174
|
+
}
|
|
1175
|
+
async function submitMessage(input, callbacks = {}) {
|
|
1176
|
+
const message = input.message?.trim() ?? "";
|
|
1177
|
+
const parts = normalizeSubmitParts(input.parts, message);
|
|
1178
|
+
if (!parts.length || snapshot.voiceNotePending)
|
|
1179
|
+
return snapshot;
|
|
1180
|
+
const userMessage = messageSnapshot("user", parts);
|
|
1181
|
+
const runId = randomClientId("agent_run");
|
|
1182
|
+
const requestKey = randomClientId("agent_request");
|
|
1183
|
+
const record = registerRequest({
|
|
1184
|
+
requestKey,
|
|
1185
|
+
clientRunId: runId,
|
|
1186
|
+
optimisticMessageId: userMessage.id
|
|
1187
|
+
});
|
|
1188
|
+
publishActivity({
|
|
1189
|
+
messages: [...snapshot.messages, userMessage],
|
|
1190
|
+
runs: [...snapshot.runs, { id: runId, status: "queued" }],
|
|
1191
|
+
isLoading: false,
|
|
1192
|
+
error: null
|
|
1193
|
+
});
|
|
1194
|
+
try {
|
|
1195
|
+
await ensureConversation();
|
|
1196
|
+
}
|
|
1197
|
+
catch (error) {
|
|
1198
|
+
if (!isCurrentRequest(record))
|
|
1199
|
+
return snapshot;
|
|
1200
|
+
const nextError = asError(error);
|
|
1201
|
+
rejectRequest(record, nextError, { accepted: false, cancelled: isAbortError(error) });
|
|
1202
|
+
callbacks.onAcceptanceError?.(nextError);
|
|
1203
|
+
return snapshot;
|
|
1204
|
+
}
|
|
1205
|
+
if (!isCurrentRequest(record))
|
|
1206
|
+
return snapshot;
|
|
1207
|
+
return executeTurn(record, {
|
|
1208
|
+
...(input.parts ? { parts } : { message }),
|
|
1209
|
+
...callbacks
|
|
1210
|
+
});
|
|
1211
|
+
}
|
|
1212
|
+
return {
|
|
1213
|
+
async load() {
|
|
1214
|
+
// A closed client is reloadable. React StrictMode runs the hook's
|
|
1215
|
+
// lifecycle as load → close → load on one memoized instance, so the
|
|
1216
|
+
// second load must clear the closed latch or the room socket is never
|
|
1217
|
+
// reopened: messages still fetch, but nothing arrives live afterwards.
|
|
1218
|
+
closed = false;
|
|
1219
|
+
setSnapshot({ status: "loading", isLoading: true, error: null });
|
|
1220
|
+
try {
|
|
1221
|
+
if (conversationId) {
|
|
1222
|
+
try {
|
|
1223
|
+
await openConversationInternal(conversationId, { fromStorage: options.conversationId === undefined });
|
|
1224
|
+
return snapshot;
|
|
1225
|
+
}
|
|
1226
|
+
catch (error) {
|
|
1227
|
+
if (options.conversationId !== undefined || !isRecoverableConversationError(error))
|
|
1228
|
+
throw error;
|
|
1229
|
+
}
|
|
1230
|
+
}
|
|
1231
|
+
const conversations = await refreshConversations();
|
|
1232
|
+
if (conversations[0]) {
|
|
1233
|
+
try {
|
|
1234
|
+
await openConversationInternal(conversations[0].conversationId, { fromStorage: true });
|
|
1235
|
+
return snapshot;
|
|
1236
|
+
}
|
|
1237
|
+
catch (error) {
|
|
1238
|
+
if (!isRecoverableConversationError(error))
|
|
1239
|
+
throw error;
|
|
1240
|
+
}
|
|
1241
|
+
}
|
|
1242
|
+
olderCursor = null;
|
|
1243
|
+
setSnapshot({
|
|
1244
|
+
conversationId: null,
|
|
1245
|
+
messages: [],
|
|
1246
|
+
status: "ready",
|
|
1247
|
+
isLoading: false,
|
|
1248
|
+
isRunning: false,
|
|
1249
|
+
committedResponseRunId: null,
|
|
1250
|
+
hasLoaded: true,
|
|
1251
|
+
error: null,
|
|
1252
|
+
hasOlder: false,
|
|
1253
|
+
loadingOlder: false,
|
|
1254
|
+
markers: [],
|
|
1255
|
+
olderError: null
|
|
1256
|
+
});
|
|
1257
|
+
}
|
|
1258
|
+
catch (error) {
|
|
1259
|
+
setSnapshot({ status: "error", isLoading: false, isRunning: false, hasLoaded: true, error: asError(error) });
|
|
1260
|
+
}
|
|
1261
|
+
return snapshot;
|
|
1262
|
+
},
|
|
1263
|
+
async connect() {
|
|
1264
|
+
// Same revival as load(): connect() is an explicit ask for a live socket.
|
|
1265
|
+
closed = false;
|
|
1266
|
+
await ensureConversation();
|
|
1267
|
+
await openRoomSocket().catch(() => { });
|
|
1268
|
+
return snapshot;
|
|
1269
|
+
},
|
|
1270
|
+
async listConversations(query) {
|
|
1271
|
+
try {
|
|
1272
|
+
const conversations = await refreshConversations(query);
|
|
1273
|
+
return conversations;
|
|
1274
|
+
}
|
|
1275
|
+
catch (error) {
|
|
1276
|
+
publishActivity({ isLoading: false, hasLoaded: true, error: asError(error) });
|
|
1277
|
+
return snapshot.conversations;
|
|
1278
|
+
}
|
|
1279
|
+
},
|
|
1280
|
+
async openConversation(id) {
|
|
1281
|
+
try {
|
|
1282
|
+
return await openConversationInternal(id);
|
|
1283
|
+
}
|
|
1284
|
+
catch (error) {
|
|
1285
|
+
publishActivity({ isLoading: false, hasLoaded: true, error: asError(error) });
|
|
1286
|
+
return snapshot;
|
|
1287
|
+
}
|
|
1288
|
+
},
|
|
1289
|
+
async newConversation() {
|
|
1290
|
+
resetRoomState();
|
|
1291
|
+
conversationId = null;
|
|
1292
|
+
basePath = null;
|
|
1293
|
+
conversationToken = null;
|
|
1294
|
+
forgetConversation();
|
|
1295
|
+
return setSnapshot({
|
|
1296
|
+
conversationId: null,
|
|
1297
|
+
messages: [],
|
|
1298
|
+
runs: [],
|
|
1299
|
+
status: "ready",
|
|
1300
|
+
isLoading: false,
|
|
1301
|
+
isRunning: false,
|
|
1302
|
+
voiceNotePending: false,
|
|
1303
|
+
committedResponseRunId: null,
|
|
1304
|
+
hasLoaded: true,
|
|
1305
|
+
error: null
|
|
1306
|
+
});
|
|
1307
|
+
},
|
|
1308
|
+
async renameConversation(id, title) {
|
|
1309
|
+
try {
|
|
1310
|
+
const response = await fetcher(urlFor(options.baseUrl, `${agentBasePath}/${encodeURIComponent(options.agentName)}/conversations/${encodeURIComponent(id)}`), {
|
|
1311
|
+
method: "PATCH",
|
|
1312
|
+
credentials: "same-origin",
|
|
1313
|
+
headers: raybaseAgentHeaders(options),
|
|
1314
|
+
body: JSON.stringify({ title })
|
|
1315
|
+
});
|
|
1316
|
+
const body = await readResponseBody(response);
|
|
1317
|
+
if (!response.ok) {
|
|
1318
|
+
throw new RaybaseAgentRequestError(body.error ?? `Raybase agent rename failed with ${response.status}`, response.status);
|
|
1319
|
+
}
|
|
1320
|
+
return setSnapshot({
|
|
1321
|
+
conversations: snapshot.conversations.map((conversation) => conversation.conversationId === id ? { ...conversation, title: body.title ?? null } : conversation)
|
|
1322
|
+
});
|
|
1323
|
+
}
|
|
1324
|
+
catch (error) {
|
|
1325
|
+
publishActivity({ isLoading: false, hasLoaded: true, error: asError(error) });
|
|
1326
|
+
return snapshot;
|
|
1327
|
+
}
|
|
1328
|
+
},
|
|
1329
|
+
async pinConversation(id, pinned) {
|
|
1330
|
+
try {
|
|
1331
|
+
const response = await fetcher(urlFor(options.baseUrl, `${agentBasePath}/${encodeURIComponent(options.agentName)}/conversations/${encodeURIComponent(id)}`), {
|
|
1332
|
+
method: "PATCH",
|
|
1333
|
+
credentials: "same-origin",
|
|
1334
|
+
headers: raybaseAgentHeaders(options),
|
|
1335
|
+
body: JSON.stringify({ pinned })
|
|
1336
|
+
});
|
|
1337
|
+
const body = await readResponseBody(response);
|
|
1338
|
+
if (!response.ok) {
|
|
1339
|
+
throw new RaybaseAgentRequestError(body.error ?? `Raybase agent pin update failed with ${response.status}`, response.status);
|
|
1340
|
+
}
|
|
1341
|
+
const conversations = snapshot.conversations
|
|
1342
|
+
.map((conversation) => conversation.conversationId === id
|
|
1343
|
+
? { ...conversation, pinnedAt: body.pinnedAt ?? null }
|
|
1344
|
+
: conversation)
|
|
1345
|
+
.sort(compareAgentConversations);
|
|
1346
|
+
return setSnapshot({ conversations });
|
|
1347
|
+
}
|
|
1348
|
+
catch (error) {
|
|
1349
|
+
publishActivity({ isLoading: false, hasLoaded: true, error: asError(error) });
|
|
1350
|
+
return snapshot;
|
|
1351
|
+
}
|
|
1352
|
+
},
|
|
1353
|
+
async deleteConversation(id = conversationId ?? undefined) {
|
|
1354
|
+
if (!id) {
|
|
1355
|
+
resetRoomState();
|
|
1356
|
+
conversationId = null;
|
|
1357
|
+
basePath = null;
|
|
1358
|
+
conversationToken = null;
|
|
1359
|
+
forgetConversation();
|
|
1360
|
+
return setSnapshot({
|
|
1361
|
+
conversationId: null,
|
|
1362
|
+
messages: [],
|
|
1363
|
+
runs: [],
|
|
1364
|
+
status: "ready",
|
|
1365
|
+
isLoading: false,
|
|
1366
|
+
isRunning: false,
|
|
1367
|
+
voiceNotePending: false,
|
|
1368
|
+
committedResponseRunId: null,
|
|
1369
|
+
hasLoaded: true,
|
|
1370
|
+
error: null
|
|
1371
|
+
});
|
|
1372
|
+
}
|
|
1373
|
+
const deletingCurrent = id === conversationId;
|
|
1374
|
+
try {
|
|
1375
|
+
const response = await fetcher(urlFor(options.baseUrl, `${agentBasePath}/${encodeURIComponent(options.agentName)}/conversations/${encodeURIComponent(id)}`), {
|
|
1376
|
+
method: "DELETE",
|
|
1377
|
+
credentials: "same-origin",
|
|
1378
|
+
headers: raybaseAgentHeaders(options)
|
|
1379
|
+
});
|
|
1380
|
+
const body = await readResponseBody(response);
|
|
1381
|
+
if (!response.ok) {
|
|
1382
|
+
throw new RaybaseAgentRequestError(body.error ?? `Raybase agent delete failed with ${response.status}`, response.status);
|
|
1383
|
+
}
|
|
1384
|
+
if (deletingCurrent) {
|
|
1385
|
+
resetRoomState();
|
|
1386
|
+
conversationId = null;
|
|
1387
|
+
basePath = null;
|
|
1388
|
+
conversationToken = null;
|
|
1389
|
+
forgetConversation();
|
|
1390
|
+
}
|
|
1391
|
+
const update = {
|
|
1392
|
+
conversationId,
|
|
1393
|
+
conversations: snapshot.conversations.filter((conversation) => conversation.conversationId !== id),
|
|
1394
|
+
messages: deletingCurrent ? [] : snapshot.messages,
|
|
1395
|
+
runs: deletingCurrent ? [] : snapshot.runs,
|
|
1396
|
+
status: "ready",
|
|
1397
|
+
isLoading: false,
|
|
1398
|
+
isRunning: false,
|
|
1399
|
+
voiceNotePending: deletingCurrent ? false : snapshot.voiceNotePending,
|
|
1400
|
+
committedResponseRunId: deletingCurrent ? null : snapshot.committedResponseRunId,
|
|
1401
|
+
hasLoaded: true,
|
|
1402
|
+
error: null
|
|
1403
|
+
};
|
|
1404
|
+
return deletingCurrent ? setSnapshot(update) : publishActivity(update);
|
|
1405
|
+
}
|
|
1406
|
+
catch (error) {
|
|
1407
|
+
publishActivity({ isLoading: false, hasLoaded: true, error: asError(error) });
|
|
1408
|
+
return snapshot;
|
|
1409
|
+
}
|
|
1410
|
+
},
|
|
1411
|
+
async submit(input) {
|
|
1412
|
+
return submitMessage(input, {
|
|
1413
|
+
...(input.onAccepted ? { onAccepted: input.onAccepted } : {}),
|
|
1414
|
+
...(input.onAcceptanceError ? { onAcceptanceError: input.onAcceptanceError } : {})
|
|
1415
|
+
});
|
|
1416
|
+
},
|
|
1417
|
+
async submitVoiceNote(input) {
|
|
1418
|
+
if (snapshot.voiceNotePending || snapshot.status === "error")
|
|
1419
|
+
return snapshot;
|
|
1420
|
+
const pipeline = {
|
|
1421
|
+
controller: new AbortController(),
|
|
1422
|
+
generation: conversationGeneration
|
|
1423
|
+
};
|
|
1424
|
+
voicePipeline = pipeline;
|
|
1425
|
+
setSnapshot({ voiceNotePending: true });
|
|
1426
|
+
try {
|
|
1427
|
+
await ensureConversation();
|
|
1428
|
+
if (closed || voicePipeline !== pipeline || pipeline.generation !== conversationGeneration)
|
|
1429
|
+
return snapshot;
|
|
1430
|
+
const capability = snapshot.voiceNotes;
|
|
1431
|
+
if (!capability.enabled || !capability.bucket) {
|
|
1432
|
+
throw new RaybaseAgentRequestError("Voice notes are unavailable for this agent", 404);
|
|
1433
|
+
}
|
|
1434
|
+
let fileId = uploadedVoiceNotes.get(input.bytes);
|
|
1435
|
+
if (!fileId) {
|
|
1436
|
+
const upload = await fetcher(urlFor(options.baseUrl, `/api/files/${encodeURIComponent(capability.bucket)}`), {
|
|
1437
|
+
method: "POST",
|
|
1438
|
+
credentials: "same-origin",
|
|
1439
|
+
headers: {
|
|
1440
|
+
"content-type": "audio/wav",
|
|
1441
|
+
"x-raybase-filename": "voice-note.wav"
|
|
1442
|
+
},
|
|
1443
|
+
signal: pipeline.controller.signal,
|
|
1444
|
+
body: input.bytes
|
|
1445
|
+
});
|
|
1446
|
+
const uploaded = await readResponseBody(upload);
|
|
1447
|
+
if (!upload.ok || typeof uploaded.id !== "string") {
|
|
1448
|
+
throw new RaybaseAgentRequestError(uploaded.error ?? `Voice note upload failed with ${upload.status}`, upload.status);
|
|
1449
|
+
}
|
|
1450
|
+
fileId = uploaded.id;
|
|
1451
|
+
uploadedVoiceNotes.set(input.bytes, fileId);
|
|
1452
|
+
}
|
|
1453
|
+
if (closed || voicePipeline !== pipeline || pipeline.generation !== conversationGeneration)
|
|
1454
|
+
return snapshot;
|
|
1455
|
+
const response = await fetcher(urlFor(options.baseUrl, `${agentBasePath}/${encodeURIComponent(options.agentName)}/voice-transcriptions`), {
|
|
1456
|
+
method: "POST",
|
|
1457
|
+
credentials: "same-origin",
|
|
1458
|
+
signal: pipeline.controller.signal,
|
|
1459
|
+
headers: raybaseAgentHeaders(options),
|
|
1460
|
+
body: JSON.stringify({ fileId })
|
|
1461
|
+
});
|
|
1462
|
+
const transcribed = await readResponseBody(response);
|
|
1463
|
+
if (!response.ok || typeof transcribed.transcript !== "string" || !transcribed.transcript.trim()) {
|
|
1464
|
+
throw new RaybaseAgentRequestError(transcribed.error ?? `Voice transcription failed with ${response.status}`, response.status);
|
|
1465
|
+
}
|
|
1466
|
+
if (closed || voicePipeline !== pipeline || pipeline.generation !== conversationGeneration)
|
|
1467
|
+
return snapshot;
|
|
1468
|
+
const transcript = transcribed.transcript.trim();
|
|
1469
|
+
const parts = [
|
|
1470
|
+
{ type: "file", mediaType: "audio/wav", url: `raybase-file:${fileId}`, filename: "voice-note.wav" },
|
|
1471
|
+
{ type: "data-voice-note", data: { durationSeconds: input.durationSeconds } },
|
|
1472
|
+
{ type: "text", text: transcript }
|
|
1473
|
+
];
|
|
1474
|
+
voicePipeline = null;
|
|
1475
|
+
publishActivity({ isLoading: false, voiceNotePending: false, hasLoaded: true });
|
|
1476
|
+
return await new Promise((resolve) => {
|
|
1477
|
+
let resolved = false;
|
|
1478
|
+
const finish = (value) => {
|
|
1479
|
+
if (resolved)
|
|
1480
|
+
return;
|
|
1481
|
+
resolved = true;
|
|
1482
|
+
resolve(value);
|
|
1483
|
+
};
|
|
1484
|
+
void submitMessage({ message: transcript, parts }, {
|
|
1485
|
+
onAccepted: () => finish(snapshot),
|
|
1486
|
+
onAcceptanceError: (error) => finish({ ...snapshot, error })
|
|
1487
|
+
}).then(finish);
|
|
1488
|
+
});
|
|
1489
|
+
}
|
|
1490
|
+
catch (error) {
|
|
1491
|
+
if (voicePipeline !== pipeline || pipeline.generation !== conversationGeneration || closed)
|
|
1492
|
+
return snapshot;
|
|
1493
|
+
voicePipeline = null;
|
|
1494
|
+
publishActivity({ isLoading: false, voiceNotePending: false, hasLoaded: true });
|
|
1495
|
+
return { ...snapshot, error: asError(error) };
|
|
1496
|
+
}
|
|
1497
|
+
},
|
|
1498
|
+
async retry() {
|
|
1499
|
+
if (snapshot.isRunning || !conversationId)
|
|
1500
|
+
return snapshot;
|
|
1501
|
+
const runId = randomClientId("agent_run");
|
|
1502
|
+
const requestKey = randomClientId("agent_request");
|
|
1503
|
+
const record = registerRequest({ requestKey, clientRunId: runId });
|
|
1504
|
+
publishActivity({
|
|
1505
|
+
runs: [...snapshot.runs, { id: runId, status: "queued" }],
|
|
1506
|
+
isLoading: false,
|
|
1507
|
+
error: null
|
|
1508
|
+
});
|
|
1509
|
+
try {
|
|
1510
|
+
await ensureConversation();
|
|
1511
|
+
}
|
|
1512
|
+
catch (error) {
|
|
1513
|
+
if (!isCurrentRequest(record))
|
|
1514
|
+
return snapshot;
|
|
1515
|
+
rejectRequest(record, asError(error), { accepted: false, cancelled: isAbortError(error) });
|
|
1516
|
+
return snapshot;
|
|
1517
|
+
}
|
|
1518
|
+
if (!isCurrentRequest(record))
|
|
1519
|
+
return snapshot;
|
|
1520
|
+
return executeTurn(record, {
|
|
1521
|
+
retry: true,
|
|
1522
|
+
// Only hide the failed turn once the server has accepted the retry; a
|
|
1523
|
+
// refused retry (e.g. 409 while running) must keep it visible.
|
|
1524
|
+
onAccepted: () => {
|
|
1525
|
+
setSnapshot({ messages: supersedeTrailingTurnErrorMessages(snapshot.messages) });
|
|
1526
|
+
}
|
|
1527
|
+
});
|
|
1528
|
+
},
|
|
1529
|
+
async cancel(_runId) {
|
|
1530
|
+
if (!conversationId || !conversationToken)
|
|
1531
|
+
return snapshot;
|
|
1532
|
+
try {
|
|
1533
|
+
const response = await fetcher(urlFor(options.baseUrl, `${agentBasePath}/${encodeURIComponent(options.agentName)}/conversations/${encodeURIComponent(conversationId)}/cancel`), {
|
|
1534
|
+
method: "POST",
|
|
1535
|
+
credentials: "same-origin",
|
|
1536
|
+
headers: {
|
|
1537
|
+
...raybaseAgentHeaders(options),
|
|
1538
|
+
authorization: `Bearer ${conversationToken}`
|
|
1539
|
+
}
|
|
1540
|
+
});
|
|
1541
|
+
const body = await readResponseBody(response);
|
|
1542
|
+
if (!response.ok) {
|
|
1543
|
+
throw new RaybaseAgentRequestError(body.error ?? `Raybase agent cancel failed with ${response.status}`, response.status);
|
|
1544
|
+
}
|
|
1545
|
+
for (const record of requests.values())
|
|
1546
|
+
record.controller.abort();
|
|
1547
|
+
requests.clear();
|
|
1548
|
+
pendingMessageIds.clear();
|
|
1549
|
+
outputOwnedRunIds.clear();
|
|
1550
|
+
if (voicePipeline)
|
|
1551
|
+
voicePipeline.controller.abort();
|
|
1552
|
+
voicePipeline = null;
|
|
1553
|
+
conversationGeneration += 1;
|
|
1554
|
+
publishActivity({
|
|
1555
|
+
runs: snapshot.runs.map((run) => isLiveRunStatus(run.status) ? { ...run, status: "cancelled" } : run),
|
|
1556
|
+
isLoading: false,
|
|
1557
|
+
voiceNotePending: false,
|
|
1558
|
+
committedResponseRunId: null,
|
|
1559
|
+
error: null
|
|
1560
|
+
});
|
|
1561
|
+
}
|
|
1562
|
+
catch (error) {
|
|
1563
|
+
publishActivity({ isLoading: false, error: asError(error) });
|
|
1564
|
+
}
|
|
1565
|
+
return snapshot;
|
|
1566
|
+
},
|
|
1567
|
+
async loadOlder() {
|
|
1568
|
+
return loadOlderMessages();
|
|
1569
|
+
},
|
|
1570
|
+
async markRead() {
|
|
1571
|
+
return markCurrentConversationRead();
|
|
1572
|
+
},
|
|
1573
|
+
async editMessage(messageId, text) {
|
|
1574
|
+
const next = text.trim();
|
|
1575
|
+
if (!next)
|
|
1576
|
+
return snapshot;
|
|
1577
|
+
return mutateCurrentMessage(messageId, { method: "PATCH", body: { text: next } });
|
|
1578
|
+
},
|
|
1579
|
+
async removeMessage(messageId) {
|
|
1580
|
+
return mutateCurrentMessage(messageId, { method: "DELETE" });
|
|
1581
|
+
},
|
|
1582
|
+
async setReaction(messageId, emoji) {
|
|
1583
|
+
return mutateCurrentMessage(messageId, {
|
|
1584
|
+
method: emoji === null ? "DELETE" : "PUT",
|
|
1585
|
+
suffix: "/reaction",
|
|
1586
|
+
...(emoji === null ? {} : { body: { emoji } })
|
|
1587
|
+
});
|
|
1588
|
+
},
|
|
1589
|
+
close() {
|
|
1590
|
+
closed = true;
|
|
1591
|
+
invalidateAsyncWork();
|
|
1592
|
+
closeRoomSocket();
|
|
1593
|
+
listeners.clear();
|
|
1594
|
+
},
|
|
1595
|
+
getSnapshot() {
|
|
1596
|
+
return snapshot;
|
|
1597
|
+
},
|
|
1598
|
+
subscribe(listener) {
|
|
1599
|
+
listeners.add(listener);
|
|
1600
|
+
return () => listeners.delete(listener);
|
|
1601
|
+
}
|
|
1602
|
+
};
|
|
1603
|
+
}
|
|
1604
|
+
export function useRaybaseAgentChat(options) {
|
|
1605
|
+
const chat = useMemo(() => createRaybaseAgentChat(options), [options.agentName, options.conversationId, options.route, options.surface, options.initialConversationTitle, options.title, options.baseUrl, options.agentBasePath, options.fetch, options.storageKey, options.persistConversation, options.onDataChanged, options.webSocket]);
|
|
1606
|
+
useSyncExternalStore(chat.subscribe, chat.getSnapshot, chat.getSnapshot);
|
|
1607
|
+
useEffect(() => {
|
|
1608
|
+
void chat.load();
|
|
1609
|
+
return () => chat.close();
|
|
1610
|
+
}, [chat]);
|
|
1611
|
+
return chat;
|
|
1612
|
+
}
|
|
1613
|
+
export function useRaybaseAgentRuntime(props) {
|
|
1614
|
+
const snapshot = useSyncExternalStore(props.chat.subscribe, props.chat.getSnapshot, props.chat.getSnapshot);
|
|
1615
|
+
return useExternalStoreRuntime({
|
|
1616
|
+
messages: snapshot.messages,
|
|
1617
|
+
isRunning: snapshot.isRunning,
|
|
1618
|
+
isLoading: snapshot.isLoading,
|
|
1619
|
+
isDisabled: props.disabled === true || props.sendDisabled === true || snapshot.status === "error" || snapshot.voiceNotePending,
|
|
1620
|
+
convertMessage: (message) => raybaseMessageToThreadMessage(message, snapshot.currentUserId, snapshot.attachments.bucket ?? snapshot.voiceNotes.bucket),
|
|
1621
|
+
onNew: async (message) => {
|
|
1622
|
+
if (snapshot.isRunning || snapshot.voiceNotePending || snapshot.status === "error" || props.disabled === true || props.sendDisabled === true)
|
|
1623
|
+
return;
|
|
1624
|
+
const text = appendMessageToText(message);
|
|
1625
|
+
if (text)
|
|
1626
|
+
await props.chat.submit({ message: text });
|
|
1627
|
+
},
|
|
1628
|
+
onCancel: async () => {
|
|
1629
|
+
const run = [...snapshot.runs].reverse().find((candidate) => candidate.status === "queued" || candidate.status === "running");
|
|
1630
|
+
await props.chat.cancel(run?.id);
|
|
1631
|
+
}
|
|
1632
|
+
});
|
|
1633
|
+
}
|
|
1634
|
+
export function RaybaseAgentRuntimeProvider(props) {
|
|
1635
|
+
const runtime = useRaybaseAgentRuntime(props);
|
|
1636
|
+
return createElement(AssistantRuntimeProvider, { runtime }, props.children);
|
|
1637
|
+
}
|
|
1638
|
+
export function RaybaseAgentPanel(props) {
|
|
1639
|
+
// The panel `title` prop is the header label; it must not become the stored
|
|
1640
|
+
// title of every conversation opened through the panel.
|
|
1641
|
+
const chat = useRaybaseAgentChat({ ...props, title: undefined });
|
|
1642
|
+
const snapshot = useSyncExternalStore(chat.subscribe, chat.getSnapshot, chat.getSnapshot);
|
|
1643
|
+
const inputRef = useRef(null);
|
|
1644
|
+
const title = props.title ?? props.agentName;
|
|
1645
|
+
const labels = raybaseAgentWidgetLabels(title, {});
|
|
1646
|
+
const placeholder = props.placeholder ?? labels.placeholder;
|
|
1647
|
+
return createElement("section", { "data-raybase-agent": props.agentName }, createElement("header", null, title), createElement(RaybaseAgentRuntimeProvider, {
|
|
1648
|
+
chat,
|
|
1649
|
+
children: createElement(RaybaseAgentChatSurface, {
|
|
1650
|
+
autoFocus: props.autoFocus !== false,
|
|
1651
|
+
emptyContent: props.emptyContent,
|
|
1652
|
+
inputRef,
|
|
1653
|
+
chat,
|
|
1654
|
+
onRetry: () => void chat.retry(),
|
|
1655
|
+
onRoomRead: chat.markRead,
|
|
1656
|
+
placeholder,
|
|
1657
|
+
snapshot,
|
|
1658
|
+
viewportClassName: props.viewportClassName
|
|
1659
|
+
})
|
|
1660
|
+
}));
|
|
1661
|
+
}
|
|
1662
|
+
export function RaybaseAgentWidget(props) {
|
|
1663
|
+
const route = useRaybaseAgentRoute(props.route);
|
|
1664
|
+
const surface = props.surface ?? props.resolveSurface?.(route) ?? "app";
|
|
1665
|
+
const title = props.title ?? props.agentName;
|
|
1666
|
+
const labels = raybaseAgentWidgetLabels(title, props.labels);
|
|
1667
|
+
const [uncontrolledOpen, setUncontrolledOpen] = useState(props.defaultOpen === true);
|
|
1668
|
+
const open = props.open ?? uncontrolledOpen;
|
|
1669
|
+
const setOpen = (nextOpen) => {
|
|
1670
|
+
if (props.open === undefined)
|
|
1671
|
+
setUncontrolledOpen(nextOpen);
|
|
1672
|
+
props.onOpenChange?.(nextOpen);
|
|
1673
|
+
};
|
|
1674
|
+
if (props.enabled === false || props.isSurfaceEnabled?.(surface, route) === false)
|
|
1675
|
+
return null;
|
|
1676
|
+
return createElement(RaybaseAgentWidgetRuntime, {
|
|
1677
|
+
agentBasePath: props.agentBasePath,
|
|
1678
|
+
agentName: props.agentName,
|
|
1679
|
+
baseUrl: props.baseUrl,
|
|
1680
|
+
conversationId: props.conversationId,
|
|
1681
|
+
fetch: props.fetch,
|
|
1682
|
+
initialConversationTitle: props.initialConversationTitle,
|
|
1683
|
+
labels,
|
|
1684
|
+
onDataChanged: props.onDataChanged,
|
|
1685
|
+
open,
|
|
1686
|
+
persistConversation: props.persistConversation,
|
|
1687
|
+
route,
|
|
1688
|
+
setOpen,
|
|
1689
|
+
storageKey: props.storageKey,
|
|
1690
|
+
surface,
|
|
1691
|
+
title,
|
|
1692
|
+
webSocket: props.webSocket
|
|
1693
|
+
});
|
|
1694
|
+
}
|
|
1695
|
+
export const RaybaseAgentFloatingWidget = RaybaseAgentWidget;
|
|
1696
|
+
const AgentHistoryIcon = History;
|
|
1697
|
+
const AgentLifeBuoyIcon = LifeBuoy;
|
|
1698
|
+
const AgentMessageCircleIcon = MessageCircle;
|
|
1699
|
+
const AgentMicIcon = Mic;
|
|
1700
|
+
const AgentPinIcon = Pin;
|
|
1701
|
+
const AgentPlusIcon = Plus;
|
|
1702
|
+
const AgentRotateCwIcon = RotateCw;
|
|
1703
|
+
const AgentSendIcon = Send;
|
|
1704
|
+
const AgentSearchIcon = Search;
|
|
1705
|
+
const AgentSquareIcon = Square;
|
|
1706
|
+
const AgentTrash2Icon = Trash2;
|
|
1707
|
+
const AgentXIcon = X;
|
|
1708
|
+
function useRaybaseAgentRoute(controlledRoute) {
|
|
1709
|
+
const [route, setRoute] = useState(controlledRoute ?? currentRaybaseAgentRoute());
|
|
1710
|
+
useEffect(() => {
|
|
1711
|
+
if (controlledRoute !== undefined) {
|
|
1712
|
+
setRoute(controlledRoute || "/");
|
|
1713
|
+
return;
|
|
1714
|
+
}
|
|
1715
|
+
const updateRoute = () => setRoute(currentRaybaseAgentRoute());
|
|
1716
|
+
updateRoute();
|
|
1717
|
+
return subscribeRaybaseAgentRoute(updateRoute);
|
|
1718
|
+
}, [controlledRoute]);
|
|
1719
|
+
return controlledRoute ?? route;
|
|
1720
|
+
}
|
|
1721
|
+
const raybaseAgentRouteListeners = new Set();
|
|
1722
|
+
let raybaseAgentRouteHistoryPatch = null;
|
|
1723
|
+
let raybaseAgentRouteCurrentPath = "/";
|
|
1724
|
+
function currentRaybaseAgentRoute() {
|
|
1725
|
+
if (typeof window === "undefined")
|
|
1726
|
+
return "/";
|
|
1727
|
+
return window.location.pathname || "/";
|
|
1728
|
+
}
|
|
1729
|
+
function subscribeRaybaseAgentRoute(listener) {
|
|
1730
|
+
if (typeof window === "undefined")
|
|
1731
|
+
return () => { };
|
|
1732
|
+
raybaseAgentRouteListeners.add(listener);
|
|
1733
|
+
if (raybaseAgentRouteListeners.size === 1)
|
|
1734
|
+
installRaybaseAgentRouteListener();
|
|
1735
|
+
return () => {
|
|
1736
|
+
raybaseAgentRouteListeners.delete(listener);
|
|
1737
|
+
if (raybaseAgentRouteListeners.size === 0)
|
|
1738
|
+
uninstallRaybaseAgentRouteListener();
|
|
1739
|
+
};
|
|
1740
|
+
}
|
|
1741
|
+
function installRaybaseAgentRouteListener() {
|
|
1742
|
+
if (raybaseAgentRouteHistoryPatch || typeof window === "undefined")
|
|
1743
|
+
return;
|
|
1744
|
+
const originalPushState = window.history.pushState;
|
|
1745
|
+
const originalReplaceState = window.history.replaceState;
|
|
1746
|
+
const pushState = function (...args) {
|
|
1747
|
+
const result = originalPushState.apply(this, args);
|
|
1748
|
+
notifyRaybaseAgentRouteChanged();
|
|
1749
|
+
return result;
|
|
1750
|
+
};
|
|
1751
|
+
const replaceState = function (...args) {
|
|
1752
|
+
const result = originalReplaceState.apply(this, args);
|
|
1753
|
+
notifyRaybaseAgentRouteChanged();
|
|
1754
|
+
return result;
|
|
1755
|
+
};
|
|
1756
|
+
raybaseAgentRouteCurrentPath = currentRaybaseAgentRoute();
|
|
1757
|
+
raybaseAgentRouteHistoryPatch = { originalPushState, originalReplaceState, pushState, replaceState };
|
|
1758
|
+
window.history.pushState = pushState;
|
|
1759
|
+
window.history.replaceState = replaceState;
|
|
1760
|
+
window.addEventListener("popstate", notifyRaybaseAgentRouteChanged);
|
|
1761
|
+
window.addEventListener("hashchange", notifyRaybaseAgentRouteChanged);
|
|
1762
|
+
}
|
|
1763
|
+
function uninstallRaybaseAgentRouteListener() {
|
|
1764
|
+
if (!raybaseAgentRouteHistoryPatch || typeof window === "undefined")
|
|
1765
|
+
return;
|
|
1766
|
+
window.removeEventListener("popstate", notifyRaybaseAgentRouteChanged);
|
|
1767
|
+
window.removeEventListener("hashchange", notifyRaybaseAgentRouteChanged);
|
|
1768
|
+
if (window.history.pushState === raybaseAgentRouteHistoryPatch.pushState)
|
|
1769
|
+
window.history.pushState = raybaseAgentRouteHistoryPatch.originalPushState;
|
|
1770
|
+
if (window.history.replaceState === raybaseAgentRouteHistoryPatch.replaceState)
|
|
1771
|
+
window.history.replaceState = raybaseAgentRouteHistoryPatch.originalReplaceState;
|
|
1772
|
+
raybaseAgentRouteHistoryPatch = null;
|
|
1773
|
+
raybaseAgentRouteCurrentPath = currentRaybaseAgentRoute();
|
|
1774
|
+
}
|
|
1775
|
+
function notifyRaybaseAgentRouteChanged() {
|
|
1776
|
+
const nextPath = currentRaybaseAgentRoute();
|
|
1777
|
+
if (nextPath === raybaseAgentRouteCurrentPath)
|
|
1778
|
+
return;
|
|
1779
|
+
raybaseAgentRouteCurrentPath = nextPath;
|
|
1780
|
+
for (const listener of raybaseAgentRouteListeners)
|
|
1781
|
+
listener();
|
|
1782
|
+
}
|
|
1783
|
+
function RaybaseAgentWidgetRuntime(props) {
|
|
1784
|
+
const chat = useRaybaseAgentChat({
|
|
1785
|
+
agentBasePath: props.agentBasePath,
|
|
1786
|
+
agentName: props.agentName,
|
|
1787
|
+
baseUrl: props.baseUrl,
|
|
1788
|
+
conversationId: props.conversationId,
|
|
1789
|
+
fetch: props.fetch,
|
|
1790
|
+
initialConversationTitle: props.initialConversationTitle,
|
|
1791
|
+
onDataChanged: props.onDataChanged,
|
|
1792
|
+
persistConversation: props.persistConversation,
|
|
1793
|
+
route: props.route,
|
|
1794
|
+
storageKey: props.storageKey,
|
|
1795
|
+
surface: props.surface,
|
|
1796
|
+
webSocket: props.webSocket
|
|
1797
|
+
});
|
|
1798
|
+
return createElement(RaybaseAgentWidgetPanel, { chat, labels: props.labels, open: props.open, setOpen: props.setOpen, title: props.title });
|
|
1799
|
+
}
|
|
1800
|
+
function RaybaseAgentWidgetPanel(props) {
|
|
1801
|
+
const { chat, labels, open, setOpen, title } = props;
|
|
1802
|
+
const [showConversations, setShowConversations] = useState(false);
|
|
1803
|
+
const inputRef = useRef(null);
|
|
1804
|
+
const snapshot = useSyncExternalStore(chat.subscribe, chat.getSnapshot, chat.getSnapshot);
|
|
1805
|
+
function focusInput() {
|
|
1806
|
+
window.requestAnimationFrame(() => inputRef.current?.focus());
|
|
1807
|
+
}
|
|
1808
|
+
useEffect(() => {
|
|
1809
|
+
if (open)
|
|
1810
|
+
inputRef.current?.focus();
|
|
1811
|
+
}, [open]);
|
|
1812
|
+
useEffect(() => {
|
|
1813
|
+
if (open) {
|
|
1814
|
+
void chat.listConversations();
|
|
1815
|
+
}
|
|
1816
|
+
}, [chat, open]);
|
|
1817
|
+
async function startNewConversation() {
|
|
1818
|
+
setShowConversations(false);
|
|
1819
|
+
await chat.newConversation();
|
|
1820
|
+
focusInput();
|
|
1821
|
+
}
|
|
1822
|
+
async function openConversation(conversationId) {
|
|
1823
|
+
setShowConversations(false);
|
|
1824
|
+
try {
|
|
1825
|
+
await chat.openConversation(conversationId);
|
|
1826
|
+
}
|
|
1827
|
+
finally {
|
|
1828
|
+
focusInput();
|
|
1829
|
+
}
|
|
1830
|
+
}
|
|
1831
|
+
return createElement("div", { className: "fixed bottom-4 right-4 z-50" }, open
|
|
1832
|
+
? createElement("section", { className: "grid h-[min(620px,calc(100vh-2rem))] w-[min(420px,calc(100vw-2rem))] grid-rows-[auto_1fr_auto] overflow-hidden rounded-lg border border-zinc-200 bg-white shadow-xl" }, createElement("div", { className: "border-b border-zinc-200" }, createElement("header", { className: "flex items-center justify-between px-3 py-2" }, createElement("div", { className: "flex min-w-0 items-center gap-2 text-sm font-semibold text-zinc-950" }, createElement(AgentMessageCircleIcon, { className: "h-4 w-4 shrink-0" }), createElement("span", { className: "truncate" }, title)), createElement("div", { className: "flex items-center gap-1" }, createElement("button", { className: agentWidgetToolbarButtonClass, type: "button", onClick: () => void startNewConversation(), "aria-label": labels.newConversation, title: labels.newConversation }, createElement(AgentPlusIcon, { className: "h-4 w-4" })), createElement("button", {
|
|
1833
|
+
className: agentWidgetToolbarButtonClass,
|
|
1834
|
+
type: "button",
|
|
1835
|
+
onClick: () => {
|
|
1836
|
+
setShowConversations((value) => !value);
|
|
1837
|
+
void chat.listConversations();
|
|
1838
|
+
},
|
|
1839
|
+
"aria-label": labels.conversations,
|
|
1840
|
+
title: labels.conversations
|
|
1841
|
+
}, createElement(AgentHistoryIcon, { className: "h-4 w-4" })), createElement("button", { className: agentWidgetToolbarButtonClass, type: "button", onClick: () => setOpen(false), "aria-label": labels.close, title: labels.close }, createElement(AgentXIcon, { className: "h-4 w-4" })))), showConversations ? createElement(RaybaseAgentConversationList, { chat, conversations: snapshot.conversations, labels, openConversation }) : null), createElement(RaybaseAgentRuntimeProvider, {
|
|
1842
|
+
chat,
|
|
1843
|
+
children: createElement(RaybaseAgentChatSurface, {
|
|
1844
|
+
emptyContent: createElement("div", { className: "rounded-md border border-zinc-200 bg-white px-3 py-2 text-sm text-zinc-600" }, labels.empty),
|
|
1845
|
+
inputRef,
|
|
1846
|
+
chat,
|
|
1847
|
+
labels,
|
|
1848
|
+
onRetry: () => void chat.retry(),
|
|
1849
|
+
onRoomRead: chat.markRead,
|
|
1850
|
+
placeholder: labels.placeholder,
|
|
1851
|
+
snapshot,
|
|
1852
|
+
viewportClassName: "space-y-3 overflow-y-auto bg-zinc-50 p-3"
|
|
1853
|
+
})
|
|
1854
|
+
}))
|
|
1855
|
+
: createElement("button", { className: "rounded-full bg-zinc-950 p-3 text-white shadow-lg", type: "button", onClick: () => setOpen(true), "aria-label": labels.open }, createElement(AgentLifeBuoyIcon, { className: "h-5 w-5" })));
|
|
1856
|
+
}
|
|
1857
|
+
function RaybaseAgentConversationList(props) {
|
|
1858
|
+
const [query, setQuery] = useState("");
|
|
1859
|
+
return createElement("div", { className: "max-h-48 overflow-y-auto border-t border-zinc-200 bg-white p-2" }, createElement("label", { className: "mb-2 flex items-center gap-1.5 rounded-md border border-zinc-200 px-2 py-1.5" }, createElement(AgentSearchIcon, { className: "h-3.5 w-3.5 text-zinc-400" }), createElement("input", {
|
|
1860
|
+
className: "min-w-0 flex-1 bg-transparent text-xs outline-none",
|
|
1861
|
+
value: query,
|
|
1862
|
+
placeholder: "Search conversations",
|
|
1863
|
+
onChange: (event) => {
|
|
1864
|
+
const next = event.target.value;
|
|
1865
|
+
setQuery(next);
|
|
1866
|
+
void props.chat.listConversations(next);
|
|
1867
|
+
}
|
|
1868
|
+
})), props.conversations.length
|
|
1869
|
+
? props.conversations.map((conversation) => createElement("div", { key: conversation.conversationId, className: "flex items-center gap-1 rounded-md hover:bg-zinc-50" }, createElement("button", {
|
|
1870
|
+
className: "min-w-0 flex-1 px-2 py-1.5 text-left",
|
|
1871
|
+
type: "button",
|
|
1872
|
+
onClick: () => void props.openConversation(conversation.conversationId)
|
|
1873
|
+
}, createElement("span", { className: "block truncate text-xs font-medium text-zinc-900" }, agentConversationLabel(conversation, props.labels.conversationFallback)), createElement("span", { className: "block truncate text-[11px] text-zinc-500" }, `${conversation.archived ? "Archived · " : ""}${agentConversationMeta(conversation)}`)), createElement("button", {
|
|
1874
|
+
className: `rounded-md p-1.5 ${conversation.pinnedAt ? "text-zinc-900" : "text-zinc-400"} hover:bg-zinc-100`,
|
|
1875
|
+
type: "button",
|
|
1876
|
+
onClick: () => void props.chat.pinConversation(conversation.conversationId, !conversation.pinnedAt),
|
|
1877
|
+
"aria-label": conversation.pinnedAt ? "Unpin conversation" : "Pin conversation",
|
|
1878
|
+
title: conversation.pinnedAt ? "Unpin" : "Pin"
|
|
1879
|
+
}, createElement(AgentPinIcon, { className: "h-3.5 w-3.5" })), createElement("button", {
|
|
1880
|
+
className: "rounded-md p-1.5 text-zinc-500 hover:bg-zinc-100 hover:text-red-700",
|
|
1881
|
+
type: "button",
|
|
1882
|
+
onClick: () => void props.chat.deleteConversation(conversation.conversationId),
|
|
1883
|
+
"aria-label": props.labels.deleteConversation,
|
|
1884
|
+
title: "Delete"
|
|
1885
|
+
}, createElement(AgentTrash2Icon, { className: "h-3.5 w-3.5" }))))
|
|
1886
|
+
: createElement("div", { className: "px-2 py-1.5 text-xs text-zinc-500" }, props.labels.noConversations));
|
|
1887
|
+
}
|
|
1888
|
+
const raybaseSourcesDataPartName = "raybase-sources";
|
|
1889
|
+
const raybaseSupportRequestCreatedDataPartName = "raybase-support-request-created";
|
|
1890
|
+
const raybaseTurnErrorDataPartName = "raybase-turn-error";
|
|
1891
|
+
const raybaseAgentThreadMessageComponents = {
|
|
1892
|
+
UserMessage: RaybaseAgentUserMessage,
|
|
1893
|
+
AssistantMessage: RaybaseAgentModelMessage
|
|
1894
|
+
};
|
|
1895
|
+
const raybaseAgentMessagePartComponents = {
|
|
1896
|
+
Text: RaybaseAgentTextMessagePart,
|
|
1897
|
+
Reasoning: () => null
|
|
1898
|
+
};
|
|
1899
|
+
// Lets the per-message components interleave chapter markers chronologically
|
|
1900
|
+
// without giving up ThreadPrimitive.Messages as the message renderer.
|
|
1901
|
+
const RaybaseAgentScrollbackContext = createContext(null);
|
|
1902
|
+
/** Markers whose span ends after the previous message and no later than this one. */
|
|
1903
|
+
function chapterMarkersBeforeMessage(value, messageId) {
|
|
1904
|
+
const index = value.messages.findIndex((message) => message.id === messageId);
|
|
1905
|
+
if (index < 0)
|
|
1906
|
+
return [];
|
|
1907
|
+
const previous = index > 0 ? value.messages[index - 1].createdAt : "";
|
|
1908
|
+
const current = value.messages[index].createdAt;
|
|
1909
|
+
return value.markers.filter((marker) => marker.endedAt > previous && marker.endedAt <= current);
|
|
1910
|
+
}
|
|
1911
|
+
/** Markers ending after every message; they trail the last one. */
|
|
1912
|
+
function chapterMarkersAfterMessage(value, messageId) {
|
|
1913
|
+
const last = value.messages[value.messages.length - 1];
|
|
1914
|
+
if (!last || last.id !== messageId)
|
|
1915
|
+
return [];
|
|
1916
|
+
return value.markers.filter((marker) => marker.endedAt > last.createdAt);
|
|
1917
|
+
}
|
|
1918
|
+
function chapterMarkerDateRange(marker) {
|
|
1919
|
+
const started = new Date(marker.startedAt);
|
|
1920
|
+
const ended = new Date(marker.endedAt);
|
|
1921
|
+
if (Number.isNaN(started.getTime()) || Number.isNaN(ended.getTime()))
|
|
1922
|
+
return "";
|
|
1923
|
+
const format = (date) => date.toLocaleDateString([], { month: "short", day: "numeric" });
|
|
1924
|
+
const from = format(started);
|
|
1925
|
+
const to = format(ended);
|
|
1926
|
+
return from === to ? from : `${from} – ${to}`;
|
|
1927
|
+
}
|
|
1928
|
+
function RaybaseAgentChapterMarkerDivider(props) {
|
|
1929
|
+
const range = chapterMarkerDateRange(props.marker);
|
|
1930
|
+
return createElement("div", {
|
|
1931
|
+
className: "flex items-center gap-2 py-1 text-[11px] text-zinc-400",
|
|
1932
|
+
role: "separator",
|
|
1933
|
+
title: props.marker.summary || undefined,
|
|
1934
|
+
"data-raybase-chapter-marker": props.marker.chapterId
|
|
1935
|
+
}, createElement("span", { className: "h-px min-w-4 flex-1 bg-zinc-200", "aria-hidden": true }), createElement("span", { className: "max-w-[70%] truncate" }, range ? `${props.marker.title} · ${range}` : props.marker.title), createElement("span", { className: "h-px min-w-4 flex-1 bg-zinc-200", "aria-hidden": true }));
|
|
1936
|
+
}
|
|
1937
|
+
export function RaybaseAgentChatSurface(props) {
|
|
1938
|
+
const labels = { ...raybaseAgentWidgetLabels("Agent", {}), ...props.labels };
|
|
1939
|
+
const viewportRef = useRef(null);
|
|
1940
|
+
const isSyncing = props.snapshot.isLoading && !props.snapshot.isRunning;
|
|
1941
|
+
const retryableTurnError = props.onRetry && !props.snapshot.isLoading ? raybaseAgentRetryableTurnError(props.snapshot) : null;
|
|
1942
|
+
const markers = props.snapshot.markers ?? [];
|
|
1943
|
+
const scrollback = useMemo(() => ({ markers, messages: props.snapshot.messages }), [markers, props.snapshot.messages]);
|
|
1944
|
+
// Empty state comes from the snapshot, not ThreadPrimitive.Empty: the
|
|
1945
|
+
// external-store runtime ingests snapshot.messages a frame after this
|
|
1946
|
+
// render, so an Empty-based empty state repaints for one frame as a loaded
|
|
1947
|
+
// conversation arrives. hasLoaded additionally holds it back until the
|
|
1948
|
+
// initial load settles, instead of flashing it over incoming messages.
|
|
1949
|
+
// Chapter markers count as content: a fully summarized conversation is
|
|
1950
|
+
// not an empty one.
|
|
1951
|
+
const showEmpty = props.snapshot.hasLoaded && props.snapshot.messages.length === 0 && markers.length === 0;
|
|
1952
|
+
const maybeLoadOlder = () => {
|
|
1953
|
+
const viewport = viewportRef.current;
|
|
1954
|
+
const chat = props.chat;
|
|
1955
|
+
if (!chat || !viewport || !props.snapshot.hasOlder || props.snapshot.loadingOlder)
|
|
1956
|
+
return;
|
|
1957
|
+
if (viewport.scrollTop > 48)
|
|
1958
|
+
return;
|
|
1959
|
+
const previousHeight = viewport.scrollHeight;
|
|
1960
|
+
const previousTop = viewport.scrollTop;
|
|
1961
|
+
void chat.loadOlder().then(() => {
|
|
1962
|
+
if (typeof window === "undefined")
|
|
1963
|
+
return;
|
|
1964
|
+
// Keep the reader anchored on the same message across the prepend.
|
|
1965
|
+
window.requestAnimationFrame(() => {
|
|
1966
|
+
const current = viewportRef.current;
|
|
1967
|
+
if (current && current.scrollHeight > previousHeight) {
|
|
1968
|
+
current.scrollTop = previousTop + (current.scrollHeight - previousHeight);
|
|
1969
|
+
}
|
|
1970
|
+
});
|
|
1971
|
+
});
|
|
1972
|
+
};
|
|
1973
|
+
useEffect(() => {
|
|
1974
|
+
if (!props.onRoomRead
|
|
1975
|
+
|| props.snapshot.isRunning
|
|
1976
|
+
|| props.snapshot.messages.length === 0
|
|
1977
|
+
|| typeof window === "undefined")
|
|
1978
|
+
return;
|
|
1979
|
+
const frame = window.requestAnimationFrame(() => {
|
|
1980
|
+
if (roomIsVisible() && roomViewportIsAtBottom(viewportRef.current))
|
|
1981
|
+
props.onRoomRead?.();
|
|
1982
|
+
});
|
|
1983
|
+
return () => window.cancelAnimationFrame(frame);
|
|
1984
|
+
}, [props.onRoomRead, props.snapshot.isRunning, props.snapshot.messages]);
|
|
1985
|
+
return createElement(RaybaseAgentScrollbackContext.Provider, { value: scrollback }, createElement(ThreadPrimitive.Root, {
|
|
1986
|
+
className: "contents",
|
|
1987
|
+
onFocusCapture: () => {
|
|
1988
|
+
if (roomIsVisible())
|
|
1989
|
+
props.onRoomRead?.();
|
|
1990
|
+
}
|
|
1991
|
+
}, createElement(ThreadPrimitive.Viewport, {
|
|
1992
|
+
className: props.viewportClassName ?? "space-y-3",
|
|
1993
|
+
ref: viewportRef,
|
|
1994
|
+
onScroll: () => {
|
|
1995
|
+
maybeLoadOlder();
|
|
1996
|
+
if (!props.snapshot.isRunning && roomIsVisible() && roomViewportIsAtBottom(viewportRef.current))
|
|
1997
|
+
props.onRoomRead?.();
|
|
1998
|
+
}
|
|
1999
|
+
}, props.snapshot.loadingOlder
|
|
2000
|
+
? createElement("div", { className: "flex items-center justify-center gap-2 py-1 text-xs text-zinc-400", role: "status", "data-raybase-loading-older": true }, createElement(AgentRotateCwIcon, { className: "h-3 w-3 animate-spin" }), "Loading earlier messages")
|
|
2001
|
+
: null,
|
|
2002
|
+
// With no messages the per-message interleave has no host, so the
|
|
2003
|
+
// markers render on their own.
|
|
2004
|
+
props.snapshot.messages.length === 0
|
|
2005
|
+
? markers.map((marker) => createElement(RaybaseAgentChapterMarkerDivider, { key: marker.chapterId, marker }))
|
|
2006
|
+
: null, props.emptyContent === undefined || !showEmpty ? null : props.emptyContent, createElement(ThreadPrimitive.Messages, { components: raybaseAgentThreadMessageComponents }), raybaseAgentHasCommittedResponse(props.snapshot)
|
|
2007
|
+
? createElement(ThreadPrimitive.If, { running: true }, createElement(RaybaseAgentStatusRow, { label: labels.thinking }))
|
|
2008
|
+
: null, isSyncing ? createElement(RaybaseAgentStatusRow, { label: labels.syncing }) : null, retryableTurnError
|
|
2009
|
+
? createElement("button", {
|
|
2010
|
+
className: "flex items-center gap-2 rounded-md border border-zinc-300 bg-white px-3 py-1.5 text-sm text-zinc-700 hover:bg-zinc-100",
|
|
2011
|
+
type: "button",
|
|
2012
|
+
onClick: () => props.onRetry?.(),
|
|
2013
|
+
"aria-label": labels.tryAgain,
|
|
2014
|
+
title: labels.tryAgain
|
|
2015
|
+
}, createElement(AgentRotateCwIcon, { className: "h-3.5 w-3.5" }), labels.tryAgain)
|
|
2016
|
+
: null, props.snapshot.error ? createElement("div", { className: "rounded-md border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-800", role: "alert" }, props.snapshot.error.message) : null), createElement(ComposerPrimitive.Root, { className: "flex gap-2 border-t border-zinc-200 p-2" }, props.chat
|
|
2017
|
+
? createElement(RaybaseVoiceNoteComposerControls, { chat: props.chat, snapshot: props.snapshot })
|
|
2018
|
+
: null, createElement(ComposerPrimitive.Input, {
|
|
2019
|
+
ref: props.inputRef,
|
|
2020
|
+
autoFocus: props.autoFocus === true,
|
|
2021
|
+
className: "min-h-10 min-w-0 flex-1 resize-none rounded-md border border-zinc-300 px-3 py-2 text-sm text-zinc-950 outline-none focus:border-zinc-500",
|
|
2022
|
+
maxRows: 4,
|
|
2023
|
+
minRows: 1,
|
|
2024
|
+
placeholder: props.placeholder
|
|
2025
|
+
}), createElement(ThreadPrimitive.If, { running: true }, createElement(ComposerPrimitive.Cancel, { className: "rounded-md border border-zinc-300 p-2 text-zinc-700 hover:bg-zinc-100 disabled:opacity-50", "aria-label": labels.cancel, title: labels.cancel }, createElement(AgentSquareIcon, { className: "h-4 w-4" }))), createElement(ComposerPrimitive.Send, { className: "rounded-md bg-zinc-950 p-2 text-white disabled:opacity-50", "aria-label": labels.send, title: labels.send }, createElement(AgentSendIcon, { className: "h-4 w-4" })))));
|
|
2026
|
+
}
|
|
2027
|
+
export function isRaybaseVoiceNoteAvailable(snapshot, recorderSupported = isVoiceRecordingSupported()) {
|
|
2028
|
+
return snapshot.voiceNotes.enabled && Boolean(snapshot.voiceNotes.bucket) && recorderSupported;
|
|
2029
|
+
}
|
|
2030
|
+
export function voiceNoteDurationLabel(durationSeconds) {
|
|
2031
|
+
const total = Math.max(0, Math.round(durationSeconds));
|
|
2032
|
+
return `${Math.floor(total / 60)}:${String(total % 60).padStart(2, "0")}`;
|
|
2033
|
+
}
|
|
2034
|
+
export function raybaseVoiceNoteFailure(error) {
|
|
2035
|
+
if (error.status === 422) {
|
|
2036
|
+
return {
|
|
2037
|
+
retryable: false,
|
|
2038
|
+
message: "We couldn’t hear any speech. Record again, or type your message instead."
|
|
2039
|
+
};
|
|
2040
|
+
}
|
|
2041
|
+
return {
|
|
2042
|
+
retryable: true,
|
|
2043
|
+
message: error.message || "Transcription is unavailable. Try again, or type your message instead."
|
|
2044
|
+
};
|
|
2045
|
+
}
|
|
2046
|
+
function RaybaseVoiceNoteComposerControls(props) {
|
|
2047
|
+
const recorderRef = useRef(null);
|
|
2048
|
+
const autoStopRef = useRef(null);
|
|
2049
|
+
const tickerRef = useRef(null);
|
|
2050
|
+
const pendingRef = useRef(null);
|
|
2051
|
+
const [state, setState] = useState("idle");
|
|
2052
|
+
const [elapsedSeconds, setElapsedSeconds] = useState(0);
|
|
2053
|
+
const [error, setError] = useState(null);
|
|
2054
|
+
function clearTimers() {
|
|
2055
|
+
if (autoStopRef.current)
|
|
2056
|
+
clearTimeout(autoStopRef.current);
|
|
2057
|
+
if (tickerRef.current)
|
|
2058
|
+
clearInterval(tickerRef.current);
|
|
2059
|
+
autoStopRef.current = null;
|
|
2060
|
+
tickerRef.current = null;
|
|
2061
|
+
}
|
|
2062
|
+
useEffect(() => () => {
|
|
2063
|
+
clearTimers();
|
|
2064
|
+
recorderRef.current?.cancel();
|
|
2065
|
+
}, []);
|
|
2066
|
+
async function submitRecording(recording) {
|
|
2067
|
+
pendingRef.current = recording;
|
|
2068
|
+
setState("transcribing");
|
|
2069
|
+
setError(null);
|
|
2070
|
+
const result = await props.chat.submitVoiceNote(recording);
|
|
2071
|
+
if (result.error && !result.isRunning) {
|
|
2072
|
+
const failure = raybaseVoiceNoteFailure(result.error);
|
|
2073
|
+
if (!failure.retryable) {
|
|
2074
|
+
pendingRef.current = null;
|
|
2075
|
+
setState("idle");
|
|
2076
|
+
setElapsedSeconds(0);
|
|
2077
|
+
setError(failure.message);
|
|
2078
|
+
return;
|
|
2079
|
+
}
|
|
2080
|
+
setState("retry");
|
|
2081
|
+
setError(failure.message);
|
|
2082
|
+
return;
|
|
2083
|
+
}
|
|
2084
|
+
pendingRef.current = null;
|
|
2085
|
+
setState("idle");
|
|
2086
|
+
setElapsedSeconds(0);
|
|
2087
|
+
}
|
|
2088
|
+
async function stopRecording() {
|
|
2089
|
+
const recorder = recorderRef.current;
|
|
2090
|
+
if (!recorder || state !== "recording")
|
|
2091
|
+
return;
|
|
2092
|
+
recorderRef.current = null;
|
|
2093
|
+
clearTimers();
|
|
2094
|
+
const recording = await recorder.stop();
|
|
2095
|
+
if (recording.durationSeconds < 0.4 || recording.bytes.byteLength <= 44) {
|
|
2096
|
+
setState("idle");
|
|
2097
|
+
setElapsedSeconds(0);
|
|
2098
|
+
setError("Hold the mic a little longer, then try again.");
|
|
2099
|
+
return;
|
|
2100
|
+
}
|
|
2101
|
+
await submitRecording(recording);
|
|
2102
|
+
}
|
|
2103
|
+
async function startRecording() {
|
|
2104
|
+
setError(null);
|
|
2105
|
+
const recorder = createVoiceRecorder({ maxSeconds: props.snapshot.voiceNotes.maxSeconds });
|
|
2106
|
+
recorderRef.current = recorder;
|
|
2107
|
+
try {
|
|
2108
|
+
await recorder.start();
|
|
2109
|
+
setElapsedSeconds(0);
|
|
2110
|
+
setState("recording");
|
|
2111
|
+
const startedAt = Date.now();
|
|
2112
|
+
tickerRef.current = setInterval(() => setElapsedSeconds((Date.now() - startedAt) / 1000), 250);
|
|
2113
|
+
autoStopRef.current = setTimeout(() => void stopRecording(), props.snapshot.voiceNotes.maxSeconds * 1000);
|
|
2114
|
+
}
|
|
2115
|
+
catch {
|
|
2116
|
+
recorderRef.current = null;
|
|
2117
|
+
recorder.cancel();
|
|
2118
|
+
setState("idle");
|
|
2119
|
+
setError("Microphone access was blocked. Allow it in your browser, or type instead.");
|
|
2120
|
+
}
|
|
2121
|
+
}
|
|
2122
|
+
function discard() {
|
|
2123
|
+
clearTimers();
|
|
2124
|
+
recorderRef.current?.cancel();
|
|
2125
|
+
recorderRef.current = null;
|
|
2126
|
+
pendingRef.current = null;
|
|
2127
|
+
setElapsedSeconds(0);
|
|
2128
|
+
setError(null);
|
|
2129
|
+
setState("idle");
|
|
2130
|
+
}
|
|
2131
|
+
if (!isRaybaseVoiceNoteAvailable(props.snapshot) && state === "idle")
|
|
2132
|
+
return null;
|
|
2133
|
+
if (state === "idle") {
|
|
2134
|
+
return createElement("div", { className: "relative flex items-center" }, createElement("button", {
|
|
2135
|
+
className: "rounded-md border border-zinc-300 p-2 text-zinc-700 hover:bg-zinc-100 disabled:opacity-50",
|
|
2136
|
+
type: "button",
|
|
2137
|
+
disabled: props.snapshot.isRunning,
|
|
2138
|
+
onClick: () => void startRecording(),
|
|
2139
|
+
"aria-label": "Record voice note",
|
|
2140
|
+
title: "Record voice note"
|
|
2141
|
+
}, createElement(AgentMicIcon, { className: "h-4 w-4" })), error ? createElement("span", { className: "absolute bottom-full left-0 mb-2 w-64 rounded-md border border-red-200 bg-red-50 px-2 py-1 text-xs text-red-800", role: "alert" }, error) : null);
|
|
2142
|
+
}
|
|
2143
|
+
if (state === "recording") {
|
|
2144
|
+
return createElement("div", { className: "flex items-center gap-1", "data-raybase-voice-recording": true }, createElement("span", { className: "min-w-12 text-xs tabular-nums text-red-700" }, voiceNoteDurationLabel(elapsedSeconds)), createElement("button", { className: agentWidgetToolbarButtonClass, type: "button", onClick: () => void stopRecording(), "aria-label": "Stop recording", title: "Stop recording" }, createElement(AgentSquareIcon, { className: "h-4 w-4" })), createElement("button", { className: agentWidgetToolbarButtonClass, type: "button", onClick: discard, "aria-label": "Discard recording", title: "Discard recording" }, createElement(AgentTrash2Icon, { className: "h-4 w-4" })));
|
|
2145
|
+
}
|
|
2146
|
+
if (state === "transcribing") {
|
|
2147
|
+
return createElement("div", { className: "flex items-center gap-2 px-1 text-xs text-zinc-600", role: "status" }, createElement(AgentRotateCwIcon, { className: "h-4 w-4 animate-spin" }), "Transcribing…");
|
|
2148
|
+
}
|
|
2149
|
+
return createElement("div", { className: "flex items-center gap-1", role: "alert" }, createElement("span", { className: "max-w-56 text-xs text-red-800" }, error), createElement("button", { className: agentWidgetToolbarButtonClass, type: "button", onClick: () => pendingRef.current && void submitRecording(pendingRef.current), "aria-label": "Retry transcription", title: "Retry transcription" }, createElement(AgentRotateCwIcon, { className: "h-4 w-4" })), createElement("button", { className: agentWidgetToolbarButtonClass, type: "button", onClick: discard, "aria-label": "Discard recording", title: "Discard recording" }, createElement(AgentTrash2Icon, { className: "h-4 w-4" })));
|
|
2150
|
+
}
|
|
2151
|
+
function RaybaseAgentUserMessage() {
|
|
2152
|
+
return createElement(RaybaseAgentPrimitiveMessage, { role: "user" });
|
|
2153
|
+
}
|
|
2154
|
+
function RaybaseAgentModelMessage() {
|
|
2155
|
+
return createElement(RaybaseAgentPrimitiveMessage, { role: "assistant" });
|
|
2156
|
+
}
|
|
2157
|
+
function RaybaseAgentPrimitiveMessage(props) {
|
|
2158
|
+
const parts = useAssistantState(({ message }) => message.parts);
|
|
2159
|
+
const messageId = useAssistantState(({ message }) => message.id);
|
|
2160
|
+
const scrollback = useContext(RaybaseAgentScrollbackContext);
|
|
2161
|
+
const custom = useAssistantState(({ message }) => message.metadata.custom);
|
|
2162
|
+
const author = custom?.raybaseAuthor;
|
|
2163
|
+
const isSelf = custom?.raybaseSelf === true;
|
|
2164
|
+
const editedAt = typeof custom?.raybaseEditedAt === "string" ? custom.raybaseEditedAt : null;
|
|
2165
|
+
const removed = custom?.raybaseRemoved === true;
|
|
2166
|
+
const reactions = custom?.raybaseReactions && typeof custom.raybaseReactions === "object"
|
|
2167
|
+
? custom.raybaseReactions
|
|
2168
|
+
: {};
|
|
2169
|
+
const rawParts = Array.isArray(custom?.raybaseParts)
|
|
2170
|
+
? custom.raybaseParts
|
|
2171
|
+
: [];
|
|
2172
|
+
const voiceNote = raybaseVoiceNoteFromParts(rawParts);
|
|
2173
|
+
const attachmentBucket = typeof custom?.raybaseAttachmentBucket === "string"
|
|
2174
|
+
? custom.raybaseAttachmentBucket
|
|
2175
|
+
: null;
|
|
2176
|
+
const leadingMarkers = scrollback ? chapterMarkersBeforeMessage(scrollback, messageId) : [];
|
|
2177
|
+
const trailingMarkers = scrollback ? chapterMarkersAfterMessage(scrollback, messageId) : [];
|
|
2178
|
+
const withMarkers = (body) => leadingMarkers.length || trailingMarkers.length
|
|
2179
|
+
? createElement(Fragment, null, leadingMarkers.map((marker) => createElement(RaybaseAgentChapterMarkerDivider, { key: marker.chapterId, marker })), body, trailingMarkers.map((marker) => createElement(RaybaseAgentChapterMarkerDivider, { key: marker.chapterId, marker })))
|
|
2180
|
+
: body;
|
|
2181
|
+
if (!voiceNote && !parts.some(isRenderableAgentUiMessagePart))
|
|
2182
|
+
return withMarkers(null);
|
|
2183
|
+
const isNotice = author?.kind === "app";
|
|
2184
|
+
const showAuthor = author?.kind === "user" && !isSelf && Boolean(author.name);
|
|
2185
|
+
return withMarkers(createElement(MessagePrimitive.Root, {
|
|
2186
|
+
className: isNotice ? "text-center" : props.role === "user" ? "text-right" : "text-left",
|
|
2187
|
+
"data-raybase-author-kind": author?.kind,
|
|
2188
|
+
"data-raybase-author-self": isSelf || undefined,
|
|
2189
|
+
"data-raybase-message-removed": removed || undefined
|
|
2190
|
+
}, showAuthor
|
|
2191
|
+
? createElement("div", { className: "mb-1 text-xs font-medium text-zinc-500", "data-raybase-author-label": true }, author?.name)
|
|
2192
|
+
: null, createElement("div", null, createElement("div", {
|
|
2193
|
+
className: isNotice
|
|
2194
|
+
? "inline-block max-w-[90%] px-2 py-1 text-center text-xs text-zinc-500"
|
|
2195
|
+
: props.role === "user" ? agentWidgetUserBubbleClass : agentWidgetAssistantBubbleClass,
|
|
2196
|
+
"data-raybase-author-kind": author?.kind,
|
|
2197
|
+
"data-raybase-author-self": isSelf ? "true" : undefined
|
|
2198
|
+
}, voiceNote
|
|
2199
|
+
? createElement(RaybaseAgentVoiceNoteView, { attachmentBucket, voiceNote })
|
|
2200
|
+
: parts.map((part, index) => createElement("div", { key: index, className: part.type === "text" ? isNotice ? "text-center" : "text-left" : "mt-2 first:mt-0" }, isDataMessagePart(part)
|
|
2201
|
+
? createElement(RaybaseAgentDataMessagePart, { part })
|
|
2202
|
+
: createElement(MessagePrimitive.PartByIndex, { index, components: raybaseAgentMessagePartComponents })))), editedAt
|
|
2203
|
+
? createElement("span", {
|
|
2204
|
+
className: "mt-0.5 block text-[10px] text-zinc-400",
|
|
2205
|
+
title: editedAt,
|
|
2206
|
+
"data-raybase-message-edited": true
|
|
2207
|
+
}, "edited")
|
|
2208
|
+
: null, Object.keys(reactions).length
|
|
2209
|
+
? createElement("div", {
|
|
2210
|
+
className: `mt-1 flex flex-wrap gap-1 ${props.role === "user" ? "justify-end" : "justify-start"}`,
|
|
2211
|
+
"data-raybase-message-reactions": true
|
|
2212
|
+
}, Object.entries(reactions).map(([userId, emoji]) => createElement("span", {
|
|
2213
|
+
key: userId,
|
|
2214
|
+
className: "rounded-full border border-zinc-200 bg-white px-1.5 py-0.5 text-xs",
|
|
2215
|
+
title: userId
|
|
2216
|
+
}, emoji)))
|
|
2217
|
+
: null)));
|
|
2218
|
+
}
|
|
2219
|
+
function RaybaseAgentTextMessagePart(props) {
|
|
2220
|
+
const role = useAssistantState(({ message }) => message.role);
|
|
2221
|
+
if (role === "assistant")
|
|
2222
|
+
return createElement(RaybaseAgentMarkdown, { markdown: props.text });
|
|
2223
|
+
return createElement(MessagePartPrimitive.Text, { component: "p", smooth: false, style: plainTextStyle });
|
|
2224
|
+
}
|
|
2225
|
+
function RaybaseAgentDataMessagePart(props) {
|
|
2226
|
+
if (props.part.name === raybaseSourcesDataPartName) {
|
|
2227
|
+
const sources = Array.isArray(props.part.data?.sources) ? props.part.data.sources : [];
|
|
2228
|
+
return createElement(RaybaseSourceChips, { sources });
|
|
2229
|
+
}
|
|
2230
|
+
if (props.part.name === raybaseSupportRequestCreatedDataPartName && props.part.data) {
|
|
2231
|
+
return createElement(RaybaseSupportRequestCard, { supportRequest: props.part.data });
|
|
2232
|
+
}
|
|
2233
|
+
if (props.part.name === raybaseTurnErrorDataPartName && props.part.data) {
|
|
2234
|
+
return createElement(RaybaseTurnErrorNotice, { turnError: props.part.data });
|
|
2235
|
+
}
|
|
2236
|
+
return null;
|
|
2237
|
+
}
|
|
2238
|
+
function RaybaseAgentStatusRow(props) {
|
|
2239
|
+
return createElement("div", { className: "flex items-center gap-2 rounded-md border border-zinc-200 bg-white px-3 py-2 text-sm text-zinc-600" }, createElement(AgentRotateCwIcon, { className: "h-3.5 w-3.5 animate-spin" }), props.label);
|
|
2240
|
+
}
|
|
2241
|
+
function isRenderableAgentUiMessagePart(part) {
|
|
2242
|
+
if (part.type === "text")
|
|
2243
|
+
return Boolean(part.text?.trim());
|
|
2244
|
+
if (part.type === "reasoning" || part.type === "tool-call" || part.type === "file" || part.type === "source")
|
|
2245
|
+
return false;
|
|
2246
|
+
if (part.type === "data")
|
|
2247
|
+
return isRenderableRaybaseDataMessagePart(part);
|
|
2248
|
+
return true;
|
|
2249
|
+
}
|
|
2250
|
+
function isRenderableRaybaseDataMessagePart(part) {
|
|
2251
|
+
if (part.name === raybaseSourcesDataPartName)
|
|
2252
|
+
return Array.isArray(part.data?.sources) && part.data.sources.length > 0;
|
|
2253
|
+
if (part.name === raybaseSupportRequestCreatedDataPartName)
|
|
2254
|
+
return Boolean(part.data);
|
|
2255
|
+
if (part.name === raybaseTurnErrorDataPartName)
|
|
2256
|
+
return Boolean(part.data) && part.data.superseded !== true;
|
|
2257
|
+
return false;
|
|
2258
|
+
}
|
|
2259
|
+
function isDataMessagePart(part) {
|
|
2260
|
+
return part.type === "data";
|
|
2261
|
+
}
|
|
2262
|
+
const agentWidgetUserBubbleClass = "inline-block max-w-[82%] rounded-md bg-zinc-950 px-3 py-2 text-left text-sm text-white";
|
|
2263
|
+
const agentWidgetAssistantBubbleClass = "inline-block max-w-[82%] rounded-md border border-zinc-200 bg-white px-3 py-2 text-left text-sm text-zinc-950";
|
|
2264
|
+
const agentWidgetToolbarButtonClass = "rounded-md p-1 text-zinc-600 hover:bg-zinc-100";
|
|
2265
|
+
function raybaseAgentWidgetLabels(title, labels = {}) {
|
|
2266
|
+
const conversationTitle = `${title} conversation`;
|
|
2267
|
+
return {
|
|
2268
|
+
cancel: "Cancel",
|
|
2269
|
+
close: `Close ${title}`,
|
|
2270
|
+
conversationFallback: conversationTitle,
|
|
2271
|
+
conversations: `Open ${title} conversations`,
|
|
2272
|
+
deleteConversation: `Delete ${conversationTitle}`,
|
|
2273
|
+
empty: "How can I help?",
|
|
2274
|
+
newConversation: `New ${conversationTitle}`,
|
|
2275
|
+
noConversations: "No conversations yet",
|
|
2276
|
+
open: `Open ${title}`,
|
|
2277
|
+
placeholder: `Ask ${title}`,
|
|
2278
|
+
send: "Send",
|
|
2279
|
+
syncing: "Syncing",
|
|
2280
|
+
thinking: "Thinking",
|
|
2281
|
+
tryAgain: "Try again",
|
|
2282
|
+
...labels
|
|
2283
|
+
};
|
|
2284
|
+
}
|
|
2285
|
+
function agentConversationLabel(conversation, fallback) {
|
|
2286
|
+
return conversation.title || conversation.route || fallback;
|
|
2287
|
+
}
|
|
2288
|
+
function agentConversationMeta(conversation) {
|
|
2289
|
+
const date = new Date(conversation.lastActiveAt || conversation.updatedAt || conversation.createdAt);
|
|
2290
|
+
if (Number.isNaN(date.getTime()))
|
|
2291
|
+
return conversation.surface;
|
|
2292
|
+
return `${conversation.surface} · ${date.toLocaleString([], { month: "short", day: "numeric", hour: "numeric", minute: "2-digit" })}`;
|
|
2293
|
+
}
|
|
2294
|
+
function compareAgentConversations(left, right) {
|
|
2295
|
+
if (Boolean(left.pinnedAt) !== Boolean(right.pinnedAt))
|
|
2296
|
+
return left.pinnedAt ? -1 : 1;
|
|
2297
|
+
if (left.pinnedAt && right.pinnedAt && left.pinnedAt !== right.pinnedAt)
|
|
2298
|
+
return right.pinnedAt.localeCompare(left.pinnedAt);
|
|
2299
|
+
return (right.lastActiveAt || right.updatedAt).localeCompare(left.lastActiveAt || left.updatedAt);
|
|
2300
|
+
}
|
|
2301
|
+
export function isVisibleRaybaseAgentMessagePart(part) {
|
|
2302
|
+
return part.type !== raybaseAgentDataPartTypes.modelMessages;
|
|
2303
|
+
}
|
|
2304
|
+
export function isRenderableRaybaseAgentMessagePart(part) {
|
|
2305
|
+
if (!isVisibleRaybaseAgentMessagePart(part))
|
|
2306
|
+
return false;
|
|
2307
|
+
if (part.type === "text")
|
|
2308
|
+
return Boolean(part.text?.trim());
|
|
2309
|
+
if (part.type === "file")
|
|
2310
|
+
return typeof part.mediaType === "string" && Boolean(part.mediaType);
|
|
2311
|
+
if (part.type === raybaseAgentDataPartTypes.sources)
|
|
2312
|
+
return Array.isArray(part.data?.sources) && part.data.sources.length > 0;
|
|
2313
|
+
if (part.type === raybaseAgentDataPartTypes.supportRequestCreated)
|
|
2314
|
+
return Boolean(part.data);
|
|
2315
|
+
if (part.type === raybaseAgentDataPartTypes.turnError)
|
|
2316
|
+
return Boolean(part.data) && part.data.superseded !== true;
|
|
2317
|
+
return false;
|
|
2318
|
+
}
|
|
2319
|
+
/** The turn-error marker of a message, or null when the message is a normal turn. */
|
|
2320
|
+
export function raybaseAgentMessageTurnError(message) {
|
|
2321
|
+
return raybaseAgentTurnError(message);
|
|
2322
|
+
}
|
|
2323
|
+
/**
|
|
2324
|
+
* The failed last turn a "Try again" affordance should offer to retry, or null.
|
|
2325
|
+
* Superseded failures (already retried) and mid-run snapshots never qualify —
|
|
2326
|
+
* this is the single error surface for both live and reloaded conversations.
|
|
2327
|
+
*/
|
|
2328
|
+
export function raybaseAgentRetryableTurnError(snapshot) {
|
|
2329
|
+
if (snapshot.isRunning)
|
|
2330
|
+
return null;
|
|
2331
|
+
const last = snapshot.messages[snapshot.messages.length - 1];
|
|
2332
|
+
if (!last)
|
|
2333
|
+
return null;
|
|
2334
|
+
const turnError = raybaseAgentTurnError(last);
|
|
2335
|
+
return turnError && !turnError.superseded ? turnError : null;
|
|
2336
|
+
}
|
|
2337
|
+
export function raybaseVoiceNoteFromParts(parts) {
|
|
2338
|
+
const marker = parts.find((part) => part.type === "data-voice-note");
|
|
2339
|
+
const duration = marker?.data && typeof marker.data === "object"
|
|
2340
|
+
? Number(marker.data.durationSeconds)
|
|
2341
|
+
: Number.NaN;
|
|
2342
|
+
const audio = parts.find((part) => part.type === "file"
|
|
2343
|
+
&& typeof part.mediaType === "string"
|
|
2344
|
+
&& part.mediaType.startsWith("audio/")
|
|
2345
|
+
&& typeof part.url === "string");
|
|
2346
|
+
const fileId = audio && typeof audio.url === "string" ? raybaseFileId(audio.url) : null;
|
|
2347
|
+
if (!marker || !fileId || !Number.isFinite(duration) || duration < 0)
|
|
2348
|
+
return null;
|
|
2349
|
+
return {
|
|
2350
|
+
durationSeconds: duration,
|
|
2351
|
+
fileId,
|
|
2352
|
+
transcript: parts
|
|
2353
|
+
.filter((part) => part.type === "text" && typeof part.text === "string")
|
|
2354
|
+
.map((part) => part.text.trim())
|
|
2355
|
+
.filter(Boolean)
|
|
2356
|
+
.join("\n\n")
|
|
2357
|
+
};
|
|
2358
|
+
}
|
|
2359
|
+
/** The bucket's normal file route; it authorizes the read on its own. */
|
|
2360
|
+
export function raybaseAttachmentDownloadUrl(bucket, fileId) {
|
|
2361
|
+
return `/api/files/${encodeURIComponent(bucket)}/${encodeURIComponent(fileId)}/download`;
|
|
2362
|
+
}
|
|
2363
|
+
export function voiceNoteDownloadUrl(bucket, fileId) {
|
|
2364
|
+
return raybaseAttachmentDownloadUrl(bucket, fileId);
|
|
2365
|
+
}
|
|
2366
|
+
export function raybaseVoiceNotePlaybackState(input) {
|
|
2367
|
+
const expired = input.expired || !input.attachmentBucket;
|
|
2368
|
+
return {
|
|
2369
|
+
expired,
|
|
2370
|
+
label: expired ? "Voice note expired" : `Voice note · ${voiceNoteDurationLabel(input.durationSeconds)}`,
|
|
2371
|
+
transcriptVisible: expired || input.showTranscript
|
|
2372
|
+
};
|
|
2373
|
+
}
|
|
2374
|
+
function RaybaseAgentVoiceNoteView(props) {
|
|
2375
|
+
const [expired, setExpired] = useState(!props.attachmentBucket);
|
|
2376
|
+
const [showTranscript, setShowTranscript] = useState(false);
|
|
2377
|
+
const playback = raybaseVoiceNotePlaybackState({
|
|
2378
|
+
attachmentBucket: props.attachmentBucket,
|
|
2379
|
+
durationSeconds: props.voiceNote.durationSeconds,
|
|
2380
|
+
expired,
|
|
2381
|
+
showTranscript
|
|
2382
|
+
});
|
|
2383
|
+
return createElement("div", { className: "space-y-2 text-left", "data-raybase-voice-note": true }, createElement("div", { className: "flex items-center gap-2 text-xs font-medium" }, createElement(AgentMicIcon, { className: "h-3.5 w-3.5" }), playback.label), playback.expired
|
|
2384
|
+
? null
|
|
2385
|
+
: createElement("audio", {
|
|
2386
|
+
controls: true,
|
|
2387
|
+
preload: "metadata",
|
|
2388
|
+
src: voiceNoteDownloadUrl(props.attachmentBucket, props.voiceNote.fileId),
|
|
2389
|
+
onError: () => setExpired(true),
|
|
2390
|
+
className: "max-w-full"
|
|
2391
|
+
}), props.voiceNote.transcript
|
|
2392
|
+
? createElement("div", null, playback.expired
|
|
2393
|
+
? createElement("span", { className: "text-xs text-zinc-500" }, "The audio is no longer available; the transcript remains.")
|
|
2394
|
+
: createElement("button", {
|
|
2395
|
+
type: "button",
|
|
2396
|
+
className: "text-xs underline underline-offset-2",
|
|
2397
|
+
onClick: () => setShowTranscript((value) => !value),
|
|
2398
|
+
"aria-expanded": playback.transcriptVisible
|
|
2399
|
+
}, playback.transcriptVisible ? "Hide transcript" : "Show transcript"), createElement("div", { className: playback.transcriptVisible ? "mt-2 text-sm" : "sr-only", "data-raybase-voice-transcript": true }, props.voiceNote.transcript))
|
|
2400
|
+
: null);
|
|
2401
|
+
}
|
|
2402
|
+
function raybaseFileId(value) {
|
|
2403
|
+
if (!value.startsWith("raybase-file:"))
|
|
2404
|
+
return null;
|
|
2405
|
+
const fileId = value.slice("raybase-file:".length).trim();
|
|
2406
|
+
return fileId && !/[\s/?#]/.test(fileId) ? fileId : null;
|
|
2407
|
+
}
|
|
2408
|
+
export function RaybaseAgentMessagePartView(props) {
|
|
2409
|
+
const { part } = props;
|
|
2410
|
+
if (part.type === "text") {
|
|
2411
|
+
return props.role === "user"
|
|
2412
|
+
? createElement(RaybaseAgentPlainText, { text: part.text ?? "" })
|
|
2413
|
+
: createElement(RaybaseAgentMarkdown, { markdown: part.text ?? "" });
|
|
2414
|
+
}
|
|
2415
|
+
if (part.type === raybaseAgentDataPartTypes.modelMessages)
|
|
2416
|
+
return null;
|
|
2417
|
+
if (part.type === "file" && typeof part.mediaType === "string") {
|
|
2418
|
+
const fileId = typeof part.url === "string" ? raybaseFileId(part.url) : null;
|
|
2419
|
+
if (part.mediaType.startsWith("audio/")) {
|
|
2420
|
+
return fileId && props.attachmentBucket
|
|
2421
|
+
? createElement("audio", {
|
|
2422
|
+
controls: true,
|
|
2423
|
+
preload: "metadata",
|
|
2424
|
+
src: raybaseAttachmentDownloadUrl(props.attachmentBucket, fileId)
|
|
2425
|
+
})
|
|
2426
|
+
: null;
|
|
2427
|
+
}
|
|
2428
|
+
if (part.mediaType.startsWith("image/") && fileId && props.attachmentBucket) {
|
|
2429
|
+
return createElement("img", {
|
|
2430
|
+
alt: typeof part.filename === "string" ? part.filename : "Attached image",
|
|
2431
|
+
className: "max-w-full rounded",
|
|
2432
|
+
loading: "lazy",
|
|
2433
|
+
src: raybaseAttachmentDownloadUrl(props.attachmentBucket, fileId)
|
|
2434
|
+
});
|
|
2435
|
+
}
|
|
2436
|
+
return createElement(RaybaseAgentPlainText, {
|
|
2437
|
+
text: agentFilePlaceholder({
|
|
2438
|
+
type: "file",
|
|
2439
|
+
mediaType: part.mediaType,
|
|
2440
|
+
url: typeof part.url === "string" ? part.url : "",
|
|
2441
|
+
...(typeof part.filename === "string" && part.filename.trim() ? { filename: part.filename.trim() } : {})
|
|
2442
|
+
})
|
|
2443
|
+
});
|
|
2444
|
+
}
|
|
2445
|
+
if (part.type === raybaseAgentDataPartTypes.sources)
|
|
2446
|
+
return createElement(RaybaseSourceChips, { sources: Array.isArray(part.data?.sources) ? part.data.sources : [] });
|
|
2447
|
+
if (part.type === raybaseAgentDataPartTypes.supportRequestCreated)
|
|
2448
|
+
return createElement(RaybaseSupportRequestCard, { supportRequest: part.data });
|
|
2449
|
+
if (part.type === raybaseAgentDataPartTypes.turnError) {
|
|
2450
|
+
const turnError = part.data;
|
|
2451
|
+
return turnError && turnError.superseded !== true ? createElement(RaybaseTurnErrorNotice, { turnError }) : null;
|
|
2452
|
+
}
|
|
2453
|
+
return null;
|
|
2454
|
+
}
|
|
2455
|
+
export function RaybaseTurnErrorNotice(props) {
|
|
2456
|
+
return createElement("div", { "data-raybase-turn-error": true, role: "alert", className: "text-sm text-red-800" }, props.turnError.message);
|
|
2457
|
+
}
|
|
2458
|
+
export const RaybaseAgentMarkdown = memo(function RaybaseAgentMarkdown(props) {
|
|
2459
|
+
return createElement(ReactMarkdown, {
|
|
2460
|
+
components: raybaseMarkdownComponents,
|
|
2461
|
+
remarkPlugins: raybaseMarkdownRemarkPlugins
|
|
2462
|
+
}, props.markdown);
|
|
2463
|
+
});
|
|
2464
|
+
export function RaybaseAgentPlainText(props) {
|
|
2465
|
+
return createElement("p", { style: plainTextStyle }, props.text);
|
|
2466
|
+
}
|
|
2467
|
+
// `remarkRaybaseLatexProse` runs at render time only: the stored transcript
|
|
2468
|
+
// keeps whatever the model actually said, so the mapping can change later
|
|
2469
|
+
// without rewriting history.
|
|
2470
|
+
const raybaseMarkdownRemarkPlugins = [remarkGfm, remarkRaybaseLatexProse];
|
|
2471
|
+
const plainTextStyle = {
|
|
2472
|
+
margin: "0.35em 0",
|
|
2473
|
+
whiteSpace: "pre-wrap"
|
|
2474
|
+
};
|
|
2475
|
+
const raybaseMarkdownComponents = {
|
|
2476
|
+
a: ({ node: _node, ...props }) => createElement("a", {
|
|
2477
|
+
...props,
|
|
2478
|
+
rel: "noreferrer",
|
|
2479
|
+
target: "_blank",
|
|
2480
|
+
style: mergeStyle(props.style, { color: "inherit", textDecoration: "underline", textUnderlineOffset: "0.14em" })
|
|
2481
|
+
}),
|
|
2482
|
+
blockquote: ({ node: _node, ...props }) => createElement("blockquote", {
|
|
2483
|
+
...props,
|
|
2484
|
+
style: mergeStyle(props.style, { borderLeft: "3px solid currentColor", margin: "0.6em 0", opacity: 0.78, paddingLeft: "0.8em" })
|
|
2485
|
+
}),
|
|
2486
|
+
code: ({ node: _node, ...props }) => createElement("code", {
|
|
2487
|
+
...props,
|
|
2488
|
+
style: mergeStyle(props.style, {
|
|
2489
|
+
fontSize: "0.92em"
|
|
2490
|
+
})
|
|
2491
|
+
}),
|
|
2492
|
+
li: ({ node: _node, ...props }) => createElement("li", {
|
|
2493
|
+
...props,
|
|
2494
|
+
style: mergeStyle(props.style, { margin: "0.18em 0" })
|
|
2495
|
+
}),
|
|
2496
|
+
// `listStyleType: revert` is doing real work here, and it is not decoration.
|
|
2497
|
+
// Tailwind's preflight — which every scaffolded Raybase app loads — sets
|
|
2498
|
+
// `list-style: none` on all `ol`/`ul`, so an agent that wrote a bulleted list
|
|
2499
|
+
// rendered as unmarked lines under an unexplained 1.4em indent: the padding
|
|
2500
|
+
// below survived the reset and the markers did not. These styles are inline,
|
|
2501
|
+
// so they outrank any host stylesheet, and `revert` rolls the property back
|
|
2502
|
+
// past the host's author-origin reset to the browser's own value — which
|
|
2503
|
+
// keeps what an explicit `disc`/`decimal` would throw away: nested bullets
|
|
2504
|
+
// still alternate disc/circle/square by depth, and an `ol` still honors its
|
|
2505
|
+
// own `type`. Everything else in this map is set the same way and for the
|
|
2506
|
+
// same reason: agent markdown has to read correctly in a host whose CSS
|
|
2507
|
+
// Core has never seen.
|
|
2508
|
+
ol: ({ node: _node, ...props }) => createElement("ol", {
|
|
2509
|
+
...props,
|
|
2510
|
+
style: mergeStyle(props.style, { listStyleType: "revert", margin: "0.45em 0", paddingLeft: "1.4em" })
|
|
2511
|
+
}),
|
|
2512
|
+
p: ({ node: _node, ...props }) => createElement("p", {
|
|
2513
|
+
...props,
|
|
2514
|
+
style: mergeStyle(props.style, { ...plainTextStyle })
|
|
2515
|
+
}),
|
|
2516
|
+
pre: ({ node: _node, ...props }) => createElement("pre", {
|
|
2517
|
+
...props,
|
|
2518
|
+
style: mergeStyle(props.style, {
|
|
2519
|
+
background: "color-mix(in srgb, currentColor 9%, transparent)",
|
|
2520
|
+
borderRadius: "0.375rem",
|
|
2521
|
+
margin: "0.6em 0",
|
|
2522
|
+
overflowX: "auto",
|
|
2523
|
+
padding: "0.65em 0.75em"
|
|
2524
|
+
})
|
|
2525
|
+
}),
|
|
2526
|
+
table: ({ node: _node, ...props }) => createElement("div", { style: { overflowX: "auto" } }, createElement("table", { ...props, style: mergeStyle(props.style, { borderCollapse: "collapse", margin: "0.6em 0", width: "100%" }) })),
|
|
2527
|
+
td: ({ node: _node, ...props }) => createElement("td", {
|
|
2528
|
+
...props,
|
|
2529
|
+
style: mergeStyle(props.style, { border: "1px solid color-mix(in srgb, currentColor 22%, transparent)", padding: "0.3em 0.45em" })
|
|
2530
|
+
}),
|
|
2531
|
+
th: ({ node: _node, ...props }) => createElement("th", {
|
|
2532
|
+
...props,
|
|
2533
|
+
style: mergeStyle(props.style, { border: "1px solid color-mix(in srgb, currentColor 22%, transparent)", padding: "0.3em 0.45em", textAlign: "left" })
|
|
2534
|
+
}),
|
|
2535
|
+
ul: ({ node: _node, ...props }) => createElement("ul", {
|
|
2536
|
+
...props,
|
|
2537
|
+
style: mergeStyle(props.style, { listStyleType: "revert", margin: "0.45em 0", paddingLeft: "1.4em" })
|
|
2538
|
+
})
|
|
2539
|
+
};
|
|
2540
|
+
function mergeStyle(base, overrides) {
|
|
2541
|
+
return { ...base, ...overrides };
|
|
2542
|
+
}
|
|
2543
|
+
export function RaybaseSourceChips(props) {
|
|
2544
|
+
if (!props.sources.length)
|
|
2545
|
+
return null;
|
|
2546
|
+
return createElement("div", { "data-raybase-sources": true }, props.sources.map((source, index) => source.url
|
|
2547
|
+
? createElement("a", { key: source.sourceId, href: source.url, target: "_blank", rel: "noreferrer" }, `${index + 1}. ${source.title}`)
|
|
2548
|
+
: createElement("span", { key: source.sourceId }, `${index + 1}. ${source.title}`)));
|
|
2549
|
+
}
|
|
2550
|
+
export function RaybaseSupportRequestCard(props) {
|
|
2551
|
+
return createElement("div", { "data-raybase-support-request": props.supportRequest.supportRequestId }, createElement("strong", null, props.supportRequest.subject), createElement("span", null, props.supportRequest.status));
|
|
2552
|
+
}
|
|
2553
|
+
export function raybaseMessageToThreadMessage(message, currentUserId = null, attachmentBucket = null) {
|
|
2554
|
+
// A failed turn renders through its turn-error part alone; the text part
|
|
2555
|
+
// repeats the same public copy for clients that only read message text.
|
|
2556
|
+
const turnError = raybaseAgentTurnError(message);
|
|
2557
|
+
const parts = turnError ? message.parts.filter((part) => part.type !== "text") : message.parts;
|
|
2558
|
+
const author = message.author ?? normalizeMessageAuthor(undefined, message.role);
|
|
2559
|
+
return {
|
|
2560
|
+
id: message.id,
|
|
2561
|
+
role: message.role,
|
|
2562
|
+
content: raybaseMessagePartsToThreadParts(parts, { attachmentBucket, role: message.role }),
|
|
2563
|
+
createdAt: new Date(message.createdAt),
|
|
2564
|
+
metadata: {
|
|
2565
|
+
custom: {
|
|
2566
|
+
raybaseAuthor: author,
|
|
2567
|
+
raybaseSelf: author.kind === "user"
|
|
2568
|
+
&& Boolean(currentUserId)
|
|
2569
|
+
&& author.userId === currentUserId,
|
|
2570
|
+
raybaseEditedAt: message.editedAt,
|
|
2571
|
+
raybaseRemoved: message.removed,
|
|
2572
|
+
raybaseReactions: message.reactions,
|
|
2573
|
+
raybaseParts: message.parts,
|
|
2574
|
+
raybaseAttachmentBucket: attachmentBucket
|
|
2575
|
+
}
|
|
2576
|
+
}
|
|
2577
|
+
};
|
|
2578
|
+
}
|
|
2579
|
+
export function raybaseMessagePartsToThreadParts(parts, options = {}) {
|
|
2580
|
+
return parts.flatMap((part) => raybaseMessagePartToThreadPart(part, options));
|
|
2581
|
+
}
|
|
2582
|
+
export function raybaseMessagePartToThreadPart(part, options = {}) {
|
|
2583
|
+
if (part.type === "text") {
|
|
2584
|
+
const text = part.text ?? "";
|
|
2585
|
+
return text.trim() ? [{ type: "text", text }] : [];
|
|
2586
|
+
}
|
|
2587
|
+
if (part.type === "file") {
|
|
2588
|
+
const mediaType = typeof part.mediaType === "string" ? part.mediaType : "";
|
|
2589
|
+
// Audio belongs to the voice-note view, which reads the raw parts and
|
|
2590
|
+
// owns the whole bubble; a second player here would double it.
|
|
2591
|
+
if (mediaType.startsWith("audio/"))
|
|
2592
|
+
return [];
|
|
2593
|
+
const fileId = typeof part.url === "string" ? raybaseFileId(part.url) : null;
|
|
2594
|
+
const filename = typeof part.filename === "string" && part.filename.trim() ? part.filename.trim() : undefined;
|
|
2595
|
+
if (mediaType.startsWith("image/")
|
|
2596
|
+
&& fileId
|
|
2597
|
+
&& options.attachmentBucket
|
|
2598
|
+
&& options.role !== "assistant") {
|
|
2599
|
+
return [{
|
|
2600
|
+
type: "image",
|
|
2601
|
+
image: raybaseAttachmentDownloadUrl(options.attachmentBucket, fileId),
|
|
2602
|
+
...(filename ? { filename } : {})
|
|
2603
|
+
}];
|
|
2604
|
+
}
|
|
2605
|
+
// Unreadable here — no bucket to address it through, or a shape this
|
|
2606
|
+
// renderer cannot show. The stand-in is what the member sees instead.
|
|
2607
|
+
const standIn = agentFilePlaceholder({ type: "file", mediaType, url: typeof part.url === "string" ? part.url : "", ...(filename ? { filename } : {}) });
|
|
2608
|
+
return standIn ? [{ type: "text", text: standIn }] : [];
|
|
2609
|
+
}
|
|
2610
|
+
if (part.type === raybaseAgentDataPartTypes.modelMessages)
|
|
2611
|
+
return [];
|
|
2612
|
+
if (part.type === raybaseAgentDataPartTypes.sources) {
|
|
2613
|
+
const sources = Array.isArray(part.data?.sources) ? part.data.sources : [];
|
|
2614
|
+
return sources.length ? [{ type: "data", name: raybaseSourcesDataPartName, data: { sources } }] : [];
|
|
2615
|
+
}
|
|
2616
|
+
if (part.type === raybaseAgentDataPartTypes.supportRequestCreated && part.data) {
|
|
2617
|
+
return [{ type: "data", name: raybaseSupportRequestCreatedDataPartName, data: part.data }];
|
|
2618
|
+
}
|
|
2619
|
+
if (part.type === raybaseAgentDataPartTypes.turnError) {
|
|
2620
|
+
const turnError = part.data;
|
|
2621
|
+
if (!turnError || turnError.superseded === true)
|
|
2622
|
+
return [];
|
|
2623
|
+
return [{ type: "data", name: raybaseTurnErrorDataPartName, data: turnError }];
|
|
2624
|
+
}
|
|
2625
|
+
if (part.type.startsWith("data-"))
|
|
2626
|
+
return [{ type: "data", name: part.type.slice("data-".length), data: part.data }];
|
|
2627
|
+
return [];
|
|
2628
|
+
}
|
|
2629
|
+
export function snapshotMessages(snapshot) {
|
|
2630
|
+
return snapshot.messages;
|
|
2631
|
+
}
|
|
2632
|
+
function raybaseAgentHeaders(options) {
|
|
2633
|
+
const headers = { "content-type": "application/json" };
|
|
2634
|
+
if (options.route)
|
|
2635
|
+
headers["x-raybase-agent-route"] = options.route;
|
|
2636
|
+
if (options.surface)
|
|
2637
|
+
headers["x-raybase-agent-surface"] = options.surface;
|
|
2638
|
+
return headers;
|
|
2639
|
+
}
|
|
2640
|
+
function defaultConversationStorageKey(options) {
|
|
2641
|
+
return [
|
|
2642
|
+
"raybase",
|
|
2643
|
+
"agent",
|
|
2644
|
+
options.agentName,
|
|
2645
|
+
options.surface ?? "app",
|
|
2646
|
+
"conversation"
|
|
2647
|
+
].map((part) => encodeURIComponent(part)).join(":");
|
|
2648
|
+
}
|
|
2649
|
+
function readStoredConversationId(storageKey) {
|
|
2650
|
+
return readStorageValue(storageKey, "session") ?? readStorageValue(storageKey, "local");
|
|
2651
|
+
}
|
|
2652
|
+
function writeStoredConversationId(storageKey, conversationId, kind) {
|
|
2653
|
+
const storage = browserStorage(kind);
|
|
2654
|
+
if (!storage)
|
|
2655
|
+
return;
|
|
2656
|
+
try {
|
|
2657
|
+
storage.setItem(storageKey, conversationId);
|
|
2658
|
+
}
|
|
2659
|
+
catch {
|
|
2660
|
+
// Storage can be unavailable in private or locked-down browser contexts.
|
|
2661
|
+
}
|
|
2662
|
+
}
|
|
2663
|
+
function removeStoredConversationId(storageKey, kind) {
|
|
2664
|
+
const storage = browserStorage(kind);
|
|
2665
|
+
if (!storage)
|
|
2666
|
+
return;
|
|
2667
|
+
try {
|
|
2668
|
+
storage.removeItem(storageKey);
|
|
2669
|
+
}
|
|
2670
|
+
catch {
|
|
2671
|
+
// Storage can be unavailable in private or locked-down browser contexts.
|
|
2672
|
+
}
|
|
2673
|
+
}
|
|
2674
|
+
function readStorageValue(storageKey, kind) {
|
|
2675
|
+
const storage = browserStorage(kind);
|
|
2676
|
+
if (!storage)
|
|
2677
|
+
return null;
|
|
2678
|
+
try {
|
|
2679
|
+
const value = storage.getItem(storageKey)?.trim();
|
|
2680
|
+
return value || null;
|
|
2681
|
+
}
|
|
2682
|
+
catch {
|
|
2683
|
+
return null;
|
|
2684
|
+
}
|
|
2685
|
+
}
|
|
2686
|
+
function browserStorage(kind) {
|
|
2687
|
+
if (typeof window === "undefined")
|
|
2688
|
+
return null;
|
|
2689
|
+
try {
|
|
2690
|
+
return kind === "session" ? window.sessionStorage : window.localStorage;
|
|
2691
|
+
}
|
|
2692
|
+
catch {
|
|
2693
|
+
return null;
|
|
2694
|
+
}
|
|
2695
|
+
}
|
|
2696
|
+
function normalizeMessageParts(parts, text) {
|
|
2697
|
+
const validParts = Array.isArray(parts)
|
|
2698
|
+
? parts.filter((part) => Boolean(part && typeof part === "object" && typeof part.type === "string"))
|
|
2699
|
+
: [];
|
|
2700
|
+
if (validParts.length)
|
|
2701
|
+
return validParts;
|
|
2702
|
+
return typeof text === "string" && text ? [{ type: "text", text }] : [{ type: "text", text: "" }];
|
|
2703
|
+
}
|
|
2704
|
+
function normalizeSubmitParts(parts, message) {
|
|
2705
|
+
if (parts) {
|
|
2706
|
+
return parts.filter((part) => Boolean(part && typeof part === "object" && typeof part.type === "string"));
|
|
2707
|
+
}
|
|
2708
|
+
return message ? [{ type: "text", text: message }] : [];
|
|
2709
|
+
}
|
|
2710
|
+
function disabledAttachmentsCapability() {
|
|
2711
|
+
return { enabled: false, bucket: null, maxPerMessage: 0, mediaTypes: [] };
|
|
2712
|
+
}
|
|
2713
|
+
/**
|
|
2714
|
+
* Older servers report only the voice-note capability. Its bucket is the
|
|
2715
|
+
* attachment bucket, so it stands in until the server sends its own.
|
|
2716
|
+
*/
|
|
2717
|
+
function normalizeAttachmentsCapability(value, voiceNotes) {
|
|
2718
|
+
const bucket = typeof value?.bucket === "string" && value.bucket.trim()
|
|
2719
|
+
? value.bucket.trim()
|
|
2720
|
+
: typeof voiceNotes?.bucket === "string" && voiceNotes.bucket.trim()
|
|
2721
|
+
? voiceNotes.bucket.trim()
|
|
2722
|
+
: null;
|
|
2723
|
+
if (!value?.enabled && !bucket)
|
|
2724
|
+
return disabledAttachmentsCapability();
|
|
2725
|
+
return {
|
|
2726
|
+
enabled: value?.enabled !== false,
|
|
2727
|
+
bucket,
|
|
2728
|
+
maxPerMessage: Number.isInteger(value?.maxPerMessage) && Number(value?.maxPerMessage) > 0
|
|
2729
|
+
? Number(value?.maxPerMessage)
|
|
2730
|
+
: 0,
|
|
2731
|
+
mediaTypes: Array.isArray(value?.mediaTypes)
|
|
2732
|
+
? value.mediaTypes.filter((mediaType) => typeof mediaType === "string")
|
|
2733
|
+
: []
|
|
2734
|
+
};
|
|
2735
|
+
}
|
|
2736
|
+
function disabledVoiceNotesCapability() {
|
|
2737
|
+
return { enabled: false, maxSeconds: defaultVoiceNoteMaxSeconds, bucket: null };
|
|
2738
|
+
}
|
|
2739
|
+
function normalizeVoiceNotesCapability(value) {
|
|
2740
|
+
if (!value?.enabled)
|
|
2741
|
+
return disabledVoiceNotesCapability();
|
|
2742
|
+
return {
|
|
2743
|
+
enabled: true,
|
|
2744
|
+
maxSeconds: Number.isInteger(value.maxSeconds) && Number(value.maxSeconds) > 0
|
|
2745
|
+
? Number(value.maxSeconds)
|
|
2746
|
+
: defaultVoiceNoteMaxSeconds,
|
|
2747
|
+
bucket: typeof value.bucket === "string" && value.bucket.trim() ? value.bucket.trim() : null
|
|
2748
|
+
};
|
|
2749
|
+
}
|
|
2750
|
+
function notifyDataChangedParts(options, conversationId, parts, notified) {
|
|
2751
|
+
for (const part of parts) {
|
|
2752
|
+
if (part.type !== raybaseAgentDataPartTypes.dataChanged || !part.data || typeof part.data !== "object")
|
|
2753
|
+
continue;
|
|
2754
|
+
const data = part.data;
|
|
2755
|
+
if (typeof data.actionName !== "string" || typeof data.toolName !== "string")
|
|
2756
|
+
continue;
|
|
2757
|
+
const event = {
|
|
2758
|
+
actionName: data.actionName,
|
|
2759
|
+
toolName: data.toolName,
|
|
2760
|
+
toolCallId: typeof data.toolCallId === "string" ? data.toolCallId : undefined,
|
|
2761
|
+
resource: data.resource ?? null,
|
|
2762
|
+
effects: Array.isArray(data.effects) ? data.effects.map((effect) => String(effect)) : [],
|
|
2763
|
+
agentName: options.agentName,
|
|
2764
|
+
conversationId,
|
|
2765
|
+
route: options.route ?? "/",
|
|
2766
|
+
surface: options.surface ?? "app"
|
|
2767
|
+
};
|
|
2768
|
+
const key = part.id ?? `${event.agentName}:${event.conversationId ?? ""}:${event.actionName}:${event.toolCallId ?? ""}:${JSON.stringify(event.resource)}:${event.effects.join(",")}`;
|
|
2769
|
+
if (notified.has(key))
|
|
2770
|
+
continue;
|
|
2771
|
+
notified.add(key);
|
|
2772
|
+
dispatchRaybaseDataChanged(event);
|
|
2773
|
+
void Promise.resolve(options.onDataChanged?.(event)).catch(() => { });
|
|
2774
|
+
}
|
|
2775
|
+
}
|
|
2776
|
+
function dispatchRaybaseDataChanged(event) {
|
|
2777
|
+
if (typeof window === "undefined")
|
|
2778
|
+
return;
|
|
2779
|
+
window.dispatchEvent(new CustomEvent("raybase:data-changed", { detail: event }));
|
|
2780
|
+
}
|
|
2781
|
+
function normalizeSnapshotMessages(messages, memberNames = new Map(), messageRunIds) {
|
|
2782
|
+
if (!Array.isArray(messages))
|
|
2783
|
+
return [];
|
|
2784
|
+
return messages.flatMap((message) => {
|
|
2785
|
+
if (!message || typeof message !== "object")
|
|
2786
|
+
return [];
|
|
2787
|
+
const record = message;
|
|
2788
|
+
if (record.role !== "user" && record.role !== "assistant")
|
|
2789
|
+
return [];
|
|
2790
|
+
if (isHiddenTranscriptMessage(record))
|
|
2791
|
+
return [];
|
|
2792
|
+
const id = typeof record.id === "string" ? record.id : randomClientId("agent_msg");
|
|
2793
|
+
const createdAt = typeof record.createdAt === "string" ? record.createdAt : new Date().toISOString();
|
|
2794
|
+
const raybase = record.metadata && typeof record.metadata === "object" && !Array.isArray(record.metadata)
|
|
2795
|
+
? record.metadata.raybase
|
|
2796
|
+
: undefined;
|
|
2797
|
+
const mutation = raybase && typeof raybase === "object" && !Array.isArray(raybase)
|
|
2798
|
+
? raybase
|
|
2799
|
+
: {};
|
|
2800
|
+
if (record.role === "assistant" && typeof mutation.runId === "string" && mutation.runId.trim()) {
|
|
2801
|
+
messageRunIds?.set(id, mutation.runId);
|
|
2802
|
+
}
|
|
2803
|
+
const reactions = Object.fromEntries(Object.entries(mutation.reactions && typeof mutation.reactions === "object" && !Array.isArray(mutation.reactions)
|
|
2804
|
+
? mutation.reactions
|
|
2805
|
+
: {}).filter((entry) => typeof entry[1] === "string"));
|
|
2806
|
+
return [{
|
|
2807
|
+
id,
|
|
2808
|
+
role: record.role,
|
|
2809
|
+
parts: normalizeTranscriptMessageParts(record.parts, record.role),
|
|
2810
|
+
createdAt,
|
|
2811
|
+
author: normalizeMessageAuthor(record.author ?? roomMessageAuthorFromMetadata(record.metadata), record.role, memberNames),
|
|
2812
|
+
editedAt: typeof mutation.editedAt === "string" ? mutation.editedAt : null,
|
|
2813
|
+
removed: mutation.removed === true,
|
|
2814
|
+
reactions
|
|
2815
|
+
}];
|
|
2816
|
+
});
|
|
2817
|
+
}
|
|
2818
|
+
function normalizeTranscriptMessageParts(parts, role) {
|
|
2819
|
+
if (!Array.isArray(parts))
|
|
2820
|
+
return [];
|
|
2821
|
+
return parts.flatMap((part) => {
|
|
2822
|
+
if (!part || typeof part !== "object" || Array.isArray(part))
|
|
2823
|
+
return [];
|
|
2824
|
+
const record = part;
|
|
2825
|
+
const type = typeof record.type === "string" ? record.type : "";
|
|
2826
|
+
if (type === "text" && typeof record.text === "string") {
|
|
2827
|
+
return [{ type: "text", text: record.text }];
|
|
2828
|
+
}
|
|
2829
|
+
// Attachments survive rehydration exactly as they arrive live: the stored
|
|
2830
|
+
// transcript carries the durable `raybase-file:` reference and, for a
|
|
2831
|
+
// voice note, its duration marker. Dropping either here is what used to
|
|
2832
|
+
// leave a reloaded conversation showing a text stand-in and no player.
|
|
2833
|
+
if (type === "file" && typeof record.mediaType === "string" && typeof record.url === "string") {
|
|
2834
|
+
return [{
|
|
2835
|
+
type: "file",
|
|
2836
|
+
mediaType: record.mediaType,
|
|
2837
|
+
url: record.url,
|
|
2838
|
+
...(typeof record.filename === "string" && record.filename.trim()
|
|
2839
|
+
? { filename: record.filename.trim() }
|
|
2840
|
+
: {})
|
|
2841
|
+
}];
|
|
2842
|
+
}
|
|
2843
|
+
if (type === "data-voice-note" && "data" in record) {
|
|
2844
|
+
return [{ type, data: record.data }];
|
|
2845
|
+
}
|
|
2846
|
+
if (role === "user"
|
|
2847
|
+
&& /^data-[a-z0-9][a-z0-9-]*$/.test(type)
|
|
2848
|
+
&& type !== "data-voice-note"
|
|
2849
|
+
&& type !== "data-raybase"
|
|
2850
|
+
&& !type.startsWith("data-raybase-")
|
|
2851
|
+
&& "data" in record) {
|
|
2852
|
+
return [{ type, data: record.data }];
|
|
2853
|
+
}
|
|
2854
|
+
// A data-changed part is the agent reporting what its own tool call did,
|
|
2855
|
+
// and the live room handler refreshes route data from it. It survives
|
|
2856
|
+
// here so a reloaded or fanned-out assistant message still carries it —
|
|
2857
|
+
// and only there: a member cannot author one, so on a user message it is
|
|
2858
|
+
// dropped with the rest of the `data-raybase-*` family (the branch above
|
|
2859
|
+
// already refuses those for user-authored parts).
|
|
2860
|
+
if (type === raybaseAgentDataPartTypes.sources
|
|
2861
|
+
|| type === raybaseAgentDataPartTypes.citations
|
|
2862
|
+
|| (type === raybaseAgentDataPartTypes.dataChanged && role === "assistant")
|
|
2863
|
+
|| type === raybaseAgentDataPartTypes.supportRequestCreated
|
|
2864
|
+
|| type === raybaseAgentDataPartTypes.turnError) {
|
|
2865
|
+
return [{
|
|
2866
|
+
type,
|
|
2867
|
+
...(typeof record.id === "string" ? { id: record.id } : {}),
|
|
2868
|
+
data: record.data
|
|
2869
|
+
}];
|
|
2870
|
+
}
|
|
2871
|
+
return [];
|
|
2872
|
+
});
|
|
2873
|
+
}
|
|
2874
|
+
function isHiddenTranscriptMessage(message) {
|
|
2875
|
+
const metadata = message.metadata;
|
|
2876
|
+
if (!metadata || typeof metadata !== "object" || Array.isArray(metadata))
|
|
2877
|
+
return false;
|
|
2878
|
+
const raybase = metadata.raybase;
|
|
2879
|
+
if (!raybase || typeof raybase !== "object" || Array.isArray(raybase))
|
|
2880
|
+
return false;
|
|
2881
|
+
const record = raybase;
|
|
2882
|
+
return record.hidden === true && record.entryKickoff === true;
|
|
2883
|
+
}
|
|
2884
|
+
function normalizeMessageAuthor(value, role, memberNames = new Map()) {
|
|
2885
|
+
const record = value && typeof value === "object" ? value : {};
|
|
2886
|
+
const kind = record.kind === "user" || record.kind === "agent" || record.kind === "app"
|
|
2887
|
+
? record.kind
|
|
2888
|
+
: role === "assistant" ? "agent" : "user";
|
|
2889
|
+
const userId = kind === "user" && typeof record.userId === "string" ? record.userId : null;
|
|
2890
|
+
return {
|
|
2891
|
+
kind,
|
|
2892
|
+
userId,
|
|
2893
|
+
name: typeof record.name === "string" ? record.name : userId ? memberNames.get(userId) ?? null : null
|
|
2894
|
+
};
|
|
2895
|
+
}
|
|
2896
|
+
function roomMessageAuthorFromMetadata(value) {
|
|
2897
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
2898
|
+
return undefined;
|
|
2899
|
+
const raybase = value.raybase;
|
|
2900
|
+
if (!raybase || typeof raybase !== "object" || Array.isArray(raybase))
|
|
2901
|
+
return undefined;
|
|
2902
|
+
return raybase.author;
|
|
2903
|
+
}
|
|
2904
|
+
function normalizeRoomPresenceMembers(value) {
|
|
2905
|
+
if (!Array.isArray(value))
|
|
2906
|
+
return [];
|
|
2907
|
+
return value.flatMap((member) => {
|
|
2908
|
+
if (!member || typeof member !== "object" || Array.isArray(member))
|
|
2909
|
+
return [];
|
|
2910
|
+
const record = member;
|
|
2911
|
+
if (typeof record.userId !== "string"
|
|
2912
|
+
|| typeof record.connectionId !== "string"
|
|
2913
|
+
|| typeof record.joinedAt !== "string")
|
|
2914
|
+
return [];
|
|
2915
|
+
return [{
|
|
2916
|
+
userId: record.userId,
|
|
2917
|
+
name: typeof record.name === "string" ? record.name : "Member",
|
|
2918
|
+
connectionId: record.connectionId,
|
|
2919
|
+
joinedAt: record.joinedAt
|
|
2920
|
+
}];
|
|
2921
|
+
});
|
|
2922
|
+
}
|
|
2923
|
+
function normalizeRoomMembers(value) {
|
|
2924
|
+
if (!Array.isArray(value))
|
|
2925
|
+
return [];
|
|
2926
|
+
return value.flatMap((member) => {
|
|
2927
|
+
if (!member || typeof member !== "object" || Array.isArray(member))
|
|
2928
|
+
return [];
|
|
2929
|
+
const record = member;
|
|
2930
|
+
if (typeof record.userId !== "string"
|
|
2931
|
+
|| (record.role !== "owner" && record.role !== "member")
|
|
2932
|
+
|| typeof record.status !== "string"
|
|
2933
|
+
|| typeof record.joinedAt !== "string")
|
|
2934
|
+
return [];
|
|
2935
|
+
return [{
|
|
2936
|
+
userId: record.userId,
|
|
2937
|
+
name: typeof record.name === "string" && record.name.trim() ? record.name : "Someone",
|
|
2938
|
+
role: record.role,
|
|
2939
|
+
status: record.status,
|
|
2940
|
+
joinedAt: record.joinedAt,
|
|
2941
|
+
lastReadAt: typeof record.lastReadAt === "string" ? record.lastReadAt : null
|
|
2942
|
+
}];
|
|
2943
|
+
});
|
|
2944
|
+
}
|
|
2945
|
+
function normalizeChapterMarkers(value) {
|
|
2946
|
+
if (!Array.isArray(value))
|
|
2947
|
+
return [];
|
|
2948
|
+
return value.flatMap((marker) => {
|
|
2949
|
+
if (!marker || typeof marker !== "object" || Array.isArray(marker))
|
|
2950
|
+
return [];
|
|
2951
|
+
const record = marker;
|
|
2952
|
+
if (typeof record.chapterId !== "string"
|
|
2953
|
+
|| !record.chapterId
|
|
2954
|
+
|| typeof record.startedAt !== "string"
|
|
2955
|
+
|| typeof record.endedAt !== "string")
|
|
2956
|
+
return [];
|
|
2957
|
+
return [{
|
|
2958
|
+
chapterId: record.chapterId,
|
|
2959
|
+
ordinal: Number.isInteger(record.ordinal) ? Number(record.ordinal) : 0,
|
|
2960
|
+
title: typeof record.title === "string" ? record.title : "",
|
|
2961
|
+
summary: typeof record.summary === "string" ? record.summary : "",
|
|
2962
|
+
messageCount: Number.isInteger(record.messageCount) && Number(record.messageCount) >= 0 ? Number(record.messageCount) : 0,
|
|
2963
|
+
startedAt: record.startedAt,
|
|
2964
|
+
endedAt: record.endedAt,
|
|
2965
|
+
reason: record.reason === "pending-rewrite" || record.reason === "unavailable" ? record.reason : "summary-only"
|
|
2966
|
+
}];
|
|
2967
|
+
});
|
|
2968
|
+
}
|
|
2969
|
+
function mergeChapterMarkers(current, incoming) {
|
|
2970
|
+
const byChapter = new Map(current.map((marker) => [marker.chapterId, marker]));
|
|
2971
|
+
for (const marker of incoming)
|
|
2972
|
+
byChapter.set(marker.chapterId, marker);
|
|
2973
|
+
return [...byChapter.values()].sort((left, right) => left.endedAt.localeCompare(right.endedAt) || left.ordinal - right.ordinal);
|
|
2974
|
+
}
|
|
2975
|
+
async function readAgentResponseBody(response) {
|
|
2976
|
+
return readResponseBody(response);
|
|
2977
|
+
}
|
|
2978
|
+
async function readResponseBody(response) {
|
|
2979
|
+
const text = await response.text().catch(() => "");
|
|
2980
|
+
if (!text)
|
|
2981
|
+
return {};
|
|
2982
|
+
try {
|
|
2983
|
+
return JSON.parse(text);
|
|
2984
|
+
}
|
|
2985
|
+
catch {
|
|
2986
|
+
return { error: truncateErrorText(text) };
|
|
2987
|
+
}
|
|
2988
|
+
}
|
|
2989
|
+
function agentMessageText(message) {
|
|
2990
|
+
return messagePartsText(message.parts);
|
|
2991
|
+
}
|
|
2992
|
+
function messagePartsText(parts) {
|
|
2993
|
+
return parts
|
|
2994
|
+
.map((part) => part.type === "text" && typeof part.text === "string" ? part.text : "")
|
|
2995
|
+
.join("");
|
|
2996
|
+
}
|
|
2997
|
+
function abortableAgentDelay(ms, signal) {
|
|
2998
|
+
return new Promise((resolve, reject) => {
|
|
2999
|
+
if (signal.aborted) {
|
|
3000
|
+
reject(signal.reason ?? new DOMException("Aborted", "AbortError"));
|
|
3001
|
+
return;
|
|
3002
|
+
}
|
|
3003
|
+
const timeout = setTimeout(resolve, ms);
|
|
3004
|
+
signal.addEventListener("abort", () => {
|
|
3005
|
+
clearTimeout(timeout);
|
|
3006
|
+
reject(signal.reason ?? new DOMException("Aborted", "AbortError"));
|
|
3007
|
+
}, { once: true });
|
|
3008
|
+
});
|
|
3009
|
+
}
|
|
3010
|
+
function isRecoverableConversationError(error) {
|
|
3011
|
+
return error instanceof RaybaseAgentRequestError && (error.status === 403 || error.status === 404 || error.status === 410);
|
|
3012
|
+
}
|
|
3013
|
+
function truncateErrorText(text) {
|
|
3014
|
+
const trimmed = text.trim();
|
|
3015
|
+
if (trimmed.length <= 1200)
|
|
3016
|
+
return trimmed;
|
|
3017
|
+
return `${trimmed.slice(0, 1200)}...`;
|
|
3018
|
+
}
|
|
3019
|
+
function supersedeTrailingTurnErrorMessages(messages) {
|
|
3020
|
+
const next = [...messages];
|
|
3021
|
+
for (let index = next.length - 1; index >= 0; index -= 1) {
|
|
3022
|
+
const message = next[index];
|
|
3023
|
+
if (!message || raybaseAgentTurnError(message) === null)
|
|
3024
|
+
break;
|
|
3025
|
+
next[index] = {
|
|
3026
|
+
...message,
|
|
3027
|
+
parts: message.parts.map((part) => part.type === raybaseAgentDataPartTypes.turnError
|
|
3028
|
+
? { ...part, data: { ...(part.data && typeof part.data === "object" ? part.data : {}), superseded: true } }
|
|
3029
|
+
: part)
|
|
3030
|
+
};
|
|
3031
|
+
}
|
|
3032
|
+
return next;
|
|
3033
|
+
}
|
|
3034
|
+
function messageSnapshot(role, parts) {
|
|
3035
|
+
return {
|
|
3036
|
+
id: randomClientId("agent_msg"),
|
|
3037
|
+
role,
|
|
3038
|
+
parts,
|
|
3039
|
+
createdAt: new Date().toISOString(),
|
|
3040
|
+
author: {
|
|
3041
|
+
kind: role === "assistant" ? "agent" : "user",
|
|
3042
|
+
userId: null,
|
|
3043
|
+
name: null
|
|
3044
|
+
},
|
|
3045
|
+
editedAt: null,
|
|
3046
|
+
removed: false,
|
|
3047
|
+
reactions: {}
|
|
3048
|
+
};
|
|
3049
|
+
}
|
|
3050
|
+
function appendMessageToText(message) {
|
|
3051
|
+
const content = Array.isArray(message.content)
|
|
3052
|
+
? message.content
|
|
3053
|
+
: [];
|
|
3054
|
+
return content
|
|
3055
|
+
.map((part) => part.type === "text" && typeof part.text === "string" ? part.text : "")
|
|
3056
|
+
.join("")
|
|
3057
|
+
.trim();
|
|
3058
|
+
}
|
|
3059
|
+
function urlFor(baseUrl, path) {
|
|
3060
|
+
if (!baseUrl)
|
|
3061
|
+
return path;
|
|
3062
|
+
return `${baseUrl.replace(/\/$/, "")}${path.startsWith("/") ? path : `/${path}`}`;
|
|
3063
|
+
}
|
|
3064
|
+
function roomWebSocketUrl(baseUrl, path, token) {
|
|
3065
|
+
const browserBase = typeof window !== "undefined" ? window.location.href : "http://localhost/";
|
|
3066
|
+
const url = new URL(urlFor(baseUrl, path), browserBase);
|
|
3067
|
+
url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
|
|
3068
|
+
url.searchParams.set("access_token", token);
|
|
3069
|
+
return url.toString();
|
|
3070
|
+
}
|
|
3071
|
+
function roomIsVisible() {
|
|
3072
|
+
return typeof document === "undefined" || document.visibilityState !== "hidden";
|
|
3073
|
+
}
|
|
3074
|
+
function roomViewportIsAtBottom(viewport) {
|
|
3075
|
+
return viewport !== null && viewport.scrollHeight - viewport.scrollTop - viewport.clientHeight <= 2;
|
|
3076
|
+
}
|
|
3077
|
+
function randomClientId(prefix) {
|
|
3078
|
+
if (typeof crypto !== "undefined" && "randomUUID" in crypto)
|
|
3079
|
+
return `${prefix}_${crypto.randomUUID()}`;
|
|
3080
|
+
return `${prefix}_${Math.random().toString(36).slice(2)}`;
|
|
3081
|
+
}
|
|
3082
|
+
function asError(error) {
|
|
3083
|
+
return error instanceof Error ? error : new Error(String(error));
|
|
3084
|
+
}
|
|
3085
|
+
function isAbortError(error) {
|
|
3086
|
+
return typeof error === "object" && error !== null && "name" in error && error.name === "AbortError";
|
|
3087
|
+
}
|
|
3088
|
+
//# sourceMappingURL=index.js.map
|