@arbidocs/react 0.4.109 → 0.4.111

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,18 +1,18 @@
1
1
  import { arbiQueryKeys, useDocuments, useConversations, useAssistantQuery, useConversationThreads, useWorkspaces, useParsedDocument, useTags, useActivity, useThumbnails } from './chunk-5WXNTCI3.js';
2
2
  export { PROJECT_CREATION_DENIED_REASON, arbiQueryKeys, isUsageMetered, useActivity, useAgents, useAssistantQuery, useCanCreateProjects, useConfigs, useConversationThreads, useConversations, useCurrentUser, useDeleteAgents, useDocuments, useFacts, useFirmPool, useHealth, useParsedDocument, useProjectInvoices, useProjectUsage, useProjects, useProjectsUsage, useSessions, useTags, useThumbnails, useTopUpFirmPool, useUserUsageToday, useWorkspaceActivity, useWorkspaceUsers, useWorkspaces } from './chunk-5WXNTCI3.js';
3
- export { cleanDraftMarkdown, cleanDraftWithReport, promoteBoldTitle, repairParsedStructure, repairParsedTitle, stripAgentPreamble, unescapeMarkdown, unwrapCitationLinks } from './chunk-G6FHNURH.js';
4
3
  import { formatRelativeTime } from './chunk-ECOSGMTW.js';
5
4
  export { DEFAULT_NOTIFY_TONE, NotificationBell, Toaster, formatRelativeTime, notify, seedNotifications, selectUnread, toast, useNotify } from './chunk-ECOSGMTW.js';
