@jsb188/graphql 1.1.11 → 1.1.13

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 (174) hide show
  1. package/LICENSE +21 -0
  2. package/audience.d.ts +205 -0
  3. package/cache/config.ts +65 -28
  4. package/cache/index.helpers.ts +96 -0
  5. package/cache/index.ts +364 -808
  6. package/cache/mounted-queries.ts +33 -0
  7. package/cache/optimistic-ui-runtime.ts +46 -0
  8. package/cache/optimistic-ui.ts +401 -0
  9. package/cache/persist.ts +107 -22
  10. package/cache/realtime-fence.ts +47 -0
  11. package/cache/realtime-live.ts +17 -0
  12. package/cache/store.ts +22 -64
  13. package/cache/value.helpers.ts +17 -0
  14. package/{drafts/store.ts → client/draft-persistence-indexed-db.ts} +19 -3
  15. package/{drafts/index.ts → client/draft-persistence.ts} +13 -39
  16. package/client/index.ts +4 -2
  17. package/client/request.helpers.ts +14 -0
  18. package/client/request.ts +122 -232
  19. package/client/storage-asset.ts +58 -0
  20. package/gql/fragments/accountAuthFragments.ts +0 -4
  21. package/gql/fragments/agentMemoryFragments.ts +5 -1
  22. package/gql/fragments/agentNoteFragments.ts +156 -0
  23. package/gql/fragments/aiChatFragments.ts +35 -11
  24. package/gql/fragments/aiChatLinkFragments.ts +8 -0
  25. package/gql/fragments/audienceFragments.ts +76 -0
  26. package/gql/fragments/dataTableFragments.ts +48 -80
  27. package/gql/fragments/emailFragments.ts +49 -21
  28. package/gql/fragments/emailOutreachFragments.ts +281 -0
  29. package/gql/fragments/fieldDocFragments.ts +222 -40
  30. package/gql/fragments/inboundContactFragments.ts +2 -0
  31. package/gql/fragments/libraryFragments.ts +120 -0
  32. package/gql/fragments/logFragments.ts +93 -2
  33. package/gql/fragments/organizationFragments.ts +12 -0
  34. package/gql/fragments/qrCodeFragments.ts +29 -0
  35. package/gql/fragments/scheduleFragments.ts +574 -145
  36. package/gql/fragments/sheetFragments.ts +86 -424
  37. package/gql/fragments/storageFragments.ts +25 -1
  38. package/gql/fragments/workWaitFragments.ts +13 -0
  39. package/gql/fragments/workflowFragments.ts +32 -4
  40. package/gql/mutations/agentMemoryMutations.ts +32 -0
  41. package/gql/mutations/agentNoteMutations.ts +64 -0
  42. package/gql/mutations/aiChatLinkMutations.ts +13 -0
  43. package/gql/mutations/aiChatMutations.ts +34 -4
  44. package/gql/mutations/audienceMutations.ts +58 -0
  45. package/gql/mutations/authMutations.ts +24 -28
  46. package/gql/mutations/billingMutations.ts +24 -0
  47. package/gql/mutations/contactMutations.ts +23 -0
  48. package/gql/mutations/dataTableMutations.ts +18 -75
  49. package/gql/mutations/emailMutations.ts +22 -0
  50. package/gql/mutations/emailOutreachMutations.ts +139 -0
  51. package/gql/mutations/fieldDocMutations.ts +162 -13
  52. package/gql/mutations/index.ts +10 -5
  53. package/gql/mutations/organizationMutations.ts +6 -0
  54. package/gql/mutations/qrCodeMutations.ts +20 -0
  55. package/gql/mutations/scheduleMutations.ts +389 -417
  56. package/gql/mutations/sheetMutations.ts +62 -118
  57. package/gql/mutations/storageMutations.ts +1 -1
  58. package/gql/mutations/workflowMutations.ts +94 -0
  59. package/gql/queries/agentMemoryQueries.ts +12 -2
  60. package/gql/queries/agentNoteQueries.ts +86 -0
  61. package/gql/queries/aiChatQueries.ts +63 -12
  62. package/gql/queries/audienceQueries.ts +104 -0
  63. package/gql/queries/authQueries.ts +20 -4
  64. package/gql/queries/billingQueries.ts +114 -9
  65. package/gql/queries/dataTableQueries.ts +43 -75
  66. package/gql/queries/emailOutreachQueries.ts +282 -0
  67. package/gql/queries/emailQueries.ts +48 -64
  68. package/gql/queries/emailReplyReportQueries.ts +127 -0
  69. package/gql/queries/fieldDocQueries.ts +128 -98
  70. package/gql/queries/inboundContactQueries.ts +15 -4
  71. package/gql/queries/index.ts +5 -3
  72. package/gql/queries/libraryQueries.ts +112 -0
  73. package/gql/queries/logQueries.ts +86 -12
  74. package/gql/queries/organizationQueries.ts +44 -12
  75. package/gql/queries/qrCodeQueries.ts +27 -0
  76. package/gql/queries/scheduleQueries.ts +401 -278
  77. package/gql/queries/sheetQueries.ts +94 -165
  78. package/gql/queries/storageQueries.ts +11 -4
  79. package/gql/queries/workflowQueries.ts +61 -12
  80. package/gql/reactivity.ts +98 -0
  81. package/gql/recordReads.ts +171 -0
  82. package/hooks/index.helpers.ts +52 -0
  83. package/hooks/index.ts +920 -715
  84. package/hooks/use-agentMemory-mtn.ts +29 -31
  85. package/hooks/use-agentMemory-qry.ts +15 -3
  86. package/hooks/use-agentNote-mtn.ts +89 -0
  87. package/hooks/use-agentNote-qry.ts +162 -0
  88. package/hooks/use-agentNote-recovery.helpers.ts +58 -0
  89. package/hooks/use-agentNote-recovery.ts +57 -0
  90. package/hooks/use-aiChat-mtn.ts +104 -115
  91. package/hooks/use-aiChat-qry.helpers.ts +124 -0
  92. package/hooks/use-aiChat-qry.ts +254 -387
  93. package/hooks/use-aiChat-stream-mtn.ts +14 -0
  94. package/hooks/use-audience-mtn.ts +170 -0
  95. package/hooks/use-audience-qry.helpers.ts +39 -0
  96. package/hooks/use-audience-qry.ts +245 -0
  97. package/hooks/use-auth-mtn.ts +30 -1
  98. package/hooks/use-billing-mtn.ts +31 -0
  99. package/hooks/use-billing-qry.ts +76 -0
  100. package/hooks/use-dataTable-mtn.ts +23 -115
  101. package/hooks/use-dataTable-qry.ts +69 -914
  102. package/hooks/use-email-mtn.ts +26 -0
  103. package/hooks/use-email-qry.helpers.ts +37 -0
  104. package/hooks/use-email-qry.ts +44 -174
  105. package/hooks/use-emailOutreach-mtn.ts +211 -0
  106. package/hooks/use-emailOutreach-qry.helpers.ts +25 -0
  107. package/hooks/use-emailOutreach-qry.ts +367 -0
  108. package/hooks/use-emailOutreachReplyReport-qry.ts +46 -0
  109. package/hooks/use-fieldDoc-mtn.ts +244 -32
  110. package/hooks/use-fieldDoc-qry.helpers.ts +49 -0
  111. package/hooks/use-fieldDoc-qry.ts +134 -102
  112. package/hooks/use-inboundContact-qry.ts +7 -9
  113. package/hooks/use-library-qry.ts +233 -0
  114. package/hooks/use-log-mtn.ts +25 -12
  115. package/hooks/use-log-qry.ts +99 -46
  116. package/hooks/use-organization-qry.ts +16 -60
  117. package/hooks/use-qrCode-mtn.ts +40 -0
  118. package/hooks/use-qrCode-qry.ts +78 -0
  119. package/hooks/use-schedule-mtn.ts +231 -348
  120. package/hooks/use-schedule-qry.ts +208 -139
  121. package/hooks/use-schedule-reactive.ts +218 -0
  122. package/hooks/use-sheet-mtn.ts +91 -199
  123. package/hooks/use-sheet-qry.ts +88 -237
  124. package/hooks/use-storage-qry.ts +84 -61
  125. package/hooks/use-workflow-mtn.ts +84 -23
  126. package/hooks/use-workflow-qry.ts +60 -61
  127. package/libs/ai-chat-link-events.ts +78 -0
  128. package/libs/ai-chat-outgoing.helpers.ts +153 -0
  129. package/libs/ai-chat-outgoing.ts +11 -0
  130. package/libs/ai-chat-outgoing.types.ts +25 -0
  131. package/libs/ai-chat-run-realtime.ts +20 -0
  132. package/libs/ai-chat-submission-realtime.ts +150 -0
  133. package/libs/data-changes.helpers.ts +161 -0
  134. package/libs/data-changes.ts +382 -0
  135. package/libs/fragment-realtime-sequence.ts +55 -0
  136. package/libs/open-sheet.ts +138 -0
  137. package/libs/record-read.ts +327 -0
  138. package/libs/sheet-command-batch.ts +45 -0
  139. package/libs/sheet-realtime-packet.ts +53 -0
  140. package/libs/sheet-view-realtime-router.ts +99 -0
  141. package/loaders/emailPreference.ts +69 -0
  142. package/loaders/rest.ts +12 -0
  143. package/package.json +77 -25
  144. package/schedule.d.ts +1183 -0
  145. package/sse.helpers.ts +19 -0
  146. package/sse.ts +26 -115
  147. package/types.d.ts +48 -25
  148. package/cache/index.test.ts +0 -881
  149. package/client/data-table-realtime-subscriptions.test.ts +0 -740
  150. package/client/data-table-realtime-subscriptions.ts +0 -955
  151. package/client/data-table-realtime.test.ts +0 -792
  152. package/client/data-table-realtime.ts +0 -1218
  153. package/client/fragment-realtime-sequence.ts +0 -52
  154. package/client/open-sheet.ts +0 -137
  155. package/client/request-managed-session.test.ts +0 -574
  156. package/client/request-no-store.test.ts +0 -157
  157. package/client/sse-ticket.test.ts +0 -26
  158. package/deno.lock +0 -170
  159. package/deno.test.json +0 -10
  160. package/gql/fragments/agentDocFragments.ts +0 -46
  161. package/gql/fragments/billingFragments.ts +0 -14
  162. package/gql/fragments/campaignFragments.ts +0 -277
  163. package/gql/mutations/agentDocMutations.ts +0 -177
  164. package/gql/mutations/campaignMutations.ts +0 -215
  165. package/gql/queries/agentDocQueries.ts +0 -120
  166. package/gql/queries/appQueries.ts +0 -14
  167. package/gql/queries/campaignQueries.ts +0 -127
  168. package/hooks/use-agentDoc-mtn.ts +0 -285
  169. package/hooks/use-agentDoc-qry.ts +0 -208
  170. package/hooks/use-app-qry.ts +0 -22
  171. package/hooks/use-campaign-mtn.ts +0 -377
  172. package/hooks/use-campaign-qry.ts +0 -257
  173. package/loaders/campaign.ts +0 -137
  174. package/tsconfig.json +0 -13
