@ateam-ai-mobile/core 0.1.38 → 0.1.41

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.mjs CHANGED
@@ -108,8 +108,8 @@ async function apiFetch(path, options = {}) {
108
108
  notifyAuthFailure();
109
109
  throw new Error("Session expired");
110
110
  }
111
- const text = await retryRes.text().catch(() => "");
112
- throw new Error(`API ${retryRes.status}: ${text}`);
111
+ const text2 = await retryRes.text().catch(() => "");
112
+ throw new Error(`API ${retryRes.status}: ${text2}`);
113
113
  }
114
114
  if (outcome.ok === "auth_failed") {
115
115
  console.warn(`[adas] refresh auth_failed on ${path} (${outcome.reason}) \u2014 auth failure`);
@@ -119,8 +119,8 @@ async function apiFetch(path, options = {}) {
119
119
  throw new Error(`API 401: refresh transient (${outcome.reason})`);
120
120
  }
121
121
  if (!res.ok) {
122
- const text = await res.text();
123
- throw new Error(`API ${res.status}: ${text}`);
122
+ const text2 = await res.text();
123
+ throw new Error(`API ${res.status}: ${text2}`);
124
124
  }
125
125
  return res.json();
126
126
  }
@@ -150,8 +150,8 @@ async function connectorCall(connectorId, tool, args = {}) {
150
150
  }
151
151
  );
152
152
  if (!res.ok) {
153
- const text = await res.text();
154
- return { ok: false, result: null, error: `HTTP ${res.status}: ${text}` };
153
+ const text2 = await res.text();
154
+ return { ok: false, result: null, error: `HTTP ${res.status}: ${text2}` };
155
155
  }
156
156
  const data = await res.json();
157
157
  if (data.ok !== void 0) return data;
@@ -167,8 +167,8 @@ async function mcpFetch(body) {
167
167
  body: typeof body === "string" ? body : JSON.stringify(body)
168
168
  });
169
169
  if (!res.ok) {
170
- const text = await res.text();
171
- throw new Error(`MCP fetch failed: HTTP ${res.status}: ${text}`);
170
+ const text2 = await res.text();
171
+ throw new Error(`MCP fetch failed: HTTP ${res.status}: ${text2}`);
172
172
  }
173
173
  return res.json();
174
174
  }
@@ -1147,30 +1147,30 @@ async function postJson(path, body, jwt) {
1147
1147
  },
1148
1148
  body: JSON.stringify(body)
1149
1149
  });
1150
- const text = await res.text();
1150
+ const text2 = await res.text();
1151
1151
  let parsed = null;
1152
1152
  try {
1153
- parsed = JSON.parse(text);
1153
+ parsed = JSON.parse(text2);
1154
1154
  } catch {
1155
1155
  }
1156
1156
  if (!res.ok || parsed?.ok === false) {
1157
1157
  if (parsed?.error) throw new Error(parsed.error);
1158
- throw new Error(cleanErrorMessage(res.status, text, `consumer-auth ${path} failed`));
1158
+ throw new Error(cleanErrorMessage(res.status, text2, `consumer-auth ${path} failed`));
1159
1159
  }
1160
1160
  return parsed;
1161
1161
  }
1162
1162
  async function fetchConsumerConfig() {
1163
1163
  const url = `${getConsumerAuthApiUrl()}/platform/consumer/config?tenant=${encodeURIComponent(getTenant())}`;
1164
1164
  const res = await fetch(url);
1165
- const text = await res.text();
1165
+ const text2 = await res.text();
1166
1166
  let data = null;
1167
1167
  try {
1168
- data = JSON.parse(text);
1168
+ data = JSON.parse(text2);
1169
1169
  } catch {
1170
1170
  }
1171
1171
  if (!res.ok || !data?.ok) {
1172
1172
  if (data?.error) throw new Error(data.error);
1173
- throw new Error(cleanErrorMessage(res.status, text, "Failed to load sign-in config"));
1173
+ throw new Error(cleanErrorMessage(res.status, text2, "Failed to load sign-in config"));
1174
1174
  }
1175
1175
  return data;
1176
1176
  }
