Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

feat(desktop): 增加移动端下载与远程控制入口 (#413)

nanaco1d48b4094816
diff --git a/apps/desktop/src/renderer/__tests__/mobileDownloadDialog.test.tsx b/apps/desktop/src/renderer/__tests__/mobileDownloadDialog.test.tsx
new file mode 100644
index 0000000000..d54bc167ad
--- /dev/null
+++ b/apps/desktop/src/renderer/__tests__/mobileDownloadDialog.test.tsx
@@ -0,0 +1,672 @@
+// @vitest-environment jsdom
+
+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { useRef, useState } from 'react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string) => key,
+ }),
+}));
+
+const { toDataURL } = vi.hoisted(() => ({
+ toDataURL: vi.fn(async () => 'data:image/png;base64,mobile-download'),
+}));
+vi.mock('qrcode', () => ({ toDataURL }));
+
+const { toastError } = vi.hoisted(() => ({ toastError: vi.fn() }));
+vi.mock('@/lib/toast', () => ({
+ toast: { error: toastError, success: vi.fn(), info: vi.fn(), warning: vi.fn() },
+}));
+
+import {
+ MobileDownloadDialog,
+ resolveMobileRemotePresentation,
+ resolveMobileDownloadUrl,
+} from '@/components/sidebar/MobileDownloadDialog';
+
+const source = readFileSync(
+ resolve(__dirname, '..', 'components', 'sidebar', 'MobileDownloadDialog.tsx'),
+ 'utf8',
+);
+const globalStyles = readFileSync(resolve(__dirname, '..', 'styles', 'globals.css'), 'utf8');
+const themeColors = readFileSync(resolve(__dirname, '..', 'themes', 'colors.ts'), 'utf8');
+
+const openExternal = vi.fn(async () => ({ success: true }));
+type DeviceLinkState = Awaited<ReturnType<ElectronAPI['deviceLink']['getState']>>;
+const getState = vi.fn<() => Promise<DeviceLinkState>>(async () => ({
+ remoteControlEnabled: true,
+ keepAwake: false,
+ linkStatus: 'online',
+ connectionIssue: null,
+ controlledBy: [],
+ revokedControllers: [],
+ disabledControlDeviceIds: [],
+}));
+const listDevices = vi.fn(async () => ({
+ devices: [
+ {
+ deviceId: 'desktop-device-1',
+ name: 'Studio Mac',
+ platform: 'darwin',
+ appVersion: '1.0.0',
+ lastSeenAt: null,
+ online: true,
+ busy: false,
+ remoteControlEnabled: true,
+ controlEnabled: true,
+ isSelf: true,
+ },
+ {
+ deviceId: 'mobile-device-1',
+ name: 'My iPhone',
+ platform: 'ios',
+ appVersion: '1.0.0',
+ lastSeenAt: null,
+ online: true,
+ busy: false,
+ remoteControlEnabled: false,
+ controlEnabled: true,
+ isSelf: false,
+ },
+ ],
+}));
+let presenceChangedHandler: (() => void) | undefined;
+const onPresenceChanged = vi.fn((handler: () => void) => {
+ presenceChangedHandler = handler;
+ return vi.fn();
+});
+const onStatusChanged = vi.fn(() => vi.fn());
+const onConnectionIssue = vi.fn(() => vi.fn());
+const detachedTriggerRef = { current: null as HTMLButtonElement | null };
+
+beforeEach(() => {
+ toDataURL.mockClear();
+ toastError.mockClear();
+ openExternal.mockClear();
+ getState.mockClear();
+ listDevices.mockClear();
+ presenceChangedHandler = undefined;
+ onPresenceChanged.mockClear();
+ onStatusChanged.mockClear();
+ onConnectionIssue.mockClear();
+ Object.defineProperty(window, 'electronAPI', {
+ configurable: true,
+ value: {
+ clientEndpoints: { websiteUrl: 'https://cindy.cn' },
+ openExternal,
+ deviceLink: {
+ getState,
+ listDevices,
+ onPresenceChanged,
+ onStatusChanged,
+ onConnectionIssue,
+ },
+ },
+ });
+ Object.defineProperty(window, 'matchMedia', {
+ configurable: true,
+ value: vi.fn(() => ({
+ matches: false,
+ media: '',
+ onchange: null,
+ addListener: vi.fn(),
+ removeListener: vi.fn(),
+ addEventListener: vi.fn(),
+ removeEventListener: vi.fn(),
+ dispatchEvent: vi.fn(),
+ })),
+ });
+ Object.defineProperty(window, 'requestAnimationFrame', {
+ configurable: true,
+ value: (callback: FrameRequestCallback) =>
+ window.setTimeout(() => callback(window.performance.now()), 0),
+ });
+ Object.defineProperty(window, 'cancelAnimationFrame', {
+ configurable: true,
+ value: (frameId: number) => window.clearTimeout(frameId),
+ });
+});
+
+afterEach(() => {
+ cleanup();
+ vi.restoreAllMocks();
+});
+
+describe('resolveMobileDownloadUrl', () => {
+ it('builds the download page from the regional website endpoint', () => {
+ expect(resolveMobileDownloadUrl('https://cindy.cn')).toBe('https://cindy.cn/download/');
+ expect(resolveMobileDownloadUrl('https://cindy.app')).toBe('https://cindy.app/download/');
+ });
+
+ it('maps the shipped endpoint hosts onto the canonical download pages', () => {
+ // 打包配置的真实取值:CN 是 config/endpoint.json 的 cindy.com.cn(官网 302 到
+ // cindy.cn),Global 是 cindy.app。二维码直接给最终地址,手机上少一跳。
+ const shipped = (configPath: string) =>
+ JSON.parse(readFileSync(resolve(__dirname, configPath), 'utf8')).websiteUrl as string;
+
+ expect(resolveMobileDownloadUrl(shipped('../../../../../config/endpoint.json'))).toBe(
+ 'https://cindy.cn/download/',
+ );
+ expect(resolveMobileDownloadUrl(shipped('../../../../../config/endpoint.global.json'))).toBe(
+ 'https://cindy.app/download/',
+ );
+ });
+
+ it('accepts the loopback http endpoint used by the dev manifest', () => {
+ // config/endpoint.dev.json.example 的 websiteUrl 是 http://localhost:3000,
+ // 开发机不该看到一个禁用的二维码。
+ expect(resolveMobileDownloadUrl('http://localhost:3000')).toBe(
+ 'http://localhost:3000/download/',
+ );
+ expect(resolveMobileDownloadUrl('http://127.0.0.1:5173')).toBe(
+ 'http://127.0.0.1:5173/download/',
+ );
+ });
+
+ it.each(['', 'not-a-url', 'http://cindy.cn', 'https://user:[email protected]'])(
+ 'rejects an unsafe regional website endpoint: %s',
+ (websiteUrl) => {
+ expect(resolveMobileDownloadUrl(websiteUrl)).toBeNull();
+ },
+ );
+});
+
+describe('resolveMobileRemotePresentation', () => {
+ const selfDevice = {
+ deviceId: 'desktop-device-1',
+ name: 'Studio Mac',
+ platform: 'darwin',
+ appVersion: null,
+ lastSeenAt: null,
+ online: true,
+ busy: false,
+ remoteControlEnabled: true,
+ controlEnabled: true,
+ isSelf: true,
+ };
+
+ it('keeps permission state separate from the mobile-linked layout', () => {
+ expect(
+ resolveMobileRemotePresentation({
+ enabled: false,
+ devices: [selfDevice],
+ }),
+ ).toMatchObject({
+ layout: 'onboarding',
+ remoteEnabled: false,
+ linkedMobileCount: 0,
+ otherDeviceCount: 0,
+ selfDeviceId: 'desktop-device-1',
+ });
+ expect(
+ resolveMobileRemotePresentation({
+ enabled: true,
+ devices: [
+ selfDevice,
+ {
+ ...selfDevice,
+ deviceId: 'desktop-2',
+ name: 'Other desktop',
+ isSelf: false,
+ },
+ ],
+ }),
+ ).toMatchObject({
+ layout: 'onboarding',
+ remoteEnabled: true,
+ linkedMobileCount: 0,
+ otherDeviceCount: 1,
+ });
+ expect(
+ resolveMobileRemotePresentation({
+ enabled: true,
+ devices: [
+ selfDevice,
+ {
+ ...selfDevice,
+ deviceId: 'mobile-1',
+ name: 'My iPhone',
+ platform: 'ios',
+ isSelf: false,
+ },
+ ],
+ }),
+ ).toMatchObject({
+ layout: 'linked',
+ remoteEnabled: true,
+ linkedMobileCount: 1,
+ otherDeviceCount: 1,
+ selfDeviceId: 'desktop-device-1',
+ linkedMobileName: 'My iPhone',
+ });
+ });
+
+ it('orders the preview mobile-first and then by name, without relying on sort stability', () => {
+ const other = (deviceId: string, name: string, platform: string) => ({
+ ...selfDevice,
+ deviceId,
+ name,
+ platform,
+ isSelf: false,
+ });
+
+ expect(
+ resolveMobileRemotePresentation({
+ enabled: true,
+ devices: [
+ selfDevice,
+ other('d-1', 'Zeta desktop', 'win32'),
+ other('m-1', 'Zeta phone', 'ios'),
+ other('d-2', 'Alpha desktop', 'linux'),
+ other('m-2', 'Alpha phone', 'android'),
+ ],
+ }).previewDevices.map((device) => device.deviceId),
+ ).toEqual(['m-2', 'm-1', 'd-2']);
+ });
+
+ it('keeps an unavailable device list distinct from a confirmed empty list', () => {
+ expect(
+ resolveMobileRemotePresentation({
+ enabled: true,
+ devices: null,
+ }),
+ ).toMatchObject({
+ layout: 'checking',
+ remoteEnabled: true,
+ selfDeviceId: null,
+ });
+ });
+});
+
+describe('MobileDownloadDialog', () => {
+ it('warms the QR code and remote snapshot before the dialog opens', async () => {
+ render(
+ <MobileDownloadDialog
+ open={false}
+ onOpenChange={vi.fn()}
+ remoteAvailable
+ onOpenRemoteSettings={vi.fn()}
+ onOpenDevices={vi.fn()}
+ triggerRef={detachedTriggerRef}
+ />,
+ );
+ await waitFor(() => expect(toDataURL).toHaveBeenCalledTimes(1));
+ expect(getState).toHaveBeenCalledTimes(1);
+ });
+
+ it('generates the regional QR code and exposes an equivalent browser action', async () => {
+ render(
+ <MobileDownloadDialog
+ open
+ onOpenChange={vi.fn()}
+ remoteAvailable
+ onOpenRemoteSettings={vi.fn()}
+ onOpenDevices={vi.fn()}
+ triggerRef={detachedTriggerRef}
+ />,
+ );
+
+ expect(await screen.findByAltText('sidebar.mobileDownload.qrAlt')).toBeTruthy();
+
+ const openButton = screen.getByRole('button', {
+ name: 'sidebar.mobileDownload.openPage',
+ });
+ await waitFor(() => expect(document.activeElement).toBe(openButton));
+ fireEvent.click(openButton);
+ expect(openExternal).toHaveBeenCalledWith('https://cindy.cn/download/');
+ });
+
+ it('reports a failed handoff to the system browser', async () => {
+ openExternal.mockResolvedValueOnce({ success: false });
+ render(
+ <MobileDownloadDialog
+ open
+ onOpenChange={vi.fn()}
+ remoteAvailable
+ onOpenRemoteSettings={vi.fn()}
+ onOpenDevices={vi.fn()}
+ triggerRef={detachedTriggerRef}
+ />,
+ );
+
+ fireEvent.click(screen.getByRole('button', { name: 'sidebar.mobileDownload.openPage' }));
+ await waitFor(() =>
+ expect(toastError).toHaveBeenCalledWith('sidebar.mobileDownload.openFailed'),
+ );
+
+ toastError.mockClear();
+ openExternal.mockRejectedValueOnce(new Error('ipc down'));
+ fireEvent.click(screen.getByRole('button', { name: 'sidebar.mobileDownload.openPage' }));
+ await waitFor(() =>
+ expect(toastError).toHaveBeenCalledWith('sidebar.mobileDownload.openFailed'),
+ );
+ });
+
+ it('retries QR generation when the dialog is reopened after a failure', async () => {
+ // 用独立站点绕开模块级二维码缓存(缓存按 URL 命中,复用 cindy.cn 会直接拿到
+ // 前面用例生成好的结果,失败路径根本走不到)。
+ window.electronAPI.clientEndpoints.websiteUrl = 'https://qr-retry.example.com';
+ toDataURL.mockRejectedValueOnce(new Error('canvas busy'));
+ const props = {
+ onOpenChange: vi.fn(),
+ remoteAvailable: false,
+ onOpenRemoteSettings: vi.fn(),
+ onOpenDevices: vi.fn(),
+ triggerRef: detachedTriggerRef,
+ };
+ const view = render(<MobileDownloadDialog open {...props} />);
+
+ expect(await screen.findByText('sidebar.mobileDownload.error')).toBeTruthy();
+
+ view.rerender(<MobileDownloadDialog open={false} {...props} />);
+ view.rerender(<MobileDownloadDialog open {...props} />);
+
+ expect(await screen.findByAltText('sidebar.mobileDownload.qrAlt')).toBeTruthy();
+ });
+
+ it('subscribes to Device Link pushes only while the dialog is open', async () => {
+ const props = {
+ onOpenChange: vi.fn(),
+ remoteAvailable: true,
+ onOpenRemoteSettings: vi.fn(),
+ onOpenDevices: vi.fn(),
+ triggerRef: detachedTriggerRef,
+ };
+ const view = render(<MobileDownloadDialog open={false} {...props} />);
+ await waitFor(() => expect(getState).toHaveBeenCalledTimes(1));
+ expect(onPresenceChanged).not.toHaveBeenCalled();
+
+ view.rerender(<MobileDownloadDialog open {...props} />);
+ expect(onPresenceChanged).toHaveBeenCalledTimes(1);
+ expect(onStatusChanged).toHaveBeenCalledTimes(1);
+ expect(onConnectionIssue).toHaveBeenCalledTimes(1);
+ });
+
+ it('re-reads the remote state every time the dialog reopens', async () => {
+ // 设置页改权限、重命名/删除设备都不经过 presence/status/connection-issue 推送,
+ // 重新打开必须自己重读一次。
+ const props = {
+ onOpenChange: vi.fn(),
+ remoteAvailable: true,
+ onOpenRemoteSettings: vi.fn(),
+ onOpenDevices: vi.fn(),
+ triggerRef: detachedTriggerRef,
+ };
+ const view = render(<MobileDownloadDialog open={false} {...props} />);
+ await waitFor(() => expect(getState).toHaveBeenCalledTimes(1));
+
+ view.rerender(<MobileDownloadDialog open {...props} />);
+ await waitFor(() => expect(getState).toHaveBeenCalledTimes(2));
+
+ view.rerender(<MobileDownloadDialog open={false} {...props} />);
+ view.rerender(<MobileDownloadDialog open {...props} />);
+ await waitFor(() => expect(getState).toHaveBeenCalledTimes(3));
+ });
+
+ it('shows the compact QR, device preview, and separate settings actions when mobile is linked', async () => {
+ const onOpenRemoteSettings = vi.fn();
+ const onOpenDevices = vi.fn();
+ render(
+ <MobileDownloadDialog
+ open
+ onOpenChange={vi.fn()}
+ remoteAvailable
+ onOpenRemoteSettings={onOpenRemoteSettings}
+ onOpenDevices={onOpenDevices}
+ triggerRef={detachedTriggerRef}
+ />,
+ );
+
+ expect(await screen.findByText('sidebar.mobileDownload.myDevices')).toBeTruthy();
+ expect(screen.getByText('My iPhone')).toBeTruthy();
+ expect(screen.getByText('sidebar.mobileDownload.deviceId')).toBeTruthy();
+ expect(screen.getByTestId('mobile-download-qr-card').dataset.compact).toBe('true');
+ fireEvent.click(screen.getByRole('button', { name: /sidebar\.mobileDownload\.myDevices/ }));
+ expect(onOpenDevices).toHaveBeenCalledTimes(1);
+ fireEvent.click(screen.getByRole('button', { name: /sidebar\.mobileDownload\.allowControl/ }));
+ expect(onOpenRemoteSettings).toHaveBeenCalledTimes(1);
+ });
+
+ it('preserves the linked layout when a later device-list refresh fails', async () => {
+ render(
+ <MobileDownloadDialog
+ open
+ onOpenChange={vi.fn()}
+ remoteAvailable
+ onOpenRemoteSettings={vi.fn()}
+ onOpenDevices={vi.fn()}
+ triggerRef={detachedTriggerRef}
+ />,
+ );
+
+ await waitFor(() =>
+ expect(screen.getByTestId('mobile-download-qr-card').dataset.compact).toBe('true'),
+ );
+ listDevices.mockRejectedValueOnce(new Error('temporary list failure'));
+ await act(async () => {
+ presenceChangedHandler?.();
+ });
+ await waitFor(() => expect(listDevices).toHaveBeenCalledTimes(2));
+ expect(screen.getByTestId('mobile-download-qr-card').dataset.compact).toBe('true');
+ expect(screen.getByText('My iPhone')).toBeTruthy();
+ });
+
+ it('keeps the newest remote snapshot when event-driven refreshes resolve out of order', async () => {
+ let resolveStaleState!: (state: Awaited<ReturnType<typeof getState>>) => void;
+ const staleState = {
+ remoteControlEnabled: false,
+ keepAwake: false,
+ linkStatus: 'connecting' as const,
+ connectionIssue: null,
+ controlledBy: [],
+ revokedControllers: [],
+ disabledControlDeviceIds: [],
+ };
+ getState
+ .mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ resolveStaleState = resolve;
+ }),
+ )
+ .mockResolvedValueOnce({
+ ...staleState,
+ remoteControlEnabled: true,
+ linkStatus: 'online',
+ });
+
+ render(
+ <MobileDownloadDialog
+ open
+ onOpenChange={vi.fn()}
+ remoteAvailable
+ onOpenRemoteSettings={vi.fn()}
+ onOpenDevices={vi.fn()}
+ triggerRef={detachedTriggerRef}
+ />,
+ );
+
+ await waitFor(() => expect(presenceChangedHandler).toBeTypeOf('function'));
+ await act(async () => {
+ presenceChangedHandler?.();
+ });
+ expect(await screen.findByText('sidebar.mobileDownload.remoteAction.enabled')).toBeTruthy();
+
+ await act(async () => {
+ resolveStaleState(staleState);
+ });
+ await waitFor(() =>
+ expect(screen.getByText('sidebar.mobileDownload.remoteAction.enabled')).toBeTruthy(),
+ );
+ expect(screen.queryByText('sidebar.mobileDownload.remoteAction.enable')).toBeNull();
+ });
+
+ it('keeps the settings path available when the remote state cannot be read', async () => {
+ getState.mockRejectedValueOnce(new Error('state unavailable'));
+ render(
+ <MobileDownloadDialog
+ open
+ onOpenChange={vi.fn()}
+ remoteAvailable
+ onOpenRemoteSettings={vi.fn()}
+ onOpenDevices={vi.fn()}
+ triggerRef={detachedTriggerRef}
+ />,
+ );
+
+ expect(await screen.findByText('sidebar.mobileDownload.remoteAction.unavailable')).toBeTruthy();
+ expect(
+ screen.getByRole('button', { name: /sidebar\.mobileDownload\.allowControl/ }),
+ ).toBeTruthy();
+ });
+
+ it('drops the enabled dot once the remote state read fails', async () => {
+ render(
+ <MobileDownloadDialog
+ open
+ onOpenChange={vi.fn()}
+ remoteAvailable
+ onOpenRemoteSettings={vi.fn()}
+ onOpenDevices={vi.fn()}
+ triggerRef={detachedTriggerRef}
+ />,
+ );
+
+ const readyDot = () =>
+ screen
+ .getByRole('button', { name: /sidebar\.mobileDownload\.allowControl/ })
+ .querySelector('[class*="--remote-status-ready"]');
+
+ expect(await screen.findByText('sidebar.mobileDownload.remoteAction.enabled')).toBeTruthy();
+ expect(readyDot()).toBeTruthy();
+
+ getState.mockRejectedValueOnce(new Error('state unavailable'));
+ await waitFor(() => expect(presenceChangedHandler).toBeTypeOf('function'));
+ await act(async () => {
+ presenceChangedHandler?.();
+ });
+
+ expect(await screen.findByText('sidebar.mobileDownload.remoteAction.unavailable')).toBeTruthy();
+ // 陈旧的 enabled 快照不能和「暂不可用」文案同时出现。
+ expect(readyDot()).toBeNull();
+ });
+
+ it('uses the official Cindy artwork and the shared dialog tokens', () => {
+ expect(source).toContain('@/../../resources/icon.png?url');
+ expect(source).toContain("t('sidebar.mobileDownload.title')");
+ expect(source).toContain('<Smartphone');
+ expect(source).toContain('<Monitor');
+ expect(source).toContain("t('sidebar.mobileDownload.subtitle')");
+ expect(source).toContain('bg-[var(--confirm-bg)] shadow-[var(--confirm-shadow)]');
+ expect(source).not.toMatch(/(?:linear|conic|radial)-gradient/);
+ expect(source).not.toMatch(/#[0-9a-f]{3,8}|rgba?\(/i);
+ });
+
+ it('focuses a usable fallback when the download endpoint is invalid', async () => {
+ window.electronAPI.clientEndpoints.websiteUrl = 'not-a-url';
+ render(
+ <MobileDownloadDialog
+ open
+ onOpenChange={vi.fn()}
+ remoteAvailable
+ onOpenRemoteSettings={vi.fn()}
+ onOpenDevices={vi.fn()}
+ triggerRef={detachedTriggerRef}
+ />,
+ );
+
+ await waitFor(() =>
+ expect(document.activeElement).toBe(
+ screen.getByRole('button', { name: /sidebar\.mobileDownload\.allowControl/ }),
+ ),
+ );
+ });
+
+ it('returns focus to the sidebar trigger when the dialog closes', async () => {
+ function FocusReturnHarness() {
+ const [open, setOpen] = useState(true);
+ const triggerRef = useRef<HTMLButtonElement>(null);
+ return (
+ <>
+ <button ref={triggerRef} type="button">
+ download trigger
+ </button>
+ <MobileDownloadDialog
+ open={open}
+ onOpenChange={setOpen}
+ remoteAvailable
+ onOpenRemoteSettings={vi.fn()}
+ onOpenDevices={vi.fn()}
+ triggerRef={triggerRef}
+ />
+ </>
+ );
+ }
+
+ render(<FocusReturnHarness />);
+ fireEvent.click(
+ await screen.findByRole('button', {
+ name: 'sidebar.mobileDownload.close',
+ }),
+ );
+
+ await waitFor(() =>
+ expect(document.activeElement).toBe(screen.getByRole('button', { name: 'download trigger' })),
+ );
+ });
+
+ it('keeps the brand edge inside its registered exception', () => {
+ // §15.7 / §14.4 登记的窄范围例外只覆盖「品牌资产 + 纯 transform 的常驻旋转」。
+ // 例外之外的两项(卡片阴影、指针 3D 倾斜)必须保持关闭。
+ expect(source).not.toMatch(/perspective\(|scale3d\(|onPointerMove|requestAnimationFrame/);
+ expect(source).not.toMatch(/mobile-download-qr-shadow/);
+ expect(globalStyles).not.toMatch(/--mobile-download-qr-shadow/);
+ expect(themeColors).not.toMatch(/mobile-download-qr-shadow/);
+ // 红蓝只能来自官方 icon 资产,不自写品牌渐变/色值。
+ expect(source).not.toMatch(/linear-gradient|conic-gradient|#[0-9a-fA-F]{3,8}\b/);
+
+ const cardRule = globalStyles.slice(
+ globalStyles.indexOf('.mobile-download-qr-card {'),
+ globalStyles.indexOf('.mobile-download-qr-edge {'),
+ );
+ expect(cardRule).not.toMatch(/box-shadow|animation:|transform:/);
+ expect(cardRule).toMatch(
+ /transition:\s*\n\s*width var\(--motion-base\) var\(--motion-ease-move\),/,
+ );
+ expect(cardRule).toMatch(/height var\(--motion-base\) var\(--motion-ease-move\);/);
+
+ // 常驻动画只能碰 transform(合成器层),且必须登记进 reduced-motion 白名单。
+ const edgeStart = globalStyles.indexOf('.mobile-download-qr-edge {');
+ const edgeRule = globalStyles.slice(
+ edgeStart,
+ globalStyles.indexOf('@media (prefers-reduced-motion: reduce)', edgeStart),
+ );
+ expect(edgeRule).toContain(
+ 'animation: mobile-download-edge-turn var(--mobile-download-edge-cycle) linear infinite',
+ );
+ expect(edgeRule).not.toMatch(/filter:|backdrop-filter:|mask-image:|width:|height:/);
+ expect(globalStyles).toMatch(/\.mobile-download-qr-edge\s*\{\s*animation: none;\s*transform:/);
+ });
+
+ it('renders the brand edge behind the QR surface', () => {
+ render(
+ <MobileDownloadDialog
+ open
+ onOpenChange={vi.fn()}
+ remoteAvailable={false}
+ onOpenRemoteSettings={vi.fn()}
+ onOpenDevices={vi.fn()}
+ triggerRef={detachedTriggerRef}
+ />,
+ );
+
+ const card = screen.getByTestId('mobile-download-qr-card');
+ const edge = card.querySelector('.mobile-download-qr-edge');
+ expect(edge).toBeTruthy();
+ expect(edge?.getAttribute('aria-hidden')).toBe('true');
+ });
+});
diff --git a/apps/desktop/src/renderer/__tests__/remoteControlDevicesDeepLink.test.tsx b/apps/desktop/src/renderer/__tests__/remoteControlDevicesDeepLink.test.tsx
new file mode 100644
index 0000000000..bc5d58f69d
--- /dev/null
+++ b/apps/desktop/src/renderer/__tests__/remoteControlDevicesDeepLink.test.tsx
@@ -0,0 +1,139 @@
+// @vitest-environment jsdom
+
+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { renderToStaticMarkup } from 'react-dom/server';
+import { MemoryRouter, useLocation, useNavigate } from 'react-router-dom';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+const { deviceLinkSettings } = vi.hoisted(() => ({
+ deviceLinkSettings: {
+ enabled: true,
+ linkStatus: 'online',
+ connectionIssue: null,
+ devices: [
+ {
+ deviceId: 'self',
+ name: 'Studio Mac',
+ platform: 'darwin',
+ appVersion: '1.0.0',
+ lastSeenAt: null,
+ online: true,
+ busy: false,
+ remoteControlEnabled: true,
+ controlEnabled: true,
+ isSelf: true,
+ },
+ ],
+ controlledBy: [],
+ revokedControllers: [],
+ disabledControlDeviceIds: [],
+ listError: null,
+ refreshing: false,
+ },
+}));
+vi.mock('@/hooks/useDeviceLinkSettings', () => ({
+ useDeviceLinkSettings: () => deviceLinkSettings,
+}));
+vi.mock('@/contexts/AuthContext', () => ({ useAuth: () => ({ mode: 'cloud' }) }));
+vi.mock('../components/settings/MyDevicesPanel', () => ({
+ MyDevicesPanel: () => <div data-testid="my-devices-panel" />,
+}));
+vi.mock('../components/settings/RemoteSection', () => ({
+ RemoteSection: () => <div data-testid="remote-section" />,
+}));
+
+import { RemoteControlSection } from '@/components/settings/RemoteControlSection';
+
+// 收起态的 header 无障碍名里还会带上摘要文案,所以用前缀匹配。
+const devicesHeader = () =>
+ screen.getByRole('button', { name: /^settings\.remoteControl\.sections\.myDevices/ });
+
+function DeepLinkTrigger() {
+ const navigate = useNavigate();
+ return (
+ <button type="button" onClick={() => navigate('/settings?tab=remote-control&section=devices')}>
+ go devices
+ </button>
+ );
+}
+
+function LocationProbe() {
+ const location = useLocation();
+ return <span data-testid="search">{location.search}</span>;
+}
+
+const currentSearch = () => screen.getByTestId('search').textContent ?? '';
+
+beforeEach(() => {
+ Object.defineProperty(window, 'electronAPI', {
+ configurable: true,
+ value: {
+ remoteSsh: {
+ list: vi.fn(async () => ({ hosts: [] })),
+ onStatusChanged: vi.fn(() => vi.fn()),
+ },
+ },
+ });
+});
+
+afterEach(() => {
+ cleanup();
+ vi.restoreAllMocks();
+});
+
+describe('RemoteControlSection devices deep link', () => {
+ it('renders the devices section expanded on the very first paint', () => {
+ // 用 SSR 渲染拿「effect 跑之前」的那一帧:放在 effect 里展开会先画一帧收起,
+ // 再把下方内容顶开一格。render() 会同步冲掉 effect,分辨不出这一帧。
+ const firstPaint = renderToStaticMarkup(
+ <MemoryRouter initialEntries={['/settings?tab=remote-control&section=devices']}>
+ <RemoteControlSection />
+ </MemoryRouter>,
+ );
+
+ // 只看「我的设备」那颗 header:SSH 子块默认收起,它的 aria-expanded=false 是对的。
+ expect(firstPaint).toMatch(
+ /aria-expanded="true"[\s\S]{0,300}?settings\.remoteControl\.sections\.myDevices/,
+ );
+ expect(firstPaint).not.toMatch(
+ /aria-expanded="false"[\s\S]{0,300}?settings\.remoteControl\.sections\.myDevices/,
+ );
+ });
+
+ it('keeps the deep link when it arrives while the page is already mounted', async () => {
+ render(
+ <MemoryRouter initialEntries={['/settings?tab=remote-control']}>
+ <LocationProbe />
+ <DeepLinkTrigger />
+ <RemoteControlSection />
+ </MemoryRouter>,
+ );
+ expect(devicesHeader().getAttribute('aria-expanded')).toBe('false');
+
+ fireEvent.click(screen.getByRole('button', { name: 'go devices' }));
+ await waitFor(() => expect(devicesHeader().getAttribute('aria-expanded')).toBe('true'));
+
+ // 清 URL 的 effect 不能拿这一帧还没提交的 devicesOpen=false 把刚进来的深链清掉,
+ // 否则刷新/返回时这条链接就失效了。
+ expect(currentSearch()).toContain('section=devices');
+ });
+
+ it('drops the section param once the user collapses the list', async () => {
+ render(
+ <MemoryRouter initialEntries={['/settings?tab=remote-control&section=devices']}>
+ <LocationProbe />
+ <RemoteControlSection />
+ </MemoryRouter>,
+ );
+
+ fireEvent.click(devicesHeader());
+
+ await waitFor(() => expect(currentSearch()).not.toContain('section=devices'));
+ expect(currentSearch()).toContain('tab=remote-control');
+ expect(devicesHeader().getAttribute('aria-expanded')).toBe('false');
+ });
+});
diff --git a/apps/desktop/src/renderer/__tests__/userInfoSectionHover.test.ts b/apps/desktop/src/renderer/__tests__/userInfoSectionHover.test.ts
index 57598481e8..e1e7553fba 100644
--- a/apps/desktop/src/renderer/__tests__/userInfoSectionHover.test.ts
+++ b/apps/desktop/src/renderer/__tests__/userInfoSectionHover.test.ts
@@ -18,17 +18,14 @@ import { describe, it, expect } from 'vitest';
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
-const sourcePath = resolve(
- __dirname,
- '..',
- 'components',
- 'sidebar',
- 'UserInfoSection.tsx',
-);
+const sourcePath = resolve(__dirname, '..', 'components', 'sidebar', 'UserInfoSection.tsx');
const source = readFileSync(sourcePath, 'utf8');
const localePath = resolve(__dirname, '..', 'i18n', 'locales', 'zh-CN', 'common.json');
const locale = JSON.parse(readFileSync(localePath, 'utf8')) as {
- sidebar: { user: { settingsLink: string; canaryBadge: string } };
+ sidebar: {
+ user: { settingsLink: string; canaryBadge: string; downloadMobile: string };
+ mobileDownload: { title: string };
+ };
};
// ── 改动 1: 外层 footer slot + tokenized account capsule ────────────────
@@ -51,30 +48,22 @@ describe('UserInfoSection — outer wrapper takes over full-row hover', () => {
});
it('capsule owns the hover state via the glass hover token', () => {
- expect(source).toContain(
- "'transition-colors hover:bg-[var(--sidebar-user-card-bg-hover)]'",
- );
+ expect(source).toContain("'transition-colors hover:bg-[var(--sidebar-user-card-bg-hover)]'");
});
it('capsule hover is suppressed while the flame button is hovered (:has() exclusion)', () => {
// 悬停火焰按钮时胶囊底色还原,只让火焰自己高亮 —— 方案 D 语义
- expect(source).toContain(
- "'has-[.flame-btn:hover]:bg-[var(--sidebar-user-card-bg)]'",
- );
+ expect(source).toContain("'has-[.flame-btn:hover]:bg-[var(--sidebar-user-card-bg)]'");
});
});
describe('UserInfoSection — version label', () => {
it('shows the build region alongside the app version', () => {
- expect(source).toContain(
- "import { CURRENT_CINDY_REGION } from '../../../shared/brandRegion';",
- );
+ expect(source).toContain("import { CURRENT_CINDY_REGION } from '../../../shared/brandRegion';");
expect(source).toContain(
"const appRegionLabel = CURRENT_CINDY_REGION === 'global' ? 'Global' : 'CN';",
);
- expect(source).toContain(
- 'const appVersionLabel = `${appRegionLabel} · ${appDisplayVersion}`;',
- );
+ expect(source).toContain('const appVersionLabel = `${appRegionLabel} · ${appDisplayVersion}`;');
expect(source).not.toContain('XD.Inc');
expect(source).toContain('{appVersionLabel}');
expect(source).toContain('title={appVersionLabelDetail}');
@@ -83,7 +72,7 @@ describe('UserInfoSection — version label', () => {
describe('UserInfoSection — Canary avatar badge', () => {
it('shows only the shield decoration when isCanary is true', () => {
- expect(source).toContain("import { Flame, Shield } from 'lucide-react';");
+ expect(source).toContain("import { Flame, Shield, Smartphone } from 'lucide-react';");
expect(source).toContain('const { user, mode, isCanary } = useAuth();');
expect(source).toContain('{isCanary && (');
expect(source).toContain("aria-label={t('sidebar.user.canaryBadge')}");
@@ -93,6 +82,36 @@ describe('UserInfoSection — Canary avatar badge', () => {
});
});
+describe('UserInfoSection — mobile download entry', () => {
+ it('uses the local Lucide Smartphone icon in a matching 22x22 capsule action', () => {
+ expect(source).toContain("import { Flame, Shield, Smartphone } from 'lucide-react';");
+ expect(source).toMatch(/'mobile-download-btn',\s*\n\s*'flex h-\[22px\] w-\[22px\]/);
+ expect(source).toContain("!isCollapsed && 'mr-1'");
+ expect(source).toContain('<Smartphone className="h-3 w-3" aria-hidden="true" />');
+ });
+
+ it('suppresses capsule hover while the mobile button owns the hover state', () => {
+ expect(source).toContain("'has-[.mobile-download-btn:hover]:bg-[var(--sidebar-user-card-bg)]'");
+ });
+
+ it('opens the mobile download dialog with an accessible label', () => {
+ expect(source).toContain('onClick={() => setMobileDownloadOpen(true)}');
+ expect(source).toContain("aria-label={t('sidebar.user.downloadMobile')}");
+ expect(source).toContain("navigate('/settings?tab=remote-control')");
+ expect(source).toContain("const remoteAvailable = mode === 'cloud';");
+ expect(source).toContain('remoteAvailable={remoteAvailable}');
+ expect(locale.sidebar.user.downloadMobile).toBe('下载 Cindy 移动端');
+ expect(locale.sidebar.mobileDownload.title).toBe('远程控制 Cindy');
+ });
+
+ it('keeps the same entry and dialog available in the collapsed sidebar', () => {
+ expect(source).toContain(
+ 'className="mt-auto flex h-[66px] flex-col items-center justify-center gap-1 px-3"',
+ );
+ expect(source).toContain('{mobileDownloadEntry}');
+ });
+});
+
// ── 改动 2: 内部主按钮去掉冗余 hover / 圆角 ───────────────────────────
describe('UserInfoSection — inner main button no longer owns hover background', () => {
@@ -104,9 +123,7 @@ describe('UserInfoSection — inner main button no longer owns hover background'
it('main button does not own hover:bg-sidebar-item-hover (delegated to outer div)', () => {
// 旧第二行: 'transition-colors text-left hover:bg-sidebar-item-hover',
- expect(source).not.toMatch(
- /'transition-colors text-left hover:bg-sidebar-item-hover'/,
- );
+ expect(source).not.toMatch(/'transition-colors text-left hover:bg-sidebar-item-hover'/);
});
it('main button keeps its layout classes (flex / w-full / gap)', () => {
@@ -121,9 +138,7 @@ describe('UserInfoSection — inner main button no longer owns hover background'
it('main button preserves onClick / role="link" / aria-label (跳转和无障碍不破)', () => {
expect(source).toContain('onClick={handleClick}');
expect(source).toContain('role="link"');
- expect(source).toContain(
- "aria-label={t('sidebar.user.settingsLink', { name: displayName })}",
- );
+ expect(source).toContain("aria-label={t('sidebar.user.settingsLink', { name: displayName })}");
expect(locale.sidebar.user.settingsLink).toBe('设置, 当前用户: {{name}}');
});
});
@@ -136,11 +151,9 @@ describe('UserInfoSection — Flame button carries .flame-btn marker class', ()
expect(source).toMatch(/'flame-btn',\s*\n\s*'flex h-\[22px\] w-\[22px\]/);
});
- it("Flame button retains its own hover:bg-sidebar-item-hover (capsule highlight when hovered)", () => {
+ it('Flame button retains its own hover:bg-sidebar-item-hover (capsule highlight when hovered)', () => {
// Flame 自己的胶囊 hover 不能丢,这是方案 D 的视觉表达
- expect(source).toMatch(
- /'transition-colors hover:bg-sidebar-item-hover'/,
- );
+ expect(source).toMatch(/'transition-colors hover:bg-sidebar-item-hover'/);
});
it('Flame button keeps rounded-full + 22x22 size inside the account capsule', () => {
diff --git a/apps/desktop/src/renderer/__tests__/userInfoSectionMobileDownload.test.tsx b/apps/desktop/src/renderer/__tests__/userInfoSectionMobileDownload.test.tsx
new file mode 100644
index 0000000000..21f2f2006a
--- /dev/null
+++ b/apps/desktop/src/renderer/__tests__/userInfoSectionMobileDownload.test.tsx
@@ -0,0 +1,109 @@
+// @vitest-environment jsdom
+
+import { cleanup, fireEvent, render, screen } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const { navigate } = vi.hoisted(() => ({
+ navigate: vi.fn(),
+}));
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string) => key,
+ }),
+}));
+
+vi.mock('react-router-dom', () => ({
+ useLocation: () => ({ pathname: '/' }),
+ useNavigate: () => navigate,
+}));
+
+vi.mock('@/contexts/AuthContext', () => ({
+ useAuth: () => ({
+ user: { name: 'Cindy user', avatar: null },
+ mode: 'cloud',
+ isCanary: false,
+ }),
+}));
+
+vi.mock('@/hooks/useUpdateStatus', () => ({
+ useUpdateStatus: () => ({ status: 'idle' }),
+}));
+
+vi.mock('@/hooks/useUpdateBannerDismiss', () => ({
+ useUpdateBannerDismiss: () => ({ dismissed: false, restore: vi.fn() }),
+}));
+
+vi.mock('@/components/sidebar/MobileDownloadDialog', () => ({
+ MobileDownloadDialog: ({
+ open,
+ remoteAvailable,
+ onOpenRemoteSettings,
+ onOpenDevices,
+ }: {
+ open: boolean;
+ remoteAvailable: boolean;
+ onOpenRemoteSettings: () => void;
+ onOpenDevices: () => void;
+ }) =>
+ open ? (
+ <div role="dialog">
+ <span>{remoteAvailable ? 'remote available' : 'remote unavailable'}</span>
+ <button type="button" onClick={onOpenRemoteSettings}>
+ open remote settings
+ </button>
+ <button type="button" onClick={onOpenDevices}>
+ open linked devices
+ </button>
+ </div>
+ ) : null,
+}));
+
+import { UserInfoSection } from '@/components/sidebar/UserInfoSection';
+
+beforeEach(() => {
+ navigate.mockClear();
+ Object.defineProperty(window, 'electronAPI', {
+ configurable: true,
+ value: {
+ appDisplayVersion: '1.0.0',
+ appDisplayVersionDetail: '1.0.0-test',
+ },
+ });
+});
+
+afterEach(cleanup);
+
+describe('UserInfoSection mobile download entry', () => {
+ it.each([
+ ['expanded', false],
+ ['collapsed', true],
+ ])('opens the dialog from the %s sidebar', (_label, isCollapsed) => {
+ render(<UserInfoSection isCollapsed={isCollapsed} />);
+
+ fireEvent.click(
+ screen.getByRole('button', {
+ name: 'sidebar.user.downloadMobile',
+ }),
+ );
+
+ expect(screen.getByRole('dialog')).toBeTruthy();
+ expect(screen.getByText('remote available')).toBeTruthy();
+
+ fireEvent.click(screen.getByRole('button', { name: 'open remote settings' }));
+ expect(navigate).toHaveBeenCalledWith('/settings?tab=remote-control');
+ });
+
+ it('opens the expanded device list from the dialog', () => {
+ render(<UserInfoSection isCollapsed={false} />);
+
+ fireEvent.click(
+ screen.getByRole('button', {
+ name: 'sidebar.user.downloadMobile',
+ }),
+ );
+ fireEvent.click(screen.getByRole('button', { name: 'open linked devices' }));
+
+ expect(navigate).toHaveBeenCalledWith('/settings?tab=remote-control&section=devices');
+ });
+});
diff --git a/apps/desktop/src/renderer/components/settings/RemoteControlSection.tsx b/apps/desktop/src/renderer/components/settings/RemoteControlSection.tsx
index bbb1833980..167bd04ccd 100644
--- a/apps/desktop/src/renderer/components/settings/RemoteControlSection.tsx
+++ b/apps/desktop/src/renderer/components/settings/RemoteControlSection.tsx
@@ -17,8 +17,9 @@
* SSH 主机摘要由本组件自取轻量快照(list + onStatusChanged),不侵入 RemoteSection。
*/
-import { useCallback, useEffect, useState, type ReactNode } from 'react';
+import { useCallback, useEffect, useRef, useState, type ReactNode } from 'react';
import { useTranslation } from 'react-i18next';
+import { useLocation, useNavigate } from 'react-router-dom';
import { ChevronDown, ChevronRight } from 'lucide-react';
import { useDeviceLinkSettings, type DeviceLinkSettings } from '@/hooks/useDeviceLinkSettings';
@@ -136,16 +137,57 @@ function sshSummary(
export function RemoteControlSection() {
const { t } = useTranslation();
const { mode } = useAuth();
+ const location = useLocation();
+ const navigate = useNavigate();
const deviceLinkAvailable = mode === 'cloud';
const s = useDeviceLinkSettings(deviceLinkAvailable);
- const [devicesOpen, setDevicesOpen] = useState(false);
+ // 深链 ?section=devices 必须在首帧就是展开态:放到 effect 里会先画一帧收起,
+ // 再把下方内容顶开一格。
+ const [devicesOpen, setDevicesOpen] = useState(
+ () => new URLSearchParams(location.search).get('section') === 'devices',
+ );
const [sshOpen, setSshOpen] = useState(false);
// SSH 主机轻量快照 —— 只为收起态摘要服务。RemoteSection 内部自管自己的一份;
// 这里不外提它的状态是有意的(979 行组件不为一行摘要重构)。
const [hosts, setHosts] = useState<RemoteHostSnapshot[] | null>(null);
+ useEffect(() => {
+ if (new URLSearchParams(location.search).get('section') === 'devices') {
+ setDevicesOpen(true);
+ }
+ }, [location.search]);
+
+ const collapseRequestedRef = useRef(false);
+ const toggleDevices = useCallback(() => {
+ setDevicesOpen((previous) => {
+ // 只有用户主动收起才需要清 URL;更新函数里只记录这次意图,幂等、可重入。
+ collapseRequestedRef.current = previous;
+ return !previous;
+ });
+ }, []);
+
+ // 收起后把 ?section=devices 摘掉,否则刷新/返回还会再展开一次。挂 effect 是为了
+ // 让 toggle 保持函数式更新;必须再看 collapseRequestedRef,否则「页面已挂载时才
+ // 导航进深链」那一帧会读到还没提交的 devicesOpen=false,把刚进来的深链清掉。
+ useEffect(() => {
+ if (devicesOpen || !collapseRequestedRef.current) return;
+ collapseRequestedRef.current = false;
+
+ const next = new URLSearchParams(location.search);
+ if (next.get('section') !== 'devices') return;
+ next.delete('section');
+ const search = next.toString();
+ navigate(
+ {
+ pathname: location.pathname,
+ search: search ? `?${search}` : '',
+ },
+ { replace: true },
+ );
+ }, [devicesOpen, location.pathname, location.search, navigate]);
+
const refreshHosts = useCallback(async () => {
try {
const res = await window.electronAPI.remoteSsh.list();
@@ -201,7 +243,7 @@ export function RemoteControlSection() {
summary={devSumText}
dotColor={null}
open={devicesOpen}
- onToggle={() => setDevicesOpen((v) => !v)}
+ onToggle={toggleDevices}
pinned={<MyDevicesPanel s={s} variant="self" />}
>
<MyDevicesPanel s={s} variant="others" />
diff --git a/apps/desktop/src/renderer/components/settings/SettingsView.tsx b/apps/desktop/src/renderer/components/settings/SettingsView.tsx
index 16a9e1cd20..c1e6cc4e8c 100644
--- a/apps/desktop/src/renderer/components/settings/SettingsView.tsx
+++ b/apps/desktop/src/renderer/components/settings/SettingsView.tsx
@@ -117,6 +117,7 @@ export function SettingsView() {
next.delete('openPanel');
next.delete('ghost');
next.delete('imGroup');
+ next.delete('section');
// providers 页深链参数(connect/wizard):切走 tab 即作废,防再切回来被误消费。
next.delete('connect');
next.delete('wizard');
diff --git a/apps/desktop/src/renderer/components/sidebar/MobileDownloadDialog.tsx b/apps/desktop/src/renderer/components/sidebar/MobileDownloadDialog.tsx
new file mode 100644
index 0000000000..bd25104007
--- /dev/null
+++ b/apps/desktop/src/renderer/components/sidebar/MobileDownloadDialog.tsx
@@ -0,0 +1,632 @@
+import * as Dialog from '@radix-ui/react-dialog';
+import { useEffect, useMemo, useRef, useState, type RefObject } from 'react';
+import { useTranslation } from 'react-i18next';
+import { ChevronRight, Monitor, QrCode, Settings2, Smartphone, X } from 'lucide-react';
+import * as QRCode from 'qrcode';
+
+import cindyIconUrl from '@/../../resources/icon.png?url';
+import { Spinner } from '@/components/ui/spinner';
+import { compareDevicesByName } from '@/features/device-link/deviceSort';
+import { toast } from '@/lib/toast';
+import { cn } from '@/lib/utils';
+
+interface MobileDownloadDialogProps {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ remoteAvailable: boolean;
+ onOpenRemoteSettings: () => void;
+ onOpenDevices: () => void;
+ triggerRef: RefObject<HTMLButtonElement | null>;
+}
+
+const qrDataUrlCache = new Map<string, string>();
+const qrDataUrlPromises = new Map<string, Promise<string>>();
+
+interface MobileRemoteSnapshot {
+ enabled: boolean;
+ devices: DeviceLinkDeviceView[] | null;
+}
+
+export interface MobileRemotePresentation {
+ layout: 'checking' | 'onboarding' | 'linked';
+ remoteEnabled: boolean;
+ linkedMobileCount: number;
+ otherDeviceCount: number;
+ selfDeviceId: string | null;
+ linkedMobileName: string | null;
+ previewDevices: DeviceLinkDeviceView[];
+}
+
+function isMobileDevice(device: DeviceLinkDeviceView): boolean {
+ return device.platform === 'ios' || device.platform === 'android';
+}
+
+/**
+ * Layout and permission state are intentionally orthogonal: transient relay
+ * connectivity never makes the whole dialog jump between onboarding and
+ * device-management layouts.
+ */
+export function resolveMobileRemotePresentation(
+ snapshot: MobileRemoteSnapshot,
+): MobileRemotePresentation {
+ if (!snapshot.devices) {
+ return {
+ layout: 'checking',
+ remoteEnabled: snapshot.enabled,
+ linkedMobileCount: 0,
+ otherDeviceCount: 0,
+ selfDeviceId: null,
+ linkedMobileName: null,
+ previewDevices: [],
+ };
+ }
+
+ const selfDevice = snapshot.devices.find((device) => device.isSelf);
+ const otherDevices = snapshot.devices
+ .filter((device) => !device.isSelf)
+ .sort(compareDevicesByName);
+ const linkedMobileDevices = otherDevices.filter(isMobileDevice);
+ // 手机优先,同组内继续按名字排;显式写出并列条件,不依赖 sort 的稳定性。
+ const previewDevices = [...otherDevices]
+ .sort(
+ (left, right) =>
+ Number(isMobileDevice(right)) - Number(isMobileDevice(left)) ||
+ compareDevicesByName(left, right),
+ )
+ .slice(0, 3);
+
+ return {
+ layout: linkedMobileDevices.length > 0 ? 'linked' : 'onboarding',
+ remoteEnabled: snapshot.enabled,
+ linkedMobileCount: linkedMobileDevices.length,
+ otherDeviceCount: otherDevices.length,
+ selfDeviceId: selfDevice?.deviceId ?? null,
+ linkedMobileName: linkedMobileDevices[0]?.name ?? null,
+ previewDevices,
+ };
+}
+
+const LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', '::1']);
+
+/**
+ * https 之外只放行本机回环 —— `config/endpoint.dev.json.example` 的
+ * `websiteUrl` 是 `http://localhost:3000`,开发机不该看到一个禁用的二维码;
+ * 但公网 http 仍然拒绝,免得区域配置被改成明文站点。
+ */
+function parseWebsiteUrl(value: string): URL | null {
+ try {
+ const url = new URL(value);
+ if (url.username || url.password) return null;
+ if (url.protocol === 'https:') return url;
+ return url.protocol === 'http:' && LOOPBACK_HOSTS.has(url.hostname) ? url : null;
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * 官网 CN 主站是 `cindy.cn`,打包配置里的 `cindy.com.cn` 只是会 302 过去的别名。
+ * 二维码是给手机扫的,直接给最终地址少一跳,也避免手机上先闪一下跳转页。
+ */
+const WEBSITE_HOST_ALIASES: Record<string, string> = {
+ 'cindy.com.cn': 'cindy.cn',
+ 'www.cindy.com.cn': 'cindy.cn',
+ 'www.cindy.cn': 'cindy.cn',
+ 'www.cindy.app': 'cindy.app',
+};
+
+export function resolveMobileDownloadUrl(websiteUrl: string): string | null {
+ const website = parseWebsiteUrl(websiteUrl);
+ if (!website) return null;
+
+ const downloadUrl = new URL('/download/', website);
+ const canonicalHost = WEBSITE_HOST_ALIASES[downloadUrl.hostname];
+ if (canonicalHost) downloadUrl.hostname = canonicalHost;
+ return downloadUrl.toString();
+}
+
+function getQrDataUrl(downloadUrl: string): Promise<string> {
+ const cached = qrDataUrlCache.get(downloadUrl);
+ if (cached) return Promise.resolve(cached);
+
+ const pending = qrDataUrlPromises.get(downloadUrl);
+ if (pending) return pending;
+
+ const promise = QRCode.toDataURL(downloadUrl, {
+ margin: 2,
+ width: 234,
+ })
+ .then((dataUrl) => {
+ qrDataUrlCache.set(downloadUrl, dataUrl);
+ qrDataUrlPromises.delete(downloadUrl);
+ return dataUrl;
+ })
+ .catch((error) => {
+ qrDataUrlPromises.delete(downloadUrl);
+ throw error;
+ });
+
+ qrDataUrlPromises.set(downloadUrl, promise);
+ return promise;
+}
+
+function platformLabel(platform: string | null): string {
+ switch (platform) {
+ case 'darwin':
+ return 'macOS';
+ case 'win32':
+ return 'Windows';
+ case 'linux':
+ return 'Linux';
+ case 'ios':
+ return 'iOS';
+ case 'android':
+ return 'Android';
+ default:
+ return platform ?? '—';
+ }
+}
+
+/**
+ * Desktop promotion surface for the regional Cindy mobile download page.
+ * The QR edge reuses the official app artwork, so its brand colors stay
+ * coupled to the asset instead of introducing component-level color values
+ * (registered exception: DESIGN.md §15.7 / §14.4). The card itself carries no
+ * shadow and no pointer tilt.
+ */
+export function MobileDownloadDialog({
+ open,
+ onOpenChange,
+ remoteAvailable,
+ onOpenRemoteSettings,
+ onOpenDevices,
+ triggerRef,
+}: MobileDownloadDialogProps) {
+ const { t } = useTranslation();
+ const [qrDataUrl, setQrDataUrl] = useState<string | null>(null);
+ const [qrError, setQrError] = useState(false);
+ const [qrAttempt, setQrAttempt] = useState(0);
+ const [remoteSnapshot, setRemoteSnapshot] = useState<MobileRemoteSnapshot | null>(null);
+ const [remoteStatusError, setRemoteStatusError] = useState(false);
+ const primaryActionRef = useRef<HTMLButtonElement>(null);
+ const remoteActionRef = useRef<HTMLButtonElement>(null);
+ const closeActionRef = useRef<HTMLButtonElement>(null);
+ const refreshRemoteRef = useRef<(() => void) | null>(null);
+ const skipNextOpenRefreshRef = useRef(false);
+ const openHandledRef = useRef(false);
+ const websiteUrl = window.electronAPI.clientEndpoints.websiteUrl;
+ const downloadUrl = useMemo(() => resolveMobileDownloadUrl(websiteUrl), [websiteUrl]);
+
+ // Prepare the QR before the first click so opening the dialog never waits on
+ // canvas encoding. The module-level cache keeps this a once-per-endpoint cost.
+ // qrAttempt only moves when a reopen retries a previous failure — the sidebar
+ // keeps this component mounted, so without it one transient encoding error
+ // would strand the card in its error state until the app restarts.
+ useEffect(() => {
+ let active = true;
+ setQrError(false);
+
+ if (!downloadUrl) {
+ setQrDataUrl(null);
+ setQrError(true);
+ return;
+ }
+
+ const cached = qrDataUrlCache.get(downloadUrl);
+ if (cached) {
+ setQrDataUrl(cached);
+ return;
+ }
+
+ setQrDataUrl(null);
+ void getQrDataUrl(downloadUrl)
+ .then((dataUrl) => {
+ if (active) setQrDataUrl(dataUrl);
+ })
+ .catch(() => {
+ if (active) setQrError(true);
+ });
+
+ return () => {
+ active = false;
+ };
+ }, [downloadUrl, qrAttempt]);
+
+ // Device state is also warmed while the dialog is closed. This makes its
+ // first rendered layout stable instead of showing a large QR and then
+ // shrinking it after the IPC calls resolve.
+ useEffect(() => {
+ if (!remoteAvailable) {
+ setRemoteSnapshot(null);
+ setRemoteStatusError(false);
+ return;
+ }
+
+ let active = true;
+ let refreshGeneration = 0;
+ const refreshRemoteSnapshot = async () => {
+ refreshGeneration += 1;
+ const generation = refreshGeneration;
+ try {
+ const state = await window.electronAPI.deviceLink.getState();
+ let devices: DeviceLinkDeviceView[] | null = null;
+ try {
+ devices = (await window.electronAPI.deviceLink.listDevices()).devices;
+ } catch {
+ // The permission switch remains useful even if the device list is
+ // temporarily unavailable. Null prevents a failed list from being
+ // presented as a confirmed empty state.
+ }
+ if (!active || generation !== refreshGeneration) return;
+ setRemoteSnapshot((previous) => ({
+ enabled: state.remoteControlEnabled,
+ // A transient list failure is unknown, not a confirmed empty
+ // account. Keep the last known devices so the dialog layout does
+ // not jump from linked back to onboarding during relay turbulence.
+ devices: devices ?? previous?.devices ?? null,
+ }));
+ setRemoteStatusError(false);
+ } catch {
+ if (!active || generation !== refreshGeneration) return;
+ // Preserve the last known layout while exposing this failure through
+ // the permission card. A later presence/status event will retry.
+ setRemoteStatusError(true);
+ }
+ };
+
+ // 设置页改权限、重命名/删除设备都不会经过下面这三个事件(离线时 presence
+ // 更是发不出去),所以每次打开弹窗都要主动重读一次,而不是只靠推送。
+ refreshRemoteRef.current = () => {
+ void refreshRemoteSnapshot();
+ };
+
+ void refreshRemoteSnapshot();
+ // 这一轮预热已经覆盖了「挂载时就是打开状态」的情况,下面的重开刷新不要重复打一次。
+ skipNextOpenRefreshRef.current = true;
+ return () => {
+ active = false;
+ refreshGeneration += 1;
+ refreshRemoteRef.current = null;
+ };
+ }, [remoteAvailable]);
+
+ // 三个推送只在弹窗打开期间订阅 —— 组件随侧边栏常驻,关着的时候没人看这份快照,
+ // 没必要为每次 presence 抖动跑一轮 IPC;重新打开时上面那次全量读取会补上。
+ useEffect(() => {
+ if (!open || !remoteAvailable) return;
+
+ const refresh = () => refreshRemoteRef.current?.();
+ const offPresence = window.electronAPI.deviceLink.onPresenceChanged(refresh);
+ const offStatus = window.electronAPI.deviceLink.onStatusChanged(refresh);
+ const offConnectionIssue = window.electronAPI.deviceLink.onConnectionIssue(refresh);
+ return () => {
+ offPresence();
+ offStatus();
+ offConnectionIssue();
+ };
+ }, [open, remoteAvailable]);
+
+ useEffect(() => {
+ if (!open) {
+ skipNextOpenRefreshRef.current = false;
+ openHandledRef.current = false;
+ return;
+ }
+ // 每次打开只处理一次:后续 qrError / remoteAvailable 的变化不该再触发重试,
+ // 否则一次持续失败会变成打开期间的无限重试。
+ if (openHandledRef.current) return;
+ openHandledRef.current = true;
+
+ if (qrError && downloadUrl) setQrAttempt((attempt) => attempt + 1);
+
+ if (skipNextOpenRefreshRef.current) {
+ skipNextOpenRefreshRef.current = false;
+ return;
+ }
+ refreshRemoteRef.current?.();
+ }, [open, remoteAvailable, qrError, downloadUrl]);
+
+ const openDownloadPage = async () => {
+ if (!downloadUrl) return;
+ try {
+ const result = await window.electronAPI.openExternal(downloadUrl);
+ if (!result.success) toast.error(t('sidebar.mobileDownload.openFailed'));
+ } catch {
+ toast.error(t('sidebar.mobileDownload.openFailed'));
+ }
+ };
+
+ const remotePresentation = remoteSnapshot
+ ? resolveMobileRemotePresentation(remoteSnapshot)
+ : null;
+ const hasLinkedMobile = remotePresentation?.layout === 'linked';
+ const remoteStateKey = remoteStatusError
+ ? 'unavailable'
+ : remoteSnapshot
+ ? remoteSnapshot.enabled
+ ? 'enabled'
+ : 'enable'
+ : 'checking';
+
+ return (
+ <Dialog.Root open={open} onOpenChange={onOpenChange}>
+ <Dialog.Portal>
+ <Dialog.Overlay
+ className={cn(
+ 'fixed inset-0 z-[10000] bg-[var(--overlay-modal)]',
+ 'data-[state=open]:animate-confirm-overlay-in',
+ 'data-[state=closed]:animate-confirm-overlay-out',
+ )}
+ style={{ WebkitAppRegion: 'no-drag' } as React.CSSProperties}
+ />
+ <Dialog.Content
+ className={cn(
+ 'fixed left-1/2 top-1/2 z-[10000] -translate-x-1/2 -translate-y-1/2',
+ 'max-h-[calc(100vh-32px)] w-[400px] max-w-[calc(100vw-32px)] overflow-y-auto overscroll-contain',
+ 'select-none rounded-xl p-4',
+ 'bg-[var(--confirm-bg)] shadow-[var(--confirm-shadow)]',
+ 'data-[state=open]:animate-confirm-content-in',
+ 'data-[state=closed]:animate-confirm-content-out',
+ )}
+ style={{ WebkitAppRegion: 'no-drag' } as React.CSSProperties}
+ onOpenAutoFocus={(event) => {
+ event.preventDefault();
+ const initialFocus =
+ (downloadUrl ? primaryActionRef.current : null) ??
+ (remoteAvailable ? remoteActionRef.current : null) ??
+ closeActionRef.current;
+ initialFocus?.focus();
+ }}
+ onCloseAutoFocus={(event) => {
+ event.preventDefault();
+ triggerRef.current?.focus();
+ }}
+ >
+ <Dialog.Close asChild>
+ <button
+ ref={closeActionRef}
+ type="button"
+ aria-label={t('sidebar.mobileDownload.close')}
+ className={cn(
+ 'absolute right-3 top-3 z-10 flex h-8 w-8 items-center justify-center rounded-full',
+ 'text-[var(--confirm-desc)] transition-colors',
+ 'hover:bg-[var(--surface-hover)] hover:text-[var(--confirm-title)]',
+ 'active:scale-[0.98]',
+ 'focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]',
+ )}
+ >
+ <X className="h-4 w-4" aria-hidden="true" />
+ </button>
+ </Dialog.Close>
+
+ <div className="flex flex-col items-center text-center">
+ <img
+ src={cindyIconUrl}
+ alt=""
+ aria-hidden="true"
+ className="h-16 w-16 select-none object-contain"
+ draggable={false}
+ />
+
+ <Dialog.Title className="mt-3 text-lg font-medium text-[var(--confirm-title)]">
+ {t('sidebar.mobileDownload.title')}
+ </Dialog.Title>
+ <Dialog.Description
+ className="mt-2 flex items-center justify-center gap-2 text-[var(--confirm-desc)]"
+ aria-label={t('sidebar.mobileDownload.subtitle')}
+ >
+ <Smartphone className="h-4 w-4" strokeWidth={1.8} aria-hidden="true" />
+ <span aria-hidden="true" className="text-11 tracking-[0.2em]">
+ ---
+ </span>
+ <Monitor className="h-4 w-4" strokeWidth={1.8} aria-hidden="true" />
+ <span className="sr-only">{t('sidebar.mobileDownload.subtitle')}</span>
+ </Dialog.Description>
+
+ <div
+ className={cn(
+ 'mt-5 flex w-full items-center justify-center',
+ hasLinkedMobile ? 'gap-5 text-left' : 'flex-col text-center',
+ )}
+ >
+ <button
+ ref={primaryActionRef}
+ type="button"
+ disabled={!downloadUrl}
+ data-testid="mobile-download-qr-card"
+ data-compact={hasLinkedMobile ? 'true' : 'false'}
+ aria-label={t('sidebar.mobileDownload.openPage')}
+ className={cn(
+ 'mobile-download-qr-card relative shrink-0 overflow-hidden rounded-xl',
+ hasLinkedMobile ? 'h-[132px] w-[132px]' : 'h-[228px] w-[228px]',
+ 'focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]',
+ 'disabled:cursor-not-allowed disabled:opacity-60',
+ )}
+ onClick={() => {
+ void openDownloadPage();
+ }}
+ >
+ <span
+ aria-hidden="true"
+ className="mobile-download-qr-edge pointer-events-none absolute inset-[-45%]"
+ >
+ <img
+ src={cindyIconUrl}
+ alt=""
+ className="h-full w-full select-none object-cover"
+ draggable={false}
+ />
+ </span>
+ {/* 2px:1px 时红蓝几乎看不见,3px 起就压成相框边了。 */}
+ <span
+ className={cn(
+ 'absolute inset-[2px] flex items-center justify-center overflow-hidden',
+ 'rounded-[10px] bg-[var(--confirm-bg)]',
+ )}
+ aria-live="polite"
+ >
+ {qrDataUrl ? (
+ <img
+ src={qrDataUrl}
+ alt={t('sidebar.mobileDownload.qrAlt')}
+ className="h-full w-full select-none"
+ draggable={false}
+ />
+ ) : qrError ? (
+ <span className="flex max-w-[160px] flex-col items-center gap-2 text-center text-[var(--error-fg-strong)]">
+ <QrCode className="h-6 w-6" aria-hidden="true" />
+ <span className="text-12 leading-[18px]">
+ {t('sidebar.mobileDownload.error')}
+ </span>
+ </span>
+ ) : (
+ <span className="flex flex-col items-center gap-3 text-[var(--confirm-desc)]">
+ <Spinner size={20} />
+ <span className="text-12">{t('sidebar.mobileDownload.preparing')}</span>
+ </span>
+ )}
+ </span>
+ </button>
+
+ <div className={cn(hasLinkedMobile ? 'min-w-0 flex-1' : 'mt-4')}>
+ {/* 未连设备时只留扫码这一行说明(要求同时说清"登录同一账号"),
+ 不再补平台支持副标题。 */}
+ <p
+ className={cn(
+ 'text-14 font-medium text-[var(--confirm-title)]',
+ !hasLinkedMobile && 'max-w-[260px]',
+ )}
+ >
+ {t(
+ hasLinkedMobile
+ ? 'sidebar.mobileDownload.scanAnother'
+ : 'sidebar.mobileDownload.scanToOpen',
+ )}
+ </p>
+ {hasLinkedMobile ? (
+ <p className="mt-1 text-12 leading-[18px] text-[var(--confirm-desc)]">
+ {t('sidebar.mobileDownload.scanAnotherHint')}
+ </p>
+ ) : null}
+ </div>
+ </div>
+
+ {hasLinkedMobile && remotePresentation ? (
+ <button
+ type="button"
+ onClick={onOpenDevices}
+ className={cn(
+ 'mt-5 w-full rounded-xl border border-[var(--border-default)] px-3 py-3 text-left',
+ 'transition-colors hover:bg-[var(--surface-hover-soft)]',
+ 'active:scale-[0.98]',
+ 'focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]',
+ )}
+ >
+ <span className="flex items-center justify-between gap-3">
+ <span className="text-14 font-medium text-[var(--confirm-title)]">
+ {t('sidebar.mobileDownload.myDevices')}
+ </span>
+ <span className="flex items-center gap-2 text-[var(--confirm-desc)]">
+ <span className="rounded-full bg-[var(--surface-chip)] px-2 py-0.5 text-11 font-medium text-[var(--confirm-title)]">
+ {remotePresentation.otherDeviceCount}
+ </span>
+ <ChevronRight className="h-4 w-4" aria-hidden="true" />
+ </span>
+ </span>
+
+ <span className="mt-2 flex flex-col">
+ {remotePresentation.previewDevices.map((device, index) => {
+ const online = device.online;
+ return (
+ <span
+ key={device.deviceId}
+ className={cn(
+ 'flex items-center gap-3 py-2',
+ index > 0 && 'border-t border-[var(--border-default)]',
+ )}
+ >
+ <span className="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-[var(--surface-hover-soft)] text-[var(--confirm-desc)]">
+ {isMobileDevice(device) ? (
+ <Smartphone className="h-4 w-4" strokeWidth={1.8} aria-hidden="true" />
+ ) : (
+ <Monitor className="h-4 w-4" strokeWidth={1.8} aria-hidden="true" />
+ )}
+ </span>
+ <span className="flex min-w-0 flex-1 flex-col">
+ <span className="truncate text-13 font-medium text-[var(--confirm-title)]">
+ {device.name}
+ </span>
+ <span className="mt-0.5 flex items-center gap-1.5 text-11 text-[var(--confirm-desc)]">
+ <span
+ className="h-1.5 w-1.5 rounded-full"
+ style={{
+ backgroundColor: online
+ ? 'var(--remote-status-ready)'
+ : 'var(--remote-status-disconnected)',
+ }}
+ aria-hidden="true"
+ />
+ {online
+ ? t('settings.devices.status.online')
+ : t('sidebar.mobileDownload.deviceOffline')}
+ <span aria-hidden="true">·</span>
+ {platformLabel(device.platform)}
+ </span>
+ </span>
+ </span>
+ );
+ })}
+ </span>
+ </button>
+ ) : null}
+
+ {remoteAvailable ? (
+ <button
+ ref={remoteActionRef}
+ type="button"
+ onClick={onOpenRemoteSettings}
+ className={cn(
+ 'mt-3 flex w-full items-center gap-3 rounded-xl border border-[var(--border-default)] px-3 py-3 text-left',
+ 'transition-colors hover:bg-[var(--surface-hover-soft)]',
+ 'active:scale-[0.98]',
+ 'focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]',
+ )}
+ >
+ <span className="flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-[var(--surface-chip)] text-[var(--confirm-title)]">
+ <Settings2 className="h-4 w-4" strokeWidth={1.8} aria-hidden="true" />
+ </span>
+ <span className="flex min-w-0 flex-1 flex-col">
+ <span className="text-13 font-medium leading-[18px] text-[var(--confirm-title)]">
+ {t('sidebar.mobileDownload.allowControl')}
+ </span>
+ {remotePresentation?.selfDeviceId ? (
+ <span
+ className="mt-0.5 truncate font-mono text-10 leading-[14px] text-[var(--confirm-desc)]"
+ title={remotePresentation.selfDeviceId}
+ >
+ {t('sidebar.mobileDownload.deviceId', {
+ id: remotePresentation.selfDeviceId,
+ })}
+ </span>
+ ) : null}
+ </span>
+ <span className="flex shrink-0 items-center gap-1.5 text-12 text-[var(--confirm-desc)]">
+ {/* 状态读取失败时右侧文案已经是「暂不可用」,再留一颗上一次成功
+ 读到的绿点会同时给出两个互相矛盾的信号。 */}
+ {!remoteStatusError && remoteSnapshot?.enabled ? (
+ <span
+ className="h-1.5 w-1.5 rounded-full bg-[var(--remote-status-ready)]"
+ aria-hidden="true"
+ />
+ ) : null}
+ <span>{t(`sidebar.mobileDownload.remoteAction.${remoteStateKey}`)}</span>
+ <ChevronRight className="h-4 w-4" aria-hidden="true" />
+ </span>
+ </button>
+ ) : null}
+ </div>
+ </Dialog.Content>
+ </Dialog.Portal>
+ </Dialog.Root>
+ );
+}
diff --git a/apps/desktop/src/renderer/components/sidebar/UserInfoSection.tsx b/apps/desktop/src/renderer/components/sidebar/UserInfoSection.tsx
index 9338de83db..636b35f245 100644
--- a/apps/desktop/src/renderer/components/sidebar/UserInfoSection.tsx
+++ b/apps/desktop/src/renderer/components/sidebar/UserInfoSection.tsx
@@ -1,13 +1,14 @@
-import { useEffect, useState } from 'react';
+import { useEffect, useRef, useState } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
-import { Flame, Shield } from 'lucide-react';
+import { Flame, Shield, Smartphone } from 'lucide-react';
import { cn } from '@/lib/utils';
import { useAuth } from '@/contexts/AuthContext';
import { useUpdateStatus } from '@/hooks/useUpdateStatus';
import { useUpdateBannerDismiss } from '@/hooks/useUpdateBannerDismiss';
import { CURRENT_CINDY_REGION } from '../../../shared/brandRegion';
+import { MobileDownloadDialog } from './MobileDownloadDialog';
interface UserInfoSectionProps {
isCollapsed: boolean;
@@ -19,6 +20,8 @@ export function UserInfoSection({ isCollapsed, onOpenUpdateNotice }: UserInfoSec
const navigate = useNavigate();
const location = useLocation();
const [avatarError, setAvatarError] = useState(false);
+ const [mobileDownloadOpen, setMobileDownloadOpen] = useState(false);
+ const mobileDownloadButtonRef = useRef<HTMLButtonElement>(null);
const { t } = useTranslation();
// 火焰按钮双职责:
@@ -47,6 +50,7 @@ export function UserInfoSection({ isCollapsed, onOpenUpdateNotice }: UserInfoSec
const appRegionLabel = CURRENT_CINDY_REGION === 'global' ? 'Global' : 'CN';
const appVersionLabel = `${appRegionLabel} · ${appDisplayVersion}`;
const appVersionLabelDetail = `${appRegionLabel} · ${appDisplayVersionDetail}`;
+ const remoteAvailable = mode === 'cloud';
const handleClick = () => {
if (location.pathname !== '/settings') {
@@ -54,63 +58,104 @@ export function UserInfoSection({ isCollapsed, onOpenUpdateNotice }: UserInfoSec
}
};
+ const openRemoteSettings = () => {
+ setMobileDownloadOpen(false);
+ navigate('/settings?tab=remote-control');
+ };
+
+ const openLinkedDevices = () => {
+ setMobileDownloadOpen(false);
+ navigate('/settings?tab=remote-control&section=devices');
+ };
+
+ const mobileDownloadEntry = (
+ <button
+ ref={mobileDownloadButtonRef}
+ type="button"
+ onClick={() => setMobileDownloadOpen(true)}
+ aria-label={t('sidebar.user.downloadMobile')}
+ className={cn(
+ 'mobile-download-btn',
+ 'flex h-[22px] w-[22px] shrink-0 items-center justify-center rounded-full',
+ !isCollapsed && 'mr-1',
+ 'border border-[var(--sidebar-user-card-border)] bg-[var(--sidebar-user-card-bg)]',
+ 'text-[var(--sidebar-user-card-text)] transition-colors hover:bg-sidebar-item-hover',
+ 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]',
+ )}
+ >
+ <Smartphone className="h-3 w-3" aria-hidden="true" />
+ </button>
+ );
+
if (isCollapsed) {
return (
- <div className="mt-auto flex h-[66px] items-center justify-center px-3">
- <button
- onClick={handleClick}
- role="link"
- aria-label={t('sidebar.user.settingsLink', { name: displayName })}
- className="flex min-w-0 items-center justify-center text-left"
- >
- <div
- className="relative h-9 w-9 shrink-0"
- title={isCanary ? t('sidebar.user.canaryBadge') : undefined}
+ <>
+ <div className="mt-auto flex h-[66px] flex-col items-center justify-center gap-1 px-3">
+ <button
+ onClick={handleClick}
+ role="link"
+ aria-label={t('sidebar.user.settingsLink', { name: displayName })}
+ className="flex min-w-0 items-center justify-center text-left"
>
- {user?.avatar && !avatarError ? (
- <img
- src={user.avatar}
- alt={displayName}
- className="h-9 w-9 rounded-full object-cover"
- onError={() => setAvatarError(true)}
- />
- ) : (
- <div
- className={cn(
- 'flex h-9 w-9 items-center justify-center rounded-full',
- 'border border-sidebar-border bg-sidebar-item-hover text-base font-medium text-foreground',
- )}
- >
- {initial}
- </div>
- )}
- {isCanary && (
- <span
- aria-label={t('sidebar.user.canaryBadge')}
- className={cn(
- 'absolute -bottom-0.5 -right-0.5',
- 'flex h-3 w-3 items-center justify-center rounded-full',
- 'bg-foreground text-background ring-2 ring-sidebar',
- )}
- >
- <Shield size={8} strokeWidth={2.5} />
- </span>
- )}
- </div>
- </button>
- </div>
+ <div
+ className="relative h-9 w-9 shrink-0"
+ title={isCanary ? t('sidebar.user.canaryBadge') : undefined}
+ >
+ {user?.avatar && !avatarError ? (
+ <img
+ src={user.avatar}
+ alt={displayName}
+ className="h-9 w-9 rounded-full object-cover"
+ onError={() => setAvatarError(true)}
+ />
+ ) : (
+ <div
+ className={cn(
+ 'flex h-9 w-9 items-center justify-center rounded-full',
+ 'border border-sidebar-border bg-sidebar-item-hover text-base font-medium text-foreground',
+ )}
+ >
+ {initial}
+ </div>
+ )}
+ {isCanary && (
+ <span
+ aria-label={t('sidebar.user.canaryBadge')}
+ className={cn(
+ 'absolute -bottom-0.5 -right-0.5',
+ 'flex h-3 w-3 items-center justify-center rounded-full',
+ 'bg-foreground text-background ring-2 ring-sidebar',
+ )}
+ >
+ <Shield size={8} strokeWidth={2.5} />
+ </span>
+ )}
+ </div>
+ </button>
+ {mobileDownloadEntry}
+ </div>
+ <MobileDownloadDialog
+ open={mobileDownloadOpen}
+ onOpenChange={setMobileDownloadOpen}
+ remoteAvailable={remoteAvailable}
+ onOpenRemoteSettings={openRemoteSettings}
+ onOpenDevices={openLinkedDevices}
+ triggerRef={mobileDownloadButtonRef}
+ />
+ </>
);
}
return (
<div className="mt-auto px-3 pb-3 pt-2">
- {/* 胶囊整体承载 hover(方案 D):玻璃底色加深一档;悬停火焰按钮时用 :has()
- 把胶囊底色还原,只让火焰自己高亮,避免双层叠色。 */}
+ {/* 胶囊整体承载 hover(方案 D):玻璃底色加深一档;悬停右侧操作按钮时用
+ :has() 把胶囊底色还原,只让当前按钮高亮,避免双层叠色。 */}
<div
className={cn(
'flex h-10 items-center rounded-full border border-[var(--sidebar-user-card-border)] bg-[var(--sidebar-user-card-bg)] px-[7px]',
'transition-colors hover:bg-[var(--sidebar-user-card-bg-hover)]',
'has-[.flame-btn:hover]:bg-[var(--sidebar-user-card-bg)]',
+ 'has-[.mobile-download-btn:hover]:bg-[var(--sidebar-user-card-bg)]',
)}
>
<button
@@ -128,9 +173,7 @@ export function UserInfoSection({ isCollapsed, onOpenUpdateNotice }: UserInfoSec
<img
src={user.avatar}
alt={displayName}
- className={cn(
- 'h-[27px] w-[27px] rounded-full object-cover',
- )}
+ className={cn('h-[27px] w-[27px] rounded-full object-cover')}
onError={() => setAvatarError(true)}
/>
) : (
@@ -181,6 +224,8 @@ export function UserInfoSection({ isCollapsed, onOpenUpdateNotice }: UserInfoSec
</div>
</button>
+ {mobileDownloadEntry}
+
{/* Flame icon button — 默认打开更新历史;banner 被 dismiss 且有 pending
update 时切换为「唤回 banner」入口,视觉涂黑(fill 实心 + foreground 主色)
告诉用户还有更新等待确认。 */}
@@ -219,6 +264,15 @@ export function UserInfoSection({ isCollapsed, onOpenUpdateNotice }: UserInfoSec
</button>
)}
</div>
+
+ <MobileDownloadDialog
+ open={mobileDownloadOpen}
+ onOpenChange={setMobileDownloadOpen}
+ remoteAvailable={remoteAvailable}
+ onOpenRemoteSettings={openRemoteSettings}
+ onOpenDevices={openLinkedDevices}
+ triggerRef={mobileDownloadButtonRef}
+ />
</div>
);
}
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 28a4faaf61..2226abe4d0 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -3612,7 +3612,31 @@
"settingsLink": "Settings, current user: {{name}}",
"canaryBadge": "Canary user",
"viewReleaseNotes": "View release notes",
- "reopenUpdateBanner": "Update ready — click to review"
+ "reopenUpdateBanner": "Update ready — click to review",
+ "downloadMobile": "Download Cindy Mobile"
+ },
+ "mobileDownload": {
+ "title": "Control Cindy Remotely",
+ "subtitle": "Connect your phone to this desktop",
+ "qrAlt": "QR code to download Cindy mobile",
+ "preparing": "Preparing QR code…",
+ "error": "Couldn’t create the QR code. Try again later.",
+ "openPage": "Open Download Page",
+ "openFailed": "Couldn’t open the download page. Check your system browser settings.",
+ "scanToOpen": "Scan to open the Cindy app and sign in with the same account",
+ "scanAnother": "Scan Another Device",
+ "scanAnotherHint": "Open Cindy on another phone",
+ "myDevices": "My Devices",
+ "deviceOffline": "Offline",
+ "allowControl": "Allow same-account devices to control this machine",
+ "deviceId": "This device · {{id}}",
+ "remoteAction": {
+ "checking": "Checking…",
+ "unavailable": "Unavailable",
+ "enable": "Enable",
+ "enabled": "Enabled"
+ },
+ "close": "Close Download Dialog"
},
"vendorReadiness": {
"loading": "loading"
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index e237a85e83..0e8753dd98 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -3611,7 +3611,31 @@
"settingsLink": "設定, 現在のユーザー: {{name}}",
"canaryBadge": "Canary ユーザー",
"viewReleaseNotes": "リリースノートを表示",
- "reopenUpdateBanner": "更新の準備完了 — クリックして確認"
+ "reopenUpdateBanner": "更新の準備完了 — クリックして確認",
+ "downloadMobile": "Cindy モバイル版をダウンロード"
+ },
+ "mobileDownload": {
+ "title": "Cindy をリモート操作",
+ "subtitle": "モバイルからデスクトップへ接続",
+ "qrAlt": "Cindy モバイル版ダウンロード用 QR コード",
+ "preparing": "QR コードを準備しています…",
+ "error": "QR コードを作成できませんでした。しばらくしてからお試しください。",
+ "openPage": "ダウンロードページを開く",
+ "openFailed": "ダウンロードページを開けませんでした。システムのブラウザー設定を確認してください",
+ "scanToOpen": "スキャンして Cindy アプリを開き、同じアカウントでログイン",
+ "scanAnother": "別のデバイスをスキャン",
+ "scanAnotherHint": "別のスマートフォンで Cindy を開く",
+ "myDevices": "自分のデバイス",
+ "deviceOffline": "オフライン",
+ "allowControl": "同じアカウントのデバイスによるこのマシンの操作を許可",
+ "deviceId": "このデバイス · {{id}}",
+ "remoteAction": {
+ "checking": "確認中…",
+ "unavailable": "利用できません",
+ "enable": "有効にする",
+ "enabled": "有効"
+ },
+ "close": "ダウンロード画面を閉じる"
},
"vendorReadiness": {
"loading": "読み込み中"
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index b2842a3e1b..4f67ad4d46 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -3611,7 +3611,31 @@
"settingsLink": "설정, 현재 사용자: {{name}}",
"canaryBadge": "Canary 사용자",
"viewReleaseNotes": "릴리즈 노트 보기",
- "reopenUpdateBanner": "업데이트 준비됨 — 클릭하여 확인"
+ "reopenUpdateBanner": "업데이트 준비됨 — 클릭하여 확인",
+ "downloadMobile": "Cindy 모바일 다운로드"
+ },
+ "mobileDownload": {
+ "title": "Cindy 원격 제어",
+ "subtitle": "모바일에서 데스크톱으로 연결",
+ "qrAlt": "Cindy 모바일 다운로드 QR 코드",
+ "preparing": "QR 코드 준비 중…",
+ "error": "QR 코드를 만들 수 없습니다. 잠시 후 다시 시도해 주세요.",
+ "openPage": "다운로드 페이지 열기",
+ "openFailed": "다운로드 페이지를 열 수 없습니다. 시스템 브라우저 설정을 확인해 주세요",
+ "scanToOpen": "스캔하여 Cindy 앱을 열고 같은 계정으로 로그인",
+ "scanAnother": "다른 기기 스캔",
+ "scanAnotherHint": "다른 휴대폰에서 Cindy 열기",
+ "myDevices": "내 기기",
+ "deviceOffline": "오프라인",
+ "allowControl": "동일 계정 기기에서 이 컴퓨터를 제어하도록 허용",
+ "deviceId": "이 기기 · {{id}}",
+ "remoteAction": {
+ "checking": "확인 중…",
+ "unavailable": "사용할 수 없음",
+ "enable": "켜기",
+ "enabled": "켜짐"
+ },
+ "close": "다운로드 화면 닫기"
},
"vendorReadiness": {
"loading": "로딩 중"
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index 19b8596d24..437f7496f4 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -3611,7 +3611,31 @@
"settingsLink": "设置, 当前用户: {{name}}",
"canaryBadge": "灰度用户",
"viewReleaseNotes": "查看版本日志",
- "reopenUpdateBanner": "有更新待重启,点击查看"
+ "reopenUpdateBanner": "有更新待重启,点击查看",
+ "downloadMobile": "下载 Cindy 移动端"
+ },
+ "mobileDownload": {
+ "title": "远程控制 Cindy",
+ "subtitle": "移动端连接桌面端",
+ "qrAlt": "Cindy 移动端下载二维码",
+ "preparing": "正在生成二维码…",
+ "error": "二维码生成失败,请稍后重试",
+ "openPage": "打开下载页面",
+ "openFailed": "下载页面打开失败,请检查系统默认浏览器设置",
+ "scanToOpen": "扫码打开 Cindy App,并登录同一账号",
+ "scanAnother": "扫码添加另一台设备",
+ "scanAnotherHint": "在另一台手机上打开 Cindy",
+ "myDevices": "我的设备",
+ "deviceOffline": "离线",
+ "allowControl": "允许同账号设备控制本机",
+ "deviceId": "本机 · {{id}}",
+ "remoteAction": {
+ "checking": "正在检查…",
+ "unavailable": "暂不可用",
+ "enable": "去开启",
+ "enabled": "已开启"
+ },
+ "close": "关闭"
},
"vendorReadiness": {
"loading": "加载中"
diff --git a/apps/desktop/src/renderer/styles/globals.css b/apps/desktop/src/renderer/styles/globals.css
index 413071ffa7..53e3233bf8 100644
--- a/apps/desktop/src/renderer/styles/globals.css
+++ b/apps/desktop/src/renderer/styles/globals.css
@@ -57,6 +57,8 @@
--motion-ease-out: cubic-bezier(0.16, 1, 0.3, 1); /* 入场/展开 */
--motion-ease-in: cubic-bezier(0.4, 0, 1, 1); /* 退场 */
--motion-ease-move: cubic-bezier(0.4, 0, 0.2, 1); /* 位置/尺寸插值 */
+ /* 移动端下载卡品牌边的旋转周期(§14.4 登记的第四类常驻动效)。 */
+ --mobile-download-edge-cycle: 20s;
}
body {
@@ -195,6 +197,38 @@
}
}
+/* 移动端下载卡:官方 App icon 在 2px 裁切边缘内缓慢旋转,形成与卡片一体的
+ 红蓝折射(DESIGN.md §15.7 / §14.4 登记的窄范围例外)。卡片本身不加阴影、
+ 不做 3D 倾斜;除品牌边外,唯一动效是设备列表刷新驱动的尺寸补间。 */
+@keyframes mobile-download-edge-turn {
+ from {
+ transform: rotate(0deg) scale(1.45);
+ }
+ to {
+ transform: rotate(360deg) scale(1.45);
+ }
+}
+
+.mobile-download-qr-card {
+ transition:
+ width var(--motion-base) var(--motion-ease-move),
+ height var(--motion-base) var(--motion-ease-move);
+}
+
+/* 只转 transform,不挂 filter/blur:滤镜会让这层每帧重新走一遍 GPU 滤镜通道,
+ 而纯 transform 旋转能整层交给合成器,常驻动画不占 CPU。 */
+.mobile-download-qr-edge {
+ animation: mobile-download-edge-turn var(--mobile-download-edge-cycle) linear infinite;
+ will-change: transform;
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .mobile-download-qr-edge {
+ animation: none;
+ transform: rotate(18deg) scale(1.45);
+ }
+}
+
/* 按 <html lang> 切换 CJK 字体栈 —— 同一汉字在中/日/韩字体中字形不同
(康熙体 vs 新字体 vs 한국체);不按 lang 区分会出现"日文界面里的汉字看起来像中文"。
useLocale.ts 在 setLocale 时把 lang 写到 <html>,:lang() 选择器自动接管。
diff --git a/docs/design-rules/DESIGN.md b/docs/design-rules/DESIGN.md
index 286607c58e..0e3110ab53 100644
--- a/docs/design-rules/DESIGN.md
+++ b/docs/design-rules/DESIGN.md
@@ -587,6 +587,10 @@ Global tokens live in `:root` of `apps/desktop/src/renderer/styles/globals.css`;
- **Form** (finalized over four/five review rounds, 2026-07-23): **true parabolic toss + vanish on landing** — all particles launch simultaneously from the segment center in a ~**100° fan** (±50° of straight up) at equal speed, **constant horizontal velocity + constant vertical gravity** (decelerating up, accelerating down past the apex), so perceived speed is consistent from burst to fall; wider-angle particles fly lower arcs, travel farther, land earlier — the scatter comes from physics, not scripting. The final stretch before the ground line ends in a **short fade**: landing is fine, but lingering after landing ("corpsing") or vanishing without a fade is forbidden; the ground line jitters randomly so landing points don't queue up.
- **Parameter red lines**: a one-shot celebration — simultaneous launch, no stagger delay; per-particle duration follows arc physics clamped to 0.9s–1.6s, total ≈1.6s (the number roll settles at 1.2s, then the last confetti falls a few tenths more; arc scale and rhythm are user-tuned, finalized 2026-07-23); ≤18 particles, 3–5px, torn down when done, never looping or persistent; particles are HTML elements animating only `transform` / `opacity` (compositor-only, engineering conventions §7; x/y split across two nested spans keeps horizontal velocity constant); colors come only from the four status-dot hue exemptions (done green / awaiting teal / thinking orange / error red), same values in both modes; must skip entirely under `prefers-reduced-motion`.
- **Scope boundary**: this one spot only. Confetti must not leak into task completion, send success, or anywhere else — those stay on the §14.4 baseline (a new exemption requires a new entry here). Implementation: `apps/desktop/src/renderer/components/status/QuotaResetConfetti.tsx`.
+- **Mobile-download QR brand edge** — the fourth sanctioned motion class and the only sanctioned *persistent* one (approved 2026-07-25), **only** for the QR card in `MobileDownloadDialog` (brand-surface registration: §15.7):
+ - **Definition**: the official app icon sits scaled behind the QR card and is clipped to a 2px hairline edge; it turns a full circle every **20s** (`--mobile-download-edge-cycle`, linear, infinite), so the artwork's own red/blue drifts along the card edge. The dialog is a promotion surface for the mobile app — the slow drift is what marks the QR as "ours" without adding any component-authored color.
+ - **Parameter red lines**: the animation touches **only `transform`** on an HTML wrapper (compositor-only, engineering conventions §7 — no `filter` / `backdrop-filter` / `mask-image`, nothing on SVG, no per-frame background work); one cycle length, linear, no easing games; registered in the `prefers-reduced-motion` whitelist in `globals.css`, where it degrades to a static angle. The card carries **no shadow and no pointer tilt** — both were evaluated and removed the same day; do not re-add them under this exception.
+ - **Scope boundary**: this card only. Persistent motion elsewhere stays forbidden by the red lines above; a new persistent animation requires a new entry here. Implementation: `.mobile-download-qr-edge` in `globals.css`; contract test: `mobileDownloadDialog.test.tsx` → `keeps the brand edge inside its registered exception`.
## 15. CINDY Skin Family(品牌化可选 family)
@@ -647,6 +651,13 @@ The brand block reads only `brand.icon/logo` — no compatibility with the legac
The splash wordmark is a separate asset pair (`assets/splash/wordmark.png`, white text, for DARK / `wordmark-light.png`, dark text, for LIGHT): both 459×156 (@2x) with a 229.5×78 render frame (its exact 2x full frame), and **neither carries a drop shadow** — `SplashScreen.test.tsx` asserts the absence. (Asset-size and shadow history: decision log.)
+**Sanctioned brand surface — mobile download dialog (approved 2026-07-25).** The fourth surface allowed to carry brand artwork, alongside login / splash / new-session:
+
+- **Where**: `components/sidebar/MobileDownloadDialog.tsx` only — the dialog header icon (64px `resources/icon.png`) and the QR card's 2px edge, where the same asset is scaled behind the card and clipped to a hairline (1px reads as almost no color, 3px starts looking like a picture frame) so the artwork's own red/blue reads as the card's edge. This is a promotion surface for the mobile app, so showing the app's own icon is identification, not decoration.
+- **Constraints**: the color comes only from the official asset — no component-authored gradient or brand hex; the edge layer carries no `filter` / `backdrop-filter` / `mask-image`; its motion is governed by §14.4. The card itself stays flat: **no shadow and no pointer 3D tilt** (both were tried and removed 2026-07-25 — they are not part of this exception).
+- **Scope boundary**: this dialog only. Other working-UI surfaces keep the neutral treatment; a new brand surface needs a new entry here. Contract test: `mobileDownloadDialog.test.tsx` → `keeps the brand edge inside its registered exception`.
+- **Reference renders** (light theme, zh-CN, @2x — `assets/mobile-download-dialog/`): [local mode](assets/mobile-download-dialog/guest-local.webp) (QR only — no account, so no permission card) · [signed in, no linked mobile](assets/mobile-download-dialog/onboarding.webp) (228px QR + permission card) · [signed in, mobile linked](assets/mobile-download-dialog/linked.webp) (132px QR + device list). Re-shoot these when the dialog's layout changes.
+
### 15.8 status-badge-fg
- The orange badge (bg `status-bar-accent` `#EA6B17`) has its own foreground token `status-badge-fg`: **default mirrors `accent-pure-cta-fg`** (light white / dark black — zero change for the 9 existing themes); **CINDY overrides both modes to `#1F1F1F`** (near-black), contrast × `#EA6B17` = **5.19:1 ≥ 4.5** (user-approved; darken toward `#000000` if a future orange fails 4.5).
diff --git a/docs/design-rules/assets/mobile-download-dialog/guest-local.webp b/docs/design-rules/assets/mobile-download-dialog/guest-local.webp
new file mode 100644
index 0000000000..c4cb9c8200
Binary files /dev/null and b/docs/design-rules/assets/mobile-download-dialog/guest-local.webp differ
diff --git a/docs/design-rules/assets/mobile-download-dialog/linked.webp b/docs/design-rules/assets/mobile-download-dialog/linked.webp
new file mode 100644
index 0000000000..3a2f0982f9
Binary files /dev/null and b/docs/design-rules/assets/mobile-download-dialog/linked.webp differ
diff --git a/docs/design-rules/assets/mobile-download-dialog/onboarding.webp b/docs/design-rules/assets/mobile-download-dialog/onboarding.webp
new file mode 100644
index 0000000000..4f0358c41d
Binary files /dev/null and b/docs/design-rules/assets/mobile-download-dialog/onboarding.webp differ