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。

fix(desktop): 优化启动端点错误反馈 (#1540)

Dash2b762f749437
diff --git a/apps/desktop/src/main/__tests__/clientEndpointsService.test.ts b/apps/desktop/src/main/__tests__/clientEndpointsService.test.ts
index 7511332912..6a08133e52 100644
--- a/apps/desktop/src/main/__tests__/clientEndpointsService.test.ts
+++ b/apps/desktop/src/main/__tests__/clientEndpointsService.test.ts
@@ -21,6 +21,8 @@ import { TEST_CLIENT_ENDPOINTS } from '../../test/vitest/clientEndpointsFixture'
const ipcOn = vi.hoisted(() => vi.fn());
const netRequest = vi.hoisted(() => vi.fn());
+const showMessageBoxSync = vi.hoisted(() => vi.fn());
+const clipboardWriteText = vi.hoisted(() => vi.fn());
vi.mock('electron', () => ({
app: {
getPath: vi.fn(),
@@ -28,7 +30,8 @@ vi.mock('electron', () => ({
isPackaged: false,
exit: vi.fn(),
},
- dialog: { showMessageBoxSync: vi.fn() },
+ dialog: { showMessageBoxSync },
+ clipboard: { writeText: clipboardWriteText },
ipcMain: { on: ipcOn },
net: { request: netRequest },
// netLog 是静态 import(architecture-invariants.md §2);captureEndpointNetLog 这条
@@ -46,6 +49,7 @@ import {
activateClientEndpointRealm,
captureNetLogAround,
prepareEndpointNetLogFile,
+ promptRetryDialog,
verifyEndpointNetLogCapture,
classifyManifestFailure,
getClientEndpoint,
@@ -67,6 +71,8 @@ afterEach(() => {
resetClientEndpointsForTest();
ipcOn.mockClear();
netRequest.mockReset();
+ showMessageBoxSync.mockReset();
+ clipboardWriteText.mockReset();
});
const FULL_MANIFEST = JSON.stringify({
@@ -97,6 +103,93 @@ const LOCAL_MANIFEST = JSON.stringify({
deviceLinkApiBaseUrl: 'http://localhost:3335',
});
+describe('启动失败系统提示框', () => {
+ it('使用友好警告文案并展示简短错误信息,但不展示地址、网络诊断或本机路径', () => {
+ showMessageBoxSync.mockReturnValueOnce(0);
+
+ const choice = promptRetryDialog(
+ {
+ reason: 'fetch-failed:ERR_CONNECTION_RESET',
+ kind: 'network',
+ diagnosis: 'proxy=DIRECT dns=ok(43.146.61.38) tcp=ok(12ms)',
+ logPath: '/Users/example/Library/Logs/Cindy/endpoint-netlog/capture.json',
+ offlineSavedAt: null,
+ },
+ 'https://hotfix.cindy.app/cindy/endpoint.json',
+ 'zh-CN',
+ );
+
+ expect(choice).toBe('retry');
+ expect(showMessageBoxSync).toHaveBeenCalledTimes(1);
+ const options = showMessageBoxSync.mock.calls[0]?.[0] as {
+ type: string;
+ message: string;
+ detail: string;
+ buttons: string[];
+ };
+ const visibleText = `${options.message}\n${options.detail}\n${options.buttons.join('\n')}`;
+ expect(options.type).toBe('warning');
+ expect(options.message).toBe('Cindy 暂时无法连接');
+ expect(visibleText).toContain('请确认设备已联网');
+ expect(visibleText).toContain('错误信息:ERR_CONNECTION_RESET');
+ expect(visibleText).toContain('复制诊断信息');
+ expect(visibleText).not.toContain('截图');
+ expect(visibleText).not.toContain('CINDY-NET-');
+ expect(visibleText).not.toContain('43.146.61.38');
+ expect(visibleText).not.toContain('proxy=DIRECT');
+ expect(visibleText).not.toContain('/Users/example');
+ });
+
+ it('复制诊断后保留弹框,不触发重试或退出,并显示已复制反馈', () => {
+ showMessageBoxSync.mockReturnValueOnce(1).mockReturnValueOnce(0);
+
+ const choice = promptRetryDialog(
+ {
+ reason: 'fetch-failed:ERR_CONNECTION_RESET',
+ kind: 'network',
+ diagnosis: 'proxy=DIRECT dns=ok(43.146.61.38) tcp=ok(12ms)',
+ logPath: '/Users/example/Library/Logs/Cindy/endpoint-netlog/capture.json',
+ offlineSavedAt: null,
+ },
+ 'https://hotfix.cindy.app/cindy/endpoint.json',
+ 'zh-CN',
+ );
+
+ expect(choice).toBe('retry');
+ expect(showMessageBoxSync).toHaveBeenCalledTimes(2);
+ expect(clipboardWriteText).toHaveBeenCalledTimes(1);
+ expect(clipboardWriteText.mock.calls[0]?.[0]).toContain('ERR_CONNECTION_RESET');
+ expect(clipboardWriteText.mock.calls[0]?.[0]).toContain('hotfix.cindy.app');
+ expect(clipboardWriteText.mock.calls[0]?.[0]).toContain('proxy=DIRECT');
+ expect(clipboardWriteText.mock.calls[0]?.[0]).toContain('/Users/example');
+ expect(showMessageBoxSync.mock.calls[1]?.[0].detail).toContain('诊断信息已复制');
+ });
+
+ it('复制诊断失败时在弹框内明确提示,不误报为已复制', () => {
+ showMessageBoxSync.mockReturnValueOnce(1).mockReturnValueOnce(0);
+ clipboardWriteText.mockImplementationOnce(() => {
+ throw new Error('clipboard unavailable');
+ });
+
+ const choice = promptRetryDialog(
+ {
+ reason: 'fetch-failed:ERR_CONNECTION_RESET',
+ kind: 'network',
+ diagnosis: 'proxy=DIRECT dns=ok(43.146.61.38) tcp=ok(12ms)',
+ logPath: '/Users/example/Library/Logs/Cindy/endpoint-netlog/capture.json',
+ offlineSavedAt: null,
+ },
+ 'https://hotfix.cindy.app/cindy/endpoint.json',
+ 'zh-CN',
+ );
+
+ expect(choice).toBe('retry');
+ expect(showMessageBoxSync).toHaveBeenCalledTimes(2);
+ expect(showMessageBoxSync.mock.calls[1]?.[0].detail).toContain('诊断信息未能复制');
+ expect(showMessageBoxSync.mock.calls[1]?.[0].detail).not.toContain('诊断信息已复制');
+ });
+});
+
describe('resolveEndpointSource(清单来源三选一)', () => {
const REPO_ROOT = path.join('/repo');
const DEFAULT_FILE = path.join(REPO_ROOT, 'config', 'endpoint.json');
@@ -463,24 +556,27 @@ describe('弹框前的自动重试(mac 首装瞬时失败自愈)', () => {
expect(result).toBeNull();
});
- it.each([407, 408, 425, 429])('非配置错 HTTP %d 仍消耗重试预算(与分类共用同一判定)', async (status) => {
- const fetchManifest = vi.fn<BlockingResolveDeps['fetchManifest']>().mockResolvedValue({
- ok: false,
- detail: `http-${status}`,
- });
- const sleep = vi.fn<(ms: number) => Promise<void>>().mockResolvedValue(undefined);
+ it.each([407, 408, 425, 429])(
+ '非配置错 HTTP %d 仍消耗重试预算(与分类共用同一判定)',
+ async (status) => {
+ const fetchManifest = vi.fn<BlockingResolveDeps['fetchManifest']>().mockResolvedValue({
+ ok: false,
+ detail: `http-${status}`,
+ });
+ const sleep = vi.fn<(ms: number) => Promise<void>>().mockResolvedValue(undefined);
- await resolveClientEndpointsBlocking({
- fetchManifest,
- promptRetry: vi.fn().mockReturnValue('exit'),
- exitApp: vi.fn(),
- autoRetryDelaysMs: [10, 20],
- sleep,
- });
+ await resolveClientEndpointsBlocking({
+ fetchManifest,
+ promptRetry: vi.fn().mockReturnValue('exit'),
+ exitApp: vi.fn(),
+ autoRetryDelaysMs: [10, 20],
+ sleep,
+ });
- expect(fetchManifest).toHaveBeenCalledTimes(3); // 首发 + 2 次自动重试
- expect(sleep).toHaveBeenCalledTimes(2);
- });
+ expect(fetchManifest).toHaveBeenCalledTimes(3); // 首发 + 2 次自动重试
+ expect(sleep).toHaveBeenCalledTimes(2);
+ },
+ );
it('HTTP 502(瞬时服务端错误)仍消耗重试预算', async () => {
const fetchManifest = vi.fn<BlockingResolveDeps['fetchManifest']>().mockResolvedValue({
@@ -753,20 +849,23 @@ describe('用户确认的离线出口', () => {
},
);
- it.each([407, 408, 429])('非配置错 HTTP %d 仍给离线出口(代理没登录/被限流不该连缓存都用不上)', async (status) => {
- const promptRetry = vi.fn().mockReturnValue('offline');
+ it.each([407, 408, 429])(
+ '非配置错 HTTP %d 仍给离线出口(代理没登录/被限流不该连缓存都用不上)',
+ async (status) => {
+ const promptRetry = vi.fn().mockReturnValue('offline');
- const result = await resolveClientEndpointsBlocking({
- fetchManifest: failFetch(`http-${status}`),
- promptRetry,
- exitApp: vi.fn(),
- loadOfflineManifest: offlineCandidate,
- ...NO_AUTO_RETRY,
- });
+ const result = await resolveClientEndpointsBlocking({
+ fetchManifest: failFetch(`http-${status}`),
+ promptRetry,
+ exitApp: vi.fn(),
+ loadOfflineManifest: offlineCandidate,
+ ...NO_AUTO_RETRY,
+ });
- expect(result?.authApiBaseUrl).toBe('https://auth.cached.example.com');
- expect(promptRetry.mock.calls[0][0]).toMatchObject({ kind: 'network' });
- });
+ expect(result?.authApiBaseUrl).toBe('https://auth.cached.example.com');
+ expect(promptRetry.mock.calls[0][0]).toMatchObject({ kind: 'network' });
+ },
+ );
it('HTTP 502(瞬时)仍给离线出口', async () => {
const loadOfflineManifest = vi.fn(offlineCandidate);
@@ -925,7 +1024,7 @@ describe('netlog 抓取(captureNetLogAround)', () => {
const file = await captureNetLogAround(
{ startLogging: () => gate.promise, stopLogging },
- "/tmp/n.json",
+ '/tmp/n.json',
async () => {},
10,
);
@@ -944,11 +1043,11 @@ describe('netlog 抓取(captureNetLogAround)', () => {
});
const file = await captureNetLogAround(
{ startLogging: async () => {}, stopLogging },
- "/tmp/n.json",
+ '/tmp/n.json',
async () => {},
20,
);
- expect(file).toBe("/tmp/n.json");
+ expect(file).toBe('/tmp/n.json');
expect(calls).toBe(2); // NETLOG_STOP_ATTEMPTS
});
@@ -1238,7 +1337,6 @@ describe('getter / IPC', () => {
expect(isUsingCachedClientEndpoints()).toBe(false);
});
-
it('init 之前 getClientEndpoint / getResolvedClientEndpoints 直接抛错(启动时序守卫)', () => {
expect(() => getClientEndpoint('authApiBaseUrl')).toThrow(/not initialized/);
expect(() => getResolvedClientEndpoints()).toThrow(/not initialized/);
diff --git a/apps/desktop/src/main/__tests__/endpointManifestDialogCopy.test.ts b/apps/desktop/src/main/__tests__/endpointManifestDialogCopy.test.ts
index b3b576f0ed..1e64f9201c 100644
--- a/apps/desktop/src/main/__tests__/endpointManifestDialogCopy.test.ts
+++ b/apps/desktop/src/main/__tests__/endpointManifestDialogCopy.test.ts
@@ -11,17 +11,17 @@ import { describe, expect, it } from 'vitest';
import {
ENDPOINT_MANIFEST_DIALOG_COPY,
+ buildEndpointManifestDiagnosticsText,
buildEndpointManifestDialogContent,
+ formatEndpointManifestVisibleError,
type EndpointManifestDialogLocale,
} from '../endpointManifestDialogCopy';
const LOCALES: EndpointManifestDialogLocale[] = ['zh-CN', 'en', 'ja', 'ko'];
-/** CJK 与拉丁字母混排检测用:排除产品名与占位符后还剩英文单词即视为混排。 */
+/** CJK 与拉丁字母混排检测用:排除产品名、已裁决术语与占位符后仍有英文单词即视为混排。 */
function stripAllowedLatin(text: string): string {
- return text
- .replace(/\{\{\w+\}\}/g, ' ')
- .replace(/Cindy/g, ' ');
+ return text.replace(/\{\{\w+\}\}/g, ' ').replace(/Cindy|Proxy/g, ' ');
}
describe('端点清单弹框文案', () => {
@@ -36,14 +36,11 @@ describe('端点清单弹框文案', () => {
}
});
- it('带占位的行都保留了自己的占位符', () => {
+ it('动态文案保留自己的占位符', () => {
for (const locale of LOCALES) {
const copy = ENDPOINT_MANIFEST_DIALOG_COPY[locale];
- expect(copy.sourceLine).toContain('{{source}}');
- expect(copy.reasonLine).toContain('{{reason}}');
- expect(copy.diagnosisLine).toContain('{{diagnosis}}');
- expect(copy.logLine).toContain('{{path}}');
expect(copy.offlineHint).toContain('{{savedAt}}');
+ expect(copy.errorLine).toContain('{{error}}');
}
});
@@ -56,31 +53,27 @@ describe('端点清单弹框文案', () => {
}
});
- it('网络失败 + 有缓存:三个按钮,choices 与 buttons 对齐', () => {
+ it('网络失败 + 有缓存:复制诊断与离线出口都出现,choices 与 buttons 对齐', () => {
const content = buildEndpointManifestDialogContent({
locale: 'zh-CN',
kind: 'network',
- reason: 'fetch-failed:ERR_FAILED',
- source: 'https://cdn.example.com/endpoint.json',
- diagnosis: 'proxy=DIRECT dns=ok(1.2.3.4) tcp=ok(12ms)',
- logPath: '/tmp/logs',
+ reason: 'fetch-failed:ERR_CONNECTION_RESET',
offlineSavedAt: '2026/7/29 06:22',
});
const copy = ENDPOINT_MANIFEST_DIALOG_COPY['zh-CN'];
expect(content.buttons).toEqual([
copy.retryButton,
+ copy.copyDiagnosticsButton,
copy.offlineButton,
copy.quitButton,
]);
- expect(content.choices).toEqual(['retry', 'offline', 'exit']);
+ expect(content.choices).toEqual(['retry', 'copy-diagnostics', 'offline', 'exit']);
expect(content.buttons).toHaveLength(content.choices.length);
expect(content.defaultId).toBe(0);
- expect(content.cancelId).toBe(2);
- expect(content.message).toBe(copy.title);
- expect(content.detail).toContain('fetch-failed:ERR_FAILED');
- expect(content.detail).toContain('https://cdn.example.com/endpoint.json');
- expect(content.detail).toContain('proxy=DIRECT');
- expect(content.detail).toContain('/tmp/logs');
+ expect(content.cancelId).toBe(3);
+ expect(content.message).toBe(copy.networkTitle);
+ expect(content.detail).toContain(copy.networkBody);
+ expect(content.detail).toContain('ERR_CONNECTION_RESET');
expect(content.detail).toContain('2026/7/29 06:22');
});
@@ -88,11 +81,11 @@ describe('端点清单弹框文案', () => {
const content = buildEndpointManifestDialogContent({
locale: 'en',
kind: 'network',
- reason: 'fetch-failed:ERR_FAILED',
- source: 'https://cdn.example.com/endpoint.json',
+ reason: 'fetch-failed:ERR_CONNECTION_RESET',
offlineSavedAt: null,
});
- expect(content.choices).toEqual(['retry', 'exit']);
+ expect(content.choices).toEqual(['retry', 'copy-diagnostics', 'exit']);
+ expect(content.detail).toContain(ENDPOINT_MANIFEST_DIALOG_COPY.en.noSavedConfigurationHint);
expect(content.detail).not.toContain(
ENDPOINT_MANIFEST_DIALOG_COPY.en.offlineHint.split('{{')[0],
);
@@ -103,25 +96,64 @@ describe('端点清单弹框文案', () => {
locale: 'zh-CN',
kind: 'config',
reason: 'invalid-json',
- source: 'https://cdn.example.com/endpoint.json',
offlineSavedAt: '2026/7/29 06:22',
});
- expect(content.choices).toEqual(['retry', 'exit']);
+ expect(content.choices).toEqual(['retry', 'copy-diagnostics', 'exit']);
+ expect(content.message).toBe(ENDPOINT_MANIFEST_DIALOG_COPY['zh-CN'].configTitle);
expect(content.detail).toContain(ENDPOINT_MANIFEST_DIALOG_COPY['zh-CN'].configBody);
expect(content.detail).not.toContain('2026/7/29 06:22');
});
- it('诊断与日志缺失时不留空行占位', () => {
+ it('可见文案展示简短错误信息,不暴露来源、诊断或本机路径', () => {
const content = buildEndpointManifestDialogContent({
locale: 'zh-CN',
kind: 'network',
- reason: 'fetch-failed',
+ reason: 'fetch-failed:ERR_CONNECTION_RESET',
source: 'https://cdn.example.com/endpoint.json',
- diagnosis: null,
- logPath: null,
+ diagnosis: 'proxy=DIRECT dns=ok(1.2.3.4)',
+ logPath: '/Users/example/Library/Logs/Cindy/capture.json',
offlineSavedAt: null,
});
expect(content.detail).not.toContain('{{');
- expect(content.detail.split('\n').filter((line) => line === '')).toHaveLength(1);
+ expect(content.detail).toContain(ENDPOINT_MANIFEST_DIALOG_COPY['zh-CN'].networkBody);
+ expect(content.detail).toContain('错误信息:ERR_CONNECTION_RESET');
+ expect(content.detail).not.toContain('fetch-failed:');
+ expect(content.detail).not.toContain('cdn.example.com');
+ expect(content.detail).not.toContain('proxy=DIRECT');
+ expect(content.detail).not.toContain('/Users/example');
+ expect(content.diagnosticsText).toContain('ERR_CONNECTION_RESET');
+ expect(content.diagnosticsText).toContain('cdn.example.com');
+ expect(content.diagnosticsText).toContain('proxy=DIRECT');
+ expect(content.diagnosticsText).toContain('/Users/example');
+ });
+
+ it('可见错误去掉 fetch-failed 包装,配置错误保持原值', () => {
+ expect(formatEndpointManifestVisibleError('fetch-failed:ERR_CONNECTION_RESET')).toBe(
+ 'ERR_CONNECTION_RESET',
+ );
+ expect(formatEndpointManifestVisibleError('invalid-json')).toBe('invalid-json');
+ });
+
+ it('诊断文本缺失可选字段时使用 n/a,不留 undefined', () => {
+ const text = buildEndpointManifestDiagnosticsText({
+ kind: 'config',
+ reason: 'invalid-json',
+ });
+ expect(text).not.toContain('undefined');
+ expect(text).toContain('reason=invalid-json');
+ expect(text).toContain('source=n/a');
+ });
+
+ it('复制失败时展示可见失败反馈,不误报为已复制', () => {
+ const content = buildEndpointManifestDialogContent({
+ locale: 'zh-CN',
+ kind: 'network',
+ reason: 'fetch-failed:ERR_CONNECTION_RESET',
+ copyStatus: 'failed',
+ offlineSavedAt: null,
+ });
+
+ expect(content.detail).toContain(ENDPOINT_MANIFEST_DIALOG_COPY['zh-CN'].copyFailedHint);
+ expect(content.detail).not.toContain(ENDPOINT_MANIFEST_DIALOG_COPY['zh-CN'].copiedHint);
});
});
diff --git a/apps/desktop/src/main/clientEndpointsService.ts b/apps/desktop/src/main/clientEndpointsService.ts
index 5161fe003d..dad75d44ed 100644
--- a/apps/desktop/src/main/clientEndpointsService.ts
+++ b/apps/desktop/src/main/clientEndpointsService.ts
@@ -23,7 +23,8 @@
*
* 传输层失败在弹框前还会跑一轮分阶段诊断(endpointFetchDiagnostics:代理决策 /
* DNS / TCP,每段各有硬 deadline——这段跑在阻断路径上,探针挂住等于启动卡死)
- * 并抓一份 netlog,摘要同时进日志和弹框。原因是 Electron `net.request`
+ * 并抓一份 netlog,摘要与产物路径只进日志,不直接展示给普通用户;用户主动点击「复制
+ * 诊断信息」时才将它们交给剪贴板。原因是 Electron `net.request`
* 把 DNS、代理、TLS、被本机网络过滤扩展拦下全折叠成通用的 `ERR_FAILED`,
* 只报一个错误码等于没有现场(2026-07 实测:同一 URL curl 与裸 Electron 都是 200,
* 安装版毫秒级 ERR_FAILED,单看错误码无从下手)。
@@ -48,7 +49,7 @@
import fs from 'node:fs';
import path from 'node:path';
-import { app, dialog, ipcMain, net, netLog } from 'electron';
+import { app, clipboard, dialog, ipcMain, net, netLog } from 'electron';
import {
resolveClientEndpointsStrict,
@@ -75,15 +76,14 @@ import {
} from './endpointManifestCache';
import {
buildEndpointManifestDialogContent,
+ type EndpointManifestDialogCopyStatus,
+ type EndpointManifestDialogAction,
type EndpointManifestDialogChoice,
type EndpointManifestDialogLocale,
type EndpointManifestFailureKind,
} from './endpointManifestDialogCopy';
import { createLogger, getLogDir } from './logger';
-import {
- ENDPOINT_MANIFEST_BASE_URL,
- ENDPOINT_MANIFEST_PEER_BASE_URL,
-} from '../shared/endpoints';
+import { ENDPOINT_MANIFEST_BASE_URL, ENDPOINT_MANIFEST_PEER_BASE_URL } from '../shared/endpoints';
import { resolvePreferredSystemLocale } from '../shared/locale';
const log = createLogger('clientEndpoints');
@@ -91,8 +91,7 @@ const log = createLogger('clientEndpoints');
const MANIFEST_FILE_NAME = 'endpoint.json';
const BUILD_VARIANT = import.meta.env.VITE_CINDY_AUTH_REGION;
/** 与 authManager 的构建区域判定保持一致;dev 使用 CN auth 身份。 */
-const BUILD_AUTH_REGION: ClientEndpointRegion =
- BUILD_VARIANT === 'global' ? 'global' : 'cn';
+const BUILD_AUTH_REGION: ClientEndpointRegion = BUILD_VARIANT === 'global' ? 'global' : 'cn';
const DEFAULT_REALM_MANIFEST_BASE_URLS: RealmManifestBaseUrls =
BUILD_AUTH_REGION === 'global'
? {
@@ -263,17 +262,11 @@ function fetchTextViaNet(url: string, timeoutMs: number): Promise<ManifestFetchR
});
response.on('end', () => finish({ ok: true, text: body }, timeout));
response.on('error', (err) =>
- finish(
- { ok: false, detail: describeFetchError(err), raw: rawFetchError(err) },
- timeout,
- ),
+ finish({ ok: false, detail: describeFetchError(err), raw: rawFetchError(err) }, timeout),
);
});
request.on('error', (err) =>
- finish(
- { ok: false, detail: describeFetchError(err), raw: rawFetchError(err) },
- timeout,
- ),
+ finish({ ok: false, detail: describeFetchError(err), raw: rawFetchError(err) }, timeout),
);
request.end();
} catch (err) {
@@ -372,7 +365,7 @@ export interface OfflineManifestCandidate {
/** 阻断循环的依赖注入面(规则 14:测试用内存 harness 驱动,不起 Electron)。 */
export interface BlockingResolveDeps {
fetchManifest(timeoutMs: number): Promise<ManifestFetchResult>;
- /** 拉取/校验失败时问用户;生产实现是系统模态错误框。 */
+ /** 拉取/校验失败时问用户;生产实现是系统模态提示框。 */
promptRetry(context: ManifestPromptContext): EndpointManifestDialogChoice;
exitApp(): void;
timeoutMs?: number;
@@ -521,10 +514,11 @@ export async function resolveClientEndpointsBlocking(
}
log.warn(
- 'client endpoints manifest unavailable (%s, kind=%s, diagnosis=%s, offline=%s), prompting user',
+ 'client endpoints manifest unavailable (%s, kind=%s, diagnosis=%s, logPath=%s, offline=%s), prompting user',
reason,
kind,
diagnosis ?? 'n/a',
+ logPath ?? 'n/a',
offline ? 'available' : 'none',
);
const choice = deps.promptRetry({
@@ -550,33 +544,55 @@ export async function resolveClientEndpointsBlocking(
}
}
-/** 弹框宿主实现:按系统语言取四语文案(不再中英混排),返回用户选择的语义。 */
-function promptRetryDialog(
+/**
+ * 弹框宿主实现:按系统语言取四语文案(不再中英混排),返回用户选择的语义。
+ *
+ * context 里的简短错误信息直接展示;完整来源、诊断结果和日志路径只在用户主动
+ * 点击复制时交给剪贴板,避免把普通提示变成一屏技术现场。
+ */
+export function promptRetryDialog(
context: ManifestPromptContext,
sourceLabel: string,
locale: EndpointManifestDialogLocale,
): EndpointManifestDialogChoice {
- const content = buildEndpointManifestDialogContent({
- locale,
- kind: context.kind,
- reason: context.reason,
- source: sourceLabel,
- diagnosis: context.diagnosis,
- logPath: context.logPath,
- offlineSavedAt: context.offlineSavedAt,
- });
- // createWindow 之前无父窗口,showMessageBoxSync 直接系统模态。
- const clicked = dialog.showMessageBoxSync({
- type: 'error',
- title: 'Cindy',
- message: content.message,
- detail: content.detail,
- buttons: content.buttons,
- defaultId: content.defaultId,
- cancelId: content.cancelId,
- noLink: true,
- });
- return content.choices[clicked] ?? 'exit';
+ let copyStatus: EndpointManifestDialogCopyStatus = 'idle';
+ for (;;) {
+ const content = buildEndpointManifestDialogContent({
+ locale,
+ kind: context.kind,
+ reason: context.reason,
+ source: sourceLabel,
+ diagnosis: context.diagnosis,
+ logPath: context.logPath,
+ copyStatus,
+ offlineSavedAt: context.offlineSavedAt,
+ });
+ // createWindow 之前无父窗口,showMessageBoxSync 直接系统模态。
+ const clicked = dialog.showMessageBoxSync({
+ type: 'warning',
+ title: 'Cindy',
+ message: content.message,
+ detail: content.detail,
+ buttons: content.buttons,
+ defaultId: content.defaultId,
+ cancelId: content.cancelId,
+ noLink: true,
+ });
+ const action: EndpointManifestDialogAction = content.choices[clicked] ?? 'exit';
+ if (action !== 'copy-diagnostics') return action;
+ try {
+ clipboard.writeText(content.diagnosticsText);
+ copyStatus = 'success';
+ log.info('copied endpoint manifest diagnostics (reason=%s)', context.reason);
+ } catch (err) {
+ copyStatus = 'failed';
+ log.warn(
+ 'failed to copy endpoint manifest diagnostics (reason=%s): %s',
+ context.reason,
+ String(err),
+ );
+ }
+ }
}
// ── 模块状态与启动入口 ──────────────────────────────────────────────────────
@@ -640,18 +656,7 @@ const NETLOG_STOP_ATTEMPTS = 2;
* 定时器 unref,不拖住进程退出;长间隔阶段的成本可以忽略,而"抓包还在录"必须有人收。
*/
const NETLOG_BACKGROUND_STOP_SCHEDULE_MS: readonly number[] = [
- 5_000,
- 5_000,
- 5_000,
- 5_000,
- 5_000,
- 5_000,
- 30_000,
- 30_000,
- 30_000,
- 30_000,
- 30_000,
- 30_000,
+ 5_000, 5_000, 5_000, 5_000, 5_000, 5_000, 30_000, 30_000, 30_000, 30_000, 30_000, 30_000,
];
const NETLOG_BACKGROUND_STOP_LONG_DELAY_MS = 300_000;
@@ -762,7 +767,11 @@ export function verifyEndpointNetLogCapture(capture: PreparedNetLogCapture): boo
try {
const dirStat = fs.lstatSync(path.dirname(capture.file));
if (!dirStat.isDirectory()) return false;
- if (capture.dirIno && dirStat.ino && (dirStat.ino !== capture.dirIno || dirStat.dev !== capture.dirDev)) {
+ if (
+ capture.dirIno &&
+ dirStat.ino &&
+ (dirStat.ino !== capture.dirIno || dirStat.dev !== capture.dirDev)
+ ) {
return false;
}
return fs.lstatSync(capture.file).isFile();
@@ -874,7 +883,9 @@ export async function captureNetLogAround(
}
// 前台两次都没停下:抓包可能还在跑,这比"收尾慢"严重,按 warn 记而不是 debug,
// 并把后续收尾交给后台重试(review 抓到:上一版到这里就彻底没有触发点了)。
- log.warn('netlog capture still running after foreground stop attempts; retrying in background');
+ log.warn(
+ 'netlog capture still running after foreground stop attempts; retrying in background',
+ );
scheduleBackgroundStop();
} finally {
stopping = false;
@@ -1283,8 +1294,7 @@ export function resetClientEndpointsForTest(
resolvedRegion = resolved ? (options?.buildRegion ?? null) : null;
startedFromCachedManifest = false;
crossRealmOrgLoginEnabled = options?.crossRealmOrgLoginEnabled ?? BUILD_VARIANT !== 'dev';
- realmManifestBaseUrls =
- options?.realmManifestBaseUrls ?? DEFAULT_REALM_MANIFEST_BASE_URLS;
+ realmManifestBaseUrls = options?.realmManifestBaseUrls ?? DEFAULT_REALM_MANIFEST_BASE_URLS;
activeSessionRealm = resolvedRegion;
realmEndpointCache.clear();
// 既有 desktop 单测只注入一份逻辑端点,不关心物理区域;让两种构建区域都能
diff --git a/apps/desktop/src/main/endpointManifestDialogCopy.ts b/apps/desktop/src/main/endpointManifestDialogCopy.ts
index c0840f7858..b8449af6cc 100644
--- a/apps/desktop/src/main/endpointManifestDialogCopy.ts
+++ b/apps/desktop/src/main/endpointManifestDialogCopy.ts
@@ -12,7 +12,9 @@
* 也避免测试为了拿文案去 import 整个 Electron 主进程模块。
*
* 组装逻辑(buildEndpointManifestDialogContent)是纯函数:失败分类、按钮集合与
- * detail 排版都不碰 Electron,由 clientEndpointsService 负责真正弹框。
+ * detail 排版都不碰 Electron,由 clientEndpointsService 负责真正弹框。弹框直接展示
+ * 简短错误信息;清单来源、网络探针与本机路径默认只进日志,用户主动点击「复制诊断
+ * 信息」时才组装进剪贴板文本。
*/
import type { SupportedLocale } from '../shared/locale.js';
@@ -32,16 +34,22 @@ export type EndpointManifestFailureKind = 'network' | 'config';
/** 用户在弹框上做出的选择。 */
export type EndpointManifestDialogChoice = 'retry' | 'offline' | 'exit';
+/** 弹框内部动作;复制诊断后仍停留在当前弹框,不会进入阻断循环。 */
+export type EndpointManifestDialogAction = EndpointManifestDialogChoice | 'copy-diagnostics';
+/** 复制诊断的结果,用于在同一个弹框里明确反馈成功或失败。 */
+export type EndpointManifestDialogCopyStatus = 'idle' | 'success' | 'failed';
export interface EndpointManifestDialogCopy {
- title: string;
+ networkTitle: string;
+ configTitle: string;
networkBody: string;
configBody: string;
- /** 以下四条均带 {{}} 占位,由 buildEndpointManifestDialogContent 填充。 */
- sourceLine: string;
- reasonLine: string;
- diagnosisLine: string;
- logLine: string;
+ errorLine: string;
+ diagnosticsHint: string;
+ copyDiagnosticsButton: string;
+ copiedHint: string;
+ copyFailedHint: string;
+ noSavedConfigurationHint: string;
offlineHint: string;
retryButton: string;
offlineButton: string;
@@ -53,66 +61,80 @@ export const ENDPOINT_MANIFEST_DIALOG_COPY: Record<
EndpointManifestDialogCopy
> = {
'zh-CN': {
- title: '无法获取服务器配置',
+ networkTitle: 'Cindy 暂时无法连接',
+ configTitle: 'Cindy 暂时无法启动',
networkBody:
- 'Cindy 启动前需要先获取服务器配置,这次请求没有成功。请检查网络连接后重新获取。',
- configBody:
- '服务器没有返回可用的配置,重新获取不会改变结果。请稍后再试或联系我们。',
- sourceLine: '配置来源:{{source}}',
- reasonLine: '失败原因:{{reason}}',
- diagnosisLine: '网络诊断:{{diagnosis}}',
- logLine: '诊断日志位置:{{path}}',
+ '启动时未能连接到 Cindy 服务。请确认设备已联网,然后重新尝试启动。如果正在使用 Proxy 或公司网络,可以切换网络后再试。',
+ configBody: 'Cindy 暂时无法完成启动。请稍后重新尝试;如果问题持续出现,请联系技术支持。',
+ errorLine: '错误信息:{{error}}',
+ diagnosticsHint: '需要反馈时,可以复制诊断信息后粘贴给我们。',
+ copyDiagnosticsButton: '复制诊断信息',
+ copiedHint: '诊断信息已复制。请粘贴到反馈消息中。',
+ copyFailedHint: '诊断信息未能复制,请重试。',
+ noSavedConfigurationHint: '这台设备没有可用的历史配置,需要恢复连接后才能继续启动。',
offlineHint:
'也可以用上次成功获取的配置离线启动(获取于 {{savedAt}}),需要联网的功能会不可用。',
- retryButton: '重新获取配置',
+ retryButton: '重试启动 Cindy',
offlineButton: '用上次配置启动',
quitButton: '退出 Cindy',
},
en: {
- title: 'Cannot load server configuration',
+ networkTitle: "Cindy Couldn't Connect",
+ configTitle: "Cindy Couldn't Start",
networkBody:
- 'Cindy needs the server configuration before it can start, and this request did not go through. Check your network connection and fetch it again.',
+ "Cindy couldn't connect to its services during startup. Check that this device is online, then try starting again. If you're using a proxy or company network, try switching networks.",
configBody:
- 'The server did not return a usable configuration, so fetching it again will not change the result. Try later or contact us.',
- sourceLine: 'Configuration source: {{source}}',
- reasonLine: 'Failure reason: {{reason}}',
- diagnosisLine: 'Network diagnosis: {{diagnosis}}',
- logLine: 'Diagnostic log location: {{path}}',
+ "Cindy couldn't finish starting right now. Try again later. If the problem continues, contact support.",
+ errorLine: 'Error: {{error}}',
+ diagnosticsHint: 'If you need help, copy the diagnostics into your support message.',
+ copyDiagnosticsButton: 'Copy Diagnostics',
+ copiedHint: 'Diagnostics copied. Paste them into your support message.',
+ copyFailedHint: "Diagnostics couldn't be copied. Try again.",
+ noSavedConfigurationHint:
+ 'This device has no saved configuration yet, so Cindy needs to reconnect before it can start.',
offlineHint:
'You can also start offline with the configuration Cindy last fetched ({{savedAt}}). Features that need a network connection will be unavailable.',
- retryButton: 'Fetch Configuration',
+ retryButton: 'Try Starting Cindy Again',
offlineButton: 'Use Last Configuration',
quitButton: 'Quit Cindy',
},
ja: {
- title: 'サーバー設定を取得できません',
+ networkTitle: 'Cindy に一時的に接続できません',
+ configTitle: 'Cindy を一時的に起動できません',
networkBody:
- 'Cindy の起動にはサーバー設定の取得が必要ですが、今回のリクエストは失敗しました。ネットワーク接続を確認してから再取得してください。',
+ '起動時に Cindy のサービスへ接続できませんでした。デバイスがネットワークに接続されていることを確認して、もう一度起動してください。プロキシや社内ネットワークを使用している場合は、ネットワークを切り替えてお試しください。',
configBody:
- 'サーバーから使用可能な設定を取得できませんでした。再取得しても結果は変わりません。時間をおいて試すか、お問い合わせください。',
- sourceLine: '設定の取得先: {{source}}',
- reasonLine: '失敗の原因: {{reason}}',
- diagnosisLine: 'ネットワーク診断: {{diagnosis}}',
- logLine: '診断ログの場所: {{path}}',
+ 'Cindy の起動を完了できませんでした。時間をおいてもう一度お試しください。問題が続く場合は、サポートにお問い合わせください。',
+ errorLine: 'エラー情報: {{error}}',
+ diagnosticsHint: 'サポートが必要な場合は、診断情報をコピーしてメッセージに貼り付けてください。',
+ copyDiagnosticsButton: '診断情報をコピー',
+ copiedHint: '診断情報をコピーしました。サポートへのメッセージに貼り付けてください。',
+ copyFailedHint: '診断情報をコピーできませんでした。もう一度お試しください。',
+ noSavedConfigurationHint:
+ 'このデバイスには利用できる保存済み設定がないため、接続が回復してから起動を続ける必要があります。',
offlineHint:
'前回取得できた設定でオフライン起動することもできます(取得日時: {{savedAt}})。ネットワークが必要な機能は利用できません。',
- retryButton: '設定を再取得',
+ retryButton: 'Cindy の起動を再試行',
offlineButton: '前回の設定で起動',
quitButton: 'Cindy を終了',
},
ko: {
- title: '서버 설정을 가져올 수 없습니다',
+ networkTitle: 'Cindy에 일시적으로 연결할 수 없습니다',
+ configTitle: 'Cindy를 일시적으로 시작할 수 없습니다',
networkBody:
- 'Cindy를 시작하려면 먼저 서버 설정을 가져와야 하지만 이번 요청이 실패했습니다. 네트워크 연결을 확인한 후 다시 가져오세요.',
+ '시작하는 동안 Cindy 서비스에 연결하지 못했습니다. 기기가 네트워크에 연결되어 있는지 확인한 후 다시 시작해 보세요. 프록시나 회사 네트워크를 사용 중이라면 다른 네트워크로 전환해 보세요.',
configBody:
- '서버에서 사용할 수 있는 설정을 가져오지 못했습니다. 다시 가져와도 결과는 바뀌지 않습니다. 잠시 후 다시 시도하거나 문의해 주세요.',
- sourceLine: '설정 출처: {{source}}',
- reasonLine: '실패 원인: {{reason}}',
- diagnosisLine: '네트워크 진단: {{diagnosis}}',
- logLine: '진단 로그 위치: {{path}}',
+ '지금은 Cindy 시작을 완료할 수 없습니다. 잠시 후 다시 시도해 주세요. 문제가 계속되면 지원팀에 문의해 주세요.',
+ errorLine: '오류 정보: {{error}}',
+ diagnosticsHint: '도움이 필요하면 진단 정보를 복사해 지원 메시지에 붙여 넣어 주세요.',
+ copyDiagnosticsButton: '진단 정보 복사',
+ copiedHint: '진단 정보를 복사했습니다. 지원 메시지에 붙여 넣어 주세요.',
+ copyFailedHint: '진단 정보를 복사하지 못했습니다. 다시 시도해 주세요.',
+ noSavedConfigurationHint:
+ '이 기기에는 사용할 수 있는 저장된 설정이 없어 연결이 복구된 후에 시작할 수 있습니다.',
offlineHint:
'마지막으로 가져온 설정으로 오프라인 시작할 수도 있습니다({{savedAt}} 기준). 네트워크가 필요한 기능은 사용할 수 없습니다.',
- retryButton: '설정 다시 가져오기',
+ retryButton: 'Cindy 시작 다시 시도',
offlineButton: '지난 설정으로 시작',
quitButton: 'Cindy 종료',
},
@@ -121,20 +143,13 @@ export const ENDPOINT_MANIFEST_DIALOG_COPY: Record<
export interface EndpointManifestDialogInput {
locale: EndpointManifestDialogLocale;
kind: EndpointManifestFailureKind;
- /** 错误码级别的短标识(fetch-failed:ERR_FAILED / invalid-json 等)。 */
+ /** 失败原因会以简短形态展示,并完整进入 diagnosticsText。 */
reason: string;
- /**
- * 清单来源:CDN 路径是 URL,dev 的 file 模式是本地文件路径。四语文案因此用中性的
- * 「来源 / source / 取得先 / 출처」,不写「URL / 地址」——否则 file 模式下名不副实。
- */
- source: string;
- /** 网络分阶段诊断摘要;没跑或跑失败时省略。 */
+ source?: string;
diagnosis?: string | null;
- /**
- * 诊断产物位置:netlog 抓成功时是那个文件,失败时回落成日志目录——所以文案用
- * 「诊断日志位置」而不是「诊断日志」,不承诺一定是单个文件。
- */
logPath?: string | null;
+ /** 复制后在同一个弹框中显示成功或失败反馈。 */
+ copyStatus?: EndpointManifestDialogCopyStatus;
/** 上次成功配置的获取时间(已格式化);有值即提供离线启动按钮。 */
offlineSavedAt?: string | null;
}
@@ -147,7 +162,9 @@ export interface EndpointManifestDialogContent {
defaultId: number;
cancelId: number;
/** 按钮下标 → 语义,避免调用方按 index 猜。 */
- choices: EndpointManifestDialogChoice[];
+ choices: EndpointManifestDialogAction[];
+ /** 复制按钮使用的技术文本;永远不放进 message/detail。 */
+ diagnosticsText: string;
}
function fill(template: string, values: Record<string, string>): string {
@@ -156,6 +173,25 @@ function fill(template: string, values: Record<string, string>): string {
);
}
+/** 去掉内部传输包装,直接向用户展示真正有用的错误码或校验原因。 */
+export function formatEndpointManifestVisibleError(reason: string): string {
+ return reason.startsWith('fetch-failed:') ? reason.slice('fetch-failed:'.length) : reason;
+}
+
+/** 供复制按钮使用的完整技术上下文;不参与普通用户可见文案。 */
+export function buildEndpointManifestDiagnosticsText(
+ input: Pick<EndpointManifestDialogInput, 'kind' | 'reason' | 'source' | 'diagnosis' | 'logPath'>,
+): string {
+ return [
+ 'Cindy startup diagnostics',
+ `kind=${input.kind}`,
+ `reason=${input.reason}`,
+ `source=${input.source ?? 'n/a'}`,
+ `diagnosis=${input.diagnosis ?? 'n/a'}`,
+ `logPath=${input.logPath ?? 'n/a'}`,
+ ].join('\n');
+}
+
/**
* 组装弹框内容。离线按钮只在 kind === 'network' 且确实有可用缓存时出现——配置内容
* 非法时给离线出口等于让用户绕过一次真实的配置事故。
@@ -166,24 +202,26 @@ export function buildEndpointManifestDialogContent(
const copy = ENDPOINT_MANIFEST_DIALOG_COPY[input.locale];
const offlineAvailable = input.kind === 'network' && Boolean(input.offlineSavedAt);
- const lines = [
- input.kind === 'network' ? copy.networkBody : copy.configBody,
- '',
- fill(copy.reasonLine, { reason: input.reason }),
- fill(copy.sourceLine, { source: input.source }),
- ];
- if (input.diagnosis) {
- lines.push(fill(copy.diagnosisLine, { diagnosis: input.diagnosis }));
+ const lines = [input.kind === 'network' ? copy.networkBody : copy.configBody];
+ if (input.kind === 'network' && !offlineAvailable) {
+ lines.push('', copy.noSavedConfigurationHint);
}
- if (input.logPath) {
- lines.push(fill(copy.logLine, { path: input.logPath }));
+ lines.push(
+ '',
+ fill(copy.errorLine, { error: formatEndpointManifestVisibleError(input.reason) }),
+ copy.diagnosticsHint,
+ );
+ if (input.copyStatus === 'success') {
+ lines.push('', copy.copiedHint);
+ } else if (input.copyStatus === 'failed') {
+ lines.push('', copy.copyFailedHint);
}
if (offlineAvailable) {
lines.push('', fill(copy.offlineHint, { savedAt: input.offlineSavedAt ?? '' }));
}
- const buttons = [copy.retryButton];
- const choices: EndpointManifestDialogChoice[] = ['retry'];
+ const buttons = [copy.retryButton, copy.copyDiagnosticsButton];
+ const choices: EndpointManifestDialogAction[] = ['retry', 'copy-diagnostics'];
if (offlineAvailable) {
buttons.push(copy.offlineButton);
choices.push('offline');
@@ -192,11 +230,12 @@ export function buildEndpointManifestDialogContent(
choices.push('exit');
return {
- message: copy.title,
+ message: input.kind === 'network' ? copy.networkTitle : copy.configTitle,
detail: lines.join('\n'),
buttons,
defaultId: 0,
cancelId: buttons.length - 1,
choices,
+ diagnosticsText: buildEndpointManifestDiagnosticsText(input),
};
}
diff --git a/prototypes/startup-error-dialog.html b/prototypes/startup-error-dialog.html
new file mode 100644
index 0000000000..8137327f84
--- /dev/null
+++ b/prototypes/startup-error-dialog.html
@@ -0,0 +1,639 @@
+<!doctype html>
+<html lang="zh-CN">
+ <head>
+ <meta charset="UTF-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <title>Cindy 启动提示原型</title>
+ <style>
+ :root {
+ color-scheme: light;
+ --surface: #f8f8f6;
+ --surface-elevated: #ffffff;
+ --surface-chip: #e5e5e5;
+ --surface-hover: #ededeb;
+ --border-default: #d7d7d4;
+ --text-primary: #262626;
+ --text-secondary: #737373;
+ --text-tertiary: #a3a3a3;
+ --text-placeholder: #c4c4c4;
+ --accent-cta-bg: #000000;
+ --accent-cta-fg: #ffffff;
+ --warning-accent: #ea6b17;
+ --overlay-modal: rgba(20, 20, 18, 0.32);
+ --radius-card: 12px;
+ --radius-control: 8px;
+ --radius-pill: 9999px;
+ }
+
+ [data-theme="dark"] {
+ color-scheme: dark;
+ --surface: #1f1f1e;
+ --surface-elevated: #2c2c2a;
+ --surface-chip: #3c3c3a;
+ --surface-hover: #454543;
+ --border-default: #3c3c3a;
+ --text-primary: #d4d4d4;
+ --text-secondary: #a3a3a3;
+ --text-tertiary: #737373;
+ --text-placeholder: #525252;
+ --accent-cta-bg: #ffffff;
+ --accent-cta-fg: #000000;
+ --overlay-modal: rgba(0, 0, 0, 0.56);
+ }
+
+ * {
+ box-sizing: border-box;
+ }
+
+ html,
+ body {
+ min-height: 100%;
+ }
+
+ body {
+ margin: 0;
+ background: var(--surface);
+ color: var(--text-primary);
+ font-family:
+ Inter,
+ system-ui,
+ -apple-system,
+ BlinkMacSystemFont,
+ "Segoe UI",
+ sans-serif;
+ -webkit-font-smoothing: antialiased;
+ }
+
+ button,
+ select {
+ font: inherit;
+ }
+
+ .prototype-shell {
+ min-height: 100vh;
+ padding: 28px;
+ background:
+ linear-gradient(
+ 90deg,
+ transparent 0,
+ transparent calc(50% - 520px),
+ var(--border-default) calc(50% - 520px),
+ transparent calc(50% - 519px),
+ transparent 100%
+ ),
+ var(--surface);
+ }
+
+ .prototype-toolbar {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 16px;
+ max-width: 1080px;
+ margin: 0 auto 26px;
+ }
+
+ .prototype-label {
+ color: var(--text-secondary);
+ font-size: 12px;
+ letter-spacing: 0.08em;
+ text-transform: uppercase;
+ }
+
+ .toolbar-controls {
+ display: flex;
+ gap: 8px;
+ align-items: center;
+ }
+
+ .toolbar-controls select,
+ .theme-toggle {
+ min-height: 34px;
+ padding: 0 12px;
+ border: 1px solid var(--border-default);
+ border-radius: var(--radius-pill);
+ background: var(--surface-elevated);
+ color: var(--text-primary);
+ font-size: 12px;
+ cursor: pointer;
+ }
+
+ .app-stage {
+ position: relative;
+ min-height: calc(100vh - 112px);
+ max-width: 1080px;
+ margin: 0 auto;
+ overflow: hidden;
+ border: 1px solid var(--border-default);
+ border-radius: var(--radius-card);
+ background: var(--surface);
+ }
+
+ .app-chrome {
+ display: grid;
+ grid-template-columns: 190px 1fr;
+ min-height: 580px;
+ }
+
+ .sidebar {
+ border-right: 1px solid var(--border-default);
+ padding: 24px 18px;
+ }
+
+ .brand {
+ display: flex;
+ gap: 9px;
+ align-items: center;
+ margin-bottom: 42px;
+ font-size: 18px;
+ letter-spacing: -0.03em;
+ }
+
+ .brand-mark {
+ display: inline-grid;
+ place-items: center;
+ width: 24px;
+ height: 24px;
+ border-radius: 50%;
+ background: var(--text-primary);
+ color: var(--surface);
+ font-size: 12px;
+ font-weight: 500;
+ }
+
+ .nav-item {
+ height: 34px;
+ margin: 5px 0;
+ padding: 0 11px;
+ border-radius: var(--radius-pill);
+ color: var(--text-secondary);
+ font-size: 13px;
+ line-height: 34px;
+ }
+
+ .nav-item.active {
+ background: var(--surface-chip);
+ color: var(--text-primary);
+ }
+
+ .workspace {
+ position: relative;
+ padding: 32px 40px;
+ }
+
+ .workspace-header {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ padding-bottom: 20px;
+ border-bottom: 1px solid var(--border-default);
+ }
+
+ .workspace-title {
+ font-size: 22px;
+ font-weight: 500;
+ letter-spacing: -0.03em;
+ }
+ .workspace-meta {
+ color: var(--text-tertiary);
+ font-size: 12px;
+ }
+
+ .empty-state {
+ display: grid;
+ place-items: center;
+ min-height: 390px;
+ color: var(--text-secondary);
+ text-align: center;
+ }
+
+ .empty-state p {
+ max-width: 270px;
+ margin: 10px 0 0;
+ font-size: 14px;
+ line-height: 1.55;
+ }
+
+ .empty-orb {
+ width: 58px;
+ height: 58px;
+ border: 1px solid var(--border-default);
+ border-radius: 50%;
+ background: var(--surface-elevated);
+ }
+
+ .modal-scrim {
+ position: absolute;
+ inset: 0;
+ display: grid;
+ place-items: center;
+ padding: 24px;
+ background: var(--overlay-modal);
+ }
+
+ .dialog {
+ width: min(100%, 440px);
+ padding: 24px;
+ border: 1px solid var(--border-default);
+ border-radius: var(--radius-card);
+ background: var(--surface-elevated);
+ }
+
+ .dialog-head {
+ display: flex;
+ gap: 14px;
+ align-items: flex-start;
+ }
+
+ .status-icon {
+ display: grid;
+ flex: 0 0 auto;
+ place-items: center;
+ width: 30px;
+ height: 30px;
+ border: 1px solid
+ color-mix(in srgb, var(--warning-accent) 45%, var(--border-default));
+ border-radius: 50%;
+ color: var(--warning-accent);
+ font-size: 16px;
+ font-weight: 500;
+ }
+
+ .dialog-title {
+ margin: 1px 0 0;
+ font-size: 22px;
+ font-weight: 500;
+ letter-spacing: -0.03em;
+ }
+
+ .dialog-body {
+ margin: 20px 0 0 44px;
+ color: var(--text-secondary);
+ font-size: 14px;
+ line-height: 1.6;
+ }
+
+ .error-panel {
+ margin: 18px 0 0 44px;
+ padding: 12px 14px;
+ border: 1px solid var(--border-default);
+ border-radius: var(--radius-control);
+ background: var(--surface);
+ }
+
+ .error-label {
+ color: var(--text-tertiary);
+ font-size: 11px;
+ line-height: 1.4;
+ }
+
+ .error-value {
+ display: block;
+ margin-top: 4px;
+ color: var(--text-primary);
+ font-family:
+ "JetBrains Mono", ui-monospace, SFMono-Regular, Menlo, Monaco,
+ Consolas, monospace;
+ font-size: 14px;
+ font-weight: 500;
+ letter-spacing: 0.04em;
+ }
+
+ .dialog-note {
+ margin: 12px 0 0 44px;
+ color: var(--text-tertiary);
+ font-size: 12px;
+ line-height: 1.5;
+ }
+
+ .dialog-actions {
+ display: flex;
+ flex-wrap: wrap;
+ justify-content: flex-end;
+ gap: 8px;
+ margin-top: 26px;
+ }
+
+ .button {
+ min-height: 38px;
+ padding: 0 16px;
+ border-radius: var(--radius-pill);
+ cursor: pointer;
+ font-size: 13px;
+ font-weight: 500;
+ transition:
+ background 120ms ease,
+ border-color 120ms ease,
+ transform 120ms ease;
+ }
+
+ .button:active {
+ transform: translateY(1px);
+ }
+ .button:focus-visible,
+ .toolbar-controls select:focus-visible,
+ .theme-toggle:focus-visible {
+ outline: 2px solid #417cdd;
+ outline-offset: 2px;
+ }
+
+ .button-primary {
+ border: 1px solid var(--accent-cta-bg);
+ background: var(--accent-cta-bg);
+ color: var(--accent-cta-fg);
+ }
+ .button-primary:hover {
+ opacity: 0.88;
+ }
+ .button-secondary {
+ border: 1px solid var(--border-default);
+ background: var(--surface-elevated);
+ color: var(--text-primary);
+ }
+ .button-secondary:hover {
+ background: var(--surface-hover);
+ }
+ .button-quiet {
+ border: 1px solid transparent;
+ background: transparent;
+ color: var(--text-secondary);
+ }
+ .button-quiet:hover {
+ background: var(--surface-hover);
+ color: var(--text-primary);
+ }
+
+ .toast {
+ position: absolute;
+ right: 24px;
+ bottom: 24px;
+ max-width: 270px;
+ padding: 10px 13px;
+ border: 1px solid var(--border-default);
+ border-radius: var(--radius-pill);
+ background: var(--surface-elevated);
+ color: var(--text-secondary);
+ font-size: 12px;
+ opacity: 0;
+ transform: translateY(8px);
+ pointer-events: none;
+ transition:
+ opacity 160ms ease,
+ transform 160ms ease;
+ }
+
+ .toast.visible {
+ opacity: 1;
+ transform: translateY(0);
+ }
+
+ @media (max-width: 720px) {
+ .prototype-shell {
+ padding: 16px;
+ }
+ .prototype-toolbar {
+ align-items: flex-start;
+ flex-direction: column;
+ }
+ .app-chrome {
+ display: block;
+ }
+ .sidebar {
+ display: none;
+ }
+ .workspace {
+ min-height: 620px;
+ padding: 22px;
+ }
+ .dialog {
+ padding: 20px;
+ }
+ .dialog-body,
+ .dialog-note,
+ .error-panel {
+ margin-left: 0;
+ }
+ .dialog-actions {
+ justify-content: stretch;
+ }
+ .button {
+ flex: 1 1 100%;
+ }
+ }
+ </style>
+ </head>
+ <body data-theme="light">
+ <main class="prototype-shell">
+ <div class="prototype-toolbar">
+ <div>
+ <div class="prototype-label">Cindy · Startup prompt prototype</div>
+ </div>
+ <div class="toolbar-controls" aria-label="原型控制">
+ <select id="failure-kind" aria-label="失败类型">
+ <option value="network">网络连接失败</option>
+ <option value="config">配置暂不可用</option>
+ </select>
+ <select id="cache-state" aria-label="历史配置状态">
+ <option value="empty">新设备 · 无历史配置</option>
+ <option value="available">已有历史配置</option>
+ </select>
+ <button id="theme-toggle" class="theme-toggle" type="button">
+ 切换 Dark
+ </button>
+ </div>
+ </div>
+
+ <section class="app-stage" aria-label="Cindy 启动失败界面预览">
+ <div class="app-chrome" aria-hidden="true">
+ <aside class="sidebar">
+ <div class="brand">
+ <span class="brand-mark">C</span><span>Cindy</span>
+ </div>
+ <div class="nav-item active">新任务</div>
+ <div class="nav-item">最近任务</div>
+ <div class="nav-item">设置</div>
+ </aside>
+ <div class="workspace">
+ <div class="workspace-header">
+ <div class="workspace-title">准备开始</div>
+ <div class="workspace-meta">启动准备中</div>
+ </div>
+ <div class="empty-state">
+ <div>
+ <div class="empty-orb"></div>
+ <p>Cindy 正在准备工作区。启动后,你可以在这里开始新的任务。</p>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <div class="modal-scrim">
+ <section
+ class="dialog"
+ role="dialog"
+ aria-modal="true"
+ aria-labelledby="dialog-title"
+ aria-describedby="dialog-body"
+ >
+ <div class="dialog-head">
+ <div class="status-icon" aria-hidden="true">!</div>
+ <h1 id="dialog-title" class="dialog-title">Cindy 暂时无法连接</h1>
+ </div>
+ <p id="dialog-body" class="dialog-body">
+ 启动时未能连接到 Cindy
+ 服务。请确认设备已联网,然后重新尝试启动。如果正在使用 Proxy
+ 或公司网络,可以切换网络后再试。
+ </p>
+ <div class="error-panel" aria-label="错误信息">
+ <div class="error-label">错误信息</div>
+ <code id="error-value" class="error-value"
+ >ERR_CONNECTION_RESET</code
+ >
+ </div>
+ <p class="dialog-note">
+ 这台设备没有可用的历史配置,需要恢复连接后才能继续启动。需要反馈时,可以复制诊断信息后直接粘贴给我们。
+ </p>
+ <div class="dialog-actions">
+ <button
+ class="button button-primary"
+ data-action="retry"
+ type="button"
+ >
+ 重试启动 Cindy
+ </button>
+ <button
+ class="button button-secondary"
+ data-action="copy"
+ type="button"
+ >
+ 复制诊断信息
+ </button>
+ <button
+ class="button button-secondary"
+ data-action="offline"
+ type="button"
+ hidden
+ >
+ 用上次配置启动
+ </button>
+ <button
+ class="button button-quiet"
+ data-action="exit"
+ type="button"
+ >
+ 退出 Cindy
+ </button>
+ </div>
+ </section>
+ </div>
+
+ <div id="toast" class="toast" role="status" aria-live="polite"></div>
+ </section>
+ </main>
+
+ <script>
+ const copy = {
+ network: {
+ title: "Cindy 暂时无法连接",
+ body: "启动时未能连接到 Cindy 服务。请确认设备已联网,然后重新尝试启动。如果正在使用 Proxy 或公司网络,可以切换网络后再试。",
+ reason: "fetch-failed:ERR_CONNECTION_RESET",
+ },
+ config: {
+ title: "Cindy 暂时无法启动",
+ body: "Cindy 暂时无法完成启动。请稍后重新尝试;如果问题持续出现,请联系技术支持。",
+ reason: "invalid-json",
+ },
+ };
+
+ const body = document.body;
+ const kindSelect = document.querySelector("#failure-kind");
+ const cacheSelect = document.querySelector("#cache-state");
+ const themeToggle = document.querySelector("#theme-toggle");
+ const title = document.querySelector("#dialog-title");
+ const dialogBody = document.querySelector("#dialog-body");
+ const errorValue = document.querySelector("#error-value");
+ const note = document.querySelector(".dialog-note");
+ const offlineButton = document.querySelector('[data-action="offline"]');
+ const toast = document.querySelector("#toast");
+
+ function showToast(message) {
+ toast.textContent = message;
+ toast.classList.add("visible");
+ window.clearTimeout(showToast.timer);
+ showToast.timer = window.setTimeout(
+ () => toast.classList.remove("visible"),
+ 2200,
+ );
+ }
+
+ function renderFailure(kind) {
+ const current = copy[kind];
+ const hasCachedConfiguration = cacheSelect.value === "available";
+ title.textContent = current.title;
+ dialogBody.textContent = current.body;
+ errorValue.textContent = current.reason.replace("fetch-failed:", "");
+ note.textContent =
+ kind === "network" && !hasCachedConfiguration
+ ? "这台设备没有可用的历史配置,需要恢复连接后才能继续启动。需要反馈时,可以复制诊断信息后直接粘贴给我们。"
+ : "需要反馈时,可以复制诊断信息后直接粘贴给我们。";
+ offlineButton.hidden = kind !== "network" || !hasCachedConfiguration;
+ }
+
+ function buildDiagnostics(kind) {
+ const current = copy[kind];
+ return [
+ "Cindy startup diagnostics",
+ `kind=${kind}`,
+ `reason=${current.reason}`,
+ "source=https://hotfix.cindy.app/cindy/endpoint.json",
+ kind === "network"
+ ? "diagnosis=proxy=DIRECT dns=ok tcp=ok tls=connection-reset"
+ : "diagnosis=n/a",
+ "logPath=/Users/example/Library/Logs/Cindy/endpoint-netlog/capture.json",
+ `savedConfiguration=${cacheSelect.value === "available" ? "available" : "none"}`,
+ ].join("\n");
+ }
+
+ async function copyDiagnostics() {
+ const diagnostics = buildDiagnostics(kindSelect.value);
+ try {
+ await navigator.clipboard.writeText(diagnostics);
+ } catch {
+ const textarea = document.createElement("textarea");
+ textarea.value = diagnostics;
+ textarea.style.position = "fixed";
+ textarea.style.opacity = "0";
+ document.body.appendChild(textarea);
+ textarea.select();
+ document.execCommand("copy");
+ textarea.remove();
+ }
+ showToast("诊断信息已复制,可以直接粘贴到反馈消息中");
+ }
+
+ kindSelect.addEventListener("change", (event) => {
+ renderFailure(event.target.value);
+ });
+
+ cacheSelect.addEventListener("change", () => {
+ renderFailure(kindSelect.value);
+ });
+
+ themeToggle.addEventListener("click", () => {
+ const isDark = body.dataset.theme === "dark";
+ body.dataset.theme = isDark ? "light" : "dark";
+ themeToggle.textContent = isDark ? "切换 Dark" : "切换 Light";
+ });
+
+ document.querySelectorAll("[data-action]").forEach((button) => {
+ button.addEventListener("click", () => {
+ const action = button.dataset.action;
+ if (action === "retry") showToast("正在重新尝试启动…");
+ if (action === "copy") void copyDiagnostics();
+ if (action === "offline") showToast("将使用上次配置启动");
+ if (action === "exit") showToast("原型中不会真正退出应用");
+ });
+ });
+ </script>
+ </body>
+</html>