@adminide-stack/yantra-mobile 12.0.28-alpha.7 → 12.0.28-alpha.72

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.
Files changed (75) hide show
  1. package/lib/api/stt.js +54 -0
  2. package/lib/api/stt.js.map +1 -0
  3. package/lib/assets/icon.png +0 -0
  4. package/lib/components/CustomDrawer.js +479 -0
  5. package/lib/components/CustomDrawer.js.map +1 -0
  6. package/lib/components/GatewayConnector/GatewayConnector.js +18 -0
  7. package/lib/components/GatewayConnector/GatewayConnector.js.map +1 -0
  8. package/lib/components/GatewayToolbarButtonMobile.js +84 -0
  9. package/lib/components/GatewayToolbarButtonMobile.js.map +1 -0
  10. package/lib/components/NavigationHeader/NavigationHeader.js +214 -0
  11. package/lib/components/NavigationHeader/NavigationHeader.js.map +1 -0
  12. package/lib/components/ThinkingIndicator.js +55 -0
  13. package/lib/components/ThinkingIndicator.js.map +1 -0
  14. package/lib/components/YantraBrandLoader.js +94 -0
  15. package/lib/components/YantraBrandLoader.js.map +1 -0
  16. package/lib/compute.js +114 -5
  17. package/lib/compute.js.map +1 -1
  18. package/lib/config/constants.js +16 -0
  19. package/lib/config/constants.js.map +1 -0
  20. package/lib/config/env-config.js +74 -19
  21. package/lib/config/env-config.js.map +1 -1
  22. package/lib/contexts/CdecliConnectionContext.js +47 -0
  23. package/lib/contexts/CdecliConnectionContext.js.map +1 -0
  24. package/lib/contexts/GatewayContext.js +77 -0
  25. package/lib/contexts/GatewayContext.js.map +1 -0
  26. package/lib/features/audio-input/AudioRecorderPanel.js +224 -0
  27. package/lib/features/audio-input/AudioRecorderPanel.js.map +1 -0
  28. package/lib/features/audio-input/MicErrorBoundary.js +34 -0
  29. package/lib/features/audio-input/MicErrorBoundary.js.map +1 -0
  30. package/lib/graphql/agentGatewayDocuments.js +53 -0
  31. package/lib/graphql/agentGatewayDocuments.js.map +1 -0
  32. package/lib/hooks/useCdecliAutoConnect.js +242 -0
  33. package/lib/hooks/useCdecliAutoConnect.js.map +1 -0
  34. package/lib/hooks/useCdecliChannel.js +226 -0
  35. package/lib/hooks/useCdecliChannel.js.map +1 -0
  36. package/lib/hooks/useChatApi.js +338 -171
  37. package/lib/hooks/useChatApi.js.map +1 -1
  38. package/lib/hooks/useChatStream.js +281 -64
  39. package/lib/hooks/useChatStream.js.map +1 -1
  40. package/lib/hooks/useGatewayConnection.js +123 -0
  41. package/lib/hooks/useGatewayConnection.js.map +1 -0
  42. package/lib/hooks/useGatewayRegistry.js +28 -0
  43. package/lib/hooks/useGatewayRegistry.js.map +1 -0
  44. package/lib/hooks/usePrerequisiteIds.js +181 -0
  45. package/lib/hooks/usePrerequisiteIds.js.map +1 -0
  46. package/lib/hooks/useWorkspaceProvisioner.js +236 -0
  47. package/lib/hooks/useWorkspaceProvisioner.js.map +1 -0
  48. package/lib/index.js +1 -1
  49. package/lib/index.js.map +1 -1
  50. package/lib/routes.json +120 -5
  51. package/lib/screens/Chat/index.js +404 -0
  52. package/lib/screens/Chat/index.js.map +1 -0
  53. package/lib/screens/ChatHistory/index.js +56 -0
  54. package/lib/screens/ChatHistory/index.js.map +1 -0
  55. package/lib/screens/Home/HomeScreen.js +397 -143
  56. package/lib/screens/Home/HomeScreen.js.map +1 -1
  57. package/lib/screens/Home/components/ChatHistoryLanding.js +487 -0
  58. package/lib/screens/Home/components/ChatHistoryLanding.js.map +1 -0
  59. package/lib/screens/Home/components/DeepSearchModal.js +349 -0
  60. package/lib/screens/Home/components/DeepSearchModal.js.map +1 -0
  61. package/lib/screens/Home/deepSearchUtils.js +41 -0
  62. package/lib/screens/Home/deepSearchUtils.js.map +1 -0
  63. package/lib/screens/NewChat/index.js +79 -0
  64. package/lib/screens/NewChat/index.js.map +1 -0
  65. package/lib/services/agentSessionManager.js +451 -0
  66. package/lib/services/agentSessionManager.js.map +1 -0
  67. package/lib/services/gatewayApiKeyBridge.js +4 -0
  68. package/lib/services/gatewayApiKeyBridge.js.map +1 -0
  69. package/lib/services/gatewayClient.js +470 -0
  70. package/lib/services/gatewayClient.js.map +1 -0
  71. package/lib/theme/mobileTokens.js +18 -0
  72. package/lib/theme/mobileTokens.js.map +1 -0
  73. package/lib/utils/gatewaySelectionStorage.js +21 -0
  74. package/lib/utils/gatewaySelectionStorage.js.map +1 -0
  75. package/package.json +7 -3
