@jsb188/graphql 1.1.10 → 1.1.12

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 (176) hide show
  1. package/audience.d.ts +343 -0
  2. package/cache/config.ts +98 -50
  3. package/cache/index.chat-activity.test.ts +119 -0
  4. package/cache/index.chat.test.ts +92 -0
  5. package/cache/index.helpers.ts +96 -0
  6. package/cache/index.regression.test.ts +149 -0
  7. package/cache/index.test.ts +1017 -127
  8. package/cache/index.ts +1256 -1269
  9. package/cache/optimistic-ui-runtime.ts +46 -0
  10. package/cache/optimistic-ui.ts +401 -0
  11. package/cache/persist.ts +800 -0
  12. package/cache/store.ts +395 -0
  13. package/cache/value.helpers.ts +17 -0
  14. package/client/draft-persistence-indexed-db.ts +413 -0
  15. package/client/draft-persistence.ts +152 -0
  16. package/client/index.ts +3 -0
  17. package/client/request.helpers.ts +14 -0
  18. package/client/request.ts +870 -164
  19. package/deno.lock +187 -0
  20. package/deno.test.json +10 -4
  21. package/gql/eagerQueryMap.ts +12 -0
  22. package/gql/fragments/accountAuthFragments.ts +5 -0
  23. package/gql/fragments/accountFragments.ts +0 -3
  24. package/gql/fragments/accountSessionFragments.ts +16 -0
  25. package/gql/fragments/agentMemoryFragments.ts +23 -0
  26. package/gql/fragments/agentNoteFragments.ts +150 -0
  27. package/gql/fragments/aiChatFragments.ts +42 -0
  28. package/gql/fragments/audienceFragments.ts +141 -0
  29. package/gql/fragments/campaignFragments.ts +566 -0
  30. package/gql/fragments/dataTableFragments.ts +50 -192
  31. package/gql/fragments/emailFragments.ts +32 -17
  32. package/gql/fragments/fieldDocFragments.ts +264 -0
  33. package/gql/fragments/inboundContactFragments.ts +2 -0
  34. package/gql/fragments/logFragments.ts +101 -69
  35. package/gql/fragments/organizationFragments.ts +53 -5
  36. package/gql/fragments/qrCodeFragments.ts +29 -0
  37. package/gql/fragments/scheduleFragments.ts +667 -0
  38. package/gql/fragments/sheetFragments.ts +304 -63
  39. package/gql/fragments/storageFragments.ts +45 -0
  40. package/gql/fragments/workflowFragments.ts +41 -5
  41. package/gql/mutations/accountMutations.ts +0 -2
  42. package/gql/mutations/agentMemoryMutations.ts +68 -0
  43. package/gql/mutations/agentNoteMutations.ts +62 -0
  44. package/gql/mutations/aiChatMutations.ts +49 -4
  45. package/gql/mutations/audienceMutations.ts +71 -0
  46. package/gql/mutations/authMutations.ts +203 -18
  47. package/gql/mutations/billingMutations.ts +17 -27
  48. package/gql/mutations/campaignMutations.ts +258 -0
  49. package/gql/mutations/contactMutations.ts +23 -0
  50. package/gql/mutations/dataTableMutations.ts +19 -54
  51. package/gql/mutations/fieldDocMutations.ts +173 -0
  52. package/gql/mutations/index.ts +10 -2
  53. package/gql/mutations/logMutations.ts +6 -29
  54. package/gql/mutations/organizationMutations.ts +19 -4
  55. package/gql/mutations/qrCodeMutations.ts +20 -0
  56. package/gql/mutations/scheduleMutations.ts +1121 -0
  57. package/gql/mutations/sheetMutations.ts +221 -60
  58. package/gql/mutations/storageMutations.ts +19 -0
  59. package/gql/mutations/workflowMutations.ts +60 -0
  60. package/gql/queries/agentMemoryQueries.ts +28 -0
  61. package/gql/queries/agentNoteQueries.ts +89 -0
  62. package/gql/queries/aiChatQueries.ts +70 -2
  63. package/gql/queries/audienceQueries.ts +128 -0
  64. package/gql/queries/authQueries.ts +47 -0
  65. package/gql/queries/billingQueries.ts +118 -6
  66. package/gql/queries/campaignQueries.ts +236 -0
  67. package/gql/queries/dataTableQueries.ts +61 -13
  68. package/gql/queries/emailQueries.ts +26 -17
  69. package/gql/queries/emailReplyReportQueries.ts +76 -0
  70. package/gql/queries/fieldDocQueries.ts +166 -0
  71. package/gql/queries/inboundContactQueries.ts +4 -0
  72. package/gql/queries/index.ts +10 -2
  73. package/gql/queries/logQueries.ts +68 -30
  74. package/gql/queries/organizationQueries.ts +65 -1
  75. package/gql/queries/qrCodeQueries.ts +20 -0
  76. package/gql/queries/scheduleQueries.ts +691 -0
  77. package/gql/queries/sheetQueries.ts +244 -26
  78. package/gql/queries/storageQueries.ts +38 -0
  79. package/gql/queries/workflowQueries.ts +77 -2
  80. package/hooks/index.helpers.test.ts +50 -0
  81. package/hooks/index.helpers.ts +52 -0
  82. package/hooks/index.ts +2254 -982
  83. package/hooks/use-account-mtn.ts +76 -81
  84. package/hooks/use-agentMemory-mtn.ts +71 -0
  85. package/hooks/use-agentMemory-qry.ts +56 -0
  86. package/hooks/use-agentNote-mtn.ts +82 -0
  87. package/hooks/use-agentNote-qry.ts +190 -0
  88. package/hooks/use-agentNote-recovery.helpers.test.ts +68 -0
  89. package/hooks/use-agentNote-recovery.helpers.ts +58 -0
  90. package/hooks/use-agentNote-recovery.ts +72 -0
  91. package/hooks/use-aiChat-mtn.ts +220 -141
  92. package/hooks/use-aiChat-qry.helpers.test.ts +63 -0
  93. package/hooks/use-aiChat-qry.helpers.ts +124 -0
  94. package/hooks/use-aiChat-qry.ts +341 -237
  95. package/hooks/use-aiChat-stream-mtn.ts +14 -0
  96. package/hooks/use-app-qry.ts +12 -9
  97. package/hooks/use-audience-mtn.ts +194 -0
  98. package/hooks/use-audience-qry.helpers.test.ts +80 -0
  99. package/hooks/use-audience-qry.helpers.ts +63 -0
  100. package/hooks/use-audience-qry.ts +330 -0
  101. package/hooks/use-auth-mtn.ts +435 -252
  102. package/hooks/use-auth-qry.ts +51 -0
  103. package/hooks/use-billing-mtn.ts +31 -0
  104. package/hooks/use-billing-qry.ts +76 -0
  105. package/hooks/use-campaign-generation-recovery.ts +53 -0
  106. package/hooks/use-campaign-mtn.ts +436 -0
  107. package/hooks/use-campaign-qry.helpers.ts +40 -0
  108. package/hooks/use-campaign-qry.ts +834 -0
  109. package/hooks/use-dataTable-mtn.ts +37 -46
  110. package/hooks/use-dataTable-qry.ts +102 -128
  111. package/hooks/use-email-qry.helpers.ts +37 -0
  112. package/hooks/use-email-qry.ts +56 -86
  113. package/hooks/use-emailCampaignReplyReport-qry.ts +27 -0
  114. package/hooks/use-fieldDoc-mtn.ts +262 -0
  115. package/hooks/use-fieldDoc-qry.helpers.test.ts +65 -0
  116. package/hooks/use-fieldDoc-qry.helpers.ts +49 -0
  117. package/hooks/use-fieldDoc-qry.ts +212 -0
  118. package/hooks/use-inboundContact-mtn.ts +19 -16
  119. package/hooks/use-inboundContact-qry.ts +62 -56
  120. package/hooks/use-integration-mtn.ts +56 -38
  121. package/hooks/use-integration-qry.ts +24 -9
  122. package/hooks/use-log-mtn.ts +88 -59
  123. package/hooks/use-log-qry.ts +150 -73
  124. package/hooks/use-organization-mtn.ts +334 -277
  125. package/hooks/use-organization-qry.ts +155 -129
  126. package/hooks/use-publicFormEmail-mtn.ts +27 -0
  127. package/hooks/use-qrCode-mtn.ts +40 -0
  128. package/hooks/use-qrCode-qry.ts +78 -0
  129. package/hooks/use-schedule-mtn.ts +589 -0
  130. package/hooks/use-schedule-qry.ts +738 -0
  131. package/hooks/use-schedule-reactive.ts +486 -0
  132. package/hooks/use-sheet-mtn.ts +157 -79
  133. package/hooks/use-sheet-qry.ts +221 -92
  134. package/hooks/use-storage-mtn.ts +81 -41
  135. package/hooks/use-storage-qry.ts +128 -14
  136. package/hooks/use-workflow-mtn.ts +72 -0
  137. package/hooks/use-workflow-qry.ts +184 -47
  138. package/libs/ai-chat-outgoing.helpers.ts +153 -0
  139. package/libs/ai-chat-outgoing.ts +11 -0
  140. package/libs/ai-chat-outgoing.types.ts +25 -0
  141. package/libs/ai-chat-run-realtime.ts +20 -0
  142. package/libs/ai-chat-submission-realtime.ts +150 -0
  143. package/libs/fragment-realtime-sequence.ts +55 -0
  144. package/libs/fragment-recovery.test.ts +326 -0
  145. package/libs/fragment-recovery.ts +325 -0
  146. package/libs/open-sheet.ts +138 -0
  147. package/libs/orchestrator-realtime.helpers.test.ts +229 -0
  148. package/libs/orchestrator-realtime.helpers.ts +317 -0
  149. package/libs/orchestrator-realtime.ts +433 -0
  150. package/libs/request-cache-regression.test.ts +122 -0
  151. package/libs/request-managed-session.test.ts +574 -0
  152. package/libs/request-no-store.test.ts +419 -0
  153. package/libs/sheet-command-batch.ts +44 -0
  154. package/libs/sheet-view-realtime-router.test.ts +214 -0
  155. package/libs/sheet-view-realtime-router.ts +99 -0
  156. package/libs/sse-ticket.test.ts +26 -0
  157. package/loaders/campaign.test.ts +186 -0
  158. package/loaders/campaign.ts +110 -0
  159. package/loaders/emailPreference.ts +75 -0
  160. package/loaders/rest.ts +12 -0
  161. package/package.json +119 -71
  162. package/schedule.d.ts +1790 -0
  163. package/sse.helpers.ts +19 -0
  164. package/sse.ts +70 -106
  165. package/tests/agent-note-detail-cache.test.ts +120 -0
  166. package/tests/agent-note-search.test.ts +444 -0
  167. package/tsconfig.json +11 -10
  168. package/types.d.ts +77 -26
  169. package/utils.ts +78 -49
  170. package/gql/fragments/billingFragments.ts +0 -25
  171. package/gql/fragments/productFragments.ts +0 -39
  172. package/gql/fragments/reportFragments.ts +0 -90
  173. package/gql/queries/productQueries.ts +0 -31
  174. package/gql/queries/reportQueries.ts +0 -134
  175. package/hooks/use-product-qry.ts +0 -67
  176. package/hooks/use-report-qry.ts +0 -153
