@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,72 @@
1
+ import type { UseMutationParams } from '@jsb188/graphql/types.d';
2
+ import { OpenModalPopUpFn } from '@jsb188/react/states';
3
+ import {
4
+ cancelReminderMtn,
5
+ deleteWorkflowMtn,
6
+ editProgramWorkflowMtn,
7
+ updateReminderMtn,
8
+ } from '../gql/mutations/workflowMutations.ts';
9
+ import { useMutation } from './index.ts';
10
+
11
+ /**
12
+ * Cancel one reminder (deactivates it and stops open runs);
13
+ * cache updates arrive via the server's realtime fragment emit
14
+ */
15
+
16
+ export function useCancelReminder(params: UseMutationParams = {}, openModalPopUp?: OpenModalPopUpFn) {
17
+ const [cancelReminder, mtnValues, mtnHandlers] = useMutation(cancelReminderMtn, {
18
+ openModalPopUp,
19
+ ...params,
20
+ });
21
+
22
+ return {
23
+ cancelReminder,
24
+ ...mtnValues,
25
+ ...mtnHandlers,
26
+ };
27
+ }
28
+
29
+ /**
30
+ * Update one reminder's title/schedule;
31
+ * cache updates arrive via the server's realtime fragment emit
32
+ */
33
+
34
+ export function useUpdateReminder(params: UseMutationParams = {}, openModalPopUp?: OpenModalPopUpFn) {
35
+ const [updateReminder, mtnValues, mtnHandlers] = useMutation(updateReminderMtn, {
36
+ openModalPopUp,
37
+ ...params,
38
+ });
39
+
40
+ return {
41
+ updateReminder,
42
+ ...mtnValues,
43
+ ...mtnHandlers,
44
+ };
45
+ }
46
+
47
+ /**
48
+ * Pause, resume or set the user instructions of one program-managed
49
+ * workflow; the result is the catalog-merged workflow, which updates its
50
+ * cached fragment
51
+ */
52
+
53
+ export function useEditProgramWorkflow(params: UseMutationParams = {}, openModalPopUp?: OpenModalPopUpFn) {
54
+ const [editProgramWorkflow, mtnValues, mtnHandlers] = useMutation(editProgramWorkflowMtn, {
55
+ openModalPopUp,
56
+ ...params,
57
+ });
58
+
59
+ return {
60
+ editProgramWorkflow,
61
+ ...mtnValues,
62
+ ...mtnHandlers,
63
+ };
64
+ }
65
+
66
+ /*
67
+ * Permanently delete an eligible workflow; server events remove it from cached lists.
68
+ */
69
+ export function useDeleteWorkflow(params: UseMutationParams = {}, openModalPopUp?: OpenModalPopUpFn) {
70
+ const [deleteWorkflow, mtnValues, mtnHandlers] = useMutation(deleteWorkflowMtn, { openModalPopUp, ...params });
71
+ return { deleteWorkflow, ...mtnValues, ...mtnHandlers };
72
+ }
@@ -1,62 +1,187 @@
1
- import { useQuery, useReactiveFragment } from '@jsb188/graphql/client';
2
- import { workflowRunsQry, workflowsQry } from '../gql/queries/workflowQueries.ts';
1
+ import { useQuery, useReactiveFragment, useReactiveFragmentMap } from '@jsb188/graphql/client';
2
+ import type { WorkflowRunsFilterGQL, WorkflowsFilterGQL } from '@jsb188/mday/types/workflow.d.ts';
3
+ import { FRAGMENT_NAMES, getFragmentBaseName, makeFragmentKey } from '@jsb188/mday/constants/graphqlReactivity.ts';
4
+ import { useCallback } from 'react';
5
+ import { workflowQry, workflowRunQry, workflowRunsQry, workflowsQry } from '../gql/queries/workflowQueries.ts';
3
6
  import type { PaginationArgs, UseQueryParams } from '../types.d.ts';
4
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
+
5
33
  /**
6
34
  * Constants
7
35
  */
8
36
 