@@ -1192,16 +1192,16 @@ async function exchangeHandoff(code) {
1192
1192
  async function previewInvite(code) {
1193
1193
  const url = `${getConsumerAuthApiUrl()}/platform/consumer/invite/${encodeURIComponent(code)}`;
1194
1194
  const res = await fetch(url);
1195
- const text = await res.text();
1195
+ const text2 = await res.text();
1196
1196
  let data = null;
1197
1197
  try {
1198
- data = JSON.parse(text);
1198
+ data = JSON.parse(text2);
1199
1199
  } catch {
1200
1200
  }
1201
1201
  if (res.status === 404) throw new Error("This invite is invalid or has expired.");
1202
1202
  if (!res.ok || !data?.ok) {
1203
1203
  if (data?.error) throw new Error(data.error);
1204
- throw new Error(cleanErrorMessage(res.status, text, "Could not load invite"));
1204
+ throw new Error(cleanErrorMessage(res.status, text2, "Could not load invite"));
1205
1205
  }
1206
1206
  return data;
1207
1207
  }
@@ -1481,7 +1481,7 @@ var COMPARISON_BLOCK_CLOSE = "\uE109";
1481
1481
  var TIMELINE_BLOCK_OPEN = "\uE10A";
1482
1482
  var TIMELINE_BLOCK_CLOSE = "\uE10B";
1483
1483
  var SENTINEL_CHARS = /[\uE100-\uE10B]/g;
1484
- var clean = (text) => text.replace(SENTINEL_CHARS, "");
1484
+ var clean = (text2) => text2.replace(SENTINEL_CHARS, "");
1485
1485
  function renderTableShape(content) {
1486
1486
  if (!content || typeof content !== "object") return null;
1487
1487
  const cols = Array.isArray(content.columns) ? content.columns : null;
@@ -1502,14 +1502,14 @@ function diagramView(content) {
1502
1502
  kept[i + 1] = 0;
1503
1503
  if (!s || typeof s !== "object") return;
1504
1504
  const title = str(s.title);
1505
- const text = str(s.text);
1506
- if (!title && !text) return;
1505
+ const text2 = str(s.text);
1506
+ if (!title && !text2) return;
1507
1507
  const badges = [];
1508
1508
  for (const b of Array.isArray(s.badges) ? s.badges : []) {
1509
1509
  const bt = str(b && typeof b === "object" ? b.text : b);
1510
1510
  if (bt) badges.push({ text: bt, status: statusOf(b && b.status) });
1511
1511
  }
1512
- steps.push({ title: title || text, text: title ? text : "", status: statusOf(s.status), badges, decision: s.kind === "decision" || s.decision === true, next: null });
1512
+ steps.push({ title: title || text2, text: title ? text2 : "", status: statusOf(s.status), badges, decision: s.kind === "decision" || s.decision === true, next: null });
1513
1513
  rawNext.push(Array.isArray(s.next) ? s.next : null);
1514
1514
  kept[i + 1] = steps.length;
1515
1515
  });
@@ -1685,10 +1685,10 @@ function blocksToText(blocks) {
1685
1685
  if (!blocks || blocks.length === 0) return "";
1686
1686
  return blocks.map((b) => {
1687
1687
  if (!b || typeof b !== "object") return "";
1688
- const text = blockText(b);
1689
- if (!text) return "";
1690
- if (text.startsWith(TABLE_BLOCK_OPEN) || Object.values(VISUALS).some((v) => text.startsWith(v.open))) return text;
1691
- return b.meta?.display === "folded" ? `${DETAILS_BLOCK_OPEN}${encodeURIComponent(text)}${DETAILS_BLOCK_CLOSE}` : text;
1688
+ const text2 = blockText(b);
1689
+ if (!text2) return "";
1690
+ if (text2.startsWith(TABLE_BLOCK_OPEN) || Object.values(VISUALS).some((v) => text2.startsWith(v.open))) return text2;
1691
+ return b.meta?.display === "folded" ? `${DETAILS_BLOCK_OPEN}${encodeURIComponent(text2)}${DETAILS_BLOCK_CLOSE}` : text2;
1692
1692
  }).filter(Boolean).join("\n\n");
1693
1693
  }
1694
1694
  var PAIRS = [
@@ -1752,6 +1752,32 @@ function plainTextOf(content) {
1752
1752
  }).join("");
1753
1753
  }
1754
1754
 
