@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
@@ -0,0 +1,138 @@
1
+ import type {
2
+ SheetBootstrapGQL,
3
+ SheetJournalSeqInput,
4
+ SheetRealtimeCapabilityGQL,
5
+ SheetTabBootstrapGQL,
6
+ } from '@jsb188/mday/types/sheet.d.ts';
7
+ import { parseSheetJournalSeq } from '@jsb188/mday/utils/sheetSequence.ts';
8
+ import { graphqlRequestNoStore } from '../client/request.ts';
9
+ import { openSheetQry, renewSheetRealtimeCapabilityQry, syncSheetTabQry } from '../gql/queries/sheetQueries.ts';
10
+
11
+ /*
12
+ * Bootstrap contract 4 (DESIGN §1.3): openSheet negotiates the workbook and
13
+ * its selected tab, syncSheetTab one tab once the manifest is known. Both ask
14
+ * for the rows after the tab's applied `sinceSeq` (DELTA) and fall back to a
15
+ * snapshot plus its tail; there is no viewport and no base-snapshot proof.
16
+ */
17
+
18
+ export type FetchOpenSheetOnceParams = {
19
+ selectedTabId?: string | null;
20
+ sinceSeq?: SheetJournalSeqInput;
21
+ requireSnapshot?: boolean;
22
+
23
+ authToken?: string | null;
24
+ signal?: AbortSignal | null;
25
+ };
26
+
27
+ export type FetchSyncSheetTabOnceParams = {
28
+ sinceSeq?: SheetJournalSeqInput;
29
+ requireSnapshot?: boolean;
30
+ minimumCellsRevision?: SheetJournalSeqInput;
31
+ minimumDesignRevision?: SheetJournalSeqInput;
32
+
33
+ authToken?: string | null;
34
+ signal?: AbortSignal | null;
35
+ };
36
+
37
+ /*
38
+ * Return the canonical openSheet variables of one fetch. Journal cursors are
39
+ * sent as canonical decimal strings; an absent or malformed one is null..
40
+ */
41
+ export function getOpenSheetQueryVariables(sheetId: string, params: FetchOpenSheetOnceParams = {}) {
42
+ return {
43
+ sheetId,
44
+ selectedTabId: params.selectedTabId || null,
45
+ sinceSeq: parseSheetJournalSeq(params.sinceSeq),
46
+ requireSnapshot: Boolean(params.requireSnapshot),
47
+ };
48
+ }
49
+
50
+ /*
51
+ * Return the canonical syncSheetTab variables of one fetch.
52
+ */
53
+ export function getSyncSheetTabQueryVariables(sheetId: string, sheetTabId: string, params: FetchSyncSheetTabOnceParams = {}) {
54
+ return {
55
+ sheetId,
56
+ sheetTabId,
57
+ sinceSeq: parseSheetJournalSeq(params.sinceSeq),
58
+ requireSnapshot: Boolean(params.requireSnapshot),
59
+ minimumCellsRevision: parseSheetJournalSeq(params.minimumCellsRevision),
60
+ minimumDesignRevision: parseSheetJournalSeq(params.minimumDesignRevision),
61
+ };
62
+ }
63
+
64
+ /*
65
+ * Return one no-store operation's field, throwing an AbortError for an
66
+ * aborted request and the normalized server error for a failed one.
67
+ */
68
+ function getSheetBootstrapOperationResult<T>(
69
+ result: any,
70
+ operation: 'openSheet' | 'renewSheetRealtimeCapability' | 'syncSheetTab',
71
+ ): T | null {
72
+ if (result?.aborted) {
73
+ throw new DOMException(`${operation} request was aborted.`, 'AbortError');
74
+ }
75
+ if (result?.error) {
76
+ throw result.error;
77
+ }
78
+
79
+ return result?.[operation] || null;
80
+ }
81
+
82
+ /*
83
+ * Imperatively fetch one openSheet response exactly once without reading,
84
+ * writing, or joining the normalized GraphQL cache. Each invocation owns its
85
+ * network request and carries its authorization token only in request headers.
86
+ */
87
+ export async function fetchOpenSheetOnce(sheetId: string, params: FetchOpenSheetOnceParams = {}): Promise<SheetBootstrapGQL | null> {
88
+ const result = await graphqlRequestNoStore(
89
+ openSheetQry,
90
+ getOpenSheetQueryVariables(sheetId, params),
91
+ { authToken: params.authToken },
92
+ params.signal,
93
+ );
94
+
95
+ return getSheetBootstrapOperationResult<SheetBootstrapGQL>(result, 'openSheet');
96
+ }
97
+
98
+ /*
99
+ * Renew one Sheet's realtime capability without reading or writing the normalized GraphQL cache.
100
+ */
101
+ export async function fetchSheetRealtimeCapabilityOnce(
102
+ sheetId: string,
103
+ params: {
104
+ authToken?: string | null;
105
+
106
+ signal?: AbortSignal | null;
107
+ } = {},
108
+ ): Promise<SheetRealtimeCapabilityGQL | null> {
109
+ const result = await graphqlRequestNoStore(
110
+ renewSheetRealtimeCapabilityQry,
111
+ {
112
+ sheetId,
113
+ },
114
+ { authToken: params.authToken },
115
+ params.signal,
116
+ );
117
+
118
+ return getSheetBootstrapOperationResult<SheetRealtimeCapabilityGQL>(result, 'renewSheetRealtimeCapability');
119
+ }
120
+
121
+ /*
122
+ * Synchronize one tab through the snapshot/delta negotiation without
123
+ * consulting or mutating the normalized GraphQL cache.
124
+ */
125
+ export async function fetchSyncSheetTabOnce(
126
+ sheetId: string,
127
+ sheetTabId: string,
128
+ params: FetchSyncSheetTabOnceParams = {},
129
+ ): Promise<SheetTabBootstrapGQL | null> {
130
+ const result = await graphqlRequestNoStore(
131
+ syncSheetTabQry,
132
+ getSyncSheetTabQueryVariables(sheetId, sheetTabId, params),
133
+ { authToken: params.authToken },
134
+ params.signal,
135
+ );
136
+
137
+ return getSheetBootstrapOperationResult<SheetTabBootstrapGQL>(result, 'syncSheetTab');
138
+ }
@@ -0,0 +1,229 @@
1
+ import type { OrchestratorArtifactWSObj } from '@jsb188/app/types/app.d.ts';
2
+ import {
3
+ applyOrchestratorArtifactUpdate,
4
+ type OrchestratorSessionData,
5
+ getEmptyOrchestratorSessionData,
6
+ mergeOrchestratorArtifactUpdates,
7
+ } from './orchestrator-realtime.helpers.ts';
8
+
9
+ /*
10
+ * Throw one readable test failure when a condition is false.
11
+ */
12
+ function expect(value: unknown, message: string) {
13
+ if (!value) {
14
+ throw new Error(message);
15
+ }
16
+ }
17
+
18
+ /*
19
+ * Build one artifact event of the orchestrator chat used by every case.
20
+ */
21
+ function event(callId: string, at: string, fields: Partial<OrchestratorArtifactWSObj>): OrchestratorArtifactWSObj {
22
+ return {
23
+ aiChatId: 'chat-1',
24
+ runId: 'run-1',
25
+ callId,
26
+ organizationId: 'org-1',
27
+ toolName: 'create_sheet_tab',
28
+ kind: 'SHEET_TAB',
29
+ action: 'CREATED',
30
+ sheetId: 'S1',
31
+ at: `2026-09-25T00:00:0${at}.000Z`,
32
+ ...fields,
33
+ };
34
+ }
35
+
36
+ /*
37
+ * Apply live events in order, the way the store does as they arrive.
38
+ */
39
+ function applyLive(updates: OrchestratorArtifactWSObj[]) {
40
+ let session: OrchestratorSessionData = {
41
+ ...getEmptyOrchestratorSessionData(),
42
+ aiChatId: 'chat-1',
43
+ };
44
+ for (const update of updates) {
45
+ session = applyOrchestratorArtifactUpdate(session, update)?.session || session;
46
+ }
47
+ return session;
48
+ }
49
+
50
+ Deno.test('caught-up events fill gaps without regressing newer live entries', () => {
51
+ const renamed = event('c3', '3', {
52
+ toolName: 'update_sheet_tab',
53
+ action: 'UPDATED',
54
+ sheetTabId: 'T1',
55
+ title: 'Costs',
56
+ });
57
+ const live = applyLive([renamed]);
58
+ const merged = mergeOrchestratorArtifactUpdates(live, [
59
+ event('c1', '1', { sheetTabId: 'T1', title: 'Sheet 2' }),
60
+ event('c2', '2', {
61
+ toolName: 'create_data_table',
62
+ kind: 'DATA_TABLE',
63
+ sheetId: null,
64
+ dataTableId: 'D1',
65
+ title: 'Inventory',
66
+ }),
67
+ renamed,
68
+ ]);
69
+
70
+ expect(merged, 'Missed calls must change the session.');
71
+ const [tab, table] = merged!.artifacts;
72
+ expect(
73
+ tab.key === 'SHEET_TAB:T1' && tab.state === 'CREATED' && tab.title === 'Costs' && tab.at === renamed.at,
74
+ 'An older caught-up creation may add the CREATED state but must keep the newer title and time.',
75
+ );
76
+ expect(table.key === 'DATA_TABLE:D1' && merged!.artifacts.length === 2, 'The missed table is listed after the newer tab.');
77
+ expect(merged!.hasCreated, 'Caught-up creations count toward hasCreated.');
78
+ expect(merged!.callIds.join() === 'c1,c2,c3', 'Caught-up call ids are remembered as the newest.');
79
+ expect(mergeOrchestratorArtifactUpdates(merged!, [renamed]) === null, 'A repeated catch-up changes nothing.');
80
+ });
81
+
82
+ Deno.test('a deletion received live still wins over its older caught-up creation', () => {
83
+ const deleted = event('c2', '2', {
84
+ toolName: 'delete_sheet_tab',
85
+ action: 'DELETED',
86
+ sheetTabId: 'T1',
87
+ });
88
+ const merged = mergeOrchestratorArtifactUpdates(applyLive([deleted]), [event('c1', '1', { sheetTabId: 'T1' }), deleted]);
89
+
90
+ expect(merged && merged.artifacts.length === 0, 'The deleted tab must not be resurrected by its creation.');
91
+ });
92
+
93
+ Deno.test('live creations navigate once, and a data table only before any other grid', () => {
94
+ const tab = event('c1', '1', { sheetTabId: 'T1' });
95
+ const first = applyOrchestratorArtifactUpdate(applyLive([]), tab);
96
+ expect(first?.navigateTo?.key === 'SHEET_TAB:T1' && first.session.hasCreated, 'A created tab navigates and counts as a creation.');
97
+ expect(applyOrchestratorArtifactUpdate(first!.session, tab) === null, 'A tool call is applied once.');
98
+ expect(
99
+ applyOrchestratorArtifactUpdate(first!.session, { ...tab, callId: 'c1b' })?.navigateTo === null,
100
+ 'A replayed creation of an already created entry does not navigate again.',
101
+ );
102
+
103
+ const table = event('c2', '2', {
104
+ toolName: 'create_data_table',
105
+ kind: 'DATA_TABLE',
106
+ sheetId: null,
107
+ dataTableId: 'D1',
108
+ });
109
+ expect(
110
+ applyOrchestratorArtifactUpdate(applyLive([]), table)?.navigateTo?.key === 'DATA_TABLE:D1',
111
+ 'A data table created first navigates.',
112
+ );
113
+ expect(
114
+ applyOrchestratorArtifactUpdate(first!.session, table)?.navigateTo === null,
115
+ 'A data table created after a sheet tab is only listed.',
116
+ );
117
+ });
118
+
119
+ Deno.test('forms and workflows are listed with their organization and state, never navigated to', () => {
120
+ const form = event('c1', '1', {
121
+ toolName: 'save_field_doc',
122
+ kind: 'FIELD_DOC',
123
+ sheetId: null,
124
+ fieldDocId: 'F1',
125
+ fieldDocProgramId: 'P1',
126
+ title: 'Delivery check',
127
+ });
128
+ const workflow = event('c2', '2', {
129
+ toolName: 'save_workflow',
130
+ kind: 'WORKFLOW',
131
+ sheetId: null,
132
+ workflowId: 'W1',
133
+ active: false,
134
+ title: 'Notify dispatch',
135
+ });
136
+ const applied = applyOrchestratorArtifactUpdate(applyLive([]), form);
137
+ expect(
138
+ applied?.navigateTo === null && !applied.session.hasCreated,
139
+ 'A created form is not navigated to and does not block table navigation.',
140
+ );
141
+
142
+ const activated = event('c3', '3', {
143
+ toolName: 'set_workflow_active',
144
+ kind: 'WORKFLOW',
145
+ action: 'UPDATED',
146
+ sheetId: null,
147
+ workflowId: 'W1',
148
+ active: true,
149
+ organizationId: null,
150
+ });
151
+ const session = applyLive([form, workflow, activated]);
152
+ const [listedWorkflow, listedForm] = session.artifacts;
153
+ expect(
154
+ listedWorkflow.key === 'WORKFLOW:W1' &&
155
+ listedWorkflow.state === 'CREATED' &&
156
+ listedWorkflow.active === true &&
157
+ listedWorkflow.title === 'Notify dispatch' &&
158
+ listedWorkflow.organizationId === 'org-1',
159
+ 'Activation updates the state and keeps what the creation reported.',
160
+ );
161
+ expect(
162
+ listedForm.key === 'FIELD_DOC:F1' && listedForm.fieldDocProgramId === 'P1' && listedForm.organizationId === 'org-1',
163
+ 'The form keeps its program and organization.',
164
+ );
165
+
166
+ const merged = mergeOrchestratorArtifactUpdates(applyLive([activated]), [workflow, activated]);
167
+ expect(
168
+ merged?.artifacts[0].active === true && merged.artifacts[0].state === 'CREATED',
169
+ 'An older caught-up save adds CREATED without undoing the newer activation.',
170
+ );
171
+ });
172
+
173
+ Deno.test('deleting a tab clears it from its spreadsheet entry', () => {
174
+ const sheet = event('c1', '1', {
175
+ toolName: 'create_spreadsheet',
176
+ kind: 'SHEET',
177
+ sheetTabId: 'T1',
178
+ });
179
+ const deleted = event('c2', '2', {
180
+ toolName: 'delete_sheet_tab',
181
+ action: 'DELETED',
182
+ sheetTabId: 'T1',
183
+ });
184
+ const live = applyLive([sheet, deleted]);
185
+ expect(live.artifacts.length === 1 && live.artifacts[0].sheetTabId === null, 'The spreadsheet no longer opens on the deleted tab.');
186
+
187
+ const merged = mergeOrchestratorArtifactUpdates(applyLive([deleted, sheet]), [sheet, deleted]);
188
+ expect(
189
+ merged?.artifacts[0].key === 'SHEET:S1' && merged.artifacts[0].sheetTabId === null,
190
+ 'A caught-up deletion clears a tab the spreadsheet regained from a live event.',
191
+ );
192
+ });
193
+
194
+ Deno.test('publishing clears a draft and delayed draft receipts cannot bring it back', () => {
195
+ const draft = event('draft', '1', {
196
+ kind: 'FIELD_DOC',
197
+ fieldDocId: 'F1',
198
+ fieldDocProgramId: 'P1',
199
+ hasDraft: true,
200
+ });
201
+ const published = event('publish', '3', {
202
+ kind: 'FIELD_DOC',
203
+ fieldDocId: 'F1',
204
+ action: 'UPDATED',
205
+ hasDraft: false,
206
+ });
207
+ const live = applyLive([draft, published]);
208
+ expect(live.artifacts[0].hasDraft === false, 'Publishing must clear the saved draft reminder.');
209
+ const delayed = applyOrchestratorArtifactUpdate(live, { ...draft, callId: 'delayed' });
210
+ expect(delayed?.session.artifacts[0].hasDraft === false, 'An older live save cannot restore draft status.');
211
+ const caughtUp = mergeOrchestratorArtifactUpdates(applyLive([published]), [draft]);
212
+ expect(caughtUp?.artifacts[0].hasDraft === false, 'An older caught-up draft cannot restore draft status.');
213
+ });
214
+
215
+ Deno.test('catch-up refreshes an already-seen draft from current stored state independently of call order', () => {
216
+ const draft = event('draft', '1', {
217
+ kind: 'FIELD_DOC',
218
+ fieldDocId: 'F1',
219
+ hasDraft: true,
220
+ });
221
+ const publishedElsewhere = { ...draft, hasDraft: false, draftStateAt: '2026-09-25T00:00:04.000Z' };
222
+ const merged = mergeOrchestratorArtifactUpdates(applyLive([draft]), [publishedElsewhere]);
223
+ expect(merged?.artifacts[0].hasDraft === false, 'An already-seen call must accept freshly read publication state.');
224
+ expect(merged?.artifacts[0].at === draft.at, 'Refreshing current state must not pretend another tool edit occurred.');
225
+ const staleCatchUp = mergeOrchestratorArtifactUpdates(merged!, [{ ...draft, draftStateAt: '2026-09-25T00:00:02.000Z' }]);
226
+ expect(staleCatchUp === null, 'An older response arriving late must not replace newer observed publication state.');
227
+ const nextDraft = applyOrchestratorArtifactUpdate(merged!, { ...draft, callId: 'next', at: '2026-09-25T00:00:05.000Z' });
228
+ expect(nextDraft?.session.artifacts[0].hasDraft === true, 'A later edit can create a new draft after publication.');
229
+ });
@@ -0,0 +1,317 @@
1
+ import type { AIChatType } from '@jsb188/app/types/ai.d.ts';
2
+ import type { OrchestratorArtifactKind, OrchestratorArtifactWSObj } from '@jsb188/app/types/app.d.ts';
3
+
4
+ /**
5
+ * Types
6
+ */
7
+
8
+ // CREATED sticks for the rest of the session; later edits never downgrade it
9
+ export type OrchestratorArtifactState = 'CREATED' | 'EDITED';
10
+
11
+ // One sheet, tab, data table, form or workflow the orchestrator created or edited in a session
12
+ export interface OrchestratorArtifactObj {
13
+ key: string;
14
+ kind: OrchestratorArtifactKind;
15
+ state: OrchestratorArtifactState;
16
+ // The organization the orchestrator made it in; its page only opens under that login
17
+ organizationId: string | null;
18
+ sheetId: string | null;
19
+ sheetTabId: string | null;
20
+ dataTableId: string | null;
21
+ fieldDocId: string | null;
22
+ fieldDocProgramId: string | null;
23
+ // Current publication state is observed separately from the historical tool event.
24
+ hasDraft: boolean | null;
25
+ draftStateAt: string | null;
26
+ workflowId: string | null;
27
+ // Workflows only: whether new matching logs run it (null while unknown)
28
+ active: boolean | null;
29
+ title: string | null;
30
+ at: string;
31
+ }
32
+
33
+ // In-memory chat selection and artifact state
34
+ export interface OrchestratorSessionData {
35
+ aiChatId: string | null;
36
+ chatType: AIChatType | null;
37
+ artifacts: OrchestratorArtifactObj[];
38
+ // Whether any sheet, tab or data table was CREATED in this session (gates DATA_TABLE navigation)
39
+ hasCreated: boolean;
40
+ // Tool call ids already applied, oldest first
41
+ callIds: string[];
42
+ }
43
+
44
+ export interface OrchestratorArtifactApplyResult {
45
+ session: OrchestratorSessionData;
46
+ // The artifact the owning tab should navigate to, if this event calls for it
47
+ navigateTo: OrchestratorArtifactObj | null;
48
+ }
49
+
50
+ /**
51
+ * Constants
52
+ */
53
+
54
+ export const ORCHESTRATOR_SESSION_LIMITS = {
55
+ maxArtifacts: 50,
56
+ // Twice the server's catch-up window (orchestratorArtifactOps.ts), so a caught-up call is never applied twice
57
+ maxCallIds: 200,
58
+ };
59
+
60
+ /*
61
+ * Return a fresh session with no chat and no artifacts.
62
+ */
63
+ export function getEmptyOrchestratorSessionData(): OrchestratorSessionData {
64
+ return {
65
+ aiChatId: null,
66
+ chatType: null,
67
+ artifacts: [],
68
+ hasCreated: false,
69
+ callIds: [],
70
+ };
71
+ }
72
+
73
+ /*
74
+ * Return the list identity of one artifact (kind + its own id), or null when the id is missing.
75
+ */
76
+ export function getOrchestratorArtifactKey(p: {
77
+ kind: OrchestratorArtifactKind;
78
+ sheetId?: string | null;
79
+ sheetTabId?: string | null;
80
+ dataTableId?: string | null;
81
+ fieldDocId?: string | null;
82
+ workflowId?: string | null;
83
+ }) {
84
+ let id: string | null | undefined;
85
+ switch (p.kind) {
86
+ case 'SHEET':
87
+ id = p.sheetId;
88
+ break;
89
+ case 'SHEET_TAB':
90
+ id = p.sheetTabId;
91
+ break;
92
+ case 'DATA_TABLE':
93
+ id = p.dataTableId;
94
+ break;
95
+ case 'FIELD_DOC':
96
+ id = p.fieldDocId;
97
+ break;
98
+ case 'WORKFLOW':
99
+ id = p.workflowId;
100
+ break;
101
+ }
102
+
103
+ return id ? `${p.kind}:${id}` : null;
104
+ }
105
+
106
+ /*
107
+ * Return whether a live creation of this kind may open its page on its own. Forms and workflows are only
108
+ * listed, so the grid behind the orchestrator stays put.
109
+ */
110
+ function isOrchestratorNavigableKind(kind: OrchestratorArtifactKind) {
111
+ return kind === 'SHEET' || kind === 'SHEET_TAB' || kind === 'DATA_TABLE';
112
+ }
113
+
114
+ /*
115
+ * Return the artifact list after one deletion. A deleted spreadsheet takes its listed tabs with it, and a
116
+ * deleted tab is no longer the tab its spreadsheet opens on. Unchanged entries keep their identity.
117
+ */
118
+ function removeOrchestratorDeletedArtifact(artifacts: OrchestratorArtifactObj[], key: string, update: OrchestratorArtifactWSObj) {
119
+ return artifacts.flatMap((artifact) => {
120
+ if (artifact.key === key || (update.kind === 'SHEET' && artifact.kind === 'SHEET_TAB' && artifact.sheetId === update.sheetId)) {
121
+ return [];
122
+ }
123
+
124
+ if (
125
+ update.kind === 'SHEET_TAB' &&
126
+ artifact.kind === 'SHEET' &&
127
+ artifact.sheetId === update.sheetId &&
128
+ artifact.sheetTabId === update.sheetTabId
129
+ ) {
130
+ return [{ ...artifact, sheetTabId: null }];
131
+ }
132
+
133
+ return [artifact];
134
+ });
135
+ }
136
+
137
+ /*
138
+ * Return whether two artifact lists hold the same entries in the same order.
139
+ */
140
+ function isSameOrchestratorArtifactList(a: OrchestratorArtifactObj[], b: OrchestratorArtifactObj[]) {
141
+ return a.length === b.length && a.every((artifact, i) => artifact === b[i]);
142
+ }
143
+
144
+ /*
145
+ * Merge a form's current draft state by observation time, so a delayed catch-up cannot restore an old draft.
146
+ */
147
+ function getOrchestratorDraftState(update: OrchestratorArtifactWSObj, existing?: OrchestratorArtifactObj) {
148
+ const draftStateAt = update.draftStateAt || update.at;
149
+ if (
150
+ update.kind === 'FIELD_DOC' &&
151
+ typeof update.hasDraft === 'boolean' &&
152
+ (!existing?.draftStateAt || draftStateAt >= existing.draftStateAt)
153
+ ) {
154
+ return { hasDraft: update.hasDraft, draftStateAt };
155
+ }
156
+ return { hasDraft: existing?.hasDraft ?? null, draftStateAt: existing?.draftStateAt || null };
157
+ }
158
+
159
+ /*
160
+ * Refresh an already-seen call's form state after catch-up reads the current draft without replaying the edit.
161
+ */
162
+ function refreshOrchestratorDraftState(session: OrchestratorSessionData, update: OrchestratorArtifactWSObj) {
163
+ if (update.kind !== 'FIELD_DOC' || typeof update.hasDraft !== 'boolean') return null;
164
+ const key = getOrchestratorArtifactKey(update);
165
+ let changed = false;
166
+ const artifacts = session.artifacts.map((artifact) => {
167
+ if (artifact.key !== key) return artifact;
168
+ const next = getOrchestratorDraftState(update, artifact);
169
+ if (next.hasDraft === artifact.hasDraft && next.draftStateAt === artifact.draftStateAt) return artifact;
170
+ changed = true;
171
+ return { ...artifact, ...next };
172
+ });
173
+ return changed ? { ...session, artifacts } : null;
174
+ }
175
+
176
+ /*
177
+ * Return one artifact after an event, keeping what an earlier event already knew when this one omits it.
178
+ */
179
+ function getUpdatedOrchestratorArtifact(
180
+ key: string,
181
+ update: OrchestratorArtifactWSObj,
182
+ existing: OrchestratorArtifactObj | undefined,
183
+ ): OrchestratorArtifactObj {
184
+ return {
185
+ key,
186
+ kind: update.kind,
187
+ state: update.action === 'CREATED' || existing?.state === 'CREATED' ? 'CREATED' : 'EDITED',
188
+ organizationId: update.organizationId || existing?.organizationId || null,
189
+ sheetId: update.sheetId || existing?.sheetId || null,
190
+ sheetTabId: update.sheetTabId || existing?.sheetTabId || null,
191
+ dataTableId: update.dataTableId || existing?.dataTableId || null,
192
+ fieldDocId: update.fieldDocId || existing?.fieldDocId || null,
193
+ fieldDocProgramId: update.fieldDocProgramId || existing?.fieldDocProgramId || null,
194
+ ...getOrchestratorDraftState(update, existing),
195
+ workflowId: update.workflowId || existing?.workflowId || null,
196
+ active: typeof update.active === 'boolean' ? update.active : (existing?.active ?? null),
197
+ title: update.title || existing?.title || null,
198
+ at: update.at || new Date().toISOString(),
199
+ };
200
+ }
201
+
202
+ /*
203
+ * Apply one live artifact event to a session. Already-applied calls only refresh current draft state.
204
+ * Navigation: SHEET and SHEET_TAB creations always navigate; a DATA_TABLE creation only when
205
+ * no sheet, tab or table was created earlier in the session. Forms, workflows, updates and
206
+ * deletions never navigate.
207
+ */
208
+ export function applyOrchestratorArtifactUpdate(
209
+ session: OrchestratorSessionData,
210
+ update: OrchestratorArtifactWSObj,
211
+ ): OrchestratorArtifactApplyResult | null {
212
+ if (session.callIds.includes(update.callId)) {
213
+ const refreshed = refreshOrchestratorDraftState(session, update);
214
+ return refreshed ? { session: refreshed, navigateTo: null } : null;
215
+ }
216
+
217
+ const callIds = [...session.callIds, update.callId].slice(-ORCHESTRATOR_SESSION_LIMITS.maxCallIds);
218
+ const key = getOrchestratorArtifactKey(update);
219
+ if (!key) {
220
+ return { session: { ...session, callIds }, navigateTo: null };
221
+ }
222
+
223
+ if (update.action === 'DELETED') {
224
+ const artifacts = removeOrchestratorDeletedArtifact(session.artifacts, key, update);
225
+ return { session: { ...session, artifacts, callIds }, navigateTo: null };
226
+ }
227
+
228
+ const existing = session.artifacts.find((artifact) => artifact.key === key);
229
+ const artifact = getUpdatedOrchestratorArtifact(key, update, existing);
230
+ // Most recently touched first
231
+ const artifacts = [artifact, ...session.artifacts.filter((item) => item.key !== key)].slice(
232
+ 0,
233
+ ORCHESTRATOR_SESSION_LIMITS.maxArtifacts,
234
+ );
235
+ const createdGrid = update.action === 'CREATED' && isOrchestratorNavigableKind(update.kind);
236
+ const shouldNavigate = createdGrid && existing?.state !== 'CREATED' && (update.kind !== 'DATA_TABLE' || !session.hasCreated);
237
+
238
+ return {
239
+ session: {
240
+ ...session,
241
+ artifacts,
242
+ callIds,
243
+ hasCreated: session.hasCreated || createdGrid,
244
+ },
245
+ navigateTo: shouldNavigate ? artifact : null,
246
+ };
247
+ }
248
+
249
+ /*
250
+ * Apply one caught-up artifact event (see mergeOrchestratorArtifactUpdates). An already applied
251
+ * deletion is applied again, since the creation it follows may only be arriving now.
252
+ */
253
+ function mergeOrchestratorArtifactUpdate(
254
+ session: OrchestratorSessionData,
255
+ update: OrchestratorArtifactWSObj,
256
+ ): OrchestratorSessionData {
257
+ const key = getOrchestratorArtifactKey(update);
258
+ if (session.callIds.includes(update.callId)) {
259
+ if (!key || update.action !== 'DELETED') {
260
+ return refreshOrchestratorDraftState(session, update) || session;
261
+ }
262
+ const artifacts = removeOrchestratorDeletedArtifact(session.artifacts, key, update);
263
+ return isSameOrchestratorArtifactList(artifacts, session.artifacts) ? session : { ...session, artifacts };
264
+ }
265
+
266
+ const newer = session.artifacts.find((artifact) => artifact.key === key && artifact.at > update.at);
267
+ const merged = applyOrchestratorArtifactUpdate(session, update)?.session;
268
+ if (!merged || !newer) {
269
+ return merged || session;
270
+ }
271
+
272
+ // Older than what this tab already lists: it may only add a CREATED state or missing fields
273
+ return {
274
+ ...merged,
275
+ artifacts: merged.artifacts.map((artifact) =>
276
+ artifact.key === key
277
+ ? {
278
+ ...artifact,
279
+ sheetTabId: newer.sheetTabId || artifact.sheetTabId,
280
+ fieldDocProgramId: newer.fieldDocProgramId || artifact.fieldDocProgramId,
281
+ active: newer.active ?? artifact.active,
282
+ title: newer.title || artifact.title,
283
+ at: newer.at,
284
+ }
285
+ : artifact,
286
+ ),
287
+ };
288
+ }
289
+
290
+ /*
291
+ * Merge caught-up artifact events (oldest first) that this tab may have missed while it was not
292
+ * watching. Unlike live events they never navigate. Calls already applied are skipped, entries are
293
+ * re-sorted newest first (a caught-up event can be older than one received live), and the caught-up
294
+ * call ids are remembered as the newest, so a later catch-up only refreshes current form draft state.
295
+ * Returns null when nothing changed.
296
+ */
297
+ export function mergeOrchestratorArtifactUpdates(
298
+ session: OrchestratorSessionData,
299
+ updates: OrchestratorArtifactWSObj[],
300
+ ): OrchestratorSessionData | null {
301
+ let merged = session;
302
+ for (const update of updates) {
303
+ merged = mergeOrchestratorArtifactUpdate(merged, update);
304
+ }
305
+ if (merged === session) {
306
+ return null;
307
+ }
308
+
309
+ const caughtUpCallIds = new Set(updates.map((update) => update.callId));
310
+ return {
311
+ ...merged,
312
+ artifacts: [...merged.artifacts].sort((a, b) => (a.at === b.at ? 0 : a.at > b.at ? -1 : 1)),
313
+ callIds: [...session.callIds.filter((callId) => !caughtUpCallIds.has(callId)), ...caughtUpCallIds].slice(
314
+ -ORCHESTRATOR_SESSION_LIMITS.maxCallIds,
315
+ ),
316
+ };
317
+ }