@arbidocs/react 0.5.0 → 0.5.2

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.js CHANGED
@@ -1,29 +1,28 @@
1
- import { invalidateConversationLists, patchConversation, invalidateConversationDetails, addConversationToList, findConversation, isConversationShared, isKnownSoloConversation, patchConversationList, removeConversationFromLists, ArbiWsContext, useArbiWsContext, useAccountClient, applyChatEvent, myChatId, upsertChat, appendToThread, dropFromThread, deleteChatMessage, removeChat, cachedChats } from './chunk-SNUNLXFE.js';
2
- export { AUDIENCE_CHOICES, CALL_CAPTION_TOPIC, CALL_CHAT_MAX_CHARS, CALL_CHAT_TOPIC, CALL_MODERATION_TOPIC, CALL_RECORDING_TOPIC, CALL_TRANSCRIPTION_TOPIC, CALL_WEBINAR_TOPIC, CAPTION_MAX_CHARS, COMPOSITE_AUDIO_BITS_PER_SECOND, COMPOSITE_VIDEO_BITS_PER_SECOND, DEFAULT_JOIN_CHOICES, EMPTY_CALL_SESSION, EXPORT_SAMPLE_RATE, HISTORY_LIMIT, LIVE_SEGMENTER, MAX_AVATAR_FILE_BYTES, MUTED_DEDUPE_MS, PLAYBACK_LOOKAHEAD_MS, READ_ONLY_MEETING_TEXT, RECORDING_CHUNK_MS, RECORDING_SEGMENTER, SEGMENT_FRAME_MS, SEGMENT_ID_PATTERN, SEGMENT_PRE_ROLL_MS, SHORT_PIECE_MERGE_GAP_MS, SPEAKER_AUDIO_BITS_PER_SECOND, TrackUploader, UPLOAD_ATTEMPTS, UPLOAD_BACKOFF_MS, acceptRing, addConversationToList, appendToThread, applyAgentDmStatus, applyCallEvent, applyChatEvent, applyChatMessage, applyChatRead, applyChatUpdated, arbiAccountClient, buildMeetingChatBody, cachedChat, cachedChats, callLink, callMemberKeys, callSession, chatByExtId, chatHasLiveCall, chatLiveCallId, chatTranscriptRef, clearMeetingChatCache, clearTrackUploaders, clockTime, compositeFiles, compositeTrack, conversationKeyForCall, createMutedNotifier, createTrackCutter, cutAtPauses, declineRing, decodeCallChatPacket, decodeCaptionPacket, decodeMono16k, decryptPart, encodeCallChatPacket, encodeCaptionPacket, encodeWav, encryptPart, ensureMeetingChat, entitlementRefusal, extensionFor, fetchPart, fileSafe, findConversation, floatToWav, formatTranscriptMarkdown, getOpenChat, hasRecordingTranscript, invalidateCall, invalidateConversationDetails, invalidateConversationLists, isConversationListKey, isConversationShared, isKnownSoloConversation, isRecordingOver, isRecordingSegmentId, isRetryable, isWorkspaceGuestOf, joinFromPreJoin, knownMeetingChat, loadMeetingHistory, markRejoining, meetingChatRefFrom, meetingRefForCall, mergeChatLines, mutedNoticeFromEvent, mutedNoticeFromPacket, mutedNoticeText, myChatId, newPacketId, newSegmentId, newTrackKey, nextSeqAfter, onCallEvent, openCall, openQuestion, openRecording, parseWebinarPacket, partKey, partOffsetMs, partsDue, patchConversation, patchConversationList, persistMeetingMessage, persistTranscriptSegment, playheadAt, postRecordingDocsToThread, postTranscriptToThread, recordingFiles, recordingWindowsOf, rejoinAsAudience, removeChat, removeConversationFromLists, resetCallSession, resolveMeetingChat, saveRecordingFilesToThread, schedulePart, sealQuestionText, setOpenChat, sortTranscriptMessages, sortedParts, speakerTracks, speakerWav, splitIntoFiles, standalone, startChatCall, startContactsCall, startDmCall, startThreadCall, startsMediaFile, storeTranscriptSegment, stripSpeakerPrefix, supersedeLiveTranscript, supersededTranscriptLines, threadHasLiveCall, threadLiveCallId, threadTranscriptLines, threadTranscriptRef, threadTranscriptText, timelineDurationMs, timelineOf, toProfileView, trackUploaderFor, transcribeRecording, transcriptPersistRole, transcriptSegmentOf, unwrapTrackKey, upsertChat, useAccountClient, useArbiWsContext, useAvatarCrop, useCall, useCallInviteLinks, useCallLiveUpdates, useCallRecording, useCallRecordings, useCallSession, useCallTranscriptionAvailable, useCallsConfig, useCallsEnabled, useCanHostCalls, useEntitlements, useIsEntitled, useMeetingReadOnly, useNameEditor, useOpenCallMeetingChat, useProfile, useRecordingActions, useRecordingWindows, useRevokeCallInviteLink, useSaveToThread, useServerCallsEnabled, useUpdateProfile, wrapTrackKey, writeSamples } from './chunk-SNUNLXFE.js';
1
+ import { invalidateConversationLists, patchConversation, invalidateConversationDetails, addConversationToList, findConversation, isConversationShared, isKnownSoloConversation, patchConversationList, removeConversationFromLists, ArbiWsContext, useArbiWsContext, useAccountClient, applyChatEvent, myChatId, upsertChat, appendToThread, dropFromThread, deleteChatMessage, removeChat } from './chunk-BF5ASP3L.js';
2
+ export { AUDIENCE_CHOICES, CALL_CAPTION_TOPIC, CALL_CHAT_MAX_CHARS, CALL_CHAT_TOPIC, CALL_MODERATION_TOPIC, CALL_RECORDING_TOPIC, CALL_TRANSCRIPTION_TOPIC, CALL_WEBINAR_TOPIC, CAPTION_MAX_CHARS, COMPOSITE_AUDIO_BITS_PER_SECOND, COMPOSITE_VIDEO_BITS_PER_SECOND, DEFAULT_JOIN_CHOICES, EMPTY_CALL_SESSION, EXPORT_SAMPLE_RATE, HISTORY_LIMIT, LIVE_SEGMENTER, MAX_AVATAR_FILE_BYTES, MUTED_DEDUPE_MS, PLAYBACK_LOOKAHEAD_MS, READ_ONLY_MEETING_TEXT, RECORDING_CHUNK_MS, RECORDING_SEGMENTER, SEGMENT_FRAME_MS, SEGMENT_ID_PATTERN, SEGMENT_PRE_ROLL_MS, SHORT_PIECE_MERGE_GAP_MS, SPEAKER_AUDIO_BITS_PER_SECOND, TrackUploader, UPLOAD_ATTEMPTS, UPLOAD_BACKOFF_MS, acceptRing, addConversationToList, appendToThread, applyAgentDmStatus, applyCallEvent, applyChatEvent, applyChatMessage, applyChatRead, applyChatUpdated, arbiAccountClient, buildMeetingChatBody, cachedChat, cachedChats, callLink, callMemberKeys, callSession, chatByExtId, chatHasLiveCall, chatLiveCallId, chatTranscriptRef, clearMeetingChatCache, clearTrackUploaders, clockTime, compositeFiles, compositeTrack, conversationKeyForCall, createMutedNotifier, createTrackCutter, cutAtPauses, declineRing, decodeCallChatPacket, decodeCaptionPacket, decodeMono16k, decryptPart, encodeCallChatPacket, encodeCaptionPacket, encodeWav, encryptPart, ensureMeetingChat, entitlementRefusal, extensionFor, fetchPart, fileSafe, findConversation, floatToWav, formatTranscriptMarkdown, getOpenChat, hasRecordingTranscript, invalidateCall, invalidateConversationDetails, invalidateConversationLists, isConversationListKey, isConversationShared, isKnownSoloConversation, isRecordingOver, isRecordingSegmentId, isRetryable, isWorkspaceGuestOf, joinFromPreJoin, knownMeetingChat, loadMeetingHistory, markRejoining, meetingChatRefFrom, meetingRefForCall, mergeChatLines, mutedNoticeFromEvent, mutedNoticeFromPacket, mutedNoticeText, myChatId, newPacketId, newSegmentId, newTrackKey, nextSeqAfter, onCallEvent, openCall, openQuestion, openRecording, parseWebinarPacket, partKey, partOffsetMs, partsDue, patchConversation, patchConversationList, persistMeetingMessage, persistTranscriptSegment, playheadAt, postRecordingDocsToThread, postTranscriptToThread, recordingFiles, recordingWindowsOf, rejoinAsAudience, removeChat, removeConversationFromLists, resetCallSession, resolveMeetingChat, saveRecordingFilesToThread, schedulePart, sealQuestionText, setOpenChat, sortTranscriptMessages, sortedParts, speakerTracks, speakerWav, splitIntoFiles, standalone, startChatCall, startContactsCall, startDmCall, startThreadCall, startsMediaFile, storeTranscriptSegment, stripSpeakerPrefix, supersedeLiveTranscript, supersededTranscriptLines, threadHasLiveCall, threadLiveCallId, threadTranscriptLines, threadTranscriptRef, threadTranscriptText, timelineDurationMs, timelineOf, toProfileView, trackUploaderFor, transcribeRecording, transcriptPersistRole, transcriptSegmentOf, unwrapTrackKey, upsertChat, useAccountClient, useArbiWsContext, useAvatarCrop, useCall, useCallInviteLinks, useCallLiveUpdates, useCallRecording, useCallRecordings, useCallSession, useCallTranscriptionAvailable, useCallsConfig, useCallsEnabled, useCanHostCalls, useEntitlements, useIsEntitled, useMeetingReadOnly, useNameEditor, useOpenCallMeetingChat, useProfile, useRecordingActions, useRecordingWindows, useRevokeCallInviteLink, useSaveToThread, useServerCallsEnabled, useUpdateProfile, wrapTrackKey, writeSamples } from './chunk-BF5ASP3L.js';
3
3
  import { settledByRows, isStaleTaskUpdate, replayableTagMutations, patchDocuments, setCachedDocument, adjustTagCounts, patchCachedDocument, forgetDocuments, getCachedDocuments, refreshDocuments, FINISHED_DOCUMENT_STATUSES, useSimilarDocuments, SIMILARITY_THRESHOLD, useDocuments, finishEntityExtraction } from './chunk-6YLK5AGS.js';
4
4
  export { DOCUMENTS_FIRST_PAGE_MEASURE, DOCUMENTS_FIRST_PAGE_SIZE, DOCUMENTS_PAGE_SIZE, FINISHED_DOCUMENT_STATUSES, IN_FLIGHT_DOCUMENT_STATUSES, SIMILARITY_THRESHOLD, adjustTagCounts, dropTagFromCachedDocuments, finishEntityExtraction, forgetDocuments, getCachedDocuments, invalidateTagData, invalidateTagTables, isDocumentsLoading, isRowNewer, isStaleTaskUpdate, patchCachedDocument, patchDocuments, patchWorkspaceTags, refreshDocuments, resolveDocumentStatus, setCachedDocument, settledByRows, startEntityExtraction, stopDocumentsLoading, subscribeDocumentRows, upsertDocuments, useCreateTag, useDeleteTag, useDocument, useDocuments, useDocumentsById, useDocumentsLoading, useEntityExtractionDocIds, useExtractEntities, useInvalidateTagData, useIsCreatingTag, useSetTagValues, useSimilarDocuments, useTagKindSchema, useUpdateTag, useUpdateTagKindSchema } from './chunk-6YLK5AGS.js';
5
- import { useArbiSessionState, useConversations, useArbiSession, useWorkspaces, useConfig, useArbiSessionStore, useAvailableModels, useParsedDocument, useTags, selectDraft, useConversationThreads, createArbiSessionStore, useAgents, useAssistantQuery, useActivity, queuedMessages, MIN_QUEUED_MESSAGE_VISIBILITY_MS } from './chunk-EOFEAME5.js';
6
- export { DEFAULT_DOCUMENT_VIEWER_STATE, EMPTY_SESSION_STATE, MAX_THREAD_TABS, MIN_QUEUED_MESSAGE_VISIBILITY_MS, PROJECT_CREATION_DENIED_REASON, agentControl, clearSealedDrafts, conversationKey, createArbiSessionStore, createSealedDraftStorage, isUsageMetered, nextViewingDocument, queuedMessages, selectDraft, selectIsGenerating, selectViewingDocumentId, threadTabId, useActivity, useAgents, useArbiSession, useArbiSessionState, useArbiSessionStore, useAssistantQuery, useAvailableModels, useBuiltinCommands, useCanCreateProjects, useConfig, useConfigs, useConversationThreads, useConversations, useCurrentUser, useDeleteAgents, useDocumentVersionList, useFirmPool, useHealth, useMessageDetails, useParsedDocument, useProjectInvoices, useProjectUsage, useProjects, useProjectsUsage, useSignedInSession, useTags, useThumbnails, useTopUpFirmPool, useUserUsageToday, useWorkspaceActivity, useWorkspaces } from './chunk-EOFEAME5.js';
5
+ import { useArbiSessionState, useConversations, useArbiSession, useWorkspaces, useConfig, useArbiSessionStore, useAvailableModels, useParsedDocument, useTags, selectDraft, useConversationThreads, createArbiSessionStore, useAgents, useAssistantQuery, useActivity, queuedMessages, MIN_QUEUED_MESSAGE_VISIBILITY_MS } from './chunk-5DI27KJG.js';
6
+ export { DEFAULT_DOCUMENT_VIEWER_STATE, EMPTY_SESSION_STATE, MAX_THREAD_TABS, MIN_QUEUED_MESSAGE_VISIBILITY_MS, PROJECT_CREATION_DENIED_REASON, agentControl, clearSealedDrafts, conversationKey, createArbiSessionStore, createSealedDraftStorage, isUsageMetered, nextViewingDocument, queuedMessages, selectDraft, selectIsGenerating, selectViewingDocumentId, threadTabId, useActivity, useAgents, useArbiSession, useArbiSessionState, useArbiSessionStore, useAssistantQuery, useAvailableModels, useBuiltinCommands, useCanCreateProjects, useConfig, useConfigs, useConversationThreads, useConversations, useCurrentUser, useDeleteAgents, useDocumentVersionList, useFirmPool, useHealth, useMessageDetails, useParsedDocument, useProjectInvoices, useProjectUsage, useProjects, useProjectsUsage, useSignedInSession, useTags, useThumbnails, useTopUpFirmPool, useUserUsageToday, useWorkspaceActivity, useWorkspaces } from './chunk-5DI27KJG.js';
7
+ import { fetchDocumentFile, downloadBlob, fetchMarkupPdf } from './chunk-YWYCEEBF.js';
8
+ import { arbiMutationKeys, arbiQueryKeys, mailQueryKeys, connectorQueryKeys, calendarQueryKeys } from './chunk-NVAIVJID.js';
9
+ export { arbiMutationKeys, arbiQueryKeys, calendarQueryKeys, callQueryKeys, connectorQueryKeys, isUnderQueryKey, mailQueryKeys } from './chunk-NVAIVJID.js';
7
10
  import { ArbiHost, extractMentions, toMessageMentions, takeOpenDocumentForTurn, hasMessageBody, createSearchSession, clearSearchSession, formatRelativeTime } from './chunk-DGMK3EUN.js';
8
11
  export { MENTION_HREF_PREFIX, NotificationBell, Toaster, clearSearchSession, createSearchSession, extractMentions, filterMentionCandidates, findMentionQuery, formatRelativeTime, hasMessageBody, insertMention, linkMentions, mentionFromHref, persistSearchSession, requestSearch, savedDocumentIdFor, sharedSearchSession, takeOpenDocumentForTurn, takePendingSearch, toMessageMentions, useOpenDocumentId, useRegisterOpenDocument } from './chunk-DGMK3EUN.js';
9
12
  import { notify } from './chunk-5HDC43MF.js';
10
13
  export { DEFAULT_NOTIFY_TONE, MAX_SESSION_NOTIFICATIONS, configureNotify, notify, persistNotifyHistory, seedNotifications, selectUnread, toast, useNotify } from './chunk-5HDC43MF.js';
11
14
  export { mergeHostConfig } from './chunk-DPYBZDJB.js';