@@ -0,0 +1,58 @@
1
+ type AgentNoteQueryName = 'agentNote' | 'agentNotes' | 'searchAgentNotes';
2
+
3
+ /*
4
+ * The note resolver reports missing and unreadable notes with the same 404.
5
+ * Preserve that privacy boundary without treating other errors as absence.
6
+ * Server formatting may encode the error code numerically.
7
+ */
8
+ export function isAgentNoteMissingError(error: unknown): boolean {
9
+ if (!error || typeof error !== 'object') return false;
10
+ const value = error as { errorCode?: unknown; statusCode?: unknown };
11
+ return String(value.errorCode) === '20232' && value.statusCode === 404;
12
+ }
13
+
14
+ /*
15
+ * A retained fragment cannot resurrect a detail that the current authorized
16
+ * read declared missing, including the resolver's exact typed 404 result.
17
+ */
18
+ export function getVisibleAgentNote<T>(
19
+ data: { agentNote?: T | null } | null | undefined,
20
+ fragment: (T & { __deleted?: boolean }) | null,
21
+ error: unknown,
22
+ ): T | null {
23
+ return !data || data.agentNote === null || fragment?.__deleted || isAgentNoteMissingError(error) ? null : fragment;
24
+ }
25
+
26
+ /*
27
+ * Accept only complete authorized note responses. A missing detail
28
+ * (agentNote: null), including the exact 20232/404 result, confirms absence.
29
+ */
30
+ export function agentNoteRecoveryReadSucceeded(result: unknown, queryName: AgentNoteQueryName): boolean {
31
+ if (!result || typeof result !== 'object') return false;
32
+ const response = result as Record<string, unknown>;
33
+ const search = response.searchAgentNotes as { items?: unknown; revision?: unknown } | null | undefined;
34
+ const validSearch =
35
+ queryName !== 'searchAgentNotes' ||
36
+ (Array.isArray(search?.items) && typeof search.revision === 'string' && /^\d+$/.test(search.revision));
37
+ const missingDetail = queryName === 'agentNote' && response.agentNote === null && isAgentNoteMissingError(response.error);
38
+ return (
39
+ validSearch &&
40
+ (!response.error || missingDetail) &&
41
+ !response.aborted &&
42
+ !response.skipped &&
43
+ !response.__clientResultRejected &&
44
+ Object.hasOwn(response, queryName)
45
+ );
46
+ }
47
+
48
+ /*
49
+ * Read a revision only when the same successful response contains the search
50
+ * items. A separate revision request cannot certify another content snapshot.
51
+ */
52
+ export function getAgentNoteResponseRevision(result: unknown, queryName: AgentNoteQueryName): string | null {
53
+ if (queryName !== 'searchAgentNotes' || !agentNoteRecoveryReadSucceeded(result, queryName)) return null;
54
+ const snapshot = (result as { searchAgentNotes?: { items?: unknown; revision?: unknown } }).searchAgentNotes;
55
+ return Array.isArray(snapshot?.items) && typeof snapshot.revision === 'string' && /^\d+$/.test(snapshot.revision)
56
+ ? snapshot.revision
57
+ : null;
58
+ }
@@ -0,0 +1,72 @@
1
+ import { getAuthToken, getManagedAccessTokenBinding, managedAccessTokensShareBinding } from '@jsb188/app/utils/api.ts';
2
+ import { makeGraphQLVariablesKey } from '@jsb188/app/utils/logic.ts';
3
+ import { useCurrentAccount, useRealtimeConnectionGenerationValue } from '@jsb188/react/states';
4
+ import { useEffect, useLayoutEffect, useMemo, useRef } from 'react';
5
+ import type { GraphQLQueryOptions } from '../types.d.ts';
6
+ import { useQuery } from './index.ts';
7
+
8
+ /* Allow transparent token renewal only within the same authenticated session. */
9
+ function sameAuthenticationContext(initialToken: string | null, currentToken: string | null) {
10
+ return (
11
+ initialToken === currentToken || !!(initialToken && currentToken && managedAccessTokensShareBinding(initialToken, currentToken))
12
+ );
13
+ }
14
+
15
+ /*
16
+ * Guard note responses before normalization and recover after a replacement
17
+ * socket. Collection invalidations coalesce through the shared query lifecycle;
18
+ * a request overtaken by an invalidation cannot normalize stale rows. Point
19
+ * reads share this fence so their late results cannot regress collection data.
20
+ */
21
+ export function useRecoverableAgentNoteQuery(query: any, organizationId: string | null | undefined, options: GraphQLQueryOptions) {
22
+ const { account } = useCurrentAccount();
23
+ const generation = useRealtimeConnectionGenerationValue();
24
+ const authToken = options.authToken || getAuthToken();
25
+ const session = authToken ? getManagedAccessTokenBinding(authToken) : null;
26
+ const scopeKey = JSON.stringify([account?.id, organizationId, session || authToken]);
27
+ const queryName = query.definitions[0].name.value;
28
+ const queryKey = `#${queryName}:${makeGraphQLVariablesKey(options.variables)}`;
29
+ const current = useRef({ scopeKey, queryKey, active: !options.skip });
30
+ const requestScope = useMemo(() => ({ active: false }), [scopeKey, queryKey, options.skip]);
31
+
32
+ /* Publish only committed scope changes to pending network-response guards. */
33
+ useLayoutEffect(() => {
34
+ current.current = { scopeKey, queryKey, active: !options.skip };
35
+ requestScope.active = !options.skip;
36
+ return () => {
37
+ current.current.active = false;
38
+ requestScope.active = false;
39
+ };
40
+ }, [scopeKey, queryKey, options.skip, requestScope]);
41
+
42
+ /* Reject a late result before the shared GraphQL client normalizes it. */
43
+ const isCurrent = () =>
44
+ requestScope.active &&
45
+ current.current.active &&
46
+ current.current.scopeKey === scopeKey &&
47
+ current.current.queryKey === queryKey &&
48
+ sameAuthenticationContext(authToken, options.authToken || getAuthToken());
49
+ const result = useQuery(query, {
50
+ ...options,
51
+ requestTimeoutMs: 30_000,
52
+ rejectInvalidatedResults: true,
53
+ shouldAcceptResult: (data, variables) =>
54
+ isCurrent() && (!options.shouldAcceptResult || options.shouldAcceptResult(data, variables)),
55
+ });
56
+ const previousConnection = useRef({ generation, requestScope, pending: false });
57
+
58
+ /* Retain one reconnect recovery until loading settles, scoped to this query activation. */
59
+ useEffect(() => {
60
+ const previous = previousConnection.current;
61
+ const pending = previous.requestScope === requestScope && (previous.pending || previous.generation !== generation);
62
+ previousConnection.current = { generation, requestScope, pending: pending && isCurrent() };
63
+ if (!previousConnection.current.pending || result.loading !== false) return;
64
+
65
+ previousConnection.current.pending = false;
66
+ void result.refetch().catch(() => {
67
+ // Query state owns the load error; do not create an unhandled reconnect rejection.
68
+ });
69
+ }, [generation, requestScope, result.loading]);
70
+
71
+ return { ...result, data: !options.skip && result.queryKey === queryKey ? result.data : null };
72
+ }
@@ -1,38 +1,38 @@
1
- import { resetQuery, updateFragment, updateQuery } from '../cache/index.ts';
2
- import { useMutation } from '../client/index.ts';
3
- import { updateAIChats } from './use-aiChat-qry.ts';
4
- import { deleteAIChatMtn, editAIChatMtn, sendAIChatMessageMtn, startAIChatMtn, stopAIChatMessageMtn } from '../gql/mutations/aiChatMutations.ts';
5
- import type { UseMutationParams } from '../types.d.ts';
6
- import { useOpenModalPopUp } from '@jsb188/react/states';
7
- import { useEffect, useRef } from 'react';
1
+ import { FRAGMENT_NAMES, makeFragmentKey } from '@jsb188/mday/constants/graphqlReactivity.ts';
2
+ import { type OpenModalPopUpFn, useOpenModalPopUp } from '@jsb188/react/states';
3
+ import { useCallback, useEffect, useRef } from 'react';
4
+ import { normalizeServerError } from '@jsb188/app/utils/api.ts';
5
+ import { loadFragment, resetQuery, updateFragment, updateQuery } from '../cache/index.ts';
6
+ import { type GraphQLMutationFn, useMutation } from '../client/index.ts';
7
+ import {
8
+ deleteAIChatMtn,
9
+ editAIChatMtn,
10
+ sendAIChatMessageMtn,
11
+ startAIChatMtn,
12
+ stopAIChatMessageMtn,
13
+ } from '../gql/mutations/aiChatMutations.ts';
14
+ import type { UseMutationParams, UseMutationParamsExtra } from '../types.d.ts';
15
+ import { acceptAIChatOutgoingMessage, failAIChatOutgoingMessage } from '../libs/ai-chat-outgoing.ts';
8
16
 