@@ -1,7 +1,13 @@
1
1
  import type { UseMutationParams } from '@jsb188/graphql/types.d';
2
- import { OpenModalPopUpFn } from '@jsb188/react/states';
2
+ import type { OpenModalPopUpFn } from '@jsb188/react/states';
3
3
  import {
4
4
  cancelReminderMtn,
5
+ deleteWorkflowMtn,
6
+ discardWorkflowDraftMtn,
7
+ editProgramWorkflowMtn,
8
+ publishWorkflowMtn,
9
+ removeWorkflowAddedBehaviorMtn,
10
+ setWorkflowActiveMtn,
5
11
  updateReminderMtn,
6
12
  } from '../gql/mutations/workflowMutations.ts';
7
13
  import { useMutation } from './index.ts';
@@ -11,17 +17,11 @@ import { useMutation } from './index.ts';
11
17
  * cache updates arrive via the server's realtime fragment emit
12
18
  */
13
19
 
14
- export function useCancelReminder(
15
- params: UseMutationParams = {},
16
- openModalPopUp?: OpenModalPopUpFn,
17
- ) {
18
- const [cancelReminder, mtnValues, mtnHandlers] = useMutation(
19
- cancelReminderMtn,
20
- {
21
- openModalPopUp,
22
- ...params,
23
- },
24
- );
20
+ export function useCancelReminder(params: UseMutationParams = {}, openModalPopUp?: OpenModalPopUpFn) {
21
+ const [cancelReminder, mtnValues, mtnHandlers] = useMutation(cancelReminderMtn, {
22
+ openModalPopUp,
23
+ ...params,
24
+ });
25
25
 
26
26
  return {
27
27
  cancelReminder,
@@ -35,17 +35,11 @@ export function useCancelReminder(
35
35
  * cache updates arrive via the server's realtime fragment emit
36
36
  */
37
37
 
38
- export function useUpdateReminder(
39
- params: UseMutationParams = {},
40
- openModalPopUp?: OpenModalPopUpFn,
41
- ) {
42
- const [updateReminder, mtnValues, mtnHandlers] = useMutation(
43
- updateReminderMtn,
44
- {
45
- openModalPopUp,
46
- ...params,
47
- },
48
- );
38
+ export function useUpdateReminder(params: UseMutationParams = {}, openModalPopUp?: OpenModalPopUpFn) {
39
+ const [updateReminder, mtnValues, mtnHandlers] = useMutation(updateReminderMtn, {
40
+ openModalPopUp,
41
+ ...params,
42
+ });
49
43
 
50
44
  return {
51
45
  updateReminder,
@@ -53,3 +47,70 @@ export function useUpdateReminder(
53
47
  ...mtnHandlers,
54
48
  };
55
49
  }
50
+
51
+ /**
52
+ * Pause, resume or set the user instructions of one program-managed
53
+ * workflow; the result is the catalog-merged workflow, which updates its
54
+ * cached fragment
55
+ */
56
+
57
+ export function useEditProgramWorkflow(params: UseMutationParams = {}, openModalPopUp?: OpenModalPopUpFn) {
58
+ const [editProgramWorkflow, mtnValues, mtnHandlers] = useMutation(editProgramWorkflowMtn, {
59
+ openModalPopUp,
60
+ ...params,
61
+ });
62
+
63
+ return {
64
+ editProgramWorkflow,
65
+ ...mtnValues,
66
+ ...mtnHandlers,
67
+ };
68
+ }
69
+
70
+ /*
71
+ * Permanently delete an eligible workflow; server events remove it from cached lists.
72
+ */
73
+ export function useDeleteWorkflow(params: UseMutationParams = {}, openModalPopUp?: OpenModalPopUpFn) {
74
+ const [deleteWorkflow, mtnValues, mtnHandlers] = useMutation(deleteWorkflowMtn, { openModalPopUp, ...params });
75
+ return { deleteWorkflow, ...mtnValues, ...mtnHandlers };
76
+ }
77
+
78
+ /*
79
+ * Make the draft at the given revision the live version and switch the workflow on; the returned workflow updates its
80
+ * cached fragment. A stale revision fails with the revision conflict error and leaves the cached (newer) draft as it is.
81
+ */
82
+ export function usePublishWorkflow(params: UseMutationParams = {}, openModalPopUp?: OpenModalPopUpFn) {
83
+ const [publishWorkflow, mtnValues, mtnHandlers] = useMutation(publishWorkflowMtn, { openModalPopUp, ...params });
84
+ return { publishWorkflow, ...mtnValues, ...mtnHandlers };
85
+ }
86
+
87
+ /*
88
+ * Pause or resume a log workflow that has a live version, or a form's workflow; the returned workflow updates its
89
+ * cached fragment.
90
+ */
91
+ export function useSetWorkflowActive(params: UseMutationParams = {}, openModalPopUp?: OpenModalPopUpFn) {
92
+ const [setWorkflowActive, mtnValues, mtnHandlers] = useMutation(setWorkflowActiveMtn, { openModalPopUp, ...params });
93
+ return { setWorkflowActive, ...mtnValues, ...mtnHandlers };
94
+ }
95
+
96
+ /*
97
+ * Delete a workflow's draft; the returned workflow updates its cached fragment. The result is null when a log workflow
98
+ * was never published and was deleted with its draft: the server's deleted change then marks the cached record
99
+ * __deleted, as for deleteWorkflow.
100
+ */
101
+ export function useDiscardWorkflowDraft(params: UseMutationParams = {}, openModalPopUp?: OpenModalPopUpFn) {
102
+ const [discardWorkflowDraft, mtnValues, mtnHandlers] = useMutation(discardWorkflowDraftMtn, { openModalPopUp, ...params });
103
+ return { discardWorkflowDraft, ...mtnValues, ...mtnHandlers };
104
+ }
105
+
106
+ /*
107
+ * Remove what the organization added to a form's workflow, so the form goes back to only filling; the returned
108
+ * workflow updates its cached fragment.
109
+ */
110
+ export function useRemoveWorkflowAddedBehavior(params: UseMutationParams = {}, openModalPopUp?: OpenModalPopUpFn) {
111
+ const [removeWorkflowAddedBehavior, mtnValues, mtnHandlers] = useMutation(removeWorkflowAddedBehaviorMtn, {
112
+ openModalPopUp,
113
+ ...params,
114
+ });
115
+ return { removeWorkflowAddedBehavior, ...mtnValues, ...mtnHandlers };
116
+ }
@@ -1,25 +1,35 @@
1
- import {
2
- useQuery,
3
- useReactiveFragment,
4
- useReactiveFragmentMap,
5
- } from '@jsb188/graphql/client';
6
- import type {
7
- WorkflowRunsFilterGQL,
8
- WorkflowsFilterGQL,
9
- } from '@jsb188/mday/types/workflow.d.ts';
10
- import {
11
- FRAGMENT_NAMES,
12
- getFragmentBaseName,
13
- makeFragmentKey,
14
- } from '@jsb188/mday/constants/graphqlReactivity.ts';
1
+ import { useQuery, useReactiveFragment, useReactiveFragmentMap } from '@jsb188/graphql/client';
2
+ import { FRAGMENT_NAMES, getFragmentBaseName, makeFragmentKey } from '@jsb188/mday/constants/graphqlReactivity.ts';
3
+ import type { WorkflowRunsFilterGQL, WorkflowsFilterGQL } from '@jsb188/mday/types/workflow.d.ts';
15
4
  import { useCallback } from 'react';
16
- import {
17
- workflowRunQry,
18
- workflowRunsQry,
19
- workflowsQry,
20
- } from '../gql/queries/workflowQueries.ts';
5
+ import { fieldDocWorkflowQry, workflowQry, workflowRunQry, workflowRunsQry, workflowsQry } from '../gql/queries/workflowQueries.ts';
21
6
  import type { PaginationArgs, UseQueryParams } from '../types.d.ts';
22
7
 
8
+ /*
9
+ * Reuse the requested reactive workflow from cache and only query when it is absent.
10
+ */
11
+ export function useWorkflow(workflowId: string, params: UseQueryParams = {}) {
12
+ // Read the reactive fragment first; it already loads and observes the workflow in cache.
13
+ // A separate loadFragment() call would duplicate that cache lookup.
14
+ const observedWorkflow = useReactiveWorkflowFragment(workflowId);
15
+ // The observer can retain the previous workflow until its effect runs after an ID change.
16
+ // Only the requested workflow may satisfy this read or prevent its query from running.
17
+ const reactiveWorkflow = observedWorkflow?.id === workflowId ? observedWorkflow : null;
18
+ // Always call the query hook to preserve hook order, but skip its automatic request when
19
+ // the requested workflow is cached, its ID is absent, or the caller explicitly skips.
20
+ const { data, ...rest } = useQuery(workflowQry, {
21
+ ...params,
22
+ variables: { workflowId },
23
+ skip: !!reactiveWorkflow || !workflowId || params.skip,
24
+ });
25
+
26
+ return {
27
+ // Prefer the reactive cache; otherwise use a matching query result while the cache observer catches up.
28
+ workflow: reactiveWorkflow || (data?.workflow?.id === workflowId ? data.workflow : null),
29
+ ...rest,
30
+ };
31
+ }
32
+
23
33
  /**
24
34
  * Constants
25
35
  */
@@ -31,11 +41,11 @@ const WORKFLOW_LISTS_LIMIT = 60;
31
41
  * (route table filters carry extra URL-only keys)
32
42
  */
33
43
 
34
- function normalizeWorkflowsFilter(
35
- filter?: Record<string, any> | null,
36
- ): WorkflowsFilterGQL {
44
+ function normalizeWorkflowsFilter(filter?: Record<string, any> | null): WorkflowsFilterGQL {
37
45
  return {
46
+ activeOnly: filter?.activeOnly === true,
38
47
  kind: filter?.kind || null,
48
+ fieldDocId: filter?.fieldDocId || null,
39
49
  startDate: filter?.startDate || null,
40
50
  endDate: filter?.endDate || null,
41
51
  };
@@ -45,9 +55,7 @@ function normalizeWorkflowsFilter(
45
55
  * Keep run list filters aligned with the WorkflowRunsFilter input shape
46
56
  */
47
57
 
48
- function normalizeWorkflowRunsFilter(
49
- filter?: Record<string, any> | null,
50
- ): WorkflowRunsFilterGQL {
58
+ function normalizeWorkflowRunsFilter(filter?: Record<string, any> | null): WorkflowRunsFilterGQL {
51
59
  return {
52
60
  workflowId: filter?.workflowId || null,
53
61
  kind: filter?.kind || null,
@@ -108,10 +116,7 @@ export function useWorkflows(
108
116
  skip: !variables.organizationId || params.skip,
109
117
  });
110
118
 
111
- const fetchMoreWorkflows = useNormalizedFilterFetchMore(
112
- fetchMore,
113
- normalizeWorkflowsFilter,
114
- );
119
+ const fetchMoreWorkflows = useNormalizedFilterFetchMore(fetchMore, normalizeWorkflowsFilter);
115
120
 
116
121
  return {
117
122
  workflows: data?.workflows,
@@ -120,6 +125,25 @@ export function useWorkflows(
120
125
  };
121
126
  }
122
127
 
128
+ /*
129
+ * Fetch the workflow of one form (null while the form has none yet); a live query that refetches by itself.
130
+ */
131
+ export function useFieldDocWorkflow(
132
+ variables: { organizationId?: string | null; fieldDocId?: string | null },
133
+ params: UseQueryParams = {},
134
+ ) {
135
+ const { data, ...rest } = useQuery(fieldDocWorkflowQry, {
136
+ ...params,
137
+ variables,
138
+ skip: !variables.organizationId || !variables.fieldDocId || params.skip,
139
+ });
140
+
141
+ return {
142
+ workflow: data?.fieldDocWorkflow?.[0] || null,
143
+ ...rest,
144
+ };
145
+ }
146
+
123
147
  /**
124
148
  * Fetch the paginated runs list for an organization,
125
149
  * optionally scoped to one workflow via filter.workflowId
@@ -145,10 +169,7 @@ export function useWorkflowRuns(
145
169
  skip: !variables.organizationId || params.skip,
146
170
  });
147
171
 
148
- const fetchMoreWorkflowRuns = useNormalizedFilterFetchMore(
149
- fetchMore,
150
- normalizeWorkflowRunsFilter,
151
- );
172
+ const fetchMoreWorkflowRuns = useNormalizedFilterFetchMore(fetchMore, normalizeWorkflowRunsFilter);
152
173
 
153
174
  return {
154
175
  workflowRuns: data?.workflowRuns,
@@ -175,10 +196,7 @@ export function useWorkflowRun(
175
196
  });
176
197
 
177
198
  // Always query; the cached list fragment does not carry the nested workflow
178
- const reactiveWorkflowRun = useReactiveWorkflowRunFragment(
179
- variables.workflowRunId || '',
180
- data?.workflowRun ?? null,
181
- );
199
+ const reactiveWorkflowRun = useReactiveWorkflowRunFragment(variables.workflowRunId || '', data?.workflowRun ?? null);
182
200
 
183
201
  return {
184
202
  workflowRun: reactiveWorkflowRun || data?.workflowRun,
@@ -190,32 +208,16 @@ export function useWorkflowRun(
190
208
  * Get reactive workflow fragment
191
209
  */
192
210
 
193
- export function useReactiveWorkflowFragment(
194
- workflowId: string,
195
- currentData?: any,
196
- queryCount?: number,
197
- ) {
198
- return useReactiveFragment(
199
- currentData,
200
- [makeFragmentKey(FRAGMENT_NAMES.workflow, workflowId)],
201
- queryCount,
202
- );
211
+ export function useReactiveWorkflowFragment(workflowId: string, currentData?: any, queryCount?: number) {
212
+ return useReactiveFragment(currentData, [makeFragmentKey(FRAGMENT_NAMES.workflow, workflowId)], queryCount);
203
213
  }
204
214
 
205
215
  /**
206
216
  * Get reactive workflow run fragment for a single run
207
217
  */
208
218
 
209
- export function useReactiveWorkflowRunFragment(
210
- workflowRunId: string,
211
- currentData?: any,
212
- queryCount?: number,
213
- ) {
214
- return useReactiveFragment(
215
- currentData,
216
- [makeFragmentKey(FRAGMENT_NAMES.workflowRun, workflowRunId)],
217
- queryCount,
218
- );
219
+ export function useReactiveWorkflowRunFragment(workflowRunId: string, currentData?: any, queryCount?: number) {
220
+ return useReactiveFragment(currentData, [makeFragmentKey(FRAGMENT_NAMES.workflowRun, workflowRunId)], queryCount);
219
221
  }
220
222
 
221
223
  /**
@@ -223,8 +225,5 @@ export function useReactiveWorkflowRunFragment(
223
225
  */
224
226
 
225
227
  export function useReactiveWorkflowRunFragmentMap(workflowRuns?: any[] | null) {
226
- return useReactiveFragmentMap(
227
- workflowRuns || null,
228
- getFragmentBaseName(FRAGMENT_NAMES.workflowRun),
229
- );
228
+ return useReactiveFragmentMap(workflowRuns || null, getFragmentBaseName(FRAGMENT_NAMES.workflowRun));
230
229
  }
@@ -0,0 +1,78 @@
1
+ import type { AIChatLinkEvent } from '@jsb188/mday/types/linkedEntity.d.ts';
2
+ import { LINKED_ENTITY_TYPES } from '@jsb188/mday/constants/linkedEntity.ts';
3
+ import { useCallback, useSyncExternalStore } from 'react';
4
+
5
+ const FILE_CONSTANTS = {
6
+ events: new Map<string, readonly AIChatLinkEvent[]>(),
7
+ listeners: new Map<string, Set<() => void>>(),
8
+ empty: Object.freeze([]) as readonly AIChatLinkEvent[],
9
+ maxEvents: 200,
10
+ maxChats: 100,
11
+ };
12
+
13
+ /* Read immutable UI hints without using them as the persisted chat item list. */
14
+ export function getAIChatLinkEvents(aiChatId?: string | null) {
15
+ return (aiChatId && FILE_CONSTANTS.events.get(aiChatId)) || FILE_CONSTANTS.empty;
16
+ }
17
+
18
+ /* Subscribe only to the mounted web chat; absent IDs create no subscription. */
19
+ export function subscribeToAIChatLinkEvents(aiChatId: string | null | undefined, listener: () => void) {
20
+ if (!aiChatId) return () => {};
21
+ const listeners = FILE_CONSTANTS.listeners.get(aiChatId) || new Set<() => void>();
22
+ FILE_CONSTANTS.listeners.set(aiChatId, listeners);
23
+ listeners.add(listener);
24
+ return () => {
25
+ listeners.delete(listener);
26
+ if (!listeners.size) FILE_CONSTANTS.listeners.delete(aiChatId);
27
+ };
28
+ }
29
+
30
+ /* Accept each tool effect once and bound tab-local hint retention across visited chats. */
31
+ export function publishAIChatLinkEvent(event: AIChatLinkEvent) {
32
+ if (
33
+ !event ||
34
+ ![event.aiChatId, event.runId, event.callId, event.aiChatLinkId, event.entityId].every(
35
+ (value) => typeof value === 'string' && value.length > 0,
36
+ ) ||
37
+ !LINKED_ENTITY_TYPES.includes(event.entityType) ||
38
+ !['CREATED', 'UPDATED', 'DELETED'].includes(event.action) ||
39
+ (event.organizationId !== null && typeof event.organizationId !== 'string') ||
40
+ (event.sheetTabId != null && typeof event.sheetTabId !== 'string') ||
41
+ (event.titleHint != null && typeof event.titleHint !== 'string') ||
42
+ typeof event.at !== 'string' ||
43
+ !Number.isFinite(Date.parse(event.at))
44
+ )
45
+ return;
46
+ const previous = getAIChatLinkEvents(event.aiChatId);
47
+ if (
48
+ previous.some(
49
+ (item) =>
50
+ item.runId === event.runId &&
51
+ item.callId === event.callId &&
52
+ item.entityType === event.entityType &&
53
+ item.entityId === event.entityId &&
54
+ item.action === event.action,
55
+ )
56
+ )
57
+ return;
58
+ FILE_CONSTANTS.events.delete(event.aiChatId);
59
+ FILE_CONSTANTS.events.set(event.aiChatId, [...previous.slice(1 - FILE_CONSTANTS.maxEvents), Object.freeze({ ...event })]);
60
+ for (const aiChatId of FILE_CONSTANTS.events.keys()) {
61
+ if (FILE_CONSTANTS.events.size <= FILE_CONSTANTS.maxChats) break;
62
+ if (aiChatId !== event.aiChatId && !FILE_CONSTANTS.listeners.has(aiChatId)) FILE_CONSTANTS.events.delete(aiChatId);
63
+ }
64
+ FILE_CONSTANTS.listeners.get(event.aiChatId)?.forEach((listener) => listener());
65
+ }
66
+
67
+ /* Clear private event hints with the authenticated cache, including subscribed snapshots. */
68
+ export function clearAIChatLinkEvents() {
69
+ FILE_CONSTANTS.events.clear();
70
+ FILE_CONSTANTS.listeners.forEach((listeners) => listeners.forEach((listener) => listener()));
71
+ }
72
+
73
+ /* Observe live UI hints independently from the durable query and its fragment observers. */
74
+ export function useAIChatLinkEvents(aiChatId?: string | null) {
75
+ const subscribe = useCallback((listener: () => void) => subscribeToAIChatLinkEvents(aiChatId, listener), [aiChatId]);
76
+ const getSnapshot = useCallback(() => getAIChatLinkEvents(aiChatId), [aiChatId]);
77
+ return useSyncExternalStore(subscribe, getSnapshot, getAIChatLinkEvents);
78
+ }
@@ -0,0 +1,153 @@
1
+ import type { ServerErrorObj } from '@jsb188/app/types/app.d.ts';
2
+ import { releaseObjectUrl, retainObjectUrl } from '@jsb188/app/utils/url_client.ts';
3
+ import { getOptimisticAIChatMessageAttachments, type OptimisticAIChatAttachmentInput } from '@jsb188/mday/utils/storage.ts';
4
+ import { clearAIChatSubmission, registerAIChatSubmission } from './ai-chat-submission-realtime.ts';
5
+ import type { AIChatOutgoingMessage, AIChatSendVariables } from './ai-chat-outgoing.types.ts';
6
+
7
+ export type { AIChatOutgoingMessage } from './ai-chat-outgoing.types.ts';
8
+
9
+ const OUTGOING = {
10
+ messages: new Map<string, AIChatOutgoingMessage[]>(),
11
+ listeners: new Map<string, Set<() => void>>(),
12
+ empty: [] as AIChatOutgoingMessage[],
13
+ };
14
+
15
+ /* Publish immutable snapshots independently of the composer's mount lifetime. */
16
+ function publishOutgoingMessages(aiChatId: string, messages: AIChatOutgoingMessage[]) {
17
+ if (messages.length) OUTGOING.messages.set(aiChatId, messages);
18
+ else OUTGOING.messages.delete(aiChatId);
19
+ OUTGOING.listeners.get(aiChatId)?.forEach((listener) => {
20
+ listener();
21
+ });
22
+ }
23
+
24
+ /* Read pending messages without inventing server cache entries or pagination IDs. */
25
+ export function getAIChatOutgoingMessages(aiChatId?: string) {
26
+ return (aiChatId && OUTGOING.messages.get(aiChatId)) || OUTGOING.empty;
27
+ }
28
+
29
+ /* Observe tab-local sends; unmounting a thread does not discard an unfinished send. */
30
+ export function subscribeToAIChatOutgoingMessages(aiChatId: string | undefined, listener: () => void) {
31
+ if (!aiChatId) return () => {};
32
+ const listeners = OUTGOING.listeners.get(aiChatId) || new Set();
33
+ OUTGOING.listeners.set(aiChatId, listeners);
34
+ listeners.add(listener);
35
+ return () => {
36
+ listeners.delete(listener);
37
+ if (!listeners.size) OUTGOING.listeners.delete(aiChatId);
38
+ };
39
+ }
40
+
41
+ /* Snapshot one existing-chat submission and retain its previews before clearing the editor. */
42
+ export function beginAIChatOutgoingMessage(p: {
43
+ aiChatId: string;
44
+ accountId: string;
45
+ variables: AIChatSendVariables;
46
+ attachments: OptimisticAIChatAttachmentInput[];
47
+ qrCodes?: AIChatOutgoingMessage['qrCodes'];
48
+ }) {
49
+ const messages = getAIChatOutgoingMessages(p.aiChatId);
50
+ if (messages.some((message) => message.deliveryStatus === 'SENDING')) return false;
51
+ const variables = structuredClone(p.variables);
52
+ const at = new Date().toISOString();
53
+ const previewUrls = p.attachments.flatMap((attachment) => (attachment.previewUrl ? [attachment.previewUrl] : []));
54
+ previewUrls.forEach(retainObjectUrl);
55
+ const message: AIChatOutgoingMessage = {
56
+ id: `pending:${variables.clientRequestId}`,
57
+ clientRequestId: variables.clientRequestId,
58
+ accountId: p.accountId,
59
+ type: 'MESSAGE',
60
+ text: variables.text?.trim() || '',
61
+ at,
62
+ cursor: null,
63
+ finished: true,
64
+ attachments: getOptimisticAIChatMessageAttachments(p.attachments, at),
65
+ qrCodes: p.qrCodes ? structuredClone(p.qrCodes) : undefined,
66
+ deliveryStatus: 'SENDING',
67
+ variables,
68
+ previewUrls,
69
+ };
70
+ registerAIChatSubmission(p.aiChatId, variables.clientRequestId);
71
+ publishOutgoingMessages(p.aiChatId, [...messages, message]);
72
+ return true;
73
+ }
74
+
75
+ /* Replay the original immutable payload, preserving the server's idempotency key. */
76
+ export function retryAIChatOutgoingMessage(aiChatId: string, clientRequestId: string) {
77
+ const messages = getAIChatOutgoingMessages(aiChatId);
78
+ const message = messages.find((item) => item.clientRequestId === clientRequestId);
79
+ if (message?.deliveryStatus !== 'FAILED' || messages.some((item) => item.deliveryStatus === 'SENDING')) return null;
80
+ registerAIChatSubmission(aiChatId, clientRequestId);
81
+ publishOutgoingMessages(
82
+ aiChatId,
83
+ messages.map((item) => (item === message ? { ...item, deliveryStatus: 'SENDING', error: null } : item)),
84
+ );
85
+ return structuredClone(message.variables);
86
+ }
87
+
88
+ /* Keep a recoverable row on failure without overwriting anything typed into the next draft. */
89
+ export function failAIChatOutgoingMessage(aiChatId: string, clientRequestId: string, error?: ServerErrorObj | null) {
90
+ const messages = getAIChatOutgoingMessages(aiChatId);
91
+ const message = messages.find((item) => item.clientRequestId === clientRequestId);
92
+ if (!message || message.deliveryStatus === 'ACCEPTED') return;
93
+ clearAIChatSubmission(aiChatId, clientRequestId);
94
+ publishOutgoingMessages(
95
+ aiChatId,
96
+ messages.map((item) => (item === message ? { ...item, deliveryStatus: 'FAILED', error } : item)),
97
+ );
98
+ }
99
+
100
+ /* Remove pending opacity only after the server returns canonical message data. */
101
+ export function acceptAIChatOutgoingMessage(aiChatId: string, clientRequestId: string, canonicalMessage: any) {
102
+ const messages = getAIChatOutgoingMessages(aiChatId);
103
+ const message = messages.find((item) => item.clientRequestId === clientRequestId);
104
+ if (!message || !canonicalMessage?.id) return;
105
+ publishOutgoingMessages(
106
+ aiChatId,
107
+ messages.map((item) =>
108
+ item === message
109
+ ? {
110
+ ...item,
111
+ ...canonicalMessage,
112
+ clientRequestId,
113
+ deliveryStatus: 'ACCEPTED',
114
+ error: null,
115
+ }
116
+ : item,
117
+ ),
118
+ );
119
+ }
120
+
121
+ /* Release one locally retained payload after canonical handoff or explicit dismissal. */
122
+ export function dismissAIChatOutgoingMessage(aiChatId: string, clientRequestId: string) {
123
+ const messages = getAIChatOutgoingMessages(aiChatId);
124
+ const message = messages.find((item) => item.clientRequestId === clientRequestId);
125
+ if (!message) return;
126
+ clearAIChatSubmission(aiChatId, clientRequestId);
127
+ message.previewUrls.forEach(releaseObjectUrl);
128
+ publishOutgoingMessages(
129
+ aiChatId,
130
+ messages.filter((item) => item !== message),
131
+ );
132
+ }
133
+
134
+ /* Retire only submissions whose canonical rows have entered the thread's latest message data. */
135
+ export function reconcileAIChatOutgoingMessages(aiChatId: string, messages: { id: string; clientRequestId?: string | null }[]) {
136
+ const ids = new Set(messages.map((message) => message.id));
137
+ const requestIds = new Set(messages.map((message) => message.clientRequestId).filter(Boolean));
138
+ for (const message of getAIChatOutgoingMessages(aiChatId)) {
139
+ if (ids.has(message.id) || requestIds.has(message.clientRequestId))
140
+ dismissAIChatOutgoingMessage(aiChatId, message.clientRequestId);
141
+ }
142
+ }
143
+
144
+ /* Clear private outgoing content and local preview holds when the app clears its authenticated cache. */
145
+ export function clearAIChatOutgoingMessages() {
146
+ for (const [aiChatId, messages] of OUTGOING.messages) {
147
+ clearAIChatSubmission(aiChatId);
148
+ messages.forEach((message) => {
149
+ message.previewUrls.forEach(releaseObjectUrl);
150
+ });
151
+ publishOutgoingMessages(aiChatId, []);
152
+ }
153
+ }
@@ -0,0 +1,11 @@
1
+ import { useCallback, useSyncExternalStore } from 'react';
2
+ import { getAIChatOutgoingMessages, subscribeToAIChatOutgoingMessages } from './ai-chat-outgoing.helpers.ts';
3
+
4
+ export * from './ai-chat-outgoing.helpers.ts';
5
+
6
+ /* Subscribe to one existing chat's outgoing rows using immutable store snapshots. */
7
+ export function useAIChatOutgoingMessages(aiChatId?: string) {
8
+ const subscribe = useCallback((listener: () => void) => subscribeToAIChatOutgoingMessages(aiChatId, listener), [aiChatId]);
9
+ const getSnapshot = useCallback(() => getAIChatOutgoingMessages(aiChatId), [aiChatId]);
10
+ return useSyncExternalStore(subscribe, getSnapshot, getAIChatOutgoingMessages);
11
+ }
@@ -0,0 +1,25 @@
1
+ import type { QrCodeJSONValue } from '@jsb188/mday/types/qrCode.d.ts';
2
+ import type { ServerErrorObj } from '@jsb188/app/types/app.d.ts';
3
+ import type { getOptimisticAIChatMessageAttachments } from '@jsb188/mday/utils/storage.ts';
4
+
5
+ export interface AIChatSendVariables extends Record<string, any> {
6
+ aiChatId: string;
7
+ clientRequestId: string;
8
+ }
9
+
10
+ export interface AIChatOutgoingMessage {
11
+ qrCodes?: Record<string, QrCodeJSONValue>[];
12
+ id: string;
13
+ clientRequestId: string;
14
+ accountId: string;
15
+ type: 'MESSAGE';
16
+ text: string;
17
+ at: string;
18
+ cursor: string | null;
19
+ finished: boolean;
20
+ attachments: ReturnType<typeof getOptimisticAIChatMessageAttachments>;
21
+ deliveryStatus: 'SENDING' | 'FAILED' | 'ACCEPTED';
22
+ variables: AIChatSendVariables;
23
+ error?: ServerErrorObj | null;
24
+ previewUrls: string[];
25
+ }
@@ -0,0 +1,20 @@
1
+ import type { AIChatRunData } from '@jsb188/app/types/ai.d.ts';
2
+ import { FRAGMENT_NAMES, makeFragmentKey } from '@jsb188/mday/constants/graphqlReactivity.ts';
3
+ import { mergeAIChatRuns } from '@jsb188/mday/utils/aiChatWork.ts';
4
+ import { addFragmentToCache, loadFragment, updateFragment } from '../cache/index.ts';
5
+ import type { UpdateObserversFn } from '../types.d.ts';
6
+
7
+ /*
8
+ * Persist authoritative timing and source associations so returning to a cached
9
+ * chat cannot restart its timer. Older stream snapshots cannot reopen a run.
10
+ */
11
+ export function cacheAIChatRunUpdate(run: AIChatRunData, updateObservers: UpdateObserversFn) {
12
+ const runKey = makeFragmentKey(FRAGMENT_NAMES.aiChatRun, run.id);
13
+ const previousRun = loadFragment(runKey);
14
+ const canonicalRun = mergeAIChatRuns(previousRun ? { [run.id]: previousRun } : {}, [run])[run.id];
15
+ if (!updateFragment(runKey, canonicalRun, null, false, updateObservers)) addFragmentToCache(runKey, canonicalRun);
16
+ for (const sourceId of canonicalRun.sourceMessageIds) {
17
+ updateFragment(makeFragmentKey(FRAGMENT_NAMES.aiChatMessage, sourceId), { run: canonicalRun }, null, false, updateObservers);
18
+ }
19
+ return canonicalRun;
20
+ }