12
- import { fetchDocumentFile, downloadBlob, fetchMarkupPdf } from './chunk-YWYCEEBF.js';
13
- import { arbiMutationKeys, arbiQueryKeys, mailQueryKeys, connectorQueryKeys, calendarQueryKeys } from './chunk-NVAIVJID.js';
14
- export { arbiMutationKeys, arbiQueryKeys, calendarQueryKeys, callQueryKeys, connectorQueryKeys, isUnderQueryKey, mailQueryKeys } from './chunk-NVAIVJID.js';
15
15
  export { cleanDraftMarkdown, cleanDraftWithReport, promoteBoldTitle, repairParsedStructure, repairParsedTitle, stripAgentPreamble, unescapeMarkdown, unwrapCitationLinks } from './chunk-NNWMHMEC.js';
16
16
  import './chunk-WUTL62MC.js';
17
- import { returnFocusToMark, MarkMenu, getDocumentTitle, Badge, TagEntity, useAudioRecorder, MicWaveformIndicator, IconToggle, classifyMediaError, formatElapsed, AiMarkdown, Card, Input, FILE_TYPE_COLORS, getEntityIcon, UserEntity, getEntityColorStyles, AgentBadge, Textarea, Label, Slider, getEntityLabel, getDocumentDate } from './chunk-3WIBD44F.js';
17
+ import { returnFocusToMark, MarkMenu, getDocumentTitle, Badge, TagEntity, useAudioRecorder, MicWaveformIndicator, IconToggle, classifyMediaError, formatElapsed, AiMarkdown, Card, Input, FILE_TYPE_COLORS, getEntityIcon, UserEntity, getEntityColorStyles, AgentBadge, Textarea, Slider, getEntityLabel, getDocumentDate } from './chunk-3WIBD44F.js';
18
18
  export { ARBI_MARK_SRC, AUDIO_MIME_PREFERENCE, AgentBadge, AiMarkdown, ArbiBotHeadIcon, ArbiIcon, AudIcon, BASE_COLORS, Badge, COLUMN_LABEL_FALLBACKS, Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle, Checkbox, ClaudeIcon, Collapsible, CollapsibleContent, CollapsibleTrigger, Command, CommandDialog, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList, CommandSeparator, CommandShortcut, DEFAULT_METADATA_TAGS, DebouncedInput, DocIcon, DocumentCard, DocumentEntity, ENTITY_MAPPINGS, EmlIcon, EntityIcon, EntityPill, FILE_TYPE_COLORS, FireworksIcon, GeminiIcon, GoogleIcon, HoverCard, HoverCardContent, HoverCardTrigger, HtmlIcon, IconToggle, ImgIcon, InlineMicButton, Input, Label, MarkMenu, MicRecordingOverlay, MicWaveformIndicator, NEUTRAL_GRAY, OpenAIIcon, PLACEHOLDER_COLOR, PassageCard, PdfIcon, Popover, PopoverAnchor, PopoverClose, PopoverContent, PopoverTrigger, PresenceLabel, Progress, ProjectEntity, ProviderIcon, RadioGroup, RadioGroupItem, RagDot, RelevanceDot, Select, SelectContent, SelectGroup, SelectItem, SelectLabel, SelectScrollDownButton, SelectScrollUpButton, SelectSeparator, SelectTrigger, SelectValue, Separator, ShieldIcon, Slider, StatusPill, Switch, TAG_TYPE_ICONS, TAG_TYPE_LABELS, Table, TableBody, TableCaption, TableCell, TableFooter, TableHead, TableHeader, TableRow, Tabs, TabsContent, TabsList, TabsTrigger, TagEntity, Textarea, ThreadVisibilityIcon, Toggle, ToggleGroup, ToggleGroupItem, Tooltip, TooltipContent, TooltipProvider, TooltipTrigger, TxtIcon, UserEntity, UserMenu, VIDEO_MIME_PREFERENCE, VISIBILITY_ICONS, VerifiedBadge, VerifiedToggle, VidIcon, VisibilityIcon, VisibilityToggle, XlsIcon, agentAvatarColors, badgeVariants, buildFolderTree, canonicalFolderPath, cardVariants, classifyMediaError, configureEntityRegistry, configureRagLabels, configureStatusRegistry, createChunkedRecorder, extensionFromMime, formatDocDate, formatElapsed, formatFolderLabel, formatFriendlyDate, friendlyFileType, getDocIcon, getDocumentAuthor, getDocumentDate, getDocumentNature, getDocumentSubject, getDocumentTitle, getEntityColor, getEntityColorStyles, getEntityIcon, getEntityLabel, getFileExtension, getFileTypeIcon, getStatusVariant, getTagTypeIcon, getTagTypeLabel, getWorkspaceColor, isAudioFile, isDocumentAddableToConversation, isDownloadOnlyFile, isImageDocument, isImageFile, isMediaFile, isVideoFile, markdownToPlainText, markdownToPlainTextBlocks, pickRecorderMimeType, tagKindNouns, tagKindTitle, toggleVariants, useAudioRecorder, useDictateContext, usesOriginalBytesForViewer } from './chunk-3WIBD44F.js';
19
19
  import { getUserDisplayName, isAgent } from './chunk-APZZQZ6P.js';
20
20
  export { Avatar, AvatarFallback, AvatarImage, DEFAULT_SEGMENTER_CONFIG, INITIAL_SEGMENTER_STATE, createUserAvatarIcon, flushSegmenter, getUserAvatarColor, getUserDisplayName, getUserInitials, isAgent, levelFromRms, stepSegmenter } from './chunk-APZZQZ6P.js';
21
21
  import { MarkdownRenderer } from './chunk-C44GO33B.js';
22
22
  export { MarkdownCode, MarkdownLink, MarkdownRenderer, MarkdownStreamingContext, markdownBaseComponents, markdownSanitizeSchema, splitMarkdownBlocks } from './chunk-C44GO33B.js';
23
- import { ScrollArea } from './chunk-W4H6XAIU.js';
24
- export { ScrollArea, ScrollBar } from './chunk-W4H6XAIU.js';
25
23
  import { Button, Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from './chunk-YNNAJJ5Z.js';
26
24
  export { Button, Dialog, DialogClose, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogOverlay, DialogPortal, DialogTitle, DialogTrigger, buttonVariants } from './chunk-YNNAJJ5Z.js';
25
+ export { ScrollArea, ScrollBar } from './chunk-W4H6XAIU.js';
27
26
  import { DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator } from './chunk-47CCGUWR.js';
28
27
  export { DropdownMenu, DropdownMenuCheckboxItem, DropdownMenuContent, DropdownMenuGroup, DropdownMenuItem, DropdownMenuLabel, DropdownMenuPortal, DropdownMenuRadioGroup, DropdownMenuRadioItem, DropdownMenuSeparator, DropdownMenuShortcut, DropdownMenuSub, DropdownMenuSubContent, DropdownMenuSubTrigger, DropdownMenuTrigger, PortalContainerProvider, usePortalContainer } from './chunk-47CCGUWR.js';
29
28
  import { normalizeCitationMarkup } from './chunk-QRCMKEE6.js';
@@ -34,12 +33,12 @@ import { AudioViewer, ImageViewer, VideoViewer } from './chunk-HDCRPPBW.js';
34
33
  import { useArbi, useArbiHost } from './chunk-KGCGA452.js';
35
34
  export { useArbi, useArbiHost, useDeploymentDomain } from './chunk-KGCGA452.js';
36
35
  export { useHostConfigRecord } from './chunk-CPZ36AQS.js';
37
- import React, { memo, useState, createContext, useMemo, useCallback, useEffect, useRef, useLayoutEffect, useId, useSyncExternalStore, useContext, Fragment as Fragment$1 } from 'react';
36
+ import React, { memo, useState, createContext, useMemo, useCallback, useEffect, useRef, useLayoutEffect, useId, useSyncExternalStore, useContext } from 'react';
38
37
  import { useQueryClient, useMutation, useQuery, onlineManager, keepPreviousData, useQueries, partialMatchKey } from '@tanstack/react-query';
39
- import { documents, doctags, houseTemplates, STOP_ID_WAIT_MS, resolveCitations, summarizeCitations, createIndexAssigner, reduceOutputItem, findReplyTarget, ArbiApiError, quotaFromStreamError, STOP_REPEAT_WINDOW_MS, getRunToCancel, pickMainThread, extractDocumentIdsFromMessages, extractFactIdsFromMessages, hydrateAgentSteps, getSubagentBranchRecord, getRunToAttach, settings, isConnectorVendorVisible, ACCOUNT_VENDOR, searchChunks, chats, formatFileSize, connectWithReconnect, ArbiWorkspaceSupersededError, identityErrorCode } from '@arbidocs/sdk/browser';
38
+ import { documents, doctags, houseTemplates, STOP_ID_WAIT_MS, resolveCitations, summarizeCitations, createIndexAssigner, reduceOutputItem, findReplyTarget, ArbiApiError, quotaFromStreamError, STOP_REPEAT_WINDOW_MS, getRunToCancel, pickMainThread, extractDocumentIdsFromMessages, extractFactIdsFromMessages, hydrateAgentSteps, getSubagentBranchRecord, getRunToAttach, settings, isConnectorVendorVisible, ACCOUNT_VENDOR, searchChunks, formatFileSize, chats, connectWithReconnect, ArbiWorkspaceSupersededError, identityErrorCode } from '@arbidocs/sdk/browser';
40
39
  export { ACCOUNT_VENDOR, Arbi, ArbiError, DEFAULT_AI_USD_PER_GBP, DRIVE_SYNC_VENDORS, GOOGLE_VENDORS, IMANAGE_VENDORS, MAILBOX_SYNC_VENDORS, MAX_RETRIEVE_DOC_IDS, MICROSOFT_VENDORS, PublicBookingError, SHAREPOINT_VENDORS, bookPublicSlot, cancelPublicBooking, connectErrorMessage, formatGbp, formatGbpPerMillionTokens, getPublicBookingPage, isConnectorVendorVisible, isDriveSyncVendor, isMailboxSyncVendor, isSharePointVendor, usdToGbp } from '@arbidocs/sdk/browser';
41
40
  import { create } from 'zustand';
42
- import { Link, Trash2, CheckCheck, Check, MoreHorizontal, SquarePen, Pencil, Download, X, Mic, Pause, Play, Square, Loader2, RotateCcw, Sparkles, Camera, Circle, AlertTriangle, ShieldCheck, Copy, FileText, GitCompareArrows, Search, CornerDownLeft, Send, Tags, Info, Activity, HardDrive, Gauge, Gift, PartyPopper, UserPlus, UserCheck, Reply, PenLine, AtSign, MessageCircleMore, FileX2, FileCheck2, FolderPlus, SquareArrowOutUpRight, MessagesSquare, Paperclip, ArrowRight, Image as Image$1, AppWindow } from 'lucide-react';
41
+ import { Link, Trash2, CheckCheck, Check, MoreHorizontal, SquarePen, Pencil, Download, X, Mic, Pause, Play, Square, Loader2, RotateCcw, Sparkles, Camera, Circle, AlertTriangle, ShieldCheck, Copy, FileText, GitCompareArrows, Search, CornerDownLeft, Send, Tags, Info, Activity, HardDrive, Gauge, Gift, PartyPopper, UserPlus, UserCheck, Reply, PenLine, AtSign, MessageCircleMore, FileX2, FileCheck2, FolderPlus, SquareArrowOutUpRight, Paperclip, ArrowRight, Image as Image$1, AppWindow } from 'lucide-react';
43
42
  import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
44
43
  import { isMessageType, getUserEncryptionKeypair, decryptMessage, passwordChangeErrorMessage, createRecoveryFile } from '@arbidocs/client';
45
44
  export { isMessageType } from '@arbidocs/client';
@@ -162,12 +161,20 @@ function useStartTaskQuery() {
162
161
  });
163
162
  }
164
163
  });
