@jsb188/graphql 1.1.11 → 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 (165) hide show
  1. package/audience.d.ts +343 -0
  2. package/cache/config.ts +58 -24
  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 +370 -42
  8. package/cache/index.ts +326 -799
  9. package/cache/optimistic-ui-runtime.ts +46 -0
  10. package/cache/optimistic-ui.ts +401 -0
  11. package/cache/persist.ts +98 -19
  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} +5 -2
  16. package/client/index.ts +3 -2
  17. package/client/request.helpers.ts +14 -0
  18. package/client/request.ts +130 -215
  19. package/deno.lock +17 -0
  20. package/deno.test.json +2 -0
  21. package/gql/fragments/agentMemoryFragments.ts +5 -1
  22. package/gql/fragments/agentNoteFragments.ts +150 -0
  23. package/gql/fragments/aiChatFragments.ts +36 -10
  24. package/gql/fragments/audienceFragments.ts +141 -0
  25. package/gql/fragments/campaignFragments.ts +415 -126
  26. package/gql/fragments/dataTableFragments.ts +48 -80
  27. package/gql/fragments/emailFragments.ts +28 -23
  28. package/gql/fragments/fieldDocFragments.ts +222 -40
  29. package/gql/fragments/inboundContactFragments.ts +2 -0
  30. package/gql/fragments/logFragments.ts +93 -2
  31. package/gql/fragments/organizationFragments.ts +10 -0
  32. package/gql/fragments/qrCodeFragments.ts +29 -0
  33. package/gql/fragments/scheduleFragments.ts +652 -140
  34. package/gql/fragments/sheetFragments.ts +84 -373
  35. package/gql/fragments/storageFragments.ts +25 -1
  36. package/gql/fragments/workflowFragments.ts +13 -1
  37. package/gql/mutations/agentMemoryMutations.ts +32 -0
  38. package/gql/mutations/agentNoteMutations.ts +62 -0
  39. package/gql/mutations/aiChatMutations.ts +36 -4
  40. package/gql/mutations/audienceMutations.ts +71 -0
  41. package/gql/mutations/authMutations.ts +45 -1
  42. package/gql/mutations/billingMutations.ts +24 -0
  43. package/gql/mutations/campaignMutations.ts +170 -127
  44. package/gql/mutations/contactMutations.ts +23 -0
  45. package/gql/mutations/dataTableMutations.ts +18 -75
  46. package/gql/mutations/fieldDocMutations.ts +162 -13
  47. package/gql/mutations/index.ts +8 -5
  48. package/gql/mutations/organizationMutations.ts +6 -0
  49. package/gql/mutations/qrCodeMutations.ts +20 -0
  50. package/gql/mutations/scheduleMutations.ts +1052 -354
  51. package/gql/mutations/sheetMutations.ts +62 -118
  52. package/gql/mutations/storageMutations.ts +0 -1
  53. package/gql/mutations/workflowMutations.ts +18 -0
  54. package/gql/queries/agentMemoryQueries.ts +6 -0
  55. package/gql/queries/agentNoteQueries.ts +89 -0
  56. package/gql/queries/aiChatQueries.ts +56 -4
  57. package/gql/queries/audienceQueries.ts +128 -0
  58. package/gql/queries/authQueries.ts +6 -0
  59. package/gql/queries/billingQueries.ts +95 -6
  60. package/gql/queries/campaignQueries.ts +132 -23
  61. package/gql/queries/dataTableQueries.ts +24 -65
  62. package/gql/queries/emailQueries.ts +18 -61
  63. package/gql/queries/emailReplyReportQueries.ts +76 -0
  64. package/gql/queries/fieldDocQueries.ts +100 -92
  65. package/gql/queries/inboundContactQueries.ts +4 -0
  66. package/gql/queries/index.ts +3 -1
  67. package/gql/queries/logQueries.ts +62 -7
  68. package/gql/queries/organizationQueries.ts +13 -0
  69. package/gql/queries/qrCodeQueries.ts +20 -0
  70. package/gql/queries/scheduleQueries.ts +633 -257
  71. package/gql/queries/sheetQueries.ts +59 -152
  72. package/gql/queries/workflowQueries.ts +10 -4
  73. package/hooks/index.helpers.test.ts +50 -0
  74. package/hooks/index.helpers.ts +52 -0
  75. package/hooks/index.ts +863 -685
  76. package/hooks/use-agentMemory-mtn.ts +29 -31
  77. package/hooks/use-agentMemory-qry.ts +15 -3
  78. package/hooks/use-agentNote-mtn.ts +82 -0
  79. package/hooks/use-agentNote-qry.ts +190 -0
  80. package/hooks/use-agentNote-recovery.helpers.test.ts +68 -0
  81. package/hooks/use-agentNote-recovery.helpers.ts +58 -0
  82. package/hooks/use-agentNote-recovery.ts +72 -0
  83. package/hooks/use-aiChat-mtn.ts +96 -112
  84. package/hooks/use-aiChat-qry.helpers.test.ts +63 -0
  85. package/hooks/use-aiChat-qry.helpers.ts +124 -0
  86. package/hooks/use-aiChat-qry.ts +229 -383
  87. package/hooks/use-aiChat-stream-mtn.ts +14 -0
  88. package/hooks/use-audience-mtn.ts +194 -0
  89. package/hooks/use-audience-qry.helpers.test.ts +80 -0
  90. package/hooks/use-audience-qry.helpers.ts +63 -0
  91. package/hooks/use-audience-qry.ts +330 -0
  92. package/hooks/use-auth-mtn.ts +30 -1
  93. package/hooks/use-billing-mtn.ts +31 -0
  94. package/hooks/use-billing-qry.ts +76 -0
  95. package/hooks/use-campaign-generation-recovery.ts +53 -0
  96. package/hooks/use-campaign-mtn.ts +224 -165
  97. package/hooks/use-campaign-qry.helpers.ts +40 -0
  98. package/hooks/use-campaign-qry.ts +631 -54
  99. package/hooks/use-dataTable-mtn.ts +23 -115
  100. package/hooks/use-dataTable-qry.ts +66 -916
  101. package/hooks/use-email-qry.helpers.ts +37 -0
  102. package/hooks/use-email-qry.ts +33 -178
  103. package/hooks/use-emailCampaignReplyReport-qry.ts +27 -0
  104. package/hooks/use-fieldDoc-mtn.ts +244 -32
  105. package/hooks/use-fieldDoc-qry.helpers.test.ts +65 -0
  106. package/hooks/use-fieldDoc-qry.helpers.ts +49 -0
  107. package/hooks/use-fieldDoc-qry.ts +134 -102
  108. package/hooks/use-inboundContact-qry.ts +7 -9
  109. package/hooks/use-log-mtn.ts +25 -12
  110. package/hooks/use-log-qry.ts +99 -46
  111. package/hooks/use-organization-qry.ts +16 -60
  112. package/hooks/use-publicFormEmail-mtn.ts +27 -0
  113. package/hooks/use-qrCode-mtn.ts +40 -0
  114. package/hooks/use-qrCode-qry.ts +78 -0
  115. package/hooks/use-schedule-mtn.ts +506 -333
  116. package/hooks/use-schedule-qry.ts +682 -101
  117. package/hooks/use-schedule-reactive.ts +486 -0
  118. package/hooks/use-sheet-mtn.ts +91 -199
  119. package/hooks/use-sheet-qry.ts +84 -238
  120. package/hooks/use-storage-qry.ts +84 -61
  121. package/hooks/use-workflow-mtn.ts +39 -22
  122. package/hooks/use-workflow-qry.ts +40 -61
  123. package/libs/ai-chat-outgoing.helpers.ts +153 -0
  124. package/libs/ai-chat-outgoing.ts +11 -0
  125. package/libs/ai-chat-outgoing.types.ts +25 -0
  126. package/libs/ai-chat-run-realtime.ts +20 -0
  127. package/libs/ai-chat-submission-realtime.ts +150 -0
  128. package/libs/fragment-realtime-sequence.ts +55 -0
  129. package/libs/fragment-recovery.test.ts +326 -0
  130. package/libs/fragment-recovery.ts +325 -0
  131. package/libs/open-sheet.ts +138 -0
  132. package/libs/orchestrator-realtime.helpers.test.ts +229 -0
  133. package/libs/orchestrator-realtime.helpers.ts +317 -0
  134. package/libs/orchestrator-realtime.ts +433 -0
  135. package/libs/request-cache-regression.test.ts +122 -0
  136. package/{client → libs}/request-managed-session.test.ts +1 -1
  137. package/libs/request-no-store.test.ts +419 -0
  138. package/libs/sheet-command-batch.ts +44 -0
  139. package/libs/sheet-view-realtime-router.test.ts +214 -0
  140. package/libs/sheet-view-realtime-router.ts +99 -0
  141. package/loaders/campaign.test.ts +186 -0
  142. package/loaders/campaign.ts +56 -83
  143. package/loaders/emailPreference.ts +75 -0
  144. package/loaders/rest.ts +12 -0
  145. package/package.json +42 -17
  146. package/schedule.d.ts +1790 -0
  147. package/sse.helpers.ts +19 -0
  148. package/sse.ts +26 -115
  149. package/tests/agent-note-detail-cache.test.ts +120 -0
  150. package/tests/agent-note-search.test.ts +444 -0
  151. package/types.d.ts +46 -25
  152. package/client/data-table-realtime-subscriptions.test.ts +0 -740
  153. package/client/data-table-realtime-subscriptions.ts +0 -955
  154. package/client/data-table-realtime.test.ts +0 -792
  155. package/client/data-table-realtime.ts +0 -1218
  156. package/client/fragment-realtime-sequence.ts +0 -52
  157. package/client/open-sheet.ts +0 -137
  158. package/client/request-no-store.test.ts +0 -157
  159. package/gql/fragments/agentDocFragments.ts +0 -46
  160. package/gql/fragments/billingFragments.ts +0 -14
  161. package/gql/mutations/agentDocMutations.ts +0 -177
  162. package/gql/queries/agentDocQueries.ts +0 -120
  163. package/hooks/use-agentDoc-mtn.ts +0 -285
  164. package/hooks/use-agentDoc-qry.ts +0 -208
  165. /package/{client → libs}/sse-ticket.test.ts +0 -0
