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): add workspace switcher, invite dialog, and settings sub-tabs
Gabriel Steina60c0707a7ae
diff --git a/src/components/AcceptInvitationModal.tsx b/src/components/AcceptInvitationModal.tsxnew file mode 100644index 000000000..ea19ab201--- /dev/null+++ b/src/components/AcceptInvitationModal.tsx@@ -0,0 +1,128 @@+import React, { useEffect, useState } from "react";+import { useTranslation } from "react-i18next";+import {+ Dialog,+ DialogContent,+ DialogHeader,+ DialogTitle,+ DialogDescription,+ DialogFooter,+} from "./ui/dialog";+import { Button } from "./ui/button";+import { InvitationsService } from "../services/InvitationsService";+import { useWorkspaceStore } from "../stores/workspaceStore";+import { useToast } from "./ui/useToast";+import type { InvitationPreview } from "../types/electron";++interface Props {+ token: string | null;+ onClose: () => void;+ isSignedIn: boolean;+ onSignIn: () => void;+}++const STORAGE_KEY = "pendingInvitationToken";++export default function AcceptInvitationModal({ token, onClose, isSignedIn, onSignIn }: Props) {+ const { t } = useTranslation();+ const { toast } = useToast();+ const refresh = useWorkspaceStore((s) => s.refresh);+ const setActive = useWorkspaceStore((s) => s.setActiveWorkspaceId);+ const [preview, setPreview] = useState<InvitationPreview | null>(null);+ const [loading, setLoading] = useState(false);+ const [accepting, setAccepting] = useState(false);+ const [error, setError] = useState<string | null>(null);++ useEffect(() => {+ if (!token) {+ setPreview(null);+ setError(null);+ return;+ }+ setLoading(true);+ InvitationsService.preview(token)+ .then(setPreview)+ .catch((err) => setError(err instanceof Error ? err.message : t("common.unknownError")))+ .finally(() => setLoading(false));+ }, [token, t]);++ async function handleAccept() {+ if (!token) return;+ if (!isSignedIn) {+ localStorage.setItem(STORAGE_KEY, token);+ onSignIn();+ return;+ }+ setAccepting(true);+ try {+ const result = await InvitationsService.accept(token);+ localStorage.removeItem(STORAGE_KEY);+ await refresh();+ setActive(result.workspace_id);+ toast({+ title: t("workspaces.accept.successTitle"),+ description: preview ? t("workspaces.accept.successDescription", { name: preview.workspace_name }) : undefined,+ });+ onClose();+ } catch (err) {+ toast({+ title: t("workspaces.accept.errorTitle"),+ description: err instanceof Error ? err.message : t("common.unknownError"),+ variant: "destructive",+ });+ } finally {+ setAccepting(false);+ }+ }++ function handleDecline() {+ if (token) localStorage.removeItem(STORAGE_KEY);+ onClose();+ }++ return (+ <Dialog open={!!token} onOpenChange={(open) => !open && handleDecline()}>+ <DialogContent className="max-w-md">+ <DialogHeader>+ <DialogTitle>{t("workspaces.accept.title")}</DialogTitle>+ {preview && (+ <DialogDescription>+ {t("workspaces.accept.description", {+ inviter: preview.inviter_name || preview.inviter_email || "",+ workspace: preview.workspace_name,+ role: preview.workspace_role,+ })}+ </DialogDescription>+ )}+ {error && <DialogDescription className="text-destructive">{error}</DialogDescription>}+ {loading && (+ <DialogDescription>{t("workspaces.accept.loading")}</DialogDescription>+ )}+ </DialogHeader>+ <DialogFooter>+ <Button variant="ghost" onClick={handleDecline} disabled={accepting}>+ {t("common.cancel")}+ </Button>+ <Button onClick={handleAccept} disabled={!preview || accepting || !!error}>+ {accepting+ ? t("workspaces.accept.accepting")+ : isSignedIn+ ? t("workspaces.accept.accept")+ : t("workspaces.accept.signInToAccept")}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ );+}++export function consumePendingInvitationToken(): string | null {+ if (typeof window === "undefined") return null;+ const token = localStorage.getItem(STORAGE_KEY);+ return token;+}++export function clearPendingInvitationToken(): void {+ if (typeof window === "undefined") return;+ localStorage.removeItem(STORAGE_KEY);+}diff --git a/src/components/ControlPanelSidebar.tsx b/src/components/ControlPanelSidebar.tsxindex f8e6bc5fa..a3bca5e0d 100644--- a/src/components/ControlPanelSidebar.tsx+++ b/src/components/ControlPanelSidebar.tsx@@ -10,6 +10,7 @@ import {Settings,HelpCircle,UserCircle,+ UserPlus,X,Search,} from "lucide-react";@@ -18,6 +19,10 @@ import { useTranslation } from "react-i18next";import { cn } from "./lib/utils";import SupportDropdown from "./ui/SupportDropdown";import { getCachedPlatform } from "../utils/platform";+import WorkspaceSwitcher from "./WorkspaceSwitcher";+import InviteTeammateDialog from "./InviteTeammateDialog";+import CreateWorkspaceDialog from "./CreateWorkspaceDialog";+import { useWorkspace } from "../hooks/useWorkspace";const platform = getCachedPlatform();@@ -68,6 +73,9 @@ export default function ControlPanelSidebar({const [upgradeDismissed, setUpgradeDismissed] = useState(() => localStorage.getItem("upgradeProDismissed") === "true");+ const [inviteOpen, setInviteOpen] = useState(false);+ const [createWorkspaceOpen, setCreateWorkspaceOpen] = useState(false);+ const { active: activeWorkspace } = useWorkspace();const showLimitBanner = authLoaded && isSignedIn && !isProUser && isOverLimit;const showUpgradeBanner =@@ -97,6 +105,12 @@ export default function ControlPanelSidebar({style={{ WebkitAppRegion: "drag" } as React.CSSProperties}/>+ {isSignedIn && (+ <div className="px-2 pt-1 pb-1">+ <WorkspaceSwitcher userName={userName} />+ </div>+ )}+{onOpenSearch && (<div className="px-2 pt-2 pb-1"><button@@ -239,6 +253,26 @@ export default function ControlPanelSidebar({</button>)}+ {isSignedIn && (+ <button+ onClick={() =>+ activeWorkspace ? setInviteOpen(true) : setCreateWorkspaceOpen(true)+ }+ aria-label={+ activeWorkspace ? t("sidebar.inviteTeammate") : t("sidebar.createWorkspace")+ }+ className="group flex items-center gap-2.5 w-full h-8 px-2.5 rounded-md text-left outline-none hover:bg-foreground/4 dark:hover:bg-white/4 focus-visible:ring-1 focus-visible:ring-primary/30 transition-colors duration-150"+ >+ <UserPlus+ size={15}+ className="shrink-0 text-foreground/60 group-hover:text-foreground/75 dark:text-foreground/50 dark:group-hover:text-foreground/65 transition-colors duration-150"+ />+ <span className="text-xs text-foreground/80 group-hover:text-foreground dark:text-foreground/70 dark:group-hover:text-foreground/85 transition-colors duration-150">+ {activeWorkspace ? t("sidebar.inviteTeammate") : t("sidebar.createWorkspace")}+ </span>+ </button>+ )}+<buttononClick={onOpenSettings}aria-label={t("sidebar.settings")}@@ -298,6 +332,16 @@ export default function ControlPanelSidebar({</div></div></div>++ {activeWorkspace && (+ <InviteTeammateDialog+ open={inviteOpen}+ onOpenChange={setInviteOpen}+ workspaceId={activeWorkspace.id}+ workspaceName={activeWorkspace.name}+ />+ )}+ <CreateWorkspaceDialog open={createWorkspaceOpen} onOpenChange={setCreateWorkspaceOpen} /></div>);}diff --git a/src/components/CreateWorkspaceDialog.tsx b/src/components/CreateWorkspaceDialog.tsxnew file mode 100644index 000000000..056062170--- /dev/null+++ b/src/components/CreateWorkspaceDialog.tsx@@ -0,0 +1,94 @@+import React, { useState } from "react";+import { useTranslation } from "react-i18next";+import {+ Dialog,+ DialogContent,+ DialogHeader,+ DialogTitle,+ DialogDescription,+ DialogFooter,+} from "./ui/dialog";+import { Button } from "./ui/button";+import { Input } from "./ui/input";+import { Label } from "./ui/label";+import { useWorkspaceStore } from "../stores/workspaceStore";+import { useToast } from "./ui/useToast";++interface Props {+ open: boolean;+ onOpenChange: (open: boolean) => void;+ onCreated?: (workspaceId: string) => void;+}++export default function CreateWorkspaceDialog({ open, onOpenChange, onCreated }: Props) {+ const { t } = useTranslation();+ const { toast } = useToast();+ const createWorkspace = useWorkspaceStore((s) => s.createWorkspace);+ const setActive = useWorkspaceStore((s) => s.setActiveWorkspaceId);+ const [name, setName] = useState("");+ const [submitting, setSubmitting] = useState(false);++ async function handleSubmit(e: React.FormEvent) {+ e.preventDefault();+ if (!name.trim()) return;+ setSubmitting(true);+ try {+ const workspace = await createWorkspace(name.trim());+ setActive(workspace.id);+ onCreated?.(workspace.id);+ onOpenChange(false);+ setName("");+ toast({+ title: t("workspaces.created.title"),+ description: t("workspaces.created.description", { name: workspace.name }),+ });+ } catch (error) {+ toast({+ title: t("workspaces.create.errorTitle"),+ description: error instanceof Error ? error.message : t("common.unknownError"),+ variant: "destructive",+ });+ } finally {+ setSubmitting(false);+ }+ }++ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent className="max-w-md">+ <DialogHeader>+ <DialogTitle>{t("workspaces.create.title")}</DialogTitle>+ <DialogDescription>{t("workspaces.create.description")}</DialogDescription>+ </DialogHeader>+ <form onSubmit={handleSubmit} className="space-y-3">+ <div className="space-y-1.5">+ <Label htmlFor="workspace-name" className="text-xs font-medium">+ {t("workspaces.create.nameLabel")}+ </Label>+ <Input+ id="workspace-name"+ autoFocus+ value={name}+ onChange={(e) => setName(e.target.value)}+ placeholder={t("workspaces.create.namePlaceholder")}+ maxLength={80}+ />+ </div>+ <DialogFooter className="pt-2">+ <Button+ type="button"+ variant="ghost"+ onClick={() => onOpenChange(false)}+ disabled={submitting}+ >+ {t("common.cancel")}+ </Button>+ <Button type="submit" disabled={!name.trim() || submitting}>+ {submitting ? t("workspaces.create.submitting") : t("workspaces.create.submit")}+ </Button>+ </DialogFooter>+ </form>+ </DialogContent>+ </Dialog>+ );+}diff --git a/src/components/InviteTeammateDialog.tsx b/src/components/InviteTeammateDialog.tsxnew file mode 100644index 000000000..8e18b5faf--- /dev/null+++ b/src/components/InviteTeammateDialog.tsx@@ -0,0 +1,188 @@+import React, { useEffect, useState } from "react";+import { useTranslation } from "react-i18next";+import {+ Dialog,+ DialogContent,+ DialogHeader,+ DialogTitle,+ DialogDescription,+ DialogFooter,+} from "./ui/dialog";+import { Button } from "./ui/button";+import { Input } from "./ui/input";+import { Label } from "./ui/label";+import { cn } from "./lib/utils";+import { useWorkspaceStore } from "../stores/workspaceStore";+import { InvitationsService } from "../services/InvitationsService";+import { TeamsService } from "../services/TeamsService";+import { useToast } from "./ui/useToast";+import type { Team } from "../types/electron";++interface Props {+ open: boolean;+ onOpenChange: (open: boolean) => void;+ workspaceId: string;+ workspaceName: string;+ onInvited?: () => void;+}++export default function InviteTeammateDialog({+ open,+ onOpenChange,+ workspaceId,+ workspaceName,+ onInvited,+}: Props) {+ const { t } = useTranslation();+ const { toast } = useToast();+ const [email, setEmail] = useState("");+ const [role, setRole] = useState<"admin" | "member">("member");+ const [teams, setTeams] = useState<Team[]>([]);+ const [selectedTeams, setSelectedTeams] = useState<Set<string>>(new Set());+ const [submitting, setSubmitting] = useState(false);+ const refreshTeams = useWorkspaceStore((s) => s.refreshTeams);++ useEffect(() => {+ if (!open) return;+ TeamsService.list(workspaceId)+ .then(setTeams)+ .catch(() => setTeams([]));+ }, [open, workspaceId]);++ useEffect(() => {+ if (!open) {+ setEmail("");+ setRole("member");+ setSelectedTeams(new Set());+ }+ }, [open]);++ function toggleTeam(id: string) {+ setSelectedTeams((prev) => {+ const next = new Set(prev);+ if (next.has(id)) next.delete(id);+ else next.add(id);+ return next;+ });+ }++ async function handleSubmit(e: React.FormEvent) {+ e.preventDefault();+ if (!email.trim()) return;+ setSubmitting(true);+ try {+ await InvitationsService.send(workspaceId, {+ email: email.trim().toLowerCase(),+ role,+ team_ids: Array.from(selectedTeams),+ });+ toast({+ title: t("workspaces.invite.sentTitle"),+ description: t("workspaces.invite.sentDescription", { email }),+ });+ void refreshTeams(workspaceId);+ onInvited?.();+ onOpenChange(false);+ } catch (error) {+ toast({+ title: t("workspaces.invite.errorTitle"),+ description: error instanceof Error ? error.message : t("common.unknownError"),+ variant: "destructive",+ });+ } finally {+ setSubmitting(false);+ }+ }++ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent className="max-w-md">+ <DialogHeader>+ <DialogTitle>+ {t("workspaces.invite.title", { workspace: workspaceName })}+ </DialogTitle>+ <DialogDescription>{t("workspaces.invite.description")}</DialogDescription>+ </DialogHeader>+ <form onSubmit={handleSubmit} className="space-y-4">+ <div className="space-y-1.5">+ <Label htmlFor="invite-email" className="text-xs font-medium">+ {t("workspaces.invite.emailLabel")}+ </Label>+ <Input+ id="invite-email"+ type="email"+ autoFocus+ value={email}+ onChange={(e) => setEmail(e.target.value)}+ placeholder="[email protected]"+ required+ />+ </div>++ <div className="space-y-1.5">+ <Label className="text-xs font-medium">{t("workspaces.invite.roleLabel")}</Label>+ <div className="flex gap-1.5">+ {(["member", "admin"] as const).map((r) => (+ <button+ key={r}+ type="button"+ onClick={() => setRole(r)}+ className={cn(+ "flex-1 h-9 px-3 rounded-md border text-xs font-medium transition-colors",+ "outline-none focus-visible:ring-1 focus-visible:ring-primary/30",+ role === r+ ? "border-primary/40 bg-primary/8 text-foreground"+ : "border-border/60 text-muted-foreground hover:bg-foreground/4 hover:text-foreground"+ )}+ >+ {t(`workspaces.invite.role.${r}`)}+ </button>+ ))}+ </div>+ </div>++ {teams.length > 0 && (+ <div className="space-y-1.5">+ <Label className="text-xs font-medium">{t("workspaces.invite.teamsLabel")}</Label>+ <div className="flex flex-wrap gap-1.5">+ {teams.map((team) => {+ const checked = selectedTeams.has(team.id);+ return (+ <button+ key={team.id}+ type="button"+ onClick={() => toggleTeam(team.id)}+ className={cn(+ "h-7 px-2.5 rounded-md border text-xs transition-colors outline-none",+ "focus-visible:ring-1 focus-visible:ring-primary/30",+ checked+ ? "border-primary/40 bg-primary/8 text-foreground"+ : "border-border/60 text-muted-foreground hover:bg-foreground/4 hover:text-foreground"+ )}+ >+ {team.name}+ </button>+ );+ })}+ </div>+ </div>+ )}++ <DialogFooter className="pt-1">+ <Button+ type="button"+ variant="ghost"+ onClick={() => onOpenChange(false)}+ disabled={submitting}+ >+ {t("common.cancel")}+ </Button>+ <Button type="submit" disabled={!email.trim() || submitting}>+ {submitting ? t("workspaces.invite.submitting") : t("workspaces.invite.submit")}+ </Button>+ </DialogFooter>+ </form>+ </DialogContent>+ </Dialog>+ );+}diff --git a/src/components/SettingsModal.tsx b/src/components/SettingsModal.tsxindex 974610642..14cda8589 100644--- a/src/components/SettingsModal.tsx+++ b/src/components/SettingsModal.tsx@@ -9,6 +9,7 @@ import {Keyboard,CreditCard,Shield,+ Users,} from "lucide-react";import SidebarModal, { type SidebarItem } from "./ui/SidebarModal";import SettingsPage, { SettingsSectionType } from "./SettingsPage";@@ -66,6 +67,13 @@ export default function SettingsModal({ open, onOpenChange, initialSection }: Sedescription: t("settingsModal.sections.plansBilling.description"),group: t("settingsModal.groups.account"),},+ {+ id: "workspace",+ label: t("settingsModal.sections.workspace.label"),+ icon: Users,+ description: t("settingsModal.sections.workspace.description"),+ group: t("settingsModal.groups.account"),+ },{id: "general",label: t("settingsModal.sections.general.label"),diff --git a/src/components/SettingsPage.tsx b/src/components/SettingsPage.tsxindex bad8ed258..f6f912a7a 100644--- a/src/components/SettingsPage.tsx+++ b/src/components/SettingsPage.tsx@@ -96,6 +96,7 @@ import { syncService } from "../services/SyncService.js";import { formatBytes } from "../utils/formatBytes";import { useSettingsStore } from "../stores/settingsStore";import { canManageSystemAudioInApp } from "../utils/systemAudioAccess";+import WorkspaceSection from "./settings/WorkspaceSection";const formatAmount = (cents: number, currency: string) =>(cents / 100).toLocaleString(undefined, { style: "currency", currency });@@ -103,6 +104,7 @@ const formatAmount = (cents: number, currency: string) =>export type SettingsSectionType =| "account"| "plansBilling"+ | "workspace"| "general"| "hotkeys"| "speechToText"@@ -2246,6 +2248,9 @@ export default function SettingsPage({</div>);+ case "workspace":+ return <WorkspaceSection initialSubTab={initialSubTab} />;+case "general":return (<div className="space-y-6">diff --git a/src/components/WorkspaceSwitcher.tsx b/src/components/WorkspaceSwitcher.tsxnew file mode 100644index 000000000..63f154bea--- /dev/null+++ b/src/components/WorkspaceSwitcher.tsx@@ -0,0 +1,108 @@+import React, { useState } from "react";+import { useTranslation } from "react-i18next";+import { ChevronsUpDown, Plus, Check } from "lucide-react";+import {+ DropdownMenu,+ DropdownMenuTrigger,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuLabel,+ DropdownMenuSeparator,+} from "./ui/dropdown-menu";+import { useWorkspace } from "../hooks/useWorkspace";+import { cn } from "./lib/utils";+import CreateWorkspaceDialog from "./CreateWorkspaceDialog";++function workspaceInitials(name: string): string {+ return name+ .trim()+ .split(/\s+/)+ .map((p) => p[0])+ .slice(0, 2)+ .join("")+ .toUpperCase();+}++export default function WorkspaceSwitcher({ userName }: { userName?: string | null }) {+ const { t } = useTranslation();+ const { workspaces, active, setActive } = useWorkspace();+ const [createOpen, setCreateOpen] = useState(false);++ const label = active ? active.name : t("workspaces.switcher.personal");+ const initials = active+ ? workspaceInitials(active.name)+ : (userName?.[0]?.toUpperCase() ?? "P");++ return (+ <>+ <DropdownMenu>+ <DropdownMenuTrigger+ className={cn(+ "group flex items-center w-full h-8 px-2 rounded-md outline-none gap-2",+ "hover:bg-foreground/5 dark:hover:bg-white/5 transition-colors",+ "focus-visible:ring-1 focus-visible:ring-primary/30"+ )}+ >+ <span+ className={cn(+ "shrink-0 w-5 h-5 rounded-md text-[10px] font-semibold flex items-center justify-center",+ active+ ? "bg-primary/12 text-primary"+ : "bg-foreground/8 text-foreground/70 dark:bg-white/8 dark:text-foreground/65"+ )}+ >+ {initials}+ </span>+ <span className="flex-1 text-xs text-left text-foreground/85 truncate">{label}</span>+ <ChevronsUpDown size={12} className="text-foreground/40 shrink-0" />+ </DropdownMenuTrigger>+ <DropdownMenuContent align="start" sideOffset={4} className="min-w-[12rem]">+ <DropdownMenuLabel className="text-[10px] uppercase tracking-wide text-muted-foreground/70 font-medium">+ {t("workspaces.switcher.workspaces")}+ </DropdownMenuLabel>+ {workspaces.length === 0 && (+ <div className="px-2 py-1.5 text-xs text-muted-foreground">+ {t("workspaces.switcher.empty")}+ </div>+ )}+ {workspaces.map((ws) => {+ const isActive = active?.id === ws.id;+ return (+ <DropdownMenuItem+ key={ws.id}+ onSelect={() => setActive(ws.id)}+ className="gap-2 text-xs"+ >+ <span+ className={cn(+ "shrink-0 w-5 h-5 rounded-md text-[10px] font-semibold flex items-center justify-center",+ "bg-primary/12 text-primary"+ )}+ >+ {workspaceInitials(ws.name)}+ </span>+ <span className="flex-1 truncate">{ws.name}</span>+ {isActive && <Check size={12} className="text-foreground/60" />}+ </DropdownMenuItem>+ );+ })}+ <DropdownMenuSeparator />+ <DropdownMenuItem onSelect={() => setActive(null)} className="gap-2 text-xs">+ <span className="shrink-0 w-5 h-5 rounded-md text-[10px] font-semibold flex items-center justify-center bg-foreground/8 text-foreground/70 dark:bg-white/8 dark:text-foreground/65">+ {userName?.[0]?.toUpperCase() ?? "P"}+ </span>+ <span className="flex-1 truncate">{t("workspaces.switcher.personal")}</span>+ {!active && <Check size={12} className="text-foreground/60" />}+ </DropdownMenuItem>+ <DropdownMenuSeparator />+ <DropdownMenuItem onSelect={() => setCreateOpen(true)} className="gap-2 text-xs">+ <Plus size={12} className="text-foreground/55" />+ <span>{t("workspaces.switcher.create")}</span>+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>++ <CreateWorkspaceDialog open={createOpen} onOpenChange={setCreateOpen} />+ </>+ );+}diff --git a/src/components/settings/WorkspaceBillingTab.tsx b/src/components/settings/WorkspaceBillingTab.tsxnew file mode 100644index 000000000..2638dbc80--- /dev/null+++ b/src/components/settings/WorkspaceBillingTab.tsx@@ -0,0 +1,141 @@+import React, { useState } from "react";+import { useTranslation } from "react-i18next";+import { ExternalLink } from "lucide-react";+import { Button } from "../ui/button";+import { useToast } from "../ui/useToast";+import { WorkspacesService } from "../../services/WorkspacesService";+import { useWorkspaceStore } from "../../stores/workspaceStore";+import type { Workspace } from "../../types/electron";++interface Props {+ workspace: Workspace;+}++const PLAN_LABELS: Record<string, string> = {+ business: "Business",+ pro: "Pro",+ free: "Free",+};++export default function WorkspaceBillingTab({ workspace }: Props) {+ const { t } = useTranslation();+ const { toast } = useToast();+ const members = useWorkspaceStore((s) => s.members);+ const isOwner = workspace.role === "owner";+ const [busy, setBusy] = useState(false);++ const seatsUsed = members.length;+ const seatsTotal = Math.max(workspace.seats, seatsUsed);+ const pct = seatsTotal === 0 ? 0 : Math.min(100, (seatsUsed / seatsTotal) * 100);++ async function handleCheckout() {+ setBusy(true);+ try {+ const url = await WorkspacesService.billingCheckout(workspace.id, "monthly");+ window.electronAPI?.openExternal?.(url) ?? window.open(url, "_blank");+ } catch (error) {+ toast({+ title: t("common.error"),+ description: error instanceof Error ? error.message : t("common.unknownError"),+ variant: "destructive",+ });+ } finally {+ setBusy(false);+ }+ }++ async function handlePortal() {+ setBusy(true);+ try {+ const url = await WorkspacesService.billingPortal(workspace.id);+ window.electronAPI?.openExternal?.(url) ?? window.open(url, "_blank");+ } catch (error) {+ toast({+ title: t("common.error"),+ description: error instanceof Error ? error.message : t("common.unknownError"),+ variant: "destructive",+ });+ } finally {+ setBusy(false);+ }+ }++ return (+ <div className="space-y-4">+ <div>+ <h3 className="text-xs font-semibold text-foreground">+ {t("settingsPage.workspace.billing.title")}+ </h3>+ <p className="text-xs text-muted-foreground/80 mt-0.5">+ {t("settingsPage.workspace.billing.description")}+ </p>+ </div>++ <div className="rounded-lg border border-border/50 dark:border-border-subtle/70 bg-card/50 dark:bg-surface-2/50 p-4 space-y-3">+ <div className="flex items-baseline justify-between">+ <div>+ <p className="text-[10px] uppercase tracking-wide text-muted-foreground font-medium">+ {t("settingsPage.workspace.billing.plan")}+ </p>+ <p className="text-base font-semibold text-foreground">+ {PLAN_LABELS[workspace.plan] || workspace.plan}+ </p>+ </div>+ <span+ className={+ "text-[10px] font-medium px-2 py-0.5 rounded-md uppercase tracking-wide " ++ (workspace.status === "active" || workspace.status === "trialing"+ ? "bg-emerald-500/10 text-emerald-600 dark:text-emerald-400"+ : workspace.status === "past_due"+ ? "bg-amber-500/12 text-amber-600 dark:text-amber-400"+ : "bg-foreground/8 text-foreground/65")+ }+ >+ {workspace.status}+ </span>+ </div>++ <div className="pt-1">+ <div className="flex items-center justify-between text-xs mb-1.5">+ <span className="text-muted-foreground">+ {t("settingsPage.workspace.billing.seats")}+ </span>+ <span className="text-foreground font-medium">+ {seatsUsed} / {seatsTotal}+ </span>+ </div>+ <div className="h-1.5 rounded-full bg-foreground/5 dark:bg-white/5 overflow-hidden">+ <div+ className="h-full bg-primary/70 dark:bg-primary/80"+ style={{ width: `${pct}%` }}+ />+ </div>+ </div>++ {workspace.current_period_end && (+ <div className="flex items-center justify-between text-xs text-muted-foreground">+ <span>{t("settingsPage.workspace.billing.nextInvoice")}</span>+ <span className="text-foreground">+ {new Date(workspace.current_period_end).toLocaleDateString()}+ </span>+ </div>+ )}+ </div>++ {isOwner && (+ <div className="flex gap-2">+ {workspace.stripe_subscription_id ? (+ <Button onClick={handlePortal} disabled={busy} size="sm" variant="outline">+ <ExternalLink className="mr-1.5 h-3.5 w-3.5" />+ {t("settingsPage.workspace.billing.manageStripe")}+ </Button>+ ) : (+ <Button onClick={handleCheckout} disabled={busy} size="sm">+ {t("settingsPage.workspace.billing.startSubscription")}+ </Button>+ )}+ </div>+ )}+ </div>+ );+}diff --git a/src/components/settings/WorkspaceDeveloperTab.tsx b/src/components/settings/WorkspaceDeveloperTab.tsxnew file mode 100644index 000000000..385a6dba5--- /dev/null+++ b/src/components/settings/WorkspaceDeveloperTab.tsx@@ -0,0 +1,301 @@+import React, { useEffect, useState } from "react";+import { useTranslation } from "react-i18next";+import { Plus, Copy, Trash2, Check, Key } from "lucide-react";+import { Button } from "../ui/button";+import { Input } from "../ui/input";+import { Label } from "../ui/label";+import { useToast } from "../ui/useToast";+import {+ Dialog,+ DialogContent,+ DialogHeader,+ DialogTitle,+ DialogDescription,+ DialogFooter,+} from "../ui/dialog";+import { WorkspaceApiKeysService } from "../../services/WorkspaceApiKeysService";+import type { Workspace, WorkspaceApiKey, NewWorkspaceApiKey } from "../../types/electron";+import { cn } from "../lib/utils";++interface Props {+ workspace: Workspace;+}++const SCOPE_GROUPS: { title: string; scopes: { id: string; label: string }[] }[] = [+ {+ title: "Notes",+ scopes: [+ { id: "workspace:notes:read", label: "Read notes" },+ { id: "workspace:notes:write", label: "Write notes" },+ ],+ },+ {+ title: "Folders",+ scopes: [+ { id: "workspace:folders:read", label: "Read folders" },+ { id: "workspace:folders:write", label: "Write folders" },+ ],+ },+ {+ title: "Transcriptions",+ scopes: [{ id: "workspace:transcriptions:read", label: "Read transcriptions" }],+ },+ {+ title: "Members",+ scopes: [+ { id: "workspace:members:read", label: "Read members" },+ { id: "workspace:members:write", label: "Manage members" },+ ],+ },+ {+ title: "Billing",+ scopes: [{ id: "workspace:billing:read", label: "Read billing" }],+ },+ {+ title: "Full access",+ scopes: [{ id: "workspace:*", label: "Workspace admin" }],+ },+];++export default function WorkspaceDeveloperTab({ workspace }: Props) {+ const { t } = useTranslation();+ const { toast } = useToast();+ const [keys, setKeys] = useState<WorkspaceApiKey[]>([]);+ const [createOpen, setCreateOpen] = useState(false);+ const [newKey, setNewKey] = useState<NewWorkspaceApiKey | null>(null);+ const [copied, setCopied] = useState(false);+ const [name, setName] = useState("");+ const [selectedScopes, setSelectedScopes] = useState<Set<string>>(new Set());+ const [submitting, setSubmitting] = useState(false);+ const canManage = workspace.role === "owner" || workspace.role === "admin";++ async function refresh() {+ try {+ setKeys(await WorkspaceApiKeysService.list(workspace.id));+ } catch {+ setKeys([]);+ }+ }++ useEffect(() => {+ if (canManage) void refresh();+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [workspace.id]);++ function toggleScope(id: string) {+ setSelectedScopes((prev) => {+ const next = new Set(prev);+ if (next.has(id)) next.delete(id);+ else next.add(id);+ return next;+ });+ }++ async function handleCreate(e: React.FormEvent) {+ e.preventDefault();+ if (!name.trim() || selectedScopes.size === 0) return;+ setSubmitting(true);+ try {+ const created = await WorkspaceApiKeysService.create(workspace.id, {+ name: name.trim(),+ scopes: Array.from(selectedScopes),+ });+ setNewKey(created);+ setName("");+ setSelectedScopes(new Set());+ setCreateOpen(false);+ await refresh();+ } catch (error) {+ toast({+ title: t("common.error"),+ description: error instanceof Error ? error.message : t("common.unknownError"),+ variant: "destructive",+ });+ } finally {+ setSubmitting(false);+ }+ }++ async function handleRevoke(keyId: string) {+ try {+ await WorkspaceApiKeysService.revoke(workspace.id, keyId);+ await refresh();+ } catch (error) {+ toast({+ title: t("common.error"),+ description: error instanceof Error ? error.message : t("common.unknownError"),+ variant: "destructive",+ });+ }+ }++ async function handleCopy() {+ if (!newKey) return;+ await navigator.clipboard.writeText(newKey.key);+ setCopied(true);+ setTimeout(() => setCopied(false), 1500);+ }++ return (+ <div className="space-y-4">+ <div className="flex items-center justify-between">+ <div>+ <h3 className="text-xs font-semibold text-foreground">+ {t("settingsPage.workspace.developer.title")}+ </h3>+ <p className="text-xs text-muted-foreground/80 mt-0.5">+ {t("settingsPage.workspace.developer.description")}+ </p>+ </div>+ {canManage && (+ <Button size="sm" onClick={() => setCreateOpen(true)}>+ <Plus className="mr-1.5 h-3.5 w-3.5" />+ {t("settingsPage.workspace.developer.new")}+ </Button>+ )}+ </div>++ <div className="rounded-lg border border-border/50 dark:border-border-subtle/70 divide-y divide-border/30 dark:divide-border-subtle/50 bg-card/50 dark:bg-surface-2/50">+ {keys.length === 0 && (+ <div className="py-10 text-center">+ <Key className="w-5 h-5 text-muted-foreground/60 mx-auto mb-2" />+ <p className="text-xs text-muted-foreground">+ {t("settingsPage.workspace.developer.empty")}+ </p>+ </div>+ )}+ {keys.map((k) => (+ <div key={k.id} className="flex items-center gap-3 px-4 h-14">+ <div className="flex-1 min-w-0">+ <p className="text-xs font-medium text-foreground truncate">{k.name}</p>+ <p className="text-[11px] font-mono text-muted-foreground truncate">+ {k.key_prefix}…+ </p>+ </div>+ <span className="text-xs text-muted-foreground hidden md:inline">+ {k.last_used_at+ ? t("settingsPage.workspace.developer.lastUsed", {+ date: new Date(k.last_used_at).toLocaleDateString(),+ })+ : t("settingsPage.workspace.developer.neverUsed")}+ </span>+ {canManage && (+ <button+ type="button"+ onClick={() => handleRevoke(k.id)}+ aria-label={t("settingsPage.workspace.developer.revoke")}+ className="p-1 rounded-md text-muted-foreground hover:text-destructive hover:bg-destructive/8 outline-none focus-visible:ring-1 focus-visible:ring-primary/30"+ >+ <Trash2 className="w-3.5 h-3.5" />+ </button>+ )}+ </div>+ ))}+ </div>++ <Dialog open={createOpen} onOpenChange={setCreateOpen}>+ <DialogContent className="max-w-lg">+ <DialogHeader>+ <DialogTitle>{t("settingsPage.workspace.developer.createTitle")}</DialogTitle>+ <DialogDescription>+ {t("settingsPage.workspace.developer.createDescription")}+ </DialogDescription>+ </DialogHeader>+ <form onSubmit={handleCreate} className="space-y-3">+ <div className="space-y-1.5">+ <Label htmlFor="key-name" className="text-xs font-medium">+ {t("settingsPage.workspace.developer.nameLabel")}+ </Label>+ <Input+ id="key-name"+ value={name}+ onChange={(e) => setName(e.target.value)}+ autoFocus+ placeholder={t("settingsPage.workspace.developer.namePlaceholder")}+ required+ />+ </div>+ <div className="space-y-2 max-h-72 overflow-y-auto">+ {SCOPE_GROUPS.map((group) => (+ <div key={group.title} className="space-y-1.5">+ <p className="text-[10px] uppercase tracking-wide text-muted-foreground font-medium">+ {group.title}+ </p>+ <div className="flex flex-wrap gap-1.5">+ {group.scopes.map((s) => {+ const checked = selectedScopes.has(s.id);+ return (+ <button+ key={s.id}+ type="button"+ onClick={() => toggleScope(s.id)}+ className={cn(+ "h-7 px-2.5 rounded-md border text-xs transition-colors outline-none",+ "focus-visible:ring-1 focus-visible:ring-primary/30",+ checked+ ? "border-primary/40 bg-primary/8 text-foreground"+ : "border-border/60 text-muted-foreground hover:bg-foreground/4 hover:text-foreground"+ )}+ >+ {s.label}+ </button>+ );+ })}+ </div>+ </div>+ ))}+ </div>+ <DialogFooter className="pt-2">+ <Button+ type="button"+ variant="ghost"+ onClick={() => setCreateOpen(false)}+ disabled={submitting}+ >+ {t("common.cancel")}+ </Button>+ <Button+ type="submit"+ disabled={!name.trim() || selectedScopes.size === 0 || submitting}+ >+ {submitting ? t("common.saving") : t("settingsPage.workspace.developer.create")}+ </Button>+ </DialogFooter>+ </form>+ </DialogContent>+ </Dialog>++ <Dialog open={!!newKey} onOpenChange={(open) => !open && setNewKey(null)}>+ <DialogContent className="max-w-lg">+ <DialogHeader>+ <DialogTitle>{t("settingsPage.workspace.developer.keyCreatedTitle")}</DialogTitle>+ <DialogDescription>+ {t("settingsPage.workspace.developer.keyCreatedDescription")}+ </DialogDescription>+ </DialogHeader>+ <div className="rounded-md border border-border/60 bg-foreground/4 dark:bg-white/4 p-3 font-mono text-xs break-all">+ {newKey?.key}+ </div>+ <DialogFooter>+ <Button onClick={handleCopy} variant="outline" size="sm">+ {copied ? (+ <>+ <Check className="mr-1.5 h-3.5 w-3.5" />+ {t("common.copied")}+ </>+ ) : (+ <>+ <Copy className="mr-1.5 h-3.5 w-3.5" />+ {t("common.copy")}+ </>+ )}+ </Button>+ <Button onClick={() => setNewKey(null)} size="sm">+ {t("common.done")}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ </div>+ );+}diff --git a/src/components/settings/WorkspaceMembersTab.tsx b/src/components/settings/WorkspaceMembersTab.tsxnew file mode 100644index 000000000..2a3e5bc91--- /dev/null+++ b/src/components/settings/WorkspaceMembersTab.tsx@@ -0,0 +1,244 @@+import React, { useEffect, useState } from "react";+import { useTranslation } from "react-i18next";+import { Trash2, MoreVertical, Mail, X } from "lucide-react";+import { useWorkspaceStore } from "../../stores/workspaceStore";+import { WorkspacesService } from "../../services/WorkspacesService";+import { InvitationsService } from "../../services/InvitationsService";+import { Button } from "../ui/button";+import { useToast } from "../ui/useToast";+import type { Workspace, WorkspaceInvitation } from "../../types/electron";+import InviteTeammateDialog from "../InviteTeammateDialog";+import {+ DropdownMenu,+ DropdownMenuTrigger,+ DropdownMenuContent,+ DropdownMenuItem,+} from "../ui/dropdown-menu";+import { cn } from "../lib/utils";++interface Props {+ workspace: Workspace;+}++export default function WorkspaceMembersTab({ workspace }: Props) {+ const { t } = useTranslation();+ const { toast } = useToast();+ const members = useWorkspaceStore((s) => s.members);+ const refreshMembers = useWorkspaceStore((s) => s.refreshMembers);+ const [invitations, setInvitations] = useState<WorkspaceInvitation[]>([]);+ const [inviteOpen, setInviteOpen] = useState(false);+ const canManage = workspace.role === "owner" || workspace.role === "admin";++ async function refreshInvitations() {+ try {+ const list = await InvitationsService.list(workspace.id);+ setInvitations(list);+ } catch {+ setInvitations([]);+ }+ }++ useEffect(() => {+ void refreshMembers(workspace.id);+ if (canManage) void refreshInvitations();+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [workspace.id]);++ async function handleRoleChange(userId: string, role: "owner" | "admin" | "member") {+ try {+ await WorkspacesService.updateMemberRole(workspace.id, userId, role);+ await refreshMembers(workspace.id);+ toast({+ title: t("settingsPage.workspace.members.roleUpdated"),+ });+ } catch (error) {+ toast({+ title: t("common.error"),+ description: error instanceof Error ? error.message : t("common.unknownError"),+ variant: "destructive",+ });+ }+ }++ async function handleRemove(userId: string) {+ try {+ await WorkspacesService.removeMember(workspace.id, userId);+ await refreshMembers(workspace.id);+ } catch (error) {+ toast({+ title: t("common.error"),+ description: error instanceof Error ? error.message : t("common.unknownError"),+ variant: "destructive",+ });+ }+ }++ async function handleRevoke(inviteId: string) {+ try {+ await InvitationsService.revoke(workspace.id, inviteId);+ await refreshInvitations();+ } catch {+ // toast handled inline+ }+ }++ async function handleResend(inviteId: string) {+ try {+ await InvitationsService.resend(workspace.id, inviteId);+ toast({ title: t("settingsPage.workspace.invites.resent") });+ } catch (error) {+ toast({+ title: t("common.error"),+ description: error instanceof Error ? error.message : t("common.unknownError"),+ variant: "destructive",+ });+ }+ }++ return (+ <div className="space-y-4">+ <div className="flex items-center justify-between">+ <div>+ <h3 className="text-xs font-semibold text-foreground">+ {t("settingsPage.workspace.members.title")}+ </h3>+ <p className="text-xs text-muted-foreground/80 mt-0.5">+ {t("settingsPage.workspace.members.description", {+ count: members.length,+ seats: workspace.seats,+ })}+ </p>+ </div>+ {canManage && (+ <Button size="sm" onClick={() => setInviteOpen(true)}>+ <Mail className="mr-1.5 h-3.5 w-3.5" />+ {t("settingsPage.workspace.members.invite")}+ </Button>+ )}+ </div>++ <div className="rounded-lg border border-border/50 dark:border-border-subtle/70 divide-y divide-border/30 dark:divide-border-subtle/50 bg-card/50 dark:bg-surface-2/50">+ {members.map((member) => (+ <div+ key={member.user_id}+ className="flex items-center gap-3 px-4 h-14"+ >+ {member.image ? (+ <img+ src={member.image}+ alt=""+ className="w-7 h-7 rounded-full object-cover shrink-0"+ />+ ) : (+ <span className="w-7 h-7 rounded-full bg-primary/10 text-primary text-[10px] font-semibold flex items-center justify-center shrink-0">+ {(member.name || member.email).slice(0, 2).toUpperCase()}+ </span>+ )}+ <div className="flex-1 min-w-0">+ <p className="text-xs font-medium text-foreground truncate">+ {member.name || member.email}+ </p>+ {member.name && (+ <p className="text-xs text-muted-foreground truncate">{member.email}</p>+ )}+ </div>+ <span+ className={cn(+ "text-[10px] font-medium px-2 py-0.5 rounded-md uppercase tracking-wide",+ member.role === "owner"+ ? "bg-primary/10 text-primary"+ : "bg-foreground/6 text-foreground/65"+ )}+ >+ {t(`settingsPage.workspace.role.${member.role}`)}+ </span>+ {canManage && member.role !== "owner" && (+ <DropdownMenu>+ <DropdownMenuTrigger+ className="p-1 rounded-md text-muted-foreground hover:text-foreground hover:bg-foreground/5 outline-none focus-visible:ring-1 focus-visible:ring-primary/30"+ aria-label={t("common.actions")}+ >+ <MoreVertical className="w-3.5 h-3.5" />+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end" className="text-xs">+ {member.role !== "admin" && (+ <DropdownMenuItem onSelect={() => handleRoleChange(member.user_id, "admin")}>+ {t("settingsPage.workspace.members.promote")}+ </DropdownMenuItem>+ )}+ {member.role !== "member" && (+ <DropdownMenuItem onSelect={() => handleRoleChange(member.user_id, "member")}>+ {t("settingsPage.workspace.members.demote")}+ </DropdownMenuItem>+ )}+ {workspace.role === "owner" && (+ <DropdownMenuItem onSelect={() => handleRoleChange(member.user_id, "owner")}>+ {t("settingsPage.workspace.members.transferOwnership")}+ </DropdownMenuItem>+ )}+ <DropdownMenuItem+ className="text-destructive"+ onSelect={() => handleRemove(member.user_id)}+ >+ <Trash2 className="mr-1.5 h-3.5 w-3.5" />+ {t("settingsPage.workspace.members.remove")}+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ )}+ </div>+ ))}+ {members.length === 0 && (+ <div className="py-8 text-center text-xs text-muted-foreground">+ {t("settingsPage.workspace.members.empty")}+ </div>+ )}+ </div>++ {canManage && invitations.length > 0 && (+ <div>+ <h4 className="text-xs font-semibold text-foreground mb-2">+ {t("settingsPage.workspace.invites.title")}+ </h4>+ <div className="rounded-lg border border-border/50 dark:border-border-subtle/70 divide-y divide-border/30 dark:divide-border-subtle/50 bg-card/50 dark:bg-surface-2/50">+ {invitations.map((inv) => (+ <div key={inv.id} className="flex items-center gap-3 px-4 h-12">+ <Mail className="w-3.5 h-3.5 text-muted-foreground shrink-0" />+ <div className="flex-1 min-w-0">+ <p className="text-xs text-foreground truncate">{inv.email}</p>+ </div>+ <span className="text-[10px] uppercase tracking-wide text-muted-foreground">+ {t(`settingsPage.workspace.role.${inv.workspace_role}`)}+ </span>+ <Button+ size="sm"+ variant="ghost"+ onClick={() => handleResend(inv.id)}+ className="h-7 px-2"+ >+ {t("settingsPage.workspace.invites.resend")}+ </Button>+ <button+ type="button"+ onClick={() => handleRevoke(inv.id)}+ aria-label={t("settingsPage.workspace.invites.revoke")}+ className="p-1 rounded-md text-muted-foreground hover:text-destructive hover:bg-destructive/8 transition-colors outline-none focus-visible:ring-1 focus-visible:ring-primary/30"+ >+ <X className="w-3.5 h-3.5" />+ </button>+ </div>+ ))}+ </div>+ </div>+ )}++ <InviteTeammateDialog+ open={inviteOpen}+ onOpenChange={setInviteOpen}+ workspaceId={workspace.id}+ workspaceName={workspace.name}+ onInvited={refreshInvitations}+ />+ </div>+ );+}diff --git a/src/components/settings/WorkspaceSection.tsx b/src/components/settings/WorkspaceSection.tsxnew file mode 100644index 000000000..f9bd813e9--- /dev/null+++ b/src/components/settings/WorkspaceSection.tsx@@ -0,0 +1,326 @@+import React, { useEffect, useState } from "react";+import { useTranslation } from "react-i18next";+import { Users, UserPlus, Trash2 } from "lucide-react";+import { useWorkspaceStore } from "../../stores/workspaceStore";+import { WorkspacesService } from "../../services/WorkspacesService";+import { useLocalStorage } from "../../hooks/useLocalStorage";+import { Button } from "../ui/button";+import { Input } from "../ui/input";+import { Label } from "../ui/label";+import { useToast } from "../ui/useToast";+import {+ Dialog,+ DialogContent,+ DialogHeader,+ DialogTitle,+ DialogDescription,+ DialogFooter,+} from "../ui/dialog";+import CreateWorkspaceDialog from "../CreateWorkspaceDialog";+import {+ DropdownMenu,+ DropdownMenuTrigger,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuLabel,+ DropdownMenuSeparator,+} from "../ui/dropdown-menu";+import { cn } from "../lib/utils";+import WorkspaceMembersTab from "./WorkspaceMembersTab";+import WorkspaceTeamsTab from "./WorkspaceTeamsTab";+import WorkspaceBillingTab from "./WorkspaceBillingTab";+import WorkspaceDeveloperTab from "./WorkspaceDeveloperTab";+import type { Workspace } from "../../types/electron";++const SUB_TABS = ["general", "members", "teams", "billing", "developer"] as const;+type WorkspaceTab = (typeof SUB_TABS)[number];++interface Props {+ initialSubTab?: string;+}++export default function WorkspaceSection({ initialSubTab }: Props) {+ const { t } = useTranslation();+ const { workspaces, activeWorkspaceId, setActiveWorkspaceId, loaded, refresh } =+ useWorkspaceStore();+ const [tab, setTab] = useLocalStorage<WorkspaceTab>(+ "settings.workspaceTab",+ (SUB_TABS.includes(initialSubTab as WorkspaceTab)+ ? (initialSubTab as WorkspaceTab)+ : "members")+ );+ const [createOpen, setCreateOpen] = useState(false);++ useEffect(() => {+ if (!loaded) void refresh();+ }, [loaded, refresh]);++ const workspace = activeWorkspaceId+ ? workspaces.find((w) => w.id === activeWorkspaceId)+ : (workspaces[0] ?? null);++ useEffect(() => {+ if (!activeWorkspaceId && workspaces[0]) {+ setActiveWorkspaceId(workspaces[0].id);+ }+ }, [activeWorkspaceId, workspaces, setActiveWorkspaceId]);++ if (!loaded) {+ return (+ <div className="space-y-3">+ <div className="h-6 w-32 rounded bg-foreground/5 dark:bg-white/5 animate-pulse" />+ <div className="h-24 rounded-lg bg-foreground/5 dark:bg-white/5 animate-pulse" />+ </div>+ );+ }++ if (workspaces.length === 0) {+ return (+ <div className="space-y-4">+ <div>+ <h3 className="text-xs font-semibold text-foreground">+ {t("settingsPage.workspace.title")}+ </h3>+ <p className="text-xs text-muted-foreground/80 mt-0.5">+ {t("settingsPage.workspace.description")}+ </p>+ </div>+ <div className="rounded-lg border border-border/50 dark:border-border-subtle/70 bg-card/50 dark:bg-surface-2/50 p-6 text-center">+ <Users className="w-5 h-5 text-muted-foreground/60 mx-auto mb-2" />+ <p className="text-xs font-medium text-foreground mb-1">+ {t("settingsPage.workspace.empty.title")}+ </p>+ <p className="text-xs text-muted-foreground mb-4">+ {t("settingsPage.workspace.empty.description")}+ </p>+ <Button size="sm" onClick={() => setCreateOpen(true)}>+ <UserPlus className="mr-1.5 h-3.5 w-3.5" />+ {t("settingsPage.workspace.empty.create")}+ </Button>+ </div>+ <CreateWorkspaceDialog open={createOpen} onOpenChange={setCreateOpen} />+ </div>+ );+ }++ if (!workspace) return null;++ return (+ <div className="space-y-4">+ <div className="flex items-center justify-between">+ <div className="min-w-0">+ {workspaces.length > 1 ? (+ <DropdownMenu>+ <DropdownMenuTrigger+ className={cn(+ "group flex items-center gap-1.5 outline-none rounded-md px-2 -mx-2 py-0.5",+ "hover:bg-foreground/5 dark:hover:bg-white/5 focus-visible:ring-1 focus-visible:ring-primary/30"+ )}+ >+ <h2 className="text-sm font-semibold text-foreground truncate">+ {workspace.name}+ </h2>+ <span className="text-xs text-muted-foreground">▾</span>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="start">+ <DropdownMenuLabel className="text-[10px] uppercase tracking-wide text-muted-foreground/70 font-medium">+ {t("workspaces.switcher.workspaces")}+ </DropdownMenuLabel>+ {workspaces.map((w) => (+ <DropdownMenuItem+ key={w.id}+ onSelect={() => setActiveWorkspaceId(w.id)}+ className="text-xs"+ >+ {w.name}+ </DropdownMenuItem>+ ))}+ <DropdownMenuSeparator />+ <DropdownMenuItem onSelect={() => setCreateOpen(true)} className="text-xs">+ <UserPlus className="mr-1.5 h-3.5 w-3.5" />+ {t("workspaces.switcher.create")}+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ ) : (+ <h2 className="text-sm font-semibold text-foreground truncate">{workspace.name}</h2>+ )}+ <p className="text-xs text-muted-foreground mt-0.5">+ {t(`settingsPage.workspace.role.${workspace.role}`)} · {workspace.slug}+ </p>+ </div>+ </div>++ <div className="border-b border-border/40 dark:border-border-subtle/60 -mx-1">+ <div className="flex gap-0.5 px-1">+ {SUB_TABS.map((id) => (+ <button+ key={id}+ onClick={() => setTab(id)}+ className={cn(+ "px-3 h-8 text-xs font-medium outline-none transition-colors relative",+ "focus-visible:ring-1 focus-visible:ring-primary/30 rounded-md",+ tab === id+ ? "text-foreground"+ : "text-muted-foreground hover:text-foreground"+ )}+ >+ {t(`settingsPage.workspace.tab.${id}`)}+ {tab === id && (+ <span className="absolute -bottom-px left-2 right-2 h-px bg-primary" />+ )}+ </button>+ ))}+ </div>+ </div>++ <div className="pt-1">+ {tab === "general" && <GeneralTab workspace={workspace} />}+ {tab === "members" && <WorkspaceMembersTab workspace={workspace} />}+ {tab === "teams" && <WorkspaceTeamsTab workspace={workspace} />}+ {tab === "billing" && <WorkspaceBillingTab workspace={workspace} />}+ {tab === "developer" && <WorkspaceDeveloperTab workspace={workspace} />}+ </div>++ <CreateWorkspaceDialog open={createOpen} onOpenChange={setCreateOpen} />+ </div>+ );+}++function GeneralTab({ workspace }: { workspace: Workspace }) {+ const { t } = useTranslation();+ const { toast } = useToast();+ const refresh = useWorkspaceStore((s) => s.refresh);+ const setActive = useWorkspaceStore((s) => s.setActiveWorkspaceId);+ const [name, setName] = useState(workspace.name);+ const [slug, setSlug] = useState(workspace.slug);+ const [saving, setSaving] = useState(false);+ const [confirmOpen, setConfirmOpen] = useState(false);+ const isOwner = workspace.role === "owner";+ const dirty = name !== workspace.name || slug !== workspace.slug;++ useEffect(() => {+ setName(workspace.name);+ setSlug(workspace.slug);+ }, [workspace.id, workspace.name, workspace.slug]);++ async function handleSave() {+ setSaving(true);+ try {+ await WorkspacesService.update(workspace.id, { name, slug });+ await refresh();+ toast({ title: t("settingsPage.workspace.general.saved") });+ } catch (error) {+ toast({+ title: t("common.error"),+ description: error instanceof Error ? error.message : t("common.unknownError"),+ variant: "destructive",+ });+ } finally {+ setSaving(false);+ }+ }++ async function handleDelete() {+ setSaving(true);+ try {+ await WorkspacesService.remove(workspace.id);+ setActive(null);+ await refresh();+ setConfirmOpen(false);+ } catch (error) {+ toast({+ title: t("common.error"),+ description: error instanceof Error ? error.message : t("common.unknownError"),+ variant: "destructive",+ });+ } finally {+ setSaving(false);+ }+ }++ return (+ <div className="space-y-4">+ <div className="space-y-3 rounded-lg border border-border/50 dark:border-border-subtle/70 bg-card/50 dark:bg-surface-2/50 p-4">+ <div className="space-y-1.5">+ <Label htmlFor="ws-name" className="text-xs font-medium">+ {t("settingsPage.workspace.general.nameLabel")}+ </Label>+ <Input+ id="ws-name"+ value={name}+ onChange={(e) => setName(e.target.value)}+ disabled={!isOwner && workspace.role !== "admin"}+ maxLength={80}+ />+ </div>+ <div className="space-y-1.5">+ <Label htmlFor="ws-slug" className="text-xs font-medium">+ {t("settingsPage.workspace.general.slugLabel")}+ </Label>+ <Input+ id="ws-slug"+ value={slug}+ onChange={(e) => setSlug(e.target.value)}+ disabled={!isOwner && workspace.role !== "admin"}+ maxLength={48}+ pattern="[a-z0-9-]+"+ />+ <p className="text-[11px] text-muted-foreground">+ {t("settingsPage.workspace.general.slugHint")}+ </p>+ </div>+ <div className="pt-1">+ <Button onClick={handleSave} size="sm" disabled={!dirty || saving}>+ {saving ? t("common.saving") : t("common.save")}+ </Button>+ </div>+ </div>++ {isOwner && (+ <div className="rounded-lg border border-destructive/30 bg-destructive/3 dark:bg-destructive/6 p-4 space-y-3">+ <div>+ <p className="text-xs font-medium text-foreground">+ {t("settingsPage.workspace.general.dangerTitle")}+ </p>+ <p className="text-xs text-muted-foreground mt-0.5">+ {t("settingsPage.workspace.general.dangerDescription")}+ </p>+ </div>+ <Button+ variant="outline"+ size="sm"+ onClick={() => setConfirmOpen(true)}+ className="text-destructive border-destructive/30 hover:bg-destructive/10 hover:border-destructive/50"+ >+ <Trash2 className="mr-1.5 h-3.5 w-3.5" />+ {t("settingsPage.workspace.general.delete")}+ </Button>+ </div>+ )}++ <Dialog open={confirmOpen} onOpenChange={setConfirmOpen}>+ <DialogContent className="max-w-md">+ <DialogHeader>+ <DialogTitle>{t("settingsPage.workspace.general.confirmTitle")}</DialogTitle>+ <DialogDescription>+ {t("settingsPage.workspace.general.confirmDescription", { name: workspace.name })}+ </DialogDescription>+ </DialogHeader>+ <DialogFooter>+ <Button variant="ghost" onClick={() => setConfirmOpen(false)} disabled={saving}>+ {t("common.cancel")}+ </Button>+ <Button+ onClick={handleDelete}+ disabled={saving}+ className="bg-destructive text-destructive-foreground hover:bg-destructive/90"+ >+ {saving ? t("common.saving") : t("settingsPage.workspace.general.delete")}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ </div>+ );+}diff --git a/src/components/settings/WorkspaceTeamsTab.tsx b/src/components/settings/WorkspaceTeamsTab.tsxnew file mode 100644index 000000000..0fc3a3e9e--- /dev/null+++ b/src/components/settings/WorkspaceTeamsTab.tsx@@ -0,0 +1,182 @@+import React, { useEffect, useState } from "react";+import { useTranslation } from "react-i18next";+import { Plus, Users, Trash2 } from "lucide-react";+import { useWorkspaceStore } from "../../stores/workspaceStore";+import { TeamsService } from "../../services/TeamsService";+import { Button } from "../ui/button";+import { Input } from "../ui/input";+import { Label } from "../ui/label";+import { useToast } from "../ui/useToast";+import {+ Dialog,+ DialogContent,+ DialogHeader,+ DialogTitle,+ DialogFooter,+} from "../ui/dialog";+import type { Workspace, Team } from "../../types/electron";++interface Props {+ workspace: Workspace;+}++export default function WorkspaceTeamsTab({ workspace }: Props) {+ const { t } = useTranslation();+ const { toast } = useToast();+ const teams = useWorkspaceStore((s) => s.teams);+ const refreshTeams = useWorkspaceStore((s) => s.refreshTeams);+ const [createOpen, setCreateOpen] = useState(false);+ const [name, setName] = useState("");+ const [description, setDescription] = useState("");+ const [submitting, setSubmitting] = useState(false);+ const canManage = workspace.role === "owner" || workspace.role === "admin";++ useEffect(() => {+ void refreshTeams(workspace.id);+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [workspace.id]);++ async function handleCreate(e: React.FormEvent) {+ e.preventDefault();+ if (!name.trim()) return;+ setSubmitting(true);+ try {+ await TeamsService.create(workspace.id, {+ name: name.trim(),+ description: description.trim() || undefined,+ });+ await refreshTeams(workspace.id);+ setName("");+ setDescription("");+ setCreateOpen(false);+ } catch (error) {+ toast({+ title: t("common.error"),+ description: error instanceof Error ? error.message : t("common.unknownError"),+ variant: "destructive",+ });+ } finally {+ setSubmitting(false);+ }+ }++ async function handleDelete(team: Team) {+ try {+ await TeamsService.remove(team.id);+ await refreshTeams(workspace.id);+ } catch (error) {+ toast({+ title: t("common.error"),+ description: error instanceof Error ? error.message : t("common.unknownError"),+ variant: "destructive",+ });+ }+ }++ return (+ <div className="space-y-4">+ <div className="flex items-center justify-between">+ <div>+ <h3 className="text-xs font-semibold text-foreground">+ {t("settingsPage.workspace.teams.title")}+ </h3>+ <p className="text-xs text-muted-foreground/80 mt-0.5">+ {t("settingsPage.workspace.teams.description")}+ </p>+ </div>+ {canManage && (+ <Button size="sm" onClick={() => setCreateOpen(true)}>+ <Plus className="mr-1.5 h-3.5 w-3.5" />+ {t("settingsPage.workspace.teams.new")}+ </Button>+ )}+ </div>++ <div className="rounded-lg border border-border/50 dark:border-border-subtle/70 divide-y divide-border/30 dark:divide-border-subtle/50 bg-card/50 dark:bg-surface-2/50">+ {teams.length === 0 && (+ <div className="py-10 text-center">+ <Users className="w-5 h-5 text-muted-foreground/60 mx-auto mb-2" />+ <p className="text-xs text-muted-foreground mb-3">+ {t("settingsPage.workspace.teams.empty")}+ </p>+ {canManage && (+ <Button size="sm" variant="outline" onClick={() => setCreateOpen(true)}>+ {t("settingsPage.workspace.teams.createFirst")}+ </Button>+ )}+ </div>+ )}+ {teams.map((team) => (+ <div key={team.id} className="flex items-center gap-3 px-4 h-14">+ <div className="flex-1 min-w-0">+ <p className="text-xs font-medium text-foreground truncate">{team.name}</p>+ {team.description && (+ <p className="text-xs text-muted-foreground truncate">{team.description}</p>+ )}+ </div>+ <span className="text-xs text-muted-foreground">+ {t("settingsPage.workspace.teams.memberCount", { count: team.member_count ?? 0 })}+ </span>+ {canManage && (+ <button+ type="button"+ onClick={() => handleDelete(team)}+ aria-label={t("common.delete")}+ className="p-1 rounded-md text-muted-foreground hover:text-destructive hover:bg-destructive/8 transition-colors outline-none focus-visible:ring-1 focus-visible:ring-primary/30"+ >+ <Trash2 className="w-3.5 h-3.5" />+ </button>+ )}+ </div>+ ))}+ </div>++ <Dialog open={createOpen} onOpenChange={setCreateOpen}>+ <DialogContent className="max-w-md">+ <DialogHeader>+ <DialogTitle>{t("settingsPage.workspace.teams.createTitle")}</DialogTitle>+ </DialogHeader>+ <form onSubmit={handleCreate} className="space-y-3">+ <div className="space-y-1.5">+ <Label htmlFor="team-name" className="text-xs font-medium">+ {t("settingsPage.workspace.teams.nameLabel")}+ </Label>+ <Input+ id="team-name"+ value={name}+ onChange={(e) => setName(e.target.value)}+ autoFocus+ maxLength={80}+ required+ />+ </div>+ <div className="space-y-1.5">+ <Label htmlFor="team-description" className="text-xs font-medium">+ {t("settingsPage.workspace.teams.descriptionLabel")}+ </Label>+ <Input+ id="team-description"+ value={description}+ onChange={(e) => setDescription(e.target.value)}+ maxLength={280}+ />+ </div>+ <DialogFooter className="pt-2">+ <Button+ type="button"+ variant="ghost"+ onClick={() => setCreateOpen(false)}+ disabled={submitting}+ >+ {t("common.cancel")}+ </Button>+ <Button type="submit" disabled={!name.trim() || submitting}>+ {submitting ? t("common.saving") : t("common.create")}+ </Button>+ </DialogFooter>+ </form>+ </DialogContent>+ </Dialog>+ </div>+ );+}diff --git a/src/hooks/useWorkspace.ts b/src/hooks/useWorkspace.tsnew file mode 100644index 000000000..7c2eb1724--- /dev/null+++ b/src/hooks/useWorkspace.ts@@ -0,0 +1,39 @@+import { useEffect } from "react";+import { useWorkspaceStore } from "../stores/workspaceStore";+import type { Workspace, WorkspaceRole } from "../types/electron";++interface UseWorkspaceResult {+ workspaces: Workspace[];+ active: Workspace | null;+ role: WorkspaceRole | null;+ loaded: boolean;+ setActive: (id: string | null) => void;+ refresh: () => Promise<void>;+}++export function useWorkspace(): UseWorkspaceResult {+ const workspaces = useWorkspaceStore((s) => s.workspaces);+ const activeWorkspaceId = useWorkspaceStore((s) => s.activeWorkspaceId);+ const loaded = useWorkspaceStore((s) => s.loaded);+ const refresh = useWorkspaceStore((s) => s.refresh);+ const setActive = useWorkspaceStore((s) => s.setActiveWorkspaceId);++ useEffect(() => {+ if (!loaded) {+ void refresh();+ }+ }, [loaded, refresh]);++ const active = activeWorkspaceId+ ? (workspaces.find((w) => w.id === activeWorkspaceId) ?? null)+ : null;++ return {+ workspaces,+ active,+ role: active?.role ?? null,+ loaded,+ setActive,+ refresh,+ };+}diff --git a/src/locales/en/translation.json b/src/locales/en/translation.jsonindex a58aacc76..0ba5ec742 100644--- a/src/locales/en/translation.json+++ b/src/locales/en/translation.json@@ -155,7 +155,17 @@"private": "Private","tap": "Tap","close": "Close",- "dismiss": "Dismiss"+ "dismiss": "Dismiss",+ "save": "Save",+ "saving": "Saving…",+ "create": "Create",+ "delete": "Delete",+ "actions": "Actions",+ "error": "Something went wrong",+ "unknownError": "An unknown error occurred",+ "copy": "Copy",+ "copied": "Copied",+ "done": "Done"},"onboarding": {"steps": {@@ -1010,6 +1020,10 @@"description": "Plans, usage & billing","label": "Plans & Billing"},+ "workspace": {+ "description": "Members, teams, billing & API keys",+ "label": "Workspace"+ },"general": {"description": "Appearance, sounds & startup","label": "Preferences"@@ -1038,6 +1052,91 @@"title": "Settings"},"settingsPage": {+ "workspace": {+ "title": "Workspace",+ "description": "Collaborate with teammates, share notes, and manage billing in one place.",+ "empty": {+ "title": "Create your first workspace",+ "description": "Workspaces let you collaborate with teammates and share notes.",+ "create": "Create workspace"+ },+ "tab": {+ "general": "General",+ "members": "Members",+ "teams": "Teams",+ "billing": "Billing",+ "developer": "Developer"+ },+ "role": {+ "owner": "Owner",+ "admin": "Admin",+ "member": "Member"+ },+ "general": {+ "nameLabel": "Workspace name",+ "slugLabel": "Slug",+ "slugHint": "Used in URLs and invite links. Lowercase letters, digits, and dashes only.",+ "saved": "Workspace updated",+ "dangerTitle": "Delete workspace",+ "dangerDescription": "All shared notes, folders, and integrations will be deleted. This cannot be undone.",+ "delete": "Delete workspace",+ "confirmTitle": "Delete {{name}}?",+ "confirmDescription": "This cancels the subscription and removes all workspace data permanently."+ },+ "members": {+ "title": "Members",+ "description": "{{count}} of {{seats}} seats used.",+ "invite": "Invite",+ "empty": "No members yet.",+ "roleUpdated": "Role updated",+ "promote": "Make admin",+ "demote": "Make member",+ "transferOwnership": "Transfer ownership",+ "remove": "Remove from workspace"+ },+ "invites": {+ "title": "Pending invitations",+ "resend": "Resend",+ "revoke": "Revoke",+ "resent": "Invitation resent"+ },+ "teams": {+ "title": "Teams",+ "description": "Group members for scoped sharing.",+ "new": "New team",+ "empty": "No teams yet.",+ "createFirst": "Create your first team",+ "createTitle": "Create team",+ "nameLabel": "Team name",+ "descriptionLabel": "Description",+ "memberCount": "{{count}} members"+ },+ "billing": {+ "title": "Billing",+ "description": "Plan, seats, and payment.",+ "plan": "Plan",+ "seats": "Seats",+ "nextInvoice": "Next invoice",+ "manageStripe": "Manage in Stripe",+ "startSubscription": "Start subscription"+ },+ "developer": {+ "title": "API keys",+ "description": "Programmatic access scoped to this workspace.",+ "empty": "No API keys yet. Create one to integrate with this workspace.",+ "new": "New key",+ "create": "Create key",+ "createTitle": "Create API key",+ "createDescription": "Choose the permissions this key needs. You can revoke it any time.",+ "nameLabel": "Key name",+ "namePlaceholder": "Production integration",+ "revoke": "Revoke key",+ "lastUsed": "Last used {{date}}",+ "neverUsed": "Never used",+ "keyCreatedTitle": "API key created",+ "keyCreatedDescription": "Copy this key now — you won't be able to see it again."+ }+ },"account": {"badges": {"free": "Free",@@ -1810,7 +1909,57 @@"integrations": "Integrations","defaultUser": "User","notSignedIn": "Not signed in",- "chat": "Chat"+ "chat": "Chat",+ "inviteTeammate": "Invite teammate",+ "createWorkspace": "Create workspace"+ },+ "workspaces": {+ "switcher": {+ "personal": "Personal",+ "workspaces": "Workspaces",+ "empty": "No workspaces yet",+ "create": "Create workspace…"+ },+ "create": {+ "title": "Create workspace",+ "description": "Workspaces let you collaborate, share notes, and manage billing in one place.",+ "nameLabel": "Workspace name",+ "namePlaceholder": "Acme Corp",+ "submit": "Create workspace",+ "submitting": "Creating…",+ "errorTitle": "Couldn't create workspace"+ },+ "created": {+ "title": "Workspace created",+ "description": "You're now the owner of {{name}}."+ },+ "invite": {+ "title": "Invite to {{workspace}}",+ "description": "Add teammates by email. They'll get a link to join.",+ "emailLabel": "Email",+ "roleLabel": "Role",+ "teamsLabel": "Add to teams",+ "submit": "Send invite",+ "submitting": "Sending…",+ "sentTitle": "Invite sent",+ "sentDescription": "We sent an invitation to {{email}}.",+ "errorTitle": "Couldn't send invitation",+ "role": {+ "admin": "Admin",+ "member": "Member"+ }+ },+ "accept": {+ "title": "Join workspace",+ "description": "{{inviter}} invited you to join {{workspace}} as a {{role}}.",+ "loading": "Loading invitation…",+ "accept": "Accept invitation",+ "accepting": "Accepting…",+ "signInToAccept": "Sign in to accept",+ "successTitle": "You're in",+ "successDescription": "Welcome to {{name}}.",+ "errorTitle": "Couldn't accept invitation"+ }},"chat": {"newChat": "New chat",diff --git a/src/services/InvitationsService.ts b/src/services/InvitationsService.tsnew file mode 100644index 000000000..165ea7e94--- /dev/null+++ b/src/services/InvitationsService.ts@@ -0,0 +1,55 @@+import { cloudGet, cloudPost, cloudDelete } from "./cloudApi.js";+import type { WorkspaceInvitation, InvitationPreview } from "../types/electron";++interface DataWrap<T> {+ data: T;+}++async function list(workspaceId: string): Promise<WorkspaceInvitation[]> {+ const res = await cloudGet<DataWrap<WorkspaceInvitation[]>>(+ `/api/workspaces/${workspaceId}/invitations`+ );+ return res.data;+}++async function send(+ workspaceId: string,+ input: { email: string; role?: "admin" | "member"; team_ids?: string[] }+): Promise<WorkspaceInvitation> {+ const res = await cloudPost<DataWrap<WorkspaceInvitation>>(+ `/api/workspaces/${workspaceId}/invitations`,+ input+ );+ return res.data;+}++async function revoke(workspaceId: string, invitationId: string): Promise<void> {+ await cloudDelete(`/api/workspaces/${workspaceId}/invitations/${invitationId}`);+}++async function resend(workspaceId: string, invitationId: string): Promise<void> {+ await cloudPost(`/api/workspaces/${workspaceId}/invitations/${invitationId}`);+}++async function preview(token: string): Promise<InvitationPreview> {+ const res = await cloudGet<DataWrap<InvitationPreview>>(+ `/api/invitations/${encodeURIComponent(token)}`+ );+ return res.data;+}++async function accept(token: string): Promise<{ workspace_id: string; role: string }> {+ const res = await cloudPost<DataWrap<{ workspace_id: string; role: string }>>(+ `/api/invitations/${encodeURIComponent(token)}/accept`+ );+ return res.data;+}++export const InvitationsService = {+ list,+ send,+ revoke,+ resend,+ preview,+ accept,+};diff --git a/src/services/TeamsService.ts b/src/services/TeamsService.tsnew file mode 100644index 000000000..db0f3ef5f--- /dev/null+++ b/src/services/TeamsService.ts@@ -0,0 +1,58 @@+import { cloudGet, cloudPost, cloudPatch, cloudDelete } from "./cloudApi.js";+import type { Team, TeamMember } from "../types/electron";++interface DataWrap<T> {+ data: T;+}++async function list(workspaceId: string): Promise<Team[]> {+ const res = await cloudGet<DataWrap<Team[]>>(`/api/workspaces/${workspaceId}/teams`);+ return res.data;+}++async function create(+ workspaceId: string,+ input: { name: string; description?: string }+): Promise<Team> {+ const res = await cloudPost<DataWrap<Team>>(`/api/workspaces/${workspaceId}/teams`, input);+ return res.data;+}++async function update(+ teamId: string,+ patch: { name?: string; description?: string }+): Promise<Team> {+ const res = await cloudPatch<DataWrap<Team>>(`/api/teams/${teamId}`, patch);+ return res.data;+}++async function remove(teamId: string): Promise<void> {+ await cloudDelete(`/api/teams/${teamId}`);+}++async function listMembers(teamId: string): Promise<TeamMember[]> {+ const res = await cloudGet<DataWrap<TeamMember[]>>(`/api/teams/${teamId}/members`);+ return res.data;+}++async function addMember(+ teamId: string,+ userId: string,+ role: "admin" | "member" = "member"+): Promise<void> {+ await cloudPost(`/api/teams/${teamId}/members`, { user_id: userId, role });+}++async function removeMember(teamId: string, userId: string): Promise<void> {+ await cloudDelete(`/api/teams/${teamId}/members/${userId}`);+}++export const TeamsService = {+ list,+ create,+ update,+ remove,+ listMembers,+ addMember,+ removeMember,+};diff --git a/src/services/WorkspaceApiKeysService.ts b/src/services/WorkspaceApiKeysService.tsnew file mode 100644index 000000000..c4ff1b332--- /dev/null+++ b/src/services/WorkspaceApiKeysService.ts@@ -0,0 +1,34 @@+import { cloudGet, cloudPost, cloudDelete } from "./cloudApi.js";+import type { WorkspaceApiKey, NewWorkspaceApiKey } from "../types/electron";++interface DataWrap<T> {+ data: T;+}++async function list(workspaceId: string): Promise<WorkspaceApiKey[]> {+ const res = await cloudGet<DataWrap<WorkspaceApiKey[]>>(+ `/api/workspaces/${workspaceId}/api-keys`+ );+ return res.data;+}++async function create(+ workspaceId: string,+ input: { name: string; scopes: string[]; expires_in_days?: number; description?: string }+): Promise<NewWorkspaceApiKey> {+ const res = await cloudPost<DataWrap<NewWorkspaceApiKey>>(+ `/api/workspaces/${workspaceId}/api-keys`,+ input+ );+ return res.data;+}++async function revoke(workspaceId: string, keyId: string): Promise<void> {+ await cloudDelete(`/api/workspaces/${workspaceId}/api-keys/${keyId}`);+}++export const WorkspaceApiKeysService = {+ list,+ create,+ revoke,+};diff --git a/src/services/WorkspacesService.ts b/src/services/WorkspacesService.tsnew file mode 100644index 000000000..10bec45ef--- /dev/null+++ b/src/services/WorkspacesService.ts@@ -0,0 +1,96 @@+import { cloudGet, cloudPost, cloudPatch, cloudDelete } from "./cloudApi.js";+import type { Workspace, WorkspaceMember } from "../types/electron";++interface DataWrap<T> {+ data: T;+}++async function list(): Promise<Workspace[]> {+ const res = await cloudGet<DataWrap<Workspace[]>>("/api/workspaces");+ return res.data;+}++async function create(name: string): Promise<Workspace> {+ const res = await cloudPost<DataWrap<Workspace>>("/api/workspaces", { name });+ return res.data;+}++async function get(workspaceId: string): Promise<Workspace> {+ const res = await cloudGet<DataWrap<Workspace>>(`/api/workspaces/${workspaceId}`);+ return res.data;+}++async function update(+ workspaceId: string,+ patch: { name?: string; slug?: string }+): Promise<Workspace> {+ const res = await cloudPatch<DataWrap<Workspace>>(`/api/workspaces/${workspaceId}`, patch);+ return res.data;+}++async function remove(workspaceId: string): Promise<void> {+ await cloudDelete(`/api/workspaces/${workspaceId}`);+}++async function listMembers(workspaceId: string): Promise<WorkspaceMember[]> {+ const res = await cloudGet<DataWrap<WorkspaceMember[]>>(+ `/api/workspaces/${workspaceId}/members`+ );+ return res.data;+}++async function updateMemberRole(+ workspaceId: string,+ userId: string,+ role: "owner" | "admin" | "member"+): Promise<void> {+ await cloudPatch(`/api/workspaces/${workspaceId}/members/${userId}`, { role });+}++async function removeMember(workspaceId: string, userId: string): Promise<void> {+ await cloudDelete(`/api/workspaces/${workspaceId}/members/${userId}`);+}++async function billingCheckout(+ workspaceId: string,+ interval: "monthly" | "annual" = "monthly"+): Promise<string> {+ const res = await cloudPost<DataWrap<{ url: string }>>(+ `/api/workspaces/${workspaceId}/billing/checkout`,+ { interval }+ );+ return res.data.url;+}++async function billingPortal(workspaceId: string): Promise<string> {+ const res = await cloudPost<DataWrap<{ url: string }>>(+ `/api/workspaces/${workspaceId}/billing/portal`+ );+ return res.data.url;+}++async function previewSeats(+ workspaceId: string,+ additionalSeats: number+): Promise<{ next_quantity: number; amount_due: number; currency: string }> {+ const res = await cloudPost<+ DataWrap<{ next_quantity: number; amount_due: number; currency: string }>+ >(`/api/workspaces/${workspaceId}/billing/preview-seats`, {+ additional_seats: additionalSeats,+ });+ return res.data;+}++export const WorkspacesService = {+ list,+ create,+ get,+ update,+ remove,+ listMembers,+ updateMemberRole,+ removeMember,+ billingCheckout,+ billingPortal,+ previewSeats,+};diff --git a/src/stores/workspaceStore.ts b/src/stores/workspaceStore.tsnew file mode 100644index 000000000..88aab6639--- /dev/null+++ b/src/stores/workspaceStore.ts@@ -0,0 +1,106 @@+import { create } from "zustand";+import type { Workspace, WorkspaceMember, Team } from "../types/electron";+import { WorkspacesService } from "../services/WorkspacesService";+import { TeamsService } from "../services/TeamsService";+import logger from "../utils/logger";++interface WorkspaceState {+ workspaces: Workspace[];+ loaded: boolean;+ loading: boolean;+ activeWorkspaceId: string | null;+ members: WorkspaceMember[];+ teams: Team[];++ setActiveWorkspaceId: (id: string | null) => void;+ refresh: () => Promise<void>;+ createWorkspace: (name: string) => Promise<Workspace>;+ refreshMembers: (workspaceId: string) => Promise<void>;+ refreshTeams: (workspaceId: string) => Promise<void>;+ current: () => Workspace | null;+}++const ACTIVE_WORKSPACE_KEY = "activeWorkspaceId";++function readActiveWorkspaceId(): string | null {+ if (typeof window === "undefined") return null;+ return localStorage.getItem(ACTIVE_WORKSPACE_KEY);+}++function writeActiveWorkspaceId(id: string | null): void {+ if (typeof window === "undefined") return;+ if (id) localStorage.setItem(ACTIVE_WORKSPACE_KEY, id);+ else localStorage.removeItem(ACTIVE_WORKSPACE_KEY);+}++export const useWorkspaceStore = create<WorkspaceState>((set, get) => ({+ workspaces: [],+ loaded: false,+ loading: false,+ activeWorkspaceId: readActiveWorkspaceId(),+ members: [],+ teams: [],++ setActiveWorkspaceId: (id) => {+ writeActiveWorkspaceId(id);+ set({ activeWorkspaceId: id, members: [], teams: [] });+ },++ refresh: async () => {+ if (get().loading) return;+ set({ loading: true });+ try {+ const workspaces = await WorkspacesService.list();+ const activeId = get().activeWorkspaceId;+ const stillValid = activeId && workspaces.some((w) => w.id === activeId);+ set({+ workspaces,+ loaded: true,+ loading: false,+ activeWorkspaceId: stillValid ? activeId : null,+ });+ if (!stillValid && activeId) writeActiveWorkspaceId(null);+ } catch (error) {+ logger.error("Failed to load workspaces", { error: (error as Error).message }, "workspaces");+ set({ loading: false, loaded: true });+ }+ },++ createWorkspace: async (name) => {+ const workspace = await WorkspacesService.create(name);+ set((s) => ({ workspaces: [...s.workspaces, workspace] }));+ return workspace;+ },++ refreshMembers: async (workspaceId) => {+ try {+ const members = await WorkspacesService.listMembers(workspaceId);+ set({ members });+ } catch (error) {+ logger.error(+ "Failed to load workspace members",+ { error: (error as Error).message },+ "workspaces"+ );+ }+ },++ refreshTeams: async (workspaceId) => {+ try {+ const teams = await TeamsService.list(workspaceId);+ set({ teams });+ } catch (error) {+ logger.error(+ "Failed to load workspace teams",+ { error: (error as Error).message },+ "workspaces"+ );+ }+ },++ current: () => {+ const { activeWorkspaceId, workspaces } = get();+ if (!activeWorkspaceId) return null;+ return workspaces.find((w) => w.id === activeWorkspaceId) ?? null;+ },+}));diff --git a/src/types/electron.ts b/src/types/electron.tsindex 805a7bc74..f70b1f1b4 100644--- a/src/types/electron.ts+++ b/src/types/electron.ts@@ -60,6 +60,8 @@ export interface NoteItem {client_note_id: string;sync_status: "synced" | "pending" | "error";deleted_at: string | null;+ workspace_id?: string | null;+ team_id?: string | null;}export interface FolderItem {@@ -73,6 +75,99 @@ export interface FolderItem {cloud_id: string | null;sync_status: "synced" | "pending" | "error";deleted_at: string | null;+ workspace_id?: string | null;+ team_id?: string | null;+}++export type WorkspaceRole = "owner" | "admin" | "member";+export type TeamRole = "admin" | "member";++export interface Workspace {+ id: string;+ name: string;+ slug: string;+ created_by_user_id: string;+ stripe_customer_id: string | null;+ stripe_subscription_id: string | null;+ plan: string;+ status: string;+ trial_ends_at: string | null;+ current_period_end: string | null;+ cancel_at_period_end: boolean;+ seats: number;+ created_at: string;+ updated_at: string;+ role: WorkspaceRole;+}++export interface WorkspaceMember {+ user_id: string;+ role: WorkspaceRole;+ joined_at: string;+ email: string;+ name: string | null;+ image: string | null;+}++export interface Team {+ id: string;+ workspace_id: string;+ name: string;+ slug: string;+ description: string | null;+ created_at: string;+ updated_at: string;+ member_count?: number;+}++export interface TeamMember {+ user_id: string;+ role: TeamRole;+ joined_at: string;+ email: string;+ name: string | null;+ image: string | null;+}++export interface WorkspaceInvitation {+ id: string;+ email: string;+ workspace_role: TeamRole;+ team_ids: string[];+ invited_by_user_id: string;+ expires_at: string;+ created_at: string;+ accepted_at: string | null;+ revoked_at: string | null;+}++export interface InvitationPreview {+ id: string;+ email: string;+ workspace_role: TeamRole;+ team_ids: string[];+ expires_at: string;+ workspace_id: string;+ workspace_name: string;+ workspace_slug: string;+ inviter_name: string | null;+ inviter_email: string | null;+}++export interface WorkspaceApiKey {+ id: string;+ name: string;+ key_prefix: string;+ scopes: string[];+ last_used_at: string | null;+ expires_at: string | null;+ created_at: string;+ created_by_user_id: string | null;+ description: string | null;+}++export interface NewWorkspaceApiKey extends WorkspaceApiKey {+ key: string;}export interface ActionItem {