9
17
  /**
10
18
  * Start AI chat
11
19
  */
12
20
 
13
- export function useStartAIChat(params: UseMutationParams = {}) {
14
-
15
- const { onCompleted, onError } = params;
16
- const openModalPopUp = useOpenModalPopUp();
17
-
18
- const [startAIChat, mtnValues,, updateObservers] = useMutation(
19
- startAIChatMtn,
20
- {
21
- openModalPopUp,
22
- onCompleted: (data: any, err: any, variables: any) => {
23
- onCompleted?.(data, err, variables);
24
-
25
- const aiChat = data.startAIChat?.node;
26
- updateAIChats(aiChat, variables?.organizationId, updateObservers);
27
- },
28
- onError,
29
- },
30
- );
31
-
32
- return {
33
- startAIChat,
34
- ...mtnValues,
35
- };
21
+ export function useStartAIChat(params: UseMutationParamsExtra = {}, openModalPopUp?: OpenModalPopUpFn) {
22
+ const { onCompleted, onError, ...rest } = params;
23
+
24
+ const [startAIChat, mtnValues, mtnHandlers] = useMutation(startAIChatMtn, {
25
+ ...rest,
26
+ openModalPopUp,
27
+ onCompleted,
28
+ onError,
29
+ });
30
+
31
+ return {
32
+ startAIChat,
33
+ ...mtnValues,
34
+ ...mtnHandlers,
35
+ };
36
36
  }
37
37
 
38
38
  /**
@@ -40,24 +40,69 @@ export function useStartAIChat(params: UseMutationParams = {}) {
40
40
  */
41
41
 
42
42
  export function useEditAIChat(params: UseMutationParams = {}) {
43
-
44
- const { onCompleted, onError } = params;
45
- const openModalPopUp = useOpenModalPopUp();
46
-
47
- const [editAIChat, mtnValues, mtnHandlers] = useMutation(
48
- editAIChatMtn,
49
- {
50
- openModalPopUp,
51
- onCompleted,
52
- onError,
53
- },
54
- );
55
-
56
- return {
57
- editAIChat,
58
- ...mtnValues,
59
- ...mtnHandlers,
60
- };
43
+ const { onCompleted, onError } = params;
44
+ const openModalPopUp = useOpenModalPopUp();
45
+
46
+ const [mutateAIChat, mtnValues, mtnHandlers, updateObservers] = useMutation(editAIChatMtn, {
47
+ openModalPopUp,
48
+ onCompleted,
49
+ onError,
50
+ });
51
+
52
+ /*
53
+ * Optimistically write a submitted summary to its fragment and roll it back
54
+ * only when the mutation fails before an authoritative response arrives.
55
+ */
56
+ const editAIChat = useCallback<GraphQLMutationFn>(
57
+ async (graphqlOptions, triedCount) => {
58
+ const aiChatId = graphqlOptions?.variables?.aiChatId;
59
+ const nextSummary = graphqlOptions?.variables?.summary;
60
+
61
+ if (!aiChatId || typeof nextSummary !== 'string') {
62
+ return mutateAIChat(graphqlOptions, triedCount);
63
+ }
64
+
65
+ const fragmentKey = makeFragmentKey(FRAGMENT_NAMES.aiChat, aiChatId);
66
+ const previousFragment = loadFragment(fragmentKey);
67
+ updateFragment(
68
+ fragmentKey,
69
+ {
70
+ summary: nextSummary,
71
+ userManagedSummary: true,
72
+ },
73
+ null,
74
+ false,
75
+ updateObservers,
76
+ );
77
+
78
+ const result = await mutateAIChat(graphqlOptions, triedCount);
79
+
80
+ if (result?.error && previousFragment) {
81
+ updateFragment(
82
+ fragmentKey,
83
+ (currentFragment: any) =>
84
+ currentFragment?.summary === nextSummary
85
+ ? {
86
+ summary: previousFragment.summary,
87
+ userManagedSummary: previousFragment.userManagedSummary,
88
+ }
89
+ : {},
90
+ null,
91
+ false,
92
+ updateObservers,
93
+ );
94
+ }
95
+
96
+ return result;
97
+ },
98
+ [mutateAIChat, updateObservers],
99
+ );
100
+
101
+ return {
102
+ editAIChat,
103
+ ...mtnValues,
104
+ ...mtnHandlers,
105
+ };
61
106
  }
62
107
 
63
108
  /**
@@ -65,75 +110,113 @@ export function useEditAIChat(params: UseMutationParams = {}) {
65
110
  */
66
111
 
67
112
  export function useAIChatTextarea(variablesKey: string, params: UseMutationParams = {}) {
68
-
69
- const { onCompleted, onError } = params;
70
- const didSendRef = useRef(false);
71
- const openModalPopUp = useOpenModalPopUp();
72
-
73
- // Send AI chat message
74
-
75
- const [sendAIChatMessage, mtnValues1,, updateObservers] = useMutation(
76
- sendAIChatMessageMtn,
77
- {
78
- openModalPopUp,
79
- onCompleted: (data: any, err: any, variables: any) => {
80
- didSendRef.current = true;
81
-
82
- onCompleted?.(data, err, variables);
83
-
84
- const aiChatId = variables.aiChatId;
85
- const messageId = data.sendAIChatMessage?.node?.id;
86
-
87
- if (messageId && aiChatId && variablesKey) {
88
- updateQuery(`#aiChat:${variablesKey}`, (currentData: any) => {
89
- if (Array.isArray(currentData.messages?.data)) {
90
- currentData.messages.data.push([`$aiChatMessageFragment:${messageId}`]);
91
- }
92
- return currentData;
93
- }, false, updateObservers);
94
- } else if (data && !err) {
95
- console.dev(`Unknown error: {${messageId ? 'aiChatId' : 'messageId'}} was not found.`, 'warning');
96
- }
97
- },
98
- onError,
99
- },
100
- );
101
-
102
- // Stop AI chat message
103
-
104
- const [stopAIChatMessage, mtnValues2] = useMutation(
105
- stopAIChatMessageMtn,
106
- {
107
- openModalPopUp,
108
- onCompleted: (data: any, err: any, variables: any) => {
109
- onCompleted?.(data, err, variables);
110
- },
111
- onError,
112
- },
113
- );
114
-
115
- // Reset query on unmount if a message was sent;
116
- // This fixes an issue where in-progress messages that are stopped midway remain broken
117
- // as a result of the SSE pipe breaking at unmount.
118
-
119
- useEffect(() => {
120
- return () => {
121
- if (didSendRef.current) {
122
- resetQuery(`#aiChat:${variablesKey}`, true, updateObservers);
123
- }
124
- };
125
- }, []);
126
-
127
- return {
128
- send: {
129
- sendAIChatMessage,
130
- ...mtnValues1,
131
- },
132
- stop: {
133
- stopAIChatMessage,
134
- ...mtnValues2,
135
- }
136
- };
113
+ const { onCompleted, onError } = params;
114
+ const didSendRef = useRef(false);
115
+ const openModalPopUp = useOpenModalPopUp();
116
+
117
+ // Send AI chat message
118
+
119
+ const [mutateAIChatMessage, mtnValues1, sendHandlers, updateObservers] = useMutation(sendAIChatMessageMtn, {
120
+ onCompleted: (data: any, err: any, variables: any) => {
121
+ if (data.sendAIChatMessage?.node?.id) {
122
+ acceptAIChatOutgoingMessage(variables.aiChatId, variables.clientRequestId, data.sendAIChatMessage.node);
123
+ }
124
+
125
+ onCompleted?.(data, err, variables);
126
+
127
+ const aiChatId = variables.aiChatId;
128
+ const messageId = data.sendAIChatMessage?.node?.id;
129
+
130
+ if (messageId && aiChatId && variablesKey) {
131
+ const fragmentKey = makeFragmentKey(FRAGMENT_NAMES.aiChatMessage, messageId);
132
+
133
+ updateQuery(
134
+ `#aiChat:${variablesKey}`,
135
+ (currentData: any) => {
136
+ const currentList = currentData?.messages?.data;
137
+
138
+ // The updater receives the stored references by reference, so the
139
+ // new message must be appended into fresh objects; mutating them
140
+ // in place leaves the version stamp (and the persisted snapshot)
141
+ // unchanged, which drops the sent message on the next page load.
142
+ if (!Array.isArray(currentList) || currentList.some((item: any) => item?.[0] === fragmentKey)) {
143
+ return currentData;
144
+ }
145
+
146
+ return {
147
+ ...currentData,
148
+ messages: {
149
+ ...currentData.messages,
150
+ data: [...currentList, [fragmentKey]],
151
+ },
152
+ };
153
+ },
154
+ false,
155
+ updateObservers,
156
+ );
157
+ } else if (data && !err) {
158
+ console.dev(`Unknown error: {${messageId ? 'aiChatId' : 'messageId'}} was not found.`, 'warning');
159
+ }
160
+ },
161
+ onError: (error, variables) => {
162
+ failAIChatOutgoingMessage(variables?.aiChatId, variables?.clientRequestId, error);
163
+ onError?.(error, variables);
164
+ },
165
+ });
166
+
167
+ /* Mutations can abort without callbacks; preserve those outgoing payloads for retry too. */
168
+ const sendAIChatMessage = useCallback<GraphQLMutationFn>(
169
+ async (options, triedCount) => {
170
+ didSendRef.current = true;
171
+ try {
172
+ const result = await mutateAIChatMessage(options, triedCount);
173
+ if (result?.aborted || (!result?.sendAIChatMessage?.node?.id && !result?.error)) {
174
+ failAIChatOutgoingMessage(options?.variables?.aiChatId, options?.variables?.clientRequestId);
175
+ }
176
+ return result;
177
+ } catch (error) {
178
+ const serverError = normalizeServerError(error);
179
+ sendHandlers.setSaving(false);
180
+ failAIChatOutgoingMessage(options?.variables?.aiChatId, options?.variables?.clientRequestId, serverError);
181
+ return { error: serverError };
182
+ }
183
+ },
184
+ [mutateAIChatMessage],
185
+ );
186
+
187
+ // Stop AI chat message
188
+
189
+ const [stopAIChatMessage, mtnValues2] = useMutation(stopAIChatMessageMtn, {
190
+ openModalPopUp,
191
+ onCompleted: (data: any, err: any, variables: any) => {
192
+ onCompleted?.(data, err, variables);
193
+ },
194
+ onError,
195
+ });
196
+
197
+ // Reset query on unmount if a message was sent;
198
+ // This fixes an issue where in-progress messages that are stopped midway remain broken
199
+ // as a result of the SSE pipe breaking at unmount.
200
+
201
+ useEffect(() => {
202
+ didSendRef.current = false;
203
+ return () => {
204
+ if (didSendRef.current) {
205
+ resetQuery(`#aiChat:${variablesKey}`, true, updateObservers);
206
+ }
207
+ };
208
+ }, [variablesKey]);
209
+
210
+ return {
211
+ send: {
212
+ sendAIChatMessage,
213
+ ...mtnValues1,
214
+ },
215
+ stop: {
216
+ stopAIChatMessage,
217
+ ...mtnValues2,
218
+ },
219
+ };
137
220
  }
138
221
 
139
222
  /**
@@ -141,28 +224,24 @@ export function useAIChatTextarea(variablesKey: string, params: UseMutationParam
141
224
  */
142
225
 
143
226
  export function useDeleteAIChat(params: UseMutationParams = {}) {
144
-
145
- const { onCompleted, onError } = params;
146
- const openModalPopUp = useOpenModalPopUp();
147
-
148
- const [deleteAIChat, mtnValues, mtnHandlers, updateObservers] = useMutation(
149
- deleteAIChatMtn,
150
- {
151
- openModalPopUp,
152
- onCompleted: (data: any, err: any, variables: any) => {
153
- if (data?.deleteAIChat) {
154
- updateFragment(`$aiChatFragment:${variables.aiChatId}`, { __deleted: true }, null, false, updateObservers);
155
- }
156
-
157
- onCompleted?.(data, err, variables);
158
- },
159
- onError,
160
- },
161
- );
162
-
163
- return {
164
- deleteAIChat,
165
- ...mtnValues,
166
- ...mtnHandlers,
167
- };
227
+ const { onCompleted, onError } = params;
228
+ const openModalPopUp = useOpenModalPopUp();
229
+
230
+ const [deleteAIChat, mtnValues, mtnHandlers, updateObservers] = useMutation(deleteAIChatMtn, {
231
+ openModalPopUp,
232
+ onCompleted: (data: any, err: any, variables: any) => {
233
+ if (data?.deleteAIChat) {
234
+ updateFragment(makeFragmentKey(FRAGMENT_NAMES.aiChat, variables.aiChatId), { __deleted: true }, null, false, updateObservers);
235
+ }
236
+
237
+ onCompleted?.(data, err, variables);
238
+ },
239
+ onError,
240
+ });
241
+
242
+ return {
243
+ deleteAIChat,
244
+ ...mtnValues,
245
+ ...mtnHandlers,
246
+ };
168
247
  }
@@ -0,0 +1,63 @@
1
+ import {
2
+ mergeLocalAIChatMessages,
3
+ mergeSSEPayloadToLocalAIChatMessages,
4
+ upsertLocalAIChatMessage,
5
+ } from './use-aiChat-qry.helpers.ts';
6
+
7
+ Deno.test('reconnected chat checkpoints ignore stale revisions without bigint precision loss', () => {
8
+ const latest = {
9
+ id: 'message',
10
+ revision: '9007199254740993',
11
+ text: 'Complete answer',
12
+ finished: true,
13
+ };
14
+ const stale = {
15
+ ...latest,
16
+ revision: '9007199254740992',
17
+ text: 'Complete',
18
+ finished: false,
19
+ };
20
+ const rows = [latest];
21
+ if (upsertLocalAIChatMessage(rows, stale) !== rows)
22
+ throw new Error('Old reconnect must not overwrite completed text');
23
+ const merged = mergeSSEPayloadToLocalAIChatMessages(rows, {
24
+ __type: 'DATA_UPDATE',
25
+ fragmentKey: '$aiChatMessageFragment:message',
26
+ data: stale,
27
+ });
28
+ if (merged[0].text !== latest.text)
29
+ throw new Error('Stale stream update must be ignored');
30
+ const cached = mergeLocalAIChatMessages({ messages: [latest] }, [stale]);
31
+ if (cached.messages.length !== 1 || cached.messages[0].text !== latest.text)
32
+ throw new Error('Stale local draft must not mask fresher database data');
33
+ });
34
+
35
+ Deno.test('replaying a full checkpoint does not duplicate message rows or append its text twice', () => {
36
+ const payload = {
37
+ __type: 'QUERY_APPEND',
38
+ fragmentKey: '#aiChat:chat',
39
+ dataFragmentKey: '$aiChatMessageFragment:message',
40
+ data: { id: 'message', revision: '8', text: 'Hello' },
41
+ } as const;
42
+ const first = mergeSSEPayloadToLocalAIChatMessages([], payload);
43
+ const second = mergeSSEPayloadToLocalAIChatMessages(first, payload);
44
+ if (second.length !== 1 || second[0].text !== 'Hello')
45
+ throw new Error('Full checkpoints must be idempotent');
46
+ });
47
+
48
+ Deno.test('a terminal checkpoint cannot be reopened by an equal-revision streaming snapshot', () => {
49
+ const terminal = {
50
+ id: 'message',
51
+ revision: '12',
52
+ generationStatus: 'INCOMPLETE',
53
+ finished: true,
54
+ };
55
+ const rows = [terminal];
56
+ const streaming = {
57
+ ...terminal,
58
+ generationStatus: 'STREAMING',
59
+ finished: false,
60
+ };
61
+ if (upsertLocalAIChatMessage(rows, streaming) !== rows)
62
+ throw new Error('Terminal checkpoint must win a same-revision tie');
63
+ });