teodor-new-chat-ui 4.3.381 → 4.3.382

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/dist/index.esm.js CHANGED
@@ -2,7 +2,7 @@ var Bm = Object.defineProperty;
2
2
  var zm = (e, t, n) => t in e ? Bm(e, t, { enumerable: !0, configurable: !0, writable: !0, value: n }) : e[t] = n;
3
3
  var Il = (e, t, n) => zm(e, typeof t != "symbol" ? t + "" : t, n);
4
4
  import * as m from "react";
5
- import se, { createContext as co, useContext as Cs, useReducer as Um, useRef as $e, useCallback as ue, useEffect as ut, useMemo as Me, useState as de, useLayoutEffect as Hm, createElement as Bo, memo as Wm, useImperativeHandle as Vm } from "react";
5
+ import se, { createContext as co, useContext as Cs, useState as de, useRef as $e, useEffect as ut, useCallback as ue, useMemo as Me, useReducer as Um, useLayoutEffect as Hm, createElement as Bo, memo as Wm, useImperativeHandle as Vm } from "react";
6
6
  import { Square as Km, Send as qm, ChevronRight as vu, Check as Ts, Circle as Gm, X as vr, ExternalLink as Ym, Download as Xm, Image as Jm, FileText as El, Loader as va, ChevronUp as wa, ChevronDown as ks, Bot as di, Wrench as Zm, User as Qm, Paperclip as Bi, ChevronLeft as eg, Copy as Rl, Edit as Nl, RotateCcw as zi, Loader2 as qn, Edit3 as ba, Plus as tg, FileSpreadsheet as ng, Search as rg, Calendar as og, MoreHorizontal as sg, Share2 as ig, Trash2 as ag, MessageSquare as lg, Settings as cg, Server as ug, EyeOff as dg, Eye as fg, Layout as hg, MessageCircle as pg, Save as mg } from "lucide-react";
7
7
  import { Slot as gg, createSlot as Tr } from "@radix-ui/react-slot";
8
8
  import { cva as Is } from "class-variance-authority";
@@ -3121,1424 +3121,1431 @@ function ec() {
3121
3121
  for (const t of e)
3122
3122
  window.localStorage.removeItem(t);
3123
3123
  }
