Skip to content

A cross-platform desktop All-in-One assistant for Claude Code, Codex, OpenCode,DeepSeek Harness and more. Only official website: ccswitch.io

feat: add onboarding tutorial with multi-language support (#9236)

funkpopo64482a7d6869
diff --git a/src/App.tsx b/src/App.tsx
index b5b70a77f..ed974b553 100644
--- a/src/App.tsx
+++ b/src/App.tsx
@@ -1603,6 +1603,7 @@ function App() {
<Button
variant="solid"
size="regular"
+ data-tour="add-provider"
onClick={() => openAddProvider(currentModeView)}
>
<Plus className="h-4 w-4" />
@@ -1857,7 +1858,11 @@ function App() {
</Badge>
</>
}
- actions={<RefreshAllQuotaButton />}
+ actions={
+ <span data-tour="auth-refresh" className="inline-flex">
+ <RefreshAllQuotaButton />
+ </span>
+ }
/>
<div
id="main-content"
@@ -2099,7 +2104,18 @@ function App() {
/>
<DeepLinkImportDialog />
- <FirstRunNoticeDialog />
+ <FirstRunNoticeDialog
+ onBeforeOpen={() => {
+ // 教程要圈的元素都在供应商页上:从设置 → 关于重新打开时先回到这一页
+ closeProviderPanels();
+ setCurrentView("providers");
+ }}
+ onNavigatePage={(page) => {
+ closeProviderPanels();
+ if (page === "usage") setUsageAppFilter("all");
+ setCurrentView(page);
+ }}
+ />
<NewLayoutDialog />
<WhatsNewNotice />
</WindowControlsContext.Provider>
diff --git a/src/components/FirstRunNoticeDialog.tsx b/src/components/FirstRunNoticeDialog.tsx
index b302447b1..aedde01a8 100644
--- a/src/components/FirstRunNoticeDialog.tsx
+++ b/src/components/FirstRunNoticeDialog.tsx
@@ -1,31 +1,46 @@
-import { useTranslation } from "react-i18next";
+import { useState } from "react";
import { useQueryClient } from "@tanstack/react-query";
import { getVersion } from "@tauri-apps/api/app";
-import { Sparkles } from "lucide-react";
-import {
- Dialog,
- DialogContent,
- DialogDescription,
- DialogFooter,
- DialogHeader,
- DialogTitle,
-} from "@/components/ui/dialog";
-import { Button } from "@/components/ui/button";
+import { OnboardingTour, type TourPage } from "@/components/OnboardingTour";
import { useSettingsQuery } from "@/lib/query";
import { settingsApi } from "@/lib/api";
import { markSeen } from "@/lib/whatsNew";
+import { useOnboardingTourRequest } from "@/lib/onboardingTour";
-/** 首次运行欢迎提示:仅当后端启动阶段保留 firstRunNoticeConfirmed 为空时弹出。 */
-export function FirstRunNoticeDialog() {
- const { t } = useTranslation();
+interface FirstRunNoticeDialogProps {
+ /** 手动重看前把界面切到供应商页:要圈的侧栏、按钮、卡片都在这一页上 */
+ onBeforeOpen?: () => void;
+ /** 教程走到应用 / 用量 / 授权中心步骤时自动切过去,离开或结束时切回供应商页 */
+ onNavigatePage?: (page: TourPage) => void;
+}
+
+/**
+ * 使用教程的宿主:settings.json 里 firstRunNoticeConfirmed 为空时自动打开,
+ * 跳过或看完都写成 true,以后不再自动打开;关于页可以用 startOnboardingTour() 手动重看。
+ */
+export function FirstRunNoticeDialog({
+ onBeforeOpen,
+ onNavigatePage,
+}: FirstRunNoticeDialogProps = {}) {
const queryClient = useQueryClient();
const { data: settings } = useSettingsQuery();
+ // 点了就先关,不等保存回来
+ const [closed, setClosed] = useState(false);
+ const [replaying, setReplaying] = useState(false);
+
+ const firstRunPending =
+ !closed && settings != null && settings.firstRunNoticeConfirmed !== true;
+ const isOpen = firstRunPending || replaying;
- // 后端启动时已经决定好要不要弹:条件不满足的话字段会立即被写成 true,
- // 所以前端这里只需要判空即可——与其他既有确认标记的模式一致。
- const isOpen = settings != null && settings.firstRunNoticeConfirmed !== true;
+ // 手动重看(从设置 → 关于)时先回到供应商页;首次启动本来就停在供应商页,
+ // 而且设置是异步读到的,那时再切页面会把用户刚点开的页面拽回去
+ useOnboardingTourRequest(() => {
+ onBeforeOpen?.();
+ setReplaying(true);
+ });
- const handleAcknowledge = async () => {
+ const acknowledgeFirstRun = async () => {
+ setClosed(true);
if (!settings) return;
try {
const { webdavSync: _, ...rest } = settings;
@@ -43,34 +58,16 @@ export function FirstRunNoticeDialog() {
}
};
+ const handleClose = () => {
+ setReplaying(false);
+ if (firstRunPending) void acknowledgeFirstRun();
+ };
+
return (
- <Dialog
+ <OnboardingTour
open={isOpen}
- onOpenChange={(open) => {
- if (!open) void handleAcknowledge();
- }}
- >
- <DialogContent className="max-w-md" zIndex="top">
- <DialogHeader>
- <DialogTitle className="flex items-center gap-2">
- <Sparkles className="h-5 w-5 text-fg-1" />
- {t("firstRunNotice.title")}
- </DialogTitle>
- </DialogHeader>
- <div className="space-y-3 px-6 py-5">
- <DialogDescription className="whitespace-pre-line leading-relaxed">
- {t("firstRunNotice.bodyDefault")}
- </DialogDescription>
- <DialogDescription className="whitespace-pre-line leading-relaxed">
- {t("firstRunNotice.bodyOfficial")}
- </DialogDescription>
- </div>
- <DialogFooter>
- <Button onClick={handleAcknowledge}>
- {t("firstRunNotice.confirm")}
- </Button>
- </DialogFooter>
- </DialogContent>
- </Dialog>
+ onClose={handleClose}
+ onNavigatePage={onNavigatePage}
+ />
);
}
diff --git a/src/components/OnboardingTour.tsx b/src/components/OnboardingTour.tsx
new file mode 100644
index 000000000..a6bafccf7
--- /dev/null
+++ b/src/components/OnboardingTour.tsx
@@ -0,0 +1,1025 @@
+import {
+ useEffect,
+ useId,
+ useLayoutEffect,
+ useRef,
+ useState,
+ type CSSProperties,
+} from "react";
+import { createPortal } from "react-dom";
+import { useTranslation } from "react-i18next";
+import {
+ ArrowLeftRight,
+ ChartColumn,
+ KeyRound,
+ LayoutGrid,
+ PanelLeft,
+ Plus,
+ Route,
+ Server,
+ Settings,
+ Sparkles,
+ type LucideIcon,
+} from "lucide-react";
+import { ModalDragStrip } from "@/components/shell/AppPageHeader";
+import { Button } from "@/components/ui/button";
+import { cn } from "@/lib/utils";
+
+/**
+ * 界面上给教程指路的锚点:元素上写 `data-tour="<id>"`,教程按 id 找到它、把它圈出来。
+ * 同一个 id 有多个元素时只取第一个(供应商卡片就是列表里的第一张)。
+ */
+export type TourAnchor =
+ | "apps"
+ | "nav-apps"
+ | "provider-card"
+ | "provider-empty"
+ | "add-provider"
+ | "mode-tabs"
+ | "nav-mcp"
+ | "nav-skills"
+ | "nav-plugins"
+ | "nav-prompts"
+ | "nav-sessions"
+ | "nav-auth"
+ | "nav-usage"
+ | "nav-settings"
+ | "apps-row"
+ | "apps-actions"
+ | "usage-filters"
+ | "usage-actions"
+ | "auth-toggles"
+ | "auth-refresh";
+
+export type TourPage = "providers" | "apps" | "usage" | "auth";
+
+interface TourTarget {
+ /** 要圈出来的元素组:每个子数组圈成一个独立亮框(避免合并后误圈中间的其他按钮) */
+ groups: TourAnchor[][];
+ /** 匹配这一组时换用的正文;不给就用步骤的 bodyKeys */
+ bodyKeys?: string[];
+ /** 匹配这一组时的提示条;不给就用步骤的 calloutKey(传 null 可显式隐藏) */
+ calloutKey?: string | null;
+}
+
+interface ModeGuideItem {
+ mode: "direct" | "route" | "stack";
+ titleKey: string;
+ descKey: string;
+}
+
+interface TourStep {
+ id: string;
+ icon: LucideIcon;
+ /** 需要切到对应全局页面再高亮的步骤;不填表示停在供应商主界面 */
+ page?: Exclude<TourPage, "providers">;
+ titleKey: string;
+ /** 正文段落的 i18n key,按顺序各占一段 */
+ bodyKeys: string[];
+ /** 辅助提示条(放在浅底圆角框里,区分主操作说明和补充提示) */
+ calloutKey?: string;
+ /** 连接模式步骤的结构化说明项 */
+ modeItems?: ModeGuideItem[];
+ /**
+ * 按顺序找,第一组在界面上的就圈它(比如有供应商时圈卡片,还没有时圈空列表)。
+ * 空的或一组都找不到时不圈,卡片居中。
+ */
+ targets: TourTarget[];
+ /** 一组都找不到时的提示条(比如当前应用没有模式切换) */
+ missingCalloutKey?: string;
+}
+
+const MODE_GUIDE_ITEMS: ModeGuideItem[] = [
+ {
+ mode: "direct",
+ titleKey: "tutorial.modes.directTitle",
+ descKey: "tutorial.modes.directDesc",
+ },
+ {
+ mode: "route",
+ titleKey: "tutorial.modes.routeTitle",
+ descKey: "tutorial.modes.routeDesc",
+ },
+ {
+ mode: "stack",
+ titleKey: "tutorial.modes.stackTitle",
+ descKey: "tutorial.modes.stackDesc",
+ },
+];
+
+const MODE_DOT_CLASS: Record<ModeGuideItem["mode"], string> = {
+ direct: "bg-direct",
+ route: "bg-route",
+ stack: "bg-stack",
+};
+
+export const TOUR_STEPS: TourStep[] = [
+ {
+ id: "welcome",
+ icon: Sparkles,
+ titleKey: "firstRunNotice.title",
+ bodyKeys: ["firstRunNotice.bodyDefault"],
+ calloutKey: "firstRunNotice.bodyBackup",
+ targets: [],
+ },
+ {
+ id: "apps",
+ icon: PanelLeft,
+ titleKey: "tutorial.apps.title",
+ bodyKeys: ["tutorial.apps.body"],
+ targets: [{ groups: [["apps"], ["nav-apps"]] }],
+ },
+ {
+ id: "providers",
+ icon: ArrowLeftRight,
+ titleKey: "tutorial.providers.title",
+ bodyKeys: ["tutorial.providers.body"],
+ calloutKey: "firstRunNotice.bodyOfficial",
+ targets: [
+ { groups: [["provider-card"]] },
+ // 新装、还没有供应商:圈空列表内容区,说明如何添加第一家
+ {
+ groups: [["provider-empty"]],
+ bodyKeys: ["tutorial.providers.empty"],
+ calloutKey: null,
+ },
+ ],
+ },
+ {
+ id: "add",
+ icon: Plus,
+ titleKey: "tutorial.add.title",
+ bodyKeys: ["tutorial.add.body"],
+ targets: [{ groups: [["add-provider"]] }],
+ },
+ {
+ id: "modes",
+ icon: Route,
+ titleKey: "tutorial.modes.title",
+ bodyKeys: ["tutorial.modes.body"],
+ modeItems: MODE_GUIDE_ITEMS,
+ // 只有 Claude Code / Codex / Gemini CLI / Grok Build / Antigravity / Claude Desktop 有这组切换;
+ // 其他应用没有时,卡片居中并用提示条说明去哪里找
+ targets: [{ groups: [["mode-tabs"]] }],
+ missingCalloutKey: "tutorial.modes.unavailable",
+ },
+ {
+ id: "shared",
+ icon: Server,
+ titleKey: "tutorial.shared.title",
+ bodyKeys: ["tutorial.shared.body"],
+ targets: [
+ {
+ groups: [
+ [
+ "nav-mcp",
+ "nav-skills",
+ "nav-plugins",
+ "nav-prompts",
+ "nav-sessions",
+ ],
+ ],
+ },
+ ],
+ },
+ {
+ id: "appsPage",
+ icon: LayoutGrid,
+ page: "apps",
+ titleKey: "tutorial.appsPage.title",
+ bodyKeys: ["tutorial.appsPage.body"],
+ calloutKey: "tutorial.appsPage.callout",
+ targets: [{ groups: [["apps-row"], ["apps-actions"]] }],
+ },
+ {
+ id: "usage",
+ icon: ChartColumn,
+ page: "usage",
+ titleKey: "tutorial.usage.title",
+ bodyKeys: ["tutorial.usage.body"],
+ calloutKey: "tutorial.usage.callout",
+ targets: [{ groups: [["usage-filters"], ["usage-actions"]] }],
+ },
+ {
+ id: "auth",
+ icon: KeyRound,
+ page: "auth",
+ titleKey: "tutorial.auth.title",
+ bodyKeys: ["tutorial.auth.body"],
+ calloutKey: "tutorial.auth.callout",
+ targets: [{ groups: [["auth-toggles"], ["auth-refresh"]] }],
+ },
+ {
+ id: "more",
+ icon: Settings,
+ titleKey: "tutorial.more.title",
+ bodyKeys: ["tutorial.more.body"],
+ calloutKey: "tutorial.more.replay",
+ targets: [{ groups: [["nav-settings"]] }],
+ },
+];
+
+interface Rect {
+ top: number;
+ left: number;
+ width: number;
+ height: number;
+}
+
+interface Viewport {
+ width: number;
+ height: number;
+}
+
+/** 圈的范围比元素本身大一圈 */
+const SPOT_PADDING = 6;
+/** 卡片和圈之间的距离 */
+const CARD_GAP = 14;
+/** 卡片离窗口边缘至少留这么多 */
+const VIEWPORT_MARGIN = 12;
+const CLIPPING_OVERFLOW = new Set(["auto", "scroll", "hidden", "clip"]);
+
+function findAnchor(anchor: TourAnchor): HTMLElement | null {
+ return document.querySelector<HTMLElement>(`[data-tour="${anchor}"]`);
+}
+
+function readViewport(): Viewport {
+ return { width: window.innerWidth, height: window.innerHeight };
+}
+
+/** 把元素矩形裁到可滚动 / 裁剪祖先的可见范围内,避免长列表的高亮框溢出到别的区块上 */
+function getClippedElementRect(el: HTMLElement): Rect | null {
+ const r = el.getBoundingClientRect();
+ if (r.width === 0 && r.height === 0) return null;
+
+ let top = r.top;
+ let left = r.left;
+ let right = r.right;
+ let bottom = r.bottom;
+
+ let parent = el.parentElement;
+ while (
+ parent &&
+ parent !== document.body &&
+ parent !== document.documentElement
+ ) {
+ const style = getComputedStyle(parent);
+ if (
+ CLIPPING_OVERFLOW.has(style.overflowY) ||
+ CLIPPING_OVERFLOW.has(style.overflowX)
+ ) {
+ const pr = parent.getBoundingClientRect();
+ if (CLIPPING_OVERFLOW.has(style.overflowY)) {
+ top = Math.max(top, pr.top);
+ bottom = Math.min(bottom, pr.bottom);
+ }
+ if (CLIPPING_OVERFLOW.has(style.overflowX)) {
+ left = Math.max(left, pr.left);
+ right = Math.min(right, pr.right);
+ }
+ }
+ parent = parent.parentElement;
+ }
+
+ if (right <= left || bottom <= top) return null;
+ return { top, left, width: right - left, height: bottom - top };
+}
+
+/** 量出这一组锚点要圈的范围(已裁到窗口内);一个元素都没找到就是 null */
+function measureAnchors(
+ anchors: TourAnchor[],
+ viewport: Viewport,
+): Rect | null {
+ let top = Infinity;
+ let left = Infinity;
+ let right = -Infinity;
+ let bottom = -Infinity;
+
+ for (const anchor of anchors) {
+ const el = findAnchor(anchor);
+ if (!el) continue;
+ const r = getClippedElementRect(el);
+ if (!r) continue;
+ top = Math.min(top, r.top);
+ left = Math.min(left, r.left);
+ right = Math.max(right, r.left + r.width);
+ bottom = Math.max(bottom, r.top + r.height);
+ }
+ if (top === Infinity) return null;
+
+ top = Math.max(top - SPOT_PADDING, 0);
+ left = Math.max(left - SPOT_PADDING, 0);
+ right = Math.min(right + SPOT_PADDING, viewport.width);
+ bottom = Math.min(bottom + SPOT_PADDING, viewport.height);
+ if (right <= left || bottom <= top) return null;
+ return { top, left, width: right - left, height: bottom - top };
+}
+
+function unionRect(rects: Rect[]): Rect | null {
+ if (rects.length === 0) return null;
+ let top = Infinity;
+ let left = Infinity;
+ let right = -Infinity;
+ let bottom = -Infinity;
+ for (const r of rects) {
+ top = Math.min(top, r.top);
+ left = Math.min(left, r.left);
+ right = Math.max(right, r.left + r.width);
+ bottom = Math.max(bottom, r.top + r.height);
+ }
+ return { top, left, width: right - left, height: bottom - top };
+}
+
+interface MeasuredTarget {
+ /** 圈的是 targets 里的第几组;-1 表示一组都不在界面上 */
+ match: number;
+ rects: Rect[];
+}
+
+const NO_TARGET: MeasuredTarget = { match: -1, rects: [] };
+
+/** 按顺序找第一组在界面上的目标 */
+function measureTargets(
+ targets: TourTarget[],
+ viewport: Viewport,
+): MeasuredTarget {
+ for (let i = 0; i < targets.length; i++) {
+ const rects = targets[i].groups
+ .map((group) => measureAnchors(group, viewport))
+ .filter((rect): rect is Rect => rect !== null);
+ if (rects.length > 0) return { match: i, rects };
+ }
+ return NO_TARGET;
+}
+
+function sameRects(a: Rect[], b: Rect[]): boolean {
+ if (a.length !== b.length) return false;
+ return a.every(
+ (ra, idx) =>
+ Math.abs(ra.top - b[idx].top) < 0.5 &&
+ Math.abs(ra.left - b[idx].left) < 0.5 &&
+ Math.abs(ra.width - b[idx].width) < 0.5 &&
+ Math.abs(ra.height - b[idx].height) < 0.5,
+ );
+}
+
+const clamp = (value: number, min: number, max: number) =>
+ Math.max(min, Math.min(value, Math.max(min, max)));
+
+type CardPlacement =
+ | "center"
+ | "right"
+ | "bottom"
+ | "left"
+ | "top"
+ | "fallback";
+
+interface CardCaret {
+ side: "left" | "top" | "right" | "bottom";
+ offset: number;
+}
+
+interface CardPosition {
+ top: number;
+ left: number;
+ placement: CardPlacement;
+ caret: CardCaret | null;
+}
+
+function overlapArea(a: Rect, b: Rect): number {
+ const x = Math.max(
+ 0,
+ Math.min(a.left + a.width, b.left + b.width) - Math.max(a.left, b.left),
+ );
+ const y = Math.max(
+ 0,
+ Math.min(a.top + a.height, b.top + b.height) - Math.max(a.top, b.top),
+ );
+ return x * y;
+}
+
+function computeCaret(
+ spot: Rect,
+ cardPos: { top: number; left: number },
+ card: { width: number; height: number },
+ placement: CardPlacement,
+): CardCaret | null {
+ const spotCenterX = spot.left + spot.width / 2;
+ const spotCenterY = spot.top + spot.height / 2;
+ const edgePadding = 22;
+
+ switch (placement) {
+ case "right":
+ return {
+ side: "left",
+ offset: Math.round(
+ clamp(
+ spotCenterY - cardPos.top,
+ edgePadding,
+ card.height - edgePadding,
+ ),
+ ),
+ };
+ case "left":
+ return {
+ side: "right",
+ offset: Math.round(
+ clamp(
+ spotCenterY - cardPos.top,
+ edgePadding,
+ card.height - edgePadding,
+ ),
+ ),
+ };
+ case "bottom":
+ return {
+ side: "top",
+ offset: Math.round(
+ clamp(
+ spotCenterX - cardPos.left,
+ edgePadding,
+ card.width - edgePadding,
+ ),
+ ),
+ };
+ case "top":
+ return {
+ side: "bottom",
+ offset: Math.round(
+ clamp(
+ spotCenterX - cardPos.left,
+ edgePadding,
+ card.width - edgePadding,
+ ),
+ ),
+ };
+ default:
+ return null;
+ }
+}
+
+/**
+ * 卡片优先放在亮框右 / 下 / 左 / 上不重叠的一侧;若四侧空间都略紧,
+ * 选与亮框重叠面积最小的位置,而不是硬压在内容区右下角。
+ */
+function placeCard(
+ spot: Rect | null,
+ card: { width: number; height: number },
+ viewport: Viewport,
+): CardPosition {
+ const vw = viewport.width;
+ const vh = viewport.height;
+ const maxLeft = vw - card.width - VIEWPORT_MARGIN;
+ const maxTop = vh - card.height - VIEWPORT_MARGIN;
+
+ if (!spot) {
+ return {
+ top: Math.round(clamp((vh - card.height) / 2, VIEWPORT_MARGIN, maxTop)),
+ left: Math.round(clamp((vw - card.width) / 2, VIEWPORT_MARGIN, maxLeft)),
+ placement: "center",
+ caret: null,
+ };
+ }
+
+ const right = spot.left + spot.width;
+ const bottom = spot.top + spot.height;
+ const spotCenterX = spot.left + spot.width / 2;
+ // 亮框偏左时卡片左对齐,偏右时右对齐,视觉连接更顺
+ const alignedX = clamp(
+ spotCenterX < vw / 2 ? spot.left : right - card.width,
+ VIEWPORT_MARGIN,
+ maxLeft,
+ );
+
+ const candidates: {
+ placement: Exclude<CardPlacement, "center" | "fallback">;
+ fits: boolean;
+ top: number;
+ left: number;
+ }[] = [
+ {
+ placement: "right",
+ fits: right + CARD_GAP + card.width <= vw - VIEWPORT_MARGIN,
+ left: clamp(right + CARD_GAP, VIEWPORT_MARGIN, maxLeft),
+ top: clamp(spot.top, VIEWPORT_MARGIN, maxTop),
+ },
+ {
+ placement: "bottom",
+ fits: bottom + CARD_GAP + card.height <= vh - VIEWPORT_MARGIN,
+ top: clamp(bottom + CARD_GAP, VIEWPORT_MARGIN, maxTop),
+ left: alignedX,
+ },
+ {
+ placement: "left",
+ fits: spot.left - CARD_GAP - card.width >= VIEWPORT_MARGIN,
+ left: clamp(spot.left - CARD_GAP - card.width, VIEWPORT_MARGIN, maxLeft),
+ top: clamp(spot.top, VIEWPORT_MARGIN, maxTop),
+ },
+ {
+ placement: "top",
+ fits: spot.top - CARD_GAP - card.height >= VIEWPORT_MARGIN,
+ top: clamp(spot.top - CARD_GAP - card.height, VIEWPORT_MARGIN, maxTop),
+ left: alignedX,
+ },
+ ];
+
+ const exact = candidates.find((c) => c.fits);
+ if (exact) {
+ const pos = {
+ top: Math.round(exact.top),
+ left: Math.round(exact.left),
+ };
+ return {
+ ...pos,
+ placement: exact.placement,
+ caret: computeCaret(spot, pos, card, exact.placement),
+ };
+ }
+
+ // 四侧都放不下时按与亮框重叠面积最小择优
+ let best = { top: maxTop, left: maxLeft, overlap: Infinity };
+ for (const c of [...candidates, { top: maxTop, left: maxLeft }]) {
+ const overlap = overlapArea(spot, {
+ top: c.top,
+ left: c.left,
+ width: card.width,
+ height: card.height,
+ });
+ if (overlap < best.overlap) {
+ best = { top: c.top, left: c.left, overlap };
+ }
+ }
+
+ return {
+ top: Math.round(best.top),
+ left: Math.round(best.left),
+ placement: "fallback",
+ caret: null,
+ };
+}
+
+function caretStyle(caret: CardCaret): {
+ className: string;
+ style: CSSProperties;
+} {
+ const base = "pointer-events-none absolute h-2.5 w-2.5 rotate-45 bg-surface";
+ switch (caret.side) {
+ case "left":
+ return {
+ className: cn(
+ base,
+ "-left-[6px] -translate-y-1/2 border-b border-l border-border",
+ ),
+ style: { top: caret.offset },
+ };
+ case "right":
+ return {
+ className: cn(
+ base,
+ "-right-[6px] -translate-y-1/2 border-r border-t border-border",
+ ),
+ style: { top: caret.offset },
+ };
+ case "top":
+ return {
+ className: cn(
+ base,
+ "-top-[6px] -translate-x-1/2 border-l border-t border-border",
+ ),
+ style: { left: caret.offset },
+ };
+ case "bottom":
+ return {
+ className: cn(
+ base,
+ "-bottom-[6px] -translate-x-1/2 border-b border-r border-border",
+ ),
+ style: { left: caret.offset },
+ };
+ }
+}
+
+interface OnboardingTourProps {
+ open: boolean;
+ /** 跳过、关闭、完成、按 Esc 都走这里 */
+ onClose: () => void;
+ /** 切到应用 / 用量 / 授权中心步骤时联动切换页面,离开或关闭时回到供应商页 */
+ onNavigatePage?: (page: TourPage) => void;
+}
+
+/**
+ * 使用教程:压暗非关注区域,在真实界面元素上开出圆角亮框,旁边放置引导卡片。
+ * 要圈的元素不在当前界面上时(比如当前应用没有模式切换),这一步退回居中卡片。
+ * 首次启动时由 FirstRunNoticeDialog 打开,设置 → 关于页可随时重新打开。
+ */
+export function OnboardingTour({
+ open,
+ onClose,
+ onNavigatePage,
+}: OnboardingTourProps) {
+ const { t } = useTranslation();
+ const titleId = useId();
+ const descId = useId();
+ const maskId = useId();
+ const [index, setIndex] = useState(0);
+ const [target, setTarget] = useState<MeasuredTarget>(NO_TARGET);
+ const [viewport, setViewport] = useState<Viewport>(readViewport);
+ const [cardSize, setCardSize] = useState({ width: 360, height: 220 });
+ const cardRef = useRef<HTMLDivElement>(null);
+ const primaryRef = useRef<HTMLButtonElement>(null);
+ const visitedSubPageRef = useRef(false);
+ const onNavigatePageRef = useRef(onNavigatePage);
+ onNavigatePageRef.current = onNavigatePage;
+
+ // 关掉时回到第一步、清掉亮框:重新打开时第一帧不会带着上次最后一步的圈
+ useEffect(() => {
+ if (open) return;
+ setIndex(0);
+ setTarget(NO_TARGET);
+ }, [open]);
+
+ const step = TOUR_STEPS[index];
+ const matchedTarget = target.match >= 0 ? step.targets[target.match] : null;
+ const bodyKeys = matchedTarget?.bodyKeys ?? step.bodyKeys;
+ const calloutKey = matchedTarget
+ ? matchedTarget.calloutKey === undefined
+ ? step.calloutKey
+ : matchedTarget.calloutKey
+ : (step.missingCalloutKey ?? step.calloutKey);
+ const isFirst = index === 0;
+ const isLast = index === TOUR_STEPS.length - 1;
+ const Icon = step.icon;
+
+ // 走到「应用 / 用量统计 / 授权中心」步骤时自动切换页面;离开或关掉教程时回到供应商页
+ useEffect(() => {
+ if (!open) {
+ if (visitedSubPageRef.current) {
+ visitedSubPageRef.current = false;
+ onNavigatePageRef.current?.("providers");
+ }
+ return;
+ }
+ if (step.page) {
+ visitedSubPageRef.current = true;
+ onNavigatePageRef.current?.(step.page);
+ } else if (visitedSubPageRef.current) {
+ visitedSubPageRef.current = false;
+ onNavigatePageRef.current?.("providers");
+ }
+ }, [open, step]);
+
+ // 换步骤时把焦点放到主按钮上
+ useEffect(() => {
+ if (!open) return;
+ primaryRef.current?.focus();
+ }, [open, step]);
+
+ // 换步骤或懒加载页面挂载出锚点后,把要圈的元素滚进视野
+ useEffect(() => {
+ if (!open) return;
+ const first = step.targets
+ .flatMap((tItem) => tItem.groups.flat())
+ .map(findAnchor)
+ .find(Boolean);
+ first?.scrollIntoView?.({ block: "nearest", inline: "nearest" });
+ }, [open, step, target.match]);
+
+ // 切换步骤或匹配分支后,在绘制前同步量一次卡片尺寸,避免首帧位置跳变
+ useLayoutEffect(() => {
+ if (!open) return;
+ const card = cardRef.current;
+ if (!card) return;
+ const w = card.offsetWidth;
+ const h = card.offsetHeight;
+ if (w > 0 && h > 0) {
+ setCardSize((prev) =>
+ prev.width === w && prev.height === h ? prev : { width: w, height: h },
+ );
+ }
+ }, [open, index, target.match]);
+
+ // 打开期间每帧同步亮框、窗口尺寸与卡片尺寸:侧栏收起展开、窗口缩放、懒加载晚到都能跟上
+ useEffect(() => {
+ if (!open) return;
+ let frame = 0;
+ let last: MeasuredTarget | undefined;
+ let lastVp = readViewport();
+ setViewport(lastVp);
+ let lastW = 0;
+ let lastH = 0;
+
+ const tick = () => {
+ const vp = readViewport();
+ if (vp.width !== lastVp.width || vp.height !== lastVp.height) {
+ lastVp = vp;
+ setViewport(vp);
+ }
+
+ const next = measureTargets(step.targets, vp);
+ if (
+ !last ||
+ next.match !== last.match ||
+ !sameRects(next.rects, last.rects)
+ ) {
+ last = next;
+ setTarget(next);
+ }
+
+ const card = cardRef.current;
+ if (card && (card.offsetWidth !== lastW || card.offsetHeight !== lastH)) {
+ lastW = card.offsetWidth;
+ lastH = card.offsetHeight;
+ if (lastW > 0 && lastH > 0) {
+ setCardSize({ width: lastW, height: lastH });
+ }
+ }
+ frame = requestAnimationFrame(tick);
+ };
+ tick();
+ return () => cancelAnimationFrame(frame);
+ }, [open, step]);
+
+ const goNext = () => {
+ if (isLast) onClose();
+ else setIndex((i) => i + 1);
+ };
+ const goBack = () => setIndex((i) => Math.max(0, i - 1));
+
+ const keyStateRef = useRef({ isFirst, isLast, onClose });
+ keyStateRef.current = { isFirst, isLast, onClose };
+
+ useEffect(() => {
+ if (!open) return;
+ const onKeyDown = (event: KeyboardEvent) => {
+ const {
+ isFirst: firstStep,
+ isLast: lastStep,
+ onClose: closeTour,
+ } = keyStateRef.current;
+
+ // 教程开启期间拦截会修改底层页面或布局的全局快捷键(如 Cmd/Ctrl+F、Cmd/Ctrl+,、Cmd/Ctrl+\)
+ if (
+ (event.metaKey || event.ctrlKey) &&
+ ["f", ",", "\\"].includes(event.key.toLowerCase())
+ ) {
+ event.preventDefault();
+ event.stopPropagation();
+ return;
+ }
+
+ if (event.key === "Escape") {
+ event.preventDefault();
+ event.stopPropagation();
+ closeTour();
+ } else if (event.key === "ArrowRight") {
+ event.preventDefault();
+ event.stopPropagation();
+ if (lastStep) closeTour();
+ else setIndex((i) => i + 1);
+ } else if (event.key === "ArrowLeft" && !firstStep) {
+ event.preventDefault();
+ event.stopPropagation();
+ setIndex((i) => Math.max(0, i - 1));
+ } else if (event.key === "Tab") {
+ // 焦点只在卡片里的按钮间打转,不会跑到压暗的界面上
+ const buttons = Array.from(
+ cardRef.current?.querySelectorAll<HTMLElement>("button") ?? [],
+ );
+ if (buttons.length === 0) return;
+ const at = buttons.indexOf(document.activeElement as HTMLElement);
+ const next =
+ at === -1
+ ? event.shiftKey
+ ? buttons.length - 1
+ : 0
+ : event.shiftKey
+ ? (at <= 0 ? buttons.length : at) - 1
+ : (at + 1) % buttons.length;
+ event.preventDefault();
+ event.stopPropagation();
+ buttons[next].focus();
+ }
+ };
+
+ window.addEventListener("keydown", onKeyDown, true);
+ return () => window.removeEventListener("keydown", onKeyDown, true);
+ }, [open]);
+
+ if (!open) return null;
+
+ const spots = target.rects;
+ const anchorBox = unionRect(spots);
+ const cardPos = placeCard(anchorBox, cardSize, viewport);
+ const caret = cardPos.caret ? caretStyle(cardPos.caret) : null;
+
+ return createPortal(
+ <div className="fixed inset-0 z-[110]" data-testid="onboarding-tour">
+ {/* 整片挡住点击:教程期间不让误点到下面的界面,也不让点击遮罩抢走按钮焦点 */}
+ <div
+ className="absolute inset-0"
+ aria-hidden="true"
+ data-testid="tour-backdrop"
+ onMouseDown={(event) => event.preventDefault()}
+ />
+
+ {/* SVG 遮罩:支持同时挖出多个独立圆角亮框,且居中步骤无需出现缩放点 */}
+ <svg
+ aria-hidden="true"
+ className="pointer-events-none fixed inset-0 h-full w-full"
+ >
+ <defs>
+ <mask id={maskId}>
+ <rect x="0" y="0" width="100%" height="100%" fill="white" />
+ {spots.map((spot, i) => (
+ <rect
+ key={i}
+ x={spot.left}
+ y={spot.top}
+ width={spot.width}
+ height={spot.height}
+ rx={10}
+ ry={10}
+ fill="black"
+ />
+ ))}
+ </mask>
+ </defs>
+ <rect
+ x="0"
+ y="0"
+ width="100%"
+ height="100%"
+ mask={`url(#${maskId})`}
+ className="fill-black/45 dark:fill-black/60"
+ />
+ </svg>
+
+ <ModalDragStrip />
+
+ {/* 每个亮框自己的高亮描边与轻柔外发光 */}
+ {spots.map((spot, i) => (
+ <div
+ key={i}
+ aria-hidden="true"
+ data-testid="tour-spotlight"
+ className="pointer-events-none fixed rounded-[10px] ring-2 ring-action shadow-[0_0_0_4px_rgba(249,115,22,0.16)]"
+ style={{
+ top: spot.top,
+ left: spot.left,
+ width: spot.width,
+ height: spot.height,
+ }}
+ />
+ ))}
+
+ <div
+ ref={cardRef}
+ role="dialog"
+ aria-modal="true"
+ aria-labelledby={titleId}
+ aria-describedby={descId}
+ tabIndex={-1}
+ className="fixed flex max-h-[calc(100vh-24px)] w-[360px] max-w-[calc(100vw-24px)] flex-col rounded-dialog border border-border bg-surface text-fg-1 shadow-v7-lg transition-[top,left] duration-300 ease-out focus:outline-none motion-reduce:transition-none"
+ style={{ top: cardPos.top, left: cardPos.left }}
+ >
+ {caret && (
+ <span
+ aria-hidden="true"
+ className={caret.className}
+ style={caret.style}
+ />
+ )}
+
+ <div className="flex items-center gap-2.5 px-5 pb-2.5 pt-4">
+ <span
+ aria-hidden="true"
+ className="flex h-7 w-7 shrink-0 items-center justify-center rounded-control bg-action-soft text-action-text"
+ >
+ <Icon className="h-4 w-4" />
+ </span>
+ <h2
+ id={titleId}
+ className="m-0 min-w-0 flex-1 text-title font-semibold text-fg-1"
+ >
+ {t(step.titleKey)}
+ </h2>
+ <span className="shrink-0 text-caption font-medium tabular-nums text-fg-3">
+ {t("tutorial.stepCounter", {
+ current: index + 1,
+ total: TOUR_STEPS.length,
+ defaultValue: `${index + 1} / ${TOUR_STEPS.length}`,
+ })}
+ </span>
+ {!isLast && (
+ <Button
+ type="button"
+ variant="quiet"
+ size="compact"
+ onClick={onClose}
+ className="-me-2 shrink-0 px-2 text-caption text-fg-3 hover:text-fg-1"
+ >
+ {t("tutorial.skip")}
+ </Button>
+ )}
+ </div>
+
+ <div
+ id={descId}
+ className="min-h-0 flex-auto space-y-2.5 overflow-y-auto px-5 pb-4 pt-1"
+ >
+ {bodyKeys.map((key) => (
+ <p
+ key={key}
+ className="m-0 whitespace-pre-line text-body leading-relaxed text-fg-2"
+ >
+ {t(key)}
+ </p>
+ ))}
+
+ {step.modeItems && (
+ <div className="divide-y divide-border overflow-hidden rounded-panel border border-border bg-muted/40">
+ {step.modeItems.map((item) => (
+ <div
+ key={item.mode}
+ className="flex items-start gap-2.5 px-3 py-2"
+ >
+ <span
+ aria-hidden="true"
+ className={cn(
+ "mt-[6px] h-2 w-2 shrink-0 rounded-full",
+ MODE_DOT_CLASS[item.mode],
+ )}
+ />
+ <div className="min-w-0">
+ <div className="text-caption font-semibold text-fg-1">
+ {t(item.titleKey)}
+ </div>
+ <div className="text-caption leading-relaxed text-fg-2">
+ {t(item.descKey)}
+ </div>
+ </div>
+ </div>
+ ))}
+ </div>
+ )}
+
+ {calloutKey && (
+ <div className="rounded-panel border border-border bg-muted/70 px-3 py-2 text-caption leading-relaxed text-fg-2">
+ {t(calloutKey)}
+ </div>
+ )}
+ </div>
+
+ <div className="flex items-center justify-between gap-3 border-t border-border px-5 py-3">
+ <div
+ className="flex items-center gap-0.5"
+ role="group"
+ aria-label={t("tutorial.progress", {
+ current: index + 1,
+ total: TOUR_STEPS.length,
+ })}
+ >
+ {TOUR_STEPS.map((s, i) => (
+ <button
+ key={s.id}
+ type="button"
+ onClick={() => setIndex(i)}
+ aria-label={t("tutorial.progress", {
+ current: i + 1,
+ total: TOUR_STEPS.length,
+ })}
+ aria-current={i === index ? "step" : undefined}
+ className="flex items-center justify-center px-0.5 py-1.5 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring rounded-sm"
+ >
+ <span
+ className={cn(
+ "h-1.5 rounded-full transition-all",
+ i === index
+ ? "w-4 bg-action"
+ : "w-1.5 bg-border-strong hover:bg-fg-3",
+ )}
+ />
+ </button>
+ ))}
+ </div>
+ <div className="flex items-center gap-2">
+ {!isFirst && (
+ <Button variant="neutral" size="compact" onClick={goBack}>
+ {t("tutorial.back")}
+ </Button>
+ )}
+ <Button
+ ref={primaryRef}
+ variant="solid"
+ size="compact"
+ onClick={goNext}
+ >
+ {isLast ? t("tutorial.done") : t("tutorial.next")}
+ </Button>
+ </div>
+ </div>
+ </div>
+ </div>,
+ document.body,
+ );
+}
diff --git a/src/components/WhatsNewDialog.tsx b/src/components/WhatsNewDialog.tsx
index e87a2907b..81494979d 100644
--- a/src/components/WhatsNewDialog.tsx
+++ b/src/components/WhatsNewDialog.tsx
@@ -155,7 +155,8 @@ export function WhatsNewDialog({
/**
* 启动时的更新摘要:当前版本比 settings.json 里记的 whatsNewSeenVersion 新,
* 就把这之间有内容的版本弹给用户看,关掉后记下当前版本。
- * 排在欢迎弹窗和「界面改版了」后面,那两个确认时会顺手记下当前版本,不会接着弹。
+ * 排在首次运行教程和「界面改版了」后面,那两个确认时会顺手记下当前版本,不会接着弹;
+ * 这次启动弹过首次运行教程的话,整个会话都不弹。
*/
export function WhatsNewNotice() {
const queryClient = useQueryClient();
@@ -168,6 +169,16 @@ export function WhatsNewNotice() {
});
const [closed, setClosed] = useState(false);
const stampedRef = useRef(false);
+ // 这次启动弹过首次运行教程:整个会话都不弹更新摘要,教程确认后只静默记下当前版本。
+ // 教程确认时本来就会记下版本,这里兜住它读不到版本、没记上的情况。
+ const [firstRunSession, setFirstRunSession] = useState(false);
+ if (
+ !firstRunSession &&
+ settings != null &&
+ settings.firstRunNoticeConfirmed !== true
+ ) {
+ setFirstRunSession(true);
+ }
const seen = settings?.whatsNewSeenVersion;
const due =
@@ -190,7 +201,7 @@ export function WhatsNewNotice() {
entries: WhatsNewEntry[];
since?: string;
} | null>(null);
- if (shown === null && entries.length > 0) {
+ if (shown === null && entries.length > 0 && !firstRunSession) {
setShown({ entries, since: seen });
}
@@ -212,12 +223,13 @@ export function WhatsNewNotice() {
}
}, [settings, currentVersion, queryClient]);
- // 区间里没有可显示的内容:静默记下当前版本,下次升级才有准确的起点
+ // 区间里没有可显示的内容、或者是首次运行:静默记下当前版本,下次升级才有准确的起点
+ const silent = entries.length === 0 || firstRunSession;
useEffect(() => {
- if (!due || entries.length > 0 || stampedRef.current) return;
+ if (!due || !silent || stampedRef.current) return;
stampedRef.current = true;
void acknowledge();
- }, [due, entries.length, acknowledge]);
+ }, [due, silent, acknowledge]);
if (!shown) return null;
diff --git a/src/components/apps/AppsPage.tsx b/src/components/apps/AppsPage.tsx
index 6b0334748..3bb8e94d2 100644
--- a/src/components/apps/AppsPage.tsx
+++ b/src/components/apps/AppsPage.tsx
@@ -607,7 +607,7 @@ export function AppsPage() {
</HelpTip>
}
actions={
- <>
+ <div data-tour="apps-actions" className="flex items-center gap-2">
<span className="whitespace-nowrap text-caption text-fg-3">
{lastChecked}
</span>
@@ -699,7 +699,7 @@ export function AppsPage() {
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
- </>
+ </div>
}
/>
@@ -874,7 +874,11 @@ function AppRow({
const { t } = useTranslation();
const dragHandle = useContext(DragHandleContext);
return (
- <div data-tool-row={app} className="group relative px-4 py-3">
+ <div
+ data-tool-row={app}
+ data-tour="apps-row"
+ className="group relative px-4 py-3"
+ >
{dragHandle && (
// 放在行首的内边距里,不占列宽,表头和各列照旧对齐
<button
diff --git a/src/components/providers/DshAccount.tsx b/src/components/providers/DshAccount.tsx
index f3313b71e..f4ce3a109 100644
--- a/src/components/providers/DshAccount.tsx
+++ b/src/components/providers/DshAccount.tsx
@@ -306,7 +306,10 @@ export function DshAccountCard({ status }: { status: DshAccountStatus }) {
}
const balance = status.wallets.map(formatWallet).join(" · ");
return (
- <div className="group relative rounded-panel border border-border bg-surface transition-[border-color,box-shadow,background-color] duration-150 hover:border-border-strong hover:shadow-v7-sm">
+ <div
+ data-tour="provider-card"
+ className="group relative rounded-panel border border-border bg-surface transition-[border-color,box-shadow,background-color] duration-150 hover:border-border-strong hover:shadow-v7-sm"
+ >
<div className="flex min-h-[58px] items-center gap-3 py-2.5 pe-3 ps-2">
<span className="w-4 shrink-0" />
<ProviderIconBox
diff --git a/src/components/providers/ProviderCard.tsx b/src/components/providers/ProviderCard.tsx
index 02905b3e7..ed059178d 100644
--- a/src/components/providers/ProviderCard.tsx
+++ b/src/components/providers/ProviderCard.tsx
@@ -506,6 +506,7 @@ export function ProviderCard({
);
return (
<div
+ data-tour="provider-card"
className={cn(
"group relative rounded-panel border transition-[border-color,box-shadow,background-color] duration-150",
presentation.tone
diff --git a/src/components/providers/ProviderEmptyState.tsx b/src/components/providers/ProviderEmptyState.tsx
index 8afb92835..81171f05a 100644
--- a/src/components/providers/ProviderEmptyState.tsx
+++ b/src/components/providers/ProviderEmptyState.tsx
@@ -39,47 +39,52 @@ export function ProviderEmptyState({
return (
<div className="flex flex-col items-center justify-center px-6 py-16 text-center">
- <div className="mb-5 flex h-14 w-14 items-center justify-center rounded-2xl border border-border bg-subtle text-fg-2">
- <Server className="h-6 w-6" strokeWidth={1.5} aria-hidden="true" />
- </div>
- <h2 className="text-section text-fg-1">
- {emptyCopyNs
- ? t(`${emptyCopyNs}.empty.title`)
- : t("provider.noProviders")}
- </h2>
- {emptyCopyNs && (
- <p className="mt-2 max-w-lg text-body text-fg-2">
- {t(`${emptyCopyNs}.empty.description`)}
- </p>
- )}
- {showKeyFieldsHint && (
- <p className="mt-2 max-w-lg text-body text-fg-2">
- {t("provider.noProvidersDescriptionKeyFields")}
- </p>
- )}
- {(onImport || onCreate) && (
- <div className="mt-5 flex flex-wrap items-center justify-center gap-2">
- {onImport && (
- <Button variant="neutral" size="regular" onClick={onImport}>
- <Download className="h-4 w-4" />
- {appId === "claude-desktop"
- ? t("provider.importFromClaude")
- : t("provider.importCurrent")}
- </Button>
- )}
- {onCreate && (
- <Button variant="neutral" size="regular" onClick={onCreate}>
- <Plus className="h-4 w-4" />
- {t("provider.addProvider")}
- </Button>
- )}
- {!emptyCopyNs && onImport && (
- <HelpTip title={t("provider.noProviders")}>
- {t("provider.noProvidersDescription")}
- </HelpTip>
- )}
+ <div
+ data-tour="provider-empty"
+ className="flex max-w-lg flex-col items-center rounded-panel px-6 py-4"
+ >
+ <div className="mb-5 flex h-14 w-14 items-center justify-center rounded-2xl border border-border bg-subtle text-fg-2">
+ <Server className="h-6 w-6" strokeWidth={1.5} aria-hidden="true" />
</div>
- )}
+ <h2 className="text-section text-fg-1">
+ {emptyCopyNs
+ ? t(`${emptyCopyNs}.empty.title`)
+ : t("provider.noProviders")}
+ </h2>
+ {emptyCopyNs && (
+ <p className="mt-2 max-w-lg text-body text-fg-2">
+ {t(`${emptyCopyNs}.empty.description`)}
+ </p>
+ )}
+ {showKeyFieldsHint && (
+ <p className="mt-2 max-w-lg text-body text-fg-2">
+ {t("provider.noProvidersDescriptionKeyFields")}
+ </p>
+ )}
+ {(onImport || onCreate) && (
+ <div className="mt-5 flex flex-wrap items-center justify-center gap-2">
+ {onImport && (
+ <Button variant="neutral" size="regular" onClick={onImport}>
+ <Download className="h-4 w-4" />
+ {appId === "claude-desktop"
+ ? t("provider.importFromClaude")
+ : t("provider.importCurrent")}
+ </Button>
+ )}
+ {onCreate && (
+ <Button variant="neutral" size="regular" onClick={onCreate}>
+ <Plus className="h-4 w-4" />
+ {t("provider.addProvider")}
+ </Button>
+ )}
+ {!emptyCopyNs && onImport && (
+ <HelpTip title={t("provider.noProviders")}>
+ {t("provider.noProvidersDescription")}
+ </HelpTip>
+ )}
+ </div>
+ )}
+ </div>
</div>
);
}
diff --git a/src/components/providers/QoderPanel.tsx b/src/components/providers/QoderPanel.tsx
index 9039b0848..3ae5ede21 100644
--- a/src/components/providers/QoderPanel.tsx
+++ b/src/components/providers/QoderPanel.tsx
@@ -154,6 +154,7 @@ function QoderEditionPanel({
<Button
variant="solid"
size="regular"
+ data-tour="add-provider"
disabled={!query.data || busy}
onClick={() => setEditing({})}
>
diff --git a/src/components/providers/mode/ModeTabs.tsx b/src/components/providers/mode/ModeTabs.tsx
index 03e436e98..d24ed3d72 100644
--- a/src/components/providers/mode/ModeTabs.tsx
+++ b/src/components/providers/mode/ModeTabs.tsx
@@ -82,6 +82,7 @@ export function ModeTabs({
ref={indicator.ref}
role="group"
aria-label={t("mode.tabsLabel")}
+ data-tour="mode-tabs"
className="relative inline-flex h-9 shrink-0 items-center gap-0.5 rounded-[10px] bg-subtle p-[3px]"
>
<SegmentThumb
diff --git a/src/components/settings/AboutSection.tsx b/src/components/settings/AboutSection.tsx
index 09a237ae5..a38c9c6d8 100644
--- a/src/components/settings/AboutSection.tsx
+++ b/src/components/settings/AboutSection.tsx
@@ -5,6 +5,7 @@ import {
ExternalLink,
Github,
Globe,
+ GraduationCap,
Info,
Loader2,
RefreshCw,
@@ -20,6 +21,7 @@ import { providersApi, settingsApi } from "@/lib/api";
import { useUpdate } from "@/contexts/UpdateContext";
import { Badge } from "@/components/ui/badge";
import { WhatsNewDialog } from "@/components/WhatsNewDialog";
+import { startOnboardingTour } from "@/lib/onboardingTour";
import { WHATS_NEW_ENTRIES, entriesUpTo } from "@/lib/whatsNew";
import ccswitchLogo from "@/assets/icons/logo.svg";
import { extractErrorMessage } from "@/utils/errorUtils";
@@ -385,6 +387,15 @@ export function AboutSection({
{t("whatsNew.recentTitle")}
</Button>
)}
+ <Button
+ type="button"
+ variant="neutral"
+ size="compact"
+ onClick={startOnboardingTour}
+ >
+ <GraduationCap className="h-3.5 w-3.5" />
+ {t("tutorial.open")}
+ </Button>
</div>
{/* 下载与更新都走 ccswitch.io,用户不再经过仓库页,邀 Star 单独占一行;按钮即 GitHub 入口。
diff --git a/src/components/settings/AuthCenterPanel.tsx b/src/components/settings/AuthCenterPanel.tsx
index 3f7ea41f5..de7d4f577 100644
--- a/src/components/settings/AuthCenterPanel.tsx
+++ b/src/components/settings/AuthCenterPanel.tsx
@@ -266,8 +266,10 @@ export function AuthCenterPanel({
{t("settings.authCenter.description")}
</p>
)}
- <OpenBrowserToggle />
- <AutoQuotaToggle />
+ <div data-tour="auth-toggles" className="flex flex-col gap-3">
+ <OpenBrowserToggle />
+ <AutoQuotaToggle />
+ </div>
{cards.map((card, index) => {
// 多张卡片时,最后一张贴近底部,说明卡向上弹;只有一张时贴近顶部,照常向下弹
const helpSide: HelpSide =
diff --git a/src/components/shell/Sidebar.tsx b/src/components/shell/Sidebar.tsx
index 78a80ae76..7785a5542 100644
--- a/src/components/shell/Sidebar.tsx
+++ b/src/components/shell/Sidebar.tsx
@@ -45,6 +45,7 @@ import { useSidebarStatus, type AppNavStatus } from "@/hooks/useSidebarStatus";
import { HoverTip } from "@/components/ui/hover-tip";
import { DRAG_REGION_ATTR, DRAG_REGION_STYLE, isMac } from "@/lib/platform";
import { cn } from "@/lib/utils";
+import type { TourAnchor } from "@/components/OnboardingTour";
import ccswitchLogo from "@/assets/icons/logo.svg";
import { APP_DISPLAY_NAME, AppGlyph } from "./AppGlyph";
@@ -309,6 +310,7 @@ function MainDirectory({
<div
role="group"
aria-label={t("nav.appsGroup")}
+ data-tour="apps"
className="flex shrink-0 flex-col"
>
{apps.map((app) => (
@@ -342,6 +344,7 @@ function MainDirectory({
trailing={item.trailing}
trailingLabel={item.trailingLabel}
alert={item.alert}
+ tourAnchor={`nav-${item.page}` as TourAnchor}
onClick={() => onSelectPage(item.page)}
/>
))}
@@ -372,6 +375,7 @@ function MainDirectory({
appsUpdateAvailable ? t("nav.appsHasUpdate") : t("nav.appsTitle")
}
dot={appsUpdateAvailable}
+ tourAnchor="nav-apps"
onClick={() => onSelectPage("apps")}
/>
<NavItem
@@ -383,6 +387,7 @@ function MainDirectory({
title={hasUpdate ? t("nav.settingsHasUpdate") : t("nav.settings")}
dot={hasUpdate}
dotTone="success"
+ tourAnchor="nav-settings"
onClick={() => onSelectPage("settings")}
/>
</div>
@@ -543,6 +548,7 @@ function NavItem({
dot = false,
dotTone = "neutral",
endDot = false,
+ tourAnchor,
onClick,
}: {
collapsed: boolean;
@@ -564,6 +570,8 @@ function NavItem({
dotTone?: "neutral" | "success";
/** 圆点放在行尾(设置目录里的「关于」),而不是图标角上 */
endDot?: boolean;
+ /** 使用教程圈这一项时找它用 */
+ tourAnchor?: TourAnchor;
onClick: () => void;
}) {
const ring = selected ? "border-selected" : "border-sidebar";
@@ -614,6 +622,7 @@ function NavItem({
onClick={onClick}
aria-label={title ?? accessibleName}
aria-current={selected ? "page" : undefined}
+ data-tour={tourAnchor}
className={cn(
"mx-auto flex h-8 w-rail-item shrink-0 items-center justify-center rounded-control transition-colors hover:bg-subtle",
selected && "bg-selected hover:bg-selected",
@@ -644,6 +653,7 @@ function NavItem({
onClick={onClick}
aria-label={trailingLabel ? accessibleName : undefined}
aria-current={selected ? "page" : undefined}
+ data-tour={tourAnchor}
className={cn(
"flex h-nav-row shrink-0 items-center gap-2 rounded-control px-2 text-start transition-colors hover:bg-subtle",
// 底栏两项按各自文字分宽度:「Apps」这类短词不必占满一半,长词(Optionen、Настройки)才放得下
diff --git a/src/components/usage/UsageDashboard.tsx b/src/components/usage/UsageDashboard.tsx
index b22e52ef4..5da8a0b48 100644
--- a/src/components/usage/UsageDashboard.tsx
+++ b/src/components/usage/UsageDashboard.tsx
@@ -520,7 +520,10 @@ export function UsageDashboard({
});
const headerActions = (
- <div className="flex h-8 shrink-0 items-stretch overflow-hidden rounded-control border border-border-strong bg-surface">
+ <div
+ data-tour="usage-actions"
+ className="flex h-8 shrink-0 items-stretch overflow-hidden rounded-control border border-border-strong bg-surface"
+ >
<HoverTip
content={
sessionAutoSyncEnabled
@@ -601,7 +604,10 @@ export function UsageDashboard({
// 范围栏:决定下面所有数据的四个条件放一组、左对齐;时间排第一,图表和指标都跟着它
const filterRow = (
- <div className="flex min-h-12 shrink-0 flex-wrap items-center gap-2 px-6 py-2">
+ <div
+ data-tour="usage-filters"
+ className="flex min-h-12 shrink-0 flex-wrap items-center gap-2 px-6 py-2"
+ >
<UsageDateRangePicker
selection={range}
triggerLabel={rangeLabel}
diff --git a/src/i18n/locales/de.json b/src/i18n/locales/de.json
index d3c95e015..216ff4965 100644
--- a/src/i18n/locales/de.json
+++ b/src/i18n/locales/de.json
@@ -53,9 +53,66 @@
},
"firstRunNotice": {
"title": "Willkommen bei CC Switch",
- "bodyDefault": "Mit CC Switch wechseln Sie mit einem Klick zwischen mehreren Anbietern für Claude Code / Codex / Gemini CLI. Wenn Sie diese Tools bereits konfiguriert hatten, hat CC Switch Ihre bestehende Einrichtung als Anbieter mit dem Namen „default“ gespeichert, sodass keine Ihrer bisherigen Konfigurationen verloren geht.",
- "bodyOfficial": "In der Liste finden Sie außerdem eine Voreinstellung „Official“ – klicken Sie darauf, wenn Sie jederzeit zur offiziellen Standardeinstellung zurückwechseln möchten. CC Switch sichert Ihre aktuelle Konfiguration vor dem Wechsel automatisch unter „default“, sodass Sie frei hin- und herwechseln können. So funktioniert CC Switch 😊",
- "confirm": "Verstanden"
+ "bodyDefault": "Mit CC Switch wechseln Sie mit einem Klick zwischen Anbietern für Claude Code, Codex, Gemini CLI und weitere KI-Coding-Tools und verwalten MCP, Skills, Plugins sowie Sitzungen zentral.",
+ "bodyBackup": "Wenn Sie diese Tools bereits konfiguriert hatten, hat CC Switch Ihre bestehende Einrichtung automatisch als Anbieter „default“ gespeichert, sodass keine Konfiguration verloren geht.",
+ "bodyOfficial": "Eine Voreinstellung „Official“ ist ebenfalls enthalten, damit Sie jederzeit zu den offiziellen Standardwerten zurückkehren können. Vor jedem Wechsel sichert CC Switch Ihre aktuelle Konfiguration automatisch unter „default“."
+ },
+ "tutorial": {
+ "open": "Einführung",
+ "progress": "Schritt {{current}} von {{total}}",
+ "stepCounter": "{{current}} / {{total}}",
+ "skip": "Überspringen",
+ "back": "Zurück",
+ "next": "Weiter",
+ "done": "Loslegen",
+ "apps": {
+ "title": "App auswählen",
+ "body": "Diese Seitenleiste zeigt die von CC Switch verwalteten Apps (Claude Code, Codex, Gemini CLI usw.). Wählen Sie eine App aus, um rechts ihre Anbieter zu sehen. Über „Apps“ unten können Sie Tools installieren oder festlegen, welche Apps hier angezeigt werden."
+ },
+ "providers": {
+ "title": "Anbieter wechseln & verwalten",
+ "body": "Jede Karte steht für einen Anbieter. Klicken Sie rechts auf der Karte auf das Aktionssymbol (z. B. „Wechseln ▶“ oder „Aktivieren“), um ihn in die Konfigurationsdatei der App zu schreiben – oder wechseln Sie schnell über das Tray-Menü.",
+ "empty": "Diese App hat noch keine Anbieter. Klicken Sie unten auf „Aktuelle Konfiguration importieren“ oder „Anbieter hinzufügen“, um Ihre erste Karte anzulegen, und aktivieren Sie sie anschließend über das Aktionssymbol der Karte."
+ },
+ "add": {
+ "title": "Anbieter hinzufügen",
+ "body": "Klicken Sie hier, um einen Anbieter hinzuzufügen. Für gängige Dienste gibt es fertige Voreinstellungen – einfach auswählen und API-Schlüssel einfügen, oder einen eigenen Endpunkt samt Modellen eintragen."
+ },
+ "modes": {
+ "title": "Verbindungsmodi",
+ "body": "Bei unterstützten Apps legen Sie in der oberen Leiste fest, wie Anfragen gesendet werden:",
+ "directTitle": "Direkt",
+ "directDesc": "Standardmodus. Die App verbindet sich ohne lokalen Proxy direkt mit dem aktiven Anbieter.",
+ "routeTitle": "Routing",
+ "routeDesc": "Anfragen laufen über den lokalen Routing-Dienst von CC Switch – für nahtlosen Wechsel, Failover-Warteschlangen und Nutzungserfassung.",
+ "stackTitle": "Aggregation",
+ "stackDesc": "Für Claude Code, Codex, Antigravity und Claude Desktop direkt in den oberen Tabs auswählbar, um Modelle mehrerer Anbieter gemeinsam bereitzustellen.",
+ "unavailable": "Die aktuelle App verwendet keine Verbindungsmodi. Wählen Sie Claude Code, Codex, Gemini CLI, Grok Build, Antigravity oder Claude Desktop, um die Modus-Tabs oben anzuzeigen."
+ },
+ "shared": {
+ "title": "MCP, Skills, Plugins, Prompts & Sitzungen",
+ "body": "Auf den Seiten MCP, Skills und Prompts verwalten Sie gemeinsame Konfigurationen zentral und synchronisieren jeden Eintrag mit ausgewählten Apps. Unter „Plugins“ verwalten Sie offizielle CLI-Plugins je App, und unter „Sitzungen“ durchsuchen und setzen Sie frühere Gespräche fort."
+ },
+ "more": {
+ "title": "Optionen & Einstellungen",
+ "body": "In den „Optionen“ passen Sie allgemeine Einstellungen, Konfigurationsordner, lokales Routing, Netzwerk und Datensicherungen an.",
+ "replay": "Möchten Sie die Einführung erneut ansehen? Sie können sie jederzeit unter Optionen → Über wieder öffnen."
+ },
+ "appsPage": {
+ "title": "Apps & Seitenleiste verwalten",
+ "body": "Erkennen, installieren und aktualisieren Sie CLI-Tools hier zentral. Mit den Schaltern rechts steuern Sie die Sichtbarkeit in der Seitenleiste; installierte Zeilen lassen sich per Ziehen neu anordnen.",
+ "callout": "Oben rechts prüfen Sie auf Tool-Updates, diagnostizieren Installationskonflikte oder kopieren manuelle Installations- und Deinstallationsbefehle."
+ },
+ "usage": {
+ "title": "Nutzung & Anfragenprotokoll",
+ "body": "Filtern Sie Anfragen, Tokens, Cache-Trefferquote und Kosten nach Zeitraum, App, Anbieter oder Modell und prüfen Sie Trends, Heatmap und Detailprotokolle.",
+ "callout": "Oben rechts synchronisieren Sie Sitzungsprotokolle sofort oder öffnen über das Zahnrad Sync-Intervall, Spalten und Modellpreise."
+ },
+ "auth": {
+ "title": "Konten & Abonnements",
+ "body": "Verwalten Sie Anmeldungen und Kontingente für Claude, GitHub Copilot, ChatGPT, xAI, Kimi, DeepSeek und weitere Dienste an einem Ort.",
+ "callout": "Deaktivieren Sie das automatische Öffnen des Browsers für getrennte Browser-Profile, oder aktualisieren Sie oben rechts alle Kontingente auf einmal."
+ }
},
"apiKeyInput": {
"placeholder": "API-Schlüssel eingeben",
diff --git a/src/i18n/locales/en.json b/src/i18n/locales/en.json
index 2fbc01eda..c8ff17d4e 100644
--- a/src/i18n/locales/en.json
+++ b/src/i18n/locales/en.json
@@ -53,9 +53,66 @@
},
"firstRunNotice": {
"title": "Welcome to CC Switch",
- "bodyDefault": "CC Switch lets you switch between multiple Claude Code / Codex / Gemini CLI providers with a single click. If you already had these tools configured, CC Switch has saved your existing setup as a provider named “default” so none of your previous configuration is lost.",
- "bodyOfficial": "An “Official” preset is also included in the list — click it any time you want to switch back to the official default. CC Switch automatically backs up your current config to “default” before switching, so you can move back and forth freely. That's how CC Switch works 😊",
- "confirm": "Got it"
+ "bodyDefault": "CC Switch lets you switch providers for Claude Code, Codex, Gemini CLI, and other AI coding tools in one click, while managing shared MCP servers, Skills, plugins, and sessions.",
+ "bodyBackup": "If you already had these tools configured, CC Switch has automatically saved your existing setup as a provider named “default” so none of your configuration is lost.",
+ "bodyOfficial": "An “Official” preset is also included so you can jump back to official defaults any time. Before switching, CC Switch backs up your current config to “default”, so feel free to switch back and forth."
+ },
+ "tutorial": {
+ "open": "Tutorial",
+ "progress": "Step {{current}} of {{total}}",
+ "stepCounter": "{{current}} / {{total}}",
+ "skip": "Skip",
+ "back": "Back",
+ "next": "Next",
+ "done": "Get started",
+ "apps": {
+ "title": "Pick an app",
+ "body": "This sidebar list shows the apps CC Switch manages (Claude Code, Codex, Gemini CLI, and more). Select one to view its providers on the right. Use “Apps” at the bottom to install tools or choose which apps appear here."
+ },
+ "providers": {
+ "title": "Switch & manage providers",
+ "body": "Each card is a provider. Click the action icon on the right of a card (such as Switch ▶ or Enable) to write it into that app's config file, or switch quickly from the tray menu.",
+ "empty": "This app has no providers yet. Click “Import current” or “Add provider” below to create your first card, then activate it from the card's action icon."
+ },
+ "add": {
+ "title": "Add a provider",
+ "body": "Click here to add a provider. Presets are ready for common services—pick one and paste your API key, or enter a custom endpoint and models."
+ },
+ "modes": {
+ "title": "Connection modes",
+ "body": "Supported apps let you switch how requests are routed from the top bar:",
+ "directTitle": "Direct",
+ "directDesc": "Default mode. The app connects directly to the active provider without a local proxy.",
+ "routeTitle": "Routing",
+ "routeDesc": "Requests go through CC Switch's local proxy for hot-switching, failover queues, and usage tracking.",
+ "stackTitle": "Aggregation",
+ "stackDesc": "Switch directly to Aggregation in the top tabs for Claude Code, Codex, Antigravity, and Claude Desktop to expose models from multiple providers together.",
+ "unavailable": "The current app doesn't use connection modes. Select Claude Code, Codex, Gemini CLI, Grok Build, Antigravity, or Claude Desktop to see the mode tabs at the top."
+ },
+ "shared": {
+ "title": "MCP, Skills, Plugins, Prompts & Sessions",
+ "body": "The MCP, Skills, and Prompts pages manage shared configurations in one place and sync each item to chosen apps. Use Plugins to install and toggle official CLI plugins per app, and Sessions to browse and resume past conversations."
+ },
+ "more": {
+ "title": "Settings & preferences",
+ "body": "Configure general preferences, app config directories, local proxy routing and failover, network settings, and data backups in Settings.",
+ "replay": "Want to see this again? Reopen the tutorial anytime from Settings → About."
+ },
+ "appsPage": {
+ "title": "Manage apps & sidebar",
+ "body": "Detect, install, and update supported CLI tools here. Use the switches on the right to control sidebar visibility, and drag installed rows to reorder them.",
+ "callout": "Use the top-right actions to check for tool updates, diagnose install conflicts, or copy manual install and uninstall commands."
+ },
+ "usage": {
+ "title": "Usage & request logs",
+ "body": "Filter requests, tokens, cache hit rate, and estimated cost by date range, app, provider, or model, with trend charts, heatmaps, and detailed request logs below.",
+ "callout": "Use the top-right controls to sync session logs immediately, or open the gear drawer to adjust sync intervals, table columns, and model pricing."
+ },
+ "auth": {
+ "title": "Accounts & subscriptions",
+ "body": "Manage sign-ins and subscription quotas for Claude, GitHub Copilot, ChatGPT, xAI, Kimi, DeepSeek, and more in one place.",
+ "callout": "Turn off auto-open browser to copy login links for separate browser profiles, or use Refresh all in the header to update every account's quota."
+ }
},
"apiKeyInput": {
"placeholder": "Enter API Key",
diff --git a/src/i18n/locales/ja.json b/src/i18n/locales/ja.json
index 252990db0..5aaf37287 100644
--- a/src/i18n/locales/ja.json
+++ b/src/i18n/locales/ja.json
@@ -53,9 +53,66 @@
},
"firstRunNotice": {
"title": "CC Switch へようこそ",
- "bodyDefault": "CC Switch は Claude Code / Codex / Gemini CLI の複数プロバイダーをワンクリックで切り替えられるツールです。すでにこれらのツールを設定済みの場合、CC Switch は現在の設定を「default」という名前のプロバイダーとして自動的に保存するので、既存の設定が失われることはありません。",
- "bodyOfficial": "リストには「Official(公式)」プリセットも用意されており、公式バージョンに戻したくなったらクリックするだけで切り替えられます。切り替える前に現在の設定は自動で default にバックアップされるので、自由に行き来できます。これが CC Switch の仕組みです 😊",
- "confirm": "了解しました"
+ "bodyDefault": "CC Switch は Claude Code、Codex、Gemini CLI などの AI コーディングツールのプロバイダーをワンクリックで切り替え、MCP・Skills・プラグイン・セッションをまとめて管理できるツールです。",
+ "bodyBackup": "すでにこれらのツールを設定済みの場合、CC Switch は現在の設定を「default」という名前のプロバイダーとして自動的に保存しているため、既存の設定は失われません。",
+ "bodyOfficial": "「Official(公式)」プリセットも用意されており、いつでも公式設定に戻せます。切り替える前に現在の設定は自動で default にバックアップされるため、安心して行き来できます。"
+ },
+ "tutorial": {
+ "open": "チュートリアル",
+ "progress": "ステップ {{current}} / {{total}}",
+ "stepCounter": "{{current}} / {{total}}",
+ "skip": "スキップ",
+ "back": "戻る",
+ "next": "次へ",
+ "done": "使い始める",
+ "apps": {
+ "title": "アプリを選ぶ",
+ "body": "サイドバーのこの列は CC Switch が管理するアプリ(Claude Code、Codex、Gemini CLI など)です。選ぶと右側にそのアプリのプロバイダーが表示されます。ツールの導入や表示するアプリの調整は下の「アプリ」から行えます。"
+ },
+ "providers": {
+ "title": "プロバイダーの切り替えと管理",
+ "body": "カード 1 枚が 1 つのプロバイダーです。カード右側の操作アイコン(「切り替え ▶」や「有効化」など)をクリックすると設定ファイルに書き込まれます。トレイメニューからもすばやく切り替えられます。",
+ "empty": "このアプリにはまだプロバイダーがありません。下の「現在の設定をインポート」または「プロバイダーを追加」から最初のカードを作成すると、カード右側のボタンから切り替え・有効化できるようになります。"
+ },
+ "add": {
+ "title": "プロバイダーを追加",
+ "body": "ここから新しいプロバイダーを追加します。主要なサービスはプリセットが用意されているため、選んで API Key を入力するだけで設定できます。カスタム接続先にも対応しています。"
+ },
+ "modes": {
+ "title": "接続モード:直接接続・ルーティング・集約",
+ "body": "対応アプリではページ上部からリクエストの接続方式を切り替えられます:",
+ "directTitle": "直接接続",
+ "directDesc": "既定のモード。ローカルプロキシを通さず、アプリが選択中のプロバイダーに直接接続します。",
+ "routeTitle": "ルーティング",
+ "routeDesc": "このマシン上のローカルルーティングサービスを経由し、ホットスイッチ・キューによるフェイルオーバー・使用量記録を行います。",
+ "stackTitle": "集約",
+ "stackDesc": "Claude Code・Codex・Antigravity・Claude Desktop では上部タブから直接「集約」に切り替え、複数プロバイダーのモデルをモデル一覧にまとめて表示できます。",
+ "unavailable": "現在のアプリには接続モードの切り替えがありません。Claude Code、Codex、Gemini CLI、Grok Build、Antigravity、Claude Desktop を選ぶとページ上部にモードタブが表示されます。"
+ },
+ "shared": {
+ "title": "MCP・Skills・プラグイン・プロンプト・セッション",
+ "body": "MCP、Skills、プロンプトの各ページで共通設定を一元管理し、項目ごとに同期先のアプリを選べます。「プラグイン」では各アプリの公式プラグインを管理でき、「セッション」では過去の会話を閲覧・再開できます。"
+ },
+ "more": {
+ "title": "設定とチュートリアル",
+ "body": "「設定」では一般設定、設定フォルダー、ローカルルーティングとフェイルオーバー、ネットワーク、WebDAV バックアップなどを調整できます。",
+ "replay": "もう一度見たいときは「設定 → 情報」からいつでもこのチュートリアルを開けます。"
+ },
+ "appsPage": {
+ "title": "アプリ管理とサイドバー",
+ "body": "対応 CLI ツールの検出・インストール・アップデートをまとめて管理できます。右側のスイッチでサイドバーへの表示を切り替え、インストール済みアプリはドラッグで並び替えられます。",
+ "callout": "右上からツール更新の確認や「⋯」メニューでの競合診断、手動インストール/アンインストールコマンドの確認ができます。"
+ },
+ "usage": {
+ "title": "使用量とリクエスト履歴",
+ "body": "上部のフィルターで期間・アプリ・プロバイダー・モデルごとにリクエスト数、トークン、キャッシュヒット率、費用を絞り込み、推移グラフや明細を確認できます。",
+ "callout": "右上からセッションログの即時同期ができ、歯車アイコンから同期頻度・表示列・モデル単価を設定できます。"
+ },
+ "auth": {
+ "title": "アカウント管理",
+ "body": "Claude、GitHub Copilot、ChatGPT、xAI、Kimi、DeepSeek などのサブスクリプションログインとクォータを一元管理します。",
+ "callout": "自動ブラウザ起動をオフにするとリンクをコピーして別プロファイルでログインできます。右上の「すべて更新」で全アカウントの残量を再取得します。"
+ }
},
"apiKeyInput": {
"placeholder": "API Key を入力",
diff --git a/src/i18n/locales/ko.json b/src/i18n/locales/ko.json
index 724da2ea0..4855cd6f4 100644
--- a/src/i18n/locales/ko.json
+++ b/src/i18n/locales/ko.json
@@ -53,9 +53,66 @@
},
"firstRunNotice": {
"title": "CC Switch에 오신 것을 환영합니다",
- "bodyDefault": "CC Switch를 사용하면 Claude Code / Codex / Gemini CLI의 여러 공급자 간에 클릭 한 번으로 전환할 수 있습니다. 이러한 도구가 이미 설정되어 있다면 CC Switch가 기존 설정을 \"default\"라는 공급자로 자동 저장하므로 기존 설정이 손실되지 않습니다.",
- "bodyOfficial": "목록에는 ‘공식(Official)’ 공급자도 미리 등록되어 있습니다. 언제든지 선택하여 공식 기본 설정으로 돌아갈 수 있습니다. CC Switch는 전환 전에 현재 설정을 ‘default’에 자동으로 백업하므로 안심하고 전환할 수 있습니다. CC Switch는 이렇게 작동합니다 😊",
- "confirm": "알겠습니다"
+ "bodyDefault": "CC Switch를 사용하면 Claude Code, Codex, Gemini CLI 등 AI 코딩 도구의 공급자를 클릭 한 번으로 전환하고 MCP, 스킬, 플러그인, 세션을 한곳에서 관리할 수 있습니다.",
+ "bodyBackup": "이러한 도구를 이미 설정해 두셨다면 CC Switch가 기존 구성을 ‘default’라는 공급자로 자동 저장해 두었으므로 기존 설정을 잃을 걱정 없이 안심하고 사용해 보세요.",
+ "bodyOfficial": "‘공식(Official)’ 프리셋도 함께 제공되므로 언제든지 공식 기본 설정으로 돌아갈 수 있습니다. 전환할 때마다 현재 설정을 ‘default’에 자동 백업하므로 자유롭게 오갈 수 있습니다."
+ },
+ "tutorial": {
+ "open": "사용 튜토리얼",
+ "progress": "{{total}}단계 중 {{current}}단계",
+ "stepCounter": "{{current}} / {{total}}",
+ "skip": "건너뛰기",
+ "back": "이전",
+ "next": "다음",
+ "done": "시작하기",
+ "apps": {
+ "title": "앱 선택",
+ "body": "사이드바의 이 목록은 CC Switch가 관리하는 앱(Claude Code, Codex, Gemini CLI 등)입니다. 앱을 선택하면 오른쪽에 해당 앱의 공급자가 표시됩니다. 도구를 설치하거나 사이드바에 표시할 앱을 고르려면 하단의 ‘앱’을 눌러 주세요."
+ },
+ "providers": {
+ "title": "공급자 전환 및 관리",
+ "body": "각 카드가 하나의 공급자입니다. 카드 오른쪽의 작업 아이콘(‘전환 ▶’ 또는 ‘활성화’ 등)을 누르면 해당 앱의 설정 파일에 반영됩니다. 트레이 메뉴에서도 빠르게 전환할 수 있습니다.",
+ "empty": "이 앱에는 아직 공급자가 없습니다. 아래의 ‘현재 설정 가져오기’ 또는 ‘공급자 추가’를 눌러 첫 카드를 만든 뒤, 카드 오른쪽 작업 아이콘으로 전환하거나 활성화할 수 있습니다."
+ },
+ "add": {
+ "title": "공급자 추가",
+ "body": "여기를 눌러 새 공급자를 추가하세요. 주요 서비스는 프리셋이 준비되어 있어 선택 후 API 키만 입력하면 되며, 사용자 지정 엔드포인트와 모델도 설정할 수 있습니다."
+ },
+ "modes": {
+ "title": "연결 모드: 직접 연결·라우팅·통합",
+ "body": "지원되는 앱에서는 상단 탭에서 요청 처리 방식을 선택할 수 있습니다:",
+ "directTitle": "직접 연결",
+ "directDesc": "기본 모드입니다. 로컬 프록시를 거치지 않고 앱이 현재 공급자에 직접 연결합니다.",
+ "routeTitle": "라우팅",
+ "routeDesc": "이 기기의 로컬 라우팅 서비스를 거쳐 요청을 전달하며, 즉시 전환, 대기열 기반 장애 조치 및 사용량 기록을 지원합니다.",
+ "stackTitle": "통합",
+ "stackDesc": "Claude Code, Codex, Antigravity 및 Claude Desktop에서는 상단 탭에서 바로 ‘통합’으로 전환하여 여러 공급자의 모델을 모델 목록에 함께 표시할 수 있습니다.",
+ "unavailable": "현재 앱은 연결 모드 전환을 지원하지 않습니다. Claude Code, Codex, Gemini CLI, Grok Build, Antigravity 또는 Claude Desktop을 선택하면 페이지 상단에 모드 탭이 나타납니다."
+ },
+ "shared": {
+ "title": "MCP·스킬·플러그인·프롬프트·세션",
+ "body": "MCP, 스킬, 프롬프트 페이지에서 공용 설정을 한곳에서 관리하고 항목별로 동기화할 앱을 고를 수 있습니다. ‘플러그인’에서는 각 앱의 공식 플러그인을 설치·관리하고, ‘세션’에서는 이전 대화를 둘러보고 이어서 진행할 수 있습니다."
+ },
+ "more": {
+ "title": "설정 및 다시 보기",
+ "body": "‘설정’에서 일반 환경설정, 설정 폴더, 로컬 라우팅 및 장애 조치, 네트워크, 데이터 백업을 조정할 수 있습니다.",
+ "replay": "다시 보고 싶다면 ‘설정 → 정보’에서 언제든 튜토리얼을 다시 열 수 있습니다."
+ },
+ "appsPage": {
+ "title": "앱 및 사이드바 관리",
+ "body": "지원되는 CLI 도구의 감지, 설치, 업데이트를 한곳에서 관리합니다. 오른쪽 스위치로 사이드바 표시 여부를 켜고 끌 수 있으며, 설치된 항목은 드래그해 순서를 바꿀 수 있습니다.",
+ "callout": "오른쪽 상단에서 업데이트 확인, 설치 충돌 진단, 수동 설치/제거 명령 확인을 바로 실행할 수 있습니다."
+ },
+ "usage": {
+ "title": "사용량 및 요청 로그",
+ "body": "상단 필터에서 기간, 앱, 공급자, 모델별로 요청 수, 토큰, 캐시 적중률과 비용을 필터링하고 추이 차트와 상세 로그를 확인합니다.",
+ "callout": "오른쪽 상단에서 세션 로그를 즉시 동기화하거나 톱니바퀴 아이콘으로 동기화 주기, 표시 열, 모델 단가를 설정하세요."
+ },
+ "auth": {
+ "title": "인증 센터",
+ "body": "Claude, GitHub Copilot, ChatGPT, xAI, Kimi, DeepSeek 등 구독 계정의 로그인 상태와 할당량을 한곳에서 관리합니다.",
+ "callout": "브라우저 자동 열기를 끄면 링크를 복사해 별도 브라우저 프로필로 로그인할 수 있으며, 상단 ‘전체 새로고침’으로 모든 할당량을 한 번에 갱신합니다."
+ }
},
"apiKeyInput": {
"placeholder": "API 키를 입력하세요",
diff --git a/src/i18n/locales/ru.json b/src/i18n/locales/ru.json
index 7c3272a2f..efc2d7ab8 100644
--- a/src/i18n/locales/ru.json
+++ b/src/i18n/locales/ru.json
@@ -53,9 +53,66 @@
},
"firstRunNotice": {
"title": "Добро пожаловать в CC Switch",
- "bodyDefault": "CC Switch позволяет переключаться между несколькими провайдерами Claude Code / Codex / Gemini CLI одним щелчком. Если у вас уже были настроены эти инструменты, CC Switch сохранил текущую конфигурацию как провайдера с именем «default», чтобы ничего не потерялось.",
- "bodyOfficial": "В список также добавлен пресет «Официальный» — нажмите его в любой момент, чтобы вернуться к официальной конфигурации по умолчанию. Перед переключением CC Switch автоматически сохраняет текущую конфигурацию в «default», так что вы можете свободно переключаться туда и обратно.",
- "confirm": "Понятно"
+ "bodyDefault": "CC Switch позволяет в один клик переключать провайдеров для Claude Code, Codex, Gemini CLI и других ИИ-инструментов разработки, а также централизованно управлять MCP, навыками, плагинами и сессиями.",
+ "bodyBackup": "Если эти инструменты уже были настроены, CC Switch автоматически сохранил текущую конфигурацию как провайдера с именем «default», поэтому ваши прежние настройки не пропадут.",
+ "bodyOfficial": "В списке также есть пресет «Official» — вы в любой момент можете вернуться к официальным настройкам по умолчанию. Перед каждым переключением CC Switch автоматически сохраняет текущую конфигурацию в «default»."
+ },
+ "tutorial": {
+ "open": "Обучение",
+ "progress": "Шаг {{current}} из {{total}}",
+ "stepCounter": "{{current}} / {{total}}",
+ "skip": "Пропустить",
+ "back": "Назад",
+ "next": "Далее",
+ "done": "Начать работу",
+ "apps": {
+ "title": "Выбор приложения",
+ "body": "В этом разделе боковой панели показаны приложения, которыми управляет CC Switch (Claude Code, Codex, Gemini CLI и др.). Выберите приложение, чтобы увидеть его провайдеров справа. Чтобы установить инструменты или настроить список приложений, нажмите «Приложения» внизу."
+ },
+ "providers": {
+ "title": "Переключение и управление провайдерами",
+ "body": "Каждая карточка — это провайдер. Нажмите значок действия справа на карточке (например, «Переключить ▶» или «Включить»), чтобы записать его в конфиг приложения; также можно быстро переключаться из меню трея.",
+ "empty": "В этом приложении пока нет провайдеров. Нажмите «Импортировать текущую конфигурацию» или «Добавить провайдера» ниже, чтобы создать первую карточку, а затем активируйте её кнопкой действия на карточке."
+ },
+ "add": {
+ "title": "Добавление провайдера",
+ "body": "Нажмите здесь, чтобы добавить провайдера. Для популярных сервисов уже готовы пресеты — выберите нужный и вставьте API-ключ, либо укажите собственный адрес и модели."
+ },
+ "modes": {
+ "title": "Режимы подключения",
+ "body": "В поддерживаемых приложениях способ отправки запросов переключается на верхней панели:",
+ "directTitle": "Напрямую",
+ "directDesc": "Режим по умолчанию. Приложение подключается к выбранному провайдеру напрямую без локального прокси.",
+ "routeTitle": "Маршрутизация",
+ "routeDesc": "Запросы проходят через локальный прокси CC Switch: доступно горячее переключение, очередь резервирования и учёт статистики.",
+ "stackTitle": "Агрегация",
+ "stackDesc": "Для Claude Code, Codex, Antigravity и Claude Desktop можно сразу переключиться на вкладку «Агрегация» вверху, чтобы объединить модели нескольких провайдеров в одном списке.",
+ "unavailable": "Текущее приложение не использует режимы подключения. Выберите Claude Code, Codex, Gemini CLI, Grok Build, Antigravity или Claude Desktop, чтобы вверху появились вкладки режимов."
+ },
+ "shared": {
+ "title": "MCP, навыки, плагины, промпты и сессии",
+ "body": "Разделы MCP, «Навыки» и «Промпты» позволяют централизованно управлять общими настройками и синхронизировать каждый элемент с нужными приложениями. В разделе «Плагины» управляются официальные CLI-плагины приложений, а в «Сессиях» можно просматривать и продолжать прошлые диалоги."
+ },
+ "more": {
+ "title": "Настройки и параметры",
+ "body": "В «Настройках» задаются общие параметры, папки конфигураций, локальная маршрутизация, сеть и резервное копирование.",
+ "replay": "Хотите посмотреть обучение ещё раз? Его всегда можно открыть снова в разделе «Настройки → О программе»."
+ },
+ "appsPage": {
+ "title": "Приложения и боковая панель",
+ "body": "Здесь управляются обнаружение, установка и обновление CLI-инструментов. Переключатели справа скрывают или показывают приложения в боковой панели, а установленные строки можно перетаскивать.",
+ "callout": "В правом верхнем углу можно проверить обновления инструментов, диагностировать конфликты установки или скопировать команды ручной установки и удаления."
+ },
+ "usage": {
+ "title": "Статистика и журнал запросов",
+ "body": "Фильтруйте запросы, токены, попадания в кэш и расходы по периоду, приложению, провайдеру и модели, просматривая графики, тепловую карту и детальный журнал.",
+ "callout": "Справа сверху можно сразу синхронизировать журналы сессий, а через значок шестерёнки — настроить интервал, столбцы и тарифы моделей."
+ },
+ "auth": {
+ "title": "Аккаунты и подписки",
+ "body": "Управляйте входами и квотами подписок Claude, GitHub Copilot, ChatGPT, xAI, Kimi, DeepSeek и других сервисов в одном разделе.",
+ "callout": "Отключите автооткрытие браузера, чтобы копировать ссылку для разных профилей, или обновите квоты всех аккаунтов кнопкой в правом верхнем углу."
+ }
},
"apiKeyInput": {
"placeholder": "Введите API-ключ",
diff --git a/src/i18n/locales/tr.json b/src/i18n/locales/tr.json
index f6dc98209..05a235b46 100644
--- a/src/i18n/locales/tr.json
+++ b/src/i18n/locales/tr.json
@@ -53,9 +53,66 @@
},
"firstRunNotice": {
"title": "CC Switch’e hoş geldiniz",
- "bodyDefault": "CC Switch, tek bir tıklamayla birden fazla Claude Code / Codex / Gemini CLI sağlayıcısı arasında geçiş yapmanızı sağlar. Bu araçları zaten yapılandırdıysanız, CC Switch mevcut kurulumunuzu \"varsayılan\" adlı bir sağlayıcı olarak kaydetmiştir, böylece önceki yapılandırmalarınızın hiçbiri kaybolmaz.",
- "bodyOfficial": "Listede “Resmî” ön ayarı da bulunur; resmî varsayılan ayarlara dönmek istediğinizde buna tıklayın. CC Switch, geçiş yapmadan önce mevcut yapılandırmanızı “default” olarak yedekler; böylece iki yapılandırma arasında rahatça geçiş yapabilirsiniz. CC Switch böyle çalışır 😊",
- "confirm": "Anladım"
+ "bodyDefault": "CC Switch; Claude Code, Codex, Gemini CLI ve diğer yapay zeka kodlama araçları arasında tek tıkla sağlayıcı değiştirmenizi ve MCP, Beceriler, Eklentiler ile oturumları tek yerden yönetmenizi sağlar.",
+ "bodyBackup": "Bu araçları daha önce yapılandırdıysanız, CC Switch mevcut kurulumunuzu otomatik olarak “default” adlı bir sağlayıcı olarak kaydetmiştir; önceki ayarlarınız kaybolmaz.",
+ "bodyOfficial": "İstediğiniz zaman resmî varsayılanlara dönebilmeniz için “Official” ön ayarı da listede yer alır. Geçiş yapmadan önce mevcut yapılandırmanız otomatik olarak default’a yedeklenir, böylece güvenle geçiş yapabilirsiniz."
+ },
+ "tutorial": {
+ "open": "Eğitim",
+ "progress": "Adım {{current}} / {{total}}",
+ "stepCounter": "{{current}} / {{total}}",
+ "skip": "Atla",
+ "back": "Geri",
+ "next": "İleri",
+ "done": "Başla",
+ "apps": {
+ "title": "Bir uygulama seçin",
+ "body": "Bu kenar çubuğu listesi CC Switch'in yönettiği uygulamaları gösterir (Claude Code, Codex, Gemini CLI ve daha fazlası). Sağda sağlayıcılarını görmek için birini seçin. Araç yüklemek veya hangi uygulamaların görüneceğini seçmek için alttaki “Uygulamalar”ı kullanın."
+ },
+ "providers": {
+ "title": "Sağlayıcı değiştirin ve yönetin",
+ "body": "Her kart bir sağlayıcıdır. Kartın sağındaki işlem simgesine (ör. Değiştir ▶ veya Etkinleştir) tıklayarak uygulamanın yapılandırma dosyasına yazın; tepsi menüsünden de hızlıca geçiş yapabilirsiniz.",
+ "empty": "Bu uygulamada henüz sağlayıcı yok. İlk kartınızı oluşturmak için aşağıdaki “Mevcut Yapılandırmayı İçe Aktar” veya “Sağlayıcı Ekle” düğmesini kullanın; ardından kartın işlem simgesinden etkinleştirin."
+ },
+ "add": {
+ "title": "Sağlayıcı ekleyin",
+ "body": "Yeni bir sağlayıcı eklemek için buraya tıklayın. Yaygın hizmetler için hazır ön ayarlar bulunur; birini seçip API anahtarınızı yapıştırmanız yeterlidir veya özel uç nokta tanımlayabilirsiniz."
+ },
+ "modes": {
+ "title": "Bağlantı modları",
+ "body": "Desteklenen uygulamalarda üst çubuktan isteklerin nasıl iletileceğini seçebilirsiniz:",
+ "directTitle": "Doğrudan",
+ "directDesc": "Varsayılan mod. Uygulama yerel proxy olmadan doğrudan seçili sağlayıcıya bağlanır.",
+ "routeTitle": "Yönlendirme",
+ "routeDesc": "İstekler CC Switch'in yerel yönlendirme hizmetinden geçer; anlık geçiş, yedekleme sırası ve kullanım takibi sağlar.",
+ "stackTitle": "Birleştirme",
+ "stackDesc": "Claude Code, Codex, Antigravity ve Claude Desktop için üst sekmelerden doğrudan Birleştirme'ye geçerek birden fazla sağlayıcının modellerini aynı anda model listesine ekleyebilirsiniz.",
+ "unavailable": "Geçerli uygulamada bağlantı modu geçişi yok. Üstteki mod sekmelerini görmek için Claude Code, Codex, Gemini CLI, Grok Build, Antigravity veya Claude Desktop seçin."
+ },
+ "shared": {
+ "title": "MCP, Beceriler, Eklentiler, İstemler ve Oturumlar",
+ "body": "MCP, Beceriler ve İstemler sayfaları paylaşılan yapılandırmaları tek yerden yönetir ve her öğeyi seçtiğiniz uygulamalara eşitler. Eklentiler sayfasından uygulamaların resmî CLI eklentilerini yönetebilir, Oturumlar sayfasından geçmiş konuşmalara göz atıp devam edebilirsiniz."
+ },
+ "more": {
+ "title": "Ayarlar ve tercihler",
+ "body": "Ayarlar bölümünde genel tercihleri, yapılandırma klasörlerini, yerel yönlendirmeyi, ağı ve veri yedeklemelerini düzenleyebilirsiniz.",
+ "replay": "Tekrar görmek isterseniz eğitimi Ayarlar → Hakkında bölümünden istediğiniz zaman yeniden açabilirsiniz."
+ },
+ "appsPage": {
+ "title": "Uygulamalar ve kenar çubuğu",
+ "body": "Desteklenen CLI araçlarını buradan algılayıp kurun ve güncelleyin. Sağdaki anahtarlarla kenar çubuğu görünürlüğünü ayarlayabilir, kurulu satırları sürükleyerek sıralayabilirsiniz.",
+ "callout": "Sağ üstten araç güncellemelerini denetleyebilir, kurulum çakışmalarını tanılama ile kontrol edebilir veya manuel kurulum/kaldırma komutlarını kopyalayabilirsiniz."
+ },
+ "usage": {
+ "title": "Kullanım ve istek günlükleri",
+ "body": "Üstteki filtrelerden tarih aralığı, uygulama, sağlayıcı ve modele göre istekleri, token'ları, önbellek isabet oranını ve maliyeti inceleyin.",
+ "callout": "Sağ üstten oturum günlüklerini hemen eşitleyebilir veya dişli simgesiyle eşitleme sıklığını, sütunları ve model fiyatlarını düzenleyebilirsiniz."
+ },
+ "auth": {
+ "title": "Hesaplar ve abonelikler",
+ "body": "Claude, GitHub Copilot, ChatGPT, xAI, Kimi, DeepSeek ve diğer abonelik oturumları ile kotaları tek yerden yönetin.",
+ "callout": "Ayrı tarayıcı profilleri için bağlantıyı kopyalamak üzere otomatik tarayıcı açmayı kapatabilir veya sağ üstten tüm kotaları tek seferde yenileyebilirsiniz."
+ }
},
"apiKeyInput": {
"placeholder": "API Anahtarını Girin",
diff --git a/src/i18n/locales/zh-TW.json b/src/i18n/locales/zh-TW.json
index afddfcc4f..ff242271c 100644
--- a/src/i18n/locales/zh-TW.json
+++ b/src/i18n/locales/zh-TW.json
@@ -53,9 +53,66 @@
},
"firstRunNotice": {
"title": "歡迎使用 CC Switch",
- "bodyDefault": "CC Switch 可以協助您在 Claude Code / Codex / Gemini CLI 的多個供應商之間一鍵切換。如果您之前已經設定過這些工具,CC Switch 會自動將現有設定儲存為名為 default 的供應商,確保您的設定不會遺失。",
- "bodyOfficial": "清單中還預設了「官方 (Official)」供應商,隨時點擊即可切換回官方預設設定。切換前 CC Switch 會自動將目前設定備份回 default,可以放心來回切換。這就是 CC Switch 的運作方式。",
- "confirm": "我了解了"
+ "bodyDefault": "CC Switch 可以協助您在 Claude Code、Codex、Gemini CLI 等 AI 程式設計工具的多個供應商之間一鍵切換,並統一管理 MCP、Skills、外掛與歷史工作階段。",
+ "bodyBackup": "如果您之前已經設定過這些工具,CC Switch 已自動將現有設定儲存為名為「default」的供應商,可以放心試用,原有設定不會遺失。",
+ "bodyOfficial": "清單中還預設了「官方 (Official)」供應商,隨時可切換回官方設定;每次切換前 CC Switch 都會先把目前設定自動備份到 default,可以放心來回切換。"
+ },
+ "tutorial": {
+ "open": "使用教學",
+ "progress": "第 {{current}} 步,共 {{total}} 步",
+ "stepCounter": "{{current}} / {{total}}",
+ "skip": "略過",
+ "back": "上一步",
+ "next": "下一步",
+ "done": "開始使用",
+ "apps": {
+ "title": "選擇應用",
+ "body": "側欄這一列是 CC Switch 管理的應用(Claude Code、Codex、Gemini CLI 等),點選後右側就會顯示它的供應商。想安裝應用或調整側欄顯示哪些應用,可點底部的「應用」。"
+ },
+ "providers": {
+ "title": "切換與管理供應商",
+ "body": "每張卡片是一個供應商。點擊卡片右側的操作圖示(如「切換 ▶」或「啟用」)即可寫入這個應用的設定檔;系統匣選單裡也能快速切換。",
+ "empty": "這個應用還沒有供應商。可以先點擊下方的「匯入目前設定」或「新增供應商」建立第一張卡片,之後在卡片右側即可一鍵切換或啟用。"
+ },
+ "add": {
+ "title": "新增供應商",
+ "body": "點這裡新增供應商。常見服務商都準備好了預設,選中後只需填入 API Key;也支援自訂請求位址與模型。"
+ },
+ "modes": {
+ "title": "連線模式:直連、路由與聚合",
+ "body": "部分應用支援在頂部切換請求方式,按需選擇即可:",
+ "directTitle": "直連",
+ "directDesc": "預設模式。應用直接請求目前的供應商,不經過本機代理。",
+ "routeTitle": "路由",
+ "routeDesc": "請求先經過本機的路由服務,支援熱切換、按佇列做故障轉移並記錄用量。",
+ "stackTitle": "聚合",
+ "stackDesc": "Claude Code、Codex、Antigravity 和 Claude Desktop 可直接在頂部切到「聚合」,把多家供應商的模型同時放進模型清單。",
+ "unavailable": "目前的應用沒有連線模式切換。選中 Claude Code、Codex、Gemini CLI、Grok Build、Antigravity 或 Claude Desktop,頁面頂部就會出現模式標籤。"
+ },
+ "shared": {
+ "title": "MCP、Skills、外掛、提示詞與工作階段",
+ "body": "MCP、Skills 和提示詞頁面集中管理跨應用的共享設定,每一項都可以選擇同步到哪些應用;「外掛」頁面可安裝、啟停各應用的官方外掛;「工作階段」頁面用於瀏覽並恢復各個應用的歷史對話。"
+ },
+ "more": {
+ "title": "設定與重溫教學",
+ "body": "在「設定」裡可以調整一般偏好、應用設定目錄、本機路由與容錯轉移規則、網路代理及 WebDAV 資料備份。",
+ "replay": "想隨時重溫這份教學,可以在「設定 → 關於」裡重新開啟。"
+ },
+ "appsPage": {
+ "title": "管理應用與側欄",
+ "body": "這裡集中管理各 CLI 工具的偵測、安裝與升級;右側開關可控制哪些應用顯示在側欄,已安裝的應用還能拖動行首調整順序。",
+ "callout": "右上角可一鍵檢查工具更新,或在「⋯」選單裡診斷安裝衝突、檢視手動安裝與解除安裝指令。"
+ },
+ "usage": {
+ "title": "用量統計與日誌",
+ "body": "頂部篩選列可依時間範圍、應用、供應商與模型篩選請求次數、Token、快取命中率與費用,並檢視趨勢圖、熱力圖與請求明細。",
+ "callout": "右上角可立即同步各工具工作階段日誌;點齒輪圖示可調整自動同步頻率、顯示欄位、模型定價與本機路由統計。"
+ },
+ "auth": {
+ "title": "授權中心",
+ "body": "集中管理 Claude、GitHub Copilot、ChatGPT、xAI、Kimi、DeepSeek 等訂閱帳號的登入狀態與額度查詢。",
+ "callout": "可關閉「自動開啟瀏覽器」改為複製連結以多帳號登入;右上角「全部重新整理」會一併更新目前所有帳號的額度。"
+ }
},
"apiKeyInput": {
"placeholder": "請輸入 API Key",
diff --git a/src/i18n/locales/zh.json b/src/i18n/locales/zh.json
index 25a075863..2bee92adb 100644
--- a/src/i18n/locales/zh.json
+++ b/src/i18n/locales/zh.json
@@ -53,9 +53,66 @@
},
"firstRunNotice": {
"title": "欢迎使用 CC Switch",
- "bodyDefault": "CC Switch 可以帮你在 Claude Code / Codex / Gemini CLI 的多个供应商之间一键切换。如果你之前已经配置过这些工具,CC Switch 会自动把现有设置保存为名为 “default” 的供应商,保证你的配置不会丢失。",
- "bodyOfficial": "列表里还预置了 “官方(Official)” 供应商,随时点一下即可切回官方默认配置。切换前 CC Switch 会自动把当前配置备份回 default,可以放心来回切。CC Switch 就是这样工作的 😊",
- "confirm": "我知道了"
+ "bodyDefault": "CC Switch 可以帮你在 Claude Code、Codex、Gemini CLI 等 AI 编程工具的多个供应商之间一键切换,并统一管理 MCP、Skills、插件与历史会话。",
+ "bodyBackup": "如果你之前已经配置过这些工具,CC Switch 已自动把现有设置保存为名为 “default” 的供应商,可以放心试用,原有配置不会丢失。",
+ "bodyOfficial": "列表里还预置了 “官方(Official)” 供应商,随时可切回官方配置;每次切换前 CC Switch 都会先把当前配置自动备份到 default,可以放心来回切。"
+ },
+ "tutorial": {
+ "open": "使用教程",
+ "progress": "第 {{current}} 步,共 {{total}} 步",
+ "stepCounter": "{{current}} / {{total}}",
+ "skip": "跳过",
+ "back": "上一步",
+ "next": "下一步",
+ "done": "开始使用",
+ "apps": {
+ "title": "选择应用",
+ "body": "侧栏这一列是 CC Switch 管理的应用(Claude Code、Codex、Gemini CLI 等),点选后右侧就会显示它的供应商。想安装应用或调整侧栏显示哪些应用,可点底部的「应用」。"
+ },
+ "providers": {
+ "title": "切换与管理供应商",
+ "body": "每张卡片是一个供应商。点击卡片右侧的操作图标(如「切换 ▶」或「启用」)即可写入该应用的配置文件;系统托盘菜单里也能快速切换。",
+ "empty": "这个应用还没有供应商。可以先点击下方的「导入当前配置」或「添加供应商」创建第一张卡片,之后在卡片右侧即可一键切换或启用。"
+ },
+ "add": {
+ "title": "添加供应商",
+ "body": "点这里新增供应商。常见服务商都准备好了预设,选中后只需填入 API Key;也支持自定义请求地址与模型。"
+ },
+ "modes": {
+ "title": "连接模式:直连、路由与聚合",
+ "body": "部分应用支持在顶部切换请求方式,按需选择即可:",
+ "directTitle": "直连",
+ "directDesc": "默认模式。应用直接请求当前供应商,不经过本地代理。",
+ "routeTitle": "路由",
+ "routeDesc": "请求先经过本机的路由服务,支持热切换、按队列做故障转移并记录用量。",
+ "stackTitle": "聚合",
+ "stackDesc": "Claude Code、Codex、Antigravity 和 Claude Desktop 可直接在顶部切到「聚合」,把多家供应商的模型同时放进模型列表。",
+ "unavailable": "当前应用没有连接模式切换。选中 Claude Code、Codex、Gemini CLI、Grok Build、Antigravity 或 Claude Desktop,页面顶部就会出现模式标签。"
+ },
+ "shared": {
+ "title": "MCP、Skills、插件、提示词与会话",
+ "body": "MCP、Skills 和提示词页面集中管理跨应用的共享配置,每一项都可以选择同步到哪些应用;「插件」页面可安装、启停各应用的官方插件;「会话」页面用于浏览并恢复各应用的历史对话。"
+ },
+ "more": {
+ "title": "设置与重温教程",
+ "body": "在「设置」里可以调整常规偏好、应用配置目录、本地路由与故障转移规则、网络代理及 WebDAV 数据备份。",
+ "replay": "想随时重温这份教程,可以在「设置 → 关于」里重新打开。"
+ },
+ "appsPage": {
+ "title": "管理应用与侧栏",
+ "body": "这里集中管理各 CLI 工具的检测、安装与升级;右侧开关可控制哪些应用显示在侧栏,已安装的应用还能拖动行首调整顺序。",
+ "callout": "右上角可一键检查工具更新,或在「⋯」菜单里诊断安装冲突、查看手动安装与卸载命令。"
+ },
+ "usage": {
+ "title": "用量统计与日志",
+ "body": "顶部筛选栏可按时间范围、应用、供应商与模型筛选请求次数、Token、缓存命中率和费用,并查看趋势图、热力图与请求明细。",
+ "callout": "右上角可立即同步各工具会话日志;点齿轮图标可调整自动同步频率、显示列、模型定价与本地路由统计。"
+ },
+ "auth": {
+ "title": "授权中心",
+ "body": "集中管理 Claude、GitHub Copilot、ChatGPT、xAI、Kimi、DeepSeek 等订阅账号的登录状态与额度查询。",
+ "callout": "可关闭「自动打开浏览器」改为复制链接多账号登录;右上角「全部刷新」会一并更新当前所有账号的额度。"
+ }
},
"apiKeyInput": {
"placeholder": "请输入API Key",
diff --git a/src/lib/onboardingTour.ts b/src/lib/onboardingTour.ts
new file mode 100644
index 000000000..b58a5b2ef
--- /dev/null
+++ b/src/lib/onboardingTour.ts
@@ -0,0 +1,18 @@
+import { useEffect, useRef } from "react";
+
+const START_EVENT = "cc-switch:onboarding-tour-start";
+
+/** 从任何地方(如关于页)重新打开使用教程;由 App 里常驻的 FirstRunNoticeDialog 接住 */
+export function startOnboardingTour() {
+ window.dispatchEvent(new Event(START_EVENT));
+}
+
+export function useOnboardingTourRequest(onRequest: () => void) {
+ const ref = useRef(onRequest);
+ ref.current = onRequest;
+ useEffect(() => {
+ const handler = () => ref.current();
+ window.addEventListener(START_EVENT, handler);
+ return () => window.removeEventListener(START_EVENT, handler);
+ }, []);
+}
diff --git a/tests/components/DshAccountCard.test.tsx b/tests/components/DshAccountCard.test.tsx
index 22c35cb15..f23e98209 100644
--- a/tests/components/DshAccountCard.test.tsx
+++ b/tests/components/DshAccountCard.test.tsx
@@ -28,6 +28,9 @@ function renderCard(status: DshAccountStatus) {
describe("DshAccountCard", () => {
it("shows the account as an official card with its balance and no add or remove action", () => {
renderCard(signedIn);
+ expect(
+ document.querySelector('[data-tour="provider-card"]'),
+ ).toBeInTheDocument();
expect(screen.getByRole("heading", { name: "Jason" })).toBeInTheDocument();
expect(screen.getByText("providerCard.chip.official")).toBeInTheDocument();
expect(screen.getByText("dsh.account.balance")).toBeInTheDocument();
diff --git a/tests/components/FirstRunNoticeDialog.test.tsx b/tests/components/FirstRunNoticeDialog.test.tsx
new file mode 100644
index 000000000..ab2b980b7
--- /dev/null
+++ b/tests/components/FirstRunNoticeDialog.test.tsx
@@ -0,0 +1,698 @@
+import {
+ act,
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+} from "@testing-library/react";
+import { QueryClientProvider } from "@tanstack/react-query";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { createTestQueryClient } from "../utils/testQueryClient";
+
+const mocks = vi.hoisted(() => ({
+ save: vi.fn(),
+ settings: undefined as { firstRunNoticeConfirmed?: boolean } | undefined,
+}));
+
+vi.mock("@/lib/api", () => ({
+ settingsApi: { save: mocks.save },
+}));
+vi.mock("@/lib/query", () => ({
+ useSettingsQuery: () => ({ data: mocks.settings }),
+}));
+vi.mock("@tauri-apps/api/app", () => ({
+ getVersion: async () => "4.0.25",
+}));
+
+import { FirstRunNoticeDialog } from "@/components/FirstRunNoticeDialog";
+import { OnboardingTour, TOUR_STEPS } from "@/components/OnboardingTour";
+import { WindowControlsContext } from "@/components/shell/AppPageHeader";
+import { startOnboardingTour } from "@/lib/onboardingTour";
+
+function withClient(ui: React.ReactNode) {
+ const client = createTestQueryClient();
+ return <QueryClientProvider client={client}>{ui}</QueryClientProvider>;
+}
+
+const next = () =>
+ fireEvent.click(screen.getByRole("button", { name: "tutorial.next" }));
+
+describe("FirstRunNoticeDialog", () => {
+ beforeEach(() => {
+ mocks.settings = { firstRunNoticeConfirmed: undefined };
+ mocks.save.mockReset().mockResolvedValue(true);
+ });
+
+ it("walks a fresh install through the tour and records it once finished", async () => {
+ const onBeforeOpen = vi.fn();
+ const onNavigatePage = vi.fn();
+ render(
+ withClient(
+ <FirstRunNoticeDialog
+ onBeforeOpen={onBeforeOpen}
+ onNavigatePage={onNavigatePage}
+ />,
+ ),
+ );
+ expect(screen.getByText("firstRunNotice.title")).toBeInTheDocument();
+ // 首次启动不切页面:设置是异步读到的,那时切会把用户刚点开的页面拽回去
+ expect(onBeforeOpen).not.toHaveBeenCalled();
+ expect(onNavigatePage).not.toHaveBeenCalled();
+
+ // 第一步没有「上一步」,「跳过」统一放在小窗右上角
+ expect(
+ screen.queryByRole("button", { name: "tutorial.back" }),
+ ).not.toBeInTheDocument();
+ expect(
+ screen.getAllByRole("button", { name: "tutorial.skip" }),
+ ).toHaveLength(1);
+
+ for (const step of TOUR_STEPS.slice(1)) {
+ next();
+ expect(screen.getByText(step.titleKey)).toBeInTheDocument();
+ }
+
+ expect(onNavigatePage.mock.calls.map((c) => c[0])).toEqual([
+ "apps",
+ "usage",
+ "auth",
+ "providers",
+ ]);
+
+ // 最后一步没有「下一步」和「跳过」,按钮换成「开始使用」
+ expect(
+ screen.queryByRole("button", { name: "tutorial.next" }),
+ ).not.toBeInTheDocument();
+ expect(
+ screen.queryByRole("button", { name: "tutorial.skip" }),
+ ).not.toBeInTheDocument();
+ expect(mocks.save).not.toHaveBeenCalled();
+
+ fireEvent.click(screen.getByRole("button", { name: "tutorial.done" }));
+ await waitFor(() =>
+ expect(screen.queryByText("tutorial.more.title")).not.toBeInTheDocument(),
+ );
+ // 新装用户看的就是当前版本,「界面改版了」和更新摘要一并记成已看
+ expect(mocks.save).toHaveBeenCalledTimes(1);
+ expect(mocks.save).toHaveBeenCalledWith(
+ expect.objectContaining({
+ firstRunNoticeConfirmed: true,
+ newLayoutNoticeConfirmed: true,
+ whatsNewSeenVersion: "4.0.25",
+ }),
+ );
+ });
+
+ it("records the tour as seen when skipped", async () => {
+ render(withClient(<FirstRunNoticeDialog />));
+ fireEvent.click(screen.getByRole("button", { name: "tutorial.skip" }));
+ await waitFor(() =>
+ expect(mocks.save).toHaveBeenCalledWith(
+ expect.objectContaining({ firstRunNoticeConfirmed: true }),
+ ),
+ );
+ expect(screen.queryByText("firstRunNotice.title")).not.toBeInTheDocument();
+ });
+
+ it("records the tour as seen when dismissed with Escape", async () => {
+ render(withClient(<FirstRunNoticeDialog />));
+ fireEvent.keyDown(screen.getByRole("dialog"), { key: "Escape" });
+ await waitFor(() => expect(mocks.save).toHaveBeenCalledTimes(1));
+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
+ });
+
+ it("goes back a step", () => {
+ render(withClient(<FirstRunNoticeDialog />));
+ next();
+ fireEvent.click(screen.getByRole("button", { name: "tutorial.back" }));
+ expect(screen.getByText("firstRunNotice.title")).toBeInTheDocument();
+ });
+
+ it("moves between steps with the arrow keys", () => {
+ render(withClient(<FirstRunNoticeDialog />));
+ const dialog = screen.getByRole("dialog");
+ fireEvent.keyDown(dialog, { key: "ArrowRight" });
+ expect(screen.getByText(TOUR_STEPS[1].titleKey)).toBeInTheDocument();
+ fireEvent.keyDown(dialog, { key: "ArrowLeft" });
+ expect(screen.getByText("firstRunNotice.title")).toBeInTheDocument();
+ });
+
+ it("stays hidden once confirmed", () => {
+ mocks.settings = { firstRunNoticeConfirmed: true };
+ render(withClient(<FirstRunNoticeDialog />));
+ expect(screen.queryByText("firstRunNotice.title")).not.toBeInTheDocument();
+ });
+
+ it("stays hidden until settings load", () => {
+ mocks.settings = undefined;
+ render(withClient(<FirstRunNoticeDialog />));
+ expect(screen.queryByText("firstRunNotice.title")).not.toBeInTheDocument();
+ });
+
+ it("replays on request without touching settings", async () => {
+ mocks.settings = { firstRunNoticeConfirmed: true };
+ const onBeforeOpen = vi.fn();
+ render(withClient(<FirstRunNoticeDialog onBeforeOpen={onBeforeOpen} />));
+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
+
+ act(() => startOnboardingTour());
+ expect(screen.getByText("firstRunNotice.title")).toBeInTheDocument();
+ expect(onBeforeOpen).toHaveBeenCalledTimes(1);
+
+ fireEvent.click(screen.getByRole("button", { name: "tutorial.skip" }));
+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
+ expect(mocks.save).not.toHaveBeenCalled();
+ });
+});
+
+describe("OnboardingTour", () => {
+ afterEach(() => {
+ document.querySelectorAll("[data-tour]").forEach((el) => el.remove());
+ });
+
+ const spotlights = () => screen.queryAllByTestId("tour-spotlight");
+ const spotlight = () => {
+ const list = spotlights();
+ expect(list.length).toBeGreaterThan(0);
+ return list[0];
+ };
+
+ it("restarts from the first step when reopened", () => {
+ const onClose = vi.fn();
+ const { rerender } = render(<OnboardingTour open onClose={onClose} />);
+ next();
+ expect(screen.getByText(TOUR_STEPS[1].titleKey)).toBeInTheDocument();
+
+ rerender(<OnboardingTour open={false} onClose={onClose} />);
+ rerender(<OnboardingTour open onClose={onClose} />);
+ expect(screen.getByText("firstRunNotice.title")).toBeInTheDocument();
+ });
+
+ it("cuts the spotlight out around the anchored element", () => {
+ const anchor = document.createElement("div");
+ anchor.setAttribute("data-tour", "apps");
+ anchor.getBoundingClientRect = () =>
+ ({
+ top: 50,
+ left: 10,
+ right: 210,
+ bottom: 250,
+ width: 200,
+ height: 200,
+ }) as DOMRect;
+ document.body.appendChild(anchor);
+
+ render(<OnboardingTour open onClose={vi.fn()} />);
+ // 欢迎页没有要圈的元素:不渲染亮框
+ expect(spotlights()).toHaveLength(0);
+
+ next();
+ expect(screen.getByText("tutorial.apps.title")).toBeInTheDocument();
+ // 四周各外扩 6px
+ expect(spotlight().style.top).toBe("44px");
+ expect(spotlight().style.left).toBe("4px");
+ expect(spotlight().style.width).toBe("212px");
+ expect(spotlight().style.height).toBe("212px");
+ });
+
+ const addAnchor = (
+ id: string,
+ rect: Partial<DOMRect>,
+ parent: HTMLElement = document.body,
+ ) => {
+ const el = document.createElement("div");
+ el.setAttribute("data-tour", id);
+ el.getBoundingClientRect = () =>
+ ({
+ top: 0,
+ left: 0,
+ right: 0,
+ bottom: 0,
+ width: 0,
+ height: 0,
+ ...rect,
+ }) as DOMRect;
+ parent.appendChild(el);
+ return el;
+ };
+ const goTo = (stepId: string) => {
+ const target = TOUR_STEPS.findIndex((step) => step.id === stepId);
+ for (let i = 0; i < target; i++) next();
+ };
+
+ it("drops the previous highlight when the next step has nothing to point at", () => {
+ // 加供应商按钮在、模式切换不在(如 OpenCode):模式那一步不能还圈着按钮
+ addAnchor("add-provider", {
+ top: 10,
+ left: 600,
+ right: 700,
+ bottom: 40,
+ width: 100,
+ height: 30,
+ });
+ render(<OnboardingTour open onClose={vi.fn()} />);
+ goTo("add");
+ expect(spotlight().style.width).toBe("112px");
+
+ next();
+ expect(screen.getByText("tutorial.modes.title")).toBeInTheDocument();
+ expect(spotlights()).toHaveLength(0);
+ expect(screen.getByText("tutorial.modes.unavailable")).toBeInTheDocument();
+ });
+
+ it("opens on the centered welcome step after closing on a highlighted one", () => {
+ addAnchor("nav-settings", {
+ top: 400,
+ left: 10,
+ right: 100,
+ bottom: 430,
+ width: 90,
+ height: 30,
+ });
+ const onClose = vi.fn();
+ const { rerender } = render(<OnboardingTour open onClose={onClose} />);
+ goTo("more");
+ expect(spotlights()).toHaveLength(1);
+
+ rerender(<OnboardingTour open={false} onClose={onClose} />);
+ rerender(<OnboardingTour open onClose={onClose} />);
+ expect(screen.getByText("firstRunNotice.title")).toBeInTheDocument();
+ expect(spotlights()).toHaveLength(0);
+ });
+
+ it("points at the first provider card, or the empty list on a fresh install", () => {
+ const empty = addAnchor("provider-empty", {
+ top: 100,
+ left: 220,
+ right: 800,
+ bottom: 400,
+ width: 580,
+ height: 300,
+ });
+ const { unmount } = render(<OnboardingTour open onClose={vi.fn()} />);
+ goTo("providers");
+ expect(screen.getByText("tutorial.providers.empty")).toBeInTheDocument();
+ expect(
+ screen.queryByText("tutorial.providers.body"),
+ ).not.toBeInTheDocument();
+ expect(
+ screen.queryByText("firstRunNotice.bodyOfficial"),
+ ).not.toBeInTheDocument();
+ expect(spotlight().style.top).toBe("94px");
+ unmount();
+ empty.remove();
+
+ addAnchor("provider-card", {
+ top: 120,
+ left: 220,
+ right: 800,
+ bottom: 180,
+ width: 580,
+ height: 60,
+ });
+ render(<OnboardingTour open onClose={vi.fn()} />);
+ goTo("providers");
+ expect(screen.getByText("tutorial.providers.body")).toBeInTheDocument();
+ expect(screen.getByText("firstRunNotice.bodyOfficial")).toBeInTheDocument();
+ expect(
+ screen.queryByText("tutorial.providers.empty"),
+ ).not.toBeInTheDocument();
+ expect(spotlight().style.top).toBe("114px");
+ });
+
+ it("highlights the mode switch when the app has one", () => {
+ addAnchor("mode-tabs", {
+ top: 60,
+ left: 220,
+ right: 420,
+ bottom: 96,
+ width: 200,
+ height: 36,
+ });
+ render(<OnboardingTour open onClose={vi.fn()} />);
+ goTo("modes");
+ expect(spotlight().style.width).toBe("212px");
+ expect(screen.getByText("tutorial.modes.directTitle")).toBeInTheDocument();
+ expect(screen.getByText("tutorial.modes.routeTitle")).toBeInTheDocument();
+ expect(screen.getByText("tutorial.modes.stackTitle")).toBeInTheDocument();
+ expect(
+ screen.queryByText("tutorial.modes.unavailable"),
+ ).not.toBeInTheDocument();
+ });
+
+ it("falls back to a centered card when the anchor is missing", () => {
+ render(<OnboardingTour open onClose={vi.fn()} />);
+ next();
+ expect(screen.getByText("tutorial.apps.title")).toBeInTheDocument();
+ expect(spotlights()).toHaveLength(0);
+ });
+
+ it("allows skipping via the header skip button on any step", () => {
+ const onClose = vi.fn();
+ render(<OnboardingTour open onClose={onClose} />);
+ goTo("add");
+ fireEvent.click(screen.getByRole("button", { name: "tutorial.skip" }));
+ expect(onClose).toHaveBeenCalledTimes(1);
+ });
+
+ it("jumps directly to a step when clicking progress dots", () => {
+ render(<OnboardingTour open onClose={vi.fn()} />);
+ const dots = screen.getByRole("group").querySelectorAll("button");
+ expect(dots).toHaveLength(TOUR_STEPS.length);
+ fireEvent.click(dots[3]);
+ expect(screen.getByText(TOUR_STEPS[3].titleKey)).toBeInTheDocument();
+ });
+
+ it("highlights Settings on the last step", () => {
+ addAnchor("nav-settings", {
+ top: 470,
+ left: 102,
+ right: 192,
+ bottom: 498,
+ width: 90,
+ height: 28,
+ });
+
+ render(<OnboardingTour open onClose={vi.fn()} />);
+ goTo("more");
+ const list = spotlights();
+ expect(list).toHaveLength(1);
+ expect(list[0].style.left).toBe("96px");
+ expect(list[0].style.width).toBe("102px");
+ });
+
+ it("navigates across apps, usage, and auth steps and returns to providers on back or close", () => {
+ const onNavigatePage = vi.fn();
+ const onClose = vi.fn();
+ addAnchor("apps-row", {
+ top: 100,
+ left: 224,
+ right: 960,
+ bottom: 160,
+ width: 736,
+ height: 60,
+ });
+ addAnchor("apps-actions", {
+ top: 10,
+ left: 780,
+ right: 980,
+ bottom: 42,
+ width: 200,
+ height: 32,
+ });
+ addAnchor("usage-filters", {
+ top: 56,
+ left: 224,
+ right: 960,
+ bottom: 96,
+ width: 736,
+ height: 40,
+ });
+ addAnchor("usage-actions", {
+ top: 10,
+ left: 800,
+ right: 980,
+ bottom: 42,
+ width: 180,
+ height: 32,
+ });
+ addAnchor("auth-toggles", {
+ top: 68,
+ left: 224,
+ right: 960,
+ bottom: 180,
+ width: 736,
+ height: 112,
+ });
+ addAnchor("auth-refresh", {
+ top: 10,
+ left: 860,
+ right: 980,
+ bottom: 42,
+ width: 120,
+ height: 32,
+ });
+
+ const { rerender } = render(
+ <OnboardingTour open onClose={onClose} onNavigatePage={onNavigatePage} />,
+ );
+ expect(onNavigatePage).not.toHaveBeenCalled();
+
+ goTo("appsPage");
+ expect(onNavigatePage).toHaveBeenLastCalledWith("apps");
+ expect(spotlights()).toHaveLength(2);
+
+ // 从「应用」退回「共享资源」时切回供应商页
+ fireEvent.click(screen.getByRole("button", { name: "tutorial.back" }));
+ expect(onNavigatePage).toHaveBeenLastCalledWith("providers");
+
+ next();
+ expect(onNavigatePage).toHaveBeenLastCalledWith("apps");
+ next();
+ expect(onNavigatePage).toHaveBeenLastCalledWith("usage");
+ expect(spotlights()).toHaveLength(2);
+
+ next();
+ expect(onNavigatePage).toHaveBeenLastCalledWith("auth");
+ expect(spotlights()).toHaveLength(2);
+
+ // 在授权中心步骤直接关闭时也切回供应商页
+ rerender(
+ <OnboardingTour
+ open={false}
+ onClose={onClose}
+ onNavigatePage={onNavigatePage}
+ />,
+ );
+ expect(onNavigatePage).toHaveBeenLastCalledWith("providers");
+ });
+
+ it("clips overflowing anchors to their scrollable ancestor bounds", () => {
+ const scroller = document.createElement("div");
+ scroller.style.overflowY = "auto";
+ scroller.getBoundingClientRect = () =>
+ ({
+ top: 44,
+ left: 0,
+ right: 200,
+ bottom: 300,
+ width: 200,
+ height: 256,
+ }) as DOMRect;
+ document.body.appendChild(scroller);
+
+ addAnchor(
+ "apps",
+ {
+ top: 44,
+ left: 8,
+ right: 192,
+ bottom: 480,
+ width: 184,
+ height: 436,
+ },
+ scroller,
+ );
+
+ render(<OnboardingTour open onClose={vi.fn()} />);
+ next();
+ expect(spotlight().style.top).toBe("38px");
+ expect(spotlight().style.height).toBe("268px");
+ scroller.remove();
+ });
+
+ it("includes nav-plugins in the shared sidebar spotlight group", () => {
+ addAnchor("nav-mcp", {
+ top: 260,
+ left: 8,
+ right: 192,
+ bottom: 288,
+ width: 184,
+ height: 28,
+ });
+ addAnchor("nav-skills", {
+ top: 288,
+ left: 8,
+ right: 192,
+ bottom: 316,
+ width: 184,
+ height: 28,
+ });
+ addAnchor("nav-plugins", {
+ top: 316,
+ left: 8,
+ right: 192,
+ bottom: 344,
+ width: 184,
+ height: 28,
+ });
+ addAnchor("nav-prompts", {
+ top: 344,
+ left: 8,
+ right: 192,
+ bottom: 372,
+ width: 184,
+ height: 28,
+ });
+ addAnchor("nav-sessions", {
+ top: 372,
+ left: 8,
+ right: 192,
+ bottom: 400,
+ width: 184,
+ height: 28,
+ });
+
+ render(<OnboardingTour open onClose={vi.fn()} />);
+ goTo("shared");
+ const box = spotlight();
+ expect(box.style.top).toBe("254px");
+ expect(box.style.height).toBe("152px");
+ });
+
+ it("renders ModalDragStrip window controls in the overlay outside the dialog card", () => {
+ render(
+ <WindowControlsContext.Provider
+ value={<button type="button">WindowClose</button>}
+ >
+ <OnboardingTour open onClose={vi.fn()} />
+ </WindowControlsContext.Provider>,
+ );
+ const closeWin = screen.getByRole("button", { name: "WindowClose" });
+ const overlay = screen.getByTestId("onboarding-tour");
+ const dialog = screen.getByRole("dialog");
+ expect(overlay).toContainElement(closeWin);
+ expect(dialog).not.toContainElement(closeWin);
+ });
+
+ it("handles navigation keys globally and blocks Ctrl+F, Ctrl+, and Ctrl+\\ while open", () => {
+ const onClose = vi.fn();
+ render(<OnboardingTour open onClose={onClose} />);
+
+ fireEvent.keyDown(document.body, { key: "ArrowRight" });
+ expect(screen.getByText(TOUR_STEPS[1].titleKey)).toBeInTheDocument();
+
+ fireEvent.keyDown(document.body, { key: "ArrowLeft" });
+ expect(screen.getByText(TOUR_STEPS[0].titleKey)).toBeInTheDocument();
+
+ for (const key of ["f", ",", "\\"]) {
+ const blocked = new KeyboardEvent("keydown", {
+ key,
+ ctrlKey: true,
+ bubbles: true,
+ cancelable: true,
+ });
+ window.dispatchEvent(blocked);
+ expect(blocked.defaultPrevented).toBe(true);
+ }
+
+ fireEvent.keyDown(document.body, { key: "Escape" });
+ expect(onClose).toHaveBeenCalledTimes(1);
+ });
+
+ it("highlights both the app list and the bottom Apps button on the apps step", () => {
+ addAnchor("apps", {
+ top: 50,
+ left: 8,
+ right: 192,
+ bottom: 250,
+ width: 184,
+ height: 200,
+ });
+ addAnchor("nav-apps", {
+ top: 520,
+ left: 8,
+ right: 100,
+ bottom: 548,
+ width: 92,
+ height: 28,
+ });
+
+ render(<OnboardingTour open onClose={vi.fn()} />);
+ next();
+ const list = spotlights();
+ expect(list).toHaveLength(2);
+ expect(list[0].style.top).toBe("44px");
+ expect(list[1].style.top).toBe("514px");
+
+ const dialog = screen.getByRole("dialog");
+ expect(dialog).toHaveAttribute("aria-describedby");
+ expect(
+ document.getElementById(dialog.getAttribute("aria-describedby")!),
+ ).toHaveTextContent("tutorial.apps.body");
+ });
+
+ it("keeps Tab trapped and Escape working after clicking the backdrop or dialog card", () => {
+ const onClose = vi.fn();
+ render(
+ <>
+ <button type="button">OutsideAction</button>
+ <OnboardingTour open onClose={onClose} />
+ </>,
+ );
+
+ const outside = screen.getByRole("button", { name: "OutsideAction" });
+ const dialog = screen.getByRole("dialog");
+ const backdrop = screen.getByTestId("tour-backdrop");
+ const primary = screen.getByRole("button", { name: "tutorial.next" });
+
+ expect(primary).toHaveFocus();
+
+ const mouseDown = new MouseEvent("mousedown", {
+ bubbles: true,
+ cancelable: true,
+ });
+ backdrop.dispatchEvent(mouseDown);
+ expect(mouseDown.defaultPrevented).toBe(true);
+ fireEvent.click(backdrop);
+ expect(primary).toHaveFocus();
+
+ fireEvent.keyDown(document.body, { key: "Tab" });
+ expect(dialog).toContainElement(document.activeElement as HTMLElement);
+ expect(outside).not.toHaveFocus();
+
+ // 即使点击卡片非按钮区域使焦点落到卡片容器或 body,Tab 仍会回到卡片按钮内,Esc 仍能关闭
+ dialog.focus();
+ expect(dialog).toHaveFocus();
+ fireEvent.keyDown(dialog, { key: "Tab" });
+ expect(Array.from(dialog.querySelectorAll("button"))).toContain(
+ document.activeElement,
+ );
+
+ fireEvent.keyDown(document.body, { key: "Tab", shiftKey: true });
+ expect(Array.from(dialog.querySelectorAll("button"))).toContain(
+ document.activeElement,
+ );
+
+ fireEvent.keyDown(dialog, { key: "Escape" });
+ expect(onClose).toHaveBeenCalledTimes(1);
+ });
+
+ it("snaps centered card coordinates to whole pixels on odd viewports", () => {
+ const prevWidth = window.innerWidth;
+ const prevHeight = window.innerHeight;
+ Object.defineProperty(window, "innerWidth", {
+ configurable: true,
+ value: 1001,
+ });
+ Object.defineProperty(window, "innerHeight", {
+ configurable: true,
+ value: 701,
+ });
+ try {
+ render(<OnboardingTour open onClose={vi.fn()} />);
+ const dialog = screen.getByRole("dialog");
+ expect(dialog.style.left).toBe("321px");
+ expect(dialog.style.top).toBe("241px");
+ } finally {
+ Object.defineProperty(window, "innerWidth", {
+ configurable: true,
+ value: prevWidth,
+ });
+ Object.defineProperty(window, "innerHeight", {
+ configurable: true,
+ value: prevHeight,
+ });
+ }
+ });
+});
diff --git a/tests/components/QoderPanel.test.tsx b/tests/components/QoderPanel.test.tsx
index f2b2fe2f6..d57325712 100644
--- a/tests/components/QoderPanel.test.tsx
+++ b/tests/components/QoderPanel.test.tsx
@@ -1296,4 +1296,13 @@ describe("Qoder model management", () => {
expect.anything(),
);
});
+
+ it("marks the header add-provider button for the onboarding tour", async () => {
+ state.qoder.providers.native = structuredClone(provider);
+ mount("qoder");
+ const addButton = await screen.findByRole("button", {
+ name: "provider.addProvider",
+ });
+ expect(addButton).toHaveAttribute("data-tour", "add-provider");
+ });
});
diff --git a/tests/components/WhatsNewNotice.test.tsx b/tests/components/WhatsNewNotice.test.tsx
index 28bf5963e..ef74a4638 100644
--- a/tests/components/WhatsNewNotice.test.tsx
+++ b/tests/components/WhatsNewNotice.test.tsx
@@ -158,6 +158,29 @@ describe("WhatsNewNotice", () => {
expect(mocks.save).not.toHaveBeenCalled();
});
+ it("stays hidden for the rest of a first-run session, even if the tutorial did not record a version", async () => {
+ mocks.settings = { firstRunNoticeConfirmed: undefined };
+ const view = renderNotice();
+ await settle();
+
+ // 教程确认了,但当时没读到版本,whatsNewSeenVersion 还是空的
+ mocks.settings = {
+ firstRunNoticeConfirmed: true,
+ newLayoutNoticeConfirmed: true,
+ };
+ view.rerender(
+ <QueryClientProvider client={createTestQueryClient()}>
+ <WhatsNewNotice />
+ </QueryClientProvider>,
+ );
+ await waitFor(() =>
+ expect(mocks.save).toHaveBeenCalledWith(
+ expect.objectContaining({ whatsNewSeenVersion: "4.0.4" }),
+ ),
+ );
+ expect(title()).not.toBeInTheDocument();
+ });
+
it("waits while the new layout dialog is showing", async () => {
mocks.settings = {
firstRunNoticeConfirmed: true,
diff --git a/tests/integration/App.test.tsx b/tests/integration/App.test.tsx
index 19149cb10..ab2af7604 100644
--- a/tests/integration/App.test.tsx
+++ b/tests/integration/App.test.tsx
@@ -231,6 +231,10 @@ const renderApp = (AppComponent: ComponentType) => {
describe("App integration with MSW", () => {
beforeEach(() => {
resetProviderState();
+ setSettings({
+ firstRunNoticeConfirmed: true,
+ newLayoutNoticeConfirmed: true,
+ });
toastSuccessMock.mockReset();
toastErrorMock.mockReset();
skillsPanelMocks.initialViews = [];