@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.js CHANGED
@@ -32,6 +32,7 @@ __export(index_exports, {
32
32
  MAX_ATTACHMENT_BYTES: () => MAX_ATTACHMENT_BYTES,
33
33
  MAX_INLINE_ATTACHMENT_BYTES: () => MAX_INLINE_ATTACHMENT_BYTES,
34
34
  PluginCommandEmitter: () => PluginCommandEmitter,
35
+ SIDE_CHAT_LIMITS: () => SIDE_CHAT_LIMITS,
35
36
  TABLE_BLOCK_CLOSE: () => TABLE_BLOCK_CLOSE,
36
37
  TABLE_BLOCK_OPEN: () => TABLE_BLOCK_OPEN,
37
38
  TIMELINE_BLOCK_CLOSE: () => TIMELINE_BLOCK_CLOSE,
@@ -46,6 +47,7 @@ __export(index_exports, {
46
47
  chartAsText: () => chartAsText,
47
48
  chartScale: () => chartScale,
48
49
  chartView: () => chartView,
50
+ clearSideChats: () => clearSideChats,
49
51
  closeChatStream: () => closeChatStream,
50
52
  colors: () => colors,
51
53
  comparisonAsText: () => comparisonAsText,
@@ -72,10 +74,12 @@ __export(index_exports, {
72
74
  getNotifPrefs: () => getPrefs,
73
75
  getNotifTelegramBotInfo: () => getTelegramBotInfo,
74
76
  getSession: () => getSession,
77
+ getSideChatStore: () => getSideChatStore,
75
78
  getTenant: () => getTenant,
76
79
  getToken: () => getToken,
77
80
  getUser: () => getUser,
78
81
  getVoiceApiUrl: () => getVoiceApiUrl,
82
+ goalRows: () => goalRows,
79
83
  initAdas: () => initAdas,
80
84
  isAdasInitialized: () => isAdasInitialized,
81
85
  isDevHost: () => isDevHost,
@@ -91,6 +95,7 @@ __export(index_exports, {
91
95
  listSurface: () => listSurface,
92
96
  mcpFetch: () => mcpFetch,
93
97
  mcpToolCall: () => mcpToolCall,
98
+ mergeSideChatHistory: () => mergeSideChatHistory,
94
99
  nestByMaster: () => nestByMaster,
95
100
  notifyAcsWsForeground: () => notifyAcsWsForeground,
96
101
  notifyAppForeground: () => notifyAppForeground,
@@ -123,6 +128,7 @@ __export(index_exports, {
123
128
  setHomeActionOrder: () => setHomeActionOrder,
124
129
  setNotifPrefs: () => setPrefs,
125
130
  setOrder: () => setOrder,
131
+ sideChatOptions: () => sideChatOptions,
126
132
  signInWithApple: () => signInWithApple,
127
133
  signInWithGoogle: () => signInWithGoogle,
128
134
  spacing: () => spacing,
@@ -131,6 +137,7 @@ __export(index_exports, {
131
137
  tenantFromToken: () => tenantFromToken,
132
138
  timelineAsText: () => timelineAsText,
133
139
  timelineView: () => timelineView,
140
+ topicLabel: () => topicLabel,
134
141
  unlinkNotifChannel: () => unlinkChannel,
135
142
  unregisterPushDevice: () => unregisterDevice,
136
143
  unwrapMcpResult: () => unwrapMcpResult,
@@ -254,8 +261,8 @@ async function apiFetch(path, options = {}) {
254
261
  notifyAuthFailure();
255
262
  throw new Error("Session expired");
256
263
  }
257
- const text = await retryRes.text().catch(() => "");
258
- throw new Error(`API ${retryRes.status}: ${text}`);
264
+ const text2 = await retryRes.text().catch(() => "");
265
+ throw new Error(`API ${retryRes.status}: ${text2}`);
259
266
  }
260
267
  if (outcome.ok === "auth_failed") {
261
268
  console.warn(`[adas] refresh auth_failed on ${path} (${outcome.reason}) \u2014 auth failure`);
@@ -265,8 +272,8 @@ async function apiFetch(path, options = {}) {
265
272
  throw new Error(`API 401: refresh transient (${outcome.reason})`);
266
273
  }
267
274
  if (!res.ok) {
268
- const text = await res.text();
269
- throw new Error(`API ${res.status}: ${text}`);
275
+ const text2 = await res.text();
276
+ throw new Error(`API ${res.status}: ${text2}`);
270
277
  }
271
278
  return res.json();
272
279
  }
@@ -296,8 +303,8 @@ async function connectorCall(connectorId, tool, args = {}) {
296
303
  }
297
304
  );
298
305
  if (!res.ok) {
299
- const text = await res.text();
300
- return { ok: false, result: null, error: `HTTP ${res.status}: ${text}` };
306
+ const text2 = await res.text();
307
+ return { ok: false, result: null, error: `HTTP ${res.status}: ${text2}` };
301
308
  }
302
309
  const data = await res.json();
303
310
  if (data.ok !== void 0) return data;
@@ -313,8 +320,8 @@ async function mcpFetch(body) {
313
320
  body: typeof body === "string" ? body : JSON.stringify(body)
314
321
  });
315
322
  if (!res.ok) {
316
- const text = await res.text();
317
- throw new Error(`MCP fetch failed: HTTP ${res.status}: ${text}`);
323
+ const text2 = await res.text();
324
+ throw new Error(`MCP fetch failed: HTTP ${res.status}: ${text2}`);
318
325
  }
319
326
  return res.json();
320
327
  }
@@ -1293,30 +1300,30 @@ async function postJson(path, body, jwt) {
1293
1300
  },
1294
1301
  body: JSON.stringify(body)
1295
1302
  });
1296
- const text = await res.text();
1303
+ const text2 = await res.text();
1297
1304
  let parsed = null;
1298
1305
  try {
1299
- parsed = JSON.parse(text);
1306
+ parsed = JSON.parse(text2);
1300
1307
  } catch {
1301
1308
  }
1302
1309
  if (!res.ok || parsed?.ok === false) {
1303
1310
  if (parsed?.error) throw new Error(parsed.error);
1304
- throw new Error(cleanErrorMessage(res.status, text, `consumer-auth ${path} failed`));
1311
+ throw new Error(cleanErrorMessage(res.status, text2, `consumer-auth ${path} failed`));
1305
1312
  }
1306
1313
  return parsed;
1307
1314
  }
1308
1315
  async function fetchConsumerConfig() {
1309
1316
  const url = `${getConsumerAuthApiUrl()}/platform/consumer/config?tenant=${encodeURIComponent(getTenant())}`;
1310
1317
  const res = await fetch(url);
1311
- const text = await res.text();
1318
+ const text2 = await res.text();
1312
1319
  let data = null;
1313
1320
  try {
1314
- data = JSON.parse(text);
1321
+ data = JSON.parse(text2);
1315
1322
  } catch {
1316
1323
  }
1317
1324
  if (!res.ok || !data?.ok) {
1318
1325
  if (data?.error) throw new Error(data.error);
1319
- throw new Error(cleanErrorMessage(res.status, text, "Failed to load sign-in config"));
1326
+ throw new Error(cleanErrorMessage(res.status, text2, "Failed to load sign-in config"));
1320
1327
  }
1321
1328
  return data;
1322
1329
  }
@@ -1338,16 +1345,16 @@ async function exchangeHandoff(code) {
1338
1345
  async function previewInvite(code) {
1339
1346
  const url = `${getConsumerAuthApiUrl()}/platform/consumer/invite/${encodeURIComponent(code)}`;
1340
1347
  const res = await fetch(url);
1341
- const text = await res.text();
1348
+ const text2 = await res.text();
1342
1349
  let data = null;
1343
1350
  try {
1344
- data = JSON.parse(text);
1351
+ data = JSON.parse(text2);
1345
1352
  } catch {
1346
1353
  }
1347
1354
  if (res.status === 404) throw new Error("This invite is invalid or has expired.");
1348
1355
  if (!res.ok || !data?.ok) {
1349
1356
  if (data?.error) throw new Error(data.error);
1350
- throw new Error(cleanErrorMessage(res.status, text, "Could not load invite"));
1357
+ throw new Error(cleanErrorMessage(res.status, text2, "Could not load invite"));
1351
1358
  }
1352
1359
  return data;
1353
1360
  }
@@ -1627,7 +1634,7 @@ var COMPARISON_BLOCK_CLOSE = "\uE109";
1627
1634
  var TIMELINE_BLOCK_OPEN = "\uE10A";
1628
1635
  var TIMELINE_BLOCK_CLOSE = "\uE10B";
1629
1636
  var SENTINEL_CHARS = /[\uE100-\uE10B]/g;
1630
- var clean = (text) => text.replace(SENTINEL_CHARS, "");
1637
+ var clean = (text2) => text2.replace(SENTINEL_CHARS, "");
1631
1638
  function renderTableShape(content) {
1632
1639
  if (!content || typeof content !== "object") return null;
1633
1640
  const cols = Array.isArray(content.columns) ? content.columns : null;
@@ -1648,14 +1655,14 @@ function diagramView(content) {
1648
1655
  kept[i + 1] = 0;
1649
1656
  if (!s || typeof s !== "object") return;
1650
1657
  const title = str(s.title);
1651
- const text = str(s.text);
1652
- if (!title && !text) return;
1658
+ const text2 = str(s.text);
1659
+ if (!title && !text2) return;
1653
1660
  const badges = [];
1654
1661
  for (const b of Array.isArray(s.badges) ? s.badges : []) {
1655
1662
  const bt = str(b && typeof b === "object" ? b.text : b);
1656
1663
  if (bt) badges.push({ text: bt, status: statusOf(b && b.status) });
1657
1664
  }
1658
- steps.push({ title: title || text, text: title ? text : "", status: statusOf(s.status), badges, decision: s.kind === "decision" || s.decision === true, next: null });
1665
+ steps.push({ title: title || text2, text: title ? text2 : "", status: statusOf(s.status), badges, decision: s.kind === "decision" || s.decision === true, next: null });
1659
1666
  rawNext.push(Array.isArray(s.next) ? s.next : null);
1660
1667
  kept[i + 1] = steps.length;
1661
1668
  });
@@ -1831,10 +1838,10 @@ function blocksToText(blocks) {
1831
1838
  if (!blocks || blocks.length === 0) return "";
1832
1839
  return blocks.map((b) => {
1833
1840
  if (!b || typeof b !== "object") return "";
1834
- const text = blockText(b);
1835
- if (!text) return "";
1836
- if (text.startsWith(TABLE_BLOCK_OPEN) || Object.values(VISUALS).some((v) => text.startsWith(v.open))) return text;
1837
- return b.meta?.display === "folded" ? `${DETAILS_BLOCK_OPEN}${encodeURIComponent(text)}${DETAILS_BLOCK_CLOSE}` : text;
1841
+ const text2 = blockText(b);
1842
+ if (!text2) return "";
1843
+ if (text2.startsWith(TABLE_BLOCK_OPEN) || Object.values(VISUALS).some((v) => text2.startsWith(v.open))) return text2;
1844
+ return b.meta?.display === "folded" ? `${DETAILS_BLOCK_OPEN}${encodeURIComponent(text2)}${DETAILS_BLOCK_CLOSE}` : text2;
1838
1845
  }).filter(Boolean).join("\n\n");
1839
1846
  }
1840
1847
  var PAIRS = [
@@ -1898,6 +1905,32 @@ function plainTextOf(content) {
1898
1905
  }).join("");
1899
1906
  }
1900
1907
 
1908
+ // src/chat/liveGoals.ts
1909
+ var MAX_TOOLS = 4;
1910
+ function foldGoals(prev, wire, liveMessage, liveSeq) {
1911
+ const g = wire && Array.isArray(wire.l) ? wire : null;
1912
+ if (g && g.l.length === 0) return void 0;
1913
+ const goals = g ? { l: g.l, c: g.c ?? null } : prev ? { l: prev.l, c: prev.c } : null;
1914
+ if (!goals) return void 0;
1915
+ const ids = goals.l.map((x) => x[0]).join("|");
1916
+ const tools = ids === prev?.ids ? { ...prev?.tools || {} } : {};
1917
+ const key = liveSeq != null ? `s${liveSeq}` : `m${liveMessage ?? ""}`;
1918
+ const fresh = key !== prev?.lastKey;
1919
+ if (fresh && goals.c && liveMessage && liveMessage.startsWith("\u2192 ")) {
1920
+ const tool = liveMessage.slice(2).trim();
1921
+ const list2 = tools[goals.c] || [];
1922
+ if (tool && list2[list2.length - 1] !== tool) tools[goals.c] = [...list2, tool].slice(-MAX_TOOLS);
1923
+ }
1924
+ return { ...goals, tools, lastKey: key, ids };
1925
+ }
1926
+ function goalRows(goals) {
1927
+ if (!goals?.l?.length) return [];
1928
+ return goals.l.map(([id, title, s]) => {
1929
+ const state = s === "d" ? "done" : id === goals.c ? "current" : "todo";
1930
+ return { id, title, state, tools: state === "current" ? goals.tools?.[id] || [] : [] };
1931
+ });
1932
+ }
1933
+
1901
1934
  // src/chat/store.ts
1902
1935
  function coreHeaders() {
1903
1936
  const token = getToken();
@@ -1933,7 +1966,8 @@ function extractLiveProgress(snap) {
1933
1966
  return {
1934
1967
  message: String(latest.message || ""),
1935
1968
  ...latest.step != null ? { step: latest.step } : {},
1936
- ...latest.total != null ? { total: latest.total } : {}
1969
+ ...latest.total != null ? { total: latest.total } : {},
1970
+ ...latest.seq != null ? { seq: latest.seq } : {}
1937
1971
  };
1938
1972
  }
1939
1973
  function extractCurrentTool(state) {
@@ -1962,6 +1996,7 @@ function snapshotToProgress(snap, rootJobId) {
1962
1996
  if (liveProgress) progress.liveProgress = liveProgress;
1963
1997
  if (typeof snap?.humanStatus === "string" && snap.humanStatus) progress.humanStatus = snap.humanStatus;
1964
1998
  if (snap?.humanLabels && typeof snap.humanLabels === "object") progress.humanLabels = snap.humanLabels;
1999
+ if (snap?.goals && Array.isArray(snap.goals.l)) progress.goalsWire = snap.goals;
1965
2000
  if (pq) {
1966
2001
  progress.pendingQuestion = {
1967
2002
  inputId: pq.correlation_id || pq.correlationId || pq.inputId || "",
@@ -2116,12 +2151,14 @@ var useChatStore = (0, import_zustand4.create)((set, get) => ({
2116
2151
  );
2117
2152
  const chainCreatedAt = typeof slim.createdAt === "number" ? slim.createdAt : typeof slim.lastUpdate === "number" ? slim.lastUpdate : Date.now();
2118
2153
  const chainLastUpdate = typeof slim.lastUpdate === "number" ? slim.lastUpdate : chainCreatedAt;
2154
+ const { goalsWire, ...progressRest } = progress;
2119
2155
  const jobProgress = {
2120
2156
  jobId: chainId,
2121
2157
  actorId: extractActorId(slim),
2122
2158
  status: "running",
2123
2159
  chainStartedAt: chainCreatedAt,
2124
- ...progress
2160
+ ...progressRest,
2161
+ goals: foldGoals(void 0, goalsWire, progress.liveProgress?.message, progress.liveProgress?.seq)
2125
2162
  };
2126
2163
  const goal = typeof slim.goal === "string" ? slim.goal : "";
2127
2164
  const userExists = finalMessages.some(
@@ -2180,11 +2217,11 @@ var useChatStore = (0, import_zustand4.create)((set, get) => ({
2180
2217
  // Send message via Core API
2181
2218
  // POST /api/chat { goal } → { jobId } → stream → fetch turn result
2182
2219
  // -----------------------------------------------------------------------
2183
- sendMessage: async (text, skillSlug, attachments) => {
2220
+ sendMessage: async (text2, skillSlug, attachments) => {
2184
2221
  const userMsg = {
2185
2222
  id: `user-${Date.now()}`,
2186
2223
  role: "user",
2187
- content: text,
2224
+ content: text2,
2188
2225
  timestamp: /* @__PURE__ */ new Date(),
2189
2226
  ...attachments?.length ? {
2190
2227
  attachments: attachments.map((a) => ({
@@ -2201,7 +2238,7 @@ var useChatStore = (0, import_zustand4.create)((set, get) => ({
2201
2238
  try {
2202
2239
  const actor = getUser();
2203
2240
  const body = {
2204
- goal: text,
2241
+ goal: text2,
2205
2242
  // Opt in to the Chain Additions router (attach/cancel/new while a
2206
2243
  // chain runs). Backend ignores it where not applicable — safe to send.
2207
2244
  chainRouting: true,
@@ -2228,11 +2265,11 @@ var useChatStore = (0, import_zustand4.create)((set, get) => ({
2228
2265
  if (!res.ok) {
2229
2266
  let errMsg = `Server error (${res.status})`;
2230
2267
  try {
2231
- const text2 = await res.text();
2232
- if (text2.startsWith("<") || text2.startsWith("<!")) {
2268
+ const text3 = await res.text();
2269
+ if (text3.startsWith("<") || text3.startsWith("<!")) {
2233
2270
  errMsg = res.status === 502 ? "Server is temporarily unavailable. Please try again." : `Server error (${res.status})`;
2234
2271
  } else {
2235
- const parsed = JSON.parse(text2);
2272
+ const parsed = JSON.parse(text3);
2236
2273
  errMsg = parsed.error || errMsg;
2237
2274
  }
2238
2275
  } catch {
@@ -2321,7 +2358,9 @@ var useChatStore = (0, import_zustand4.create)((set, get) => ({
2321
2358
  set((s) => ({
2322
2359
  messages: s.messages.map((m) => {
2323
2360
  if (m.jobProgress?.jobId === jobId) {
2324
- const updated = { ...m.jobProgress, ...progress };
2361
+ const { goalsWire, ...rest } = progress;
2362
+ const updated = { ...m.jobProgress, ...rest };
2363
+ updated.goals = foldGoals(m.jobProgress.goals, goalsWire, progress.liveProgress?.message, progress.liveProgress?.seq);
2325
2364
  if (progress.status && progress.status !== "paused") {
2326
2365
  updated.pendingQuestion = void 0;
2327
2366
  }
@@ -2515,12 +2554,12 @@ async function fetchTurnResult(jobId, jobSnap) {
2515
2554
  const turn = items[0];
2516
2555
  if (turn?.assistant || turn?.turn?.assistant) {
2517
2556
  const assistant = turn.assistant || turn.turn?.assistant;
2518
- const text = blocksToText(assistant.blocks);
2557
+ const text2 = blocksToText(assistant.blocks);
2519
2558
  const actions = Array.isArray(assistant.actions) && assistant.actions.length ? assistant.actions : void 0;
2520
- if (text) {
2559
+ if (text2) {
2521
2560
  updateJobProgress(jobId, {
2522
2561
  status,
2523
- resultMessage: text,
2562
+ resultMessage: text2,
2524
2563
  ...actions ? { resultActions: actions } : {}
2525
2564
  });
2526
2565
  return;
@@ -2573,6 +2612,186 @@ async function pollJob(jobId, token) {
2573
2612
  }
2574
2613
  }
2575
2614
 
2615
+ // src/chat/sideChat.ts
2616
+ var import_zustand5 = require("zustand");
2617
+
2618
+ // src/chat/sideChatPure.ts
2619
+ var SIDE_CHAT_LIMITS = { title: 60, header: 40, welcome: 200, placeholder: 60 };
2620
+ var HEX = /^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/;
2621
+ var text = (v, max) => typeof v === "string" ? v.replace(/\s+/g, " ").trim().slice(0, max) : "";
2622
+ function sideChatOptions(payload) {
2623
+ const p = payload && typeof payload === "object" ? payload : {};
2624
+ return {
2625
+ title: text(p.title, SIDE_CHAT_LIMITS.title),
2626
+ header: text(p.header, SIDE_CHAT_LIMITS.header),
2627
+ welcome: text(p.welcome, SIDE_CHAT_LIMITS.welcome),
2628
+ placeholder: text(p.placeholder, SIDE_CHAT_LIMITS.placeholder),
2629
+ accent: typeof p.accent === "string" && HEX.test(p.accent.trim()) ? p.accent.trim() : null,
2630
+ side: p.side === "left" ? "left" : "right"
2631
+ };
2632
+ }
2633
+ var SHORT = /* @__PURE__ */ new Set(["ui", "ai", "mcp", "api", "crm", "sms", "pa"]);
2634
+ var nameOf = (slug) => slug.split(/[-_]+/).filter(Boolean).map((w) => SHORT.has(w.toLowerCase()) ? w.toUpperCase() : w[0].toUpperCase() + w.slice(1)).join(" ");
2635
+ function topicLabel(pageId, title) {
2636
+ if (title) return title;
2637
+ const last = String(pageId || "").split(":").pop() || "";
2638
+ return nameOf(last) || "Side chat";
2639
+ }
2640
+ function mergeSideChatHistory(saved, current) {
2641
+ const savedChains = new Set(saved.map((m) => m.chainId).filter(Boolean));
2642
+ const keep = current.filter((m) => m.local && !(m.chainId && savedChains.has(m.chainId)));
2643
+ return [...saved, ...keep];
2644
+ }
2645
+
2646
+ // src/chat/sideChat.ts
2647
+ var HISTORY_TURNS = 20;
2648
+ var stores = /* @__PURE__ */ new Map();
2649
+ function getSideChatStore(pageId) {
2650
+ const key = `${getTenant()}\0${pageId}`;
2651
+ let s = stores.get(key);
2652
+ if (!s) {
2653
+ s = createSideChatStore(pageId);
2654
+ stores.set(key, s);
2655
+ }
2656
+ return s;
2657
+ }
2658
+ function clearSideChats() {
2659
+ stores.clear();
2660
+ }
2661
+ function turnToMessages(turn) {
2662
+ const out = [];
2663
+ const chainId = typeof turn?.chainId === "string" ? turn.chainId : void 0;
2664
+ const base = turn?.jobId || turn?.chainId || `${turn?.startedAt || Date.now()}`;
2665
+ const userText = blocksToText(turn?.user?.blocks);
2666
+ const userAtts = blocksToAttachments(turn?.user?.blocks);
2667
+ if (userText || userAtts) {
2668
+ out.push({ id: `user-${base}`, role: "user", content: userText || "", timestamp: new Date(turn.startedAt || Date.now()), ...userAtts ? { attachments: userAtts } : {}, ...chainId ? { chainId } : {} });
2669
+ }
2670
+ const answer = blocksToText(turn?.assistant?.blocks);
2671
+ const actions = Array.isArray(turn?.assistant?.actions) && turn.assistant.actions.length ? turn.assistant.actions : void 0;
2672
+ if (answer || actions) {
2673
+ 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 } : {} });
2674
+ } else if (turn?.status === "failed") {
2675
+ out.push({ id: `err-${base}`, role: "system", content: turn.failReason || "This turn failed.", timestamp: new Date(turn.finishedAt || turn.startedAt || Date.now()), ...chainId ? { chainId } : {} });
2676
+ }
2677
+ return out;
2678
+ }
2679
+ function createSideChatStore(pageId) {
2680
+ return (0, import_zustand5.create)((set, get) => {
2681
+ const local = (m) => ({ ...m, local: true });
2682
+ const patchJob = (jobId, p) => {
2683
+ const { goalsWire, ...rest } = p;
2684
+ set((s) => ({
2685
+ 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)
2686
+ }));
2687
+ };
2688
+ async function follow(jobId, chainId) {
2689
+ let ended = null;
2690
+ for (let i = 0; !ended; i++) {
2691
+ if (i > 0) await new Promise((r) => setTimeout(r, i < 120 ? 1500 : 5e3));
2692
+ if (!get().messages.some((m) => m.jobProgress?.jobId === jobId)) return;
2693
+ try {
2694
+ const res = await fetch(`${getCoreApiUrl()}/api/job/${encodeURIComponent(jobId)}/status`, { headers: coreHeaders() });
2695
+ if (!res.ok) {
2696
+ if (res.status === 404) break;
2697
+ continue;
2698
+ }
2699
+ const snap = await res.json();
2700
+ const handoff = snap?.isHandoff || snap?.state?.handoffTransfer;
2701
+ if (isTerminalSnapshot(snap) && !(normalizeJobStatus(snap) === "done" && handoff)) ended = snap;
2702
+ else patchJob(jobId, snapshotToProgress(snap, jobId));
2703
+ } catch {
2704
+ }
2705
+ }
2706
+ for (let t = 0; t < 5; t++) {
2707
+ await get().load();
2708
+ if (!get().messages.some((m) => m.jobProgress?.jobId === jobId)) {
2709
+ set({ loading: false });
2710
+ return;
2711
+ }
2712
+ await new Promise((r) => setTimeout(r, 800));
2713
+ }
2714
+ const failed = ended ? normalizeJobStatus(ended) === "error" : false;
2715
+ const fallback = ended?.result?.message || ended?.state?.finalReply || (failed ? "Something went wrong. Please try again." : "Done.");
2716
+ set((s) => ({
2717
+ loading: false,
2718
+ messages: s.messages.map((m) => m.jobProgress?.jobId === jobId ? { ...m, id: `done-${jobId}`, content: fallback, jobProgress: { ...m.jobProgress, status: failed ? "error" : "done" }, chainId } : m)
2719
+ }));
2720
+ }
2721
+ return {
2722
+ pageId,
2723
+ messages: [],
2724
+ loading: false,
2725
+ loaded: false,
2726
+ load: async () => {
2727
+ try {
2728
+ const res = await fetch(`${getCoreApiUrl()}/api/conversation?topic=${encodeURIComponent(pageId)}&page_size=${HISTORY_TURNS}`, { headers: coreHeaders() });
2729
+ if (!res.ok) {
2730
+ set({ loaded: true });
2731
+ return;
2732
+ }
2733
+ const json = await res.json();
2734
+ const items = Array.isArray(json?.items) ? [...json.items].reverse() : [];
2735
+ const seen = /* @__PURE__ */ new Set();
2736
+ const saved = items.filter((t) => {
2737
+ const k = t?.jobId;
2738
+ if (!k) return true;
2739
+ if (seen.has(k)) return false;
2740
+ seen.add(k);
2741
+ return true;
2742
+ }).flatMap(turnToMessages);
2743
+ set((s) => ({ messages: mergeSideChatHistory(saved, s.messages), loaded: true }));
2744
+ } catch {
2745
+ set({ loaded: true });
2746
+ }
2747
+ },
2748
+ send: async (text2) => {
2749
+ const t = text2.trim();
2750
+ if (!t || get().loading) return false;
2751
+ const echo = local({ id: `user-${Date.now()}`, role: "user", content: t, timestamp: /* @__PURE__ */ new Date() });
2752
+ set((s) => ({ messages: [...s.messages, echo], loading: true }));
2753
+ const fail = (msg) => set((s) => ({ loading: false, messages: [...s.messages, local({ id: `error-${Date.now()}`, role: "system", content: msg, timestamp: /* @__PURE__ */ new Date() })] }));
2754
+ try {
2755
+ const actor = getUser();
2756
+ const res = await fetch(`${getCoreApiUrl()}/api/chat`, {
2757
+ method: "POST",
2758
+ headers: coreHeaders(),
2759
+ body: JSON.stringify({
2760
+ goal: t,
2761
+ triggerContext: {
2762
+ channel: "mobile",
2763
+ replyContext: { chatId: actor?.actorId || "unknown" },
2764
+ pageContext: { page: pageId, chat: "page" }
2765
+ }
2766
+ })
2767
+ });
2768
+ const json = await res.json().catch(() => null);
2769
+ const jobId = json?.jobId || json?.id;
2770
+ if (!res.ok || !jobId) {
2771
+ fail(json?.error || `Could not start (${res.status}).`);
2772
+ return false;
2773
+ }
2774
+ const chainId = json.job?.chainId || jobId;
2775
+ const bubble = local({
2776
+ id: `job-${jobId}`,
2777
+ role: "assistant",
2778
+ content: "Working on it...",
2779
+ timestamp: /* @__PURE__ */ new Date(),
2780
+ chainId,
2781
+ jobProgress: { jobId, actorId: actor?.actorId, status: "running", subStatus: "Starting...", chainStartedAt: Date.now() }
2782
+ });
2783
+ set((s) => ({ messages: [...s.messages.map((m) => m.id === echo.id ? { ...m, chainId } : m), bubble] }));
2784
+ void follow(jobId, chainId);
2785
+ return true;
2786
+ } catch (e) {
2787
+ fail(`Request failed: ${e?.message || e}`);
2788
+ return false;
2789
+ }
2790
+ }
2791
+ };
2792
+ });
2793
+ }
2794
+
2576
2795
  // src/api/tenants.ts
2577
2796
  function nestByMaster(tenants) {
2578
2797
  const ids = new Set(tenants.map((t) => t.id));
@@ -2640,6 +2859,7 @@ async function switchTenant(targetTenantId) {
2640
2859
  await onSession(session);
2641
2860
  closeChatStream();
2642
2861
  useChatStore.getState().clearChat();
2862
+ clearSideChats();
2643
2863
  return session;
2644
2864
  }
2645
2865
 
@@ -2756,6 +2976,7 @@ var borderRadius = {
2756
2976
  MAX_ATTACHMENT_BYTES,
2757
2977
  MAX_INLINE_ATTACHMENT_BYTES,
2758
2978
  PluginCommandEmitter,
2979
+ SIDE_CHAT_LIMITS,
2759
2980
  TABLE_BLOCK_CLOSE,
2760
2981
  TABLE_BLOCK_OPEN,
2761
2982
  TIMELINE_BLOCK_CLOSE,
@@ -2770,6 +2991,7 @@ var borderRadius = {
2770
2991
  chartAsText,
2771
2992
  chartScale,
2772
2993
  chartView,
2994
+ clearSideChats,
2773
2995
  closeChatStream,
2774
2996
  colors,
2775
2997
  comparisonAsText,
@@ -2796,10 +3018,12 @@ var borderRadius = {
2796
3018
  getNotifPrefs,
2797
3019
  getNotifTelegramBotInfo,
2798
3020
  getSession,
3021
+ getSideChatStore,
2799
3022
  getTenant,
2800
3023
  getToken,
2801
3024
  getUser,
2802
3025
  getVoiceApiUrl,
3026
+ goalRows,
2803
3027
  initAdas,
2804
3028
  isAdasInitialized,
2805
3029
  isDevHost,
@@ -2815,6 +3039,7 @@ var borderRadius = {
2815
3039
  listSurface,
2816
3040
  mcpFetch,
2817
3041
  mcpToolCall,
3042
+ mergeSideChatHistory,
2818
3043
  nestByMaster,
2819
3044
  notifyAcsWsForeground,
2820
3045
  notifyAppForeground,
@@ -2847,6 +3072,7 @@ var borderRadius = {
2847
3072
  setHomeActionOrder,
2848
3073
  setNotifPrefs,
2849
3074
  setOrder,
3075
+ sideChatOptions,
2850
3076
  signInWithApple,
2851
3077
  signInWithGoogle,
2852
3078
  spacing,
@@ -2855,6 +3081,7 @@ var borderRadius = {
2855
3081
  tenantFromToken,
2856
3082
  timelineAsText,
2857
3083
  timelineView,
3084
+ topicLabel,
2858
3085
  unlinkNotifChannel,
2859
3086
  unregisterPushDevice,
2860
3087
  unwrapMcpResult,