@adminide-stack/yantra-mobile 12.0.28-alpha.8 → 12.0.28-alpha.80

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 (85) 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 +18 -0
  19. package/lib/config/constants.js.map +1 -0
  20. package/lib/config/env-config.js +75 -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 +220 -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/features/audio-input/useAudioPermission.js +24 -0
  31. package/lib/features/audio-input/useAudioPermission.js.map +1 -0
  32. package/lib/graphql/agentGatewayDocuments.js +53 -0
  33. package/lib/graphql/agentGatewayDocuments.js.map +1 -0
  34. package/lib/hooks/useAccountDefaultSettings.js +38 -0
  35. package/lib/hooks/useAccountDefaultSettings.js.map +1 -0
  36. package/lib/hooks/useCdecliAutoConnect.js +244 -0
  37. package/lib/hooks/useCdecliAutoConnect.js.map +1 -0
  38. package/lib/hooks/useCdecliChannel.js +161 -0
  39. package/lib/hooks/useCdecliChannel.js.map +1 -0
  40. package/lib/hooks/useChatApi.js +390 -171
  41. package/lib/hooks/useChatApi.js.map +1 -1
  42. package/lib/hooks/useChatStream.js +179 -137
  43. package/lib/hooks/useChatStream.js.map +1 -1
  44. package/lib/hooks/useGatewayConnection.js +123 -0
  45. package/lib/hooks/useGatewayConnection.js.map +1 -0
  46. package/lib/hooks/useGatewayRegistry.js +28 -0
  47. package/lib/hooks/useGatewayRegistry.js.map +1 -0
  48. package/lib/hooks/usePrerequisiteIds.js +209 -0
  49. package/lib/hooks/usePrerequisiteIds.js.map +1 -0
  50. package/lib/hooks/useWorkspaceProvisioner.js +236 -0
  51. package/lib/hooks/useWorkspaceProvisioner.js.map +1 -0
  52. package/lib/index.js +1 -1
  53. package/lib/index.js.map +1 -1
  54. package/lib/routes.json +120 -5
  55. package/lib/screens/Chat/index.js +409 -0
  56. package/lib/screens/Chat/index.js.map +1 -0
  57. package/lib/screens/ChatHistory/index.js +56 -0
  58. package/lib/screens/ChatHistory/index.js.map +1 -0
  59. package/lib/screens/Home/HomeScreen.js +364 -144
  60. package/lib/screens/Home/HomeScreen.js.map +1 -1
  61. package/lib/screens/Home/components/ChatHistoryLanding.js +487 -0
  62. package/lib/screens/Home/components/ChatHistoryLanding.js.map +1 -0
  63. package/lib/screens/Home/components/DeepSearchModal.js +349 -0
  64. package/lib/screens/Home/components/DeepSearchModal.js.map +1 -0
  65. package/lib/screens/Home/deepSearchUtils.js +41 -0
  66. package/lib/screens/Home/deepSearchUtils.js.map +1 -0
  67. package/lib/screens/NewChat/index.js +43 -0
  68. package/lib/screens/NewChat/index.js.map +1 -0
  69. package/lib/services/agentSessionManager.js +451 -0
  70. package/lib/services/agentSessionManager.js.map +1 -0
  71. package/lib/services/gatewayApiKeyBridge.js +4 -0
  72. package/lib/services/gatewayApiKeyBridge.js.map +1 -0
  73. package/lib/services/gatewayClient.js +470 -0
  74. package/lib/services/gatewayClient.js.map +1 -0
  75. package/lib/theme/mobileTokens.js +18 -0
  76. package/lib/theme/mobileTokens.js.map +1 -0
  77. package/lib/utils/cdecodeUri.js +68 -0
  78. package/lib/utils/cdecodeUri.js.map +1 -0
  79. package/lib/utils/gatewaySelectionStorage.js +21 -0
  80. package/lib/utils/gatewaySelectionStorage.js.map +1 -0
  81. package/lib/utils/syncMobileOrgRouteContext.js +61 -0
  82. package/lib/utils/syncMobileOrgRouteContext.js.map +1 -0
  83. package/package.json +7 -3
  84. package/lib/api/chatApi.js +0 -102
  85. package/lib/api/chatApi.js.map +0 -1
@@ -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;
48
116
  return {
49
- __typename: "AccountChatSessionEdge",
50
- cursor: "",
51
- node: __spreadValues({
52
- __typename: "AccountChatSession"
53
- }, node)
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
54
124
  };
55
125
  }
56
- function buildMessageEdge(node) {
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;
57
152
  return {
58
- __typename: "AccountChatMessageEdge",
59
- cursor: "",
60
- node: __spreadValues({
61
- __typename: "AccountChatMessage"
62
- }, node)
153
+ sessions,
154
+ loading,
155
+ sessionsLoaded,
156
+ error,
157
+ refetch,
158
+ sourceChannelCount
159
+ };
160
+ }
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);
184
+ return {
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,244 @@ 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
  }
