@arbidocs/react 0.3.115 → 0.3.117

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
@@ -3,8 +3,8 @@ import React__default, { createContext, memo, useState, forwardRef, useMemo, use
3
3
  import { Arbi, connectWithReconnect, resolveCitations, summarizeCitations } from '@arbidocs/sdk/browser';
4
4
  export { Arbi, ArbiError } from '@arbidocs/sdk/browser';
5
5
  import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
6
- import { useQuery, useMutation, QueryClient, QueryClientProvider, useQueryClient } from '@tanstack/react-query';
7
- import { Trash2, CheckCheck, Check, Circle, X, ChevronRight, ChevronDown, ChevronUp, Search, MoreVertical, MessageCircleMore, Bot, Calendar, Folder, StickyNote, Hash, List, SquareCheckBig, Loader2, AlertTriangle, ShieldCheck, Copy, Sparkles, FileText, GitCompareArrows, Download, Image, CornerDownLeft, Send, Tags, Crown, Eye, FolderOpen, Package } from 'lucide-react';
6
+ import { useQuery, useMutation, useQueries, QueryClient, QueryClientProvider, useQueryClient } from '@tanstack/react-query';
7
+ import { Trash2, CheckCheck, Check, Circle, X, ChevronRight, ChevronDown, ChevronUp, Search, MoreVertical, MessageCircleMore, MessageSquareLock, Info, FileQuestion, BookOpen, Upload, LogOut, LayoutGrid, Bell, MessageSquare, CircleUserRound, Wrench, Package, ClipboardList, UserPlus, Contact, Settings2, Users, User, StickyNote, FolderPlus, Hash, EyeOff, Eye, CaptionsOff, FolderOpen, MessageSquareMore, MessageSquarePlus, MessageSquareText, MessageSquareOff, MessagesSquare, Columns3Cog, SquarePlus, SquareM, ChevronsDown, Bot, Calendar, Folder, List, SquareCheckBig, Loader2, AlertTriangle, ShieldCheck, Copy, Sparkles, FileText, GitCompareArrows, Download, Image as Image$1, CornerDownLeft, Send, Tags, Crown, Activity, Gauge, Gift, PartyPopper, UserCheck, FileX2, FileCheck2, Pencil, SquareArrowOutUpRight, XCircle, CheckCircle2, ArrowRight } from 'lucide-react';
8
8
  import { clsx } from 'clsx';
9
9
  import { twMerge } from 'tailwind-merge';
10
10
  import { isMessageType } from '@arbidocs/client';
@@ -36,6 +36,7 @@ import ReactMarkdown from 'react-markdown';
36
36
  import remarkGfm from 'remark-gfm';
37
37
  import rehypeRaw from 'rehype-raw';
38
38
  import { AnimatePresence, motion } from 'framer-motion';
39
+ import Cropper from 'react-easy-crop';
39
40
  import { AgGridReact } from 'ag-grid-react';
40
41
  import { ModuleRegistry, AllCommunityModule } from 'ag-grid-community';
41
42
 
@@ -630,7 +631,13 @@ var arbiQueryKeys = {
630
631
  health: () => ["arbi", "health"],
631
632
  tasks: () => ["arbi", "tasks"],
632
633
  memories: (workspaceId) => ["arbi", "memories", workspaceId],
633
- configs: () => ["arbi", "configs"]
634
+ configs: () => ["arbi", "configs"],
635
+ activity: () => ["arbi", "activity"],
636
+ projects: () => ["arbi", "projects"],
637
+ projectUsage: (projectExtId, monthsBack) => ["arbi", "projectUsage", projectExtId, monthsBack],
638
+ projectInvoices: (projectExtId) => ["arbi", "projectInvoices", projectExtId],
639
+ userUsageToday: () => ["arbi", "userUsageToday"],
640
+ workspaceChronology: (workspaceId) => ["arbi", "workspaceChronology", workspaceId]
634
641
  };
635
642
  function useWorkspaces(options) {
636
643
  const arbi = useArbi();
@@ -741,6 +748,119 @@ function useConfigs(options) {
741
748
  enabled: options?.enabled ?? arbi.isLoggedIn
742
749
  });
743
750
  }
