@adminide-stack/yantra-mobile 12.0.53-alpha.2 → 12.0.53-alpha.21

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.
@@ -1,4 +1,4 @@
1
- import {useApolloClient}from'@apollo/client/index.js';import {SortEnum,RoomType,PostTypeEnum,AiAgentMessageRole}from'common';import {useGetChannelsByUserWithLastMessageQuery,useMessagesQuery,useAddChannelMutation,useSendMessagesMutation,MessagesDocument,GetChannelsByUserWithLastMessageDocument}from'common/graphql';import {useMemo,useCallback}from'react';import {v4}from'uuid';import {isAttachedCaption,historyAttachmentTitle,attachmentsFromUserContent}from'../features/attachments/historyAttachmentLabel.js';var __defProp = Object.defineProperty;
1
+ import {useApolloClient}from'@apollo/client/index.js';import {SortEnum,RoomType,PostTypeEnum,AiAgentMessageRole}from'common';import {useGetChannelsByUserWithLastMessageQuery,useMessagesQuery,useAddChannelMutation,useSendMessagesMutation,OnChatMessageAddedDocument,MessagesDocument,GetChannelsByUserWithLastMessageDocument}from'common/graphql';import {useMemo,useCallback,useEffect}from'react';import {v4}from'uuid';import {isAttachedCaption,historyAttachmentTitle,attachmentsFromUserContent}from'../features/attachments/historyAttachmentLabel.js';import {stripAskUser}from'../features/chat/askUser.js';import {parseToolActivity}from'../features/chat/toolActivity.js';var __defProp = Object.defineProperty;
2
2
  var __defProps = Object.defineProperties;
3
3
  var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
4
4
  var __getOwnPropSymbols = Object.getOwnPropertySymbols;
@@ -81,11 +81,7 @@ function getThreadMessagesQueryVariables(sessionId) {
81
81
  return {
82
82
  channelId: sessionId,
83
83
  limit: MESSAGES_PAGE_LIMIT,
84
- skip: 0,
85
- sort: {
86
- key: "createdAt",
87
- value: SortEnum.Asc
88
- }
84
+ skip: 0
89
85
  };
90
86
  }
