@arbidocs/react 0.5.138 → 0.5.139

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.
package/dist/index.d.ts CHANGED
@@ -4161,6 +4161,11 @@ interface ArbiWsState {
4161
4161
  * document was dismissed a moment ago. Resolves whether it was taken.
4162
4162
  */
4163
4163
  applyTaskUpdate: (msg: WsTaskUpdateMessage) => boolean;
4164
+ /**
4165
+ * Take several `task_update`s in one write (one notification of the store's subscribers), each
4166
+ * as {@link applyTaskUpdate} would. Resolves the ones taken, in order.
4167
+ */
4168
+ applyTaskUpdates: (messages: WsTaskUpdateMessage[]) => WsTaskUpdateMessage[];
4164
4169
  /** Set a document's live processing directly (an optimistic status, or an undo). */
4165
4170
  putTask: (task: LiveTask) => void;
4166
4171
  /** Drop a document's processing row, and ignore its late updates for a while. */
@@ -15227,19 +15232,25 @@ declare function subscribeDocumentReads(qc: QueryClient, onRows: (rows: Workspac
15227
15232
  * A workspace's documents in processing, live: what every site's file views show while uploads
15228
15233
  * and re-processing run.
15229
15234
  *
15230
- * - `applyTaskEvent` (the provider runs it on each taken `task_update`): an upload appears as a
15231
- * row the moment it is queued (a light placeholder, so the table and the gallery show it with
15232
- * its live progress), and a finished document replaces its row with the one read afresh.
15235
+ * - `applyTaskEvents` (the provider runs it on the `task_update`s it took, a few times a second):
15236
+ * an upload appears as a row the moment it is queued (a light placeholder, so the table and the
15237
+ * gallery show it with its live progress), and a finished document replaces its row with the one
15238
+ * read afresh. A burst is one write to each list and one read of the finished documents.
15233
15239
  * - `useWorkspaceProcessing(workspaceId)`: the workspace's processing rows and their counts
15234
15240
  * (a snapshot every half second, so a batch upload does not re-render on every event), kept
15235
15241
  * honest: stale or orphaned rows are dropped when the workspace opens, rows a document read says
15236
15242
  * finished are settled, and the in-flight ones are re-checked when the connection comes back.
15237
15243
  */
15238
15244
 
15239
- /** Apply one taken `task_update` to the documents list (`me`: who uploads, i.e. this user). */
15240
- declare function applyTaskEvent(queryClient: QueryClient, arbi: Arbi, message: WsTaskUpdateMessage & {
15245
+ type TaskEvent = WsTaskUpdateMessage & {
15241
15246
  folder?: string | null;
15242
- }, me: string | null | undefined): void;
15247
+ };
15248
+ /**
15249
+ * Apply taken `task_update`s to the documents lists (`me`: who uploads, i.e. this user): the
15250
+ * finished documents are re-read (together, see `queueDocumentReads`), the others not yet listed
15251
+ * join their list as placeholder rows, in one write per list.
15252
+ */
15253
+ declare function applyTaskEvents(queryClient: QueryClient, arbi: Arbi, messages: TaskEvent[], me: string | null | undefined): void;
15243
15254
  /** The workspace's processing rows (in the order of their document ids) and their counts. */
15244
15255
  interface WorkspaceProcessing {
15245
15256
  tasks: Record<string, LiveTask>;
@@ -15920,15 +15931,6 @@ declare function VideoCapture({ onSave, onDiscard, onError, isSaving }: VideoCap
15920
15931
  */
15921
15932
  declare function hasVideoTrack(blob: Blob): Promise<boolean>;
15922
15933
 
15923
- /**
15924
- * Upload chosen files to the open workspace, with progress. Files go in batches (one per folder
15925
- * they land in, at most 100 files each, four at a time); each file keeps the folder it sat in below
15926
- * where the upload started. All the batches are one upload set: the person is told once, when every
15927
- * file of it is processed (the server's `upload_set_complete` notification), not once per batch.
15928
- * With direct upload on in the user's settings, and the workspace key
15929
- * held here, files are encrypted here and sent straight to storage; otherwise through the server.
15930
- * The new documents join their list in their folder; the labels asked for fill their AI fields.
15931
- */
15932
15934
  interface UploadFilesInput {
15933
15935
  files: File[];
15934
15936
  /** Upload to this member workspace instead of the currently open workspace. */
@@ -15958,6 +15960,11 @@ interface UploadFilesResult {
15958
15960
  file_name: string;
15959
15961
  reason: string;
15960
15962
  }[];
15963
+ /**
15964
+ * The follow-up after the files were sent: the new rows re-read into their lists, the workspace
15965
+ * counts refreshed and the AI fields started. Never rejects.
15966
+ */
15967
+ settled: Promise<void>;
15961
15968
  }
15962
15969
  /** The folder an upload put `docId` in, while its row has not been read yet. */
15963
15970
  declare function uploadedDocumentFolder(workspaceId: string, docId: string): string | null | undefined;
@@ -16312,4 +16319,4 @@ declare function useRateSupportTicket(): _tanstack_react_query.UseMutationResult
16312
16319
  rating: SupportRating;
16313
16320
  }, unknown>;
16314
16321
 
16315
- export { AGENT_CONTROL_COMMANDS, AGGREGATE_FIELDS, ALLOWED_PORTAL_ORIGINS, ANALYTICS_CHART_VIEW, ARCHIVE_POLL_MS, ASSISTANT_MENTION_LABEL, AUDIO_MIME_PREFERENCE, AUTO_CHAT_MODEL, AUTO_SYNC_EVERY_MS, type AccessRequestPayload, type AccessRequestRecipient, type AccountClient, type AccountClientContextValue, type AccountHost, type AccountSession, type AccountSignOutOptions, ActiveCall, type ActivityContent, type ActivityDescription, ActivityFeed, type ActivityFeedProps, type ActivitySourceLabels, type AddWorkspaceMembersRequest, type AgentAccessMode, type AgentConfigSections, type AgentControlMaps, AgentDmStatus, type AgentQuestionRef, type AgentRunControlState, type AggregateOp, AiAnswer, type AiRunOptions, type AiTaskStatus, type AnalyticsChartRequest, AppNotification, AppleIcon, type ApplyCallEventOptions, ArbiBotHeadIcon, type ArbiChatActions, type ArbiChatCitation, type ArbiChatDocument, type ArbiChatHost, type ArbiChatMessage, type ArbiChatMessageStatus, type ArbiChatPassage, type ArbiChatRole, type ArbiChatState, type ArbiChatStore, type ArbiChatStoreOptions, type ArbiChatThread, type ArbiConversation, type ArbiConversationDocument, type ArbiConversationGeneration, type ArbiDmTab, type ArbiDocumentCommentTarget, type ArbiDocumentSessionActions, type ArbiDocumentSessionState, type ArbiDocumentSessionStore, type ArbiDocumentSessionStoreOptions, type ArbiDocumentViewerState, type ArbiDocumentsPersist, type ArbiDraftDocument, type ArbiDraftKind, type ArbiDraftStorage, type ArbiFeature, type ArbiFeatures, type ArbiGridLayoutState, ArbiHost, type ArbiHostConfig, ArbiHostConnection, ArbiHostProps, type ArbiKeyValueStorage, type ArbiLayoutActions, type ArbiLayoutState, type ArbiLayoutStore, type ArbiLayoutStoreOptions, type ArbiMessageTimer, type ArbiPanelMode, type ArbiPanelsState, type ArbiPassageCitationState, type ArbiPickedPassage, type ArbiQueryClient, type ArbiQueryClientOptions, type ArbiQueryPersistOptions, type ArbiSavedChat, type ArbiSavedDocuments, type ArbiSavedLayout, type ArbiSessionParts, type ArbiSessionPersist, type ArbiSessionState, type ArbiSessionStatus, type ArbiSessionStore, type ArbiSessionStoreOptions, type ArbiShellState, type ArbiSidebarState, type ArbiSignedInSession, type ArbiTabsState, type ArbiThreadComposer, type ArbiThreadTab, type ArbiThreadTabShow, type ArbiThreadTabView, type ArbiThreadTabsController, type ArbiThreadTabsState, type ArbiThreadView, type ArbiViewerTab, type ArbiViewingDocument, type ArbiViewingDocumentInput, type ArbiViewsState, ArbiWebSocketProvider, type ArbiWebSocketProviderProps, type ArbiWorkspaceState, type ArbiWorkspaceStatus, type ArbiWorkspaceStorage, type ArbiWorkspaceStore, type ArbiWorkspaceStoreOptions, type ArbiWsHandlers, type ArbiWsState, type ArbiWsStatus, ArtifactCanvas, type AskAgain, type AspectOption, type AssignDocTagsInput, type AssistantMode, AudIcon, type AudioPiece, type AvatarCrop, type AvatarFileProblem, BOOT_GATE_TIMEOUT_MS, BOX_SEAT_REFUSED, BOX_SEAT_REFUSED_ACTION, BOX_SEAT_REFUSED_TITLE, BUILTIN_DATA_SOURCES, type BranchNavigation, type BranchPoint, type BrowserWorkspaceStorageOptions, type BuildArchiveInput, type BuiltArchive, CALL_MODERATION_TOPIC, CONVERSATION_SWITCH_MEASURE, type CalendarConnectorSupport, type CalendarNotificationMeta, type CalendarOfflineSupport, type CalendarPendingWrite, type CalendarSupport, type CalendarWriteOp, type CallInviteContact, type CallMutedNotice, type CallRoomEvents, type CallSlotMode, type CallsHost, type ChartSpec, type ChartType, type ChatArrival, ChatBubble, type ChatBubbleProps, ChatMemberKey, type ChatPost, ChatResponse, type ChatSummary, ChatThreadMessage, type Chunk, type ChunkActivation, type ChunkedRecorder, type ChunkedRecorderOptions, CitationRenderer, type CitationRendererProps, type CitationState, ClaudeIcon, type ConfigUpdate, type ControllingAgent, type ConversationActionsInput, type ConversationEvent, ConversationList, type ConversationListProps, ConversationScope, type ConversationScopeProps, type ConversationsSourceLabels, type CreateProjectVars, type CreateSkillPackOptions, type CreateTagInput, type CreateWorkspaceVars, type CreatedProject, type CropArea, type CropOutput, type CropResult, type CurrentWorkspace, DATABASE_RELATION_PICK_LIMIT, DATABASE_ROWS_PAGE, DEFAULT_ACTIVITY_SOURCE_LABELS, DEFAULT_ASPECT_OPTIONS, DEFAULT_CONVERSATIONS_SOURCE_LABELS, DEFAULT_DATABASE_SOURCE_LABELS, DEFAULT_DOCUMENTS_SOURCE_LABELS, DEFAULT_DOCUMENT_VIEWER_STATE, DEFAULT_FACTS_SOURCE_LABELS, DEFAULT_PASSWORD_CHANGE_FORM_MESSAGES, DEFAULT_PROJECTS_SOURCE_LABELS, DEFAULT_TAGS_SOURCE_LABELS, DEFAULT_USAGE_BREAKDOWN_SOURCE_LABELS, DEFAULT_USAGE_SOURCE_LABELS, DEFAULT_WORKFLOWS_SOURCE_LABELS, DEFAULT_WORKSPACES_SOURCE_LABELS, DISMISSED_TASK_TTL_MS, DOCUMENTS_FIRST_PAGE_MEASURE, DOCUMENTS_FIRST_PAGE_SIZE, DOCUMENTS_PAGE_SIZE, DOCUMENT_VIEWER_PANEL, type DashboardSpec, type DashboardStore, type DashboardsHost, type DataSource, type DataSourceFieldsState, type DataSourceOption, type DataSourceParam, type DataSourceParams, type DataSourceRef, type DataSourceRegistry, type DatabaseAggregateRequest, type DatabaseAggregateResult, type DatabaseDashboardStoreOptions, type DatabaseSourceLabels, type Dataset, type DatasetField, type DatasetFieldType, type DatasetFilter, type DatasetOrder, type DatasetQuery, type DatasetRow, type DatasetSort, type DatasetState, type DatasetValue, DateSeparator, type DateSeparatorProps, type DebouncedWriter, type DebouncedWriterOptions, type DefineSkillPackOptions, type DefinedSkillPack, type DeleteAccountBlocker, type DeleteAccountFlow, type DeletedDocument, type DeletedDocumentsPage, type DescribeCalendarNotificationOptions, type DescribeServerNotificationOptions, DictateContextValue, DmAvatar, type DmAvatarProps, type DmClassNames, DmComposer, type DmComposerProps, type DmConversation, type DmMessage, type DmUser, DocIcon, type DocumentHostActions, type DocumentPerson, DocumentReview, type DocumentReviewProps, type DocumentRowChange, type DocumentStartItem, type DocumentsSourceLabels, type DocumentsSupport, type DraftKeyValueStore, DraftTitleControls, type DraftTitleControlsProps, EMPTY_CHAT_STATE, EMPTY_DOCUMENT_STATE, EMPTY_GROUP_LABEL, EMPTY_SESSION_STATE, EXPORT_SAMPLE_RATE, type EmailChange, type EmailPreferences, EmlIcon, type EnableDriveSyncVars, type EnableMailboxSyncVars, type EntitledFeature, EntityIconComponent, EntitySize, EntityVocabulary, type ExportDownloadRequest, type ExportFileKind, type ExtractedZip, FACTS_SEARCH_VIEW, FILE_TYPE_COLORS, FINISHED_DOCUMENT_STATUSES, FIRST_TOKEN_MEASURE, type FactListFilter, type FactSearchHit, type FactsSearch, type FactsSearchState, type FactsSourceLabels, type FeatureEntitlements, type FeatureRefusal, type FeatureSource, type FeatureSwitch, type FilterOp, FireworksIcon, type FollowSaveCallbacks, GeminiIcon, type GenerateDocTagsInput, GitHubIcon, GoogleIcon, type GrantAgentAccessVars, type GuidedStep, HostConfigRecord, HtmlIcon, IN_FLIGHT_DOCUMENT_STATUSES, IdentityPurchase, IdentityStatus, IdentityStep, type IdentityVerificationApi, IdentityVerificationFlow, ImageCropModal, type ImageCropModalProps, ImageCropper, type ImageCropperProps, ImgIcon, IncomingCall, InlineMicButton, type InlineMicButtonProps, type InstallSkillPackVariables, JoinChoices, LIVE_UPDATE_TYPES, LinkedInIcon, type LiveTask, type LocalDraft, type LocalFeatureStore, type LocalFeatureStoreOptions, MAIL_DRAFT_REPLACED_EVENT, MAX_AVATAR_FILE_BYTES, MAX_DASHBOARD_SPEC_CHARS, MAX_SERIES, MAX_THREAD_TABS, MIN_NARRATION_DWELL_MS, MIN_QUEUED_MESSAGE_VISIBILITY_MS, MODEL_GROUP_LABELS, MUTED_DEDUPE_MS, type MailAccount, type MailAddress, type MailAttachment, type MailChange, type MailClient, type MailClientContextValue, type MailCompose, type MailConversation, type MailConversationPage, type MailDeliveryRecipient, type MailDeliveryStatus, type MailDeviceFallback, type MailDraftEditorRequest, type MailDraftEditorSession, type MailFetch, type MailFileRequest, type MailFiled, type MailFilingRule, type MailFilingState, type MailFolder, type MailHost, type MailMessage, type MailMessageUpdate, MailOfflineUnavailableError, type MailPage, type MailPolicy, type MailProject, type MailThread, MeetingChatRef, MeetingChatTarget, MentionCandidate, type MessageArtifact, MessageArtifactCard, MessageMentionRef, type MessageTimerResult, MicRecordingOverlay, type MicRecordingOverlayProps, MicWaveformIndicator, type MicWaveformIndicatorProps, type ModeratedTrack, type MountDiditOptions, type NameEditor, type NativeMailFiling, type NotificationPreferencesModel, type NotificationTarget, type NotificationTypeMeta, NotifyVariant, OUTBOX_FOLDER, type OfflineDocumentRecord, type OfflineMailReadsOptions, type OfflineMailRuntimeOptions, type OfflineMailScope, type OfflineMailSettings, type OfflineMailStatus, OpenAIIcon, type OpenedRecording, type OptimisticDocumentEdit, type OrderResolver, type OutboxItem, PENDING_SYNC_PREDICATE, PLAYBACK_LOOKAHEAD_MS, POLL_EVERY_MS, PROJECT_CREATION_DENIED_REASON, type PanelDatasetState, type PanelSpec, type ParsedChunk, type ParsedChunkMetadata, type ParsedDocument, type ParsedDocumentMetadata, type PassageResolvers, type PasswordChangeForm, type PasswordChangeFormMessages, type PasswordChangeVars, PdfIcon, type PendingMailChange, type PendingSyncItem, type PeopleDirectory, type Person, PhotoCapture, type PhotoCaptureProps, PresIcon, type ProcessingTask, type ProfileView, type ProjectCreationRefusal, type ProjectsSourceLabels, type ProjectsSourceOptions, type QueuedCalendarWrite, type QueuedMessage, type QueuedMessages, type QuoteResolver, RECORDING_SEGMENTER, REMOTE_CONTROL_VIEW, RUN_WINDOW_MS, type RawPending, type ReconnectOutcome, type RecordedChunk, type RecordingWindow, type RefusedUploadFile, type RelatedDocs, type RelatedDocsMap, type RelevancePatch, type RemoteControlMessage, type RemoteControlRequest, type RemoteControlSession, type RemoteControlState, type RemoveDocTagsInput, type RenderMarkdown, type RequestAccessOptions, type RowsSourceDefinition, type RowsState, SEGMENT_FRAME_MS, SEGMENT_PRE_ROLL_MS, SHORT_PIECE_MERGE_GAP_MS, SIGNATURE_NOTIFICATION_TYPES, SIMILARITY_THRESHOLD, SLOW_AFTER_MS, STILL_WORKING, type SaveAgentConfigVars, type SavedDashboard, type SealedDraftStorageOptions, type SearchMode, SearchSession, SearchStatus, SegmenterConfig, type SemanticSearch, type SemanticSearchOptions, type SendMessageOptions, type SequencedRow, type SequencedTask, type ServerNotificationBellOptions, type ServerNotificationDescription, type ShellRecentWorkspaceItem, type ShellWorkspaceItem, type ShellWorkspaceKind, type ShellWorkspaceMember, type ShellWorkspaceSeed, type ShellWorkspaceSource, type SignatureNotificationType, type SkillPack, type SkillPackEntry, type SkillPackField, type SkillPackSkill, type SkillPackSkillDefinition, type StartTaskQuery, StorageActionError, type StorageActions, type StorageDeploymentUsage, type StorageItem, type StorageItemKind, type StorageItemState, type StorageItemsQuery, type StorageKindUsage, type StoragePersistOptions, type StorageProjectUsage, type StorageScope, type StorageSnapshot, type StreamHandlerContext, type StreamHandlerParams, type StreamHandlers, type StreamState, type SwitchWorkspaceTarget, TRANSFER_POLL_MS, type TableView, type TableViewTable, type TagsSourceLabels, TaskThreadPendingError, type ThreadAccessors, ThreadBinding, type ThreadItem, type TimeBucket, type TimelinePart, type ToolResponses, type TrackCutter, type TrackPiece, type TranscriptExportLine, type TranscriptLineRef, type TranscriptSegmentMarker, type TransferConflictPolicy, type TransferKind, type TransferMode, type TransferPlan, type TransferScope, type TransferStatus, type TurnTarget, type TurnTools, TxtIcon, TypingIndicator, UPLOAD_ACCEPT, UPLOAD_MAX_FILE_SIZE, type UiStateStorage, type UnarchiveEstimate, type UpdateDocTagInput, type UpdateDocumentsInput, type UpdateProfileVars, type UploadDocumentsInput, type UploadFilesInput, type UploadFilesProgress, type UploadFilesResult, type UploadFromUrlsInput, type UploadFromUrlsResult, type UploadRefusal, type UploadUrlsInput, type UsageBreakdownBy, type UsageBreakdownKey, type UsageBreakdownSourceLabels, type UsageSourceLabels, type UsageTotals, type UseAskAgainOptions, type UseAvatarCropOptions, type UseCameraStreamResult, type UseConversationOptions, type UseDeleteAccountFlowOptions, type UseDownloadDocumentsOptions, type UseEmailChangeOptions, type UseFactsSearchOptions, type UseIdentityVerificationFlowOptions, type UseMessageTimerOptions, type UseNameEditorOptions, type UsePasswordChangeFormOptions, type UseShellWorkspacesOptions, type UseShellWorkspacesResult, type UseSwitchWorkspaceResult, type UseVideoRecorderResult, type UserResponse, type UserSettingFlag, type UserSettingsPatch, VIDEO_MIME_PREFERENCE, VidIcon, VideoCapture, type VideoCaptureProps, type VideoRecorderState, VoiceNoteRecorder, type VoiceNoteRecorderProps, WORKSPACE_LAST_OPENED_KEY, WORKSPACE_STORAGE_KEY, WORK_NOTIFICATION_LABELS, WORK_OFFLINE_VIEW, type WorkflowsSourceLabels, type WorkspaceArchive, type WorkspaceArchiveState, type WorkspaceDocument, type WorkspaceExport, type WorkspaceMember, type WorkspaceNotificationLevel, type WorkspaceProcessing, type WorkspaceRole, type WorkspaceSwitchContext, type WorkspaceUpdate, type WorkspacesSourceLabels, XlsIcon, type ZipExtractor, __resetPendingFinalCommitsForTests, __resetStreamingTokenBufferForTests, acceptRing, accountPath, addAssistantMessageToCache, addConversationToList, addUserMessageToCache, adjustTagCounts, adoptNewChatDocument, agentControl, aggregateDataset, aliasTakenMessage, allConversationThreads, annotateThread, announceMailDraftReplaced, appendTokenToMessage, applyCallEvent, applyConversationEvent, applyFinalContextToMessage, applyLiveUpdate, applyNotificationRow, applyOptimisticDocumentEdit, applyOutputItemToMessage, applyTaskEvent, arbiAccountClient, arbiMailClient, archiveName, archivedWorkspaceMessage, assistantLabels, bindThreadDocument, boundDocumentOf, browserWorkspaceStorage, bucketOf, bucketRange, buildDocumentMetadataRows, buildMentionCandidates, buildPendingFirstTurn, buildPendingSyncItem, buildWorkspaceArchive, cacheThreadBinding, cachedAssistantMode, cachedMentionCandidates, cachedQuotaUsedUp, calendarNotificationMeta, calendarOfflineSupport, callLink, callNotificationMeta, captureFrameAsBlob, chatTranscriptRef, claimOfflineQueue, classifyMediaError, clearLoadingState, clearSealedDrafts, clearUserInputRequest, clockTime, closePanelIn, commitFinalMessage, completeQueuedUserMessageByContent, composeArbiSessionStore, compositeFiles, compositeTrack, computeOnline, confirmLosingOfflineMail, connectOAuthCalendarAccount, connectorErrorStatus, connectorReturnTo, conversationKey, conversationsPath, createActivitySource, createArbiChatStore, createArbiDocumentSessionStore, createArbiLayoutStore, createArbiQueryClient, createArbiSessionStore, createArbiWorkspaceStore, createBrowserStateStorage, createChunkedRecorder, createConversationsSource, createDataSourceRegistry, createDatabaseSource, createDebouncedWriter, createDocumentsSource, createFactsSource, createLocalFeatureStore, createMailClient, createMemoryDashboardStore, createMutedNotifier, createProjectsSource, createSealedDraftStorage, createSkillPack, createStoragePersist, createStreamHandlers, createTagsSource, createTrackCutter, createUiStateStorage, createUsageBreakdownSource, createUsageSource, createWorkflowsSource, createWorkspaceSwitch, createWorkspacesSource, cropImage, cutAtPauses, dayKey, declineRing, decodeMono16k, defaultLayoutState, defaultMailAlias, defineRowsSource, defineSkillPack, deleteLocalDraft, deleteOutboxItem, deploymentUserMeta, describeActivity, describeCalendarNotification, describeServerNotification, discardStreamingTokensForMessage, disconnectAttachedRun, dmTabId, documentActivityMeta, documentActivityPhrase, documentDisplayName, documentMailAttachment, docxMentionMeta, downloadRecoveryFile, dropTagFromCachedDocuments, encodeWav, enqueueOutbox, ensureAssistantMessageLoading, entitlementRefusal, extensionFor, extractZipFile, fallbackFileName, fetchPart, fileAttachment, fileSafe, filesFromDrop, fillTimeGaps, filterRows, findConversation, finishEntityExtraction, floatToWav, flushDocumentForTurn, flushOnPageExit, flushStreamingTokens, forgetDocuments, forgetUploadedDocumentFolder, formatConfigValidationError, formatElapsed, formatIdentityPrice, formatTranscriptMarkdown, getCachedDocuments, getInterjectionText, getNotificationTypeMeta, getOfflineDocument, getOrphanedLastMessage, getRelatedLabels, getRelatedTotal, getRunStartedAt, getThreadsQueryKey, getWorkspaceActionText, getWorkspaceKind, getWorkspaceSentPhrase, groupMailConversations, hasPendingFinalCommit, hasPendingMailChange, hasRecordingTranscript, hasVideoTrack, identityStepFor, inputRequestTitle, invalidateCalendarEvents, invalidateCalendars, invalidateCall, invalidateConversationActivity, invalidateConversationDetails, invalidateConversationLists, invalidateTagData, invalidateTagTables, isActivityKey, isAliasTakenError, isArchiveMoving, isCommentToPeople, isConversationListKey, isConversationShared, isDeploymentAdmin, isDeploymentUserNotification, isDocumentsLoading, isFullConfig, isMessageRunning, isNetworkFailure, isNotificationRow, isOrphanedUserMessage, isPanelOpen, isQueuedCalendarWrite, isRecordingSegmentId, isReplayableArbiMutation, isRowNewer, isSignatureNotificationType, isStaleTaskUpdate, isTableViewOf, isTransferFinished, isTransferResumable, isUsageMetered, isWorkingOffline, isWorkspaceArchivedError, isWorkspaceGuestOf, isWorkspaceNotificationType, isZipFile, joinFromPreJoin, layoutActionsOf, loadOfflineDocument, loadAttachment as loadOfflineMailAttachment, mailConversationKey, mailDraftIdFromContent, mailJson, mailThreadRoot, markMessageAsFailed, markNarrationSettled, mergeHostConfig, migrateLegacyThreadDocuments, mountDiditVerification, mutedNoticeFromEvent, mutedNoticeFromPacket, mutedNoticeText, nativeThreadKeys, nextAliasSuggestion, nextViewingDocument, notificationUserName, offlineMailReads, onCallEvent, openAccessRequest, openCall, openPanelIn, openRecording, panelPlace, parseActivityContent, parseDashboardSpec, parseDeleteAccountBlockers, parseSavedChat, parseSavedDocuments, parseSavedLayout, partKey, partsDue, patchCachedDocument, patchConversation, patchConversationList, patchDocuments, patchWorkspaceTags, pendingChatModelSave, peopleDirectory, personOfUser, pickRecentWorkspaces, pickRecorderMimeType, playheadAt, postRecordingDocsToThread, postTranscriptToThread, prepareUploadFiles, queryOfChart, queueMailChange, queuedMessages, readLocalFeature, readWorkspaceLastOpened, recordingFiles, recordingWindowsOf, recordsOf, redlineStats, refreshDocuments, refuseChatWhenOffline, registerArbiMutationDefaults, registerAttachedRun, registerDocumentTurnFlush, remoteControlActions, remoteControlStateOf, removeConversationFromLists, removeSettledNarration, requestPersistentStorage, resetCalendarAccountSyncState, resetMessageContent, resolveActiveWorkspace, resolveConfigModel, resolveDocumentStatus, resolveReplyTarget, restoreLayout, restoreSavedDocuments, retryOutboxItem, rollbackOptimisticDocumentEdit, safePortalUrl, saveLocalDraft, saveRecordingFilesToThread, savedChatOf, savedDocumentsOf, savedLayoutOf, schedulePart, selectDraft, selectIsGenerating, selectViewingDocumentId, sendMailFile, serializeDashboardSpec, serverCallsExperimental, serverNotificationBellEntry, setCachedDocument, setMessageContent, setUserInputRequest, setWorkOfflineIn, settledByRows, signatureNotificationPhrase, signatureRequestMeta, skillPackPrompt, sortTranscriptMessages, sortedParts, speakerTracks, speakerWav, splitIntoFiles, standalone, startChatCall, startContactsCall, startDmCall, startEntityExtraction, startThreadCall, startsMediaFile, stopDocumentsLoading, stripSpeakerPrefix, subscribeDocumentReads, subscribeDocumentRows, supersedeLiveTranscript, supersededTranscriptLines, supportsHouseTemplates, textToArtifact, threadBinding, threadEndingAtContains, threadPath, threadTabId, threadTranscriptLines, threadTranscriptRef, timelineDurationMs, timelineOf, titleFromQuestion, toChatCitations, toMailConversation, toNotificationPreferences, toProfileView, toRedlineMarkdown, toRemoteControlRequest, toShellWorkspace, transcribeRecording, transcriptSegmentOf, updateMessageWithMetadata, updateUserMessageInCache, updateUserMessageStateInCache, uploadFolderOf, uploadedDocumentFolder, upsertDocuments, useAccountClient, useActOnStep, useActiveConfigId, useActivity, useAddChatMembers, useAddDatabaseRows, useAddHolidayCalendar, useAddProjectAddonBlock, useAddWorkspaceMembers, useAddonQuote, useAgentChats, useAgentConfig, useAgentDmStatus, useAgentModels, useAgentRunControl, useAgentSession, useAgentWorkspaces, useAgents, useAiTask, useAnswerAgentQuestion, useApplyChatModel, useArbi, useArbiHost, useArbiSession, useArbiSessionState, useArbiSessionStore, useArbiWebSocket, useArbiWsContext, useArbiWsMessage, useArbiWsStatus, useArbiWsStore, useArchiveProgressPolling, useArchiveWorkspace, useAskAgain, useAssignDocTags, useAssistantArrivals, useAssistantBrief, useAssistantQuery, useAssistantStatus, useAuthorizeLimits, useAutoSendDraft, useAvailableModels, useAvatarCrop, useBookingPages, useBootTimeout, useBoxRole, useBranchNavigation, useBuiltinCommands, useCalDavProfiles, useCalendarAccounts, useCalendarEvent, useCalendarEventByUid, useCalendarEvents, useCalendarInvitations, useCalendarOfflineRuntime, useCalendarOutbox, useCalendarOverlays, useCalendarSettings, useCalendarShares, useCalendarSupport, useCalendars, useCall, useCallInviteLinks, useCallRecording, useCallRecordings, useCallTranscriptionAvailable, useCallsConfig, useCallsEnabled, useCameraStream, useCanCreateProjects, useCanCreateWorkspaces, useCanEditShared, useCanHostCalls, useCancelDriveSync, useCancelMailboxSync, useCancelManyPendingSync, useCancelProjectSubscription, useCancelWorkspaceTransfer, useChangeProjectPlan, useChargeWatch, useChatArrivals, useChatPost, useChatSummaries, useChatThread, useChatUnreadTotal, useChats, useClaimNativeAlias, useClaimSecureMail, useCloseAgentSession, useConfig, useConfigSchema, useConfigs, useConfirmEmailChange, useConfirmProjectSpendLimits, useConnectCalDavAccount, useConnectMailAccount, useConnectOAuthAccount, useConnectRunStream, useConnectedMailFiling, useConnectorAutoSync, useConnectorCatalog, useConnectorVendorVisibility, useContacts, useConversation, useConversationActions, useConversationActivity, useConversationData, useConversationDocuments, useConversationIsShared, useConversationItems, useConversationPendingAuth, useConversationSearch, useConversationSettings, useConversationThreads, useConversationTurn, useConversationWorkspace, useConversations, useCreateAgent, useCreateCalendar, useCreateContact, useCreateDatabase, useCreateEvent, useCreateFact, useCreateFacts, useCreateGroupChat, useCreateProject, useCreateProjectCheckout, useCreateRoom, useCreateTag, useCreateWork, useCreateWorkflow, useCreateWorkspace, useCurrentSessionId, useCurrentUser, useCurrentWorkspace, useDashboardStore, useDataSources, useDatabase, useDatabaseAggregate, useDatabaseDashboardStore, useDatabaseRows, useDatabases, useDecideCounter, useDeleteAccount, useDeleteAccountFlow, useDeleteAgents, useDeleteBookingPage, useDeleteCalendar, useDeleteChatMessage, useDeleteConfig, useDeleteContact, useDeleteConversation, useDeleteDashboard, useDeleteDatabase, useDeleteDatabaseRows, useDeleteDocuments, useDeleteEvent, useDeleteFact, useDeleteMessage, useDeleteNotifications, useDeleteProject, useDeleteSkill, useDeleteTag, useDeleteWorkflow, useDeleteWorkspaces, useDeploymentDomain, useDirectModelUsage, useDisconnectCalendarAccount, useDisconnectConnector, useDisconnectMailAccount, useDisconnectSlack, useDismissedTips, useDocument, useDocumentAutoAdd, useDocumentHostActions, useDocumentPendingSync, useDocumentThumbnails, useDocumentVersionList, useDocuments, useDocumentsLoading, useDocumentsSupport, useDownloadDocuments, useDriveFolderChildren, useDriveFolderDocCount, useDriveFolders, useDriveSyncEstimate, useDriveSyncProgress, useEmailChange, useEnableDriveSync, useEnableMailboxSync, useEntitlements, useEntityExtractionDocIds, useExportDatabase, useExtractEntities, useFacts, useFactsSearch, useFeature, useFeatureCheck, useFeatureSwitch, useFetchCalendarEvent, useFileWaitingNativeMail, useFinaliseTranslation, useFindTime, useFlushOutbox, useFollowThread, useFreeBusy, useGenerateAgentAvatar, useGenerateDocTags, useGrantAgentAccess, useHealth, useHolidayCountries, useHouseTemplateCandidates, useIdentityVerification, useIdentityVerificationFlow, useImportCalendar, useImportContacts, useImportDatabase, useImportDatabaseRows, useInstallSkillPack, useInvalidateAfterTransfer, useInvalidateAssistant, useInvalidateEntitlements, useInvalidateProjects, useInvalidateStorage, useInvalidateTagData, useInvalidateWorkflows, useInviteContacts, useIsCreatingTag, useIsEntitled, useIsSlow, useIsWorkspaceOwner, useKeepDocumentsOffline, useLinkContact, useLinkMentions, useLocalDrafts, useMailAccounts, useMailAttachmentText, useMailCache, useMailClient, useMailConversations, useMailDraftCompose, useMailDraftEditor, useMailDraftReplaced, useMailFiling, useMailFolders, useMailMessage, useMailMessages, useMailOnline, useMailPolicy, useMailProjects, useMailThread, useMailUnlock, useMailWorkspacePrimer, useMailboxFolders, useMailboxSyncProgress, useMarkArrivalWrong, useMarkChatRead, useMarkDocumentShared, useMarkMessageDraftSent, useMarkNotificationsRead, useMcpTools, useMeetingReadOnly, useMessageDetails, useMessageTimer, useModelConnections, useMoveEvent, useMoveWorkspaceToProject, useMyConnectors, useNameEditor, useNativeMailFiling, useNativeThreadKeys, useNotificationPreferences, useNotifications, useOfflineDocumentIds, useOfflineMailActive, useOfflineMailRuntime, useOfflineMailSettings, useOfflineMailStatus, useOpenCallMeetingChat, useOpenSelectedWorkspace, useOpenViewerDocumentId, useOutbox, usePanelDataset, useParsedDocument, usePassageQuotes, usePasswordChange, usePasswordChangeForm, usePendingMailChanges, usePendingSyncCounts, usePendingSyncItems, usePeople, usePeopleSearch, usePlanQuote, usePlanWork, usePlanWorkspaceTransfer, usePreviewProjectPlanChange, useProcessingTask, useProcessingTasks, useProducts, useProfile, useProjectBillingCache, useProjectBillingPortal, useProjectConversationUsage, useProjectCreationDenial, useProjectInvoices, useProjectUsage, useProjects, usePublishCalendar, useRateSupportTicket, useReadMailMessage, useReconnect, useRecordingActions, useRecordingWindows, useReferralSummary, useRefreshCalendar, useRefreshConnectorsOnRunEnd, useRefreshDocuments, useRefreshProject, useRelatedDocuments, useRemoteControl, useRemoveChatMember, useRemoveDocTags, useRemoveDocumentsOffline, useRemoveModelConnection, useRemoveWorkspaceMembers, useRenameChat, useRenameFolder, useRequestEmailChange, useRequestWorkspaceAccess, useRespondToEvent, useResumeCalendarAccountConnect, useResumeWorkspaceTransfer, useRevokeAgentAccess, useRevokeCallInviteLink, useRooms, useRunConversation, useRunWorkflow, useSaveAgentConfig, useSaveBookingPage, useSaveCalendarSettings, useSaveConfig, useSaveConfigField, useSaveDashboard, useSaveMailDraft, useSaveModelConnection, useSaveSkill, useSaveToThread, useSavedDashboards, useSearchContacts, useSearchDatabaseRows, useSearchFacts, useSemanticSearch, useSendMail, useServerCallsEnabled, useServerCallsExperimental, useSessionPageTab, useSessionView, useSessions, useSetDeploymentHouseTemplate, useSetNativeMailFiling, useSetSkillVisibility, useSetTagValues, useSetWorkspaceHouseTemplate, useSetWorkspaceMemberRoles, useShareCalendar, useShellWorkspaces, useSignOut, useSignedInSession, useSimilarDocuments, useSkillSource, useSkills, useSlackConnection, useStartAgentSession, useStartCalendarAccountOAuth, useStartTaskQuery, useStartWorkspaceTransfer, useStopMailFilingRule, useStorageActions, useStorageItemNames, useStorageItems, useStorageProjects, useStorageSnapshots, useStreamHandlers, useSubscribeCalendar, useSupportTicket, useSupportTickets, useSwitchWorkspace, useSyncAccountsOnOpen, useSyncCalendarAccount, useSyncOfflineMailbox, useTagKindSchema, useTags, useTerminateSession, useThinkingContent, useThreadDocument, useThumbnails, useTransientView, useTriggerDriveSync, useTriggerMailboxSync, useUnarchiveWorkspace, useUnlockModelConnections, useUnreadByPeer, useUnshareCalendar, useUpdateAssistantBrief, useUpdateCalendar, useUpdateCalendarAccount, useUpdateContact, useUpdateConversation, useUpdateDatabase, useUpdateDatabaseRow, useUpdateDocTag, useUpdateDocuments, useUpdateEvent, useUpdateFact, useUpdateProfile, useUpdateProjectAddonSettings, useUpdateProjectFields, useUpdateProjectNextPeriodAddons, useUpdateTag, useUpdateTagKindSchema, useUpdateUserSettings, useUpdateWorkflow, useUpdateWorkspace, useUploadDocuments, useUploadFiles, useUploadFromUrls, useUploadSkillFiles, useUploadUrls, useUserDashboardStore, useUserSettings, useUserUsageToday, useVideoRecorder, useWorkItems, useWorkOffline, useWorkflowRuns, useWorkflows, useWorkspaceActivity, useWorkspaceArchive, useWorkspaceDocs, useWorkspaceExportDownload, useWorkspaceNotificationLevel, useWorkspaceProcessing, useWorkspaceRole, useWorkspaceTransfer, useWorkspaceTransfers, useWorkspaceTrash, useWorkspaceUsers, useWorkspaces, userDisplayName, userInitials, viewsOfTable, waitForResponseId, wipeCalendarOffline, wipeOfflineDocuments, wipeOfflineMail, withRelativePath, workflowRunTitle, workflowStepOf, workspaceHouseTemplateId, writeSamples };
16322
+ export { AGENT_CONTROL_COMMANDS, AGGREGATE_FIELDS, ALLOWED_PORTAL_ORIGINS, ANALYTICS_CHART_VIEW, ARCHIVE_POLL_MS, ASSISTANT_MENTION_LABEL, AUDIO_MIME_PREFERENCE, AUTO_CHAT_MODEL, AUTO_SYNC_EVERY_MS, type AccessRequestPayload, type AccessRequestRecipient, type AccountClient, type AccountClientContextValue, type AccountHost, type AccountSession, type AccountSignOutOptions, ActiveCall, type ActivityContent, type ActivityDescription, ActivityFeed, type ActivityFeedProps, type ActivitySourceLabels, type AddWorkspaceMembersRequest, type AgentAccessMode, type AgentConfigSections, type AgentControlMaps, AgentDmStatus, type AgentQuestionRef, type AgentRunControlState, type AggregateOp, AiAnswer, type AiRunOptions, type AiTaskStatus, type AnalyticsChartRequest, AppNotification, AppleIcon, type ApplyCallEventOptions, ArbiBotHeadIcon, type ArbiChatActions, type ArbiChatCitation, type ArbiChatDocument, type ArbiChatHost, type ArbiChatMessage, type ArbiChatMessageStatus, type ArbiChatPassage, type ArbiChatRole, type ArbiChatState, type ArbiChatStore, type ArbiChatStoreOptions, type ArbiChatThread, type ArbiConversation, type ArbiConversationDocument, type ArbiConversationGeneration, type ArbiDmTab, type ArbiDocumentCommentTarget, type ArbiDocumentSessionActions, type ArbiDocumentSessionState, type ArbiDocumentSessionStore, type ArbiDocumentSessionStoreOptions, type ArbiDocumentViewerState, type ArbiDocumentsPersist, type ArbiDraftDocument, type ArbiDraftKind, type ArbiDraftStorage, type ArbiFeature, type ArbiFeatures, type ArbiGridLayoutState, ArbiHost, type ArbiHostConfig, ArbiHostConnection, ArbiHostProps, type ArbiKeyValueStorage, type ArbiLayoutActions, type ArbiLayoutState, type ArbiLayoutStore, type ArbiLayoutStoreOptions, type ArbiMessageTimer, type ArbiPanelMode, type ArbiPanelsState, type ArbiPassageCitationState, type ArbiPickedPassage, type ArbiQueryClient, type ArbiQueryClientOptions, type ArbiQueryPersistOptions, type ArbiSavedChat, type ArbiSavedDocuments, type ArbiSavedLayout, type ArbiSessionParts, type ArbiSessionPersist, type ArbiSessionState, type ArbiSessionStatus, type ArbiSessionStore, type ArbiSessionStoreOptions, type ArbiShellState, type ArbiSidebarState, type ArbiSignedInSession, type ArbiTabsState, type ArbiThreadComposer, type ArbiThreadTab, type ArbiThreadTabShow, type ArbiThreadTabView, type ArbiThreadTabsController, type ArbiThreadTabsState, type ArbiThreadView, type ArbiViewerTab, type ArbiViewingDocument, type ArbiViewingDocumentInput, type ArbiViewsState, ArbiWebSocketProvider, type ArbiWebSocketProviderProps, type ArbiWorkspaceState, type ArbiWorkspaceStatus, type ArbiWorkspaceStorage, type ArbiWorkspaceStore, type ArbiWorkspaceStoreOptions, type ArbiWsHandlers, type ArbiWsState, type ArbiWsStatus, ArtifactCanvas, type AskAgain, type AspectOption, type AssignDocTagsInput, type AssistantMode, AudIcon, type AudioPiece, type AvatarCrop, type AvatarFileProblem, BOOT_GATE_TIMEOUT_MS, BOX_SEAT_REFUSED, BOX_SEAT_REFUSED_ACTION, BOX_SEAT_REFUSED_TITLE, BUILTIN_DATA_SOURCES, type BranchNavigation, type BranchPoint, type BrowserWorkspaceStorageOptions, type BuildArchiveInput, type BuiltArchive, CALL_MODERATION_TOPIC, CONVERSATION_SWITCH_MEASURE, type CalendarConnectorSupport, type CalendarNotificationMeta, type CalendarOfflineSupport, type CalendarPendingWrite, type CalendarSupport, type CalendarWriteOp, type CallInviteContact, type CallMutedNotice, type CallRoomEvents, type CallSlotMode, type CallsHost, type ChartSpec, type ChartType, type ChatArrival, ChatBubble, type ChatBubbleProps, ChatMemberKey, type ChatPost, ChatResponse, type ChatSummary, ChatThreadMessage, type Chunk, type ChunkActivation, type ChunkedRecorder, type ChunkedRecorderOptions, CitationRenderer, type CitationRendererProps, type CitationState, ClaudeIcon, type ConfigUpdate, type ControllingAgent, type ConversationActionsInput, type ConversationEvent, ConversationList, type ConversationListProps, ConversationScope, type ConversationScopeProps, type ConversationsSourceLabels, type CreateProjectVars, type CreateSkillPackOptions, type CreateTagInput, type CreateWorkspaceVars, type CreatedProject, type CropArea, type CropOutput, type CropResult, type CurrentWorkspace, DATABASE_RELATION_PICK_LIMIT, DATABASE_ROWS_PAGE, DEFAULT_ACTIVITY_SOURCE_LABELS, DEFAULT_ASPECT_OPTIONS, DEFAULT_CONVERSATIONS_SOURCE_LABELS, DEFAULT_DATABASE_SOURCE_LABELS, DEFAULT_DOCUMENTS_SOURCE_LABELS, DEFAULT_DOCUMENT_VIEWER_STATE, DEFAULT_FACTS_SOURCE_LABELS, DEFAULT_PASSWORD_CHANGE_FORM_MESSAGES, DEFAULT_PROJECTS_SOURCE_LABELS, DEFAULT_TAGS_SOURCE_LABELS, DEFAULT_USAGE_BREAKDOWN_SOURCE_LABELS, DEFAULT_USAGE_SOURCE_LABELS, DEFAULT_WORKFLOWS_SOURCE_LABELS, DEFAULT_WORKSPACES_SOURCE_LABELS, DISMISSED_TASK_TTL_MS, DOCUMENTS_FIRST_PAGE_MEASURE, DOCUMENTS_FIRST_PAGE_SIZE, DOCUMENTS_PAGE_SIZE, DOCUMENT_VIEWER_PANEL, type DashboardSpec, type DashboardStore, type DashboardsHost, type DataSource, type DataSourceFieldsState, type DataSourceOption, type DataSourceParam, type DataSourceParams, type DataSourceRef, type DataSourceRegistry, type DatabaseAggregateRequest, type DatabaseAggregateResult, type DatabaseDashboardStoreOptions, type DatabaseSourceLabels, type Dataset, type DatasetField, type DatasetFieldType, type DatasetFilter, type DatasetOrder, type DatasetQuery, type DatasetRow, type DatasetSort, type DatasetState, type DatasetValue, DateSeparator, type DateSeparatorProps, type DebouncedWriter, type DebouncedWriterOptions, type DefineSkillPackOptions, type DefinedSkillPack, type DeleteAccountBlocker, type DeleteAccountFlow, type DeletedDocument, type DeletedDocumentsPage, type DescribeCalendarNotificationOptions, type DescribeServerNotificationOptions, DictateContextValue, DmAvatar, type DmAvatarProps, type DmClassNames, DmComposer, type DmComposerProps, type DmConversation, type DmMessage, type DmUser, DocIcon, type DocumentHostActions, type DocumentPerson, DocumentReview, type DocumentReviewProps, type DocumentRowChange, type DocumentStartItem, type DocumentsSourceLabels, type DocumentsSupport, type DraftKeyValueStore, DraftTitleControls, type DraftTitleControlsProps, EMPTY_CHAT_STATE, EMPTY_DOCUMENT_STATE, EMPTY_GROUP_LABEL, EMPTY_SESSION_STATE, EXPORT_SAMPLE_RATE, type EmailChange, type EmailPreferences, EmlIcon, type EnableDriveSyncVars, type EnableMailboxSyncVars, type EntitledFeature, EntityIconComponent, EntitySize, EntityVocabulary, type ExportDownloadRequest, type ExportFileKind, type ExtractedZip, FACTS_SEARCH_VIEW, FILE_TYPE_COLORS, FINISHED_DOCUMENT_STATUSES, FIRST_TOKEN_MEASURE, type FactListFilter, type FactSearchHit, type FactsSearch, type FactsSearchState, type FactsSourceLabels, type FeatureEntitlements, type FeatureRefusal, type FeatureSource, type FeatureSwitch, type FilterOp, FireworksIcon, type FollowSaveCallbacks, GeminiIcon, type GenerateDocTagsInput, GitHubIcon, GoogleIcon, type GrantAgentAccessVars, type GuidedStep, HostConfigRecord, HtmlIcon, IN_FLIGHT_DOCUMENT_STATUSES, IdentityPurchase, IdentityStatus, IdentityStep, type IdentityVerificationApi, IdentityVerificationFlow, ImageCropModal, type ImageCropModalProps, ImageCropper, type ImageCropperProps, ImgIcon, IncomingCall, InlineMicButton, type InlineMicButtonProps, type InstallSkillPackVariables, JoinChoices, LIVE_UPDATE_TYPES, LinkedInIcon, type LiveTask, type LocalDraft, type LocalFeatureStore, type LocalFeatureStoreOptions, MAIL_DRAFT_REPLACED_EVENT, MAX_AVATAR_FILE_BYTES, MAX_DASHBOARD_SPEC_CHARS, MAX_SERIES, MAX_THREAD_TABS, MIN_NARRATION_DWELL_MS, MIN_QUEUED_MESSAGE_VISIBILITY_MS, MODEL_GROUP_LABELS, MUTED_DEDUPE_MS, type MailAccount, type MailAddress, type MailAttachment, type MailChange, type MailClient, type MailClientContextValue, type MailCompose, type MailConversation, type MailConversationPage, type MailDeliveryRecipient, type MailDeliveryStatus, type MailDeviceFallback, type MailDraftEditorRequest, type MailDraftEditorSession, type MailFetch, type MailFileRequest, type MailFiled, type MailFilingRule, type MailFilingState, type MailFolder, type MailHost, type MailMessage, type MailMessageUpdate, MailOfflineUnavailableError, type MailPage, type MailPolicy, type MailProject, type MailThread, MeetingChatRef, MeetingChatTarget, MentionCandidate, type MessageArtifact, MessageArtifactCard, MessageMentionRef, type MessageTimerResult, MicRecordingOverlay, type MicRecordingOverlayProps, MicWaveformIndicator, type MicWaveformIndicatorProps, type ModeratedTrack, type MountDiditOptions, type NameEditor, type NativeMailFiling, type NotificationPreferencesModel, type NotificationTarget, type NotificationTypeMeta, NotifyVariant, OUTBOX_FOLDER, type OfflineDocumentRecord, type OfflineMailReadsOptions, type OfflineMailRuntimeOptions, type OfflineMailScope, type OfflineMailSettings, type OfflineMailStatus, OpenAIIcon, type OpenedRecording, type OptimisticDocumentEdit, type OrderResolver, type OutboxItem, PENDING_SYNC_PREDICATE, PLAYBACK_LOOKAHEAD_MS, POLL_EVERY_MS, PROJECT_CREATION_DENIED_REASON, type PanelDatasetState, type PanelSpec, type ParsedChunk, type ParsedChunkMetadata, type ParsedDocument, type ParsedDocumentMetadata, type PassageResolvers, type PasswordChangeForm, type PasswordChangeFormMessages, type PasswordChangeVars, PdfIcon, type PendingMailChange, type PendingSyncItem, type PeopleDirectory, type Person, PhotoCapture, type PhotoCaptureProps, PresIcon, type ProcessingTask, type ProfileView, type ProjectCreationRefusal, type ProjectsSourceLabels, type ProjectsSourceOptions, type QueuedCalendarWrite, type QueuedMessage, type QueuedMessages, type QuoteResolver, RECORDING_SEGMENTER, REMOTE_CONTROL_VIEW, RUN_WINDOW_MS, type RawPending, type ReconnectOutcome, type RecordedChunk, type RecordingWindow, type RefusedUploadFile, type RelatedDocs, type RelatedDocsMap, type RelevancePatch, type RemoteControlMessage, type RemoteControlRequest, type RemoteControlSession, type RemoteControlState, type RemoveDocTagsInput, type RenderMarkdown, type RequestAccessOptions, type RowsSourceDefinition, type RowsState, SEGMENT_FRAME_MS, SEGMENT_PRE_ROLL_MS, SHORT_PIECE_MERGE_GAP_MS, SIGNATURE_NOTIFICATION_TYPES, SIMILARITY_THRESHOLD, SLOW_AFTER_MS, STILL_WORKING, type SaveAgentConfigVars, type SavedDashboard, type SealedDraftStorageOptions, type SearchMode, SearchSession, SearchStatus, SegmenterConfig, type SemanticSearch, type SemanticSearchOptions, type SendMessageOptions, type SequencedRow, type SequencedTask, type ServerNotificationBellOptions, type ServerNotificationDescription, type ShellRecentWorkspaceItem, type ShellWorkspaceItem, type ShellWorkspaceKind, type ShellWorkspaceMember, type ShellWorkspaceSeed, type ShellWorkspaceSource, type SignatureNotificationType, type SkillPack, type SkillPackEntry, type SkillPackField, type SkillPackSkill, type SkillPackSkillDefinition, type StartTaskQuery, StorageActionError, type StorageActions, type StorageDeploymentUsage, type StorageItem, type StorageItemKind, type StorageItemState, type StorageItemsQuery, type StorageKindUsage, type StoragePersistOptions, type StorageProjectUsage, type StorageScope, type StorageSnapshot, type StreamHandlerContext, type StreamHandlerParams, type StreamHandlers, type StreamState, type SwitchWorkspaceTarget, TRANSFER_POLL_MS, type TableView, type TableViewTable, type TagsSourceLabels, TaskThreadPendingError, type ThreadAccessors, ThreadBinding, type ThreadItem, type TimeBucket, type TimelinePart, type ToolResponses, type TrackCutter, type TrackPiece, type TranscriptExportLine, type TranscriptLineRef, type TranscriptSegmentMarker, type TransferConflictPolicy, type TransferKind, type TransferMode, type TransferPlan, type TransferScope, type TransferStatus, type TurnTarget, type TurnTools, TxtIcon, TypingIndicator, UPLOAD_ACCEPT, UPLOAD_MAX_FILE_SIZE, type UiStateStorage, type UnarchiveEstimate, type UpdateDocTagInput, type UpdateDocumentsInput, type UpdateProfileVars, type UploadDocumentsInput, type UploadFilesInput, type UploadFilesProgress, type UploadFilesResult, type UploadFromUrlsInput, type UploadFromUrlsResult, type UploadRefusal, type UploadUrlsInput, type UsageBreakdownBy, type UsageBreakdownKey, type UsageBreakdownSourceLabels, type UsageSourceLabels, type UsageTotals, type UseAskAgainOptions, type UseAvatarCropOptions, type UseCameraStreamResult, type UseConversationOptions, type UseDeleteAccountFlowOptions, type UseDownloadDocumentsOptions, type UseEmailChangeOptions, type UseFactsSearchOptions, type UseIdentityVerificationFlowOptions, type UseMessageTimerOptions, type UseNameEditorOptions, type UsePasswordChangeFormOptions, type UseShellWorkspacesOptions, type UseShellWorkspacesResult, type UseSwitchWorkspaceResult, type UseVideoRecorderResult, type UserResponse, type UserSettingFlag, type UserSettingsPatch, VIDEO_MIME_PREFERENCE, VidIcon, VideoCapture, type VideoCaptureProps, type VideoRecorderState, VoiceNoteRecorder, type VoiceNoteRecorderProps, WORKSPACE_LAST_OPENED_KEY, WORKSPACE_STORAGE_KEY, WORK_NOTIFICATION_LABELS, WORK_OFFLINE_VIEW, type WorkflowsSourceLabels, type WorkspaceArchive, type WorkspaceArchiveState, type WorkspaceDocument, type WorkspaceExport, type WorkspaceMember, type WorkspaceNotificationLevel, type WorkspaceProcessing, type WorkspaceRole, type WorkspaceSwitchContext, type WorkspaceUpdate, type WorkspacesSourceLabels, XlsIcon, type ZipExtractor, __resetPendingFinalCommitsForTests, __resetStreamingTokenBufferForTests, acceptRing, accountPath, addAssistantMessageToCache, addConversationToList, addUserMessageToCache, adjustTagCounts, adoptNewChatDocument, agentControl, aggregateDataset, aliasTakenMessage, allConversationThreads, annotateThread, announceMailDraftReplaced, appendTokenToMessage, applyCallEvent, applyConversationEvent, applyFinalContextToMessage, applyLiveUpdate, applyNotificationRow, applyOptimisticDocumentEdit, applyOutputItemToMessage, applyTaskEvents, arbiAccountClient, arbiMailClient, archiveName, archivedWorkspaceMessage, assistantLabels, bindThreadDocument, boundDocumentOf, browserWorkspaceStorage, bucketOf, bucketRange, buildDocumentMetadataRows, buildMentionCandidates, buildPendingFirstTurn, buildPendingSyncItem, buildWorkspaceArchive, cacheThreadBinding, cachedAssistantMode, cachedMentionCandidates, cachedQuotaUsedUp, calendarNotificationMeta, calendarOfflineSupport, callLink, callNotificationMeta, captureFrameAsBlob, chatTranscriptRef, claimOfflineQueue, classifyMediaError, clearLoadingState, clearSealedDrafts, clearUserInputRequest, clockTime, closePanelIn, commitFinalMessage, completeQueuedUserMessageByContent, composeArbiSessionStore, compositeFiles, compositeTrack, computeOnline, confirmLosingOfflineMail, connectOAuthCalendarAccount, connectorErrorStatus, connectorReturnTo, conversationKey, conversationsPath, createActivitySource, createArbiChatStore, createArbiDocumentSessionStore, createArbiLayoutStore, createArbiQueryClient, createArbiSessionStore, createArbiWorkspaceStore, createBrowserStateStorage, createChunkedRecorder, createConversationsSource, createDataSourceRegistry, createDatabaseSource, createDebouncedWriter, createDocumentsSource, createFactsSource, createLocalFeatureStore, createMailClient, createMemoryDashboardStore, createMutedNotifier, createProjectsSource, createSealedDraftStorage, createSkillPack, createStoragePersist, createStreamHandlers, createTagsSource, createTrackCutter, createUiStateStorage, createUsageBreakdownSource, createUsageSource, createWorkflowsSource, createWorkspaceSwitch, createWorkspacesSource, cropImage, cutAtPauses, dayKey, declineRing, decodeMono16k, defaultLayoutState, defaultMailAlias, defineRowsSource, defineSkillPack, deleteLocalDraft, deleteOutboxItem, deploymentUserMeta, describeActivity, describeCalendarNotification, describeServerNotification, discardStreamingTokensForMessage, disconnectAttachedRun, dmTabId, documentActivityMeta, documentActivityPhrase, documentDisplayName, documentMailAttachment, docxMentionMeta, downloadRecoveryFile, dropTagFromCachedDocuments, encodeWav, enqueueOutbox, ensureAssistantMessageLoading, entitlementRefusal, extensionFor, extractZipFile, fallbackFileName, fetchPart, fileAttachment, fileSafe, filesFromDrop, fillTimeGaps, filterRows, findConversation, finishEntityExtraction, floatToWav, flushDocumentForTurn, flushOnPageExit, flushStreamingTokens, forgetDocuments, forgetUploadedDocumentFolder, formatConfigValidationError, formatElapsed, formatIdentityPrice, formatTranscriptMarkdown, getCachedDocuments, getInterjectionText, getNotificationTypeMeta, getOfflineDocument, getOrphanedLastMessage, getRelatedLabels, getRelatedTotal, getRunStartedAt, getThreadsQueryKey, getWorkspaceActionText, getWorkspaceKind, getWorkspaceSentPhrase, groupMailConversations, hasPendingFinalCommit, hasPendingMailChange, hasRecordingTranscript, hasVideoTrack, identityStepFor, inputRequestTitle, invalidateCalendarEvents, invalidateCalendars, invalidateCall, invalidateConversationActivity, invalidateConversationDetails, invalidateConversationLists, invalidateTagData, invalidateTagTables, isActivityKey, isAliasTakenError, isArchiveMoving, isCommentToPeople, isConversationListKey, isConversationShared, isDeploymentAdmin, isDeploymentUserNotification, isDocumentsLoading, isFullConfig, isMessageRunning, isNetworkFailure, isNotificationRow, isOrphanedUserMessage, isPanelOpen, isQueuedCalendarWrite, isRecordingSegmentId, isReplayableArbiMutation, isRowNewer, isSignatureNotificationType, isStaleTaskUpdate, isTableViewOf, isTransferFinished, isTransferResumable, isUsageMetered, isWorkingOffline, isWorkspaceArchivedError, isWorkspaceGuestOf, isWorkspaceNotificationType, isZipFile, joinFromPreJoin, layoutActionsOf, loadOfflineDocument, loadAttachment as loadOfflineMailAttachment, mailConversationKey, mailDraftIdFromContent, mailJson, mailThreadRoot, markMessageAsFailed, markNarrationSettled, mergeHostConfig, migrateLegacyThreadDocuments, mountDiditVerification, mutedNoticeFromEvent, mutedNoticeFromPacket, mutedNoticeText, nativeThreadKeys, nextAliasSuggestion, nextViewingDocument, notificationUserName, offlineMailReads, onCallEvent, openAccessRequest, openCall, openPanelIn, openRecording, panelPlace, parseActivityContent, parseDashboardSpec, parseDeleteAccountBlockers, parseSavedChat, parseSavedDocuments, parseSavedLayout, partKey, partsDue, patchCachedDocument, patchConversation, patchConversationList, patchDocuments, patchWorkspaceTags, pendingChatModelSave, peopleDirectory, personOfUser, pickRecentWorkspaces, pickRecorderMimeType, playheadAt, postRecordingDocsToThread, postTranscriptToThread, prepareUploadFiles, queryOfChart, queueMailChange, queuedMessages, readLocalFeature, readWorkspaceLastOpened, recordingFiles, recordingWindowsOf, recordsOf, redlineStats, refreshDocuments, refuseChatWhenOffline, registerArbiMutationDefaults, registerAttachedRun, registerDocumentTurnFlush, remoteControlActions, remoteControlStateOf, removeConversationFromLists, removeSettledNarration, requestPersistentStorage, resetCalendarAccountSyncState, resetMessageContent, resolveActiveWorkspace, resolveConfigModel, resolveDocumentStatus, resolveReplyTarget, restoreLayout, restoreSavedDocuments, retryOutboxItem, rollbackOptimisticDocumentEdit, safePortalUrl, saveLocalDraft, saveRecordingFilesToThread, savedChatOf, savedDocumentsOf, savedLayoutOf, schedulePart, selectDraft, selectIsGenerating, selectViewingDocumentId, sendMailFile, serializeDashboardSpec, serverCallsExperimental, serverNotificationBellEntry, setCachedDocument, setMessageContent, setUserInputRequest, setWorkOfflineIn, settledByRows, signatureNotificationPhrase, signatureRequestMeta, skillPackPrompt, sortTranscriptMessages, sortedParts, speakerTracks, speakerWav, splitIntoFiles, standalone, startChatCall, startContactsCall, startDmCall, startEntityExtraction, startThreadCall, startsMediaFile, stopDocumentsLoading, stripSpeakerPrefix, subscribeDocumentReads, subscribeDocumentRows, supersedeLiveTranscript, supersededTranscriptLines, supportsHouseTemplates, textToArtifact, threadBinding, threadEndingAtContains, threadPath, threadTabId, threadTranscriptLines, threadTranscriptRef, timelineDurationMs, timelineOf, titleFromQuestion, toChatCitations, toMailConversation, toNotificationPreferences, toProfileView, toRedlineMarkdown, toRemoteControlRequest, toShellWorkspace, transcribeRecording, transcriptSegmentOf, updateMessageWithMetadata, updateUserMessageInCache, updateUserMessageStateInCache, uploadFolderOf, uploadedDocumentFolder, upsertDocuments, useAccountClient, useActOnStep, useActiveConfigId, useActivity, useAddChatMembers, useAddDatabaseRows, useAddHolidayCalendar, useAddProjectAddonBlock, useAddWorkspaceMembers, useAddonQuote, useAgentChats, useAgentConfig, useAgentDmStatus, useAgentModels, useAgentRunControl, useAgentSession, useAgentWorkspaces, useAgents, useAiTask, useAnswerAgentQuestion, useApplyChatModel, useArbi, useArbiHost, useArbiSession, useArbiSessionState, useArbiSessionStore, useArbiWebSocket, useArbiWsContext, useArbiWsMessage, useArbiWsStatus, useArbiWsStore, useArchiveProgressPolling, useArchiveWorkspace, useAskAgain, useAssignDocTags, useAssistantArrivals, useAssistantBrief, useAssistantQuery, useAssistantStatus, useAuthorizeLimits, useAutoSendDraft, useAvailableModels, useAvatarCrop, useBookingPages, useBootTimeout, useBoxRole, useBranchNavigation, useBuiltinCommands, useCalDavProfiles, useCalendarAccounts, useCalendarEvent, useCalendarEventByUid, useCalendarEvents, useCalendarInvitations, useCalendarOfflineRuntime, useCalendarOutbox, useCalendarOverlays, useCalendarSettings, useCalendarShares, useCalendarSupport, useCalendars, useCall, useCallInviteLinks, useCallRecording, useCallRecordings, useCallTranscriptionAvailable, useCallsConfig, useCallsEnabled, useCameraStream, useCanCreateProjects, useCanCreateWorkspaces, useCanEditShared, useCanHostCalls, useCancelDriveSync, useCancelMailboxSync, useCancelManyPendingSync, useCancelProjectSubscription, useCancelWorkspaceTransfer, useChangeProjectPlan, useChargeWatch, useChatArrivals, useChatPost, useChatSummaries, useChatThread, useChatUnreadTotal, useChats, useClaimNativeAlias, useClaimSecureMail, useCloseAgentSession, useConfig, useConfigSchema, useConfigs, useConfirmEmailChange, useConfirmProjectSpendLimits, useConnectCalDavAccount, useConnectMailAccount, useConnectOAuthAccount, useConnectRunStream, useConnectedMailFiling, useConnectorAutoSync, useConnectorCatalog, useConnectorVendorVisibility, useContacts, useConversation, useConversationActions, useConversationActivity, useConversationData, useConversationDocuments, useConversationIsShared, useConversationItems, useConversationPendingAuth, useConversationSearch, useConversationSettings, useConversationThreads, useConversationTurn, useConversationWorkspace, useConversations, useCreateAgent, useCreateCalendar, useCreateContact, useCreateDatabase, useCreateEvent, useCreateFact, useCreateFacts, useCreateGroupChat, useCreateProject, useCreateProjectCheckout, useCreateRoom, useCreateTag, useCreateWork, useCreateWorkflow, useCreateWorkspace, useCurrentSessionId, useCurrentUser, useCurrentWorkspace, useDashboardStore, useDataSources, useDatabase, useDatabaseAggregate, useDatabaseDashboardStore, useDatabaseRows, useDatabases, useDecideCounter, useDeleteAccount, useDeleteAccountFlow, useDeleteAgents, useDeleteBookingPage, useDeleteCalendar, useDeleteChatMessage, useDeleteConfig, useDeleteContact, useDeleteConversation, useDeleteDashboard, useDeleteDatabase, useDeleteDatabaseRows, useDeleteDocuments, useDeleteEvent, useDeleteFact, useDeleteMessage, useDeleteNotifications, useDeleteProject, useDeleteSkill, useDeleteTag, useDeleteWorkflow, useDeleteWorkspaces, useDeploymentDomain, useDirectModelUsage, useDisconnectCalendarAccount, useDisconnectConnector, useDisconnectMailAccount, useDisconnectSlack, useDismissedTips, useDocument, useDocumentAutoAdd, useDocumentHostActions, useDocumentPendingSync, useDocumentThumbnails, useDocumentVersionList, useDocuments, useDocumentsLoading, useDocumentsSupport, useDownloadDocuments, useDriveFolderChildren, useDriveFolderDocCount, useDriveFolders, useDriveSyncEstimate, useDriveSyncProgress, useEmailChange, useEnableDriveSync, useEnableMailboxSync, useEntitlements, useEntityExtractionDocIds, useExportDatabase, useExtractEntities, useFacts, useFactsSearch, useFeature, useFeatureCheck, useFeatureSwitch, useFetchCalendarEvent, useFileWaitingNativeMail, useFinaliseTranslation, useFindTime, useFlushOutbox, useFollowThread, useFreeBusy, useGenerateAgentAvatar, useGenerateDocTags, useGrantAgentAccess, useHealth, useHolidayCountries, useHouseTemplateCandidates, useIdentityVerification, useIdentityVerificationFlow, useImportCalendar, useImportContacts, useImportDatabase, useImportDatabaseRows, useInstallSkillPack, useInvalidateAfterTransfer, useInvalidateAssistant, useInvalidateEntitlements, useInvalidateProjects, useInvalidateStorage, useInvalidateTagData, useInvalidateWorkflows, useInviteContacts, useIsCreatingTag, useIsEntitled, useIsSlow, useIsWorkspaceOwner, useKeepDocumentsOffline, useLinkContact, useLinkMentions, useLocalDrafts, useMailAccounts, useMailAttachmentText, useMailCache, useMailClient, useMailConversations, useMailDraftCompose, useMailDraftEditor, useMailDraftReplaced, useMailFiling, useMailFolders, useMailMessage, useMailMessages, useMailOnline, useMailPolicy, useMailProjects, useMailThread, useMailUnlock, useMailWorkspacePrimer, useMailboxFolders, useMailboxSyncProgress, useMarkArrivalWrong, useMarkChatRead, useMarkDocumentShared, useMarkMessageDraftSent, useMarkNotificationsRead, useMcpTools, useMeetingReadOnly, useMessageDetails, useMessageTimer, useModelConnections, useMoveEvent, useMoveWorkspaceToProject, useMyConnectors, useNameEditor, useNativeMailFiling, useNativeThreadKeys, useNotificationPreferences, useNotifications, useOfflineDocumentIds, useOfflineMailActive, useOfflineMailRuntime, useOfflineMailSettings, useOfflineMailStatus, useOpenCallMeetingChat, useOpenSelectedWorkspace, useOpenViewerDocumentId, useOutbox, usePanelDataset, useParsedDocument, usePassageQuotes, usePasswordChange, usePasswordChangeForm, usePendingMailChanges, usePendingSyncCounts, usePendingSyncItems, usePeople, usePeopleSearch, usePlanQuote, usePlanWork, usePlanWorkspaceTransfer, usePreviewProjectPlanChange, useProcessingTask, useProcessingTasks, useProducts, useProfile, useProjectBillingCache, useProjectBillingPortal, useProjectConversationUsage, useProjectCreationDenial, useProjectInvoices, useProjectUsage, useProjects, usePublishCalendar, useRateSupportTicket, useReadMailMessage, useReconnect, useRecordingActions, useRecordingWindows, useReferralSummary, useRefreshCalendar, useRefreshConnectorsOnRunEnd, useRefreshDocuments, useRefreshProject, useRelatedDocuments, useRemoteControl, useRemoveChatMember, useRemoveDocTags, useRemoveDocumentsOffline, useRemoveModelConnection, useRemoveWorkspaceMembers, useRenameChat, useRenameFolder, useRequestEmailChange, useRequestWorkspaceAccess, useRespondToEvent, useResumeCalendarAccountConnect, useResumeWorkspaceTransfer, useRevokeAgentAccess, useRevokeCallInviteLink, useRooms, useRunConversation, useRunWorkflow, useSaveAgentConfig, useSaveBookingPage, useSaveCalendarSettings, useSaveConfig, useSaveConfigField, useSaveDashboard, useSaveMailDraft, useSaveModelConnection, useSaveSkill, useSaveToThread, useSavedDashboards, useSearchContacts, useSearchDatabaseRows, useSearchFacts, useSemanticSearch, useSendMail, useServerCallsEnabled, useServerCallsExperimental, useSessionPageTab, useSessionView, useSessions, useSetDeploymentHouseTemplate, useSetNativeMailFiling, useSetSkillVisibility, useSetTagValues, useSetWorkspaceHouseTemplate, useSetWorkspaceMemberRoles, useShareCalendar, useShellWorkspaces, useSignOut, useSignedInSession, useSimilarDocuments, useSkillSource, useSkills, useSlackConnection, useStartAgentSession, useStartCalendarAccountOAuth, useStartTaskQuery, useStartWorkspaceTransfer, useStopMailFilingRule, useStorageActions, useStorageItemNames, useStorageItems, useStorageProjects, useStorageSnapshots, useStreamHandlers, useSubscribeCalendar, useSupportTicket, useSupportTickets, useSwitchWorkspace, useSyncAccountsOnOpen, useSyncCalendarAccount, useSyncOfflineMailbox, useTagKindSchema, useTags, useTerminateSession, useThinkingContent, useThreadDocument, useThumbnails, useTransientView, useTriggerDriveSync, useTriggerMailboxSync, useUnarchiveWorkspace, useUnlockModelConnections, useUnreadByPeer, useUnshareCalendar, useUpdateAssistantBrief, useUpdateCalendar, useUpdateCalendarAccount, useUpdateContact, useUpdateConversation, useUpdateDatabase, useUpdateDatabaseRow, useUpdateDocTag, useUpdateDocuments, useUpdateEvent, useUpdateFact, useUpdateProfile, useUpdateProjectAddonSettings, useUpdateProjectFields, useUpdateProjectNextPeriodAddons, useUpdateTag, useUpdateTagKindSchema, useUpdateUserSettings, useUpdateWorkflow, useUpdateWorkspace, useUploadDocuments, useUploadFiles, useUploadFromUrls, useUploadSkillFiles, useUploadUrls, useUserDashboardStore, useUserSettings, useUserUsageToday, useVideoRecorder, useWorkItems, useWorkOffline, useWorkflowRuns, useWorkflows, useWorkspaceActivity, useWorkspaceArchive, useWorkspaceDocs, useWorkspaceExportDownload, useWorkspaceNotificationLevel, useWorkspaceProcessing, useWorkspaceRole, useWorkspaceTransfer, useWorkspaceTransfers, useWorkspaceTrash, useWorkspaceUsers, useWorkspaces, userDisplayName, userInitials, viewsOfTable, waitForResponseId, wipeCalendarOffline, wipeOfflineDocuments, wipeOfflineMail, withRelativePath, workflowRunTitle, workflowStepOf, workspaceHouseTemplateId, writeSamples };
@@ -0,0 +1,43 @@
1
+ function throttle(fn, intervalMs) {
2
+ let last = -Infinity;
3
+ let pending = null;
4
+ let timer = null;
5
+ const run = (args) => {
6
+ last = Date.now();
7
+ pending = null;
8
+ fn(...args);
9
+ };
10
+ const clear = () => {
11
+ if (timer) clearTimeout(timer);
12
+ timer = null;
13
+ };
14
+ const throttled = ((...args) => {
15
+ const wait = last + intervalMs - Date.now();
16
+ if (wait <= 0 && !timer) {
17
+ run(args);
18
+ return;
19
+ }
20
+ pending = args;
21
+ if (!timer)
22
+ timer = setTimeout(
23
+ () => {
24
+ timer = null;
25
+ if (pending) run(pending);
26
+ },
27
+ Math.max(0, wait)
28
+ );
29
+ });
30
+ throttled.flush = () => {
31
+ clear();
32
+ if (pending) run(pending);
33
+ };
34
+ throttled.cancel = () => {
35
+ clear();
36
+ pending = null;
37
+ };
38
+ return throttled;
39
+ }
40
+ export {
41
+ throttle
42
+ };
43
+ //# sourceMappingURL=throttle.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/lib/throttle.ts"],
4
+ "sourcesContent": ["/**\n * A throttled callback: the first call runs at once, later calls within `intervalMs` collapse into\n * one trailing call with the latest arguments. `flush()` runs a pending call now (a final value\n * must not wait for the timer), `cancel()` drops it.\n *\n * For callbacks that fire far faster than a person can see (upload progress per XHR event), so a\n * React state update happens a few times a second instead of hundreds.\n */\n\nexport interface Throttled<A extends unknown[]> {\n (...args: A): void\n flush(): void\n cancel(): void\n}\n\nexport function throttle<A extends unknown[]>(\n fn: (...args: A) => void,\n intervalMs: number\n): Throttled<A> {\n let last = -Infinity\n let pending: A | null = null\n let timer: ReturnType<typeof setTimeout> | null = null\n\n const run = (args: A) => {\n last = Date.now()\n pending = null\n fn(...args)\n }\n const clear = () => {\n if (timer) clearTimeout(timer)\n timer = null\n }\n\n const throttled = ((...args: A) => {\n const wait = last + intervalMs - Date.now()\n if (wait <= 0 && !timer) {\n run(args)\n return\n }\n pending = args\n if (!timer)\n timer = setTimeout(\n () => {\n timer = null\n if (pending) run(pending)\n },\n Math.max(0, wait)\n )\n }) as Throttled<A>\n throttled.flush = () => {\n clear()\n if (pending) run(pending)\n }\n throttled.cancel = () => {\n clear()\n pending = null\n }\n return throttled\n}\n"],
5
+ "mappings": "AAeO,SAAS,SACd,IACA,YACc;AACd,MAAI,OAAO;AACX,MAAI,UAAoB;AACxB,MAAI,QAA8C;AAElD,QAAM,MAAM,CAAC,SAAY;AACvB,WAAO,KAAK,IAAI;AAChB,cAAU;AACV,OAAG,GAAG,IAAI;AAAA,EACZ;AACA,QAAM,QAAQ,MAAM;AAClB,QAAI,MAAO,cAAa,KAAK;AAC7B,YAAQ;AAAA,EACV;AAEA,QAAM,aAAa,IAAI,SAAY;AACjC,UAAM,OAAO,OAAO,aAAa,KAAK,IAAI;AAC1C,QAAI,QAAQ,KAAK,CAAC,OAAO;AACvB,UAAI,IAAI;AACR;AAAA,IACF;AACA,cAAU;AACV,QAAI,CAAC;AACH,cAAQ;AAAA,QACN,MAAM;AACJ,kBAAQ;AACR,cAAI,QAAS,KAAI,OAAO;AAAA,QAC1B;AAAA,QACA,KAAK,IAAI,GAAG,IAAI;AAAA,MAClB;AAAA,EACJ;AACA,YAAU,QAAQ,MAAM;AACtB,UAAM;AACN,QAAI,QAAS,KAAI,OAAO;AAAA,EAC1B;AACA,YAAU,SAAS,MAAM;AACvB,UAAM;AACN,cAAU;AAAA,EACZ;AACA,SAAO;AACT;",
6
+ "names": []
7
+ }
@@ -1,4 +1,5 @@
1
1
  import { get, set, del } from "idb-keyval";
2
+ import { throttle } from "./lib/throttle.js";
2
3
  import {
3
4
  isOfflineReadableArbiQuery,
4
5
  isReplayableArbiMutation,
@@ -19,9 +20,16 @@ const IDB_KEY = "arbi-react-query-cache";
19
20
  const OWNER_KEY = "arbi-react-query-cache-owner";
20
21
  const CACHE_BUSTER = "arbi-rq-v2";
21
22
  const MAX_AGE = 1e3 * 60 * 60 * 24 * 7;
23
+ const PERSIST_THROTTLE_MS = 1e3;
22
24
  function createIDBPersister() {
25
+ const write = throttle((client) => {
26
+ void withStorage(() => set(IDB_KEY, client));
27
+ }, PERSIST_THROTTLE_MS);
28
+ if (typeof window !== "undefined") window.addEventListener("pagehide", () => write.flush());
23
29
  return {
24
- persistClient: (client) => withStorage(() => set(IDB_KEY, client)),
30
+ persistClient: async (client) => {
31
+ write(client);
32
+ },
25
33
  // The offline persister must be INERT when online. Because the documents
26
34
  // list never auto-refetches, a rehydrated copy would be trusted
27
35
  // indefinitely and surface stale statuses across a reload — e.g. a document
@@ -43,7 +51,10 @@ function createIDBPersister() {
43
51
  );
44
52
  return persisted;
45
53
  },
46
- removeClient: () => withStorage(() => del(IDB_KEY))
54
+ removeClient: () => {
55
+ write.cancel();
56
+ return withStorage(() => del(IDB_KEY));
57
+ }
47
58
  };
48
59
  }
49
60
  async function claimOfflineQueue(userExtId) {
@@ -73,6 +84,7 @@ function createArbiQueryPersistOptions() {
73
84
  };
74
85
  }
75
86
  export {
87
+ PERSIST_THROTTLE_MS,
76
88
  claimOfflineQueue,
77
89
  createArbiQueryPersistOptions
78
90
  };
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/query-persist.ts"],
4
- "sourcesContent": ["/**\n * The query cache kept for an offline start (`createArbiQueryClient({ persist: true })`).\n *\n * Persists a *metadata-only* slice of the query cache to IndexedDB so an already signed-in user\n * can cold-start offline and still see their workspaces and documents list (and open a pinned\n * document). Deliberately conservative about what is written to disk: only the families\n * {@link isOfflineReadableArbiQuery} names; NEVER conversations, messages or document bytes (the\n * pinned bytes live separately, encrypted: `offline-documents.ts`).\n *\n * An async IndexedDB persister (idb-keyval, structured clone) rather than the JSON sync persister:\n * the robust choice for binary-capable storage.\n */\n\nimport { get, set, del } from 'idb-keyval'\nimport type {\n PersistedClient,\n Persister,\n PersistQueryClientOptions,\n} from '@tanstack/react-query-persist-client'\nimport {\n isOfflineReadableArbiQuery,\n isReplayableArbiMutation,\n isRestorableArbiQueryOnline,\n} from './offline'\n\nlet storageFailed = false\n\n// Optional offline persistence must never prevent an online sign-in. Once storage fails,\n// keep it disabled for this page, including restoration, so another account's queue cannot replay.\nasync function withStorage<T>(operation: () => Promise<T>): Promise<T | undefined> {\n if (storageFailed) return undefined\n try {\n return await operation()\n } catch {\n storageFailed = true\n console.warn('[offline] Browser storage unavailable; offline persistence is disabled.')\n return undefined\n }\n}\n\nconst IDB_KEY = 'arbi-react-query-cache'\n\n// Which account the persisted offline queue belongs to. The queue is one record\n// per browser, so it is only valid for the account that wrote it.\nconst OWNER_KEY = 'arbi-react-query-cache-owner'\n\n// Bump to invalidate everyone's persisted cache after an incompatible change.\n// v2: documents and their writes moved to the `@arbidocs/react` keys.\nconst CACHE_BUSTER = 'arbi-rq-v2'\n\nconst MAX_AGE = 1000 * 60 * 60 * 24 * 7 // 7 days\n\n/** What `<PersistQueryClientProvider persistOptions>` takes for the package's offline cache. */\nexport type ArbiQueryPersistOptions = Omit<PersistQueryClientOptions, 'queryClient'>\n\nfunction createIDBPersister(): Persister {\n return {\n persistClient: (client: PersistedClient) => withStorage(() => set(IDB_KEY, client)),\n // The offline persister must be INERT when online. Because the documents\n // list never auto-refetches, a rehydrated copy would be trusted\n // indefinitely and surface stale statuses across a reload \u2014 e.g. a document\n // that finished processing while the tab was closed (its one-shot\n // completion WS event is long gone) still renders as \"queued\". So when\n // online we strip that query from the restored cache; it then loads\n // fresh from the server exactly as it did before offline support existed.\n // A document caught mid-processing is stripped for the same reason, and the\n // entitlements are read fresh (isRestorableArbiQueryOnline).\n // Queued offline mutations and all other queries restore normally. When\n // offline we keep everything so the pages still have something to show.\n restoreClient: async () => {\n const persisted = await withStorage(() => get<PersistedClient>(IDB_KEY))\n if (!persisted) return persisted\n const isOffline = typeof navigator !== 'undefined' && navigator.onLine === false\n if (isOffline) return persisted\n persisted.clientState.queries = persisted.clientState.queries.filter((q) =>\n isRestorableArbiQueryOnline(q.queryKey, q.state.data)\n )\n return persisted\n },\n removeClient: () => withStorage(() => del(IDB_KEY)),\n }\n}\n\n/**\n * Hand the offline write queue to the account that is signing in. Queued edits\n * are replayed under whoever is logged in on reload, so a queue left by a\n * different account (or one whose owner was never recorded) must be discarded\n * here \u2014 otherwise another person's edit syncs, and fails, as this user.\n * The same account keeps its queue across logins.\n */\nexport async function claimOfflineQueue(userExtId: string): Promise<void> {\n await withStorage(async () => {\n const owner = await get<string>(OWNER_KEY)\n if (owner !== userExtId) await del(IDB_KEY)\n await set(OWNER_KEY, userExtId)\n })\n}\n\n/** The persistence of the offline cache (see the module comment). */\nexport function createArbiQueryPersistOptions(): ArbiQueryPersistOptions {\n return {\n persister: createIDBPersister(),\n maxAge: MAX_AGE,\n buster: CACHE_BUSTER,\n dehydrateOptions: {\n // Persist mutations that were paused offline so a queued write (apply tag,\n // edit field) survives a reload and replays on reconnect. Resuming them\n // after a reload requires the registered mutation defaults\n // (registerArbiMutationDefaults). Scope to real offline EDITS: an incidental\n // paused mutation (e.g. workspace-open) isn't a user change to queue/replay.\n shouldDehydrateMutation: (mutation) =>\n mutation.state.isPaused && isReplayableArbiMutation(mutation.options.mutationKey),\n shouldDehydrateQuery: (query) => {\n if (query.state.status !== 'success') return false\n // Every query key comes from the package factory: its offline families are the whole\n // list (document metadata, the workspace list, the settings, the projects, the\n // entitlements; never a document's content or bytes).\n return isOfflineReadableArbiQuery(query.queryKey)\n },\n },\n }\n}\n"],
5
- "mappings": "AAaA,SAAS,KAAK,KAAK,WAAW;AAM9B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,IAAI,gBAAgB;AAIpB,eAAe,YAAe,WAAqD;AACjF,MAAI,cAAe,QAAO;AAC1B,MAAI;AACF,WAAO,MAAM,UAAU;AAAA,EACzB,QA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,2BAA2B,MAAM,QAAQ;AAAA,MAClD;AAAA,IACF;AAAA,EACF;AACF;",
4
+ "sourcesContent": ["/**\n * The query cache kept for an offline start (`createArbiQueryClient({ persist: true })`).\n *\n * Persists a *metadata-only* slice of the query cache to IndexedDB so an already signed-in user\n * can cold-start offline and still see their workspaces and documents list (and open a pinned\n * document). Deliberately conservative about what is written to disk: only the families\n * {@link isOfflineReadableArbiQuery} names; NEVER conversations, messages or document bytes (the\n * pinned bytes live separately, encrypted: `offline-documents.ts`).\n *\n * An async IndexedDB persister (idb-keyval, structured clone) rather than the JSON sync persister:\n * the robust choice for binary-capable storage.\n */\n\nimport { get, set, del } from 'idb-keyval'\nimport type {\n PersistedClient,\n Persister,\n PersistQueryClientOptions,\n} from '@tanstack/react-query-persist-client'\nimport { throttle } from './lib/throttle'\nimport {\n isOfflineReadableArbiQuery,\n isReplayableArbiMutation,\n isRestorableArbiQueryOnline,\n} from './offline'\n\nlet storageFailed = false\n\n// Optional offline persistence must never prevent an online sign-in. Once storage fails,\n// keep it disabled for this page, including restoration, so another account's queue cannot replay.\nasync function withStorage<T>(operation: () => Promise<T>): Promise<T | undefined> {\n if (storageFailed) return undefined\n try {\n return await operation()\n } catch {\n storageFailed = true\n console.warn('[offline] Browser storage unavailable; offline persistence is disabled.')\n return undefined\n }\n}\n\nconst IDB_KEY = 'arbi-react-query-cache'\n\n// Which account the persisted offline queue belongs to. The queue is one record\n// per browser, so it is only valid for the account that wrote it.\nconst OWNER_KEY = 'arbi-react-query-cache-owner'\n\n// Bump to invalidate everyone's persisted cache after an incompatible change.\n// v2: documents and their writes moved to the `@arbidocs/react` keys.\nconst CACHE_BUSTER = 'arbi-rq-v2'\n\nconst MAX_AGE = 1000 * 60 * 60 * 24 * 7 // 7 days\n\n/**\n * At most this often the cache is written. The persist subscription hands over the whole dehydrated\n * cache on every cache event (a processing burst is hundreds a second) and leaves throttling to the\n * persister, so writing each one would clone and store the documents lists on every event.\n */\nexport const PERSIST_THROTTLE_MS = 1000\n\n/** What `<PersistQueryClientProvider persistOptions>` takes for the package's offline cache. */\nexport type ArbiQueryPersistOptions = Omit<PersistQueryClientOptions, 'queryClient'>\n\nfunction createIDBPersister(): Persister {\n const write = throttle((client: PersistedClient) => {\n void withStorage(() => set(IDB_KEY, client))\n }, PERSIST_THROTTLE_MS)\n // A page going away writes what is pending.\n if (typeof window !== 'undefined') window.addEventListener('pagehide', () => write.flush())\n return {\n persistClient: async (client: PersistedClient) => {\n write(client)\n },\n // The offline persister must be INERT when online. Because the documents\n // list never auto-refetches, a rehydrated copy would be trusted\n // indefinitely and surface stale statuses across a reload \u2014 e.g. a document\n // that finished processing while the tab was closed (its one-shot\n // completion WS event is long gone) still renders as \"queued\". So when\n // online we strip that query from the restored cache; it then loads\n // fresh from the server exactly as it did before offline support existed.\n // A document caught mid-processing is stripped for the same reason, and the\n // entitlements are read fresh (isRestorableArbiQueryOnline).\n // Queued offline mutations and all other queries restore normally. When\n // offline we keep everything so the pages still have something to show.\n restoreClient: async () => {\n const persisted = await withStorage(() => get<PersistedClient>(IDB_KEY))\n if (!persisted) return persisted\n const isOffline = typeof navigator !== 'undefined' && navigator.onLine === false\n if (isOffline) return persisted\n persisted.clientState.queries = persisted.clientState.queries.filter((q) =>\n isRestorableArbiQueryOnline(q.queryKey, q.state.data)\n )\n return persisted\n },\n removeClient: () => {\n write.cancel()\n return withStorage(() => del(IDB_KEY))\n },\n }\n}\n\n/**\n * Hand the offline write queue to the account that is signing in. Queued edits\n * are replayed under whoever is logged in on reload, so a queue left by a\n * different account (or one whose owner was never recorded) must be discarded\n * here \u2014 otherwise another person's edit syncs, and fails, as this user.\n * The same account keeps its queue across logins.\n */\nexport async function claimOfflineQueue(userExtId: string): Promise<void> {\n await withStorage(async () => {\n const owner = await get<string>(OWNER_KEY)\n if (owner !== userExtId) await del(IDB_KEY)\n await set(OWNER_KEY, userExtId)\n })\n}\n\n/** The persistence of the offline cache (see the module comment). */\nexport function createArbiQueryPersistOptions(): ArbiQueryPersistOptions {\n return {\n persister: createIDBPersister(),\n maxAge: MAX_AGE,\n buster: CACHE_BUSTER,\n dehydrateOptions: {\n // Persist mutations that were paused offline so a queued write (apply tag,\n // edit field) survives a reload and replays on reconnect. Resuming them\n // after a reload requires the registered mutation defaults\n // (registerArbiMutationDefaults). Scope to real offline EDITS: an incidental\n // paused mutation (e.g. workspace-open) isn't a user change to queue/replay.\n shouldDehydrateMutation: (mutation) =>\n mutation.state.isPaused && isReplayableArbiMutation(mutation.options.mutationKey),\n shouldDehydrateQuery: (query) => {\n if (query.state.status !== 'success') return false\n // Every query key comes from the package factory: its offline families are the whole\n // list (document metadata, the workspace list, the settings, the projects, the\n // entitlements; never a document's content or bytes).\n return isOfflineReadableArbiQuery(query.queryKey)\n },\n },\n }\n}\n"],
5
+ "mappings": "AAaA,SAAS,KAAK,KAAK,WAAW;AAM9B,SAAS,gBAAgB;AACzB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,IAAI,gBAAgB;AAIpB,eAAe,YAAe,WAAqD;AACjF,MAAI,cAAe,QAAO;AAC1B,MAAI;AACF,WAAO,MAAM,UAAU;AAAA,EACzB,QAAQ;AACN,oBAAgB;AAChB,YAAQ,KAAK,yEAAyE;AACtF,WAAO;AAAA,EACT;AACF;AAEA,MAAM,UAAU;AAIhB,MAAM,YAAY;AAIlB,MAAM,eAAe;AAErB,MAAM,UAAU,MAAO,KAAK,KAAK,KAAK;AAO/B,MAAM,sBAAsB;AAKnC,SAAS,qBAAgC;AACvC,QAAM,QAAQ,SAAS,CAAC,WAA4B;AAClD,SAAK,YAAY,MAAM,IAAI,SAAS,MAAM,CAAC;AAAA,EAC7C,GAAG,mBAAmB;AAEtB,MAAI,OAAO,WAAW,YAAa,QAAO,iBAAiB,YAAY,MAAM,MAAM,MAAM,CAAC;AAC1F,SAAO;AAAA,IACL,eAAe,OAAO,WAA4B;AAChD,YAAM,MAAM;AAAA,IACd;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAYA,eAAe,YAAY;AACzB,YAAM,YAAY,MAAM,YAAY,MAAM,IAAqB,OAAO,CAAC;AACvE,UAAI,CAAC,UAAW,QAAO;AACvB,YAAM,YAAY,OAAO,cAAc,eAAe,UAAU,WAAW;AAC3E,UAAI,UAAW,QAAO;AACtB,gBAAU,YAAY,UAAU,UAAU,YAAY,QAAQ;AAAA,QAAO,CAAC,MACpE,4BAA4B,EAAE,UAAU,EAAE,MAAM,IAAI;AAAA,MACtD;AACA,aAAO;AAAA,IACT;AAAA,IACA,cAAc,MAAM;AAClB,YAAM,OAAO;AACb,aAAO,YAAY,MAAM,IAAI,OAAO,CAAC;AAAA,IACvC;AAAA,EACF;AACF;AASA,eAAsB,kBAAkB,WAAkC;AACxE,QAAM,YAAY,YAAY;AAC5B,UAAM,QAAQ,MAAM,IAAY,SAAS;AACzC,QAAI,UAAU,UAAW,OAAM,IAAI,OAAO;AAC1C,UAAM,IAAI,WAAW,SAAS;AAAA,EAChC,CAAC;AACH;AAGO,SAAS,gCAAyD;AACvE,SAAO;AAAA,IACL,WAAW,mBAAmB;AAAA,IAC9B,QAAQ;AAAA,IACR,QAAQ;AAAA,IACR,kBAAkB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,MAMhB,yBAAyB,CAAC,aACxB,SAAS,MAAM,YAAY,yBAAyB,SAAS,QAAQ,WAAW;AAAA,MAClF,sBAAsB,CAAC,UAAU;AAC/B,YAAI,MAAM,MAAM,WAAW,UAAW,QAAO;AAI7C,eAAO,2BAA2B,MAAM,QAAQ;AAAA,MAClD;AAAA,IACF;AAAA,EACF;AACF;",
6
6
  "names": []
7
7
  }
@@ -16,8 +16,8 @@ import { useArbiSessionStore } from "../session/session-hooks.js";
16
16
  import { applyChatEvent } from "../directmessages/chat-cache.js";
17
17
  import { applyCallEvent } from "../calls/events.js";
18
18
  import { applyNotificationRow, isNotificationRow } from "../notifications/live.js";
19
- import { applyTaskEvent } from "../documents/processing-live.js";
20
- import { refreshDocuments } from "../documents/documents-data.js";
19
+ import { applyTaskEvents } from "../documents/processing-live.js";
20
+ import { queueDocumentReads } from "../documents/documents-data.js";
21
21
  import { arbiQueryKeys } from "../query-keys.js";
22
22
  import { useFeature } from "../host/features.js";
23
23
  import { useOnlineSync } from "../connectivity.js";
@@ -27,6 +27,7 @@ function signedInId(arbi) {
27
27
  return arbi.isLoggedIn ? arbi.user.identity()?.externalId ?? null : null;
28
28
  }
29
29
  const EVICTED_CLOSE_CODE = 1008;
30
+ const TASK_UPDATE_FLUSH_MS = 250;
30
31
  function ArbiWebSocketProvider({
31
32
  enabled = true,
32
33
  onAuthenticated,
@@ -39,7 +40,7 @@ function ArbiWebSocketProvider({
39
40
  const queryClient = useQueryClient();
40
41
  const subscribersRef = useRef(/* @__PURE__ */ new Set());
41
42
  const setStatus = useArbiWsStore((s) => s.setStatus);
42
- const applyTaskUpdate = useArbiWsStore((s) => s.applyTaskUpdate);
43
+ const applyTaskUpdates = useArbiWsStore((s) => s.applyTaskUpdates);
43
44
  const applyPresence = useArbiWsStore((s) => s.applyPresence);
44
45
  const reset = useArbiWsStore((s) => s.reset);
45
46
  const setEvicted = useArbiWsStore((s) => s.setEvicted);
@@ -77,13 +78,43 @@ function ArbiWebSocketProvider({
77
78
  let cancelled = false;
78
79
  let evicted = false;
79
80
  const me = () => signedInId(arbiRef.current);
81
+ const deliver = (msg) => {
82
+ const type = msg.type;
83
+ try {
84
+ handlersRef.current?.[type]?.(msg);
85
+ } catch (error) {
86
+ logger.error(`[WebSocket] The host's ${type} handler failed:`, error);
87
+ }
88
+ for (const fn of subscribersRef.current) {
89
+ try {
90
+ fn(msg);
91
+ } catch {
92
+ }
93
+ }
94
+ };
95
+ let taskBuffer = [];
96
+ let taskTimer = null;
97
+ const flushTasks = () => {
98
+ if (taskTimer) clearTimeout(taskTimer);
99
+ taskTimer = null;
100
+ if (!taskBuffer.length) return;
101
+ const batch = taskBuffer;
102
+ taskBuffer = [];
103
+ const taken = applyTaskUpdates(batch);
104
+ if (taken.length) applyTaskEvents(queryClient, arbiRef.current, taken, me());
105
+ for (const msg of batch) deliver(msg);
106
+ };
80
107
  const onMessage = (msg) => {
81
108
  const type = msg.type;
109
+ if (isMessageType(msg, "task_update")) {
110
+ taskBuffer.push(msg);
111
+ taskTimer ??= setTimeout(flushTasks, TASK_UPDATE_FLUSH_MS);
112
+ return;
113
+ }
114
+ flushTasks();
82
115
  if (type === "connection_closed") {
83
116
  evicted = true;
84
117
  setEvicted(true);
85
- } else if (isMessageType(msg, "task_update")) {
86
- if (applyTaskUpdate(msg)) applyTaskEvent(queryClient, arbiRef.current, msg, me());
87
118
  } else if (isMessageType(msg, "presence_update")) applyPresence(msg);
88
119
  else if (isMessageType(msg, "response_complete"))
89
120
  applyRunFinished(
@@ -102,7 +133,7 @@ function ArbiWebSocketProvider({
102
133
  }
103
134
  if (msg.batch_type === "upload" || msg.batch_type === "entity_extract") {
104
135
  if (msg.doc_ext_ids?.length)
105
- void refreshDocuments(queryClient, arbiRef.current, msg.doc_ext_ids);
136
+ queueDocumentReads(queryClient, arbiRef.current, msg.doc_ext_ids);
106
137
  void queryClient.invalidateQueries({ queryKey: arbiQueryKeys.allTags() });
107
138
  }
108
139
  } else if (type.startsWith("chat.") || type === "agent_dm_status")
@@ -111,17 +142,7 @@ function ArbiWebSocketProvider({
111
142
  applyCallEvent(queryClient, msg, { me: me(), acceptRings: acceptRingsRef.current });
112
143
  else if (isNotificationRow(msg)) applyNotificationRow(queryClient, msg, me());
113
144
  else void applyLiveUpdate(queryClient, msg);
114
- try {
115
- handlersRef.current?.[type]?.(msg);
116
- } catch (error) {
117
- logger.error(`[WebSocket] The host's ${type} handler failed:`, error);
118
- }
119
- for (const fn of subscribersRef.current) {
120
- try {
121
- fn(msg);
122
- } catch {
123
- }
124
- }
145
+ deliver(msg);
125
146
  };
126
147
  let retryTimer = null;
127
148
  let attempt = 0;
@@ -194,14 +215,16 @@ function ArbiWebSocketProvider({
194
215
  void start();
195
216
  return () => {
196
217
  cancelled = true;
218
+ if (taskTimer) clearTimeout(taskTimer);
197
219
  if (retryTimer) clearTimeout(retryTimer);
198
220
  conn?.close();
199
221
  reset();
200
222
  };
201
- }, [enabled, queryClient, setStatus, setEvicted, applyTaskUpdate, applyPresence, reset]);
223
+ }, [enabled, queryClient, setStatus, setEvicted, applyTaskUpdates, applyPresence, reset]);
202
224
  return /* @__PURE__ */ jsx(ArbiWsContext.Provider, { value: context, children });
203
225
  }
204
226
  export {
205
- ArbiWebSocketProvider
227
+ ArbiWebSocketProvider,
228
+ TASK_UPDATE_FLUSH_MS
206
229
  };
207
230
  //# sourceMappingURL=ArbiWebSocketProvider.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/websocket/ArbiWebSocketProvider.tsx"],
4
- "sourcesContent": ["/**\n * ArbiWebSocketProvider \u2014 one shared, reconnecting WebSocket for the whole app.\n *\n * Opens a single authenticated socket (via the SDK transport's\n * `connectWithReconnect`, which handles auth, backoff, and live-token refresh),\n * feeds the canonical WS store, applies what every site applies (tasks, presence,\n * chats, calls, notification rows, finished runs, conversation, mail-draft and skill\n * events), then hands each message to the host's own `handlers` for its type and\n * fans it out to subscribers registered by the `useArbiWebSocket` /\n * `useArbiWsMessage` hooks.\n *\n * Mount it inside an `<ArbiHost>` with an `arbi` (it reads the Arbi instance for the base\n * URL + live access token). Gate it with `enabled` so it connects only once the\n * app is authenticated against a live backend.\n */\n\nimport { useEffect, useMemo, useRef, type ReactNode } from 'react'\nimport { useQueryClient } from '@tanstack/react-query'\nimport { connectWithReconnect, type ReconnectableWsConnection } from '@arbidocs/sdk/browser'\nimport {\n isMessageType,\n type WebSocketServerMessage,\n type WsTaskUpdateMessage,\n type WsBatchCompleteMessage,\n type WsPresenceUpdateMessage,\n type WsAuthResultMessage,\n type WsResponseCompleteMessage,\n logger,\n} from '@arbidocs/client'\nimport { useArbi } from '../useArbi'\nimport { finishEntityExtraction } from '../entity-extraction'\nimport { useArbiWsStore } from './store'\nimport { nextReconnectDelay, resolveSocketBaseUrl } from './reconnect'\nimport { applyLiveUpdate } from './live-updates'\nimport { applyRunFinished } from '../chat/run-finished'\nimport { useArbiSessionStore } from '../session/session-hooks'\nimport { applyChatEvent } from '../directmessages/chat-cache'\nimport { applyCallEvent } from '../calls/events'\nimport { applyNotificationRow, isNotificationRow } from '../notifications/live'\nimport { applyTaskEvent } from '../documents/processing-live'\nimport { refreshDocuments } from '../documents/documents-data'\nimport { arbiQueryKeys } from '../query-keys'\nimport { useFeature } from '../host/features'\nimport { useOnlineSync } from '../connectivity'\nimport { useArbiHost } from '../host/config'\nimport { ArbiWsContext, type ArbiWsContextValue, type ArbiWsSubscriber } from './context'\n\n/** A host's own handling of server messages, by message type (e.g. `remote_control`). */\nexport type ArbiWsHandlers = Partial<Record<string, (message: WebSocketServerMessage) => void>>\n\nexport interface ArbiWebSocketProviderProps {\n /**\n * Open the socket only when the app is authenticated against a live backend.\n * Defaults to `true`; pass the connection status so demo/logged-out sessions\n * don't try to connect.\n */\n enabled?: boolean\n /** Called each time the server accepts the socket's auth (e.g. to show the unread count). */\n onAuthenticated?: (message: WsAuthResultMessage) => void\n /**\n * The host's own handling of message types the provider does not apply (e.g. `remote_control`),\n * each called after the provider's own and before the subscribers. Read on each message, so a\n * new object never reopens the socket.\n */\n handlers?: ArbiWsHandlers\n children: ReactNode\n}\n\n/** The signed-in person's id on `arbi`, or null when nobody is signed in. */\nfunction signedInId(arbi: ReturnType<typeof useArbi>): string | null {\n return arbi.isLoggedIn ? (arbi.user.identity()?.externalId ?? null) : null\n}\n\n/** The close code of a server-side single-session eviction (a newer session of the same user). */\nconst EVICTED_CLOSE_CODE = 1008\n\nexport function ArbiWebSocketProvider({\n enabled = true,\n onAuthenticated,\n handlers,\n children,\n}: ArbiWebSocketProviderProps) {\n // The latest `Arbi`, read on each use: a host renews its instance (another server session, an\n // opened workspace) without that reopening the socket; the token is read afresh on each connect.\n const arbi = useArbi()\n const arbiRef = useRef(arbi)\n arbiRef.current = arbi\n const queryClient = useQueryClient()\n const subscribersRef = useRef<Set<ArbiWsSubscriber>>(new Set())\n const setStatus = useArbiWsStore((s) => s.setStatus)\n const applyTaskUpdate = useArbiWsStore((s) => s.applyTaskUpdate)\n const applyPresence = useArbiWsStore((s) => s.applyPresence)\n const reset = useArbiWsStore((s) => s.reset)\n const setEvicted = useArbiWsStore((s) => s.setEvicted)\n const onAuthenticatedRef = useRef(onAuthenticated)\n onAuthenticatedRef.current = onAuthenticated\n const handlersRef = useRef(handlers)\n handlersRef.current = handlers\n const session = useArbiSessionStore()\n const sessionRef = useRef(session)\n sessionRef.current = session\n const host = useArbiHost()\n const hostRef = useRef(host)\n hostRef.current = host\n // Calls ring only a person whose `calls` feature is on (ARBI: Settings \u2192 Experimental); unlisted, on.\n const acceptRings = useFeature('calls')\n const acceptRingsRef = useRef(acceptRings)\n acceptRingsRef.current = acceptRings\n // Online or not follows this connection too (and the network, and \"Work offline\").\n useOnlineSync()\n\n // Stable subscribe API \u2014 the subscriber set lives in a ref, so registering a\n // handler never re-opens the socket.\n const context = useMemo<ArbiWsContextValue>(\n () => ({\n subscribe: (fn) => {\n subscribersRef.current.add(fn)\n return () => {\n subscribersRef.current.delete(fn)\n }\n },\n }),\n []\n )\n\n useEffect(() => {\n if (!enabled) {\n reset()\n return\n }\n\n let conn: ReconnectableWsConnection | null = null\n let cancelled = false\n // Taken over by another connection of this session (the server says so, then closes):\n // reconnecting would take it back, and the two would evict each other in turn.\n let evicted = false\n\n const me = () => signedInId(arbiRef.current)\n\n // What every site applies, before the host's own subscribers hear the message.\n const onMessage = (msg: WebSocketServerMessage) => {\n const type = msg.type as string\n if (type === 'connection_closed') {\n evicted = true\n setEvicted(true)\n } else if (isMessageType<WsTaskUpdateMessage>(msg, 'task_update')) {\n // The live processing row, then the documents list (an upload's row, a finished re-read).\n if (applyTaskUpdate(msg)) applyTaskEvent(queryClient, arbiRef.current, msg, me())\n } else if (isMessageType<WsPresenceUpdateMessage>(msg, 'presence_update')) applyPresence(msg)\n else if (isMessageType<WsResponseCompleteMessage>(msg, 'response_complete'))\n // A run finished: its conversation stops generating, its follow-up leaves the queue, the\n // documents it saved are read again, the thread follows, and a run failed for the AI usage\n // says so the chat host's way.\n applyRunFinished(queryClient, arbiRef.current, sessionRef.current, msg, (quota) =>\n hostRef.current.chat?.onQuotaExceeded?.(quota)\n )\n else if (type === 'error')\n logger.error('[WebSocket] Server error:', (msg as { message?: unknown }).message)\n else if (isMessageType<WsBatchCompleteMessage>(msg, 'batch_complete')) {\n // An upload or an extraction finished: its documents are read again, and the tags (an\n // upload may create sender labels; an extraction creates people and organisations and\n // links facts). AI fields (`doctag_generate`) are the AI review's (blocks).\n if (msg.batch_type === 'entity_extract') {\n finishEntityExtraction(msg.doc_ext_ids ?? [])\n void queryClient.invalidateQueries({ queryKey: arbiQueryKeys.allFacts() })\n }\n if (msg.batch_type === 'upload' || msg.batch_type === 'entity_extract') {\n if (msg.doc_ext_ids?.length)\n void refreshDocuments(queryClient, arbiRef.current, msg.doc_ext_ids)\n void queryClient.invalidateQueries({ queryKey: arbiQueryKeys.allTags() })\n }\n } else if (type.startsWith('chat.') || type === 'agent_dm_status')\n // Chats (direct messages, agent DM progress).\n void applyChatEvent(arbiRef.current, queryClient, msg)\n else if (type.startsWith('call.'))\n applyCallEvent(queryClient, msg, { me: me(), acceptRings: acceptRingsRef.current })\n else if (isNotificationRow(msg)) applyNotificationRow(queryClient, msg, me())\n // Conversation, mail-draft and skill events.\n else void applyLiveUpdate(queryClient, msg as unknown as { type: string })\n\n // The host's own handler for this type, then the subscribers. A throwing handler must not\n // kill the stream.\n try {\n handlersRef.current?.[type]?.(msg)\n } catch (error) {\n logger.error(`[WebSocket] The host's ${type} handler failed:`, error)\n }\n for (const fn of subscribersRef.current) {\n try {\n fn(msg)\n } catch {\n /* swallow \u2014 one bad handler can't break the socket */\n }\n }\n }\n\n let retryTimer: ReturnType<typeof setTimeout> | null = null\n let attempt = 0\n\n // The socket is best-effort and never gives up: after the transport's own retries (or a failed\n // connect) a fresh one is opened after a capped backoff, offline meanwhile. It never ends the\n // session; that is the HTTP layer's job.\n const scheduleRestart = () => {\n if (cancelled || evicted || retryTimer) return\n setStatus('disconnected')\n const delay = nextReconnectDelay(attempt)\n attempt += 1\n retryTimer = setTimeout(() => {\n retryTimer = null\n void start()\n }, delay)\n }\n\n const start = async () => {\n if (cancelled) return\n const info = arbiRef.current.getConnectionInfo()\n if (!info) {\n // Not signed in on this client yet: try again shortly.\n scheduleRestart()\n return\n }\n conn?.close()\n conn = null\n setStatus('connecting')\n try {\n const c = await connectWithReconnect({\n baseUrl: resolveSocketBaseUrl(\n info.baseUrl,\n typeof window === 'undefined' ? undefined : window.location.origin\n ),\n accessToken: info.accessToken,\n // Resolve the freshest token on every (re)connect so rotation is picked up.\n getAccessToken: () => arbiRef.current.getConnectionInfo()?.accessToken ?? null,\n // A reconnect refused for its token re-logs in silently first.\n refreshAuth: () => arbiRef.current.refreshAccess(),\n onAuthenticated: (message) => onAuthenticatedRef.current?.(message),\n // The session's: a sign-out closes the socket before the server revokes the token.\n signal: info.signal,\n onMessage,\n onReconnecting: () => setStatus('reconnecting'),\n onReconnected: () => {\n attempt = 0\n setStatus('connected')\n },\n // Evicted (a newer session of the same user, or the server took this connection over for a\n // newer one of this session): reconnecting would be evicted again, or evict that one.\n shouldReconnect: (code) => {\n if (code !== EVICTED_CLOSE_CODE && !evicted) return true\n evicted = true\n setEvicted(true)\n setStatus('disconnected')\n return false\n },\n onReconnectFailed: scheduleRestart,\n onClose: () => {\n if (!cancelled) setStatus(evicted ? 'disconnected' : 'reconnecting')\n },\n })\n if (cancelled) {\n c.close()\n return\n }\n conn = c\n attempt = 0\n setStatus('connected')\n } catch {\n // Stopped by a sign-out: the session is gone, nothing to reopen.\n if (!info.signal.aborted) scheduleRestart()\n }\n }\n setEvicted(false)\n void start()\n\n return () => {\n cancelled = true\n if (retryTimer) clearTimeout(retryTimer)\n conn?.close()\n reset()\n }\n }, [enabled, queryClient, setStatus, setEvicted, applyTaskUpdate, applyPresence, reset])\n\n return <ArbiWsContext.Provider value={context}>{children}</ArbiWsContext.Provider>\n}\n"],
5
- "mappings": "AAyRS;AAzQT,SAAS,WAAW,SAAS,cAA8B;AAC3D,SAAS,sBAAsB;AAC/B,SAAS,4BAA4D;AACrE;AAAA,EACE;AAAA,EAOA;AAAA,OACK;AACP,SAAS,eAAe;AACxB,SAAS,8BAA8B;AACvC,SAAS,sBAAsB;AAC/B,SAAS,oBAAoB,4BAA4B;AACzD,SAAS,uBAAuB;AAChC,SAAS,wBAAwB;AACjC,SAAS,2BAA2B;AACpC,SAAS,sBAAsB;AAC/B,SAAS,sBAAsB;AAC/B,SAAS,sBAAsB,yBAAyB;AACxD,SAAS,sBAAsB;AAC/B,SAAS,wBAAwB;AACjC,SAAS,qBAAqB;AAC9B,SAAS,kBAAkB;AAC3B,SAAS,qBAAqB;AAC9B,SAAS,mBAAmB;AAC5B,SAAS,qBAAqE;AAwB9E,SAAS,WAAW,MAAiD;AACnE,SAAO,KAAK,aAAc,KAAK,KAAK,SAAS,GAAG,cAAc,OAAQ;AACxE;AAGA,MAAM,qBAAqB;AAEpB,SAAS,sBAAsB;AAAA,EACpC,UAAU;AAAA,EACV;AAAA,EACA;AAAA,EACA;AACF,GAA+B;AAG7B,QAAM,OAAO,QAAQ;AACrB,QAAM,UAAU,OAAO,IAAI;AAC3B,UAAQ,UAAU;AAClB,QAAM,cAAc,eAAe;AACnC,QAAM,iBAAiB,OAA8B,oBAAI,IAAI,CAAC;AAC9D,QAAM,YAAY,eAAe,CAAC,MAAM,EAAE,SAAS;AACnD,QAAM,kBAAkB,eAAe,CAAC,MAAM,EAAE,eAAe;AAC/D,QAAM,gBAAgB,eAAe,CAAC,MAAM,EAAE,aAAa;AAC3D,QAAM,QAAQ,eAAe,CAAC,MAAM,EAAE,KAAK;AAC3C,QAAM,aAAa,eAAe,CA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AM,MAAM;AACZ,YAAM;AAAA,IACR;AAAA,EACF,GAAG,CAAC,SAAS,aAAa,WAAW,YAAY,iBAAiB,eAAe,KAAK,CAAC;AAEvF,SAAO,oBAAC,cAAc,UAAd,EAAuB,OAAO,SAAU,UAAS;AAC3D;",
4
+ "sourcesContent": ["/**\n * ArbiWebSocketProvider \u2014 one shared, reconnecting WebSocket for the whole app.\n *\n * Opens a single authenticated socket (via the SDK transport's\n * `connectWithReconnect`, which handles auth, backoff, and live-token refresh),\n * feeds the canonical WS store, applies what every site applies (tasks, presence,\n * chats, calls, notification rows, finished runs, conversation, mail-draft and skill\n * events), then hands each message to the host's own `handlers` for its type and\n * fans it out to subscribers registered by the `useArbiWebSocket` /\n * `useArbiWsMessage` hooks.\n *\n * Mount it inside an `<ArbiHost>` with an `arbi` (it reads the Arbi instance for the base\n * URL + live access token). Gate it with `enabled` so it connects only once the\n * app is authenticated against a live backend.\n */\n\nimport { useEffect, useMemo, useRef, type ReactNode } from 'react'\nimport { useQueryClient } from '@tanstack/react-query'\nimport { connectWithReconnect, type ReconnectableWsConnection } from '@arbidocs/sdk/browser'\nimport {\n isMessageType,\n type WebSocketServerMessage,\n type WsTaskUpdateMessage,\n type WsBatchCompleteMessage,\n type WsPresenceUpdateMessage,\n type WsAuthResultMessage,\n type WsResponseCompleteMessage,\n logger,\n} from '@arbidocs/client'\nimport { useArbi } from '../useArbi'\nimport { finishEntityExtraction } from '../entity-extraction'\nimport { useArbiWsStore } from './store'\nimport { nextReconnectDelay, resolveSocketBaseUrl } from './reconnect'\nimport { applyLiveUpdate } from './live-updates'\nimport { applyRunFinished } from '../chat/run-finished'\nimport { useArbiSessionStore } from '../session/session-hooks'\nimport { applyChatEvent } from '../directmessages/chat-cache'\nimport { applyCallEvent } from '../calls/events'\nimport { applyNotificationRow, isNotificationRow } from '../notifications/live'\nimport { applyTaskEvents } from '../documents/processing-live'\nimport { queueDocumentReads } from '../documents/documents-data'\nimport { arbiQueryKeys } from '../query-keys'\nimport { useFeature } from '../host/features'\nimport { useOnlineSync } from '../connectivity'\nimport { useArbiHost } from '../host/config'\nimport { ArbiWsContext, type ArbiWsContextValue, type ArbiWsSubscriber } from './context'\n\n/** A host's own handling of server messages, by message type (e.g. `remote_control`). */\nexport type ArbiWsHandlers = Partial<Record<string, (message: WebSocketServerMessage) => void>>\n\nexport interface ArbiWebSocketProviderProps {\n /**\n * Open the socket only when the app is authenticated against a live backend.\n * Defaults to `true`; pass the connection status so demo/logged-out sessions\n * don't try to connect.\n */\n enabled?: boolean\n /** Called each time the server accepts the socket's auth (e.g. to show the unread count). */\n onAuthenticated?: (message: WsAuthResultMessage) => void\n /**\n * The host's own handling of message types the provider does not apply (e.g. `remote_control`),\n * each called after the provider's own and before the subscribers. Read on each message, so a\n * new object never reopens the socket.\n */\n handlers?: ArbiWsHandlers\n children: ReactNode\n}\n\n/** The signed-in person's id on `arbi`, or null when nobody is signed in. */\nfunction signedInId(arbi: ReturnType<typeof useArbi>): string | null {\n return arbi.isLoggedIn ? (arbi.user.identity()?.externalId ?? null) : null\n}\n\n/** The close code of a server-side single-session eviction (a newer session of the same user). */\nconst EVICTED_CLOSE_CODE = 1008\n\n/**\n * How long `task_update`s gather before they are handled together. A batch upload sends hundreds\n * a second; each would otherwise be its own store write, list write and re-render. Any other\n * message handles the gathered ones first, so the order of messages is kept.\n */\nexport const TASK_UPDATE_FLUSH_MS = 250\n\nexport function ArbiWebSocketProvider({\n enabled = true,\n onAuthenticated,\n handlers,\n children,\n}: ArbiWebSocketProviderProps) {\n // The latest `Arbi`, read on each use: a host renews its instance (another server session, an\n // opened workspace) without that reopening the socket; the token is read afresh on each connect.\n const arbi = useArbi()\n const arbiRef = useRef(arbi)\n arbiRef.current = arbi\n const queryClient = useQueryClient()\n const subscribersRef = useRef<Set<ArbiWsSubscriber>>(new Set())\n const setStatus = useArbiWsStore((s) => s.setStatus)\n const applyTaskUpdates = useArbiWsStore((s) => s.applyTaskUpdates)\n const applyPresence = useArbiWsStore((s) => s.applyPresence)\n const reset = useArbiWsStore((s) => s.reset)\n const setEvicted = useArbiWsStore((s) => s.setEvicted)\n const onAuthenticatedRef = useRef(onAuthenticated)\n onAuthenticatedRef.current = onAuthenticated\n const handlersRef = useRef(handlers)\n handlersRef.current = handlers\n const session = useArbiSessionStore()\n const sessionRef = useRef(session)\n sessionRef.current = session\n const host = useArbiHost()\n const hostRef = useRef(host)\n hostRef.current = host\n // Calls ring only a person whose `calls` feature is on (ARBI: Settings \u2192 Experimental); unlisted, on.\n const acceptRings = useFeature('calls')\n const acceptRingsRef = useRef(acceptRings)\n acceptRingsRef.current = acceptRings\n // Online or not follows this connection too (and the network, and \"Work offline\").\n useOnlineSync()\n\n // Stable subscribe API \u2014 the subscriber set lives in a ref, so registering a\n // handler never re-opens the socket.\n const context = useMemo<ArbiWsContextValue>(\n () => ({\n subscribe: (fn) => {\n subscribersRef.current.add(fn)\n return () => {\n subscribersRef.current.delete(fn)\n }\n },\n }),\n []\n )\n\n useEffect(() => {\n if (!enabled) {\n reset()\n return\n }\n\n let conn: ReconnectableWsConnection | null = null\n let cancelled = false\n // Taken over by another connection of this session (the server says so, then closes):\n // reconnecting would take it back, and the two would evict each other in turn.\n let evicted = false\n\n const me = () => signedInId(arbiRef.current)\n\n // The host's own handler for a message, then the subscribers. A throwing handler must not kill\n // the stream.\n const deliver = (msg: WebSocketServerMessage) => {\n const type = msg.type as string\n try {\n handlersRef.current?.[type]?.(msg)\n } catch (error) {\n logger.error(`[WebSocket] The host's ${type} handler failed:`, error)\n }\n for (const fn of subscribersRef.current) {\n try {\n fn(msg)\n } catch {\n /* swallow \u2014 one bad handler can't break the socket */\n }\n }\n }\n\n // Gathered `task_update`s: taken into the live processing in one store write, then into the\n // documents lists (an upload's rows, the finished ones re-read), then delivered in order.\n let taskBuffer: WsTaskUpdateMessage[] = []\n let taskTimer: ReturnType<typeof setTimeout> | null = null\n const flushTasks = () => {\n if (taskTimer) clearTimeout(taskTimer)\n taskTimer = null\n if (!taskBuffer.length) return\n const batch = taskBuffer\n taskBuffer = []\n const taken = applyTaskUpdates(batch)\n if (taken.length) applyTaskEvents(queryClient, arbiRef.current, taken, me())\n for (const msg of batch) deliver(msg)\n }\n\n // What every site applies, before the host's own subscribers hear the message.\n const onMessage = (msg: WebSocketServerMessage) => {\n const type = msg.type as string\n if (isMessageType<WsTaskUpdateMessage>(msg, 'task_update')) {\n taskBuffer.push(msg)\n taskTimer ??= setTimeout(flushTasks, TASK_UPDATE_FLUSH_MS)\n return\n }\n flushTasks()\n if (type === 'connection_closed') {\n evicted = true\n setEvicted(true)\n } else if (isMessageType<WsPresenceUpdateMessage>(msg, 'presence_update')) applyPresence(msg)\n else if (isMessageType<WsResponseCompleteMessage>(msg, 'response_complete'))\n // A run finished: its conversation stops generating, its follow-up leaves the queue, the\n // documents it saved are read again, the thread follows, and a run failed for the AI usage\n // says so the chat host's way.\n applyRunFinished(queryClient, arbiRef.current, sessionRef.current, msg, (quota) =>\n hostRef.current.chat?.onQuotaExceeded?.(quota)\n )\n else if (type === 'error')\n logger.error('[WebSocket] Server error:', (msg as { message?: unknown }).message)\n else if (isMessageType<WsBatchCompleteMessage>(msg, 'batch_complete')) {\n // An upload or an extraction finished: its documents are read again, and the tags (an\n // upload may create sender labels; an extraction creates people and organisations and\n // links facts). AI fields (`doctag_generate`) are the AI review's (blocks).\n if (msg.batch_type === 'entity_extract') {\n finishEntityExtraction(msg.doc_ext_ids ?? [])\n void queryClient.invalidateQueries({ queryKey: arbiQueryKeys.allFacts() })\n }\n if (msg.batch_type === 'upload' || msg.batch_type === 'entity_extract') {\n if (msg.doc_ext_ids?.length)\n queueDocumentReads(queryClient, arbiRef.current, msg.doc_ext_ids)\n void queryClient.invalidateQueries({ queryKey: arbiQueryKeys.allTags() })\n }\n } else if (type.startsWith('chat.') || type === 'agent_dm_status')\n // Chats (direct messages, agent DM progress).\n void applyChatEvent(arbiRef.current, queryClient, msg)\n else if (type.startsWith('call.'))\n applyCallEvent(queryClient, msg, { me: me(), acceptRings: acceptRingsRef.current })\n else if (isNotificationRow(msg)) applyNotificationRow(queryClient, msg, me())\n // Conversation, mail-draft and skill events.\n else void applyLiveUpdate(queryClient, msg as unknown as { type: string })\n\n deliver(msg)\n }\n\n let retryTimer: ReturnType<typeof setTimeout> | null = null\n let attempt = 0\n\n // The socket is best-effort and never gives up: after the transport's own retries (or a failed\n // connect) a fresh one is opened after a capped backoff, offline meanwhile. It never ends the\n // session; that is the HTTP layer's job.\n const scheduleRestart = () => {\n if (cancelled || evicted || retryTimer) return\n setStatus('disconnected')\n const delay = nextReconnectDelay(attempt)\n attempt += 1\n retryTimer = setTimeout(() => {\n retryTimer = null\n void start()\n }, delay)\n }\n\n const start = async () => {\n if (cancelled) return\n const info = arbiRef.current.getConnectionInfo()\n if (!info) {\n // Not signed in on this client yet: try again shortly.\n scheduleRestart()\n return\n }\n conn?.close()\n conn = null\n setStatus('connecting')\n try {\n const c = await connectWithReconnect({\n baseUrl: resolveSocketBaseUrl(\n info.baseUrl,\n typeof window === 'undefined' ? undefined : window.location.origin\n ),\n accessToken: info.accessToken,\n // Resolve the freshest token on every (re)connect so rotation is picked up.\n getAccessToken: () => arbiRef.current.getConnectionInfo()?.accessToken ?? null,\n // A reconnect refused for its token re-logs in silently first.\n refreshAuth: () => arbiRef.current.refreshAccess(),\n onAuthenticated: (message) => onAuthenticatedRef.current?.(message),\n // The session's: a sign-out closes the socket before the server revokes the token.\n signal: info.signal,\n onMessage,\n onReconnecting: () => setStatus('reconnecting'),\n onReconnected: () => {\n attempt = 0\n setStatus('connected')\n },\n // Evicted (a newer session of the same user, or the server took this connection over for a\n // newer one of this session): reconnecting would be evicted again, or evict that one.\n shouldReconnect: (code) => {\n if (code !== EVICTED_CLOSE_CODE && !evicted) return true\n evicted = true\n setEvicted(true)\n setStatus('disconnected')\n return false\n },\n onReconnectFailed: scheduleRestart,\n onClose: () => {\n if (!cancelled) setStatus(evicted ? 'disconnected' : 'reconnecting')\n },\n })\n if (cancelled) {\n c.close()\n return\n }\n conn = c\n attempt = 0\n setStatus('connected')\n } catch {\n // Stopped by a sign-out: the session is gone, nothing to reopen.\n if (!info.signal.aborted) scheduleRestart()\n }\n }\n setEvicted(false)\n void start()\n\n return () => {\n cancelled = true\n if (taskTimer) clearTimeout(taskTimer)\n if (retryTimer) clearTimeout(retryTimer)\n conn?.close()\n reset()\n }\n }, [enabled, queryClient, setStatus, setEvicted, applyTaskUpdates, applyPresence, reset])\n\n return <ArbiWsContext.Provider value={context}>{children}</ArbiWsContext.Provider>\n}\n"],
5
+ "mappings": "AAwTS;AAxST,SAAS,WAAW,SAAS,cAA8B;AAC3D,SAAS,sBAAsB;AAC/B,SAAS,4BAA4D;AACrE;AAAA,EACE;AAAA,EAOA;AAAA,OACK;AACP,SAAS,eAAe;AACxB,SAAS,8BAA8B;AACvC,SAAS,sBAAsB;AAC/B,SAAS,oBAAoB,4BAA4B;AACzD,SAAS,uBAAuB;AAChC,SAAS,wBAAwB;AACjC,SAAS,2BAA2B;AACpC,SAAS,sBAAsB;AAC/B,SAAS,sBAAsB;AAC/B,SAAS,sBAAsB,yBAAyB;AACxD,SAAS,uBAAuB;AAChC,SAAS,0BAA0B;AACnC,SAAS,qBAAqB;AAC9B,SAAS,kBAAkB;AAC3B,SAAS,qBAAqB;AAC9B,SAAS,mBAAmB;AAC5B,SAAS,qBAAqE;AAwB9E,SAAS,WAAW,MAAiD;AACnE,SAAO,KAAK,aAAc,KAAK,KAAK,SAAS,GAAG,cAAc,OAAQ;AACxE;AAGA,MAAM,qBAAqB;AAOpB,MAAM,uBAAuB;AAE7B,SAAS,sBAAsB;AAAA,EACpC,UAAU;AAAA,EACV;AAAA,EACA;AAAA,EACA;AACF,GAA+B;AAG7B,QAAM,OAAO,QAAQ;AACrB,QAAM,UAAU,OAAO,IAAI;AAC3B,UAAQ,UAAU;AAClB,QAAM,cAAc,eAAe;AACnC,QAAM,iBAAiB,OAA8B,oBAAI,IAAI,CAAC;AAC9D,QAAM,YA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AA,UAC9C,eAAe,MAAM;AACnB,sBAAU;AACV,sBAAU,WAAW;AAAA,UACvB;AAAA;AAAA;AAAA,UAGA,iBAAiB,CAAC,SAAS;AACzB,gBAAI,SAAS,sBAAsB,CAAC,QAAS,QAAO;AACpD,sBAAU;AACV,uBAAW,IAAI;AACf,sBAAU,cAAc;AACxB,mBAAO;AAAA,UACT;AAAA,UACA,mBAAmB;AAAA,UACnB,SAAS,MAAM;AACb,gBAAI,CAAC,UAAW,WAAU,UAAU,iBAAiB,cAAc;AAAA,UACrE;AAAA,QACF,CAAC;AACD,YAAI,WAAW;AACb,YAAE,MAAM;AACR;AAAA,QACF;AACA,eAAO;AACP,kBAAU;AACV,kBAAU,WAAW;AAAA,MACvB,QAAQ;AAEN,YAAI,CAAC,KAAK,OAAO,QAAS,iBAAgB;AAAA,MAC5C;AAAA,IACF;AACA,eAAW,KAAK;AAChB,SAAK,MAAM;AAEX,WAAO,MAAM;AACX,kBAAY;AACZ,UAAI,UAAW,cAAa,SAAS;AACrC,UAAI,WAAY,cAAa,UAAU;AACvC,YAAM,MAAM;AACZ,YAAM;AAAA,IACR;AAAA,EACF,GAAG,CAAC,SAAS,aAAa,WAAW,YAAY,kBAAkB,eAAe,KAAK,CAAC;AAExF,SAAO,oBAAC,cAAc,UAAd,EAAuB,OAAO,SAAU,UAAS;AAC3D;",
6
6
  "names": []
7
7
  }
@@ -15,20 +15,27 @@ const useArbiWsStore = create((set, get) => ({
15
15
  evicted: false,
16
16
  setStatus: (status) => set({ status }),
17
17
  setEvicted: (evicted) => set({ evicted }),
18
- applyTaskUpdate: (msg) => {
18
+ applyTaskUpdate: (msg) => get().applyTaskUpdates([msg]).length > 0,
19
+ applyTaskUpdates: (messages) => {
19
20
  const { tasks, dismissed } = get();
20
- const dismissedAt = dismissed[msg.doc_ext_id];
21
- if (dismissedAt !== void 0 && Date.now() - dismissedAt < DISMISSED_TASK_TTL_MS) return false;
22
- const held = tasks[msg.doc_ext_id];
23
- if (isStaleTaskUpdate(held, msg)) return false;
24
21
  const now = Date.now();
25
- const task = {
26
- ...msg,
27
- startTime: held?.startTime ?? now,
28
- endTime: finished(msg.status) ? held?.endTime ?? now : void 0
29
- };
30
- set({ tasks: { ...tasks, [msg.doc_ext_id]: task }, lastTaskUpdate: msg });
31
- return true;
22
+ let next = null;
23
+ const taken = [];
24
+ for (const msg of messages) {
25
+ const dismissedAt = dismissed[msg.doc_ext_id];
26
+ if (dismissedAt !== void 0 && now - dismissedAt < DISMISSED_TASK_TTL_MS) continue;
27
+ const held = (next ?? tasks)[msg.doc_ext_id];
28
+ if (isStaleTaskUpdate(held, msg)) continue;
29
+ next ??= { ...tasks };
30
+ next[msg.doc_ext_id] = {
31
+ ...msg,
32
+ startTime: held?.startTime ?? now,
33
+ endTime: finished(msg.status) ? held?.endTime ?? now : void 0
34
+ };
35
+ taken.push(msg);
36
+ }
37
+ if (next) set({ tasks: next, lastTaskUpdate: taken[taken.length - 1] });
38
+ return taken;
32
39
  },
33
40
  putTask: (task) => set((s) => ({ tasks: { ...s.tasks, [task.doc_ext_id]: task } })),
34
41
  clearTask: (docId) => set((s) => {