6
- import { returnFocusToMark, MarkMenu, AiMarkdown, Card, Badge, TagEntity, Input, FILE_TYPE_COLORS, getEntityIcon, UserEntity, getEntityColorStyles, AgentBadge, Textarea, Label, Slider, DocumentEntity, DocumentCard, useAudioRecorder, MicWaveformIndicator, IconToggle, classifyMediaError, formatElapsed, PassageCard } from './chunk-P4A5EG5B.js';
7
- export { AgentBadge, AiMarkdown, ArbiBotHeadIcon, AudIcon, Avatar, AvatarFallback, AvatarImage, BASE_COLORS, Badge, Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle, Checkbox, Collapsible, CollapsibleContent, CollapsibleTrigger, Command, CommandDialog, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList, CommandSeparator, CommandShortcut, DictateProvider, DocIcon, DocumentCard, DocumentEntity, ENTITY_MAPPINGS, EmlIcon, EntityIcon, EntityPill, FILE_TYPE_COLORS, HoverCard, HoverCardContent, HoverCardTrigger, HtmlIcon, IconToggle, ImgIcon, InlineMicButton, Input, Label, MarkMenu, MicRecordingOverlay, MicWaveformIndicator, NEUTRAL_GRAY, PLACEHOLDER_COLOR, PassageCard, PdfIcon, Popover, PopoverAnchor, PopoverContent, PopoverTrigger, PresenceLabel, Progress, ProjectEntity, RadioGroup, RadioGroupItem, RagDot, RelevanceDot, Select, SelectContent, SelectGroup, SelectItem, SelectLabel, SelectScrollDownButton, SelectScrollUpButton, SelectSeparator, SelectTrigger, SelectValue, Separator, 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, VISIBILITY_ICONS, VerifiedBadge, VidIcon, VisibilityIcon, VisibilityToggle, XlsIcon, badgeVariants, cardVariants, classifyMediaError, configureEntityRegistry, configureRagLabels, configureStatusRegistry, formatElapsed, getDocIcon, getEntityColor, getEntityColorStyles, getEntityIcon, getEntityLabel, getStatusVariant, getTagTypeIcon, getTagTypeLabel, getWorkspaceColor, toggleVariants, useAudioRecorder } from './chunk-P4A5EG5B.js';
8
- import { Button, Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from './chunk-YNNAJJ5Z.js';
9
- export { Button, Dialog, DialogClose, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogOverlay, DialogPortal, DialogTitle, DialogTrigger, buttonVariants } from './chunk-YNNAJJ5Z.js';
5
+ export { cleanDraftMarkdown, cleanDraftWithReport, promoteBoldTitle, repairParsedStructure, repairParsedTitle, stripAgentPreamble, unescapeMarkdown, unwrapCitationLinks } from './chunk-G6FHNURH.js';
6
+ import { returnFocusToMark, MarkMenu, AiMarkdown, Card, Badge, TagEntity, Input, FILE_TYPE_COLORS, getEntityIcon, UserEntity, getEntityColorStyles, AgentBadge, Textarea, Label, Slider, DocumentEntity, DocumentCard, useAudioRecorder, MicWaveformIndicator, IconToggle, classifyMediaError, formatElapsed, PassageCard } from './chunk-5L46Z7HZ.js';
7
+ export { AUDIO_MIME_PREFERENCE, AgentBadge, AiMarkdown, ArbiBotHeadIcon, AudIcon, Avatar, AvatarFallback, AvatarImage, BASE_COLORS, Badge, Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle, Checkbox, Collapsible, CollapsibleContent, CollapsibleTrigger, Command, CommandDialog, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList, CommandSeparator, CommandShortcut, DEFAULT_SEGMENTER_CONFIG, DictateProvider, DocIcon, DocumentCard, DocumentEntity, ENTITY_MAPPINGS, EmlIcon, EntityIcon, EntityPill, FILE_TYPE_COLORS, HoverCard, HoverCardContent, HoverCardTrigger, HtmlIcon, INITIAL_SEGMENTER_STATE, IconToggle, ImgIcon, InlineMicButton, Input, Label, MarkMenu, MicRecordingOverlay, MicWaveformIndicator, NEUTRAL_GRAY, PLACEHOLDER_COLOR, PassageCard, PdfIcon, Popover, PopoverAnchor, PopoverContent, PopoverTrigger, PresenceLabel, Progress, ProjectEntity, RadioGroup, RadioGroupItem, RagDot, RelevanceDot, Select, SelectContent, SelectGroup, SelectItem, SelectLabel, SelectScrollDownButton, SelectScrollUpButton, SelectSeparator, SelectTrigger, SelectValue, Separator, 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, VidIcon, VisibilityIcon, VisibilityToggle, XlsIcon, badgeVariants, cardVariants, classifyMediaError, configureEntityRegistry, configureRagLabels, configureStatusRegistry, createChunkedRecorder, flushSegmenter, formatElapsed, getDocIcon, getEntityColor, getEntityColorStyles, getEntityIcon, getEntityLabel, getStatusVariant, getTagTypeIcon, getTagTypeLabel, getWorkspaceColor, levelFromRms, pickRecorderMimeType, stepSegmenter, toggleVariants, useAudioRecorder } from './chunk-5L46Z7HZ.js';
10
8
  import { MarkdownRenderer } from './chunk-EKRRORFO.js';
11
9
  export { MarkdownRenderer, MarkdownStreamingContext, markdownBaseComponents, splitMarkdownBlocks } from './chunk-EKRRORFO.js';
12
- import { normalizeCitationMarkup } from './chunk-QRCMKEE6.js';
13
- export { closeOpenEmphasis, normalizeCitationMarkup, trimOpenCitation } from './chunk-QRCMKEE6.js';
14
10
  import { ScrollArea } from './chunk-W4H6XAIU.js';
15
11
  export { ScrollArea, ScrollBar } from './chunk-W4H6XAIU.js';
12
+ import { Button, Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from './chunk-YNNAJJ5Z.js';
13
+ export { Button, Dialog, DialogClose, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogOverlay, DialogPortal, DialogTitle, DialogTrigger, buttonVariants } from './chunk-YNNAJJ5Z.js';
14
+ import { normalizeCitationMarkup } from './chunk-QRCMKEE6.js';
15
+ export { closeOpenEmphasis, normalizeCitationMarkup, trimOpenCitation } from './chunk-QRCMKEE6.js';
16
16
  import { DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator } from './chunk-47CCGUWR.js';
17
17
  export { DropdownMenu, DropdownMenuCheckboxItem, DropdownMenuContent, DropdownMenuGroup, DropdownMenuItem, DropdownMenuLabel, DropdownMenuPortal, DropdownMenuRadioGroup, DropdownMenuRadioItem, DropdownMenuSeparator, DropdownMenuShortcut, DropdownMenuSub, DropdownMenuSubContent, DropdownMenuSubTrigger, DropdownMenuTrigger, PortalContainerProvider, usePortalContainer } from './chunk-47CCGUWR.js';
18
18
  import { cn } from './chunk-SN5YV6FF.js';
@@ -22,7 +22,7 @@ import { useArbi, ArbiContext } from './chunk-BUFDJCDS.js';
22
22
  export { ArbiProvider, useArbi, useDeploymentDomain } from './chunk-BUFDJCDS.js';
23
23
  import React, { memo, useState, createContext, useMemo, useCallback, useEffect, useRef, useLayoutEffect, useContext, useId, useSyncExternalStore, Fragment as Fragment$1 } from 'react';
24
24
  import { useQueryClient, useMutation, useQuery, onlineManager } from '@tanstack/react-query';
25
- import { resolveCitations, summarizeCitations, settings, formatFileSize, connectWithReconnect, dm, identityErrorCode } from '@arbidocs/sdk/browser';
25
+ import { resolveCitations, summarizeCitations, settings, formatFileSize, connectWithReconnect, chats, identityErrorCode } from '@arbidocs/sdk/browser';
26
26
  export { Arbi, ArbiError, DEFAULT_AI_USD_PER_GBP, formatGbp, formatGbpPerMillionTokens, usdToGbp } from '@arbidocs/sdk/browser';
27
27
  import { Link, Trash2, CheckCheck, Check, Loader2, AlertTriangle, ShieldCheck, Copy, Sparkles, FileText, GitCompareArrows, Download, Search, CornerDownLeft, X, ArrowLeft, Send, Tags, Crown, Info, Activity, Gauge, Gift, PartyPopper, UserCheck, Reply, PenLine, AtSign, MessageCircleMore, FileX2, FileCheck2, Pencil, FolderPlus, SquareArrowOutUpRight, MessagesSquare, Paperclip, ArrowRight, MoreHorizontal, SquarePen, Mic, Pause, Play, Square, RotateCcw, Camera, Circle, Image as Image$1, AppWindow } from 'lucide-react';
28
28
  import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
@@ -1589,27 +1589,45 @@ function useContacts(options) {
1589
1589
  function usePendingContacts(options) {
1590
1590
  const contacts = useContacts(options);
1591
1591
  const pending = useMemo(
1592
- () => (contacts.data ?? []).filter(
1593
- (c) => c.status === "invitation_pending" || c.status === "invitation_expired"
1594
- ),
1592
+ () => (contacts.data ?? []).filter((c) => c.status === "invited" || c.status === "expired"),
1595
1593
  [contacts.data]
1596
1594
  );
1597
1595
  return { ...contacts, pending };
1598
1596
  }
1599
- function useAddContacts() {
1600
- const arbi = useArbi();
1597
+ function useInvalidateContacts() {
1601
1598
  const qc = useQueryClient();
1599
+ return () => qc.invalidateQueries({ queryKey: arbiQueryKeys.contacts() });
1600
+ }
1601
+ function useInviteContacts() {
1602
+ const arbi = useArbi();
1603
+ const invalidate = useInvalidateContacts();
1602
1604
  return useMutation({
1603
- mutationFn: (emails) => arbi.contacts.add(emails),
1604
- onSuccess: () => qc.invalidateQueries({ queryKey: arbiQueryKeys.contacts() })
1605
+ mutationFn: (emails) => arbi.contacts.invite(emails),
1606
+ onSuccess: () => invalidate()
1605
1607
  });
1606
1608
  }
1607
- function useRemoveContacts() {
1609
+ function useCreateContact() {
1608
1610
  const arbi = useArbi();
1609
- const qc = useQueryClient();
1611
+ const invalidate = useInvalidateContacts();
1612
+ return useMutation({
1613
+ mutationFn: (body) => arbi.contacts.create(body),
1614
+ onSuccess: () => invalidate()
1615
+ });
1616
+ }
1617
+ function useUpdateContact() {
1618
+ const arbi = useArbi();
1619
+ const invalidate = useInvalidateContacts();
1620
+ return useMutation({
1621
+ mutationFn: ({ id, card }) => arbi.contacts.update(id, card),
1622
+ onSuccess: () => invalidate()
1623
+ });
1624
+ }
1625
+ function useDeleteContact() {
1626
+ const arbi = useArbi();
1627
+ const invalidate = useInvalidateContacts();
1610
1628
  return useMutation({
1611
- mutationFn: (contactIds) => arbi.contacts.remove(contactIds),
1612
- onSuccess: () => qc.invalidateQueries({ queryKey: arbiQueryKeys.contacts() })
1629
+ mutationFn: (contactId) => arbi.contacts.delete(contactId),
1630
+ onSuccess: () => invalidate()
1613
1631
  });
1614
1632
  }
1615
1633
  function toProfileView(profile) {
@@ -4617,8 +4635,6 @@ function getNotificationTypeMeta(type) {
4617
4635
  switch (type) {
4618
4636
  case "agent_input_requested":
4619
4637
  return { Icon: MessageCircleMore, iconClassName: "text-primary", label: "Input needed" };
4620
- case "user_message":
4621
- return { Icon: MessageCircleMore, iconClassName: "text-primary", label: "Message" };
4622
4638
  case "workspaceuser_added_owner":
4623
4639
  case "workspaceuser_added_collaborator":
4624
4640
  case "workspaceuser_added_guest":
@@ -4860,6 +4876,7 @@ function isAgentUser(user) {
4860
4876
  return user.external_id.startsWith("agt-");
4861
4877
  }
4862
4878
  var DM_QUERY_KEY = ["arbi", "directMessages"];
4879
+ var THREAD_LIMIT = 100;
4863
4880
  function mergeContacts(threads, contacts) {
4864
4881
  const byPeer = /* @__PURE__ */ new Map();
4865
4882
  for (const t of threads) byPeer.set(t.peer.external_id, t);
@@ -4877,43 +4894,45 @@ function mergeContacts(threads, contacts) {
4877
4894
  return userDisplayName(a.peer).localeCompare(userDisplayName(b.peer));
4878
4895
  });
4879
4896
  }
4880
- function groupConversations(notifications, myExtId) {
4881
- const messagesByPeer = /* @__PURE__ */ new Map();
4882
- const peers = /* @__PURE__ */ new Map();
4883
- for (const n of notifications) {
4884
- if (n.type !== "user_message") continue;
4885
- if (n.sender.external_id === n.recipient.external_id) continue;
4886
- const isMine = n.sender.external_id === myExtId;
4887
- const peer = isMine ? n.recipient : n.sender;
4888
- if (!peer?.external_id) continue;
4889
- const message = {
4890
- externalId: n.external_id,
4891
- body: n.content ?? "",
4892
- createdAt: n.created_at,
4897
+ function toConversation(loaded, myExtId, pending) {
4898
+ const { chat } = loaded;
4899
+ const peerMember = chat.members.find((m) => m.user.external_id !== myExtId);
4900
+ if (!peerMember) return null;
4901
+ const meMember = chat.members.find((m) => m.user.external_id === myExtId);
4902
+ const peer = peerMember.user;
4903
+ const userById = new Map(chat.members.map((m) => [m.user.external_id, m.user]));
4904
+ const seen = new Set(loaded.messages.map((m) => m.external_id));
4905
+ const rows = [
4906
+ ...loaded.messages,
4907
+ ...pending.filter((m) => m.chat_ext_id === chat.external_id && !seen.has(m.external_id))
4908
+ ].filter((m) => m.kind === "text" && !m.context_only);
4909
+ const messages = rows.map((m) => {
4910
+ const isMine = m.sender_ext_id === myExtId;
4911
+ const sender = userById.get(m.sender_ext_id ?? "") ?? { external_id: m.sender_ext_id ?? "usr-unknown" };
4912
+ return {
4913
+ externalId: m.external_id,
4914
+ // A tombstone (deleted) has no content: it renders as "Message deleted".
4915
+ body: m.deleted ? "" : m.content ?? "",
4916
+ createdAt: m.created_at,
4893
4917
  isMine,
4894
- read: n.read,
4895
- sender: n.sender,
4896
- recipient: n.recipient
4918
+ // Mine: has the peer read it? Theirs: have I?
4919
+ read: chats.hasRead(isMine ? peerMember : meMember, m),
4920
+ sender,
4921
+ recipient: isMine ? peer : meMember?.user,
4922
+ chatExtId: chat.external_id,
4923
+ ...m.deleted ? { deleted: true } : {}
4897
4924
  };
4898
- if (!messagesByPeer.has(peer.external_id)) {
4899
- messagesByPeer.set(peer.external_id, []);
4900
- peers.set(peer.external_id, peer);
4901
- }
4902
- messagesByPeer.get(peer.external_id).push(message);
4903
- }
4904
- const conversations = [];
4905
- for (const [peerId, messages] of messagesByPeer) {
4906
- messages.sort((a, b) => a.createdAt.localeCompare(b.createdAt));
4907
- const unreadCount = messages.filter((m) => !m.isMine && !m.read).length;
4908
- conversations.push({
4909
- peer: peers.get(peerId),
4910
- messages,
4911
- lastMessage: messages[messages.length - 1],
4912
- unreadCount
4913
- });
4914
- }
4915
- conversations.sort((a, b) => b.lastMessage.createdAt.localeCompare(a.lastMessage.createdAt));
4916
- return conversations;
4925
+ });
4926
+ messages.sort((a, b) => a.createdAt.localeCompare(b.createdAt));
4927
+ if (messages.length === 0) return null;
4928
+ const shown = messages.filter((m) => !m.deleted);
4929
+ return {
4930
+ peer,
4931
+ chatExtId: chat.external_id,
4932
+ messages,
4933
+ lastMessage: shown[shown.length - 1],
4934
+ unreadCount: chat.unread_count ?? 0
4935
+ };
4917
4936
  }
4918
4937
  function useDirectMessages(options) {
4919
4938
  const arbi = useArbi();
@@ -4921,7 +4940,10 @@ function useDirectMessages(options) {
4921
4940
  const enabled = options?.enabled ?? arbi.isLoggedIn;
4922
4941
  const query = useQuery({
4923
4942
  queryKey: DM_QUERY_KEY,
4924
- queryFn: () => arbi.dm.list(),
4943
+ queryFn: async () => {
4944
+ const direct = await arbi.chats.list("direct");
4945
+ return Promise.all(direct.map((c) => arbi.chats.load(c.external_id, { limit: THREAD_LIMIT })));
4946
+ },
4925
4947
  enabled
4926
4948
  });
4927
4949
  const contactsQuery = useQuery({
@@ -4929,9 +4951,10 @@ function useDirectMessages(options) {
4929
4951
  queryFn: () => arbi.contacts.list(),
4930
4952
  enabled
4931
4953
  });
4932
- useArbiWsMessage("user_message", () => {
4933
- queryClient.invalidateQueries({ queryKey: DM_QUERY_KEY });
4934
- });
4954
+ const invalidate = () => queryClient.invalidateQueries({ queryKey: DM_QUERY_KEY });
4955
+ useArbiWsMessage("chat.message", () => void invalidate());
4956
+ useArbiWsMessage("chat.read", () => void invalidate());
4957
+ useArbiWsMessage("chat.updated", () => void invalidate());
4935
4958
  let myExtId = null;
4936
4959
  try {
4937
4960
  myExtId = arbi.user.identity()?.externalId ?? null;
@@ -4940,33 +4963,56 @@ function useDirectMessages(options) {
4940
4963
  }
4941
4964
  const [pendingSent, setPendingSent] = useState([]);
4942
4965
  const serverIds = useMemo(
4943
- () => new Set((query.data ?? []).map((n) => n.external_id)),
4966
+ () => new Set((query.data ?? []).flatMap((c) => c.messages.map((m) => m.external_id))),
4944
4967
  [query.data]
4945
4968
  );
4946
4969
  useEffect(() => {
4947
4970
  setPendingSent(
4948
- (pending) => pending.some((n) => serverIds.has(n.external_id)) ? pending.filter((n) => !serverIds.has(n.external_id)) : pending
4971
+ (pending) => pending.some((p) => serverIds.has(p.message.external_id)) ? pending.filter((p) => !serverIds.has(p.message.external_id)) : pending
4949
4972
  );
4950
4973
  }, [serverIds]);
4951
4974
  const conversations = useMemo(() => {
4952
- const all = [...pendingSent.filter((n) => !serverIds.has(n.external_id)), ...query.data ?? []];
4953
- return mergeContacts(groupConversations(all, myExtId), contactsQuery.data ?? []);
4975
+ const pending = pendingSent.filter((p) => !serverIds.has(p.message.external_id));
4976
+ const pendingMessages = pending.map((p) => p.message);
4977
+ const threads = (query.data ?? []).map((loaded) => toConversation(loaded, myExtId, pendingMessages)).filter((c) => c !== null);
4978
+ const merged = mergeContacts(threads, contactsQuery.data ?? []);
4979
+ return merged.map((c) => {
4980
+ if (c.chatExtId) return c;
4981
+ const mine = pending.filter((p) => p.peerExtId === c.peer.external_id);
4982
+ if (!mine.length) return c;
4983
+ const messages = mine.map(({ message: m }) => ({
4984
+ externalId: m.external_id,
4985
+ body: m.content ?? "",
4986
+ createdAt: m.created_at,
4987
+ isMine: true,
4988
+ read: false,
4989
+ sender: { external_id: myExtId ?? "usr-me" },
4990
+ recipient: c.peer,
4991
+ chatExtId: m.chat_ext_id
4992
+ })).sort((a, b) => a.createdAt.localeCompare(b.createdAt));
4993
+ return {
4994
+ ...c,
4995
+ isContactOnly: false,
4996
+ chatExtId: messages[0].chatExtId,
4997
+ messages,
4998
+ lastMessage: messages[messages.length - 1]
4999
+ };
5000
+ });
4954
5001
  }, [query.data, serverIds, pendingSent, contactsQuery.data, myExtId]);
4955
- const invalidate = () => queryClient.invalidateQueries({ queryKey: DM_QUERY_KEY });
4956
- const absorbSent = (created) => {
4957
- setPendingSent((pending) => [...created, ...pending]);
4958
- invalidate();
5002
+ const absorbSent = (message, peerExtId) => {
5003
+ setPendingSent((pending) => [{ message, peerExtId }, ...pending]);
5004
+ void invalidate();
4959
5005
  };
4960
5006
  const sendMutation = useMutation({
4961
- mutationFn: (vars) => arbi.dm.sendTo(vars.recipientExtId, vars.recipientPublicKey, vars.text),
4962
- onSuccess: absorbSent
5007
+ mutationFn: (vars) => arbi.dm.sendTo(vars.recipientExtId, vars.text),
5008
+ onSuccess: (message, vars) => absorbSent(message, vars.recipientExtId)
4963
5009
  });
4964
5010
  const sendToMutation = useMutation({
4965
5011
  mutationFn: (vars) => arbi.dm.send(vars.recipient, vars.text),
4966
- onSuccess: absorbSent
5012
+ onSuccess: (message, vars) => absorbSent(message, vars.recipient.includes("@") ? void 0 : vars.recipient)
4967
5013
  });
4968
5014
  const markReadMutation = useMutation({
4969
- mutationFn: (messageIds) => arbi.dm.markRead(messageIds),
5015
+ mutationFn: (vars) => arbi.chats.markRead(vars.chatExtId, vars.messageExtId),
4970
5016
  onSuccess: invalidate
4971
5017
  });
4972
5018
  return {
@@ -4975,12 +5021,12 @@ function useDirectMessages(options) {
4975
5021
  isLoading: (query.isLoading || contactsQuery.isLoading) && enabled,
4976
5022
  isError: query.isError,
4977
5023
  error: query.error,
4978
- refetch: () => query.refetch(),
4979
- sendMessage: (recipientExtId, recipientPublicKey, text) => sendMutation.mutateAsync({ recipientExtId, recipientPublicKey, text }),
5024
+ refetch: () => void query.refetch(),
5025
+ sendMessage: (recipientExtId, _recipientPublicKey, text) => sendMutation.mutateAsync({ recipientExtId, text }),
4980
5026
  sendMessageTo: (recipient, text) => sendToMutation.mutateAsync({ recipient, text }),
4981
5027
  isSending: sendMutation.isPending || sendToMutation.isPending,
4982
5028
  sendError: sendMutation.error ?? sendToMutation.error,
4983
- markRead: (messageIds) => markReadMutation.mutateAsync(messageIds)
5029
+ markRead: (chatExtId, messageExtId) => markReadMutation.mutateAsync({ chatExtId, messageExtId })
4984
5030
  };
4985
5031
  }
4986
5032
  function DmAvatar({ user, className, size = "lg" }) {
@@ -5033,8 +5079,9 @@ function ConversationList({
5033
5079
  lead,
5034
5080
  /* @__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) => {
5035
5081
  const { peer, lastMessage, unreadCount } = c;
5082
+ const rowId = c.id ?? peer.external_id;
5036
5083
  const newSection = c.sectionLabel && c.sectionLabel !== conversations[i - 1]?.sectionLabel;
5037
- const active = peer.external_id === selectedPeerId;
5084
+ const active = rowId === selectedPeerId;
5038
5085
  const preview = lastMessage?.body ?? "No messages yet \u2014 say hello";
5039
5086
  const unread = unreadCount > 0;
5040
5087
  const body = /* @__PURE__ */ jsxs(Fragment, { children: [
@@ -5049,7 +5096,7 @@ function ConversationList({
5049
5096
  "truncate text-sm text-foreground",
5050
5097
  unread ? "font-bold" : "font-semibold"
5051
5098
  ),
5052
- children: userDisplayName(peer)
5099
+ children: c.title ?? userDisplayName(peer)
5053
5100
  }
5054
5101
  ),
5055
5102
  c.badge ?? (isAgentUser(peer) ? /* @__PURE__ */ jsx(AgentBadge, {}) : null)
@@ -5122,27 +5169,20 @@ function ConversationList({
5122
5169
  children: c.sectionLabel
5123
5170
  }
5124
5171
  ),
5125
- c.disabled ? /* @__PURE__ */ jsxs(
5126
- "div",
5127
- {
5128
- "data-testid": `arbi-dm-conversation-${peer.external_id}`,
5129
- className: rowClass,
5130
- children: [
5131
- body,
5132
- c.trailing
5133
- ]
5134
- }
5135
- ) : /* @__PURE__ */ jsx(
5172
+ c.disabled ? /* @__PURE__ */ jsxs("div", { "data-testid": `arbi-dm-conversation-${rowId}`, className: rowClass, children: [
5173
+ body,
5174
+ c.trailing
5175
+ ] }) : /* @__PURE__ */ jsx(
5136
5176
  "button",
5137
5177
  {
5138
5178
  type: "button",
5139
- onClick: () => onSelect(peer.external_id),
5140
- "data-testid": `arbi-dm-conversation-${peer.external_id}`,
5179
+ onClick: () => onSelect(rowId),
5180
+ "data-testid": `arbi-dm-conversation-${rowId}`,
5141
5181
  className: rowClass,
5142
5182
  children: body
5143
5183
  }
5144
5184
  )
5145
- ] }, peer.external_id);
5185
+ ] }, rowId);
5146
5186
  }) }) })
5147
5187
  ]
5148
5188
  }
@@ -5206,8 +5246,7 @@ function MessageThread({
5206
5246
  classNames,
5207
5247
  emptyState,
5208
5248
  formatDay,
5209
- onDeleteMessage,
5210
- deletedIds
5249
+ onDeleteMessage
5211
5250
  }) {
5212
5251
  const bottomRef = useRef(null);
5213
5252
  const items = useMemo(
@@ -5216,7 +5255,7 @@ function MessageThread({
5216
5255
  );
5217
5256
  useEffect(() => {
5218
5257
  bottomRef.current?.scrollIntoView({ block: "end" });
5219
- }, [conversation?.peer.external_id, conversation?.messages.length]);
5258
+ }, [conversation?.id, conversation?.peer.external_id, conversation?.messages.length]);
5220
5259
  if (!conversation) {
5221
5260
  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: [
5222
5261
  /* @__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" }) }),
@@ -5226,13 +5265,13 @@ function MessageThread({
5226
5265
  ] })
5227
5266
  ] }) });
5228
5267
  }
5229
- const { peer } = conversation;
5268
+ const { peer, title, memberCount } = conversation;
5230
5269
  return /* @__PURE__ */ jsxs(Fragment, { children: [
5231
5270
  /* @__PURE__ */ jsxs("header", { className: "flex items-center gap-3 border-b border-border px-4 py-3", children: [
5232
5271
  /* @__PURE__ */ jsx(DmAvatar, { user: peer, className: "size-9" }),
5233
5272
  /* @__PURE__ */ jsxs("div", { className: "min-w-0", children: [
5234
- /* @__PURE__ */ jsx("p", { className: "truncate text-sm font-semibold text-foreground", children: userDisplayName(peer) }),
5235
- /* @__PURE__ */ jsx("p", { className: "truncate text-xs text-muted-foreground", children: peer.email })
5273
+ /* @__PURE__ */ jsx("p", { className: "truncate text-sm font-semibold text-foreground", children: title ?? userDisplayName(peer) }),
5274
+ /* @__PURE__ */ jsx("p", { className: "truncate text-xs text-muted-foreground", children: memberCount != null ? `${memberCount} members` : peer.email })
5236
5275
  ] })
5237
5276
  ] }),
5238
5277
  /* @__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: [
@@ -5244,8 +5283,8 @@ function MessageThread({
5244
5283
  message: m,
5245
5284
  classNames,
5246
5285
  isLastOfRun,
5247
- deleted: deletedIds?.has(m.externalId),
5248
- onDelete: onDeleteMessage ? () => onDeleteMessage(m) : void 0
5286
+ deleted: m.deleted,
5287
+ onDelete: onDeleteMessage && !m.deleted ? () => onDeleteMessage(m) : void 0
5249
5288
  }
5250
5289
  )
5251
5290
  ] }, m.externalId)),
@@ -5273,7 +5312,7 @@ function DmComposer({
5273
5312
  if (!allowAttachments || added.length === 0) return;
5274
5313
  const next = [...files, ...added];
5275
5314
  try {
5276
- dm.checkDmAttachmentLimits(next);
5315
+ chats.checkChatAttachmentLimits(next);
5277
5316
  setFiles(next);
5278
5317
  setAttachError(null);
5279
5318
  } catch (err) {
@@ -5563,31 +5602,35 @@ function DirectMessages({
5563
5602
  markRead
5564
5603
  } = useDirectMessages();
5565
5604
  const [selectedPeerId, setSelectedPeerId] = useState(null);
5605
+ const [startedChatId, setStartedChatId] = useState(null);
5566
5606
  const conversations = useMemo(
5567
5607
  () => hideOwnContact && myExtId ? allConversations.filter((c) => c.peer.external_id !== myExtId) : allConversations,
5568
5608
  [allConversations, hideOwnContact, myExtId]
5569
5609
  );
5570
5610
  const openStarted = (created) => {
5571
- const peer = Array.isArray(created) ? created[0]?.recipient?.external_id : void 0;
5572
- if (peer) setSelectedPeerId(peer);
5611
+ const chatId = created?.chat_ext_id;
5612
+ if (chatId) setStartedChatId(chatId);
5573
5613
  };
5614
+ useEffect(() => {
5615
+ if (!startedChatId) return;
5616
+ const started = conversations.find((c) => c.chatExtId === startedChatId);
5617
+ if (started) {
5618
+ setSelectedPeerId(started.id ?? started.peer.external_id);
5619
+ setStartedChatId(null);
5620
+ }
5621
+ }, [conversations, startedChatId]);
5574
5622
  const loadError = isError ? error instanceof Error ? error.message : "Couldn\u2019t load messages." : null;
5575
5623
  const selected = useMemo(
5576
- () => conversations.find((c) => c.peer.external_id === selectedPeerId) ?? null,
5624
+ () => conversations.find((c) => (c.id ?? c.peer.external_id) === selectedPeerId) ?? null,
5577
5625
  [conversations, selectedPeerId]
5578
5626
  );
5579
5627
  useEffect(() => {
5580
- if (!selected || selected.unreadCount === 0) return;
5581
- const unreadIds = selected.messages.filter((m) => !m.isMine && !m.read).map((m) => m.externalId);
5582
- if (unreadIds.length) void markRead(unreadIds);
5583
- }, [selected?.peer.external_id, selected?.unreadCount]);
5628
+ if (!selected?.chatExtId || selected.unreadCount === 0) return;
5629
+ void markRead(selected.chatExtId);
5630
+ }, [selected?.chatExtId, selected?.unreadCount]);
5584
5631
  const handleSend = async (text) => {
5585
5632
  if (!selected) return;
5586
- if (selected.peer.encryption_public_key) {
5587
- await sendMessage(selected.peer.external_id, selected.peer.encryption_public_key, text);
5588
- } else {
5589
- await sendMessageTo(selected.peer.external_id, text);
5590
- }
5633
+ await sendMessage(selected.peer.external_id, selected.peer.encryption_public_key, text);
5591
5634
  };
5592
5635
  return /* @__PURE__ */ jsxs(
5593
5636
  "div",
@@ -5611,7 +5654,7 @@ function DirectMessages({
5611
5654
  ConversationList,
5612
5655
  {
5613
5656
  conversations,
5614
- selectedPeerId: selected?.peer.external_id ?? null,
5657
+ selectedPeerId: selected ? selected.id ?? selected.peer.external_id : null,
5615
5658
  onSelect: setSelectedPeerId,
5616
5659
  classNames,
5617
5660
  emptyState: isLoading ? "Loading messages\u2026" : emptyList,
@@ -5635,7 +5678,7 @@ function DirectMessages({
5635
5678
  selected ? /* @__PURE__ */ jsx(
5636
5679
  DmComposer,
5637
5680
  {
5638
- placeholder: `Message ${userDisplayName(selected.peer).split(" ")[0]}\u2026`,
5681
+ placeholder: `Message ${(selected.title ?? userDisplayName(selected.peer)).split(" ")[0]}\u2026`,
5639
5682
  onSend: handleSend,
5640
5683
  error: sendError?.message ?? null,
5641
5684
  classNames
@@ -7046,6 +7089,6 @@ function hasVideoTrack(blob) {
7046
7089
  });
7047
7090
  }
7048
7091
 
7049
- export { ActivityFeed, AiActionCard, AiAnswer, AppleIcon, ArbiBotIcon, ArbiIcon, ArbiWebSocketProvider, ArtifactCanvas, ChatBubble, CitationRenderer, ClaudeIcon, CommandPalette, CommandPaletteProvider, ConversationList, DEFAULT_ASPECT_OPTIONS, DEFAULT_PASSWORD_CHANGE_FORM_MESSAGES, DEFAULT_START_BY_EMAIL_LABELS, DateSeparator, DirectMessages, DmAvatar, DmComposer, DocQaPanel, DocSearch, DocumentCardMenu, DocumentGallery, DocumentReview, DocumentTable, DraftTitleControls, FileIcon, FireworksIcon, GeminiIcon, GitHubIcon, GoogleIcon, ImageCropModal, ImageCropper, LinkedInIcon, MAIL_DRAFT_REPLACED_EVENT, MAX_AVATAR_FILE_BYTES, MailClientProvider, MailOfflineUnavailableError, MessageArtifactCard, MessageBubble, MessageThread, OpenAIIcon, PhotoCapture, ProviderIcon, RUN_WINDOW_MS, SemanticSearch, StartByEmail, TypingIndicator, VideoCapture, VoiceNoteRecorder, accountPath, aliasTakenMessage, annotateThread, announceMailDraftReplaced, arbiMailClient, captureFrameAsBlob, createMailClient, cropImage, dayKey, defaultMailAlias, describeActivity, fileAttachment, formatIdentityPrice, getNotificationTypeMeta, getWorkspaceActionText, getWorkspaceKind, getWorkspaceSentPhrase, hasVideoTrack, identityStepFor, invalidateTagData, isAliasTakenError, isWorkspaceNotificationType, mailDraftIdFromContent, mailJson, mailQueryKeys, mountDiditVerification, nextAliasSuggestion, parseActivityContent, parseDeleteAccountBlockers, pickRecentWorkspaces, redlineStats, resolveActiveWorkspace, textToArtifact, titleFromQuestion, toChatCitations, toNotificationPreferences, toProfileView, toRedlineMarkdown, toShellWorkspace, useActOnStep, useAddContacts, useAgentChats, useAgentConfig, useAgentModels, useAgentSession, useAgentWorkspaces, useAiTask, useArbiChat, useArbiConnected, useArbiDocumentSync, useArbiShellWorkspaces, useArbiUiStore, useArbiWebSocket, useArbiWsContext, useArbiWsMessage, useArbiWsStatus, useArbiWsStore, useArbiWsTask, useArbiWsTasks, useAvatarCrop, useCameraStream, useClaimNativeAlias, useCloseAgentSession, useCommandPalette, useConfirmEmailChange, useConnectMailAccount, useContacts, useConversationActivity, useConversationPendingAuth, useConversationUsage, useCreateAgent, useCreateWork, useCreateWorkflow, useCurrentSessionId, useDeleteAccount, useDeleteAccountFlow, useDeleteWorkflow, useDirectMessages, useDisconnectMailAccount, useEmailChange, useFilteredProjects, useFollowThread, useGrantAgentAccess, useIdentityVerification, useIdentityVerificationFlow, useInvalidateTagData, useLogoutAllSessions, useMailAccounts, useMailCache, useMailClient, useMailDraftCompose, useMailDraftEditor, useMailDraftReplaced, useMailFolders, useMailMessage, useMailMessages, useMailOnline, useMailPolicy, useMailProjects, useMailUnlock, useNameEditor, useNotificationPreferences, usePasswordChange, usePasswordChangeForm, usePendingContacts, usePlanWork, useProfile, useProjectConversationUsage, useProjectEvents, useRemoveContacts, useRequestEmailChange, useRevokeAgentAccess, useRunConversation, useRunWorkflow, useSaveAgentConfig, useSaveMailDraft, useSemanticSearch, useSendBackStep, useSendMail, useSetTagValues, useShellWorkspaces, useSkills, useStartAgentSession, useStartWorkQuery, useTagKindSchema, useTerminateSession, useUpdateConversation, useUpdateMailMessage, useUpdateProfile, useUpdateProjectFields, useUpdateTagKindSchema, useUpdateWorkflow, useUploadSkillFiles, useUserSettings, useVideoRecorder, useWorkNotifications, useWorkflows, useWorkspaceDocs, useWorkspaceNotificationLevel, userDisplayName, userInitials, workflowStepOf };
7092
+ export { ActivityFeed, AiActionCard, AiAnswer, AppleIcon, ArbiBotIcon, ArbiIcon, ArbiWebSocketProvider, ArtifactCanvas, ChatBubble, CitationRenderer, ClaudeIcon, CommandPalette, CommandPaletteProvider, ConversationList, DEFAULT_ASPECT_OPTIONS, DEFAULT_PASSWORD_CHANGE_FORM_MESSAGES, DEFAULT_START_BY_EMAIL_LABELS, DateSeparator, DirectMessages, DmAvatar, DmComposer, DocQaPanel, DocSearch, DocumentCardMenu, DocumentGallery, DocumentReview, DocumentTable, DraftTitleControls, FileIcon, FireworksIcon, GeminiIcon, GitHubIcon, GoogleIcon, ImageCropModal, ImageCropper, LinkedInIcon, MAIL_DRAFT_REPLACED_EVENT, MAX_AVATAR_FILE_BYTES, MailClientProvider, MailOfflineUnavailableError, MessageArtifactCard, MessageBubble, MessageThread, OpenAIIcon, PhotoCapture, ProviderIcon, RUN_WINDOW_MS, SemanticSearch, StartByEmail, TypingIndicator, VideoCapture, VoiceNoteRecorder, accountPath, aliasTakenMessage, annotateThread, announceMailDraftReplaced, arbiMailClient, captureFrameAsBlob, createMailClient, cropImage, dayKey, defaultMailAlias, describeActivity, fileAttachment, formatIdentityPrice, getNotificationTypeMeta, getWorkspaceActionText, getWorkspaceKind, getWorkspaceSentPhrase, hasVideoTrack, identityStepFor, invalidateTagData, isAliasTakenError, isWorkspaceNotificationType, mailDraftIdFromContent, mailJson, mailQueryKeys, mountDiditVerification, nextAliasSuggestion, parseActivityContent, parseDeleteAccountBlockers, pickRecentWorkspaces, redlineStats, resolveActiveWorkspace, textToArtifact, titleFromQuestion, toChatCitations, toNotificationPreferences, toProfileView, toRedlineMarkdown, toShellWorkspace, useActOnStep, useAgentChats, useAgentConfig, useAgentModels, useAgentSession, useAgentWorkspaces, useAiTask, useArbiChat, useArbiConnected, useArbiDocumentSync, useArbiShellWorkspaces, useArbiUiStore, useArbiWebSocket, useArbiWsContext, useArbiWsMessage, useArbiWsStatus, useArbiWsStore, useArbiWsTask, useArbiWsTasks, useAvatarCrop, useCameraStream, useClaimNativeAlias, useCloseAgentSession, useCommandPalette, useConfirmEmailChange, useConnectMailAccount, useContacts, useConversationActivity, useConversationPendingAuth, useConversationUsage, useCreateAgent, useCreateContact, useCreateWork, useCreateWorkflow, useCurrentSessionId, useDeleteAccount, useDeleteAccountFlow, useDeleteContact, useDeleteWorkflow, useDirectMessages, useDisconnectMailAccount, useEmailChange, useFilteredProjects, useFollowThread, useGrantAgentAccess, useIdentityVerification, useIdentityVerificationFlow, useInvalidateTagData, useInviteContacts, useLogoutAllSessions, useMailAccounts, useMailCache, useMailClient, useMailDraftCompose, useMailDraftEditor, useMailDraftReplaced, useMailFolders, useMailMessage, useMailMessages, useMailOnline, useMailPolicy, useMailProjects, useMailUnlock, useNameEditor, useNotificationPreferences, usePasswordChange, usePasswordChangeForm, usePendingContacts, usePlanWork, useProfile, useProjectConversationUsage, useProjectEvents, useRequestEmailChange, useRevokeAgentAccess, useRunConversation, useRunWorkflow, useSaveAgentConfig, useSaveMailDraft, useSemanticSearch, useSendBackStep, useSendMail, useSetTagValues, useShellWorkspaces, useSkills, useStartAgentSession, useStartWorkQuery, useTagKindSchema, useTerminateSession, useUpdateContact, useUpdateConversation, useUpdateMailMessage, useUpdateProfile, useUpdateProjectFields, useUpdateTagKindSchema, useUpdateWorkflow, useUploadSkillFiles, useUserSettings, useVideoRecorder, useWorkNotifications, useWorkflows, useWorkspaceDocs, useWorkspaceNotificationLevel, userDisplayName, userInitials, workflowStepOf };
7050
7093
  //# sourceMappingURL=index.js.map
7051
7094
  //# sourceMappingURL=index.js.map