@arbidocs/react 0.4.166 → 0.4.168

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 (97) hide show
  1. package/dist/artifacts/index.cjs +15 -12
  2. package/dist/artifacts/index.cjs.map +1 -1
  3. package/dist/artifacts/index.js +6 -3
  4. package/dist/artifacts/index.js.map +1 -1
  5. package/dist/calls/livekit/index.cjs +977 -0
  6. package/dist/calls/livekit/index.cjs.map +1 -0
  7. package/dist/calls/livekit/index.d.cts +280 -0
  8. package/dist/calls/livekit/index.d.ts +280 -0
  9. package/dist/calls/livekit/index.js +961 -0
  10. package/dist/calls/livekit/index.js.map +1 -0
  11. package/dist/{chunk-ON4PL6DQ.cjs → chunk-2M4B4FFA.cjs} +48 -4
  12. package/dist/chunk-2M4B4FFA.cjs.map +1 -0
  13. package/dist/chunk-3J7MEBOW.cjs +2551 -0
  14. package/dist/chunk-3J7MEBOW.cjs.map +1 -0
  15. package/dist/chunk-3NVSUYUV.js +528 -0
  16. package/dist/chunk-3NVSUYUV.js.map +1 -0
  17. package/dist/{chunk-QJHCVQ6C.js → chunk-3WIBD44F.js} +4734 -4673
  18. package/dist/chunk-3WIBD44F.js.map +1 -0
  19. package/dist/chunk-5B4PPJNW.cjs +1035 -0
  20. package/dist/chunk-5B4PPJNW.cjs.map +1 -0
  21. package/dist/chunk-5HDC43MF.js +145 -0
  22. package/dist/chunk-5HDC43MF.js.map +1 -0
  23. package/dist/{chunk-D66JCVBB.cjs → chunk-7NHOKV7N.cjs} +4093 -4040
  24. package/dist/chunk-7NHOKV7N.cjs.map +1 -0
  25. package/dist/chunk-APZZQZ6P.js +147 -0
  26. package/dist/chunk-APZZQZ6P.js.map +1 -0
  27. package/dist/{chunk-I5ZBQ63Y.js → chunk-DGMK3EUN.js} +188 -181
  28. package/dist/chunk-DGMK3EUN.js.map +1 -0
  29. package/dist/chunk-DPYBZDJB.js +18 -0
  30. package/dist/chunk-DPYBZDJB.js.map +1 -0
  31. package/dist/chunk-EEIYXVM4.cjs +181 -0
  32. package/dist/chunk-EEIYXVM4.cjs.map +1 -0
  33. package/dist/chunk-H3LMKO3T.js +2362 -0
  34. package/dist/chunk-H3LMKO3T.js.map +1 -0
  35. package/dist/{chunk-JSSKEXRR.js → chunk-KGCGA452.js} +2 -2
  36. package/dist/chunk-KGCGA452.js.map +1 -0
  37. package/dist/chunk-MJNZLWJD.js +986 -0
  38. package/dist/chunk-MJNZLWJD.js.map +1 -0
  39. package/dist/chunk-N73IMVFF.cjs +21 -0
  40. package/dist/chunk-N73IMVFF.cjs.map +1 -0
  41. package/dist/chunk-NVAIVJID.js +298 -0
  42. package/dist/chunk-NVAIVJID.js.map +1 -0
  43. package/dist/{chunk-GTJ667CP.cjs → chunk-QQ7SCJRY.cjs} +2 -2
  44. package/dist/chunk-QQ7SCJRY.cjs.map +1 -0
  45. package/dist/chunk-S4PCA3ES.cjs +572 -0
  46. package/dist/chunk-S4PCA3ES.cjs.map +1 -0
  47. package/dist/chunk-VAMPYLQ4.cjs +157 -0
  48. package/dist/chunk-VAMPYLQ4.cjs.map +1 -0
  49. package/dist/chunk-VLK52VXC.cjs +307 -0
  50. package/dist/chunk-VLK52VXC.cjs.map +1 -0
  51. package/dist/{chunk-SVHGCX25.js → chunk-YWYCEEBF.js} +43 -4
  52. package/dist/chunk-YWYCEEBF.js.map +1 -0
  53. package/dist/{chunk-EUC2BTNS.cjs → chunk-ZI2VJOID.cjs} +206 -199
  54. package/dist/chunk-ZI2VJOID.cjs.map +1 -0
  55. package/dist/document-tools/index.cjs +85 -109
  56. package/dist/document-tools/index.cjs.map +1 -1
  57. package/dist/document-tools/index.d.cts +19 -5
  58. package/dist/document-tools/index.d.ts +19 -5
  59. package/dist/document-tools/index.js +28 -70
  60. package/dist/document-tools/index.js.map +1 -1
  61. package/dist/index.cjs +12692 -9494
  62. package/dist/index.cjs.map +1 -1
  63. package/dist/{index.d-DfCFKora.d.cts → index.d-Bvp6rKNo.d.cts} +139 -1
  64. package/dist/{index.d-DfCFKora.d.ts → index.d-Bvp6rKNo.d.ts} +139 -1
  65. package/dist/{index.d-DCjYj7YK.d.ts → index.d-Dx9sGkW2.d.cts} +20 -8
  66. package/dist/{index.d-DCjYj7YK.d.cts → index.d-Dx9sGkW2.d.ts} +20 -8
  67. package/dist/index.d.cts +5465 -2291
  68. package/dist/index.d.ts +5465 -2291
  69. package/dist/index.js +11047 -8858
  70. package/dist/index.js.map +1 -1
  71. package/dist/query-keys.d-Kw0JMoff.d.cts +308 -0
  72. package/dist/query-keys.d-Kw0JMoff.d.ts +308 -0
  73. package/dist/shell/index.cjs +78 -21
  74. package/dist/shell/index.d.cts +1 -1
  75. package/dist/shell/index.d.ts +1 -1
  76. package/dist/shell/index.js +6 -1
  77. package/dist/ui/index.cjs +200 -195
  78. package/dist/ui/index.d.cts +1 -1
  79. package/dist/ui/index.d.ts +1 -1
  80. package/dist/ui/index.js +4 -3
  81. package/dist/useAudioRecorder.d-CWFDsb_S.d.cts +778 -0
  82. package/dist/useAudioRecorder.d-CWFDsb_S.d.ts +778 -0
  83. package/dist/viewers/index.cjs +2 -2
  84. package/dist/viewers/index.js +1 -1
  85. package/package.json +13 -3
  86. package/dist/chunk-6MTKKT2O.cjs +0 -999
  87. package/dist/chunk-6MTKKT2O.cjs.map +0 -1
  88. package/dist/chunk-CEZCFQ47.js +0 -932
  89. package/dist/chunk-CEZCFQ47.js.map +0 -1
  90. package/dist/chunk-D66JCVBB.cjs.map +0 -1
  91. package/dist/chunk-EUC2BTNS.cjs.map +0 -1
  92. package/dist/chunk-GTJ667CP.cjs.map +0 -1
  93. package/dist/chunk-I5ZBQ63Y.js.map +0 -1
  94. package/dist/chunk-JSSKEXRR.js.map +0 -1
  95. package/dist/chunk-ON4PL6DQ.cjs.map +0 -1
  96. package/dist/chunk-QJHCVQ6C.js.map +0 -1
  97. package/dist/chunk-SVHGCX25.js.map +0 -1
