Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

Unify settings layout and auto-save (#5257)

Jiayuan Zhangd51a3cbbbda8
diff --git a/apps/desktop/src/renderer/src/components/daemon-settings-tab.tsx b/apps/desktop/src/renderer/src/components/daemon-settings-tab.tsx
index 9fd108caa7..838673bc74 100644
--- a/apps/desktop/src/renderer/src/components/daemon-settings-tab.tsx
+++ b/apps/desktop/src/renderer/src/components/daemon-settings-tab.tsx
@@ -3,6 +3,12 @@ import { AlertCircle, Info, LogIn } from "lucide-react";
import { Button } from "@multica/ui/components/ui/button";
import { Switch } from "@multica/ui/components/ui/switch";
import { cn } from "@multica/ui/lib/utils";
+import {
+ SettingsCard,
+ SettingsRow,
+ SettingsSection,
+ SettingsTab,
+} from "@multica/views/settings";
import { reauthenticateDaemon } from "../platform/daemon-reauth";
import type { DaemonPrefs, DaemonStatus } from "../../../shared/daemon-types";
import {
@@ -11,26 +17,6 @@ import {
formatUptime,
} from "../../../shared/daemon-types";
-function SettingRow({
- label,
- description,
- children,
-}: {
- label: string;
- description: string;
- children: ReactNode;
-}) {
- return (
- <div className="flex items-center justify-between gap-6 py-4">
- <div className="min-w-0">
- <p className="text-sm font-medium">{label}</p>
- <p className="text-sm text-muted-foreground mt-0.5">{description}</p>
- </div>
- <div className="shrink-0">{children}</div>
- </div>
- );
-}
-
// One row inside the diagnostics block. Values that are likely to be
// long IDs / URLs render as monospaced + truncated with a tooltip.
function DiagnosticsRow({
@@ -95,11 +81,10 @@ export function DaemonSettingsTab() {
const externallyManaged = status.externallyManaged === true;
return (
- <div>
- <h2 className="text-lg font-semibold">Daemon</h2>
- <p className="text-sm text-muted-foreground mt-1">
- Configure how the local agent daemon behaves with the desktop app.
- </p>
+ <SettingsTab
+ title="Daemon"
+ description="Configure how the local agent daemon behaves with the desktop app."
+ >
{status.state === "auth_expired" && (
<div className="mt-4 flex items-start gap-3 rounded-lg border border-destructive/40 bg-destructive/5 px-4 py-3">
@@ -138,8 +123,8 @@ export function DaemonSettingsTab() {
</div>
)}
- <div className="mt-6 divide-y">
- <SettingRow
+ <SettingsCard>
+ <SettingsRow
label="Auto-start on launch"
description="Automatically start the daemon when the app opens and you are logged in."
>
@@ -148,9 +133,9 @@ export function DaemonSettingsTab() {
onCheckedChange={(checked) => updatePref("autoStart", checked)}
disabled={saving || externallyManaged}
/>
- </SettingRow>
+ </SettingsRow>
- <SettingRow
+ <SettingsRow
label="Auto-stop on quit"
description="Stop the daemon when the desktop app is closed. Disable this to keep the daemon running in the background."
>
@@ -159,22 +144,22 @@ export function DaemonSettingsTab() {
onCheckedChange={(checked) => updatePref("autoStop", checked)}
disabled={saving || externallyManaged}
/>
- </SettingRow>
+ </SettingsRow>
- <div className="py-4">
- <p className="text-sm font-medium">CLI Status</p>
- <p className="text-sm text-muted-foreground mt-1">
- {cliInstalled === null
+ <SettingsRow
+ label="CLI Status"
+ description={
+ cliInstalled === null
? "Checking…"
: cliInstalled
? "multica CLI is installed and available in PATH."
- : "multica CLI not found. Install it to enable daemon management."}
- </p>
+ : "multica CLI not found. Install it to enable daemon management."
+ }
+ >
{cliInstalled === false && (
<Button
variant="outline"
size="sm"
- className="mt-2"
onClick={() =>
window.desktopAPI.openExternal(
"https://github.com/multica-ai/multica#cli-installation",
@@ -184,19 +169,19 @@ export function DaemonSettingsTab() {
Installation Guide
</Button>
)}
- </div>
- </div>
+ {cliInstalled !== false && <span />}
+ </SettingsRow>
+ </SettingsCard>
{/* Diagnostics — moved out of the logs panel so the panel can focus
on logs. These fields matter for support tickets and bug reports,
not for everyday use. */}
- <div className="mt-8">
- <h3 className="text-sm font-semibold">Diagnostics</h3>
- <p className="text-xs text-muted-foreground mt-1">
- Identification and connection details. Useful when filing a bug
- report or investigating why a runtime isn&apos;t showing up.
- </p>
- <div className="mt-3 rounded-lg border bg-muted/20 px-4 py-2">
+ <SettingsSection
+ title="Diagnostics"
+ description="Identification and connection details. Useful when filing a bug report or investigating why a runtime isn't showing up."
+ >
+ <SettingsCard>
+ <div className="px-4 py-2">
<DiagnosticsRow
label="State"
value={
@@ -246,8 +231,9 @@ export function DaemonSettingsTab() {
: "—"
}
/>
- </div>
- </div>
- </div>
+ </div>
+ </SettingsCard>
+ </SettingsSection>
+ </SettingsTab>
);
}
diff --git a/apps/desktop/src/renderer/src/components/updates-settings-tab.tsx b/apps/desktop/src/renderer/src/components/updates-settings-tab.tsx
index 370bcad2ab..5175813e41 100644
--- a/apps/desktop/src/renderer/src/components/updates-settings-tab.tsx
+++ b/apps/desktop/src/renderer/src/components/updates-settings-tab.tsx
@@ -2,6 +2,7 @@ import { useCallback, useState } from "react";
import { AlertCircle, ArrowDownToLine, Check, Loader2 } from "lucide-react";
import { Button } from "@multica/ui/components/ui/button";
import { useT } from "@multica/views/i18n";
+import { SettingsCard, SettingsRow, SettingsTab } from "@multica/views/settings";
type CheckState =
| { status: "idle" }
@@ -30,48 +31,44 @@ export function UpdatesSettingsTab() {
}, []);
return (
- <div>
- <h2 className="text-lg font-semibold">{t(($) => $.desktop.updates.title)}</h2>
- <p className="text-sm text-muted-foreground mt-1">
- {t(($) => $.desktop.updates.description)}
- </p>
+ <SettingsTab
+ title={t(($) => $.desktop.updates.title)}
+ description={t(($) => $.desktop.updates.description)}
+ >
+ <SettingsCard>
+ <SettingsRow label={t(($) => $.desktop.updates.current_version)}>
+ <span className="font-mono text-xs text-muted-foreground">
+ v{currentVersion}
+ </span>
+ </SettingsRow>
- <div className="mt-6 divide-y">
- <div className="flex items-center justify-between gap-6 py-4">
- <div className="min-w-0">
- <p className="text-sm font-medium">{t(($) => $.desktop.updates.current_version)}</p>
- <p className="text-sm text-muted-foreground mt-0.5 font-mono">
- v{currentVersion}
- </p>
- </div>
- </div>
-
- <div className="flex items-start justify-between gap-6 py-4">
- <div className="min-w-0">
- <p className="text-sm font-medium">{t(($) => $.desktop.updates.check_section_title)}</p>
- <p className="text-sm text-muted-foreground mt-0.5">
- {t(($) => $.desktop.updates.check_section_description)}
- </p>
+ <SettingsRow
+ label={t(($) => $.desktop.updates.check_section_title)}
+ align="start"
+ description={
+ <>
+ <p>{t(($) => $.desktop.updates.check_section_description)}</p>
{state.status === "up-to-date" && (
- <p className="text-sm text-muted-foreground mt-2 inline-flex items-center gap-1.5">
+ <p className="mt-2 inline-flex items-center gap-1.5">
<Check className="size-3.5 text-success" />
{t(($) => $.desktop.updates.up_to_date)}
</p>
)}
{state.status === "available" && (
- <p className="text-sm text-muted-foreground mt-2 inline-flex items-center gap-1.5">
+ <p className="mt-2 inline-flex items-center gap-1.5">
<ArrowDownToLine className="size-3.5 text-primary" />
{t(($) => $.desktop.updates.downloading, { version: state.latestVersion })}
</p>
)}
{state.status === "error" && (
- <p className="text-sm text-destructive mt-2 inline-flex items-center gap-1.5">
+ <p className="mt-2 inline-flex items-center gap-1.5 text-destructive">
<AlertCircle className="size-3.5" />
{state.message}
</p>
)}
- </div>
- <div className="shrink-0">
+ </>
+ }
+ >
<Button
variant="outline"
size="sm"
@@ -87,9 +84,8 @@ export function UpdatesSettingsTab() {
t(($) => $.desktop.updates.check_now)
)}
</Button>
- </div>
- </div>
- </div>
- </div>
+ </SettingsRow>
+ </SettingsCard>
+ </SettingsTab>
);
}
diff --git a/packages/views/locales/en/settings.json b/packages/views/locales/en/settings.json
index 44c5ea465f..30fc827033 100644
--- a/packages/views/locales/en/settings.json
+++ b/packages/views/locales/en/settings.json
@@ -1,5 +1,11 @@
{
+ "auto_save": {
+ "saving": "Saving…",
+ "saved": "Saved",
+ "failed": "Couldn't save"
+ },
"preferences": {
+ "general_title": "General",
"theme": {
"title": "Theme",
"light": "Light",
@@ -45,7 +51,8 @@
}
},
"account": {
- "section_profile": "Profile",
+ "section_profile": "Personal information",
+ "avatar_label": "Avatar",
"click_avatar_hint": "Click to upload avatar",
"name_label": "Name",
"profile_description_label": "About you",
@@ -136,7 +143,8 @@
}
},
"workspace": {
- "section_general": "General",
+ "section_general": "Workspace details",
+ "logo_label": "Workspace logo",
"change_logo_aria": "Change workspace logo",
"click_logo_hint": "Click the logo to upload a new image",
"toast_logo_updated": "Workspace logo updated",
@@ -393,6 +401,10 @@
"edit_aria": "Edit repository",
"cancel_aria": "Cancel edit",
"delete_aria": "Delete repository",
+ "delete_confirm_title": "Delete repository?",
+ "delete_confirm_description": "This repository will be removed from the workspace immediately.",
+ "delete_confirm_cancel": "Cancel",
+ "delete_confirm_action": "Delete repository",
"manage_hint": "Only admins and owners can manage repositories.",
"toast_saved": "Repositories saved",
"toast_save_failed": "Failed to save repositories"
diff --git a/packages/views/locales/ja/settings.json b/packages/views/locales/ja/settings.json
index 6cc843beec..54565f6a26 100644
--- a/packages/views/locales/ja/settings.json
+++ b/packages/views/locales/ja/settings.json
@@ -1,5 +1,11 @@
{
+ "auto_save": {
+ "saving": "保存中…",
+ "saved": "保存済み",
+ "failed": "保存できませんでした"
+ },
"preferences": {
+ "general_title": "一般",
"theme": {
"title": "テーマ",
"light": "ライト",
@@ -45,7 +51,8 @@
}
},
"account": {
- "section_profile": "プロフィール",
+ "section_profile": "個人情報",
+ "avatar_label": "アバター",
"click_avatar_hint": "クリックしてアバターをアップロード",
"name_label": "名前",
"profile_description_label": "自己紹介",
@@ -136,7 +143,8 @@
}
},
"workspace": {
- "section_general": "一般",
+ "section_general": "ワークスペース情報",
+ "logo_label": "ワークスペースロゴ",
"name_label": "名前",
"description_label": "説明",
"description_placeholder": "このワークスペースは何に注力していますか?",
@@ -393,6 +401,10 @@
"edit_aria": "リポジトリを編集",
"cancel_aria": "編集をキャンセル",
"delete_aria": "リポジトリを削除",
+ "delete_confirm_title": "リポジトリを削除しますか?",
+ "delete_confirm_description": "このリポジトリはワークスペースから直ちに削除されます。",
+ "delete_confirm_cancel": "キャンセル",
+ "delete_confirm_action": "リポジトリを削除",
"manage_hint": "リポジトリを管理できるのは admin と owner のみです。",
"toast_saved": "リポジトリを保存しました",
"toast_save_failed": "リポジトリを保存できませんでした"
diff --git a/packages/views/locales/ko/settings.json b/packages/views/locales/ko/settings.json
index 5716e500b7..d00dfba221 100644
--- a/packages/views/locales/ko/settings.json
+++ b/packages/views/locales/ko/settings.json
@@ -1,5 +1,11 @@
{
+ "auto_save": {
+ "saving": "저장 중…",
+ "saved": "저장됨",
+ "failed": "저장하지 못했습니다"
+ },
"preferences": {
+ "general_title": "일반",
"theme": {
"title": "테마",
"light": "라이트",
@@ -45,7 +51,8 @@
}
},
"account": {
- "section_profile": "프로필",
+ "section_profile": "개인 정보",
+ "avatar_label": "아바타",
"click_avatar_hint": "클릭해서 아바타 업로드",
"name_label": "이름",
"profile_description_label": "내 소개",
@@ -136,7 +143,8 @@
}
},
"workspace": {
- "section_general": "일반",
+ "section_general": "워크스페이스 정보",
+ "logo_label": "워크스페이스 로고",
"change_logo_aria": "워크스페이스 로고 변경",
"click_logo_hint": "로고를 클릭하여 새 이미지를 업로드하세요",
"toast_logo_updated": "워크스페이스 로고를 업데이트했습니다",
@@ -245,6 +253,10 @@
"edit_aria": "저장소 수정",
"cancel_aria": "수정 취소",
"delete_aria": "저장소 삭제",
+ "delete_confirm_title": "저장소를 삭제할까요?",
+ "delete_confirm_description": "이 저장소는 워크스페이스에서 즉시 제거됩니다.",
+ "delete_confirm_cancel": "취소",
+ "delete_confirm_action": "저장소 삭제",
"manage_hint": "관리자와 소유자만 저장소를 관리할 수 있습니다.",
"toast_saved": "저장소를 저장했습니다",
"toast_save_failed": "저장소를 저장하지 못했습니다"
diff --git a/packages/views/locales/zh-Hans/settings.json b/packages/views/locales/zh-Hans/settings.json
index 5d18728f2b..526075c477 100644
--- a/packages/views/locales/zh-Hans/settings.json
+++ b/packages/views/locales/zh-Hans/settings.json
@@ -1,5 +1,11 @@
{
+ "auto_save": {
+ "saving": "正在保存…",
+ "saved": "已保存",
+ "failed": "保存失败"
+ },
"preferences": {
+ "general_title": "常规",
"theme": {
"title": "主题",
"light": "浅色",
@@ -45,7 +51,8 @@
}
},
"account": {
- "section_profile": "个人资料",
+ "section_profile": "个人信息",
+ "avatar_label": "头像",
"click_avatar_hint": "点击上传头像",
"name_label": "姓名",
"profile_description_label": "关于你",
@@ -136,7 +143,8 @@
}
},
"workspace": {
- "section_general": "通用",
+ "section_general": "工作区信息",
+ "logo_label": "工作区标志",
"change_logo_aria": "更换工作区图标",
"click_logo_hint": "点击图标上传新图片",
"toast_logo_updated": "工作区图标已更新",
@@ -393,6 +401,10 @@
"edit_aria": "编辑仓库",
"cancel_aria": "取消编辑",
"delete_aria": "删除仓库",
+ "delete_confirm_title": "删除代码仓库?",
+ "delete_confirm_description": "此代码仓库将立即从工作区中移除。",
+ "delete_confirm_cancel": "取消",
+ "delete_confirm_action": "删除代码仓库",
"manage_hint": "只有管理员和所有者可以管理代码仓库。",
"toast_saved": "已保存代码仓库",
"toast_save_failed": "保存代码仓库失败"
diff --git a/packages/views/settings/components/account-tab.tsx b/packages/views/settings/components/account-tab.tsx
index 2304e6ae54..c200f3625c 100644
--- a/packages/views/settings/components/account-tab.tsx
+++ b/packages/views/settings/components/account-tab.tsx
@@ -1,17 +1,21 @@
"use client";
-import { useEffect, useState } from "react";
-import { Save } from "lucide-react";
+import { useCallback, useEffect, useMemo, useState } from "react";
import { Input } from "@multica/ui/components/ui/input";
-import { Label } from "@multica/ui/components/ui/label";
-import { Button } from "@multica/ui/components/ui/button";
-import { Card, CardContent } from "@multica/ui/components/ui/card";
import { Textarea } from "@multica/ui/components/ui/textarea";
import { toast } from "sonner";
import { useAuthStore } from "@multica/core/auth";
import { api } from "@multica/core/api";
import { AvatarUploadControl } from "../../common/avatar-upload-control";
import { useT } from "../../i18n";
+import {
+ SettingsCard,
+ SettingsRow,
+ SettingsSaveState,
+ SettingsSection,
+ SettingsTab,
+} from "./settings-layout";
+import { useAutoSave } from "./use-auto-save";
// Mirror server/internal/handler/auth.go:MaxProfileDescriptionLen. Counted in
// JS String.length (UTF-16 code units) here while the server counts runes,
@@ -19,6 +23,15 @@ import { useT } from "../../i18n";
// before the server's — which is the safer direction of drift.
const MAX_PROFILE_DESCRIPTION_LEN = 2000;
+interface ProfileDraft {
+ name: string;
+ profileDescription: string;
+}
+
+function profilesEqual(left: ProfileDraft, right: ProfileDraft) {
+ return left.name === right.name && left.profileDescription === right.profileDescription;
+}
+
export function AccountTab() {
const { t } = useT("settings");
const user = useAuthStore((s) => s.user);
@@ -28,41 +41,72 @@ export function AccountTab() {
const [profileDescription, setProfileDescription] = useState(
user?.profile_description ?? "",
);
- const [profileSaving, setProfileSaving] = useState(false);
useEffect(() => {
setProfileName(user?.name ?? "");
setProfileDescription(user?.profile_description ?? "");
- }, [user]);
+ // Preserve in-progress edits when an avatar upload or auto-save replaces
+ // the current user object in the auth store.
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- intentionally keyed on user identity
+ }, [user?.id]);
const descriptionTooLong = profileDescription.length > MAX_PROFILE_DESCRIPTION_LEN;
- const handleProfileSave = async () => {
- if (descriptionTooLong) return;
- setProfileSaving(true);
- try {
+ const draft = useMemo(
+ () => ({ name: profileName, profileDescription }),
+ [profileDescription, profileName],
+ );
+ const savedDraft = useMemo(
+ () => ({
+ name: user?.name ?? "",
+ profileDescription: user?.profile_description ?? "",
+ }),
+ [user?.name, user?.profile_description],
+ );
+ const saveProfile = useCallback(
+ async (next: ProfileDraft) => {
const updated = await api.updateMe({
- name: profileName,
- profile_description: profileDescription,
+ name: next.name,
+ profile_description: next.profileDescription,
});
setUser(updated);
- toast.success(t(($) => $.account.toast_profile_updated));
- } catch (e) {
- toast.error(e instanceof Error ? e.message : t(($) => $.account.toast_profile_failed));
- } finally {
- setProfileSaving(false);
- }
- };
+ },
+ [setUser],
+ );
+ const autoSave = useAutoSave({
+ value: draft,
+ savedValue: savedDraft,
+ onSave: saveProfile,
+ onError: (error) =>
+ toast.error(
+ error instanceof Error
+ ? error.message
+ : t(($) => $.account.toast_profile_failed),
+ ),
+ enabled: !!user && !!profileName.trim() && !descriptionTooLong,
+ isEqual: profilesEqual,
+ });
return (
- <div className="space-y-8">
- <section className="space-y-4">
- <h2 className="text-sm font-semibold">{t(($) => $.account.section_profile)}</h2>
-
- <Card>
- <CardContent className="space-y-4">
- {/* Avatar upload */}
- <div className="flex items-center gap-4">
+ <SettingsTab title={t(($) => $.page.tabs.profile)}>
+ <SettingsSection
+ title={t(($) => $.account.section_profile)}
+ action={
+ <SettingsSaveState
+ status={autoSave.status}
+ savingLabel={t(($) => $.auto_save.saving)}
+ savedLabel={t(($) => $.auto_save.saved)}
+ errorLabel={t(($) => $.auto_save.failed)}
+ />
+ }
+ >
+ <SettingsCard>
+ <SettingsRow
+ label={t(($) => $.account.avatar_label)}
+ description={t(($) => $.account.click_avatar_hint)}
+ controlClassName="sm:max-w-none"
+ >
+ <div className="flex justify-start sm:justify-end">
<AvatarUploadControl
variant="user"
value={user?.avatar_url ?? null}
@@ -73,34 +117,45 @@ export function AccountTab() {
setUser(updated);
}}
/>
- <div className="text-xs text-muted-foreground">
- {t(($) => $.account.click_avatar_hint)}
- </div>
</div>
+ </SettingsRow>
+ <SettingsRow
+ label={t(($) => $.account.name_label)}
+ controlClassName="sm:w-80"
+ >
+ <Input
+ type="text"
+ name="profile-name"
+ autoComplete="name"
+ aria-label={t(($) => $.account.name_label)}
+ value={profileName}
+ onChange={(event) => setProfileName(event.target.value)}
+ onBlur={autoSave.flush}
+ />
+ </SettingsRow>
+
+ <SettingsRow
+ label={t(($) => $.account.profile_description_label)}
+ description={t(($) => $.account.profile_description_hint)}
+ controlClassName="sm:w-96"
+ align="start"
+ >
<div>
- <Label className="text-xs text-muted-foreground">{t(($) => $.account.name_label)}</Label>
- <Input
- type="search"
- value={profileName}
- onChange={(e) => setProfileName(e.target.value)}
- className="mt-1"
- />
- </div>
- <div>
- <Label className="text-xs text-muted-foreground">
- {t(($) => $.account.profile_description_label)}
- </Label>
<Textarea
+ name="profile-description"
+ autoComplete="off"
+ aria-label={t(($) => $.account.profile_description_label)}
value={profileDescription}
- onChange={(e) => setProfileDescription(e.target.value)}
+ onChange={(event) => setProfileDescription(event.target.value)}
+ onBlur={autoSave.flush}
placeholder={t(($) => $.account.profile_description_placeholder)}
rows={5}
maxLength={MAX_PROFILE_DESCRIPTION_LEN}
- className="mt-1 resize-y"
+ aria-invalid={descriptionTooLong}
+ className="resize-y"
/>
- <div className="mt-1 flex items-start justify-between gap-3 text-xs text-muted-foreground">
- <span>{t(($) => $.account.profile_description_hint)}</span>
+ <div className="mt-1 flex justify-end text-xs text-muted-foreground">
<span
className={descriptionTooLong ? "text-destructive shrink-0" : "shrink-0"}
aria-live="polite"
@@ -117,19 +172,9 @@ export function AccountTab() {
</p>
) : null}
</div>
- <div className="flex items-center justify-end gap-2 pt-1">
- <Button
- size="sm"
- onClick={handleProfileSave}
- disabled={profileSaving || !profileName.trim() || descriptionTooLong}
- >
- <Save className="h-3 w-3" />
- {profileSaving ? t(($) => $.account.saving) : t(($) => $.account.save)}
- </Button>
- </div>
- </CardContent>
- </Card>
- </section>
- </div>
+ </SettingsRow>
+ </SettingsCard>
+ </SettingsSection>
+ </SettingsTab>
);
}
diff --git a/packages/views/settings/components/browser-notification-setting.tsx b/packages/views/settings/components/browser-notification-setting.tsx
index a57eba51d0..3c385615cb 100644
--- a/packages/views/settings/components/browser-notification-setting.tsx
+++ b/packages/views/settings/components/browser-notification-setting.tsx
@@ -8,9 +8,9 @@ import {
type WebNotificationPermission,
} from "@multica/core/platform";
import { Button } from "@multica/ui/components/ui/button";
-import { Card, CardContent } from "@multica/ui/components/ui/card";
import { isDesktopShell } from "../../platform";
import { useT } from "../../i18n";
+import { SettingsCard, SettingsRow } from "./settings-layout";
/**
* Web-only control for the browser permission that native notification banners
@@ -48,15 +48,11 @@ export function BrowserNotificationSetting() {
: t(($) => $.notifications.browser.hint);
return (
- <Card>
- <CardContent>
- <div className="flex items-center justify-between gap-4">
- <div className="space-y-0.5 pr-4">
- <p className="text-sm font-medium">
- {t(($) => $.notifications.browser.label)}
- </p>
- <p className="text-xs text-muted-foreground">{statusHint}</p>
- </div>
+ <SettingsCard>
+ <SettingsRow
+ label={t(($) => $.notifications.browser.label)}
+ description={statusHint}
+ >
{permission === "default" && (
<Button size="sm" variant="outline" onClick={handleEnable}>
{t(($) => $.notifications.browser.enable)}
@@ -67,8 +63,7 @@ export function BrowserNotificationSetting() {
{t(($) => $.notifications.browser.enabled_badge)}
</span>
)}
- </div>
- </CardContent>
- </Card>
+ </SettingsRow>
+ </SettingsCard>
);
}
diff --git a/packages/views/settings/components/chat-tab.tsx b/packages/views/settings/components/chat-tab.tsx
index 36cb58f475..a1e74d1730 100644
--- a/packages/views/settings/components/chat-tab.tsx
+++ b/packages/views/settings/components/chat-tab.tsx
@@ -3,6 +3,12 @@
import { Switch } from "@multica/ui/components/ui/switch";
import { useChatStore } from "@multica/core/chat";
import { useT } from "../../i18n";
+import {
+ SettingsCard,
+ SettingsRow,
+ SettingsSection,
+ SettingsTab,
+} from "./settings-layout";
/**
* Chat settings — its own tab under "My Account". Currently just the
@@ -17,19 +23,21 @@ export function ChatTab() {
const setEnabled = useChatStore((s) => s.setFloatingChatEnabled);
return (
- <div className="space-y-8">
- <section className="space-y-4">
- <h2 className="text-sm font-semibold">{t(($) => $.chat.floating_title)}</h2>
- <label className="flex items-center justify-between gap-4">
- <div className="space-y-0.5 pr-4">
- <p className="text-sm font-medium">{t(($) => $.chat.floating_label)}</p>
- <p className="text-xs text-muted-foreground">
- {t(($) => $.chat.floating_hint)}
- </p>
- </div>
- <Switch checked={enabled} onCheckedChange={setEnabled} />
- </label>
- </section>
- </div>
+ <SettingsTab title={t(($) => $.page.tabs.chat)}>
+ <SettingsSection title={t(($) => $.chat.floating_title)}>
+ <SettingsCard>
+ <SettingsRow
+ label={t(($) => $.chat.floating_label)}
+ description={t(($) => $.chat.floating_hint)}
+ >
+ <Switch
+ checked={enabled}
+ onCheckedChange={setEnabled}
+ aria-label={t(($) => $.chat.floating_label)}
+ />
+ </SettingsRow>
+ </SettingsCard>
+ </SettingsSection>
+ </SettingsTab>
);
}
diff --git a/packages/views/settings/components/github-tab.tsx b/packages/views/settings/components/github-tab.tsx
index 51487163b2..b7a0ed3272 100644
--- a/packages/views/settings/components/github-tab.tsx
+++ b/packages/views/settings/components/github-tab.tsx
@@ -30,6 +30,7 @@ import { api } from "@multica/core/api";
import type { Workspace } from "@multica/core/types";
import { useNavigation } from "../../navigation";
import { useT } from "../../i18n";
+import { SettingsTab } from "./settings-layout";
import { GitHubMark } from "./github-mark";
type SettingsKey =
@@ -125,13 +126,10 @@ export function GitHubTab() {
const repositoriesHref = `${navigation.pathname}?tab=repositories`;
return (
- <div className="space-y-8">
- <section className="space-y-1">
- <p className="text-sm text-muted-foreground">
- {t(($) => $.github.page_description)}
- </p>
- </section>
-
+ <SettingsTab
+ title={t(($) => $.page.tabs.github)}
+ description={t(($) => $.github.page_description)}
+ >
<section className="space-y-3">
<Card>
<CardContent>
@@ -255,8 +253,8 @@ export function GitHubTab() {
<section className="space-y-3">
<h2 className="text-sm font-semibold">{t(($) => $.github.section_features)}</h2>
- <Card>
- <CardContent className="space-y-4">
+ <Card className="gap-0 py-0">
+ <CardContent className="divide-y divide-surface-border px-0">
<FeatureRow
id="github-pr-sidebar"
icon={<PanelRight className="h-4 w-4" />}
@@ -354,7 +352,7 @@ export function GitHubTab() {
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
- </div>
+ </SettingsTab>
);
}
@@ -376,7 +374,7 @@ function FeatureRow({
onCheckedChange: (v: boolean) => void;
}) {
return (
- <div className="flex items-start justify-between gap-4">
+ <div className="flex items-start justify-between gap-4 px-4 py-3.5">
<div className="flex items-start gap-3">
<div className="rounded-md border bg-muted/50 p-2 text-muted-foreground">{icon}</div>
<div className="space-y-1">
diff --git a/packages/views/settings/components/integrations-tab.tsx b/packages/views/settings/components/integrations-tab.tsx
index affcf0b1db..ac338b5d62 100644
--- a/packages/views/settings/components/integrations-tab.tsx
+++ b/packages/views/settings/components/integrations-tab.tsx
@@ -9,6 +9,7 @@ import { composioToolkitsOptions } from "@multica/core/composio";
import { useFeatureEnabled } from "@multica/core/config";
import { COMPOSIO_MCP_APPS_FLAG } from "@multica/core/feature-flags";
import { useT } from "../../i18n";
+import { SettingsSection, SettingsTab } from "./settings-layout";
// Integrations is the umbrella tab for third-party platform connections.
// GitHub has its own top-level tab (see github-tab.tsx); everything else
@@ -31,21 +32,18 @@ export function IntegrationsTab() {
composioToolkits.error instanceof ApiError && composioToolkits.error.status === 503;
return (
- <div className="space-y-10">
- <section className="space-y-4">
- <h2 className="text-sm font-semibold">{t(($) => $.lark.section_title)}</h2>
+ <SettingsTab title={t(($) => $.page.tabs.integrations)}>
+ <SettingsSection title={t(($) => $.lark.section_title)}>
<LarkTab />
- </section>
+ </SettingsSection>
{composioEnabled && !composioUnconfigured && (
- <section className="space-y-4">
- <h2 className="text-sm font-semibold">{t(($) => $.composio.section_title)}</h2>
+ <SettingsSection title={t(($) => $.composio.section_title)}>
<ComposioTab />
- </section>
+ </SettingsSection>
)}
- <section className="space-y-4">
- <h2 className="text-sm font-semibold">{t(($) => $.slack.section_title)}</h2>
+ <SettingsSection title={t(($) => $.slack.section_title)}>
<SlackTab />
- </section>
- </div>
+ </SettingsSection>
+ </SettingsTab>
);
}
diff --git a/packages/views/settings/components/labs-tab.tsx b/packages/views/settings/components/labs-tab.tsx
index 0b0b0028a2..23025e2772 100644
--- a/packages/views/settings/components/labs-tab.tsx
+++ b/packages/views/settings/components/labs-tab.tsx
@@ -9,6 +9,7 @@ import {
EmptyTitle,
} from "@multica/ui/components/ui/empty";
import { useT } from "../../i18n";
+import { SettingsCard, SettingsTab } from "./settings-layout";
// The Co-authored-by trailer toggle moved into the dedicated GitHub Settings
// tab (see github-tab.tsx). Labs is kept as a container for future
@@ -16,18 +17,20 @@ import { useT } from "../../i18n";
export function LabsTab() {
const { t } = useT("settings");
return (
- <div className="space-y-4">
- <Empty>
- <EmptyHeader>
- <EmptyMedia variant="icon">
- <FlaskConical className="h-4 w-4" />
- </EmptyMedia>
- <EmptyTitle>{t(($) => $.labs.section_placeholder_title)}</EmptyTitle>
- <EmptyDescription>
- {t(($) => $.labs.section_placeholder_description)}
- </EmptyDescription>
- </EmptyHeader>
- </Empty>
- </div>
+ <SettingsTab title={t(($) => $.page.tabs.labs)}>
+ <SettingsCard>
+ <Empty>
+ <EmptyHeader>
+ <EmptyMedia variant="icon">
+ <FlaskConical className="h-4 w-4" />
+ </EmptyMedia>
+ <EmptyTitle>{t(($) => $.labs.section_placeholder_title)}</EmptyTitle>
+ <EmptyDescription>
+ {t(($) => $.labs.section_placeholder_description)}
+ </EmptyDescription>
+ </EmptyHeader>
+ </Empty>
+ </SettingsCard>
+ </SettingsTab>
);
}
diff --git a/packages/views/settings/components/members-tab.tsx b/packages/views/settings/components/members-tab.tsx
index f7d57425cd..c7232f0bbf 100644
--- a/packages/views/settings/components/members-tab.tsx
+++ b/packages/views/settings/components/members-tab.tsx
@@ -1,7 +1,7 @@
"use client";
import { useState } from "react";
-import { Crown, Shield, User, Plus, MoreHorizontal, UserMinus, Users, Clock, X, Mail } from "lucide-react";
+import { Crown, Shield, User, Plus, MoreHorizontal, UserMinus, Clock, X, Mail } from "lucide-react";
import { ActorAvatar } from "../../common/actor-avatar";
import type { MemberWithUser, MemberRole, Invitation } from "@multica/core/types";
import { Input } from "@multica/ui/components/ui/input";
@@ -43,6 +43,7 @@ import { useCurrentWorkspace } from "@multica/core/paths";
import { memberListOptions, invitationListOptions, workspaceKeys } from "@multica/core/workspace/queries";
import { api } from "@multica/core/api";
import { useT } from "../../i18n";
+import { SettingsCard, SettingsSection, SettingsTab } from "./settings-layout";
const ROLE_ICONS: Record<MemberRole, typeof Crown> = {
owner: Crown,
@@ -331,12 +332,8 @@ export function MembersTab() {
if (!workspace) return null;
return (
- <div className="space-y-8">
- <section className="space-y-4">
- <div className="flex items-center gap-2">
- <Users className="h-4 w-4 text-muted-foreground" />
- <h2 className="text-sm font-semibold">{t(($) => $.members.section_title, { count: members.length })}</h2>
- </div>
+ <SettingsTab title={t(($) => $.page.tabs.members)}>
+ <SettingsSection title={t(($) => $.members.section_title, { count: members.length })}>
{canManageWorkspace && (
<Card>
@@ -348,6 +345,10 @@ export function MembersTab() {
<div className="grid gap-3 sm:grid-cols-[1fr_120px_auto]">
<Input
type="email"
+ name="invite-email"
+ autoComplete="email"
+ spellCheck={false}
+ aria-label={t(($) => $.members.invite_email_placeholder)}
value={inviteEmail}
onChange={(e) => setInviteEmail(e.target.value)}
placeholder={t(($) => $.members.invite_email_placeholder)}
@@ -376,9 +377,9 @@ export function MembersTab() {
)}
{members.length > 0 ? (
- <div className="overflow-hidden rounded-xl ring-1 ring-foreground/10">
- {members.map((m, i) => (
- <div key={m.id} className={i > 0 ? "border-t border-border/50" : ""}>
+ <SettingsCard>
+ {members.map((m) => (
+ <div key={m.id}>
<MemberRow
member={m}
canManage={canManageWorkspace}
@@ -391,21 +392,17 @@ export function MembersTab() {
/>
</div>
))}
- </div>
+ </SettingsCard>
) : (
<p className="text-sm text-muted-foreground">{t(($) => $.members.no_members)}</p>
)}
- </section>
+ </SettingsSection>
{invitations.length > 0 && (
- <section className="space-y-4">
- <div className="flex items-center gap-2">
- <Clock className="h-4 w-4 text-muted-foreground" />
- <h2 className="text-sm font-semibold">{t(($) => $.members.pending_title, { count: invitations.length })}</h2>
- </div>
- <div className="overflow-hidden rounded-xl ring-1 ring-foreground/10">
- {invitations.map((inv, i) => (
- <div key={inv.id} className={i > 0 ? "border-t border-border/50" : ""}>
+ <SettingsSection title={t(($) => $.members.pending_title, { count: invitations.length })}>
+ <SettingsCard>
+ {invitations.map((inv) => (
+ <div key={inv.id}>
<InvitationRow
invitation={inv}
canManage={canManageWorkspace}
@@ -414,8 +411,8 @@ export function MembersTab() {
/>
</div>
))}
- </div>
- </section>
+ </SettingsCard>
+ </SettingsSection>
)}
<AlertDialog open={!!confirmAction} onOpenChange={(v) => { if (!v) setConfirmAction(null); }}>
@@ -438,6 +435,6 @@ export function MembersTab() {
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
- </div>
+ </SettingsTab>
);
}
diff --git a/packages/views/settings/components/notifications-tab.tsx b/packages/views/settings/components/notifications-tab.tsx
index e6ecb11aea..87ddce6d33 100644
--- a/packages/views/settings/components/notifications-tab.tsx
+++ b/packages/views/settings/components/notifications-tab.tsx
@@ -5,11 +5,16 @@ import { useWorkspaceId } from "@multica/core/hooks";
import { notificationPreferenceOptions } from "@multica/core/notification-preferences/queries";
import { useUpdateNotificationPreferences } from "@multica/core/notification-preferences/mutations";
import type { NotificationGroupKey, NotificationPreferences } from "@multica/core/types";
-import { Card, CardContent } from "@multica/ui/components/ui/card";
import { Switch } from "@multica/ui/components/ui/switch";
import { toast } from "sonner";
import { useT } from "../../i18n";
import { BrowserNotificationSetting } from "./browser-notification-setting";
+import {
+ SettingsCard,
+ SettingsRow,
+ SettingsSection,
+ SettingsTab,
+} from "./settings-layout";
// Inbox event groups rendered in the per-event toggle list. `system_notifications`
// is a sibling preference key but lives in its own section below.
@@ -52,70 +57,52 @@ export function NotificationsTab() {
const systemEnabled = preferences.system_notifications !== "muted";
return (
- <div className="space-y-8">
- <section className="space-y-4">
- <div>
- <h2 className="text-sm font-semibold">{t(($) => $.notifications.title)}</h2>
- <p className="text-sm text-muted-foreground mt-1">
- {t(($) => $.notifications.description)}
- </p>
- </div>
-
- <Card>
- <CardContent className="divide-y">
+ <SettingsTab title={t(($) => $.page.tabs.notifications)}>
+ <SettingsSection
+ title={t(($) => $.notifications.title)}
+ description={t(($) => $.notifications.description)}
+ >
+ <SettingsCard>
{INBOX_GROUP_KEYS.map((key: InboxGroupKey) => {
const enabled = preferences[key] !== "muted";
return (
- <div
+ <SettingsRow
key={key}
- className="flex items-center justify-between py-3 first:pt-0 last:pb-0"
+ label={t(($) => $.notifications.groups[key].label)}
+ description={t(($) => $.notifications.groups[key].description)}
>
- <div className="space-y-0.5 pr-4">
- <p className="text-sm font-medium">{t(($) => $.notifications.groups[key].label)}</p>
- <p className="text-xs text-muted-foreground">
- {t(($) => $.notifications.groups[key].description)}
- </p>
- </div>
<Switch
checked={enabled}
+ aria-label={t(($) => $.notifications.groups[key].label)}
onCheckedChange={(checked) => handleToggle(key, checked)}
/>
- </div>
+ </SettingsRow>
);
})}
- </CardContent>
- </Card>
- </section>
-
- <section className="space-y-4">
- <div>
- <h2 className="text-sm font-semibold">{t(($) => $.notifications.system.title)}</h2>
- <p className="text-sm text-muted-foreground mt-1">
- {t(($) => $.notifications.system.description)}
- </p>
- </div>
+ </SettingsCard>
+ </SettingsSection>
- <Card>
- <CardContent>
- <div className="flex items-center justify-between">
- <div className="space-y-0.5 pr-4">
- <p className="text-sm font-medium">{t(($) => $.notifications.system.label)}</p>
- <p className="text-xs text-muted-foreground">
- {t(($) => $.notifications.system.hint)}
- </p>
- </div>
+ <SettingsSection
+ title={t(($) => $.notifications.system.title)}
+ description={t(($) => $.notifications.system.description)}
+ >
+ <SettingsCard>
+ <SettingsRow
+ label={t(($) => $.notifications.system.label)}
+ description={t(($) => $.notifications.system.hint)}
+ >
<Switch
checked={systemEnabled}
+ aria-label={t(($) => $.notifications.system.label)}
onCheckedChange={(checked) => handleToggle("system_notifications", checked)}
/>
- </div>
- </CardContent>
- </Card>
+ </SettingsRow>
+ </SettingsCard>
{/* Web-only: the browser permission banners require. Renders nothing on
desktop (OS-native delivery) or where the Notification API is absent. */}
<BrowserNotificationSetting />
- </section>
- </div>
+ </SettingsSection>
+ </SettingsTab>
);
}
diff --git a/packages/views/settings/components/preferences-tab.test.tsx b/packages/views/settings/components/preferences-tab.test.tsx
index fbf686167b..d2e28e069c 100644
--- a/packages/views/settings/components/preferences-tab.test.tsx
+++ b/packages/views/settings/components/preferences-tab.test.tsx
@@ -95,11 +95,19 @@ describe("PreferencesTab — Language switcher", () => {
vi.useRealTimers();
});
+ async function pickLanguage(
+ user: ReturnType<typeof userEvent.setup>,
+ name: string,
+ ) {
+ await user.click(screen.getByRole("combobox", { name: "Language" }));
+ await user.click(await screen.findByRole("option", { name }));
+ }
+
it("does nothing when clicking the current locale", async () => {
const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime });
render(<PreferencesTab />, { wrapper: I18nWrapper });
- await user.click(screen.getByRole("radio", { name: "English" }));
+ await pickLanguage(user, "English");
expect(mockPersist).not.toHaveBeenCalled();
expect(mockUpdateMe).not.toHaveBeenCalled();
@@ -110,7 +118,7 @@ describe("PreferencesTab — Language switcher", () => {
const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime });
render(<PreferencesTab />, { wrapper: I18nWrapper });
- await user.click(screen.getByRole("radio", { name: "한국어" }));
+ await pickLanguage(user, "한국어");
expect(mockPersist).toHaveBeenCalledWith("ko");
expect(mockUpdateMe).not.toHaveBeenCalled();
@@ -122,7 +130,7 @@ describe("PreferencesTab — Language switcher", () => {
const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime });
render(<PreferencesTab />, { wrapper: I18nWrapper });
- await user.click(screen.getByRole("radio", { name: "日本語" }));
+ await pickLanguage(user, "日本語");
expect(mockPersist).toHaveBeenCalledWith("ja");
expect(mockUpdateMe).not.toHaveBeenCalled();
@@ -136,7 +144,7 @@ describe("PreferencesTab — Language switcher", () => {
const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime });
render(<PreferencesTab />, { wrapper: I18nWrapper });
- await user.click(screen.getByRole("radio", { name: "中文" }));
+ await pickLanguage(user, "中文");
expect(mockPersist).toHaveBeenCalledWith("zh-Hans");
expect(mockUpdateMe).toHaveBeenCalledWith({ language: "zh-Hans" });
@@ -150,7 +158,7 @@ describe("PreferencesTab — Language switcher", () => {
const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime });
render(<PreferencesTab />, { wrapper: I18nWrapper });
- await user.click(screen.getByRole("radio", { name: "中文" }));
+ await pickLanguage(user, "中文");
// Local persist still happened so the reload below sees the new locale.
expect(mockPersist).toHaveBeenCalledWith("zh-Hans");
@@ -187,7 +195,7 @@ describe("PreferencesTab — Timezone section", () => {
user: ReturnType<typeof userEvent.setup>,
name: RegExp | string,
) {
- await user.click(screen.getByRole("combobox"));
+ await user.click(screen.getByRole("combobox", { name: "Viewing Timezone" }));
await user.click(await screen.findByRole("option", { name }));
}
@@ -195,7 +203,9 @@ describe("PreferencesTab — Timezone section", () => {
userRef.current = { id: "user-1", timezone: "Asia/Shanghai" };
render(<PreferencesTab />, { wrapper: I18nWrapper });
- expect(screen.getByRole("combobox").textContent).toContain("Asia/Shanghai");
+ expect(
+ screen.getByRole("combobox", { name: "Viewing Timezone" }).textContent,
+ ).toContain("Asia/Shanghai");
});
// handleChange PATCHes then updates the store asynchronously, so the
diff --git a/packages/views/settings/components/preferences-tab.tsx b/packages/views/settings/components/preferences-tab.tsx
index 18e7b428ed..70410e1479 100644
--- a/packages/views/settings/components/preferences-tab.tsx
+++ b/packages/views/settings/components/preferences-tab.tsx
@@ -10,7 +10,6 @@ import {
SelectValue,
} from "@multica/ui/components/ui/select";
import { useTheme } from "@multica/ui/components/common/theme-provider";
-import { cn } from "@multica/ui/lib/utils";
import {
DEFAULT_LOCALE,
SUPPORTED_LOCALES,
@@ -21,81 +20,12 @@ import { useAuthStore } from "@multica/core/auth";
import { api } from "@multica/core/api";
import { browserTimezone, timezoneOptions } from "../../common/timezone-select";
import { useT } from "../../i18n";
-
-const LIGHT_COLORS = {
- titleBar: "#e8e8e8",
- content: "#ffffff",
- sidebar: "#f4f4f5",
- bar: "#e4e4e7",
- barMuted: "#d4d4d8",
-};
-
-const DARK_COLORS = {
- titleBar: "#333338",
- content: "#27272a",
- sidebar: "#1e1e21",
- bar: "#3f3f46",
- barMuted: "#52525b",
-};
-
-function WindowMockup({
- variant,
- className,
-}: {
- variant: "light" | "dark";
- className?: string;
-}) {
- const colors = variant === "light" ? LIGHT_COLORS : DARK_COLORS;
-
- return (
- <div className={cn("flex h-full w-full flex-col", className)}>
- {/* Title bar */}
- <div
- className="flex items-center gap-[3px] px-2 py-1.5"
- style={{ backgroundColor: colors.titleBar }}
- >
- <span className="size-[6px] rounded-full bg-[#ff5f57]" />
- <span className="size-[6px] rounded-full bg-[#febc2e]" />
- <span className="size-[6px] rounded-full bg-[#28c840]" />
- </div>
- {/* Content area */}
- <div
- className="flex flex-1"
- style={{ backgroundColor: colors.content }}
- >
- {/* Sidebar */}
- <div
- className="w-[30%] space-y-1 p-2"
- style={{ backgroundColor: colors.sidebar }}
- >
- <div
- className="h-1 w-3/4 rounded-full"
- style={{ backgroundColor: colors.bar }}
- />
- <div
- className="h-1 w-1/2 rounded-full"
- style={{ backgroundColor: colors.bar }}
- />
- </div>
- {/* Main */}
- <div className="flex-1 space-y-1.5 p-2">
- <div
- className="h-1.5 w-4/5 rounded-full"
- style={{ backgroundColor: colors.bar }}
- />
- <div
- className="h-1 w-full rounded-full"
- style={{ backgroundColor: colors.barMuted }}
- />
- <div
- className="h-1 w-3/5 rounded-full"
- style={{ backgroundColor: colors.barMuted }}
- />
- </div>
- </div>
- </div>
- );
-}
+import {
+ SettingsCard,
+ SettingsRow,
+ SettingsSection,
+ SettingsTab,
+} from "./settings-layout";
export function PreferencesTab() {
const { theme, setTheme } = useTheme();
@@ -157,92 +87,71 @@ export function PreferencesTab() {
};
return (
- <div className="space-y-8">
- <section className="space-y-4">
- <h2 className="text-sm font-semibold">
- {t(($) => $.preferences.theme.title)}
- </h2>
- <div className="flex gap-6" role="radiogroup">
- {themeOptions.map((opt) => {
- const active = theme === opt.value;
- return (
- <button
- type="button"
- key={opt.value}
- role="radio"
- aria-checked={active}
- onClick={() => setTheme(opt.value)}
- className="group flex flex-col items-center gap-2 rounded-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/70 focus-visible:ring-offset-2 focus-visible:ring-offset-page-canvas"
+ <SettingsTab title={t(($) => $.page.tabs.preferences)}>
+ <SettingsSection title={t(($) => $.preferences.general_title)}>
+ <SettingsCard>
+ <SettingsRow
+ label={t(($) => $.preferences.theme.title)}
+ controlClassName="sm:w-48"
+ >
+ <Select
+ value={theme}
+ onValueChange={(next) => {
+ if (next) setTheme(next as (typeof themeOptions)[number]["value"]);
+ }}
+ >
+ <SelectTrigger
+ size="sm"
+ className="w-full"
+ aria-label={t(($) => $.preferences.theme.title)}
>
- <div
- className={cn(
- "aspect-[4/3] w-36 overflow-hidden rounded-lg ring-1 transition-shadow",
- active
- ? "ring-2 ring-brand"
- : "ring-surface-border group-hover:ring-2 group-hover:ring-surface-border"
- )}
- >
- {opt.value === "system" ? (
- <div className="relative h-full w-full">
- <WindowMockup
- variant="light"
- className="absolute inset-0"
- />
- <WindowMockup
- variant="dark"
- className="absolute inset-0 [clip-path:inset(0_0_0_50%)]"
- />
- </div>
- ) : (
- <WindowMockup variant={opt.value} />
- )}
- </div>
- <span
- className={cn(
- "text-sm transition-colors",
- active
- ? "font-medium text-foreground"
- : "text-muted-foreground"
- )}
- >
- {opt.label}
- </span>
- </button>
- );
- })}
- </div>
- </section>
-
- <section className="space-y-4">
- <h2 className="text-sm font-semibold">
- {t(($) => $.preferences.language.title)}
- </h2>
- <div className="flex gap-3" role="radiogroup">
- {languageOptions.map((opt) => {
- const active = currentLocale === opt.value;
- return (
- <button
- type="button"
- key={opt.value}
- role="radio"
- aria-checked={active}
- onClick={() => handleLanguageChange(opt.value)}
- className={cn(
- "rounded-md border px-4 py-2 text-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/70 focus-visible:ring-offset-2 focus-visible:ring-offset-page-canvas",
- active
- ? "border-brand/50 bg-surface-selected font-medium text-foreground"
- : "border-surface-border text-muted-foreground hover:border-foreground/30 hover:bg-surface-hover"
- )}
+ <SelectValue>
+ {themeOptions.find((option) => option.value === theme)?.label}
+ </SelectValue>
+ </SelectTrigger>
+ <SelectContent align="end">
+ {themeOptions.map((option) => (
+ <SelectItem key={option.value} value={option.value}>
+ {option.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </SettingsRow>
+
+ <SettingsRow
+ label={t(($) => $.preferences.language.title)}
+ controlClassName="sm:w-48"
+ >
+ <Select
+ value={currentLocale}
+ onValueChange={(next) => {
+ if (next) void handleLanguageChange(next as SupportedLocale);
+ }}
+ >
+ <SelectTrigger
+ size="sm"
+ className="w-full"
+ aria-label={t(($) => $.preferences.language.title)}
>
- {opt.label}
- </button>
- );
- })}
- </div>
- </section>
-
- <TimezoneSection />
- </div>
+ <SelectValue>
+ {languageOptions.find((option) => option.value === currentLocale)?.label}
+ </SelectValue>
+ </SelectTrigger>
+ <SelectContent align="end">
+ {languageOptions.map((option) => (
+ <SelectItem key={option.value} value={option.value}>
+ {option.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </SettingsRow>
+
+ <TimezoneRow />
+ </SettingsCard>
+ </SettingsSection>
+ </SettingsTab>
);
}
@@ -250,7 +159,7 @@ export function PreferencesTab() {
// state through this sentinel and translate at the wire boundary.
const BROWSER_TZ_VALUE = "__browser__";
-function TimezoneSection() {
+function TimezoneRow() {
const { t } = useT("settings");
const user = useAuthStore((s) => s.user);
const setUser = useAuthStore((s) => s.setUser);
@@ -289,33 +198,35 @@ function TimezoneSection() {
};
return (
- <section className="space-y-2">
- <h2 className="text-sm font-semibold">
- {t(($) => $.preferences.timezone.title)}
- </h2>
+ <SettingsRow
+ label={t(($) => $.preferences.timezone.title)}
+ description={t(($) => $.preferences.timezone.hint)}
+ controlClassName="sm:w-72"
+ >
<Select
value={value}
onValueChange={(next) => {
- if (next) handleChange(next);
+ if (next) void handleChange(next);
}}
>
- <SelectTrigger size="sm" className="w-72 rounded-md font-mono text-xs">
+ <SelectTrigger
+ size="sm"
+ className="w-full font-mono text-xs"
+ aria-label={t(($) => $.preferences.timezone.title)}
+ >
<SelectValue>{formatTZLabel(value)}</SelectValue>
</SelectTrigger>
- <SelectContent align="start" className="max-h-72">
+ <SelectContent align="end" className="max-h-72">
<SelectItem value={BROWSER_TZ_VALUE} className="font-mono text-xs">
{formatTZLabel(BROWSER_TZ_VALUE)}
</SelectItem>
- {options.map((tz) => (
- <SelectItem key={tz} value={tz} className="font-mono text-xs">
- {formatTZLabel(tz)}
+ {options.map((timezone) => (
+ <SelectItem key={timezone} value={timezone} className="font-mono text-xs">
+ {formatTZLabel(timezone)}
</SelectItem>
))}
</SelectContent>
</Select>
- <p className="text-[11px] leading-snug text-muted-foreground">
- {t(($) => $.preferences.timezone.hint)}
- </p>
- </section>
+ </SettingsRow>
);
}
diff --git a/packages/views/settings/components/repositories-tab.test.tsx b/packages/views/settings/components/repositories-tab.test.tsx
index e77867b468..d86b7a9860 100644
--- a/packages/views/settings/components/repositories-tab.test.tsx
+++ b/packages/views/settings/components/repositories-tab.test.tsx
@@ -1,5 +1,5 @@
import type { ReactNode } from "react";
-import { describe, it, expect, beforeEach, vi } from "vitest";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { I18nProvider } from "@multica/core/i18n/react";
@@ -12,11 +12,14 @@ const workspaceRef = vi.hoisted(() => ({
id: "workspace-1",
name: "Test Workspace",
slug: "test-workspace",
- repos: [{ url: "https://github.com/multica-ai/multica" }] as { url: string; description?: string }[],
+ repos: [{ url: "https://github.com/multica-ai/multica" }] as {
+ url: string;
+ description?: string;
+ }[],
},
}));
const membersRef = vi.hoisted(() => ({
- current: [{ user_id: "user-1", role: "owner" as const }],
+ current: [{ user_id: "user-1", role: "owner" as "owner" | "admin" | "member" }],
}));
vi.mock("@tanstack/react-query", () => ({
@@ -43,8 +46,8 @@ vi.mock("@multica/core/api", () => ({
vi.mock("@multica/core/auth", () => {
const useAuthStore = Object.assign(
- (sel?: (s: { user: { id: string } }) => unknown) =>
- sel ? sel({ user: { id: "user-1" } }) : { user: { id: "user-1" } },
+ (selector?: (state: { user: { id: string } }) => unknown) =>
+ selector ? selector({ user: { id: "user-1" } }) : { user: { id: "user-1" } },
{ getState: () => ({ user: { id: "user-1" } }) },
);
return { useAuthStore };
@@ -68,9 +71,10 @@ function I18nWrapper({ children }: { children: ReactNode }) {
);
}
-describe("RepositoriesTab — view/edit toggle", () => {
+describe("RepositoriesTab — automatic updates", () => {
beforeEach(() => {
vi.clearAllMocks();
+ vi.useFakeTimers({ shouldAdvanceTime: true });
workspaceRef.current = {
id: "workspace-1",
name: "Test Workspace",
@@ -78,147 +82,108 @@ describe("RepositoriesTab — view/edit toggle", () => {
repos: [{ url: "https://github.com/multica-ai/multica" }],
};
membersRef.current = [{ user_id: "user-1", role: "owner" }];
+ mockUpdateWorkspace.mockImplementation(
+ async (_id: string, payload: { repos: { url: string; description?: string }[] }) => ({
+ ...workspaceRef.current,
+ repos: payload.repos,
+ }),
+ );
});
- it("renders persisted repos in display mode (no input)", () => {
- render(<RepositoriesTab />, { wrapper: I18nWrapper });
- expect(screen.queryByRole("textbox")).toBeNull();
- expect(screen.getByText("https://github.com/multica-ai/multica")).toBeTruthy();
+ afterEach(() => {
+ vi.useRealTimers();
});
- it("Save button is disabled when clean", () => {
- render(<RepositoriesTab />, { wrapper: I18nWrapper });
- expect(screen.getByRole("button", { name: /^Save$/ })).toBeDisabled();
- });
+ function setupUser() {
+ return userEvent.setup({ advanceTimers: vi.advanceTimersByTime });
+ }
- it("clicking Edit reveals an input pre-filled with the URL", async () => {
- const user = userEvent.setup();
+ it("renders persisted repositories as the same shared input controls used for editing", () => {
render(<RepositoriesTab />, { wrapper: I18nWrapper });
- await user.click(screen.getByRole("button", { name: "Edit repository" }));
-
const inputs = screen.getAllByRole("textbox") as HTMLInputElement[];
+ expect(inputs).toHaveLength(2);
expect(inputs[0]!.value).toBe("https://github.com/multica-ai/multica");
+ expect(screen.queryByRole("button", { name: /^Save$/ })).toBeNull();
});
- it("Save re-enables after editing, then returns to display mode + disabled on success", async () => {
- const user = userEvent.setup();
- mockUpdateWorkspace.mockImplementation(async (_id: string, payload: { repos: { url: string; description?: string }[] }) => ({
- ...workspaceRef.current,
- repos: payload.repos,
- }));
-
+ it("updates a changed URL automatically on blur", async () => {
+ const user = setupUser();
render(<RepositoriesTab />, { wrapper: I18nWrapper });
- await user.click(screen.getByRole("button", { name: "Edit repository" }));
- const input = screen.getAllByRole("textbox")[0]!;
- await user.clear(input);
- await user.type(input, "https://github.com/multica-ai/edited");
-
- const saveBtn = screen.getByRole("button", { name: /^Save$/ });
- expect(saveBtn).not.toBeDisabled();
-
- // Simulate the workspace cache resync that the parent provider does
- // after a successful save — `setQueryData` updates the cache and the
- // useCurrentWorkspace hook would yield the new value on the next render.
- mockUpdateWorkspace.mockImplementationOnce(async (_id: string, payload: { repos: { url: string; description?: string }[] }) => {
- workspaceRef.current = { ...workspaceRef.current, repos: payload.repos };
- return workspaceRef.current;
- });
-
- await user.click(saveBtn);
+ const urlInput = screen.getAllByRole("textbox")[0]!;
+ await user.clear(urlInput);
+ await user.type(urlInput, "https://github.com/multica-ai/edited");
+ await user.tab();
await waitFor(() => {
- expect(mockUpdateWorkspace).toHaveBeenCalled();
- });
-
- // After successful save, edit mode is cleared — input gone, Save disabled.
- await waitFor(() => {
- expect(screen.queryByRole("textbox")).toBeNull();
+ expect(mockUpdateWorkspace).toHaveBeenCalledWith("workspace-1", {
+ repos: [{ url: "https://github.com/multica-ai/edited" }],
+ });
});
- expect(screen.getByRole("button", { name: /^Save$/ })).toBeDisabled();
});
- it("newly added rows start in edit mode", async () => {
- const user = userEvent.setup();
+ it("debounces updates while the user is still typing", async () => {
+ const user = setupUser();
render(<RepositoriesTab />, { wrapper: I18nWrapper });
- expect(screen.queryByRole("textbox")).toBeNull();
- await user.click(screen.getByRole("button", { name: /Add repository/ }));
+ const urlInput = screen.getAllByRole("textbox")[0]!;
+ await user.type(urlInput, "-next");
+ expect(mockUpdateWorkspace).not.toHaveBeenCalled();
- expect(screen.getAllByRole("textbox").length).toBe(2); // url + description
- expect(screen.getByRole("button", { name: /^Save$/ })).not.toBeDisabled();
+ vi.advanceTimersByTime(650);
+ await waitFor(() => expect(mockUpdateWorkspace).toHaveBeenCalledTimes(1));
});
- it("Edit clean row → Cancel returns to display mode without changing URL or dirtying Save", async () => {
- const user = userEvent.setup();
+ it("does not persist a new row until its URL is non-empty", async () => {
+ const user = setupUser();
render(<RepositoriesTab />, { wrapper: I18nWrapper });
- await user.click(screen.getByRole("button", { name: "Edit repository" }));
- expect(screen.getAllByRole("textbox").length).toBe(2);
-
- await user.click(screen.getByRole("button", { name: "Cancel edit" }));
-
- expect(screen.queryByRole("textbox")).toBeNull();
- expect(screen.getByText("https://github.com/multica-ai/multica")).toBeTruthy();
- expect(screen.getByRole("button", { name: /^Save$/ })).toBeDisabled();
+ await user.click(screen.getByRole("button", { name: /Add repository/ }));
+ expect(screen.getAllByRole("textbox")).toHaveLength(4);
+ vi.advanceTimersByTime(1000);
expect(mockUpdateWorkspace).not.toHaveBeenCalled();
- });
- it("Cancel on a dirty edited row reverts the URL and exits edit mode", async () => {
- const user = userEvent.setup();
- render(<RepositoriesTab />, { wrapper: I18nWrapper });
+ const newUrlInput = screen.getAllByRole("textbox")[2]!;
+ await user.type(newUrlInput, "[email protected]:multica-ai/second.git");
+ await user.tab();
- await user.click(screen.getByRole("button", { name: "Edit repository" }));
- const input = screen.getAllByRole("textbox")[0] as HTMLInputElement;
- await user.clear(input);
- await user.type(input, "https://github.com/multica-ai/changed");
- expect(screen.getByRole("button", { name: /^Save$/ })).not.toBeDisabled();
-
- await user.click(screen.getByRole("button", { name: "Cancel edit" }));
-
- expect(screen.queryByRole("textbox")).toBeNull();
- expect(screen.getByText("https://github.com/multica-ai/multica")).toBeTruthy();
- expect(screen.getByRole("button", { name: /^Save$/ })).toBeDisabled();
+ await waitFor(() => {
+ expect(mockUpdateWorkspace).toHaveBeenCalledWith("workspace-1", {
+ repos: [
+ { url: "https://github.com/multica-ai/multica" },
+ { url: "[email protected]:multica-ai/second.git" },
+ ],
+ });
+ });
});
- it("Cancel on a newly added (never saved) row removes the row entirely", async () => {
- const user = userEvent.setup();
+ it("persists deletion immediately without a separate save action", async () => {
+ const user = setupUser();
render(<RepositoriesTab />, { wrapper: I18nWrapper });
- await user.click(screen.getByRole("button", { name: /Add repository/ }));
- expect(screen.getAllByRole("textbox").length).toBe(2);
-
- await user.click(screen.getByRole("button", { name: "Cancel edit" }));
+ await user.click(screen.getByRole("button", { name: "Delete repository" }));
+ expect(mockUpdateWorkspace).not.toHaveBeenCalled();
+ await user.click(
+ screen.getByRole("button", { name: "Delete repository" }),
+ );
- expect(screen.queryByRole("textbox")).toBeNull();
- // Original persisted row is still there; the new empty row is gone.
- expect(screen.getByText("https://github.com/multica-ai/multica")).toBeTruthy();
- expect(screen.getByRole("button", { name: /^Save$/ })).toBeDisabled();
+ await waitFor(() => {
+ expect(mockUpdateWorkspace).toHaveBeenCalledWith("workspace-1", { repos: [] });
+ });
+ expect(screen.getByText("No repositories yet.")).toBeTruthy();
});
- it("accepts scp-like shorthand without browser URL validation blocking submit", async () => {
- const user = userEvent.setup();
- mockUpdateWorkspace.mockImplementation(
- async (_id: string, payload: { repos: { url: string; description?: string }[] }) => {
- workspaceRef.current = { ...workspaceRef.current, repos: payload.repos };
- return workspaceRef.current;
- },
- );
-
+ it("accepts scp-like repository shorthand", async () => {
+ const user = setupUser();
render(<RepositoriesTab />, { wrapper: I18nWrapper });
- await user.click(screen.getByRole("button", { name: "Edit repository" }));
- const input = screen.getAllByRole("textbox")[0] as HTMLInputElement;
- await user.clear(input);
- await user.type(input, "[email protected]:multica-ai/multica.git");
-
- // type="text" (not "url") so the browser does not run native URL
- // validation; the value reaches the server which has the real check.
- expect(input.type).toBe("text");
- expect(input.validity.valid).toBe(true);
-
- await user.click(screen.getByRole("button", { name: /^Save$/ }));
+ const urlInput = screen.getAllByRole("textbox")[0] as HTMLInputElement;
+ await user.clear(urlInput);
+ await user.type(urlInput, "[email protected]:multica-ai/multica.git");
+ expect(urlInput.type).toBe("text");
+ expect(urlInput.validity.valid).toBe(true);
+ await user.tab();
await waitFor(() => {
expect(mockUpdateWorkspace).toHaveBeenCalledWith("workspace-1", {
@@ -227,61 +192,37 @@ describe("RepositoriesTab — view/edit toggle", () => {
});
});
- it("deleting a row shifts tracked edit indices so the wrong row doesn't open", async () => {
- workspaceRef.current = {
- ...workspaceRef.current,
- repos: [{ url: "https://a.example/repo.git" }, { url: "https://b.example/repo.git" }],
- };
- const user = userEvent.setup();
- render(<RepositoriesTab />, { wrapper: I18nWrapper });
-
- // Edit the second row.
- const editButtons = screen.getAllByRole("button", { name: "Edit repository" });
- await user.click(editButtons[1]!);
- expect((screen.getAllByRole("textbox")[0] as HTMLInputElement).value).toBe(
- "https://b.example/repo.git",
- );
-
- // Delete the first row. The remaining row should remain in edit mode
- // (its index dropped from 1 → 0).
- const deleteButtons = screen.getAllByRole("button", { name: "Delete repository" });
- await user.click(deleteButtons[0]!);
-
- const input = screen.getAllByRole("textbox")[0] as HTMLInputElement;
- expect(input.value).toBe("https://b.example/repo.git");
- });
-
- it("description field is editable and included in save payload", async () => {
+ it("includes the description in the automatic update payload", async () => {
workspaceRef.current = {
...workspaceRef.current,
repos: [{ url: "https://github.com/multica-ai/multica", description: "Main app" }],
};
- const user = userEvent.setup();
- mockUpdateWorkspace.mockImplementation(
- async (_id: string, payload: { repos: { url: string; description?: string }[] }) => {
- workspaceRef.current = { ...workspaceRef.current, repos: payload.repos };
- return workspaceRef.current;
- },
- );
-
+ const user = setupUser();
render(<RepositoriesTab />, { wrapper: I18nWrapper });
- // Description is shown in display mode.
- expect(screen.getByText("Main app")).toBeTruthy();
-
- await user.click(screen.getByRole("button", { name: "Edit repository" }));
- const inputs = screen.getAllByRole("textbox") as HTMLInputElement[];
- expect(inputs[1]!.value).toBe("Main app");
-
- await user.clear(inputs[1]!);
- await user.type(inputs[1]!, "Updated description");
-
- await user.click(screen.getByRole("button", { name: /^Save$/ }));
+ const descriptionInput = screen.getAllByRole("textbox")[1] as HTMLInputElement;
+ expect(descriptionInput.value).toBe("Main app");
+ await user.clear(descriptionInput);
+ await user.type(descriptionInput, "Updated description");
+ await user.tab();
await waitFor(() => {
expect(mockUpdateWorkspace).toHaveBeenCalledWith("workspace-1", {
- repos: [{ url: "https://github.com/multica-ai/multica", description: "Updated description" }],
+ repos: [
+ {
+ url: "https://github.com/multica-ai/multica",
+ description: "Updated description",
+ },
+ ],
});
});
});
+
+ it("keeps repository controls read-only for members", () => {
+ membersRef.current = [{ user_id: "user-1", role: "member" }];
+ render(<RepositoriesTab />, { wrapper: I18nWrapper });
+
+ expect(screen.getAllByRole("textbox").every((input) => input.hasAttribute("disabled"))).toBe(true);
+ expect(screen.queryByRole("button", { name: /Add repository/ })).toBeNull();
+ });
});
diff --git a/packages/views/settings/components/repositories-tab.tsx b/packages/views/settings/components/repositories-tab.tsx
index 0fc1511f17..38a967aee9 100644
--- a/packages/views/settings/components/repositories-tab.tsx
+++ b/packages/views/settings/components/repositories-tab.tsx
@@ -1,10 +1,19 @@
"use client";
-import { useEffect, useState } from "react";
-import { Save, Plus, Trash2, Pencil, X } from "lucide-react";
+import { useCallback, useEffect, useMemo, useState } from "react";
+import { Plus, Trash2 } from "lucide-react";
import { Input } from "@multica/ui/components/ui/input";
import { Button } from "@multica/ui/components/ui/button";
-import { Card, CardContent } from "@multica/ui/components/ui/card";
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+} from "@multica/ui/components/ui/alert-dialog";
import { toast } from "sonner";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { useAuthStore } from "@multica/core/auth";
@@ -14,229 +23,222 @@ import { memberListOptions, workspaceKeys } from "@multica/core/workspace/querie
import { api } from "@multica/core/api";
import type { Workspace, WorkspaceRepo } from "@multica/core/types";
import { useT } from "../../i18n";
-
-function dropAndShiftIndex(set: Set<number>, removed: number): Set<number> {
- const next = new Set<number>();
- set.forEach((i) => {
- if (i === removed) return;
- next.add(i > removed ? i - 1 : i);
- });
- return next;
-}
-
-function isDirty(local: WorkspaceRepo[], saved: WorkspaceRepo[]): boolean {
- if (local.length !== saved.length) return true;
- return local.some((r, i) => r.url !== saved[i]?.url || (r.description ?? "") !== (saved[i]?.description ?? ""));
+import {
+ SettingsCard,
+ SettingsSaveState,
+ SettingsSection,
+ SettingsTab,
+} from "./settings-layout";
+import { useAutoSave } from "./use-auto-save";
+
+const EMPTY_REPOSITORIES: WorkspaceRepo[] = [];
+
+function repositoriesEqual(left: WorkspaceRepo[], right: WorkspaceRepo[]) {
+ if (left.length !== right.length) return false;
+ return left.every(
+ (repo, index) =>
+ repo.url === right[index]?.url &&
+ (repo.description ?? "") === (right[index]?.description ?? ""),
+ );
}
export function RepositoriesTab() {
const { t } = useT("settings");
- const user = useAuthStore((s) => s.user);
+ const user = useAuthStore((state) => state.user);
const workspace = useCurrentWorkspace();
const wsId = useWorkspaceId();
- const qc = useQueryClient();
+ const queryClient = useQueryClient();
const { data: members = [] } = useQuery(memberListOptions(wsId));
+ const [repositories, setRepositories] = useState<WorkspaceRepo[]>(
+ workspace?.repos ?? EMPTY_REPOSITORIES,
+ );
+ const [pendingRemovalIndex, setPendingRemovalIndex] = useState<number | null>(null);
- const [repos, setRepos] = useState<WorkspaceRepo[]>(workspace?.repos ?? []);
- const [editingIndices, setEditingIndices] = useState<Set<number>>(new Set());
- const [saving, setSaving] = useState(false);
-
- const currentMember = members.find((m) => m.user_id === user?.id) ?? null;
- const canManageWorkspace = currentMember?.role === "owner" || currentMember?.role === "admin";
+ const currentMember = members.find((member) => member.user_id === user?.id) ?? null;
+ const canManageWorkspace =
+ currentMember?.role === "owner" || currentMember?.role === "admin";
useEffect(() => {
- setRepos(workspace?.repos ?? []);
- }, [workspace]);
-
- const savedRepos = workspace?.repos ?? [];
- const dirty = isDirty(repos, savedRepos);
-
- const handleSave = async () => {
- if (!workspace) return;
- setSaving(true);
- try {
- const updated = await api.updateWorkspace(workspace.id, { repos });
- qc.setQueryData(workspaceKeys.list(), (old: Workspace[] | undefined) =>
- old?.map((ws) => (ws.id === updated.id ? updated : ws)),
+ setRepositories(workspace?.repos ?? EMPTY_REPOSITORIES);
+ // A cache update after auto-save replaces the Workspace object. Keying on
+ // identity prevents that response from wiping a newer local keystroke.
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- intentionally keyed on workspace identity
+ }, [workspace?.id]);
+
+ const savedRepositories = workspace?.repos ?? EMPTY_REPOSITORIES;
+ const draft = useMemo(() => repositories, [repositories]);
+ const saveRepositories = useCallback(
+ async (next: WorkspaceRepo[]) => {
+ if (!workspace) return;
+ const updated = await api.updateWorkspace(workspace.id, { repos: next });
+ queryClient.setQueryData(
+ workspaceKeys.list(),
+ (old: Workspace[] | undefined) =>
+ old?.map((item) => (item.id === updated.id ? updated : item)),
);
- setEditingIndices(new Set());
- toast.success(t(($) => $.repositories.toast_saved));
- } catch (e) {
- toast.error(e instanceof Error ? e.message : t(($) => $.repositories.toast_save_failed));
- } finally {
- setSaving(false);
- }
- };
-
- const handleAddRepo = () => {
- const nextIndex = repos.length;
- setRepos([...repos, { url: "" }]);
- setEditingIndices(new Set(editingIndices).add(nextIndex));
- };
-
- const handleRemoveRepo = (index: number) => {
- setRepos(repos.filter((_, i) => i !== index));
- setEditingIndices(dropAndShiftIndex(editingIndices, index));
- };
+ },
+ [queryClient, workspace],
+ );
+ const allUrlsValid = repositories.every((repo) => repo.url.trim().length > 0);
+ const autoSave = useAutoSave({
+ value: draft,
+ savedValue: savedRepositories,
+ onSave: saveRepositories,
+ onError: (error) =>
+ toast.error(
+ error instanceof Error
+ ? error.message
+ : t(($) => $.repositories.toast_save_failed),
+ ),
+ enabled: !!workspace && canManageWorkspace && allUrlsValid,
+ isEqual: repositoriesEqual,
+ });
- const handleRepoChange = (index: number, field: keyof WorkspaceRepo, value: string) => {
- setRepos(repos.map((r, i) => (i === index ? { ...r, [field]: value } : r)));
+ const updateRepository = (
+ index: number,
+ field: keyof WorkspaceRepo,
+ value: string,
+ ) => {
+ setRepositories((current) =>
+ current.map((repo, repoIndex) =>
+ repoIndex === index ? { ...repo, [field]: value } : repo,
+ ),
+ );
};
- const handleEditRepo = (index: number) => {
- setEditingIndices(new Set(editingIndices).add(index));
+ const addRepository = () => {
+ setRepositories((current) => [...current, { url: "" }]);
};
- const handleCancelEdit = (index: number) => {
- const saved = savedRepos[index];
- if (saved === undefined) {
- // Newly added row that was never persisted — drop it entirely.
- handleRemoveRepo(index);
- return;
- }
- setRepos(repos.map((r, i) => (i === index ? { ...r, url: saved.url, description: saved.description } : r)));
- const next = new Set(editingIndices);
- next.delete(index);
- setEditingIndices(next);
+ const removeRepository = (index: number) => {
+ const next = repositories.filter((_, repoIndex) => repoIndex !== index);
+ setRepositories(next);
+ autoSave.saveNow(next);
};
if (!workspace) return null;
return (
- <div className="space-y-8">
- <section className="space-y-4">
- <h2 className="text-sm font-semibold">{t(($) => $.repositories.section_title)}</h2>
-
- <Card>
- <CardContent className="space-y-3">
- <p className="text-xs text-muted-foreground">
- {t(($) => $.repositories.description)}
- </p>
-
- {repos.length === 0 && (
- <p className="text-xs text-muted-foreground italic">
- {t(($) => $.repositories.empty)}
- </p>
- )}
-
- {repos.map((repo, index) => {
- const isEditing = editingIndices.has(index);
- return (
- <div
- key={index}
- className="group flex items-start gap-2"
+ <SettingsTab title={t(($) => $.page.tabs.repositories)}>
+ <SettingsSection
+ description={t(($) => $.repositories.description)}
+ action={
+ <SettingsSaveState
+ status={autoSave.status}
+ savingLabel={t(($) => $.auto_save.saving)}
+ savedLabel={t(($) => $.auto_save.saved)}
+ errorLabel={t(($) => $.auto_save.failed)}
+ />
+ }
+ >
+ <SettingsCard>
+ {repositories.length === 0 ? (
+ <div className="px-4 py-8 text-center text-xs text-muted-foreground">
+ {t(($) => $.repositories.empty)}
+ </div>
+ ) : null}
+
+ {repositories.map((repository, index) => (
+ <div
+ key={index}
+ className="grid gap-2 px-4 py-3.5 sm:grid-cols-[minmax(0,1fr)_minmax(0,0.8fr)_auto] sm:items-center"
+ >
+ <Input
+ type="text"
+ name={`repository-${index}-url`}
+ autoComplete="off"
+ spellCheck={false}
+ aria-label={t(($) => $.repositories.url_placeholder)}
+ value={repository.url}
+ onChange={(event) =>
+ updateRepository(index, "url", event.target.value)
+ }
+ onBlur={autoSave.flush}
+ disabled={!canManageWorkspace}
+ aria-invalid={!repository.url.trim()}
+ placeholder={t(($) => $.repositories.url_placeholder)}
+ className="font-mono text-xs"
+ />
+ <Input
+ type="text"
+ name={`repository-${index}-description`}
+ autoComplete="off"
+ aria-label={t(($) => $.repositories.description_placeholder)}
+ value={repository.description ?? ""}
+ onChange={(event) =>
+ updateRepository(index, "description", event.target.value)
+ }
+ onBlur={autoSave.flush}
+ disabled={!canManageWorkspace}
+ placeholder={t(($) => $.repositories.description_placeholder)}
+ />
+ {canManageWorkspace ? (
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ aria-label={t(($) => $.repositories.delete_aria)}
+ className="justify-self-end text-muted-foreground hover:text-destructive"
+ onClick={() => setPendingRemovalIndex(index)}
>
- {isEditing ? (
- <div className="flex-1 min-w-0 space-y-1.5">
- <Input
- type="text"
- value={repo.url}
- onChange={(e) => handleRepoChange(index, "url", e.target.value)}
- disabled={!canManageWorkspace}
- placeholder={t(($) => $.repositories.url_placeholder)}
- className="text-sm"
- />
- <Input
- type="text"
- value={repo.description ?? ""}
- onChange={(e) => handleRepoChange(index, "description", e.target.value)}
- disabled={!canManageWorkspace}
- placeholder={t(($) => $.repositories.description_placeholder)}
- className="text-sm"
- />
- </div>
- ) : (
- <div className="flex-1 min-w-0 rounded-md border bg-muted/50 px-3 py-2">
- <div
- className="truncate font-mono text-xs text-muted-foreground"
- title={repo.url}
- >
- {repo.url || t(($) => $.repositories.url_empty)}
- </div>
- {repo.description && (
- <div className="mt-0.5 truncate text-xs text-muted-foreground/70" title={repo.description}>
- {repo.description}
- </div>
- )}
- </div>
- )}
- {canManageWorkspace && (
- <div
- className={
- isEditing
- ? "flex shrink-0 items-center gap-0.5 pt-1.5"
- : "flex shrink-0 items-center gap-0.5 pt-1.5 opacity-0 transition-opacity group-hover:opacity-100 group-focus-within:opacity-100 [@media(hover:none)]:opacity-100"
- }
- >
- {!isEditing && (
- <Button
- variant="ghost"
- size="icon"
- aria-label={t(($) => $.repositories.edit_aria)}
- className="text-muted-foreground hover:text-foreground"
- onClick={() => handleEditRepo(index)}
- >
- <Pencil className="h-3.5 w-3.5" />
- </Button>
- )}
- {isEditing && (
- <Button
- variant="ghost"
- size="icon"
- aria-label={t(($) => $.repositories.cancel_aria)}
- className="text-muted-foreground hover:text-foreground"
- onClick={() => handleCancelEdit(index)}
- >
- <X className="h-3.5 w-3.5" />
- </Button>
- )}
- <Button
- variant="ghost"
- size="icon"
- aria-label={t(($) => $.repositories.delete_aria)}
- className="text-muted-foreground hover:text-destructive"
- onClick={() => handleRemoveRepo(index)}
- >
- <Trash2 className="h-3.5 w-3.5" />
- </Button>
- </div>
- )}
- </div>
- );
- })}
-
- {canManageWorkspace && (
- <div className="flex flex-wrap items-center justify-between gap-2 pt-1">
- <Button variant="outline" size="sm" onClick={handleAddRepo}>
- <Plus className="h-3 w-3" />
- {t(($) => $.repositories.add)}
+ <Trash2 className="size-3.5" />
</Button>
- <div className="flex items-center gap-3">
- {!dirty && repos.length > 0 && (
- <span className="text-xs text-muted-foreground">
- {t(($) => $.repositories.saved_hint)}
- </span>
- )}
- <Button
- size="sm"
- onClick={handleSave}
- disabled={saving || !dirty}
- >
- <Save className="h-3 w-3" />
- {saving ? t(($) => $.repositories.saving) : t(($) => $.repositories.save)}
- </Button>
- </div>
- </div>
- )}
-
- {!canManageWorkspace && (
- <p className="text-xs text-muted-foreground">
- {t(($) => $.repositories.manage_hint)}
- </p>
- )}
- </CardContent>
- </Card>
- </section>
- </div>
+ ) : null}
+ </div>
+ ))}
+
+ {canManageWorkspace ? (
+ <div className="flex items-center justify-between gap-3 px-4 py-3.5">
+ <Button variant="outline" size="sm" onClick={addRepository}>
+ <Plus className="size-3.5" />
+ {t(($) => $.repositories.add)}
+ </Button>
+ {!allUrlsValid ? (
+ <span className="text-xs text-muted-foreground">
+ {t(($) => $.repositories.url_empty)}
+ </span>
+ ) : null}
+ </div>
+ ) : (
+ <div className="px-4 py-3 text-xs text-muted-foreground">
+ {t(($) => $.repositories.manage_hint)}
+ </div>
+ )}
+ </SettingsCard>
+ </SettingsSection>
+
+ <AlertDialog
+ open={pendingRemovalIndex !== null}
+ onOpenChange={(open) => {
+ if (!open) setPendingRemovalIndex(null);
+ }}
+ >
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>
+ {t(($) => $.repositories.delete_confirm_title)}
+ </AlertDialogTitle>
+ <AlertDialogDescription>
+ {t(($) => $.repositories.delete_confirm_description)}
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel>
+ {t(($) => $.repositories.delete_confirm_cancel)}
+ </AlertDialogCancel>
+ <AlertDialogAction
+ variant="destructive"
+ onClick={() => {
+ if (pendingRemovalIndex !== null) {
+ removeRepository(pendingRemovalIndex);
+ }
+ setPendingRemovalIndex(null);
+ }}
+ >
+ {t(($) => $.repositories.delete_confirm_action)}
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ </SettingsTab>
);
}
diff --git a/packages/views/settings/components/settings-layout.tsx b/packages/views/settings/components/settings-layout.tsx
new file mode 100644
index 0000000000..6601ccbb09
--- /dev/null
+++ b/packages/views/settings/components/settings-layout.tsx
@@ -0,0 +1,166 @@
+import type { ReactNode } from "react";
+import { AlertCircle, Check, Loader2 } from "lucide-react";
+import { Card, CardContent } from "@multica/ui/components/ui/card";
+import { cn } from "@multica/ui/lib/utils";
+
+export type SettingsSaveStatus = "idle" | "saving" | "saved" | "error";
+
+export function SettingsTab({
+ title,
+ description,
+ children,
+}: {
+ title: ReactNode;
+ description?: ReactNode;
+ children: ReactNode;
+}) {
+ return (
+ <div className="space-y-8">
+ <header>
+ <h2 className="text-xl font-semibold tracking-tight">{title}</h2>
+ {description ? (
+ <p className="mt-1 max-w-2xl text-sm leading-6 text-muted-foreground">
+ {description}
+ </p>
+ ) : null}
+ </header>
+ {children}
+ </div>
+ );
+}
+
+export function SettingsSection({
+ title,
+ description,
+ action,
+ children,
+ className,
+}: {
+ title?: ReactNode;
+ description?: ReactNode;
+ action?: ReactNode;
+ children: ReactNode;
+ className?: string;
+}) {
+ return (
+ <section className={cn("space-y-3", className)}>
+ {title || description || action ? (
+ <div className="flex min-w-0 items-end justify-between gap-4 px-0.5">
+ <div className="min-w-0">
+ {title ? <h3 className="text-sm font-semibold">{title}</h3> : null}
+ {description ? (
+ <p className="mt-1 text-xs leading-5 text-muted-foreground">
+ {description}
+ </p>
+ ) : null}
+ </div>
+ {action ? <div className="shrink-0">{action}</div> : null}
+ </div>
+ ) : null}
+ {children}
+ </section>
+ );
+}
+
+export function SettingsCard({
+ children,
+ className,
+}: {
+ children: ReactNode;
+ className?: string;
+}) {
+ return (
+ <Card className={cn("gap-0 py-0", className)}>
+ <CardContent className="divide-y divide-surface-border px-0">
+ {children}
+ </CardContent>
+ </Card>
+ );
+}
+
+export function SettingsRow({
+ label,
+ description,
+ children,
+ className,
+ controlClassName,
+ align = "center",
+}: {
+ label: ReactNode;
+ description?: ReactNode;
+ children: ReactNode;
+ className?: string;
+ controlClassName?: string;
+ align?: "center" | "start";
+}) {
+ return (
+ <div
+ className={cn(
+ "flex min-h-16 flex-col gap-3 px-4 py-3.5 sm:flex-row sm:justify-between sm:gap-8",
+ align === "center" ? "sm:items-center" : "sm:items-start",
+ className,
+ )}
+ >
+ <div className="min-w-0 flex-1">
+ <div className="text-sm font-medium">{label}</div>
+ {description ? (
+ <div className="mt-0.5 text-xs leading-5 text-muted-foreground">
+ {description}
+ </div>
+ ) : null}
+ </div>
+ <div
+ className={cn(
+ "w-full shrink-0 sm:w-auto sm:max-w-[56%]",
+ controlClassName,
+ )}
+ >
+ {children}
+ </div>
+ </div>
+ );
+}
+
+export function SettingsSaveState({
+ status,
+ savingLabel,
+ savedLabel,
+ errorLabel,
+}: {
+ status: SettingsSaveStatus;
+ savingLabel: string;
+ savedLabel: string;
+ errorLabel: string;
+}) {
+ if (status === "idle") return null;
+
+ const content =
+ status === "saving" ? (
+ <>
+ <Loader2 className="size-3 animate-spin" />
+ {savingLabel}
+ </>
+ ) : status === "saved" ? (
+ <>
+ <Check className="size-3 text-success" />
+ {savedLabel}
+ </>
+ ) : (
+ <>
+ <AlertCircle className="size-3 text-destructive" />
+ {errorLabel}
+ </>
+ );
+
+ return (
+ <span
+ role="status"
+ className={cn(
+ "inline-flex items-center gap-1.5 text-xs text-muted-foreground",
+ status === "error" && "text-destructive",
+ )}
+ >
+ {content}
+ </span>
+ );
+}
diff --git a/packages/views/settings/components/tokens-tab.tsx b/packages/views/settings/components/tokens-tab.tsx
index 457b678907..9552fe9261 100644
--- a/packages/views/settings/components/tokens-tab.tsx
+++ b/packages/views/settings/components/tokens-tab.tsx
@@ -1,7 +1,7 @@
"use client";
import { useEffect, useState, useCallback } from "react";
-import { Key, Trash2, Copy, Check } from "lucide-react";
+import { Trash2, Copy, Check } from "lucide-react";
import { Tooltip, TooltipTrigger, TooltipContent } from "@multica/ui/components/ui/tooltip";
import type { PersonalAccessToken } from "@multica/core/types";
import { Input } from "@multica/ui/components/ui/input";
@@ -37,6 +37,7 @@ import { copyText } from "@multica/ui/lib/clipboard";
import { toast } from "sonner";
import { api } from "@multica/core/api";
import { useT } from "../../i18n";
+import { SettingsSection, SettingsTab } from "./settings-layout";
const EXPIRY_KEYS = ["30", "90", "365", "never"] as const;
@@ -103,27 +104,25 @@ export function TokensTab() {
};
return (
- <div className="space-y-8">
- <section className="space-y-4">
- <div className="flex items-center gap-2">
- <Key className="h-4 w-4 text-muted-foreground" />
- <h2 className="text-sm font-semibold">{t(($) => $.tokens.title)}</h2>
- </div>
-
+ <SettingsTab title={t(($) => $.tokens.title)}>
+ <SettingsSection description={t(($) => $.tokens.description)}>
<Card>
<CardContent className="space-y-3">
- <p className="text-xs text-muted-foreground">
- {t(($) => $.tokens.description)}
- </p>
<div className="grid gap-3 sm:grid-cols-[1fr_120px_auto]">
<Input
type="text"
+ name="token-name"
+ autoComplete="off"
+ aria-label={t(($) => $.tokens.name_placeholder)}
value={tokenName}
onChange={(e) => setTokenName(e.target.value)}
placeholder={t(($) => $.tokens.name_placeholder)}
/>
<Select value={tokenExpiry} onValueChange={(v) => { if (v) setTokenExpiry(v); }}>
- <SelectTrigger size="sm"><SelectValue /></SelectTrigger>
+ <SelectTrigger
+ size="sm"
+ aria-label={t(($) => $.tokens.title)}
+ ><SelectValue /></SelectTrigger>
<SelectContent>
{EXPIRY_KEYS.map((key) => (
<SelectItem key={key} value={key}>{t(($) => $.tokens.expiry[key])}</SelectItem>
@@ -194,7 +193,7 @@ export function TokensTab() {
))}
</div>
)}
- </section>
+ </SettingsSection>
<AlertDialog open={!!revokeConfirmId} onOpenChange={(v) => { if (!v) setRevokeConfirmId(null); }}>
<AlertDialogContent>
@@ -247,6 +246,6 @@ export function TokensTab() {
</DialogFooter>
</DialogContent>
</Dialog>
- </div>
+ </SettingsTab>
);
}
diff --git a/packages/views/settings/components/use-auto-save.ts b/packages/views/settings/components/use-auto-save.ts
new file mode 100644
index 0000000000..99c8f7547a
--- /dev/null
+++ b/packages/views/settings/components/use-auto-save.ts
@@ -0,0 +1,135 @@
+"use client";
+
+import { useCallback, useEffect, useRef, useState } from "react";
+import type { SettingsSaveStatus } from "./settings-layout";
+
+interface UseAutoSaveOptions<T> {
+ value: T;
+ savedValue: T;
+ onSave: (value: T) => Promise<void>;
+ onError?: (error: unknown) => void;
+ enabled?: boolean;
+ delay?: number;
+ isEqual: (left: T, right: T) => boolean;
+}
+
+interface AutoSaveResult<T> {
+ status: SettingsSaveStatus;
+ flush: () => void;
+ saveNow: (value: T) => void;
+}
+
+/**
+ * Debounces text-heavy settings while serializing requests. If a user edits
+ * again during an in-flight save, only the latest queued value is persisted
+ * next, so a slower response can never overwrite a newer request.
+ */
+export function useAutoSave<T>({
+ value,
+ savedValue,
+ onSave,
+ onError,
+ enabled = true,
+ delay = 650,
+ isEqual,
+}: UseAutoSaveOptions<T>): AutoSaveResult<T> {
+ const [status, setStatus] = useState<SettingsSaveStatus>("idle");
+ const mountedRef = useRef(true);
+ const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+ const savingRef = useRef(false);
+ const queuedRef = useRef<T | null>(null);
+ const latestValueRef = useRef(value);
+ const persistedRef = useRef(savedValue);
+ const observedSavedRef = useRef(savedValue);
+ const enabledRef = useRef(enabled);
+ const onSaveRef = useRef(onSave);
+ const onErrorRef = useRef(onError);
+ const isEqualRef = useRef(isEqual);
+
+ latestValueRef.current = value;
+ enabledRef.current = enabled;
+ onSaveRef.current = onSave;
+ onErrorRef.current = onError;
+ isEqualRef.current = isEqual;
+
+ if (!isEqual(savedValue, observedSavedRef.current)) {
+ observedSavedRef.current = savedValue;
+ persistedRef.current = savedValue;
+ }
+
+ const runSave = useCallback(async (next: T) => {
+ if (!enabledRef.current || isEqualRef.current(next, persistedRef.current)) {
+ return;
+ }
+ if (savingRef.current) {
+ queuedRef.current = next;
+ return;
+ }
+
+ savingRef.current = true;
+ if (mountedRef.current) setStatus("saving");
+ try {
+ await onSaveRef.current(next);
+ persistedRef.current = next;
+ if (mountedRef.current) setStatus("saved");
+ } catch (error) {
+ if (mountedRef.current) setStatus("error");
+ onErrorRef.current?.(error);
+ } finally {
+ savingRef.current = false;
+ const queued = queuedRef.current;
+ queuedRef.current = null;
+ if (queued && !isEqualRef.current(queued, persistedRef.current)) {
+ void runSave(queued);
+ }
+ }
+ }, []);
+
+ const saveNow = useCallback(
+ (next: T) => {
+ if (timerRef.current) {
+ clearTimeout(timerRef.current);
+ timerRef.current = null;
+ }
+ void runSave(next);
+ },
+ [runSave],
+ );
+
+ const flush = useCallback(() => {
+ saveNow(latestValueRef.current);
+ }, [saveNow]);
+
+ useEffect(() => {
+ if (timerRef.current) clearTimeout(timerRef.current);
+
+ if (!enabled || isEqual(value, persistedRef.current)) {
+ timerRef.current = null;
+ if (!enabled) setStatus("idle");
+ return;
+ }
+
+ setStatus("saving");
+ timerRef.current = setTimeout(() => {
+ timerRef.current = null;
+ void runSave(latestValueRef.current);
+ }, delay);
+
+ return () => {
+ if (timerRef.current) {
+ clearTimeout(timerRef.current);
+ timerRef.current = null;
+ }
+ };
+ }, [delay, enabled, isEqual, runSave, value]);
+
+ useEffect(
+ () => () => {
+ mountedRef.current = false;
+ if (timerRef.current) clearTimeout(timerRef.current);
+ },
+ [],
+ );
+
+ return { status, flush, saveNow };
+}
diff --git a/packages/views/settings/components/workspace-tab.test.tsx b/packages/views/settings/components/workspace-tab.test.tsx
index 5b55f98366..b2bbb0c1d5 100644
--- a/packages/views/settings/components/workspace-tab.test.tsx
+++ b/packages/views/settings/components/workspace-tab.test.tsx
@@ -1,5 +1,5 @@
import type { ReactNode } from "react";
-import { describe, it, expect, beforeEach, vi } from "vitest";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { I18nProvider } from "@multica/core/i18n/react";
@@ -32,10 +32,6 @@ vi.mock("@tanstack/react-query", () => ({
}),
}));
-vi.mock("@multica/core/hooks", () => ({
- useWorkspaceId: () => "workspace-1",
-}));
-
vi.mock("@multica/core/paths", () => ({
useCurrentWorkspace: () => workspaceRef.current,
useHasOnboarded: () => true,
@@ -53,7 +49,7 @@ vi.mock("@multica/core/workspace/queries", () => ({
}));
vi.mock("@multica/core/issues/queries", () => ({
- issueKeys: { all: (wsId: string) => ["issues", wsId] },
+ issueKeys: { all: (workspaceId: string) => ["issues", workspaceId] },
}));
vi.mock("@multica/core/workspace/mutations", () => ({
@@ -62,13 +58,16 @@ vi.mock("@multica/core/workspace/mutations", () => ({
}));
vi.mock("@multica/core/api", () => ({
- api: { updateWorkspace: mockUpdateWorkspace, getBaseUrl: () => "http://127.0.0.1:8080" },
+ api: {
+ updateWorkspace: mockUpdateWorkspace,
+ getBaseUrl: () => "http://127.0.0.1:8080",
+ },
}));
vi.mock("@multica/core/auth", () => {
const useAuthStore = Object.assign(
- (sel?: (s: { user: { id: string } }) => unknown) =>
- sel ? sel({ user: { id: "user-1" } }) : { user: { id: "user-1" } },
+ (selector?: (state: { user: { id: string } }) => unknown) =>
+ selector ? selector({ user: { id: "user-1" } }) : { user: { id: "user-1" } },
{ getState: () => ({ user: { id: "user-1" } }) },
);
return { useAuthStore };
@@ -100,9 +99,10 @@ function I18nWrapper({ children }: { children: ReactNode }) {
);
}
-describe("WorkspaceTab — issue prefix editing", () => {
+describe("WorkspaceTab — automatic updates", () => {
beforeEach(() => {
vi.clearAllMocks();
+ vi.useFakeTimers({ shouldAdvanceTime: true });
workspaceRef.current = {
id: "workspace-1",
name: "Test Workspace",
@@ -114,25 +114,32 @@ describe("WorkspaceTab — issue prefix editing", () => {
};
membersRef.current = [{ user_id: "user-1", role: "owner" }];
mockUpdateWorkspace.mockImplementation(
- async (
- _id: string,
- payload: { issue_prefix?: string; name?: string },
- ) => ({
+ async (_id: string, payload: Record<string, unknown>) => ({
...workspaceRef.current,
...payload,
- issue_prefix: payload.issue_prefix ?? workspaceRef.current.issue_prefix,
+ issue_prefix:
+ (payload.issue_prefix as string | undefined) ?? workspaceRef.current.issue_prefix,
}),
);
});
- it("renders the current prefix in the input", () => {
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ function setupUser() {
+ return userEvent.setup({ advanceTimers: vi.advanceTimersByTime });
+ }
+
+ it("renders the current prefix in the shared input control", () => {
render(<WorkspaceTab />, { wrapper: I18nWrapper });
const input = screen.getByPlaceholderText("TES") as HTMLInputElement;
expect(input.value).toBe("TES");
+ expect(screen.queryByRole("button", { name: /^Save$/ })).toBeNull();
});
- it("uppercases and strips non-alphanumeric input as the user types", async () => {
- const user = userEvent.setup();
+ it("uppercases and strips non-alphanumeric prefix input", async () => {
+ const user = setupUser();
render(<WorkspaceTab />, { wrapper: I18nWrapper });
const input = screen.getByPlaceholderText("TES") as HTMLInputElement;
@@ -142,43 +149,35 @@ describe("WorkspaceTab — issue prefix editing", () => {
expect(input.value).toBe("AB12CD");
});
- it("saves directly without confirm when the prefix is unchanged", async () => {
- const user = userEvent.setup();
+ it("auto-saves ordinary workspace fields without invalidating issue caches", async () => {
+ const user = setupUser();
render(<WorkspaceTab />, { wrapper: I18nWrapper });
+ const nameInput = screen.getByDisplayValue("Test Workspace");
- await user.click(screen.getByRole("button", { name: /^Save$/ }));
+ await user.clear(nameInput);
+ await user.type(nameInput, "Renamed Workspace");
+ await user.tab();
await waitFor(() => {
- expect(mockUpdateWorkspace).toHaveBeenCalledTimes(1);
+ expect(mockUpdateWorkspace).toHaveBeenCalledWith("workspace-1", {
+ name: "Renamed Workspace",
+ description: "",
+ context: "",
+ });
});
- // No issue_prefix in the payload when unchanged — avoids no-op churn
- // and keeps the request shape identical to pre-feature behavior.
- expect(mockUpdateWorkspace).toHaveBeenCalledWith(
- "workspace-1",
- expect.not.objectContaining({ issue_prefix: expect.anything() }),
- );
- expect(screen.queryByText(/Change issue prefix/i)).toBeNull();
- // Non-prefix saves must NOT invalidate the issue cache — would
- // trigger an unnecessary workspace-wide refetch on every name edit.
- expect(mockInvalidateQueries).not.toHaveBeenCalledWith(
- expect.objectContaining({ queryKey: ["issues", "workspace-1"] }),
- );
+ expect(mockInvalidateQueries).not.toHaveBeenCalled();
});
- it("shows a confirm dialog before saving when the prefix changes, and only saves on confirm", async () => {
- const user = userEvent.setup();
+ it("asks for confirmation on prefix blur and persists only after confirmation", async () => {
+ const user = setupUser();
render(<WorkspaceTab />, { wrapper: I18nWrapper });
-
const input = screen.getByPlaceholderText("TES") as HTMLInputElement;
+
await user.clear(input);
await user.type(input, "NEW");
+ await user.tab();
- await user.click(screen.getByRole("button", { name: /^Save$/ }));
-
- // Save is gated behind the dialog — no API call yet.
expect(mockUpdateWorkspace).not.toHaveBeenCalled();
-
- // Dialog body mentions both the old and new prefix in the warning.
await screen.findByText(/Change issue prefix/i);
expect(screen.getByText(/TES-N/)).toBeTruthy();
expect(screen.getByText(/NEW-N/)).toBeTruthy();
@@ -186,52 +185,47 @@ describe("WorkspaceTab — issue prefix editing", () => {
await user.click(screen.getByRole("button", { name: "Confirm" }));
await waitFor(() => {
- expect(mockUpdateWorkspace).toHaveBeenCalledTimes(1);
+ expect(mockUpdateWorkspace).toHaveBeenCalledWith("workspace-1", {
+ issue_prefix: "NEW",
+ });
+ });
+ expect(mockInvalidateQueries).toHaveBeenCalledWith({
+ queryKey: ["issues", "workspace-1"],
});
- expect(mockUpdateWorkspace).toHaveBeenCalledWith(
- "workspace-1",
- expect.objectContaining({ issue_prefix: "NEW" }),
- );
- // Issue identifiers (`MUL-123`) are recomputed from the workspace
- // prefix at read time, so cached issues display the stale OLD-N key
- // until invalidated. Without this the confirm dialog's promise that
- // "all issues will be renumbered to NEW-N" is a lie.
- expect(mockInvalidateQueries).toHaveBeenCalledWith(
- expect.objectContaining({ queryKey: ["issues", "workspace-1"] }),
- );
});
- it("cancelling the confirm dialog does not save", async () => {
- const user = userEvent.setup();
+ it("does not persist a prefix when the confirmation is cancelled", async () => {
+ const user = setupUser();
render(<WorkspaceTab />, { wrapper: I18nWrapper });
-
const input = screen.getByPlaceholderText("TES") as HTMLInputElement;
+
await user.clear(input);
await user.type(input, "NEW");
-
- await user.click(screen.getByRole("button", { name: /^Save$/ }));
-
+ await user.tab();
await screen.findByText(/Change issue prefix/i);
await user.click(screen.getByRole("button", { name: "Cancel" }));
expect(mockUpdateWorkspace).not.toHaveBeenCalled();
- // The user's edited value is preserved so they can resume.
expect(input.value).toBe("NEW");
});
- it("disables Save when the prefix is empty", async () => {
- const user = userEvent.setup();
+ it("marks an empty prefix invalid and does not persist it", async () => {
+ const user = setupUser();
render(<WorkspaceTab />, { wrapper: I18nWrapper });
-
const input = screen.getByPlaceholderText("TES") as HTMLInputElement;
+
await user.clear(input);
+ await user.tab();
- expect(screen.getByRole("button", { name: /^Save$/ })).toBeDisabled();
+ expect(input).toHaveAttribute("aria-invalid", "true");
+ expect(mockUpdateWorkspace).not.toHaveBeenCalled();
});
- it("disables the prefix input for non-admins", () => {
+ it("disables editable workspace controls for regular members", () => {
membersRef.current = [{ user_id: "user-1", role: "member" }];
render(<WorkspaceTab />, { wrapper: I18nWrapper });
+
expect(screen.getByPlaceholderText("TES")).toBeDisabled();
+ expect(screen.getByDisplayValue("Test Workspace")).toBeDisabled();
});
});
diff --git a/packages/views/settings/components/workspace-tab.tsx b/packages/views/settings/components/workspace-tab.tsx
index 1edd13330e..77f76b2515 100644
--- a/packages/views/settings/components/workspace-tab.tsx
+++ b/packages/views/settings/components/workspace-tab.tsx
@@ -1,12 +1,10 @@
"use client";
-import { useEffect, useState } from "react";
-import { Save, LogOut } from "lucide-react";
+import { useCallback, useEffect, useMemo, useState } from "react";
+import { LogOut } from "lucide-react";
import { Input } from "@multica/ui/components/ui/input";
import { Textarea } from "@multica/ui/components/ui/textarea";
-import { Label } from "@multica/ui/components/ui/label";
import { Button } from "@multica/ui/components/ui/button";
-import { Card, CardContent } from "@multica/ui/components/ui/card";
import {
AlertDialog,
AlertDialogContent,
@@ -39,6 +37,32 @@ import { AvatarUploadControl } from "../../common/avatar-upload-control";
import { useNavigation } from "../../navigation";
import { DeleteWorkspaceDialog } from "./delete-workspace-dialog";
import { useT } from "../../i18n";
+import {
+ SettingsCard,
+ SettingsRow,
+ SettingsSaveState,
+ SettingsSection,
+ SettingsTab,
+ type SettingsSaveStatus,
+} from "./settings-layout";
+import { useAutoSave } from "./use-auto-save";
+
+interface WorkspaceDetailsDraft {
+ name: string;
+ description: string;
+ context: string;
+}
+
+function workspaceDetailsEqual(
+ left: WorkspaceDetailsDraft,
+ right: WorkspaceDetailsDraft,
+) {
+ return (
+ left.name === right.name &&
+ left.description === right.description &&
+ left.context === right.context
+ );
+}
export function WorkspaceTab() {
const { t } = useT("settings");
@@ -107,7 +131,8 @@ export function WorkspaceTab() {
const [description, setDescription] = useState(workspace?.description ?? "");
const [context, setContext] = useState(workspace?.context ?? "");
const [issuePrefix, setIssuePrefix] = useState(workspace?.issue_prefix ?? "");
- const [saving, setSaving] = useState(false);
+ const [prefixSaveStatus, setPrefixSaveStatus] =
+ useState<SettingsSaveStatus>("idle");
const [actionId, setActionId] = useState<string | null>(null);
const [confirmAction, setConfirmAction] = useState<{
title: string;
@@ -151,50 +176,78 @@ export function WorkspaceTab() {
!!workspace && normalizedPrefix !== workspace.issue_prefix;
const prefixInvalid = normalizedPrefix.length === 0;
- const performSave = async (includePrefix: boolean) => {
+ const detailsDraft = useMemo(
+ () => ({ name, description, context }),
+ [context, description, name],
+ );
+ const savedDetails = useMemo(
+ () => ({
+ name: workspace?.name ?? "",
+ description: workspace?.description ?? "",
+ context: workspace?.context ?? "",
+ }),
+ [workspace?.context, workspace?.description, workspace?.name],
+ );
+ const saveDetails = useCallback(
+ async (next: WorkspaceDetailsDraft) => {
+ if (!workspace) return;
+ const updated = await api.updateWorkspace(workspace.id, next);
+ qc.setQueryData(workspaceKeys.list(), (old: Workspace[] | undefined) =>
+ old?.map((ws) => (ws.id === updated.id ? updated : ws)),
+ );
+ },
+ [qc, workspace],
+ );
+ const detailsAutoSave = useAutoSave({
+ value: detailsDraft,
+ savedValue: savedDetails,
+ onSave: saveDetails,
+ onError: (error) =>
+ toast.error(
+ error instanceof Error
+ ? error.message
+ : t(($) => $.workspace.toast_save_failed),
+ ),
+ enabled: !!workspace && canManageWorkspace && !!name.trim(),
+ isEqual: workspaceDetailsEqual,
+ });
+
+ const performPrefixSave = async (nextPrefix: string) => {
if (!workspace) return;
- setSaving(true);
+ setPrefixSaveStatus("saving");
try {
const updated = await api.updateWorkspace(workspace.id, {
- name,
- description,
- context,
- ...(includePrefix ? { issue_prefix: normalizedPrefix } : {}),
+ issue_prefix: nextPrefix,
});
qc.setQueryData(workspaceKeys.list(), (old: Workspace[] | undefined) =>
old?.map((ws) => (ws.id === updated.id ? updated : ws)),
);
- // Issue identifiers (`MUL-123`) are computed from `issue_prefix` at
- // read time, not stored on each issue row. When the prefix changes,
- // every cached issue's rendered identifier is stale until refetched.
- // Limit invalidation to the prefix-changed branch so unrelated saves
- // (name / description / context) stay cheap.
- if (includePrefix) {
- qc.invalidateQueries({ queryKey: issueKeys.all(updated.id) });
- }
- toast.success(t(($) => $.workspace.toast_saved));
- } catch (e) {
- toast.error(e instanceof Error ? e.message : t(($) => $.workspace.toast_save_failed));
- } finally {
- setSaving(false);
+ // Issue identifiers are computed from the workspace prefix at read time,
+ // so every cached issue key is stale after this confirmed change.
+ await qc.invalidateQueries({ queryKey: issueKeys.all(updated.id) });
+ setPrefixSaveStatus("saved");
+ } catch (error) {
+ setPrefixSaveStatus("error");
+ toast.error(
+ error instanceof Error
+ ? error.message
+ : t(($) => $.workspace.toast_save_failed),
+ );
}
};
- const handleSave = () => {
- if (!workspace || prefixInvalid) return;
- if (prefixChanged) {
- setConfirmAction({
- title: t(($) => $.workspace.prefix_confirm_title),
- description: t(($) => $.workspace.prefix_confirm_description, {
- oldPrefix: workspace.issue_prefix,
- newPrefix: normalizedPrefix,
- }),
- variant: "destructive",
- onConfirm: () => performSave(true),
- });
- return;
- }
- void performSave(false);
+ const handlePrefixBlur = () => {
+ if (!workspace || prefixInvalid || !prefixChanged) return;
+ const nextPrefix = normalizedPrefix;
+ setConfirmAction({
+ title: t(($) => $.workspace.prefix_confirm_title),
+ description: t(($) => $.workspace.prefix_confirm_description, {
+ oldPrefix: workspace.issue_prefix,
+ newPrefix: nextPrefix,
+ }),
+ variant: "destructive",
+ onConfirm: () => performPrefixSave(nextPrefix),
+ });
};
const handleLeaveWorkspace = () => {
@@ -241,14 +294,31 @@ export function WorkspaceTab() {
if (!workspace) return null;
return (
- <div className="space-y-8">
- {/* Workspace settings */}
- <section className="space-y-4">
- <h2 className="text-sm font-semibold">{t(($) => $.workspace.section_general)}</h2>
-
- <Card>
- <CardContent className="space-y-3">
- <div className="flex items-center gap-4">
+ <SettingsTab title={t(($) => $.page.tabs.general)}>
+ <SettingsSection
+ title={t(($) => $.workspace.section_general)}
+ action={
+ <SettingsSaveState
+ status={
+ prefixSaveStatus === "saving" || prefixSaveStatus === "error"
+ ? prefixSaveStatus
+ : detailsAutoSave.status === "idle"
+ ? prefixSaveStatus
+ : detailsAutoSave.status
+ }
+ savingLabel={t(($) => $.auto_save.saving)}
+ savedLabel={t(($) => $.auto_save.saved)}
+ errorLabel={t(($) => $.auto_save.failed)}
+ />
+ }
+ >
+ <SettingsCard>
+ <SettingsRow
+ label={t(($) => $.workspace.logo_label)}
+ description={t(($) => $.workspace.click_logo_hint)}
+ controlClassName="sm:max-w-none"
+ >
+ <div className="flex justify-start sm:justify-end">
<AvatarUploadControl
variant="workspace"
value={workspace.avatar_url ?? null}
@@ -267,107 +337,131 @@ export function WorkspaceTab() {
);
}}
/>
- <div className="text-xs text-muted-foreground">
- {t(($) => $.workspace.click_logo_hint)}
- </div>
- </div>
- <div>
- <Label className="text-xs text-muted-foreground">{t(($) => $.workspace.name_label)}</Label>
- <Input
- type="text"
- value={name}
- onChange={(e) => setName(e.target.value)}
- disabled={!canManageWorkspace}
- className="mt-1"
- />
- </div>
- <div>
- <Label className="text-xs text-muted-foreground">{t(($) => $.workspace.description_label)}</Label>
- <Textarea
- value={description}
- onChange={(e) => setDescription(e.target.value)}
- rows={3}
- disabled={!canManageWorkspace}
- className="mt-1 resize-none"
- placeholder={t(($) => $.workspace.description_placeholder)}
- />
- </div>
- <div>
- <Label className="text-xs text-muted-foreground">{t(($) => $.workspace.context_label)}</Label>
- <Textarea
- value={context}
- onChange={(e) => setContext(e.target.value)}
- rows={4}
- disabled={!canManageWorkspace}
- className="mt-1 resize-none"
- placeholder={t(($) => $.workspace.context_placeholder)}
- />
</div>
- <div>
- <Label className="text-xs text-muted-foreground">{t(($) => $.workspace.slug_label)}</Label>
- <div className="mt-1 rounded-md border bg-muted/50 px-3 py-2 text-sm text-muted-foreground">
+ </SettingsRow>
+
+ <SettingsRow
+ label={t(($) => $.workspace.name_label)}
+ controlClassName="sm:w-80"
+ >
+ <Input
+ type="text"
+ name="workspace-name"
+ autoComplete="organization"
+ aria-label={t(($) => $.workspace.name_label)}
+ value={name}
+ onChange={(event) => setName(event.target.value)}
+ onBlur={detailsAutoSave.flush}
+ disabled={!canManageWorkspace}
+ />
+ </SettingsRow>
+
+ <SettingsRow
+ label={t(($) => $.workspace.description_label)}
+ controlClassName="sm:w-96"
+ align="start"
+ >
+ <Textarea
+ name="workspace-description"
+ autoComplete="off"
+ aria-label={t(($) => $.workspace.description_label)}
+ value={description}
+ onChange={(event) => setDescription(event.target.value)}
+ onBlur={detailsAutoSave.flush}
+ rows={3}
+ disabled={!canManageWorkspace}
+ className="resize-none"
+ placeholder={t(($) => $.workspace.description_placeholder)}
+ />
+ </SettingsRow>
+
+ <SettingsRow
+ label={t(($) => $.workspace.context_label)}
+ controlClassName="sm:w-96"
+ align="start"
+ >
+ <Textarea
+ name="workspace-context"
+ autoComplete="off"
+ aria-label={t(($) => $.workspace.context_label)}
+ value={context}
+ onChange={(event) => setContext(event.target.value)}
+ onBlur={detailsAutoSave.flush}
+ rows={4}
+ disabled={!canManageWorkspace}
+ className="resize-none"
+ placeholder={t(($) => $.workspace.context_placeholder)}
+ />
+ </SettingsRow>
+
+ <SettingsRow
+ label={t(($) => $.workspace.slug_label)}
+ controlClassName="sm:w-80"
+ >
+ <div className="rounded-lg border border-input bg-muted/50 px-2.5 py-1.5 font-mono text-xs text-muted-foreground">
{workspace.slug}
</div>
- </div>
- <div>
- <Label className="text-xs text-muted-foreground">{t(($) => $.workspace.issue_prefix_label)}</Label>
+ </SettingsRow>
+
+ <SettingsRow
+ label={t(($) => $.workspace.issue_prefix_label)}
+ description={t(($) => $.workspace.issue_prefix_hint, {
+ example: `${normalizedPrefix || workspace.issue_prefix}-123`,
+ })}
+ controlClassName="sm:w-40"
+ >
<Input
type="text"
+ name="workspace-issue-prefix"
+ autoComplete="off"
+ autoCapitalize="characters"
+ spellCheck={false}
+ aria-label={t(($) => $.workspace.issue_prefix_label)}
value={issuePrefix}
- onChange={(e) => setIssuePrefix(normalizePrefix(e.target.value))}
+ onChange={(event) => {
+ setPrefixSaveStatus("idle");
+ setIssuePrefix(normalizePrefix(event.target.value));
+ }}
+ onBlur={handlePrefixBlur}
disabled={!canManageWorkspace}
maxLength={10}
- className="mt-1 font-mono uppercase"
+ aria-invalid={prefixInvalid}
+ className="font-mono uppercase"
placeholder={workspace.issue_prefix}
/>
- <p className="mt-1 text-xs text-muted-foreground">
- {t(($) => $.workspace.issue_prefix_hint, {
- example: `${normalizedPrefix || workspace.issue_prefix}-123`,
- })}
- </p>
- </div>
- <div className="flex items-center justify-end gap-2 pt-1">
- <Button
- size="sm"
- onClick={handleSave}
- disabled={saving || !name.trim() || prefixInvalid || !canManageWorkspace}
- >
- <Save className="h-3 w-3" />
- {saving ? t(($) => $.workspace.saving) : t(($) => $.workspace.save)}
- </Button>
- </div>
+ </SettingsRow>
+
{!canManageWorkspace && (
- <p className="text-xs text-muted-foreground">
+ <div className="px-4 py-3 text-xs text-muted-foreground">
{t(($) => $.workspace.manage_hint)}
- </p>
+ </div>
)}
- </CardContent>
- </Card>
- </section>
+ </SettingsCard>
+ </SettingsSection>
{/* Danger Zone — gated on the member query settling so the owner-only
Delete button and the sole-owner Leave guidance don't flash in
after mount. */}
{membersFetched && (
- <section className="space-y-4">
- <div className="flex items-center gap-2">
- <LogOut className="h-4 w-4 text-muted-foreground" />
- <h2 className="text-sm font-semibold">{t(($) => $.workspace.danger_zone)}</h2>
- </div>
-
- <Card>
- <CardContent className="space-y-3">
- <div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
- <div>
- <p className="text-sm font-medium">{t(($) => $.workspace.leave_title)}</p>
- <p className="text-xs text-muted-foreground">
- {isSoleOwner
- ? isSoleMember
- ? t(($) => $.workspace.leave_sole_member)
- : t(($) => $.workspace.leave_sole_owner)
- : t(($) => $.workspace.leave_default)}
- </p>
- </div>
+ <SettingsSection
+ title={
+ <span className="inline-flex items-center gap-2">
+ <LogOut className="h-4 w-4 text-muted-foreground" />
+ {t(($) => $.workspace.danger_zone)}
+ </span>
+ }
+ >
+ <SettingsCard>
+ <SettingsRow
+ label={t(($) => $.workspace.leave_title)}
+ description={
+ isSoleOwner
+ ? isSoleMember
+ ? t(($) => $.workspace.leave_sole_member)
+ : t(($) => $.workspace.leave_sole_owner)
+ : t(($) => $.workspace.leave_default)
+ }
+ >
<Button
variant="outline"
size="sm"
@@ -376,16 +470,17 @@ export function WorkspaceTab() {
>
{actionId === "leave" ? t(($) => $.workspace.leaving) : t(($) => $.workspace.leave_button)}
</Button>
- </div>
+ </SettingsRow>
{isOwner && (
- <div className="flex flex-col gap-2 border-t pt-3 sm:flex-row sm:items-center sm:justify-between">
- <div>
- <p className="text-sm font-medium text-destructive">{t(($) => $.workspace.delete_title)}</p>
- <p className="text-xs text-muted-foreground">
- {t(($) => $.workspace.delete_description)}
- </p>
- </div>
+ <SettingsRow
+ label={
+ <span className="text-destructive">
+ {t(($) => $.workspace.delete_title)}
+ </span>
+ }
+ description={t(($) => $.workspace.delete_description)}
+ >
<Button
variant="destructive"
size="sm"
@@ -394,11 +489,10 @@ export function WorkspaceTab() {
>
{actionId === "delete-workspace" ? t(($) => $.workspace.deleting) : t(($) => $.workspace.delete_button)}
</Button>
- </div>
+ </SettingsRow>
)}
- </CardContent>
- </Card>
- </section>
+ </SettingsCard>
+ </SettingsSection>
)}
<AlertDialog open={!!confirmAction} onOpenChange={(v) => { if (!v) setConfirmAction(null); }}>
@@ -434,6 +528,6 @@ export function WorkspaceTab() {
}}
onConfirm={handleConfirmDelete}
/>
- </div>
+ </SettingsTab>
);
}
diff --git a/packages/views/settings/index.ts b/packages/views/settings/index.ts
index fef5002273..d3c1ae5b16 100644
--- a/packages/views/settings/index.ts
+++ b/packages/views/settings/index.ts
@@ -1,2 +1,12 @@
export { SettingsPage } from "./components";
export type { ExtraSettingsTab } from "./components";
+export {
+ SettingsCard,
+ SettingsRow,
+ SettingsSaveState,
+ SettingsSection,
+ SettingsTab,
+} from "./components/settings-layout";
+export type {
+ SettingsSaveStatus,
+} from "./components/settings-layout";