9
- const WORKFLOWS_LIST_LIMIT = 250;
37
+ const WORKFLOW_LISTS_LIMIT = 60;
38
+
39
+ /**
40
+ * Keep workflow list filters aligned with the WorkflowsFilter input shape
41
+ * (route table filters carry extra URL-only keys)
42
+ */
43
+
44
+ function normalizeWorkflowsFilter(filter?: Record<string, any> | null): WorkflowsFilterGQL {
45
+ return {
46
+ activeOnly: filter?.activeOnly === true,
47
+ kind: filter?.kind || null,
48
+ startDate: filter?.startDate || null,
49
+ endDate: filter?.endDate || null,
50
+ };
51
+ }
52
+
53
+ /**
54
+ * Keep run list filters aligned with the WorkflowRunsFilter input shape
55
+ */
56
+
57
+ function normalizeWorkflowRunsFilter(filter?: Record<string, any> | null): WorkflowRunsFilterGQL {
58
+ return {
59
+ workflowId: filter?.workflowId || null,
60
+ kind: filter?.kind || null,
61
+ statuses: filter?.statuses || null,
62
+ startDate: filter?.startDate || null,
63
+ endDate: filter?.endDate || null,
64
+ };
65
+ }
10
66
 
11
67
  /**
12
- * Fetch workflows for an organization
68
+ * Wrap a query's fetchMore so pagination calls re-normalize route filters;
69
+ * the route table rebuilds fetchMore variables from the raw route filter state
70
+ */
71
+
72
+ function useNormalizedFilterFetchMore(
73
+ fetchMore: (options: any) => Promise<any>,
74
+ normalizeFilter: (filter?: Record<string, any> | null) => Record<string, any>,
75
+ ) {
76
+ return useCallback(
77
+ (options: any) => {
78
+ if (!options?.variables?.filter) {
79
+ return fetchMore(options);
80
+ }
81
+
82
+ return fetchMore({
83
+ ...options,
84
+ variables: {
85
+ ...options.variables,
86
+ filter: normalizeFilter(options.variables.filter),
87
+ },
88
+ });
89
+ },
90
+ [fetchMore, normalizeFilter],
91
+ );
92
+ }
93
+
94
+ /**
95
+ * Fetch the merged paginated workflows list (workflows + reminders) for an organization
13
96
  */
14
97
 
15
98
  export function useWorkflows(
16
- variablesOrOrganizationId?: string | null | (PaginationArgs & {
17
- organizationId?: string | null;
18
- }),
19
- params: UseQueryParams = {},
99
+ variables: PaginationArgs & {
100
+ organizationId?: string | null;
101
+ filter?: WorkflowsFilterGQL | Record<string, any> | null;
102
+ sort?: string | null;
103
+ },
104
+ params: UseQueryParams = {},
105
+ ) {
106
+ const { data, fetchMore, ...rest } = useQuery(workflowsQry, {
107
+ ...params,
108
+ variables: {
109
+ ...variables,
110
+ filter: normalizeWorkflowsFilter(variables.filter),
111
+ cursor: null,
112
+ after: true,
113
+ limit: variables.limit ?? WORKFLOW_LISTS_LIMIT,
114
+ },
115
+ skip: !variables.organizationId || params.skip,
116
+ });
117
+
118
+ const fetchMoreWorkflows = useNormalizedFilterFetchMore(fetchMore, normalizeWorkflowsFilter);
119
+
120
+ return {
121
+ workflows: data?.workflows,
122
+ fetchMore: fetchMoreWorkflows,
123
+ ...rest,
124
+ };
125
+ }
126
+
127
+ /**
128
+ * Fetch the paginated runs list for an organization,
129
+ * optionally scoped to one workflow via filter.workflowId
130
+ */
131
+
132
+ export function useWorkflowRuns(
133
+ variables: PaginationArgs & {
134
+ organizationId?: string | null;
135
+ filter?: WorkflowRunsFilterGQL | Record<string, any> | null;
136
+ sort?: string | null;
137
+ },
138
+ params: UseQueryParams = {},
20
139
  ) {
21
- const usesPaginationVariables = typeof variablesOrOrganizationId === 'object' && variablesOrOrganizationId !== null;
22
- const variables = usesPaginationVariables
23
- ? variablesOrOrganizationId
24
- : { organizationId: variablesOrOrganizationId };
25
-
26
- const { data, ...rest } = useQuery(workflowsQry, {
27
- variables: usesPaginationVariables ? {
28
- ...variables,
29
- cursor: null,
30
- after: true,
31
- limit: WORKFLOWS_LIST_LIMIT,
32
- } : variables,
33
- skip: !variables.organizationId,
34
- ...params,
35
- });
36
-
37
- return {
38
- workflows: data?.workflows,
39
- ...rest
40
- };
140
+ const { data, fetchMore, ...rest } = useQuery(workflowRunsQry, {
141
+ ...params,
142
+ variables: {
143
+ ...variables,
144
+ filter: normalizeWorkflowRunsFilter(variables.filter),
145
+ cursor: null,
146
+ after: true,
147
+ limit: variables.limit ?? WORKFLOW_LISTS_LIMIT,
148
+ },
149
+ skip: !variables.organizationId || params.skip,
150
+ });
151
+
152
+ const fetchMoreWorkflowRuns = useNormalizedFilterFetchMore(fetchMore, normalizeWorkflowRunsFilter);
153
+
154
+ return {
155
+ workflowRuns: data?.workflowRuns,
156
+ fetchMore: fetchMoreWorkflowRuns,
157
+ ...rest,
158
+ };
41
159
  }