3124
- const jt = [];
3125
- for (let e = 0; e < 256; ++e)
3126
- jt.push((e + 256).toString(16).slice(1));
3127
- function Ay(e, t = 0) {
3128
- return (jt[e[t + 0]] + jt[e[t + 1]] + jt[e[t + 2]] + jt[e[t + 3]] + "-" + jt[e[t + 4]] + jt[e[t + 5]] + "-" + jt[e[t + 6]] + jt[e[t + 7]] + "-" + jt[e[t + 8]] + jt[e[t + 9]] + "-" + jt[e[t + 10]] + jt[e[t + 11]] + jt[e[t + 12]] + jt[e[t + 13]] + jt[e[t + 14]] + jt[e[t + 15]]).toLowerCase();
3124
+ function Ay({
3125
+ api: e,
3126
+ seed: t,
3127
+ prepend: n,
3128
+ onError: r,
3129
+ currentThreadId: o,
3130
+ initialThreadId: s = null,
3131
+ initialCheckpointId: i = null,
3132
+ initialCheckpointNs: a = null,
3133
+ autoLoadInitial: l = !0,
3134
+ isStreaming: c,
3135
+ getMessages: d
3136
+ }) {
3137
+ const [f, h] = de([]), [p, v] = de([]), [x, y] = de(!1), [g, w] = de(null), [C, T] = de(!1), [b, S] = de(!1), [k, R] = de(!1), [_, O] = de(null), F = $e(o), G = $e(null), q = $e(null), j = $e(null), N = $e(null), I = $e(!1), z = $e(null), L = $e(/* @__PURE__ */ new Map());
3138
+ ut(() => {
3139
+ F.current = o;
3140
+ }, [o]);
3141
+ const M = ue(
3142
+ async (B) => {
3143
+ var Y, xe;
3144
+ if (!B.threadId) return;
3145
+ const ee = B.threadId;
3146
+ (Y = B.onStart) == null || Y.call(B), B.setLoading(!0);
3147
+ try {
3148
+ await B.action(ee);
3149
+ } catch (ae) {
3150
+ if (F.current === ee) {
3151
+ const re = String(ae);
3152
+ (xe = B.handleError) == null || xe.call(B, re), r == null || r(re);
3153
+ }
3154
+ throw ae;
3155
+ } finally {
3156
+ B.setLoading(!1);
3157
+ }
3158
+ },
3159
+ [r]
3160
+ ), K = ue(
3161
+ async (B, ee) => {
3162
+ if (!B) return;
3163
+ const Y = `${B}:${ee ?? "latest"}`, xe = L.current.get(Y);
3164
+ if (xe)
3165
+ return xe;
3166
+ const ae = M({
3167
+ threadId: B,
3168
+ setLoading: T,
3169
+ onStart: () => O(null),
3170
+ handleError: (re) => O(re),
3171
+ action: async (re) => {
3172
+ const ge = await e.getStateHistory({
3173
+ threadId: re,
3174
+ checkpointId: ee ?? void 0
3175
+ });
3176
+ if (F.current !== re) {
3177
+ console.log(
3178
+ `[useThreadHistoryState] Thread changed during load (was ${re}, now ${F.current}), discarding stale data`
3179
+ );
3180
+ return;
3181
+ }
3182
+ const { checkpoints: be, timeline: _e } = xr(ge), Te = be.find((We) => We.messages && We.messages.length > 0) ?? (ee ? be.find((We) => We.checkpointId === ee) : null) ?? be[0];
3183
+ t((Te == null ? void 0 : Te.messages) ?? [], {
3184
+ checkpointId: (Te == null ? void 0 : Te.checkpointId) ?? null,
3185
+ checkpointNs: (Te == null ? void 0 : Te.checkpointNs) ?? null
3186
+ }), v(_e), h(be), y(!!(Te != null && Te.nextCursor)), w((Te == null ? void 0 : Te.nextCursor) ?? null);
3187
+ }
3188
+ });
3189
+ L.current.set(Y, ae);
3190
+ try {
3191
+ await ae;
3192
+ } finally {
3193
+ L.current.delete(Y);
3194
+ }
3195
+ return F.current === B && (z.current = Y), ae;
3196
+ },
3197
+ [e, t, M]
3198
+ ), J = ue(
3199
+ async (B, ee, Y) => {
3200
+ Y != null && Y.clearProgress && ec(), N.current = B;
3201
+ try {
3202
+ await K(B, ee);
3203
+ } finally {
3204
+ N.current === B && (N.current = null);
3205
+ }
3206
+ },
3207
+ [K]
3208
+ ), A = ue((B) => {
3209
+ q.current = B;
3210
+ }, []), Z = ue((B) => {
3211
+ j.current = B;
3212
+ }, []), W = ue(
3213
+ (B) => {
3214
+ const ee = B.threadId ?? F.current;
3215
+ if (!ee || F.current && F.current !== ee)
3216
+ return;
3217
+ const { checkpoints: Y, timeline: xe } = xr(B);
3218
+ if (!Y.length)
3219
+ return;
3220
+ const ae = Y.find((re) => re.messages && re.messages.length > 0) ?? Y.find((re) => !!re.checkpointId) ?? Y[0];
3221
+ t((ae == null ? void 0 : ae.messages) ?? [], {
3222
+ checkpointId: (ae == null ? void 0 : ae.checkpointId) ?? null,
3223
+ checkpointNs: (ae == null ? void 0 : ae.checkpointNs) ?? null
3224
+ }), v(xe), h(Y), y(!!(ae != null && ae.nextCursor)), w((ae == null ? void 0 : ae.nextCursor) ?? null), z.current = `${ee}:latest`, q.current = null, j.current = null;
3225
+ },
3226
+ [t]
3227
+ ), U = ue(
3228
+ async (B, ee) => {
3229
+ ec();
3230
+ const Y = F.current;
3231
+ await M({
3232
+ threadId: Y,
3233
+ setLoading: R,
3234
+ action: async (xe) => {
3235
+ const ae = await e.getStateHistory({
3236
+ threadId: xe,
3237
+ checkpointId: B,
3238
+ checkpointNs: ee ?? void 0
3239
+ });
3240
+ if (F.current !== xe) {
3241
+ console.log(
3242
+ `[useThreadHistoryState] Thread changed during checkpoint navigation (was ${xe}, now ${F.current}), discarding stale data`
3243
+ );
3244
+ return;
3245
+ }
3246
+ const { checkpoints: re, timeline: ge } = xr(ae), be = re.find(
3247
+ (_e) => _e.checkpointId === B && (ee ? _e.checkpointNs === ee : !0)
3248
+ );
3249
+ if (!be) {
3250
+ console.warn("[useThreadHistoryState] Requested checkpoint not found:", { checkpointId: B, checkpointNs: ee });
3251
+ return;
3252
+ }
3253
+ v(ge), h(re), t(be.messages ?? [], {
3254
+ checkpointId: be.checkpointId ?? null,
3255
+ checkpointNs: be.checkpointNs ?? null
3256
+ });
3257
+ }
3258
+ }).catch(() => {
3259
+ });
3260
+ },
3261
+ [e, t, M]
3262
+ ), te = ue(
3263
+ (B, ee) => {
3264
+ t(d(), {
3265
+ checkpointId: B ?? null,
3266
+ checkpointNs: ee ?? null
3267
+ });
3268
+ },
3269
+ [d, t]
3270
+ ), H = ue(async () => {
3271
+ F.current && await J(F.current);
3272
+ }, [J]), P = ue(async () => {
3273
+ const B = F.current;
3274
+ !B || !g || await M({
3275
+ threadId: B,
3276
+ setLoading: S,
3277
+ action: async (ee) => {
3278
+ const Y = await e.getStateHistory({
3279
+ threadId: ee,
3280
+ checkpointId: g
3281
+ });
3282
+ if (F.current !== ee)
3283
+ return;
3284
+ const { checkpoints: xe } = xr(Y);
3285
+ if (xe.length > 0) {
3286
+ const ae = xe[xe.length - 1];
3287
+ n((ae == null ? void 0 : ae.messages) ?? []), y(!!(ae != null && ae.nextCursor)), w((ae == null ? void 0 : ae.nextCursor) ?? null);
3288
+ }
3289
+ }
3290
+ }).catch(() => {
3291
+ });
3292
+ }, [e, g, r, n, M]);
3293
+ ut(() => {
3294
+ if (!l || !o || C || c)
3295
+ return;
3296
+ if (q.current === o) {
3297
+ q.current = null, G.current = o;
3298
+ return;
3299
+ }
3300
+ if (j.current === o) {
3301
+ G.current = o;
3302
+ return;
3303
+ }
3304
+ if (N.current === o) {
3305
+ N.current = null, G.current = o;
3306
+ return;
3307
+ }
3308
+ if (G.current === o)
3309
+ return;
3310
+ G.current = o;
3311
+ const B = !I.current && !!i && o === s;
3312
+ let ee;
3313
+ B && i ? (ee = i, I.current = !0, console.log(
3314
+ "[useThreadHistoryState] Loading thread with checkpoint:",
3315
+ ee,
3316
+ a ? `(ns: ${a})` : ""
3317
+ )) : console.log("[useThreadHistoryState] Loading thread with latest checkpoint");
3318
+ const Y = `${o}:${ee ?? "latest"}`;
3319
+ z.current !== Y && J(o, ee);
3320
+ }, [
3321
+ l,
3322
+ o,
3323
+ i,
3324
+ a,
3325
+ s,
3326
+ C,
3327
+ c,
3328
+ J
3329
+ ]);
3330
+ const V = ue(() => {
3331
+ h([]), v([]), y(!1), w(null), T(!1), S(!1), R(!1), O(null), q.current = null, j.current = null, G.current = null, z.current = null, N.current = null;
3332
+ }, []);
3333
+ return {
3334
+ threadCheckpoints: f,
3335
+ threadTimeline: p,
3336
+ isLoadingThread: C,
3337
+ isHistoryLoading: b,
3338
+ isLoadingCheckpoint: k,
3339
+ threadStateError: _,
3340
+ hasMoreHistory: x,
3341
+ loadThread: J,
3342
+ navigateToCheckpoint: U,
3343
+ loadOlderMessages: P,
3344
+ setCurrentCheckpointId: te,
3345
+ returnToLatest: H,
3346
+ handleStateHistoryEvent: W,
3347
+ markSkipNextLoad: A,
3348
+ markStreamPendingThread: Z,
3349
+ resetHistoryState: V
3350
+ };
3129
3351
  }
3130
- let gi;
3131
- const jy = new Uint8Array(16);
3132
- function _y() {
3133
- if (!gi) {
3134
- if (typeof crypto > "u" || !crypto.getRandomValues)
3135
- throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");
3136
- gi = crypto.getRandomValues.bind(crypto);
3352
+ const jy = ["detail", "message", "error", "description", "title"];
3353
+ function Wo(e) {
3354
+ if (!e) return null;
3355
+ if (typeof e == "string") {
3356
+ const t = e.trim();
3357
+ return t.length ? t : null;
3358
+ }
3359
+ if (Array.isArray(e)) {
3360
+ for (const t of e) {
3361
+ const n = Wo(t);
3362
+ if (n)
3363
+ return n;
3364
+ }
3365
+ return null;
3366
+ }
3367
+ if (typeof e == "object") {
3368
+ const t = e;
3369
+ for (const n of jy) {
3370
+ const r = Wo(t[n]);
3371
+ if (r)
3372
+ return r;
3373
+ }
3374
+ if ("errors" in t) {
3375
+ const n = Wo(t.errors);
3376
+ if (n) return n;
3377
+ }
3137
3378
  }
3138
- return gi(jy);
3379
+ return null;
3139
3380
  }
3140
- const My = typeof crypto < "u" && crypto.randomUUID && crypto.randomUUID.bind(crypto), tc = { randomUUID: My };
3141
- function Py(e, t, n) {
3142
- var o;
3143
- e = e || {};
3144
- const r = e.random ?? ((o = e.rng) == null ? void 0 : o.call(e)) ?? _y();
3145
- if (r.length < 16)
3146
- throw new Error("Random bytes length must be >= 16");
3147
- return r[6] = r[6] & 15 | 64, r[8] = r[8] & 63 | 128, Ay(r);
3148
- }
3149
- function Oy(e, t, n) {
3150
- return tc.randomUUID && !e ? tc.randomUUID() : Py(e);
3151
- }
3152
- function xi(e) {
3153
- return e.filter((t) => {
3154
- var s;
3155
- if (t.role !== "assistant") return !0;
3156
- const n = (t.content || []).some(
3157
- (i) => {
3158
- var a;
3159
- return i && i.type === "text" && ((a = i.text) == null ? void 0 : a.trim());
3160
- }
3161
- ), r = (t.content || []).some((i) => i && i.type === "image_url"), o = !!((s = t.artifact) != null && s.plots && t.artifact.plots.length > 0);
3162
- return !!(n || r || o);
3163
- });
3164
- }
3165
- function Wo(e, t, n) {
3166
- return t < 0 || t >= e.length ? e : [...e.slice(0, t), n, ...e.slice(t + 1)];
3167
- }
3168
- function Qu(e) {
3169
- let t = !1;
3170
- const n = e.map((r) => {
3171
- const o = (r.content ?? []).filter((s) => s.type !== "interrupt");
3172
- return o.length !== r.content.length ? (t = !0, { ...r, content: o }) : r;
3173
- });
3174
- return t ? n : e;
3175
- }
3176
- function nc(e) {
3177
- for (let t = e.length - 1; t >= 0; t--)
3178
- if (e[t].role === "assistant") return e[t].id;
3179
- return null;
3180
- }
3181
- function rc(e) {
3182
- const t = /* @__PURE__ */ new Set(), n = (r) => {
3183
- typeof r == "string" && r.trim() && t.add(r.trim());
3184
- };
3185
- return n(e.id), n(e == null ? void 0 : e.call_id), n(e == null ? void 0 : e.callId), Array.from(t);
3186
- }
3187
- function Dy(e, t) {
3188
- const n = /* @__PURE__ */ new Set();
3189
- for (const o of t)
3190
- typeof o == "string" && o.trim() && n.add(o.trim());
3191
- const r = Hy(e);
3192
- for (const o of r)
3193
- n.add(o);
3194
- return Array.from(n);
3195
- }
3196
- function oc(e, t, n) {
3197
- if (!n.length) return e;
3198
- let r = !1;
3199
- const o = { ...e };
3200
- for (const s of n)
3201
- s && o[s] !== t && (o[s] = t, r = !0);
3202
- return r ? o : e;
3203
- }
3204
- function Ly(e, t, n, r) {
3205
- const o = /* @__PURE__ */ new Set(), s = (l) => {
3206
- typeof l == "string" && l.trim() && o.add(l.trim());
3207
- };
3208
- for (const l of t)
3209
- s(l);
3210
- const i = Array.from(o), a = {};
3211
- if (i.length) {
3212
- a.toolCallIds = i;
3213
- const l = typeof a.toolCallId == "string" ? a.toolCallId.trim() : null;
3214
- a.toolCallId = l && o.has(l) ? l : i[0];
3381
+ function _y(e) {
3382
+ if (!e) return "Request failed";
3383
+ const t = e.response, n = Wo(t == null ? void 0 : t.data);
3384
+ if (n) return n;
3385
+ if (t != null && t.statusText)
3386
+ return t.statusText;
3387
+ if (e instanceof Error && e.message)
3388
+ return e.message;
3389
+ if (typeof e == "string") {
3390
+ const r = e.trim();
3391
+ if (r.length) return r;
3215
3392
  }
3216
- return n && (a.toolName = n), r !== void 0 && (a.toolArgs = r), a;
3217
- }
3218
- function No(e, t, n) {
3219
- const r = e.findIndex((c) => c.id === t);
3220
- if (r === -1) return e;
3221
- const o = e[r], s = [...e], i = { ...o.additionalKwargs ?? {} }, a = Array.isArray(i.toolProgress) ? [...i.toolProgress] : [], l = {
3222
- id: Oy(),
3223
- idx: a.length + 1,
3224
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
3225
- ...n
3226
- };
3227
- return a.push(l), Ry(o.id, a, {
3228
- checkpointId: o.checkpointId ?? null,
3229
- checkpointNs: o.checkpointNs ?? null
3230
- }), i.toolProgress = a, s[r] = { ...o, additionalKwargs: i }, s;
3231
- }
3232
- function sc(e, t) {
3233
- return e.includes(t) ? e : [...e, t];
3234
- }
3235
- function $y(e, t) {
3236
- const n = [...e], r = n.lastIndexOf(t);
3237
- return r !== -1 && n.splice(r, 1), n;
3393
+ return t != null && t.status ? `Request failed with status code ${t.status}` : "Request failed";
3238
3394
  }
3239
- function yr(e, t) {
3240
- let n = !1;
3241
- const r = {}, o = e.map((s) => {
3242
- const i = Wy(s);
3243
- if (i.length)
3244
- return r[s.id] = i, s;
3245
- const a = t[s.id] ?? Ny(s.id);
3246
- if (a != null && a.length) {
3247
- const l = [...a];
3248
- r[s.id] = l, n = !0;
3249
- const c = { ...s.additionalKwargs ?? {}, toolProgress: l };
3250
- return { ...s, additionalKwargs: c };
3395
+ function My({
3396
+ api: e,
3397
+ initialThreadId: t = null,
3398
+ onError: n,
3399
+ onThreadChange: r,
3400
+ onCurrentThreadDeleted: o
3401
+ }) {
3402
+ const [s, i] = de([]), [a, l] = de(t), [c, d] = de(!1), [f, h] = de(null), [p, v] = de([]), [x, y] = de(!1), [, g] = de(null), [w, C] = de([]), [T, b] = de(!1), [, S] = de(null), [k, R] = de(null), [_, O] = de(!1), F = $e(a), G = $e(/* @__PURE__ */ new Map());
3403
+ ut(() => {
3404
+ F.current = a;
3405
+ }, [a]);
3406
+ const q = ue(async () => {
3407
+ d(!0), h(null);
3408
+ try {
3409
+ const W = await e.listThreads();
3410
+ i(W ?? []);
3411
+ } catch (W) {
3412
+ const U = String(W);
3413
+ h(U), n == null || n(U);
3414
+ } finally {
3415
+ d(!1);
3251
3416
  }
3252
- return s;
3253
- });
3254
- return {
3255
- messages: n ? o : e,
3256
- toolTimelines: r
3257
- };
3258
- }
3259
- function ed(e) {
3260
- return !e || !e.length ? "" : e.filter((t) => t.type === "text").map((t) => t.text ?? "").join("");
3261
- }
3262
- function Fy(e, t, n, r) {
3263
- const o = { ...n };
3264
- if (r !== null && typeof r == "number") {
3265
- if (typeof o.lastSeq == "number" && r <= o.lastSeq)
3266
- return { newParts: e, newMeta: o, changed: !1 };
3267
- o.lastSeq = r;
3268
- }
3269
- const s = t.filter((f) => f.type === "text").map((f) => f.text ?? "").join(""), i = t.filter((f) => f.type !== "text"), a = o.lastText ?? ed(e);
3270
- let l = "", c = e.slice();
3271
- if (s) {
3272
- const f = By(a, s);
3273
- if (f === "" ? l = "" : f === s ? l = s : l = f, l) {
3274
- const h = c[c.length - 1];
3275
- if ((h == null ? void 0 : h.type) === "text") {
3276
- const p = h.text ?? "", v = { ...h, text: p + l };
3277
- c = [...c.slice(0, c.length - 1), v];
3278
- } else
3279
- c = [...c, { type: "text", text: l }];
3280
- o.lastText = a + l;
3281
- } else
3282
- o.lastText = a;
3283
- }
3284
- i.length && (c = [...c, ...i]);
3285
- const d = !!(l || i.length);
3286
- return { newParts: c, newMeta: o, changed: d };
3287
- }
3288
- function ic(e) {
3289
- return e.replace(/\s+/g, " ").trim();
3290
- }
3291
- function By(e, t) {
3292
- if (!t) return "";
3293
- if (!e) return t;
3294
- if (e === t) return "";
3295
- const n = Math.min(e.length, t.length);
3296
- for (let i = n; i > 0; i--)
3297
- if (e.slice(-i) === t.slice(0, i))
3298
- return t.slice(i);
3299
- const r = ic(e), o = ic(t);
3300
- if (r === o) return "";
3301
- const s = Math.min(r.length, o.length);
3302
- for (let i = s; i > 0; i--)
3303
- if (r.slice(-i) === o.slice(0, i))
3304
- return t;
3305
- return t;
3306
- }
3307
- function zy(e, t, n) {
3308
- for (let r = e.length - 1; r >= 0; r--)
3309
- if (e[r].role === "assistant") {
3310
- const s = { ...e[r], checkpointId: t, checkpointNs: n ?? void 0 };
3311
- return Wo(e, r, s);
3417
+ }, [e, n]), j = ue(async () => {
3418
+ y(!0), g(null);
3419
+ try {
3420
+ const W = await e.listSharedThreads();
3421
+ v(W ?? []);
3422
+ } catch (W) {
3423
+ const U = String(W);
3424
+ g(U), n == null || n(U);
3425
+ } finally {
3426
+ y(!1);
3312
3427
  }
3313
- return e;
3314
- }
3315
- function Uy(e) {
3316
- if (!e) return null;
3317
- const t = e.split("/");
3318
- return t[t.length - 1] || null;
3319
- }
3320
- function Hy(e) {
3321
- if (!e) return [];
3322
- const t = /* @__PURE__ */ new Set(), n = (o) => {
3323
- typeof o == "string" && o.trim() && t.add(o.trim());
3324
- }, r = e.additionalKwargs;
3325
- if (r) {
3326
- n(r.toolCallId);
3327
- const o = r.toolCallIds;
3328
- if (Array.isArray(o))
3329
- for (const s of o)
3330
- n(s);
3331
- }
3332
- for (const o of e.content ?? [])
3333
- (o == null ? void 0 : o.type) === "tool_call" && n(o.id);
3334
- return Array.from(t);
3335
- }
3336
- function Wy(e) {
3337
- const t = e.additionalKwargs ?? {};
3338
- return Array.isArray(t.toolProgress) ? [...t.toolProgress] : [];
3339
- }
3340
- const Vy = {
3341
- messages: [],
3342
- assemblingId: null,
3343
- lastCheckpointId: null,
3344
- lastCheckpointNs: null,
3345
- toolIndex: {},
3346
- toolStreamingMessageId: null,
3347
- toolStreamingStack: [],
3348
- messagesStreamMeta: {},
3349
- pendingInterrupt: null,
3350
- toolTimelines: {}
3351
- };
3352
- function Ky(e, t) {
3353
- var n;
3354
- switch (t.type) {
3355
- case "reset":
3356
- return {
3357
- messages: xi(((n = t.payload) == null ? void 0 : n.messages) ?? []),
3358
- assemblingId: null,
3359
- lastCheckpointId: null,
3360
- lastCheckpointNs: null,
3361
- toolIndex: {},
3362
- toolStreamingMessageId: null,
3363
- toolStreamingStack: [],
3364
- pendingInterrupt: null,
3365
- toolTimelines: {}
3366
- };
3367
- case "user_message": {
3368
- const { message: r } = t.payload;
3369
- return { ...e, messages: [...e.messages, r] };
3428
+ }, [e, n]), N = ue(async () => {
3429
+ b(!0), S(null);
3430
+ try {
3431
+ const W = await e.listSmartOrgUsers();
3432
+ C(W ?? []);
3433
+ } catch (W) {
3434
+ const U = String(W);
3435
+ S(U), n == null || n(U);
3436
+ } finally {
3437
+ b(!1);
3370
3438
  }
3371
- case "seed": {
3372
- const r = xi(t.payload.messages), { messages: o, toolTimelines: s } = yr(
3373
- r,
3374
- e.toolTimelines
3375
- ), i = {
3376
- ...e,
3377
- messages: o,
3378
- // REPLACE with incoming messages (don't merge with existing)
3379
- assemblingId: null,
3380
- // Clear any streaming state on seed
3381
- pendingInterrupt: t.payload.pendingInterrupt ?? null,
3382
- toolStreamingMessageId: null,
3383
- toolStreamingStack: [],
3384
- toolTimelines: s
3385
- };
3386
- return Object.prototype.hasOwnProperty.call(t.payload, "checkpointId") && (i.lastCheckpointId = t.payload.checkpointId ?? null), Object.prototype.hasOwnProperty.call(t.payload, "checkpointNs") && (i.lastCheckpointNs = t.payload.checkpointNs ?? null), i;
3387
- }
3388
- case "prepend": {
3389
- const r = xi(t.payload.messages);
3390
- if (!r.length)
3391
- return e;
3392
- const o = new Set(e.messages.map((c) => c.id)), s = r.filter((c) => !o.has(c.id));
3393
- if (!s.length)
3394
- return e;
3395
- const i = [...s, ...e.messages], { messages: a, toolTimelines: l } = yr(
3396
- i,
3397
- e.toolTimelines
3398
- );
3399
- return { ...e, messages: a, toolTimelines: l };
3400
- }
3401
- case "event":
3402
- return ac(e, t.payload.ev);
3403
- case "batch": {
3404
- const { events: r } = t.payload;
3405
- return r.length ? r.reduce((o, s) => ac(o, s), e) : e;
3406
- }
3407
- case "interrupt_response":
3408
- return { ...e, messages: Qu(e.messages), pendingInterrupt: null };
3409
- default:
3410
- return e;
3411
- }
3412
- }
3413
- function qy(e = []) {
3414
- const [t, n] = Um(Ky, { ...Vy, messages: e }), r = $e([]), o = $e(null), s = $e(null), i = ue(() => {
3415
- o.current !== null && typeof window < "u" && window.cancelAnimationFrame(o.current), s.current !== null && clearTimeout(s.current), o.current = null, s.current = null;
3416
- const d = r.current;
3417
- d.length && (r.current = [], n({ type: "batch", payload: { events: d } }));
3418
- }, []), a = ue(() => {
3419
- typeof window < "u" && typeof window.requestAnimationFrame == "function" ? o.current === null && (o.current = window.requestAnimationFrame(() => i())) : s.current === null && (s.current = setTimeout(i, 8));
3420
- }, [i]), l = ue((d) => {
3421
- r.current.push(d), a();
3422
- }, [a]);
3423
- ut(() => () => {
3424
- o.current !== null && typeof window < "u" && window.cancelAnimationFrame(o.current), s.current !== null && clearTimeout(s.current), r.current = [];
3425
- }, []);
3426
- const c = Me(() => ({
3427
- reset: (d) => n({ type: "reset", payload: { messages: d } }),
3428
- seed: (d, f) => n({ type: "seed", payload: { messages: d, ...f ?? {} } }),
3429
- prepend: (d) => n({ type: "prepend", payload: { messages: d } }),
3430
- pushUser: (d) => n({ type: "user_message", payload: { message: d } }),
3431
- onEvent: l
3432
- }), [l]);
3433
- return { state: t, dispatch: n, ...c };
3434
- }
3435
- function ac(e, t) {
3436
- var n, r, o, s;
3437
- if (t.type === "message.start" && t.role === "assistant") {
3438
- const i = t.id, a = Uy(t.model);
3439
- if (e.messages.some((d) => d.id === i)) {
3440
- const d = e.messagesStreamMeta ?? {}, f = {
3441
- ...d,
3442
- [i]: d[i] ?? { lastSeq: t.seq ?? null, lastText: "" }
3443
- };
3444
- return { ...e, assemblingId: i, messagesStreamMeta: f };
3445
- }
3446
- const c = {
3447
- id: i,
3448
- role: "assistant",
3449
- name: a || void 0,
3450
- model: t.model,
3451
- createdAt: (/* @__PURE__ */ new Date()).toISOString(),
3452
- content: []
3453
- };
3454
- return { ...e, assemblingId: i, messages: [...e.messages, c] };
3455
- }
3456
- if (t.type === "message.delta") {
3457
- const i = e.assemblingId ?? nc(e.messages);
3458
- if (!i) return e;
3459
- const a = e.messages, l = a.findIndex((C) => C.id === i && C.role === "assistant");
3460
- if (l === -1) return e;
3461
- const c = a[l], d = e.messagesStreamMeta ?? {}, f = d[i] ?? { lastSeq: null, lastText: ed(c.content) }, h = t.seq ?? null;
3462
- if (h !== null && typeof h == "number" && typeof f.lastSeq == "number" && h <= f.lastSeq)
3463
- return console.debug("[MessageReducer] skipping delta - seq <= lastSeq", { seq: h, lastSeq: f.lastSeq }), e;
3464
- const { newParts: p, newMeta: v, changed: x } = Fy(c.content, t.delta, f, h);
3465
- if (!x) return e;
3466
- const y = { ...c, content: p }, g = Wo(a, l, y), w = { ...d, [i]: v };
3467
- return { ...e, messages: g, messagesStreamMeta: w };
3468
- }
3469
- if (t.type === "message.end") {
3470
- const i = e.assemblingId ?? nc(e.messages);
3471
- if (!i) return { ...e, assemblingId: null };
3472
- const a = e.messages, l = a.findIndex((c) => c.id === i && c.role === "assistant");
3473
- if (l >= 0) {
3474
- const c = a[l];
3475
- if (!((n = c.content) == null ? void 0 : n.some((f) => {
3476
- var h;
3477
- return (f == null ? void 0 : f.type) === "text" && ((h = f.text) == null ? void 0 : h.trim());
3478
- }))) {
3479
- console.debug("[MessageReducer] pruning assistant message with no visible text", {
3480
- id: c.id,
3481
- contentTypes: (r = c.content) == null ? void 0 : r.map((h) => h == null ? void 0 : h.type),
3482
- contentPreview: (o = c.content) == null ? void 0 : o.map((h) => (h == null ? void 0 : h.type) === "text" ? String(h.text).slice(0, 100) : h == null ? void 0 : h.type)
3483
- });
3484
- const f = [...a.slice(0, l), ...a.slice(l + 1)];
3485
- return { ...e, assemblingId: null, messages: f };
3439
+ }, [e, n]);
3440
+ ut(() => {
3441
+ q(), N();
3442
+ }, [N, q]), ut(() => {
3443
+ j();
3444
+ }, [j]), ut(() => {
3445
+ r == null || r(a);
3446
+ }, [a, r]);
3447
+ const I = ue(
3448
+ async (W) => {
3449
+ try {
3450
+ const U = await e.createThread(W);
3451
+ return l(U.threadId), await q(), U.threadId;
3452
+ } catch (U) {
3453
+ const te = String(U);
3454
+ return n == null || n(te), null;
3486
3455
  }
3487
- }
3488
- return e;
3489
- }
3490
- if (t.type === "tool.start") {
3491
- const i = rc(t), a = i[0] ?? (typeof t.id == "string" ? t.id : null) ?? (typeof t.call_id == "string" ? t.call_id : null), l = t.name ?? t.tool ?? "tool";
3492
- !a && i.length === 0 && i.push(`${l}-${Date.now()}`);
3493
- const c = i.length ? i : a ? [a] : [], d = c[0] ?? `${l}-${Date.now()}`, f = { type: "tool_call", id: d, name: l, args: t.args }, h = {
3494
- type: e.toolStreamingMessageId ? "tool.call" : "tool.start",
3495
- toolId: a ?? d,
3496
- toolName: l,
3497
- metadata: {
3498
- args: t.args
3456
+ },
3457
+ [e, n, q]
3458
+ ), z = ue(
3459
+ async (W) => {
3460
+ const U = s;
3461
+ i((H) => H.filter((P) => P.threadId !== W));
3462
+ const te = new AbortController();
3463
+ G.current.set(W, te);
3464
+ try {
3465
+ await e.deleteThread(W), F.current === W && (l(null), o == null || o());
3466
+ } catch (H) {
3467
+ i(U);
3468
+ const P = String(H);
3469
+ n == null || n(P);
3470
+ } finally {
3471
+ G.current.delete(W);
3499
3472
  }
3500
- }, p = e.toolStreamingMessageId;
3501
- if (!p) {
3502
- const w = {
3503
- id: `tool-${d}`,
3504
- role: "tool",
3505
- name: l,
3506
- createdAt: (/* @__PURE__ */ new Date()).toISOString(),
3507
- content: [f],
3508
- additionalKwargs: {
3509
- ...Ly(void 0, c.length ? c : [d], l, t.args),
3510
- toolStreaming: !0
3511
- }
3512
- }, C = Dy(w, c.length ? c : [d]), T = [...e.messages, w], b = No(T, w.id, h), { messages: S, toolTimelines: k } = yr(b, e.toolTimelines);
3513
- return {
3514
- ...e,
3515
- messages: S,
3516
- toolIndex: oc(e.toolIndex, w.id, C),
3517
- toolStreamingMessageId: w.id,
3518
- toolStreamingStack: sc(e.toolStreamingStack ?? [], a ?? d),
3519
- toolTimelines: k
3520
- };
3521
- }
3522
- const v = No(e.messages, p, h), { messages: x, toolTimelines: y } = yr(v, e.toolTimelines);
3523
- return {
3524
- ...e,
3525
- messages: x,
3526
- toolIndex: oc(e.toolIndex, p, c),
3527
- toolStreamingStack: sc(e.toolStreamingStack ?? [], a ?? d),
3528
- toolTimelines: y
3529
- };
3530
- }
3531
- if (t.type === "tool.end") {
3532
- const i = rc(t);
3533
- if (!i.length && !(typeof t.id == "string" && t.id))
3534
- return e;
3535
- const a = i[0] ?? (typeof t.id == "string" ? t.id : null);
3536
- if (!a)
3537
- return e;
3538
- const l = e.toolStreamingStack ?? [], c = l[0] ?? null, d = $y(l, a), f = d[0] ? e.toolIndex[d[0]] : null, h = e.toolStreamingMessageId, p = c === a, v = t.name ?? ((s = e.messages.find((b) => b.id === h)) == null ? void 0 : s.name) ?? "tool", x = typeof t.output == "string" ? t.output.trim() : JSON.stringify(t.output ?? ""), y = {
3539
- type: "tool.end",
3540
- toolId: a,
3541
- toolName: v,
3542
- content: x == null ? void 0 : x.slice(0, 200)
3543
- };
3544
- let g = e.messages;
3545
- if (h && (g = No(g, h, y)), p && h) {
3546
- const b = g.findIndex((S) => S.id === h);
3547
- if (b >= 0) {
3548
- const S = g[b], R = {
3549
- type: "text",
3550
- text: (() => {
3551
- if (typeof t.output == "string") {
3552
- const O = t.output.trim();
3553
- try {
3554
- return O;
3555
- } catch {
3556
- return O;
3557
- }
3558
- }
3559
- return JSON.stringify(t.output ?? "");
3560
- })()
3561
- }, _ = {
3562
- ...S,
3563
- content: [R],
3564
- artifact: t.artifact ?? S.artifact,
3565
- additionalKwargs: { ...S.additionalKwargs ?? {} }
3566
- };
3567
- g = Wo(g, b, _);
3473
+ },
3474
+ [e, o, n, s]
3475
+ ), L = ue(
3476
+ async (W, U) => {
3477
+ try {
3478
+ await e.updateThread(W, U), await q();
3479
+ } catch (te) {
3480
+ n == null || n(String(te));
3568
3481
  }
3569
- }
3570
- const w = d, { messages: C, toolTimelines: T } = yr(g, e.toolTimelines);
3571
- return {
3572
- ...e,
3573
- messages: C,
3574
- toolTimelines: T,
3575
- toolStreamingMessageId: p ? f : h,
3576
- toolStreamingStack: w
3577
- };
3578
- }
3579
- if (t.type === "tool.progress") {
3580
- const i = e.toolStreamingMessageId;
3581
- if (!i)
3582
- return e;
3583
- const a = {
3584
- type: "tool.progress",
3585
- content: t.content ?? null
3586
- }, l = No(e.messages, i, a), c = l.findIndex((y) => y.id === i);
3587
- if (c === -1)
3588
- return e;
3589
- const d = l[c], f = {
3590
- ...d.additionalKwargs ?? {},
3591
- toolStreaming: !0
3592
- }, h = { ...d, additionalKwargs: f }, p = Wo(l, c, h), { messages: v, toolTimelines: x } = yr(p, e.toolTimelines);
3593
- return { ...e, messages: v, toolTimelines: x };
3594
- }
3595
- if (t.type === "checkpoint") {
3596
- const i = t.checkpointNs ?? e.lastCheckpointNs ?? null, a = zy(e.messages, t.checkpointId, i);
3597
- return { ...e, lastCheckpointId: t.checkpointId, lastCheckpointNs: i, messages: a };
3598
- }
3599
- if (t.type === "error") {
3600
- const i = {
3601
- id: `err-${Date.now()}`,
3602
- role: "system",
3603
- content: [{ type: "text", text: `Error: ${t.message}` }],
3604
- createdAt: (/* @__PURE__ */ new Date()).toISOString()
3605
- };
3606
- return { ...e, messages: [...e.messages, i] };
3607
- }
3608
- if (t.type === "state_history") {
3609
- const i = xr(t), a = i.interrupt, l = i.latest, c = a === null ? Qu(e.messages) : e.messages;
3610
- return {
3611
- ...e,
3612
- messages: c,
3613
- pendingInterrupt: a,
3614
- lastCheckpointId: (l == null ? void 0 : l.checkpointId) ?? e.lastCheckpointId,
3615
- lastCheckpointNs: (l == null ? void 0 : l.checkpointNs) ?? e.lastCheckpointNs
3616
- };
3617
- }
3618
- return t.type === "thread_info", e;
3619
- }
3620
- function Gy(e = {}) {
3621
- const t = Me(() => En(e.baseUrl), [e.baseUrl]), n = e.streamPath ?? "/runs/stream", [r, o] = de(e.token ?? null), s = $e(e.headers ?? {}), i = e.credentials ?? "include", [a, l] = de(!1), [c, d] = de(null), [f, h] = de(""), [p, v] = de(null), [x, y] = de(0), [g, w] = de(!1), C = $e(null), T = $e(!0), b = $e(0), S = $e(null), k = $e(null), R = $e(null), _ = $e(null), O = ue((j) => {
3622
- o(j);
3623
- }, []), F = ue(() => {
3624
- h(""), v(null), d(null), k.current = null, R.current = null, _.current = null;
3625
- }, []), G = ue(() => {
3626
- var j;
3627
- console.debug("[use-chat] stop() invoked - aborting stream"), (j = C.current) == null || j.abort(), C.current = null, S.current = null, l(!1), w(!1), b.current = 0, y(0);
3628
- }, []), q = ue(
3629
- (j, N, I) => {
3630
- C.current && (C.current.abort(), C.current = null), l(!0), d(null), e.autoAppendAssistant !== !1 && h(""), v(null), k.current = null, R.current = null, _.current = null;
3631
- const z = new AbortController();
3632
- C.current = z;
3633
- let L = null, M = null, K = !1;
3634
- return S.current = {
3635
- threadId: j.threadId ?? null,
3636
- headers: {}
3637
- }, (async () => {
3638
- var A, Z, W, U, te, H, P, V, B, ee, Y, xe, ae, re, ge, be, _e, Te;
3639
- const J = (We) => {
3640
- var nt;
3641
- try {
3642
- const rt = JSON.parse(JSON.stringify(We));
3643
- return (nt = rt == null ? void 0 : rt.payload) != null && nt.files_info && Array.isArray(rt.payload.files_info) && (rt.payload.files_info = rt.payload.files_info.map((Ke) => ({
3644
- ...Ke,
3645
- data: Ke != null && Ke.data ? `<base64 ${String(Ke.data).length} chars>` : Ke == null ? void 0 : Ke.data
3646
- }))), rt;
3647
- } catch {
3648
- return We;
3649
- }
3650
- };
3651
- try {
3652
- let We = {};
3653
- try {
3654
- if (r)
3655
- We = { Authorization: `Bearer ${r}` };
3656
- else if (typeof window < "u") {
3657
- const Ve = window.__AUTH_TOKEN__, dt = ((A = window.localStorage) == null ? void 0 : A.getItem("authToken")) || null;
3658
- let Et = null;
3659
- try {
3660
- const X = (Z = window.localStorage) == null ? void 0 : Z.getItem("chat-settings");
3661
- X && (Et = ((W = JSON.parse(X)) == null ? void 0 : W.apiKey) || null);
3662
- } catch {
3663
- }
3664
- const qe = Ve || dt || Et || null;
3665
- qe && (We = { Authorization: `Bearer ${qe}` });
3666
- }
3667
- } catch {
3668
- }
3669
- console.debug(
3670
- "[use-chat] POST",
3671
- t + n,
3672
- J(j)
3673
- );
3674
- let nt = {};
3675
- if (typeof window < "u")
3676
- try {
3677
- const Je = (U = window.localStorage) == null ? void 0 : U.getItem("authSessionId");
3678
- Je && (nt = { "X-Session-Id": Je });
3679
- } catch {
3680
- }
3681
- const rt = {
3682
- ...We,
3683
- ...nt,
3684
- ...s.current
3685
- }, Ke = {
3686
- "Content-Type": "application/json",
3687
- Accept: "text/event-stream",
3688
- ...rt
3689
- }, Xe = await fetch(t + n, {
3690
- method: "POST",
3691
- headers: Ke,
3692
- body: JSON.stringify(j),
3693
- signal: z.signal,
3694
- credentials: i
3695
- });
3696
- if (S.current && (S.current.headers = rt), !Xe.ok || !Xe.body) {
3697
- const Je = await Xe.text().catch(() => "");
3698
- console.debug(
3699
- "[use-chat] non-OK response",
3700
- Xe.status,
3701
- Je == null ? void 0 : Je.slice(0, 500)
3702
- );
3703
- const Ve = `stream ${Xe.status}${Je ? ": " + Je : ""}`;
3704
- throw (te = I == null ? void 0 : I.onConnectionError) == null || te.call(I, Ve), K = !0, L = "error", M = Ve, new Error(Ve);
3705
- }
3706
- w(!0);
3707
- const at = Xe.body.getReader(), bt = new TextDecoder();
3708
- let pt = "", It = [];
3709
- b.current = 0, y(0);
3710
- let Ie = 0, ze = null;
3711
- const mt = () => {
3712
- if (It.length) {
3713
- const Je = It.join("");
3714
- It = [], T.current && h((Ve) => Ve + Je);
3715
- }
3716
- ze = null;
3717
- }, St = () => {
3718
- typeof window < "u" && ze == null && (ze = requestAnimationFrame(mt));
3719
- };
3720
- let Pt = Date.now();
3721
- const Pe = setInterval(() => {
3722
- var Je;
3723
- if (Date.now() - Pt > 18e5) {
3724
- const Ve = "Stream idle timeout";
3725
- d(Ve), L = "error", M = Ve, z.abort(), (Je = I == null ? void 0 : I.onError) == null || Je.call(I, Ve);
3726
- }
3727
- }, 5e3), Wt = 1024 * 1024;
3728
- try {
3729
- const Je = Xe.headers.get("X-Thread-Id") || Xe.headers.get("x-thread-id"), Ve = Xe.headers.get("X-Thread-Created") || Xe.headers.get("x-thread-created"), dt = Je ?? null, Et = String(Ve ?? "").toLowerCase() === "true";
3730
- for (S.current && !S.current.threadId && (S.current = {
3731
- ...S.current,
3732
- threadId: dt
3733
- }), (H = I == null ? void 0 : I.onOpen) == null || H.call(I, { threadId: dt, created: Et }); ; ) {
3734
- const { value: qe, done: X } = await at.read();
3735
- if (X) break;
3736
- pt += bt.decode(qe, { stream: !0 }), pt.length > Wt && (pt = "", console.warn("Stream buffer reset: exceeded 1MB"));
3737
- let D;
3738
- for (; (D = pt.indexOf(`
3739
-
3740
- `)) >= 0; ) {
3741
- const le = pt.slice(0, D);
3742
- pt = pt.slice(D + 2);
3743
- const ye = Xy(le);
3744
- if (!ye) continue;
3745
- let Ue;
3746
- try {
3747
- Ue = JSON.parse(ye);
3748
- } catch {
3749
- console.debug("[use-chat] malformed SSE:", ye.slice(0, 200));
3750
- continue;
3751
- }
3752
- const De = Yy(Ue) ? Ue.data : Ue;
3753
- Pt = Date.now();
3754
- const gt = De.seq;
3755
- if (gt !== void 0) {
3756
- if (gt <= Ie) {
3757
- console.debug("[use-chat] drop duplicate/out-of-order event", { seq: gt, lastProcessedSeq: Ie, type: De.type });
3758
- continue;
3759
- }
3760
- Ie > 0 && gt > Ie + 1 && ((P = I == null ? void 0 : I.onGap) == null || P.call(I, { from: Ie, to: gt })), Ie = gt, b.current = gt, y(gt);
3761
- }
3762
- if (De.type === "checkpoint")
3763
- k.current = De.checkpointId ?? null, R.current = De.checkpointNs ?? null, v(De.checkpointId ?? null);
3764
- else if (De.type === "state_history") {
3765
- _.current = De;
3766
- try {
3767
- const Rt = xr(De).latest;
3768
- Rt && (k.current = Rt.checkpointId ?? null, R.current = Rt.checkpointNs ?? null, v(Rt.checkpointId ?? null));
3769
- } catch (Ze) {
3770
- console.warn("[use-chat] Failed to hydrate state_history payload", Ze);
3771
- }
3772
- }
3773
- try {
3774
- N == null || N(De);
3775
- } catch (Ze) {
3776
- console.error("[use-chat] Error in onEvent callback:", Ze, "for event:", De.type);
3777
- }
3778
- if (De.type === "message.delta") {
3779
- const Ze = De.delta.filter((Rt) => Rt.type === "text").map((Rt) => Rt.text).join("");
3780
- Ze && e.autoAppendAssistant !== !1 && (It.push(Ze), St());
3781
- } else if (De.type === "heartbeat") {
3782
- console.debug("[use-chat] heartbeat received");
3783
- try {
3784
- (V = I == null ? void 0 : I.onHeartbeat) == null || V.call(I, De);
3785
- } catch (Ze) {
3786
- console.warn("[use-chat] heartbeat callback failed", Ze);
3787
- }
3788
- } else if (ze !== null && cancelAnimationFrame(ze), mt(), De.type === "checkpoint")
3789
- v(De.checkpointId);
3790
- else if (De.type === "error") {
3791
- const Ze = De;
3792
- if (d(Ze.message), L = "error", M = Ze.message, Ze.error_type === "auth_error" || Ze.code === "TOKEN_EXPIRED" || ((B = Ze.message) == null ? void 0 : B.includes("token")) || ((ee = Ze.message) == null ? void 0 : ee.includes("401")) || ((Y = Ze.message) == null ? void 0 : Y.includes("unauthorized")) || ((xe = Ze.message) == null ? void 0 : xe.includes("Unauthorized"))) {
3793
- console.error("[use-chat] Auth error detected:", Ze.message);
3794
- try {
3795
- (ae = I == null ? void 0 : I.onAuthError) == null || ae.call(I, Ze.message);
3796
- } catch (Dr) {
3797
- console.warn("[use-chat] onAuthError handler failed", Dr);
3798
- }
3799
- z.abort();
3800
- }
3801
- }
3802
- }
3803
- }
3804
- mt(), L === null && !z.signal.aborted && (L = "complete");
3805
- } catch (Je) {
3806
- if (Je.name === "AbortError")
3807
- L = L ?? "aborted";
3808
- else {
3809
- const Ve = Je.message || String(Je);
3810
- L = "error", M = Ve, d(Ve), (re = I == null ? void 0 : I.onError) == null || re.call(I, Ve);
3811
- }
3812
- } finally {
3813
- try {
3814
- await at.cancel();
3815
- } catch {
3816
- } finally {
3817
- (ge = at.releaseLock) == null || ge.call(at);
3818
- }
3819
- ze !== null && typeof window < "u" && window.cancelAnimationFrame(ze), clearInterval(Pe);
3820
- }
3821
- } catch (We) {
3822
- if (We.name === "AbortError")
3823
- L = L ?? "aborted";
3824
- else {
3825
- const nt = We.message || String(We);
3826
- L = "error", M = nt, d(nt), (be = I == null ? void 0 : I.onError) == null || be.call(I, nt), K || ((_e = I == null ? void 0 : I.onConnectionError) == null || _e.call(I, nt), K = !0);
3827
- }
3828
- } finally {
3829
- const We = b.current, nt = k.current, rt = R.current, Ke = _.current, Xe = L ?? (z.signal.aborted ? "aborted" : M ? "error" : "complete");
3830
- try {
3831
- (Te = I == null ? void 0 : I.onClosed) == null || Te.call(I, {
3832
- reason: Xe,
3833
- lastSeq: We,
3834
- lastCheckpointId: nt,
3835
- lastCheckpointNs: rt,
3836
- lastStateHistory: Ke,
3837
- error: M
3838
- });
3839
- } catch (at) {
3840
- console.warn("[use-chat] onClosed callback failed", at);
3841
- }
3842
- l(!1), w(!1), C.current = null, b.current = 0, y(0), S.current = null;
3843
- }
3844
- })(), { close: () => z.abort() };
3845
3482
  },
3846
- [t, n, r, e.autoAppendAssistant]
3847
- );
3848
- return ut(() => () => {
3849
- var j;
3850
- T.current = !1, (j = C.current) == null || j.abort();
3851
- }, []), {
3852
- isStreaming: a,
3853
- error: c,
3854
- assistantText: f,
3855
- lastCheckpointId: p,
3856
- lastSeq: x,
3857
- connected: g,
3858
- stream: q,
3859
- stop: G,
3860
- clear: F,
3861
- setToken: O
3483
+ [e, n, q]
3484
+ ), M = ue(
3485
+ async (W, U) => {
3486
+ O(!0), R("Sharing thread…");
3487
+ try {
3488
+ await e.shareThread(W, U), await j(), R("Shared successfully");
3489
+ } catch (te) {
3490
+ const H = _y(te);
3491
+ throw n == null || n(H), R(`Failed to share: ${H}`), new Error(H);
3492
+ } finally {
3493
+ O(!1);
3494
+ }
3495
+ },
3496
+ [e, n, j]
3497
+ ), K = ue(
3498
+ async (W, U) => {
3499
+ try {
3500
+ await e.unshareThread(W, U), await j();
3501
+ } catch (te) {
3502
+ const H = String(te);
3503
+ throw n == null || n(H), te;
3504
+ }
3505
+ },
3506
+ [e, n, j]
3507
+ ), J = Me(
3508
+ () => ({
3509
+ createThread: I,
3510
+ deleteThread: z,
3511
+ renameThread: L,
3512
+ refreshThreads: q,
3513
+ refreshSharedThreads: j,
3514
+ refreshSmartOrgUsers: N,
3515
+ shareThread: M,
3516
+ unshareThread: K
3517
+ }),
3518
+ [I, z, L, q, j, N, M, K]
3519
+ ), A = ue((W) => {
3520
+ if (!(W != null && W.threadId)) return;
3521
+ const U = {
3522
+ threadId: W.threadId,
3523
+ title: W.title || `Thread ${W.threadId.slice(0, 8)}`,
3524
+ createdAt: W.createdAt || (/* @__PURE__ */ new Date()).toISOString(),
3525
+ updatedAt: W.updatedAt || (/* @__PURE__ */ new Date()).toISOString(),
3526
+ messageCount: W.messageCount ?? 1
3527
+ };
3528
+ i((te) => {
3529
+ let H = !1;
3530
+ const P = te.map((V) => V.threadId === U.threadId ? (H = !0, console.debug("[useThreadsState] thread_info: updating existing thread", U.threadId), {
3531
+ ...V,
3532
+ title: U.title ?? V.title,
3533
+ updatedAt: U.updatedAt ?? V.updatedAt,
3534
+ messageCount: U.messageCount ?? V.messageCount
3535
+ }) : V);
3536
+ return H ? P : (console.debug("[useThreadsState] thread_info: adding thread to list", U.threadId), [U, ...te]);
3537
+ });
3538
+ }, []), Z = ue(() => R(null), []);
3539
+ return {
3540
+ threads: s,
3541
+ currentThreadId: a,
3542
+ currentThreadIdRef: F,
3543
+ setCurrentThreadId: l,
3544
+ isLoadingThreads: c,
3545
+ threadsError: f,
3546
+ sharedThreads: p,
3547
+ isLoadingSharedThreads: x,
3548
+ smartOrgUsers: w,
3549
+ isLoadingSmartOrgUsers: T,
3550
+ actions: J,
3551
+ addThreadFromEvent: A,
3552
+ shareInFlight: _,
3553
+ shareStatus: k,
3554
+ clearShareStatus: Z
3862
3555
  };
3863
3556
  }
3864
- function Yy(e) {
3865
- return !!e && typeof e == "object" && e.protocolVersion === "v1" && "data" in e;
3557
+ const jt = [];
3558
+ for (let e = 0; e < 256; ++e)
3559
+ jt.push((e + 256).toString(16).slice(1));
3560
+ function Py(e, t = 0) {
3561
+ return (jt[e[t + 0]] + jt[e[t + 1]] + jt[e[t + 2]] + jt[e[t + 3]] + "-" + jt[e[t + 4]] + jt[e[t + 5]] + "-" + jt[e[t + 6]] + jt[e[t + 7]] + "-" + jt[e[t + 8]] + jt[e[t + 9]] + "-" + jt[e[t + 10]] + jt[e[t + 11]] + jt[e[t + 12]] + jt[e[t + 13]] + jt[e[t + 14]] + jt[e[t + 15]]).toLowerCase();
3866
3562
  }
3867
- function Xy(e) {
3868
- const t = e.split(/\r?\n/), n = [];
3869
- for (const r of t)
3870
- if (r && !r.startsWith(":") && r.startsWith("data:")) {
3871
- const o = r.slice(5);
3872
- n.push(o.startsWith(" ") ? o.slice(1) : o);
3563
+ let gi;
3564
+ const Oy = new Uint8Array(16);
3565
+ function Dy() {
3566
+ if (!gi) {
3567
+ if (typeof crypto > "u" || !crypto.getRandomValues)
3568
+ throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");
3569
+ gi = crypto.getRandomValues.bind(crypto);
3570
+ }
3571
+ return gi(Oy);
3572
+ }
3573
+ const Ly = typeof crypto < "u" && crypto.randomUUID && crypto.randomUUID.bind(crypto), tc = { randomUUID: Ly };
3574
+ function $y(e, t, n) {
3575
+ var o;
3576
+ e = e || {};
3577
+ const r = e.random ?? ((o = e.rng) == null ? void 0 : o.call(e)) ?? Dy();
3578
+ if (r.length < 16)
3579
+ throw new Error("Random bytes length must be >= 16");
3580
+ return r[6] = r[6] & 15 | 64, r[8] = r[8] & 63 | 128, Py(r);
3581
+ }
3582
+ function Fy(e, t, n) {
3583
+ return tc.randomUUID && !e ? tc.randomUUID() : $y(e);
3584
+ }
3585
+ function xi(e) {
3586
+ return e.filter((t) => {
3587
+ var s;
3588
+ if (t.role !== "assistant") return !0;
3589
+ const n = (t.content || []).some(
3590
+ (i) => {
3591
+ var a;
3592
+ return i && i.type === "text" && ((a = i.text) == null ? void 0 : a.trim());
3593
+ }
3594
+ ), r = (t.content || []).some((i) => i && i.type === "image_url"), o = !!((s = t.artifact) != null && s.plots && t.artifact.plots.length > 0);
3595
+ return !!(n || r || o);
3596
+ });
3597
+ }
3598
+ function Vo(e, t, n) {
3599
+ return t < 0 || t >= e.length ? e : [...e.slice(0, t), n, ...e.slice(t + 1)];
3600
+ }
3601
+ function Qu(e) {
3602
+ let t = !1;
3603
+ const n = e.map((r) => {
3604
+ const o = (r.content ?? []).filter((s) => s.type !== "interrupt");
3605
+ return o.length !== r.content.length ? (t = !0, { ...r, content: o }) : r;
3606
+ });
3607
+ return t ? n : e;
3608
+ }
3609
+ function nc(e) {
3610
+ for (let t = e.length - 1; t >= 0; t--)
3611
+ if (e[t].role === "assistant") return e[t].id;
3612
+ return null;
3613
+ }
3614
+ function rc(e) {
3615
+ const t = /* @__PURE__ */ new Set(), n = (r) => {
3616
+ typeof r == "string" && r.trim() && t.add(r.trim());
3617
+ };
3618
+ return n(e.id), n(e == null ? void 0 : e.call_id), n(e == null ? void 0 : e.callId), Array.from(t);
3619
+ }
3620
+ function By(e, t) {
3621
+ const n = /* @__PURE__ */ new Set();
3622
+ for (const o of t)
3623
+ typeof o == "string" && o.trim() && n.add(o.trim());
3624
+ const r = qy(e);
3625
+ for (const o of r)
3626
+ n.add(o);
3627
+ return Array.from(n);
3628
+ }
3629
+ function oc(e, t, n) {
3630
+ if (!n.length) return e;
3631
+ let r = !1;
3632
+ const o = { ...e };
3633
+ for (const s of n)
3634
+ s && o[s] !== t && (o[s] = t, r = !0);
3635
+ return r ? o : e;
3636
+ }
3637
+ function zy(e, t, n, r) {
3638
+ const o = /* @__PURE__ */ new Set(), s = (l) => {
3639
+ typeof l == "string" && l.trim() && o.add(l.trim());
3640
+ };
3641
+ for (const l of t)
3642
+ s(l);
3643
+ const i = Array.from(o), a = {};
3644
+ if (i.length) {
3645
+ a.toolCallIds = i;
3646
+ const l = typeof a.toolCallId == "string" ? a.toolCallId.trim() : null;
3647
+ a.toolCallId = l && o.has(l) ? l : i[0];
3648
+ }
3649
+ return n && (a.toolName = n), r !== void 0 && (a.toolArgs = r), a;
3650
+ }
3651
+ function No(e, t, n) {
3652
+ const r = e.findIndex((c) => c.id === t);
3653
+ if (r === -1) return e;
3654
+ const o = e[r], s = [...e], i = { ...o.additionalKwargs ?? {} }, a = Array.isArray(i.toolProgress) ? [...i.toolProgress] : [], l = {
3655
+ id: Fy(),
3656
+ idx: a.length + 1,
3657
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
3658
+ ...n
3659
+ };
3660
+ return a.push(l), Ry(o.id, a, {
3661
+ checkpointId: o.checkpointId ?? null,
3662
+ checkpointNs: o.checkpointNs ?? null
3663
+ }), i.toolProgress = a, s[r] = { ...o, additionalKwargs: i }, s;
3664
+ }
3665
+ function sc(e, t) {
3666
+ return e.includes(t) ? e : [...e, t];
3667
+ }
3668
+ function Uy(e, t) {
3669
+ const n = [...e], r = n.lastIndexOf(t);
3670
+ return r !== -1 && n.splice(r, 1), n;
3671
+ }
3672
+ function yr(e, t) {
3673
+ let n = !1;
3674
+ const r = {}, o = e.map((s) => {
3675
+ const i = Gy(s);
3676
+ if (i.length)
3677
+ return r[s.id] = i, s;
3678
+ const a = t[s.id] ?? Ny(s.id);
3679
+ if (a != null && a.length) {
3680
+ const l = [...a];
3681
+ r[s.id] = l, n = !0;
3682
+ const c = { ...s.additionalKwargs ?? {}, toolProgress: l };
3683
+ return { ...s, additionalKwargs: c };
3684
+ }
3685
+ return s;
3686
+ });
3687
+ return {
3688
+ messages: n ? o : e,
3689
+ toolTimelines: r
3690
+ };
3691
+ }
3692
+ function ed(e) {
3693
+ return !e || !e.length ? "" : e.filter((t) => t.type === "text").map((t) => t.text ?? "").join("");
3694
+ }
3695
+ function Hy(e, t, n, r) {
3696
+ const o = { ...n };
3697
+ if (r !== null && typeof r == "number") {
3698
+ if (typeof o.lastSeq == "number" && r <= o.lastSeq)
3699
+ return { newParts: e, newMeta: o, changed: !1 };
3700
+ o.lastSeq = r;
3701
+ }
3702
+ const s = t.filter((f) => f.type === "text").map((f) => f.text ?? "").join(""), i = t.filter((f) => f.type !== "text"), a = o.lastText ?? ed(e);
3703
+ let l = "", c = e.slice();
3704
+ if (s) {
3705
+ const f = Wy(a, s);
3706
+ if (f === "" ? l = "" : f === s ? l = s : l = f, l) {
3707
+ const h = c[c.length - 1];
3708
+ if ((h == null ? void 0 : h.type) === "text") {
3709
+ const p = h.text ?? "", v = { ...h, text: p + l };
3710
+ c = [...c.slice(0, c.length - 1), v];
3711
+ } else
3712
+ c = [...c, { type: "text", text: l }];
3713
+ o.lastText = a + l;
3714
+ } else
3715
+ o.lastText = a;
3716
+ }
3717
+ i.length && (c = [...c, ...i]);
3718
+ const d = !!(l || i.length);
3719
+ return { newParts: c, newMeta: o, changed: d };
3720
+ }
3721
+ function ic(e) {
3722
+ return e.replace(/\s+/g, " ").trim();
3723
+ }
3724
+ function Wy(e, t) {
3725
+ if (!t) return "";
3726
+ if (!e) return t;
3727
+ if (e === t) return "";
3728
+ const n = Math.min(e.length, t.length);
3729
+ for (let i = n; i > 0; i--)
3730
+ if (e.slice(-i) === t.slice(0, i))
3731
+ return t.slice(i);
3732
+ const r = ic(e), o = ic(t);
3733
+ if (r === o) return "";
3734
+ const s = Math.min(r.length, o.length);
3735
+ for (let i = s; i > 0; i--)
3736
+ if (r.slice(-i) === o.slice(0, i))
3737
+ return t;
3738
+ return t;
3739
+ }
3740
+ function Vy(e, t, n) {
3741
+ for (let r = e.length - 1; r >= 0; r--)
3742
+ if (e[r].role === "assistant") {
3743
+ const s = { ...e[r], checkpointId: t, checkpointNs: n ?? void 0 };
3744
+ return Vo(e, r, s);
3745
+ }
3746
+ return e;
3747
+ }
3748
+ function Ky(e) {
3749
+ if (!e) return null;
3750
+ const t = e.split("/");
3751
+ return t[t.length - 1] || null;
3752
+ }
3753
+ function qy(e) {
3754
+ if (!e) return [];
3755
+ const t = /* @__PURE__ */ new Set(), n = (o) => {
3756
+ typeof o == "string" && o.trim() && t.add(o.trim());
3757
+ }, r = e.additionalKwargs;
3758
+ if (r) {
3759
+ n(r.toolCallId);
3760
+ const o = r.toolCallIds;
3761
+ if (Array.isArray(o))
3762
+ for (const s of o)
3763
+ n(s);
3764
+ }
3765
+ for (const o of e.content ?? [])
3766
+ (o == null ? void 0 : o.type) === "tool_call" && n(o.id);
3767
+ return Array.from(t);
3768
+ }
3769
+ function Gy(e) {
3770
+ const t = e.additionalKwargs ?? {};
3771
+ return Array.isArray(t.toolProgress) ? [...t.toolProgress] : [];
3772
+ }
3773
+ const Yy = {
3774
+ messages: [],
3775
+ assemblingId: null,
3776
+ lastCheckpointId: null,
3777
+ lastCheckpointNs: null,
3778
+ toolIndex: {},
3779
+ toolStreamingMessageId: null,
3780
+ toolStreamingStack: [],
3781
+ messagesStreamMeta: {},
3782
+ pendingInterrupt: null,
3783
+ toolTimelines: {}
3784
+ };
3785
+ function Xy(e, t) {
3786
+ var n;
3787
+ switch (t.type) {
3788
+ case "reset":
3789
+ return {
3790
+ messages: xi(((n = t.payload) == null ? void 0 : n.messages) ?? []),
3791
+ assemblingId: null,
3792
+ lastCheckpointId: null,
3793
+ lastCheckpointNs: null,
3794
+ toolIndex: {},
3795
+ toolStreamingMessageId: null,
3796
+ toolStreamingStack: [],
3797
+ pendingInterrupt: null,
3798
+ toolTimelines: {}
3799
+ };
3800
+ case "user_message": {
3801
+ const { message: r, editingMessageId: o } = t.payload;
3802
+ if (o) {
3803
+ const s = e.messages.findIndex((i) => i.id === o);
3804
+ if (s >= 0) {
3805
+ const i = e.messages.slice(0, s);
3806
+ return { ...e, messages: [...i, r] };
3807
+ }
3808
+ }
3809
+ return { ...e, messages: [...e.messages, r] };
3873
3810
  }
3874
- return n.length === 0 ? null : n.join(`
3875
- `);
3811
+ case "seed": {
3812
+ const r = xi(t.payload.messages), { messages: o, toolTimelines: s } = yr(
3813
+ r,
3814
+ e.toolTimelines
3815
+ ), i = {
3816
+ ...e,
3817
+ messages: o,
3818
+ // REPLACE with incoming messages (don't merge with existing)
3819
+ assemblingId: null,
3820
+ // Clear any streaming state on seed
3821
+ pendingInterrupt: t.payload.pendingInterrupt ?? null,
3822
+ toolStreamingMessageId: null,
3823
+ toolStreamingStack: [],
3824
+ toolTimelines: s
3825
+ };
3826
+ return Object.prototype.hasOwnProperty.call(t.payload, "checkpointId") && (i.lastCheckpointId = t.payload.checkpointId ?? null), Object.prototype.hasOwnProperty.call(t.payload, "checkpointNs") && (i.lastCheckpointNs = t.payload.checkpointNs ?? null), i;
3827
+ }
3828
+ case "prepend": {
3829
+ const r = xi(t.payload.messages);
3830
+ if (!r.length)
3831
+ return e;
3832
+ const o = new Set(e.messages.map((c) => c.id)), s = r.filter((c) => !o.has(c.id));
3833
+ if (!s.length)
3834
+ return e;
3835
+ const i = [...s, ...e.messages], { messages: a, toolTimelines: l } = yr(
3836
+ i,
3837
+ e.toolTimelines
3838
+ );
3839
+ return { ...e, messages: a, toolTimelines: l };
3840
+ }
3841
+ case "event":
3842
+ return ac(e, t.payload.ev);
3843
+ case "batch": {
3844
+ const { events: r } = t.payload;
3845
+ return r.length ? r.reduce((o, s) => ac(o, s), e) : e;
3846
+ }
3847
+ case "interrupt_response":
3848
+ return { ...e, messages: Qu(e.messages), pendingInterrupt: null };
3849
+ default:
3850
+ return e;
3851
+ }
3876
3852
  }
3877
- const Jy = ["message.start", "message.delta", "message.end"], Zy = ["tool.start", "tool.end", "tool.progress"], Qy = ["thread_info", "checkpoint"], ev = ["error", "interrupt", "heartbeat", "state_history", "cancelled"], tv = [
3878
- ...Jy,
3879
- ...Zy,
3880
- ...Qy,
3881
- ...ev
3882
- ], nv = new Set(tv);
3883
- function rv(e) {
3884
- if (typeof e != "object" || e === null || typeof e.type != "string")
3885
- return !1;
3886
- const t = e.type;
3887
- return nv.has(t);
3853
+ function Jy(e = []) {
3854
+ const [t, n] = Um(Xy, { ...Yy, messages: e }), r = $e([]), o = $e(null), s = $e(null), i = ue(() => {
3855
+ o.current !== null && typeof window < "u" && window.cancelAnimationFrame(o.current), s.current !== null && clearTimeout(s.current), o.current = null, s.current = null;
3856
+ const d = r.current;
3857
+ d.length && (r.current = [], n({ type: "batch", payload: { events: d } }));
3858
+ }, []), a = ue(() => {
3859
+ typeof window < "u" && typeof window.requestAnimationFrame == "function" ? o.current === null && (o.current = window.requestAnimationFrame(() => i())) : s.current === null && (s.current = setTimeout(i, 8));
3860
+ }, [i]), l = ue((d) => {
3861
+ r.current.push(d), a();
3862
+ }, [a]);
3863
+ ut(() => () => {
3864
+ o.current !== null && typeof window < "u" && window.cancelAnimationFrame(o.current), s.current !== null && clearTimeout(s.current), r.current = [];
3865
+ }, []);
3866
+ const c = Me(() => ({
3867
+ reset: (d) => n({ type: "reset", payload: { messages: d } }),
3868
+ seed: (d, f) => n({ type: "seed", payload: { messages: d, ...f ?? {} } }),
3869
+ prepend: (d) => n({ type: "prepend", payload: { messages: d } }),
3870
+ pushUser: (d, f) => n({ type: "user_message", payload: { message: d, editingMessageId: f } }),
3871
+ onEvent: l
3872
+ }), [l]);
3873
+ return { state: t, dispatch: n, ...c };
3888
3874
  }
3889
- const lc = 200;
3890
- function ov({
3891
- baseUrl: e,
3892
- onThreadInfo: t,
3893
- onMessageEvent: n,
3894
- onStateHistory: r,
3895
- onUnhandledEvent: o,
3896
- onSequenceGap: s,
3897
- onStreamClosed: i,
3898
- onConnectionError: a,
3899
- onAuthError: l,
3900
- onHeartbeat: c
3901
- }) {
3902
- const d = $e(null), f = $e(null), h = $e(/* @__PURE__ */ new Map()), p = $e(null), v = $e(null), x = ue((N) => {
3903
- try {
3904
- const I = globalThis.structuredClone;
3905
- if (typeof I == "function")
3906
- return I(N);
3907
- } catch {
3908
- }
3909
- try {
3910
- return JSON.parse(JSON.stringify(N));
3911
- } catch {
3912
- return N;
3875
+ function ac(e, t) {
3876
+ var n, r, o, s;
3877
+ if (t.type === "message.start" && t.role === "assistant") {
3878
+ const i = t.id, a = Ky(t.model);
3879
+ if (e.messages.some((d) => d.id === i)) {
3880
+ const d = e.messagesStreamMeta ?? {}, f = {
3881
+ ...d,
3882
+ [i]: d[i] ?? { lastSeq: t.seq ?? null, lastText: "" }
3883
+ };
3884
+ return { ...e, assemblingId: i, messagesStreamMeta: f };
3913
3885
  }
3914
- }, []), y = ue(
3915
- (N, I) => {
3916
- if (!N) return;
3917
- const z = h.current.get(N) ?? [], L = x(I), M = z.length >= lc ? [...z.slice(z.length - lc + 1), L] : [...z, L];
3918
- h.current.set(N, M);
3919
- },
3920
- [x]
3921
- ), g = ue((N) => {
3922
- N && h.current.set(N, []);
3923
- }, []), w = ue(
3924
- (N) => {
3925
- const I = N ?? f.current;
3926
- if (!I) return;
3927
- const z = h.current.get(I);
3928
- z != null && z.length && z.forEach((L) => {
3929
- try {
3930
- n(L);
3931
- } catch (M) {
3932
- console.error("[useChatStreamingService] Failed to replay buffered event", M);
3933
- }
3934
- });
3935
- },
3936
- [n]
3937
- ), C = ue(
3938
- (N) => {
3939
- f.current = N.threadId, p.current && (p.current.threadIdGuess = N.threadId), v.current = N, g(N.threadId), console.log("[useChatStreamingService] 🎯 Received thread_info event:", N);
3940
- try {
3941
- t(N);
3942
- } catch (I) {
3943
- console.error("[useChatStreamingService] Error in onThreadInfo handler:", I);
3944
- }
3945
- },
3946
- [g, t]
3947
- ), T = ue(
3948
- (N) => {
3949
- try {
3950
- c == null || c(N);
3951
- } catch (I) {
3952
- console.error("[useChatStreamingService] Error in onHeartbeat handler:", I);
3953
- }
3954
- },
3955
- [c]
3956
- ), b = ue(
3957
- (N) => {
3958
- var L, M, K, J;
3959
- const I = N;
3960
- if (I.error_type === "auth_error" || I.code === "TOKEN_EXPIRED" || ((L = I.message) == null ? void 0 : L.includes("token")) || ((M = I.message) == null ? void 0 : M.includes("401")) || ((K = I.message) == null ? void 0 : K.includes("unauthorized")) || ((J = I.message) == null ? void 0 : J.includes("Unauthorized"))) {
3961
- console.error("[useChatStreamingService] Auth error event detected:", I.message);
3962
- try {
3963
- l == null || l(I.message);
3964
- } catch (A) {
3965
- console.warn("[useChatStreamingService] onAuthError handler failed", A);
3966
- }
3886
+ const c = {
3887
+ id: i,
3888
+ role: "assistant",
3889
+ name: a || void 0,
3890
+ model: t.model,
3891
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
3892
+ content: []
3893
+ };
3894
+ return { ...e, assemblingId: i, messages: [...e.messages, c] };
3895
+ }
3896
+ if (t.type === "message.delta") {
3897
+ const i = e.assemblingId ?? nc(e.messages);
3898
+ if (!i) return e;
3899
+ const a = e.messages, l = a.findIndex((C) => C.id === i && C.role === "assistant");
3900
+ if (l === -1) return e;
3901
+ const c = a[l], d = e.messagesStreamMeta ?? {}, f = d[i] ?? { lastSeq: null, lastText: ed(c.content) }, h = t.seq ?? null;
3902
+ if (h !== null && typeof h == "number" && typeof f.lastSeq == "number" && h <= f.lastSeq)
3903
+ return console.debug("[MessageReducer] skipping delta - seq <= lastSeq", { seq: h, lastSeq: f.lastSeq }), e;
3904
+ const { newParts: p, newMeta: v, changed: x } = Hy(c.content, t.delta, f, h);
3905
+ if (!x) return e;
3906
+ const y = { ...c, content: p }, g = Vo(a, l, y), w = { ...d, [i]: v };
3907
+ return { ...e, messages: g, messagesStreamMeta: w };
3908
+ }
3909
+ if (t.type === "message.end") {
3910
+ const i = e.assemblingId ?? nc(e.messages);
3911
+ if (!i) return { ...e, assemblingId: null };
3912
+ const a = e.messages, l = a.findIndex((c) => c.id === i && c.role === "assistant");
3913
+ if (l >= 0) {
3914
+ const c = a[l];
3915
+ if (!((n = c.content) == null ? void 0 : n.some((f) => {
3916
+ var h;
3917
+ return (f == null ? void 0 : f.type) === "text" && ((h = f.text) == null ? void 0 : h.trim());
3918
+ }))) {
3919
+ console.debug("[MessageReducer] pruning assistant message with no visible text", {
3920
+ id: c.id,
3921
+ contentTypes: (r = c.content) == null ? void 0 : r.map((h) => h == null ? void 0 : h.type),
3922
+ contentPreview: (o = c.content) == null ? void 0 : o.map((h) => (h == null ? void 0 : h.type) === "text" ? String(h.text).slice(0, 100) : h == null ? void 0 : h.type)
3923
+ });
3924
+ const f = [...a.slice(0, l), ...a.slice(l + 1)];
3925
+ return { ...e, assemblingId: null, messages: f };
3967
3926
  }
3968
- },
3969
- [l]
3970
- ), S = Me(
3971
- () => ({
3972
- thread_info: (N) => (C(N), !0),
3973
- heartbeat: (N) => (T(N), !0),
3974
- error: (N) => (b(N), !1)
3975
- }),
3976
- [C, T, b]
3977
- ), k = ue(
3978
- (N) => {
3979
- var M;
3980
- const I = N.seq ?? null;
3981
- if (I !== null) {
3982
- const K = d.current;
3983
- if (K !== null) {
3984
- if (I <= K)
3985
- return;
3986
- I > K + 1 && (s == null || s({ from: K, to: I }));
3987
- }
3988
- d.current = I;
3927
+ }
3928
+ return e;
3929
+ }
3930
+ if (t.type === "tool.start") {
3931
+ const i = rc(t), a = i[0] ?? (typeof t.id == "string" ? t.id : null) ?? (typeof t.call_id == "string" ? t.call_id : null), l = t.name ?? t.tool ?? "tool";
3932
+ !a && i.length === 0 && i.push(`${l}-${Date.now()}`);
3933
+ const c = i.length ? i : a ? [a] : [], d = c[0] ?? `${l}-${Date.now()}`, f = { type: "tool_call", id: d, name: l, args: t.args }, h = {
3934
+ type: e.toolStreamingMessageId ? "tool.call" : "tool.start",
3935
+ toolId: a ?? d,
3936
+ toolName: l,
3937
+ metadata: {
3938
+ args: t.args
3989
3939
  }
3990
- const z = S[N.type];
3991
- if (z && z(N))
3992
- return;
3993
- const L = N.threadId ?? (N.type === "state_history" ? N.threadId : void 0) ?? f.current ?? ((M = p.current) == null ? void 0 : M.threadIdGuess) ?? null;
3994
- if (N.type === "state_history") {
3995
- f.current = L ?? f.current;
3996
- try {
3997
- r == null || r(N);
3998
- } catch (K) {
3999
- console.error("[useChatStreamingService] onStateHistory handler failed", K);
3940
+ }, p = e.toolStreamingMessageId;
3941
+ if (!p) {
3942
+ const w = {
3943
+ id: `tool-${d}`,
3944
+ role: "tool",
3945
+ name: l,
3946
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
3947
+ content: [f],
3948
+ additionalKwargs: {
3949
+ ...zy(void 0, c.length ? c : [d], l, t.args),
3950
+ toolStreaming: !0
4000
3951
  }
3952
+ }, C = By(w, c.length ? c : [d]), T = [...e.messages, w], b = No(T, w.id, h), { messages: S, toolTimelines: k } = yr(b, e.toolTimelines);
3953
+ return {
3954
+ ...e,
3955
+ messages: S,
3956
+ toolIndex: oc(e.toolIndex, w.id, C),
3957
+ toolStreamingMessageId: w.id,
3958
+ toolStreamingStack: sc(e.toolStreamingStack ?? [], a ?? d),
3959
+ toolTimelines: k
3960
+ };
3961
+ }
3962
+ const v = No(e.messages, p, h), { messages: x, toolTimelines: y } = yr(v, e.toolTimelines);
3963
+ return {
3964
+ ...e,
3965
+ messages: x,
3966
+ toolIndex: oc(e.toolIndex, p, c),
3967
+ toolStreamingStack: sc(e.toolStreamingStack ?? [], a ?? d),
3968
+ toolTimelines: y
3969
+ };
3970
+ }
3971
+ if (t.type === "tool.end") {
3972
+ const i = rc(t);
3973
+ if (!i.length && !(typeof t.id == "string" && t.id))
3974
+ return e;
3975
+ const a = i[0] ?? (typeof t.id == "string" ? t.id : null);
3976
+ if (!a)
3977
+ return e;
3978
+ const l = e.toolStreamingStack ?? [], c = l[0] ?? null, d = Uy(l, a), f = d[0] ? e.toolIndex[d[0]] : null, h = e.toolStreamingMessageId, p = c === a, v = t.name ?? ((s = e.messages.find((b) => b.id === h)) == null ? void 0 : s.name) ?? "tool", x = typeof t.output == "string" ? t.output.trim() : JSON.stringify(t.output ?? ""), y = {
3979
+ type: "tool.end",
3980
+ toolId: a,
3981
+ toolName: v,
3982
+ content: x == null ? void 0 : x.slice(0, 200)
3983
+ };
3984
+ let g = e.messages;
3985
+ if (h && (g = No(g, h, y)), p && h) {
3986
+ const b = g.findIndex((S) => S.id === h);
3987
+ if (b >= 0) {
3988
+ const S = g[b], R = {
3989
+ type: "text",
3990
+ text: (() => {
3991
+ if (typeof t.output == "string") {
3992
+ const O = t.output.trim();
3993
+ try {
3994
+ return O;
3995
+ } catch {
3996
+ return O;
3997
+ }
3998
+ }
3999
+ return JSON.stringify(t.output ?? "");
4000
+ })()
4001
+ }, _ = {
4002
+ ...S,
4003
+ content: [R],
4004
+ artifact: t.artifact ?? S.artifact,
4005
+ additionalKwargs: { ...S.additionalKwargs ?? {} }
4006
+ };
4007
+ g = Vo(g, b, _);
4001
4008
  }
4002
- if (rv(N)) {
4003
- N.type === "checkpoint" || N.type === "state_history" ? g(L ?? null) : y(L ?? null, N);
4009
+ }
4010
+ const w = d, { messages: C, toolTimelines: T } = yr(g, e.toolTimelines);
4011
+ return {
4012
+ ...e,
4013
+ messages: C,
4014
+ toolTimelines: T,
4015
+ toolStreamingMessageId: p ? f : h,
4016
+ toolStreamingStack: w
4017
+ };
4018
+ }
4019
+ if (t.type === "tool.progress") {
4020
+ const i = e.toolStreamingMessageId;
4021
+ if (!i)
4022
+ return e;
4023
+ const a = {
4024
+ type: "tool.progress",
4025
+ content: t.content ?? null
4026
+ }, l = No(e.messages, i, a), c = l.findIndex((y) => y.id === i);
4027
+ if (c === -1)
4028
+ return e;
4029
+ const d = l[c], f = {
4030
+ ...d.additionalKwargs ?? {},
4031
+ toolStreaming: !0
4032
+ }, h = { ...d, additionalKwargs: f }, p = Vo(l, c, h), { messages: v, toolTimelines: x } = yr(p, e.toolTimelines);
4033
+ return { ...e, messages: v, toolTimelines: x };
4034
+ }
4035
+ if (t.type === "checkpoint") {
4036
+ const i = t.checkpointNs ?? e.lastCheckpointNs ?? null, a = Vy(e.messages, t.checkpointId, i);
4037
+ return { ...e, lastCheckpointId: t.checkpointId, lastCheckpointNs: i, messages: a };
4038
+ }
4039
+ if (t.type === "error") {
4040
+ const i = {
4041
+ id: `err-${Date.now()}`,
4042
+ role: "system",
4043
+ content: [{ type: "text", text: `Error: ${t.message}` }],
4044
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
4045
+ };
4046
+ return { ...e, messages: [...e.messages, i] };
4047
+ }
4048
+ if (t.type === "state_history") {
4049
+ const i = xr(t), a = i.interrupt, l = i.latest, c = a === null ? Qu(e.messages) : e.messages;
4050
+ return {
4051
+ ...e,
4052
+ messages: c,
4053
+ pendingInterrupt: a,
4054
+ lastCheckpointId: (l == null ? void 0 : l.checkpointId) ?? e.lastCheckpointId,
4055
+ lastCheckpointNs: (l == null ? void 0 : l.checkpointNs) ?? e.lastCheckpointNs
4056
+ };
4057
+ }
4058
+ return t.type === "thread_info", e;
4059
+ }
4060
+ function Zy(e = {}) {
4061
+ const t = Me(() => En(e.baseUrl), [e.baseUrl]), n = e.streamPath ?? "/runs/stream", [r, o] = de(e.token ?? null), s = $e(e.headers ?? {}), i = e.credentials ?? "include", [a, l] = de(!1), [c, d] = de(null), [f, h] = de(""), [p, v] = de(null), [x, y] = de(0), [g, w] = de(!1), C = $e(null), T = $e(!0), b = $e(0), S = $e(null), k = $e(null), R = $e(null), _ = $e(null), O = ue((j) => {
4062
+ o(j);
4063
+ }, []), F = ue(() => {
4064
+ h(""), v(null), d(null), k.current = null, R.current = null, _.current = null;
4065
+ }, []), G = ue(() => {
4066
+ var j;
4067
+ console.debug("[use-chat] stop() invoked - aborting stream"), (j = C.current) == null || j.abort(), C.current = null, S.current = null, l(!1), w(!1), b.current = 0, y(0);
4068
+ }, []), q = ue(
4069
+ (j, N, I) => {
4070
+ C.current && (C.current.abort(), C.current = null), l(!0), d(null), e.autoAppendAssistant !== !1 && h(""), v(null), k.current = null, R.current = null, _.current = null;
4071
+ const z = new AbortController();
4072
+ C.current = z;
4073
+ let L = null, M = null, K = !1;
4074
+ return S.current = {
4075
+ threadId: j.threadId ?? null,
4076
+ headers: {}
4077
+ }, (async () => {
4078
+ var A, Z, W, U, te, H, P, V, B, ee, Y, xe, ae, re, ge, be, _e, Te;
4079
+ const J = (We) => {
4080
+ var nt;
4081
+ try {
4082
+ const rt = JSON.parse(JSON.stringify(We));
4083
+ return (nt = rt == null ? void 0 : rt.payload) != null && nt.files_info && Array.isArray(rt.payload.files_info) && (rt.payload.files_info = rt.payload.files_info.map((Ke) => ({
4084
+ ...Ke,
4085
+ data: Ke != null && Ke.data ? `<base64 ${String(Ke.data).length} chars>` : Ke == null ? void 0 : Ke.data
4086
+ }))), rt;
4087
+ } catch {
4088
+ return We;
4089
+ }
4090
+ };
4004
4091
  try {
4005
- n(N);
4006
- } catch (K) {
4007
- console.error("[useChatStreamingService] Error in onMessageEvent handler:", K);
4008
- }
4009
- return;
4010
- }
4011
- try {
4012
- o == null || o(N);
4013
- } catch (K) {
4014
- console.error("[useChatStreamingService] Error in onUnhandledEvent handler:", K);
4015
- }
4016
- },
4017
- [y, g, n, s, r, o, S]
4018
- ), { stream: R, stop: _, isStreaming: O, error: F, setToken: G } = Gy({
4019
- baseUrl: e,
4020
- token: void 0
4021
- }), q = ue(
4022
- (N, I) => {
4023
- d.current = null, v.current = null, f.current = N.threadId ?? null, p.current = {
4024
- request: N,
4025
- callbacks: I,
4026
- manualStop: !1,
4027
- threadIdGuess: N.threadId ?? null
4028
- }, R(
4029
- N,
4030
- k,
4031
- {
4032
- onOpen: I == null ? void 0 : I.onOpen,
4033
- onError: (z) => {
4034
- var L;
4035
- (L = I == null ? void 0 : I.onError) == null || L.call(I, z);
4036
- },
4037
- onGap: (I == null ? void 0 : I.onGap) ?? s,
4038
- onConnectionError: (z) => {
4039
- var L;
4040
- a == null || a(z), (L = I == null ? void 0 : I.onConnectionError) == null || L.call(I, z);
4041
- },
4042
- onAuthError: (z) => {
4043
- var L;
4044
- l == null || l(z), (L = I == null ? void 0 : I.onAuthError) == null || L.call(I, z);
4045
- },
4046
- onHeartbeat: (z) => {
4047
- var L;
4048
- try {
4049
- c == null || c(z);
4050
- } catch (M) {
4051
- console.warn("[useChatStreamingService] onHeartbeat handler failed", M);
4092
+ let We = {};
4093
+ try {
4094
+ if (r)
4095
+ We = { Authorization: `Bearer ${r}` };
4096
+ else if (typeof window < "u") {
4097
+ const Ve = window.__AUTH_TOKEN__, dt = ((A = window.localStorage) == null ? void 0 : A.getItem("authToken")) || null;
4098
+ let Et = null;
4099
+ try {
4100
+ const X = (Z = window.localStorage) == null ? void 0 : Z.getItem("chat-settings");
4101
+ X && (Et = ((W = JSON.parse(X)) == null ? void 0 : W.apiKey) || null);
4102
+ } catch {
4103
+ }
4104
+ const qe = Ve || dt || Et || null;
4105
+ qe && (We = { Authorization: `Bearer ${qe}` });
4052
4106
  }
4107
+ } catch {
4108
+ }
4109
+ console.debug(
4110
+ "[use-chat] POST",
4111
+ t + n,
4112
+ J(j)
4113
+ );
4114
+ let nt = {};
4115
+ if (typeof window < "u")
4053
4116
  try {
4054
- (L = I == null ? void 0 : I.onHeartbeat) == null || L.call(I, z);
4055
- } catch (M) {
4056
- console.warn("[useChatStreamingService] downstream onHeartbeat handler failed", M);
4117
+ const Je = (U = window.localStorage) == null ? void 0 : U.getItem("authSessionId");
4118
+ Je && (nt = { "X-Session-Id": Je });
4119
+ } catch {
4120
+ }
4121
+ const rt = {
4122
+ ...We,
4123
+ ...nt,
4124
+ ...s.current
4125
+ }, Ke = {
4126
+ "Content-Type": "application/json",
4127
+ Accept: "text/event-stream",
4128
+ ...rt
4129
+ }, Xe = await fetch(t + n, {
4130
+ method: "POST",
4131
+ headers: Ke,
4132
+ body: JSON.stringify(j),
4133
+ signal: z.signal,
4134
+ credentials: i
4135
+ });
4136
+ if (S.current && (S.current.headers = rt), !Xe.ok || !Xe.body) {
4137
+ const Je = await Xe.text().catch(() => "");
4138
+ console.debug(
4139
+ "[use-chat] non-OK response",
4140
+ Xe.status,
4141
+ Je == null ? void 0 : Je.slice(0, 500)
4142
+ );
4143
+ const Ve = `stream ${Xe.status}${Je ? ": " + Je : ""}`;
4144
+ throw (te = I == null ? void 0 : I.onConnectionError) == null || te.call(I, Ve), K = !0, L = "error", M = Ve, new Error(Ve);
4145
+ }
4146
+ w(!0);
4147
+ const at = Xe.body.getReader(), bt = new TextDecoder();
4148
+ let pt = "", It = [];
4149
+ b.current = 0, y(0);
4150
+ let Ie = 0, ze = null;
4151
+ const mt = () => {
4152
+ if (It.length) {
4153
+ const Je = It.join("");
4154
+ It = [], T.current && h((Ve) => Ve + Je);
4155
+ }
4156
+ ze = null;
4157
+ }, St = () => {
4158
+ typeof window < "u" && ze == null && (ze = requestAnimationFrame(mt));
4159
+ };
4160
+ let Pt = Date.now();
4161
+ const Pe = setInterval(() => {
4162
+ var Je;
4163
+ if (Date.now() - Pt > 18e5) {
4164
+ const Ve = "Stream idle timeout";
4165
+ d(Ve), L = "error", M = Ve, z.abort(), (Je = I == null ? void 0 : I.onError) == null || Je.call(I, Ve);
4166
+ }
4167
+ }, 5e3), Wt = 1024 * 1024;
4168
+ try {
4169
+ const Je = Xe.headers.get("X-Thread-Id") || Xe.headers.get("x-thread-id"), Ve = Xe.headers.get("X-Thread-Created") || Xe.headers.get("x-thread-created"), dt = Je ?? null, Et = String(Ve ?? "").toLowerCase() === "true";
4170
+ for (S.current && !S.current.threadId && (S.current = {
4171
+ ...S.current,
4172
+ threadId: dt
4173
+ }), (H = I == null ? void 0 : I.onOpen) == null || H.call(I, { threadId: dt, created: Et }); ; ) {
4174
+ const { value: qe, done: X } = await at.read();
4175
+ if (X) break;
4176
+ pt += bt.decode(qe, { stream: !0 }), pt.length > Wt && (pt = "", console.warn("Stream buffer reset: exceeded 1MB"));
4177
+ let D;
4178
+ for (; (D = pt.indexOf(`
4179
+
4180
+ `)) >= 0; ) {
4181
+ const le = pt.slice(0, D);
4182
+ pt = pt.slice(D + 2);
4183
+ const ye = ev(le);
4184
+ if (!ye) continue;
4185
+ let Ue;
4186
+ try {
4187
+ Ue = JSON.parse(ye);
4188
+ } catch {
4189
+ console.debug("[use-chat] malformed SSE:", ye.slice(0, 200));
4190
+ continue;
4191
+ }
4192
+ const De = Qy(Ue) ? Ue.data : Ue;
4193
+ Pt = Date.now();
4194
+ const gt = De.seq;
4195
+ if (gt !== void 0) {
4196
+ if (gt <= Ie) {
4197
+ console.debug("[use-chat] drop duplicate/out-of-order event", { seq: gt, lastProcessedSeq: Ie, type: De.type });
4198
+ continue;
4199
+ }
4200
+ Ie > 0 && gt > Ie + 1 && ((P = I == null ? void 0 : I.onGap) == null || P.call(I, { from: Ie, to: gt })), Ie = gt, b.current = gt, y(gt);
4201
+ }
4202
+ if (De.type === "checkpoint")
4203
+ k.current = De.checkpointId ?? null, R.current = De.checkpointNs ?? null, v(De.checkpointId ?? null);
4204
+ else if (De.type === "state_history") {
4205
+ _.current = De;
4206
+ try {
4207
+ const Rt = xr(De).latest;
4208
+ Rt && (k.current = Rt.checkpointId ?? null, R.current = Rt.checkpointNs ?? null, v(Rt.checkpointId ?? null));
4209
+ } catch (Ze) {
4210
+ console.warn("[use-chat] Failed to hydrate state_history payload", Ze);
4211
+ }
4212
+ }
4213
+ try {
4214
+ N == null || N(De);
4215
+ } catch (Ze) {
4216
+ console.error("[use-chat] Error in onEvent callback:", Ze, "for event:", De.type);
4217
+ }
4218
+ if (De.type === "message.delta") {
4219
+ const Ze = De.delta.filter((Rt) => Rt.type === "text").map((Rt) => Rt.text).join("");
4220
+ Ze && e.autoAppendAssistant !== !1 && (It.push(Ze), St());
4221
+ } else if (De.type === "heartbeat") {
4222
+ console.debug("[use-chat] heartbeat received");
4223
+ try {
4224
+ (V = I == null ? void 0 : I.onHeartbeat) == null || V.call(I, De);
4225
+ } catch (Ze) {
4226
+ console.warn("[use-chat] heartbeat callback failed", Ze);
4227
+ }
4228
+ } else if (ze !== null && cancelAnimationFrame(ze), mt(), De.type === "checkpoint")
4229
+ v(De.checkpointId);
4230
+ else if (De.type === "error") {
4231
+ const Ze = De;
4232
+ if (d(Ze.message), L = "error", M = Ze.message, Ze.error_type === "auth_error" || Ze.code === "TOKEN_EXPIRED" || ((B = Ze.message) == null ? void 0 : B.includes("token")) || ((ee = Ze.message) == null ? void 0 : ee.includes("401")) || ((Y = Ze.message) == null ? void 0 : Y.includes("unauthorized")) || ((xe = Ze.message) == null ? void 0 : xe.includes("Unauthorized"))) {
4233
+ console.error("[use-chat] Auth error detected:", Ze.message);
4234
+ try {
4235
+ (ae = I == null ? void 0 : I.onAuthError) == null || ae.call(I, Ze.message);
4236
+ } catch (Dr) {
4237
+ console.warn("[use-chat] onAuthError handler failed", Dr);
4238
+ }
4239
+ z.abort();
4240
+ }
4241
+ }
4242
+ }
4057
4243
  }
4058
- },
4059
- onClosed: (z) => {
4060
- var J, A, Z, W;
4061
- const L = ((J = p.current) == null ? void 0 : J.manualStop) ?? !1, M = f.current ?? ((A = p.current) == null ? void 0 : A.threadIdGuess) ?? ((Z = z.lastStateHistory) == null ? void 0 : Z.threadId) ?? null;
4062
- (z.reason === "complete" || z.reason === "aborted" && L) && g(M);
4063
- const K = {
4064
- ...z,
4065
- threadId: M,
4066
- threadInfo: v.current,
4067
- // ✅ Include thread_info for recovery
4068
- manualStop: L
4069
- };
4070
- try {
4071
- i == null || i(K);
4072
- } catch (U) {
4073
- console.warn("[useChatStreamingService] onStreamClosed handler failed", U);
4244
+ mt(), L === null && !z.signal.aborted && (L = "complete");
4245
+ } catch (Je) {
4246
+ if (Je.name === "AbortError")
4247
+ L = L ?? "aborted";
4248
+ else {
4249
+ const Ve = Je.message || String(Je);
4250
+ L = "error", M = Ve, d(Ve), (re = I == null ? void 0 : I.onError) == null || re.call(I, Ve);
4074
4251
  }
4252
+ } finally {
4075
4253
  try {
4076
- (W = I == null ? void 0 : I.onClosed) == null || W.call(I, K);
4077
- } catch (U) {
4078
- console.warn("[useChatStreamingService] downstream onClosed handler failed", U);
4254
+ await at.cancel();
4255
+ } catch {
4256
+ } finally {
4257
+ (ge = at.releaseLock) == null || ge.call(at);
4079
4258
  }
4080
- p.current && (p.current = null);
4081
- }
4082
- }
4083
- );
4084
- },
4085
- [
4086
- g,
4087
- k,
4088
- l,
4089
- a,
4090
- c,
4091
- s,
4092
- i,
4093
- R
4094
- ]
4095
- ), j = ue(() => {
4096
- p.current && (p.current.manualStop = !0), _();
4097
- }, [_]);
4098
- return Me(
4099
- () => ({
4100
- startStream: q,
4101
- stop: j,
4102
- isStreaming: O,
4103
- error: F,
4104
- setAuthToken: G,
4105
- replayBufferedEvents: w
4106
- }),
4107
- [q, j, O, F, G, w]
4108
- );
4109
- }
4110
- function sv({
4111
- api: e,
4112
- seed: t,
4113
- prepend: n,
4114
- onError: r,
4115
- currentThreadId: o,
4116
- initialThreadId: s = null,
4117
- initialCheckpointId: i = null,
4118
- initialCheckpointNs: a = null,
4119
- autoLoadInitial: l = !0,
4120
- isStreaming: c,
4121
- getMessages: d
4122
- }) {
4123
- const [f, h] = de([]), [p, v] = de([]), [x, y] = de(!1), [g, w] = de(null), [C, T] = de(!1), [b, S] = de(!1), [k, R] = de(!1), [_, O] = de(null), F = $e(o), G = $e(null), q = $e(null), j = $e(null), N = $e(null), I = $e(!1), z = $e(null), L = $e(/* @__PURE__ */ new Map());
4124
- ut(() => {
4125
- F.current = o;
4126
- }, [o]);
4127
- const M = ue(
4128
- async (B) => {
4129
- var Y, xe;
4130
- if (!B.threadId) return;
4131
- const ee = B.threadId;
4132
- (Y = B.onStart) == null || Y.call(B), B.setLoading(!0);
4133
- try {
4134
- await B.action(ee);
4135
- } catch (ae) {
4136
- if (F.current === ee) {
4137
- const re = String(ae);
4138
- (xe = B.handleError) == null || xe.call(B, re), r == null || r(re);
4139
- }
4140
- throw ae;
4141
- } finally {
4142
- B.setLoading(!1);
4143
- }
4144
- },
4145
- [r]
4146
- ), K = ue(
4147
- async (B, ee) => {
4148
- if (!B) return;
4149
- const Y = `${B}:${ee ?? "latest"}`, xe = L.current.get(Y);
4150
- if (xe)
4151
- return xe;
4152
- const ae = M({
4153
- threadId: B,
4154
- setLoading: T,
4155
- onStart: () => O(null),
4156
- handleError: (re) => O(re),
4157
- action: async (re) => {
4158
- const ge = await e.getStateHistory({
4159
- threadId: re,
4160
- checkpointId: ee ?? void 0
4161
- });
4162
- if (F.current !== re) {
4163
- console.log(
4164
- `[useThreadHistoryState] Thread changed during load (was ${re}, now ${F.current}), discarding stale data`
4165
- );
4166
- return;
4167
- }
4168
- const { checkpoints: be, timeline: _e } = xr(ge), Te = be.find((We) => We.messages && We.messages.length > 0) ?? (ee ? be.find((We) => We.checkpointId === ee) : null) ?? be[0];
4169
- t((Te == null ? void 0 : Te.messages) ?? [], {
4170
- checkpointId: (Te == null ? void 0 : Te.checkpointId) ?? null,
4171
- checkpointNs: (Te == null ? void 0 : Te.checkpointNs) ?? null
4172
- }), v(_e), h(be), y(!!(Te != null && Te.nextCursor)), w((Te == null ? void 0 : Te.nextCursor) ?? null);
4173
- }
4174
- });
4175
- L.current.set(Y, ae);
4176
- try {
4177
- await ae;
4178
- } finally {
4179
- L.current.delete(Y);
4180
- }
4181
- return F.current === B && (z.current = Y), ae;
4182
- },
4183
- [e, t, M]
4184
- ), J = ue(
4185
- async (B, ee, Y) => {
4186
- Y != null && Y.clearProgress && ec(), N.current = B;
4187
- try {
4188
- await K(B, ee);
4189
- } finally {
4190
- N.current === B && (N.current = null);
4191
- }
4192
- },
4193
- [K]
4194
- ), A = ue((B) => {
4195
- q.current = B;
4196
- }, []), Z = ue((B) => {
4197
- j.current = B;
4198
- }, []), W = ue(
4199
- (B) => {
4200
- const ee = B.threadId ?? F.current;
4201
- if (!ee || F.current && F.current !== ee)
4202
- return;
4203
- const { checkpoints: Y, timeline: xe } = xr(B);
4204
- if (!Y.length)
4205
- return;
4206
- const ae = Y.find((re) => re.messages && re.messages.length > 0) ?? Y.find((re) => !!re.checkpointId) ?? Y[0];
4207
- t((ae == null ? void 0 : ae.messages) ?? [], {
4208
- checkpointId: (ae == null ? void 0 : ae.checkpointId) ?? null,
4209
- checkpointNs: (ae == null ? void 0 : ae.checkpointNs) ?? null
4210
- }), v(xe), h(Y), y(!!(ae != null && ae.nextCursor)), w((ae == null ? void 0 : ae.nextCursor) ?? null), z.current = `${ee}:latest`, q.current = null, j.current = null;
4211
- },
4212
- [t]
4213
- ), U = ue(
4214
- async (B, ee) => {
4215
- ec();
4216
- const Y = F.current;
4217
- await M({
4218
- threadId: Y,
4219
- setLoading: R,
4220
- action: async (xe) => {
4221
- const ae = await e.getStateHistory({
4222
- threadId: xe,
4223
- checkpointId: B,
4224
- checkpointNs: ee ?? void 0
4225
- });
4226
- if (F.current !== xe) {
4227
- console.log(
4228
- `[useThreadHistoryState] Thread changed during checkpoint navigation (was ${xe}, now ${F.current}), discarding stale data`
4229
- );
4230
- return;
4259
+ ze !== null && typeof window < "u" && window.cancelAnimationFrame(ze), clearInterval(Pe);
4231
4260
  }
4232
- const { checkpoints: re, timeline: ge } = xr(ae), be = re.find(
4233
- (_e) => _e.checkpointId === B && (ee ? _e.checkpointNs === ee : !0)
4234
- );
4235
- if (!be) {
4236
- console.warn("[useThreadHistoryState] Requested checkpoint not found:", { checkpointId: B, checkpointNs: ee });
4237
- return;
4261
+ } catch (We) {
4262
+ if (We.name === "AbortError")
4263
+ L = L ?? "aborted";
4264
+ else {
4265
+ const nt = We.message || String(We);
4266
+ L = "error", M = nt, d(nt), (be = I == null ? void 0 : I.onError) == null || be.call(I, nt), K || ((_e = I == null ? void 0 : I.onConnectionError) == null || _e.call(I, nt), K = !0);
4238
4267
  }
4239
- v(ge), h(re), t(be.messages ?? [], {
4240
- checkpointId: be.checkpointId ?? null,
4241
- checkpointNs: be.checkpointNs ?? null
4242
- });
4268
+ } finally {
4269
+ const We = b.current, nt = k.current, rt = R.current, Ke = _.current, Xe = L ?? (z.signal.aborted ? "aborted" : M ? "error" : "complete");
4270
+ try {
4271
+ (Te = I == null ? void 0 : I.onClosed) == null || Te.call(I, {
4272
+ reason: Xe,
4273
+ lastSeq: We,
4274
+ lastCheckpointId: nt,
4275
+ lastCheckpointNs: rt,
4276
+ lastStateHistory: Ke,
4277
+ error: M
4278
+ });
4279
+ } catch (at) {
4280
+ console.warn("[use-chat] onClosed callback failed", at);
4281
+ }
4282
+ l(!1), w(!1), C.current = null, b.current = 0, y(0), S.current = null;
4243
4283
  }
4244
- }).catch(() => {
4245
- });
4246
- },
4247
- [e, t, M]
4248
- ), te = ue(
4249
- (B, ee) => {
4250
- t(d(), {
4251
- checkpointId: B ?? null,
4252
- checkpointNs: ee ?? null
4253
- });
4284
+ })(), { close: () => z.abort() };
4254
4285
  },
4255
- [d, t]
4256
- ), H = ue(async () => {
4257
- F.current && await J(F.current);
4258
- }, [J]), P = ue(async () => {
4259
- const B = F.current;
4260
- !B || !g || await M({
4261
- threadId: B,
4262
- setLoading: S,
4263
- action: async (ee) => {
4264
- const Y = await e.getStateHistory({
4265
- threadId: ee,
4266
- checkpointId: g
4267
- });
4268
- if (F.current !== ee)
4269
- return;
4270
- const { checkpoints: xe } = xr(Y);
4271
- if (xe.length > 0) {
4272
- const ae = xe[xe.length - 1];
4273
- n((ae == null ? void 0 : ae.messages) ?? []), y(!!(ae != null && ae.nextCursor)), w((ae == null ? void 0 : ae.nextCursor) ?? null);
4274
- }
4275
- }
4276
- }).catch(() => {
4277
- });
4278
- }, [e, g, r, n, M]);
4279
- ut(() => {
4280
- if (!l || !o || C || c)
4281
- return;
4282
- if (q.current === o) {
4283
- q.current = null, G.current = o;
4284
- return;
4285
- }
4286
- if (j.current === o) {
4287
- G.current = o;
4288
- return;
4289
- }
4290
- if (N.current === o) {
4291
- N.current = null, G.current = o;
4292
- return;
4293
- }
4294
- if (G.current === o)
4295
- return;
4296
- G.current = o;
4297
- const B = !I.current && !!i && o === s;
4298
- let ee;
4299
- B && i ? (ee = i, I.current = !0, console.log(
4300
- "[useThreadHistoryState] Loading thread with checkpoint:",
4301
- ee,
4302
- a ? `(ns: ${a})` : ""
4303
- )) : console.log("[useThreadHistoryState] Loading thread with latest checkpoint");
4304
- const Y = `${o}:${ee ?? "latest"}`;
4305
- z.current !== Y && J(o, ee);
4306
- }, [
4307
- l,
4308
- o,
4309
- i,
4310
- a,
4311
- s,
4312
- C,
4313
- c,
4314
- J
4315
- ]);
4316
- const V = ue(() => {
4317
- h([]), v([]), y(!1), w(null), T(!1), S(!1), R(!1), O(null), q.current = null, j.current = null, G.current = null, z.current = null, N.current = null;
4318
- }, []);
4319
- return {
4320
- threadCheckpoints: f,
4321
- threadTimeline: p,
4322
- isLoadingThread: C,
4323
- isHistoryLoading: b,
4324
- isLoadingCheckpoint: k,
4325
- threadStateError: _,
4326
- hasMoreHistory: x,
4327
- loadThread: J,
4328
- navigateToCheckpoint: U,
4329
- loadOlderMessages: P,
4330
- setCurrentCheckpointId: te,
4331
- returnToLatest: H,
4332
- handleStateHistoryEvent: W,
4333
- markSkipNextLoad: A,
4334
- markStreamPendingThread: Z,
4335
- resetHistoryState: V
4286
+ [t, n, r, e.autoAppendAssistant]
4287
+ );
4288
+ return ut(() => () => {
4289
+ var j;
4290
+ T.current = !1, (j = C.current) == null || j.abort();
4291
+ }, []), {
4292
+ isStreaming: a,
4293
+ error: c,
4294
+ assistantText: f,
4295
+ lastCheckpointId: p,
4296
+ lastSeq: x,
4297
+ connected: g,
4298
+ stream: q,
4299
+ stop: G,
4300
+ clear: F,
4301
+ setToken: O
4336
4302
  };
4337
4303
  }
4338
- const iv = ["detail", "message", "error", "description", "title"];
4339
- function Vo(e) {
4340
- if (!e) return null;
4341
- if (typeof e == "string") {
4342
- const t = e.trim();
4343
- return t.length ? t : null;
4344
- }
4345
- if (Array.isArray(e)) {
4346
- for (const t of e) {
4347
- const n = Vo(t);
4348
- if (n)
4349
- return n;
4350
- }
4351
- return null;
4352
- }
4353
- if (typeof e == "object") {
4354
- const t = e;
4355
- for (const n of iv) {
4356
- const r = Vo(t[n]);
4357
- if (r)
4358
- return r;
4359
- }
4360
- if ("errors" in t) {
4361
- const n = Vo(t.errors);
4362
- if (n) return n;
4304
+ function Qy(e) {
4305
+ return !!e && typeof e == "object" && e.protocolVersion === "v1" && "data" in e;
4306
+ }
4307
+ function ev(e) {
4308
+ const t = e.split(/\r?\n/), n = [];
4309
+ for (const r of t)
4310
+ if (r && !r.startsWith(":") && r.startsWith("data:")) {
4311
+ const o = r.slice(5);
4312
+ n.push(o.startsWith(" ") ? o.slice(1) : o);
4363
4313
  }
4364
- }
4365
- return null;
4314
+ return n.length === 0 ? null : n.join(`
4315
+ `);
4366
4316
  }
4317
+ const tv = ["message.start", "message.delta", "message.end"], nv = ["tool.start", "tool.end", "tool.progress"], rv = ["thread_info", "checkpoint"], ov = ["error", "interrupt", "heartbeat", "state_history", "cancelled"], sv = [
4318
+ ...tv,
4319
+ ...nv,
4320
+ ...rv,
4321
+ ...ov
4322
+ ], iv = new Set(sv);
4367
4323
  function av(e) {
4368
- if (!e) return "Request failed";
4369
- const t = e.response, n = Vo(t == null ? void 0 : t.data);
4370
- if (n) return n;
4371
- if (t != null && t.statusText)
4372
- return t.statusText;
4373
- if (e instanceof Error && e.message)
4374
- return e.message;
4375
- if (typeof e == "string") {
4376
- const r = e.trim();
4377
- if (r.length) return r;
4378
- }
4379
- return t != null && t.status ? `Request failed with status code ${t.status}` : "Request failed";
4324
+ if (typeof e != "object" || e === null || typeof e.type != "string")
4325
+ return !1;
4326
+ const t = e.type;
4327
+ return iv.has(t);
4380
4328
  }
4329
+ const lc = 200;
4381
4330
  function lv({
4382
- api: e,
4383
- initialThreadId: t = null,
4384
- onError: n,
4385
- onThreadChange: r,
4386
- onCurrentThreadDeleted: o
4331
+ baseUrl: e,
4332
+ onThreadInfo: t,
4333
+ onMessageEvent: n,
4334
+ onStateHistory: r,
4335
+ onUnhandledEvent: o,
4336
+ onSequenceGap: s,
4337
+ onStreamClosed: i,
4338
+ onConnectionError: a,
4339
+ onAuthError: l,
4340
+ onHeartbeat: c
4387
4341
  }) {
4388
- const [s, i] = de([]), [a, l] = de(t), [c, d] = de(!1), [f, h] = de(null), [p, v] = de([]), [x, y] = de(!1), [, g] = de(null), [w, C] = de([]), [T, b] = de(!1), [, S] = de(null), [k, R] = de(null), [_, O] = de(!1), F = $e(a), G = $e(/* @__PURE__ */ new Map());
4389
- ut(() => {
4390
- F.current = a;
4391
- }, [a]);
4392
- const q = ue(async () => {
4393
- d(!0), h(null);
4394
- try {
4395
- const W = await e.listThreads();
4396
- i(W ?? []);
4397
- } catch (W) {
4398
- const U = String(W);
4399
- h(U), n == null || n(U);
4400
- } finally {
4401
- d(!1);
4402
- }
4403
- }, [e, n]), j = ue(async () => {
4404
- y(!0), g(null);
4342
+ const d = $e(null), f = $e(null), h = $e(/* @__PURE__ */ new Map()), p = $e(null), v = $e(null), x = ue((N) => {
4405
4343
  try {
4406
- const W = await e.listSharedThreads();
4407
- v(W ?? []);
4408
- } catch (W) {
4409
- const U = String(W);
4410
- g(U), n == null || n(U);
4411
- } finally {
4412
- y(!1);
4344
+ const I = globalThis.structuredClone;
4345
+ if (typeof I == "function")
4346
+ return I(N);
4347
+ } catch {
4413
4348
  }
4414
- }, [e, n]), N = ue(async () => {
4415
- b(!0), S(null);
4416
4349
  try {
4417
- const W = await e.listSmartOrgUsers();
4418
- C(W ?? []);
4419
- } catch (W) {
4420
- const U = String(W);
4421
- S(U), n == null || n(U);
4422
- } finally {
4423
- b(!1);
4350
+ return JSON.parse(JSON.stringify(N));
4351
+ } catch {
4352
+ return N;
4424
4353
  }
4425
- }, [e, n]);
4426
- ut(() => {
4427
- q(), N();
4428
- }, [N, q]), ut(() => {
4429
- j();
4430
- }, [j]), ut(() => {
4431
- r == null || r(a);
4432
- }, [a, r]);
4433
- const I = ue(
4434
- async (W) => {
4435
- try {
4436
- const U = await e.createThread(W);
4437
- return l(U.threadId), await q(), U.threadId;
4438
- } catch (U) {
4439
- const te = String(U);
4440
- return n == null || n(te), null;
4441
- }
4354
+ }, []), y = ue(
4355
+ (N, I) => {
4356
+ if (!N) return;
4357
+ const z = h.current.get(N) ?? [], L = x(I), M = z.length >= lc ? [...z.slice(z.length - lc + 1), L] : [...z, L];
4358
+ h.current.set(N, M);
4359
+ },
4360
+ [x]
4361
+ ), g = ue((N) => {
4362
+ N && h.current.set(N, []);
4363
+ }, []), w = ue(
4364
+ (N) => {
4365
+ const I = N ?? f.current;
4366
+ if (!I) return;
4367
+ const z = h.current.get(I);
4368
+ z != null && z.length && z.forEach((L) => {
4369
+ try {
4370
+ n(L);
4371
+ } catch (M) {
4372
+ console.error("[useChatStreamingService] Failed to replay buffered event", M);
4373
+ }
4374
+ });
4442
4375
  },
4443
- [e, n, q]
4444
- ), z = ue(
4445
- async (W) => {
4446
- const U = s;
4447
- i((H) => H.filter((P) => P.threadId !== W));
4448
- const te = new AbortController();
4449
- G.current.set(W, te);
4376
+ [n]
4377
+ ), C = ue(
4378
+ (N) => {
4379
+ f.current = N.threadId, p.current && (p.current.threadIdGuess = N.threadId), v.current = N, g(N.threadId), console.log("[useChatStreamingService] 🎯 Received thread_info event:", N);
4450
4380
  try {
4451
- await e.deleteThread(W), F.current === W && (l(null), o == null || o());
4452
- } catch (H) {
4453
- i(U);
4454
- const P = String(H);
4455
- n == null || n(P);
4456
- } finally {
4457
- G.current.delete(W);
4381
+ t(N);
4382
+ } catch (I) {
4383
+ console.error("[useChatStreamingService] Error in onThreadInfo handler:", I);
4458
4384
  }
4459
4385
  },
4460
- [e, o, n, s]
4461
- ), L = ue(
4462
- async (W, U) => {
4386
+ [g, t]
4387
+ ), T = ue(
4388
+ (N) => {
4463
4389
  try {
4464
- await e.updateThread(W, U), await q();
4465
- } catch (te) {
4466
- n == null || n(String(te));
4390
+ c == null || c(N);
4391
+ } catch (I) {
4392
+ console.error("[useChatStreamingService] Error in onHeartbeat handler:", I);
4467
4393
  }
4468
4394
  },
4469
- [e, n, q]
4470
- ), M = ue(
4471
- async (W, U) => {
4472
- O(!0), R("Sharing thread…");
4473
- try {
4474
- await e.shareThread(W, U), await j(), R("Shared successfully");
4475
- } catch (te) {
4476
- const H = av(te);
4477
- throw n == null || n(H), R(`Failed to share: ${H}`), new Error(H);
4478
- } finally {
4479
- O(!1);
4395
+ [c]
4396
+ ), b = ue(
4397
+ (N) => {
4398
+ var L, M, K, J;
4399
+ const I = N;
4400
+ if (I.error_type === "auth_error" || I.code === "TOKEN_EXPIRED" || ((L = I.message) == null ? void 0 : L.includes("token")) || ((M = I.message) == null ? void 0 : M.includes("401")) || ((K = I.message) == null ? void 0 : K.includes("unauthorized")) || ((J = I.message) == null ? void 0 : J.includes("Unauthorized"))) {
4401
+ console.error("[useChatStreamingService] Auth error event detected:", I.message);
4402
+ try {
4403
+ l == null || l(I.message);
4404
+ } catch (A) {
4405
+ console.warn("[useChatStreamingService] onAuthError handler failed", A);
4406
+ }
4480
4407
  }
4481
4408
  },
4482
- [e, n, j]
4483
- ), K = ue(
4484
- async (W, U) => {
4409
+ [l]
4410
+ ), S = Me(
4411
+ () => ({
4412
+ thread_info: (N) => (C(N), !0),
4413
+ heartbeat: (N) => (T(N), !0),
4414
+ error: (N) => (b(N), !1)
4415
+ }),
4416
+ [C, T, b]
4417
+ ), k = ue(
4418
+ (N) => {
4419
+ var M;
4420
+ const I = N.seq ?? null;
4421
+ if (I !== null) {
4422
+ const K = d.current;
4423
+ if (K !== null) {
4424
+ if (I <= K)
4425
+ return;
4426
+ I > K + 1 && (s == null || s({ from: K, to: I }));
4427
+ }
4428
+ d.current = I;
4429
+ }
4430
+ const z = S[N.type];
4431
+ if (z && z(N))
4432
+ return;
4433
+ const L = N.threadId ?? (N.type === "state_history" ? N.threadId : void 0) ?? f.current ?? ((M = p.current) == null ? void 0 : M.threadIdGuess) ?? null;
4434
+ if (N.type === "state_history") {
4435
+ f.current = L ?? f.current;
4436
+ try {
4437
+ r == null || r(N);
4438
+ } catch (K) {
4439
+ console.error("[useChatStreamingService] onStateHistory handler failed", K);
4440
+ }
4441
+ }
4442
+ if (av(N)) {
4443
+ N.type === "checkpoint" || N.type === "state_history" ? g(L ?? null) : y(L ?? null, N);
4444
+ try {
4445
+ n(N);
4446
+ } catch (K) {
4447
+ console.error("[useChatStreamingService] Error in onMessageEvent handler:", K);
4448
+ }
4449
+ return;
4450
+ }
4485
4451
  try {
4486
- await e.unshareThread(W, U), await j();
4487
- } catch (te) {
4488
- const H = String(te);
4489
- throw n == null || n(H), te;
4452
+ o == null || o(N);
4453
+ } catch (K) {
4454
+ console.error("[useChatStreamingService] Error in onUnhandledEvent handler:", K);
4490
4455
  }
4491
4456
  },
4492
- [e, n, j]
4493
- ), J = Me(
4457
+ [y, g, n, s, r, o, S]
4458
+ ), { stream: R, stop: _, isStreaming: O, error: F, setToken: G } = Zy({
4459
+ baseUrl: e,
4460
+ token: void 0
4461
+ }), q = ue(
4462
+ (N, I) => {
4463
+ d.current = null, v.current = null, f.current = N.threadId ?? null, p.current = {
4464
+ request: N,
4465
+ callbacks: I,
4466
+ manualStop: !1,
4467
+ threadIdGuess: N.threadId ?? null
4468
+ }, R(
4469
+ N,
4470
+ k,
4471
+ {
4472
+ onOpen: I == null ? void 0 : I.onOpen,
4473
+ onError: (z) => {
4474
+ var L;
4475
+ (L = I == null ? void 0 : I.onError) == null || L.call(I, z);
4476
+ },
4477
+ onGap: (I == null ? void 0 : I.onGap) ?? s,
4478
+ onConnectionError: (z) => {
4479
+ var L;
4480
+ a == null || a(z), (L = I == null ? void 0 : I.onConnectionError) == null || L.call(I, z);
4481
+ },
4482
+ onAuthError: (z) => {
4483
+ var L;
4484
+ l == null || l(z), (L = I == null ? void 0 : I.onAuthError) == null || L.call(I, z);
4485
+ },
4486
+ onHeartbeat: (z) => {
4487
+ var L;
4488
+ try {
4489
+ c == null || c(z);
4490
+ } catch (M) {
4491
+ console.warn("[useChatStreamingService] onHeartbeat handler failed", M);
4492
+ }
4493
+ try {
4494
+ (L = I == null ? void 0 : I.onHeartbeat) == null || L.call(I, z);
4495
+ } catch (M) {
4496
+ console.warn("[useChatStreamingService] downstream onHeartbeat handler failed", M);
4497
+ }
4498
+ },
4499
+ onClosed: (z) => {
4500
+ var J, A, Z, W;
4501
+ const L = ((J = p.current) == null ? void 0 : J.manualStop) ?? !1, M = f.current ?? ((A = p.current) == null ? void 0 : A.threadIdGuess) ?? ((Z = z.lastStateHistory) == null ? void 0 : Z.threadId) ?? null;
4502
+ (z.reason === "complete" || z.reason === "aborted" && L) && g(M);
4503
+ const K = {
4504
+ ...z,
4505
+ threadId: M,
4506
+ threadInfo: v.current,
4507
+ // ✅ Include thread_info for recovery
4508
+ manualStop: L
4509
+ };
4510
+ try {
4511
+ i == null || i(K);
4512
+ } catch (U) {
4513
+ console.warn("[useChatStreamingService] onStreamClosed handler failed", U);
4514
+ }
4515
+ try {
4516
+ (W = I == null ? void 0 : I.onClosed) == null || W.call(I, K);
4517
+ } catch (U) {
4518
+ console.warn("[useChatStreamingService] downstream onClosed handler failed", U);
4519
+ }
4520
+ p.current && (p.current = null);
4521
+ }
4522
+ }
4523
+ );
4524
+ },
4525
+ [
4526
+ g,
4527
+ k,
4528
+ l,
4529
+ a,
4530
+ c,
4531
+ s,
4532
+ i,
4533
+ R
4534
+ ]
4535
+ ), j = ue(() => {
4536
+ p.current && (p.current.manualStop = !0), _();
4537
+ }, [_]);
4538
+ return Me(
4494
4539
  () => ({
4495
- createThread: I,
4496
- deleteThread: z,
4497
- renameThread: L,
4498
- refreshThreads: q,
4499
- refreshSharedThreads: j,
4500
- refreshSmartOrgUsers: N,
4501
- shareThread: M,
4502
- unshareThread: K
4540
+ startStream: q,
4541
+ stop: j,
4542
+ isStreaming: O,
4543
+ error: F,
4544
+ setAuthToken: G,
4545
+ replayBufferedEvents: w
4503
4546
  }),
4504
- [I, z, L, q, j, N, M, K]
4505
- ), A = ue((W) => {
4506
- if (!(W != null && W.threadId)) return;
4507
- const U = {
4508
- threadId: W.threadId,
4509
- title: W.title || `Thread ${W.threadId.slice(0, 8)}`,
4510
- createdAt: W.createdAt || (/* @__PURE__ */ new Date()).toISOString(),
4511
- updatedAt: W.updatedAt || (/* @__PURE__ */ new Date()).toISOString(),
4512
- messageCount: W.messageCount ?? 1
4513
- };
4514
- i((te) => {
4515
- let H = !1;
4516
- const P = te.map((V) => V.threadId === U.threadId ? (H = !0, console.debug("[useThreadsState] thread_info: updating existing thread", U.threadId), {
4517
- ...V,
4518
- title: U.title ?? V.title,
4519
- updatedAt: U.updatedAt ?? V.updatedAt,
4520
- messageCount: U.messageCount ?? V.messageCount
4521
- }) : V);
4522
- return H ? P : (console.debug("[useThreadsState] thread_info: adding thread to list", U.threadId), [U, ...te]);
4523
- });
4524
- }, []), Z = ue(() => R(null), []);
4525
- return {
4526
- threads: s,
4527
- currentThreadId: a,
4528
- currentThreadIdRef: F,
4529
- setCurrentThreadId: l,
4530
- isLoadingThreads: c,
4531
- threadsError: f,
4532
- sharedThreads: p,
4533
- isLoadingSharedThreads: x,
4534
- smartOrgUsers: w,
4535
- isLoadingSmartOrgUsers: T,
4536
- actions: J,
4537
- addThreadFromEvent: A,
4538
- shareInFlight: _,
4539
- shareStatus: k,
4540
- clearShareStatus: Z
4541
- };
4547
+ [q, j, O, F, G, w]
4548
+ );
4542
4549
  }
4543
4550
  const td = co(null), nd = co(null), rd = co(null);
4544
4551
  co(!1);
@@ -4553,7 +4560,7 @@ function cv({
4553
4560
  onThreadChange: a,
4554
4561
  onConnectionError: l
4555
4562
  }) {
4556
- const { api: c, baseUrl: d } = Ku(), f = Me(() => En(d), [d]), { state: h, seed: p, prepend: v, pushUser: x, onEvent: y } = qy(), {
4563
+ const { api: c, baseUrl: d } = Ku(), f = Me(() => En(d), [d]), { state: h, seed: p, prepend: v, pushUser: x, onEvent: y } = Jy(), {
4557
4564
  threads: g,
4558
4565
  currentThreadId: w,
4559
4566
  setCurrentThreadId: C,
@@ -4569,7 +4576,7 @@ function cv({
4569
4576
  shareInFlight: q,
4570
4577
  shareStatus: j,
4571
4578
  clearShareStatus: N
4572
- } = lv({
4579
+ } = My({
4573
4580
  api: c,
4574
4581
  initialThreadId: t,
4575
4582
  onError: s,
@@ -4592,7 +4599,7 @@ function cv({
4592
4599
  markSkipNextLoad: Y,
4593
4600
  markStreamPendingThread: xe,
4594
4601
  resetHistoryState: ae
4595
- } = sv({
4602
+ } = Ay({
4596
4603
  api: c,
4597
4604
  seed: p,
4598
4605
  prepend: v,
@@ -4606,7 +4613,7 @@ function cv({
4606
4613
  getMessages: L
4607
4614
  }), re = Me(() => sy(M), [M]), ge = ue((Ie) => {
4608
4615
  console.log("[ChatSessionProvider] 🎯 Received thread_info:", Ie.threadId), G(Ie), T.current !== Ie.threadId && ((Ie.created ?? !T.current) && Y(Ie.threadId), xe(Ie.threadId), console.log("[ChatSessionProvider] thread_info: marking to skip auto-load for new thread"), C(Ie.threadId));
4609
- }, [G, Y, xe]), { startStream: be, stop: _e, isStreaming: Te, error: We, setAuthToken: nt } = ov({
4616
+ }, [G, Y, xe]), { startStream: be, stop: _e, isStreaming: Te, error: We, setAuthToken: nt } = lv({
4610
4617
  baseUrl: f,
4611
4618
  onThreadInfo: ge,
4612
4619
  onMessageEvent: y,
@@ -4673,7 +4680,7 @@ function cv({
4673
4680
  role: "user",
4674
4681
  content: qe,
4675
4682
  createdAt: (/* @__PURE__ */ new Date()).toISOString()
4676
- }, D || x(ye));
4683
+ }, D ? x(ye, X) : x(ye));
4677
4684
  const Ue = Ve ? Je : ye ? [ye] : [], De = {
4678
4685
  ...Wt,
4679
4686
  ...Et.length ? { files_info: Et } : {}
@@ -19198,8 +19205,8 @@ export {
19198
19205
  Qx as put,
19199
19206
  Yi as setChatToken,
19200
19207
  Ku as useApi,
19201
- Gy as useChatStream,
19202
- qy as useMessagesReducer,
19208
+ Zy as useChatStream,
19209
+ Jy as useMessagesReducer,
19203
19210
  uv as useStream,
19204
19211
  Ra as useThreadState,
19205
19212
  Ea as useThreads