@@ -1,932 +0,0 @@
1
- import { parseVersionRef } from './chunk-NNWMHMEC.js';
2
- import { useArbi } from './chunk-JSSKEXRR.js';
3
- import { useMemo, useRef, useEffect, useCallback, useSyncExternalStore } from 'react';
4
- import { useQuery, useMutation, useQueryClient, useInfiniteQuery, useQueries } from '@tanstack/react-query';
5
- import { create } from 'zustand';
6
- import { tags } from '@arbidocs/sdk/browser';
7
-
8
- // src/usage-metered.ts
9
- function isUsageMetered(usage, subscription) {
10
- const empty = usage.total_spend === 0 && usage.total_tokens === 0 && usage.total_requests === 0;
11
- return !(empty && subscription === "dev");
12
- }
13
- var arbiQueryKeys = {
14
- workspaces: () => ["arbi", "workspaces"],
15
- /** Every workspace's member list: what a workspace switch drops. */
16
- allWorkspaceUsers: () => ["arbi", "workspaceUsers"],
17
- workspaceUsers: (workspaceId) => ["arbi", "workspaceUsers", workspaceId],
18
- /** Every workspace's documents list: the prefix a write patches when it does not know the workspace. */
19
- allDocuments: () => ["arbi", "documents"],
20
- documents: (workspaceId) => ["arbi", "documents", workspaceId],
21
- /** One document (a viewer's); writes keep it current next to the list. */
22
- document: (docId) => ["arbi", "document", docId],
23
- documentsById: (docIds) => ["arbi", "documentsById", [...docIds].sort().join(",")],
24
- /** Every workspace's near-duplicate pairs. */
25
- allSimilarDocuments: () => ["arbi", "similarDocuments"],
26
- similarDocuments: (workspaceId, threshold) => ["arbi", "similarDocuments", workspaceId, threshold],
27
- /** Every version list: the prefix a new version invalidates. */
28
- allDocumentVersions: () => ["arbi", "documentVersions"],
29
- documentVersions: (docId) => ["arbi", "documentVersions", docId],
30
- conversations: (workspaceId) => ["arbi", "conversations", workspaceId],
31
- /** Every workspace's conversation list (and threads): the prefix a conversation write invalidates. */
32
- allConversations: () => ["arbi", "conversations"],
33
- conversationThreads: (workspaceId, conversationId) => ["arbi", "conversations", workspaceId, "threads", conversationId],
34
- /** Every workspace's tags (lists, tables and kinds): what a cross-workspace change refreshes. */
35
- allTags: () => ["arbi", "tags"],
36
- tags: (workspaceId) => ["arbi", "tags", workspaceId],
37
- /** Under the workspace's tags: the kinds' fields (refreshed with the tags). */
38
- tagKinds: (workspaceId) => ["arbi", "tags", workspaceId, "kinds"],
39
- /** Every filtered list (a table of tags): what a tag write refreshes, the whole list aside. */
40
- tagLists: (workspaceId) => ["arbi", "tags", workspaceId, "list"],
41
- /** Under the workspace's tags: a tag, doctag or fact write that invalidates `tags` refreshes it. */
42
- tagList: (workspaceId, query) => ["arbi", "tags", workspaceId, "list", query],
43
- /** A kind's fields, under the workspace's tags. */
44
- tagKind: (workspaceId, kind) => ["arbi", "tags", workspaceId, "kind", kind],
45
- /** A task's history, under the conversations prefix: every conversation write refreshes it. */
46
- conversationActivity: (conversationId) => ["arbi", "conversations", conversationId, "activity"],
47
- /** Under the conversations prefix: every step action or conversation write refreshes it. */
48
- conversationUsage: (conversationId) => ["arbi", "conversations", conversationId, "usage"],
49
- thumbnails: (docIds) => ["arbi", "thumbnails", [...docIds].sort().join(",")],
50
- /** Every stage of a document's parsed content. */
51
- parsedDocument: (docId) => ["arbi", "parsedDoc", docId],
52
- parsedDoc: (docId, stage) => ["arbi", "parsedDoc", docId, stage],
53
- agents: () => ["arbi", "agents"],
54
- sessions: () => ["arbi", "sessions"],
55
- health: () => ["arbi", "health"],
56
- workflows: () => ["arbi", "workflows"],
57
- /** Under `workflows()`: a workflow write or run refreshes its runs too. */
58
- workflowRuns: (workflowId) => ["arbi", "workflows", workflowId, "runs"],
59
- /** Every workspace's facts: the prefix a fact write invalidates. */
60
- allFacts: () => ["arbi", "facts"],
61
- facts: (workspaceId) => ["arbi", "facts", workspaceId],
62
- configs: () => ["arbi", "configs"],
63
- activity: () => ["arbi", "activity"],
64
- /** A workspace's activity feed (all its pages). */
65
- workspaceActivity: (workspaceId) => ["arbi", "workspaceActivity", workspaceId],
66
- projects: () => ["arbi", "projects"],
67
- /** A filtered project list, under `projects()`. */
68
- projectsFiltered: (stage, leadUser) => ["arbi", "projects", "list", stage ?? "", leadUser ?? ""],
69
- /** Under `projects()`: a project update refreshes its events too. */
70
- projectEvents: (projectExtId) => ["arbi", "projects", projectExtId, "events"],
71
- projectUsage: (projectExtId, monthsBack) => ["arbi", "projectUsage", projectExtId, monthsBack],
72
- projectConversationUsage: (projectExtId, monthsBack) => ["arbi", "projectUsage", projectExtId, "byConversation", monthsBack],
73
- projectInvoices: (projectExtId) => ["arbi", "projectInvoices", projectExtId],
74
- /** The plans and add-ons on sale. */
75
- products: () => ["arbi", "products"],
76
- /** Prices of a purchase or a change (quotes, previews); nothing is bought. */
77
- billingQuotes: () => ["arbi", "billingQuote"],
78
- userUsageToday: () => ["arbi", "userUsageToday"],
79
- currentUser: () => ["arbi", "currentUser"],
80
- firmPool: () => ["arbi", "firmPool"],
81
- contacts: () => ["arbi", "contacts"],
82
- /** Every chat query (the list and each open thread). */
83
- chats: () => ["arbi", "chats"],
84
- /** My chats, raw (titles and last messages are ciphertext), most recently active first. */
85
- chatList: () => ["arbi", "chats", "list"],
86
- /** One thread's loaded messages, decrypted, oldest first (`ChatThreadData`). */
87
- chatThread: (chatExtId) => ["arbi", "chats", "thread", chatExtId],
88
- /** My own agent's progress on my last message to it (`agent_dm_status`), per agent. */
89
- agentDmStatus: (agentExtId) => ["arbi", "chats", "agentStatus", agentExtId],
90
- /** The paid features this person may use (`/v1/user/entitlements`). */
91
- entitlements: () => ["arbi", "entitlements"],
92
- skills: () => ["arbi", "skills"],
93
- /** A skill's main file (SKILL.md), as text. */
94
- skillSource: (docExtId) => ["arbi", "skills", "source", docExtId],
95
- /** An agent's pinned config; `undefined` = the library default config. */
96
- agentConfig: (agentExtId) => ["arbi", "agentConfig", agentExtId ?? "default"],
97
- agentWorkspaces: (agentExtId) => ["arbi", "agentWorkspaces", agentExtId],
98
- /** An agent's own login, polled while its controls are open. */
99
- agentSession: (agentExtId) => ["arbi", "agentSession", agentExtId],
100
- agentChats: (agentExtId) => ["arbi", "agentChats", agentExtId],
101
- authorizeLimits: () => ["arbi", "authorizeLimits"],
102
- mcpTools: () => ["arbi", "mcpTools"],
103
- models: () => ["arbi", "models"],
104
- availableModels: () => ["arbi", "availableModels"],
105
- /** The signed-in user's own profile (name, picture, email). */
106
- profile: () => ["arbi", "profile"],
107
- identity: () => ["arbi", "identity"],
108
- /** The signed-in user's settings record (notification preferences, flags). */
109
- userSettings: () => ["arbi", "userSettings"],
110
- /** Every notification list: the prefix a delete, a read receipt or an arrival invalidates. */
111
- allNotifications: () => ["arbi", "notifications"],
112
- /** The newest `limit` notifications, received and sent. */
113
- notifications: (limit) => ["arbi", "notifications", limit],
114
- /** The documents a workspace may use as its Word house template. */
115
- houseTemplateCandidates: (workspaceId) => ["arbi", "houseTemplateCandidates", workspaceId]
116
- };
117
- var arbiMutationKeys = {
118
- /** A member's role changed. */
119
- setWorkspaceMemberRoles: () => ["arbi", "workspaces", "roles"],
120
- runWorkflow: () => ["arbi", "workflows", "run"],
121
- updateTagKindSchema: () => ["arbi", "tags", "kinds", "update"],
122
- createTag: () => ["arbi", "tags", "create"],
123
- updateTag: () => ["arbi", "tags", "update"],
124
- deleteTag: () => ["arbi", "tags", "delete"],
125
- extractEntities: () => ["arbi", "tags", "entities", "extract"],
126
- updateDocuments: () => ["arbi", "documents", "update"],
127
- deleteDocuments: () => ["arbi", "documents", "delete"],
128
- uploadDocuments: () => ["arbi", "documents", "upload"],
129
- uploadUrls: () => ["arbi", "documents", "uploadUrls"],
130
- assignDocTags: () => ["arbi", "doctags", "assign"],
131
- removeDocTags: () => ["arbi", "doctags", "remove"],
132
- updateDocTag: () => ["arbi", "doctags", "update"],
133
- generateDocTags: () => ["arbi", "doctags", "generate"],
134
- /** Members added to or removed from a workspace (leaving included). */
135
- workspaceMembership: () => ["arbi", "workspaces", "members"]
136
- };
137
- function useWorkspaces(options) {
138
- const arbi = useArbi();
139
- return useQuery({
140
- queryKey: arbiQueryKeys.workspaces(),
141
- queryFn: () => arbi.workspaces.list(),
142
- enabled: options?.enabled ?? arbi.isLoggedIn
143
- });
144
- }
145
- function useDocumentVersionList(docId, options) {
146
- const arbi = useArbi();
147
- return useQuery({
148
- queryKey: arbiQueryKeys.documentVersions(docId ?? ""),
149
- queryFn: () => arbi.documents.versions(docId),
150
- enabled: (options?.enabled ?? true) && !!docId && arbi.hasWorkspace
151
- });
152
- }
153
- function useConversations(workspaceId, options) {
154
- const arbi = useArbi();
155
- return useQuery({
156
- queryKey: arbiQueryKeys.conversations(workspaceId ?? ""),
157
- queryFn: () => arbi.conversations.list(),
158
- enabled: (options?.enabled ?? true) && !!workspaceId && arbi.hasWorkspace,
159
- refetchInterval: options?.live ? (query) => query.state.data?.some((conversation) => conversation.status === "generating") ? 3e3 : 15e3 : false
160
- });
161
- }
162
- function useConversationThreads(workspaceId, conversationId, options) {
163
- const arbi = useArbi();
164
- return useQuery({
165
- queryKey: arbiQueryKeys.conversationThreads(workspaceId ?? "", conversationId ?? ""),
166
- queryFn: () => arbi.conversations.getThreads(conversationId),
167
- enabled: (options?.enabled ?? true) && !!workspaceId && !!conversationId && arbi.hasWorkspace,
168
- gcTime: 0,
169
- refetchInterval: options?.live ? 3e3 : false
170
- });
171
- }
172
- var tagListKey = (query) => [
173
- query.kind ? `kind:${query.kind}` : "",
174
- query.parentId ? `parent:${query.parentId}` : "",
175
- query.ids?.length ? `ids:${query.ids.join(",")}` : "",
176
- query.include?.length ? `include:${query.include.join(",")}` : "",
177
- query.linksLimit !== void 0 ? `links:${query.linksLimit}` : ""
178
- ].filter(Boolean).join("|");
179
- function useTags(workspaceId, options) {
180
- const arbi = useArbi();
181
- const { enabled, ...query } = options ?? {};
182
- const workspace = workspaceId ?? (arbi.hasWorkspace ? arbi.getWorkspaceId() : "");
183
- const key = tagListKey(query);
184
- return useQuery({
185
- queryKey: key ? arbiQueryKeys.tagList(workspace, key) : arbiQueryKeys.tags(workspace),
186
- queryFn: () => arbi.tags.list(key ? query : void 0),
187
- enabled: (enabled ?? true) && !!workspace && arbi.hasWorkspace && (query.ids === void 0 || query.ids.length > 0),
188
- ...key ? {} : { staleTime: Infinity }
189
- });
190
- }
191
- function useThumbnails(docIds, options) {
192
- const arbi = useArbi();
193
- return useQuery({
194
- queryKey: arbiQueryKeys.thumbnails(docIds),
195
- queryFn: () => arbi.documents.getThumbnails(docIds),
196
- enabled: (options?.enabled ?? true) && docIds.length > 0 && arbi.hasWorkspace,
197
- staleTime: 5 * 6e4
198
- });
199
- }
200
- function useParsedDocument(docId, stage = "final", options) {
201
- const arbi = useArbi();
202
- return useQuery({
203
- queryKey: arbiQueryKeys.parsedDoc(docId ?? "", stage),
204
- queryFn: () => {
205
- const { docId: id, version } = parseVersionRef(docId);
206
- return arbi.documents.getParsedContent(
207
- id,
208
- stage,
209
- version ?? void 0
210
- );
211
- },
212
- enabled: (options?.enabled ?? true) && !!docId && arbi.hasWorkspace
213
- });
214
- }
215
- function useAssistantQuery() {
216
- const arbi = useArbi();
217
- return useMutation({
218
- mutationFn: ({ question, ...options }) => arbi.assistant.query(question, options)
219
- });
220
- }
221
- function useAgents(options) {
222
- const arbi = useArbi();
223
- return useQuery({
224
- queryKey: arbiQueryKeys.agents(),
225
- queryFn: () => arbi.agents.list(),
226
- enabled: (options?.enabled ?? true) && arbi.isLoggedIn
227
- });
228
- }
229
- function useDeleteAgents() {
230
- const arbi = useArbi();
231
- const qc = useQueryClient();
232
- return useMutation({
233
- mutationFn: ({ agentExtIds }) => arbi.agents.delete(agentExtIds),
234
- onSuccess: (_result, { agentExtIds }) => {
235
- for (const id of agentExtIds) {
236
- qc.removeQueries({ queryKey: arbiQueryKeys.agentConfig(id) });
237
- qc.removeQueries({ queryKey: arbiQueryKeys.agentWorkspaces(id) });
238
- }
239
- return Promise.all([
240
- qc.invalidateQueries({ queryKey: arbiQueryKeys.agents() }),
241
- qc.invalidateQueries({ queryKey: arbiQueryKeys.workflows() }),
242
- qc.invalidateQueries({ queryKey: arbiQueryKeys.allConversations() }),
243
- qc.invalidateQueries({ queryKey: arbiQueryKeys.configs() })
244
- ]);
245
- }
246
- });
247
- }
248
- function useHealth(options) {
249
- const arbi = useArbi();
250
- return useQuery({
251
- queryKey: arbiQueryKeys.health(),
252
- queryFn: () => arbi.health.check(),
253
- enabled: options?.enabled
254
- });
255
- }
256
- function useAvailableModels(options) {
257
- const arbi = useArbi();
258
- return useQuery({
259
- queryKey: arbiQueryKeys.availableModels(),
260
- queryFn: () => arbi.health.models(),
261
- staleTime: Infinity,
262
- enabled: (options?.enabled ?? true) && arbi.isLoggedIn
263
- });
264
- }
265
- function useConfigs(options) {
266
- const arbi = useArbi();
267
- return useQuery({
268
- queryKey: arbiQueryKeys.configs(),
269
- queryFn: () => arbi.agentConfig.list(),
270
- enabled: options?.enabled ?? arbi.isLoggedIn
271
- });
272
- }
273
- function useActivity(options) {
274
- const arbi = useArbi();
275
- return useQuery({
276
- queryKey: arbiQueryKeys.activity(),
277
- queryFn: () => arbi.dm.listActivity({ limit: options?.limit, offset: options?.offset }),
278
- enabled: options?.enabled ?? arbi.isLoggedIn
279
- });
280
- }
281
- function useWorkspaceActivity(workspaceId, options) {
282
- const arbi = useArbi();
283
- return useInfiniteQuery({
284
- queryKey: arbiQueryKeys.workspaceActivity(workspaceId ?? ""),
285
- queryFn: async ({ pageParam }) => {
286
- await options?.beforeFetch?.();
287
- return arbi.workspaces.activity(workspaceId, {
288
- cursor: pageParam,
289
- limit: options?.limit
290
- });
291
- },
292
- initialPageParam: null,
293
- getNextPageParam: (page) => page.next_cursor ?? void 0,
294
- enabled: (options?.enabled ?? true) && !!workspaceId && arbi.isLoggedIn
295
- });
296
- }
297
- function useProjects(options) {
298
- const arbi = useArbi();
299
- return useQuery({
300
- queryKey: arbiQueryKeys.projects(),
301
- queryFn: () => arbi.projects.list(),
302
- enabled: options?.enabled ?? arbi.isLoggedIn
303
- });
304
- }
305
- function useProjectUsage(projectExtId, monthsBack = 0, options) {
306
- const arbi = useArbi();
307
- const usage = useQuery({
308
- queryKey: arbiQueryKeys.projectUsage(projectExtId ?? "", monthsBack),
309
- queryFn: () => arbi.projects.usage(projectExtId, monthsBack),
310
- enabled: (options?.enabled ?? true) && !!projectExtId && arbi.isLoggedIn
311
- });
312
- const projects = useProjects({ enabled: !!projectExtId && (options?.enabled ?? true) });
313
- const subscription = projects.data?.find((p) => p.external_id === projectExtId)?.subscription;
314
- const metered = usage.data ? isUsageMetered(usage.data, subscription) : void 0;
315
- return { ...usage, metered };
316
- }
317
- function useProjectsUsage(projectExtIds, monthsBack = 0, options) {
318
- const arbi = useArbi();
319
- const enabled = (options?.enabled ?? true) && arbi.isLoggedIn;
320
- const projects = useProjects({ enabled: enabled && projectExtIds.length > 0 });
321
- const results = useQueries({
322
- queries: projectExtIds.map((id) => ({
323
- queryKey: arbiQueryKeys.projectUsage(id, monthsBack),
324
- queryFn: () => arbi.projects.usage(id, monthsBack),
325
- enabled: enabled && !!id
326
- }))
327
- });
328
- const signature = results.map((r) => `${r.status}:${r.dataUpdatedAt ?? 0}`).join("|") + `#${projects.dataUpdatedAt}`;
329
- return useMemo(() => {
330
- const dailyMap = /* @__PURE__ */ new Map();
331
- const modelMap = /* @__PURE__ */ new Map();
332
- let totalGbp = 0;
333
- let anyData = false;
334
- let anyMetered = false;
335
- let totalTokens = 0;
336
- let totalRequests = 0;
337
- results.forEach((r, i) => {
338
- const d = r.data;
339
- if (!d) return;
340
- anyData = true;
341
- const subscription = projects.data?.find(
342
- (p) => p.external_id === projectExtIds[i]
343
- )?.subscription;
344
- if (isUsageMetered(d, subscription)) anyMetered = true;
345
- totalGbp += d.total_spend ?? 0;
346
- totalTokens += d.total_tokens ?? 0;
347
- totalRequests += d.total_requests ?? 0;
348
- for (const day of d.daily ?? []) {
349
- const cur = dailyMap.get(day.date) ?? {
350
- date: day.date,
351
- gbp: 0,
352
- totalTokens: 0,
353
- apiRequests: 0
354
- };
355
- cur.gbp += day.spend ?? 0;
356
- cur.totalTokens += day.total_tokens ?? 0;
357
- cur.apiRequests += day.api_requests ?? 0;
358
- dailyMap.set(day.date, cur);
359
- }
360
- for (const [model, mg] of Object.entries(d.model_groups ?? {})) {
361
- const cur = modelMap.get(model) ?? {
362
- model,
363
- gbp: 0,
364
- totalTokens: 0,
365
- promptTokens: 0,
366
- completionTokens: 0,
367
- successfulRequests: 0
368
- };
369
- cur.gbp += mg.spend ?? 0;
370
- cur.totalTokens += mg.total_tokens ?? 0;
371
- cur.promptTokens += mg.prompt_tokens ?? 0;
372
- cur.completionTokens += mg.completion_tokens ?? 0;
373
- cur.successfulRequests += mg.successful_requests ?? 0;
374
- modelMap.set(model, cur);
375
- }
376
- });
377
- return {
378
- totalGbp,
379
- totalTokens,
380
- totalRequests,
381
- daily: [...dailyMap.values()].sort((a, b) => a.date.localeCompare(b.date)),
382
- modelGroups: [...modelMap.values()].sort(
383
- (a, b) => b.gbp - a.gbp || b.totalTokens - a.totalTokens
384
- ),
385
- metered: !anyData || anyMetered,
386
- isLoading: results.some((r) => r.isLoading),
387
- isError: results.some((r) => r.isError)
388
- };
389
- }, [signature]);
390
- }
391
- function useProjectInvoices(projectExtId, options) {
392
- const arbi = useArbi();
393
- return useQuery({
394
- queryKey: arbiQueryKeys.projectInvoices(projectExtId ?? ""),
395
- queryFn: () => arbi.projects.invoices(projectExtId),
396
- enabled: (options?.enabled ?? true) && !!projectExtId && arbi.isLoggedIn
397
- });
398
- }
399
- function useCurrentUser(options) {
400
- const arbi = useArbi();
401
- return useQuery({
402
- queryKey: arbiQueryKeys.currentUser(),
403
- queryFn: () => arbi.user.me(),
404
- enabled: options?.enabled ?? arbi.isLoggedIn,
405
- refetchOnWindowFocus: true,
406
- staleTime: 3e4
407
- });
408
- }
409
- function useFirmPool(options) {
410
- const arbi = useArbi();
411
- return useQuery({
412
- queryKey: arbiQueryKeys.firmPool(),
413
- queryFn: () => arbi.firm.pool(),
414
- enabled: options?.enabled ?? arbi.isLoggedIn,
415
- retry: false,
416
- refetchOnWindowFocus: true,
417
- staleTime: 6e4
418
- });
419
- }
420
- function useTopUpFirmPool() {
421
- const arbi = useArbi();
422
- const queryClient = useQueryClient();
423
- return useMutation({
424
- mutationFn: (aiAddons) => arbi.firm.topUp(aiAddons),
425
- onSuccess: (result) => {
426
- queryClient.setQueryData(arbiQueryKeys.firmPool(), result.pool);
427
- }
428
- });
429
- }
430
- var PROJECT_CREATION_DENIED_REASON = "Only members of your firm can create projects and workspaces.";
431
- function useCanCreateProjects() {
432
- const user = useCurrentUser();
433
- const { data: workspaces } = useWorkspaces({ enabled: user.isSuccess });
434
- const membership = workspaces?.map((w) => w.external_id).join(",");
435
- const { refetch } = user;
436
- const seen = useRef(void 0);
437
- useEffect(() => {
438
- if (membership === void 0 || membership === seen.current) return;
439
- const first = seen.current === void 0;
440
- seen.current = membership;
441
- if (!first) void refetch();
442
- }, [membership, refetch]);
443
- return user.data?.can_create_projects;
444
- }
445
- function useUserUsageToday(options) {
446
- const arbi = useArbi();
447
- return useQuery({
448
- queryKey: arbiQueryKeys.userUsageToday(),
449
- queryFn: () => arbi.user.usageToday(),
450
- enabled: (options?.enabled ?? true) && arbi.isLoggedIn,
451
- refetchOnWindowFocus: true,
452
- refetchOnMount: "always",
453
- staleTime: 15e3
454
- });
455
- }
456
-
457
- // src/documents/documents-cache.ts
458
- var rowListeners = /* @__PURE__ */ new Set();
459
- function subscribeDocumentRows(listener) {
460
- rowListeners.add(listener);
461
- return () => {
462
- rowListeners.delete(listener);
463
- };
464
- }
465
- function getCachedDocuments(qc, workspaceId) {
466
- if (!workspaceId) return void 0;
467
- return qc.getQueryData(arbiQueryKeys.documents(workspaceId));
468
- }
469
- function cachedLists(qc) {
470
- return qc.getQueriesData({ queryKey: arbiQueryKeys.allDocuments() }).flatMap(
471
- ([key, data]) => typeof key[2] === "string" && Array.isArray(data) ? [[key[2], data]] : []
472
- );
473
- }
474
- function diffRows(workspaceId, before, after) {
475
- const beforeById = new Map(before.map((doc) => [doc.external_id, doc]));
476
- const add = [];
477
- const update2 = [];
478
- const seen = /* @__PURE__ */ new Set();
479
- for (const doc of after) {
480
- seen.add(doc.external_id);
481
- const previous = beforeById.get(doc.external_id);
482
- if (!previous) add.push(doc);
483
- else if (previous !== doc) update2.push(doc);
484
- }
485
- const remove = [...beforeById.keys()].filter((id) => !seen.has(id));
486
- return { workspaceId, add, update: update2, remove };
487
- }
488
- function patchDocuments(qc, reducer, workspaceId) {
489
- const lists = workspaceId ? (() => {
490
- const current = getCachedDocuments(qc, workspaceId);
491
- return current ? [[workspaceId, current]] : [];
492
- })() : cachedLists(qc);
493
- for (const [id, before] of lists) {
494
- const after = reducer(before);
495
- if (after === before) continue;
496
- qc.setQueryData(arbiQueryKeys.documents(id), after);
497
- const change = diffRows(id, before, after);
498
- const beforeById = new Map(before.map((doc) => [doc.external_id, doc]));
499
- if (change.update.some(
500
- (doc) => doc.current_version !== beforeById.get(doc.external_id)?.current_version
501
- ))
502
- void qc.invalidateQueries({ queryKey: arbiQueryKeys.allDocumentVersions() });
503
- if (change.add.length || change.update.length || change.remove.length)
504
- for (const listener of rowListeners) listener(change);
505
- }
506
- }
507
- function upsertDocuments(qc, documents, workspaceId) {
508
- if (!documents.length) return;
509
- const byId = new Map(documents.map((doc) => [doc.external_id, doc]));
510
- const byWorkspace = /* @__PURE__ */ new Map();
511
- for (const doc of documents) {
512
- const ws = workspaceId ?? doc.workspace_ext_id;
513
- byWorkspace.set(ws, [...byWorkspace.get(ws) ?? [], doc]);
514
- }
515
- for (const [ws, incoming] of byWorkspace) {
516
- patchDocuments(
517
- qc,
518
- (old) => {
519
- const known = new Set(old.map((doc) => doc.external_id));
520
- return [
521
- ...old.map((doc) => byId.get(doc.external_id) ?? doc),
522
- ...incoming.filter((doc) => !known.has(doc.external_id))
523
- ];
524
- },
525
- ws
526
- );
527
- }
528
- }
529
- function setCachedDocument(qc, doc) {
530
- qc.setQueryData(arbiQueryKeys.document(doc.external_id), doc);
531
- }
532
- function patchCachedDocument(qc, docId, reducer) {
533
- const current = qc.getQueryData(arbiQueryKeys.document(docId));
534
- if (current) qc.setQueryData(arbiQueryKeys.document(docId), reducer(current));
535
- }
536
- function dropTagFromCachedDocuments(qc, tagId) {
537
- const strip = (doc) => {
538
- const doctags = doc.doctags?.filter((dt) => dt.tag_ext_id !== tagId);
539
- return doctags && doctags.length !== doc.doctags?.length ? { ...doc, doctags } : doc;
540
- };
541
- const carriers = [];
542
- patchDocuments(qc, (docs) => {
543
- const next = docs.map(strip);
544
- next.forEach((doc, i) => doc !== docs[i] && carriers.push(doc.external_id));
545
- return carriers.length ? next : docs;
546
- });
547
- for (const id of carriers) patchCachedDocument(qc, id, strip);
548
- }
549
- function forgetDocuments(qc, docIds) {
550
- for (const id of docIds) {
551
- qc.removeQueries({ queryKey: arbiQueryKeys.document(id) });
552
- qc.removeQueries({ queryKey: arbiQueryKeys.documentVersions(id) });
553
- qc.removeQueries({ queryKey: arbiQueryKeys.parsedDocument(id) });
554
- }
555
- }
556
- var useEntityExtractionStore = create(() => ({ docIds: [] }));
557
- function update(docIds, running) {
558
- if (!docIds.length) return;
559
- useEntityExtractionStore.setState((state) => {
560
- const ids = new Set(state.docIds);
561
- docIds.forEach((id) => running ? ids.add(id) : ids.delete(id));
562
- return { docIds: [...ids] };
563
- });
564
- }
565
- function startEntityExtraction(docIds) {
566
- update(docIds, true);
567
- }
568
- function finishEntityExtraction(docIds) {
569
- update(docIds, false);
570
- }
571
- function useEntityExtractionDocIds() {
572
- return useEntityExtractionStore((state) => state.docIds);
573
- }
574
- function openWorkspaceId(arbi) {
575
- return arbi.hasWorkspace ? arbi.getWorkspaceId() : null;
576
- }
577
- function patchWorkspaceTags(qc, workspaceId, reducer) {
578
- const key = arbiQueryKeys.tags(workspaceId);
579
- const current = qc.getQueryData(key);
580
- if (!current) return;
581
- const next = reducer(current);
582
- if (next !== current) qc.setQueryData(key, next);
583
- }
584
- function invalidateTagTables(qc, workspaceId) {
585
- return qc.invalidateQueries({ queryKey: arbiQueryKeys.tagLists(workspaceId) });
586
- }
587
- function invalidateTagData(qc, workspaceId) {
588
- return Promise.all([
589
- qc.invalidateQueries({ queryKey: arbiQueryKeys.tags(workspaceId) }),
590
- qc.invalidateQueries({ queryKey: arbiQueryKeys.facts(workspaceId) })
591
- ]);
592
- }
593
- function useInvalidateTagData() {
594
- const arbi = useArbi();
595
- const qc = useQueryClient();
596
- return useCallback(() => {
597
- const workspaceId = openWorkspaceId(arbi);
598
- return workspaceId ? invalidateTagData(qc, workspaceId) : Promise.resolve();
599
- }, [arbi, qc]);
600
- }
601
- function settleCreatedTag(qc, created) {
602
- const workspaceId = created.workspace_ext_id;
603
- patchWorkspaceTags(
604
- qc,
605
- workspaceId,
606
- (old) => old.some((t) => t.external_id === created.external_id) ? old : [...old, created]
607
- );
608
- return invalidateTagTables(qc, workspaceId);
609
- }
610
- function settleChangedTag(qc, tag) {
611
- const workspaceId = tag.workspace_ext_id;
612
- patchWorkspaceTags(
613
- qc,
614
- workspaceId,
615
- (old) => old.map((t) => t.external_id === tag.external_id ? { ...t, ...tag } : t)
616
- );
617
- return invalidateTagTables(qc, workspaceId);
618
- }
619
- var replayableTagMutations = [
620
- {
621
- mutationKey: arbiMutationKeys.createTag(),
622
- run: (client, input) => tags.createTag(client, input),
623
- settle: (qc, created) => settleCreatedTag(qc, created)
624
- }
625
- ];
626
- function useCreateTag() {
627
- const arbi = useArbi();
628
- const qc = useQueryClient();
629
- return useMutation({
630
- mutationKey: arbiMutationKeys.createTag(),
631
- mutationFn: (input) => arbi.tags.create(input),
632
- onSuccess: (created) => settleCreatedTag(qc, created)
633
- });
634
- }
635
- function useIsCreatingTag() {
636
- const qc = useQueryClient();
637
- return useCallback(
638
- (name) => {
639
- const wanted = name.trim().toLowerCase();
640
- return qc.getMutationCache().findAll({
641
- mutationKey: arbiMutationKeys.createTag(),
642
- predicate: (m) => m.state.status === "pending" && m.state.variables?.name.trim().toLowerCase() === wanted
643
- }).length > 0;
644
- },
645
- [qc]
646
- );
647
- }
648
- function useUpdateTag() {
649
- const arbi = useArbi();
650
- const qc = useQueryClient();
651
- return useMutation({
652
- mutationKey: arbiMutationKeys.updateTag(),
653
- mutationFn: ({ tagId, change }) => arbi.tags.update(tagId, change),
654
- onSuccess: (tag) => settleChangedTag(qc, tag)
655
- });
656
- }
657
- function useSetTagValues() {
658
- const arbi = useArbi();
659
- const qc = useQueryClient();
660
- return useMutation({
661
- mutationKey: arbiMutationKeys.updateTag(),
662
- mutationFn: ({
663
- tagId,
664
- values
665
- }) => arbi.tags.setValues(tagId, values),
666
- onSuccess: (tag) => settleChangedTag(qc, tag)
667
- });
668
- }
669
- function useDeleteTag() {
670
- const arbi = useArbi();
671
- const qc = useQueryClient();
672
- return useMutation({
673
- mutationKey: arbiMutationKeys.deleteTag(),
674
- mutationFn: (tagId) => arbi.tags.delete(tagId),
675
- onSuccess: (_data, tagId) => {
676
- dropTagFromCachedDocuments(qc, tagId);
677
- const workspaceId = openWorkspaceId(arbi);
678
- if (!workspaceId) return;
679
- patchWorkspaceTags(
680
- qc,
681
- workspaceId,
682
- (old) => old.filter((t) => t.external_id !== tagId).map((t) => t.parent_ext_id === tagId ? { ...t, parent_ext_id: null } : t)
683
- );
684
- return Promise.all([
685
- invalidateTagTables(qc, workspaceId),
686
- qc.invalidateQueries({ queryKey: arbiQueryKeys.facts(workspaceId) })
687
- ]);
688
- }
689
- });
690
- }
691
- function useExtractEntities() {
692
- const arbi = useArbi();
693
- return useMutation({
694
- mutationKey: arbiMutationKeys.extractEntities(),
695
- mutationFn: (docIds) => arbi.tags.extractEntities(docIds),
696
- onSuccess: (data) => startEntityExtraction(data.doc_ext_ids)
697
- });
698
- }
699
- function useTagKindSchema(kind, options) {
700
- const arbi = useArbi();
701
- const workspaceId = openWorkspaceId(arbi) ?? "";
702
- return useQuery({
703
- queryKey: arbiQueryKeys.tagKind(workspaceId, kind ?? ""),
704
- queryFn: () => arbi.tagKinds.get(kind),
705
- enabled: (options?.enabled ?? true) && !!kind && !!workspaceId
706
- });
707
- }
708
- function useUpdateTagKindSchema() {
709
- const arbi = useArbi();
710
- const qc = useQueryClient();
711
- return useMutation({
712
- mutationKey: arbiMutationKeys.updateTagKindSchema(),
713
- mutationFn: ({
714
- kind,
715
- fields
716
- }) => arbi.tagKinds.update(kind, fields),
717
- onSuccess: (schema) => {
718
- const workspaceId = openWorkspaceId(arbi);
719
- if (!workspaceId) return;
720
- qc.setQueryData(arbiQueryKeys.tagKind(workspaceId, schema.kind), schema);
721
- return invalidateTagData(qc, workspaceId);
722
- }
723
- });
724
- }
725
- var DOCUMENTS_FIRST_PAGE_SIZE = 500;
726
- var DOCUMENTS_PAGE_SIZE = 2e3;
727
- var DOCUMENTS_FIRST_PAGE_MEASURE = "arbi:document-list:page1";
728
- var FIRST_PAGE_MEASURE = DOCUMENTS_FIRST_PAGE_MEASURE;
729
- var FIRST_PAGE_START = "arbi:document-list:start";
730
- function mark(name) {
731
- try {
732
- performance.mark(name);
733
- } catch {
734
- }
735
- }
736
- function measure(name, start) {
737
- try {
738
- performance.measure(name, start);
739
- } catch {
740
- }
741
- }
742
- var backgroundReads = /* @__PURE__ */ new Map();
743
- var loadingListeners = /* @__PURE__ */ new Set();
744
- function emitLoading() {
745
- for (const listener of loadingListeners) listener();
746
- }
747
- function subscribeLoading(listener) {
748
- loadingListeners.add(listener);
749
- return () => {
750
- loadingListeners.delete(listener);
751
- };
752
- }
753
- function isDocumentsLoading() {
754
- return backgroundReads.size > 0;
755
- }
756
- function useDocumentsLoading() {
757
- return useSyncExternalStore(subscribeLoading, isDocumentsLoading, () => false);
758
- }
759
- function stopDocumentsLoading(workspaceId) {
760
- const controller = backgroundReads.get(workspaceId);
761
- if (!controller) return;
762
- controller.abort();
763
- backgroundReads.delete(workspaceId);
764
- emitLoading();
765
- }
766
- async function loadDocuments(qc, arbi, workspaceId, signal) {
767
- let stopped = false;
768
- for (const [id, controller2] of backgroundReads) {
769
- if (id === workspaceId) continue;
770
- controller2.abort();
771
- backgroundReads.delete(id);
772
- stopped = true;
773
- }
774
- if (stopped) emitLoading();
775
- const controller = new AbortController();
776
- signal?.addEventListener("abort", () => controller.abort(), { once: true });
777
- const pages = arbi.documents.listPaginated({
778
- pageSize: DOCUMENTS_PAGE_SIZE,
779
- firstPageSize: DOCUMENTS_FIRST_PAGE_SIZE,
780
- signal: controller.signal
781
- });
782
- mark(FIRST_PAGE_START);
783
- const first = await pages.next();
784
- const firstPage = first.done ? [] : first.value;
785
- measure(FIRST_PAGE_MEASURE, FIRST_PAGE_START);
786
- if (first.done || firstPage.length < DOCUMENTS_FIRST_PAGE_SIZE) return firstPage;
787
- if (backgroundReads.has(workspaceId)) {
788
- controller.abort();
789
- return firstPage;
790
- }
791
- backgroundReads.set(workspaceId, controller);
792
- emitLoading();
793
- void appendRemainingPages(qc, workspaceId, pages, controller.signal).finally(() => {
794
- if (backgroundReads.get(workspaceId) !== controller) return;
795
- backgroundReads.delete(workspaceId);
796
- emitLoading();
797
- });
798
- return firstPage;
799
- }
800
- async function appendRemainingPages(qc, workspaceId, pages, signal) {
801
- await Promise.resolve();
802
- try {
803
- for await (const page of pages) {
804
- if (signal.aborted) return;
805
- patchDocuments(
806
- qc,
807
- (old) => {
808
- const known = new Set(old.map((doc) => doc.external_id));
809
- const fresh = page.filter((doc) => !known.has(doc.external_id));
810
- return fresh.length ? [...old, ...fresh] : old;
811
- },
812
- workspaceId
813
- );
814
- }
815
- } catch (error) {
816
- if (!signal.aborted) console.error(`Reading the documents of ${workspaceId} failed:`, error);
817
- }
818
- }
819
- var FINISHED_DOCUMENT_STATUSES = /* @__PURE__ */ new Set([
820
- "completed",
821
- "low-content",
822
- "failed",
823
- "skipped",
824
- "empty"
825
- ]);
826
- function openWorkspaceId2(arbi) {
827
- return arbi.hasWorkspace ? arbi.getWorkspaceId() : null;
828
- }
829
- function useDocuments(workspaceId, options) {
830
- const arbi = useArbi();
831
- const qc = useQueryClient();
832
- const workspace = workspaceId ?? openWorkspaceId2(arbi) ?? "";
833
- return useQuery({
834
- queryKey: arbiQueryKeys.documents(workspace),
835
- queryFn: ({ signal }) => {
836
- if (openWorkspaceId2(arbi) !== workspace)
837
- return Promise.reject(new Error("The selected workspace changed."));
838
- return loadDocuments(qc, arbi, workspace, signal);
839
- },
840
- enabled: (options?.enabled ?? true) && !!workspace && arbi.hasWorkspace,
841
- staleTime: Infinity,
842
- refetchOnMount: false,
843
- refetchOnReconnect: false,
844
- refetchOnWindowFocus: false
845
- });
846
- }
847
- var DOCUMENT_STATUS_POLL_MS = 4e3;
848
- function processingInterval(doc) {
849
- return doc?.status && !FINISHED_DOCUMENT_STATUSES.has(doc.status) ? DOCUMENT_STATUS_POLL_MS : false;
850
- }
851
- function useDocument(docId, options) {
852
- const arbi = useArbi();
853
- return useQuery({
854
- queryKey: arbiQueryKeys.document(docId ?? ""),
855
- queryFn: async () => (await arbi.documents.get([docId]))[0] ?? null,
856
- enabled: (options?.enabled ?? true) && !!docId && arbi.isLoggedIn,
857
- refetchInterval: options?.pollWhileProcessing ? (query) => processingInterval(query.state.data) : false
858
- });
859
- }
860
- function useDocumentsById(docIds, options) {
861
- const arbi = useArbi();
862
- return useQuery({
863
- queryKey: arbiQueryKeys.documentsById(docIds),
864
- queryFn: () => arbi.documents.get(docIds),
865
- enabled: (options?.enabled ?? true) && docIds.length > 0 && arbi.isLoggedIn
866
- });
867
- }
868
- var SIMILARITY_THRESHOLD = 0.98;
869
- function useSimilarDocuments(options) {
870
- const arbi = useArbi();
871
- const workspace = openWorkspaceId2(arbi) ?? "";
872
- return useQuery({
873
- queryKey: arbiQueryKeys.similarDocuments(workspace, SIMILARITY_THRESHOLD),
874
- queryFn: () => arbi.documents.similar({ threshold: SIMILARITY_THRESHOLD }),
875
- enabled: (options?.enabled ?? true) && !!workspace
876
- });
877
- }
878
- var readSeq = 0;
879
- var latestReadByDoc = /* @__PURE__ */ new Map();
880
- async function refreshDocuments(qc, arbi, docIds, options) {
881
- if (!docIds.length) return [];
882
- const seq = ++readSeq;
883
- for (const id of docIds) latestReadByDoc.set(id, seq);
884
- try {
885
- const read = await arbi.documents.get(docIds);
886
- const fresh = read.filter((doc) => latestReadByDoc.get(doc.external_id) === seq).map((doc) => {
887
- const live = options?.processingStatus?.(doc.external_id);
888
- return live && FINISHED_DOCUMENT_STATUSES.has(live) && doc.status !== live ? { ...doc, status: live } : doc;
889
- });
890
- if (!fresh.length) return [];
891
- reconcileTagCounts(qc, fresh);
892
- upsertDocuments(qc, fresh);
893
- for (const doc of fresh) setCachedDocument(qc, doc);
894
- return fresh;
895
- } catch (error) {
896
- console.error("Re-reading documents failed; the cached ones are kept:", error);
897
- return [];
898
- } finally {
899
- for (const id of docIds) if (latestReadByDoc.get(id) === seq) latestReadByDoc.delete(id);
900
- }
901
- }
902
- function reconcileTagCounts(qc, fresh) {
903
- const byWorkspace = /* @__PURE__ */ new Map();
904
- for (const doc of fresh) {
905
- const cached = getCachedDocuments(qc, doc.workspace_ext_id)?.find(
906
- (d) => d.external_id === doc.external_id
907
- );
908
- const before = new Set((cached?.doctags ?? []).map((dt) => dt.tag_ext_id));
909
- const after = new Set((doc.doctags ?? []).map((dt) => dt.tag_ext_id));
910
- const delta = byWorkspace.get(doc.workspace_ext_id) ?? /* @__PURE__ */ new Map();
911
- for (const id of after) if (!before.has(id)) delta.set(id, (delta.get(id) ?? 0) + 1);
912
- for (const id of before) if (!after.has(id)) delta.set(id, (delta.get(id) ?? 0) - 1);
913
- byWorkspace.set(doc.workspace_ext_id, delta);
914
- }
915
- for (const [workspaceId, delta] of byWorkspace) adjustTagCounts(qc, workspaceId, delta);
916
- }
917
- function adjustTagCounts(qc, workspaceId, delta) {
918
- if (![...delta.values()].some(Boolean)) return;
919
- patchWorkspaceTags(
920
- qc,
921
- workspaceId,
922
- (tags) => tags.map((tag) => {
923
- const change = delta.get(tag.external_id);
924
- return change ? { ...tag, doctag_count: Math.max(0, tag.doctag_count + change) } : tag;
925
- })
926
- );
927
- void invalidateTagTables(qc, workspaceId);
928
- }
929
-
930
- export { DOCUMENTS_FIRST_PAGE_MEASURE, DOCUMENTS_FIRST_PAGE_SIZE, DOCUMENTS_PAGE_SIZE, FINISHED_DOCUMENT_STATUSES, PROJECT_CREATION_DENIED_REASON, SIMILARITY_THRESHOLD, adjustTagCounts, arbiMutationKeys, arbiQueryKeys, dropTagFromCachedDocuments, finishEntityExtraction, forgetDocuments, getCachedDocuments, invalidateTagData, invalidateTagTables, isDocumentsLoading, isUsageMetered, patchCachedDocument, patchDocuments, patchWorkspaceTags, refreshDocuments, replayableTagMutations, setCachedDocument, startEntityExtraction, stopDocumentsLoading, subscribeDocumentRows, upsertDocuments, useActivity, useAgents, useAssistantQuery, useAvailableModels, useCanCreateProjects, useConfigs, useConversationThreads, useConversations, useCreateTag, useCurrentUser, useDeleteAgents, useDeleteTag, useDocument, useDocumentVersionList, useDocuments, useDocumentsById, useDocumentsLoading, useEntityExtractionDocIds, useExtractEntities, useFirmPool, useHealth, useInvalidateTagData, useIsCreatingTag, useParsedDocument, useProjectInvoices, useProjectUsage, useProjects, useProjectsUsage, useSetTagValues, useSimilarDocuments, useTagKindSchema, useTags, useThumbnails, useTopUpFirmPool, useUpdateTag, useUpdateTagKindSchema, useUserUsageToday, useWorkspaceActivity, useWorkspaces };
931
- //# sourceMappingURL=chunk-CEZCFQ47.js.map
932
- //# sourceMappingURL=chunk-CEZCFQ47.js.map