91
87
  function getChatHistoryMessagesQueryVariables(accountUserId, options) {
@@ -215,7 +211,7 @@ function cleanMessageText(raw) {
215
211
  return raw.replace(ACTIVE_CONNECTORS_PREFIX_RE, "").replace(/\s+/g, " ").trim();
216
212
  }
217
213
  function isTransientHistoryText(text) {
218
- const t = cleanMessageText(text);
214
+ const t = cleanHistoryPreview(text) || cleanMessageText(text);
219
215
  if (!t) return true;
220
216
  if (/^thinking[.…]*$/i.test(t)) return true;
221
217
  if (/^let me check on that requested skill/i.test(t)) return true;
@@ -232,10 +228,14 @@ function looksLikeAssistantReply(text, role) {
232
228
  return false;
233
229
  }
234
230
  function cleanHistoryPreview(raw) {
235
- let t = cleanMessageText(raw);
231
+ const withoutAsk = stripAskUser(raw);
232
+ const {
233
+ text: withoutTools
234
+ } = parseToolActivity(withoutAsk, false);
235
+ let t = cleanMessageText(withoutTools);
236
236
  t = t.replace(/^(thinking[.…]*\s*)+/i, "").trim();
237
237
  t = t.replace(/^let me check on that requested skill[^\n.!?]*[.!?-]?\s*/i, "").trim();
238
- t = t.replace(/^(?:⚙️[^\n]*\n)+\s*/g, "").trim();
238
+ t = t.replace(/^(?:[⚙🔧⚙️⚠][^\n]*\n)+\s*/gu, "").trim();
239
239
  return t;
240
240
  }
241
241
  function buildSessionFromChannel(channel) {
@@ -298,26 +298,151 @@ function chatHistorySessionsFromChannels(data) {
298
298
  return channels.filter((c) => Boolean(c == null ? void 0 : c.id) && (!(c == null ? void 0 : c.type) || c.type === RoomType.Aiassistant)).map((c) => buildSessionFromChannel(c)).filter((row) => row !== null).sort((a, b) => b.updatedAt.getTime() - a.updatedAt.getTime());
299
299
  }
300
300
  const rememberedHistoryTitles = /* @__PURE__ */ new Map();
301
+ const rememberedHistoryListeners = /* @__PURE__ */ new Set();
302
+ function subscribeRememberedHistory(listener) {
303
+ rememberedHistoryListeners.add(listener);
304
+ return () => {
305
+ rememberedHistoryListeners.delete(listener);
306
+ };
307
+ }
308
+ function mergeRememberedHistory(channelId, patch, notify = true) {
309
+ var _a, _b;
310
+ const existing = (_a = rememberedHistoryTitles.get(channelId)) != null ? _a : {};
311
+ const next = {
312
+ title: patch.title || existing.title,
313
+ preview: patch.preview || existing.preview,
314
+ isAttachment: (_b = patch.isAttachment) != null ? _b : existing.isAttachment,
315
+ running: patch.running !== void 0 ? patch.running : existing.running
316
+ };
317
+ rememberedHistoryTitles.set(channelId, next);
318
+ if (notify && (next.title !== existing.title || next.preview !== existing.preview || next.running !== existing.running)) {
319
+ rememberedHistoryListeners.forEach((fn) => fn());
320
+ }
321
+ return next;
322
+ }
301
323
  function rememberHistoryTitle(session) {
302
- var _a;
303
- if (session.isPlaceholder) return;
304
- const title = (_a = session.title) == null ? void 0 : _a.trim();
305
- if (!title || /^new chat$/i.test(title) || isTransientHistoryText(title)) return;
306
- rememberedHistoryTitles.set(session.channelId, {
307
- title,
324
+ var _a, _b;
325
+ const existing = rememberedHistoryTitles.get(session.channelId);
326
+ const title = session.isPlaceholder || /^new chat$/i.test(session.title) ? "" : (_a = session.title) == null ? void 0 : _a.trim();
327
+ if (existing == null ? void 0 : existing.running) {
328
+ if (title && !isTransientHistoryText(title)) {
329
+ mergeRememberedHistory(session.channelId, {
330
+ title
331
+ }, false);
332
+ }
333
+ return;
334
+ }
335
+ const preview = ((_b = session.preview) == null ? void 0 : _b.trim()) && !isTransientHistoryText(session.preview) ? session.preview.trim() : "";
336
+ if (title && isTransientHistoryText(title) && !preview) return;
337
+ if (!title && !preview) return;
338
+ mergeRememberedHistory(session.channelId, __spreadProps(__spreadValues(__spreadValues({}, title && !isTransientHistoryText(title) ? {
339
+ title
340
+ } : {}), preview ? {
341
+ preview
342
+ } : {}), {
308
343
  isAttachment: session.isAttachment
344
+ }), false);
345
+ }
346
+ function deriveHistoryTitleFromPrompt(rawPrompt) {
347
+ const cleaned = cleanMessageText(rawPrompt);
348
+ if (!cleaned || isTransientHistoryText(cleaned) || /^new chat$/i.test(cleaned)) return "";
349
+ if (cleaned.length <= 64) return cleaned;
350
+ return `${cleaned.slice(0, 64).trim()}...`;
351
+ }
352
+ function patchChannelHistoryTitle(client, channelId, rawPrompt) {
353
+ const cleaned = deriveHistoryTitleFromPrompt(rawPrompt);
354
+ if (!channelId || !cleaned) return;
355
+ mergeRememberedHistory(channelId, {
356
+ title: cleaned,
357
+ isAttachment: isAttachedCaption(cleaned)
358
+ });
359
+ const channelCacheId = client.cache.identify({
360
+ __typename: "Channel",
361
+ id: channelId
362
+ });
363
+ if (!channelCacheId) return;
364
+ try {
365
+ client.cache.modify({
366
+ id: channelCacheId,
367
+ fields: {
368
+ title(existing) {
369
+ return cleanChannelTitle(existing) ? existing : cleaned;
370
+ }
371
+ // Do not touch updatedAt here. Bumping it on open/hydrate moves the
372
+ // row to TODAY / "now". Activity time is only written when the user
373
+ // actually sends (touchChannelHistoryUpdatedAt).
374
+ }
375
+ });
376
+ } catch (err) {
377
+ console.warn("[useChatApi] patchChannelHistoryTitle failed:", err);
378
+ }
379
+ }
380
+ function touchChannelHistoryUpdatedAt(client, channelId) {
381
+ if (!channelId) return;
382
+ const channelCacheId = client.cache.identify({
383
+ __typename: "Channel",
384
+ id: channelId
385
+ });
386
+ if (!channelCacheId) return;
387
+ try {
388
+ client.cache.modify({
389
+ id: channelCacheId,
390
+ fields: {
391
+ updatedAt() {
392
+ return (/* @__PURE__ */ new Date()).toISOString();
393
+ }
394
+ }
395
+ });
396
+ } catch (err) {
397
+ console.warn("[useChatApi] touchChannelHistoryUpdatedAt failed:", err);
398
+ }
399
+ }
400
+ function patchChannelHistoryPreview(channelId, rawPreview) {
401
+ var _a, _b;
402
+ if (!channelId) return;
403
+ const preview = cleanHistoryPreview(rawPreview);
404
+ if (!preview || isTransientHistoryText(preview) || isAttachedCaption(preview)) return;
405
+ const title = (_b = (_a = rememberedHistoryTitles.get(channelId)) == null ? void 0 : _a.title) != null ? _b : "";
406
+ if (title && preview === title) return;
407
+ mergeRememberedHistory(channelId, {
408
+ preview
409
+ });
410
+ }
411
+ function markChannelHistoryRunning(channelId, rawPreview) {
412
+ if (!channelId) return;
413
+ const preview = rawPreview ? cleanHistoryPreview(rawPreview) : "";
414
+ const usable = preview && !isTransientHistoryText(preview) && !isAttachedCaption(preview) ? preview : void 0;
415
+ mergeRememberedHistory(channelId, __spreadValues({
416
+ running: true
417
+ }, usable ? {
418
+ preview: usable
419
+ } : {}));
420
+ }
421
+ function clearChannelHistoryRunning(channelId) {
422
+ if (!channelId) return;
423
+ const existing = rememberedHistoryTitles.get(channelId);
424
+ if (!(existing == null ? void 0 : existing.running)) return;
425
+ mergeRememberedHistory(channelId, {
426
+ running: false
309
427
  });
310
428
  }
311
429
  function applyRememberedHistoryTitles(rows) {
312
430
  return rows.map((row) => {
431
+ var _a;
313
432
  rememberHistoryTitle(row);
314
- if (!row.isPlaceholder && !/^new chat$/i.test(row.title)) return row;
315
433
  const mem = rememberedHistoryTitles.get(row.channelId);
316
434
  if (!mem) return row;
435
+ const titleMissing = row.isPlaceholder || /^new chat$/i.test(row.title);
436
+ const previewMissing = !((_a = row.preview) == null ? void 0 : _a.trim());
437
+ const nextTitle = titleMissing && mem.title ? mem.title : row.title;
438
+ const livePreview = mem.running && mem.preview && mem.preview !== nextTitle ? mem.preview : previewMissing && mem.preview && mem.preview !== nextTitle ? mem.preview : row.preview;
439
+ if (!titleMissing && !previewMissing && !mem.running) return row;
317
440
  return __spreadProps(__spreadValues({}, row), {
318
- title: mem.title,
319
- isPlaceholder: false,
320
- isAttachment: mem.isAttachment || row.isAttachment
441
+ title: nextTitle,
442
+ preview: livePreview,
443
+ isPlaceholder: titleMissing && mem.title ? false : row.isPlaceholder,
444
+ isAttachment: mem.isAttachment || row.isAttachment,
445
+ isRunning: Boolean(mem.running)
321
446
  });
322
447
  });
323
448
  }
@@ -490,19 +615,23 @@ function mapPostToChatMessageUI(post, fallbackChannelId) {
490
615
  };
491
616
  }
492
617
  function useChatMessages(sessionId, options) {
618
+ const client = useApolloClient();
493
619
  const {
494
620
  data,
495
621
  loading,
496
622
  error,
497
- refetch
623
+ refetch,
624
+ subscribeToMore
498
625
  } = useMessagesQuery({
499
626
  variables: sessionId ? getThreadMessagesQueryVariables(sessionId) : void 0,
500
627
  skip: !sessionId || (void 0 ),
501
- // cache-first + `messages` typePolicy (keyed by channelId). Opening a thread
502
- // that was already loaded does not refetch. New channels still hit the
503
- // network once. saveMessages writes new posts into this cache slot.
504
- fetchPolicy: "cache-first",
628
+ // Same as browser: paint cache immediately, then hit the network so a thread
629
+ // opened from history is not stuck on a cache-first snapshot that only has
630
+ // the latest user post (assistant replies persist after the first query).
631
+ fetchPolicy: "cache-and-network",
505
632
  nextFetchPolicy: "cache-first",
633
+ errorPolicy: "all",
634
+ notifyOnNetworkStatusChange: true,
506
635
  /**
507
636
  * Cache key is per-channel so switching sessions doesn't read another channel's response.
508
637
  * Keeping this as a constant ('messages-list') used to cause cross-session bleed in the
@@ -512,12 +641,77 @@ function useChatMessages(sessionId, options) {
512
641
  cacheKey: sessionId ? `messages-list:${sessionId}` : "messages-list"
513
642
  }
514
643
  });
644
+ useEffect(() => {
645
+ if (!sessionId || (void 0 )) return;
646
+ const unsubscribe = subscribeToMore({
647
+ document: OnChatMessageAddedDocument,
648
+ variables: {
649
+ channelId: sessionId
650
+ },
651
+ updateQuery: (prev, {
652
+ subscriptionData
653
+ }) => {
654
+ var _a, _b, _c, _d, _e;
655
+ const post = (_a = subscriptionData == null ? void 0 : subscriptionData.data) == null ? void 0 : _a.chatMessageAdded;
656
+ if (!(post == null ? void 0 : post.id)) return prev;
657
+ if (!(prev == null ? void 0 : prev.messages)) return prev;
658
+ const existing = (_b = prev.messages.data) != null ? _b : [];
659
+ const idx = existing.findIndex((row) => (row == null ? void 0 : row.id) === post.id);
660
+ let nextData;
661
+ let nextTotal;
662
+ if (idx >= 0) {
663
+ nextData = [...existing.slice(0, idx), post, ...existing.slice(idx + 1)];
664
+ nextTotal = (_c = prev.messages.totalCount) != null ? _c : existing.length;
665
+ } else {
666
+ nextData = [...existing, post];
667
+ nextTotal = ((_d = prev.messages.totalCount) != null ? _d : existing.length) + 1;
668
+ const parentId = (_e = post.parentId) != null ? _e : null;
669
+ if (parentId) {
670
+ nextData = nextData.map((root) => {
671
+ var _a2, _b2, _c2, _d2, _e2, _f, _g;
672
+ if ((root == null ? void 0 : root.id) !== parentId) return root;
673
+ const replies = (_b2 = (_a2 = root.replies) == null ? void 0 : _a2.data) != null ? _b2 : [];
674
+ if (replies.some((reply) => (reply == null ? void 0 : reply.id) === post.id)) return root;
675
+ return __spreadProps(__spreadValues({}, root), {
676
+ replies: __spreadProps(__spreadValues({}, (_c2 = root.replies) != null ? _c2 : {}), {
677
+ __typename: (_e2 = (_d2 = root.replies) == null ? void 0 : _d2.__typename) != null ? _e2 : "Messages",
678
+ data: [...replies, post],
679
+ totalCount: ((_g = (_f = root.replies) == null ? void 0 : _f.totalCount) != null ? _g : replies.length) + 1
680
+ })
681
+ });
682
+ });
683
+ }
684
+ }
685
+ const seen = /* @__PURE__ */ new Set();
686
+ nextData = nextData.filter((row) => {
687
+ if (!(row == null ? void 0 : row.id) || seen.has(row.id)) return false;
688
+ seen.add(row.id);
689
+ return true;
690
+ });
691
+ return __spreadProps(__spreadValues({}, prev), {
692
+ messages: __spreadProps(__spreadValues({}, prev.messages), {
693
+ data: nextData,
694
+ totalCount: nextTotal
695
+ })
696
+ });
697
+ },
698
+ onError: (err) => {
699
+ console.error("[useChatMessages] subscribeToMore error:", err);
700
+ }
701
+ });
702
+ return () => unsubscribe();
703
+ }, [sessionId, void 0 , subscribeToMore, client]);
515
704
  const messagesLoaded = data !== void 0;
516
705
  const messages = useMemo(() => {
517
706
  var _a, _b;
518
707
  if (!sessionId) return [];
519
708
  const rows = (_b = (_a = data == null ? void 0 : data.messages) == null ? void 0 : _a.data) != null ? _b : [];
520
- return flattenPostsWithReplies(rows, sessionId);
709
+ const ownRows = rows.filter((post) => {
710
+ var _a2;
711
+ const postChannelId = (_a2 = post == null ? void 0 : post.channel) == null ? void 0 : _a2.id;
712
+ return !postChannelId || postChannelId === sessionId;
713
+ });
714
+ return flattenPostsWithReplies(ownRows, sessionId);
521
715
  }, [data, sessionId]);
522
716
  return {
523
717
  messages,
@@ -775,13 +969,18 @@ function useChatMutations() {
775
969
  }
776
970
  };
777
971
  }, [client, sendMessagesMutation]);