246
+ function isDuplicatePostError(error) {
247
+ var _a;
248
+ const parts = [];
249
+ if (error && typeof error === "object" && "graphQLErrors" in error) {
250
+ const gqlErrors = (_a = error.graphQLErrors) != null ? _a : [];
251
+ parts.push(...gqlErrors.map((e) => {
252
+ var _a2;
253
+ return (_a2 = e == null ? void 0 : e.message) != null ? _a2 : "";
254
+ }));
255
+ }
256
+ if (error instanceof Error) {
257
+ parts.push(error.message);
258
+ } else if (error != null) {
259
+ parts.push(String(error));
260
+ }
261
+ const msg = parts.join(" ");
262
+ return /E11000|duplicate key/i.test(msg);
263
+ }
105
264
  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
- });
265
+ const [addChannelMutation, {
266
+ loading: createChannelLoading
267
+ }] = useAddChannelMutation();
268
+ const [sendMessagesMutation, {
269
+ loading: sendMessagesLoading
270
+ }] = useSendMessagesMutation();
271
+ const createChannel = useCallback(async (input) => {
272
+ var _b, _c, _d, _e, _f, _g, _h, _i, _j, _k;
273
+ const _a = input != null ? input : {}, {
274
+ orgName: orgNameArg,
275
+ projectId: projectIdArg
276
+ } = _a, inputForSettings = __objRest(_a, [
277
+ "orgName",
278
+ "projectId"
279
+ ]);
280
+ const orgName = typeof orgNameArg === "string" && orgNameArg.trim().length > 0 ? orgNameArg.trim() : void 0;
281
+ const projectId = typeof projectIdArg === "string" && projectIdArg.trim().length > 0 ? projectIdArg.trim() : void 0;
282
+ const settings = __spreadValues({
283
+ title: (_b = input == null ? void 0 : input.title) != null ? _b : "New Chat",
284
+ description: (_c = input == null ? void 0 : input.systemPrompt) != null ? _c : null,
285
+ isShared: false,
286
+ sharedSlug: null,
287
+ isArchived: false,
288
+ isPinned: false,
289
+ model: (_d = input == null ? void 0 : input.model) != null ? _d : null,
290
+ systemPrompt: (_e = input == null ? void 0 : input.systemPrompt) != null ? _e : null
291
+ }, inputForSettings);
122
292
  const {
123
293
  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
- }
294
+ } = await addChannelMutation({
295
+ variables: __spreadValues(__spreadValues({
296
+ channelId: (_f = input == null ? void 0 : input.id) != null ? _f : null,
297
+ name: (_g = input == null ? void 0 : input.title) != null ? _g : "New Chat",
298
+ description: (_h = input == null ? void 0 : input.systemPrompt) != null ? _h : null,
299
+ type: RoomType.Aiassistant,
300
+ settings
301
+ }, orgName ? {
302
+ orgName
303
+ } : {}), projectId ? {
304
+ projectId
305
+ } : {}),
306
+ /**
307
+ * Refetch every cache slot the rest of the app is watching for
308
+ * channel lists. Apollo keys cached results by `variables`, so each
309
+ * shape we emit here must match a watched query exactly.
310
+ *
311
+ * Variants:
312
+ * 1. Legacy limit:100 list (web parity, no `criteria.orgName`).
313
+ * 2. Mobile history-screen variant WITH `criteria.orgName` so the
314
+ * resolver's `$in: [slug, orgId]` matches mobile-created channels.
315
+ * 3. Same variant WITHOUT orgName, in case the screen mounted before
316
+ * org settings resolved.
317
+ */
318
+ refetchQueries: [{
319
+ query: GetChannelsByUserWithLastMessageDocument,
320
+ variables: AI_ASSISTANT_CHANNELS_QUERY_VARS
321
+ }, ...orgName ? [{
322
+ query: GetChannelsByUserWithLastMessageDocument,
323
+ variables: getHistoryChannelsQueryVariables(orgName)
324
+ }] : [], {
325
+ query: GetChannelsByUserWithLastMessageDocument,
326
+ variables: HISTORY_QUERY_BASE
327
+ }],
328
+ awaitRefetchQueries: true
152
329
  });
153
- if (!(data == null ? void 0 : data.createAccountChatSession)) {
154
- throw new Error("Failed to create session");
330
+ if (!((_i = data == null ? void 0 : data.createChannel) == null ? void 0 : _i.id)) {
331
+ throw new Error("Failed to create channel");
155
332
  }
156
- const s = data.createAccountChatSession;
333
+ const channel = data.createChannel;
334
+ const title = (_k = (_j = channel.title) != null ? _j : input == null ? void 0 : input.title) != null ? _k : "New Chat";
335
+ const now = /* @__PURE__ */ new Date();
157
336
  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)
337
+ id: channel.id,
338
+ title,
339
+ createdAt: now,
340
+ updatedAt: now
162
341
  };
163
- }, [createSessionMutation]);
342
+ }, [addChannelMutation]);
164
343
  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
