Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.
JavaScript aianthropiccross-platformgeminigroqlinuxmacosnvidiaopen-sourceopenaiparakeetspeech-to-texttranscribewhisperwindows
feat(workspaces): workspace switcher in the sidebar, profile menu in the top bar (#2876)
Chad Piha7e7c462754af
diff --git a/scripts/sync-nucleo-icons.js b/scripts/sync-nucleo-icons.jsindex 5e8040167..ee43e3352 100644--- a/scripts/sync-nucleo-icons.js+++ b/scripts/sync-nucleo-icons.js@@ -89,6 +89,7 @@ import * as Nucleo from "./nucleo";export type { IconComponent, IconProps } from "./createIcon";export {Bold,+ ChevronsUpDown,Circle,CopyRounded,FolderRounded,diff --git a/src/components/ControlPanel.tsx b/src/components/ControlPanel.tsxindex 63cb1bb77..735044a9b 100644--- a/src/components/ControlPanel.tsx+++ b/src/components/ControlPanel.tsx@@ -11,14 +11,13 @@ import PostMigrationOnboarding from "./PostMigrationOnboarding";import { RequiredModelsBanner } from "./RequiredModelsBanner";import { ConfirmDialog, AlertDialog } from "./ui/dialog";import { useDialogs } from "../hooks/useDialogs";+import { useSignOut } from "../hooks/useSignOut";import { useHotkey } from "../hooks/useHotkey";import { useToast } from "./ui/useToast";import { useUpdater } from "../hooks/useUpdater";import { useSettings } from "../hooks/useSettings";import { useAuth } from "../hooks/useAuth";import { useJoinableWorkspaces } from "../hooks/useJoinableWorkspaces";-import { useWorkspace } from "../hooks/useWorkspace";-import { manageableWorkspaces, selectWorkspaceForSpaceCreation } from "../lib/workspaceSelection";import { useUsage } from "../hooks/useUsage";import { decideUpsell } from "../lib/upsell";import { useCollapsibleSidebar } from "../hooks/useCollapsibleSidebar";@@ -61,6 +60,7 @@ import { navigateMeetingNotification } from "./meetingNotificationNavigation";import MeetingRecordingMount from "./MeetingRecordingMount";import MeetingRecordingPill from "./notes/MeetingRecordingPill";import NewNoteMenu from "./notes/NewNoteMenu";+import ProfileMenu from "./ProfileMenu";import { getCachedPlatform } from "../utils/platform";import { isAccessibilitySkipped } from "../utils/permissions";@@ -103,7 +103,6 @@ const SIDEBAR_WIDTH_PX = 192;const SettingsModal = React.lazy(() => import("./SettingsModal"));const ReferralModal = React.lazy(() => import("./ReferralModal"));-const InviteTeammateDialog = React.lazy(() => import("./InviteTeammateDialog"));const PersonalNotesView = React.lazy(() => import("./notes/PersonalNotesView"));const InsightsView = React.lazy(() => import("./InsightsView"));const DictionaryView = React.lazy(() => import("./DictionaryView"));@@ -137,7 +136,6 @@ export default function ControlPanel({ initialSettingsSection }: ControlPanelPro() => localStorage.getItem("aiCTADismissed") === "true");const [showReferrals, setShowReferrals] = useState(false);- const [showInviteTeam, setShowInviteTeam] = useState(false);const [invitationToken, setInvitationToken] = useState<string | null>(null);const [invitationNotesEntry, setInvitationNotesEntry] = useState<{workspaceId: string;@@ -185,14 +183,6 @@ export default function ControlPanel({ initialSettingsSection }: ControlPanelProdismiss: dismissJoinable,markRequested,} = useJoinableWorkspaces(user?.id ?? null, isSignedIn && !invitationToken);- const { workspaces, active: activeWorkspace } = useWorkspace();- // Invitations are owner/admin-only (server-enforced), so the sidebar row- // only exists when the user can manage a workspace.- const inviteWorkspace = selectWorkspaceForSpaceCreation(- manageableWorkspaces(workspaces),- activeWorkspace,- null- );const usage = useUsage();const upsell = decideUpsell({authLoaded,@@ -264,6 +254,7 @@ export default function ControlPanel({ initialSettingsSection }: ControlPanelProhideConfirmDialog,hideAlertDialog,} = useDialogs();+ const { requestSignOut } = useSignOut({ showConfirmDialog, showAlertDialog });const loadTranscriptions = useCallback(async (includeDiscarded?: boolean) => {@@ -944,6 +935,8 @@ export default function ControlPanel({ initialSettingsSection }: ControlPanelProdescription={confirmDialog.description}onConfirm={confirmDialog.onConfirm}variant={confirmDialog.variant}+ confirmText={confirmDialog.confirmText}+ cancelText={confirmDialog.cancelText}/><AlertDialog@@ -988,17 +981,6 @@ export default function ControlPanel({ initialSettingsSection }: ControlPanelPro</Suspense>)}- {showInviteTeam && inviteWorkspace && (- <Suspense fallback={null}>- <InviteTeammateDialog- open={showInviteTeam}- onOpenChange={setShowInviteTeam}- workspaceId={inviteWorkspace.id}- workspaceName={inviteWorkspace.name}- />- </Suspense>- )}-<AcceptInvitationModaltoken={invitationToken}onClose={() => setInvitationToken(null)}@@ -1064,17 +1046,12 @@ export default function ControlPanel({ initialSettingsSection }: ControlPanelProsetShowSettings(true);}}onOpenReferrals={() => setShowReferrals(true)}- onInviteTeam={inviteWorkspace ? () => setShowInviteTeam(true) : undefined}onUpgrade={() => {setSettingsSection("plansBilling");setShowSettings(true);}}isOverLimit={usage?.isOverLimit ?? false}- userName={user?.name}- userEmail={user?.email}- userImage={user?.image}isSignedIn={isSignedIn}- authLoaded={authLoaded}upsell={upsell}updateAction={!updateStatus.isDevelopment &&@@ -1107,10 +1084,20 @@ export default function ControlPanel({ initialSettingsSection }: ControlPanelProisSidePanelLayout={isSidePanelLayout}onExitSidePanel={handleExitSidePanel}actions={- <NewNoteMenu- onNewNote={handleNewNote}- onNewChat={agentAllowedByPolicy ? () => setActiveView("chat") : undefined}- />+ <div className="flex items-center gap-2">+ <NewNoteMenu+ onNewNote={handleNewNote}+ onNewChat={agentAllowedByPolicy ? () => setActiveView("chat") : undefined}+ />+ <ProfileMenu+ onOpenSettings={(section) => {+ setSettingsSection(section);+ setShowSettings(true);+ }}+ onOpenReferrals={() => setShowReferrals(true)}+ onSignOut={requestSignOut}+ />+ </div>}/><div className="scrollbar-hidden flex-1 overflow-y-auto">diff --git a/src/components/ControlPanelSidebar.tsx b/src/components/ControlPanelSidebar.tsxindex 1975aecb3..be78dbd05 100644--- a/src/components/ControlPanelSidebar.tsx+++ b/src/components/ControlPanelSidebar.tsx@@ -1,20 +1,11 @@import React, { useState } from "react";-import {- Gift,- Lock,- Settings,- ShieldCheck,- HelpCircle,- UserCircle,- UserPlus,- X,- Zap,-} from "./icons";+import { Gift, Lock, Settings, ShieldCheck, HelpCircle, X, Zap } from "./icons";import logoIcon from "../assets/icon.png";import { useTranslation } from "react-i18next";import { cn } from "./lib/utils";import SupportDropdown from "./ui/SupportDropdown";import { Button } from "./ui/button";+import WorkspaceSwitcher from "./WorkspaceSwitcher";import type { UpsellDecision } from "../lib/upsell";import { useControlPanelNavItems, type ControlPanelView } from "./controlPanelNav";@@ -32,14 +23,9 @@ interface ControlPanelSidebarProps {onViewChange: (view: ControlPanelView) => void;onOpenSettings: () => void;onOpenReferrals?: () => void;- onInviteTeam?: () => void;onUpgrade?: () => void;isOverLimit?: boolean;- userName?: string | null;- userEmail?: string | null;- userImage?: string | null;isSignedIn?: boolean;- authLoaded?: boolean;upsell: UpsellDecision;updateAction?: React.ReactNode;}@@ -49,14 +35,9 @@ export default function ControlPanelSidebar({onViewChange,onOpenSettings,onOpenReferrals,- onInviteTeam,onUpgrade,isOverLimit,- userName,- userEmail,- userImage,isSignedIn,- authLoaded,upsell,updateAction,}: ControlPanelSidebarProps) {@@ -64,9 +45,6 @@ export default function ControlPanelSidebar({const [upgradeDismissed, setUpgradeDismissed] = useState(() => localStorage.getItem("upgradeProDismissed") === "true");- // A blocked or expired avatar URL falls back to the icon instead of the- // broken-image glyph, like AccountAvatar and MemberAvatar.- const [failedImage, setFailedImage] = useState<string | null>(null);const showLimitBanner = upsell === "show" && Boolean(isSignedIn) && Boolean(isOverLimit);const showUpgradeBanner = upsell === "show" && !showLimitBanner && !upgradeDismissed;@@ -190,17 +168,6 @@ export default function ControlPanelSidebar({</div>)}- {onInviteTeam && (- <button- onClick={onInviteTeam}- aria-label={t("sidebar.inviteTeam")}- className={rowButtonClass}- >- <UserPlus size={16} className={rowIconClass} />- <span className={rowLabelClass}>{t("sidebar.inviteTeam")}</span>- </button>- )}-{isSignedIn && onOpenReferrals && (<buttononClick={onOpenReferrals}@@ -230,40 +197,8 @@ export default function ControlPanelSidebar({}/>- <div className="mx-1 h-px bg-border/10 dark:bg-white/6 my-1.5!" />-- <div className="flex items-center gap-2.5 px-2.5 py-1.5 rounded-md">- {userImage && userImage !== failedImage ? (- <img- src={userImage}- alt=""- onError={() => setFailedImage(userImage)}- className="w-6 h-6 rounded-full shrink-0 object-cover"- />- ) : (- <UserCircle size={18} className="shrink-0 text-foreground/50 dark:text-foreground/45" />- )}- <div className="flex-1 min-w-0">- {isSignedIn && (userName || userEmail) ? (- <>- <p- dir="auto"- className="text-xs text-foreground/80 dark:text-foreground/80 truncate leading-tight"- >- {userName || t("sidebar.defaultUser")}- </p>- {userEmail && (- <p className="text-xs text-foreground/55 dark:text-foreground/55 truncate leading-tight">- <bdi dir="ltr">{userEmail}</bdi>- </p>- )}- </>- ) : authLoaded && !isSignedIn ? (- <p className="text-xs text-foreground/45 dark:text-foreground/55">- {t("sidebar.notSignedIn")}- </p>- ) : null}- </div>+ <div className="pt-1">+ <WorkspaceSwitcher /></div></div></div>diff --git a/src/components/MemberAvatar.tsx b/src/components/MemberAvatar.tsxindex 573bb1451..1506938ea 100644--- a/src/components/MemberAvatar.tsx+++ b/src/components/MemberAvatar.tsx@@ -1,5 +1,6 @@import { useState } from "react";import { cn } from "./lib/utils";+import { avatarInitials } from "../lib/avatarInitials";const SIZES = {sm: { box: "w-5 h-5", text: "text-[9px]" },@@ -40,7 +41,7 @@ export default function MemberAvatar({ name, email, image, size = "md" }: Member"rounded-full bg-primary/10 text-primary font-semibold flex items-center justify-center shrink-0")}>- {(name || email || "?").slice(0, 2).toUpperCase()}+ {avatarInitials(name, email)}</span>);}diff --git a/src/components/ProfileMenu.tsx b/src/components/ProfileMenu.tsxnew file mode 100644index 000000000..f480a09bc--- /dev/null+++ b/src/components/ProfileMenu.tsx@@ -0,0 +1,106 @@+import React from "react";+import { useTranslation } from "react-i18next";+import { CreditCard, Gift, LogOut, UserCircle } from "./icons";+import MemberAvatar from "./MemberAvatar";+import { Badge } from "./ui/badge";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+} from "./ui/dropdown-menu";+import { useAuth } from "../hooks/useAuth";+import { useUsage } from "../hooks/useUsage";+import { useAccountPlan } from "../hooks/useAccountPlan";++const triggerClass =+ "flex h-8 w-8 shrink-0 items-center justify-center rounded-full outline-none transition-opacity duration-150 hover:opacity-85 active:opacity-75 focus-visible:ring-2 focus-visible:ring-primary/40";+const itemClass = "gap-2.5 px-2 py-1.5 text-[13px]";+const itemIconClass = "shrink-0 text-foreground/60";++interface ProfileMenuProps {+ onOpenSettings: (section: string) => void;+ onOpenReferrals: () => void;+ onSignOut: () => void;+}++export default function ProfileMenu({+ onOpenSettings,+ onOpenReferrals,+ onSignOut,+}: ProfileMenuProps): React.ReactElement {+ const { t } = useTranslation();+ const { isSignedIn, isLoaded, user } = useAuth();+ const usage = useUsage();+ const { planLabel } = useAccountPlan(usage);++ // Until the session settles a signed-in user reads as signed out; hold the slot instead of+ // flashing Sign in.+ if (!isLoaded) return <span aria-hidden="true" className="h-8 w-8 shrink-0" />;++ // Signed out there is nothing to choose between: Profile is where sign-in lives.+ if (!isSignedIn || !user) {+ return (+ <button+ type="button"+ onClick={() => onOpenSettings("account")}+ aria-label={t("common.signIn")}+ title={t("common.signIn")}+ className={triggerClass}+ >+ <UserCircle size={20} className="text-foreground/55" />+ </button>+ );+ }++ const name = user.name || t("sidebar.defaultUser");++ return (+ <DropdownMenu modal={false}>+ <DropdownMenuTrigger aria-label={t("sidebar.accountMenu", { name })} className={triggerClass}>+ <MemberAvatar name={user.name} email={user.email} image={user.image} />+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end" className="w-56">+ <div className="flex items-center gap-2.5 px-2 pt-1 pb-2">+ <MemberAvatar name={user.name} email={user.email} image={user.image} />+ <div className="min-w-0 flex-1">+ <div className="flex items-center gap-1.5">+ <p dir="auto" className="min-w-0 truncate text-[13px] font-medium text-foreground">+ {name}+ </p>+ {planLabel && (+ <Badge variant="outline" className="shrink-0 px-1.5 py-0 text-[10px] font-medium">+ {planLabel}+ </Badge>+ )}+ </div>+ {user.email && (+ <p className="truncate text-[11px] text-muted-foreground">+ <bdi dir="ltr">{user.email}</bdi>+ </p>+ )}+ </div>+ </div>+ <DropdownMenuSeparator />+ <DropdownMenuItem onSelect={() => onOpenSettings("account")} className={itemClass}>+ <UserCircle size={15} className={itemIconClass} />+ {t("settingsModal.sections.account.label")}+ </DropdownMenuItem>+ <DropdownMenuItem onSelect={() => onOpenSettings("plansBilling")} className={itemClass}>+ <CreditCard size={15} className={itemIconClass} />+ {t("settingsModal.sections.plansBilling.label")}+ </DropdownMenuItem>+ <DropdownMenuItem onSelect={onOpenReferrals} className={itemClass}>+ <Gift size={15} className={itemIconClass} />+ {t("sidebar.referral")}+ </DropdownMenuItem>+ <DropdownMenuSeparator />+ <DropdownMenuItem onSelect={onSignOut} className={itemClass}>+ <LogOut size={15} className={itemIconClass} />+ {t("settingsPage.account.signOut.signOut")}+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ );+}diff --git a/src/components/SettingsPage.tsx b/src/components/SettingsPage.tsxindex 117135c32..4ad67a88b 100644--- a/src/components/SettingsPage.tsx+++ b/src/components/SettingsPage.tsx@@ -64,6 +64,8 @@ import {import { Alert, AlertTitle, AlertDescription } from "./ui/alert";import { useSettings } from "../hooks/useSettings";import { useDialogs } from "../hooks/useDialogs";+import { useSignOut } from "../hooks/useSignOut";+import { useAccountPlan } from "../hooks/useAccountPlan";import { useInsightsSyncOptIn } from "../hooks/useInsightsSyncOptIn";import { useLeaderboardParticipation } from "../hooks/useLeaderboardParticipation";import { useWhisper } from "../hooks/useWhisper";@@ -137,8 +139,7 @@ import {type HotkeyRegistrationResult,} from "../stores/settingsStore";import { useWorkspaceStore } from "../stores/workspaceStore";-import { highestPlan } from "../lib/usageStore";-import { decideProPlanCardCta, resolveAccountPlan, storeSubscriptionsUrl } from "../lib/upsell";+import { decideProPlanCardCta, storeSubscriptionsUrl } from "../lib/upsell";import {canChangeCloudBackupPreference,effectiveAudioRetentionDays,@@ -151,7 +152,6 @@ import {} from "../stores/policyRules";import { usePolicyModeOptions, usePolicySnapshot } from "../hooks/usePolicy";import { usePolicyStore } from "../stores/policyStore";-import { stopRecording } from "../stores/meetingRecordingStore";import { requestSignIn } from "../utils/requestSignIn";import { canManageSystemAudioInApp } from "../utils/systemAudioAccess";import WorkspaceSection from "./settings/WorkspaceSection";@@ -1412,23 +1412,8 @@ export default function SettingsPage({const enterpriseCta: EnterpriseTileCta = billingWorkspacesLoaded? enterpriseTileCta(billingWorkspaces, activeWorkspaceId): { action: "contactSales", ownerName: null };- const coveringWorkspaces = billingWorkspaces.filter((workspace) =>- usage?.entitledWorkspaceIds?.includes(workspace.id)- );- const coveringWorkspaceNames = coveringWorkspaces.map((workspace) => workspace.name);- // Reads the usage payload, not the workspace store, so the upgrade affordances- // stay hidden across the window where the store is still loading.- const isWorkspaceCovered =- !usage?.isPersonallySubscribed && (usage?.entitledWorkspaceIds?.length ?? 0) > 0;- // Null until the store resolves, so the label waits rather than guessing a tier.- const coveringPlanLabel =- isWorkspaceCovered && coveringWorkspaces.length- ? t(- `settingsPage.workspace.billing.planLabel.${highestPlan(- coveringWorkspaces.map((workspace) => workspace.plan)- )}`- )- : null;+ const { accountPlan, isWorkspaceCovered, coveringWorkspaceNames, coveringPlanLabel, planLabel } =+ useAccountPlan(usage);const hasShownApproachingToast = useRef(false);useEffect(() => {if (usage?.isApproachingLimit && !hasShownApproachingToast.current) {@@ -1856,15 +1841,6 @@ export default function SettingsPage({isWorkspaceCovered,});const storeBilling = usage?.storeBilling ?? null;- const accountPlan = resolveAccountPlan({- isTrial: usage?.isTrial ?? false,- isPastDue: usage?.isPastDue ?? false,- isPersonallySubscribed: usage?.isPersonallySubscribed ?? false,- storeBilling,- isWorkspaceCovered,- hasPeriodEnd: Boolean(usage?.currentPeriodEnd),- hasCoveringWorkspaceNames: coveringWorkspaceNames.length > 0,- });const storeUrl = storeBilling?.store ? storeSubscriptionsUrl(storeBilling.store) : null;const periodEndDate = usage?.currentPeriodEnd? new Date(usage.currentPeriodEnd).toLocaleDateString(i18n.language, {@@ -1873,7 +1849,7 @@ export default function SettingsPage({year: "numeric",}): null;- const [isSigningOut, setIsSigningOut] = useState(false);+ const { requestSignOut, isSigningOut } = useSignOut({ showConfirmDialog, showAlertDialog });const [isDeletingAccount, setIsDeletingAccount] = useState(false);const [isDeleteAccountDialogOpen, setIsDeleteAccountDialogOpen] = useState(false);const [eraseDeviceData, setEraseDeviceData] = useState(false);@@ -1957,28 +1933,6 @@ export default function SettingsPage({[usage, toast, t]);- const handleSignOut = useCallback(async () => {- setIsSigningOut(true);- try {- // End a live meeting while its note is still in scope: signing out clears- // the account scope, and anything said after that could not be saved.- await stopRecording();- // Clear account-scoped renderer/session state before ending the session.- // Workspace-owned rows remain cached behind their membership boundary.- await syncService.purgeTeamSpacesForSignOut();- await signOut();- window.location.reload();- } catch (error) {- logger.error("Sign out failed", error, "auth");- showAlertDialog({- title: t("settingsPage.account.signOut.failedTitle"),- description: t("settingsPage.account.signOut.failedDescription"),- });- } finally {- setIsSigningOut(false);- }- }, [showAlertDialog, t]);-const handleDeleteAccount = useCallback(() => {setEraseDeviceData(false);setIsDeleteAccountDialogOpen(true);@@ -2211,7 +2165,7 @@ export default function SettingsPage({<div className="flex justify-end"><Button- onClick={handleSignOut}+ onClick={requestSignOut}variant="outline"disabled={isSigningOut}size="sm"@@ -2380,18 +2334,7 @@ export default function SettingsPage({<SettingsPanelRow><SettingsRow- label={- accountPlan.row === "trial"- ? t("settingsPage.account.planLabels.trial")- : accountPlan.row === "pastDue"- ? t("settingsPage.account.planLabels.free")- : accountPlan.row === "personal" || accountPlan.row === "store"- ? usage.plan === "business"- ? t("settingsPage.account.planLabels.business")- : t("settingsPage.account.planLabels.pro")- : (coveringPlanLabel ??- t("settingsPage.account.planLabels.free"))- }+ label={planLabel ?? t("settingsPage.account.planLabels.free")}description={accountPlan.description === "trial"? t("settingsPage.account.planDescriptions.trial", {diff --git a/src/components/WorkspaceSwitcher.tsx b/src/components/WorkspaceSwitcher.tsxnew file mode 100644index 000000000..d17dfbca1--- /dev/null+++ b/src/components/WorkspaceSwitcher.tsx@@ -0,0 +1,220 @@+import React, { Suspense, useRef, useState } from "react";+import { useShallow } from "zustand/react/shallow";+import { useTranslation } from "react-i18next";+import { Check, ChevronsUpDown, Loader2, Plus, UserCircle, UserPlus } from "./icons";+import MemberAvatar from "./MemberAvatar";+import CreateWorkspaceDialog from "./CreateWorkspaceDialog";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+} from "./ui/dropdown-menu";+import { cn } from "./lib/utils";+import { useAuth } from "../hooks/useAuth";+import { useWorkspace } from "../hooks/useWorkspace";+import { useWorkspaceStore } from "../stores/workspaceStore";+import { WorkspacesService } from "../services/WorkspacesService";+import { resolveWorkspaceSwitcher } from "../lib/workspaceSwitcher";+import type { Workspace } from "../types/electron";++const InviteTeammateDialog = React.lazy(() => import("./InviteTeammateDialog"));++const triggerClass =+ "group flex items-center gap-2.5 w-full h-10 px-2 rounded-md text-start outline-none hover:bg-foreground/4 dark:hover:bg-white/4 active:bg-foreground/6 data-[state=open]:bg-foreground/5 dark:data-[state=open]:bg-white/6 focus-visible:ring-1 focus-visible:ring-primary/30 transition-colors duration-150";+const nameClass = "flex-1 min-w-0 truncate text-sm font-medium text-foreground";+const itemClass = "gap-3 px-2 py-2 text-[13px] rounded-lg";+// Counting members fetches the whole roster, so each workspace's count is reused for a while.+const MEMBER_COUNT_TTL_MS = 5 * 60_000;++export default function WorkspaceSwitcher(): React.ReactElement | null {+ const { t } = useTranslation();+ const { isSignedIn } = useAuth();+ const { workspaces, setActive, refresh } = useWorkspace();+ const { activeWorkspaceId, loaded, loading, error } = useWorkspaceStore(+ useShallow((s) => ({+ activeWorkspaceId: s.activeWorkspaceId,+ loaded: s.loaded,+ loading: s.loading,+ error: s.error,+ }))+ );+ const [createOpen, setCreateOpen] = useState(false);+ // Right after creating a workspace the invite is optional, so it offers Skip.+ const [invite, setInvite] = useState<{ workspace: Workspace; afterCreate: boolean } | null>(null);+ const [memberCounts, setMemberCounts] = useState<Record<string, number>>({});+ const memberCountRequestedAt = useRef<Record<string, number>>({});++ const state = resolveWorkspaceSwitcher({+ isSignedIn: Boolean(isSignedIn),+ loaded,+ error,+ workspaces,+ activeWorkspaceId,+ });++ if (state.kind === "hidden") return null;++ if (state.kind === "loading") {+ return (+ <div className="flex items-center gap-2.5 h-10 px-2" aria-hidden="true">+ <span className="w-7 h-7 rounded-full bg-foreground/6 dark:bg-white/8 animate-pulse" />+ <span className="h-2.5 w-20 rounded bg-foreground/6 dark:bg-white/8 animate-pulse" />+ </div>+ );+ }++ if (state.kind === "error") {+ return (+ <button+ type="button"+ onClick={() => void refresh()}+ disabled={loading}+ className={cn(triggerClass, "h-auto min-h-10 py-1.5 disabled:opacity-60")}+ >+ {/* Stacked, so long translations wrap instead of truncating beside Retry. */}+ <span className="flex min-w-0 flex-1 flex-col items-start gap-0.5 text-xs leading-snug">+ <span className="text-muted-foreground">+ {t("settingsPage.workspace.loadError.title")}+ </span>+ {loading ? (+ <Loader2 size={12} className="animate-spin text-muted-foreground" />+ ) : (+ <span className="font-medium text-primary">+ {t("settingsPage.workspace.loadError.retry")}+ </span>+ )}+ </span>+ </button>+ );+ }++ const current = state.kind === "workspace" ? state.current : null;+ const currentMemberCount = current ? (memberCounts[current.id] ?? null) : null;++ const handleOpenChange = (open: boolean): void => {+ if (!open || !current) return;+ const workspaceId = current.id;+ const now = Date.now();+ if (now - (memberCountRequestedAt.current[workspaceId] ?? 0) < MEMBER_COUNT_TTL_MS) return;+ memberCountRequestedAt.current[workspaceId] = now;+ WorkspacesService.listMembers(workspaceId).then(+ (members) => setMemberCounts((counts) => ({ ...counts, [workspaceId]: members.length })),+ // The count is decoration; the menu works without it. Ask again on the next open.+ () => {+ delete memberCountRequestedAt.current[workspaceId];+ }+ );+ };++ return (+ <>+ <DropdownMenu modal={false} onOpenChange={handleOpenChange}>+ <DropdownMenuTrigger className={triggerClass}>+ {current ? (+ <MemberAvatar name={current.name} email={null} />+ ) : (+ <UserCircle size={24} className="w-7 shrink-0 text-foreground/50" />+ )}+ <span dir="auto" className={nameClass}>+ {current ? current.name : t("notes.spaces.personal")}+ </span>+ <ChevronsUpDown+ size={14}+ className="shrink-0 text-foreground/45 group-hover:text-foreground/70 transition-colors duration-150"+ />+ </DropdownMenuTrigger>+ <DropdownMenuContent+ side="top"+ align="start"+ sideOffset={8}+ // Wider than the sidebar, as in the design, so names and the invite button have room.+ className="max-h-[var(--radix-dropdown-menu-content-available-height)] w-60 overflow-y-auto"+ >+ {current && (+ <>+ <div className="flex items-center gap-3 px-2 pt-1.5 pb-2.5">+ <MemberAvatar name={current.name} email={null} />+ <div className="min-w-0">+ <p dir="auto" className="truncate text-sm font-medium text-foreground">+ {current.name}+ </p>+ {currentMemberCount !== null && (+ <p className="text-xs text-muted-foreground">+ {t("workspaces.join.memberCount", { count: currentMemberCount })}+ </p>+ )}+ </div>+ </div>+ {state.kind === "workspace" && state.canInvite && (+ <DropdownMenuItem+ onSelect={() => setInvite({ workspace: current, afterCreate: false })}+ className="mx-1 mb-1.5 justify-center gap-1.5 rounded-lg py-2 text-[13px] text-foreground/80 bg-foreground/5 dark:bg-white/6 focus:bg-foreground/8 dark:focus:bg-white/10"+ >+ <UserPlus size={14} />+ {t("workspaces.switcher.invitePeople")}+ </DropdownMenuItem>+ )}+ <DropdownMenuSeparator className="-mx-1.5 my-1.5" />+ </>+ )}+ {current ? (+ workspaces.map((workspace) => (+ <DropdownMenuItem+ key={workspace.id}+ onSelect={() => setActive(workspace.id)}+ className={itemClass}+ >+ <MemberAvatar name={workspace.name} email={null} />+ <span dir="auto" className="flex-1 min-w-0 truncate">+ {workspace.name}+ </span>+ {workspace.id === current.id && (+ <Check size={16} className="shrink-0 text-primary" />+ )}+ </DropdownMenuItem>+ ))+ ) : (+ <DropdownMenuItem className={itemClass} disabled>+ <UserCircle size={24} className="w-7 shrink-0 text-foreground/50" />+ <span className="flex-1">{t("notes.spaces.personal")}</span>+ <Check size={16} className="shrink-0 text-primary" />+ </DropdownMenuItem>+ )}+ <DropdownMenuItem+ onSelect={() => setCreateOpen(true)}+ className={cn(itemClass, "text-muted-foreground focus:text-foreground")}+ >+ <span className="flex w-7 shrink-0 justify-center">+ <Plus size={16} />+ </span>+ {t("workspaces.switcher.add")}+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>++ <CreateWorkspaceDialog+ open={createOpen}+ onOpenChange={setCreateOpen}+ onCreated={(workspaceId) => {+ const created = useWorkspaceStore.getState().workspaces.find((w) => w.id === workspaceId);+ if (created) setInvite({ workspace: created, afterCreate: true });+ }}+ />+ {invite && (+ <Suspense fallback={null}>+ <InviteTeammateDialog+ open+ onOpenChange={(open) => {+ if (!open) setInvite(null);+ }}+ workspaceId={invite.workspace.id}+ workspaceName={invite.workspace.name}+ cancelLabel={invite.afterCreate ? t("common.skip") : undefined}+ />+ </Suspense>+ )}+ </>+ );+}diff --git a/src/components/icons/index.ts b/src/components/icons/index.tsindex 57de21cc5..cafe29194 100644--- a/src/components/icons/index.ts+++ b/src/components/icons/index.ts@@ -5,6 +5,7 @@ import * as Nucleo from "./nucleo";export type { IconComponent, IconProps } from "./createIcon";export {Bold,+ ChevronsUpDown,Circle,CopyRounded,FolderRounded,diff --git a/src/components/icons/primitives.tsx b/src/components/icons/primitives.tsxindex a71e5bbe7..60ad50717 100644--- a/src/components/icons/primitives.tsx+++ b/src/components/icons/primitives.tsx@@ -186,6 +186,15 @@ const SquareSparkleMark = glyph(</>);+// The sidebar's workspace switcher.+const ChevronsUpDownMark = glyph(+ <>+ <path d="m7 15 5 5 5-5" />+ <path d="m7 9 5-5 5 5" />+ </>+);++export const ChevronsUpDown = createIcon("chevrons-up-down", ChevronsUpDownMark);export const Circle = createIcon("circle", CircleMark);export const Square = createIcon("square", SquareMark);export const SquareSlash = createIcon("square-slash", SquareSlashMark);diff --git a/src/hooks/useAccountPlan.ts b/src/hooks/useAccountPlan.tsnew file mode 100644index 000000000..a92c426f5--- /dev/null+++ b/src/hooks/useAccountPlan.ts@@ -0,0 +1,71 @@+import { useTranslation } from "react-i18next";+import { useWorkspaceStore } from "../stores/workspaceStore";+import { highestPlan } from "../lib/usageStore";+import { resolveAccountPlan } from "../lib/upsell";+import type { UseUsageResult } from "./useUsage";++interface AccountPlan {+ accountPlan: ReturnType<typeof resolveAccountPlan>;+ isWorkspaceCovered: boolean;+ coveringWorkspaceNames: string[];+ /** The covering workspaces' best plan; null until the workspace store resolves them. */+ coveringPlanLabel: string | null;+ /** The plan the account is on, as Settings → Plans & Billing names it; null until known. */+ planLabel: string | null;+}++export function useAccountPlan(usage: UseUsageResult | null): AccountPlan {+ const { t } = useTranslation();+ const workspaces = useWorkspaceStore((s) => s.workspaces);++ const coveringWorkspaces = workspaces.filter((workspace) =>+ usage?.entitledWorkspaceIds?.includes(workspace.id)+ );+ const coveringWorkspaceNames = coveringWorkspaces.map((workspace) => workspace.name);+ // Reads the usage payload, not the workspace store, so the upgrade affordances+ // stay hidden across the window where the store is still loading.+ const isWorkspaceCovered =+ !usage?.isPersonallySubscribed && (usage?.entitledWorkspaceIds?.length ?? 0) > 0;+ // Null until the store resolves, so the label waits rather than guessing a tier.+ const coveringPlanLabel =+ isWorkspaceCovered && coveringWorkspaces.length+ ? t(+ `settingsPage.workspace.billing.planLabel.${highestPlan(+ coveringWorkspaces.map((workspace) => workspace.plan)+ )}`+ )+ : null;++ const accountPlan = resolveAccountPlan({+ isTrial: usage?.isTrial ?? false,+ isPastDue: usage?.isPastDue ?? false,+ isPersonallySubscribed: usage?.isPersonallySubscribed ?? false,+ storeBilling: usage?.storeBilling ?? null,+ isWorkspaceCovered,+ hasPeriodEnd: Boolean(usage?.currentPeriodEnd),+ hasCoveringWorkspaceNames: coveringWorkspaceNames.length > 0,+ });++ const planLabel =+ usage?.status !== "success"+ ? null+ : accountPlan.row === "trial"+ ? t("settingsPage.account.planLabels.trial")+ : accountPlan.row === "pastDue"+ ? t("settingsPage.account.planLabels.free")+ : accountPlan.row === "personal" || accountPlan.row === "store"+ ? usage.plan === "business"+ ? t("settingsPage.account.planLabels.business")+ : t("settingsPage.account.planLabels.pro")+ : isWorkspaceCovered+ ? coveringPlanLabel+ : t("settingsPage.account.planLabels.free");++ return {+ accountPlan,+ isWorkspaceCovered,+ coveringWorkspaceNames,+ coveringPlanLabel,+ planLabel,+ };+}diff --git a/src/hooks/useSignOut.ts b/src/hooks/useSignOut.tsnew file mode 100644index 000000000..b340052dc--- /dev/null+++ b/src/hooks/useSignOut.ts@@ -0,0 +1,60 @@+import { useCallback, useState } from "react";+import { useTranslation } from "react-i18next";+import { signOut } from "../lib/auth";+import { syncService } from "../services/SyncService.js";+import { stopRecording, useMeetingRecordingStore } from "../stores/meetingRecordingStore";+import type { ConfirmDialogState, AlertDialogState } from "./useDialogs";+import logger from "../utils/logger";++interface SignOutDialogs {+ showConfirmDialog: (options: Omit<ConfirmDialogState, "open">) => void;+ showAlertDialog: (options: Omit<AlertDialogState, "open">) => void;+}++/** Sign out from anywhere in the control panel, asking first when it would end a meeting recording. */+export function useSignOut({ showConfirmDialog, showAlertDialog }: SignOutDialogs): {+ requestSignOut: () => void;+ isSigningOut: boolean;+} {+ const { t } = useTranslation();+ const [isSigningOut, setIsSigningOut] = useState(false);++ const performSignOut = useCallback(async () => {+ setIsSigningOut(true);+ try {+ // End a live meeting while its note is still in scope: signing out clears+ // the account scope, and anything said after that could not be saved.+ await stopRecording();+ // Clear account-scoped renderer/session state before ending the session.+ // Workspace-owned rows remain cached behind their membership boundary.+ await syncService.purgeTeamSpacesForSignOut();+ await signOut();+ window.location.reload();+ } catch (error) {+ logger.error("Sign out failed", error, "auth");+ showAlertDialog({+ title: t("settingsPage.account.signOut.failedTitle"),+ description: t("settingsPage.account.signOut.failedDescription"),+ });+ } finally {+ setIsSigningOut(false);+ }+ }, [showAlertDialog, t]);++ const requestSignOut = useCallback(() => {+ if (!useMeetingRecordingStore.getState().isRecording) {+ void performSignOut();+ return;+ }+ showConfirmDialog({+ title: t("settingsPage.account.signOut.endMeetingTitle"),+ description: t("settingsPage.account.signOut.endMeetingDescription"),+ confirmText: t("settingsPage.account.signOut.signOut"),+ cancelText: t("common.cancel"),+ variant: "destructive",+ onConfirm: () => void performSignOut(),+ });+ }, [performSignOut, showConfirmDialog, t]);++ return { requestSignOut, isSigningOut };+}diff --git a/src/hooks/useWorkspace.ts b/src/hooks/useWorkspace.tsindex 5b9fe0916..eef082e80 100644--- a/src/hooks/useWorkspace.ts+++ b/src/hooks/useWorkspace.ts@@ -3,6 +3,11 @@ import { useWorkspaceStore } from "../stores/workspaceStore";import { useAuth } from "./useAuth";import type { Workspace, WorkspaceRole } from "../types/electron";+// Focus fires on every switch back to the app, so a server that keeps failing would otherwise get+// a request each time. Shared by every mounted caller, which all listen.+const FOCUS_RETRY_INTERVAL_MS = 30_000;+let lastFocusRetryAt = 0;+interface UseWorkspaceResult {workspaces: Workspace[];active: Workspace | null;@@ -17,6 +22,7 @@ export function useWorkspace(): UseWorkspaceResult {const workspaces = useWorkspaceStore((s) => s.workspaces);const activeWorkspaceId = useWorkspaceStore((s) => s.activeWorkspaceId);const loaded = useWorkspaceStore((s) => s.loaded);+ const error = useWorkspaceStore((s) => s.error);const refresh = useWorkspaceStore((s) => s.refresh);const setActive = useWorkspaceStore((s) => s.setActiveWorkspaceId);@@ -26,6 +32,25 @@ export function useWorkspace(): UseWorkspaceResult {}}, [isSignedIn, loaded, refresh]);+ // A list that failed while offline would otherwise stay failed until the+ // user presses Retry. refresh() dedupes, so every mounted caller can listen.+ useEffect(() => {+ if (!isSignedIn || !error) return;+ const retry = (): void => void refresh();+ const retryOnFocus = (): void => {+ const now = Date.now();+ if (now - lastFocusRetryAt < FOCUS_RETRY_INTERVAL_MS) return;+ lastFocusRetryAt = now;+ retry();+ };+ window.addEventListener("online", retry);+ window.addEventListener("focus", retryOnFocus);+ return () => {+ window.removeEventListener("online", retry);+ window.removeEventListener("focus", retryOnFocus);+ };+ }, [isSignedIn, error, refresh]);+const active = activeWorkspaceId? (workspaces.find((w) => w.id === activeWorkspaceId) ?? null): null;diff --git a/src/lib/avatarInitials.ts b/src/lib/avatarInitials.tsnew file mode 100644index 000000000..014dc2921--- /dev/null+++ b/src/lib/avatarInitials.ts@@ -0,0 +1,11 @@+const firstCharacter = (text: string): string => Array.from(text)[0] ?? "";++/** First and last word's initials ("Chad Piha" → "CP"), else the email's first character. */+export function avatarInitials(name: string | null, email: string | null): string {+ const words = (name ?? "").trim().split(/\s+/).filter(Boolean);+ if (words.length > 0) {+ const last = words.length > 1 ? firstCharacter(words[words.length - 1]) : "";+ return (firstCharacter(words[0]) + last).toUpperCase();+ }+ return firstCharacter((email ?? "").trim()).toUpperCase() || "?";+}diff --git a/src/lib/workspaceSwitcher.ts b/src/lib/workspaceSwitcher.tsnew file mode 100644index 000000000..8b08eb5cf--- /dev/null+++ b/src/lib/workspaceSwitcher.ts@@ -0,0 +1,46 @@+import type { Workspace } from "../types/electron";+import { canManageWorkspace } from "./spacePermissions.ts";+import { isEnterpriseWorkspaceEntitled } from "../components/onboarding/flow.ts";++export type WorkspaceSwitcherState =+ | { kind: "hidden" }+ | { kind: "loading" }+ | { kind: "error" }+ | { kind: "personal" }+ | { kind: "workspace"; current: Workspace; canInvite: boolean };++interface WorkspaceSwitcherInput {+ isSignedIn: boolean;+ loaded: boolean;+ error: boolean;+ workspaces: Workspace[];+ activeWorkspaceId: string | null;+}++/**+ * The workspace to make active when none is chosen. An Enterprise workspace comes first, since its+ * managed providers apply only while it is active (onboarding picks it the same way).+ */+export function defaultActiveWorkspaceId(+ workspaces: Array<Pick<Workspace, "id" | "plan" | "status">>+): string | null {+ return (workspaces.find(isEnterpriseWorkspaceEntitled) ?? workspaces[0])?.id ?? null;+}++export function resolveWorkspaceSwitcher({+ isSignedIn,+ loaded,+ error,+ workspaces,+ activeWorkspaceId,+}: WorkspaceSwitcherInput): WorkspaceSwitcherState {+ if (!isSignedIn) return { kind: "hidden" };+ if (!loaded) return { kind: "loading" };+ if (workspaces.length === 0) {+ // Anyone in a workspace has one saved as active, so a failed load without one is a user who+ // had none last time: they stay Personal rather than seeing an error about workspaces.+ return error && activeWorkspaceId ? { kind: "error" } : { kind: "personal" };+ }+ const current = workspaces.find((w) => w.id === activeWorkspaceId) ?? workspaces[0];+ return { kind: "workspace", current, canInvite: canManageWorkspace(current.role) };+}diff --git a/src/locales/ar/translation.json b/src/locales/ar/translation.jsonindex 95ac2ce95..f4747cba9 100644--- a/src/locales/ar/translation.json+++ b/src/locales/ar/translation.json@@ -1298,7 +1298,9 @@"workspaces": {"switcher": {"workspaces": "مساحات العمل",- "create": "إنشاء مساحة عمل…"+ "create": "إنشاء مساحة عمل…",+ "add": "إضافة مساحة عمل",+ "invitePeople": "دعوة أشخاص"},"create": {"title": "إنشاء مساحة عمل",@@ -3406,6 +3408,8 @@},"rollingWeeklyLimit": "حد أسبوعي متجدد","signOut": {+ "endMeetingDescription": "يؤدي تسجيل الخروج إلى إيقاف تسجيل الاجتماع الجاري. يبقى ما تم تسجيله حتى الآن في ملاحظته.",+ "endMeetingTitle": "إنهاء تسجيل الاجتماع؟","failedDescription": "حدث خطأ أثناء تسجيل الخروج. يرجى المحاولة مرة أخرى.","failedTitle": "تعذر تسجيل الخروج","signOut": "تسجيل الخروج",@@ -4594,7 +4598,6 @@"upload": "رفع","dictionary": "القاموس","referral": "احصل على شهر مجاني",- "inviteTeam": "ادعُ فريقك","settings": "الإعدادات","support": "الدعم","limitReached": "تم بلوغ الحد السحابي الأسبوعي",@@ -4608,7 +4611,7 @@"learnMore": "معرفة المزيد","integrations": "التكاملات","defaultUser": "مستخدم",- "notSignedIn": "لم يتم تسجيل الدخول",+ "accountMenu": "الحساب: {{name}}","chat": "الدردشة","collapse": "طي الشريط الجانبي","expand": "توسيع الشريط الجانبي",diff --git a/src/locales/de/translation.json b/src/locales/de/translation.jsonindex 3e76f5dfb..a2e7af580 100644--- a/src/locales/de/translation.json+++ b/src/locales/de/translation.json@@ -2049,6 +2049,8 @@},"rollingWeeklyLimit": "Rollierendes Wochenlimit","signOut": {+ "endMeetingDescription": "Beim Abmelden wird die laufende Meeting-Aufnahme beendet. Was bisher aufgenommen wurde, bleibt in der Notiz.",+ "endMeetingTitle": "Meeting-Aufnahme beenden?","failedDescription": "Beim Abmelden ist ein Fehler aufgetreten. Bitte versuchen Sie es erneut.","failedTitle": "Abmeldung fehlgeschlagen","signOut": "Abmelden",@@ -3000,7 +3002,6 @@"upload": "Hochladen","dictionary": "Wörterbuch","referral": "Gratis-Monat erhalten",- "inviteTeam": "Team einladen","settings": "Einstellungen","support": "Support","limitReached": "Wöchentliches Cloud-Limit erreicht",@@ -3014,7 +3015,7 @@"learnMore": "Mehr erfahren","integrations": "Integrationen","defaultUser": "Benutzer",- "notSignedIn": "Nicht angemeldet",+ "accountMenu": "Konto: {{name}}","chat": "Chat","collapse": "Seitenleiste einklappen","expand": "Seitenleiste ausklappen"@@ -3022,7 +3023,9 @@"workspaces": {"switcher": {"workspaces": "Workspaces",- "create": "Workspace erstellen…"+ "create": "Workspace erstellen…",+ "add": "Workspace hinzufügen",+ "invitePeople": "Personen einladen"},"create": {"title": "Workspace erstellen",diff --git a/src/locales/en/translation.json b/src/locales/en/translation.jsonindex 14ba2d529..045ab7dd5 100644--- a/src/locales/en/translation.json+++ b/src/locales/en/translation.json@@ -2049,6 +2049,8 @@},"rollingWeeklyLimit": "Rolling weekly limit","signOut": {+ "endMeetingDescription": "Signing out stops the meeting that's recording. What it has captured so far stays in its note.",+ "endMeetingTitle": "End the meeting recording?","failedDescription": "Something went wrong signing out. Please try again.","failedTitle": "Couldn't sign out","signOut": "Sign Out",@@ -2874,7 +2876,6 @@"upload": "Upload","dictionary": "Dictionary","referral": "Get a free month",- "inviteTeam": "Invite your team","settings": "Settings","support": "Support","limitReached": "Weekly Cloud limit reached",@@ -2888,7 +2889,7 @@"learnMore": "Learn More","integrations": "Integrations","defaultUser": "User",- "notSignedIn": "Not signed in",+ "accountMenu": "Account: {{name}}","chat": "Chat","collapse": "Collapse sidebar","expand": "Expand sidebar"@@ -3022,7 +3023,9 @@"workspaces": {"switcher": {"workspaces": "Workspaces",- "create": "Create workspace…"+ "create": "Create workspace…",+ "add": "Add workspace",+ "invitePeople": "Invite people"},"create": {"title": "Create workspace",diff --git a/src/locales/es/translation.json b/src/locales/es/translation.jsonindex fc71400ed..1d57f8b65 100644--- a/src/locales/es/translation.json+++ b/src/locales/es/translation.json@@ -1807,6 +1807,8 @@},"rollingWeeklyLimit": "Límite semanal móvil","signOut": {+ "endMeetingDescription": "Al cerrar sesión se detiene la grabación de la reunión en curso. Lo capturado hasta ahora se queda en su nota.",+ "endMeetingTitle": "¿Detener la grabación de la reunión?","failedDescription": "Algo salió mal al cerrar sesión. Inténtalo de nuevo.","failedTitle": "No se pudo cerrar sesión","signOut": "Cerrar sesión",@@ -3744,7 +3746,6 @@"upload": "Subir","dictionary": "Diccionario","referral": "Obtener un mes gratis",- "inviteTeam": "Invita a tu equipo","settings": "Configuración","support": "Soporte","limitReached": "Límite semanal de la nube alcanzado",@@ -3758,7 +3759,7 @@"learnMore": "Más información","integrations": "Integraciones","defaultUser": "Usuario",- "notSignedIn": "Sin sesión iniciada",+ "accountMenu": "Cuenta: {{name}}","chat": "Chat","collapse": "Contraer barra lateral","expand": "Expandir barra lateral"@@ -4754,7 +4755,9 @@"workspaces": {"switcher": {"workspaces": "Espacios de trabajo",- "create": "Crear espacio de trabajo…"+ "create": "Crear espacio de trabajo…",+ "add": "Añadir espacio de trabajo",+ "invitePeople": "Invitar personas"},"create": {"title": "Crear espacio de trabajo",diff --git a/src/locales/fr/translation.json b/src/locales/fr/translation.jsonindex d637d8f96..d31dcdeef 100644--- a/src/locales/fr/translation.json+++ b/src/locales/fr/translation.json@@ -2049,6 +2049,8 @@},"rollingWeeklyLimit": "Limite hebdomadaire glissante","signOut": {+ "endMeetingDescription": "La déconnexion arrête l'enregistrement de la réunion en cours. Ce qui a déjà été capturé reste dans sa note.",+ "endMeetingTitle": "Arrêter l'enregistrement de la réunion ?","failedDescription": "Un problème est survenu lors de la déconnexion. Veuillez réessayer.","failedTitle": "Impossible de se déconnecter","signOut": "Se déconnecter",@@ -3000,7 +3002,6 @@"upload": "Importer","dictionary": "Dictionnaire","referral": "Obtenir un mois gratuit",- "inviteTeam": "Invitez votre équipe","settings": "Paramètres","support": "Assistance","limitReached": "Limite cloud hebdomadaire atteinte",@@ -3014,7 +3015,7 @@"learnMore": "En savoir plus","integrations": "Intégrations","defaultUser": "Utilisateur",- "notSignedIn": "Non connecté",+ "accountMenu": "Compte : {{name}}","chat": "Chat","collapse": "Réduire la barre latérale","expand": "Développer la barre latérale"@@ -3022,7 +3023,9 @@"workspaces": {"switcher": {"workspaces": "Espaces de travail",- "create": "Créer un espace de travail…"+ "create": "Créer un espace de travail…",+ "add": "Ajouter un espace de travail",+ "invitePeople": "Inviter des personnes"},"create": {"title": "Créer un espace de travail",diff --git a/src/locales/it/translation.json b/src/locales/it/translation.jsonindex 34606335a..8b937d9f3 100644--- a/src/locales/it/translation.json+++ b/src/locales/it/translation.json@@ -1659,6 +1659,8 @@},"rollingWeeklyLimit": "Limite settimanale progressivo","signOut": {+ "endMeetingDescription": "Uscendo dall'account si interrompe la registrazione della riunione in corso. Quanto registrato finora resta nella sua nota.",+ "endMeetingTitle": "Interrompere la registrazione della riunione?","failedDescription": "Qualcosa è andato storto durante la disconnessione. Riprova.","failedTitle": "Impossibile disconnettersi","signOut": "Disconnetti",@@ -3692,7 +3694,6 @@"upload": "Carica","dictionary": "Dizionario","referral": "Ottieni un mese gratis",- "inviteTeam": "Invita il tuo team","settings": "Impostazioni","support": "Assistenza","limitReached": "Limite cloud settimanale raggiunto",@@ -3706,7 +3707,7 @@"learnMore": "Scopri di più","integrations": "Integrazioni","defaultUser": "Utente",- "notSignedIn": "Non hai effettuato l'accesso",+ "accountMenu": "Account: {{name}}","chat": "Chat","collapse": "Comprimi barra laterale","expand": "Espandi barra laterale"@@ -4754,7 +4755,9 @@"workspaces": {"switcher": {"workspaces": "Aree di lavoro",- "create": "Crea area di lavoro…"+ "create": "Crea area di lavoro…",+ "add": "Aggiungi area di lavoro",+ "invitePeople": "Invita persone"},"create": {"title": "Crea area di lavoro",diff --git a/src/locales/ja/translation.json b/src/locales/ja/translation.jsonindex cd1f6254e..ae6abbc81 100644--- a/src/locales/ja/translation.json+++ b/src/locales/ja/translation.json@@ -1755,6 +1755,8 @@},"rollingWeeklyLimit": "週間利用上限(ローリング)","signOut": {+ "endMeetingDescription": "サインアウトすると、録音中の会議が終了します。それまでに記録された内容はノートに残ります。",+ "endMeetingTitle": "会議の録音を終了しますか?","failedDescription": "サインアウト中に問題が発生しました。もう一度お試しください。","failedTitle": "サインアウトできませんでした","signOut": "サインアウト",@@ -3692,7 +3694,6 @@"upload": "アップロード","dictionary": "辞書","referral": "1か月無料を取得",- "inviteTeam": "チームを招待","settings": "設定","support": "サポート","limitReached": "週間のクラウド上限に達しました",@@ -3706,7 +3707,7 @@"learnMore": "詳しく見る","integrations": "連携","defaultUser": "ユーザー",- "notSignedIn": "未サインイン",+ "accountMenu": "アカウント:{{name}}","chat": "チャット","collapse": "サイドバーを折りたたむ","expand": "サイドバーを展開"@@ -4754,7 +4755,9 @@"workspaces": {"switcher": {"workspaces": "ワークスペース",- "create": "ワークスペースを作成…"+ "create": "ワークスペースを作成…",+ "add": "ワークスペースを追加",+ "invitePeople": "メンバーを招待"},"create": {"title": "ワークスペースを作成",diff --git a/src/locales/pt/translation.json b/src/locales/pt/translation.jsonindex fa786c519..a2a8503d4 100644--- a/src/locales/pt/translation.json+++ b/src/locales/pt/translation.json@@ -1638,6 +1638,8 @@},"rollingWeeklyLimit": "Limite semanal contínuo","signOut": {+ "endMeetingDescription": "Sair da conta encerra a gravação da reunião em andamento. O que foi capturado até agora permanece na nota.",+ "endMeetingTitle": "Encerrar a gravação da reunião?","failedDescription": "Algo deu errado ao sair. Tente novamente.","failedTitle": "Não foi possível sair","signOut": "Sair",@@ -3692,7 +3694,6 @@"upload": "Enviar","dictionary": "Dicionário","referral": "Ganhe um mês grátis",- "inviteTeam": "Convide sua equipe","settings": "Configurações","support": "Suporte","limitReached": "Limite semanal da nuvem atingido",@@ -3706,7 +3707,7 @@"learnMore": "Saiba mais","integrations": "Integrações","defaultUser": "Usuário",- "notSignedIn": "Não conectado",+ "accountMenu": "Conta: {{name}}","chat": "Chat","collapse": "Recolher barra lateral","expand": "Expandir barra lateral"@@ -4754,7 +4755,9 @@"workspaces": {"switcher": {"workspaces": "Espaços de trabalho",- "create": "Criar espaço de trabalho…"+ "create": "Criar espaço de trabalho…",+ "add": "Adicionar espaço de trabalho",+ "invitePeople": "Convidar pessoas"},"create": {"title": "Criar espaço de trabalho",diff --git a/src/locales/ru/translation.json b/src/locales/ru/translation.jsonindex 42ee28894..ad8beb266 100644--- a/src/locales/ru/translation.json+++ b/src/locales/ru/translation.json@@ -1663,6 +1663,8 @@},"rollingWeeklyLimit": "Скользящий недельный лимит","signOut": {+ "endMeetingDescription": "При выходе из аккаунта запись текущей встречи остановится. Всё записанное до этого момента останется в её заметке.",+ "endMeetingTitle": "Остановить запись встречи?","failedDescription": "Произошла ошибка при выходе. Попробуйте ещё раз.","failedTitle": "Не удалось выйти","signOut": "Выйти",@@ -3736,7 +3738,6 @@"upload": "Загрузить","dictionary": "Словарь","referral": "Получить бесплатный месяц",- "inviteTeam": "Пригласите команду","settings": "Настройки","support": "Поддержка","limitReached": "Недельный облачный лимит достигнут",@@ -3750,7 +3751,7 @@"learnMore": "Узнать больше","integrations": "Интеграции","defaultUser": "Пользователь",- "notSignedIn": "Не авторизован",+ "accountMenu": "Аккаунт: {{name}}","chat": "Чат","collapse": "Свернуть боковую панель","expand": "Развернуть боковую панель"@@ -4798,7 +4799,9 @@"workspaces": {"switcher": {"workspaces": "Рабочие пространства",- "create": "Создать рабочее пространство…"+ "create": "Создать рабочее пространство…",+ "add": "Добавить рабочее пространство",+ "invitePeople": "Пригласить людей"},"create": {"title": "Создать рабочее пространство",diff --git a/src/locales/zh-CN/translation.json b/src/locales/zh-CN/translation.jsonindex 50e09a515..e6ac9da7c 100644--- a/src/locales/zh-CN/translation.json+++ b/src/locales/zh-CN/translation.json@@ -1659,6 +1659,8 @@},"rollingWeeklyLimit": "滚动周限额","signOut": {+ "endMeetingDescription": "退出登录会结束正在进行的会议录制。已录制的内容会保留在笔记中。",+ "endMeetingTitle": "结束会议录制?","failedDescription": "退出登录时出错,请重试。","failedTitle": "无法退出登录","signOut": "退出登录",@@ -3692,7 +3694,6 @@"upload": "上传","dictionary": "词典","referral": "获取免费一个月",- "inviteTeam": "邀请你的团队","settings": "设置","support": "支持","limitReached": "已达本周云端上限",@@ -3706,7 +3707,7 @@"learnMore": "了解更多","integrations": "集成","defaultUser": "用户",- "notSignedIn": "未登录",+ "accountMenu": "账户:{{name}}","chat": "聊天","collapse": "折叠侧边栏","expand": "展开侧边栏"@@ -4754,7 +4755,9 @@"workspaces": {"switcher": {"workspaces": "工作区",- "create": "创建工作区…"+ "create": "创建工作区…",+ "add": "添加工作区",+ "invitePeople": "邀请成员"},"create": {"title": "创建工作区",diff --git a/src/locales/zh-TW/translation.json b/src/locales/zh-TW/translation.jsonindex 07fba4d0b..c122c7d09 100644--- a/src/locales/zh-TW/translation.json+++ b/src/locales/zh-TW/translation.json@@ -1659,6 +1659,8 @@},"rollingWeeklyLimit": "滾動式每週額度","signOut": {+ "endMeetingDescription": "登出會結束正在進行的會議錄製。已錄製的內容會保留在筆記中。",+ "endMeetingTitle": "結束會議錄製?","failedDescription": "登出時發生錯誤。請再試一次。","failedTitle": "無法登出","signOut": "登出",@@ -3692,7 +3694,6 @@"upload": "上傳","dictionary": "字典","referral": "獲得一個月免費",- "inviteTeam": "邀請你的團隊","settings": "設定","support": "支援","limitReached": "已達本週雲端上限",@@ -3706,7 +3707,7 @@"learnMore": "瞭解更多","integrations": "整合","defaultUser": "使用者",- "notSignedIn": "尚未登入",+ "accountMenu": "帳戶:{{name}}","chat": "聊天","collapse": "收合側邊欄","expand": "展開側邊欄"@@ -4754,7 +4755,9 @@"workspaces": {"switcher": {"workspaces": "工作區",- "create": "建立工作區…"+ "create": "建立工作區…",+ "add": "新增工作區",+ "invitePeople": "邀請成員"},"create": {"title": "建立工作區",diff --git a/src/stores/workspaceStore.ts b/src/stores/workspaceStore.tsindex 67b482099..96b82e01f 100644--- a/src/stores/workspaceStore.ts+++ b/src/stores/workspaceStore.ts@@ -4,6 +4,7 @@ import { WorkspacesService } from "../services/WorkspacesService";import logger from "../utils/logger";import { usePolicyStore } from "./policyStore";import { useEnterpriseIdentityStore } from "./enterpriseIdentityStore";+import { defaultActiveWorkspaceId } from "../lib/workspaceSwitcher";interface WorkspaceState {workspaces: Workspace[];@@ -114,11 +115,7 @@ export const useWorkspaceStore = create<WorkspaceState>((set, get) => ({if (generation !== accountGeneration) return;const activeId = get().activeWorkspaceId;const stillValid = activeId && workspaces.some((w) => w.id === activeId);- const resolvedActiveId = stillValid- ? activeId- : workspaces.length === 1- ? workspaces[0].id- : null;+ const resolvedActiveId = stillValid ? activeId : defaultActiveWorkspaceId(workspaces);set({workspaces,loaded: true,diff --git a/test/components/profileMenu.test.js b/test/components/profileMenu.test.jsnew file mode 100644index 000000000..e32c03477--- /dev/null+++ b/test/components/profileMenu.test.js@@ -0,0 +1,100 @@+const test = require("node:test");+const assert = require("node:assert/strict");+const { createElement } = require("react");+const { renderToStaticMarkup } = require("react-dom/server");+const { createRendererServer, installBrowserGlobals } = require("../lib/rendererTestHarness");++async function loadProfileMenu(t) {+ t.after(() => {+ delete globalThis.__auth;+ delete globalThis.__menuItems;+ delete globalThis.__planLabel;+ });+ installBrowserGlobals(t);+ const vite = await createRendererServer(t, {+ cachePrefix: "openwhispr-profile-menu-",+ mockModules: {+ "/hooks/useAuth": "export const useAuth = () => globalThis.__auth;",+ "/hooks/useUsage": "export const useUsage = () => null;",+ "/hooks/useAccountPlan":+ "export const useAccountPlan = () => ({ planLabel: globalThis.__planLabel ?? null });",+ "/MemberAvatar": "export default function MemberAvatar() { return null; }",+ // Renders the menu open and records each item's handler under its text.+ "/ui/dropdown-menu": `+ import React from "react";+ const textOf = (node) =>+ typeof node === "string" ? node : Array.isArray(node) ? node.map(textOf).join("") : "";+ export const DropdownMenu = ({ children }) => children;+ export const DropdownMenuTrigger = ({ children, ...props }) =>+ React.createElement("button", props, children);+ export const DropdownMenuContent = ({ children }) => React.createElement("div", null, children);+ export const DropdownMenuSeparator = () => null;+ export const DropdownMenuItem = ({ children, onSelect }) => {+ globalThis.__menuItems.set(textOf(children), onSelect);+ return null;+ };+ `,+ },+ });+ const { default: ProfileMenu } = await vite.ssrLoadModule("/components/ProfileMenu.tsx");+ const opened = [];+ const render = (auth) => {+ globalThis.__auth = auth;+ globalThis.__menuItems = new Map();+ return renderToStaticMarkup(+ createElement(ProfileMenu, {+ onOpenSettings: (section) => opened.push(section),+ onOpenReferrals: () => opened.push("referrals"),+ onSignOut: () => opened.push("sign out"),+ })+ );+ };+ return { render, opened };+}++test("a session still loading shows neither Sign in nor an account", async (t) => {+ const { render } = await loadProfileMenu(t);++ const markup = render({ isLoaded: false, isSignedIn: false, user: null });++ assert.doesNotMatch(markup, /<button/);+});++test("signed out, the avatar offers Sign in", async (t) => {+ const { render } = await loadProfileMenu(t);++ const markup = render({ isLoaded: true, isSignedIn: false, user: null });++ assert.match(markup, /aria-label="common\.signIn"/);+});++const signedIn = {+ isLoaded: true,+ isSignedIn: true,+ user: { name: "Chad Piha", email: "[email protected]", image: null },+};++test("the menu holds the account's own actions, ending with Sign out", async (t) => {+ const { render, opened } = await loadProfileMenu(t);++ render(signedIn);+ const labels = [...globalThis.__menuItems.keys()];+ for (const label of labels) globalThis.__menuItems.get(label)();++ assert.deepEqual(labels, [+ "settingsModal.sections.account.label",+ "settingsModal.sections.plansBilling.label",+ "sidebar.referral",+ "settingsPage.account.signOut.signOut",+ ]);+ assert.deepEqual(opened, ["account", "plansBilling", "referrals", "sign out"]);+});++test("the header names the plan once it is known", async (t) => {+ const { render } = await loadProfileMenu(t);++ assert.doesNotMatch(render(signedIn), />Pro</);++ globalThis.__planLabel = "Pro";+ assert.match(render(signedIn), />Pro</);+});diff --git a/test/components/signOutEndsMeetingRecording.test.js b/test/components/signOutEndsMeetingRecording.test.jsindex 19daf6ba5..d8ab33fe7 100644--- a/test/components/signOutEndsMeetingRecording.test.js+++ b/test/components/signOutEndsMeetingRecording.test.js@@ -7,7 +7,7 @@ const ts = require("typescript");// Signing out clears main's account scope the moment the token is cleared, so// a live meeting's note is out of reach from then on: neither its later saves-// nor the reload's beforeunload flush can write it. Settings' Sign out and the+// nor the reload's beforeunload flush can write it. Sign out (useSignOut) and the// invitation's account switch end the meeting first, and the stop writes the// final transcript. (Account deletion deletes the note, so it has nothing to save.)// Exercise the actual callbacks without loading their components.@@ -69,18 +69,45 @@ function createContext(calls) {};}-test("Settings sign-out ends a live meeting before the account scope is cleared", async () => {+test("sign-out ends a live meeting before the account scope is cleared", async () => {const calls = [];- const handleSignOut = vm.runInNewContext(- `${extractFunction("../../src/components/SettingsPage.tsx", "handleSignOut")}\nhandleSignOut;`,+ const performSignOut = vm.runInNewContext(+ `${extractFunction("../../src/hooks/useSignOut.ts", "performSignOut")}\nperformSignOut;`,createContext(calls));- await handleSignOut();+ await performSignOut();assert.deepEqual(calls, ["meeting stopped", "team spaces purged", "signed out", "reloaded"]);});+test("sign-out asks first only when it would end a meeting recording", () => {+ const requestSignOutWhile = (isRecording) => {+ const calls = [];+ const requestSignOut = vm.runInNewContext(+ `${extractFunction("../../src/hooks/useSignOut.ts", "requestSignOut")}\nrequestSignOut;`,+ {+ useMeetingRecordingStore: { getState: () => ({ isRecording }) },+ performSignOut: async () => calls.push("signed out"),+ showConfirmDialog: (options) => {+ assert.equal(options.cancelText, "Abbrechen");+ calls.push(`asked: ${options.title}`);+ options.onConfirm();+ },+ t: (key) => (key === "common.cancel" ? "Abbrechen" : key),+ }+ );+ requestSignOut();+ return calls;+ };++ assert.deepEqual(requestSignOutWhile(false), ["signed out"]);+ assert.deepEqual(requestSignOutWhile(true), [+ "asked: settingsPage.account.signOut.endMeetingTitle",+ "signed out",+ ]);+});+test("switching account from an invitation ends a live meeting before signing out", async () => {const calls = [];const handleSwitchAccount = vm.runInNewContext(diff --git a/test/hooks/useAccountPlan.test.js b/test/hooks/useAccountPlan.test.jsnew file mode 100644index 000000000..6cbf1ddd7--- /dev/null+++ b/test/hooks/useAccountPlan.test.js@@ -0,0 +1,61 @@+const assert = require("node:assert/strict");+const test = require("node:test");+const { createElement } = require("react");+const { renderToStaticMarkup } = require("react-dom/server");+const { createRendererServer, installBrowserGlobals } = require("../lib/rendererTestHarness");++const usage = (overrides = {}) => ({+ status: "success",+ plan: "free",+ isTrial: false,+ isPastDue: false,+ isPersonallySubscribed: false,+ storeBilling: null,+ currentPeriodEnd: null,+ entitledWorkspaceIds: [],+ ...overrides,+});++test("the account's plan label matches Settings → Plans & Billing", async (t) => {+ t.after(() => delete globalThis.__workspaces);+ installBrowserGlobals(t);+ const vite = await createRendererServer(t, {+ cachePrefix: "openwhispr-use-account-plan-",+ mockModules: {+ "/stores/workspaceStore": `+ export const useWorkspaceStore = (selector) =>+ selector({ workspaces: globalThis.__workspaces ?? [] });+ `,+ },+ });+ const { useAccountPlan } = await vite.ssrLoadModule("/hooks/useAccountPlan.ts");+ const labelFor = (usageResult, workspaces = []) => {+ globalThis.__workspaces = workspaces;+ let label;+ function Probe() {+ label = useAccountPlan(usageResult).planLabel;+ return null;+ }+ renderToStaticMarkup(createElement(Probe));+ return label;+ };+ const acme = { id: "acme", name: "Acme", plan: "business" };++ assert.equal(labelFor(null), null);+ assert.equal(labelFor(usage({ status: "loading" })), null);+ assert.equal(labelFor(usage()), "settingsPage.account.planLabels.free");+ assert.equal(labelFor(usage({ isTrial: true })), "settingsPage.account.planLabels.trial");+ assert.equal(labelFor(usage({ isPastDue: true })), "settingsPage.account.planLabels.free");+ assert.equal(+ labelFor(usage({ isPersonallySubscribed: true, plan: "pro" })),+ "settingsPage.account.planLabels.pro"+ );+ assert.equal(+ labelFor(usage({ isPersonallySubscribed: true, plan: "business" })),+ "settingsPage.account.planLabels.business"+ );+ // A workspace seat names the workspace's plan, and waits until the workspace list arrives.+ const covered = usage({ entitledWorkspaceIds: ["acme"] });+ assert.equal(labelFor(covered, [acme]), "settingsPage.workspace.billing.planLabel.business");+ assert.equal(labelFor(covered, []), null);+});diff --git a/test/hooks/useWorkspaceReconnect.test.js b/test/hooks/useWorkspaceReconnect.test.jsnew file mode 100644index 000000000..b3eea83f8--- /dev/null+++ b/test/hooks/useWorkspaceReconnect.test.js@@ -0,0 +1,103 @@+const assert = require("node:assert/strict");+const test = require("node:test");+const React = require("react");+const { createRoot } = require("react-dom/client");+const {+ createRendererServer,+ installBrowserGlobals,+ installHookDom,+} = require("../lib/rendererTestHarness");++// A window whose listeners can be fired, so the test can play "back online".+function listeningWindow() {+ const listeners = new Map();+ return {+ addEventListener(type, listener) {+ if (!listeners.has(type)) listeners.set(type, new Set());+ listeners.get(type).add(listener);+ },+ removeEventListener(type, listener) {+ listeners.get(type)?.delete(listener);+ },+ fire(type) {+ for (const listener of [...(listeners.get(type) ?? [])]) listener();+ },+ count(type) {+ return listeners.get(type)?.size ?? 0;+ },+ };+}++test("a workspace list that failed to load retries when the app reconnects", async (t) => {+ let root = null;+ t.after(async () => {+ if (root) await React.act(async () => root.unmount());+ delete globalThis.__state;+ });++ const events = listeningWindow();+ installBrowserGlobals(t, {+ window: {+ addEventListener: events.addEventListener,+ removeEventListener: events.removeEventListener,+ },+ });+ const container = installHookDom(t);++ const vite = await createRendererServer(t, {+ cachePrefix: "openwhispr-use-workspace-reconnect-",+ mockModules: {+ "/useAuth": "export const useAuth = () => ({ isSignedIn: globalThis.__state.isSignedIn });",+ "/stores/workspaceStore": `+ export const useWorkspaceStore = (selector) => selector(globalThis.__state.store);+ `,+ },+ });+ const { useWorkspace } = await vite.ssrLoadModule("/hooks/useWorkspace.ts");++ function Harness() {+ useWorkspace();+ return null;+ }++ let refreshes = 0;+ const store = {+ workspaces: [],+ activeWorkspaceId: null,+ loaded: true,+ error: true,+ refresh: async () => {+ refreshes += 1;+ },+ setActiveWorkspaceId: () => {},+ };+ const render = async (state) => {+ globalThis.__state = { isSignedIn: true, ...state, store: { ...store, ...state.store } };+ await React.act(async () => {+ root.render(React.createElement(Harness));+ });+ };++ root = createRoot(container);++ await render({});+ events.fire("online");+ events.fire("focus");+ assert.equal(refreshes, 2);++ // Switching windows again soon after doesn't send another request; coming online does.+ events.fire("focus");+ assert.equal(refreshes, 2);+ events.fire("online");+ assert.equal(refreshes, 3);++ // A loaded list stops listening.+ await render({ store: { error: false } });+ assert.equal(events.count("online"), 0);+ assert.equal(events.count("focus"), 0);++ // Signed out, a stale error never triggers a request.+ await render({ isSignedIn: false });+ events.fire("online");+ assert.equal(refreshes, 3);+});diff --git a/test/lib/avatarInitials.test.js b/test/lib/avatarInitials.test.jsnew file mode 100644index 000000000..f89db9dd2--- /dev/null+++ b/test/lib/avatarInitials.test.js@@ -0,0 +1,27 @@+const assert = require("node:assert/strict");+const test = require("node:test");++const load = () => import("../../src/lib/avatarInitials.ts");++test("avatars show the first and last word's initials", async () => {+ const { avatarInitials } = await load();++ assert.equal(avatarInitials("Chad Piha", null), "CP");+ assert.equal(avatarInitials(" ada lovelace byron ", null), "AB");+ assert.equal(avatarInitials("Acme", null), "A");+ assert.equal(avatarInitials("Émile Zola", null), "ÉZ");+});++test("without a name the email's first character stands in", async () => {+ const { avatarInitials } = await load();++ assert.equal(avatarInitials(null, "[email protected]"), "C");+ assert.equal(avatarInitials(" ", "[email protected]"), "C");+ assert.equal(avatarInitials(null, null), "?");+});++test("a character outside the BMP is never split in half", async () => {+ const { avatarInitials } = await load();++ assert.equal(avatarInitials("𝒜da Lovelace", null), "𝒜L");+});diff --git a/test/lib/workspaceSwitcher.test.js b/test/lib/workspaceSwitcher.test.jsnew file mode 100644index 000000000..ae9564760--- /dev/null+++ b/test/lib/workspaceSwitcher.test.js@@ -0,0 +1,109 @@+const assert = require("node:assert/strict");+const test = require("node:test");++const load = () => import("../../src/lib/workspaceSwitcher.ts");++const workspace = (id, role = "member") => ({ id, name: id, role });++const base = {+ isSignedIn: true,+ loaded: true,+ error: false,+ workspaces: [],+ activeWorkspaceId: null,+};++test("signed-out users get no switcher", async () => {+ const { resolveWorkspaceSwitcher } = await load();++ assert.deepEqual(resolveWorkspaceSwitcher({ ...base, isSignedIn: false }), { kind: "hidden" });+});++test("a list that hasn't arrived yet shows a placeholder", async () => {+ const { resolveWorkspaceSwitcher } = await load();++ assert.deepEqual(resolveWorkspaceSwitcher({ ...base, loaded: false }), { kind: "loading" });+});++test("a failed load is not mistaken for having no workspace", async () => {+ const { resolveWorkspaceSwitcher } = await load();++ assert.deepEqual(resolveWorkspaceSwitcher({ ...base, error: true, activeWorkspaceId: "acme" }), {+ kind: "error",+ });+});++test("offline, a user who had no workspace stays personal instead of seeing an error", async () => {+ const { resolveWorkspaceSwitcher } = await load();++ assert.deepEqual(resolveWorkspaceSwitcher({ ...base, error: true }), { kind: "personal" });+});++test("a cached list survives a failed refresh", async () => {+ const { resolveWorkspaceSwitcher } = await load();+ const acme = workspace("acme");++ assert.equal(+ resolveWorkspaceSwitcher({ ...base, error: true, workspaces: [acme] }).kind,+ "workspace"+ );+});++test("users in no workspace stay personal", async () => {+ const { resolveWorkspaceSwitcher } = await load();++ assert.deepEqual(resolveWorkspaceSwitcher(base), { kind: "personal" });+});++test("the active workspace is current", async () => {+ const { resolveWorkspaceSwitcher } = await load();+ const acme = workspace("acme");+ const beta = workspace("beta");++ const state = resolveWorkspaceSwitcher({+ ...base,+ workspaces: [acme, beta],+ activeWorkspaceId: "beta",+ });++ assert.equal(state.kind, "workspace");+ assert.equal(state.current, beta);+});++test("with no active workspace the first one is current, as in Settings", async () => {+ const { resolveWorkspaceSwitcher } = await load();+ const acme = workspace("acme");++ const state = resolveWorkspaceSwitcher({+ ...base,+ workspaces: [acme, workspace("beta")],+ activeWorkspaceId: "gone",+ });++ assert.equal(state.current, acme);+});++test("only owners and admins of the current workspace can invite from it", async () => {+ const { resolveWorkspaceSwitcher } = await load();+ const stateFor = (role) =>+ resolveWorkspaceSwitcher({+ ...base,+ workspaces: [workspace("acme", role)],+ activeWorkspaceId: "acme",+ });++ assert.equal(stateFor("owner").canInvite, true);+ assert.equal(stateFor("admin").canInvite, true);+ assert.equal(stateFor("member").canInvite, false);+});++test("with none chosen, an entitled Enterprise workspace becomes active, else the first", async () => {+ const { defaultActiveWorkspaceId } = await load();+ const pro = { id: "beta", plan: "pro", status: "active" };+ const enterprise = (status) => ({ id: "acme", plan: "enterprise", status });++ assert.equal(defaultActiveWorkspaceId([pro, enterprise("active")]), "acme");+ assert.equal(defaultActiveWorkspaceId([pro, enterprise("trialing")]), "acme");+ assert.equal(defaultActiveWorkspaceId([pro, enterprise("canceled")]), "beta");+ assert.equal(defaultActiveWorkspaceId([]), null);+});diff --git a/test/stores/workspaceStore.test.js b/test/stores/workspaceStore.test.jsnew file mode 100644index 000000000..ec04c5ce9--- /dev/null+++ b/test/stores/workspaceStore.test.js@@ -0,0 +1,61 @@+const test = require("node:test");+const assert = require("node:assert/strict");+const { createRendererServer, installBrowserGlobals } = require("../lib/rendererTestHarness");++for (const { name, saved, expected } of [+ {+ name: "refresh selects and persists Enterprise first when no workspace is saved",+ saved: null,+ expected: "enterprise",+ },+ {+ name: "refresh replaces a missing saved workspace with Enterprise and persists it",+ saved: "missing",+ expected: "enterprise",+ },+ {+ name: "refresh preserves a valid saved workspace even when Enterprise is available",+ saved: "business",+ expected: "business",+ },+]) {+ test(name, async (t) => {+ const { storage } = installBrowserGlobals(t, {+ initialStorage: saved ? { activeWorkspaceId: saved } : {},+ });+ const vite = await createRendererServer(t, {+ cachePrefix: "openwhispr-workspace-store-",+ mockModules: {+ "/services/WorkspacesService": `+ export const WorkspacesService = {+ list: async () => [+ { id: "business", plan: "business", status: "active" },+ { id: "enterprise", plan: "enterprise", status: "active" },+ ],+ };+ `,+ "/policyStore": `+ export const usePolicyStore = {+ getState: () => ({ accountId: null, authGeneration: null }),+ };+ `,+ "/enterpriseIdentityStore": `+ export const useEnterpriseIdentityStore = { getState: () => ({ clear() {} }) };+ `,+ },+ });+ const { useWorkspaceStore, ACTIVE_WORKSPACE_KEY } = await vite.ssrLoadModule(+ "/stores/workspaceStore.ts"+ );++ assert.equal(useWorkspaceStore.getState().activeWorkspaceId, saved);+ await useWorkspaceStore.getState().refresh();++ assert.deepEqual(+ useWorkspaceStore.getState().workspaces.map((workspace) => workspace.id),+ ["business", "enterprise"]+ );+ assert.equal(useWorkspaceStore.getState().activeWorkspaceId, expected);+ assert.equal(storage.getItem(ACTIVE_WORKSPACE_KEY), expected);+ });+}