972
+ const patchChannelTitle = useCallback((channelId, rawPrompt, bumpActivity = false) => {
973
+ patchChannelHistoryTitle(client, channelId, rawPrompt);
974
+ if (bumpActivity) touchChannelHistoryUpdatedAt(client, channelId);
975
+ }, [client]);
778
976
  return {
779
977
  createChannel,
780
978
  createSession: createChannel,
781
979
  saveMessages,
980
+ patchChannelTitle,
782
981
  loading: {
783
982
  create: createChannelLoading,
784
983
  saveMessages: sendMessagesLoading
785
984
  }
786
985
  };
787
- }export{AI_ASSISTANT_CHANNELS_QUERY_VARS,HISTORY_PAGE_SIZE,HISTORY_QUERY_BASE,buildSessionFromChannel,chatHistorySessionsFromChannels,chatHistorySessionsFromMessages,enrichHistorySessionsWithUserPrompts,getChatHistoryChannelRefetchQueries,getChatHistoryMessagesQueryVariables,getHistoryChannelsQueryVariables,useChatHistorySessionsFromChannels,useChatHistorySessionsFromMessages,useChatMessages,useChatMutations,usePrefetchChatHistory};//# sourceMappingURL=useChatApi.js.map
986
+ }export{AI_ASSISTANT_CHANNELS_QUERY_VARS,HISTORY_PAGE_SIZE,HISTORY_QUERY_BASE,buildSessionFromChannel,chatHistorySessionsFromChannels,chatHistorySessionsFromMessages,clearChannelHistoryRunning,enrichHistorySessionsWithUserPrompts,getChatHistoryChannelRefetchQueries,getChatHistoryMessagesQueryVariables,getHistoryChannelsQueryVariables,markChannelHistoryRunning,patchChannelHistoryPreview,patchChannelHistoryTitle,subscribeRememberedHistory,touchChannelHistoryUpdatedAt,useChatHistorySessionsFromChannels,useChatHistorySessionsFromMessages,useChatMessages,useChatMutations,usePrefetchChatHistory};//# sourceMappingURL=useChatApi.js.map