- }
344
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j;
345
+ const sanitizedAssistantContent = stripModelCostHeader((_a = input.assistantMessage.content) != null ? _a : "");
346
+ const assistantMessageWithoutContent = omitContent((_b = input.assistantMessage) != null ? _b : {});
347
+ let userPost;
348
+ try {
349
+ const userResult = await sendMessagesMutation({
350
+ variables: __spreadProps(__spreadValues({
351
+ channelId: input.sessionId,
352
+ type: RoomType.Aiassistant,
353
+ content: (_c = input.userMessage.content) != null ? _c : ""
354
+ }, input.createdBy ? {
355
+ createdBy: input.createdBy
356
+ } : {}), {
357
+ extraProps: __spreadValues(__spreadValues({
358
+ type: PostTypeEnum.Aiassistant,
359
+ role: "user",
360
+ attachments: (_d = input.userMessage.attachments) != null ? _d : [],
361
+ isActive: true,
362
+ status: "complete"
363
+ }, input.userMessage), input.mode ? {
364
+ mode: input.mode
365
+ } : {})
366
+ })
367
+ });
368
+ userPost = (_e = userResult.data) == null ? void 0 : _e.sendMessage;
369
+ } catch (err) {
370
+ if (!isDuplicatePostError(err)) {
371
+ throw err;
219
372
  }
220
- });
221
- if (!(data == null ? void 0 : data.saveAccountChatMessages)) {
222
- throw new Error("Failed to save messages");
373
+ console.warn("[saveMessages] user post already persisted (skipping duplicate insert)");
374
+ }
375
+ const userPostId = (_f = userPost == null ? void 0 : userPost.id) != null ? _f : null;
376
+ let assistantPost;
377
+ try {
378
+ const assistantResult = await sendMessagesMutation({
379
+ variables: __spreadProps(__spreadValues({
380
+ channelId: input.sessionId,
381
+ type: RoomType.Aiassistant,
382
+ content: sanitizedAssistantContent
383
+ }, userPostId ? {
384
+ postId: userPostId
385
+ } : {}), {
386
+ extraProps: __spreadValues(__spreadValues(__spreadValues({
387
+ type: PostTypeEnum.Aiassistant,
388
+ role: "assistant",
389
+ attachments: (_g = input.assistantMessage.attachments) != null ? _g : [],
390
+ tokenCount: input.assistantMessage.tokenCount,
391
+ latencyMs: input.assistantMessage.latencyMs,
392
+ model: input.assistantMessage.model,
393
+ finishReason: (_h = input.assistantMessage.finishReason) != null ? _h : null,
394
+ isActive: true,
395
+ status: "complete"
396
+ }, userPostId ? {
397
+ parentId: userPostId
398
+ } : {}), assistantMessageWithoutContent), input.mode ? {
399
+ mode: input.mode
400
+ } : {})
401
+ })
402
+ });
403
+ assistantPost = (_i = assistantResult.data) == null ? void 0 : _i.sendMessage;
404
+ } catch (err) {
405
+ if (!isDuplicatePostError(err)) {
406
+ throw err;
407
+ }
408
+ console.warn("[saveMessages] assistant post already persisted (skipping duplicate insert)");
223
409
  }
224
- }, [saveMessagesMutation]);
410
+ if (!userPost && !assistantPost) {
411
+ throw new Error("Failed to send messages");
412
+ }
413
+ const now = /* @__PURE__ */ new Date();
414
+ const fallbackUser = {
415
+ id: userPostId != null ? userPostId : v4(),
416
+ sessionId: input.sessionId,
417
+ role: "user",
418
+ content: (_j = input.userMessage.content) != null ? _j : "",
419
+ createdAt: now,
420
+ updatedAt: now
421
+ };
422
+ const fallbackAssistant = {
423
+ id: v4(),
424
+ sessionId: input.sessionId,
425
+ role: "assistant",
426
+ content: sanitizedAssistantContent,
427
+ createdAt: now,
428
+ updatedAt: now,
429
+ tokenCount: input.assistantMessage.tokenCount,
430
+ model: input.assistantMessage.model
431
+ };
432
+ return {
433
+ userMessage: userPost ? mapPostToChatMessageUI(userPost, input.sessionId) : fallbackUser,
434
+ assistantMessage: assistantPost ? mapPostToChatMessageUI(assistantPost, input.sessionId) : fallbackAssistant,
435
+ session: {
436
+ id: input.sessionId,
437
+ title: "Chat",
438
+ createdAt: now,
439
+ updatedAt: now
440
+ }
441
+ };
442
+ }, [sendMessagesMutation]);
225
443
  return {
226
- createSession,
444
+ createChannel,
445
+ createSession: createChannel,
227
446
  saveMessages,
228
447
  loading: {
229
- create: createLoading,
230
- saveMessages: saveMessagesLoading
448
+ create: createChannelLoading,
449
+ saveMessages: sendMessagesLoading
231
450
  }
232
451
  };
233
- }export{useChatMessages,useChatMutations};//# sourceMappingURL=useChatApi.js.map
452
+ }export{AI_ASSISTANT_CHANNELS_QUERY_VARS,HISTORY_PAGE_SIZE,HISTORY_QUERY_BASE,buildSessionFromChannel,chatHistorySessionsFromChannels,getHistoryChannelsQueryVariables,useChatHistorySessionsFromChannels,useChatMessages,useChatMutations};//# sourceMappingURL=useChatApi.js.map