751
+ function useActivity(options) {
752
+ const arbi = useArbi();
753
+ return useQuery({
754
+ queryKey: arbiQueryKeys.activity(),
755
+ queryFn: () => arbi.dm.listActivity({ limit: options?.limit, offset: options?.offset }),
756
+ enabled: options?.enabled ?? arbi.isLoggedIn
757
+ });
758
+ }
759
+ function useProjects(options) {
760
+ const arbi = useArbi();
761
+ return useQuery({
762
+ queryKey: arbiQueryKeys.projects(),
763
+ queryFn: () => arbi.projects.list(),
764
+ enabled: options?.enabled ?? arbi.isLoggedIn
765
+ });
766
+ }
767
+ function useProjectUsage(projectExtId, monthsBack = 0, options) {
768
+ const arbi = useArbi();
769
+ return useQuery({
770
+ queryKey: arbiQueryKeys.projectUsage(projectExtId ?? "", monthsBack),
771
+ queryFn: () => arbi.projects.usage(projectExtId, monthsBack),
772
+ enabled: (options?.enabled ?? true) && !!projectExtId && arbi.isLoggedIn
773
+ });
774
+ }
775
+ function useProjectsUsage(projectExtIds, monthsBack = 0, options) {
776
+ const arbi = useArbi();
777
+ const enabled = (options?.enabled ?? true) && arbi.isLoggedIn;
778
+ const results = useQueries({
779
+ queries: projectExtIds.map((id) => ({
780
+ queryKey: arbiQueryKeys.projectUsage(id, monthsBack),
781
+ queryFn: () => arbi.projects.usage(id, monthsBack),
782
+ enabled: enabled && !!id
783
+ }))
784
+ });
785
+ const signature = results.map((r) => `${r.status}:${r.dataUpdatedAt ?? 0}`).join("|");
786
+ return useMemo(() => {
787
+ const dailyMap = /* @__PURE__ */ new Map();
788
+ const modelMap = /* @__PURE__ */ new Map();
789
+ let totalSpend = 0;
790
+ let totalTokens = 0;
791
+ let totalRequests = 0;
792
+ for (const r of results) {
793
+ const d = r.data;
794
+ if (!d) continue;
795
+ totalSpend += d.total_spend ?? 0;
796
+ totalTokens += d.total_tokens ?? 0;
797
+ totalRequests += d.total_requests ?? 0;
798
+ for (const day of d.daily ?? []) {
799
+ const cur = dailyMap.get(day.date) ?? {
800
+ date: day.date,
801
+ spend: 0,
802
+ totalTokens: 0,
803
+ apiRequests: 0
804
+ };
805
+ cur.spend += day.spend ?? 0;
806
+ cur.totalTokens += day.total_tokens ?? 0;
807
+ cur.apiRequests += day.api_requests ?? 0;
808
+ dailyMap.set(day.date, cur);
809
+ }
810
+ for (const [model, mg] of Object.entries(d.model_groups ?? {})) {
811
+ const cur = modelMap.get(model) ?? {
812
+ model,
813
+ spend: 0,
814
+ totalTokens: 0,
815
+ promptTokens: 0,
816
+ completionTokens: 0,
817
+ successfulRequests: 0
818
+ };
819
+ cur.spend += mg.spend ?? 0;
820
+ cur.totalTokens += mg.total_tokens ?? 0;
821
+ cur.promptTokens += mg.prompt_tokens ?? 0;
822
+ cur.completionTokens += mg.completion_tokens ?? 0;
823
+ cur.successfulRequests += mg.successful_requests ?? 0;
824
+ modelMap.set(model, cur);
825
+ }
826
+ }
827
+ return {
828
+ totalSpend,
829
+ totalTokens,
830
+ totalRequests,
831
+ daily: [...dailyMap.values()].sort((a, b) => a.date.localeCompare(b.date)),
832
+ modelGroups: [...modelMap.values()].sort(
833
+ (a, b) => b.spend - a.spend || b.totalTokens - a.totalTokens
834
+ ),
835
+ isLoading: results.some((r) => r.isLoading),
836
+ isError: results.some((r) => r.isError)
837
+ };
838
+ }, [signature]);
839
+ }
840
+ function useProjectInvoices(projectExtId, options) {
841
+ const arbi = useArbi();
842
+ return useQuery({
843
+ queryKey: arbiQueryKeys.projectInvoices(projectExtId ?? ""),
844
+ queryFn: () => arbi.projects.invoices(projectExtId),
845
+ enabled: (options?.enabled ?? true) && !!projectExtId && arbi.isLoggedIn
846
+ });
847
+ }
848
+ function useUserUsageToday(options) {
849
+ const arbi = useArbi();
850
+ return useQuery({
851
+ queryKey: arbiQueryKeys.userUsageToday(),
852
+ queryFn: () => arbi.user.usageToday(),
853
+ enabled: options?.enabled ?? arbi.isLoggedIn
854
+ });
855
+ }
856
+ function useWorkspaceChronology(workspaceId, options) {
857
+ const arbi = useArbi();
858
+ return useQuery({
859
+ queryKey: arbiQueryKeys.workspaceChronology(workspaceId ?? ""),
860
+ queryFn: () => arbi.workspaces.chronology(workspaceId),
861
+ enabled: (options?.enabled ?? true) && !!workspaceId && arbi.hasWorkspace
862
+ });
863
+ }
744
864
  function WorkspaceScreen({ theme, labels, onSelect }) {
745
865
  const arbi = useArbi();
746
866
  const { data: workspaces, isLoading } = useWorkspaces();
@@ -3105,7 +3225,7 @@ function MessageArtifactCard({
3105
3225
  }) {
3106
3226
  const { docExtId, title, isComplete, mode } = artifact;
3107
3227
  const isImage = mode === "image";
3108
- const Icon2 = isImage ? Image : FileText;
3228
+ const Icon2 = isImage ? Image$1 : FileText;
3109
3229
  const statusText = isImage ? isComplete ? "Image ready" : "Generating\u2026" : isComplete ? "Draft ready" : "Drafting\u2026";
3110
3230
  return /* @__PURE__ */ jsxs(
3111
3231
  Card,
@@ -5125,6 +5245,1507 @@ var UserEntity = memo(function UserEntity2({
5125
5245
  }
5126
5246
  return avatarElement;
5127
5247
  });
5248
+ var ENTITY_MAPPINGS = {
5249
+ PRODUCT: {
5250
+ NAMES: {
5251
+ SINGULAR: "ARBI Docs"
5252
+ },
5253
+ ICONS: {
5254
+ DEFAULT: MessageSquareLock
5255
+ }
5256
+ },
5257
+ SECTION: {
5258
+ NAMES: {
5259
+ SINGULAR: "Section"
5260
+ },
5261
+ ICONS: {
5262
+ DEFAULT: ChevronsDown
5263
+ }
5264
+ },
5265
+ WORKSPACE: {
5266
+ NAMES: {
5267
+ SINGULAR: "Workspace",
5268
+ PLURAL: "Workspaces"
5269
+ },
5270
+ ICONS: {
5271
+ DEFAULT: SquareM,
5272
+ NEW: SquarePlus,
5273
+ LIST: LayoutGrid,
5274
+ SETTINGS: Columns3Cog
5275
+ }
5276
+ },
5277
+ CONVERSATION: {
5278
+ NAMES: {
5279
+ SINGULAR: "Chat",
5280
+ PLURAL: "Chats",
5281
+ NEW: "New ARBI Chat"
5282
+ },
5283
+ ICONS: {
5284
+ DEFAULT: MessagesSquare,
5285
+ OFF: MessageSquareOff,
5286
+ ACTIVE: MessageSquareText,
5287
+ NEW: MessageSquarePlus,
5288
+ LIST: MessageSquareMore
5289
+ }
5290
+ },
5291
+ DOCUMENT: {
5292
+ NAMES: {
5293
+ SINGULAR: "File",
5294
+ PLURAL: "Files"
5295
+ },
5296
+ ICONS: {
5297
+ DEFAULT: FolderOpen,
5298
+ OFF: CaptionsOff
5299
+ }
5300
+ },
5301
+ VIEWER: {
5302
+ NAMES: {
5303
+ SINGULAR: "Viewer",
5304
+ PLURAL: "Viewers"
5305
+ },
5306
+ ICONS: {
5307
+ DEFAULT: Eye,
5308
+ OFF: EyeOff
5309
+ }
5310
+ },
5311
+ TAG: {
5312
+ NAMES: {
5313
+ SINGULAR: "Field",
5314
+ PLURAL: "Fields"
5315
+ },
5316
+ ICONS: {
5317
+ DEFAULT: Hash,
5318
+ NEW: FolderPlus
5319
+ }
5320
+ },
5321
+ ANNOTATION: {
5322
+ NAMES: {
5323
+ SINGULAR: "Annotation",
5324
+ PLURAL: "Annotations"
5325
+ },
5326
+ ICONS: {
5327
+ DEFAULT: StickyNote,
5328
+ NEW: StickyNote
5329
+ }
5330
+ },
5331
+ USER: {
5332
+ NAMES: {
5333
+ SINGULAR: "User",
5334
+ PLURAL: "Users"
5335
+ },
5336
+ ICONS: {
5337
+ DEFAULT: User,
5338
+ NEW: UserPlus,
5339
+ SETTINGS: Settings2
5340
+ }
5341
+ },
5342
+ WORKSPACEUSER: {
5343
+ NAMES: {
5344
+ SINGULAR: "Member",
5345
+ PLURAL: "Members"
5346
+ },
5347
+ ICONS: {
5348
+ DEFAULT: User,
5349
+ PLURAL: Users,
5350
+ NEW: UserPlus,
5351
+ SETTINGS: Settings2
5352
+ }
5353
+ },
5354
+ CONTACT: {
5355
+ NAMES: {
5356
+ SINGULAR: "Contact",
5357
+ PLURAL: "Contacts"
5358
+ },
5359
+ ICONS: {
5360
+ DEFAULT: Contact,
5361
+ NEW: UserPlus
5362
+ }
5363
+ },
5364
+ TASK: {
5365
+ NAMES: {
5366
+ SINGULAR: "Job",
5367
+ PLURAL: "Jobs"
5368
+ },
5369
+ ICONS: {
5370
+ DEFAULT: ClipboardList
5371
+ }
5372
+ },
5373
+ PROJECT: {
5374
+ NAMES: {
5375
+ SINGULAR: "Project",
5376
+ PLURAL: "Projects"
5377
+ },
5378
+ ICONS: {
5379
+ DEFAULT: Package
5380
+ }
5381
+ },
5382
+ SKILL: {
5383
+ NAMES: {
5384
+ SINGULAR: "Skill",
5385
+ PLURAL: "Skills"
5386
+ },
5387
+ ICONS: {
5388
+ DEFAULT: Wrench
5389
+ }
5390
+ },
5391
+ ACCOUNT: {
5392
+ NAMES: {
5393
+ SINGULAR: "Account"
5394
+ },
5395
+ ICONS: {
5396
+ DEFAULT: CircleUserRound
5397
+ }
5398
+ },
5399
+ NOTIFICATIONS: {
5400
+ NAMES: {
5401
+ SINGULAR: "Activity",
5402
+ PLURAL: "Activities"
5403
+ },
5404
+ ICONS: {
5405
+ DEFAULT: Bell
5406
+ }
5407
+ },
5408
+ MESSAGE: {
5409
+ NAMES: {
5410
+ SINGULAR: "Message",
5411
+ PLURAL: "Messages"
5412
+ },
5413
+ ICONS: {
5414
+ DEFAULT: MessageSquare
5415
+ }
5416
+ },
5417
+ NOTIFICATION: {
5418
+ NAMES: {
5419
+ SINGULAR: "Notification",
5420
+ PLURAL: "Notifications"
5421
+ },
5422
+ ICONS: {
5423
+ DEFAULT: Bell
5424
+ }
5425
+ },
5426
+ APP: {
5427
+ NAMES: {
5428
+ SINGULAR: "Application",
5429
+ PLURAL: "Applications"
5430
+ },
5431
+ ICONS: {
5432
+ DEFAULT: LayoutGrid,
5433
+ HOME: LayoutGrid,
5434
+ LOGOUT: LogOut,
5435
+ UPLOAD: Upload
5436
+ }
5437
+ },
5438
+ HELP: {
5439
+ NAMES: {
5440
+ SINGULAR: "Help",
5441
+ PLURAL: "Help"
5442
+ },
5443
+ ICONS: {
5444
+ DEFAULT: MessageSquareLock,
5445
+ DOCS: BookOpen,
5446
+ FAQ: FileQuestion,
5447
+ ABOUT: Info
5448
+ }
5449
+ },
5450
+ USERSHIELD: {
5451
+ NAMES: {
5452
+ SINGULAR: "User Shield",
5453
+ PLURAL: "User Shields"
5454
+ },
5455
+ ICONS: {
5456
+ DEFAULT: MessageSquareLock
5457
+ }
5458
+ }
5459
+ };
5460
+ function configureEntityRegistry(overrides) {
5461
+ for (const [type, def] of Object.entries(overrides)) {
5462
+ const target = ENTITY_MAPPINGS[type];
5463
+ if (!target) continue;
5464
+ if (def?.NAMES) Object.assign(target.NAMES, def.NAMES);
5465
+ if (def?.ICONS) Object.assign(target.ICONS, def.ICONS);
5466
+ }
5467
+ }
5468
+ var getEntityIcon = (entityType, variant = "DEFAULT") => {
5469
+ const icons = ENTITY_MAPPINGS[entityType]?.ICONS;
5470
+ return icons?.[variant] || icons?.DEFAULT;
5471
+ };
5472
+ var getEntityLabel = (entityType, form = "SINGULAR") => {
5473
+ const entityMapping = ENTITY_MAPPINGS[entityType];
5474
+ if (!entityMapping) return "";
5475
+ const names = entityMapping.NAMES;
5476
+ const singularName = names.SINGULAR || "";
5477
+ if (form === "NEW") return names.NEW !== void 0 ? names.NEW : "New " + singularName;
5478
+ if (form === "SHORT")
5479
+ return names.SHORT !== void 0 ? names.SHORT : singularName.substring(0, 3) + ".";
5480
+ if (form === "PLURAL") return names.PLURAL !== void 0 ? names.PLURAL : singularName + "s";
5481
+ return singularName;
5482
+ };
5483
+ var EntityIcon = ({ entityType, variant = "DEFAULT", ...props }) => {
5484
+ const IconComponent = getEntityIcon(entityType, variant);
5485
+ return IconComponent ? React__default.createElement(IconComponent, props) : null;
5486
+ };
5487
+ var VISIBILITY_ICONS = {
5488
+ PRIVATE: MessageSquareLock,
5489
+ SHARED: Users
5490
+ };
5491
+ var VisibilityIcon = ({
5492
+ isShared,
5493
+ ...props
5494
+ }) => {
5495
+ const IconComponent = isShared ? VISIBILITY_ICONS.SHARED : VISIBILITY_ICONS.PRIVATE;
5496
+ return React__default.createElement(IconComponent, props);
5497
+ };
5498
+
5499
+ // src/entities/colors.ts
5500
+ var OPACITY_LIGHT = 0.15;
5501
+ var OPACITY_MEDIUM = 1;
5502
+ var OPACITY_BORDER = 0.3;
5503
+ var PLACEHOLDER_COLOR = "#9ca3af";
5504
+ var NEUTRAL_GRAY2 = "#64748b";
5505
+ var BASE_COLORS2 = {
5506
+ "0": "#10b981",
5507
+ "1": "#3b82f6",
5508
+ "2": "#8b5cf6",
5509
+ "3": "#f43f5e",
5510
+ "4": "#f59e0b",
5511
+ "5": "#84cc16",
5512
+ "6": "#a855f7",
5513
+ "7": "#06b6d4",
5514
+ "8": "#f97316",
5515
+ "9": "#14b8a6",
5516
+ a: "#ef4444",
5517
+ b: "#6366f1",
5518
+ c: "#ec4899",
5519
+ d: "#22c55e",
5520
+ e: "#eab308",
5521
+ f: "#0ea5e9"
5522
+ };
5523
+ function hexToRgba(hex, opacity) {
5524
+ const r = parseInt(hex.slice(1, 3), 16);
5525
+ const g = parseInt(hex.slice(3, 5), 16);
5526
+ const b = parseInt(hex.slice(5, 7), 16);
5527
+ return `rgba(${r}, ${g}, ${b}, ${opacity})`;
5528
+ }
5529
+ function getEntityColor2(entityId, variant = "medium") {
5530
+ const baseColor = BASE_COLORS2[entityId[4]] || BASE_COLORS2["0"];
5531
+ switch (variant) {
5532
+ case "light":
5533
+ return hexToRgba(baseColor, OPACITY_LIGHT);
5534
+ case "medium":
5535
+ return hexToRgba(baseColor, OPACITY_MEDIUM);
5536
+ case "text":
5537
+ return baseColor;
5538
+ }
5539
+ }
5540
+ function getEntityColorStyles(entityId) {
5541
+ const baseColor = BASE_COLORS2[entityId[4]] || BASE_COLORS2["0"];
5542
+ return {
5543
+ backgroundColor: getEntityColor2(entityId, "light"),
5544
+ color: baseColor,
5545
+ borderColor: hexToRgba(baseColor, OPACITY_BORDER)
5546
+ };
5547
+ }
5548
+ var getWorkspaceColor = (workspaceId, useWorkspaceColors) => {
5549
+ const shouldUseWorkspaceColors = useWorkspaceColors !== void 0 ? useWorkspaceColors : true;
5550
+ if (!shouldUseWorkspaceColors) return "hsl(var(--primary))";
5551
+ const isValidId = workspaceId && workspaceId.startsWith("wrk-") && workspaceId.length >= 5;
5552
+ if (!isValidId) return "hsl(var(--primary))";
5553
+ return getEntityColor2(workspaceId, "medium");
5554
+ };
5555
+ function getNotificationTypeMeta(type) {
5556
+ const WorkspaceIcon = getEntityIcon("WORKSPACE");
5557
+ switch (type) {
5558
+ case "user_message":
5559
+ return { Icon: MessageCircleMore, iconClassName: "text-primary", label: "Message" };
5560
+ case "workspaceuser_added_owner":
5561
+ case "workspaceuser_added_collaborator":
5562
+ case "workspaceuser_added_guest":
5563
+ return { Icon: WorkspaceIcon, iconClassName: "text-primary", label: "Added" };
5564
+ case "workspaceuser_removed":
5565
+ return { Icon: WorkspaceIcon, iconClassName: "text-primary", label: "Removed" };
5566
+ case "workspaceuser_updated_owner":
5567
+ case "workspaceuser_updated_collaborator":
5568
+ case "workspaceuser_updated_guest":
5569
+ return { Icon: WorkspaceIcon, iconClassName: "text-primary", label: "Role changed" };
5570
+ case "contact_accepted":
5571
+ return { Icon: UserCheck, iconClassName: "text-green-500", label: "Invitation" };
5572
+ case "signup_reward":
5573
+ return { Icon: PartyPopper, iconClassName: "text-green-600", label: "Signup bonus" };
5574
+ case "referral_reward":
5575
+ return { Icon: Gift, iconClassName: "text-green-600", label: "Reward earned" };
5576
+ case "quota_threshold_50":
5577
+ return { Icon: Gauge, iconClassName: "text-blue-500", label: "Usage 50%" };
5578
+ case "quota_threshold_90":
5579
+ return { Icon: Gauge, iconClassName: "text-orange-500", label: "Usage 90%" };
5580
+ case "quota_threshold_100":
5581
+ return { Icon: Gauge, iconClassName: "text-red-500", label: "Usage limit" };
5582
+ case "activity":
5583
+ return { Icon: Activity, iconClassName: "text-muted-foreground", label: "Activity" };
5584
+ default:
5585
+ return { Icon: Info, iconClassName: "text-blue-500", label: type || "Notification" };
5586
+ }
5587
+ }
5588
+ function isWorkspaceNotificationType(type) {
5589
+ return type.startsWith("workspaceuser_");
5590
+ }
5591
+ function getWorkspaceActionText(type) {
5592
+ switch (type) {
5593
+ case "workspaceuser_added_owner":
5594
+ return "added you as owner";
5595
+ case "workspaceuser_added_collaborator":
5596
+ return "added you as collaborator";
5597
+ case "workspaceuser_added_guest":
5598
+ return "added you as guest";
5599
+ case "workspaceuser_removed":
5600
+ return "removed you";
5601
+ case "workspaceuser_updated_owner":
5602
+ return "changed your role to owner";
5603
+ case "workspaceuser_updated_collaborator":
5604
+ return "changed your role to collaborator";
5605
+ case "workspaceuser_updated_guest":
5606
+ return "changed your role to guest";
5607
+ default:
5608
+ return "updated your access";
5609
+ }
5610
+ }
5611
+ function getWorkspaceSentPhrase(type) {
5612
+ switch (type) {
5613
+ case "workspaceuser_added_owner":
5614
+ return { before: "You added", after: "as owner" };
5615
+ case "workspaceuser_added_collaborator":
5616
+ return { before: "You added", after: "as collaborator" };
5617
+ case "workspaceuser_added_guest":
5618
+ return { before: "You added", after: "as guest" };
5619
+ case "workspaceuser_removed":
5620
+ return { before: "You removed", after: "" };
5621
+ case "workspaceuser_updated_owner":
5622
+ return { before: "You set", after: "as owner" };
5623
+ case "workspaceuser_updated_collaborator":
5624
+ return { before: "You set", after: "as collaborator" };
5625
+ case "workspaceuser_updated_guest":
5626
+ return { before: "You set", after: "as guest" };
5627
+ default:
5628
+ return { before: "You updated access for", after: "" };
5629
+ }
5630
+ }
5631
+ function parseActivityContent(content) {
5632
+ if (!content) return null;
5633
+ try {
5634
+ const parsed = JSON.parse(content);
5635
+ if (parsed && typeof parsed === "object" && typeof parsed.event === "string") {
5636
+ return parsed;
5637
+ }
5638
+ } catch {
5639
+ }
5640
+ return null;
5641
+ }
5642
+ function str(v) {
5643
+ return typeof v === "string" && v ? v : void 0;
5644
+ }
5645
+ function describeActivity(content) {
5646
+ const parsed = typeof content === "string" || content == null ? parseActivityContent(content) : content;
5647
+ if (!parsed) {
5648
+ return { Icon: Activity, iconClassName: "text-muted-foreground", title: "Activity" };
5649
+ }
5650
+ const fileName = str(parsed.file_name);
5651
+ switch (parsed.event) {
5652
+ case "workspace_opened":
5653
+ return {
5654
+ Icon: SquareArrowOutUpRight,
5655
+ iconClassName: "text-primary",
5656
+ title: "Opened a workspace"
5657
+ };
5658
+ case "workspace_created":
5659
+ return { Icon: FolderPlus, iconClassName: "text-green-600", title: "Created a workspace" };
5660
+ case "workspace_updated":
5661
+ return { Icon: Pencil, iconClassName: "text-primary", title: "Updated workspace settings" };
5662
+ case "workspace_deleted":
5663
+ return { Icon: Trash2, iconClassName: "text-red-500", title: "Deleted a workspace" };
5664
+ case "document_processing": {
5665
+ const failed = str(parsed.status) === "failed";
5666
+ const noun = fileName ? `\u201C${fileName}\u201D` : "a document";
5667
+ return failed ? { Icon: FileX2, iconClassName: "text-red-500", title: `Failed to process ${noun}` } : { Icon: FileCheck2, iconClassName: "text-green-600", title: `Processed ${noun}` };
5668
+ }
5669
+ default:
5670
+ return {
5671
+ Icon: parsed.workspace_ext_id ? getEntityIcon("WORKSPACE") : Activity,
5672
+ iconClassName: "text-muted-foreground",
5673
+ title: humaniseEvent(parsed.event)
5674
+ };
5675
+ }
5676
+ }
5677
+ function humaniseEvent(event) {
5678
+ const words = event.replace(/[_-]+/g, " ").trim();
5679
+ return words ? words.charAt(0).toUpperCase() + words.slice(1) : "Activity";
5680
+ }
5681
+ function formatRelative(iso) {
5682
+ const then = new Date(iso).getTime();
5683
+ if (Number.isNaN(then)) return "";
5684
+ const secs = Math.round((Date.now() - then) / 1e3);
5685
+ if (secs < 45) return "just now";
5686
+ const mins = Math.round(secs / 60);
5687
+ if (mins < 60) return `${mins}m`;
5688
+ const hours = Math.round(mins / 60);
5689
+ if (hours < 24) return `${hours}h`;
5690
+ const days = Math.round(hours / 24);
5691
+ if (days < 7) return `${days}d`;
5692
+ return new Date(iso).toLocaleDateString();
5693
+ }
5694
+ function ActivityFeed({
5695
+ limit = 20,
5696
+ className,
5697
+ emptyLabel = "No recent activity",
5698
+ enabled,
5699
+ "data-testid": testId = "activity-feed"
5700
+ }) {
5701
+ const { data, isLoading, isError } = useActivity({ limit, enabled });
5702
+ if (isLoading) {
5703
+ return /* @__PURE__ */ jsx("div", { className: cn("space-y-2", className), "data-testid": testId, "aria-busy": "true", children: Array.from({ length: 3 }).map((_, i) => /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-3 py-1.5", children: [
5704
+ /* @__PURE__ */ jsx("div", { className: "h-4 w-4 shrink-0 animate-pulse rounded-full bg-muted" }),
5705
+ /* @__PURE__ */ jsx("div", { className: "h-3 flex-1 animate-pulse rounded bg-muted" })
5706
+ ] }, i)) });
5707
+ }
5708
+ if (isError) {
5709
+ return /* @__PURE__ */ jsx("div", { className: cn("text-sm text-muted-foreground", className), "data-testid": testId, children: "Couldn\u2019t load activity." });
5710
+ }
5711
+ const items = data ?? [];
5712
+ if (items.length === 0) {
5713
+ return /* @__PURE__ */ jsxs(
5714
+ "div",
5715
+ {
5716
+ className: cn("flex items-center gap-2 text-sm text-muted-foreground", className),
5717
+ "data-testid": testId,
5718
+ children: [
5719
+ /* @__PURE__ */ jsx(Activity, { className: "h-4 w-4 shrink-0" }),
5720
+ /* @__PURE__ */ jsx("span", { children: emptyLabel })
5721
+ ]
5722
+ }
5723
+ );
5724
+ }
5725
+ return /* @__PURE__ */ jsx("ul", { className: cn("divide-y divide-border", className), "data-testid": testId, children: items.map((item) => {
5726
+ const desc = describeActivity(item.content);
5727
+ return /* @__PURE__ */ jsxs(
5728
+ "li",
5729
+ {
5730
+ className: "flex items-center gap-3 py-2",
5731
+ "data-testid": "activity-feed-item",
5732
+ children: [
5733
+ /* @__PURE__ */ jsx(desc.Icon, { className: cn("h-4 w-4 shrink-0", desc.iconClassName) }),
5734
+ /* @__PURE__ */ jsx("span", { className: "min-w-0 flex-1 truncate text-sm text-foreground", children: desc.title }),
5735
+ /* @__PURE__ */ jsx("time", { className: "shrink-0 text-xs tabular-nums text-muted-foreground", children: formatRelative(item.created_at) })
5736
+ ]
5737
+ },
5738
+ item.external_id
5739
+ );
5740
+ }) });
5741
+ }
5742
+ var seq = 0;
5743
+ var uid = () => `n${Date.now().toString(36)}${(seq++).toString(36)}`;
5744
+ var useNotify = create((set) => ({
5745
+ toasts: [],
5746
+ notifications: [],
5747
+ push: (variant, title, opts = {}) => {
5748
+ const id = uid();
5749
+ const duration = opts.duration ?? (variant === "error" ? 7e3 : 4500);
5750
+ set((s) => {
5751
+ const toast = { id, title, description: opts.description, variant, duration };
5752
+ const next = { toasts: [...s.toasts, toast] };
5753
+ if (opts.record !== false) {
5754
+ const note = {
5755
+ id,
5756
+ title,
5757
+ description: opts.description,
5758
+ variant,
5759
+ ts: Date.now(),
5760
+ read: false,
5761
+ href: opts.href
5762
+ };
5763
+ next.notifications = [note, ...s.notifications].slice(0, 50);
5764
+ }
5765
+ return next;
5766
+ });
5767
+ return id;
5768
+ },
5769
+ dismiss: (id) => set((s) => ({ toasts: s.toasts.filter((t) => t.id !== id) })),
5770
+ markRead: (id) => set((s) => ({
5771
+ notifications: s.notifications.map((n) => n.id === id ? { ...n, read: true } : n)
5772
+ })),
5773
+ markAllRead: () => set((s) => ({ notifications: s.notifications.map((n) => ({ ...n, read: true })) })),
5774
+ removeNotification: (id) => set((s) => ({ notifications: s.notifications.filter((n) => n.id !== id) })),
5775
+ clearNotifications: () => set({ notifications: [] }),
5776
+ seed: (items) => set({ notifications: items })
5777
+ }));
5778
+ function make(variant) {
5779
+ return (title, opts) => useNotify.getState().push(variant, title, opts);
5780
+ }
5781
+ var notify = {
5782
+ success: make("success"),
5783
+ error: make("error"),
5784
+ info: make("info"),
5785
+ warning: make("warning")
5786
+ };
5787
+ function seedNotifications(items) {
5788
+ useNotify.getState().seed(items);
5789
+ }
5790
+ var selectUnread = (s) => s.notifications.filter((n) => !n.read).length;
5791
+ var DEFAULT_NOTIFY_TONE = {
5792
+ success: "text-green-600",
5793
+ error: "text-destructive",
5794
+ warning: "text-amber-500",
5795
+ info: "text-blue-500"
5796
+ };
5797
+
5798
+ // src/directmessages/utils.ts
5799
+ function userInitials(user) {
5800
+ const parts = [user.given_name, user.family_name].filter(Boolean);
5801
+ if (parts.length) {
5802
+ return parts.map((p) => p[0]?.toUpperCase() ?? "").join("").slice(0, 2);
5803
+ }
5804
+ const local = user.email?.split("@")[0] ?? "";
5805
+ return local.slice(0, 2).toUpperCase() || "?";
5806
+ }
5807
+ function userDisplayName(user) {
5808
+ const name = [user.given_name, user.family_name].filter(Boolean).join(" ").trim();
5809
+ return name || user.email?.split("@")[0] || "Unknown";
5810
+ }
5811
+ var RELATIVE = new Intl.RelativeTimeFormat(void 0, { numeric: "auto" });
5812
+ var DIVISIONS = [
5813
+ { amount: 60, unit: "seconds" },
5814
+ { amount: 60, unit: "minutes" },
5815
+ { amount: 24, unit: "hours" },
5816
+ { amount: 7, unit: "days" },
5817
+ { amount: 4.34524, unit: "weeks" },
5818
+ { amount: 12, unit: "months" },
5819
+ { amount: Number.POSITIVE_INFINITY, unit: "years" }
5820
+ ];
5821
+ function formatRelativeTime(iso) {
5822
+ const then = Date.parse(iso);
5823
+ if (Number.isNaN(then)) return "";
5824
+ let duration = (then - Date.now()) / 1e3;
5825
+ if (Math.abs(duration) < 45) return "just now";
5826
+ for (const division of DIVISIONS) {
5827
+ if (Math.abs(duration) < division.amount) {
5828
+ return RELATIVE.format(Math.round(duration), division.unit);
5829
+ }
5830
+ duration /= division.amount;
5831
+ }
5832
+ return "";
5833
+ }
5834
+ var GLYPH = {
5835
+ success: CheckCircle2,
5836
+ error: XCircle,
5837
+ warning: AlertTriangle,
5838
+ info: Info
5839
+ };
5840
+ function NotificationBell({
5841
+ onNavigate,
5842
+ toneClassNames,
5843
+ emptyText = "You're all caught up.",
5844
+ testId = "notifications"
5845
+ }) {
5846
+ const notifications = useNotify((s) => s.notifications);
5847
+ const unread = useNotify(selectUnread);
5848
+ const markAllRead = useNotify((s) => s.markAllRead);
5849
+ const markRead = useNotify((s) => s.markRead);
5850
+ const tone = (v) => toneClassNames?.[v] ?? DEFAULT_NOTIFY_TONE[v];
5851
+ return /* @__PURE__ */ jsxs(DropdownMenu, { children: [
5852
+ /* @__PURE__ */ jsx(DropdownMenuTrigger, { asChild: true, children: /* @__PURE__ */ jsxs(
5853
+ "button",
5854
+ {
5855
+ className: "relative flex size-9 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-accent hover:text-foreground",
5856
+ "data-testid": testId,
5857
+ "aria-label": `Notifications${unread ? ` (${unread} unread)` : ""}`,
5858
+ children: [
5859
+ /* @__PURE__ */ jsx(Bell, { className: "size-5" }),
5860
+ unread > 0 && /* @__PURE__ */ jsx(
5861
+ "span",
5862
+ {
5863
+ className: "absolute -right-0.5 -top-0.5 flex min-w-4 items-center justify-center rounded-full bg-destructive px-1 text-[10px] font-semibold leading-4 text-white",
5864
+ "data-testid": `${testId}-badge`,
5865
+ children: unread > 9 ? "9+" : unread
5866
+ }
5867
+ )
5868
+ ]
5869
+ }
5870
+ ) }),
5871
+ /* @__PURE__ */ jsxs(DropdownMenuContent, { align: "end", className: "w-[360px] p-0", "data-testid": `${testId}-panel`, children: [
5872
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between border-b border-border px-3.5 py-2.5", children: [
5873
+ /* @__PURE__ */ jsx("p", { className: "text-sm font-semibold text-foreground", children: "Notifications" }),
5874
+ unread > 0 && /* @__PURE__ */ jsxs(
5875
+ "button",
5876
+ {
5877
+ onClick: markAllRead,
5878
+ className: "flex items-center gap-1 text-xs font-medium text-primary transition-colors hover:opacity-80",
5879
+ "data-testid": `${testId}-mark-all`,
5880
+ children: [
5881
+ /* @__PURE__ */ jsx(CheckCheck, { className: "size-3.5" }),
5882
+ " Mark all read"
5883
+ ]
5884
+ }
5885
+ )
5886
+ ] }),
5887
+ notifications.length === 0 ? /* @__PURE__ */ jsx("div", { className: "px-3.5 py-10 text-center text-sm text-muted-foreground", children: emptyText }) : /* @__PURE__ */ jsx(ScrollArea, { className: "max-h-[380px]", children: /* @__PURE__ */ jsx("ul", { "data-testid": `${testId}-list`, children: notifications.map((n) => {
5888
+ const Glyph = GLYPH[n.variant];
5889
+ return /* @__PURE__ */ jsx("li", { children: /* @__PURE__ */ jsxs(
5890
+ "button",
5891
+ {
5892
+ onClick: () => {
5893
+ markRead(n.id);
5894
+ if (n.href) onNavigate?.(n.href);
5895
+ },
5896
+ className: cn(
5897
+ "flex w-full items-start gap-3 border-b border-border/60 px-3.5 py-3 text-left transition-colors hover:bg-accent",
5898
+ !n.read && "bg-accent/40"
5899
+ ),
5900
+ "data-testid": `${testId}-item`,
5901
+ children: [
5902
+ /* @__PURE__ */ jsx(Glyph, { className: cn("mt-0.5 size-4 shrink-0", tone(n.variant)) }),
5903
+ /* @__PURE__ */ jsxs("div", { className: "min-w-0 flex-1", children: [
5904
+ /* @__PURE__ */ jsx("p", { className: "text-sm font-medium leading-snug text-foreground", children: n.title }),
5905
+ n.description && /* @__PURE__ */ jsx("p", { className: "mt-0.5 line-clamp-2 text-xs leading-relaxed text-muted-foreground", children: n.description }),
5906
+ /* @__PURE__ */ jsx("p", { className: "mt-1 text-[11px] text-muted-foreground/80", children: formatRelativeTime(new Date(n.ts).toISOString()) })
5907
+ ] }),
5908
+ !n.read && /* @__PURE__ */ jsx("span", { className: "mt-1.5 size-2 shrink-0 rounded-full bg-primary" })
5909
+ ]
5910
+ }
5911
+ ) }, n.id);
5912
+ }) }) })
5913
+ ] })
5914
+ ] });
5915
+ }
5916
+ var GLYPH2 = {
5917
+ success: CheckCircle2,
5918
+ error: XCircle,
5919
+ warning: AlertTriangle,
5920
+ info: Info
5921
+ };
5922
+ function Toaster({ className, toneClassNames, testId = "toaster" }) {
5923
+ const toasts = useNotify((s) => s.toasts);
5924
+ return /* @__PURE__ */ jsx(
5925
+ "div",
5926
+ {
5927
+ className: cn(
5928
+ "pointer-events-none fixed bottom-4 right-4 z-[100] flex w-[min(92vw,380px)] flex-col gap-2.5",
5929
+ className
5930
+ ),
5931
+ "data-testid": testId,
5932
+ "aria-live": "polite",
5933
+ "aria-atomic": "false",
5934
+ children: /* @__PURE__ */ jsx(AnimatePresence, { initial: false, children: toasts.map((t) => /* @__PURE__ */ jsx(ToastCard, { toast: t, toneClassNames }, t.id)) })
5935
+ }
5936
+ );
5937
+ }
5938
+ function ToastCard({
5939
+ toast,
5940
+ toneClassNames
5941
+ }) {
5942
+ const dismiss = useNotify((s) => s.dismiss);
5943
+ const Glyph = GLYPH2[toast.variant];
5944
+ const tone = toneClassNames?.[toast.variant] ?? DEFAULT_NOTIFY_TONE[toast.variant];
5945
+ useEffect(() => {
5946
+ if (!toast.duration) return;
5947
+ const timer = setTimeout(() => dismiss(toast.id), toast.duration);
5948
+ return () => clearTimeout(timer);
5949
+ }, [toast.id, toast.duration, dismiss]);
5950
+ return /* @__PURE__ */ jsxs(
5951
+ motion.div,
5952
+ {
5953
+ layout: true,
5954
+ initial: { opacity: 0, y: 16, scale: 0.97 },
5955
+ animate: { opacity: 1, y: 0, scale: 1 },
5956
+ exit: { opacity: 0, x: 24, scale: 0.97, transition: { duration: 0.18 } },
5957
+ transition: { type: "spring", stiffness: 380, damping: 30 },
5958
+ className: "pointer-events-auto flex items-start gap-3 rounded-lg border border-border bg-card p-3.5 shadow-lg",
5959
+ "data-testid": `toast-${toast.variant}`,
5960
+ "data-toast": "",
5961
+ role: toast.variant === "error" ? "alert" : "status",
5962
+ children: [
5963
+ /* @__PURE__ */ jsx(Glyph, { className: cn("mt-0.5 size-[18px] shrink-0", tone) }),
5964
+ /* @__PURE__ */ jsxs("div", { className: "min-w-0 flex-1", children: [
5965
+ /* @__PURE__ */ jsx("p", { className: "text-sm font-semibold leading-snug text-foreground", children: toast.title }),
5966
+ toast.description && /* @__PURE__ */ jsx("p", { className: "mt-0.5 text-xs leading-relaxed text-muted-foreground", children: toast.description })
5967
+ ] }),
5968
+ /* @__PURE__ */ jsx(
5969
+ "button",
5970
+ {
5971
+ onClick: () => dismiss(toast.id),
5972
+ className: "shrink-0 rounded p-0.5 text-muted-foreground/70 transition-colors hover:bg-accent hover:text-foreground",
5973
+ "aria-label": "Dismiss",
5974
+ "data-testid": "toast-dismiss",
5975
+ children: /* @__PURE__ */ jsx(X, { className: "size-4" })
5976
+ }
5977
+ )
5978
+ ]
5979
+ }
5980
+ );
5981
+ }
5982
+ var DM_QUERY_KEY = ["arbi", "directMessages"];
5983
+ function groupConversations(notifications, myExtId) {
5984
+ const messagesByPeer = /* @__PURE__ */ new Map();
5985
+ const peers = /* @__PURE__ */ new Map();
5986
+ for (const n of notifications) {
5987
+ if (n.type !== "user_message") continue;
5988
+ if (n.sender.external_id === n.recipient.external_id) continue;
5989
+ const isMine = n.sender.external_id === myExtId;
5990
+ const peer = isMine ? n.recipient : n.sender;
5991
+ if (!peer?.external_id) continue;
5992
+ const message = {
5993
+ externalId: n.external_id,
5994
+ body: n.content ?? "",
5995
+ createdAt: n.created_at,
5996
+ isMine,
5997
+ read: n.read,
5998
+ sender: n.sender,
5999
+ recipient: n.recipient
6000
+ };
6001
+ if (!messagesByPeer.has(peer.external_id)) {
6002
+ messagesByPeer.set(peer.external_id, []);
6003
+ peers.set(peer.external_id, peer);
6004
+ }
6005
+ messagesByPeer.get(peer.external_id).push(message);
6006
+ }
6007
+ const conversations = [];
6008
+ for (const [peerId, messages] of messagesByPeer) {
6009
+ messages.sort((a, b) => a.createdAt.localeCompare(b.createdAt));
6010
+ const unreadCount = messages.filter((m) => !m.isMine && !m.read).length;
6011
+ conversations.push({
6012
+ peer: peers.get(peerId),
6013
+ messages,
6014
+ lastMessage: messages[messages.length - 1],
6015
+ unreadCount
6016
+ });
6017
+ }
6018
+ conversations.sort((a, b) => b.lastMessage.createdAt.localeCompare(a.lastMessage.createdAt));
6019
+ return conversations;
6020
+ }
6021
+ function useDirectMessages(options) {
6022
+ const arbi = useArbi();
6023
+ const queryClient = useQueryClient();
6024
+ const enabled = options?.enabled ?? arbi.isLoggedIn;
6025
+ const query = useQuery({
6026
+ queryKey: DM_QUERY_KEY,
6027
+ queryFn: () => arbi.dm.list(),
6028
+ enabled
6029
+ });
6030
+ useArbiWsMessage("user_message", () => {
6031
+ queryClient.invalidateQueries({ queryKey: DM_QUERY_KEY });
6032
+ });
6033
+ const myExtId = useMemo(() => {
6034
+ try {
6035
+ return arbi.user.identity()?.externalId ?? null;
6036
+ } catch {
6037
+ return null;
6038
+ }
6039
+ }, [arbi, query.data]);
6040
+ const conversations = useMemo(
6041
+ () => groupConversations(query.data ?? [], myExtId),
6042
+ [query.data, myExtId]
6043
+ );
6044
+ const invalidate = () => queryClient.invalidateQueries({ queryKey: DM_QUERY_KEY });
6045
+ const sendMutation = useMutation({
6046
+ mutationFn: (vars) => arbi.dm.sendTo(vars.recipientExtId, vars.recipientPublicKey, vars.text),
6047
+ onSuccess: invalidate
6048
+ });
6049
+ const sendToMutation = useMutation({
6050
+ mutationFn: (vars) => arbi.dm.send(vars.recipient, vars.text),
6051
+ onSuccess: invalidate
6052
+ });
6053
+ const markReadMutation = useMutation({
6054
+ mutationFn: (messageIds) => arbi.dm.markRead(messageIds),
6055
+ onSuccess: invalidate
6056
+ });
6057
+ return {
6058
+ conversations,
6059
+ myExtId,
6060
+ isLoading: query.isLoading && enabled,
6061
+ isError: query.isError,
6062
+ error: query.error,
6063
+ refetch: () => query.refetch(),
6064
+ sendMessage: (recipientExtId, recipientPublicKey, text) => sendMutation.mutateAsync({ recipientExtId, recipientPublicKey, text }),
6065
+ sendMessageTo: (recipient, text) => sendToMutation.mutateAsync({ recipient, text }),
6066
+ isSending: sendMutation.isPending || sendToMutation.isPending,
6067
+ markRead: (messageIds) => markReadMutation.mutateAsync(messageIds)
6068
+ };
6069
+ }
6070
+ function DmAvatar({ user, className }) {
6071
+ const name = userDisplayName(user);
6072
+ const tint = getEntityColorStyles(user.external_id);
6073
+ return /* @__PURE__ */ jsxs(Avatar, { className: cn("size-10", className), children: [
6074
+ user.picture ? /* @__PURE__ */ jsx(AvatarImage, { src: user.picture, alt: name }) : null,
6075
+ /* @__PURE__ */ jsx(AvatarFallback, { style: tint, className: "text-xs font-semibold", children: userInitials(user) })
6076
+ ] });
6077
+ }
6078
+ function ConversationList({
6079
+ conversations,
6080
+ selectedPeerId,
6081
+ onSelect,
6082
+ classNames,
6083
+ emptyState
6084
+ }) {
6085
+ return /* @__PURE__ */ jsxs(
6086
+ "aside",
6087
+ {
6088
+ className: "flex min-h-0 flex-col border-b border-border md:w-80 md:shrink-0 md:border-b-0 md:border-r",
6089
+ "data-testid": "arbi-dm-list",
6090
+ children: [
6091
+ /* @__PURE__ */ jsxs("div", { className: "border-b border-border px-4 py-3", children: [
6092
+ /* @__PURE__ */ jsx("p", { className: "text-sm font-semibold text-foreground", children: "Conversations" }),
6093
+ /* @__PURE__ */ jsxs("p", { className: "text-xs text-muted-foreground", children: [
6094
+ conversations.length,
6095
+ " ",
6096
+ conversations.length === 1 ? "colleague" : "colleagues"
6097
+ ] })
6098
+ ] }),
6099
+ /* @__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) => {
6100
+ const { peer, lastMessage, unreadCount } = c;
6101
+ const active = peer.external_id === selectedPeerId;
6102
+ const preview = `${lastMessage.isMine ? "You: " : ""}${lastMessage.body}`;
6103
+ return /* @__PURE__ */ jsx("li", { children: /* @__PURE__ */ jsxs(
6104
+ "button",
6105
+ {
6106
+ type: "button",
6107
+ onClick: () => onSelect(peer.external_id),
6108
+ "data-testid": `arbi-dm-conversation-${peer.external_id}`,
6109
+ className: cn(
6110
+ "flex w-full items-start gap-3 border-b border-border/60 px-4 py-3 text-left transition-colors",
6111
+ active ? "bg-accent" : "hover:bg-accent/60"
6112
+ ),
6113
+ children: [
6114
+ /* @__PURE__ */ jsx(DmAvatar, { user: peer }),
6115
+ /* @__PURE__ */ jsxs("div", { className: "min-w-0 flex-1", children: [
6116
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between gap-2", children: [
6117
+ /* @__PURE__ */ jsx("span", { className: "truncate text-sm font-semibold text-foreground", children: userDisplayName(peer) }),
6118
+ /* @__PURE__ */ jsx("span", { className: "shrink-0 text-[11px] text-muted-foreground", children: formatRelativeTime(lastMessage.createdAt) })
6119
+ ] }),
6120
+ /* @__PURE__ */ jsxs("div", { className: "mt-1 flex items-center gap-2", children: [
6121
+ /* @__PURE__ */ jsx("p", { className: "min-w-0 flex-1 truncate text-xs text-muted-foreground", children: preview }),
6122
+ unreadCount > 0 ? /* @__PURE__ */ jsx(Badge, { className: cn("px-1.5 py-0 text-[10px]", classNames?.unreadBadge), children: unreadCount }) : null
6123
+ ] })
6124
+ ] })
6125
+ ]
6126
+ }
6127
+ ) }, peer.external_id);
6128
+ }) }) })
6129
+ ]
6130
+ }
6131
+ );
6132
+ }
6133
+ function MessageBubble2({ message, classNames }) {
6134
+ const { isMine } = message;
6135
+ const who = isMine ? "You" : userDisplayName(message.sender);
6136
+ return /* @__PURE__ */ jsxs(
6137
+ "div",
6138
+ {
6139
+ "data-testid": "arbi-dm-message",
6140
+ className: cn("flex flex-col gap-1", isMine ? "items-end" : "items-start"),
6141
+ children: [
6142
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 px-1", children: [
6143
+ /* @__PURE__ */ jsx("span", { className: "text-[11px] font-medium text-foreground", children: who }),
6144
+ /* @__PURE__ */ jsx("span", { className: "text-[11px] text-muted-foreground", children: formatRelativeTime(message.createdAt) })
6145
+ ] }),
6146
+ /* @__PURE__ */ jsx(
6147
+ "div",
6148
+ {
6149
+ className: cn(
6150
+ "max-w-[80%] rounded-2xl px-3.5 py-2 text-sm shadow-sm",
6151
+ isMine ? cn("rounded-br-sm bg-accent text-accent-foreground", classNames?.ownBubble) : cn(
6152
+ "rounded-bl-sm border border-border bg-card text-card-foreground",
6153
+ classNames?.peerBubble
6154
+ )
6155
+ ),
6156
+ children: message.body
6157
+ }
6158
+ )
6159
+ ]
6160
+ }
6161
+ );
6162
+ }
6163
+ function MessageThread({ conversation, classNames, emptyState }) {
6164
+ const bottomRef = useRef(null);
6165
+ useEffect(() => {
6166
+ bottomRef.current?.scrollIntoView({ block: "end" });
6167
+ }, [conversation?.peer.external_id, conversation?.messages.length]);
6168
+ if (!conversation) {
6169
+ 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: [
6170
+ /* @__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" }) }),
6171
+ /* @__PURE__ */ jsxs("div", { children: [
6172
+ /* @__PURE__ */ jsx("p", { className: "text-sm font-semibold text-foreground", children: "No conversation selected" }),
6173
+ /* @__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." })
6174
+ ] })
6175
+ ] }) });
6176
+ }
6177
+ const { peer, messages } = conversation;
6178
+ return /* @__PURE__ */ jsxs(Fragment, { children: [
6179
+ /* @__PURE__ */ jsxs("header", { className: "flex items-center gap-3 border-b border-border px-4 py-3", children: [
6180
+ /* @__PURE__ */ jsx(DmAvatar, { user: peer, className: "size-9" }),
6181
+ /* @__PURE__ */ jsxs("div", { className: "min-w-0", children: [
6182
+ /* @__PURE__ */ jsx("p", { className: "truncate text-sm font-semibold text-foreground", children: userDisplayName(peer) }),
6183
+ /* @__PURE__ */ jsx("p", { className: "truncate text-xs text-muted-foreground", children: peer.email })
6184
+ ] })
6185
+ ] }),
6186
+ /* @__PURE__ */ jsx(ScrollArea, { className: "min-h-0 flex-1 bg-background", children: /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-3 px-4 py-4", "data-testid": "arbi-dm-thread", children: [
6187
+ messages.map((m) => /* @__PURE__ */ jsx(MessageBubble2, { message: m, classNames }, m.externalId)),
6188
+ /* @__PURE__ */ jsx("div", { ref: bottomRef })
6189
+ ] }) })
6190
+ ] });
6191
+ }
6192
+ function DmComposer({ placeholder, disabled, onSend, classNames }) {
6193
+ const [draft, setDraft] = useState("");
6194
+ const submit = () => {
6195
+ const text = draft.trim();
6196
+ if (!text || disabled) return;
6197
+ onSend(text);
6198
+ setDraft("");
6199
+ };
6200
+ const onKeyDown = (e) => {
6201
+ if (e.key === "Enter" && !e.shiftKey) {
6202
+ e.preventDefault();
6203
+ submit();
6204
+ }
6205
+ };
6206
+ return /* @__PURE__ */ jsx("div", { className: "border-t border-border p-3", children: /* @__PURE__ */ jsxs("div", { className: "flex items-end gap-2", children: [
6207
+ /* @__PURE__ */ jsx(
6208
+ Textarea,
6209
+ {
6210
+ value: draft,
6211
+ onChange: (e) => setDraft(e.target.value),
6212
+ onKeyDown,
6213
+ placeholder,
6214
+ rows: 1,
6215
+ disabled,
6216
+ className: "max-h-40 min-h-[44px] resize-none",
6217
+ "data-testid": "arbi-dm-input"
6218
+ }
6219
+ ),
6220
+ /* @__PURE__ */ jsxs(
6221
+ Button,
6222
+ {
6223
+ type: "button",
6224
+ onClick: submit,
6225
+ disabled: disabled || !draft.trim(),
6226
+ className: cn(classNames?.sendButton),
6227
+ "data-testid": "arbi-dm-send",
6228
+ children: [
6229
+ /* @__PURE__ */ jsx(Send, { className: "size-4" }),
6230
+ " Send"
6231
+ ]
6232
+ }
6233
+ )
6234
+ ] }) });
6235
+ }
6236
+ function DirectMessages({
6237
+ className,
6238
+ classNames,
6239
+ emptyThread,
6240
+ emptyList
6241
+ }) {
6242
+ const { conversations, isLoading, sendMessage, markRead } = useDirectMessages();
6243
+ const [selectedPeerId, setSelectedPeerId] = useState(null);
6244
+ const selected = useMemo(
6245
+ () => conversations.find((c) => c.peer.external_id === selectedPeerId) ?? null,
6246
+ [conversations, selectedPeerId]
6247
+ );
6248
+ useEffect(() => {
6249
+ if (!selected || selected.unreadCount === 0) return;
6250
+ const unreadIds = selected.messages.filter((m) => !m.isMine && !m.read).map((m) => m.externalId);
6251
+ if (unreadIds.length) void markRead(unreadIds);
6252
+ }, [selected?.peer.external_id, selected?.unreadCount]);
6253
+ const handleSend = (text) => {
6254
+ if (!selected) return;
6255
+ void sendMessage(selected.peer.external_id, selected.peer.encryption_public_key, text);
6256
+ };
6257
+ return /* @__PURE__ */ jsxs(
6258
+ "div",
6259
+ {
6260
+ "data-testid": "arbi-dm",
6261
+ style: { height: "calc(100vh - 16rem)", minHeight: "28rem" },
6262
+ className: cn(
6263
+ "flex flex-col overflow-hidden rounded-xl border border-border bg-card md:flex-row",
6264
+ className
6265
+ ),
6266
+ children: [
6267
+ /* @__PURE__ */ jsx(
6268
+ ConversationList,
6269
+ {
6270
+ conversations,
6271
+ selectedPeerId: selected?.peer.external_id ?? null,
6272
+ onSelect: setSelectedPeerId,
6273
+ classNames,
6274
+ emptyState: isLoading ? "Loading messages\u2026" : emptyList
6275
+ }
6276
+ ),
6277
+ /* @__PURE__ */ jsxs("div", { className: "flex min-h-0 min-w-0 flex-1 flex-col", children: [
6278
+ /* @__PURE__ */ jsx(MessageThread, { conversation: selected, classNames, emptyState: emptyThread }),
6279
+ selected ? /* @__PURE__ */ jsx(
6280
+ DmComposer,
6281
+ {
6282
+ placeholder: `Message ${userDisplayName(selected.peer).split(" ")[0]}\u2026`,
6283
+ onSend: handleSend,
6284
+ classNames
6285
+ }
6286
+ ) : null
6287
+ ] })
6288
+ ]
6289
+ }
6290
+ );
6291
+ }
6292
+ var DEFAULT_ASPECT_OPTIONS = [
6293
+ { label: "1:1", value: 1 },
6294
+ { label: "4:3", value: 4 / 3 },
6295
+ { label: "3:4", value: 3 / 4 },
6296
+ { label: "16:9", value: 16 / 9 },
6297
+ { label: "9:16", value: 9 / 16 }
6298
+ ];
6299
+ function ImageCropper({
6300
+ image,
6301
+ aspect = 1,
6302
+ aspectOptions,
6303
+ cropShape = "rect",
6304
+ minZoom = 1,
6305
+ maxZoom = 3,
6306
+ className,
6307
+ onCropComplete
6308
+ }) {
6309
+ const [crop, setCrop] = useState({ x: 0, y: 0 });
6310
+ const [zoom, setZoom] = useState(1);
6311
+ const [activeAspect, setActiveAspect] = useState(aspectOptions?.[0]?.value ?? aspect);
6312
+ useEffect(() => {
6313
+ if (!aspectOptions) setActiveAspect(aspect);
6314
+ }, [aspect, aspectOptions]);
6315
+ const handleComplete = useCallback(
6316
+ (_, areaPixels) => {
6317
+ onCropComplete?.(areaPixels, activeAspect);
6318
+ },
6319
+ [onCropComplete, activeAspect]
6320
+ );
6321
+ return /* @__PURE__ */ jsxs("div", { className: cn("flex flex-col gap-3", className), children: [
6322
+ /* @__PURE__ */ jsx("div", { className: "relative h-72 w-full overflow-hidden rounded-md bg-foreground/95", children: /* @__PURE__ */ jsx(
6323
+ Cropper,
6324
+ {
6325
+ image,
6326
+ crop,
6327
+ zoom,
6328
+ aspect: activeAspect,
6329
+ cropShape,
6330
+ showGrid: cropShape === "rect",
6331
+ onCropChange: setCrop,
6332
+ onZoomChange: setZoom,
6333
+ onCropComplete: handleComplete,
6334
+ objectFit: "contain"
6335
+ }
6336
+ ) }),
6337
+ aspectOptions && aspectOptions.length > 1 ? /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center gap-1", "data-testid": "image-cropper-aspects", children: [
6338
+ /* @__PURE__ */ jsx("span", { className: "mr-1 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground", children: "Ratio" }),
6339
+ aspectOptions.map((opt) => {
6340
+ const on = opt.value === activeAspect;
6341
+ return /* @__PURE__ */ jsx(
6342
+ "button",
6343
+ {
6344
+ type: "button",
6345
+ onClick: () => setActiveAspect(opt.value),
6346
+ "data-testid": `image-cropper-aspect-${opt.label}`,
6347
+ className: cn(
6348
+ "rounded-md px-2 py-1 text-xs font-medium transition-colors",
6349
+ on ? "bg-primary text-primary-foreground" : "text-muted-foreground hover:bg-accent hover:text-foreground"
6350
+ ),
6351
+ children: opt.label
6352
+ },
6353
+ opt.label
6354
+ );
6355
+ })
6356
+ ] }) : null,
6357
+ /* @__PURE__ */ jsxs("div", { className: "space-y-1.5", children: [
6358
+ /* @__PURE__ */ jsx("label", { className: "text-[11px] font-semibold uppercase tracking-wider text-muted-foreground", children: "Zoom" }),
6359
+ /* @__PURE__ */ jsx(
6360
+ Slider,
6361
+ {
6362
+ value: [zoom],
6363
+ onValueChange: ([v]) => setZoom(v ?? 1),
6364
+ min: minZoom,
6365
+ max: maxZoom,
6366
+ step: 0.01
6367
+ }
6368
+ )
6369
+ ] })
6370
+ ] });
6371
+ }
6372
+
6373
+ // src/imagecrop/cropImage.ts
6374
+ function loadImage(src) {
6375
+ return new Promise((resolve, reject) => {
6376
+ const img = new Image();
6377
+ img.crossOrigin = "anonymous";
6378
+ img.onload = () => resolve(img);
6379
+ img.onerror = () => reject(new Error("Failed to load image for cropping"));
6380
+ img.src = src;
6381
+ });
6382
+ }
6383
+ async function cropImage(imageSrc, area, output = {}) {
6384
+ const { maxSize, mimeType = "image/jpeg", quality = 0.9, background = "#ffffff" } = output;
6385
+ const img = await loadImage(imageSrc);
6386
+ let outW = Math.max(1, Math.round(area.width));
6387
+ let outH = Math.max(1, Math.round(area.height));
6388
+ if (maxSize && Math.max(outW, outH) > maxSize) {
6389
+ const scale = maxSize / Math.max(outW, outH);
6390
+ outW = Math.max(1, Math.round(outW * scale));
6391
+ outH = Math.max(1, Math.round(outH * scale));
6392
+ }
6393
+ const canvas = document.createElement("canvas");
6394
+ canvas.width = outW;
6395
+ canvas.height = outH;
6396
+ const ctx = canvas.getContext("2d");
6397
+ if (!ctx) throw new Error("canvas 2d context unavailable");
6398
+ if (mimeType === "image/jpeg") {
6399
+ ctx.fillStyle = background;
6400
+ ctx.fillRect(0, 0, outW, outH);
6401
+ }
6402
+ ctx.drawImage(img, area.x, area.y, area.width, area.height, 0, 0, outW, outH);
6403
+ const dataUrl = canvas.toDataURL(mimeType, quality);
6404
+ const blob = await new Promise(
6405
+ (resolve, reject) => canvas.toBlob(
6406
+ (b) => b ? resolve(b) : reject(new Error("canvas toBlob returned null")),
6407
+ mimeType,
6408
+ quality
6409
+ )
6410
+ );
6411
+ return { dataUrl, blob, width: outW, height: outH };
6412
+ }
6413
+ function ImageCropModal({
6414
+ open,
6415
+ image,
6416
+ title = "Crop image",
6417
+ saveLabel = "Save",
6418
+ aspect,
6419
+ aspectOptions,
6420
+ cropShape = "rect",
6421
+ output,
6422
+ onComplete,
6423
+ onCancel
6424
+ }) {
6425
+ const [area, setArea] = useState(null);
6426
+ const [busy, setBusy] = useState(false);
6427
+ const handleSave = async () => {
6428
+ if (!image || !area) return;
6429
+ setBusy(true);
6430
+ try {
6431
+ const result = await cropImage(image, area, output);
6432
+ await onComplete(result);
6433
+ } finally {
6434
+ setBusy(false);
6435
+ }
6436
+ };
6437
+ return /* @__PURE__ */ jsx(Dialog, { open, onOpenChange: (next) => !next ? onCancel() : void 0, children: /* @__PURE__ */ jsxs(DialogContent, { className: "sm:max-w-md", "data-testid": "image-crop-modal", children: [
6438
+ /* @__PURE__ */ jsx(DialogHeader, { children: /* @__PURE__ */ jsx(DialogTitle, { children: title }) }),
6439
+ image ? /* @__PURE__ */ jsx(
6440
+ ImageCropper,
6441
+ {
6442
+ image,
6443
+ aspect,
6444
+ aspectOptions,
6445
+ cropShape,
6446
+ onCropComplete: setArea
6447
+ }
6448
+ ) : null,
6449
+ /* @__PURE__ */ jsxs(DialogFooter, { className: "gap-2 sm:gap-2", children: [
6450
+ /* @__PURE__ */ jsx(Button, { variant: "ghost", onClick: onCancel, disabled: busy, children: "Cancel" }),
6451
+ /* @__PURE__ */ jsxs(Button, { onClick: handleSave, disabled: !area || busy, "data-testid": "image-crop-save", children: [
6452
+ busy ? /* @__PURE__ */ jsx(Loader2, { className: "mr-1 size-4 animate-spin" }) : null,
6453
+ saveLabel
6454
+ ] })
6455
+ ] })
6456
+ ] }) });
6457
+ }
6458
+ var MAX_NAV = 5;
6459
+ var MAX_DOCS = 4;
6460
+ function CommandPalette({
6461
+ open,
6462
+ onOpenChange,
6463
+ navItems,
6464
+ onNavigate,
6465
+ buildAskPrompt = (q) => q,
6466
+ askDocIds = [],
6467
+ model,
6468
+ searchDocIds,
6469
+ onOpenDoc,
6470
+ placeholder = "Ask AI, or jump to a page\u2026",
6471
+ askHint = "Grounded in the live workspace",
6472
+ classNames,
6473
+ testId = "command-palette"
6474
+ }) {
6475
+ const task = useAiTask();
6476
+ const searchable = !!searchDocIds && searchDocIds.length > 0;
6477
+ const { results, search, status: searchStatus } = useSemanticSearch(searchDocIds ?? []);
6478
+ const [query, setQuery] = useState("");
6479
+ const inputRef = useRef(null);
6480
+ useEffect(() => {
6481
+ if (open) {
6482
+ setQuery("");
6483
+ task.reset();
6484
+ const t = setTimeout(() => inputRef.current?.focus(), 40);
6485
+ return () => clearTimeout(t);
6486
+ }
6487
+ }, [open]);
6488
+ const showingAnswer = task.status !== "idle";
6489
+ useEffect(() => {
6490
+ if (!searchable || showingAnswer) return;
6491
+ const q = query.trim();
6492
+ if (q.length < 2) return;
6493
+ const t = setTimeout(() => void search(q, "hybrid"), 300);
6494
+ return () => clearTimeout(t);
6495
+ }, [query, searchable, showingAnswer, search]);
6496
+ const navMatches = useMemo(() => {
6497
+ const q = query.trim().toLowerCase();
6498
+ if (!q) return navItems.slice(0, MAX_NAV);
6499
+ return navItems.filter(
6500
+ (i) => i.label.toLowerCase().includes(q) || (i.keywords ? i.keywords.toLowerCase().includes(q) : false)
6501
+ ).slice(0, MAX_NAV);
6502
+ }, [query, navItems]);
6503
+ const docHits = useMemo(() => results.slice(0, MAX_DOCS), [results]);
6504
+ const go = (to) => {
6505
+ onOpenChange(false);
6506
+ onNavigate(to);
6507
+ };
6508
+ const openDoc = (docId) => {
6509
+ onOpenChange(false);
6510
+ onOpenDoc?.(docId);
6511
+ };
6512
+ const ask = () => {
6513
+ const q = query.trim();
6514
+ if (!q || task.isRunning) return;
6515
+ void task.run(buildAskPrompt(q), askDocIds, { model });
6516
+ };
6517
+ return /* @__PURE__ */ jsx(Dialog, { open, onOpenChange, children: /* @__PURE__ */ jsxs(
6518
+ DialogContent,
6519
+ {
6520
+ className: cn(
6521
+ "top-[12%] max-w-2xl translate-y-0 gap-0 overflow-hidden p-0",
6522
+ classNames?.dialog
6523
+ ),
6524
+ "data-testid": testId,
6525
+ children: [
6526
+ /* @__PURE__ */ jsx(DialogTitle, { className: "sr-only", children: "Command palette" }),
6527
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-3 border-b border-border px-4", children: [
6528
+ /* @__PURE__ */ jsx(Sparkles, { className: cn("size-4 shrink-0 text-ai-accent", classNames?.leadingIcon) }),
6529
+ /* @__PURE__ */ jsx(
6530
+ "input",
6531
+ {
6532
+ ref: inputRef,
6533
+ value: query,
6534
+ onChange: (e) => setQuery(e.target.value),
6535
+ onKeyDown: (e) => {
6536
+ if (e.key === "Enter") {
6537
+ e.preventDefault();
6538
+ ask();
6539
+ }
6540
+ },
6541
+ placeholder,
6542
+ className: cn(
6543
+ "h-14 flex-1 bg-transparent text-base outline-none placeholder:text-muted-foreground",
6544
+ classNames?.input
6545
+ ),
6546
+ "data-testid": `${testId}-input`
6547
+ }
6548
+ ),
6549
+ /* @__PURE__ */ jsx("kbd", { className: "hidden rounded border border-border px-1.5 py-0.5 text-[10px] text-muted-foreground sm:inline", children: "\u2318K" })
6550
+ ] }),
6551
+ /* @__PURE__ */ jsxs("div", { className: "max-h-[60vh] overflow-y-auto p-2", children: [
6552
+ query.trim() && !showingAnswer && /* @__PURE__ */ jsxs(
6553
+ "button",
6554
+ {
6555
+ type: "button",
6556
+ onClick: ask,
6557
+ className: cn(
6558
+ "mb-1 flex w-full items-center gap-3 rounded-lg px-3 py-2.5 text-left hover:bg-accent",
6559
+ classNames?.askAction
6560
+ ),
6561
+ "data-testid": `${testId}-ask`,
6562
+ children: [
6563
+ /* @__PURE__ */ jsx(
6564
+ "span",
6565
+ {
6566
+ className: cn(
6567
+ "flex size-8 items-center justify-center rounded-md bg-ai-surface text-ai-accent",
6568
+ classNames?.askChip
6569
+ ),
6570
+ children: /* @__PURE__ */ jsx(Sparkles, { className: "size-4" })
6571
+ }
6572
+ ),
6573
+ /* @__PURE__ */ jsxs("span", { className: "min-w-0 flex-1", children: [
6574
+ /* @__PURE__ */ jsxs("span", { className: "block truncate text-sm font-medium text-foreground", children: [
6575
+ "Ask AI: \u201C",
6576
+ query.trim(),
6577
+ "\u201D"
6578
+ ] }),
6579
+ /* @__PURE__ */ jsx("span", { className: "block text-xs text-muted-foreground", children: askHint })
6580
+ ] }),
6581
+ /* @__PURE__ */ jsx(CornerDownLeft, { className: "size-4 text-muted-foreground" })
6582
+ ]
6583
+ }
6584
+ ),
6585
+ showingAnswer && /* @__PURE__ */ jsxs("div", { className: "px-3 py-2", "data-testid": `${testId}-answer`, children: [
6586
+ /* @__PURE__ */ jsx(
6587
+ AiAnswer,
6588
+ {
6589
+ status: task.status,
6590
+ text: task.text,
6591
+ stepCount: task.stepCount,
6592
+ error: task.error,
6593
+ testId: `${testId}-ai`
6594
+ }
6595
+ ),
6596
+ task.isDone && /* @__PURE__ */ jsx("div", { className: "mt-3 flex justify-end", children: /* @__PURE__ */ jsx(
6597
+ Button,
6598
+ {
6599
+ variant: "outline",
6600
+ size: "sm",
6601
+ onClick: () => task.reset(),
6602
+ "data-testid": `${testId}-clear`,
6603
+ children: "Ask another"
6604
+ }
6605
+ ) })
6606
+ ] }),
6607
+ !showingAnswer && /* @__PURE__ */ jsxs(Fragment, { children: [
6608
+ /* @__PURE__ */ jsx("p", { className: "px-3 pb-1 pt-2 text-[10px] font-semibold uppercase tracking-wide text-muted-foreground", children: query.trim() ? "Jump to" : "Go to" }),
6609
+ navMatches.length === 0 && /* @__PURE__ */ jsx("p", { className: "px-3 py-2 text-sm text-muted-foreground", children: "No pages match \u2014 press Enter to ask AI." }),
6610
+ navMatches.map((item) => /* @__PURE__ */ jsxs(
6611
+ "button",
6612
+ {
6613
+ type: "button",
6614
+ onClick: () => go(item.to),
6615
+ className: cn(
6616
+ "flex w-full items-center gap-3 rounded-lg px-3 py-2 text-left hover:bg-accent",
6617
+ classNames?.navItem
6618
+ ),
6619
+ "data-testid": `${testId}-nav-${item.id}`,
6620
+ children: [
6621
+ item.icon && /* @__PURE__ */ jsx(item.icon, { className: "size-4 text-muted-foreground" }),
6622
+ /* @__PURE__ */ jsx("span", { className: "flex-1 text-sm text-foreground", children: item.label }),
6623
+ /* @__PURE__ */ jsx(ArrowRight, { className: "size-3.5 text-muted-foreground" })
6624
+ ]
6625
+ },
6626
+ item.id
6627
+ )),
6628
+ searchable && query.trim().length >= 2 && /* @__PURE__ */ jsxs(Fragment, { children: [
6629
+ /* @__PURE__ */ jsx("p", { className: "px-3 pb-1 pt-3 text-[10px] font-semibold uppercase tracking-wide text-muted-foreground", children: "Documents" }),
6630
+ searchStatus === "done" && docHits.length === 0 && /* @__PURE__ */ jsx("p", { className: "px-3 py-2 text-sm text-muted-foreground", children: "No passages matched." }),
6631
+ docHits.map((hit, i) => /* @__PURE__ */ jsxs(
6632
+ "button",
6633
+ {
6634
+ type: "button",
6635
+ onClick: () => hit.docId && openDoc(hit.docId),
6636
+ className: "flex w-full items-start gap-3 rounded-lg px-3 py-2 text-left hover:bg-accent",
6637
+ "data-testid": `${testId}-doc-${i}`,
6638
+ children: [
6639
+ /* @__PURE__ */ jsx(FileText, { className: "mt-0.5 size-4 shrink-0 text-ai-accent" }),
6640
+ /* @__PURE__ */ jsxs("span", { className: "min-w-0 flex-1", children: [
6641
+ /* @__PURE__ */ jsxs("span", { className: "block truncate text-sm text-foreground", children: [
6642
+ hit.docTitle ?? "Document",
6643
+ hit.page != null && /* @__PURE__ */ jsxs("span", { className: "text-muted-foreground", children: [
6644
+ " \xB7 p.",
6645
+ hit.page
6646
+ ] })
6647
+ ] }),
6648
+ /* @__PURE__ */ jsx("span", { className: "line-clamp-1 text-xs text-muted-foreground", children: hit.content })
6649
+ ] })
6650
+ ]
6651
+ },
6652
+ `${hit.docId}-${hit.page}-${i}`
6653
+ ))
6654
+ ] })
6655
+ ] })
6656
+ ] })
6657
+ ]
6658
+ }
6659
+ ) });
6660
+ }
6661
+ var CommandPaletteCtx = createContext(null);
6662
+ function useCommandPalette() {
6663
+ const v = useContext(CommandPaletteCtx);
6664
+ if (!v) throw new Error("useCommandPalette must be used within a CommandPaletteProvider");
6665
+ return v;
6666
+ }
6667
+ function CommandPaletteProvider({
6668
+ children,
6669
+ hotkey = true,
6670
+ ...paletteProps
6671
+ }) {
6672
+ const [isOpen, setIsOpen] = useState(false);
6673
+ const open = useCallback(() => setIsOpen(true), []);
6674
+ const close = useCallback(() => setIsOpen(false), []);
6675
+ const toggle = useCallback(() => setIsOpen((o) => !o), []);
6676
+ useEffect(() => {
6677
+ if (!hotkey) return;
6678
+ const onKey = (e) => {
6679
+ if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "k") {
6680
+ e.preventDefault();
6681
+ toggle();
6682
+ }
6683
+ };
6684
+ window.addEventListener("keydown", onKey);
6685
+ return () => window.removeEventListener("keydown", onKey);
6686
+ }, [hotkey, toggle]);
6687
+ const value = useMemo(() => ({ open, close, toggle, isOpen }), [open, close, toggle, isOpen]);
6688
+ return /* @__PURE__ */ jsxs(CommandPaletteCtx.Provider, { value, children: [
6689
+ children,
6690
+ /* @__PURE__ */ jsx(CommandPalette, { open: isOpen, onOpenChange: setIsOpen, ...paletteProps })
6691
+ ] });
6692
+ }
6693
+ function nameInitials(name) {
6694
+ const parts = name.trim().split(/\s+/).filter(Boolean);
6695
+ if (!parts.length) return "?";
6696
+ return parts.slice(0, 2).map((p) => p[0]?.toUpperCase() ?? "").join("");
6697
+ }
6698
+ function UserMenu({
6699
+ user,
6700
+ items = [],
6701
+ onLogout,
6702
+ logoutLabel = "Sign out",
6703
+ align = "end",
6704
+ classNames,
6705
+ testId = "user-menu",
6706
+ logoutTestId
6707
+ }) {
6708
+ return /* @__PURE__ */ jsxs(DropdownMenu, { children: [
6709
+ /* @__PURE__ */ jsx(DropdownMenuTrigger, { asChild: true, children: /* @__PURE__ */ jsxs(
6710
+ "button",
6711
+ {
6712
+ className: cn(
6713
+ "flex items-center gap-2 rounded-md px-1.5 py-1 transition-colors hover:bg-accent",
6714
+ classNames?.trigger
6715
+ ),
6716
+ "data-testid": testId,
6717
+ children: [
6718
+ /* @__PURE__ */ jsxs(Avatar, { className: "size-8", children: [
6719
+ user.picture ? /* @__PURE__ */ jsx(AvatarImage, { src: user.picture, alt: user.name }) : null,
6720
+ /* @__PURE__ */ jsx(
6721
+ AvatarFallback,
6722
+ {
6723
+ className: cn("bg-primary text-primary-foreground", classNames?.fallback),
6724
+ children: nameInitials(user.name)
6725
+ }
6726
+ )
6727
+ ] }),
6728
+ /* @__PURE__ */ jsx(ChevronDown, { className: "size-4 text-muted-foreground" })
6729
+ ]
6730
+ }
6731
+ ) }),
6732
+ /* @__PURE__ */ jsxs(DropdownMenuContent, { align, className: "w-56", children: [
6733
+ /* @__PURE__ */ jsxs(DropdownMenuLabel, { children: [
6734
+ /* @__PURE__ */ jsx("div", { className: "font-medium text-foreground", children: user.name }),
6735
+ user.email && /* @__PURE__ */ jsx("div", { className: "text-xs font-normal text-muted-foreground", children: user.email })
6736
+ ] }),
6737
+ /* @__PURE__ */ jsx(DropdownMenuSeparator, {}),
6738
+ items.map((item) => /* @__PURE__ */ jsxs(DropdownMenuItem, { onClick: item.onSelect, "data-testid": item.testId, children: [
6739
+ item.icon && /* @__PURE__ */ jsx(item.icon, { className: "size-4" }),
6740
+ item.label
6741
+ ] }, item.label)),
6742
+ /* @__PURE__ */ jsxs(DropdownMenuItem, { onClick: onLogout, "data-testid": logoutTestId ?? `${testId}-logout`, children: [
6743
+ /* @__PURE__ */ jsx(LogOut, { className: "size-4" }),
6744
+ logoutLabel
6745
+ ] })
6746
+ ] })
6747
+ ] });
6748
+ }
5128
6749
  var useArbiUiStore = create((set) => ({
5129
6750
  selectedDocIds: [],
5130
6751
  setSelectedDocIds: (ids) => set({ selectedDocIds: ids }),
@@ -5693,6 +7314,6 @@ function DocumentReview({
5693
7314
  );
5694
7315
  }
5695
7316
 
5696
- export { AiActionCard, AiAnswer, AiMarkdown, AppleIcon, ArbiBotHeadIcon, ArbiBotIcon, ArbiChat, ArbiChatPanel, ArbiIcon, ArbiProvider, ArbiWebSocketProvider, ArtifactCanvas, AudIcon, Avatar, AvatarFallback, AvatarImage, Badge, Button, Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle, ChatBubble, Checkbox, CitationRenderer, ClaudeIcon, Collapsible, CollapsibleContent2 as CollapsibleContent, CollapsibleTrigger2 as CollapsibleTrigger, Command, CommandDialog, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList, CommandSeparator, CommandShortcut, Dialog, DialogClose, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogOverlay, DialogPortal, DialogTitle, DialogTrigger, DocIcon, DocQaPanel, DocSearch, DocumentEntity, DocumentGallery, DocumentReview, DocumentTable, DropdownMenu, DropdownMenuCheckboxItem, DropdownMenuContent, DropdownMenuGroup, DropdownMenuItem, DropdownMenuLabel, DropdownMenuPortal, DropdownMenuRadioGroup, DropdownMenuRadioItem, DropdownMenuSeparator, DropdownMenuShortcut, DropdownMenuSub, DropdownMenuSubContent, DropdownMenuSubTrigger, DropdownMenuTrigger, EmlIcon, EntityPill, FILE_TYPE_COLORS, FileIcon, FireworksIcon, GeminiIcon, GitHubIcon, GoogleIcon, HoverCard, HoverCardContent, HoverCardTrigger, HtmlIcon, ImgIcon, Input, Label, LinkedInIcon, MessageArtifactCard, OpenAIIcon, PdfIcon, Popover, PopoverAnchor, PopoverContent, PopoverTrigger, Progress, ProjectEntity, ProviderIcon, RadioGroup, RadioGroupItem, ScrollArea, ScrollBar, Select, SelectContent, SelectGroup, SelectItem, SelectLabel, SelectScrollDownButton, SelectScrollUpButton, SelectSeparator, SelectTrigger, SelectValue, Separator, Slider, Switch, TAG_TYPE_ICONS, TAG_TYPE_LABELS, Table, TableBody, TableCaption, TableCell, TableFooter, TableHead, TableHeader, TableRow, Tabs, TabsContent, TabsList, TabsTrigger, TagEntity, Textarea, Toggle, ToggleGroup, ToggleGroupItem, Tooltip, TooltipContent, TooltipProvider, TooltipTrigger, TxtIcon, TypingIndicator, UserEntity, VidIcon, XlsIcon, arbiQueryKeys, badgeVariants, buttonVariants, cardVariants, cn, getTagTypeIcon, getTagTypeLabel, markdownBaseComponents, redlineStats, textToArtifact, toRedlineMarkdown, toggleVariants, useAgents, useAiTask, useArbi, useArbiConnected, useArbiDocumentSync, useArbiUiStore, useArbiWebSocket, useArbiWsContext, useArbiWsMessage, useArbiWsStatus, useArbiWsStore, useArbiWsTask, useArbiWsTasks, useAssistantQuery, useConfigs, useConversations, useDeleteAgents, useDocuments, useHealth, useMemories, useParsedDocument, useSemanticSearch, useSessions, useTags, useTasks, useThumbnails, useWorkspaceDocs, useWorkspaces };
7317
+ export { ActivityFeed, AiActionCard, AiAnswer, AiMarkdown, AppleIcon, ArbiBotHeadIcon, ArbiBotIcon, ArbiChat, ArbiChatPanel, ArbiIcon, ArbiProvider, ArbiWebSocketProvider, ArtifactCanvas, AudIcon, Avatar, AvatarFallback, AvatarImage, BASE_COLORS2 as BASE_COLORS, Badge, Button, Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle, ChatBubble, Checkbox, CitationRenderer, ClaudeIcon, Collapsible, CollapsibleContent2 as CollapsibleContent, CollapsibleTrigger2 as CollapsibleTrigger, Command, CommandDialog, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList, CommandPalette, CommandPaletteProvider, CommandSeparator, CommandShortcut, ConversationList, DEFAULT_ASPECT_OPTIONS, DEFAULT_NOTIFY_TONE, Dialog, DialogClose, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogOverlay, DialogPortal, DialogTitle, DialogTrigger, DirectMessages, DmAvatar, DmComposer, DocIcon, DocQaPanel, DocSearch, DocumentEntity, DocumentGallery, DocumentReview, DocumentTable, DropdownMenu, DropdownMenuCheckboxItem, DropdownMenuContent, DropdownMenuGroup, DropdownMenuItem, DropdownMenuLabel, DropdownMenuPortal, DropdownMenuRadioGroup, DropdownMenuRadioItem, DropdownMenuSeparator, DropdownMenuShortcut, DropdownMenuSub, DropdownMenuSubContent, DropdownMenuSubTrigger, DropdownMenuTrigger, ENTITY_MAPPINGS, EmlIcon, EntityIcon, EntityPill, FILE_TYPE_COLORS, FileIcon, FireworksIcon, GeminiIcon, GitHubIcon, GoogleIcon, HoverCard, HoverCardContent, HoverCardTrigger, HtmlIcon, ImageCropModal, ImageCropper, ImgIcon, Input, Label, LinkedInIcon, MessageArtifactCard, MessageBubble2 as MessageBubble, MessageThread, NEUTRAL_GRAY2 as NEUTRAL_GRAY, NotificationBell, OpenAIIcon, PLACEHOLDER_COLOR, PdfIcon, Popover, PopoverAnchor, PopoverContent, PopoverTrigger, Progress, ProjectEntity, ProviderIcon, RadioGroup, RadioGroupItem, ScrollArea, ScrollBar, Select, SelectContent, SelectGroup, SelectItem, SelectLabel, SelectScrollDownButton, SelectScrollUpButton, SelectSeparator, SelectTrigger, SelectValue, Separator, Slider, Switch, TAG_TYPE_ICONS, TAG_TYPE_LABELS, Table, TableBody, TableCaption, TableCell, TableFooter, TableHead, TableHeader, TableRow, Tabs, TabsContent, TabsList, TabsTrigger, TagEntity, Textarea, Toaster, Toggle, ToggleGroup, ToggleGroupItem, Tooltip, TooltipContent, TooltipProvider, TooltipTrigger, TxtIcon, TypingIndicator, UserEntity, UserMenu, VISIBILITY_ICONS, VidIcon, VisibilityIcon, XlsIcon, arbiQueryKeys, badgeVariants, buttonVariants, cardVariants, cn, configureEntityRegistry, cropImage, describeActivity, formatRelativeTime, getEntityColor2 as getEntityColor, getEntityColorStyles, getEntityIcon, getEntityLabel, getNotificationTypeMeta, getTagTypeIcon, getTagTypeLabel, getWorkspaceActionText, getWorkspaceColor, getWorkspaceSentPhrase, isWorkspaceNotificationType, markdownBaseComponents, notify, parseActivityContent, redlineStats, seedNotifications, selectUnread, textToArtifact, toRedlineMarkdown, toggleVariants, useActivity, useAgents, useAiTask, useArbi, useArbiConnected, useArbiDocumentSync, useArbiUiStore, useArbiWebSocket, useArbiWsContext, useArbiWsMessage, useArbiWsStatus, useArbiWsStore, useArbiWsTask, useArbiWsTasks, useAssistantQuery, useCommandPalette, useConfigs, useConversations, useDeleteAgents, useDirectMessages, useDocuments, useHealth, useMemories, useNotify, useParsedDocument, useProjectInvoices, useProjectUsage, useProjects, useProjectsUsage, useSemanticSearch, useSessions, useTags, useTasks, useThumbnails, useUserUsageToday, useWorkspaceChronology, useWorkspaceDocs, useWorkspaces, userDisplayName, userInitials };
5697
7318
  //# sourceMappingURL=index.js.map
5698
7319
  //# sourceMappingURL=index.js.map