42
160
 
43
161
  /**
44
- * Fetch runs for a workflow
162
+ * Fetch one workflow run (for the run detail modal), merged with live fragment updates
45
163
  */
46
164
 
47
- export function useWorkflowRuns(workflowId?: string | null, params: UseQueryParams = {}) {
48
- const { data, ...rest } = useQuery(workflowRunsQry, {
49
- variables: {
50
- workflowId,
51
- },
52
- skip: !workflowId,
53
- ...params,
54
- });
55
-
56
- return {
57
- workflowRuns: data?.workflowRuns,
58
- ...rest
59
- };
165
+ export function useWorkflowRun(
166
+ variables: {
167
+ organizationId?: string | null;
168
+ workflowRunId?: string | null;
169
+ },
170
+ params: UseQueryParams = {},
171
+ ) {
172
+ const { data, ...rest } = useQuery(workflowRunQry, {
173
+ ...params,
174
+ variables,
175
+ skip: !variables.organizationId || !variables.workflowRunId || params.skip,
176
+ });
177
+
178
+ // Always query; the cached list fragment does not carry the nested workflow
179
+ const reactiveWorkflowRun = useReactiveWorkflowRunFragment(variables.workflowRunId || '', data?.workflowRun ?? null);
180
+
181
+ return {
182
+ workflowRun: reactiveWorkflowRun || data?.workflowRun,
183
+ ...rest,
184
+ };
60
185
  }
61
186
 
62
187
  /**
@@ -64,9 +189,21 @@ export function useWorkflowRuns(workflowId?: string | null, params: UseQueryPara
64
189
  */
65
190
 
66
191
  export function useReactiveWorkflowFragment(workflowId: string, currentData?: any, queryCount?: number) {
67
- return useReactiveFragment(
68
- currentData,
69
- [`$workflowFragment:${workflowId}`],
70
- queryCount,
71
- );
192
+ return useReactiveFragment(currentData, [makeFragmentKey(FRAGMENT_NAMES.workflow, workflowId)], queryCount);
193
+ }
194
+
195
+ /**
196
+ * Get reactive workflow run fragment for a single run
197
+ */
198
+
199
+ export function useReactiveWorkflowRunFragment(workflowRunId: string, currentData?: any, queryCount?: number) {
200
+ return useReactiveFragment(currentData, [makeFragmentKey(FRAGMENT_NAMES.workflowRun, workflowRunId)], queryCount);
201
+ }
202
+
203
+ /**
204
+ * Get reactive workflow run fragments for a list of runs (run history)
205
+ */
206
+
207
+ export function useReactiveWorkflowRunFragmentMap(workflowRuns?: any[] | null) {
208
+ return useReactiveFragmentMap(workflowRuns || null, getFragmentBaseName(FRAGMENT_NAMES.workflowRun));
72
209
  }
@@ -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
+ }
@@ -0,0 +1,150 @@
1
+ import type { AIChatSubmissionWSObj } from '@jsb188/app/types/app.d.ts';
2
+
3
+ interface AIChatSubmissionState {
4
+ acceptReceived: boolean;
5
+ clientRequestId: string;
6
+ generationActive: boolean;
7
+ listeners: Set<(waitingForGeneration: boolean) => void>;
8
+ serverReceived: boolean;
9
+ }
10
+
11
+ const AI_CHAT_SUBMISSION_STATES = new Map<string, AIChatSubmissionState>();
12
+
13
+ /*
14
+ * Return whether one chat should render its transient server-received placeholder.
15
+ */
16
+ function isWaitingForAIChatGeneration(state: AIChatSubmissionState) {
17
+ return (
18
+ state.acceptReceived && state.serverReceived && !state.generationActive
19
+ );
20
+ }
21
+
22
+ /*
23
+ * Notify every mounted observer when one chat's transient submission phase changes.
24
+ */
25
+ function notifyAIChatSubmissionState(state: AIChatSubmissionState) {
26
+ const waitingForGeneration = isWaitingForAIChatGeneration(state);
27
+ state.listeners.forEach((listener) => {
28
+ listener(waitingForGeneration);
29
+ });
30
+ }
31
+
32
+ /*
33
+ * Register the request identity that the requester tab expects the server to acknowledge.
34
+ */
35
+ export function registerAIChatSubmission(
36
+ aiChatId: string,
37
+ clientRequestId: string,
38
+ ) {
39
+ const previousState = AI_CHAT_SUBMISSION_STATES.get(aiChatId);
40
+ const state: AIChatSubmissionState = {
41
+ acceptReceived: true,
42
+ clientRequestId,
43
+ generationActive: previousState?.generationActive || false,
44
+ listeners: previousState?.listeners || new Set(),
45
+ serverReceived: false,
46
+ };
47
+ AI_CHAT_SUBMISSION_STATES.set(aiChatId, state);
48
+ notifyAIChatSubmissionState(state);
49
+ }
50
+
51
+ /*
52
+ * Apply one server acknowledgement only when it matches the current request in this tab.
53
+ */
54
+ export function receiveAIChatSubmission(update: AIChatSubmissionWSObj) {
55
+ const state = AI_CHAT_SUBMISSION_STATES.get(update.aiChatId);
56
+ if (
57
+ !state ||
58
+ state.clientRequestId !== update.clientRequestId ||
59
+ update.phase !== 'RECEIVED'
60
+ ) {
61
+ return;
62
+ }
63
+ if (state.generationActive) {
64
+ state.acceptReceived = false;
65
+ state.serverReceived = false;
66
+ notifyAIChatSubmissionState(state);
67
+ return;
68
+ }
69
+
70
+ state.serverReceived = true;
71
+ notifyAIChatSubmissionState(state);
72
+ }
73
+
74
+ /*
75
+ * Supersede the transient server acknowledgement before exposing real generation state.
76
+ */
77
+ export function startAIChatGeneration(aiChatId: string) {
78
+ const state = AI_CHAT_SUBMISSION_STATES.get(aiChatId);
79
+ if (!state) {
80
+ return;
81
+ }
82
+
83
+ state.acceptReceived = false;
84
+ state.generationActive = true;
85
+ state.serverReceived = false;
86
+ notifyAIChatSubmissionState(state);
87
+ }
88
+
89
+ /*
90
+ * Record that real generation ended without allowing an older acknowledgement to reappear.
91
+ */
92
+ export function finishAIChatGeneration(aiChatId: string) {
93
+ const state = AI_CHAT_SUBMISSION_STATES.get(aiChatId);
94
+ if (!state) {
95
+ return;
96
+ }
97
+
98
+ state.generationActive = false;
99
+ notifyAIChatSubmissionState(state);
100
+ }
101
+
102
+ /*
103
+ * Clear one failed or abandoned submission while retaining mounted chat observers.
104
+ */
105
+ export function clearAIChatSubmission(
106
+ aiChatId: string,
107
+ clientRequestId?: string | null,
108
+ ) {
109
+ const state = AI_CHAT_SUBMISSION_STATES.get(aiChatId);
110
+ if (
111
+ !state ||
112
+ (clientRequestId && state.clientRequestId !== clientRequestId)
113
+ ) {
114
+ return;
115
+ }
116
+
117
+ state.acceptReceived = false;
118
+ state.serverReceived = false;
119
+ notifyAIChatSubmissionState(state);
120
+ }
121
+
122
+ /*
123
+ * Observe the requester-tab loading phase for one mounted AI chat.
124
+ */
125
+ export function subscribeToAIChatSubmission(
126
+ aiChatId: string,
127
+ listener: (waitingForGeneration: boolean) => void,
128
+ ) {
129
+ let state = AI_CHAT_SUBMISSION_STATES.get(aiChatId);
130
+ if (!state) {
131
+ state = {
132
+ acceptReceived: false,
133
+ clientRequestId: '',
134
+ generationActive: false,
135
+ listeners: new Set(),
136
+ serverReceived: false,
137
+ };
138
+ AI_CHAT_SUBMISSION_STATES.set(aiChatId, state);
139
+ }
140
+
141
+ state.listeners.add(listener);
142
+ listener(isWaitingForAIChatGeneration(state));
143
+
144
+ return () => {
145
+ state.listeners.delete(listener);
146
+ if (!state.listeners.size) {
147
+ AI_CHAT_SUBMISSION_STATES.delete(aiChatId);
148
+ }
149
+ };
150
+ }