165
- const lookUpThread = async (messageId, attempts) => {
164
+ const threadOf = async (messageId, known) => {
165
+ const response = await arbi.assistant.getResponse(messageId);
166
+ const events = response.metadata?.events ?? [];
167
+ const posted = events.find((e) => e.type === "arbi.user_message")?.conversation_ext_id;
168
+ if (posted) return posted;
169
+ if (response.status === "queued" || response.status === "in_progress") return void 0;
170
+ return known || (await arbi.conversations.getMessage(messageId)).conversation_ext_id;
171
+ };
172
+ const lookUpThread = async (messageId, attempts, known) => {
166
173
  let conversationId;
167
174
  for (let attempt = 0; attempt < attempts && !conversationId; attempt += 1) {
168
175
  if (attempt > 0) await new Promise((r) => setTimeout(r, THREAD_LOOKUP_DELAY_MS));
169
176
  try {
170
- conversationId = (await arbi.conversations.getMessage(messageId)).conversation_ext_id;
177
+ conversationId = await threadOf(messageId, known);
171
178
  } catch (error) {
172
179
  if (!(error && typeof error === "object" && "status" in error && error.status === 404))
173
180
  throw error;
@@ -183,7 +190,11 @@ function useStartTaskQuery() {
183
190
  findThread: (messageId) => lookUpThread(messageId, 1),
184
191
  start: async (query) => {
185
192
  const accepted = await post.mutateAsync(query);
186
- const found = await lookUpThread(accepted.id, THREAD_LOOKUP_ATTEMPTS);
193
+ const found = await lookUpThread(
194
+ accepted.id,
195
+ THREAD_LOOKUP_ATTEMPTS,
196
+ accepted.conversation_ext_id
197
+ );
187
198
  if (!found) throw new TaskThreadPendingError(accepted.id);
188
199
  return found;
189
200
  }
@@ -5796,6 +5807,14 @@ var archivedWorkspaceMessage = (name) => `"${name}" is archived. Its owner can u
5796
5807
  var listedWorkspace = (queryClient, workspaceId) => queryClient.getQueryData(arbiQueryKeys.workspaces())?.find((w) => w.external_id === workspaceId);
5797
5808
  var switchEpoch = 0;
5798
5809
  var switching = /* @__PURE__ */ new Set();
5810
+ var SIGNED_IN_WAIT_MS = 1e4;
5811
+ var SIGNED_IN_POLL_MS = 50;
5812
+ async function signedIn(arbi, timeoutMs = SIGNED_IN_WAIT_MS) {
5813
+ const deadline = Date.now() + timeoutMs;
5814
+ while (!arbi().isLoggedIn && arbi().session?.getState().signedIn === true && Date.now() < deadline) {
5815
+ await new Promise((resolve) => setTimeout(resolve, SIGNED_IN_POLL_MS));
5816
+ }
5817
+ }
5799
5818
  async function switchesSettled() {
5800
5819
  while (switching.size > 0) await Promise.allSettled([...switching]);
5801
5820
  }
@@ -5829,6 +5848,8 @@ function createWorkspaceSwitch({
5829
5848
  }
5830
5849
  const epoch = ++switchEpoch;
5831
5850
  notify.info(`Opening "${name}" ${noun}\u2026`, { workspaceId: target.id, duration: 2e3 });
5851
+ await signedIn(arbi);
5852
+ if (epoch !== switchEpoch) return false;
5832
5853
  if (!isSame) {
5833
5854
  session.leaveWorkspace();
5834
5855
  drainWorkspaceQueries(queryClient);
@@ -5874,6 +5895,8 @@ function createWorkspaceSwitch({
5874
5895
  const workspaceId = session.getState().workspaceId;
5875
5896
  if (!workspaceId) return false;
5876
5897
  const epoch = switchEpoch;
5898
+ await signedIn(arbi);
5899
+ if (epoch !== switchEpoch || session.getState().workspaceId !== workspaceId) return false;
5877
5900
  performance.mark("arbi:workspace-open:start");
5878
5901
  let opened;
5879
5902
  try {
@@ -5918,15 +5941,15 @@ function useOpenSelectedWorkspace() {
5918
5941
  clearWorkspace();
5919
5942
  }, [archived, clearWorkspace]);
5920
5943
  const opening = useRef(false);
5921
- const signedIn = arbi.isLoggedIn;
5944
+ const signedIn2 = arbi.isLoggedIn;
5922
5945
  useEffect(() => {
5923
- if (!workspaceId || archived || listing || status !== "closed" || !signedIn || opening.current)
5946
+ if (!workspaceId || archived || listing || status !== "closed" || !signedIn2 || opening.current)
5924
5947
  return;
5925
5948
  opening.current = true;
5926
5949
  void openSelectedWorkspace().finally(() => {
5927
5950
  opening.current = false;
5928
5951
  });
5929
- }, [openSelectedWorkspace, workspaceId, archived, listing, status, signedIn]);
5952
+ }, [openSelectedWorkspace, workspaceId, archived, listing, status, signedIn2]);
5930
5953
  }
5931
5954
 
5932
5955
  // src/workspaces/shell-workspaces.ts
@@ -6863,7 +6886,8 @@ function useHouseTemplateCandidates(workspaceId, enabled, staleTime = 6e4) {
6863
6886
  queryKey: arbiQueryKeys.houseTemplateCandidates(workspaceId ?? ""),
6864
6887
  enabled: enabled && !!workspaceId && arbi.hasWorkspace,
6865
6888
  staleTime,
6866
- queryFn: () => arbi.houseTemplates.candidates()
6889
+ // Read in that workspace: the server answers for the session's open one.
6890
+ queryFn: () => arbi.readInWorkspace(workspaceId, () => arbi.houseTemplates.candidates())
6867
6891
  });
6868
6892
  }
6869
6893
  function useSetWorkspaceHouseTemplate() {
@@ -10666,1055 +10690,628 @@ function userDisplayName(user) {
10666
10690
  function isAgentUser(user) {
10667
10691
  return user.external_id.startsWith("agt-");
10668
10692
  }
10669
- function useChats(options = {}) {
10670
- const arbi = useArbi();
10671
- return useQuery({
10672
- queryKey: arbiQueryKeys.chatList(),
10673
- queryFn: () => arbi.chats.list(),
10674
- enabled: (options.enabled ?? true) && arbi.isLoggedIn
10675
- });
10676
- }
10677
- function useChatLiveUpdates() {
10678
- const arbi = useArbi();
10679
- const queryClient = useQueryClient();
10680
- const ws = useContext(ArbiWsContext);
10681
- const arbiRef = useRef(arbi);
10682
- arbiRef.current = arbi;
10683
- useEffect(
10684
- () => ws?.subscribe((message) => {
10685
- if (message.type.startsWith("chat.") || message.type === "agent_dm_status")
10686
- void applyChatEvent(arbiRef.current, queryClient, message);
10687
- }),
10688
- [ws, queryClient]
10693
+ function DmAvatar({ user, className, size = "lg" }) {
10694
+ const presence = useArbiWsStore((s) => s.presence[user.external_id]);
10695
+ const displayStatus = presence === void 0 ? void 0 : presence === "online" ? "connected" : "disconnected";
10696
+ return /* @__PURE__ */ jsx(
10697
+ UserEntity,
10698
+ {
10699
+ variant: "icon",
10700
+ size,
10701
+ className,
10702
+ interactive: false,
10703
+ showTooltip: false,
10704
+ initials: userInitials(user),
10705
+ displayName: userDisplayName(user),
10706
+ picture: user.picture,
10707
+ avatarStyle: getEntityColorStyles(user.external_id),
10708
+ isAgent: isAgentUser(user),
10709
+ displayStatus
10710
+ }
10689
10711
  );
10690
10712
  }
10691
- function useAgentDmStatus(agentExtId) {
10692
- const { data } = useQuery({
10693
- queryKey: arbiQueryKeys.agentDmStatus(agentExtId ?? ""),
10694
- // Written by the events only: nothing to fetch.
10695
- queryFn: () => null,
10696
- enabled: false,
10697
- staleTime: Infinity
10698
- });
10699
- return agentExtId ? data ?? void 0 : void 0;
10700
- }
10701
- function useChatUnreadTotal() {
10702
- const { data = [] } = useChats();
10703
- return useMemo(() => data.reduce((sum, c) => sum + (c.unread_count ?? 0), 0), [data]);
10704
- }
10705
- function useUnreadByPeer() {
10706
- const arbi = useArbi();
10707
- const { data = [] } = useChats();
10708
- const me = myChatId(arbi);
10709
- return useMemo(() => {
10710
- const out = /* @__PURE__ */ new Map();
10711
- for (const c of data) {
10712
- if (c.kind !== "direct" || !c.unread_count) continue;
10713
- const peer = c.members.find((m) => m.user.external_id !== me)?.user.external_id ?? me;
10714
- if (peer) out.set(peer, (out.get(peer) ?? 0) + c.unread_count);
10713
+ function ConversationList({
10714
+ conversations,
10715
+ selectedPeerId,
10716
+ onSelect,
10717
+ classNames,
10718
+ emptyState,
10719
+ header,
10720
+ lead,
10721
+ className
10722
+ }) {
10723
+ return /* @__PURE__ */ jsxs(
10724
+ "aside",
10725
+ {
10726
+ className: cn(
10727
+ "flex min-h-0 flex-col border-b border-border md:w-80 md:shrink-0 md:border-b-0 md:border-r",
10728
+ className
10729
+ ),
10730
+ "data-testid": "arbi-dm-list",
10731
+ children: [
10732
+ header === void 0 ? /* @__PURE__ */ jsxs("div", { className: "border-b border-border px-4 py-3", children: [
10733
+ /* @__PURE__ */ jsx("p", { className: "text-sm font-semibold text-foreground", children: "Conversations" }),
10734
+ /* @__PURE__ */ jsxs("p", { className: "text-xs text-muted-foreground", children: [
10735
+ conversations.length,
10736
+ " ",
10737
+ conversations.length === 1 ? "colleague" : "colleagues"
10738
+ ] })
10739
+ ] }) : header,
10740
+ lead,
10741
+ /* @__PURE__ */ jsx("div", { className: "min-h-0 flex-1 overflow-y-auto", children: conversations.length === 0 ? /* @__PURE__ */ jsx("div", { className: "px-4 py-6 text-xs text-muted-foreground", children: emptyState ?? "No conversations yet." }) : /* @__PURE__ */ jsx("ul", { className: "w-full", children: conversations.map((c, i) => {
10742
+ const { peer, lastMessage, unreadCount } = c;
10743
+ const rowId = c.id ?? peer.external_id;
10744
+ const newSection = c.sectionLabel && c.sectionLabel !== conversations[i - 1]?.sectionLabel;
10745
+ const active = rowId === selectedPeerId;
10746
+ const preview = lastMessage?.body ?? "No messages yet \u2014 say hello";
10747
+ const unread = unreadCount > 0;
10748
+ const body = /* @__PURE__ */ jsxs(Fragment, { children: [
10749
+ c.leading ?? /* @__PURE__ */ jsx(DmAvatar, { user: peer }),
10750
+ /* @__PURE__ */ jsxs("div", { className: "min-w-0 flex-1", children: [
10751
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between gap-2", children: [
10752
+ /* @__PURE__ */ jsxs("span", { className: "flex min-w-0 items-center gap-1.5", children: [
10753
+ /* @__PURE__ */ jsx(
10754
+ "span",
10755
+ {
10756
+ className: cn(
10757
+ "truncate text-sm text-foreground",
10758
+ unread ? "font-bold" : "font-semibold"
10759
+ ),
10760
+ children: c.title ?? userDisplayName(peer)
10761
+ }
10762
+ ),
10763
+ c.badge ?? (isAgentUser(peer) ? /* @__PURE__ */ jsx(AgentBadge, {}) : null)
10764
+ ] }),
10765
+ c.statusLabel ? /* @__PURE__ */ jsx(
10766
+ Badge,
10767
+ {
10768
+ variant: "outline",
10769
+ className: "shrink-0 rounded-full px-2 py-0 text-xs font-medium text-muted-foreground",
10770
+ children: c.statusLabel
10771
+ }
10772
+ ) : unreadCount > 0 ? (
10773
+ // Quiet by default: a filled brand pill with a shadow
10774
+ // shouted louder than the message it was counting.
10775
+ // Enough to catch the eye scanning the list, no more.
10776
+ /* @__PURE__ */ jsx(
10777
+ Badge,
10778
+ {
10779
+ variant: "accent",
10780
+ className: cn(
10781
+ "min-w-[1.125rem] justify-center rounded-full px-1 py-0 text-xs font-medium leading-[1.125rem] shadow-none",
10782
+ classNames?.unreadBadge
10783
+ ),
10784
+ children: unreadCount
10785
+ }
10786
+ )
10787
+ ) : null
10788
+ ] }),
10789
+ /* @__PURE__ */ jsxs("div", { className: "mt-1 flex items-center gap-1.5", children: [
10790
+ lastMessage?.isMine ? lastMessage.read ? /* @__PURE__ */ jsx(
10791
+ CheckCheck,
10792
+ {
10793
+ className: "size-3.5 shrink-0 text-ai-accent",
10794
+ "aria-label": "Read"
10795
+ }
10796
+ ) : /* @__PURE__ */ jsx(
10797
+ Check,
10798
+ {
10799
+ className: "size-3.5 shrink-0 text-muted-foreground",
10800
+ "aria-label": "Sent"
10801
+ }
10802
+ ) : null,
10803
+ /* @__PURE__ */ jsx(
10804
+ "p",
10805
+ {
10806
+ className: cn(
10807
+ "min-w-0 flex-1 truncate text-xs",
10808
+ unread ? "font-medium text-foreground" : "text-muted-foreground"
10809
+ ),
10810
+ children: c.subtitle ?? preview
10811
+ }
10812
+ ),
10813
+ /* @__PURE__ */ jsx("span", { className: "shrink-0 text-xs text-muted-foreground", children: lastMessage ? formatRelativeTime(lastMessage.createdAt) : "" })
10814
+ ] })
10815
+ ] })
10816
+ ] });
10817
+ const rowClass = cn(
10818
+ // Each row is its own opaque surface. Left transparent it takes
10819
+ // the panel's colour, and the chips stop reading as cards at all
10820
+ // — which is the whole point of them.
10821
+ "flex w-full items-start gap-3 border-b border-border/60 bg-card px-4 py-3 text-left transition-colors",
10822
+ c.disabled ? "cursor-default" : active ? "bg-ai-accent-soft" : "hover:bg-accent/40"
10823
+ );
10824
+ return /* @__PURE__ */ jsxs("li", { children: [
10825
+ newSection && /* @__PURE__ */ jsx(
10826
+ "p",
10827
+ {
10828
+ className: "bg-muted/40 px-4 py-1.5 text-xs font-medium uppercase tracking-wide text-muted-foreground",
10829
+ "data-testid": "arbi-dm-section",
10830
+ children: c.sectionLabel
10831
+ }
10832
+ ),
10833
+ c.disabled ? /* @__PURE__ */ jsxs("div", { "data-testid": `arbi-dm-conversation-${rowId}`, className: rowClass, children: [
10834
+ body,
10835
+ c.trailing
10836
+ ] }) : /* @__PURE__ */ jsx(
10837
+ "button",
10838
+ {
10839
+ type: "button",
10840
+ onClick: () => onSelect(rowId),
10841
+ "data-testid": `arbi-dm-conversation-${rowId}`,
10842
+ className: rowClass,
10843
+ children: body
10844
+ }
10845
+ )
10846
+ ] }, rowId);
10847
+ }) }) })
10848
+ ]
10715
10849
  }
10716
- return out;
10717
- }, [data, me]);
10718
- }
10719
- function useChatSummaries(chats2) {
10720
- const arbi = useArbi();
10721
- const [summaries, setSummaries] = useState({});
10722
- const runId = useRef(0);
10723
- const key = chats2.map(
10724
- (c) => `${c.external_id}:${c.key_version}:${c.title ?? ""}:${c.last_message?.external_id ?? ""}:${c.last_message?.deleted ? "x" : ""}`
10725
- ).join("|");
10726
- useEffect(() => {
10727
- if (!chats2.length || !arbi.isLoggedIn) return;
10728
- const id = ++runId.current;
10729
- void (async () => {
10730
- const next = {};
10731
- for (const chat of chats2) {
10732
- const title = await arbi.chats.title(chat).catch(() => null);
10733
- const last = chat.last_message?.deleted ? null : chat.last_message;
10734
- let preview = null;
10735
- if (last) {
10736
- preview = await arbi.chats.decrypt(chat, last).then(chats.chatMessagePreview).catch(() => chats.ENCRYPTED_PREVIEW);
10737
- }
10738
- next[chat.external_id] = { title, preview };
10739
- }
10740
- if (id === runId.current) setSummaries(next);
10741
- })();
10742
- }, [key, arbi]);
10743
- return summaries;
10850
+ );
10744
10851
  }
10745
- function useChatThread(chat) {
10746
- const arbi = useArbi();
10747
- const queryClient = useQueryClient();
10748
- const chatExtId = chat?.external_id ?? "";
10749
- const chatRef = useRef(chat);
10750
- chatRef.current = chat;
10751
- const query = useQuery({
10752
- queryKey: arbiQueryKeys.chatThread(chatExtId),
10753
- queryFn: () => arbi.chats.page(chatRef.current),
10754
- enabled: !!chat && arbi.isLoggedIn,
10755
- staleTime: Infinity
10756
- });
10757
- const [loadingOlder, setLoadingOlder] = useState(false);
10758
- const loadOlder = useCallback(async () => {
10759
- const key = arbiQueryKeys.chatThread(chatExtId);
10760
- const current = queryClient.getQueryData(key);
10761
- const oldest = current?.messages.find((m) => !m.optimistic);
10762
- if (!chatRef.current || !current?.hasMore || !oldest) return;
10763
- setLoadingOlder(true);
10852
+ function DmComposer({
10853
+ placeholder,
10854
+ disabled,
10855
+ busy,
10856
+ onSend,
10857
+ allowAttachments,
10858
+ error,
10859
+ children,
10860
+ classNames
10861
+ }) {
10862
+ const [draft, setDraft] = useState("");
10863
+ const [files, setFiles] = useState([]);
10864
+ const [attachError, setAttachError] = useState(null);
10865
+ const [dragging, setDragging] = useState(false);
10866
+ const inputRef = useRef(null);
10867
+ const fileInputRef = useRef(null);
10868
+ const addFiles = (added) => {
10869
+ if (!allowAttachments || added.length === 0) return;
10870
+ const next = [...files, ...added];
10764
10871
  try {
10765
- const page = await arbi.chats.page(chatRef.current, { before: oldest.external_id });
10766
- queryClient.setQueryData(
10767
- key,
10768
- (old) => old ? {
10769
- hasMore: page.hasMore,
10770
- messages: [
10771
- ...page.messages.filter(
10772
- (m) => !old.messages.some((o) => o.external_id === m.external_id)
10773
- ),
10774
- ...old.messages
10775
- ]
10776
- } : old
10777
- );
10778
- } finally {
10779
- setLoadingOlder(false);
10872
+ chats.checkChatAttachmentLimits(next);
10873
+ setFiles(next);
10874
+ setAttachError(null);
10875
+ } catch (err) {
10876
+ setAttachError(err instanceof Error ? err.message : "Could not attach the file");
10780
10877
  }
10781
- }, [arbi, queryClient, chatExtId]);
10782
- return {
10783
- messages: query.data?.messages ?? [],
10784
- hasMore: query.data?.hasMore ?? false,
10785
- isLoading: query.isLoading && !!chat,
10786
- loadOlder,
10787
- loadingOlder
10788
10878
  };
10789
- }
10790
- function useChatPost() {
10791
- const arbi = useArbi();
10792
- const queryClient = useQueryClient();
10793
- return useCallback(
10794
- async (target, post) => {
10795
- const me = myChatId(arbi);
10796
- if (!me) throw new Error("No active session");
10797
- let chat = target.chat;
10798
- if (!chat) {
10799
- if (!target.peerExtId) throw new Error("Could not resolve the conversation");
10800
- chat = await arbi.chats.openDirect(target.peerExtId);
10801
- upsertChat(queryClient, chat);
10802
- queryClient.setQueryData(
10803
- arbiQueryKeys.chatThread(chat.external_id),
10804
- (old) => old ?? { messages: [], hasMore: false }
10805
- );
10806
- }
10807
- const files = post.files ?? [];
10808
- const optimisticId = `optimistic-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`;
10809
- const now = (/* @__PURE__ */ new Date()).toISOString();
10810
- const optimistic = {
10811
- external_id: optimisticId,
10812
- chat_ext_id: chat.external_id,
10813
- sender_ext_id: me,
10814
- kind: "text",
10815
- content: post.text,
10816
- key_version: chat.key_version,
10817
- deleted: false,
10818
- context_only: !!post.contextOnly,
10819
- workspace_ext_id: post.workspaceExtId ?? null,
10820
- created_at: now,
10821
- updated_at: now,
10822
- optimistic: true
10823
- };
10824
- appendToThread(queryClient, chat.external_id, optimistic);
10825
- try {
10826
- let attachments = [];
10827
- if (files.length) {
10828
- chats.checkChatAttachmentLimits(files);
10829
- attachments = await arbi.chats.uploadAttachments(
10830
- await Promise.all(
10831
- files.map(async (file) => ({
10832
- name: file.name,
10833
- type: file.type,
10834
- bytes: new Uint8Array(await file.arrayBuffer())
10835
- }))
10836
- )
10837
- );
10838
- }
10839
- const message = await arbi.chats.send(chat, post.text, {
10840
- attachments,
10841
- ...post.workspaceExtId ? { workspaceExtId: post.workspaceExtId } : {},
10842
- contextOnly: !!post.contextOnly
10843
- });
10844
- appendToThread(queryClient, chat.external_id, message, optimisticId);
10845
- upsertChat(queryClient, {
10846
- ...chat,
10847
- last_message: message,
10848
- last_message_at: message.created_at
10849
- });
10850
- return { chat, message };
10851
- } catch (err) {
10852
- dropFromThread(queryClient, chat.external_id, optimisticId);
10853
- void queryClient.invalidateQueries({ queryKey: arbiQueryKeys.chatList() });
10854
- throw err;
10855
- }
10856
- },
10857
- [arbi, queryClient]
10858
- );
10859
- }
10860
- function useDeleteChatMessage() {
10861
- const arbi = useArbi();
10862
- const queryClient = useQueryClient();
10863
- return useCallback(
10864
- (chatExtId, messageExtId) => deleteChatMessage(arbi, queryClient, chatExtId, messageExtId),
10865
- [arbi, queryClient]
10866
- );
10867
- }
10868
- function useMarkChatRead() {
10869
- const arbi = useArbi();
10870
- const queryClient = useQueryClient();
10871
- return useCallback(
10872
- (chat, messageExtId) => {
10873
- upsertChat(queryClient, { ...chat, unread_count: 0 });
10874
- return arbi.chats.markRead(chat.external_id, messageExtId).then(
10875
- () => void 0,
10876
- () => void 0
10877
- );
10878
- },
10879
- [arbi, queryClient]
10880
- );
10881
- }
10882
- function useCreateGroupChat() {
10883
- const arbi = useArbi();
10884
- const queryClient = useQueryClient();
10885
- return useMutation({
10886
- mutationFn: (params) => arbi.chats.createGroup(params),
10887
- onSuccess: (chat) => upsertChat(queryClient, chat)
10888
- });
10889
- }
10890
- function useRenameChat() {
10891
- const arbi = useArbi();
10892
- const queryClient = useQueryClient();
10893
- return useMutation({
10894
- mutationFn: (vars) => arbi.chats.rename(vars.chat, vars.title),
10895
- onSuccess: (chat) => upsertChat(queryClient, chat)
10896
- });
10897
- }
10898
- function useAddChatMembers() {
10899
- const arbi = useArbi();
10900
- const queryClient = useQueryClient();
10901
- return useMutation({
10902
- mutationFn: (vars) => arbi.chats.addMembers(vars.chat, vars.members, { callKey: vars.callKey }),
10903
- onSuccess: (chat) => upsertChat(queryClient, chat)
10904
- });
10905
- }
10906
- function useRemoveChatMember() {
10907
- const arbi = useArbi();
10908
- const queryClient = useQueryClient();
10909
- return useMutation({
10910
- mutationFn: (vars) => arbi.chats.removeMember(vars.chat, vars.userExtId),
10911
- onSuccess: (_data, vars) => {
10912
- if (vars.userExtId === myChatId(arbi)) removeChat(queryClient, vars.chat.external_id);
10913
- else return queryClient.invalidateQueries({ queryKey: arbiQueryKeys.chatList() });
10879
+ const removeFile = (index) => {
10880
+ setFiles((current) => current.filter((_, i) => i !== index));
10881
+ setAttachError(null);
10882
+ };
10883
+ const submit = async () => {
10884
+ const text = draft.trim();
10885
+ if (!text && files.length === 0 || disabled || busy) return;
10886
+ const sending = files;
10887
+ setDraft("");
10888
+ setFiles([]);
10889
+ setAttachError(null);
10890
+ try {
10891
+ await onSend(text, sending);
10892
+ inputRef.current?.focus();
10893
+ } catch {
10894
+ setDraft(text);
10895
+ setFiles(sending);
10914
10896
  }
10915
- });
10916
- }
10917
-
10918
- // src/directmessages/useDirectMessages.ts
10919
- function mergeContacts(threads, contacts) {
10920
- const byPeer = /* @__PURE__ */ new Map();
10921
- for (const t of threads) byPeer.set(t.peer.external_id, t);
10922
- for (const c of contacts) {
10923
- const peer = c.user;
10924
- if (!peer?.external_id || byPeer.has(peer.external_id)) continue;
10925
- byPeer.set(peer.external_id, { peer, messages: [], unreadCount: 0, isContactOnly: true });
10926
- }
10927
- return [...byPeer.values()].sort((a, b) => {
10928
- const at = a.lastMessage?.createdAt;
10929
- const bt = b.lastMessage?.createdAt;
10930
- if (at && bt) return bt.localeCompare(at);
10931
- if (at) return -1;
10932
- if (bt) return 1;
10933
- return userDisplayName(a.peer).localeCompare(userDisplayName(b.peer));
10934
- });
10935
- }
10936
- function toConversation(chat, thread, myExtId) {
10937
- const peerMember = chat.members.find((m) => m.user.external_id !== myExtId);
10938
- if (!peerMember) return null;
10939
- const meMember = chat.members.find((m) => m.user.external_id === myExtId);
10940
- const peer = peerMember.user;
10941
- const userById = new Map(chat.members.map((m) => [m.user.external_id, m.user]));
10942
- const messages = (thread?.messages ?? []).filter((m) => m.kind === "text" && !m.context_only).map((m) => {
10943
- const isMine = m.sender_ext_id === myExtId;
10944
- const sender = userById.get(m.sender_ext_id ?? "") ?? { external_id: m.sender_ext_id ?? "usr-unknown" };
10945
- return {
10946
- externalId: m.external_id,
10947
- // A tombstone (deleted) has no content: it renders as "Message deleted".
10948
- body: m.deleted ? "" : m.content ?? "",
10949
- createdAt: m.created_at,
10950
- isMine,
10951
- // Mine: has the peer read it? Theirs: have I? (Never for a send still in flight.)
10952
- read: !m.optimistic && chats.hasRead(isMine ? peerMember : meMember, m),
10953
- sender,
10954
- recipient: isMine ? peer : meMember?.user,
10955
- chatExtId: chat.external_id,
10956
- ...m.deleted ? { deleted: true } : {}
10957
- };
10958
- });
10959
- messages.sort((a, b) => a.createdAt.localeCompare(b.createdAt));
10960
- if (messages.length === 0) return null;
10961
- const shown = messages.filter((m) => !m.deleted);
10962
- return {
10963
- peer,
10964
- chatExtId: chat.external_id,
10965
- messages,
10966
- lastMessage: shown[shown.length - 1],
10967
- unreadCount: chat.unread_count ?? 0
10968
10897
  };
10969
- }
10970
- function combineThreads(results) {
10971
- return {
10972
- data: results.map((r) => r.data),
10973
- error: results.find((r) => r.isError)?.error ?? null
10898
+ const onKeyDown = (e) => {
10899
+ if (e.key === "Enter" && !e.shiftKey) {
10900
+ e.preventDefault();
10901
+ void submit();
10902
+ }
10974
10903
  };
10975
- }
10976
- function directPeerId(chat, myExtId) {
10977
- return chat.members.find((m) => m.user.external_id !== myExtId)?.user.external_id ?? myExtId;
10978
- }
10979
- function useDirectMessages(options) {
10980
- const arbi = useArbi();
10981
- const queryClient = useQueryClient();
10982
- const enabled = (options?.enabled ?? true) && arbi.isLoggedIn;
10983
- useChatLiveUpdates();
10984
- const chatsQuery = useChats({ enabled });
10985
- const direct = useMemo(
10986
- () => (chatsQuery.data ?? []).filter((c) => c.kind === "direct"),
10987
- [chatsQuery.data]
10988
- );
10989
- const threads = useQueries({
10990
- queries: direct.map((chat) => ({
10991
- queryKey: arbiQueryKeys.chatThread(chat.external_id),
10992
- queryFn: () => arbi.chats.page(chat),
10993
- enabled,
10994
- staleTime: Infinity
10995
- })),
10996
- combine: combineThreads
10997
- });
10998
- const contactsQuery = useQuery({
10999
- queryKey: arbiQueryKeys.contacts(),
11000
- queryFn: () => arbi.contacts.list(),
11001
- enabled
11002
- });
11003
- const myExtId = myChatId(arbi);
11004
- const conversations = useMemo(() => {
11005
- const rows = direct.map((chat, i) => toConversation(chat, threads.data[i], myExtId)).filter((c) => c !== null);
11006
- return mergeContacts(rows, contactsQuery.data ?? []);
11007
- }, [direct, threads.data, contactsQuery.data, myExtId]);
11008
- const post = useChatPost();
11009
- const markChatRead = useMarkChatRead();
11010
- const [sending, setSending] = useState(0);
11011
- const [sendError, setSendError] = useState(null);
11012
- const sendToPeer = useCallback(
11013
- async (peerExtId, text) => {
11014
- setSending((n) => n + 1);
11015
- setSendError(null);
11016
- try {
11017
- const chat = cachedChats(queryClient).find(
11018
- (c) => c.kind === "direct" && directPeerId(c, myExtId) === peerExtId
11019
- ) ?? null;
11020
- return (await post({ chat, peerExtId }, { text })).message;
11021
- } catch (err) {
11022
- setSendError(err instanceof Error ? err : new Error(String(err)));
11023
- throw err;
11024
- } finally {
11025
- setSending((n) => n - 1);
11026
- }
10904
+ const onPaste = (e) => {
10905
+ if (!allowAttachments) return;
10906
+ const pasted = Array.from(e.clipboardData?.files ?? []);
10907
+ if (pasted.length === 0) return;
10908
+ e.preventDefault();
10909
+ addFiles(pasted);
10910
+ };
10911
+ const hasFiles = (e) => Array.from(e.dataTransfer?.types ?? []).includes("Files");
10912
+ const dropHandlers = allowAttachments ? {
10913
+ onDragOver: (e) => {
10914
+ if (!hasFiles(e) || disabled) return;
10915
+ e.preventDefault();
10916
+ setDragging(true);
11027
10917
  },
11028
- [post, queryClient, myExtId]
11029
- );
11030
- return {
11031
- conversations,
11032
- myExtId,
11033
- isLoading: (chatsQuery.isLoading || contactsQuery.isLoading) && enabled,
11034
- isError: chatsQuery.isError || threads.error !== null,
11035
- error: chatsQuery.error ?? threads.error,
11036
- refetch: () => void queryClient.invalidateQueries({ queryKey: arbiQueryKeys.chats() }),
11037
- sendMessage: (recipientExtId, _recipientPublicKey, text) => sendToPeer(recipientExtId, text),
11038
- sendMessageTo: async (recipient, text) => {
11039
- if (!recipient.includes("@")) return sendToPeer(recipient, text);
11040
- const resolved = await arbi.dm.resolveRecipient(recipient).catch(() => null);
11041
- if (!resolved) {
11042
- const err = new Error(
11043
- `Could not resolve recipient "${recipient}" (not a known contact, agent, or workspace member)`
11044
- );
11045
- setSendError(err);
11046
- throw err;
11047
- }
11048
- return sendToPeer(resolved.extId, text);
10918
+ onDragLeave: (e) => {
10919
+ if (e.currentTarget.contains(e.relatedTarget)) return;
10920
+ setDragging(false);
11049
10921
  },
11050
- isSending: sending > 0,
11051
- sendError,
11052
- markRead: (chatExtId, messageExtId) => {
11053
- const chat = (chatsQuery.data ?? []).find((c) => c.external_id === chatExtId);
11054
- return chat ? markChatRead(chat, messageExtId) : arbi.chats.markRead(chatExtId, messageExtId);
10922
+ onDrop: (e) => {
10923
+ setDragging(false);
10924
+ const dropped = Array.from(e.dataTransfer?.files ?? []);
10925
+ if (dropped.length === 0 || disabled) return;
10926
+ e.preventDefault();
10927
+ addFiles(dropped);
11055
10928
  }
11056
- };
11057
- }
11058
- function DmAvatar({ user, className, size = "lg" }) {
11059
- const presence = useArbiWsStore((s) => s.presence[user.external_id]);
11060
- const displayStatus = presence === void 0 ? void 0 : presence === "online" ? "connected" : "disconnected";
11061
- return /* @__PURE__ */ jsx(
11062
- UserEntity,
11063
- {
11064
- variant: "icon",
11065
- size,
11066
- className,
11067
- interactive: false,
11068
- showTooltip: false,
11069
- initials: userInitials(user),
11070
- displayName: userDisplayName(user),
11071
- picture: user.picture,
11072
- avatarStyle: getEntityColorStyles(user.external_id),
11073
- isAgent: isAgentUser(user),
11074
- displayStatus
11075
- }
11076
- );
11077
- }
11078
- function ConversationList({
11079
- conversations,
11080
- selectedPeerId,
11081
- onSelect,
11082
- classNames,
11083
- emptyState,
11084
- header,
11085
- lead,
11086
- className
11087
- }) {
10929
+ } : {};
11088
10930
  return /* @__PURE__ */ jsxs(
11089
- "aside",
10931
+ "div",
11090
10932
  {
11091
10933
  className: cn(
11092
- "flex min-h-0 flex-col border-b border-border md:w-80 md:shrink-0 md:border-b-0 md:border-r",
11093
- className
10934
+ "border-t border-border p-3",
10935
+ dragging && "bg-muted/60 outline-dashed outline-2 -outline-offset-4 outline-primary"
11094
10936
  ),
11095
- "data-testid": "arbi-dm-list",
10937
+ "data-testid": "arbi-dm-composer",
10938
+ ...dropHandlers,
11096
10939
  children: [
11097
- header === void 0 ? /* @__PURE__ */ jsxs("div", { className: "border-b border-border px-4 py-3", children: [
11098
- /* @__PURE__ */ jsx("p", { className: "text-sm font-semibold text-foreground", children: "Conversations" }),
11099
- /* @__PURE__ */ jsxs("p", { className: "text-xs text-muted-foreground", children: [
11100
- conversations.length,
11101
- " ",
11102
- conversations.length === 1 ? "colleague" : "colleagues"
11103
- ] })
11104
- ] }) : header,
11105
- lead,
11106
- /* @__PURE__ */ jsx("div", { className: "min-h-0 flex-1 overflow-y-auto", children: conversations.length === 0 ? /* @__PURE__ */ jsx("div", { className: "px-4 py-6 text-xs text-muted-foreground", children: emptyState ?? "No conversations yet." }) : /* @__PURE__ */ jsx("ul", { className: "w-full", children: conversations.map((c, i) => {
11107
- const { peer, lastMessage, unreadCount } = c;
11108
- const rowId = c.id ?? peer.external_id;
11109
- const newSection = c.sectionLabel && c.sectionLabel !== conversations[i - 1]?.sectionLabel;
11110
- const active = rowId === selectedPeerId;
11111
- const preview = lastMessage?.body ?? "No messages yet \u2014 say hello";
11112
- const unread = unreadCount > 0;
11113
- const body = /* @__PURE__ */ jsxs(Fragment, { children: [
11114
- c.leading ?? /* @__PURE__ */ jsx(DmAvatar, { user: peer }),
11115
- /* @__PURE__ */ jsxs("div", { className: "min-w-0 flex-1", children: [
11116
- /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between gap-2", children: [
11117
- /* @__PURE__ */ jsxs("span", { className: "flex min-w-0 items-center gap-1.5", children: [
11118
- /* @__PURE__ */ jsx(
11119
- "span",
11120
- {
11121
- className: cn(
11122
- "truncate text-sm text-foreground",
11123
- unread ? "font-bold" : "font-semibold"
11124
- ),
11125
- children: c.title ?? userDisplayName(peer)
11126
- }
11127
- ),
11128
- c.badge ?? (isAgentUser(peer) ? /* @__PURE__ */ jsx(AgentBadge, {}) : null)
11129
- ] }),
11130
- c.statusLabel ? /* @__PURE__ */ jsx(
11131
- Badge,
11132
- {
11133
- variant: "outline",
11134
- className: "shrink-0 rounded-full px-2 py-0 text-xs font-medium text-muted-foreground",
11135
- children: c.statusLabel
11136
- }
11137
- ) : unreadCount > 0 ? (
11138
- // Quiet by default: a filled brand pill with a shadow
11139
- // shouted louder than the message it was counting.
11140
- // Enough to catch the eye scanning the list, no more.
11141
- /* @__PURE__ */ jsx(
11142
- Badge,
11143
- {
11144
- variant: "accent",
11145
- className: cn(
11146
- "min-w-[1.125rem] justify-center rounded-full px-1 py-0 text-xs font-medium leading-[1.125rem] shadow-none",
11147
- classNames?.unreadBadge
11148
- ),
11149
- children: unreadCount
11150
- }
11151
- )
11152
- ) : null
11153
- ] }),
11154
- /* @__PURE__ */ jsxs("div", { className: "mt-1 flex items-center gap-1.5", children: [
11155
- lastMessage?.isMine ? lastMessage.read ? /* @__PURE__ */ jsx(
11156
- CheckCheck,
11157
- {
11158
- className: "size-3.5 shrink-0 text-ai-accent",
11159
- "aria-label": "Read"
11160
- }
11161
- ) : /* @__PURE__ */ jsx(
11162
- Check,
11163
- {
11164
- className: "size-3.5 shrink-0 text-muted-foreground",
11165
- "aria-label": "Sent"
11166
- }
11167
- ) : null,
11168
- /* @__PURE__ */ jsx(
11169
- "p",
11170
- {
11171
- className: cn(
11172
- "min-w-0 flex-1 truncate text-xs",
11173
- unread ? "font-medium text-foreground" : "text-muted-foreground"
11174
- ),
11175
- children: c.subtitle ?? preview
11176
- }
11177
- ),
11178
- /* @__PURE__ */ jsx("span", { className: "shrink-0 text-xs text-muted-foreground", children: lastMessage ? formatRelativeTime(lastMessage.createdAt) : "" })
11179
- ] })
11180
- ] })
11181
- ] });
11182
- const rowClass = cn(
11183
- // Each row is its own opaque surface. Left transparent it takes
11184
- // the panel's colour, and the chips stop reading as cards at all
11185
- // — which is the whole point of them.
11186
- "flex w-full items-start gap-3 border-b border-border/60 bg-card px-4 py-3 text-left transition-colors",
11187
- c.disabled ? "cursor-default" : active ? "bg-ai-accent-soft" : "hover:bg-accent/40"
11188
- );
11189
- return /* @__PURE__ */ jsxs("li", { children: [
11190
- newSection && /* @__PURE__ */ jsx(
11191
- "p",
10940
+ children,
10941
+ files.length > 0 && /* @__PURE__ */ jsx("ul", { className: "mb-2 flex flex-wrap gap-2", "aria-label": "Attached files", children: files.map((f, index) => /* @__PURE__ */ jsxs(
10942
+ "li",
10943
+ {
10944
+ "data-testid": "arbi-dm-attachment-chip",
10945
+ className: "flex max-w-full items-center gap-2 rounded-md border border-border/70 bg-muted/30 px-2.5 py-1.5 text-xs",
10946
+ children: [
10947
+ /* @__PURE__ */ jsx(Paperclip, { className: "size-3 shrink-0", "aria-hidden": "true" }),
10948
+ /* @__PURE__ */ jsx("span", { className: "truncate", children: f.name }),
10949
+ /* @__PURE__ */ jsx("span", { className: "shrink-0 text-muted-foreground", children: formatFileSize(f.size) }),
10950
+ /* @__PURE__ */ jsx(
10951
+ "button",
10952
+ {
10953
+ type: "button",
10954
+ disabled: busy,
10955
+ "aria-label": `Remove ${f.name}`,
10956
+ onClick: () => removeFile(index),
10957
+ className: "shrink-0 rounded focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring",
10958
+ children: /* @__PURE__ */ jsx(X, { className: "size-3" })
10959
+ }
10960
+ )
10961
+ ]
10962
+ },
10963
+ `${f.name}-${index}`
10964
+ )) }),
10965
+ /* @__PURE__ */ jsxs("div", { className: "flex items-end gap-2", children: [
10966
+ allowAttachments && /* @__PURE__ */ jsxs(Fragment, { children: [
10967
+ /* @__PURE__ */ jsx(
10968
+ Button,
11192
10969
  {
11193
- className: "bg-muted/40 px-4 py-1.5 text-xs font-medium uppercase tracking-wide text-muted-foreground",
11194
- "data-testid": "arbi-dm-section",
11195
- children: c.sectionLabel
10970
+ type: "button",
10971
+ variant: "ghost",
10972
+ size: "icon",
10973
+ disabled: disabled || busy,
10974
+ onClick: () => fileInputRef.current?.click(),
10975
+ "aria-label": "Attach files",
10976
+ title: "Attach files (or paste / drop them here)",
10977
+ "data-testid": "arbi-dm-attach",
10978
+ className: "min-h-[44px] shrink-0",
10979
+ children: /* @__PURE__ */ jsx(Paperclip, { className: "size-4" })
11196
10980
  }
11197
10981
  ),
11198
- c.disabled ? /* @__PURE__ */ jsxs("div", { "data-testid": `arbi-dm-conversation-${rowId}`, className: rowClass, children: [
11199
- body,
11200
- c.trailing
11201
- ] }) : /* @__PURE__ */ jsx(
11202
- "button",
10982
+ /* @__PURE__ */ jsx(
10983
+ "input",
11203
10984
  {
11204
- type: "button",
11205
- onClick: () => onSelect(rowId),
11206
- "data-testid": `arbi-dm-conversation-${rowId}`,
11207
- className: rowClass,
11208
- children: body
10985
+ ref: fileInputRef,
10986
+ type: "file",
10987
+ multiple: true,
10988
+ hidden: true,
10989
+ "data-testid": "arbi-dm-file-input",
10990
+ onChange: (e) => {
10991
+ addFiles(Array.from(e.target.files ?? []));
10992
+ e.target.value = "";
10993
+ }
11209
10994
  }
11210
10995
  )
11211
- ] }, rowId);
11212
- }) }) })
10996
+ ] }),
10997
+ /* @__PURE__ */ jsx(
10998
+ Textarea,
10999
+ {
11000
+ ref: inputRef,
11001
+ value: draft,
11002
+ onChange: (e) => setDraft(e.target.value),
11003
+ onKeyDown,
11004
+ onPaste,
11005
+ placeholder,
11006
+ rows: 1,
11007
+ disabled,
11008
+ className: "max-h-40 min-h-[44px] resize-none",
11009
+ "data-testid": "arbi-dm-input"
11010
+ }
11011
+ ),
11012
+ /* @__PURE__ */ jsxs(
11013
+ Button,
11014
+ {
11015
+ type: "button",
11016
+ onClick: () => void submit(),
11017
+ disabled: disabled || busy || !draft.trim() && files.length === 0,
11018
+ className: cn(classNames?.sendButton),
11019
+ "data-testid": "arbi-dm-send",
11020
+ "aria-label": "Send message",
11021
+ children: [
11022
+ busy ? /* @__PURE__ */ jsx(Loader2, { className: "size-4 animate-spin" }) : /* @__PURE__ */ jsx(Send, { className: "size-4" }),
11023
+ " Send"
11024
+ ]
11025
+ }
11026
+ )
11027
+ ] }),
11028
+ attachError && /* @__PURE__ */ jsx(
11029
+ "p",
11030
+ {
11031
+ className: "mt-2 text-xs text-destructive",
11032
+ role: "alert",
11033
+ "data-testid": "arbi-dm-attach-error",
11034
+ children: attachError
11035
+ }
11036
+ ),
11037
+ error && /* @__PURE__ */ jsx("p", { className: "mt-2 text-xs text-destructive", "data-testid": "arbi-dm-error", children: error })
11213
11038
  ]
11214
11039
  }
11215
11040
  );
11216
11041
  }
11217
-
11218
- // src/directmessages/grouping.ts
11219
- var RUN_WINDOW_MS = 2 * 60 * 1e3;
11220
- function dayKey(iso) {
11221
- const d = new Date(iso);
11222
- if (Number.isNaN(d.getTime())) return iso;
11223
- return `${d.getFullYear()}-${d.getMonth() + 1}-${d.getDate()}`;
11042
+ function useChats(options = {}) {
11043
+ const arbi = useArbi();
11044
+ return useQuery({
11045
+ queryKey: arbiQueryKeys.chatList(),
11046
+ queryFn: () => arbi.chats.list(),
11047
+ enabled: (options.enabled ?? true) && arbi.isLoggedIn
11048
+ });
11224
11049
  }
11225
- function annotateThread(messages, accessors, runWindowMs = RUN_WINDOW_MS) {
11226
- const { senderId, createdAt } = accessors;
11227
- return messages.map((message, i) => {
11228
- const next = messages[i + 1];
11229
- const prev = messages[i - 1];
11230
- const day = dayKey(createdAt(message));
11231
- const continuesIntoNext = !!next && senderId(next) === senderId(message) && dayKey(createdAt(next)) === day && Date.parse(createdAt(next)) - Date.parse(createdAt(message)) < runWindowMs;
11232
- return {
11233
- message,
11234
- isLastOfRun: !continuesIntoNext,
11235
- isFirstOfDay: !prev || dayKey(createdAt(prev)) !== day
11236
- };
11237
- });
11050
+ function useChatLiveUpdates() {
11051
+ const arbi = useArbi();
11052
+ const queryClient = useQueryClient();
11053
+ const ws = useContext(ArbiWsContext);
11054
+ const arbiRef = useRef(arbi);
11055
+ arbiRef.current = arbi;
11056
+ useEffect(
11057
+ () => ws?.subscribe((message) => {
11058
+ if (message.type.startsWith("chat.") || message.type === "agent_dm_status")
11059
+ void applyChatEvent(arbiRef.current, queryClient, message);
11060
+ }),
11061
+ [ws, queryClient]
11062
+ );
11238
11063
  }
11239
- function DateSeparator({ children }) {
11240
- return /* @__PURE__ */ jsx("div", { className: "my-3 flex justify-center", "data-testid": "dm-date-separator", children: /* @__PURE__ */ jsx("span", { className: "rounded-full bg-background/80 px-2 py-0.5 text-xs text-muted-foreground", children }) });
11064
+ function useAgentDmStatus(agentExtId) {
11065
+ const { data } = useQuery({
11066
+ queryKey: arbiQueryKeys.agentDmStatus(agentExtId ?? ""),
11067
+ // Written by the events only: nothing to fetch.
11068
+ queryFn: () => null,
11069
+ enabled: false,
11070
+ staleTime: Infinity
11071
+ });
11072
+ return agentExtId ? data ?? void 0 : void 0;
11241
11073
  }
11242
- function MessageBubble({
11243
- message,
11244
- classNames,
11245
- isLastOfRun = true,
11246
- onDelete,
11247
- deleted
11248
- }) {
11249
- return /* @__PURE__ */ jsx(
11250
- ChatBubble,
11251
- {
11252
- "data-testid": "arbi-dm-message",
11253
- message: message.body,
11254
- timestamp: message.createdAt,
11255
- isSent: message.isMine,
11256
- read: message.read,
11257
- deleted,
11258
- onDelete,
11259
- isLastOfRun,
11260
- senderName: message.isMine ? "You" : userDisplayName(message.sender),
11261
- classNames,
11262
- formatTimestamp: formatRelativeTime
11263
- }
11264
- );
11265
- }
11266
- var THREAD_ACCESSORS = {
11267
- senderId: (m) => m.sender.external_id,
11268
- createdAt: (m) => m.createdAt
11269
- };
11270
- function MessageThread({
11271
- conversation,
11272
- classNames,
11273
- emptyState,
11274
- formatDay,
11275
- onDeleteMessage
11276
- }) {
11277
- const bottomRef = useRef(null);
11278
- const items = useMemo(
11279
- () => annotateThread(conversation?.messages ?? [], THREAD_ACCESSORS),
11280
- [conversation?.messages]
11281
- );
11282
- useEffect(() => {
11283
- bottomRef.current?.scrollIntoView({ block: "end" });
11284
- }, [conversation?.id, conversation?.peer.external_id, conversation?.messages.length]);
11285
- if (!conversation) {
11286
- return /* @__PURE__ */ jsx("section", { className: "flex min-h-0 flex-1 flex-col items-center justify-center gap-3 p-8 text-center", children: emptyState ?? /* @__PURE__ */ jsxs(Fragment, { children: [
11287
- /* @__PURE__ */ jsx("div", { className: "flex size-14 items-center justify-center rounded-full bg-accent", children: /* @__PURE__ */ jsx(MessagesSquare, { className: "size-6 text-muted-foreground" }) }),
11288
- /* @__PURE__ */ jsxs("div", { children: [
11289
- /* @__PURE__ */ jsx("p", { className: "text-sm font-semibold text-foreground", children: "No conversation selected" }),
11290
- /* @__PURE__ */ jsx("p", { className: "mx-auto mt-1 max-w-xs text-xs text-muted-foreground", children: "Choose a colleague from the list to read the thread and send a direct message." })
11291
- ] })
11292
- ] }) });
11293
- }
11294
- const { peer, title, memberCount } = conversation;
11295
- return /* @__PURE__ */ jsxs(Fragment, { children: [
11296
- /* @__PURE__ */ jsxs("header", { className: "flex items-center gap-3 border-b border-border px-4 py-3", children: [
11297
- /* @__PURE__ */ jsx(DmAvatar, { user: peer, className: "size-9" }),
11298
- /* @__PURE__ */ jsxs("div", { className: "min-w-0", children: [
11299
- /* @__PURE__ */ jsx("p", { className: "truncate text-sm font-semibold text-foreground", children: title ?? userDisplayName(peer) }),
11300
- /* @__PURE__ */ jsx("p", { className: "truncate text-xs text-muted-foreground", children: memberCount != null ? `${memberCount} members` : peer.email })
11301
- ] })
11302
- ] }),
11303
- /* @__PURE__ */ jsx(ScrollArea, { className: "min-h-0 flex-1 bg-background", children: /* @__PURE__ */ jsxs("div", { className: "flex flex-col px-4 py-4", "data-testid": "arbi-dm-thread", children: [
11304
- items.map(({ message: m, isLastOfRun, isFirstOfDay }) => /* @__PURE__ */ jsxs(Fragment$1, { children: [
11305
- isFirstOfDay && formatDay && /* @__PURE__ */ jsx(DateSeparator, { children: formatDay(m.createdAt) }),
11306
- /* @__PURE__ */ jsx(
11307
- MessageBubble,
11308
- {
11309
- message: m,
11310
- classNames,
11311
- isLastOfRun,
11312
- deleted: m.deleted,
11313
- onDelete: onDeleteMessage && !m.deleted ? () => onDeleteMessage(m) : void 0
11314
- }
11315
- )
11316
- ] }, m.externalId)),
11317
- /* @__PURE__ */ jsx("div", { ref: bottomRef })
11318
- ] }) })
11319
- ] });
11074
+ function useChatUnreadTotal() {
11075
+ const { data = [] } = useChats();
11076
+ return useMemo(() => data.reduce((sum, c) => sum + (c.unread_count ?? 0), 0), [data]);
11320
11077
  }
11321
- function DmComposer({
11322
- placeholder,
11323
- disabled,
11324
- busy,
11325
- onSend,
11326
- allowAttachments,
11327
- error,
11328
- children,
11329
- classNames
11330
- }) {
11331
- const [draft, setDraft] = useState("");
11332
- const [files, setFiles] = useState([]);
11333
- const [attachError, setAttachError] = useState(null);
11334
- const [dragging, setDragging] = useState(false);
11335
- const inputRef = useRef(null);
11336
- const fileInputRef = useRef(null);
11337
- const addFiles = (added) => {
11338
- if (!allowAttachments || added.length === 0) return;
11339
- const next = [...files, ...added];
11340
- try {
11341
- chats.checkChatAttachmentLimits(next);
11342
- setFiles(next);
11343
- setAttachError(null);
11344
- } catch (err) {
11345
- setAttachError(err instanceof Error ? err.message : "Could not attach the file");
11346
- }
11347
- };
11348
- const removeFile = (index) => {
11349
- setFiles((current) => current.filter((_, i) => i !== index));
11350
- setAttachError(null);
11351
- };
11352
- const submit = async () => {
11353
- const text = draft.trim();
11354
- if (!text && files.length === 0 || disabled || busy) return;
11355
- const sending = files;
11356
- setDraft("");
11357
- setFiles([]);
11358
- setAttachError(null);
11359
- try {
11360
- await onSend(text, sending);
11361
- inputRef.current?.focus();
11362
- } catch {
11363
- setDraft(text);
11364
- setFiles(sending);
11365
- }
11366
- };
11367
- const onKeyDown = (e) => {
11368
- if (e.key === "Enter" && !e.shiftKey) {
11369
- e.preventDefault();
11370
- void submit();
11371
- }
11372
- };
11373
- const onPaste = (e) => {
11374
- if (!allowAttachments) return;
11375
- const pasted = Array.from(e.clipboardData?.files ?? []);
11376
- if (pasted.length === 0) return;
11377
- e.preventDefault();
11378
- addFiles(pasted);
11379
- };
11380
- const hasFiles = (e) => Array.from(e.dataTransfer?.types ?? []).includes("Files");
11381
- const dropHandlers = allowAttachments ? {
11382
- onDragOver: (e) => {
11383
- if (!hasFiles(e) || disabled) return;
11384
- e.preventDefault();
11385
- setDragging(true);
11386
- },
11387
- onDragLeave: (e) => {
11388
- if (e.currentTarget.contains(e.relatedTarget)) return;
11389
- setDragging(false);
11390
- },
11391
- onDrop: (e) => {
11392
- setDragging(false);
11393
- const dropped = Array.from(e.dataTransfer?.files ?? []);
11394
- if (dropped.length === 0 || disabled) return;
11395
- e.preventDefault();
11396
- addFiles(dropped);
11397
- }
11398
- } : {};
11399
- return /* @__PURE__ */ jsxs(
11400
- "div",
11401
- {
11402
- className: cn(
11403
- "border-t border-border p-3",
11404
- dragging && "bg-muted/60 outline-dashed outline-2 -outline-offset-4 outline-primary"
11405
- ),
11406
- "data-testid": "arbi-dm-composer",
11407
- ...dropHandlers,
11408
- children: [
11409
- children,
11410
- files.length > 0 && /* @__PURE__ */ jsx("ul", { className: "mb-2 flex flex-wrap gap-2", "aria-label": "Attached files", children: files.map((f, index) => /* @__PURE__ */ jsxs(
11411
- "li",
11412
- {
11413
- "data-testid": "arbi-dm-attachment-chip",
11414
- className: "flex max-w-full items-center gap-2 rounded-md border border-border/70 bg-muted/30 px-2.5 py-1.5 text-xs",
11415
- children: [
11416
- /* @__PURE__ */ jsx(Paperclip, { className: "size-3 shrink-0", "aria-hidden": "true" }),
11417
- /* @__PURE__ */ jsx("span", { className: "truncate", children: f.name }),
11418
- /* @__PURE__ */ jsx("span", { className: "shrink-0 text-muted-foreground", children: formatFileSize(f.size) }),
11419
- /* @__PURE__ */ jsx(
11420
- "button",
11421
- {
11422
- type: "button",
11423
- disabled: busy,
11424
- "aria-label": `Remove ${f.name}`,
11425
- onClick: () => removeFile(index),
11426
- className: "shrink-0 rounded focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring",
11427
- children: /* @__PURE__ */ jsx(X, { className: "size-3" })
11428
- }
11429
- )
11430
- ]
11431
- },
11432
- `${f.name}-${index}`
11433
- )) }),
11434
- /* @__PURE__ */ jsxs("div", { className: "flex items-end gap-2", children: [
11435
- allowAttachments && /* @__PURE__ */ jsxs(Fragment, { children: [
11436
- /* @__PURE__ */ jsx(
11437
- Button,
11438
- {
11439
- type: "button",
11440
- variant: "ghost",
11441
- size: "icon",
11442
- disabled: disabled || busy,
11443
- onClick: () => fileInputRef.current?.click(),
11444
- "aria-label": "Attach files",
11445
- title: "Attach files (or paste / drop them here)",
11446
- "data-testid": "arbi-dm-attach",
11447
- className: "min-h-[44px] shrink-0",
11448
- children: /* @__PURE__ */ jsx(Paperclip, { className: "size-4" })
11449
- }
11450
- ),
11451
- /* @__PURE__ */ jsx(
11452
- "input",
11453
- {
11454
- ref: fileInputRef,
11455
- type: "file",
11456
- multiple: true,
11457
- hidden: true,
11458
- "data-testid": "arbi-dm-file-input",
11459
- onChange: (e) => {
11460
- addFiles(Array.from(e.target.files ?? []));
11461
- e.target.value = "";
11462
- }
11463
- }
11464
- )
11465
- ] }),
11466
- /* @__PURE__ */ jsx(
11467
- Textarea,
11468
- {
11469
- ref: inputRef,
11470
- value: draft,
11471
- onChange: (e) => setDraft(e.target.value),
11472
- onKeyDown,
11473
- onPaste,
11474
- placeholder,
11475
- rows: 1,
11476
- disabled,
11477
- className: "max-h-40 min-h-[44px] resize-none",
11478
- "data-testid": "arbi-dm-input"
11479
- }
11480
- ),
11481
- /* @__PURE__ */ jsxs(
11482
- Button,
11483
- {
11484
- type: "button",
11485
- onClick: () => void submit(),
11486
- disabled: disabled || busy || !draft.trim() && files.length === 0,
11487
- className: cn(classNames?.sendButton),
11488
- "data-testid": "arbi-dm-send",
11489
- "aria-label": "Send message",
11490
- children: [
11491
- busy ? /* @__PURE__ */ jsx(Loader2, { className: "size-4 animate-spin" }) : /* @__PURE__ */ jsx(Send, { className: "size-4" }),
11492
- " Send"
11493
- ]
11494
- }
11495
- )
11496
- ] }),
11497
- attachError && /* @__PURE__ */ jsx(
11498
- "p",
11499
- {
11500
- className: "mt-2 text-xs text-destructive",
11501
- role: "alert",
11502
- "data-testid": "arbi-dm-attach-error",
11503
- children: attachError
11504
- }
11505
- ),
11506
- error && /* @__PURE__ */ jsx("p", { className: "mt-2 text-xs text-destructive", "data-testid": "arbi-dm-error", children: error })
11507
- ]
11078
+ function useUnreadByPeer() {
11079
+ const arbi = useArbi();
11080
+ const { data = [] } = useChats();
11081
+ const me = myChatId(arbi);
11082
+ return useMemo(() => {
11083
+ const out = /* @__PURE__ */ new Map();
11084
+ for (const c of data) {
11085
+ if (c.kind !== "direct" || !c.unread_count) continue;
11086
+ const peer = c.members.find((m) => m.user.external_id !== me)?.user.external_id ?? me;
11087
+ if (peer) out.set(peer, (out.get(peer) ?? 0) + c.unread_count);
11508
11088
  }
11509
- );
11089
+ return out;
11090
+ }, [data, me]);
11510
11091
  }
11511
- var DEFAULT_START_BY_EMAIL_LABELS = {
11512
- email: "Email address",
11513
- emailPlaceholder: "name@example.com",
11514
- message: "Message",
11515
- messagePlaceholder: "Write the first message\u2026",
11516
- send: "Send",
11517
- sending: "Sending\u2026",
11518
- invalidEmail: "Enter a valid email address."
11519
- };
11520
- var EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
11521
- function StartByEmail({
11522
- onStart,
11523
- onStarted,
11524
- classNames,
11525
- labels,
11526
- className
11527
- }) {
11528
- const l = { ...DEFAULT_START_BY_EMAIL_LABELS, ...labels };
11529
- const uid = useId();
11530
- const [email, setEmail] = useState("");
11531
- const [text, setText] = useState("");
11532
- const [busy, setBusy] = useState(false);
11533
- const [error, setError] = useState(null);
11534
- const address = email.trim().toLowerCase();
11535
- const valid = EMAIL.test(address);
11536
- const submit = async () => {
11537
- if (!valid || !text.trim() || busy) return;
11538
- setBusy(true);
11539
- setError(null);
11092
+ function useChatSummaries(chats2) {
11093
+ const arbi = useArbi();
11094
+ const [summaries, setSummaries] = useState({});
11095
+ const runId = useRef(0);
11096
+ const key = chats2.map(
11097
+ (c) => `${c.external_id}:${c.key_version}:${c.title ?? ""}:${c.last_message?.external_id ?? ""}:${c.last_message?.deleted ? "x" : ""}`
11098
+ ).join("|");
11099
+ useEffect(() => {
11100
+ if (!chats2.length || !arbi.isLoggedIn) return;
11101
+ const id = ++runId.current;
11102
+ void (async () => {
11103
+ const next = {};
11104
+ for (const chat of chats2) {
11105
+ const title = await arbi.chats.title(chat).catch(() => null);
11106
+ const last = chat.last_message?.deleted ? null : chat.last_message;
11107
+ let preview = null;
11108
+ if (last) {
11109
+ preview = await arbi.chats.decrypt(chat, last).then(chats.chatMessagePreview).catch(() => chats.ENCRYPTED_PREVIEW);
11110
+ }
11111
+ next[chat.external_id] = { title, preview };
11112
+ }
11113
+ if (id === runId.current) setSummaries(next);
11114
+ })();
11115
+ }, [key, arbi]);
11116
+ return summaries;
11117
+ }
11118
+ function useChatThread(chat) {
11119
+ const arbi = useArbi();
11120
+ const queryClient = useQueryClient();
11121
+ const chatExtId = chat?.external_id ?? "";
11122
+ const chatRef = useRef(chat);
11123
+ chatRef.current = chat;
11124
+ const query = useQuery({
11125
+ queryKey: arbiQueryKeys.chatThread(chatExtId),
11126
+ queryFn: () => arbi.chats.page(chatRef.current),
11127
+ enabled: !!chat && arbi.isLoggedIn,
11128
+ staleTime: Infinity
11129
+ });
11130
+ const [loadingOlder, setLoadingOlder] = useState(false);
11131
+ const loadOlder = useCallback(async () => {
11132
+ const key = arbiQueryKeys.chatThread(chatExtId);
11133
+ const current = queryClient.getQueryData(key);
11134
+ const oldest = current?.messages.find((m) => !m.optimistic);
11135
+ if (!chatRef.current || !current?.hasMore || !oldest) return;
11136
+ setLoadingOlder(true);
11540
11137
  try {
11541
- const result = await onStart(address, text.trim());
11542
- setEmail("");
11543
- setText("");
11544
- onStarted?.(result);
11545
- } catch (e) {
11546
- setError(e instanceof Error ? e.message : String(e));
11138
+ const page = await arbi.chats.page(chatRef.current, { before: oldest.external_id });
11139
+ queryClient.setQueryData(
11140
+ key,
11141
+ (old) => old ? {
11142
+ hasMore: page.hasMore,
11143
+ messages: [
11144
+ ...page.messages.filter(
11145
+ (m) => !old.messages.some((o) => o.external_id === m.external_id)
11146
+ ),
11147
+ ...old.messages
11148
+ ]
11149
+ } : old
11150
+ );
11547
11151
  } finally {
11548
- setBusy(false);
11152
+ setLoadingOlder(false);
11549
11153
  }
11154
+ }, [arbi, queryClient, chatExtId]);
11155
+ return {
11156
+ messages: query.data?.messages ?? [],
11157
+ hasMore: query.data?.hasMore ?? false,
11158
+ isLoading: query.isLoading && !!chat,
11159
+ loadOlder,
11160
+ loadingOlder
11550
11161
  };
11551
- return /* @__PURE__ */ jsxs(
11552
- "form",
11553
- {
11554
- "data-testid": "arbi-dm-start",
11555
- className: cn("flex flex-col gap-2 border-b border-border px-4 py-3", className),
11556
- onSubmit: (e) => {
11557
- e.preventDefault();
11558
- void submit();
11559
- },
11560
- children: [
11561
- /* @__PURE__ */ jsx(Label, { htmlFor: `${uid}-email`, children: l.email }),
11562
- /* @__PURE__ */ jsx(
11563
- Input,
11564
- {
11565
- id: `${uid}-email`,
11566
- type: "email",
11567
- value: email,
11568
- onChange: (e) => setEmail(e.target.value),
11569
- placeholder: l.emailPlaceholder,
11570
- "aria-invalid": email !== "" && !valid,
11571
- "aria-describedby": email !== "" && !valid ? `${uid}-bad` : void 0,
11572
- disabled: busy,
11573
- "data-testid": "arbi-dm-start-email"
11574
- }
11575
- ),
11576
- email !== "" && !valid && /* @__PURE__ */ jsx("p", { id: `${uid}-bad`, className: "text-xs text-destructive", children: l.invalidEmail }),
11577
- /* @__PURE__ */ jsx(Label, { htmlFor: `${uid}-text`, children: l.message }),
11578
- /* @__PURE__ */ jsx(
11579
- Textarea,
11580
- {
11581
- id: `${uid}-text`,
11582
- value: text,
11583
- onChange: (e) => setText(e.target.value),
11584
- placeholder: l.messagePlaceholder,
11585
- rows: 2,
11586
- disabled: busy,
11587
- "data-testid": "arbi-dm-start-message"
11588
- }
11589
- ),
11590
- error && /* @__PURE__ */ jsx("p", { role: "alert", className: "text-xs text-destructive", "data-testid": "arbi-dm-start-error", children: error }),
11591
- /* @__PURE__ */ jsxs(
11592
- Button,
11593
- {
11594
- type: "submit",
11595
- size: "sm",
11596
- disabled: !valid || !text.trim() || busy,
11597
- className: cn("self-end", classNames?.sendButton),
11598
- "data-testid": "arbi-dm-start-send",
11599
- children: [
11600
- busy ? /* @__PURE__ */ jsx(Loader2, { className: "size-4 animate-spin", "aria-hidden": true }) : /* @__PURE__ */ jsx(Send, { className: "size-4", "aria-hidden": true }),
11601
- busy ? l.sending : l.send
11602
- ]
11603
- }
11604
- )
11605
- ]
11606
- }
11162
+ }
11163
+ function useChatPost() {
11164
+ const arbi = useArbi();
11165
+ const queryClient = useQueryClient();
11166
+ return useCallback(
11167
+ async (target, post) => {
11168
+ const me = myChatId(arbi);
11169
+ if (!me) throw new Error("No active session");
11170
+ let chat = target.chat;
11171
+ if (!chat) {
11172
+ if (!target.peerExtId) throw new Error("Could not resolve the conversation");
11173
+ chat = await arbi.chats.openDirect(target.peerExtId);
11174
+ upsertChat(queryClient, chat);
11175
+ queryClient.setQueryData(
11176
+ arbiQueryKeys.chatThread(chat.external_id),
11177
+ (old) => old ?? { messages: [], hasMore: false }
11178
+ );
11179
+ }
11180
+ const files = post.files ?? [];
11181
+ const optimisticId = `optimistic-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`;
11182
+ const now = (/* @__PURE__ */ new Date()).toISOString();
11183
+ const optimistic = {
11184
+ external_id: optimisticId,
11185
+ chat_ext_id: chat.external_id,
11186
+ sender_ext_id: me,
11187
+ kind: "text",
11188
+ content: post.text,
11189
+ key_version: chat.key_version,
11190
+ deleted: false,
11191
+ context_only: !!post.contextOnly,
11192
+ workspace_ext_id: post.workspaceExtId ?? null,
11193
+ created_at: now,
11194
+ updated_at: now,
11195
+ optimistic: true
11196
+ };
11197
+ appendToThread(queryClient, chat.external_id, optimistic);
11198
+ try {
11199
+ let attachments = [];
11200
+ if (files.length) {
11201
+ chats.checkChatAttachmentLimits(files);
11202
+ attachments = await arbi.chats.uploadAttachments(
11203
+ await Promise.all(
11204
+ files.map(async (file) => ({
11205
+ name: file.name,
11206
+ type: file.type,
11207
+ bytes: new Uint8Array(await file.arrayBuffer())
11208
+ }))
11209
+ )
11210
+ );
11211
+ }
11212
+ const message = await arbi.chats.send(chat, post.text, {
11213
+ attachments,
11214
+ ...post.workspaceExtId ? { workspaceExtId: post.workspaceExtId } : {},
11215
+ contextOnly: !!post.contextOnly
11216
+ });
11217
+ appendToThread(queryClient, chat.external_id, message, optimisticId);
11218
+ upsertChat(queryClient, {
11219
+ ...chat,
11220
+ last_message: message,
11221
+ last_message_at: message.created_at
11222
+ });
11223
+ return { chat, message };
11224
+ } catch (err) {
11225
+ dropFromThread(queryClient, chat.external_id, optimisticId);
11226
+ void queryClient.invalidateQueries({ queryKey: arbiQueryKeys.chatList() });
11227
+ throw err;
11228
+ }
11229
+ },
11230
+ [arbi, queryClient]
11607
11231
  );
11608
11232
  }
11609
- function DirectMessages({
11610
- className,
11611
- classNames,
11612
- emptyThread,
11613
- emptyList,
11614
- listHeader,
11615
- listLead,
11616
- startByEmail,
11617
- hideOwnContact
11618
- }) {
11619
- const {
11620
- conversations: allConversations,
11621
- myExtId,
11622
- isLoading,
11623
- isError,
11624
- error,
11625
- sendMessage,
11626
- sendMessageTo,
11627
- sendError,
11628
- markRead
11629
- } = useDirectMessages();
11630
- const [selectedPeerId, setSelectedPeerId] = useState(null);
11631
- const [startedChatId, setStartedChatId] = useState(null);
11632
- const conversations = useMemo(
11633
- () => hideOwnContact && myExtId ? allConversations.filter((c) => c.peer.external_id !== myExtId) : allConversations,
11634
- [allConversations, hideOwnContact, myExtId]
11635
- );
11636
- const openStarted = (created) => {
11637
- const chatId = created?.chat_ext_id;
11638
- if (chatId) setStartedChatId(chatId);
11639
- };
11640
- useEffect(() => {
11641
- if (!startedChatId) return;
11642
- const started = conversations.find((c) => c.chatExtId === startedChatId);
11643
- if (started) {
11644
- setSelectedPeerId(started.id ?? started.peer.external_id);
11645
- setStartedChatId(null);
11646
- }
11647
- }, [conversations, startedChatId]);
11648
- const loadError = isError ? error instanceof Error ? error.message : "Couldn\u2019t load messages." : null;
11649
- const selected = useMemo(
11650
- () => conversations.find((c) => (c.id ?? c.peer.external_id) === selectedPeerId) ?? null,
11651
- [conversations, selectedPeerId]
11233
+ function useDeleteChatMessage() {
11234
+ const arbi = useArbi();
11235
+ const queryClient = useQueryClient();
11236
+ return useCallback(
11237
+ (chatExtId, messageExtId) => deleteChatMessage(arbi, queryClient, chatExtId, messageExtId),
11238
+ [arbi, queryClient]
11652
11239
  );
11653
- useEffect(() => {
11654
- if (!selected?.chatExtId || selected.unreadCount === 0) return;
11655
- void markRead(selected.chatExtId);
11656
- }, [selected?.chatExtId, selected?.unreadCount]);
11657
- const handleSend = async (text) => {
11658
- if (!selected) return;
11659
- await sendMessage(selected.peer.external_id, selected.peer.encryption_public_key, text);
11660
- };
11661
- return /* @__PURE__ */ jsxs(
11662
- "div",
11663
- {
11664
- "data-testid": "arbi-dm",
11665
- style: { height: "calc(100vh - 16rem)", minHeight: "28rem" },
11666
- className: cn(
11667
- "relative flex flex-col overflow-hidden rounded-xl border border-border bg-card md:flex-row",
11668
- className
11669
- ),
11670
- children: [
11671
- loadError && /* @__PURE__ */ jsx(
11672
- "p",
11673
- {
11674
- "data-testid": "arbi-dm-load-error",
11675
- className: "absolute inset-x-0 top-0 z-10 bg-destructive/10 px-3 py-2 text-center text-xs text-destructive",
11676
- children: loadError
11677
- }
11678
- ),
11679
- /* @__PURE__ */ jsx(
11680
- ConversationList,
11681
- {
11682
- conversations,
11683
- selectedPeerId: selected ? selected.id ?? selected.peer.external_id : null,
11684
- onSelect: setSelectedPeerId,
11685
- classNames,
11686
- emptyState: isLoading ? "Loading messages\u2026" : emptyList,
11687
- header: listHeader,
11688
- lead: /* @__PURE__ */ jsxs(Fragment, { children: [
11689
- listLead,
11690
- startByEmail && /* @__PURE__ */ jsx(
11691
- StartByEmail,
11692
- {
11693
- onStart: sendMessageTo,
11694
- onStarted: openStarted,
11695
- classNames,
11696
- labels: typeof startByEmail === "object" ? startByEmail.labels : void 0
11697
- }
11698
- )
11699
- ] })
11700
- }
11701
- ),
11702
- /* @__PURE__ */ jsxs("div", { className: "flex min-h-0 min-w-0 flex-1 flex-col", children: [
11703
- /* @__PURE__ */ jsx(MessageThread, { conversation: selected, classNames, emptyState: emptyThread }),
11704
- selected ? /* @__PURE__ */ jsx(
11705
- DmComposer,
11706
- {
11707
- placeholder: `Message ${(selected.title ?? userDisplayName(selected.peer)).split(" ")[0]}\u2026`,
11708
- onSend: handleSend,
11709
- error: sendError?.message ?? null,
11710
- classNames
11711
- }
11712
- ) : null
11713
- ] })
11714
- ]
11715
- }
11240
+ }
11241
+ function useMarkChatRead() {
11242
+ const arbi = useArbi();
11243
+ const queryClient = useQueryClient();
11244
+ return useCallback(
11245
+ (chat, messageExtId) => {
11246
+ upsertChat(queryClient, { ...chat, unread_count: 0 });
11247
+ return arbi.chats.markRead(chat.external_id, messageExtId).then(
11248
+ () => void 0,
11249
+ () => void 0
11250
+ );
11251
+ },
11252
+ [arbi, queryClient]
11716
11253
  );
11717
11254
  }
11255
+ function useCreateGroupChat() {
11256
+ const arbi = useArbi();
11257
+ const queryClient = useQueryClient();
11258
+ return useMutation({
11259
+ mutationFn: (params) => arbi.chats.createGroup(params),
11260
+ onSuccess: (chat) => upsertChat(queryClient, chat)
11261
+ });
11262
+ }
11263
+ function useRenameChat() {
11264
+ const arbi = useArbi();
11265
+ const queryClient = useQueryClient();
11266
+ return useMutation({
11267
+ mutationFn: (vars) => arbi.chats.rename(vars.chat, vars.title),
11268
+ onSuccess: (chat) => upsertChat(queryClient, chat)
11269
+ });
11270
+ }
11271
+ function useAddChatMembers() {
11272
+ const arbi = useArbi();
11273
+ const queryClient = useQueryClient();
11274
+ return useMutation({
11275
+ mutationFn: (vars) => arbi.chats.addMembers(vars.chat, vars.members, { callKey: vars.callKey }),
11276
+ onSuccess: (chat) => upsertChat(queryClient, chat)
11277
+ });
11278
+ }
11279
+ function useRemoveChatMember() {
11280
+ const arbi = useArbi();
11281
+ const queryClient = useQueryClient();
11282
+ return useMutation({
11283
+ mutationFn: (vars) => arbi.chats.removeMember(vars.chat, vars.userExtId),
11284
+ onSuccess: (_data, vars) => {
11285
+ if (vars.userExtId === myChatId(arbi)) removeChat(queryClient, vars.chat.external_id);
11286
+ else return queryClient.invalidateQueries({ queryKey: arbiQueryKeys.chatList() });
11287
+ }
11288
+ });
11289
+ }
11290
+ function DateSeparator({ children }) {
11291
+ return /* @__PURE__ */ jsx("div", { className: "my-3 flex justify-center", "data-testid": "dm-date-separator", children: /* @__PURE__ */ jsx("span", { className: "rounded-full bg-background/80 px-2 py-0.5 text-xs text-muted-foreground", children }) });
11292
+ }
11293
+
11294
+ // src/directmessages/grouping.ts
11295
+ var RUN_WINDOW_MS = 2 * 60 * 1e3;
11296
+ function dayKey(iso) {
11297
+ const d = new Date(iso);
11298
+ if (Number.isNaN(d.getTime())) return iso;
11299
+ return `${d.getFullYear()}-${d.getMonth() + 1}-${d.getDate()}`;
11300
+ }
11301
+ function annotateThread(messages, accessors, runWindowMs = RUN_WINDOW_MS) {
11302
+ const { senderId, createdAt } = accessors;
11303
+ return messages.map((message, i) => {
11304
+ const next = messages[i + 1];
11305
+ const prev = messages[i - 1];
11306
+ const day = dayKey(createdAt(message));
11307
+ const continuesIntoNext = !!next && senderId(next) === senderId(message) && dayKey(createdAt(next)) === day && Date.parse(createdAt(next)) - Date.parse(createdAt(message)) < runWindowMs;
11308
+ return {
11309
+ message,
11310
+ isLastOfRun: !continuesIntoNext,
11311
+ isFirstOfDay: !prev || dayKey(createdAt(prev)) !== day
11312
+ };
11313
+ });
11314
+ }
11718
11315
  var DEFAULT_ASPECT_OPTIONS = [
11719
11316
  { label: "1:1", value: 1 },
11720
11317
  { label: "4:3", value: 4 / 3 },
@@ -12127,6 +11724,6 @@ function CommandPaletteProvider({
12127
11724
  ] });
12128
11725
  }
12129
11726
 
12130
- export { AGENT_CONTROL_COMMANDS, ALLOWED_PORTAL_ORIGINS, ASSISTANT_MENTION_LABEL, AUTO_CHAT_MODEL, ActivityFeed, AiActionCard, AiAnswer, AppleIcon, ArbiBotIcon, ArbiHost2 as ArbiHost, ArbiWebSocketProvider, ArtifactCanvas, BOX_SEAT_REFUSED, BOX_SEAT_REFUSED_ACTION, BOX_SEAT_REFUSED_TITLE, CONVERSATION_SWITCH_MEASURE, ChatBubble, CitationRenderer, CommandPalette, CommandPaletteProvider, ConversationList, ConversationScope, DEFAULT_ASPECT_OPTIONS, DEFAULT_PASSWORD_CHANGE_FORM_MESSAGES, DEFAULT_START_BY_EMAIL_LABELS, DateSeparator, DirectMessages, DmAvatar, DmComposer, DocQaPanel, DocSearch, DocumentCardMenu, DocumentReview, DraftTitleControls, FIRST_TOKEN_MEASURE, FileIcon, GitHubIcon, ImageCropModal, ImageCropper, LinkedInIcon, MAIL_DRAFT_REPLACED_EVENT, MIN_NARRATION_DWELL_MS, MailOfflineUnavailableError, MessageArtifactCard, MessageBubble, MessageThread, POLL_EVERY_MS, PhotoCapture, RUN_WINDOW_MS, SIGNATURE_NOTIFICATION_TYPES, SLOW_AFTER_MS, STILL_WORKING, StartByEmail, TRANSFER_POLL_MS, TaskThreadPendingError, TypingIndicator, UPLOAD_ACCEPT, UPLOAD_MAX_FILE_SIZE, VideoCapture, VoiceNoteRecorder, WORK_NOTIFICATION_LABELS, __resetPendingFinalCommitsForTests, __resetStreamingTokenBufferForTests, accountPath, addAssistantMessageToCache, addUserMessageToCache, aliasTakenMessage, allConversationThreads, annotateThread, announceMailDraftReplaced, appendTokenToMessage, applyConversationEvent, applyFinalContextToMessage, applyOptimisticDocumentEdit, applyOutputItemToMessage, arbiMailClient, archiveName, archivedWorkspaceMessage, buildDocumentMetadataRows, buildMentionCandidates, buildPendingFirstTurn, buildWorkspaceArchive, cachedAssistantMode, cachedMentionCandidates, cachedQuotaUsedUp, callNotificationMeta, captureFrameAsBlob, clearLoadingState, clearUserInputRequest, commitFinalMessage, completeQueuedUserMessageByContent, connectOAuthCalendarAccount, connectorErrorStatus, connectorReturnTo, createMailClient, createStreamHandlers, createWorkspaceSwitch, cropImage, dayKey, defaultMailAlias, deploymentUserMeta, describeActivity, describeServerNotification, discardStreamingTokensForMessage, disconnectAttachedRun, documentActivityMeta, documentActivityPhrase, documentDisplayName, docxMentionMeta, downloadRecoveryFile, ensureAssistantMessageLoading, extractZipFile, fallbackFileName, fileAttachment, filesFromDrop, flushStreamingTokens, forgetUploadedDocumentFolder, formatConfigValidationError, formatIdentityPrice, getInterjectionText, getNotificationTypeMeta, getOrphanedLastMessage, getRelatedLabels, getRelatedTotal, getRunStartedAt, getThreadsQueryKey, getWorkspaceActionText, getWorkspaceKind, getWorkspaceSentPhrase, hasPendingFinalCommit, hasVideoTrack, identityStepFor, inputRequestTitle, invalidateCalendarEvents, invalidateCalendars, invalidateConversationActivity, isActivityKey, isAliasTakenError, isCommentToPeople, isDeploymentAdmin, isDeploymentUserNotification, isFullConfig, isMessageRunning, isOfflineReadableArbiQuery, isOrphanedUserMessage, isQueuedCalendarWrite, isReplayableArbiMutation, isRestorableArbiQueryOnline, isSignatureNotificationType, isTransferFinished, isTransferResumable, isWorkspaceArchivedError, isWorkspaceNotificationType, isZipFile, mailDraftIdFromContent, mailJson, markMessageAsFailed, markNarrationSettled, mountDiditVerification, nextAliasSuggestion, notificationUserName, openAccessRequest, parseActivityContent, parseDeleteAccountBlockers, pendingChatModelSave, peopleDirectory, personOfUser, pickRecentWorkspaces, prepareUploadFiles, redlineStats, refuseChatWhenOffline, registerArbiMutationDefaults, registerAttachedRun, removeSettledNarration, resetCalendarAccountSyncState, resetMessageContent, resolveActiveWorkspace, resolveConfigModel, resolveReplyTarget, rollbackOptimisticDocumentEdit, safePortalUrl, setMessageContent, setUserInputRequest, signatureNotificationPhrase, signatureRequestMeta, subscribeDocumentReads, supportsHouseTemplates, textToArtifact, threadEndingAtContains, titleFromQuestion, toChatCitations, toNotificationPreferences, toRedlineMarkdown, toShellWorkspace, updateMessageWithMetadata, updateUserMessageInCache, updateUserMessageStateInCache, uploadFolderOf, uploadedDocumentFolder, useActOnStep, useAddChatMembers, useAddHolidayCalendar, useAddProjectAddonBlock, useAddWorkspaceMembers, useAddonQuote, useAgentChats, useAgentConfig, useAgentDmStatus, useAgentModels, useAgentRunControl, useAgentSession, useAgentWorkspaces, useAiTask, useAnswerAgentQuestion, useApplyChatModel, useArbiConnected, useArbiDocumentSync, useArbiShellWorkspaces, useArbiWebSocket, useArbiWsMessage, useArbiWsStatus, useArbiWsStore, useArbiWsTask, useArbiWsTasks, useAskAgain, useAssignDocTags, useAuthorizeLimits, useAutoSendDraft, useBookingPages, useBranchNavigation, useCalDavProfiles, useCalendarAccounts, useCalendarEvent, useCalendarEventByUid, useCalendarEvents, useCalendarInvitations, useCalendarOutbox, useCalendarOverlays, useCalendarSettings, useCalendarShares, useCalendarSupport, useCalendars, useCameraStream, useCanEditShared, useCancelDriveSync, useCancelMailboxSync, useCancelProjectSubscription, useCancelWorkspaceTransfer, useChangeProjectPlan, useChargeWatch, useChatLiveUpdates, useChatPost, useChatSummaries, useChatThread, useChatUnreadTotal, useChats, useClaimNativeAlias, useCloseAgentSession, useCommandPalette, useConfigSchema, useConfirmEmailChange, useConnectCalDavAccount, useConnectMailAccount, useConnectOAuthAccount, useConnectRunStream, useConnectorAutoSync, useConnectorCatalog, useConnectorVendorVisibility, useContacts, useConversation, useConversationActions, useConversationActivity, useConversationData, useConversationDocuments, useConversationIsShared, useConversationItems, useConversationPendingAuth, useConversationTurn, useConversationUsage, useCreateAgent, useCreateCalendar, useCreateContact, useCreateEvent, useCreateFact, useCreateFacts, useCreateGroupChat, useCreateProject, useCreateProjectCheckout, useCreateRoom, useCreateWork, useCreateWorkflow, useCurrentSessionId, useDecideCounter, useDeleteAccount, useDeleteAccountFlow, useDeleteBookingPage, useDeleteCalendar, useDeleteChatMessage, useDeleteConfig, useDeleteContact, useDeleteDocuments, useDeleteEvent, useDeleteFact, useDeleteMessage, useDeleteNotifications, useDeleteProject, useDeleteSkill, useDeleteWorkflow, useDeleteWorkspaces, useDirectMessages, useDisconnectCalendarAccount, useDisconnectConnector, useDisconnectMailAccount, useDisconnectSlack, useDocumentAutoAdd, useDocumentHostActions, useDocumentPendingSync, useDocumentThumbnails, useDocumentsSupport, useDownloadDocuments, useDriveFolderChildren, useDriveFolderDocCount, useDriveFolders, useDriveSyncEstimate, useDriveSyncProgress, useEmailChange, useEnableDriveSync, useEnableMailboxSync, useFacts, useFetchCalendarEvent, useFilteredProjects, useFinaliseTranslation, useFindTime, useFollowThread, useFreeBusy, useGenerateAgentAvatar, useGenerateDocTags, useGrantAgentAccess, useHolidayCountries, useHouseTemplateCandidates, useIdentityVerification, useIdentityVerificationFlow, useImportCalendar, useImportContacts, useInvalidateAfterTransfer, useInvalidateProjects, useInviteContacts, useIsSlow, useIsWorkspaceOwner, useLinkContact, useMailAccounts, useMailAttachmentText, useMailCache, useMailClient, useMailDraftCompose, useMailDraftEditor, useMailDraftReplaced, useMailFolders, useMailMessage, useMailMessages, useMailOnline, useMailPolicy, useMailProjects, useMailUnlock, useMailboxFolders, useMailboxSyncProgress, useMarkChatRead, useMarkNotificationsRead, useMcpTools, useMentionCandidates, useMessageTimer, useMoveEvent, useMyConnectors, useNotificationPreferences, useNotifications, useNotifyConversation, useOfflineDocumentIds, useOpenSelectedWorkspace, useOpenViewerDocumentId, usePassageQuotes, usePasswordChange, usePasswordChangeForm, usePendingContacts, usePeople, usePeopleSearch, usePlanQuote, usePlanWork, usePlanWorkspaceTransfer, usePreviewProjectPlanChange, useProcessingTask, useProcessingTasks, useProducts, useProjectBillingPortal, useProjectConversationUsage, useProjectEvents, usePublishCalendar, useRefreshCalendar, useRefreshConnectorsOnRunEnd, useRefreshProject, useRelatedDocuments, useRemoveChatMember, useRemoveDocTags, useRemoveWorkspaceMembers, useRenameChat, useRenameFolder, useRequestEmailChange, useRequestWorkspaceAccess, useRespondToEvent, useResumeCalendarAccountConnect, useResumeWorkspaceTransfer, useRevokeAgentAccess, useRooms, useRunConversation, useRunWorkflow, useSaveAgentConfig, useSaveBookingPage, useSaveCalendarSettings, useSaveConfig, useSaveConfigField, useSaveMailDraft, useSaveSkill, useSearchContacts, useSearchFacts, useSemanticSearch, useSendBackStep, useSendMail, useSessions, useSetSkillVisibility, useSetWorkspaceHouseTemplate, useSetWorkspaceMemberRoles, useShareCalendar, useShellWorkspaces, useSignOut, useSkillSource, useSkills, useSlackConnection, useStartAgentSession, useStartCalendarAccountOAuth, useStartTaskQuery, useStartWorkspaceTransfer, useStreamHandlers, useSubscribeCalendar, useSwitchWorkspace, useSyncAccountsOnOpen, useSyncCalendarAccount, useTerminateSession, useThinkingContent, useTriggerDriveSync, useTriggerMailboxSync, useUnreadByPeer, useUnshareCalendar, useUpdateCalendar, useUpdateCalendarAccount, useUpdateContact, useUpdateConversation, useUpdateDocTag, useUpdateDocuments, useUpdateEvent, useUpdateFact, useUpdateMailMessage, useUpdateProjectAddonSettings, useUpdateProjectFields, useUpdateProjectNextPeriodAddons, useUpdateUserSettings, useUpdateWorkflow, useUpdateWorkspace, useUploadDocuments, useUploadFiles, useUploadFromUrls, useUploadSkillFiles, useUploadUrls, useUserSettings, useVideoRecorder, useWorkItems, useWorkNotifications, useWorkflowRuns, useWorkflows, useWorkspaceDocs, useWorkspaceExportDownload, useWorkspaceNotificationLevel, useWorkspaceRole, useWorkspaceTransfer, useWorkspaceTransfers, useWorkspaceUsers, userDisplayName, userInitials, waitForResponseId, withRelativePath, workflowStepOf, workspaceHouseTemplateId };
11727
+ export { AGENT_CONTROL_COMMANDS, ALLOWED_PORTAL_ORIGINS, ASSISTANT_MENTION_LABEL, AUTO_CHAT_MODEL, ActivityFeed, AiActionCard, AiAnswer, AppleIcon, ArbiBotIcon, ArbiHost2 as ArbiHost, ArbiWebSocketProvider, ArtifactCanvas, BOX_SEAT_REFUSED, BOX_SEAT_REFUSED_ACTION, BOX_SEAT_REFUSED_TITLE, CONVERSATION_SWITCH_MEASURE, ChatBubble, CitationRenderer, CommandPalette, CommandPaletteProvider, ConversationList, ConversationScope, DEFAULT_ASPECT_OPTIONS, DEFAULT_PASSWORD_CHANGE_FORM_MESSAGES, DateSeparator, DmAvatar, DmComposer, DocQaPanel, DocSearch, DocumentCardMenu, DocumentReview, DraftTitleControls, FIRST_TOKEN_MEASURE, FileIcon, GitHubIcon, ImageCropModal, ImageCropper, LinkedInIcon, MAIL_DRAFT_REPLACED_EVENT, MIN_NARRATION_DWELL_MS, MailOfflineUnavailableError, MessageArtifactCard, POLL_EVERY_MS, PhotoCapture, RUN_WINDOW_MS, SIGNATURE_NOTIFICATION_TYPES, SLOW_AFTER_MS, STILL_WORKING, TRANSFER_POLL_MS, TaskThreadPendingError, TypingIndicator, UPLOAD_ACCEPT, UPLOAD_MAX_FILE_SIZE, VideoCapture, VoiceNoteRecorder, WORK_NOTIFICATION_LABELS, __resetPendingFinalCommitsForTests, __resetStreamingTokenBufferForTests, accountPath, addAssistantMessageToCache, addUserMessageToCache, aliasTakenMessage, allConversationThreads, annotateThread, announceMailDraftReplaced, appendTokenToMessage, applyConversationEvent, applyFinalContextToMessage, applyOptimisticDocumentEdit, applyOutputItemToMessage, arbiMailClient, archiveName, archivedWorkspaceMessage, buildDocumentMetadataRows, buildMentionCandidates, buildPendingFirstTurn, buildWorkspaceArchive, cachedAssistantMode, cachedMentionCandidates, cachedQuotaUsedUp, callNotificationMeta, captureFrameAsBlob, clearLoadingState, clearUserInputRequest, commitFinalMessage, completeQueuedUserMessageByContent, connectOAuthCalendarAccount, connectorErrorStatus, connectorReturnTo, createMailClient, createStreamHandlers, createWorkspaceSwitch, cropImage, dayKey, defaultMailAlias, deploymentUserMeta, describeActivity, describeServerNotification, discardStreamingTokensForMessage, disconnectAttachedRun, documentActivityMeta, documentActivityPhrase, documentDisplayName, docxMentionMeta, downloadRecoveryFile, ensureAssistantMessageLoading, extractZipFile, fallbackFileName, fileAttachment, filesFromDrop, flushStreamingTokens, forgetUploadedDocumentFolder, formatConfigValidationError, formatIdentityPrice, getInterjectionText, getNotificationTypeMeta, getOrphanedLastMessage, getRelatedLabels, getRelatedTotal, getRunStartedAt, getThreadsQueryKey, getWorkspaceActionText, getWorkspaceKind, getWorkspaceSentPhrase, hasPendingFinalCommit, hasVideoTrack, identityStepFor, inputRequestTitle, invalidateCalendarEvents, invalidateCalendars, invalidateConversationActivity, isActivityKey, isAliasTakenError, isCommentToPeople, isDeploymentAdmin, isDeploymentUserNotification, isFullConfig, isMessageRunning, isOfflineReadableArbiQuery, isOrphanedUserMessage, isQueuedCalendarWrite, isReplayableArbiMutation, isRestorableArbiQueryOnline, isSignatureNotificationType, isTransferFinished, isTransferResumable, isWorkspaceArchivedError, isWorkspaceNotificationType, isZipFile, mailDraftIdFromContent, mailJson, markMessageAsFailed, markNarrationSettled, mountDiditVerification, nextAliasSuggestion, notificationUserName, openAccessRequest, parseActivityContent, parseDeleteAccountBlockers, pendingChatModelSave, peopleDirectory, personOfUser, pickRecentWorkspaces, prepareUploadFiles, redlineStats, refuseChatWhenOffline, registerArbiMutationDefaults, registerAttachedRun, removeSettledNarration, resetCalendarAccountSyncState, resetMessageContent, resolveActiveWorkspace, resolveConfigModel, resolveReplyTarget, rollbackOptimisticDocumentEdit, safePortalUrl, setMessageContent, setUserInputRequest, signatureNotificationPhrase, signatureRequestMeta, subscribeDocumentReads, supportsHouseTemplates, textToArtifact, threadEndingAtContains, titleFromQuestion, toChatCitations, toNotificationPreferences, toRedlineMarkdown, toShellWorkspace, updateMessageWithMetadata, updateUserMessageInCache, updateUserMessageStateInCache, uploadFolderOf, uploadedDocumentFolder, useActOnStep, useAddChatMembers, useAddHolidayCalendar, useAddProjectAddonBlock, useAddWorkspaceMembers, useAddonQuote, useAgentChats, useAgentConfig, useAgentDmStatus, useAgentModels, useAgentRunControl, useAgentSession, useAgentWorkspaces, useAiTask, useAnswerAgentQuestion, useApplyChatModel, useArbiConnected, useArbiDocumentSync, useArbiShellWorkspaces, useArbiWebSocket, useArbiWsMessage, useArbiWsStatus, useArbiWsStore, useArbiWsTask, useArbiWsTasks, useAskAgain, useAssignDocTags, useAuthorizeLimits, useAutoSendDraft, useBookingPages, useBranchNavigation, useCalDavProfiles, useCalendarAccounts, useCalendarEvent, useCalendarEventByUid, useCalendarEvents, useCalendarInvitations, useCalendarOutbox, useCalendarOverlays, useCalendarSettings, useCalendarShares, useCalendarSupport, useCalendars, useCameraStream, useCanEditShared, useCancelDriveSync, useCancelMailboxSync, useCancelProjectSubscription, useCancelWorkspaceTransfer, useChangeProjectPlan, useChargeWatch, useChatLiveUpdates, useChatPost, useChatSummaries, useChatThread, useChatUnreadTotal, useChats, useClaimNativeAlias, useCloseAgentSession, useCommandPalette, useConfigSchema, useConfirmEmailChange, useConnectCalDavAccount, useConnectMailAccount, useConnectOAuthAccount, useConnectRunStream, useConnectorAutoSync, useConnectorCatalog, useConnectorVendorVisibility, useContacts, useConversation, useConversationActions, useConversationActivity, useConversationData, useConversationDocuments, useConversationIsShared, useConversationItems, useConversationPendingAuth, useConversationTurn, useConversationUsage, useCreateAgent, useCreateCalendar, useCreateContact, useCreateEvent, useCreateFact, useCreateFacts, useCreateGroupChat, useCreateProject, useCreateProjectCheckout, useCreateRoom, useCreateWork, useCreateWorkflow, useCurrentSessionId, useDecideCounter, useDeleteAccount, useDeleteAccountFlow, useDeleteBookingPage, useDeleteCalendar, useDeleteChatMessage, useDeleteConfig, useDeleteContact, useDeleteDocuments, useDeleteEvent, useDeleteFact, useDeleteMessage, useDeleteNotifications, useDeleteProject, useDeleteSkill, useDeleteWorkflow, useDeleteWorkspaces, useDisconnectCalendarAccount, useDisconnectConnector, useDisconnectMailAccount, useDisconnectSlack, useDocumentAutoAdd, useDocumentHostActions, useDocumentPendingSync, useDocumentThumbnails, useDocumentsSupport, useDownloadDocuments, useDriveFolderChildren, useDriveFolderDocCount, useDriveFolders, useDriveSyncEstimate, useDriveSyncProgress, useEmailChange, useEnableDriveSync, useEnableMailboxSync, useFacts, useFetchCalendarEvent, useFilteredProjects, useFinaliseTranslation, useFindTime, useFollowThread, useFreeBusy, useGenerateAgentAvatar, useGenerateDocTags, useGrantAgentAccess, useHolidayCountries, useHouseTemplateCandidates, useIdentityVerification, useIdentityVerificationFlow, useImportCalendar, useImportContacts, useInvalidateAfterTransfer, useInvalidateProjects, useInviteContacts, useIsSlow, useIsWorkspaceOwner, useLinkContact, useMailAccounts, useMailAttachmentText, useMailCache, useMailClient, useMailDraftCompose, useMailDraftEditor, useMailDraftReplaced, useMailFolders, useMailMessage, useMailMessages, useMailOnline, useMailPolicy, useMailProjects, useMailUnlock, useMailboxFolders, useMailboxSyncProgress, useMarkChatRead, useMarkNotificationsRead, useMcpTools, useMentionCandidates, useMessageTimer, useMoveEvent, useMyConnectors, useNotificationPreferences, useNotifications, useNotifyConversation, useOfflineDocumentIds, useOpenSelectedWorkspace, useOpenViewerDocumentId, usePassageQuotes, usePasswordChange, usePasswordChangeForm, usePendingContacts, usePeople, usePeopleSearch, usePlanQuote, usePlanWork, usePlanWorkspaceTransfer, usePreviewProjectPlanChange, useProcessingTask, useProcessingTasks, useProducts, useProjectBillingPortal, useProjectConversationUsage, useProjectEvents, usePublishCalendar, useRefreshCalendar, useRefreshConnectorsOnRunEnd, useRefreshProject, useRelatedDocuments, useRemoveChatMember, useRemoveDocTags, useRemoveWorkspaceMembers, useRenameChat, useRenameFolder, useRequestEmailChange, useRequestWorkspaceAccess, useRespondToEvent, useResumeCalendarAccountConnect, useResumeWorkspaceTransfer, useRevokeAgentAccess, useRooms, useRunConversation, useRunWorkflow, useSaveAgentConfig, useSaveBookingPage, useSaveCalendarSettings, useSaveConfig, useSaveConfigField, useSaveMailDraft, useSaveSkill, useSearchContacts, useSearchFacts, useSemanticSearch, useSendBackStep, useSendMail, useSessions, useSetSkillVisibility, useSetWorkspaceHouseTemplate, useSetWorkspaceMemberRoles, useShareCalendar, useShellWorkspaces, useSignOut, useSkillSource, useSkills, useSlackConnection, useStartAgentSession, useStartCalendarAccountOAuth, useStartTaskQuery, useStartWorkspaceTransfer, useStreamHandlers, useSubscribeCalendar, useSwitchWorkspace, useSyncAccountsOnOpen, useSyncCalendarAccount, useTerminateSession, useThinkingContent, useTriggerDriveSync, useTriggerMailboxSync, useUnreadByPeer, useUnshareCalendar, useUpdateCalendar, useUpdateCalendarAccount, useUpdateContact, useUpdateConversation, useUpdateDocTag, useUpdateDocuments, useUpdateEvent, useUpdateFact, useUpdateMailMessage, useUpdateProjectAddonSettings, useUpdateProjectFields, useUpdateProjectNextPeriodAddons, useUpdateUserSettings, useUpdateWorkflow, useUpdateWorkspace, useUploadDocuments, useUploadFiles, useUploadFromUrls, useUploadSkillFiles, useUploadUrls, useUserSettings, useVideoRecorder, useWorkItems, useWorkNotifications, useWorkflowRuns, useWorkflows, useWorkspaceDocs, useWorkspaceExportDownload, useWorkspaceNotificationLevel, useWorkspaceRole, useWorkspaceTransfer, useWorkspaceTransfers, useWorkspaceUsers, userDisplayName, userInitials, waitForResponseId, withRelativePath, workflowStepOf, workspaceHouseTemplateId };
12131
11728
  //# sourceMappingURL=index.js.map
12132
11729
  //# sourceMappingURL=index.js.map