@@ -1,11 +1,21 @@
1
1
  import type { UseMutationParams } from '@jsb188/graphql/types.d';
2
2
  import type { OpenModalPopUpFn } from '@jsb188/react/states';
3
- import {
4
- deleteAgentMemoryMtn,
5
- editAgentMemoryMtn,
6
- } from '../gql/mutations/agentMemoryMutations.ts';
3
+ import { createAgentMemoryMtn, deleteAgentMemoryMtn, editAgentMemoryMtn } from '../gql/mutations/agentMemoryMutations.ts';
7
4
  import { useMutation } from './index.ts';
8
5
 
6
+ /*
7
+ * Add an explicitly authored memory for an authorized organization, member, or contact.
8
+ */
9
+ export function useCreateAgentMemory(params: UseMutationParams = {}, openModalPopUp?: OpenModalPopUpFn) {
10
+ const { onCompleted, ...rest } = params;
11
+ const [createAgentMemory, values, handlers] = useMutation(createAgentMemoryMtn, {
12
+ openModalPopUp,
13
+ onCompleted: (data, error, variables) => onCompleted?.(data?.createAgentMemory, error, variables),
14
+ ...rest,
15
+ });
16
+ return { createAgentMemory, ...values, ...handlers };
17
+ }
18
+
9
19
  /**
10
20
  * Edit one agent memory: its wording, its permanent flag, or its status.
11
21
  *
@@ -14,24 +24,18 @@ import { useMutation } from './index.ts';
14
24
  * makes rather than something the assistant can do to itself.
15
25
  */