@@ -1,4 +1,4 @@
1
- import {useCreateAccountChatSessionMutation,useSaveAccountChatMessagesMutation,GetAccountChatSessionsDocument,GetAccountChatMessagesDocument,useGetAccountChatMessagesQuery}from'common/graphql';import {useCallback,useMemo}from'react';var __defProp = Object.defineProperty;
1
+ import {SortEnum,RoomType,PostTypeEnum,AiAgentMessageRole}from'common';import {useGetChannelsByUserWithLastMessageQuery,useAddChannelMutation,useSendMessagesMutation,GetChannelsByUserWithLastMessageDocument,useMessagesQuery}from'common/graphql';import {useMemo,useCallback}from'react';import {v4}from'uuid';var __defProp = Object.defineProperty;
2
2
  var __defProps = Object.defineProperties;
3
3
  var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
4
4
  var __getOwnPropSymbols = Object.getOwnPropertySymbols;
@@ -17,49 +17,190 @@ var __spreadValues = (a, b) => {
17
17
  return a;
18
18
  };
19
19
  var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
20
- const SESSIONS_QUERY_VARS = {
21
- first: 25,
22
- includeArchived: false
20
+ var __objRest = (source, exclude) => {
21
+ var target = {};
22
+ for (var prop in source)
23
+ if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
24
+ target[prop] = source[prop];
25
+ if (source != null && __getOwnPropSymbols)
26
+ for (var prop of __getOwnPropSymbols(source)) {
27
+ if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
28
+ target[prop] = source[prop];
29
+ }
30
+ return target;
23
31
  };
24
- function readSessionsCache(cache) {
25
- try {
26
- return cache.readQuery({
27
- query: GetAccountChatSessionsDocument,
28
- variables: SESSIONS_QUERY_VARS
29
- });
30
- } catch (e) {
31
- return null;
32
+ const MESSAGES_PAGE_LIMIT = 100;
33
+ const AI_ASSISTANT_CHANNELS_QUERY_VARS = {
34
+ criteria: {
35
+ type: RoomType.Aiassistant
36
+ },
37
+ limit: 100,
38
+ skip: 0,
39
+ sort: {
40
+ key: "updatedAt",
41
+ value: SortEnum.Desc
32
42
  }
43
+ };
44
+ const HISTORY_PAGE_SIZE = 20;
45
+ function getHistoryChannelsQueryVariables(orgName, options) {
46
+ var _a, _b;
47
+ const trimmedOrg = typeof orgName === "string" && orgName.trim().length > 0 ? orgName.trim() : void 0;
48
+ return {
49
+ criteria: __spreadValues({
50
+ type: RoomType.Aiassistant
51
+ }, trimmedOrg ? {
52
+ orgName: trimmedOrg
53
+ } : {}),
54
+ limit: (_a = options == null ? void 0 : options.limit) != null ? _a : HISTORY_PAGE_SIZE,
55
+ skip: (_b = options == null ? void 0 : options.skip) != null ? _b : 0,
56
+ sort: {
57
+ key: "updatedAt",
58
+ value: SortEnum.Desc
59
+ }
60
+ };
33
61
  }
34
- function readMessagesCache(cache, sessionId) {
35
- try {
36
- return cache.readQuery({
37
- query: GetAccountChatMessagesDocument,
38
- variables: {
39
- sessionId,
40
- first: 100
41
- }
42
- });
43
- } catch (e) {
44
- return null;
62
+ const HISTORY_QUERY_BASE = getHistoryChannelsQueryVariables();
63
+ function getLastMessageRole(lastMessage) {
64
+ var _a, _b, _c, _d, _e, _f, _g, _h;
65
+ return String((_h = (_g = (_e = (_b = (_a = lastMessage == null ? void 0 : lastMessage.propsConfiguration) == null ? void 0 : _a.contents) == null ? void 0 : _b.role) != null ? _e : (_d = (_c = lastMessage == null ? void 0 : lastMessage.propsConfiguration) == null ? void 0 : _c.content) == null ? void 0 : _d.role) != null ? _g : (_f = lastMessage == null ? void 0 : lastMessage.props) == null ? void 0 : _f.role) != null ? _h : "").toUpperCase();
66
+ }
67
+ function getParentUserPrompt(lastMessage) {
68
+ var _a, _b, _c;
69
+ const parent = (_b = (_a = lastMessage == null ? void 0 : lastMessage.propsConfiguration) == null ? void 0 : _a.contents) == null ? void 0 : _b.parent;
70
+ if (!parent) return "";
71
+ return String((_c = parent == null ? void 0 : parent.message) != null ? _c : "").trim();
72
+ }
73
+ function detectMode(channel) {
74
+ var _a, _b;
75
+ const display = String((_a = channel == null ? void 0 : channel.displayName) != null ? _a : "").toLowerCase();
76
+ const title = String((_b = channel == null ? void 0 : channel.title) != null ? _b : "").toLowerCase();
77
+ if (display.startsWith("deep-search") || title.startsWith("deep search") || title.startsWith("deep-search")) {
78
+ return "deep-search";
45
79
  }
80
+ return "chat";
81
+ }
82
+ function cleanChannelTitle(rawTitle) {
83
+ const t = String(rawTitle != null ? rawTitle : "").trim();
84
+ if (!t) return "";
85
+ if (/^(chat[\s-]channel|deep[\s-]search)[\s-][0-9a-f][0-9a-f\s-]{7,}\.?$/i.test(t)) return "";
86
+ return t;
46
87
  }
47
- function buildSessionEdge(node) {
88
+ function buildSessionFromChannel(channel) {
89
+ var _a, _b, _c;
90
+ const channelId = String((_a = channel == null ? void 0 : channel.id) != null ? _a : "");
91
+ if (!channelId) return null;
92
+ const lastMessage = (_b = channel == null ? void 0 : channel.lastMessage) != null ? _b : null;
93
+ const lastMessageRole = getLastMessageRole(lastMessage);
94
+ const parentUserPrompt = getParentUserPrompt(lastMessage);
95
+ const parentTrimmed = parentUserPrompt.trim();
96
+ const userTurn = lastMessageRole === "USER" && (lastMessage == null ? void 0 : lastMessage.message) ? String(lastMessage.message).trim() : "";
97
+ const cleanedChannelTitle = cleanChannelTitle(channel == null ? void 0 : channel.title);
98
+ const cleanedDisplayName = cleanChannelTitle(channel == null ? void 0 : channel.displayName);
99
+ let resolvedTitle = parentTrimmed || userTurn || cleanedChannelTitle || cleanedDisplayName;
100
+ const isPlaceholder = !resolvedTitle;
101
+ if (isPlaceholder) resolvedTitle = "Thinking\u2026";
102
+ const rawPreview = String((_c = lastMessage == null ? void 0 : lastMessage.message) != null ? _c : "").replace(/\s+/g, " ").trim();
103
+ let preview = rawPreview;
104
+ if (preview && preview === parentTrimmed) preview = "";
105
+ const sortAt = (() => {
106
+ const candidates = [channel == null ? void 0 : channel.updatedAt, lastMessage == null ? void 0 : lastMessage.updatedAt, lastMessage == null ? void 0 : lastMessage.createdAt, channel == null ? void 0 : channel.createdAt];
107
+ for (const candidate of candidates) {
108
+ if (candidate) {
109
+ const t = new Date(candidate).getTime();
110
+ if (Number.isFinite(t) && t > 0) return t;
111
+ }
112
+ }
113
+ return Date.now();
114
+ })();
115
+ const createdAtRaw = (channel == null ? void 0 : channel.createdAt) ? new Date(channel.createdAt).getTime() : sortAt;
116
+ return {
117
+ channelId,
118
+ title: resolvedTitle,
119
+ preview,
120
+ mode: detectMode(channel),
121
+ updatedAt: new Date(sortAt),
122
+ createdAt: new Date(Number.isFinite(createdAtRaw) ? createdAtRaw : sortAt),
123
+ isPlaceholder
124
+ };
125
+ }
126
+ function chatHistorySessionsFromChannels(data) {
127
+ var _a;
128
+ const channels = (_a = data == null ? void 0 : data.channelsByUser) != null ? _a : [];
129
+ 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());
130
+ }
131
+ function useChatHistorySessionsFromChannels(orgName, options) {
132
+ var _a, _b;
133
+ const skip = (options == null ? void 0 : options.skip) || !orgName;
134
+ const variables = useMemo(() => getHistoryChannelsQueryVariables(orgName), [orgName]);
135
+ const {
136
+ data,
137
+ loading,
138
+ error,
139
+ refetch
140
+ } = useGetChannelsByUserWithLastMessageQuery({
141
+ variables,
142
+ skip,
143
+ fetchPolicy: "cache-and-network",
144
+ notifyOnNetworkStatusChange: true,
145
+ context: {
146
+ cacheKey: "chat-history-channels-list"
147
+ }
148
+ });
149
+ const sessions = useMemo(() => chatHistorySessionsFromChannels(data), [data]);
150
+ const sourceChannelCount = (_b = (_a = data == null ? void 0 : data.channelsByUser) == null ? void 0 : _a.length) != null ? _b : 0;
151
+ const sessionsLoaded = data !== void 0;
48
152
  return {
49
- __typename: "AccountChatSessionEdge",
50
- cursor: "",
51
- node: __spreadValues({
52
- __typename: "AccountChatSession"
53
- }, node)
153
+ sessions,
154
+ loading,
155
+ sessionsLoaded,
156
+ error,
157
+ refetch,
158
+ sourceChannelCount
54
159
  };
55
160
  }
56
- function buildMessageEdge(node) {
161
+ function stripModelCostHeader(content) {
162
+ const normalized = content.replace(/\r\n/g, "\n");
163
+ return normalized.replace(/^\s*(?:[^\w\n]+\s*)?[a-z0-9][a-z0-9._-]*\s*\(\s*\$[\d.]+\s*\/\s*MTok\s+in\s*\)\s*\n+/i, "");
164
+ }
165
+ function sanitizeAssistantContentByRole(role, content) {
166
+ return role === "assistant" ? stripModelCostHeader(content) : content;
167
+ }
168
+ function omitContent(value) {
169
+ const clone = __spreadValues({}, value != null ? value : {});
170
+ delete clone.content;
171
+ return clone;
172
+ }
173
+ function mapPostToChatMessageUI(post, fallbackChannelId) {
174
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o;
175
+ const props = (_a = post.props) != null ? _a : {};
176
+ const contents = (_c = (_b = post.propsConfiguration) == null ? void 0 : _b.contents) != null ? _c : {};
177
+ const roleRaw = (_g = (_d = props.role) != null ? _d : contents.role) != null ? _g : (_f = (_e = post.propsConfiguration) == null ? void 0 : _e.content) == null ? void 0 : _f.role;
178
+ let role = "assistant";
179
+ if (roleRaw === "user" || roleRaw === AiAgentMessageRole.User) role = "user";
180
+ else if (roleRaw === "assistant" || roleRaw === AiAgentMessageRole.Assistant) role = "assistant";
181
+ else if (roleRaw === "system") role = "system";
182
+ const rawContent = (_h = post == null ? void 0 : post.message) != null ? _h : "";
183
+ const content = sanitizeAssistantContentByRole(role, rawContent);
57
184
  return {
58
- __typename: "AccountChatMessageEdge",
59
- cursor: "",
60
- node: __spreadValues({
61
- __typename: "AccountChatMessage"
62
- }, node)
185
+ id: (_i = post == null ? void 0 : post.id) != null ? _i : v4(),
186
+ sessionId: (_k = (_j = post == null ? void 0 : post.channel) == null ? void 0 : _j.id) != null ? _k : fallbackChannelId,
187
+ role,
188
+ content,
189
+ attachments: ((_m = (_l = post == null ? void 0 : post.files) == null ? void 0 : _l.data) != null ? _m : []).map((file) => {
190
+ var _a2, _b2, _c2, _d2, _e2;
191
+ return {
192
+ id: (_a2 = file.id) != null ? _a2 : v4(),
193
+ name: (_b2 = file.name) != null ? _b2 : "file",
194
+ type: typeof file.mimeType === "string" && file.mimeType.startsWith("image/") ? "screenshot" : "file",
195
+ mimeType: (_c2 = file.mimeType) != null ? _c2 : void 0,
196
+ size: (_d2 = file.size) != null ? _d2 : void 0,
197
+ url: (_e2 = file.url) != null ? _e2 : void 0
198
+ };
199
+ }),
200
+ tokenCount: (_n = props.tokenCount) != null ? _n : void 0,
201
+ model: (_o = props.model) != null ? _o : void 0,
202
+ createdAt: (post == null ? void 0 : post.createdAt) ? new Date(post.createdAt) : /* @__PURE__ */ new Date(),
203
+ updatedAt: (post == null ? void 0 : post.updatedAt) ? new Date(post.updatedAt) : /* @__PURE__ */ new Date()
63
204
  };
64
205
  }
65
206
  function useChatMessages(sessionId, options) {
@@ -68,166 +209,192 @@ function useChatMessages(sessionId, options) {
68
209
  loading,
69
210
  error,
70
211
  refetch
71
- } = useGetAccountChatMessagesQuery({
212
+ } = useMessagesQuery({
72
213
  variables: {
73
- sessionId,
74
- first: 100
214
+ channelId: sessionId != null ? sessionId : void 0,
215
+ parentId: null,
216
+ limit: MESSAGES_PAGE_LIMIT,
217
+ skip: 0
75
218
  },
76
219
  skip: !sessionId || (void 0 ),
77
- fetchPolicy: "cache-first"
220
+ fetchPolicy: "cache-and-network",
221
+ notifyOnNetworkStatusChange: true,
222
+ /**
223
+ * Cache key is per-channel so switching sessions doesn't read another channel's response.
224
+ * Keeping this as a constant ('messages-list') used to cause cross-session bleed in the
225
+ * custom Apollo link before reaching the normalized cache.
226
+ */
227
+ context: {
228
+ cacheKey: sessionId ? `messages-list:${sessionId}` : "messages-list"
229
+ }
78
230
  });
231
+ const messagesLoaded = data !== void 0;
79
232
  const messages = useMemo(() => {
80
- var _a;
81
- if (!((_a = data == null ? void 0 : data.getAccountChatMessages) == null ? void 0 : _a.edges)) return [];
82
- return data.getAccountChatMessages.edges.map((edge) => {
83
- var _a2, _b;
84
- const n = edge.node;
85
- return {
86
- id: n.id,
87
- sessionId: n.sessionId,
88
- role: n.role,
89
- content: (_a2 = n.content) != null ? _a2 : "",
90
- attachments: (_b = n.attachments) != null ? _b : void 0,
91
- tokenCount: n.tokenCount,
92
- model: n.model,
93
- createdAt: new Date(n.createdAt),
94
- updatedAt: new Date(n.updatedAt)
95
- };
96
- });
97
- }, [data]);
233
+ var _a, _b;
234
+ if (!sessionId) return [];
235
+ const rows = (_b = (_a = data == null ? void 0 : data.messages) == null ? void 0 : _a.data) != null ? _b : [];
236
+ return rows.map((post) => mapPostToChatMessageUI(post, sessionId)).sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime());
237
+ }, [data, sessionId]);
98
238
  return {
99
239
  messages,
100
240
  loading,
241
+ messagesLoaded,
101
242
  error,
102
243
  refetch
103
244
  };
104
245
  }
105
246
  function useChatMutations() {
106
- const [createSessionMutation, {
107
- loading: createLoading
108
- }] = useCreateAccountChatSessionMutation();
109
- const [saveMessagesMutation, {
110
- loading: saveMessagesLoading
111
- }] = useSaveAccountChatMessagesMutation();
112
- const createSession = useCallback(async (input) => {
113
- var _a, _b;
114
- const inputWithId = __spreadValues(__spreadValues({
115
- id: input == null ? void 0 : input.id,
116
- title: (_a = input == null ? void 0 : input.title) != null ? _a : "New Chat"
117
- }, (input == null ? void 0 : input.model) && {
118
- model: input.model
119
- }), (input == null ? void 0 : input.systemPrompt) && {
120
- systemPrompt: input.systemPrompt
121
- });
247
+ const [addChannelMutation, {
248
+ loading: createChannelLoading
249
+ }] = useAddChannelMutation();
250
+ const [sendMessagesMutation, {
251
+ loading: sendMessagesLoading
252
+ }] = useSendMessagesMutation();
253
+ const createChannel = useCallback(async (input) => {
254
+ var _b, _c, _d, _e, _f, _g, _h, _i, _j, _k;
255
+ const _a = input != null ? input : {}, {
256
+ orgName: orgNameArg,
257
+ projectId: projectIdArg
258
+ } = _a, inputForSettings = __objRest(_a, [
259
+ "orgName",
260
+ "projectId"
261
+ ]);
262
+ const orgName = typeof orgNameArg === "string" && orgNameArg.trim().length > 0 ? orgNameArg.trim() : void 0;
263
+ const projectId = typeof projectIdArg === "string" && projectIdArg.trim().length > 0 ? projectIdArg.trim() : void 0;
264
+ const settings = __spreadValues({
265
+ title: (_b = input == null ? void 0 : input.title) != null ? _b : "New Chat",
266
+ description: (_c = input == null ? void 0 : input.systemPrompt) != null ? _c : null,
267
+ isShared: false,
268
+ sharedSlug: null,
269
+ isArchived: false,
270
+ isPinned: false,
271
+ model: (_d = input == null ? void 0 : input.model) != null ? _d : null,
272
+ systemPrompt: (_e = input == null ? void 0 : input.systemPrompt) != null ? _e : null
273
+ }, inputForSettings);
122
274
  const {
123
275
  data
124
- } = await createSessionMutation({
125
- variables: {
126
- input: inputWithId
127
- },
128
- update: (cache, {
129
- data: result
130
- }) => {
131
- var _a2;
132
- if (!(result == null ? void 0 : result.createAccountChatSession)) return;
133
- try {
134
- const existing = readSessionsCache(cache);
135
- if (existing == null ? void 0 : existing.getAccountChatSessions) {
136
- const newEdge = buildSessionEdge(result.createAccountChatSession);
137
- cache.writeQuery({
138
- query: GetAccountChatSessionsDocument,
139
- variables: SESSIONS_QUERY_VARS,
140
- data: {
141
- getAccountChatSessions: __spreadProps(__spreadValues({}, existing.getAccountChatSessions), {
142
- edges: [newEdge, ...existing.getAccountChatSessions.edges],
143
- totalCount: ((_a2 = existing.getAccountChatSessions.totalCount) != null ? _a2 : 0) + 1
144
- })
145
- }
146
- });
147
- }
148
- } catch (err) {
149
- console.warn("[useChatApi] createSession cache update failed:", err);
150
- }
151
- }
276
+ } = await addChannelMutation({
277
+ variables: __spreadValues(__spreadValues({
278
+ channelId: (_f = input == null ? void 0 : input.id) != null ? _f : null,
279
+ name: (_g = input == null ? void 0 : input.title) != null ? _g : "New Chat",
280
+ description: (_h = input == null ? void 0 : input.systemPrompt) != null ? _h : null,
281
+ type: RoomType.Aiassistant,
282
+ settings
283
+ }, orgName ? {
284
+ orgName
285
+ } : {}), projectId ? {
286
+ projectId
287
+ } : {}),
288
+ /**
289
+ * Refetch every cache slot the rest of the app is watching for
290
+ * channel lists. Apollo keys cached results by `variables`, so each
291
+ * shape we emit here must match a watched query exactly.
292
+ *
293
+ * Variants:
294
+ * 1. Legacy limit:100 list (web parity, no `criteria.orgName`).
295
+ * 2. Mobile history-screen variant WITH `criteria.orgName` so the
296
+ * resolver's `$in: [slug, orgId]` matches mobile-created channels.
297
+ * 3. Same variant WITHOUT orgName, in case the screen mounted before
298
+ * org settings resolved.
299
+ */
300
+ refetchQueries: [{
301
+ query: GetChannelsByUserWithLastMessageDocument,
302
+ variables: AI_ASSISTANT_CHANNELS_QUERY_VARS
303
+ }, ...orgName ? [{
304
+ query: GetChannelsByUserWithLastMessageDocument,
305
+ variables: getHistoryChannelsQueryVariables(orgName)
306
+ }] : [], {
307
+ query: GetChannelsByUserWithLastMessageDocument,
308
+ variables: HISTORY_QUERY_BASE
309
+ }],
310
+ awaitRefetchQueries: true
152
311
  });
153
- if (!(data == null ? void 0 : data.createAccountChatSession)) {
154
- throw new Error("Failed to create session");
312
+ if (!((_i = data == null ? void 0 : data.createChannel) == null ? void 0 : _i.id)) {
313
+ throw new Error("Failed to create channel");
155
314
  }
156
- const s = data.createAccountChatSession;
315
+ const channel = data.createChannel;
316
+ const title = (_k = (_j = channel.title) != null ? _j : input == null ? void 0 : input.title) != null ? _k : "New Chat";
317
+ const now = /* @__PURE__ */ new Date();
157
318
  return {
158
- id: s.id,
159
- title: (_b = s.title) != null ? _b : "New Chat",
160
- createdAt: new Date(s.createdAt),
161
- updatedAt: new Date(s.updatedAt)
319
+ id: channel.id,
320
+ title,
321
+ createdAt: now,
322
+ updatedAt: now
162
323
  };
163
- }, [createSessionMutation]);
324
+ }, [addChannelMutation]);
164
325
  const saveMessages = useCallback(async (input) => {
165
- const {
166
- data
167
- } = await saveMessagesMutation({
168
- variables: {
169
- input
170
- },
171
- update: (cache, {
172
- data: result
173
- }) => {
174
- var _a;
175
- if (!(result == null ? void 0 : result.saveAccountChatMessages)) return;
176
- const res = result.saveAccountChatMessages;
177
- try {
178
- const existingMessages = readMessagesCache(cache, input.sessionId);
179
- if (existingMessages == null ? void 0 : existingMessages.getAccountChatMessages) {
180
- const userEdge = buildMessageEdge(res.userMessage);
181
- const assistantEdge = buildMessageEdge(res.assistantMessage);
182
- cache.writeQuery({
183
- query: GetAccountChatMessagesDocument,
184
- variables: {
185
- sessionId: input.sessionId,
186
- first: 100
187
- },
188
- data: {
189
- getAccountChatMessages: __spreadProps(__spreadValues({}, existingMessages.getAccountChatMessages), {
190
- edges: [...existingMessages.getAccountChatMessages.edges, userEdge, assistantEdge],
191
- totalCount: ((_a = existingMessages.getAccountChatMessages.totalCount) != null ? _a : 0) + 2
192
- })
193
- }
194
- });
195
- }
196
- } catch (err) {
197
- console.warn("[useChatApi] saveMessages cache update failed:", err);
198
- }
199
- try {
200
- const existingSessions = readSessionsCache(cache);
201
- if (existingSessions == null ? void 0 : existingSessions.getAccountChatSessions) {
202
- const sessionData = res.session;
203
- const updatedEdges = existingSessions.getAccountChatSessions.edges.map((edge) => edge.node.id === sessionData.id ? __spreadProps(__spreadValues({}, edge), {
204
- node: __spreadValues(__spreadValues({}, edge.node), sessionData)
205
- }) : edge);
206
- cache.writeQuery({
207
- query: GetAccountChatSessionsDocument,
208
- variables: SESSIONS_QUERY_VARS,
209
- data: {
210
- getAccountChatSessions: __spreadProps(__spreadValues({}, existingSessions.getAccountChatSessions), {
211
- edges: updatedEdges
212
- })
213
- }
214
- });
215
- }
216
- } catch (err) {
217
- console.warn("[useChatApi] saveMessages session cache update failed:", err);
218
- }
219
- }
326
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k;
327
+ const sanitizedAssistantContent = stripModelCostHeader((_a = input.assistantMessage.content) != null ? _a : "");
328
+ const assistantMessageWithoutContent = omitContent((_b = input.assistantMessage) != null ? _b : {});
329
+ const userResult = await sendMessagesMutation({
330
+ variables: __spreadProps(__spreadValues({
331
+ channelId: input.sessionId,
332
+ type: RoomType.Aiassistant,
333
+ content: (_c = input.userMessage.content) != null ? _c : ""
334
+ }, input.createdBy ? {
335
+ createdBy: input.createdBy
336
+ } : {}), {
337
+ extraProps: __spreadValues(__spreadValues({
338
+ type: PostTypeEnum.Aiassistant,
339
+ role: "user",
340
+ attachments: (_d = input.userMessage.attachments) != null ? _d : [],
341
+ isActive: true,
342
+ status: "complete"
343
+ }, input.userMessage), input.mode ? {
344
+ mode: input.mode
345
+ } : {})
346
+ })
347
+ });
348
+ const userPostId = (_g = (_f = (_e = userResult.data) == null ? void 0 : _e.sendMessage) == null ? void 0 : _f.id) != null ? _g : null;
349
+ const assistantResult = await sendMessagesMutation({
350
+ variables: __spreadProps(__spreadValues({
351
+ channelId: input.sessionId,
352
+ type: RoomType.Aiassistant,
353
+ content: sanitizedAssistantContent
354
+ }, userPostId ? {
355
+ postId: userPostId
356
+ } : {}), {
357
+ extraProps: __spreadValues(__spreadValues(__spreadValues({
358
+ type: PostTypeEnum.Aiassistant,
359
+ role: "assistant",
360
+ attachments: (_h = input.assistantMessage.attachments) != null ? _h : [],
361
+ tokenCount: input.assistantMessage.tokenCount,
362
+ latencyMs: input.assistantMessage.latencyMs,
363
+ model: input.assistantMessage.model,
364
+ finishReason: (_i = input.assistantMessage.finishReason) != null ? _i : null,
365
+ isActive: true,
366
+ status: "complete"
367
+ }, userPostId ? {
368
+ parentId: userPostId
369
+ } : {}), assistantMessageWithoutContent), input.mode ? {
370
+ mode: input.mode
371
+ } : {})
372
+ })
220
373
  });
221
- if (!(data == null ? void 0 : data.saveAccountChatMessages)) {
222
- throw new Error("Failed to save messages");
374
+ const userPost = (_j = userResult.data) == null ? void 0 : _j.sendMessage;
375
+ const assistantPost = (_k = assistantResult.data) == null ? void 0 : _k.sendMessage;
376
+ if (!userPost || !assistantPost) {
377
+ throw new Error("Failed to send messages");
223
378
  }
224
- }, [saveMessagesMutation]);
379
+ const now = /* @__PURE__ */ new Date();
380
+ return {
381
+ userMessage: mapPostToChatMessageUI(userPost, input.sessionId),
382
+ assistantMessage: mapPostToChatMessageUI(assistantPost, input.sessionId),
383
+ session: {
384
+ id: input.sessionId,
385
+ title: "Chat",
386
+ createdAt: now,
387
+ updatedAt: now
388
+ }
389
+ };
390
+ }, [sendMessagesMutation]);
225
391
  return {
226
- createSession,
392
+ createChannel,
393
+ createSession: createChannel,
227
394
  saveMessages,
228
395
  loading: {
229
- create: createLoading,
230
- saveMessages: saveMessagesLoading
396
+ create: createChannelLoading,
397
+ saveMessages: sendMessagesLoading
231
398
  }
232
399
  };
233
- }export{useChatMessages,useChatMutations};//# sourceMappingURL=useChatApi.js.map
400
+ }export{AI_ASSISTANT_CHANNELS_QUERY_VARS,HISTORY_PAGE_SIZE,HISTORY_QUERY_BASE,buildSessionFromChannel,chatHistorySessionsFromChannels,getHistoryChannelsQueryVariables,useChatHistorySessionsFromChannels,useChatMessages,useChatMutations};//# sourceMappingURL=useChatApi.js.map