1755
+ // src/chat/liveGoals.ts
1756
+ var MAX_TOOLS = 4;
1757
+ function foldGoals(prev, wire, liveMessage, liveSeq) {
1758
+ const g = wire && Array.isArray(wire.l) ? wire : null;
1759
+ if (g && g.l.length === 0) return void 0;
1760
+ const goals = g ? { l: g.l, c: g.c ?? null } : prev ? { l: prev.l, c: prev.c } : null;
1761
+ if (!goals) return void 0;
1762
+ const ids = goals.l.map((x) => x[0]).join("|");
1763
+ const tools = ids === prev?.ids ? { ...prev?.tools || {} } : {};
1764
+ const key = liveSeq != null ? `s${liveSeq}` : `m${liveMessage ?? ""}`;
1765
+ const fresh = key !== prev?.lastKey;
1766
+ if (fresh && goals.c && liveMessage && liveMessage.startsWith("\u2192 ")) {
1767
+ const tool = liveMessage.slice(2).trim();
1768
+ const list2 = tools[goals.c] || [];
1769
+ if (tool && list2[list2.length - 1] !== tool) tools[goals.c] = [...list2, tool].slice(-MAX_TOOLS);
1770
+ }
1771
+ return { ...goals, tools, lastKey: key, ids };
1772
+ }
1773
+ function goalRows(goals) {
1774
+ if (!goals?.l?.length) return [];
1775
+ return goals.l.map(([id, title, s]) => {
1776
+ const state = s === "d" ? "done" : id === goals.c ? "current" : "todo";
1777
+ return { id, title, state, tools: state === "current" ? goals.tools?.[id] || [] : [] };
1778
+ });
1779
+ }
1780
+
1755
1781
  // src/chat/store.ts