16
26
 
17
- export function useEditAgentMemory(
18
- params: UseMutationParams = {},
19
- openModalPopUp?: OpenModalPopUpFn,
20
- ) {
27
+ export function useEditAgentMemory(params: UseMutationParams = {}, openModalPopUp?: OpenModalPopUpFn) {
21
28
  const { onCompleted, ...rest } = params;
22
29
 
23
- const [editAgentMemory, mtnValues, mtnHandlers] = useMutation(
24
- editAgentMemoryMtn,
25
- {
26
- openModalPopUp,
27
- onCompleted: (data, error, variables) => {
28
- const updatedAgentMemory = data?.editAgentMemory;
30
+ const [editAgentMemory, mtnValues, mtnHandlers] = useMutation(editAgentMemoryMtn, {
31
+ openModalPopUp,
32
+ onCompleted: (data, error, variables) => {
33
+ const updatedAgentMemory = data?.editAgentMemory;
29
34
 
30
- onCompleted?.(updatedAgentMemory, error, variables);
31
- },
32
- ...rest,
35
+ onCompleted?.(updatedAgentMemory, error, variables);
33
36
  },
34
- );
37
+ ...rest,
38
+ });
35
39
 
36
40
  return {
37
41
  editAgentMemory,
@@ -48,22 +52,16 @@ export function useEditAgentMemory(
48
52
  * existed.
49
53
  */
50
54
 
51
- export function useDeleteAgentMemory(
52
- params: UseMutationParams = {},
53
- openModalPopUp?: OpenModalPopUpFn,
54
- ) {
55
+ export function useDeleteAgentMemory(params: UseMutationParams = {}, openModalPopUp?: OpenModalPopUpFn) {
55
56
  const { onCompleted, ...rest } = params;
56
57
 
57
- const [deleteAgentMemory, mtnValues, mtnHandlers] = useMutation(
58
- deleteAgentMemoryMtn,
59
- {
60
- openModalPopUp,
61
- onCompleted: (data, error, variables) => {
62
- onCompleted?.(data?.deleteAgentMemory, error, variables);
63
- },
64
- ...rest,
58
+ const [deleteAgentMemory, mtnValues, mtnHandlers] = useMutation(deleteAgentMemoryMtn, {
59
+ openModalPopUp,
60
+ onCompleted: (data, error, variables) => {
61
+ onCompleted?.(data?.deleteAgentMemory, error, variables);
65
62
  },
66
- );
63
+ ...rest,
64
+ });
67
65
 
68
66
  return {
69
67
  deleteAgentMemory,
@@ -2,9 +2,12 @@ import { useQuery } from './index.ts';
2
2
  import type {
3
3
  AgentMemoryScopeEnum,
4
4
  AgentMemoryStatusEnum,
5
+ AgentMemorySurfaceEnum,
6
+ AgentMemoryGQL,
5
7
  } from '@jsb188/mday/types/agentMemory.d.ts';
6
8
  import { agentMemoriesQry } from '../gql/queries/agentMemoryQueries.ts';
7
9
  import type { UseQueryParams } from '../types.d.ts';
10
+ import { useReactiveFragmentMap } from '../client/index.ts';
8
11
 
9
12
  /**
10
13
  * Constants
@@ -15,15 +18,17 @@ const AGENT_MEMORIES_LIMIT = 200;
15
18
  /**
16
19
  * Fetch the assistant's memories for one organization.
17
20
  *
18
- * ACCOUNT-scope rows are filtered to the signed-in viewer by the server; that
19
- * scope is memory belonging to one person, so this list can never show a
20
- * colleague's private rows regardless of what is requested here.
21
+ * Organization managers may inspect current members' organization-scoped
22
+ * ACCOUNT rows; other viewers receive only their own ACCOUNT memory.
21
23
  */
22
24
 
23
25
  export function useAgentMemories(
24
26
  variables: {
25
27
  organizationId?: string | null;
26
28
  scope?: AgentMemoryScopeEnum | null;
29
+ accountId?: string | null;
30
+ inboundContactId?: string | null;
31
+ surface?: AgentMemorySurfaceEnum | null;
27
32
  status?: AgentMemoryStatusEnum | null;
28
33
  },
29
34
  params: UseQueryParams = {},
@@ -42,3 +47,10 @@ export function useAgentMemories(
42
47
  ...rest,
43
48
  };
44
49
  }
50
+
51
+ /*
52
+ * Observe memory changes using the same fragment identity emitted by the server.
53
+ */
54
+ export function useReactiveAgentMemories(memories?: AgentMemoryGQL[] | null) {
55
+ return useReactiveFragmentMap(memories || null, 'agentMemoryFragment');
56
+ }
@@ -0,0 +1,82 @@
1
+ import type { UseMutationParams, UseMutationParamsExtra } from '@jsb188/graphql/types.d';
2
+ import type { OpenModalPopUpFn } from '@jsb188/react/states';
3
+ import { useEffect, useRef } from 'react';
4
+ import {
5
+ deleteAgentNoteMtn,
6
+ markAgentNoteReadMtn,
7
+ refreshAgentNoteMtn,
8
+ updateAgentNoteMtn,
9
+ } from '../gql/mutations/agentNoteMutations.ts';
10
+ import { useMutation } from './index.ts';
11
+
12
+ /*
13
+ * Expose read marking for views whose explicit open action outlives detail mounts.
14
+ */
15
+ export function useMarkAgentNoteReadMutation() {
16
+ const [markAgentNoteRead] = useMutation(markAgentNoteReadMtn);
17
+ return { markAgentNoteRead };
18
+ }
19
+
20
+ /*
21
+ * Stamp that a person opened one agent note, once per mounted (organization,
22
+ * note) pair. The realtime refetches of an open note never stamp a read, so a
23
+ * page left open does not keep the note from being archived. Best-effort:
24
+ * errors are ignored.
25
+ */
26
+ export function useMarkAgentNoteRead(variables: { organizationId?: string | null; agentNoteId?: string | null }, skip = false) {
27
+ const { markAgentNoteRead } = useMarkAgentNoteReadMutation();
28
+ const markRef = useRef(markAgentNoteRead);
29
+ markRef.current = markAgentNoteRead;
30
+ const { organizationId, agentNoteId } = variables;
31
+
32
+ useEffect(() => {
33
+ if (skip || !organizationId || !agentNoteId) {
34
+ return;
35
+ }
36
+ void markRef.current({ variables: { organizationId, agentNoteId } }).catch(() => {
37
+ // The read stamp is best-effort; the note itself still loads
38
+ });
39
+ }, [skip, organizationId, agentNoteId]);
40
+ }
41
+
42
+ /*
43
+ * Explicitly update flat pin/archive and source automatic-creation arguments. Restoration checks freshness;
44
+ * server events publish the accepted state and list membership.
45
+ */
46
+ export function useUpdateAgentNote(params: UseMutationParamsExtra = {}, openModalPopUp?: OpenModalPopUpFn) {
47
+ const { onCompleted, ...rest } = params;
48
+ const [updateAgentNote, values, handlers] = useMutation(updateAgentNoteMtn, {
49
+ openModalPopUp,
50
+ onCompleted: (data, error, variables) => onCompleted?.(data?.updateAgentNote, error, variables),
51
+ ...rest,
52
+ });
53
+ return { updateAgentNote, ...values, ...handlers };
54
+ }
55
+
56
+ /*
57
+ * Refresh the shared fragment cache with the latest saved note, even when no
58
+ * job is queued. Server events deliver any subsequent background refresh.
59
+ */
60
+ export function useRefreshAgentNote(params: UseMutationParams = {}, openModalPopUp?: OpenModalPopUpFn) {
61
+ const { onCompleted, ...rest } = params;
62
+ const [refreshAgentNote, values, handlers] = useMutation(refreshAgentNoteMtn, {
63
+ openModalPopUp,
64
+ onCompleted: (data, error, variables) => onCompleted?.(data?.refreshAgentNote, error, variables),
65
+ ...rest,
66
+ });
67
+ return { refreshAgentNote, ...values, ...handlers };
68
+ }
69
+
70
+ /*
71
+ * Delete one note and its exclusively owned tables; shared tables remain standalone.
72
+ * INSIGHT deletion requires table-edit permission.
73
+ */
74
+ export function useDeleteAgentNote(params: UseMutationParams = {}, openModalPopUp?: OpenModalPopUpFn) {
75
+ const { onCompleted, ...rest } = params;
76
+ const [deleteAgentNote, values, handlers] = useMutation(deleteAgentNoteMtn, {
77
+ openModalPopUp,
78
+ onCompleted: (data, error, variables) => onCompleted?.(data?.deleteAgentNote, error, variables),
79
+ ...rest,
80
+ });
81
+ return { deleteAgentNote, ...values, ...handlers };
82
+ }
@@ -0,0 +1,190 @@
1
+ import { FRAGMENT_NAMES, getFragmentBaseName, makeFragmentKey } from '@jsb188/mday/constants/graphqlReactivity.ts';
2
+ import type {
3
+ AgentNoteBootstrapProgressGQL,
4
+ AgentNoteGQL,
5
+ AgentNoteKindEnum,
6
+ CampaignTemplateAgentNoteFocusGQL,
7
+ } from '@jsb188/mday/types/agentNote.d.ts';
8
+ import { useMemo } from 'react';
9
+ import { loadFragment } from '../cache/index.ts';
10
+ import {
11
+ agentNoteBootstrapProgressQry,
12
+ agentNoteQry,
13
+ agentNotesQry,
14
+ campaignTemplateAgentNoteFocusQry,
15
+ searchAgentNotesQry,
16
+ } from '../gql/queries/agentNoteQueries.ts';
17
+ import type { UseQueryParams } from '../types.d.ts';
18
+ import { useQuery, useReactiveFragment, useReactiveFragmentMap } from './index.ts';
19
+ import { useMarkAgentNoteRead } from './use-agentNote-mtn.ts';
20
+ import { getAgentNoteResponseRevision, getVisibleAgentNote } from './use-agentNote-recovery.helpers.ts';
21
+ import { useRecoverableAgentNoteQuery } from './use-agentNote-recovery.ts';
22
+
23
+ export type AgentNotesVariables = {
24
+ organizationId?: string | null;
25
+ };
26
+
27
+ export type SearchAgentNotesVariables = AgentNotesVariables & {
28
+ query: string;
29
+ includeArchived?: boolean | null;
30
+ kinds?: readonly AgentNoteKindEnum[] | null;
31
+ limit?: number | null;
32
+ };
33
+
34
+ export type AgentNoteVariables = {
35
+ organizationId?: string | null;
36
+ agentNoteId?: string | null;
37
+ };
38
+
39
+ export type CampaignTemplateAgentNoteFocusVariables = {
40
+ organizationId?: string | null;
41
+ campaignTemplateId?: string | null;
42
+ };
43
+
44
+ /*
45
+ * Read the safe initial-review status and recover missed status changes after reconnecting.
46
+ */
47
+ export function useAgentNoteBootstrapProgress(variables: { organizationId?: string | null }, params: UseQueryParams = {}) {
48
+ const { data, ...rest } = useRecoverableAgentNoteQuery(agentNoteBootstrapProgressQry, variables.organizationId, {
49
+ ...params,
50
+ variables,
51
+ skip: !variables.organizationId || !!params.skip,
52
+ revalidateOnMount: true,
53
+ });
54
+ const progress: AgentNoteBootstrapProgressGQL | null = rest.error ? null : data?.agentNoteBootstrapProgress || null;
55
+ return { progress, ...rest };
56
+ }
57
+
58
+ /*
59
+ * Fetch every visible homepage note once per organization. Local groups and
60
+ * display limits share this collection and never change its query variables.
61
+ */
62
+ export function useAgentNotes(variables: AgentNotesVariables, params: UseQueryParams = {}) {
63
+ const { data, ...rest } = useRecoverableAgentNoteQuery(agentNotesQry, variables.organizationId, {
64
+ ...params,
65
+ variables: {
66
+ organizationId: variables.organizationId,
67
+ },
68
+ skip: !variables.organizationId || !!params.skip,
69
+ });
70
+ const agentNotes: AgentNoteGQL[] | null = useReactiveFragmentMap(
71
+ data?.agentNotes || null,
72
+ getFragmentBaseName(FRAGMENT_NAMES.agentNote),
73
+ rest.updatedCount,
74
+ );
75
+
76
+ const visibleAgentNotes = useMemo(() => agentNotes?.filter((note) => !note.__deleted && !note.archivedAt) ?? null, [agentNotes]);
77
+ return { agentNotes: visibleAgentNotes, ...rest };
78
+ }
79
+
80
+ /*
81
+ * Search active and archived notes without pagination. The accepted query
82
+ * identifies the result so a debounced input can keep older rows visible
83
+ * without presenting them as matches for a newer draft.
84
+ */
85
+ export function useSearchAgentNotes(variables: SearchAgentNotesVariables, params: UseQueryParams = {}) {
86
+ const query = variables.query.trim();
87
+ const { data, ...rest } = useRecoverableAgentNoteQuery(searchAgentNotesQry, variables.organizationId, {
88
+ ...params,
89
+ variables: {
90
+ organizationId: variables.organizationId,
91
+ query,
92
+ kinds: variables.kinds,
93
+ includeArchived: variables.includeArchived ?? true,
94
+ limit: variables.limit ?? 16,
95
+ },
96
+ skip: !variables.organizationId || !query || !!params.skip,
97
+ revalidateOnMount: true,
98
+ });
99
+ const revision = getAgentNoteResponseRevision({ ...data, error: rest.error }, 'searchAgentNotes');
100
+ const agentNotes: AgentNoteGQL[] | null = useReactiveFragmentMap(
101
+ revision === null ? null : data.searchAgentNotes.items,
102
+ getFragmentBaseName(FRAGMENT_NAMES.agentNote),
103
+ rest.updatedCount,
104
+ );
105
+
106
+ const visibleAgentNotes = useMemo(
107
+ () =>
108
+ agentNotes?.filter(
109
+ (note) =>
110
+ !note.__deleted &&
111
+ (variables.includeArchived !== false || !note.archivedAt) &&
112
+ (!variables.kinds?.length || variables.kinds.includes(note.kind)),
113
+ ) ?? null,
114
+ [agentNotes, variables.includeArchived, variables.kinds],
115
+ );
116
+ return { agentNotes: visibleAgentNotes, acceptedQuery: revision === null ? null : query, revision, ...rest };
117
+ }
118
+
119
+ /*
120
+ * Fetch one agent note in full. Opening it stamps one read
121
+ * (markAgentNoteRead, once per mounted note); realtime fragments update its
122
+ * content without refetching or stamping another read. cacheFirst reuses full normalized
123
+ * details from any view without a request. Views that retain their own open
124
+ * identity across remounts pass markRead: false and own the read stamp.
125
+ */
126
+ export function useAgentNote(
127
+ variables: AgentNoteVariables,
128
+ params: UseQueryParams & { markRead?: boolean; cacheFirst?: boolean } = {},
129
+ ) {
130
+ const { markRead = true, cacheFirst = false, ...queryParams } = params;
131
+ const skip = !variables.organizationId || !variables.agentNoteId || !!params.skip;
132
+ const cachedNote: AgentNoteGQL | null = variables.agentNoteId
133
+ ? loadFragment(makeFragmentKey(FRAGMENT_NAMES.agentNote, variables.agentNoteId))
134
+ : null;
135
+ // Summary rows omit body and links; only a full detail or a deletion can satisfy this read.
136
+ const useCachedNote = !!(
137
+ cacheFirst &&
138
+ cachedNote &&
139
+ cachedNote.organizationId === variables.organizationId &&
140
+ (cachedNote.__deleted || (cachedNote.body !== undefined && Array.isArray(cachedNote.links)))
141
+ );
142
+ const { data, ...rest } = useRecoverableAgentNoteQuery(agentNoteQry, variables.organizationId, {
143
+ ...queryParams,
144
+ variables,
145
+ skip: skip || useCachedNote,
146
+ });
147
+ useMarkAgentNoteRead(variables, skip || !markRead);
148
+ const agentNote = useReactiveAgentNoteFragment(variables.agentNoteId, data?.agentNote, rest.updatedCount);
149
+
150
+ return {
151
+ ...rest,
152
+ agentNote:
153
+ skip || agentNote?.organizationId !== variables.organizationId
154
+ ? null
155
+ : getVisibleAgentNote(useCachedNote ? { agentNote: cachedNote } : data, agentNote, rest.error),
156
+ loading: useCachedNote ? false : rest.loading,
157
+ };
158
+ }
159
+
160
+ /*
161
+ * Observe the shared note identity, including full details previously loaded by another view.
162
+ */
163
+ export function useReactiveAgentNoteFragment(agentNoteId?: string | null, currentData?: AgentNoteGQL | null, queryCount?: number) {
164
+ const note: AgentNoteGQL | null = useReactiveFragment(
165
+ currentData || null,
166
+ agentNoteId ? [makeFragmentKey(FRAGMENT_NAMES.agentNote, agentNoteId)] : [],
167
+ queryCount,
168
+ );
169
+ return note?.id === agentNoteId ? note : null;
170
+ }
171
+
172
+ /*
173
+ * Fetch the organization's focus for one web form template: the focus the
174
+ * note of every campaign created from the template afterwards starts with
175
+ * (focus is null when none is set; existing campaigns keep their own). The
176
+ * server resets this query when the focus is set or cleared.
177
+ */
178
+ export function useCampaignTemplateAgentNoteFocus(variables: CampaignTemplateAgentNoteFocusVariables, params: UseQueryParams = {}) {
179
+ const { data, ...rest } = useQuery(campaignTemplateAgentNoteFocusQry, {
180
+ ...params,
181
+ variables,
182
+ skip: !variables.organizationId || !variables.campaignTemplateId || !!params.skip,
183
+ });
184
+ const campaignTemplateAgentNoteFocus: CampaignTemplateAgentNoteFocusGQL | null = data?.campaignTemplateAgentNoteFocus || null;
185
+
186
+ return {
187
+ campaignTemplateAgentNoteFocus,
188
+ ...rest,
189
+ };
190
+ }
@@ -0,0 +1,68 @@
1
+ import {
2
+ agentNoteRecoveryReadSucceeded,
3
+ getAgentNoteResponseRevision,
4
+ getVisibleAgentNote,
5
+ } from './use-agentNote-recovery.helpers.ts';
6
+
7
+ /* Fail note response regressions with the expected user-visible behavior. */
8
+ function assert(value: unknown, message: string): asserts value {
9
+ if (!value) throw new Error(message);
10
+ }
11
+
12
+ Deno.test('missing details are successful authoritative reads but partial errors cannot acknowledge freshness', () => {
13
+ assert(
14
+ agentNoteRecoveryReadSucceeded({ agentNote: null, error: { errorCode: 20232, statusCode: 404 } }, 'agentNote'),
15
+ 'The exact server missing-note response is authoritative absence',
16
+ );
17
+ assert(
18
+ !agentNoteRecoveryReadSucceeded({ agentNote: null, error: { errorCode: '20052', statusCode: 404 } }, 'agentNote'),
19
+ 'A different authorization error cannot acknowledge note freshness',
20
+ );
21
+ assert(
22
+ !agentNoteRecoveryReadSucceeded({ error: { errorCode: '20232', statusCode: 404 } }, 'agentNote'),
23
+ 'A missing response field cannot acknowledge a detail snapshot',
24
+ );
25
+ assert(
26
+ !agentNoteRecoveryReadSucceeded({ agentNote: { id: 'stale' }, error: { errorCode: '20232', statusCode: 404 } }, 'agentNote'),
27
+ 'A partial object is not authoritative absence',
28
+ );
29
+ assert(
30
+ agentNoteRecoveryReadSucceeded({ agentNote: null }, 'agentNote'),
31
+ 'Deletion while offline must settle to an authoritative missing result',
32
+ );
33
+ assert(
34
+ !agentNoteRecoveryReadSucceeded({ agentNote: null, error: { errorCode: '30000' } }, 'agentNote'),
35
+ 'Partial data with an error must retry',
36
+ );
37
+ assert(
38
+ !agentNoteRecoveryReadSucceeded({ agentNotes: [] }, 'agentNote'),
39
+ 'A response for another query cannot establish the baseline',
40
+ );
41
+ });
42
+
43
+ Deno.test('search freshness requires valid items and revision in the same successful response', () => {
44
+ for (const result of [
45
+ { searchAgentNotes: null },
46
+ { searchAgentNotes: { items: [], revision: 4 } },
47
+ { searchAgentNotes: { items: null, revision: '4' } },
48
+ { searchAgentNotes: { items: [], revision: '-1' } },
49
+ { searchAgentNotes: { items: [], revision: '4' }, __clientResultRejected: true },
50
+ { searchAgentNotes: { items: [], revision: '4' }, aborted: true },
51
+ ]) {
52
+ assert(!agentNoteRecoveryReadSucceeded(result, 'searchAgentNotes'), 'Malformed or rejected searches remain pending');
53
+ assert(getAgentNoteResponseRevision(result, 'searchAgentNotes') === null, 'Invalid snapshots have no accepted revision');
54
+ }
55
+ assert(
56
+ getAgentNoteResponseRevision({ searchAgentNotes: { items: [], revision: '9007199254740993' } }, 'searchAgentNotes') ===
57
+ '9007199254740993',
58
+ 'Bigint revisions must retain text precision',
59
+ );
60
+ });
61
+
62
+ Deno.test('a fragment tombstone hides retained detail content without a query refetch', () => {
63
+ const note = { id: 'note-1', body: 'Old content' };
64
+ assert(
65
+ getVisibleAgentNote({ agentNote: note }, { ...note, __deleted: true }, null) === null,
66
+ 'Deleted fragments must disappear immediately',
67
+ );
68
+ });
@@ -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
+ }