1756
1782
  function coreHeaders() {
1757
1783
  const token = getToken();
@@ -1787,7 +1813,8 @@ function extractLiveProgress(snap) {
1787
1813
  return {
1788
1814
  message: String(latest.message || ""),
1789
1815
  ...latest.step != null ? { step: latest.step } : {},
1790
- ...latest.total != null ? { total: latest.total } : {}
1816
+ ...latest.total != null ? { total: latest.total } : {},
1817
+ ...latest.seq != null ? { seq: latest.seq } : {}
1791
1818
  };
1792
1819
  }
1793
1820
  function extractCurrentTool(state) {
@@ -1816,6 +1843,7 @@ function snapshotToProgress(snap, rootJobId) {
1816
1843
  if (liveProgress) progress.liveProgress = liveProgress;
1817
1844
  if (typeof snap?.humanStatus === "string" && snap.humanStatus) progress.humanStatus = snap.humanStatus;
1818
1845
  if (snap?.humanLabels && typeof snap.humanLabels === "object") progress.humanLabels = snap.humanLabels;
1846
+ if (snap?.goals && Array.isArray(snap.goals.l)) progress.goalsWire = snap.goals;
1819
1847
  if (pq) {
1820
1848
  progress.pendingQuestion = {
1821
1849
  inputId: pq.correlation_id || pq.correlationId || pq.inputId || "",
@@ -1970,12 +1998,14 @@ var useChatStore = create4((set, get) => ({
1970
1998
  );
1971
1999
  const chainCreatedAt = typeof slim.createdAt === "number" ? slim.createdAt : typeof slim.lastUpdate === "number" ? slim.lastUpdate : Date.now();
1972
2000
  const chainLastUpdate = typeof slim.lastUpdate === "number" ? slim.lastUpdate : chainCreatedAt;
2001
+ const { goalsWire, ...progressRest } = progress;
1973
2002
  const jobProgress = {
1974
2003
  jobId: chainId,
1975
2004
  actorId: extractActorId(slim),
1976
2005
  status: "running",
1977
2006
  chainStartedAt: chainCreatedAt,
1978
- ...progress
2007
+ ...progressRest,
2008
+ goals: foldGoals(void 0, goalsWire, progress.liveProgress?.message, progress.liveProgress?.seq)
1979
2009
  };
1980
2010
  const goal = typeof slim.goal === "string" ? slim.goal : "";
1981
2011
  const userExists = finalMessages.some(
@@ -2034,11 +2064,11 @@ var useChatStore = create4((set, get) => ({
2034
2064
  // Send message via Core API
2035
2065
  // POST /api/chat { goal } → { jobId } → stream → fetch turn result
2036
2066
  // -----------------------------------------------------------------------
2037
- sendMessage: async (text, skillSlug, attachments) => {
2067
+ sendMessage: async (text2, skillSlug, attachments) => {
2038
2068
  const userMsg = {
2039
2069
  id: `user-${Date.now()}`,
2040
2070
  role: "user",
2041
- content: text,
2071
+ content: text2,
2042
2072
  timestamp: /* @__PURE__ */ new Date(),
2043
2073
  ...attachments?.length ? {
2044
2074
  attachments: attachments.map((a) => ({
@@ -2055,7 +2085,7 @@ var useChatStore = create4((set, get) => ({
2055
2085
  try {
2056
2086
  const actor = getUser();
2057
2087
  const body = {
2058
- goal: text,
2088
+ goal: text2,
2059
2089
  // Opt in to the Chain Additions router (attach/cancel/new while a
2060
2090
  // chain runs). Backend ignores it where not applicable — safe to send.
2061
2091
  chainRouting: true,
@@ -2082,11 +2112,11 @@ var useChatStore = create4((set, get) => ({
2082
2112
  if (!res.ok) {
2083
2113
  let errMsg = `Server error (${res.status})`;
2084
2114
  try {
2085
- const text2 = await res.text();
2086
- if (text2.startsWith("<") || text2.startsWith("<!")) {
2115
+ const text3 = await res.text();
2116
+ if (text3.startsWith("<") || text3.startsWith("<!")) {
2087
2117
  errMsg = res.status === 502 ? "Server is temporarily unavailable. Please try again." : `Server error (${res.status})`;
2088
2118
  } else {
2089
- const parsed = JSON.parse(text2);
2119
+ const parsed = JSON.parse(text3);
2090
2120
  errMsg = parsed.error || errMsg;
2091
2121
  }
2092
2122
  } catch {
@@ -2175,7 +2205,9 @@ var useChatStore = create4((set, get) => ({
2175
2205
  set((s) => ({
2176
2206
  messages: s.messages.map((m) => {
2177
2207
  if (m.jobProgress?.jobId === jobId) {
2178
- const updated = { ...m.jobProgress, ...progress };
2208
+ const { goalsWire, ...rest } = progress;
2209
+ const updated = { ...m.jobProgress, ...rest };
2210
+ updated.goals = foldGoals(m.jobProgress.goals, goalsWire, progress.liveProgress?.message, progress.liveProgress?.seq);
2179
2211
  if (progress.status && progress.status !== "paused") {
2180
2212
  updated.pendingQuestion = void 0;
2181
2213
  }
@@ -2369,12 +2401,12 @@ async function fetchTurnResult(jobId, jobSnap) {
2369
2401
  const turn = items[0];
2370
2402
  if (turn?.assistant || turn?.turn?.assistant) {
2371
2403
  const assistant = turn.assistant || turn.turn?.assistant;
2372
- const text = blocksToText(assistant.blocks);
2404
+ const text2 = blocksToText(assistant.blocks);
2373
2405
  const actions = Array.isArray(assistant.actions) && assistant.actions.length ? assistant.actions : void 0;
2374
- if (text) {
2406
+ if (text2) {
2375
2407
  updateJobProgress(jobId, {
2376
2408
  status,
2377
- resultMessage: text,
2409
+ resultMessage: text2,
2378
2410
  ...actions ? { resultActions: actions } : {}
2379
2411
  });
2380
2412
  return;
@@ -2427,6 +2459,186 @@ async function pollJob(jobId, token) {
2427
2459
  }
2428
2460
  }
2429
2461
 
2462
+ // src/chat/sideChat.ts
2463
+ import { create as create5 } from "zustand";
2464
+
2465
+ // src/chat/sideChatPure.ts
2466
+ var SIDE_CHAT_LIMITS = { title: 60, header: 40, welcome: 200, placeholder: 60 };
2467
+ var HEX = /^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/;
2468
+ var text = (v, max) => typeof v === "string" ? v.replace(/\s+/g, " ").trim().slice(0, max) : "";
2469
+ function sideChatOptions(payload) {
2470
+ const p = payload && typeof payload === "object" ? payload : {};
2471
+ return {
2472
+ title: text(p.title, SIDE_CHAT_LIMITS.title),
2473
+ header: text(p.header, SIDE_CHAT_LIMITS.header),
2474
+ welcome: text(p.welcome, SIDE_CHAT_LIMITS.welcome),
2475
+ placeholder: text(p.placeholder, SIDE_CHAT_LIMITS.placeholder),
2476
+ accent: typeof p.accent === "string" && HEX.test(p.accent.trim()) ? p.accent.trim() : null,
2477
+ side: p.side === "left" ? "left" : "right"
2478
+ };
2479
+ }
2480
+ var SHORT = /* @__PURE__ */ new Set(["ui", "ai", "mcp", "api", "crm", "sms", "pa"]);
2481
+ var nameOf = (slug) => slug.split(/[-_]+/).filter(Boolean).map((w) => SHORT.has(w.toLowerCase()) ? w.toUpperCase() : w[0].toUpperCase() + w.slice(1)).join(" ");
2482
+ function topicLabel(pageId, title) {
2483
+ if (title) return title;
2484
+ const last = String(pageId || "").split(":").pop() || "";
2485
+ return nameOf(last) || "Side chat";
2486
+ }
2487
+ function mergeSideChatHistory(saved, current) {
2488
+ const savedChains = new Set(saved.map((m) => m.chainId).filter(Boolean));
2489
+ const keep = current.filter((m) => m.local && !(m.chainId && savedChains.has(m.chainId)));
2490
+ return [...saved, ...keep];
2491
+ }
2492
+
2493
+ // src/chat/sideChat.ts
2494
+ var HISTORY_TURNS = 20;
2495
+ var stores = /* @__PURE__ */ new Map();
2496
+ function getSideChatStore(pageId) {
2497
+ const key = `${getTenant()}\0${pageId}`;
2498
+ let s = stores.get(key);
2499
+ if (!s) {
2500
+ s = createSideChatStore(pageId);
2501
+ stores.set(key, s);
2502
+ }
2503
+ return s;
2504
+ }
2505
+ function clearSideChats() {
2506
+ stores.clear();
2507
+ }
2508
+ function turnToMessages(turn) {
2509
+ const out = [];
2510
+ const chainId = typeof turn?.chainId === "string" ? turn.chainId : void 0;
2511
+ const base = turn?.jobId || turn?.chainId || `${turn?.startedAt || Date.now()}`;
2512
+ const userText = blocksToText(turn?.user?.blocks);
2513
+ const userAtts = blocksToAttachments(turn?.user?.blocks);
2514
+ if (userText || userAtts) {
2515
+ out.push({ id: `user-${base}`, role: "user", content: userText || "", timestamp: new Date(turn.startedAt || Date.now()), ...userAtts ? { attachments: userAtts } : {}, ...chainId ? { chainId } : {} });
2516
+ }
2517
+ const answer = blocksToText(turn?.assistant?.blocks);
2518
+ const actions = Array.isArray(turn?.assistant?.actions) && turn.assistant.actions.length ? turn.assistant.actions : void 0;
2519
+ if (answer || actions) {
2520
+ out.push({ id: `bot-${base}`, role: "assistant", content: answer || "", timestamp: new Date(turn.finishedAt || turn.startedAt || Date.now()), skillSlug: turn.skillSlug, ...actions ? { actions } : {}, ...chainId ? { chainId } : {} });
2521
+ } else if (turn?.status === "failed") {
2522
+ out.push({ id: `err-${base}`, role: "system", content: turn.failReason || "This turn failed.", timestamp: new Date(turn.finishedAt || turn.startedAt || Date.now()), ...chainId ? { chainId } : {} });
2523
+ }
2524
+ return out;
2525
+ }
2526
+ function createSideChatStore(pageId) {
2527
+ return create5((set, get) => {
2528
+ const local = (m) => ({ ...m, local: true });
2529
+ const patchJob = (jobId, p) => {
2530
+ const { goalsWire, ...rest } = p;
2531
+ set((s) => ({
2532
+ messages: s.messages.map((m) => m.jobProgress?.jobId === jobId ? { ...m, jobProgress: { ...m.jobProgress, ...rest, goals: foldGoals(m.jobProgress.goals, goalsWire, p.liveProgress?.message, p.liveProgress?.seq) } } : m)
2533
+ }));
2534
+ };
2535
+ async function follow(jobId, chainId) {
2536
+ let ended = null;
2537
+ for (let i = 0; !ended; i++) {
2538
+ if (i > 0) await new Promise((r) => setTimeout(r, i < 120 ? 1500 : 5e3));
2539
+ if (!get().messages.some((m) => m.jobProgress?.jobId === jobId)) return;
2540
+ try {
2541
+ const res = await fetch(`${getCoreApiUrl()}/api/job/${encodeURIComponent(jobId)}/status`, { headers: coreHeaders() });
2542
+ if (!res.ok) {
2543
+ if (res.status === 404) break;
2544
+ continue;
2545
+ }
2546
+ const snap = await res.json();
2547
+ const handoff = snap?.isHandoff || snap?.state?.handoffTransfer;
2548
+ if (isTerminalSnapshot(snap) && !(normalizeJobStatus(snap) === "done" && handoff)) ended = snap;
2549
+ else patchJob(jobId, snapshotToProgress(snap, jobId));
2550
+ } catch {
2551
+ }
2552
+ }
2553
+ for (let t = 0; t < 5; t++) {
2554
+ await get().load();
2555
+ if (!get().messages.some((m) => m.jobProgress?.jobId === jobId)) {
2556
+ set({ loading: false });
2557
+ return;
2558
+ }
2559
+ await new Promise((r) => setTimeout(r, 800));
2560
+ }
2561
+ const failed = ended ? normalizeJobStatus(ended) === "error" : false;
2562
+ const fallback = ended?.result?.message || ended?.state?.finalReply || (failed ? "Something went wrong. Please try again." : "Done.");
2563
+ set((s) => ({
2564
+ loading: false,
2565
+ messages: s.messages.map((m) => m.jobProgress?.jobId === jobId ? { ...m, id: `done-${jobId}`, content: fallback, jobProgress: { ...m.jobProgress, status: failed ? "error" : "done" }, chainId } : m)
2566
+ }));
2567
+ }
2568
+ return {
2569
+ pageId,
2570
+ messages: [],
2571
+ loading: false,
2572
+ loaded: false,
2573
+ load: async () => {
2574
+ try {
2575
+ const res = await fetch(`${getCoreApiUrl()}/api/conversation?topic=${encodeURIComponent(pageId)}&page_size=${HISTORY_TURNS}`, { headers: coreHeaders() });
2576
+ if (!res.ok) {
2577
+ set({ loaded: true });
2578
+ return;
2579
+ }
2580
+ const json = await res.json();
2581
+ const items = Array.isArray(json?.items) ? [...json.items].reverse() : [];
2582
+ const seen = /* @__PURE__ */ new Set();
2583
+ const saved = items.filter((t) => {
2584
+ const k = t?.jobId;
2585
+ if (!k) return true;
2586
+ if (seen.has(k)) return false;
2587
+ seen.add(k);
2588
+ return true;
2589
+ }).flatMap(turnToMessages);
2590
+ set((s) => ({ messages: mergeSideChatHistory(saved, s.messages), loaded: true }));
2591
+ } catch {
2592
+ set({ loaded: true });
2593
+ }
2594
+ },
2595
+ send: async (text2) => {
2596
+ const t = text2.trim();
2597
+ if (!t || get().loading) return false;
2598
+ const echo = local({ id: `user-${Date.now()}`, role: "user", content: t, timestamp: /* @__PURE__ */ new Date() });
2599
+ set((s) => ({ messages: [...s.messages, echo], loading: true }));
2600
+ const fail = (msg) => set((s) => ({ loading: false, messages: [...s.messages, local({ id: `error-${Date.now()}`, role: "system", content: msg, timestamp: /* @__PURE__ */ new Date() })] }));
2601
+ try {
2602
+ const actor = getUser();
2603
+ const res = await fetch(`${getCoreApiUrl()}/api/chat`, {
2604
+ method: "POST",
2605
+ headers: coreHeaders(),
2606
+ body: JSON.stringify({
2607
+ goal: t,
2608
+ triggerContext: {
2609
+ channel: "mobile",
2610
+ replyContext: { chatId: actor?.actorId || "unknown" },
2611
+ pageContext: { page: pageId, chat: "page" }
2612
+ }
2613
+ })
2614
+ });
2615
+ const json = await res.json().catch(() => null);
2616
+ const jobId = json?.jobId || json?.id;
2617
+ if (!res.ok || !jobId) {
2618
+ fail(json?.error || `Could not start (${res.status}).`);
2619
+ return false;
2620
+ }
2621
+ const chainId = json.job?.chainId || jobId;
2622
+ const bubble = local({
2623
+ id: `job-${jobId}`,
2624
+ role: "assistant",
2625
+ content: "Working on it...",
2626
+ timestamp: /* @__PURE__ */ new Date(),
2627
+ chainId,
2628
+ jobProgress: { jobId, actorId: actor?.actorId, status: "running", subStatus: "Starting...", chainStartedAt: Date.now() }
2629
+ });
2630
+ set((s) => ({ messages: [...s.messages.map((m) => m.id === echo.id ? { ...m, chainId } : m), bubble] }));
2631
+ void follow(jobId, chainId);
2632
+ return true;
2633
+ } catch (e) {
2634
+ fail(`Request failed: ${e?.message || e}`);
2635
+ return false;
2636
+ }
2637
+ }
2638
+ };
2639
+ });
2640
+ }
2641
+
2430
2642
  // src/api/tenants.ts
2431
2643
  function nestByMaster(tenants) {
2432
2644
  const ids = new Set(tenants.map((t) => t.id));
@@ -2494,6 +2706,7 @@ async function switchTenant(targetTenantId) {
2494
2706
  await onSession(session);
2495
2707
  closeChatStream();
2496
2708
  useChatStore.getState().clearChat();
2709
+ clearSideChats();
2497
2710
  return session;
2498
2711
  }
2499
2712
 
@@ -2609,6 +2822,7 @@ export {
2609
2822
  MAX_ATTACHMENT_BYTES,
2610
2823
  MAX_INLINE_ATTACHMENT_BYTES,
2611
2824
  PluginCommandEmitter,
2825
+ SIDE_CHAT_LIMITS,
2612
2826
  TABLE_BLOCK_CLOSE,
2613
2827
  TABLE_BLOCK_OPEN,
2614
2828
  TIMELINE_BLOCK_CLOSE,
@@ -2623,6 +2837,7 @@ export {
2623
2837
  chartAsText,
2624
2838
  chartScale,
2625
2839
  chartView,
2840
+ clearSideChats,
2626
2841
  closeChatStream,
2627
2842
  colors,
2628
2843
  comparisonAsText,
@@ -2649,10 +2864,12 @@ export {
2649
2864
  getPrefs as getNotifPrefs,
2650
2865
  getTelegramBotInfo as getNotifTelegramBotInfo,
2651
2866
  getSession,
2867
+ getSideChatStore,
2652
2868
  getTenant,
2653
2869
  getToken,
2654
2870
  getUser,
2655
2871
  getVoiceApiUrl,
2872
+ goalRows,
2656
2873
  initAdas,
2657
2874
  isAdasInitialized,
2658
2875
  isDevHost,
@@ -2668,6 +2885,7 @@ export {
2668
2885
  listSurface,
2669
2886
  mcpFetch,
2670
2887
  mcpToolCall,
2888
+ mergeSideChatHistory,
2671
2889
  nestByMaster,
2672
2890
  notifyAcsWsForeground,
2673
2891
  notifyAppForeground,
@@ -2700,6 +2918,7 @@ export {
2700
2918
  setHomeActionOrder,
2701
2919
  setPrefs as setNotifPrefs,
2702
2920
  setOrder,
2921
+ sideChatOptions,
2703
2922
  signInWithApple,
2704
2923
  signInWithGoogle,
2705
2924
  spacing,
@@ -2708,6 +2927,7 @@ export {
2708
2927
  tenantFromToken,
2709
2928
  timelineAsText,
2710
2929
  timelineView,
2930
+ topicLabel,
2711
2931
  unlinkChannel as unlinkNotifChannel,
2712
2932
  unregisterDevice as unregisterPushDevice,
2713
2933
  unwrapMcpResult,