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(relay): streamline route settings and recover deployments

MagicLizie80980a02c68
diff --git a/apps/desktop/scripts/fixtures/relay-service/fixture.tsx b/apps/desktop/scripts/fixtures/relay-service/fixture.tsx
new file mode 100644
index 0000000000..76f8949298
--- /dev/null
+++ b/apps/desktop/scripts/fixtures/relay-service/fixture.tsx
@@ -0,0 +1,62 @@
+import { RelayServicePanel, useSelfHostedRelayState } from '../../../src/renderer/components/settings/RelayServicePanel';
+import type { SelfHostedRelayState } from '../../../src/shared/selfHostedRelay';
+import { forbid, mountPage, subscription } from '../../ui-page/harness';
+
+const deployment = {
+ sshHostId: 'demo-server', address: '203.0.113.10', baseUrl: 'https://203.0.113.10', name: 'Test',
+ relayVersion: '0.3.1', deployedAt: '2026-10-29T00:00:00Z', active: false, upgradeAvailable: false,
+};
+
+/** default:官方在用、服务器中转已部署未使用;server:正在用服务器中转;host:这台电脑当中转在用。 */
+function initialState(name: string): SelfHostedRelayState {
+ const server = name === 'server';
+ const host = name === 'host';
+ return {
+ available: true,
+ mode: server || host ? 'self-hosted' : 'official',
+ relay: server
+ ? { name: 'Test', baseUrl: deployment.baseUrl, role: 'owner', origin: 'server' }
+ : host
+ ? { name: 'This computer', baseUrl: 'http://127.0.0.1:47820', role: 'owner', origin: 'host' }
+ : null,
+ issue: null,
+ host: {
+ enabled: host, running: host, error: null, port: 47820, listenAll: host, externalUrl: null,
+ suggestedUrls: ['http://192.168.1.20:47820'],
+ },
+ deployment: { ...deployment, active: server },
+ deployJob: null,
+ bundledRelayVersion: '0.3.1',
+ joinLink: null,
+ pendingRequests: [],
+ join: { status: 'idle' },
+ };
+}
+
+function Page() {
+ const controller = useSelfHostedRelayState(true);
+ return <div className="mx-auto max-w-3xl p-4"><RelayServicePanel controller={controller} /></div>;
+}
+
+void mountPage({
+ host: ctx => {
+ const state = initialState(ctx.case);
+ return {
+ selfHostedRelay: {
+ command: async (command: { type: string }) => {
+ if (command.type === 'state') return { state };
+ if (command.type === 'deployment-status') {
+ const certificateExpiresAt = new Date(Date.now() + 5.5 * 86_400_000).toISOString();
+ return { state, deploymentStatus: { online: true, devices: 3, onlineDevices: 2, certificateExpiresAt } };
+ }
+ return forbid(`selfHostedRelay.command:${command.type}`)();
+ },
+ onChanged: subscription('relayChanged'),
+ },
+ remoteSsh: {
+ list: async () => ({ hosts: [{ config: { id: 'demo-server', displayName: 'demo-server', hostname: '203.0.113.10', user: 'root' } }] }),
+ },
+ };
+ },
+ render: () => <Page />,
+});
diff --git a/apps/desktop/scripts/fixtures/relay-service/ui-page.mjs b/apps/desktop/scripts/fixtures/relay-service/ui-page.mjs
new file mode 100644
index 0000000000..c1131bb069
--- /dev/null
+++ b/apps/desktop/scripts/fixtures/relay-service/ui-page.mjs
@@ -0,0 +1,59 @@
+import assert from 'node:assert/strict';
+
+export default {
+ name: 'relay-service',
+ entry: './fixture.tsx',
+ viewport: { width: 760, height: 720 },
+ real: 'RelayServicePanel and useSelfHostedRelayState: route list, icon-only switch/remove actions, server details, join and host dialogs',
+ notCovered: 'Real SSH, deployment, certificate issuance, joining and switching; covered separately by deployment/runtime unit tests',
+ cases: {
+ default: { about: 'Official relay in use; a deployed server relay is available to switch to' },
+ server: { about: 'Server relay in use: details with devices, certificate and version', viewport: { width: 360, height: 900 } },
+ host: { about: 'This computer is the relay: settings icon and its add-device area' },
+ },
+ async check(page, ui) {
+ const route = 'settings.remoteControl.relay.route';
+ const relay = 'settings.remoteControl.relay';
+ const removeLabel = await ui.t(`${relay}.manage.remove`);
+ const serverRow = page.getByRole('listitem').filter({ hasText: 'Test' });
+ const serverButtons = serverRow.getByRole('button');
+ if (ui.case === 'default') {
+ // 切换在前、删除在后,都只有图标。
+ const switchLabel = await ui.t(`${route}.useNamed`, { name: 'Test' });
+ assert.equal(await serverButtons.count(), 2);
+ assert.equal(await serverButtons.nth(0).getAttribute('aria-label'), switchLabel);
+ assert.equal(await serverButtons.nth(1).getAttribute('aria-label'), removeLabel);
+ assert.equal((await serverButtons.nth(0).innerText()).trim(), '');
+ // 右侧只放图标、贴右对齐:只有一个图标的行它就在最右边;正在使用的绿点在线路名旁边,
+ // 不挤进图标列(用户 2026-10-29 反馈没对齐、单个切换图标要靠右)。
+ const hostTitle = await ui.t(`${route}.hostTitle`);
+ const hostSwitch = page
+ .getByRole('listitem')
+ .filter({ hasText: hostTitle })
+ .getByRole('button', { name: await ui.t(`${route}.useNamed`, { name: hostTitle }), exact: true });
+ const inUse = page.getByRole('listitem').first().getByRole('img', { name: await ui.t(`${relay}.server.inUse`), exact: true });
+ const [serverSwitchBox, removeBox, hostSwitchBox, inUseBox] = await Promise.all(
+ [serverButtons.nth(0), serverButtons.nth(1), hostSwitch, inUse].map((locator) => locator.boundingBox()),
+ );
+ assert.equal(hostSwitchBox.x + hostSwitchBox.width, removeBox.x + removeBox.width);
+ assert.ok(removeBox.x >= serverSwitchBox.x + serverSwitchBox.width);
+ assert.ok(inUseBox.x + inUseBox.width < serverSwitchBox.x);
+ // 加入别的中转用窗口,不在列表下面展开。
+ await page.getByRole('button', { name: await ui.t(`${relay}.actions.join`), exact: true }).click();
+ const dialog = page.getByRole('dialog', { name: await ui.t(`${relay}.join.title`) });
+ await dialog.waitFor();
+ await ui.capture('join-dialog');
+ await dialog.getByRole('button', { name: await ui.t(`${relay}.join.cancel`), exact: true }).click();
+ await dialog.waitFor({ state: 'detached' });
+ } else if (ui.case === 'server') {
+ assert.ok(await serverRow.getByText(await ui.t(`${relay}.manage.deviceCount`, { count: 3 }), { exact: true }).isVisible());
+ assert.equal(await serverRow.getByRole('button', { name: removeLabel, exact: true }).count(), 1);
+ } else {
+ const settings = page.getByRole('button', { name: await ui.t(`${relay}.actions.editHost`), exact: true });
+ await settings.click();
+ const dialog = page.getByRole('dialog', { name: await ui.t(`${route}.hostTitle`) });
+ await dialog.waitFor();
+ await ui.capture('host-dialog');
+ }
+ },
+};
diff --git a/apps/desktop/src/main/device-link/__tests__/selfHostedRelayDeploy.test.ts b/apps/desktop/src/main/device-link/__tests__/selfHostedRelayDeploy.test.ts
index 78577123cb..5925a61588 100644
--- a/apps/desktop/src/main/device-link/__tests__/selfHostedRelayDeploy.test.ts
+++ b/apps/desktop/src/main/device-link/__tests__/selfHostedRelayDeploy.test.ts
@@ -8,11 +8,14 @@
* - 现有覆盖缺口:部署脚本本身已在 systemd 容器 + Pebble 里实测(见方案),但「服务器输出 → 错误码」的判断只在这里。
* - 最小失败输入:每条用例一种服务器状态(ROOT none / BUSY 80 / 别的主人的 STATE / 证书 failed)与一条成功路径。
* - tier:unit。SSH 主机、HTTPS 检查为进程内 fake;轮询等待用 fake timers,不做真实等待。
+ * - 单文件实测:0.82 秒(Windows);新增流式进度用例覆盖命令结束前回报及超时退出。
*/
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
-import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';
+import { pathToFileURL } from 'node:url';
+import { compileFunction, constants as vmConstants } from 'node:vm';
+import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
const appRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-relay-deploy-test-'));
const appPath = path.join(appRoot, 'apps', 'desktop');
@@ -23,9 +26,10 @@ fs.writeFileSync(path.join(bundleDir, 'relay.mjs'), 'export {};\n');
type Exec = { stdout: string; stderr: string; exitCode: number | null };
const mocks = vi.hoisted(() => ({
- responses: {} as Record<string, (command: string) => Exec>,
+ responses: {} as Record<string, (command: string, input?: Buffer) => Exec>,
commands: [] as Array<{ label: string; command: string }>,
ensureReady: vi.fn(async () => undefined),
+ stream: vi.fn(),
}));
vi.mock('electron', () => ({ app: { getAppPath: () => appPath } }));
@@ -36,9 +40,11 @@ vi.mock('../../remote-ssh/index.js', () => ({
ensureRemoteHostReady: mocks.ensureReady,
getRemoteSshPool: () => ({
get: () => ({
+ execStream: mocks.stream,
exec: vi.fn(async (command: string, options: { label: string; input?: Buffer }) => {
mocks.commands.push({ label: options.label, command });
if (options.label === 'relay-deploy-upload') {
+ mocks.responses[options.label]?.(command, options.input);
const { createHash } = await import('node:crypto');
return {
stdout: `SHA ${createHash('sha256').update(options.input!).digest('hex')}\n`,
@@ -53,7 +59,7 @@ vi.mock('../../remote-ssh/index.js', () => ({
}),
}));
-import { deployRelayToServer, uninstallRelayFromServer, RelayDeployError } from '../selfHostedRelayDeploy';
+import { checkRelayServer, deployRelayToServer, uninstallRelayFromServer, RelayDeployError } from '../selfHostedRelayDeploy';
const ok = (stdout: string): Exec => ({ stdout, stderr: '', exitCode: 0 });
const PROBE_SUDO = 'OS Linux\nARCH x86_64\nROOT sudo\nSYSTEMD yes\nIPV6 no\nFETCH yes\n';
@@ -78,6 +84,7 @@ async function run(overrides: Partial<Parameters<typeof deployRelayToServer>[0]>
init,
preferMirror: false,
onStep: (step) => steps.push(step),
+ onProgress: () => {},
...overrides,
});
const settled = promise.then(
@@ -93,6 +100,25 @@ describe('deployRelayToServer', () => {
vi.useFakeTimers({ toFake: ['setTimeout'] });
mocks.commands = [];
mocks.ensureReady.mockReset().mockResolvedValue(undefined);
+ mocks.stream.mockImplementation(async (command: string) => {
+ mocks.commands.push({ label: 'relay-deploy-runtime', command });
+ let stdout: (value: string) => void = () => {};
+ let stderr: (value: string) => void = () => {};
+ let close: (value: { code: number }) => void = () => {};
+ return {
+ onStdout: (cb: typeof stdout) => { stdout = cb; return () => {}; },
+ onStderr: (cb: typeof stderr) => { stderr = cb; return () => {}; },
+ onClose: (cb: typeof close) => { close = cb; return () => {}; },
+ onError: () => () => {},
+ end: () => queueMicrotask(() => {
+ const result = mocks.responses['relay-deploy-runtime']?.(command) ?? ok('');
+ stdout(result.stdout);
+ stderr(result.stderr);
+ close({ code: result.exitCode ?? 0 });
+ }),
+ kill: vi.fn(),
+ };
+ });
mocks.responses = {
'relay-deploy-probe': () => ok(PROBE_SUDO),
'relay-deploy-runtime': () => ok('NODE_READY v24.22.1\n'),
@@ -105,6 +131,8 @@ describe('deployRelayToServer', () => {
);
});
+ afterEach(() => { vi.useRealTimers(); });
+
afterAll(() => {
vi.useRealTimers();
vi.unstubAllGlobals();
@@ -114,13 +142,67 @@ describe('deployRelayToServer', () => {
it('runs every step through sudo -n and checks the relay over https', async () => {
const result = await run();
expect(result.error).toBeNull();
- expect(result.steps).toEqual(['connect', 'check', 'runtime', 'upload', 'configure', 'certificate', 'verify']);
+ expect(result.steps).toEqual(['check', 'runtime', 'upload', 'configure', 'certificate', 'verify']);
const privileged = mocks.commands.filter((c) => c.label !== 'relay-deploy-probe');
expect(privileged.length).toBeGreaterThan(0);
expect(privileged.every((c) => c.command.startsWith('sudo -n bash -c '))).toBe(true);
expect(fetch).toHaveBeenCalledWith('https://203.0.113.10/api/device-link/relay/info', expect.anything());
});
+ // 2026-10-29:下载中界面没有反馈;旧 exec 等待命令结束才拿到输出。
+ // 最小输入:SSH 分片输出一个进度标记后保持运行;unit,回调必须先于下载完成,且不透传原文。
+ it('reports allowlisted download events before the SSH command finishes', async () => {
+ let emit!: (chunk: string) => void;
+ let finish!: (value: { code: number }) => void;
+ mocks.stream.mockImplementationOnce(async () => ({
+ onStdout: (cb: typeof emit) => { emit = cb; return () => {}; },
+ onStderr: () => () => {},
+ onClose: (cb: typeof finish) => { finish = cb; return () => {}; },
+ onError: () => () => {},
+ end: () => {},
+ kill: vi.fn(),
+ }));
+ const progress = vi.fn();
+ const steps = vi.fn();
+ const promise = deployRelayToServer({
+ sshHostId: 'my-vps', address: '203.0.113.10', baseUrl: 'https://203.0.113.10',
+ replaceExisting: false, init, preferMirror: false, onStep: steps, onProgress: progress,
+ });
+ const result = promise.then(value => ({ value, error: null }), error => ({ value: null, error }));
+ await vi.waitFor(() => expect(emit).toBeTypeOf('function'));
+ emit('private server output\nPROG');
+ emit('RESS runtime-download\nPROGRESS unknown-value\n');
+ expect(progress.mock.calls).toEqual([['runtime-download']]);
+ expect(steps).not.toHaveBeenCalledWith('upload');
+ emit('PROGRESS runtime-checksum\nNODE_READY v24.22.1\n');
+ finish({ code: 0 });
+ await vi.runAllTimersAsync();
+ expect((await result).error).toBeNull();
+ expect(progress).toHaveBeenCalledWith('runtime-checksum');
+ });
+
+ // 下载卡住或进度处理抛错时,须结束 channel 并交回失败结果,不能留下下载或让异步事件异常崩溃。
+ it.each(['timeout', 'progress-error'] as const)('ends the download on %s without uploading', async (failure) => {
+ const kill = vi.fn();
+ const opened = vi.fn();
+ let emit: (chunk: string) => void = () => {};
+ mocks.stream.mockImplementationOnce(async () => ({
+ onStdout: (cb: typeof emit) => { emit = cb; return () => {}; }, onStderr: () => () => {},
+ onClose: () => () => {}, onError: () => () => {},
+ end: () => {
+ opened();
+ if (failure === 'progress-error') queueMicrotask(() => emit('PROGRESS runtime-download\n'));
+ },
+ kill,
+ }));
+ const promise = run({ onProgress: () => { throw new Error('progress display failed'); } });
+ const { error } = await promise;
+ expect(opened).toHaveBeenCalledOnce();
+ expect(error).toMatchObject({ code: 'DOWNLOAD_FAILED', detail: failure === 'timeout' ? 'runtime download timed out' : 'progress display failed' });
+ expect(kill).toHaveBeenCalledOnce();
+ expect(mocks.commands.some(c => c.label === 'relay-deploy-upload')).toBe(false);
+ });
+
it.each([
[
'no root or passwordless sudo',
@@ -128,7 +210,31 @@ describe('deployRelayToServer', () => {
'NEEDS_ROOT',
undefined,
],
- ['port 80 used by another program', { 'relay-deploy-inspect': () => ok('BUSY 80 apache2\n') }, 'PORT_BUSY', '80 apache2'],
+ // 2026-10-29 实机:选中 [email protected],原提示为“只支持 64 位 Linux”并附 `? ?`。
+ ['an SSH account without a shell', { 'relay-deploy-probe': () => ok('') }, 'SHELL_UNAVAILABLE', undefined],
+ ['port 80 used by another program', { 'relay-deploy-inspect': () => ok('BUSY 80 apache2\n') }, 'PORT_BUSY', 'apache2'],
+ // 2026-10-29 实机:Nginx 跑在 Docker 容器里,原来只报 docker-proxy 和“已有 Nginx 会自动配置”。
+ [
+ 'ports published by a Docker container',
+ { 'relay-deploy-inspect': () => ok('BUSY 80 docker:fp2-server-nginx-1,\nBUSY 443 docker:fp2-server-nginx-1,\n') },
+ 'PORT_BUSY_CONTAINER',
+ 'fp2-server-nginx-1',
+ ],
+ [
+ 'Node rejecting the uploaded Nginx helper before it can emit JSON',
+ {
+ 'relay-deploy-inspect': () => ok('BUSY 80 nginx\n'),
+ 'relay-deploy-nginx-prepare': () => ({ stdout: '', stderr: 'TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension\n', exitCode: 1 }),
+ },
+ 'NGINX_FAILED',
+ 'ERR_UNKNOWN_FILE_EXTENSION',
+ ],
+ [
+ 'runtime download failing with a server error',
+ { 'relay-deploy-runtime': () => ({ stdout: 'ERROR DOWNLOAD\n', stderr: 'curl: (22) HTTP 404\n', exitCode: 21 }) },
+ 'DOWNLOAD_FAILED',
+ 'curl: (22) HTTP 404',
+ ],
[
'a relay owned by someone else',
{ 'relay-deploy-inspect': () => ok(`STATE 2 ${init.relayId} ${'R'.repeat(43)}\n`) },
@@ -146,12 +252,51 @@ describe('deployRelayToServer', () => {
],
])('stops on %s', async (_label, responses, code, detail) => {
Object.assign(mocks.responses, responses);
- const { error } = await run();
+ const onServerChange = vi.fn();
+ const { error } = await run({ onServerChange });
expect(error).toBeInstanceOf(RelayDeployError);
expect(error).toMatchObject({ code, detail });
// 停下时不会走到写配置、重启服务那一步(证书失败除外:那时服务已经配置好)。
const configured = mocks.commands.some((c) => c.label === 'relay-deploy-configure');
expect(configured).toBe(code === 'CERTIFICATE_FAILED');
+ // 检查阶段停下时还没动服务器:调用方不能保存部署记录(否则界面会出现一个从未装上的中转)。
+ const checkStage = ['SHELL_UNAVAILABLE', 'NEEDS_ROOT', 'PORT_BUSY', 'PORT_BUSY_CONTAINER', 'RELAY_MISMATCH'].includes(code);
+ expect(onServerChange).toHaveBeenCalledTimes(checkStage ? 0 : 1);
+ });
+
+ // 部署表单选服务器时自动检查:只能读,不能安装或改配置;结论决定界面能否点「开始部署」。
+ // 最小输入:系统 Nginx 占着 80,服务器上是本机主人的中转。tier: unit。
+ it('checks a server read-only and reports the plan and existing relay', async () => {
+ mocks.responses['relay-deploy-probe'] = () => ok(`${PROBE_SUDO}DISTRO Debian GNU/Linux 13 (trixie)\n`);
+ mocks.responses['relay-deploy-inspect'] = () => ok(`BUSY 80 nginx\nSTATE 2 ${init.relayId} ${init.ownerPublicKey}\n`);
+ await expect(checkRelayServer('my-vps', init)).resolves.toEqual({
+ system: 'Debian GNU/Linux 13 (trixie) · x86_64',
+ plan: 'nginx',
+ existing: 'mine',
+ });
+ await expect(checkRelayServer('my-vps', null)).resolves.toMatchObject({ existing: 'other' });
+ expect(new Set(mocks.commands.map((c) => c.label))).toEqual(new Set(['relay-deploy-probe', 'relay-deploy-inspect']));
+ });
+
+ // 2026-10-29 实机:中转第一次连 Let's Encrypt 时 `fetch failed`(会自行重试),部署方读到 failed 就回滚。
+ // 最小输入:status 先报 transient 失败再 ready;或一直 transient 到等待超时。tier: unit,假时钟。
+ it('waits while the relay retries an unreachable certificate authority', async () => {
+ // 等待截止时间按 Date 计算:改用同时伪造 Date 的假时钟,超时分支才不会真的等四分钟。
+ vi.useRealTimers();
+ vi.useFakeTimers({ toFake: ['setTimeout', 'Date'] });
+ const unreachable = (at: string) =>
+ ok(`ACTIVE active\nSTATUS {"certificate":{"state":"failed","transient":true,"error":"could not reach the certificate authority (ECONNRESET)","updatedAt":"${at}"}}\n`);
+ let polls = 0;
+ mocks.responses['relay-deploy-status'] = () =>
+ ++polls < 3 ? unreachable('t1') : ok('ACTIVE active\nSTATUS {"certificate":{"state":"ready"}}\n');
+ const progress = vi.fn();
+ const recovered = await run({ onProgress: progress });
+ expect(recovered.error).toBeNull();
+ expect(progress.mock.calls.filter(([message]) => message === 'certificate-retry')).toHaveLength(1);
+
+ mocks.responses['relay-deploy-status'] = () => unreachable(`t${++polls}`);
+ const { error } = await run();
+ expect(error).toMatchObject({ code: 'CA_UNREACHABLE', detail: expect.stringContaining('ECONNRESET') });
});
// 2026-10-29: 用户要求已有 Nginx 时自动部署,而不是让用户停网站或复制配置。
@@ -177,6 +322,33 @@ describe('deployRelayToServer', () => {
expect(mocks.commands.some((c) => c.label === 'relay-deploy-nginx-commit')).toBe(false);
});
+ // 2026-10-29 实机:临时程序 relay.mjs.new 被 Node 拒绝,Nginx prepare 尚未执行就失败。
+ // 旧 SSH fake 从不加载上传文件,未覆盖后缀。unit:使用生产命令实际指定的文件名,
+ // 在现有唯一临时目录写入上传内容,再由本进程的原生 Node ESM loader 加载;无子进程或网络。
+ it('uploads a staged program that the Node ESM loader can run during Nginx preparation', async () => {
+ let invokedPath = '';
+ mocks.responses['relay-deploy-inspect'] = () => ok('BUSY 80 nginx\n');
+ mocks.responses['relay-deploy-upload'] = (command, input) => {
+ const uploadedPath = /cat > (\S+)/.exec(command)![1];
+ fs.writeFileSync(path.join(appRoot, path.posix.basename(uploadedPath)), input!);
+ return ok('');
+ };
+ mocks.responses['relay-deploy-nginx-prepare'] = (command) => {
+ const staged = /if \[ -f (\S+) \]; then BUNDLE=([^;\s]+)/.exec(command)!;
+ const selected = fs.existsSync(path.join(appRoot, path.posix.basename(staged[1])))
+ ? staged[2] : /\bBUNDLE=(\S+)/.exec(command)![1];
+ invokedPath = path.join(appRoot, path.posix.basename(selected));
+ return ok('{"event":"nginx","port":47822,"challengePort":47823,"existingCertificate":false}\n');
+ };
+ const result = await run();
+ expect(result.error).toBeNull();
+ // 绕开 Vitest 的源码转换,保留与服务器 Node 相同的文件扩展名判据。
+ const nativeImport = compileFunction('return import(specifier)', ['specifier'], {
+ importModuleDynamically: vmConstants.USE_MAIN_CONTEXT_DEFAULT_LOADER,
+ }) as (specifier: string) => Promise<unknown>;
+ await expect(nativeImport(pathToFileURL(invokedPath).href)).resolves.toBeDefined();
+ });
+
it('uses the existing trusted HTTPS certificate without waiting for a new certificate', async () => {
mocks.responses['relay-deploy-inspect'] = () => ok('BUSY 80 nginx\nBUSY 443 nginx\n');
mocks.responses['relay-deploy-nginx-prepare'] = () =>
@@ -238,6 +410,15 @@ describe('deployRelayToServer', () => {
expect(mocks.commands.some((c) => c.label === 'relay-deploy-uninstall')).toBe(false);
});
+ // Bug:部署停在检查端口时服务器上还没有设备档案,移除却报“不是这台电脑部署的”,只能本机移除。
+ // 最小输入:INSPECT 没有 STATE;tier: unit,观察移除成功并执行了服务器清理。
+ it('removes an incomplete deployment that never wrote device records', async () => {
+ mocks.responses['relay-deploy-inspect'] = () => ok('');
+ mocks.responses['relay-deploy-uninstall'] = () => ok('UNINSTALLED\n');
+ await expect(uninstallRelayFromServer('my-vps', init, true, () => {})).resolves.toBeUndefined();
+ expect(mocks.commands.some((c) => c.label === 'relay-deploy-uninstall')).toBe(true);
+ });
+
it('uninstalls a matching relay and rejects an identity changed before deletion', async () => {
mocks.responses['relay-deploy-inspect'] = () => ok(`STATE 2 ${init.relayId} ${init.ownerPublicKey}\n`);
await expect(uninstallRelayFromServer('my-vps', init, true, () => {})).resolves.toBeUndefined();
diff --git a/apps/desktop/src/main/device-link/__tests__/selfHostedRelayRuntime.test.ts b/apps/desktop/src/main/device-link/__tests__/selfHostedRelayRuntime.test.ts
index 46eda778a5..472233b132 100644
--- a/apps/desktop/src/main/device-link/__tests__/selfHostedRelayRuntime.test.ts
+++ b/apps/desktop/src/main/device-link/__tests__/selfHostedRelayRuntime.test.ts
@@ -7,11 +7,12 @@
* - 现有覆盖缺口:部署器测试只验证 SSH 步骤,没有经过运行时 IPC 与账号切换,故单独覆盖该模块。
* - 最小失败输入:挂起一次部署或退出请求,换账号,再让原请求完成。
* - tier:unit;SSH、存储和 Electron 为进程内 fake,无网络、磁盘或真实等待。
- * - 单文件实测:1.39 秒(6 例,测试体 22ms,Windows)。
+ * - 单文件实测:1.08 秒(9 例,测试体 41ms,Windows)。
*/
import { afterEach, beforeEach, expect, it, vi } from 'vitest';
import type { RelayConfig } from '../selfHostedRelayConfig';
import type { SelfHostedRelayCommand, SelfHostedRelayCommandResult } from '../../../shared/selfHostedRelay';
+import { RELAY_VERSION } from '../../../../../../packages/device-link-relay/src/version';
const h = vi.hoisted(() => ({
owner: 'account-a',
@@ -62,8 +63,8 @@ vi.mock('@cindy/device-link-relay', () => ({
hashSecret: () => 'fake-hash', initializeRelay: vi.fn(), startRelayServer: h.startServer,
}));
vi.mock('../selfHostedRelayDeploy.js', () => ({
- bundledRelayVersion: () => '0.2.0', deployRelayToServer: h.deploy, uninstallRelayFromServer: h.uninstall,
- RelayDeployError: class extends Error {},
+ bundledRelayVersion: () => RELAY_VERSION, deployRelayToServer: h.deploy, uninstallRelayFromServer: h.uninstall,
+ checkRelayServer: vi.fn(), RelayDeployError: class extends Error {},
}));
vi.mock('../selfHostedRelayConfig.js', () => ({
readRelayConfig: () => structuredClone(h.config.get(h.owner)),
@@ -130,9 +131,104 @@ it('records a completed deployment and activates it for the account that started
expect(h.restart).toHaveBeenCalledOnce();
});
+// 0.3.0 已部署用户必须能从状态投影进入升级,才能获得本次证书重试修复;原版本号未递增时此用例失败。
+// 生产入口为 state IPC;现有部署成功用例不覆盖旧版记录。最小输入:已完成的 0.3.0 部署,tier: unit。
+it('offers the certificate retry update to an existing 0.3.0 relay and clears it after upgrading', async () => {
+ h.deploy.mockResolvedValueOnce({ relayVersion: '0.3.0' });
+ await command(deployCommand);
+ await vi.runAllTimersAsync();
+ expect((await command({ type: 'state' })).state.deployment?.upgradeAvailable).toBe(true);
+ h.deploy.mockResolvedValueOnce({ relayVersion: RELAY_VERSION });
+ await command({ type: 'upgrade-deployment' });
+ await vi.runAllTimersAsync();
+ expect((await command({ type: 'state' })).state.deployment).toMatchObject({
+ relayVersion: RELAY_VERSION, upgradeAvailable: false,
+ });
+});
+
+// 管理卡片的在线、设备数与证书到期来自这条只读查询;服务器回的中转 ID 不是这份部署时
+// 必须按连不上处理,不能把另一个中转的数字显示成自己的。最小输入:同一地址两次回应。tier: unit。
+it('reads the deployed relay status with the owner credential and rejects another relay’s answer', async () => {
+ h.deploy.mockResolvedValue({ relayVersion: '0.2.0' });
+ await command(deployCommand);
+ await vi.runAllTimersAsync();
+ const relayId = h.config.get('account-a')!.deployment!.relayId;
+ const fetchMock = vi.fn(async () => new Response(JSON.stringify({
+ relayId, devices: 3, online: 2, certificateExpiresAt: '2026-11-04T00:00:00.000Z',
+ })));
+ vi.stubGlobal('fetch', fetchMock);
+ const status = await command({ type: 'deployment-status' });
+ expect(status.deploymentStatus).toEqual({ online: true, devices: 3, onlineDevices: 2, certificateExpiresAt: '2026-11-04T00:00:00.000Z' });
+ expect(fetchMock).toHaveBeenCalledWith(
+ 'https://203.0.113.10/api/device-link/relay/admin/status',
+ expect.objectContaining({ headers: { authorization: 'CindyRelay fake-credential' } }),
+ );
+ fetchMock.mockResolvedValueOnce(new Response(JSON.stringify({ relayId: 'another-relay', devices: 9 })));
+ expect((await command({ type: 'deployment-status' })).deploymentStatus).toEqual({ online: false });
+});
+
+// 2026-10-29:部署期间看不出进展;原测试只看终态,未覆盖 SSH 尚未结束时的状态推送。
+// 最小输入:挂起部署,回报一条下载进展再失败;unit,观察运行中日志与失败后保留的耗时。
+it('publishes deployment progress while work is pending and retains it after failure', async () => {
+ const pending = deferred<{ relayVersion: string }>();
+ h.deploy.mockReturnValueOnce(pending.promise);
+ await command(deployCommand);
+ const params = h.deploy.mock.calls[0][0];
+ params.onStep('runtime');
+ params.onProgress('runtime-download');
+ const running = getState().deployJob!;
+ expect(running).toMatchObject({ status: 'running', step: 'runtime', startedAt: expect.any(Number) });
+ expect(running.logs?.at(-1)).toMatchObject({ step: 'runtime', message: 'runtime-download' });
+ await vi.advanceTimersByTimeAsync(5_000);
+ pending.reject(new Error('connection lost'));
+ await vi.runAllTimersAsync();
+ const failed = getState().deployJob!;
+ expect(failed).toMatchObject({ status: 'failed', step: 'runtime', error: 'DEPLOY_FAILED' });
+ expect(failed.finishedAt! - failed.startedAt!).toBe(5_000);
+ expect(failed.logs).toEqual(running.logs);
+});
+
+type DeployParams = { onServerChange?: () => void };
+/** 部署器在检查通过、改动服务器前回调 onServerChange;之后的失败才会留下部署记录。 */
+const failAfterServerChange = async (params: DeployParams) => {
+ params.onServerChange?.();
+ throw new Error('connection lost');
+};
+
+// 2026-10-29 实机:部署停在检查端口,界面却出现「我的服务器中转」卡片,且不能重新选服务器。
+// 原实现在连服务器之前就保存部署记录。最小输入:部署器在 onServerChange 之前失败。tier: unit。
+it('keeps no deployment record when deployment stops before changing the server', async () => {
+ h.deploy.mockRejectedValueOnce(new Error('ports busy'));
+ await command(deployCommand);
+ await vi.runAllTimersAsync();
+ expect(h.config.get('account-a')!.deployment).toBeNull();
+ expect(getState().deployJob).toMatchObject({ status: 'failed', serverChanged: false, target: { sshHostId: 'test-server' } });
+ await command({ type: 'dismiss-deploy-job' });
+ expect(getState().deployJob).toBeNull();
+});
+
+// 没完成的部署换到另一台服务器:原服务器可能装了一半,须先按原身份清理,再部署新服务器。tier: unit。
+it('cleans up an unfinished deployment on the previous server before deploying elsewhere', async () => {
+ h.deploy.mockImplementationOnce(failAfterServerChange);
+ await command(deployCommand);
+ await vi.runAllTimersAsync();
+ const previous = structuredClone(h.config.get('account-a')!.deployment!);
+ h.uninstall.mockResolvedValueOnce(undefined);
+ h.deploy.mockImplementationOnce(async (params: DeployParams) => {
+ expect(h.uninstall).toHaveBeenCalledWith('test-server', expect.objectContaining({ relayId: previous.relayId }), true, expect.any(Function), expect.any(Function));
+ params.onServerChange?.();
+ return { relayVersion: '0.2.0' };
+ });
+ await command({ ...deployCommand, sshHostId: 'other-server' });
+ await vi.runAllTimersAsync();
+ expect(getState().deployJob).toMatchObject({ status: 'done', steps: expect.arrayContaining(['cleanup']) });
+ expect(h.deleteSecrets).toHaveBeenCalledWith(previous.relayId);
+ expect(h.config.get('account-a')!.deployment).toMatchObject({ sshHostId: 'other-server', complete: true });
+});
+
// Bug:重启后进度对象不存在,持久部署记录仍须能继续,并保留已写入服务器的主人身份。tier: unit。
it('resumes an incomplete persisted deployment with the same relay identity', async () => {
- h.deploy.mockRejectedValueOnce(new Error('connection lost'));
+ h.deploy.mockImplementationOnce(failAfterServerChange);
await command(deployCommand);
await vi.runAllTimersAsync();
const previous = structuredClone(h.config.get('account-a')!.deployment!);
@@ -153,6 +249,7 @@ it.each(['resolve', 'reject'] as const)('ignores an old deployment that later %s
h.deploy.mockReturnValueOnce(old.promise).mockReturnValueOnce(next.promise);
await command(deployCommand);
const oldStep = h.deploy.mock.calls[0][0].onStep;
+ const oldProgress = h.deploy.mock.calls[0][0].onProgress;
await switchOwner('account-b');
expect(getState().deployJob).toBeNull();
await command(deployCommand);
@@ -165,6 +262,9 @@ it.each(['resolve', 'reject'] as const)('ignores an old deployment that later %s
expect(h.config.get('account-b')).toEqual(before);
expect(getState().deployJob?.status).toBe('running');
expect(() => oldStep('upload')).toThrow();
+ const currentJob = getState().deployJob;
+ oldProgress('runtime-download');
+ expect(getState().deployJob).toEqual(currentJob);
next.resolve({ relayVersion: '0.2.0' });
await vi.runAllTimersAsync();
expect(getState().deployJob?.status).toBe('done');
diff --git a/apps/desktop/src/main/device-link/selfHostedRelayDeploy.ts b/apps/desktop/src/main/device-link/selfHostedRelayDeploy.ts
index 19823c8b26..0f3096515c 100644
--- a/apps/desktop/src/main/device-link/selfHostedRelayDeploy.ts
+++ b/apps/desktop/src/main/device-link/selfHostedRelayDeploy.ts
@@ -20,7 +20,7 @@ import type { RemoteHost } from '@cindy/maker-remote-ssh';
import { RELAY_VERSION } from '@cindy/device-link-relay';
import { createLogger } from '../logger.js';
import { ensureRemoteHostReady, getRemoteSshPool } from '../remote-ssh/index.js';
-import type { RelayDeployErrorCode, RelayDeployStep } from '../../shared/selfHostedRelay.js';
+import type { RelayDeployErrorCode, RelayDeployProgressMessage, RelayDeployStep } from '../../shared/selfHostedRelay.js';
const log = createLogger('self-hosted-relay:deploy');
@@ -67,8 +67,18 @@ export interface DeployParams {
/** 国内网络:先试镜像再试官方源。 */
preferMirror: boolean;
onStep(step: RelayDeployStep): void;
+ onProgress?(message: RelayDeployProgressMessage): void;
/** 每次继续 SSH 操作前核对发起账号,避免连接等待期间换账号后取到另一份主机配置。 */
assertCurrent?(): void;
+ /** 检查通过、第一次改动服务器之前调用:调用方此时才保存部署记录与主人身份。 */
+ onServerChange?(): void;
+}
+
+/** 只读检查的结论;检查不通过时抛出 RelayDeployError。 */
+export interface RelayServerCheck {
+ system: string;
+ plan: 'direct' | 'nginx';
+ existing: 'none' | 'mine' | 'other';
}
function shellQuote(value: string): string {
@@ -123,17 +133,64 @@ class Remote {
) {}
/** 以 root 运行一段脚本;参数逐个转义,脚本经 `bash -c` 传入,stdin 留给上传。 */
- async root(script: string, args: string[], options: { timeoutMs?: number; label: string; input?: Buffer }) {
+ async root(script: string, args: string[], options: { timeoutMs?: number; label: string; input?: Buffer; onProgress?: (message: RelayDeployProgressMessage) => void }) {
this.assertCurrent();
if (!this.privilege) throw new Error('privilege not determined');
const command = `bash -c ${shellQuote(script)} cindy-relay ${args.map(shellQuote).join(' ')}`;
- return this.host.exec(this.privilege === 'root' ? command : `sudo -n ${command}`, {
+ const privilegedCommand = this.privilege === 'root' ? command : `sudo -n ${command}`;
+ if (options.onProgress) return this.runtimeWithProgress(privilegedCommand, options.timeoutMs ?? 120_000, options.onProgress);
+ return this.host.exec(privilegedCommand, {
timeoutMs: options.timeoutMs ?? 120_000,
label: options.label,
input: options.input,
});
}
+ /** 下载时边读边回报受控标记;原始输出只保留有界尾部用于现有错误判定。 */
+ private async runtimeWithProgress(command: string, timeoutMs: number, onProgress: (message: RelayDeployProgressMessage) => void) {
+ const stream = await this.host.execStream(command, { timeoutMs: Math.min(timeoutMs, 60_000) });
+ try { this.assertCurrent(); } catch (error) { stream.kill(); throw error; }
+ return new Promise<{ stdout: string; stderr: string; exitCode: number | null }>((resolve, reject) => {
+ let stdout = '';
+ let stderr = '';
+ let line = '';
+ let settled = false;
+ const off: Array<() => void> = [];
+ const cleanup = () => { clearTimeout(timer); off.forEach(unsubscribe => unsubscribe()); };
+ const fail = (error: Error) => {
+ if (settled) return;
+ settled = true;
+ cleanup();
+ stream.kill();
+ reject(new RelayDeployError('DOWNLOAD_FAILED', error.message.slice(0, 300)));
+ };
+ const timer = setTimeout(() => fail(new Error('runtime download timed out')), timeoutMs);
+ off.push(stream.onStdout(chunk => {
+ stdout = (stdout + chunk).slice(-65_536);
+ // 逐字符收行,防止远端无换行输出让解析缓冲无限增长。仅识别本脚本生成的事件。
+ for (const char of chunk) {
+ if (char === '\n') {
+ const match = /^PROGRESS (runtime-cached|runtime-download|runtime-fallback|runtime-checksum|runtime-extract)\r?$/.exec(line);
+ line = '';
+ if (match) {
+ try { onProgress(match[1] as RelayDeployProgressMessage); }
+ catch (error) { fail(error instanceof Error ? error : new Error('deployment progress failed')); return; }
+ }
+ } else if (line.length < 256) line += char;
+ }
+ }));
+ off.push(stream.onStderr(chunk => { stderr = (stderr + chunk).slice(-65_536); }));
+ off.push(stream.onError(fail));
+ off.push(stream.onClose(({ code }) => {
+ if (settled) return;
+ settled = true;
+ cleanup();
+ resolve({ stdout, stderr, exitCode: code });
+ }));
+ stream.end();
+ });
+ }
+
async plain(script: string, label: string) {
this.assertCurrent();
return this.host.exec(`bash -c ${shellQuote(script)}`, { timeoutMs: 60_000, label });
@@ -166,6 +223,7 @@ else echo "ROOT none"; fi
if command -v systemctl >/dev/null 2>&1 && [ -d /run/systemd/system ]; then echo "SYSTEMD yes"; else echo "SYSTEMD no"; fi
if [ -f /proc/net/if_inet6 ]; then echo "IPV6 yes"; else echo "IPV6 no"; fi
if command -v curl >/dev/null 2>&1 || command -v wget >/dev/null 2>&1; then echo "FETCH yes"; else echo "FETCH no"; fi
+echo "DISTRO $( . /etc/os-release 2>/dev/null; echo "$PRETTY_NAME")"
`;
const INSPECT_SCRIPT = `
@@ -183,7 +241,11 @@ if command -v ss >/dev/null 2>&1; then
ss -Hltnp 2>/dev/null | awk '{print $4" "$6}' | while read -r addr proc; do
port="\${addr##*:}"
if [ "$port" = 80 ] || [ "$port" = 443 ]; then
- case "$proc" in *"pid=$OWN,"*) ;; *) echo "BUSY $port $(echo "$proc" | sed -n 's/.*(("\\([^"]*\\)".*/\\1/p')";; esac
+ case "$proc" in
+ *"pid=$OWN,"*) ;;
+ *docker-proxy*) echo "BUSY $port docker:$(docker ps --filter "publish=$port" --format '{{.Names}}' 2>/dev/null | head -n 3 | tr '\\n' ',')";;
+ *) echo "BUSY $port $(echo "$proc" | sed -n 's/.*(("\\([^"]*\\)".*/\\1/p')";;
+ esac
fi
done
fi
@@ -193,20 +255,25 @@ const RUNTIME_SCRIPT = `
set -e
VERSION="$1"; SHA="$2"; URL_A="$3"; URL_B="$4"
NODE_DIR=${INSTALL_DIR}/node
-if [ -x "$NODE_DIR/bin/node" ] && [ "$("$NODE_DIR/bin/node" --version 2>/dev/null)" = "v$VERSION" ]; then echo "NODE_READY cached"; exit 0; fi
+if [ -x "$NODE_DIR/bin/node" ] && [ "$("$NODE_DIR/bin/node" --version 2>/dev/null)" = "v$VERSION" ]; then echo "PROGRESS runtime-cached"; echo "NODE_READY cached"; exit 0; fi
TMP=$(mktemp -d); trap 'rm -rf "$TMP"' EXIT
-ok=""
+ok=""; attempted=""
for url in "$URL_A" "$URL_B"; do
+ if [ -n "$attempted" ]; then echo "PROGRESS runtime-fallback"; fi
+ attempted=1
+ echo "PROGRESS runtime-download"
if command -v curl >/dev/null 2>&1; then
curl -fsSL --retry 2 --retry-delay 2 --connect-timeout 15 --max-time 900 -o "$TMP/node.tgz" "$url" || continue
else
wget -q -t 3 -T 30 -O "$TMP/node.tgz" "$url" || continue
fi
+ echo "PROGRESS runtime-checksum"
if [ "$(sha256sum "$TMP/node.tgz" | cut -d' ' -f1)" = "$SHA" ]; then ok=1; break; fi
echo "HASH_MISMATCH $url"
done
[ -n "$ok" ] || { echo "ERROR DOWNLOAD"; exit 21; }
mkdir -p "$TMP/x"
+echo "PROGRESS runtime-extract"
tar -xzf "$TMP/node.tgz" -C "$TMP/x" --strip-components=1
install -d -m 755 ${INSTALL_DIR}
rm -rf "$NODE_DIR.new"
@@ -221,8 +288,8 @@ const UPLOAD_SCRIPT = `
set -e
install -d -m 755 ${INSTALL_DIR}
umask 022
-cat > ${INSTALL_DIR}/relay.mjs.new
-echo "SHA $(sha256sum ${INSTALL_DIR}/relay.mjs.new | cut -d' ' -f1)"
+cat > ${INSTALL_DIR}/relay.new.mjs
+echo "SHA $(sha256sum ${INSTALL_DIR}/relay.new.mjs | cut -d' ' -f1)"
`;
const CONFIGURE_SCRIPT = `
@@ -236,7 +303,7 @@ fi
systemctl stop cindy-relay >/dev/null 2>&1 || true
if [ "$REPLACE" = 1 ]; then rm -rf ${DATA_DIR}; fi
install -d -m 700 -o cindy-relay -g cindy-relay ${DATA_DIR}
-mv -f ${INSTALL_DIR}/relay.mjs.new ${INSTALL_DIR}/relay.mjs
+mv -f ${INSTALL_DIR}/relay.new.mjs ${INSTALL_DIR}/relay.mjs
if [ ! -f ${DATA_DIR}/relay-state.json ]; then
"$NODE" ${INSTALL_DIR}/relay.mjs init --data ${DATA_DIR} "$@" >/dev/null
echo "INITIALIZED"
@@ -299,7 +366,7 @@ set -e
ACTION="$1"; shift
NODE=${INSTALL_DIR}/node/bin/node
BUNDLE=${INSTALL_DIR}/relay.mjs
-if [ -f ${INSTALL_DIR}/relay.mjs.new ]; then BUNDLE=${INSTALL_DIR}/relay.mjs.new; fi
+if [ -f ${INSTALL_DIR}/relay.new.mjs ]; then BUNDLE=${INSTALL_DIR}/relay.new.mjs; fi
if [ "$ACTION" != commit ]; then "$NODE" "$BUNDLE" nginx --action "$ACTION" "$@"; fi
if [ "$ACTION" = rollback ]; then
rm -f /etc/systemd/system/cindy-relay.service.new
@@ -346,8 +413,11 @@ const UNINSTALL_SCRIPT = `
set -e
NODE=${INSTALL_DIR}/node/bin/node
STATE=${DATA_DIR}/relay-state.json
-if [ ! -x "$NODE" ] || [ ! -f "$STATE" ]; then echo "RELAY_MISMATCH"; exit 22; fi
-"$NODE" -e 'try{const s=JSON.parse(require("fs").readFileSync(process.argv[1],"utf8"));if(s.relayId!==process.argv[2]||s.ownerPublicKey!==process.argv[3])process.exit(22)}catch{process.exit(22)}' "$STATE" "$2" "$3" || { echo "RELAY_MISMATCH"; exit 22; }
+# 没有设备档案时只剩未完成部署留下的程序文件,无需核对主人;有档案就必须是本机这一份。
+if [ -f "$STATE" ]; then
+ if [ ! -x "$NODE" ]; then echo "RELAY_MISMATCH"; exit 22; fi
+ "$NODE" -e 'try{const s=JSON.parse(require("fs").readFileSync(process.argv[1],"utf8"));if(s.relayId!==process.argv[2]||s.ownerPublicKey!==process.argv[3])process.exit(22)}catch{process.exit(22)}' "$STATE" "$2" "$3" || { echo "RELAY_MISMATCH"; exit 22; }
+fi
if [ -f /etc/cindy-relay/nginx/state.json ]; then
systemctl stop cindy-relay-nginx.timer cindy-relay-nginx.service >/dev/null 2>&1 || true
"$NODE" ${INSTALL_DIR}/relay.mjs nginx --action remove
@@ -372,10 +442,20 @@ function nodeUrls(arch: 'x64' | 'arm64', preferMirror: boolean): [string, string
return preferMirror ? [mirror, official] : [official, mirror];
}
+/** 服务器自报的文字只用于显示:只留可打印字符并限长。 */
+function displayText(value: string | undefined, max = 80): string {
+ return [...(value ?? '')].filter((char) => char >= ' ' && char !== '\u007f').join('').trim().slice(0, max);
+}
+
/** 连接并确认权限与系统;返回可用 root 执行的远端。 */
-async function prepare(sshHostId: string, assertCurrent: () => void): Promise<{ remote: Remote; arch: 'x64' | 'arm64'; ipv6: boolean }> {
+async function prepare(
+ sshHostId: string,
+ assertCurrent: () => void,
+): Promise<{ remote: Remote; arch: 'x64' | 'arm64'; ipv6: boolean; system: string }> {
const base = await connect(sshHostId, assertCurrent);
const probe = parseLines((await base.plain(PROBE_SCRIPT, 'relay-deploy-probe')).stdout);
+ // 连得上却一行都没跑出来:这个账号没有命令行(例如 Git 服务的 git 账号),不是系统不支持。
+ if (!first(probe, 'OS')) throw new RelayDeployError('SHELL_UNAVAILABLE');
const machine = first(probe, 'ARCH');
const arch = machine === 'x86_64' || machine === 'amd64' ? 'x64' : machine === 'aarch64' || machine === 'arm64' ? 'arm64' : null;
if (first(probe, 'OS') !== 'Linux' || !arch || first(probe, 'SYSTEMD') !== 'yes') {
@@ -384,7 +464,54 @@ async function prepare(sshHostId: string, assertCurrent: () => void): Promise<{
const privilege = first(probe, 'ROOT');
if (privilege !== 'root' && privilege !== 'sudo') throw new RelayDeployError('NEEDS_ROOT');
if (first(probe, 'FETCH') !== 'yes') throw new RelayDeployError('UNSUPPORTED_SYSTEM', 'curl / wget');
- return { remote: base.withPrivilege(privilege), arch, ipv6: first(probe, 'IPV6') === 'yes' };
+ const system = [displayText(first(probe, 'DISTRO')) || 'Linux', displayText(machine, 16)].join(' · ');
+ return { remote: base.withPrivilege(privilege), arch, ipv6: first(probe, 'IPV6') === 'yes', system };
+}
+
+const CONTAINER_NAME = /^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$/;
+
+/**
+ * 80/443 的占用情况:系统里的 Nginx 自动接入;Docker 容器与其他程序都不碰,停下说明是谁占着。
+ * 返回是否经已有 Nginx 接入。
+ */
+function assessPorts(inspected: Map<string, string[]>): boolean {
+ const containers = new Set<string>();
+ const programs = new Set<string>();
+ let nginx = false;
+ for (const line of inspected.get('BUSY') ?? []) {
+ const owner = line.split(' ')[1] ?? '';
+ if (owner === 'nginx') nginx = true;
+ else if (owner.startsWith('docker:')) {
+ const names = owner.slice('docker:'.length).split(',').filter((name) => CONTAINER_NAME.test(name));
+ for (const name of names.length ? names : ['docker-proxy']) containers.add(name);
+ } else programs.add(displayText(owner, 40) || '?');
+ }
+ if (containers.size) throw new RelayDeployError('PORT_BUSY_CONTAINER', [...containers].join(', '));
+ if (programs.size) throw new RelayDeployError('PORT_BUSY', [...programs].join(', '));
+ return nginx || first(inspected, 'NGINX_MANAGED') === 'yes';
+}
+
+function existingRelay(
+ state: string | undefined,
+ identity: { relayId: string; ownerPublicKey: string } | null,
+): RelayServerCheck['existing'] {
+ if (!state) return 'none';
+ // 设备档案还在、Node 已被保留数据卸载移除时读不出身份;部署时会先恢复 Node 再核对。
+ if (state === 'unknown') return identity ? 'mine' : 'other';
+ const [, relayId, ownerPublicKey] = state.split(' ');
+ return identity && relayId === identity.relayId && ownerPublicKey === identity.ownerPublicKey ? 'mine' : 'other';
+}
+
+/** 只读检查服务器能否部署:不安装、不写文件、不改配置。 */
+export async function checkRelayServer(
+ sshHostId: string,
+ identity: { relayId: string; ownerPublicKey: string } | null,
+ assertCurrent: () => void = () => {},
+): Promise<RelayServerCheck> {
+ const { remote, system } = await prepare(sshHostId, assertCurrent);
+ const inspected = parseLines((await remote.root(INSPECT_SCRIPT, [], { label: 'relay-deploy-inspect' })).stdout);
+ const plan = assessPorts(inspected) ? 'nginx' : 'direct';
+ return { system, plan, existing: existingRelay(first(inspected, 'STATE'), identity) };
}
function expectOk(result: { exitCode: number | null; stdout: string; stderr: string }, code: RelayDeployErrorCode): Map<string, string[]> {
@@ -396,24 +523,32 @@ function expectOk(result: { exitCode: number | null; stdout: string; stderr: str
return lines;
}
-async function waitForCertificate(remote: Remote): Promise<void> {
+async function waitForCertificate(remote: Remote, onProgress?: (message: RelayDeployProgressMessage) => void): Promise<void> {
const deadline = Date.now() + CERTIFICATE_WAIT_MS;
+ // 只是暂时连不上 CA 时中转会自己重试:继续等,到时间仍连不上才报 CA_UNREACHABLE。
+ let unreachable: string | null = null;
+ let reportedAt: string | undefined;
while (Date.now() < deadline) {
await new Promise((resolve) => setTimeout(resolve, CERTIFICATE_POLL_MS));
const lines = parseLines((await remote.root(STATUS_SCRIPT, [], { label: 'relay-deploy-status' })).stdout);
const active = first(lines, 'ACTIVE');
- let certificate: { state?: string; error?: string } | undefined;
+ type CertificateStatus = { state?: string; error?: string; transient?: boolean; updatedAt?: string };
+ let certificate: CertificateStatus | undefined;
try {
- certificate = (
- JSON.parse(first(lines, 'STATUS') ?? '{}') as {
- certificate?: { state?: string; error?: string };
- }
- ).certificate;
+ certificate = (JSON.parse(first(lines, 'STATUS') ?? '{}') as { certificate?: CertificateStatus }).certificate;
} catch {
certificate = undefined;
}
if (certificate?.state === 'ready') return;
- if (certificate?.state === 'failed') throw new RelayDeployError('CERTIFICATE_FAILED', certificate.error?.slice(0, 400));
+ if (certificate?.state === 'failed' && certificate.transient) {
+ unreachable = certificate.error ?? 'certificate authority unreachable';
+ if (certificate.updatedAt !== reportedAt) {
+ reportedAt = certificate.updatedAt;
+ onProgress?.('certificate-retry');
+ }
+ } else if (certificate?.state === 'failed') {
+ throw new RelayDeployError('CERTIFICATE_FAILED', certificate.error?.slice(0, 400));
+ }
if (active === 'failed' || (active && active !== 'active' && active !== 'activating')) {
const journal = (await remote.root(JOURNAL_SCRIPT, [], { label: 'relay-deploy-journal' })).stdout;
const errorLine = journal
@@ -423,12 +558,14 @@ async function waitForCertificate(remote: Remote): Promise<void> {
throw new RelayDeployError('DEPLOY_FAILED', errorLine?.slice(0, 400));
}
}
+ if (unreachable) throw new RelayDeployError('CA_UNREACHABLE', unreachable.slice(0, 400));
throw new RelayDeployError('CERTIFICATE_FAILED', 'timed out waiting for the certificate');
}
-async function verifyReachable(baseUrl: string, relayId: string): Promise<void> {
+async function verifyReachable(baseUrl: string, relayId: string, onRetry?: () => void): Promise<void> {
let lastError = '';
for (let attempt = 0; attempt < 4; attempt++) {
+ if (attempt > 0) onRetry?.();
try {
const res = await fetch(`${baseUrl}/api/device-link/relay/info`, {
signal: AbortSignal.timeout(10_000),
@@ -476,7 +613,9 @@ async function nginxAction(remote: Remote, action: string, args: string[] = []):
/* handled below */
}
if (result.exitCode !== 0 || parsed.event === 'error') {
- throw new RelayDeployError('NGINX_FAILED', typeof parsed.message === 'string' ? parsed.message.slice(0, 300) : undefined);
+ // Node 启动失败时 CLI 还来不及输出 JSON;只提取稳定错误码,避免原始 stderr 进入界面。
+ const runtimeCode = /\[(ERR_[A-Z0-9_]{1,80})\]/.exec(result.stderr)?.[1];
+ throw new RelayDeployError('NGINX_FAILED', typeof parsed.message === 'string' ? parsed.message.slice(0, 300) : runtimeCode);
}
return parsed;
}
@@ -487,14 +626,10 @@ export async function deployRelayToServer(params: DeployParams): Promise<{ relay
if (!bundlePath) throw new RelayDeployError('BUNDLE_MISSING');
const bundle = fs.readFileSync(bundlePath);
- params.onStep('connect');
- const { remote, arch, ipv6 } = await prepare(params.sshHostId, params.assertCurrent ?? (() => {}));
-
params.onStep('check');
+ const { remote, arch, ipv6 } = await prepare(params.sshHostId, params.assertCurrent ?? (() => {}));
const inspected = parseLines((await remote.root(INSPECT_SCRIPT, [], { label: 'relay-deploy-inspect' })).stdout);
- const busy = [...new Set(inspected.get('BUSY') ?? [])];
- if (busy.some((line) => !/^(80|443) nginx$/.test(line))) throw new RelayDeployError('PORT_BUSY', busy.join(', '));
- const useNginx = busy.length > 0 || first(inspected, 'NGINX_MANAGED') === 'yes';
+ const useNginx = assessPorts(inspected);
const state = first(inspected, 'STATE');
const assertExistingIdentity = (existingState: string) => {
const [, relayId, ownerPublicKey] = existingState.split(' ');
@@ -506,11 +641,13 @@ export async function deployRelayToServer(params: DeployParams): Promise<{ relay
assertExistingIdentity(state);
}
+ params.onServerChange?.();
params.onStep('runtime');
const [urlA, urlB] = nodeUrls(arch, params.preferMirror);
const runtime = await remote.root(RUNTIME_SCRIPT, [NODE_VERSION, NODE_SHA256[arch], urlA, urlB], {
timeoutMs: 20 * 60 * 1000,
label: 'relay-deploy-runtime',
+ onProgress: params.onProgress,
});
expectOk(runtime, 'DOWNLOAD_FAILED');
@@ -562,6 +699,7 @@ export async function deployRelayToServer(params: DeployParams): Promise<{ relay
let nginxPrepared = false;
try {
if (useNginx) {
+ params.onProgress?.('nginx-prepare');
const args = ['--address', params.address];
if (ipv6) args.push('--ipv6');
if (await existingHttpsCertificate(params.baseUrl)) args.push('--existing-certificate');
@@ -594,15 +732,19 @@ export async function deployRelayToServer(params: DeployParams): Promise<{ relay
});
params.onStep('certificate');
- if (mode !== 'nginx-existing') await waitForCertificate(remote);
+ if (mode !== 'nginx-existing') {
+ params.onProgress?.('certificate-wait');
+ await waitForCertificate(remote, params.onProgress);
+ }
if (useNginx) await nginxAction(remote, 'activate');
params.onStep('verify');
- await verifyReachable(params.baseUrl, init.relayId);
+ await verifyReachable(params.baseUrl, init.relayId, () => params.onProgress?.('verify-retry'));
if (useNginx) await nginxAction(remote, 'commit');
return { relayVersion: RELAY_VERSION };
} catch (error) {
if (nginxPrepared) {
+ params.onProgress?.('nginx-rollback');
try {
await nginxAction(remote, 'rollback');
} catch {
@@ -623,9 +765,12 @@ export async function uninstallRelayFromServer(
onStep('connect');
const { remote } = await prepare(sshHostId, assertCurrent);
const inspected = expectOk(await remote.root(INSPECT_SCRIPT, [], { label: 'relay-deploy-inspect' }), 'DEPLOY_FAILED');
- const [, relayId, ownerPublicKey] = (first(inspected, 'STATE') ?? '').split(' ');
- if (relayId !== identity.relayId || ownerPublicKey !== identity.ownerPublicKey) throw new RelayDeployError('RELAY_MISMATCH');
- onStep('configure');
+ const state = first(inspected, 'STATE');
+ if (state) {
+ const [, relayId, ownerPublicKey] = state.split(' ');
+ if (relayId !== identity.relayId || ownerPublicKey !== identity.ownerPublicKey) throw new RelayDeployError('RELAY_MISMATCH');
+ }
+ onStep('remove');
const result = await remote.root(UNINSTALL_SCRIPT, [removeData ? '1' : '0', identity.relayId, identity.ownerPublicKey], {
label: 'relay-deploy-uninstall',
});
diff --git a/apps/desktop/src/main/device-link/selfHostedRelayRuntime.ts b/apps/desktop/src/main/device-link/selfHostedRelayRuntime.ts
index ae6c741a6d..23ef2fd864 100644
--- a/apps/desktop/src/main/device-link/selfHostedRelayRuntime.ts
+++ b/apps/desktop/src/main/device-link/selfHostedRelayRuntime.ts
@@ -44,6 +44,8 @@ import { assertTrustedAppRendererEvent } from '../security/trustedAppRenderer.js
import { throwIpcError } from '../utils/ipcValidate.js';
import {
parseSelfHostedRelayCommand,
+ RELAY_DEPLOY_STEPS,
+ RELAY_UNINSTALL_STEPS,
relayBaseUrlForAddress,
SELF_HOSTED_RELAY_IPC,
type SelfHostedRelayCommand,
@@ -51,7 +53,11 @@ import {
type SelfHostedRelayErrorCode,
type SelfHostedRelayJoinView,
type SelfHostedRelayPairRequestView,
+ type SelfHostedRelayDeploymentStatus,
+ type SelfHostedRelayServerCheck,
type SelfHostedRelayState,
+ type RelayDeployProgressMessage,
+ type RelayDeployStep,
} from '../../shared/selfHostedRelay.js';
import { deviceName } from './deviceName.js';
import {
@@ -77,7 +83,13 @@ import {
type RelayDeployment,
type RelaySecrets,
} from './selfHostedRelayConfig.js';
-import { bundledRelayVersion, deployRelayToServer, RelayDeployError, uninstallRelayFromServer } from './selfHostedRelayDeploy.js';
+import {
+ bundledRelayVersion,
+ checkRelayServer,
+ deployRelayToServer,
+ RelayDeployError,
+ uninstallRelayFromServer,
+} from './selfHostedRelayDeploy.js';
import { refreshRelayCertificatesSoon } from './selfHostedRelayFrameAuth.js';
import { readDeviceLinkSettings } from './settings-store.js';
import { activeOwnerScopeKey, getActiveAppSession, isAppSessionBoundaryPending, onAppSessionInvalidated } from '../appSessionState.js';
@@ -189,9 +201,13 @@ export function getState(): SelfHostedRelayState {
// ─── 主人身份 ────────────────────────────────────────────────────────────────
+function generateOwnerSecrets(): RelaySecrets {
+ return { credential: createDeviceCredential().credential, seed: createRelaySigningKey(crypto).seed };
+}
+
/** 新建一份主人身份:凭证与签名私钥只存本机安全存储。 */
function createOwnerSecrets(relayId: string): RelaySecrets {
- const secrets = { credential: createDeviceCredential().credential, seed: createRelaySigningKey(crypto).seed };
+ const secrets = generateOwnerSecrets();
writeRelaySecrets(relayId, secrets);
return secrets;
}
@@ -483,7 +499,12 @@ async function decide(requestId: string, approve: boolean): Promise<CommandResul
// ─── 命令 ────────────────────────────────────────────────────────────────────
-type CommandResult = { state: SelfHostedRelayState; error?: SelfHostedRelayErrorCode };
+type CommandResult = {
+ state: SelfHostedRelayState;
+ error?: SelfHostedRelayErrorCode;
+ check?: SelfHostedRelayServerCheck;
+ deploymentStatus?: SelfHostedRelayDeploymentStatus;
+};
function requireReady(): SelfHostedRelayErrorCode | null {
// 账号数据作用域提交之前不能读写中转配置(否则会落进临时命名空间)。
@@ -680,57 +701,67 @@ function deploymentActive(deployment: RelayDeployment): RelayConfig['active'] {
};
}
-function runDeployJob(action: SelfHostedRelayDeployJobView['action'], work: (onStep: (step: SelfHostedRelayDeployJobView['step']) => void, assertOwner: () => void) => Promise<void>): void {
+type DeployJobPlan = Pick<SelfHostedRelayDeployJobView, 'action' | 'target' | 'serverChanged'> & { steps: RelayDeployStep[] };
+
+function runDeployJob(plan: DeployJobPlan, work: (onStep: (step: SelfHostedRelayDeployJobView['step']) => void, assertOwner: () => void, onProgress: (message: RelayDeployProgressMessage) => void) => Promise<void>): void {
+ const { action } = plan;
const assertOwner = captureOwner();
const isCurrent = () => {
try { assertOwner(); return true; } catch { return false; }
};
- deployJob = { action, step: 'connect', status: 'running' };
+ const startedAt = Date.now();
+ const first = plan.steps[0];
+ deployJob = { ...plan, step: first, status: 'running', startedAt, logs: [{ at: startedAt, step: first }] };
+ log.info('relay deployment started', { action });
+ const appendProgress = (step: SelfHostedRelayDeployJobView['step'], message?: RelayDeployProgressMessage) => {
+ if (!isCurrent() || deployJob?.status !== 'running') return;
+ const logs = deployJob.logs ?? [];
+ const last = logs.at(-1);
+ if (last?.step === step && last.message === message) return;
+ deployJob = { ...deployJob, step, logs: [...logs.slice(-99), { at: Date.now(), step, ...(message ? { message } : {}) }] };
+ emitChanged();
+ };
const onStep = (step: SelfHostedRelayDeployJobView['step']) => {
assertOwner();
- if (deployJob?.status !== 'running') return;
- deployJob = { ...deployJob, step };
- emitChanged();
+ appendProgress(step);
+ log.info('relay deployment step', { action, step });
+ };
+ const onProgress = (message: RelayDeployProgressMessage) => {
+ if (deployJob) appendProgress(deployJob.step, message);
};
- void work(onStep, assertOwner)
+ void work(onStep, assertOwner, onProgress)
.then(() => {
if (!isCurrent()) return;
- deployJob = { action, step: 'finish', status: 'done' };
+ deployJob = { ...deployJob!, action, step: 'finish', status: 'done', finishedAt: Date.now() };
+ log.info('relay deployment completed', { action });
})
.catch((error: unknown) => {
if (!isCurrent()) return;
const step = deployJob?.step ?? 'connect';
if (error instanceof RelayDeployError) {
- deployJob = { action, step, status: 'failed', error: error.code, detail: error.detail };
+ log.warn('relay deployment failed', { action, step, code: error.code });
+ deployJob = { ...deployJob!, action, step, status: 'failed', error: error.code, detail: error.detail, finishedAt: Date.now() };
} else {
- log.warn('relay deployment failed', { reason: error instanceof Error ? error.name : 'unknown' });
- deployJob = { action, step, status: 'failed', error: 'DEPLOY_FAILED', detail: error instanceof Error ? error.message.slice(0, 300) : undefined };
+ log.warn('relay deployment failed', { action, step, code: 'DEPLOY_FAILED', reason: error instanceof Error ? error.name : 'unknown' });
+ deployJob = { ...deployJob!, action, step, status: 'failed', error: 'DEPLOY_FAILED', detail: error instanceof Error ? error.message.slice(0, 300) : undefined, finishedAt: Date.now() };
}
})
.finally(() => { if (isCurrent()) emitChanged(); });
}
-/** 部署或升级。身份(中转 ID、主人秘密)跟着部署记录走:重试与升级都保留它。 */
+/**
+ * 部署或升级。身份(中转 ID、主人秘密)跟着部署记录走:重试与升级都保留它。
+ * 检查通过、第一次改动服务器前才保存记录和新身份:在检查阶段停下的部署不留下任何东西。
+ */
function deploy(input: { sshHostId: string; address: string; name: string; replaceExisting: boolean }, action: 'deploy' | 'upgrade'): CommandResult {
const notReady = requireReady();
if (notReady) return { state: getState(), error: notReady };
if (deployJob?.status === 'running') return { state: getState(), error: 'BUSY' };
if (!bundledRelayVersion()) return { state: getState(), error: 'BUNDLE_MISSING' };
- const config = readRelayConfig();
- const previous = config.deployment;
+ const previous = readRelayConfig().deployment;
const reuse = previous && previous.sshHostId === input.sshHostId && !input.replaceExisting ? readRelaySecrets(previous.relayId) : null;
const relayId = reuse && previous ? previous.relayId : randomUUID();
- const secrets = reuse ?? createOwnerSecrets(relayId);
- let replacedActive = false;
- if (previous && previous.relayId !== relayId) {
- // 换了一台服务器(或清掉重来):旧身份作废。正在用旧中转时先切回官方,不留下指向已删秘密的配置。
- replacedActive = config.active?.relayId === previous.relayId;
- if (replacedActive) {
- stopPairing();
- config.active = null;
- }
- deleteRelaySecrets(previous.relayId);
- }
+ const secrets = reuse ?? generateOwnerSecrets();
const init = ownerInitArgs(relayId, secrets, input.name);
const baseUrl = relayBaseUrlForAddress(input.address);
const record: RelayDeployment = {
@@ -744,10 +775,40 @@ function deploy(input: { sshHostId: string; address: string; name: string; repla
deployedAt: new Date().toISOString(),
complete: false,
};
- // 先记下身份再动服务器:中途失败后重试,用的还是已经写进服务器的这一份。
- writeRelayConfig({ ...config, deployment: record });
- if (replacedActive) restartDeviceLinkForRelayChange();
- runDeployJob(action, async (onStep, assertOwner) => {
+ // 没完成的部署换了服务器:原服务器上可能装了一半,先清理掉再部署到新服务器。
+ const cleanup = previous && !previous.complete && previous.sshHostId !== input.sshHostId ? previous : null;
+ const persist = () => {
+ const config = readRelayConfig();
+ const old = config.deployment;
+ let replacedActive = false;
+ if (old && old.relayId !== relayId) {
+ // 换了一台服务器(或清掉重来):旧身份作废。正在用旧中转时先切回官方,不留下指向已删秘密的配置。
+ replacedActive = config.active?.relayId === old.relayId;
+ if (replacedActive) {
+ stopPairing();
+ config.active = null;
+ }
+ deleteRelaySecrets(old.relayId);
+ }
+ if (!reuse) writeRelaySecrets(relayId, secrets);
+ // 升级沿用原记录:失败时服务器上仍是这一份中转,卡片照常显示,可以重试。
+ if (!(action === 'upgrade' && old?.relayId === relayId)) writeRelayConfig({ ...config, deployment: record });
+ if (deployJob) deployJob = { ...deployJob, serverChanged: true };
+ if (replacedActive) restartDeviceLinkForRelayChange();
+ };
+ const plan: DeployJobPlan = {
+ action,
+ steps: cleanup ? ['cleanup', ...RELAY_DEPLOY_STEPS] : [...RELAY_DEPLOY_STEPS],
+ target: { sshHostId: input.sshHostId, address: input.address, name: input.name, baseUrl },
+ serverChanged: false,
+ };
+ runDeployJob(plan, async (onStep, assertOwner, onProgress) => {
+ if (cleanup) {
+ onStep('cleanup');
+ await uninstallRelayFromServer(cleanup.sshHostId, cleanup, true, () => {}, assertOwner);
+ assertOwner();
+ forgetDeploymentLocally(cleanup, true);
+ }
const { relayVersion } = await deployRelayToServer({
sshHostId: input.sshHostId,
address: input.address,
@@ -756,7 +817,12 @@ function deploy(input: { sshHostId: string; address: string; name: string; repla
init,
preferMirror: providerShareLinkApp() === 'cindycn',
onStep,
+ onProgress,
assertCurrent: assertOwner,
+ onServerChange: () => {
+ assertOwner();
+ persist();
+ },
});
onStep('finish');
const done: RelayDeployment = { ...record, relayVersion, deployedAt: new Date().toISOString(), complete: true };
@@ -786,7 +852,8 @@ function uninstallDeployment(removeData: boolean): CommandResult {
if (deployJob?.status === 'running') return { state: getState(), error: 'BUSY' };
const deployment = readRelayConfig().deployment;
if (!deployment) return { state: getState(), error: 'NO_DEPLOYMENT' };
- runDeployJob('uninstall', async (onStep, assertOwner) => {
+ const target = { sshHostId: deployment.sshHostId, address: deployment.address, name: deployment.name, baseUrl: deployment.baseUrl };
+ runDeployJob({ action: 'uninstall', steps: [...RELAY_UNINSTALL_STEPS], target, serverChanged: true }, async (onStep, assertOwner) => {
await uninstallRelayFromServer(deployment.sshHostId, deployment, removeData, onStep, assertOwner);
onStep('finish');
forgetDeploymentLocally(deployment, removeData);
@@ -824,6 +891,63 @@ async function useDeployment(): Promise<CommandResult> {
return { state: getState() };
}
+/** 部署表单里选服务器时的只读检查;服务器上已有的中转按这台电脑的部署记录核对是不是自己的。 */
+async function checkServer(sshHostId: string): Promise<CommandResult> {
+ const notReady = requireReady();
+ if (notReady) return { state: getState(), error: notReady };
+ const assertOwner = captureOwner();
+ const deployment = readRelayConfig().deployment;
+ const identity = deployment?.sshHostId === sshHostId ? deployment : null;
+ let check: SelfHostedRelayServerCheck;
+ try {
+ check = { sshHostId, ok: true, ...(await checkRelayServer(sshHostId, identity, assertOwner)) };
+ } catch (error) {
+ if (error instanceof RelayOperationExpired) throw error;
+ check = error instanceof RelayDeployError
+ ? { sshHostId, ok: false, error: error.code, ...(error.detail ? { detail: error.detail } : {}) }
+ : { sshHostId, ok: false, error: 'DEPLOY_FAILED', ...(error instanceof Error ? { detail: error.message.slice(0, 300) } : {}) };
+ }
+ assertOwner();
+ log.info('relay server checked', check.ok ? { ok: true, plan: check.plan, existing: check.existing } : { ok: false, code: check.error });
+ return { state: getState(), check };
+}
+
+const countOf = (value: unknown) => (typeof value === 'number' && Number.isInteger(value) && value >= 0 ? value : undefined);
+
+/**
+ * 用部署记录里的主人凭证读服务器中转的管理状态;没在用它时也能看到在线、设备数与证书到期。
+ * 返回的中转 ID 不是这份部署时按连不上处理,不把别的中转的数字当成自己的。
+ */
+async function deploymentStatus(): Promise<CommandResult> {
+ const notReady = requireReady();
+ if (notReady) return { state: getState(), error: notReady };
+ const assertOwner = captureOwner();
+ const deployment = readRelayConfig().deployment;
+ if (!deployment?.complete) return { state: getState(), error: 'NO_DEPLOYMENT' };
+ const secrets = readRelaySecrets(deployment.relayId);
+ if (!secrets) return { state: getState(), deploymentStatus: { online: false } };
+ let status: SelfHostedRelayDeploymentStatus = { online: false };
+ try {
+ const res = await fetch(`${deployment.baseUrl}/api/device-link/relay/admin/status`, {
+ headers: { authorization: `CindyRelay ${secrets.credential}` },
+ signal: AbortSignal.timeout(10_000),
+ });
+ const body = (await res.json().catch(() => null)) as Record<string, unknown> | null;
+ if (res.ok && body?.relayId === deployment.relayId) {
+ status = {
+ online: true,
+ devices: countOf(body.devices),
+ onlineDevices: countOf(body.online),
+ certificateExpiresAt: typeof body.certificateExpiresAt === 'string' ? body.certificateExpiresAt : null,
+ };
+ }
+ } catch {
+ status = { online: false };
+ }
+ assertOwner();
+ return { state: getState(), deploymentStatus: status };
+}
+
async function execute(command: SelfHostedRelayCommand): Promise<CommandResult> {
switch (command.type) {
case 'state':
@@ -859,6 +983,13 @@ async function execute(command: SelfHostedRelayCommand): Promise<CommandResult>
}
case 'use-deployment':
return useDeployment();
+ case 'check-server':
+ return checkServer(command.sshHostId);
+ case 'dismiss-deploy-job':
+ if (deployJob && deployJob.status !== 'running') deployJob = null;
+ return { state: getState() };
+ case 'deployment-status':
+ return deploymentStatus();
}
}
@@ -878,7 +1009,8 @@ export function registerSelfHostedRelayIpc(): void {
if (!(error instanceof RelayOperationExpired)) throw error;
return { state: getState(), error: 'NOT_SIGNED_IN' };
}
- if (command.type !== 'state') emitChanged();
+ // 只读查询不改状态,不向所有窗口广播。
+ if (command.type !== 'state' && command.type !== 'check-server' && command.type !== 'deployment-status') emitChanged();
return result;
});
diff --git a/apps/desktop/src/renderer/components/settings/RelayServicePanel.tsx b/apps/desktop/src/renderer/components/settings/RelayServicePanel.tsx
index 5a99d4a12e..378a69205c 100644
--- a/apps/desktop/src/renderer/components/settings/RelayServicePanel.tsx
+++ b/apps/desktop/src/renderer/components/settings/RelayServicePanel.tsx
@@ -1,12 +1,33 @@
/**
- * 「远程连接 → 中转服务」:选择设备之间经 Cindy 官方中转,还是用户自己的中转
- * (这台电脑当中转 / 部署到自己的服务器 / 加入别的中转)。方案见 docs/self-hosted-relay-plan.md。
+ * 「远程连接 → 连接线路」:设备之间经 Cindy 官方中转,还是用户自己的中转
+ * (部署到自己的服务器 / 这台电脑当中转 / 加入别的中转)。方案见 docs/self-hosted-relay-plan.md。
+ *
+ * 紧跟在「我的设备」下面直接展示:单选的线路列表(选中的那条就是正在用的)、服务器中转的管理,
+ * 以及三步部署窗口(选择服务器 → 部署 → 添加设备)。
*
* 状态以 main 为准(`window.electronAPI.selfHostedRelay`):命令返回最新状态,另有 CHANGED 推送;
* 连接问题(被移出中转)来自 device-link 链路,低频轮询兜底。
*/
-import { useCallback, useEffect, useState } from 'react';
+import { useCallback, useEffect, useRef, useState } from 'react';
+import * as Dialog from '@radix-ui/react-dialog';
import { useTranslation } from 'react-i18next';
+import {
+ ArrowRightLeft,
+ Check,
+ ChevronRight,
+ CircleAlert,
+ CircleCheck,
+ Cloud,
+ Info,
+ Link2,
+ Monitor,
+ Plus,
+ RefreshCw,
+ Server,
+ Settings2,
+ Trash2,
+ TriangleAlert,
+} from 'lucide-react';
import * as QRCode from 'qrcode';
import { Button } from '@/components/ui/button';
@@ -14,15 +35,22 @@ import { useOptionalConfirmDialog } from '@/components/ui/confirm-dialog-provide
import { Input } from '@/components/ui/input';
import { SegmentedControl } from '@/components/ui/segmented-control';
import { Select } from '@/components/ui/select';
+import { Spinner } from '@/components/ui/spinner';
+import { Tip } from '@/components/ui/tooltip';
import { toast } from '@/lib/toast';
+import { cn } from '@/lib/utils';
import {
DEFAULT_RELAY_PORT,
normalizeRelayAddress,
RELAY_DEPLOY_STEPS,
+ RELAY_UNINSTALL_STEPS,
type SelfHostedRelayCommand,
type SelfHostedRelayDeployJobView,
+ type SelfHostedRelayDeploymentStatus,
type SelfHostedRelayErrorCode,
+ type SelfHostedRelayServerCheck,
type SelfHostedRelayState,
+ type RelayDeployLogEntry,
} from '../../../shared/selfHostedRelay';
const STATE_POLL_MS = 3_000;
@@ -79,41 +107,82 @@ export function useSelfHostedRelayState(enabled: boolean) {
export type SelfHostedRelayController = ReturnType<typeof useSelfHostedRelayState>;
-/** 收起态摘要:官方 / 本机中转 / 已加入的中转名。 */
-export function relaySummary(
- state: SelfHostedRelayState | null,
- t: (key: string, options?: Record<string, unknown>) => string,
-): string | null {
- if (!state) return null;
- if (state.mode === 'official' || !state.relay) return t('settings.remoteControl.relay.summary.official');
- if (state.relay.origin === 'host') return t('settings.remoteControl.relay.summary.owner');
- if (state.relay.origin === 'server') return t('settings.remoteControl.relay.summary.server', { name: state.relay.name });
- return t('settings.remoteControl.relay.summary.member', { name: state.relay.name });
-}
-
function Card({ children }: { children: React.ReactNode }) {
- return <section className="flex flex-col gap-3 rounded-xl bg-[var(--settings-input-bg)] p-3">{children}</section>;
+ return <section className="flex flex-col gap-4 rounded-xl bg-[var(--settings-input-bg)] p-4">{children}</section>;
}
function Hint({ children }: { children: React.ReactNode }) {
return <p className="text-12 leading-[1.5] text-[var(--text-tertiary)]">{children}</p>;
}
+/** 错误只在图标上用红色,说明文字保持正常颜色(DESIGN.md「Error notices」)。 */
function ErrorText({ children }: { children: React.ReactNode }) {
return (
- <p role="alert" className="text-12 leading-[1.5] text-[var(--error-fg)]">
- {children}
- </p>
+ <div role="alert" className="flex items-start gap-2">
+ <LineIcon tone="failed" />
+ <p className="min-w-0 flex-1 text-12 leading-5 text-[var(--text-secondary)]">{children}</p>
+ </div>
+ );
+}
+
+/**
+ * 加入别的中转、这台电脑当中转的设置:用与部署窗口同一套外框的小窗口,不在线路列表下面展开。
+ * 点窗口外面不关闭,免得填到一半丢失;Esc 和「取消」照常关闭。
+ */
+function FormDialog({
+ open,
+ onClose,
+ title,
+ description,
+ children,
+}: {
+ open: boolean;
+ onClose: () => void;
+ title: string;
+ description: string;
+ children: React.ReactNode;
+}) {
+ return (
+ <Dialog.Root
+ open={open}
+ onOpenChange={(next) => {
+ if (!next) onClose();
+ }}
+ >
+ <Dialog.Portal>
+ <Dialog.Overlay className="modal-scrim fixed inset-0 z-[10000]" />
+ <Dialog.Content
+ onPointerDownOutside={(event) => event.preventDefault()}
+ className="modal-panel fixed left-1/2 top-1/2 z-[10001] flex max-h-[88vh] w-[min(480px,calc(100vw-32px))] -translate-x-1/2 -translate-y-1/2 flex-col outline-none"
+ >
+ <div className="flex flex-col gap-1 px-4 pb-4 pt-4">
+ <Dialog.Title className="text-16 font-semibold text-[var(--confirm-title)]">{title}</Dialog.Title>
+ <Dialog.Description className="text-12 leading-[1.5] text-[var(--text-tertiary)]">{description}</Dialog.Description>
+ </div>
+ {children}
+ </Dialog.Content>
+ </Dialog.Portal>
+ </Dialog.Root>
);
}
+/** 窗口里命令失败的原因;用户取消不算失败。 */
+function CommandError({ error, port }: { error: SelfHostedRelayErrorCode | null; port: number }) {
+ const { t } = useTranslation();
+ if (!error || error === 'CANCELLED') return null;
+ return <ErrorText>{t(`settings.remoteControl.relay.errors.${error}`, { port, detail: '' })}</ErrorText>;
+}
+
+/** 这台电脑当中转的设置。还没在用时,开启就是切换到它:`notice` 写清楚原线路会怎样。 */
function HostForm({
state,
controller,
+ notice,
onDone,
}: {
state: SelfHostedRelayState;
controller: SelfHostedRelayController;
+ notice: string | null;
onDone: () => void;
}) {
const { t } = useTranslation();
@@ -124,60 +193,66 @@ function HostForm({
const portValid = Number.isInteger(portNumber) && portNumber >= 1024 && portNumber <= 65535;
const k = 'settings.remoteControl.relay.host';
return (
- <Card>
- <div className="flex flex-col gap-1">
- <p className="text-13 font-medium text-[var(--text-primary)]">{t(`${k}.title`)}</p>
- <Hint>{t(`${k}.hint`)}</Hint>
- </div>
- <label className="flex items-center justify-between gap-4">
- <span className="text-13 text-[var(--text-primary)]">{t(`${k}.port`)}</span>
- <Input
- value={port}
- onChange={setPort}
- inputMode="numeric"
- size="sm"
- className="w-28"
- error={!portValid}
- ariaLabel={t(`${k}.port`)}
- />
- </label>
- <div className="flex flex-col gap-2">
- <div className="flex items-center justify-between gap-4">
- <span className="text-13 text-[var(--text-primary)]">{t(`${k}.scope`)}</span>
- <SegmentedControl
- aria-label={t(`${k}.scope`)}
- value={scope}
- onValueChange={setScope}
- options={[
- { value: 'local', label: t(`${k}.scopeLocal`) },
- { value: 'all', label: t(`${k}.scopeAll`) },
- ]}
+ <>
+ <div className="flex flex-col gap-4 overflow-y-auto px-4 pb-4">
+ <label className="flex items-center justify-between gap-4">
+ <span className="text-13 text-[var(--text-primary)]">{t(`${k}.port`)}</span>
+ <Input
+ value={port}
+ onChange={setPort}
+ inputMode="numeric"
+ size="sm"
+ className="w-28"
+ error={!portValid}
+ ariaLabel={t(`${k}.port`)}
/>
+ </label>
+ <div className="flex flex-col gap-2">
+ <div className="flex items-center justify-between gap-4">
+ <span className="text-13 text-[var(--text-primary)]">{t(`${k}.scope`)}</span>
+ <SegmentedControl
+ aria-label={t(`${k}.scope`)}
+ value={scope}
+ onValueChange={setScope}
+ options={[
+ { value: 'local', label: t(`${k}.scopeLocal`) },
+ { value: 'all', label: t(`${k}.scopeAll`) },
+ ]}
+ />
+ </div>
+ <Hint>{t(scope === 'all' ? `${k}.scopeAllHint` : `${k}.scopeLocalHint`)}</Hint>
</div>
- <Hint>{t(scope === 'all' ? `${k}.scopeAllHint` : `${k}.scopeLocalHint`)}</Hint>
- </div>
- <div className="flex flex-col gap-2">
- <span className="text-13 text-[var(--text-primary)]">{t(`${k}.externalUrl`)}</span>
- <Input
- value={externalUrl}
- onChange={setExternalUrl}
- placeholder={t(`${k}.externalUrlPlaceholder`)}
- size="sm"
- mono
- ariaLabel={t(`${k}.externalUrl`)}
- />
- <Hint>{t(scope === 'all' ? `${k}.externalUrlHintAll` : `${k}.externalUrlHintLocal`)}</Hint>
- {state.host.suggestedUrls.length > 0 ? (
- <Hint>
- {t(`${k}.suggested`)} <span className="font-mono">{state.host.suggestedUrls.join(' ')}</span>
- </Hint>
+ <div className="flex flex-col gap-2">
+ <span className="text-13 text-[var(--text-primary)]">{t(`${k}.externalUrl`)}</span>
+ <Input
+ value={externalUrl}
+ onChange={setExternalUrl}
+ placeholder={t(`${k}.externalUrlPlaceholder`)}
+ size="sm"
+ mono
+ ariaLabel={t(`${k}.externalUrl`)}
+ />
+ <Hint>{t(scope === 'all' ? `${k}.externalUrlHintAll` : `${k}.externalUrlHintLocal`)}</Hint>
+ {state.host.suggestedUrls.length > 0 ? (
+ <Hint>
+ {t(`${k}.suggested`)} <span className="font-mono">{state.host.suggestedUrls.join(' ')}</span>
+ </Hint>
+ ) : null}
+ </div>
+ {notice ? (
+ <p className="flex items-start gap-2 text-12 leading-[1.5] text-[var(--text-secondary)]">
+ <Info aria-hidden size={13} className="mt-0.5 shrink-0 text-[var(--text-tertiary)]" />
+ {notice}
+ </p>
) : null}
+ <CommandError error={controller.error} port={portValid ? portNumber : state.host.port} />
</div>
- <div className="flex justify-end gap-2">
+ <DialogFooter>
<Button variant="secondary" size="sm" onClick={onDone} disabled={controller.busy}>
{t(`${k}.cancel`)}
</Button>
<Button
+ variant="cta"
size="sm"
loading={controller.busy}
disabled={!portValid || controller.busy}
@@ -196,16 +271,35 @@ function HostForm({
>
{t(state.host.enabled ? `${k}.save` : `${k}.start`)}
</Button>
- </div>
- </Card>
+ </DialogFooter>
+ </>
);
}
-function AddDevice({ state, controller }: { state: SelfHostedRelayState; controller: SelfHostedRelayController }) {
+function AddDevice({
+ state,
+ controller,
+ bare = false,
+ autoCreate = false,
+}: {
+ state: SelfHostedRelayState;
+ controller: SelfHostedRelayController;
+ /** 已放在有边界的区域里时不再画顶部分隔线。 */
+ bare?: boolean;
+ /** 部署刚完成时直接生成加入链接,不用再点一次「添加设备」。 */
+ autoCreate?: boolean;
+}) {
const { t } = useTranslation();
const [qr, setQr] = useState<string | null>(null);
const link = state.joinLink?.link ?? null;
const k = 'settings.remoteControl.relay.add';
+ const autoCreated = useRef(false);
+
+ useEffect(() => {
+ if (!autoCreate || link || autoCreated.current) return;
+ autoCreated.current = true;
+ void controller.run({ type: 'create-join-link' });
+ }, [autoCreate, link, controller]);
useEffect(() => {
if (!link) {
@@ -222,7 +316,7 @@ function AddDevice({ state, controller }: { state: SelfHostedRelayState; control
}, [link]);
return (
- <div className="flex flex-col gap-3 border-t border-[var(--border-default)] pt-3">
+ <div className={cn('flex flex-col gap-3', !bare && 'border-t border-[var(--border-default)] pt-3')}>
{link ? (
<>
<Hint>{t(`${k}.hint`)}</Hint>
@@ -305,14 +399,15 @@ function AddDevice({ state, controller }: { state: SelfHostedRelayState; control
);
}
+/** 加入别的中转:粘贴链接 → 等主人同意(显示配对码)。加入成功后窗口由外层关闭。 */
function JoinForm({
state,
controller,
- onDone,
+ onClose,
}: {
state: SelfHostedRelayState;
controller: SelfHostedRelayController;
- onDone: () => void;
+ onClose: () => void;
}) {
const { t } = useTranslation();
const [link, setLink] = useState('');
@@ -320,42 +415,41 @@ function JoinForm({
const join = state.join;
const inProgress = join.status === 'connecting' || join.status === 'waiting';
return (
- <Card>
- <div className="flex flex-col gap-1">
- <p className="text-13 font-medium text-[var(--text-primary)]">{t(`${k}.title`)}</p>
- <Hint>{t(`${k}.hint`)}</Hint>
+ <>
+ <div className="flex flex-col gap-4 overflow-y-auto px-4 pb-4">
+ {join.status === 'waiting' ? (
+ <div className="flex flex-col gap-2">
+ <p className="text-13 text-[var(--text-primary)]">{t(`${k}.waiting`, { name: join.relayName })}</p>
+ <p className="font-mono text-24 font-medium tracking-[0.3em] text-[var(--text-primary)]">{join.verifyCode}</p>
+ </div>
+ ) : join.status === 'connecting' ? (
+ <p className="inline-flex items-center gap-2 text-13 text-[var(--text-secondary)]">
+ <Spinner size={12} />
+ {t(`${k}.connecting`)}
+ </p>
+ ) : (
+ <Input
+ value={link}
+ onChange={setLink}
+ placeholder={t(`${k}.placeholder`)}
+ size="sm"
+ mono
+ ariaLabel={t(`${k}.placeholder`)}
+ />
+ )}
+ {join.status === 'failed' ? (
+ <ErrorText>{t(`settings.remoteControl.relay.errors.${join.error}`)}</ErrorText>
+ ) : (
+ <CommandError error={controller.error} port={state.host.port} />
+ )}
</div>
- {join.status === 'waiting' ? (
- <div className="flex flex-col gap-2">
- <p className="text-13 text-[var(--text-primary)]">{t(`${k}.waiting`, { name: join.relayName })}</p>
- <p className="font-mono text-24 font-medium tracking-[0.3em] text-[var(--text-primary)]">{join.verifyCode}</p>
- </div>
- ) : join.status === 'connecting' ? (
- <Hint>{t(`${k}.connecting`)}</Hint>
- ) : (
- <Input
- value={link}
- onChange={setLink}
- placeholder={t(`${k}.placeholder`)}
- size="sm"
- mono
- ariaLabel={t(`${k}.placeholder`)}
- />
- )}
- {join.status === 'failed' ? <ErrorText>{t(`settings.remoteControl.relay.errors.${join.error}`)}</ErrorText> : null}
- <div className="flex justify-end gap-2">
- <Button
- variant="secondary"
- size="sm"
- onClick={() => {
- if (inProgress) void controller.run({ type: 'cancel-join' });
- onDone();
- }}
- >
+ <DialogFooter>
+ <Button variant="secondary" size="sm" onClick={onClose}>
{t(`${k}.cancel`)}
</Button>
{!inProgress ? (
<Button
+ variant="cta"
size="sm"
disabled={!link.trim() || controller.busy}
onClick={() => void controller.run({ type: 'join', link: link.trim() })}
@@ -363,14 +457,21 @@ function JoinForm({
{t(`${k}.submit`)}
</Button>
) : null}
- </div>
- </Card>
+ </DialogFooter>
+ </>
);
}
-type SshHostOption = { id: string; label: string; hostname: string };
+type SshHostOption = { id: string; label: string; hostname: string; user: string };
+
+/** 下拉里带上登录账号:`git@…` 这类只能做 Git 操作的主机一眼就能认出来。 */
+function hostOptionLabel(host: SshHostOption): string {
+ const account = `${host.user}@${host.hostname}`;
+ return host.label === host.hostname ? account : `${host.label} · ${account}`;
+}
-function useSshHosts(enabled: boolean): SshHostOption[] | null {
+/** `refreshKey` 变化时重新读取:打开部署表单时拿到刚在「远程」里加的主机。 */
+function useSshHosts(enabled: boolean, refreshKey: unknown): SshHostOption[] | null {
const [hosts, setHosts] = useState<SshHostOption[] | null>(null);
useEffect(() => {
if (!enabled) return;
@@ -384,6 +485,7 @@ function useSshHosts(enabled: boolean): SshHostOption[] | null {
id: host.config.id,
label: host.config.displayName || host.config.id,
hostname: host.config.hostname,
+ user: host.config.user,
})),
);
})
@@ -393,269 +495,988 @@ function useSshHosts(enabled: boolean): SshHostOption[] | null {
return () => {
active = false;
};
- }, [enabled]);
+ }, [enabled, refreshKey]);
return hosts;
}
-function DeployForm({
+type DeployTarget = { sshHostId: string; address: string; name: string };
+
+const DEPLOY = 'settings.remoteControl.relay.deploy';
+const SERVER = 'settings.remoteControl.relay.server';
+/** 这些错误的 detail(程序名、容器名)已写进提示文字,不再单独展开。 */
+const DETAIL_IN_MESSAGE = new Set<SelfHostedRelayErrorCode>(['PORT_BUSY', 'PORT_BUSY_CONTAINER']);
+
+function hostLabel(hosts: SshHostOption[] | null, id: string): string {
+ return hosts?.find((host) => host.id === id)?.label ?? id;
+}
+
+function formatDuration(seconds: number): string {
+ return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, '0')}`;
+}
+
+function useConfirm() {
+ const confirmDialog = useOptionalConfirmDialog();
+ return useCallback(
+ async (title: string, description: string, confirmText: string) =>
+ !confirmDialog || (await confirmDialog.confirm({ title, description, confirmText, confirmVariant: 'destructive' })),
+ [confirmDialog],
+ );
+}
+
+/** 运行中的任务每秒刷新用时;结束后不再显示。 */
+function useElapsed(job: SelfHostedRelayDeployJobView | null): number | null {
+ const running = job?.status === 'running';
+ const [now, setNow] = useState(Date.now);
+ useEffect(() => {
+ if (!running) return;
+ setNow(Date.now());
+ const timer = setInterval(() => setNow(Date.now()), 1_000);
+ return () => clearInterval(timer);
+ }, [running, job?.startedAt]);
+ if (!running || job?.startedAt === undefined) return null;
+ return Math.max(0, Math.floor((now - job.startedAt) / 1_000));
+}
+
+type LineTone = 'progress' | 'done' | 'ok' | 'warning' | 'failed' | 'pending';
+
+/** 步骤与状态行左侧的图标:颜色只用在图标上,文字保持正常颜色。 */
+function LineIcon({ tone }: { tone: LineTone }) {
+ return (
+ <span aria-hidden className="flex h-5 w-4 shrink-0 items-center justify-center">
+ {tone === 'progress' ? (
+ <Spinner size={14} className="text-[var(--text-primary)]" />
+ ) : tone === 'failed' ? (
+ <CircleAlert size={14} className="text-[var(--error-fg)]" />
+ ) : tone === 'warning' ? (
+ <TriangleAlert size={14} className="text-[var(--warning-fg)]" />
+ ) : tone === 'ok' ? (
+ <CircleCheck size={14} className="text-[var(--status-success)]" />
+ ) : tone === 'done' ? (
+ <Check size={14} className="text-[var(--text-secondary)]" />
+ ) : (
+ <span className="h-1.5 w-1.5 rounded-full bg-[var(--border-default)]" />
+ )}
+ </span>
+ );
+}
+
+function Disclosure({ label, children }: { label: string; children: React.ReactNode }) {
+ return (
+ <details className="group text-12 text-[var(--text-tertiary)]">
+ <summary className="flex min-h-6 w-fit cursor-pointer list-none items-center gap-1 hover:text-[var(--text-secondary)] [&::-webkit-details-marker]:hidden">
+ <ChevronRight
+ size={12}
+ aria-hidden
+ className="transition-transform group-open:rotate-90 motion-reduce:transition-none"
+ />
+ {label}
+ </summary>
+ <div className="mt-1 pl-4">{children}</div>
+ </details>
+ );
+}
+
+/** 出了什么问题、怎么处理;服务器返回的技术细节默认收起。 */
+function FailureReason({ error, detail }: { error: SelfHostedRelayErrorCode; detail?: string }) {
+ const { t } = useTranslation();
+ return (
+ <div className="flex flex-col gap-0.5">
+ <p className="text-12 leading-[1.6] text-[var(--text-secondary)]">
+ {t(`settings.remoteControl.relay.errors.${error}`, { detail: detail ?? '' })}
+ </p>
+ {detail && !DETAIL_IN_MESSAGE.has(error) ? (
+ <Disclosure label={t(`${DEPLOY}.showDetails`)}>
+ <p className="select-text break-words font-mono leading-[1.5]">{detail}</p>
+ </Disclosure>
+ ) : null}
+ </div>
+ );
+}
+
+function CardHeader({ eyebrow, title, subtitle, trailing }: {
+ eyebrow?: string;
+ title: string;
+ subtitle?: React.ReactNode;
+ trailing?: React.ReactNode;
+}) {
+ return (
+ <div className="flex items-start justify-between gap-3">
+ <div className="flex min-w-0 flex-col gap-0.5">
+ {eyebrow ? <p className="text-12 leading-5 text-[var(--text-tertiary)]">{eyebrow}</p> : null}
+ <p className="truncate text-13 font-medium leading-5 text-[var(--text-primary)]">{title}</p>
+ {subtitle ? <p className="truncate text-12 leading-5 text-[var(--text-tertiary)]">{subtitle}</p> : null}
+ </div>
+ {trailing ? <div className="shrink-0 text-12 leading-5 tabular-nums text-[var(--text-tertiary)]">{trailing}</div> : null}
+ </div>
+ );
+}
+
+/** 左边放清理类操作,右边放继续类操作;窄时整组换行。 */
+function Actions({ start, children }: { start?: React.ReactNode; children?: React.ReactNode }) {
+ return (
+ <div className="flex flex-wrap items-center gap-2">
+ {start}
+ <div className="ml-auto flex flex-wrap justify-end gap-2">{children}</div>
+ </div>
+ );
+}
+
+function stepLabel(t: (key: string, options?: Record<string, unknown>) => string, step: RelayDeployLogEntry['step'], cleanupServer: string) {
+ return t(`${DEPLOY}.steps.${step}`, { server: cleanupServer });
+}
+
+/** 依次列出这次任务的步骤:进行中的一步下面写实时进展,失败的一步下面写原因,失败后不再列出没执行的步骤。 */
+function JobSteps({ job, cleanupServer }: { job: SelfHostedRelayDeployJobView; cleanupServer: string }) {
+ const { t } = useTranslation();
+ const steps = job.steps ?? (job.action === 'uninstall' ? RELAY_UNINSTALL_STEPS : RELAY_DEPLOY_STEPS);
+ const found = steps.indexOf(job.step);
+ const current = job.status === 'done' ? steps.length : found >= 0 ? found : job.step === 'finish' ? steps.length - 1 : 0;
+ const failed = job.status === 'failed';
+ const latest = job.logs?.at(-1);
+ const visible = failed ? steps.slice(0, current + 1) : steps;
+ return (
+ <ol className="flex flex-col gap-2">
+ {visible.map((step, index) => {
+ const tone: LineTone = index < current ? 'done' : index > current ? 'pending' : failed ? 'failed' : 'progress';
+ return (
+ <li key={step} aria-current={tone === 'progress' ? 'step' : undefined} className="flex items-start gap-2">
+ <LineIcon tone={tone} />
+ <div className="flex min-w-0 flex-1 flex-col gap-1">
+ <span
+ className={cn(
+ 'text-13 leading-5',
+ tone === 'pending' ? 'text-[var(--text-tertiary)]' : 'text-[var(--text-primary)]',
+ (tone === 'progress' || tone === 'failed') && 'font-medium',
+ )}
+ >
+ {stepLabel(t, step, cleanupServer)}
+ </span>
+ {tone === 'progress' && latest?.message && latest.step === step ? (
+ <p role="status" className="text-12 leading-[1.5] text-[var(--text-secondary)]">
+ {t(`${DEPLOY}.progress.${latest.message}`)}
+ </p>
+ ) : null}
+ {tone === 'failed' && job.error ? <FailureReason error={job.error} detail={job.detail} /> : null}
+ </div>
+ </li>
+ );
+ })}
+ </ol>
+ );
+}
+
+function JobLog({ job, cleanupServer }: { job: SelfHostedRelayDeployJobView; cleanupServer: string }) {
+ const { t } = useTranslation();
+ const logs = job.logs ?? [];
+ if (logs.length === 0) return null;
+ return (
+ <Disclosure label={t(`${DEPLOY}.logs`)}>
+ <ol className="flex max-h-40 select-text flex-col gap-1 overflow-y-auto text-[var(--text-secondary)]" aria-label={t(`${DEPLOY}.logs`)}>
+ {logs.map((entry, index) => (
+ <li key={`${entry.at}-${index}`} className="flex items-start gap-3 leading-[1.5]">
+ <span className="shrink-0 font-mono tabular-nums text-[var(--text-tertiary)]">
+ {formatDuration(Math.max(0, Math.floor((entry.at - (job.startedAt ?? entry.at)) / 1_000)))}
+ </span>
+ <span className="min-w-0 break-words">
+ {entry.message ? t(`${DEPLOY}.progress.${entry.message}`) : stepLabel(t, entry.step, cleanupServer)}
+ </span>
+ </li>
+ ))}
+ </ol>
+ </Disclosure>
+ );
+}
+
+/** 移除失败(服务器连不上、上面的中转不归这台电脑管)时的退路。 */
+function RemovalFallback({ controller }: { controller: SelfHostedRelayController }) {
+ const { t } = useTranslation();
+ const confirm = useConfirm();
+ return (
+ <Actions
+ start={
+ <Button
+ variant="secondary"
+ size="sm"
+ disabled={controller.busy}
+ onClick={() => {
+ void confirm(t(`${SERVER}.forgetTitle`), t(`${SERVER}.forgetDescription`), t(`${SERVER}.forget`)).then((ok) => {
+ if (ok) void controller.run({ type: 'forget-deployment' });
+ });
+ }}
+ >
+ {t(`${SERVER}.forget`)}
+ </Button>
+ }
+ >
+ <Button size="sm" disabled={controller.busy} onClick={() => void controller.run({ type: 'uninstall-deployment', removeData: true })}>
+ {t(`${DEPLOY}.retry`)}
+ </Button>
+ </Actions>
+ );
+}
+
+/** 选服务器后自动做只读检查;换服务器或点「重新检查」时重来,旧结果不会盖过新结果。 */
+function useServerCheck(sshHostId: string) {
+ const [result, setResult] = useState<SelfHostedRelayServerCheck | null>(null);
+ const [checking, setChecking] = useState(false);
+ const [attempt, setAttempt] = useState(0);
+ useEffect(() => {
+ const api = window.electronAPI?.selfHostedRelay;
+ if (!sshHostId || !api) return;
+ let active = true;
+ setChecking(true);
+ setResult(null);
+ void api
+ .command({ type: 'check-server', sshHostId })
+ .then((res) => {
+ if (active) setResult(res.check ?? { sshHostId, ok: false, error: res.error ?? 'FAILED' });
+ })
+ .catch(() => {
+ if (active) setResult({ sshHostId, ok: false, error: 'FAILED' });
+ })
+ .finally(() => {
+ if (active) setChecking(false);
+ });
+ return () => {
+ active = false;
+ };
+ }, [sshHostId, attempt]);
+ return { result, checking, recheck: () => setAttempt((value) => value + 1) };
+}
+
+function ServerCheckLine({
+ check,
+ checking,
+ cleanupServer,
+ onRecheck,
+}: {
+ check: SelfHostedRelayServerCheck | null;
+ checking: boolean;
+ cleanupServer: string | null;
+ onRecheck: () => void;
+}) {
+ const { t } = useTranslation();
+ const k = `${DEPLOY}.check`;
+ let tone: LineTone = 'progress';
+ let title = t(`${k}.checking`);
+ let meta: string | null = null;
+ let body: React.ReactNode = null;
+ if (!checking && check && !check.ok) {
+ tone = 'failed';
+ title = t(`${k}.blocked`);
+ body = <FailureReason error={check.error} detail={check.detail} />;
+ } else if (!checking && check?.ok) {
+ tone = check.existing === 'other' ? 'warning' : 'ok';
+ title = t(`${k}.ready`);
+ meta = check.system;
+ const notes = [t(`${k}.${check.plan}`)];
+ if (check.existing !== 'none') notes.push(t(`${k}.${check.existing}`));
+ if (cleanupServer) notes.push(t(`${k}.cleanup`, { server: cleanupServer }));
+ body = <p className="text-12 leading-[1.6] text-[var(--text-secondary)]">{notes.join(' ')}</p>;
+ }
+ return (
+ <div role="status" className="flex items-start gap-2">
+ <LineIcon tone={tone} />
+ <div className="flex min-w-0 flex-1 flex-col gap-0.5">
+ <p className="text-13 leading-5 text-[var(--text-primary)]">
+ {title}
+ {meta ? <span className="ml-2 text-12 text-[var(--text-tertiary)]">{meta}</span> : null}
+ </p>
+ {body}
+ </div>
+ {tone === 'failed' ? (
+ <Button variant="secondary" size="xs" compact onClick={onRecheck}>
+ {t(`${k}.recheck`)}
+ </Button>
+ ) : null}
+ </div>
+ );
+}
+
+function FieldRow({ label, hint, children }: { label: string; hint?: React.ReactNode; children: React.ReactNode }) {
+ return (
+ <div className="flex flex-col gap-1.5">
+ <div className="flex items-center justify-between gap-4">
+ <span className="text-13 text-[var(--text-primary)]">{label}</span>
+ <div className="w-60 min-w-0 shrink">{children}</div>
+ </div>
+ {hint}
+ </div>
+ );
+}
+
+const ROUTE = 'settings.remoteControl.relay.route';
+const DIALOG = 'settings.remoteControl.relay.dialog';
+const MANAGE = 'settings.remoteControl.relay.manage';
+
+/**
+ * 线路行右侧只放同样大小的图标,贴右对齐:切换在前,这条线路自己的操作(删除、设置)在后;
+ * 没有的不占位,只有一个图标时它就在最右边。正在用的线路用名字旁边的绿点表示,不进这一列。
+ */
+function RouteSide({ switchAction, action }: { switchAction?: React.ReactNode; action?: React.ReactNode }) {
+ return (
+ <>
+ {switchAction ? <span className="flex w-7 shrink-0 justify-center">{switchAction}</span> : null}
+ {action ? <span className="flex w-7 shrink-0 justify-center">{action}</span> : null}
+ </>
+ );
+}
+
+/** 正在用的线路:名字旁边一个绿点,悬停和读屏给出「正在使用」。 */
+function InUse() {
+ const { t } = useTranslation();
+ const label = t(`${SERVER}.inUse`);
+ return (
+ <Tip text={label}>
+ <span role="img" aria-label={label} className="inline-flex h-4 w-4 shrink-0 items-center justify-center">
+ <span aria-hidden className="h-2 w-2 rounded-full bg-[var(--status-success)]" />
+ </span>
+ </Tip>
+ );
+}
+
+/** 部署窗口顶部的步骤条:当前步实心,已完成打勾,后面的描边(DESIGN.md「Multi-step dialogs」)。 */
+function DialogSteps({ current }: { current: 0 | 1 | 2 }) {
+ const { t } = useTranslation();
+ const labels = [t(`${DIALOG}.steps.form`), t(`${DIALOG}.steps.deploy`), t(`${DIALOG}.steps.done`)];
+ return (
+ <ol className="flex flex-wrap items-center gap-1.5" aria-label={t(`${DIALOG}.steps.label`)}>
+ {labels.map((label, index) => (
+ <li key={label} className="flex items-center gap-1.5" aria-current={index === current ? 'step' : undefined}>
+ {index > 0 ? <span aria-hidden className="h-px w-3 bg-[var(--border-default)]" /> : null}
+ <span
+ aria-hidden
+ className={cn(
+ 'flex h-5 w-5 shrink-0 items-center justify-center rounded-full text-11 font-medium',
+ index < current && 'bg-[var(--surface-chip)] text-[var(--text-primary)]',
+ index === current && 'bg-[var(--accent-cta-bg)] text-[var(--surface-on-card)]',
+ index > current && 'border border-[var(--border-default)] text-[var(--text-tertiary)]',
+ )}
+ >
+ {index < current ? <Check size={11} /> : index + 1}
+ </span>
+ <span className={cn('text-12', index === current ? 'text-[var(--text-primary)]' : 'text-[var(--text-tertiary)]')}>
+ {label}
+ </span>
+ </li>
+ ))}
+ </ol>
+ );
+}
+
+/** 部署进度:按已完成的步骤数算,失败或完成时不显示。 */
+function DeployProgressBar({ job }: { job: SelfHostedRelayDeployJobView }) {
+ const steps = job.steps ?? RELAY_DEPLOY_STEPS;
+ const index = Math.max(0, steps.indexOf(job.step));
+ const percent = Math.round(((index + 0.5) / steps.length) * 100);
+ return (
+ <div
+ role="progressbar"
+ aria-valuemin={0}
+ aria-valuemax={100}
+ aria-valuenow={percent}
+ className="h-1 overflow-hidden rounded-full bg-[var(--surface-chip)]"
+ >
+ <div
+ className="h-full rounded-full bg-[var(--text-primary)] transition-[width] duration-300 motion-reduce:transition-none"
+ style={{ width: `${percent}%` }}
+ />
+ </div>
+ );
+}
+
+/** 第 1 步:选服务器后自动只读检查,检查通过才能开始。 */
+function DeployFormStep({
state,
controller,
- onDone,
+ hosts,
+ initial,
+ onCancel,
+ onAbandon,
+ onStarted,
}: {
state: SelfHostedRelayState;
controller: SelfHostedRelayController;
- onDone: () => void;
+ hosts: SshHostOption[] | null;
+ initial: DeployTarget | null;
+ onCancel: () => void;
+ onAbandon: (() => void) | null;
+ onStarted: () => void;
}) {
const { t } = useTranslation();
- const k = 'settings.remoteControl.relay.deploy';
- const hosts = useSshHosts(true);
- const previous = state.deployment;
- const [hostId, setHostId] = useState(previous?.sshHostId ?? '');
- const [address, setAddress] = useState(previous?.address ?? '');
- const [name, setName] = useState(previous?.name ?? t(`${k}.defaultName`));
- const [addressTouched, setAddressTouched] = useState(Boolean(previous));
-
- // 选服务器时,访问地址默认取 SSH 主机地址(是 IP 或域名时),用户可以改。
+ const [hostId, setHostId] = useState(initial?.sshHostId ?? '');
+ const [address, setAddress] = useState(initial?.address ?? '');
+ const [name, setName] = useState(initial?.name ?? t(`${DEPLOY}.defaultName`));
+ const [addressTouched, setAddressTouched] = useState(Boolean(initial));
+ const { result: check, checking, recheck } = useServerCheck(hostId);
+
+ // 不替用户预选服务器:选了才连接检查。选中后访问地址默认取 SSH 主机地址(是 IP 或域名时),用户可以改。
useEffect(() => {
- if (!hosts || hosts.length === 0) return;
- const selected = hosts.find((host) => host.id === hostId) ?? hosts[0];
- if (!hostId) setHostId(selected.id);
- if (!addressTouched) setAddress(normalizeRelayAddress(selected.hostname) ?? '');
+ const selected = hosts?.find((host) => host.id === hostId);
+ if (selected && !addressTouched) setAddress(normalizeRelayAddress(selected.hostname) ?? '');
}, [hosts, hostId, addressTouched]);
+ const deployment = state.deployment;
+ const cleanupServer = deployment && !deployment.relayVersion && deployment.sshHostId !== hostId
+ ? hostLabel(hosts, deployment.sshHostId)
+ : null;
const normalized = normalizeRelayAddress(address);
- const canSubmit = Boolean(hostId && normalized && name.trim()) && !controller.busy;
+ const ready = Boolean(!checking && check?.ok && check.sshHostId === hostId);
+ // 服务器上的中转不归这台电脑:检查结果里已用警示写明后果,按钮也直接叫「清除并部署」。
+ const replacing = Boolean(ready && check?.ok && check.existing === 'other');
+ const canSubmit = ready && Boolean(normalized && name.trim() && state.bundledRelayVersion) && !controller.busy;
+
+ const submit = async () => {
+ const ok = await controller.run({
+ type: 'deploy',
+ sshHostId: hostId,
+ address: normalized!,
+ name: name.trim(),
+ replaceExisting: replacing,
+ });
+ if (ok) onStarted();
+ };
+
return (
- <Card>
- <div className="flex flex-col gap-1">
- <p className="text-13 font-medium text-[var(--text-primary)]">{t(`${k}.title`)}</p>
- <Hint>{t(`${k}.hint`)}</Hint>
- <Hint>{t(`${k}.requirements`)}</Hint>
+ <>
+ <div className="flex flex-col gap-4 overflow-y-auto px-4 pb-4">
+ {hosts && hosts.length === 0 ? (
+ <Hint>{t(`${DEPLOY}.noHosts`)}</Hint>
+ ) : (
+ <>
+ <div className="flex flex-col gap-2">
+ <FieldRow label={t(`${DEPLOY}.server`)}>
+ <Select
+ label={t(`${DEPLOY}.serverPlaceholder`)}
+ value={hostId}
+ className="w-full"
+ truncateOptions
+ disabled={!hosts}
+ onValueChange={(value) => {
+ setHostId(value);
+ setAddressTouched(false);
+ }}
+ options={(hosts ?? []).map((host) => ({ value: host.id, label: hostOptionLabel(host) }))}
+ />
+ </FieldRow>
+ {hostId ? (
+ <div className="rounded-lg border border-[var(--border-default)] px-3 py-2.5">
+ <ServerCheckLine check={check} checking={checking} cleanupServer={cleanupServer} onRecheck={recheck} />
+ </div>
+ ) : null}
+ </div>
+ <FieldRow label={t(`${DEPLOY}.address`)} hint={<Hint>{t(`${DEPLOY}.addressHint`)}</Hint>}>
+ <Input
+ value={address}
+ onChange={(value) => {
+ setAddress(value);
+ setAddressTouched(true);
+ }}
+ placeholder={t(`${DEPLOY}.addressPlaceholder`)}
+ size="sm"
+ mono
+ className="w-full"
+ error={Boolean(address.trim()) && !normalized}
+ ariaLabel={t(`${DEPLOY}.address`)}
+ />
+ </FieldRow>
+ <FieldRow label={t(`${DEPLOY}.name`)}>
+ <Input value={name} onChange={setName} size="sm" className="w-full" ariaLabel={t(`${DEPLOY}.name`)} />
+ </FieldRow>
+ </>
+ )}
</div>
- {hosts && hosts.length === 0 ? (
- <Hint>{t(`${k}.noHosts`)}</Hint>
- ) : (
- <>
- <label className="flex items-center justify-between gap-4">
- <span className="text-13 text-[var(--text-primary)]">{t(`${k}.server`)}</span>
- <Select
- label={t(`${k}.server`)}
- value={hostId}
- className="w-56"
- truncateOptions
- disabled={!hosts}
- onValueChange={(value) => {
- setHostId(value);
- setAddressTouched(false);
- }}
- options={(hosts ?? []).map((host) => ({ value: host.id, label: host.label }))}
- />
- </label>
- <div className="flex flex-col gap-2">
- <span className="text-13 text-[var(--text-primary)]">{t(`${k}.address`)}</span>
- <Input
- value={address}
- onChange={(value) => {
- setAddress(value);
- setAddressTouched(true);
- }}
- placeholder={t(`${k}.addressPlaceholder`)}
- size="sm"
- mono
- error={Boolean(address.trim()) && !normalized}
- ariaLabel={t(`${k}.address`)}
- />
- <Hint>{t(`${k}.addressHint`)}</Hint>
- </div>
- <label className="flex items-center justify-between gap-4">
- <span className="text-13 text-[var(--text-primary)]">{t(`${k}.name`)}</span>
- <Input value={name} onChange={setName} size="sm" className="w-56" ariaLabel={t(`${k}.name`)} />
- </label>
- </>
- )}
- <div className="flex justify-end gap-2">
- <Button variant="secondary" size="sm" onClick={onDone} disabled={controller.busy}>
- {t(`${k}.cancel`)}
+ <DialogFooter
+ start={
+ onAbandon ? (
+ <Button variant="secondary" size="sm" disabled={controller.busy} onClick={onAbandon}>
+ {t(`${DEPLOY}.abandon`)}
+ </Button>
+ ) : null
+ }
+ >
+ <Button variant="secondary" size="sm" disabled={controller.busy} onClick={onCancel}>
+ {t(`${DEPLOY}.cancel`)}
</Button>
- <Button
- size="sm"
- disabled={!canSubmit}
- onClick={() => {
- void controller
- .run({ type: 'deploy', sshHostId: hostId, address: normalized!, name: name.trim(), replaceExisting: false })
- .then((ok) => {
- if (ok) onDone();
- });
- }}
- >
- {t(`${k}.submit`)}
+ <Button variant="cta" size="sm" disabled={!canSubmit} onClick={() => void submit()}>
+ {t(replacing ? `${DEPLOY}.submitReplace` : `${DEPLOY}.submit`)}
</Button>
- </div>
- </Card>
+ </DialogFooter>
+ </>
+ );
+}
+
+function DialogFooter({ start, children }: { start?: React.ReactNode; children?: React.ReactNode }) {
+ return (
+ <div className="flex flex-wrap items-center gap-2 border-t border-[var(--border-default)] px-4 py-3">
+ {start}
+ <div className="ml-auto flex flex-wrap justify-end gap-2">{children}</div>
+ </div>
);
}
-function DeployProgress({
- job,
+/**
+ * 部署窗口:选择服务器 → 部署 → 添加设备。关掉窗口部署照样在后台继续,线路列表里那一行显示进度;
+ * 失败时原因写在出错的那一步下面,可以重试、回到表单修改或放弃(清理服务器)。
+ */
+function DeployDialog({
+ open,
+ onOpenChange,
state,
controller,
+ hosts,
+ initial,
}: {
- job: SelfHostedRelayDeployJobView;
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
state: SelfHostedRelayState;
controller: SelfHostedRelayController;
+ hosts: SshHostOption[] | null;
+ initial: DeployTarget | null;
}) {
const { t } = useTranslation();
- const k = 'settings.remoteControl.relay.deploy';
- const steps = job.action === 'uninstall' ? (['connect', 'configure', 'finish'] as const) : RELAY_DEPLOY_STEPS;
- const currentIndex = steps.indexOf(job.step as (typeof steps)[number]);
+ const confirm = useConfirm();
+ // undefined:跟着部署任务显示;DeployTarget / null:回到表单(null 为空表单)。
+ const [editing, setEditing] = useState<DeployTarget | null | undefined>(undefined);
+ const job = state.deployJob?.action === 'deploy' ? state.deployJob : null;
+ const elapsed = useElapsed(job);
+ useEffect(() => {
+ if (open) setEditing(undefined);
+ }, [open]);
+
+ const view = editing !== undefined ? 'form' : job?.status === 'done' ? 'done' : job ? 'progress' : 'form';
const deployment = state.deployment;
- const retry = (replaceExisting: boolean) => {
- if (!deployment) return;
- void controller.run(
- job.action === 'upgrade' && !replaceExisting
- ? { type: 'upgrade-deployment' }
- : { type: 'deploy', sshHostId: deployment.sshHostId, address: deployment.address, name: deployment.name, replaceExisting },
- );
+ const incomplete = Boolean(deployment && !deployment.relayVersion);
+ const target = job?.target ?? deployment;
+ const close = () => onOpenChange(false);
+ // 确认框与本窗口同层,先关窗口再确认,确认框才不会被盖住。
+ const abandon = () => {
+ close();
+ void confirm(t(`${DEPLOY}.abandonTitle`), t(`${DEPLOY}.abandonDescription`), t(`${DEPLOY}.abandon`)).then((ok) => {
+ if (ok) void controller.run({ type: 'uninstall-deployment', removeData: true });
+ });
};
+ const finish = () => {
+ close();
+ void controller.run({ type: 'dismiss-deploy-job' });
+ };
+ const description =
+ view === 'form'
+ ? t(`${DEPLOY}.hint`)
+ : view === 'done'
+ ? t(`${DIALOG}.doneHint`)
+ : target
+ ? `${hostLabel(hosts, target.sshHostId)} · ${target.baseUrl}`
+ : '';
+
return (
- <Card>
- <p className="text-13 font-medium text-[var(--text-primary)]">
- {t(job.status === 'done' ? `${k}.done.${job.action}` : `${k}.running.${job.action}`, {
- version: state.bundledRelayVersion ?? '',
- })}
- </p>
- {job.status !== 'done' ? (
- <ol className="flex flex-col gap-1.5">
- {steps.map((step, index) => {
- const done = index < currentIndex || job.status === 'done';
- const current = index === currentIndex;
- const failed = current && job.status === 'failed';
- return (
- <li key={step} className="flex items-center gap-2 text-13">
- <span
- aria-hidden
- className={
- failed
- ? 'h-2 w-2 rounded-full bg-[var(--error-fg)]'
- : done
- ? 'h-2 w-2 rounded-full bg-[var(--text-secondary)]'
- : current
- ? 'h-2 w-2 rounded-full motion-safe:animate-pulse bg-[var(--text-primary)]'
- : 'h-2 w-2 rounded-full border border-[var(--border-default)]'
+ <Dialog.Root open={open} onOpenChange={onOpenChange}>
+ <Dialog.Portal>
+ <Dialog.Overlay className="modal-scrim fixed inset-0 z-[10000]" />
+ <Dialog.Content
+ onPointerDownOutside={(event) => event.preventDefault()}
+ className="modal-panel fixed left-1/2 top-1/2 z-[10001] flex max-h-[88vh] w-[min(600px,calc(100vw-32px))] -translate-x-1/2 -translate-y-1/2 flex-col outline-none"
+ >
+ <div className="flex flex-wrap items-center justify-between gap-x-4 gap-y-2 px-4 pb-3 pt-4">
+ <Dialog.Title className="text-16 font-semibold text-[var(--confirm-title)]">{t(`${DEPLOY}.title`)}</Dialog.Title>
+ <DialogSteps current={view === 'form' ? 0 : view === 'progress' ? 1 : 2} />
+ </div>
+ {view === 'form' ? (
+ <>
+ <Dialog.Description className="px-4 pb-4 text-12 leading-[1.5] text-[var(--text-tertiary)]">
+ {description}
+ </Dialog.Description>
+ <DeployFormStep
+ state={state}
+ controller={controller}
+ hosts={hosts}
+ initial={editing !== undefined ? editing : initial}
+ onCancel={() => (editing !== undefined && job ? setEditing(undefined) : close())}
+ onAbandon={incomplete ? abandon : null}
+ onStarted={() => setEditing(undefined)}
+ />
+ </>
+ ) : view === 'progress' && job ? (
+ <>
+ <div className="flex flex-col gap-4 overflow-y-auto px-4 pb-4">
+ <div className="flex flex-col gap-2">
+ <div className="flex items-baseline justify-between gap-3">
+ <p className="min-w-0 truncate text-13 font-medium text-[var(--text-primary)]">
+ {job.status === 'running'
+ ? t(`${DIALOG}.running`, { server: target ? hostLabel(hosts, target.sshHostId) : '' })
+ : t(`${DEPLOY}.failed.deploy`)}
+ </p>
+ {elapsed !== null ? (
+ <span className="shrink-0 text-12 tabular-nums text-[var(--text-tertiary)]">
+ {t(`${DEPLOY}.elapsed`, { time: formatDuration(elapsed) })}
+ </span>
+ ) : null}
+ </div>
+ <Dialog.Description className="truncate text-12 text-[var(--text-tertiary)]">{description}</Dialog.Description>
+ {job.status === 'running' ? <DeployProgressBar job={job} /> : null}
+ </div>
+ <JobSteps job={job} cleanupServer={deployment ? hostLabel(hosts, deployment.sshHostId) : ''} />
+ <JobLog job={job} cleanupServer={deployment ? hostLabel(hosts, deployment.sshHostId) : ''} />
+ </div>
+ {job.status === 'running' ? (
+ <DialogFooter start={<span className="text-12 text-[var(--text-tertiary)]">{t(`${DIALOG}.backgroundHint`)}</span>}>
+ <Button variant="secondary" size="sm" onClick={close}>
+ {t(`${DIALOG}.background`)}
+ </Button>
+ </DialogFooter>
+ ) : (
+ <DialogFooter
+ start={
+ deployment ? (
+ <Button variant="secondary" size="sm" disabled={controller.busy} onClick={abandon}>
+ {t(`${DEPLOY}.abandon`)}
+ </Button>
+ ) : (
+ <Button variant="secondary" size="sm" disabled={controller.busy} onClick={finish}>
+ {t(`${DEPLOY}.cancel`)}
+ </Button>
+ )
}
- />
- <span className={done || current ? 'text-[var(--text-primary)]' : 'text-[var(--text-tertiary)]'}>
- {t(`${k}.steps.${job.action === 'uninstall' && step === 'configure' ? 'remove' : step}`)}
- </span>
- </li>
- );
- })}
- </ol>
- ) : null}
- {job.status === 'failed' && job.error ? (
- <div className="flex flex-col gap-1">
- <ErrorText>{t(`settings.remoteControl.relay.errors.${job.error}`)}</ErrorText>
- {job.detail ? <Hint>{t(`${k}.detail`, { detail: job.detail })}</Hint> : null}
+ >
+ <Button
+ variant="secondary"
+ size="sm"
+ disabled={controller.busy || !target}
+ onClick={() => target && setEditing({ sshHostId: target.sshHostId, address: target.address, name: target.name })}
+ >
+ {t(`${DEPLOY}.edit`)}
+ </Button>
+ <Button
+ variant="cta"
+ size="sm"
+ disabled={controller.busy || !target || !state.bundledRelayVersion}
+ onClick={() =>
+ target &&
+ void controller.run({
+ type: 'deploy',
+ sshHostId: target.sshHostId,
+ address: target.address,
+ name: target.name,
+ replaceExisting: false,
+ })
+ }
+ >
+ {t(`${DEPLOY}.retry`)}
+ </Button>
+ </DialogFooter>
+ )}
+ </>
+ ) : (
+ <>
+ <div className="flex flex-col gap-4 overflow-y-auto px-4 pb-4">
+ <div className="flex items-center gap-3">
+ <span
+ aria-hidden
+ className="flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-[color-mix(in_srgb,var(--status-success)_14%,transparent)] text-[var(--status-success)]"
+ >
+ <Check size={18} />
+ </span>
+ <div className="flex min-w-0 flex-col gap-0.5">
+ <p className="truncate text-14 font-medium text-[var(--text-primary)]">
+ {t(`${DIALOG}.doneTitle`, { name: target?.name ?? '' })}
+ </p>
+ <Dialog.Description className="text-12 leading-[1.5] text-[var(--text-secondary)]">
+ {description}
+ </Dialog.Description>
+ </div>
+ </div>
+ <div className="rounded-xl border border-[var(--border-default)] p-3">
+ <AddDevice state={state} controller={controller} bare autoCreate />
+ </div>
+ </div>
+ <DialogFooter start={<span className="text-12 text-[var(--text-tertiary)]">{t(`${DIALOG}.doneLater`)}</span>}>
+ <Button variant="cta" size="sm" onClick={finish}>
+ {t(`${DIALOG}.finish`)}
+ </Button>
+ </DialogFooter>
+ </>
+ )}
+ </Dialog.Content>
+ </Dialog.Portal>
+ </Dialog.Root>
+ );
+}
+
+/**
+ * 服务器中转的实时状态:进入页面时读一次,之后每分钟刷新;刷新时保留上一次结果,不闪空。
+ * 查询本身失败(例如主进程还是旧版本)不等于服务器连不上:这时不下结论,不显示状态。
+ */
+function useDeploymentStatus(enabled: boolean) {
+ const [status, setStatus] = useState<SelfHostedRelayDeploymentStatus | null>(null);
+ const [checking, setChecking] = useState(false);
+ const [attempt, setAttempt] = useState(0);
+ useEffect(() => {
+ const api = window.electronAPI?.selfHostedRelay;
+ if (!enabled || !api) {
+ setStatus(null);
+ return;
+ }
+ let active = true;
+ setChecking(true);
+ void api
+ .command({ type: 'deployment-status' })
+ .then((res) => {
+ if (active && res.deploymentStatus) setStatus(res.deploymentStatus);
+ })
+ .catch(() => undefined)
+ .finally(() => {
+ if (active) setChecking(false);
+ });
+ return () => {
+ active = false;
+ };
+ }, [enabled, attempt]);
+ useEffect(() => {
+ if (!enabled) return;
+ const timer = setInterval(() => setAttempt((value) => value + 1), DEPLOYMENT_STATUS_POLL_MS);
+ return () => clearInterval(timer);
+ }, [enabled]);
+ return { status, checking, refresh: () => setAttempt((value) => value + 1) };
+}
+
+const DEPLOYMENT_STATUS_POLL_MS = 60_000;
+
+function StatusLabel({ status, checking }: { status: SelfHostedRelayDeploymentStatus | null; checking: boolean }) {
+ const { t } = useTranslation();
+ if (!status) return checking ? <span className="text-[var(--text-tertiary)]">{t(`${ROUTE}.statusChecking`)}</span> : null;
+ return (
+ <span className={cn('inline-flex items-center gap-1.5', checking && 'opacity-70')}>
+ <span
+ aria-hidden
+ className={cn('h-1.5 w-1.5 rounded-full', status.online ? 'bg-[var(--status-success)]' : 'bg-[var(--error-fg)]')}
+ />
+ {t(status.online ? `${ROUTE}.statusOnline` : `${ROUTE}.statusOffline`)}
+ </span>
+ );
+}
+
+/**
+ * 线路列表的一行:左边单选标记,选中的那一行就是正在用的线路。
+ * 选中的那一行在名字旁边写「正在使用」;右侧(`RouteSide`)与标题同一行、统一 28px 高、贴右对齐;
+ * 这条线路的详情直接放在说明下面,不另起卡片。
+ */
+function RouteRow({
+ selected,
+ icon,
+ title,
+ tag,
+ hint,
+ side,
+ children,
+}: {
+ selected: boolean;
+ icon: React.ReactNode;
+ title: string;
+ tag?: string | null;
+ hint?: React.ReactNode;
+ side?: React.ReactNode;
+ children?: React.ReactNode;
+}) {
+ return (
+ <li
+ aria-current={selected ? 'true' : undefined}
+ className={cn('flex items-start gap-3 px-4 py-3', selected && 'bg-[color-mix(in_srgb,var(--text-primary)_3%,transparent)]')}
+ >
+ <span
+ aria-hidden
+ className={cn(
+ 'mt-1.5 flex h-4 w-4 shrink-0 items-center justify-center rounded-full border-[1.5px]',
+ selected ? 'border-[var(--text-primary)]' : 'border-[var(--text-tertiary)]',
+ )}
+ >
+ {selected ? <span className="h-2 w-2 rounded-full bg-[var(--text-primary)]" /> : null}
+ </span>
+ <div className="flex min-w-0 flex-1 flex-col">
+ <div className="flex min-h-7 items-center justify-between gap-3">
+ <div className="flex min-w-0 items-center gap-2">
+ <span aria-hidden className="shrink-0 text-[var(--text-tertiary)]">{icon}</span>
+ <span className="truncate text-13 font-medium text-[var(--text-primary)]">{title}</span>
+ {tag ? (
+ <span className="shrink-0 rounded-full border border-[var(--border-default)] px-1.5 text-11 leading-[18px] text-[var(--text-secondary)]">
+ {tag}
+ </span>
+ ) : null}
+ {selected ? <InUse /> : null}
+ </div>
+ {side ? <div className="flex h-7 shrink-0 items-center gap-1">{side}</div> : null}
</div>
- ) : null}
- {job.status === 'failed' && job.action !== 'uninstall' && deployment ? (
- <div className="flex flex-wrap justify-end gap-2">
- {job.error === 'RELAY_MISMATCH' ? (
- <Button variant="secondary" size="sm" disabled={controller.busy} onClick={() => retry(true)}>
- {t(`${k}.replace`)}
- </Button>
- ) : null}
- <Button size="sm" disabled={controller.busy} onClick={() => retry(false)}>
- {t(`${k}.retry`)}
+ {hint ? <div className="min-w-0 text-12 leading-[1.5] text-[var(--text-secondary)]">{hint}</div> : null}
+ {children ? <div className="mt-3">{children}</div> : null}
+ </div>
+ </li>
+ );
+}
+
+/** 升级或移除服务器中转时的进度与失败处理。 */
+function TaskPanel({ job, controller }: { job: SelfHostedRelayDeployJobView; controller: SelfHostedRelayController }) {
+ const { t } = useTranslation();
+ const elapsed = useElapsed(job);
+ const running = job.status === 'running';
+ return (
+ <div className="flex flex-col gap-3">
+ <CardHeader
+ title={t(`${DEPLOY}.${running ? 'running' : 'failed'}.${job.action}`)}
+ trailing={elapsed !== null ? t(`${DEPLOY}.elapsed`, { time: formatDuration(elapsed) }) : null}
+ />
+ <JobSteps job={job} cleanupServer="" />
+ <JobLog job={job} cleanupServer="" />
+ {running ? null : job.action === 'uninstall' ? (
+ <RemovalFallback controller={controller} />
+ ) : (
+ <Actions>
+ <Button size="sm" disabled={controller.busy} onClick={() => void controller.run({ type: 'upgrade-deployment' })}>
+ {t(`${DEPLOY}.retry`)}
</Button>
- </div>
- ) : null}
- </Card>
+ </Actions>
+ )}
+ </div>
);
}
-function DeploymentCard({ state, controller }: { state: SelfHostedRelayState; controller: SelfHostedRelayController }) {
+function Stat({ label, value, sub }: { label: string; value: React.ReactNode; sub?: React.ReactNode }) {
+ return (
+ <div className="flex min-w-0 flex-col gap-0.5 px-3 py-2.5">
+ <dt className="text-11 text-[var(--text-tertiary)]">{label}</dt>
+ <dd className="break-words text-13 font-medium text-[var(--text-primary)]">{value}</dd>
+ {sub ? <dd className="break-words text-11 text-[var(--text-tertiary)]">{sub}</dd> : null}
+ </div>
+ );
+}
+
+const DAY_MS = 24 * 60 * 60 * 1000;
+
+/** 只有图标的操作:按 DESIGN.md §14.6 同时给可见 Tip 和无障碍名称。 */
+function IconAction({
+ label,
+ disabled,
+ onClick,
+ children,
+}: {
+ label: string;
+ disabled?: boolean;
+ onClick: () => void;
+ children: React.ReactNode;
+}) {
+ return (
+ <Tip text={label}>
+ <Button
+ variant="secondary"
+ tone="quiet"
+ size="sm"
+ className="w-7 px-0"
+ aria-label={label}
+ disabled={disabled}
+ onClick={onClick}
+ >
+ {children}
+ </Button>
+ </Tip>
+ );
+}
+
+/** 正在用的服务器中转的详情:状态用数字说话(设备、证书、版本),下面就是添加设备。 */
+function ServerDetails({
+ state,
+ controller,
+ status,
+}: {
+ state: SelfHostedRelayState;
+ controller: SelfHostedRelayController;
+ status: SelfHostedRelayDeploymentStatus | null;
+}) {
const { t } = useTranslation();
- const confirmDialog = useOptionalConfirmDialog();
const deployment = state.deployment!;
- const running = state.deployJob?.status === 'running';
- const k = 'settings.remoteControl.relay.server';
- const confirm = async (title: string, description: string, confirmText: string) =>
- !confirmDialog || (await confirmDialog.confirm({ title, description, confirmText, confirmVariant: 'destructive' }));
+ const job = state.deployJob;
+ const task = job && job.action !== 'deploy' && job.status !== 'done' ? job : null;
+ const busy = controller.busy || job?.status === 'running';
+ const expiresAt = status?.certificateExpiresAt ? Date.parse(status.certificateExpiresAt) : NaN;
+ const daysLeft = Number.isFinite(expiresAt) ? Math.max(0, Math.ceil((expiresAt - Date.now()) / DAY_MS)) : null;
return (
- <Card>
- <div className="flex items-center justify-between gap-4">
- <div className="flex min-w-0 flex-col gap-1">
- <p className="text-12 text-[var(--text-tertiary)]">{t(`${k}.title`)}</p>
- <p className="truncate text-13 font-medium text-[var(--text-primary)]">{deployment.name}</p>
- <p className="truncate font-mono text-12 text-[var(--text-tertiary)]">{deployment.baseUrl}</p>
- <Hint>
- {deployment.relayVersion ? t(`${k}.version`, { version: deployment.relayVersion }) : t(`${k}.incomplete`)}
- </Hint>
+ <div className="overflow-hidden rounded-lg border border-[var(--border-default)]">
+ {status && !status.online ? (
+ <div className="border-b border-[var(--border-default)] px-3 py-2.5">
+ <ErrorText>{t(`${MANAGE}.offline`)}</ErrorText>
</div>
- {!deployment.active && deployment.relayVersion ? (
- <Button size="sm" disabled={controller.busy || running} onClick={() => void controller.run({ type: 'use-deployment' })}>
- {t('settings.remoteControl.relay.actions.useDeployment')}
- </Button>
- ) : null}
- </div>
- <div className="flex flex-wrap justify-end gap-2">
- {!deployment.relayVersion && !state.deployJob ? (
- <Button
- size="sm"
- disabled={controller.busy || running || !state.bundledRelayVersion}
- onClick={() => void controller.run({ type: 'deploy', sshHostId: deployment.sshHostId, address: deployment.address, name: deployment.name, replaceExisting: false })}
- >
- {t('settings.remoteControl.relay.deploy.retry')}
- </Button>
- ) : null}
- {deployment.upgradeAvailable ? (
- <Button
- variant="secondary"
- size="sm"
- disabled={controller.busy || running}
- onClick={() => void controller.run({ type: 'upgrade-deployment' })}
- >
- {t(`${k}.upgrade`, { version: state.bundledRelayVersion ?? '' })}
- </Button>
- ) : null}
- <Button
- variant="secondary"
- size="sm"
- disabled={controller.busy || running}
- onClick={() => {
- void confirm(t(`${k}.forgetTitle`), t(`${k}.forgetDescription`), t(`${k}.forget`)).then((ok) => {
- if (ok) void controller.run({ type: 'forget-deployment' });
- });
- }}
- >
- {t(`${k}.forget`)}
- </Button>
- <Button
- variant="secondary"
- size="sm"
- disabled={controller.busy || running}
- onClick={() => {
- void confirm(t(`${k}.uninstallTitle`), t(`${k}.uninstallDescription`), t(`${k}.uninstall`)).then((ok) => {
- if (ok) void controller.run({ type: 'uninstall-deployment', removeData: true });
- });
- }}
- >
- {t(`${k}.uninstall`)}
- </Button>
+ ) : null}
+ <dl className="grid grid-cols-3 divide-x divide-[var(--border-default)]">
+ <Stat
+ label={t(`${MANAGE}.devices`)}
+ value={status?.devices !== undefined ? t(`${MANAGE}.deviceCount`, { count: status.devices }) : '—'}
+ sub={status?.onlineDevices !== undefined ? t(`${MANAGE}.onlineCount`, { count: status.onlineDevices }) : null}
+ />
+ <Stat
+ label={t(`${MANAGE}.certificate`)}
+ value={
+ !status?.online
+ ? '—'
+ : daysLeft !== null
+ ? t(`${MANAGE}.certificateDays`, { count: daysLeft })
+ : t(`${MANAGE}.certificateSite`)
+ }
+ sub={status?.online && daysLeft !== null ? t(`${MANAGE}.certificateRenew`) : null}
+ />
+ <Stat
+ label={t(`${MANAGE}.version`)}
+ value={deployment.relayVersion}
+ sub={
+ deployment.upgradeAvailable ? (
+ <Button
+ variant="secondary"
+ size="xs"
+ compact
+ className="mt-1"
+ disabled={busy}
+ onClick={() => void controller.run({ type: 'upgrade-deployment' })}
+ >
+ {t(`${SERVER}.upgrade`, { version: state.bundledRelayVersion ?? '' })}
+ </Button>
+ ) : (
+ t(`${MANAGE}.latest`)
+ )
+ }
+ />
+ </dl>
+ <div className="border-t border-[var(--border-default)] px-3 py-3">
+ {task ? <TaskPanel job={task} controller={controller} /> : <AddDevice state={state} controller={controller} bare />}
</div>
- </Card>
+ </div>
);
}
+/**
+ * 「连接线路」:所有线路是一个单选列表,选中的那条就是正在用的。切换线路都先确认;
+ * 正在用的那条在自己那一行里展开详情(服务器中转的设备数、证书、添加设备;这台电脑当中转的加入链接)。
+ */
export function RelayServicePanel({ controller }: { controller: SelfHostedRelayController }) {
const { t } = useTranslation();
const confirmDialog = useOptionalConfirmDialog();
- const [form, setForm] = useState<'none' | 'host' | 'join' | 'deploy'>('none');
+ const confirm = useConfirm();
+ const [form, setForm] = useState<'none' | 'host' | 'join'>('none');
+ const [deployOpen, setDeployOpen] = useState(false);
+ const [deployInitial, setDeployInitial] = useState<DeployTarget | null>(null);
const { state, error } = controller;
+ const hosts = useSshHosts(Boolean(state?.available), deployOpen);
const k = 'settings.remoteControl.relay';
+ const job = state?.deployJob ?? null;
+ const previousJobStatus = useRef(job?.status);
+ const complete = Boolean(state?.deployment?.relayVersion);
+ const serverActive = Boolean(complete && state?.deployment?.active);
+ const deploymentStatus = useDeploymentStatus(Boolean(state?.available && serverActive));
- // 加入成功后收起表单(main 已切换中转)。
+ // 移除完成后这一行随之消失,用一条提示说明结果。
+ useEffect(() => {
+ if (previousJobStatus.current === 'running' && job?.status === 'done' && job.action === 'uninstall') {
+ toast.success(t(`${DEPLOY}.done.uninstall`));
+ }
+ previousJobStatus.current = job?.status;
+ }, [job?.status, job?.action, t]);
+
+ // 加入成功后关掉窗口(main 已切换中转)。
useEffect(() => {
if (state?.join.status === 'joined' && form === 'join') setForm('none');
}, [state?.join.status, form]);
@@ -670,12 +1491,15 @@ export function RelayServicePanel({ controller }: { controller: SelfHostedRelayC
}
const relay = state.relay;
+ const deployment = state.deployment;
const isHost = relay?.origin === 'host';
const isServer = relay?.origin === 'server';
- const isOwner = relay?.role === 'owner';
- const currentLabel = !relay ? t(`${k}.summary.official`) : isHost ? t(`${k}.ownerName`) : relay.name;
+ const isMember = relay?.origin === 'join';
+ const deploying = job?.action === 'deploy' && job.status === 'running';
+ const deployFailed = job?.action === 'deploy' && job.status === 'failed';
+ const removing = job?.action === 'uninstall' && job.status === 'running';
const confirmKey = isHost ? 'owner' : isServer ? 'server' : 'member';
- const job = state.deployJob;
+ const busy = controller.busy || job?.status === 'running';
const switchToOfficial = async () => {
const ok = !confirmDialog || (await confirmDialog.confirm({
@@ -689,23 +1513,206 @@ export function RelayServicePanel({ controller }: { controller: SelfHostedRelayC
await controller.run({ type: 'use-official' });
}
};
+ // 切换到服务器中转前先确认,并说清楚原线路会怎样。
+ const switchToDeployment = async () => {
+ if (!deployment) return;
+ const ok = !confirmDialog || (await confirmDialog.confirm({
+ title: t(`${ROUTE}.switchTitle`, { name: deployment.name }),
+ description: t(
+ isHost ? `${ROUTE}.switchFromHost` : isMember ? `${ROUTE}.switchFromMember` : `${ROUTE}.switchFromOfficial`,
+ { name: isMember ? relay?.name ?? '' : deployment.name },
+ ),
+ confirmText: t(`${ROUTE}.switchConfirm`),
+ confirmVariant: isHost ? 'destructive' : 'default',
+ }));
+ if (!ok) return;
+ setForm('none');
+ await controller.run({ type: 'use-deployment' });
+ };
+ const removeDeployment = () => {
+ void confirm(t(`${SERVER}.removeTitle`), t(`${SERVER}.removeDescription`), t(`${SERVER}.remove`)).then((ok) => {
+ if (ok) void controller.run({ type: 'uninstall-deployment', removeData: true });
+ });
+ };
+ const openDeploy = (initial: DeployTarget | null) => {
+ controller.clearError();
+ setForm('none');
+ setDeployInitial(initial);
+ setDeployOpen(true);
+ };
+ const openForm = (next: 'host' | 'join') => {
+ controller.clearError();
+ setForm(next);
+ };
+ const closeForm = () => {
+ controller.clearError();
+ setForm('none');
+ };
+ // 等待主人同意时关窗口,就撤回这次加入申请。
+ const closeJoin = () => {
+ if (state.join.status === 'connecting' || state.join.status === 'waiting') void controller.run({ type: 'cancel-join' });
+ closeForm();
+ };
+ const switchAction = (name: string, onClick: () => void) => (
+ <IconAction label={t(`${ROUTE}.useNamed`, { name })} disabled={busy} onClick={onClick}>
+ <ArrowRightLeft aria-hidden size={14} />
+ </IconAction>
+ );
+
+ const serverTitle = job?.action === 'deploy' && job.target ? job.target.name : deployment?.name ?? '';
+ const serverHint = deploying ? (
+ <span className="inline-flex items-center gap-1.5">
+ <Spinner size={12} />
+ {t(`${ROUTE}.deployingStep`, { step: stepLabel(t, job?.step ?? 'check', deployment ? hostLabel(hosts, deployment.sshHostId) : '') })}
+ </span>
+ ) : removing ? (
+ <span className="inline-flex items-center gap-1.5">
+ <Spinner size={12} />
+ {t(`${DEPLOY}.running.uninstall`)}
+ </span>
+ ) : !complete ? (
+ t(`${DEPLOY}.failed.deploy`)
+ ) : deployment ? (
+ <span className="flex min-w-0 flex-wrap items-center gap-x-1.5">
+ <span className="truncate">
+ {hostLabel(hosts, deployment.sshHostId)} · <span className="font-mono">{deployment.address}</span>
+ </span>
+ {serverActive && (deploymentStatus.status || deploymentStatus.checking) ? (
+ <>
+ <span aria-hidden>·</span>
+ <StatusLabel status={deploymentStatus.status} checking={deploymentStatus.checking} />
+ <IconAction label={t(`${MANAGE}.check`)} disabled={deploymentStatus.checking} onClick={deploymentStatus.refresh}>
+ <RefreshCw aria-hidden size={12} className={cn(deploymentStatus.checking && 'animate-spin motion-reduce:animate-none')} />
+ </IconAction>
+ </>
+ ) : null}
+ </span>
+ ) : null;
+ const serverSide = deploying ? (
+ <Button variant="secondary" size="sm" onClick={() => openDeploy(null)}>
+ {t(`${ROUTE}.viewProgress`)}
+ </Button>
+ ) : removing ? null : !complete ? (
+ <Button
+ variant="secondary"
+ size="sm"
+ disabled={busy}
+ onClick={() =>
+ openDeploy(deployFailed && job?.target ? null : deployment ? { sshHostId: deployment.sshHostId, address: deployment.address, name: deployment.name } : null)
+ }
+ >
+ {t(`${ROUTE}.resume`)}
+ </Button>
+ ) : (
+ <RouteSide
+ switchAction={deployment?.active ? null : switchAction(deployment?.name ?? '', () => void switchToDeployment())}
+ action={
+ <IconAction label={t(`${MANAGE}.remove`)} disabled={busy} onClick={removeDeployment}>
+ <Trash2 aria-hidden size={14} />
+ </IconAction>
+ }
+ />
+ );
+ const serverTask = job && job.action !== 'deploy' && job.status === 'failed' ? job : null;
+ const showAddRow = (!deployment && !deploying && !deployFailed) || !relay;
return (
- <div className="flex flex-col gap-3">
- <Hint>{t(`${k}.description`)}</Hint>
- <Card>
- <div className="flex items-center justify-between gap-4">
- <div className="flex min-w-0 flex-col gap-1">
- <p className="text-12 text-[var(--text-tertiary)]">{t(`${k}.current`)}</p>
- <p className="truncate text-13 font-medium text-[var(--text-primary)]">{currentLabel}</p>
- {relay ? <p className="truncate font-mono text-12 text-[var(--text-tertiary)]">{relay.baseUrl}</p> : null}
- </div>
- {relay ? (
- <Button variant="secondary" size="sm" disabled={controller.busy} onClick={() => void switchToOfficial()}>
- {t(`${k}.actions.useOfficial`)}
- </Button>
+ <div className="flex flex-col gap-4">
+ <div className="flex flex-col gap-2">
+ <ul className="flex flex-col divide-y divide-[var(--border-default)] overflow-hidden rounded-xl bg-[var(--settings-input-bg)]">
+ <RouteRow
+ selected={!relay}
+ icon={<Cloud size={15} />}
+ title={t(`${k}.summary.official`)}
+ tag={t(`${ROUTE}.defaultTag`)}
+ hint={t(`${ROUTE}.officialHint`)}
+ side={<RouteSide switchAction={relay ? switchAction(t(`${k}.summary.official`), () => void switchToOfficial()) : null} />}
+ />
+ {deployment || deploying || deployFailed ? (
+ <RouteRow
+ selected={Boolean(isServer && deployment?.active)}
+ icon={<Server size={15} />}
+ title={serverTitle}
+ tag={t(`${ROUTE}.kindServer`)}
+ hint={serverHint}
+ side={serverSide}
+ >
+ {serverActive && !removing ? (
+ <ServerDetails state={state} controller={controller} status={deploymentStatus.status} />
+ ) : serverTask ? (
+ <div className="rounded-lg border border-[var(--border-default)] px-3 py-3">
+ <TaskPanel job={serverTask} controller={controller} />
+ </div>
+ ) : null}
+ </RouteRow>
) : null}
- </div>
+ <RouteRow
+ selected={isHost}
+ icon={<Monitor size={15} />}
+ title={t(`${ROUTE}.hostTitle`)}
+ hint={
+ isHost && state.host.running
+ ? t(`${k}.host.running`, {
+ address: state.host.externalUrl ?? state.host.suggestedUrls[0] ?? `127.0.0.1:${state.host.port}`,
+ })
+ : t(`${ROUTE}.hostHint`)
+ }
+ side={
+ <RouteSide
+ // 这台电脑当中转要先填端口等设置,切换就是打开设置窗口,在窗口里点「开启」。
+ switchAction={isHost ? null : switchAction(t(`${ROUTE}.hostTitle`), () => openForm('host'))}
+ action={
+ isHost ? (
+ <IconAction label={t(`${k}.actions.editHost`)} onClick={() => openForm('host')}>
+ <Settings2 aria-hidden size={14} />
+ </IconAction>
+ ) : null
+ }
+ />
+ }
+ >
+ {isHost && state.host.running ? (
+ <div className="rounded-lg border border-[var(--border-default)] px-3 py-3">
+ <AddDevice state={state} controller={controller} bare />
+ </div>
+ ) : null}
+ </RouteRow>
+ {isMember && relay ? (
+ <RouteRow
+ selected
+ icon={<Link2 size={15} />}
+ title={relay.name}
+ tag={t(`${ROUTE}.kindJoined`)}
+ hint={<span className="font-mono">{relay.baseUrl}</span>}
+ side={<RouteSide />}
+ />
+ ) : null}
+ {showAddRow ? (
+ <li className="px-4 py-2">
+ <div className="-mx-3 flex flex-wrap items-center gap-1">
+ {!deployment && !deploying && !deployFailed ? (
+ <Button
+ variant="secondary"
+ size="sm"
+ tone="quiet"
+ compact
+ disabled={!state.bundledRelayVersion || busy}
+ onClick={() => openDeploy(null)}
+ >
+ <Plus aria-hidden size={13} />
+ {t(`${k}.actions.deploy`)}
+ </Button>
+ ) : null}
+ {!relay ? (
+ <Button variant="secondary" size="sm" tone="quiet" compact disabled={busy} onClick={() => openForm('join')}>
+ <Link2 aria-hidden size={13} />
+ {t(`${k}.actions.join`)}
+ </Button>
+ ) : null}
+ </div>
+ </li>
+ ) : null}
+ </ul>
{state.issue ? (
<ErrorText>
{t(`${k}.issue.${state.issue}`)} {t(`${k}.issue.next`)}
@@ -714,76 +1721,39 @@ export function RelayServicePanel({ controller }: { controller: SelfHostedRelayC
{isHost && state.host.error ? (
<ErrorText>{t(`${k}.errors.${state.host.error}`, { port: state.host.port })}</ErrorText>
) : null}
- {isHost && state.host.running ? (
- <>
- <Hint>
- {t(`${k}.host.running`, {
- address: state.host.externalUrl ?? state.host.suggestedUrls[0] ?? `127.0.0.1:${state.host.port}`,
- })}
- </Hint>
- <AddDevice state={state} controller={controller} />
- </>
- ) : null}
- {isServer ? <AddDevice state={state} controller={controller} /> : null}
- {relay ? <Hint>{t(`${k}.limits`)}</Hint> : null}
- {!relay && form === 'none' ? (
- <div className="flex flex-wrap justify-end gap-2">
- <Button variant="secondary" size="sm" onClick={() => setForm('join')}>
- {t(`${k}.actions.join`)}
- </Button>
- <Button variant="secondary" size="sm" onClick={() => setForm('host')}>
- {t(`${k}.actions.host`)}
- </Button>
- {!state.deployment ? (
- <Button size="sm" disabled={!state.bundledRelayVersion} onClick={() => setForm('deploy')}>
- {t(`${k}.actions.deploy`)}
- </Button>
- ) : null}
- </div>
- ) : null}
- {isHost && form === 'none' ? (
- <div className="flex justify-end">
- <Button variant="secondary" size="sm" onClick={() => setForm('host')}>
- {t(`${k}.actions.editHost`)}
- </Button>
- </div>
- ) : null}
- </Card>
- {error && error !== 'CANCELLED' ? (
- <ErrorText>{t(`${k}.errors.${error}`, { port: state.host.port })}</ErrorText>
+ <p className="flex items-start gap-2 text-12 leading-[1.5] text-[var(--text-tertiary)]">
+ <Info aria-hidden size={13} className="mt-0.5 shrink-0" />
+ {t(`${k}.limits`)}
+ </p>
+ </div>
+ {/* 窗口里的命令失败写在窗口里,这里只显示列表上的操作(切换、移除等)出的错。 */}
+ {form === 'none' && error && error !== 'CANCELLED' ? (
+ <ErrorText>{t(`${k}.errors.${error}`, { port: state.host.port, detail: '' })}</ErrorText>
) : null}
- {form === 'host' ? (
+ <FormDialog
+ open={form === 'host'}
+ onClose={closeForm}
+ title={isHost ? t(`${ROUTE}.hostTitle`) : t(`${k}.host.title`)}
+ description={t(`${k}.host.hint`)}
+ >
<HostForm
state={state}
controller={controller}
- onDone={() => {
- controller.clearError();
- setForm('none');
- }}
- />
- ) : null}
- {job && (job.status !== 'done' || form === 'none') ? <DeployProgress job={job} state={state} controller={controller} /> : null}
- {state.deployment && form !== 'deploy' ? <DeploymentCard state={state} controller={controller} /> : null}
- {form === 'deploy' ? (
- <DeployForm
- state={state}
- controller={controller}
- onDone={() => {
- controller.clearError();
- setForm('none');
- }}
+ notice={!isHost && isMember ? t(`${ROUTE}.switchFromMember`, { name: relay?.name ?? '' }) : null}
+ onDone={closeForm}
/>
- ) : null}
- {form === 'join' ? (
- <JoinForm
- state={state}
- controller={controller}
- onDone={() => {
- controller.clearError();
- setForm('none');
- }}
- />
- ) : null}
+ </FormDialog>
+ <FormDialog open={form === 'join'} onClose={closeJoin} title={t(`${k}.join.title`)} description={t(`${k}.join.hint`)}>
+ <JoinForm state={state} controller={controller} onClose={closeJoin} />
+ </FormDialog>
+ <DeployDialog
+ open={deployOpen}
+ onOpenChange={setDeployOpen}
+ state={state}
+ controller={controller}
+ hosts={hosts}
+ initial={deployInitial}
+ />
</div>
);
}
diff --git a/apps/desktop/src/renderer/components/settings/RemoteControlSection.settings-search.ts b/apps/desktop/src/renderer/components/settings/RemoteControlSection.settings-search.ts
index 67d1039d31..13cc8cd615 100644
--- a/apps/desktop/src/renderer/components/settings/RemoteControlSection.settings-search.ts
+++ b/apps/desktop/src/renderer/components/settings/RemoteControlSection.settings-search.ts
@@ -5,7 +5,7 @@ export default {
id: 'remote-control',
order: 2,
entries: [
- { id: 'remoteControl.relay', isVisible: ({ mode }) => mode === 'cloud', tab: 'remote-control', targetId: 'settings-search-target-remote-relay', titleKey: 'settings.remoteControl.sections.relay', sectionKey: 'settings.sections.remoteControl', aliases: ['relay', 'self-hosted relay', '中转', '自建中转'] },
+ { id: 'remoteControl.relay', isVisible: ({ mode }) => mode === 'cloud', tab: 'remote-control', targetId: 'settings-search-target-remote-relay', titleKey: 'settings.remoteControl.relay.route.title', sectionKey: 'settings.sections.remoteControl', aliases: ['relay', 'self-hosted relay', 'connection route', '中转', '自建中转', '中转服务', '连接线路'] },
{ id: 'remoteControl.devices', isVisible: ({ mode }) => mode === 'cloud', tab: 'remote-control', targetId: 'settings-search-target-remote-devices', titleKey: 'settings.remoteControl.sections.myDevices', sectionKey: 'settings.sections.remoteControl', aliases: ['device link', 'devices', '设备互联', '我的设备'] },
{ id: 'remoteControl.ssh', tab: 'remote-control', targetId: 'settings-search-target-remote-ssh', titleKey: 'settings.remoteControl.sections.ssh', sectionKey: 'settings.sections.remoteControl', aliases: ['SSH', 'SSH host', 'SSH hosts', 'SSH主机', 'remote host', '远程主机', '主机'] },
{ id: 'remoteControl', tab: 'remote-control', targetId: 'settings-panel-remote-control', titleKey: 'settings.tabs.remoteControl', sectionKey: 'settings.sections.remoteControl' },
diff --git a/apps/desktop/src/renderer/components/settings/RemoteControlSection.tsx b/apps/desktop/src/renderer/components/settings/RemoteControlSection.tsx
index cbcee03e05..b5ca0f1112 100644
--- a/apps/desktop/src/renderer/components/settings/RemoteControlSection.tsx
+++ b/apps/desktop/src/renderer/components/settings/RemoteControlSection.tsx
@@ -24,7 +24,7 @@ import { ChevronDown, ChevronRight } from 'lucide-react';
import { useDeviceLinkSettings, type DeviceLinkSettings } from '@/hooks/useDeviceLinkSettings';
import { MyDevicesPanel } from './MyDevicesPanel';
-import { RelayServicePanel, relaySummary, useSelfHostedRelayState } from './RelayServicePanel';
+import { RelayServicePanel, useSelfHostedRelayState } from './RelayServicePanel';
import { RemoteDesktopSetting } from './RemoteDesktopSetting';
import { RemoteSection } from './RemoteSection';
import { useAuth } from '@/contexts/AuthContext';
@@ -167,9 +167,6 @@ export function RemoteControlSection() {
// 再把下方内容顶开一格。
const [devicesOpen, setDevicesOpen] = useState(() => isDevicesSection(location.search));
const relay = useSelfHostedRelayState(deviceLinkAvailable);
- const [relayOpen, setRelayOpen] = useState(
- () => new URLSearchParams(location.search).get('section') === 'remoteControl.relay',
- );
const [sshOpen, setSshOpen] = useState(
() => new URLSearchParams(location.search).get('section') === 'remoteControl.ssh',
);
@@ -190,7 +187,6 @@ export function RemoteControlSection() {
useLayoutEffect(() => {
if (entry?.targetId === 'settings-search-target-remote-ssh') setSshOpen(true);
if (entry?.targetId === 'settings-search-target-remote-devices') setDevicesOpen(true);
- if (entry?.targetId === 'settings-search-target-remote-relay') setRelayOpen(true);
}, [entry, activation]);
const collapseRequestedRef = useRef(false);
@@ -298,17 +294,18 @@ export function RemoteControlSection() {
focusRequestKey={focusRequestKey}
/>
</CollapsibleSubSection>
- <div className="h-px w-full bg-[var(--border-default)]" />
- <CollapsibleSubSection
- id="settings-search-target-remote-relay"
- title={t('settings.remoteControl.sections.relay')}
- summary={relaySummary(relay.state, t)}
- dotColor={null}
- open={relayOpen}
- onToggle={() => setRelayOpen((value) => !value)}
- >
+ {/* 设备之间经哪条线路连接:紧跟在「我的设备」下面直接展示,当前线路一眼可见,不再单独占一个入口。 */}
+ <section id="settings-search-target-remote-relay" className="flex flex-col gap-3">
+ <div className="flex flex-col gap-0.5">
+ <h3 className="text-14 font-medium text-[var(--text-primary)]">
+ {t('settings.remoteControl.relay.route.title')}
+ </h3>
+ <p className="text-12 leading-[1.5] text-[var(--text-tertiary)]">
+ {t('settings.remoteControl.relay.route.hint')}
+ </p>
+ </div>
<RelayServicePanel controller={relay} />
- </CollapsibleSubSection>
+ </section>
<div className="h-px w-full bg-[var(--border-default)]" />
</>
) : null}
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index faf727c8df..1bb96cd5c6 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -5602,10 +5602,7 @@
"remoteControl": {
"relay": {
"summary": {
- "official": "Cindy relay",
- "owner": "This computer is the relay",
- "member": "Joined {{name}}",
- "server": "Server relay \"{{name}}\""
+ "official": "Cindy relay"
},
"description": "Remote control between your devices goes through the Cindy relay by default. You can instead deploy a relay to your own server, run one on this computer, or join a relay on another computer of yours. Sign-in, models and other services are not affected.",
"current": "In use",
@@ -5613,12 +5610,10 @@
"unavailable": "To use your own relay, sign in to Cindy and make sure the system keychain is available.",
"limits": "While you use your own relay, phone push notifications, provider sharing and shared tasks are unavailable.",
"actions": {
- "host": "Run on this computer",
"join": "Join another relay",
"useOfficial": "Switch back to Cindy relay",
"editHost": "Change settings",
- "deploy": "Deploy to my server",
- "useDeployment": "Use this relay"
+ "deploy": "Deploy to my server"
},
"host": {
"title": "Run a relay on this computer",
@@ -5699,13 +5694,16 @@
"START_FAILED": "The relay couldn't start. Try another port.",
"EXTERNAL_URL_REQUIRED": "Enter the address other devices use, or set Who can connect to Any network.",
"SSH_FAILED": "Can't connect to the server. Check its SSH settings under Remote.",
+ "SHELL_UNAVAILABLE": "This SSH account can't run commands (for example, a Git service's git account), so it can't be used for deployment. Choose a server you can log in to with a shell.",
"NEEDS_ROOT": "This needs the root account, or an account that can use sudo without a password. Cindy never asks for your server password.",
"UNSUPPORTED_SYSTEM": "Only 64-bit Linux with systemd (x64 / arm64) is supported, and curl or wget must be installed.",
- "PORT_BUSY": "Another service is using port 80 or 443 and can't be configured automatically. Existing Nginx is handled automatically; check other services using these ports.",
+ "PORT_BUSY": "Port 80 or 443 on the server is in use by {{detail}}. Cindy won't stop other programs. Choose another server, or stop it and check again.",
+ "PORT_BUSY_CONTAINER": "Port 80 or 443 on the server is used by the Docker container {{detail}}. Cindy can only configure Nginx installed directly on the system, not inside a container. Choose another server.",
"NGINX_FAILED": "Nginx configuration couldn't be completed, so deployment stopped. See the details for the reason.",
"DOWNLOAD_FAILED": "The server couldn't download the runtime from the official source or the mirror. Check that the server can reach the internet.",
- "RELAY_MISMATCH": "This server already has a relay that wasn't deployed from this computer. You can remove it and redeploy.",
+ "RELAY_MISMATCH": "The relay on this server wasn't deployed from this computer, so Cindy leaves it alone.",
"CERTIFICATE_FAILED": "Couldn't get an HTTPS certificate. Usually port 80 isn't allowed in the cloud security group, or the domain doesn't point to this server yet. Fix that, then retry.",
+ "CA_UNREACHABLE": "The server couldn't reach the certificate authority Let's Encrypt, even after retrying for a few minutes. Check that the server can reach the internet, then try again later.",
"NOT_REACHABLE": "The relay is running on the server, but this computer can't reach it. Allow port 443 in the cloud security group.",
"BUNDLE_MISSING": "This version of Cindy doesn't include the relay. Update Cindy.",
"DEPLOY_FAILED": "Deployment didn't complete.",
@@ -5718,10 +5716,10 @@
},
"deploy": {
"title": "Deploy to my server",
- "hint": "Install the relay on your own Linux server so your phone and devices on other networks can connect. Cindy installs it over the SSH connection set up under Remote, gets an HTTPS certificate and renews it automatically.",
- "requirements": "Requires 64-bit Linux with systemd, root or passwordless sudo, and TCP 80 and 443 allowed in your cloud security group or firewall. Cindy automatically checks and configures existing Nginx.",
+ "hint": "Install the relay on your own Linux server so your phone and devices on other networks can connect. Cindy installs it over the SSH connection set up under Remote and gets and renews an HTTPS certificate automatically. Allow TCP 80 and 443 in your cloud security group.",
"noHosts": "No servers yet. Add an SSH host under Remote, then come back to deploy.",
"server": "Server",
+ "serverPlaceholder": "Choose a server",
"address": "Address",
"addressPlaceholder": "Public IP or domain, e.g. 203.0.113.10",
"addressHint": "The address other devices use to reach the relay. A public IP gets a 6-day IP certificate that renews automatically; a domain must already point to this server.",
@@ -5729,9 +5727,27 @@
"defaultName": "My relay",
"submit": "Deploy",
"cancel": "Cancel",
- "detail": "Details: {{detail}}",
"retry": "Retry",
- "replace": "Remove the old relay and redeploy",
+ "submitReplace": "Remove and Deploy",
+ "edit": "Edit Settings",
+ "abandon": "Discard Deployment",
+ "abandonTitle": "Discard this deployment?",
+ "abandonDescription": "What was already installed on the server is cleaned up, and the deployment record on this computer is deleted.",
+ "replaceTitle": "Remove the relay on this server?",
+ "replaceDescription": "The relay on this server wasn't deployed from this computer. Deploying deletes it and its device records, and devices that joined it need to join again.",
+ "incompleteHint": "The last deployment didn't finish. Retry, or edit the settings and deploy again.",
+ "showDetails": "Show Details",
+ "check": {
+ "checking": "Checking the server…",
+ "ready": "Ready to deploy",
+ "blocked": "Can't deploy automatically",
+ "recheck": "Check Again",
+ "direct": "Ports 80 and 443 are free, so the relay uses them directly.",
+ "nginx": "The relay connects through the server's existing Nginx and keeps your current sites.",
+ "mine": "This server already runs a relay deployed from this computer. It is updated in place, and joined devices are not affected.",
+ "other": "This server runs a relay that wasn't deployed from this computer. Deploying removes it, and devices that joined it need to join again.",
+ "cleanup": "The unfinished deployment on {{server}} is cleaned up first."
+ },
"running": {
"deploy": "Deploying to your server…",
"upgrade": "Upgrading the relay on your server…",
@@ -5740,11 +5756,31 @@
"done": {
"deploy": "Deployed. This computer now uses the relay on your server. Use Add device to bring in your phone and other computers.",
"upgrade": "The relay on your server is now version {{version}}.",
- "uninstall": "The relay was removed from your server."
+ "uninstall": "Relay removed from your server"
+ },
+ "failed": {
+ "deploy": "Deployment did not complete",
+ "upgrade": "Upgrade did not complete",
+ "uninstall": "Removal did not complete"
+ },
+ "elapsed": "Elapsed {{time}}",
+ "logs": "Deployment log",
+ "progress": {
+ "runtime-cached": "The runtime is ready. No download needed.",
+ "runtime-download": "Downloading the runtime. Speed depends on the server's network…",
+ "runtime-fallback": "The current download source is unavailable. Trying the backup…",
+ "runtime-checksum": "Download complete. Verifying the file…",
+ "runtime-extract": "File verified. Extracting and installing the runtime…",
+ "nginx-prepare": "Nginx detected. Setting up relay access…",
+ "certificate-wait": "Waiting for the certificate. This may take a few minutes…",
+ "certificate-retry": "Can't reach the certificate authority right now. Retrying automatically…",
+ "verify-retry": "The relay is not reachable yet. Checking again…",
+ "nginx-rollback": "Deployment did not complete. Restoring the previous Nginx configuration…"
},
"steps": {
+ "cleanup": "Clean up {{server}}",
"connect": "Connect to the server",
- "check": "Check the system and ports",
+ "check": "Check the server",
"runtime": "Install the runtime",
"upload": "Upload the relay",
"configure": "Configure and start the service",
@@ -5755,16 +5791,68 @@
}
},
"server": {
- "title": "My server relay",
- "version": "Relay version {{version}}",
- "incomplete": "The last deployment didn't finish. Retry or uninstall.",
+ "inUse": "In use",
"upgrade": "Upgrade to {{version}}",
- "uninstall": "Uninstall from server",
- "uninstallTitle": "Uninstall the relay from your server?",
- "uninstallDescription": "The relay and its device records are deleted from the server, and devices using it disconnect. If you deploy again, every device needs to join again.",
+ "remove": "Remove",
+ "removeTitle": "Remove the server relay?",
+ "removeDescription": "The relay and its device records are deleted from the server, and devices using it disconnect. If you deploy again, every device needs to join again.",
"forget": "Remove from this computer only",
"forgetTitle": "Remove from this computer only?",
"forgetDescription": "The relay keeps running on the server, but this computer stops managing it and can't add devices to it anymore. Do this only if you no longer use that server."
+ },
+ "route": {
+ "title": "Connection Route",
+ "hint": "Remote control between your devices goes through this route",
+ "kindServer": "My server",
+ "kindJoined": "Joined",
+ "hostTitle": "This computer as relay",
+ "hostHint": "Other devices must be able to reach this computer directly. They disconnect when it sleeps or Cindy quits",
+ "officialHint": "No setup needed. Every feature works",
+ "defaultTag": "Default",
+ "useNamed": "Switch to {{name}}",
+ "deployingStep": "{{step}}…",
+ "viewProgress": "View Progress",
+ "resume": "Resume Deployment",
+ "statusChecking": "Checking…",
+ "statusOnline": "Online",
+ "statusOffline": "Unreachable",
+ "switchTitle": "Switch to {{name}}?",
+ "switchFromHost": "The relay on this computer stops, and devices that joined it disconnect.",
+ "switchFromMember": "This computer leaves {{name}}. To join again later, its owner needs to create a new join link.",
+ "switchConfirm": "Switch",
+ "switchFromOfficial": "Remote control between your devices will go through {{name}}. Phone push notifications, provider sharing, and shared tasks aren't available while you use your own relay."
+ },
+ "dialog": {
+ "steps": {
+ "label": "Deployment steps",
+ "form": "Choose Server",
+ "deploy": "Deploy",
+ "done": "Add Devices"
+ },
+ "running": "Deploying to {{server}}…",
+ "backgroundHint": "Closing this window doesn't stop the deployment",
+ "background": "Continue in Background",
+ "doneTitle": "{{name}} is ready",
+ "doneHint": "This computer now uses it. Scan with your phone, or send the link to another computer to join.",
+ "doneLater": "You can also add devices later under Connection Route",
+ "finish": "Done"
+ },
+ "manage": {
+ "check": "Check Connection",
+ "offline": "This computer can't reach this relay right now. This happens when the server is off or its network or security group changed. Fix it, then check the connection again.",
+ "devices": "Joined devices",
+ "deviceCount_one": "{{count}} device",
+ "deviceCount_other": "{{count}} devices",
+ "onlineCount_one": "{{count}} online",
+ "onlineCount_other": "{{count}} online",
+ "certificate": "HTTPS certificate",
+ "certificateDays_one": "Expires in {{count}} day",
+ "certificateDays_other": "Expires in {{count}} days",
+ "certificateRenew": "Renews automatically",
+ "certificateSite": "Uses the site's certificate",
+ "version": "Relay version",
+ "latest": "Up to date",
+ "remove": "Remove This Relay"
}
},
"title": "Remote Connection",
@@ -5786,7 +5874,6 @@
"restoreFailed": "Failed to restore access"
},
"sections": {
- "relay": "Relay service",
"myDevices": "My devices",
"ssh": "SSH remote hosts",
"hook": "Cindy IM bots"
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 5a4d6f62b2..c404924534 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -5570,10 +5570,7 @@
"remoteControl": {
"relay": {
"summary": {
- "official": "Cindy 公式リレー",
- "owner": "このコンピュータがリレー",
- "member": "{{name}} に参加中",
- "server": "サーバーのリレー「{{name}}」"
+ "official": "Cindy 公式リレー"
},
"description": "デバイス間のリモート操作は、既定では Cindy 公式リレーを経由します。リレーを自分のサーバーにデプロイしたり、このコンピュータをリレーにしたり、自分の別のコンピュータ上のリレーに参加したりすることもできます。サインインやモデルなど他のサービスには影響しません。",
"current": "使用中",
@@ -5581,12 +5578,10 @@
"unavailable": "自分のリレーを使うには、Cindy にサインインし、システムのキーチェーンが使える必要があります。",
"limits": "自分のリレーを使っている間は、スマホのプッシュ通知、プロバイダー共有、共有タスクは使えません。",
"actions": {
- "host": "このコンピュータで開始",
"join": "別のリレーに参加",
"useOfficial": "公式リレーに戻す",
"editHost": "設定を変更",
- "deploy": "自分のサーバーにデプロイ",
- "useDeployment": "このリレーを使う"
+ "deploy": "自分のサーバーにデプロイ"
},
"host": {
"title": "このコンピュータでリレーを開始",
@@ -5667,13 +5662,16 @@
"START_FAILED": "リレーを開始できませんでした。別のポートでお試しください。",
"EXTERNAL_URL_REQUIRED": "他のデバイスが使うアドレスを入力するか、「接続を許可する範囲」をすべてのネットワークにしてください。",
"SSH_FAILED": "サーバーに接続できません。「リモート」でこのサーバーの SSH 設定を確認してください。",
+ "SHELL_UNAVAILABLE": "この SSH アカウントではコマンドを実行できません(Git サービスの git アカウントなど)。デプロイには使えないため、シェルにログインできるサーバーを選んでください。",
"NEEDS_ROOT": "root アカウント、またはパスワードなしで sudo を使えるアカウントが必要です。Cindy がサーバーのパスワードを求めることはありません。",
"UNSUPPORTED_SYSTEM": "対応しているのは systemd のある 64 ビット Linux(x64 / arm64)のみで、curl または wget が必要です。",
- "PORT_BUSY": "ポート 80 または 443 を使用中のサービスに自動接続できません。既存の Nginx は自動で設定されます。ほかにポートを使用しているサービスを確認してください。",
+ "PORT_BUSY": "サーバーのポート 80/443 は {{detail}} が使用しています。Cindy はほかのプログラムを停止しません。別のサーバーを選ぶか、停止してから再確認してください。",
+ "PORT_BUSY_CONTAINER": "サーバーのポート 80/443 は Docker コンテナ {{detail}} が使用しています。Cindy が自動設定できるのはシステムに直接インストールされた Nginx だけで、コンテナ内の設定は変更できません。別のサーバーを選んでください。",
"NGINX_FAILED": "Nginx の設定を完了できなかったため、デプロイを停止しました。詳しい理由を確認してください。",
"DOWNLOAD_FAILED": "サーバーが実行環境をダウンロードできませんでした(公式ソースとミラーの両方で失敗)。サーバーがインターネットに接続できるか確認してください。",
- "RELAY_MISMATCH": "このサーバーには、このコンピュータ以外からデプロイされたリレーがあります。削除して再デプロイできます。",
+ "RELAY_MISMATCH": "このサーバーのリレーはこのコンピュータからデプロイしたものではないため、Cindy は変更しません。",
"CERTIFICATE_FAILED": "HTTPS 証明書を取得できませんでした。多くの場合、クラウドのセキュリティグループで 80 ポートが許可されていないか、ドメインがまだこのサーバーを指していません。対処してから再試行してください。",
+ "CA_UNREACHABLE": "サーバーが証明書発行機関 Let's Encrypt に接続できず、数分間自動で再試行しても成功しませんでした。サーバーがインターネットに接続できるか確認し、しばらくしてから再試行してください。",
"NOT_REACHABLE": "サーバーのリレーは動作していますが、このコンピュータから接続できません。クラウドのセキュリティグループで 443 ポートを許可してください。",
"BUNDLE_MISSING": "このバージョンの Cindy にはリレーが含まれていません。Cindy を更新してください。",
"DEPLOY_FAILED": "デプロイを完了できませんでした。",
@@ -5686,10 +5684,10 @@
},
"deploy": {
"title": "自分のサーバーにデプロイ",
- "hint": "リレーを自分の Linux サーバーにインストールすると、スマホや別のネットワークのデバイスからも接続できます。Cindy は「リモート」で設定した SSH 接続でインストールし、HTTPS 証明書を自動で取得・更新します。",
- "requirements": "systemd のある 64 ビット Linux、root またはパスワードなしの sudo、クラウドのセキュリティグループやファイアウォールでの TCP 80 と 443 の許可が必要です。既存の Nginx は Cindy が自動で確認・設定します。",
+ "hint": "リレーを自分の Linux サーバーにインストールすると、スマホや別のネットワークのデバイスからも接続できます。Cindy は「リモート」で設定した SSH 接続でインストールし、HTTPS 証明書を自動で取得・更新します。クラウドのセキュリティグループで TCP 80 と 443 を許可してください。",
"noHosts": "使えるサーバーがまだありません。「リモート」で SSH ホストを追加してから戻ってきてください。",
"server": "サーバー",
+ "serverPlaceholder": "サーバーを選択",
"address": "アクセス用アドレス",
"addressPlaceholder": "グローバル IP またはドメイン(例:203.0.113.10)",
"addressHint": "他のデバイスがリレーに接続するアドレスです。グローバル IP なら有効期間 6 日で自動更新される IP 証明書を取得します。ドメインの場合は、先にこのサーバーを指すよう DNS を設定してください。",
@@ -5697,9 +5695,27 @@
"defaultName": "マイリレー",
"submit": "デプロイ",
"cancel": "キャンセル",
- "detail": "詳細:{{detail}}",
"retry": "再試行",
- "replace": "古いリレーを削除して再デプロイ",
+ "submitReplace": "削除してデプロイ",
+ "edit": "設定を変更",
+ "abandon": "デプロイを中止",
+ "abandonTitle": "このデプロイを中止しますか?",
+ "abandonDescription": "サーバーにインストール済みの部分を片付け、このコンピュータ上のデプロイ記録も削除します。",
+ "replaceTitle": "サーバーのリレーを削除しますか?",
+ "replaceDescription": "このサーバーのリレーはこのコンピュータからデプロイしたものではありません。デプロイを続けるとリレーとデバイス情報が削除され、参加していたデバイスは再参加が必要です。",
+ "incompleteHint": "前回のデプロイは完了していません。再試行するか、設定を変更してデプロイし直してください。",
+ "showDetails": "詳細を表示",
+ "check": {
+ "checking": "サーバーを確認しています…",
+ "ready": "デプロイできます",
+ "blocked": "自動ではデプロイできません",
+ "recheck": "再確認",
+ "direct": "ポート 80 と 443 が空いているため、リレーが直接使用します。",
+ "nginx": "サーバーの既存の Nginx 経由で接続し、既存のサイトはそのまま残します。",
+ "mine": "このコンピュータからデプロイしたリレーがすでにあります。その場で更新し、参加済みのデバイスには影響しません。",
+ "other": "このコンピュータ以外からデプロイされたリレーがあります。デプロイすると削除され、そのリレーに参加していたデバイスは再参加が必要です。",
+ "cleanup": "先に {{server}} の未完了のデプロイを片付けます。"
+ },
"running": {
"deploy": "サーバーにデプロイしています…",
"upgrade": "サーバーのリレーを更新しています…",
@@ -5708,11 +5724,31 @@
"done": {
"deploy": "デプロイが完了し、このコンピュータはサーバーのリレーを使うようになりました。「デバイスを追加」でスマホや他のコンピュータを参加させてください。",
"upgrade": "サーバーのリレーを {{version}} に更新しました。",
- "uninstall": "サーバーからリレーを削除しました。"
+ "uninstall": "サーバーからリレーを削除しました"
+ },
+ "failed": {
+ "deploy": "デプロイが完了しませんでした",
+ "upgrade": "更新が完了しませんでした",
+ "uninstall": "削除が完了しませんでした"
+ },
+ "elapsed": "経過時間 {{time}}",
+ "logs": "デプロイログ",
+ "progress": {
+ "runtime-cached": "実行環境は準備済みです。再ダウンロードは不要です。",
+ "runtime-download": "実行環境をダウンロード中です。速度はサーバーのネットワークに依存します…",
+ "runtime-fallback": "現在のダウンロード元を利用できません。別の配信元を試しています…",
+ "runtime-checksum": "ダウンロードが完了しました。ファイルを検証中…",
+ "runtime-extract": "検証が完了しました。実行環境を展開してインストール中…",
+ "nginx-prepare": "Nginx を検出しました。リレーへの接続を設定中…",
+ "certificate-wait": "証明書の発行を待っています。数分かかる場合があります…",
+ "certificate-retry": "証明書発行機関に一時的に接続できません。自動で再試行しています…",
+ "verify-retry": "まだリレーに接続できません。再確認しています…",
+ "nginx-rollback": "デプロイが完了しませんでした。元の Nginx 設定を復元中…"
},
"steps": {
+ "cleanup": "{{server}} を片付け",
"connect": "サーバーに接続",
- "check": "システムとポートを確認",
+ "check": "サーバーを確認",
"runtime": "実行環境をインストール",
"upload": "リレーをアップロード",
"configure": "サービスを設定して起動",
@@ -5723,16 +5759,68 @@
}
},
"server": {
- "title": "自分のサーバーのリレー",
- "version": "リレーのバージョン {{version}}",
- "incomplete": "前回のデプロイは完了していません。再試行するか削除してください。",
+ "inUse": "使用中",
"upgrade": "{{version}} に更新",
- "uninstall": "サーバーから削除",
- "uninstallTitle": "サーバーからリレーを削除しますか?",
- "uninstallDescription": "サーバー上のリレーとデバイス情報が削除され、使用中のデバイスは切断されます。再デプロイした場合、すべてのデバイスが再参加する必要があります。",
+ "remove": "削除",
+ "removeTitle": "サーバーのリレーを削除しますか?",
+ "removeDescription": "サーバー上のリレーとデバイス情報が削除され、使用中のデバイスは切断されます。再デプロイした場合、すべてのデバイスが再参加する必要があります。",
"forget": "このコンピュータからのみ削除",
"forgetTitle": "このコンピュータからのみ削除しますか?",
"forgetDescription": "サーバー上のリレーは削除されませんが、このコンピュータでは管理できなくなり、デバイスも追加できなくなります。そのサーバーを使わなくなった場合にのみ行ってください。"
+ },
+ "route": {
+ "title": "接続経路",
+ "hint": "デバイス間のリモート操作はこの経路で中継されます",
+ "kindServer": "自分のサーバー",
+ "kindJoined": "参加中",
+ "hostTitle": "このコンピュータをリレーにする",
+ "hostHint": "ほかのデバイスからこのコンピュータに直接アクセスできる必要があります。スリープや Cindy の終了で切断されます",
+ "officialHint": "設定不要で、すべての機能を使えます",
+ "defaultTag": "既定",
+ "useNamed": "「{{name}}」に切り替え",
+ "deployingStep": "{{step}}…",
+ "viewProgress": "進行状況を見る",
+ "resume": "デプロイを続ける",
+ "statusChecking": "確認しています…",
+ "statusOnline": "オンライン",
+ "statusOffline": "接続できません",
+ "switchTitle": "「{{name}}」に切り替えますか?",
+ "switchFromHost": "このコンピュータのリレーは停止し、参加しているデバイスは切断されます。",
+ "switchFromMember": "このコンピュータは「{{name}}」から退出します。再参加するには、相手に新しい参加リンクを作ってもらう必要があります。",
+ "switchConfirm": "切り替える",
+ "switchFromOfficial": "デバイス間のリモート操作は「{{name}}」経由になります。自分のリレーを使っている間は、スマホのシステム通知、プロバイダーの共有、共有タスクは使えません。"
+ },
+ "dialog": {
+ "steps": {
+ "label": "デプロイの手順",
+ "form": "サーバーを選択",
+ "deploy": "デプロイ",
+ "done": "デバイスを追加"
+ },
+ "running": "{{server}} にデプロイしています…",
+ "backgroundHint": "ウィンドウを閉じてもデプロイは続きます",
+ "background": "バックグラウンドで続ける",
+ "doneTitle": "「{{name}}」のデプロイが完了しました",
+ "doneHint": "このコンピュータはこのリレーを使うようになりました。スマホでスキャンするか、リンクを別のコンピュータに送って参加させてください。",
+ "doneLater": "あとから「接続経路」でもデバイスを追加できます",
+ "finish": "完了"
+ },
+ "manage": {
+ "check": "接続を確認",
+ "offline": "このコンピュータは現在このリレーに接続できません。サーバーの停止や、ネットワーク・セキュリティグループの変更で起こります。対処してから「接続を確認」を押してください。",
+ "devices": "参加済みデバイス",
+ "deviceCount_one": "{{count}} 台",
+ "deviceCount_other": "{{count}} 台",
+ "onlineCount_one": "{{count}} 台がオンライン",
+ "onlineCount_other": "{{count}} 台がオンライン",
+ "certificate": "HTTPS 証明書",
+ "certificateDays_one": "{{count}} 日後に期限切れ",
+ "certificateDays_other": "{{count}} 日後に期限切れ",
+ "certificateRenew": "自動で更新されます",
+ "certificateSite": "サイトの証明書を使用",
+ "version": "リレーのバージョン",
+ "latest": "最新",
+ "remove": "このリレーを削除"
}
},
"title": "リモート接続",
@@ -5754,7 +5842,6 @@
"restoreFailed": "復元に失敗しました"
},
"sections": {
- "relay": "リレーサービス",
"myDevices": "マイデバイス",
"ssh": "SSH リモートホスト",
"hook": "Cindy IM ボット"
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index cc54e26c25..6d2416733b 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -5570,10 +5570,7 @@
"remoteControl": {
"relay": {
"summary": {
- "official": "Cindy 공식 중계",
- "owner": "이 컴퓨터가 중계",
- "member": "{{name}}에 참여함",
- "server": "서버 중계 \"{{name}}\""
+ "official": "Cindy 공식 중계"
},
"description": "기기 간 원격 제어는 기본적으로 Cindy 공식 중계를 거칩니다. 중계를 내 서버에 배포하거나, 이 컴퓨터를 중계로 쓰거나, 내 다른 컴퓨터의 중계에 참여할 수도 있습니다. 로그인, 모델 등 다른 서비스에는 영향이 없습니다.",
"current": "사용 중",
@@ -5581,12 +5578,10 @@
"unavailable": "내 중계를 사용하려면 Cindy에 로그인하고 시스템 키체인을 사용할 수 있어야 합니다.",
"limits": "내 중계를 사용하는 동안에는 휴대폰 푸시 알림, 제공자 공유, 공유 작업을 사용할 수 없습니다.",
"actions": {
- "host": "이 컴퓨터에서 시작",
"join": "다른 중계에 참여",
"useOfficial": "공식 중계로 돌아가기",
"editHost": "설정 변경",
- "deploy": "내 서버에 배포",
- "useDeployment": "이 중계 사용"
+ "deploy": "내 서버에 배포"
},
"host": {
"title": "이 컴퓨터에서 중계 시작",
@@ -5667,13 +5662,16 @@
"START_FAILED": "중계를 시작하지 못했습니다. 다른 포트로 시도해 보세요.",
"EXTERNAL_URL_REQUIRED": "다른 기기가 사용할 주소를 입력하거나 '연결 허용 범위'를 모든 네트워크로 바꾸세요.",
"SSH_FAILED": "서버에 연결할 수 없습니다. 원격에서 이 서버의 SSH 설정을 확인하세요.",
+ "SHELL_UNAVAILABLE": "이 SSH 계정으로는 명령을 실행할 수 없습니다(예: Git 서비스의 git 계정). 배포에 사용할 수 없으니 셸에 로그인할 수 있는 서버를 선택하세요.",
"NEEDS_ROOT": "root 계정이나 암호 없이 sudo를 쓸 수 있는 계정이 필요합니다. Cindy는 서버 암호를 묻지 않습니다.",
"UNSUPPORTED_SYSTEM": "systemd가 있는 64비트 Linux(x64 / arm64)만 지원하며, curl 또는 wget이 필요합니다.",
- "PORT_BUSY": "80 또는 443 포트를 사용하는 서비스에 자동으로 연결할 수 없습니다. 기존 Nginx는 자동으로 설정됩니다. 해당 포트를 사용하는 다른 서비스를 확인하세요.",
+ "PORT_BUSY": "서버의 80/443 포트를 {{detail}}이(가) 사용 중입니다. Cindy는 다른 프로그램을 중지하지 않습니다. 다른 서버를 선택하거나, 해당 프로그램을 중지한 뒤 다시 확인하세요.",
+ "PORT_BUSY_CONTAINER": "서버의 80/443 포트를 Docker 컨테이너 {{detail}}이(가) 사용 중입니다. Cindy는 시스템에 직접 설치된 Nginx만 자동으로 설정할 수 있고, 컨테이너 안의 설정은 바꿀 수 없습니다. 다른 서버를 선택하세요.",
"NGINX_FAILED": "Nginx 설정을 완료하지 못해 배포를 중단했습니다. 자세한 이유를 확인하세요.",
"DOWNLOAD_FAILED": "서버가 실행 환경을 내려받지 못했습니다(공식 소스와 미러 모두 실패). 서버가 인터넷에 연결되는지 확인하세요.",
- "RELAY_MISMATCH": "이 서버에는 이 컴퓨터가 배포하지 않은 중계가 이미 있습니다. 지우고 다시 배포할 수 있습니다.",
+ "RELAY_MISMATCH": "이 서버의 중계는 이 컴퓨터가 배포하지 않았으므로 Cindy가 변경하지 않습니다.",
"CERTIFICATE_FAILED": "HTTPS 인증서를 발급받지 못했습니다. 대개 클라우드 보안 그룹에서 80 포트를 허용하지 않았거나 도메인이 아직 이 서버를 가리키지 않기 때문입니다. 해결한 뒤 다시 시도하세요.",
+ "CA_UNREACHABLE": "서버가 인증서 발급 기관 Let's Encrypt에 연결하지 못했고, 몇 분 동안 자동으로 다시 시도해도 성공하지 못했습니다. 서버가 인터넷에 연결되는지 확인한 뒤 잠시 후 다시 시도하세요.",
"NOT_REACHABLE": "서버의 중계는 실행 중이지만 이 컴퓨터에서 연결할 수 없습니다. 클라우드 보안 그룹에서 443 포트를 허용하세요.",
"BUNDLE_MISSING": "이 버전의 Cindy에는 중계가 포함되어 있지 않습니다. Cindy를 업데이트하세요.",
"DEPLOY_FAILED": "배포를 완료하지 못했습니다.",
@@ -5686,10 +5684,10 @@
},
"deploy": {
"title": "내 서버에 배포",
- "hint": "중계를 내 Linux 서버에 설치하면 휴대폰과 다른 네트워크의 기기도 연결할 수 있습니다. Cindy는 원격에서 설정한 SSH 연결로 설치하고, HTTPS 인증서를 자동으로 발급받아 만료 전에 갱신합니다.",
- "requirements": "systemd가 있는 64비트 Linux, root 또는 암호 없는 sudo, 클라우드 보안 그룹이나 방화벽에서 TCP 80·443 허용이 필요합니다. 기존 Nginx는 Cindy가 자동으로 확인하고 설정합니다.",
+ "hint": "중계를 내 Linux 서버에 설치하면 휴대폰과 다른 네트워크의 기기도 연결할 수 있습니다. Cindy는 원격에서 설정한 SSH 연결로 설치하고, HTTPS 인증서를 자동으로 발급받아 갱신합니다. 클라우드 보안 그룹에서 TCP 80·443을 허용하세요.",
"noHosts": "사용할 수 있는 서버가 없습니다. 원격에서 SSH 호스트를 추가한 뒤 다시 오세요.",
"server": "서버",
+ "serverPlaceholder": "서버 선택",
"address": "접속 주소",
"addressPlaceholder": "공인 IP 또는 도메인 (예: 203.0.113.10)",
"addressHint": "다른 기기가 중계에 연결할 주소입니다. 공인 IP를 입력하면 6일간 유효하고 자동 갱신되는 IP 인증서를 발급받습니다. 도메인은 먼저 이 서버를 가리키도록 설정해야 합니다.",
@@ -5697,9 +5695,27 @@
"defaultName": "내 중계",
"submit": "배포",
"cancel": "취소",
- "detail": "자세한 원인: {{detail}}",
"retry": "다시 시도",
- "replace": "이전 중계를 지우고 다시 배포",
+ "submitReplace": "지우고 배포",
+ "edit": "설정 변경",
+ "abandon": "배포 중단",
+ "abandonTitle": "이 배포를 중단할까요?",
+ "abandonDescription": "서버에 이미 설치된 부분을 정리하고, 이 컴퓨터의 배포 기록도 삭제합니다.",
+ "replaceTitle": "서버의 중계를 지울까요?",
+ "replaceDescription": "이 서버의 중계는 이 컴퓨터가 배포하지 않았습니다. 배포를 계속하면 중계와 기기 기록이 삭제되고, 참여한 기기는 다시 참여해야 합니다.",
+ "incompleteHint": "지난 배포가 끝나지 않았습니다. 다시 시도하거나 설정을 바꿔 다시 배포하세요.",
+ "showDetails": "자세히 보기",
+ "check": {
+ "checking": "서버를 확인하는 중…",
+ "ready": "배포할 수 있습니다",
+ "blocked": "자동으로 배포할 수 없습니다",
+ "recheck": "다시 확인",
+ "direct": "80·443 포트가 비어 있어 중계가 직접 사용합니다.",
+ "nginx": "서버의 기존 Nginx를 통해 연결하고, 기존 사이트는 그대로 둡니다.",
+ "mine": "이 컴퓨터에서 배포한 중계가 이미 있습니다. 그대로 업데이트하며, 참여한 기기에는 영향이 없습니다.",
+ "other": "이 컴퓨터가 배포하지 않은 중계가 있습니다. 배포하면 삭제되고, 그 중계에 참여한 기기는 다시 참여해야 합니다.",
+ "cleanup": "먼저 {{server}}의 끝나지 않은 배포를 정리합니다."
+ },
"running": {
"deploy": "서버에 배포하는 중…",
"upgrade": "서버의 중계를 업그레이드하는 중…",
@@ -5708,11 +5724,31 @@
"done": {
"deploy": "배포를 마쳤습니다. 이제 이 컴퓨터는 서버의 중계를 사용합니다. 기기 추가로 휴대폰과 다른 컴퓨터를 참여시키세요.",
"upgrade": "서버의 중계를 {{version}}(으)로 업그레이드했습니다.",
- "uninstall": "서버에서 중계를 제거했습니다."
+ "uninstall": "서버에서 중계를 제거했습니다"
+ },
+ "failed": {
+ "deploy": "배포를 완료하지 못했습니다",
+ "upgrade": "업그레이드를 완료하지 못했습니다",
+ "uninstall": "제거를 완료하지 못했습니다"
+ },
+ "elapsed": "경과 시간 {{time}}",
+ "logs": "배포 로그",
+ "progress": {
+ "runtime-cached": "실행 환경이 준비되어 있습니다. 다시 다운로드할 필요가 없습니다.",
+ "runtime-download": "실행 환경을 다운로드하고 있습니다. 속도는 서버의 네트워크에 따라 달라집니다…",
+ "runtime-fallback": "현재 다운로드 원본을 사용할 수 없습니다. 다른 원본을 시도하고 있습니다…",
+ "runtime-checksum": "다운로드를 마쳤습니다. 파일을 검증하고 있습니다…",
+ "runtime-extract": "파일 검증을 마쳤습니다. 실행 환경의 압축을 풀고 설치하고 있습니다…",
+ "nginx-prepare": "Nginx를 감지했습니다. 중계 연결을 설정하고 있습니다…",
+ "certificate-wait": "인증서 발급을 기다리고 있습니다. 몇 분 정도 걸릴 수 있습니다…",
+ "certificate-retry": "지금은 인증서 발급 기관에 연결할 수 없습니다. 자동으로 다시 시도하는 중…",
+ "verify-retry": "아직 중계에 연결할 수 없습니다. 다시 확인하고 있습니다…",
+ "nginx-rollback": "배포를 완료하지 못했습니다. 이전 Nginx 설정을 복원하고 있습니다…"
},
"steps": {
+ "cleanup": "기존 서버 {{server}} 정리",
"connect": "서버에 연결",
- "check": "시스템과 포트 확인",
+ "check": "서버 확인",
"runtime": "실행 환경 설치",
"upload": "중계 업로드",
"configure": "서비스 설정 및 시작",
@@ -5723,16 +5759,68 @@
}
},
"server": {
- "title": "내 서버 중계",
- "version": "중계 버전 {{version}}",
- "incomplete": "지난 배포가 끝나지 않았습니다. 다시 시도하거나 제거하세요.",
+ "inUse": "사용 중",
"upgrade": "{{version}}(으)로 업그레이드",
- "uninstall": "서버에서 제거",
- "uninstallTitle": "서버에서 중계를 제거할까요?",
- "uninstallDescription": "서버의 중계와 기기 기록이 삭제되고, 사용 중인 기기는 연결이 끊어집니다. 다시 배포하면 모든 기기가 다시 참여해야 합니다.",
+ "remove": "제거",
+ "removeTitle": "서버 중계를 제거할까요?",
+ "removeDescription": "서버의 중계와 기기 기록이 삭제되고, 사용 중인 기기는 연결이 끊어집니다. 다시 배포하면 모든 기기가 다시 참여해야 합니다.",
"forget": "이 컴퓨터에서만 제거",
"forgetTitle": "이 컴퓨터에서만 제거할까요?",
"forgetDescription": "서버의 중계는 그대로 실행되지만, 이 컴퓨터에서 더 이상 관리하거나 기기를 추가할 수 없습니다. 그 서버를 더 이상 쓰지 않을 때만 하세요."
+ },
+ "route": {
+ "title": "연결 경로",
+ "hint": "기기 간 원격 제어는 이 경로로 중계됩니다",
+ "kindServer": "내 서버",
+ "kindJoined": "참여 중",
+ "hostTitle": "이 컴퓨터를 중계로 사용",
+ "hostHint": "다른 기기가 이 컴퓨터에 직접 접속할 수 있어야 합니다. 절전 모드나 Cindy 종료 시 연결이 끊어집니다",
+ "officialHint": "설정 없이 모든 기능을 사용할 수 있습니다",
+ "defaultTag": "기본",
+ "useNamed": "{{name}}(으)로 전환",
+ "deployingStep": "{{step}}…",
+ "viewProgress": "진행 상황 보기",
+ "resume": "배포 계속",
+ "statusChecking": "확인하는 중…",
+ "statusOnline": "온라인",
+ "statusOffline": "연결 안 됨",
+ "switchTitle": "{{name}}(으)로 전환할까요?",
+ "switchFromHost": "이 컴퓨터의 중계가 중지되고, 참여한 기기는 연결이 끊어집니다.",
+ "switchFromMember": "이 컴퓨터는 {{name}}에서 나갑니다. 다시 참여하려면 상대방이 새 참여 링크를 만들어야 합니다.",
+ "switchConfirm": "전환",
+ "switchFromOfficial": "기기 간 원격 제어가 {{name}}을(를) 거쳐 중계됩니다. 내 중계를 사용하는 동안에는 휴대폰 시스템 알림, 제공자 공유, 공유 작업을 사용할 수 없습니다."
+ },
+ "dialog": {
+ "steps": {
+ "label": "배포 단계",
+ "form": "서버 선택",
+ "deploy": "배포",
+ "done": "기기 추가"
+ },
+ "running": "{{server}}에 배포하는 중…",
+ "backgroundHint": "창을 닫아도 배포는 계속됩니다",
+ "background": "백그라운드에서 계속",
+ "doneTitle": "{{name}} 배포를 마쳤습니다",
+ "doneHint": "이제 이 컴퓨터는 이 중계를 사용합니다. 휴대폰으로 스캔하거나, 링크를 다른 컴퓨터에 보내 참여시키세요.",
+ "doneLater": "나중에 연결 경로에서도 기기를 추가할 수 있습니다",
+ "finish": "완료"
+ },
+ "manage": {
+ "check": "연결 확인",
+ "offline": "지금 이 컴퓨터에서 이 중계에 연결할 수 없습니다. 서버가 꺼졌거나 네트워크·보안 그룹이 바뀌면 이렇게 됩니다. 해결한 뒤 연결 확인을 누르세요.",
+ "devices": "참여한 기기",
+ "deviceCount_one": "{{count}}대",
+ "deviceCount_other": "{{count}}대",
+ "onlineCount_one": "{{count}}대 온라인",
+ "onlineCount_other": "{{count}}대 온라인",
+ "certificate": "HTTPS 인증서",
+ "certificateDays_one": "{{count}}일 후 만료",
+ "certificateDays_other": "{{count}}일 후 만료",
+ "certificateRenew": "자동으로 갱신됩니다",
+ "certificateSite": "사이트 인증서 사용",
+ "version": "중계 버전",
+ "latest": "최신 버전",
+ "remove": "이 중계 제거"
}
},
"title": "원격 연결",
@@ -5754,7 +5842,6 @@
"restoreFailed": "복원에 실패했습니다"
},
"sections": {
- "relay": "중계 서비스",
"myDevices": "내 기기",
"ssh": "SSH 원격 호스트",
"hook": "Cindy IM 봇"
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 8758204256..073684884a 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -5570,10 +5570,7 @@
"remoteControl": {
"relay": {
"summary": {
- "official": "Cindy 官方中转",
- "owner": "这台电脑当中转",
- "member": "已加入 {{name}}",
- "server": "服务器中转「{{name}}」"
+ "official": "Cindy 官方中转"
},
"description": "设备之间的远程控制默认经 Cindy 官方中转。你也可以把中转部署到自己的服务器、让这台电脑当中转,或加入你自己另一台电脑上的中转。登录、模型等其他服务不受影响。",
"current": "当前使用",
@@ -5581,12 +5578,10 @@
"unavailable": "登录 Cindy 账号,并且系统钥匙串可用时,才能使用自己的中转。",
"limits": "使用自己的中转时,手机系统推送、供应商分享和共享任务暂不可用。",
"actions": {
- "host": "在这台电脑上开启",
"join": "加入别的中转",
"useOfficial": "切回官方中转",
"editHost": "修改设置",
- "deploy": "部署到我的服务器",
- "useDeployment": "改用这个中转"
+ "deploy": "部署到我的服务器"
},
"host": {
"title": "在这台电脑上开启中转",
@@ -5667,13 +5662,16 @@
"START_FAILED": "中转没能启动,可以换一个端口再试。",
"EXTERNAL_URL_REQUIRED": "请先填写其他设备访问的地址,或把「允许谁连接」改为所有网络。",
"SSH_FAILED": "连不上服务器。请在「远程」里检查这台服务器的 SSH 设置。",
+ "SHELL_UNAVAILABLE": "这个 SSH 账号不能执行命令(例如 Git 服务的 git 账号),不能用来部署。请选择一台能登录命令行的服务器。",
"NEEDS_ROOT": "需要 root 账号,或这个账号能免密码使用 sudo。Cindy 不会索要服务器密码。",
"UNSUPPORTED_SYSTEM": "目前只支持带 systemd 的 64 位 Linux(x64 / arm64),并且需要 curl 或 wget。",
- "PORT_BUSY": "服务器的 80 或 443 端口被其他服务占用,暂时无法自动接入。已有 Nginx 会自动配置,请检查占用端口的其他服务。",
+ "PORT_BUSY": "服务器的 80/443 端口正被 {{detail}} 使用。Cindy 不会停掉其他程序,可以换一台服务器,或停掉它后重新检查。",
+ "PORT_BUSY_CONTAINER": "服务器的 80/443 端口由 Docker 容器 {{detail}} 使用。Cindy 只能自动配置直接装在系统里的 Nginx,改不了容器里的配置,可以换一台服务器。",
"NGINX_FAILED": "未能完成 Nginx 配置,部署已停止。请查看详细原因。",
"DOWNLOAD_FAILED": "服务器下载运行环境失败(官方源和国内镜像都没成功)。请检查服务器能否访问外网。",
- "RELAY_MISMATCH": "这台服务器上已有一个不是这台电脑部署的中转。可以清除它后重新部署。",
+ "RELAY_MISMATCH": "这台服务器上的中转不是这台电脑部署的,Cindy 不会改动它。",
"CERTIFICATE_FAILED": "申请 HTTPS 证书失败。通常是云服务器安全组没有放行 80 端口,或域名还没解析到这台服务器。处理后点重试。",
+ "CA_UNREACHABLE": "服务器连不上证书机构 Let's Encrypt,自动重试了几分钟仍没成功。请检查服务器能否访问外网,稍后再试。",
"NOT_REACHABLE": "服务器上的中转已经运行,但这台电脑连不上它。请在云服务器安全组里放行 443 端口。",
"BUNDLE_MISSING": "这个版本的 Cindy 没有带中转程序,请更新 Cindy。",
"DEPLOY_FAILED": "部署没有完成。",
@@ -5686,10 +5684,10 @@
},
"deploy": {
"title": "部署到我的服务器",
- "hint": "把中转装到你自己的 Linux 服务器上,手机和不在同一网络的设备都能连。Cindy 通过「远程」里配置的 SSH 连接安装,并自动申请 HTTPS 证书、到期前自动续期。",
- "requirements": "需要:64 位 Linux(带 systemd)、root 或免密 sudo,并在云服务器安全组或防火墙里放行 TCP 80 和 443。Cindy 会自动检查并配置已有的 Nginx。",
+ "hint": "把中转装到你自己的 Linux 服务器上,手机和外网设备都能连。Cindy 通过「远程」里的 SSH 连接安装,自动申请并续期 HTTPS 证书。云服务器需要在安全组里放行 TCP 80 和 443。",
"noHosts": "还没有可用的服务器。先在「远程」里添加 SSH 主机,再回来部署。",
"server": "服务器",
+ "serverPlaceholder": "选择服务器",
"address": "访问地址",
"addressPlaceholder": "公网 IP 或域名,例如 203.0.113.10",
"addressHint": "其他设备连接中转用的地址。填公网 IP 会申请 6 天有效、自动续期的 IP 证书;填域名需要先把域名解析到这台服务器。",
@@ -5697,22 +5695,60 @@
"defaultName": "我的中转",
"submit": "开始部署",
"cancel": "取消",
- "detail": "详细原因:{{detail}}",
"retry": "重试",
- "replace": "清除旧中转并重新部署",
+ "submitReplace": "清除并部署",
+ "edit": "修改设置",
+ "abandon": "放弃部署",
+ "abandonTitle": "放弃这次部署?",
+ "abandonDescription": "会清理服务器上已经装好的部分,并删除这台电脑上的部署记录。",
+ "replaceTitle": "清除服务器上的中转?",
+ "replaceDescription": "这台服务器上的中转不是这台电脑部署的。继续部署会删除它和它的设备档案,已加入它的设备需要重新加入。",
+ "incompleteHint": "上次部署没有完成。可以重试,或修改设置后重新部署。",
+ "showDetails": "查看详情",
+ "check": {
+ "checking": "正在检查服务器…",
+ "ready": "可以部署",
+ "blocked": "不能自动部署",
+ "recheck": "重新检查",
+ "direct": "80 和 443 端口空闲,中转会直接使用它们。",
+ "nginx": "会接入服务器上已有的 Nginx,并保留原有网站。",
+ "mine": "服务器上已有这台电脑部署的中转,会原地更新,已加入的设备不受影响。",
+ "other": "服务器上已有不是这台电脑部署的中转,继续部署会清除它,已加入它的设备需要重新加入。",
+ "cleanup": "会先清理 {{server}} 上没完成的部署。"
+ },
"running": {
"deploy": "正在部署到服务器…",
"upgrade": "正在升级服务器上的中转…",
- "uninstall": "正在从服务器卸载…"
+ "uninstall": "正在从服务器移除…"
},
"done": {
"deploy": "部署完成,这台电脑已改用服务器上的中转。用「添加设备」让手机和其他电脑加入。",
"upgrade": "服务器上的中转已升级到 {{version}}。",
- "uninstall": "已从服务器卸载中转。"
+ "uninstall": "已从服务器移除中转"
+ },
+ "failed": {
+ "deploy": "部署未完成",
+ "upgrade": "升级未完成",
+ "uninstall": "移除未完成"
+ },
+ "elapsed": "用时 {{time}}",
+ "logs": "部署日志",
+ "progress": {
+ "runtime-cached": "运行环境已就绪,无需重新下载。",
+ "runtime-download": "正在下载运行环境,下载速度取决于服务器网络…",
+ "runtime-fallback": "当前下载源不可用,正在尝试备用源…",
+ "runtime-checksum": "下载完成,正在校验文件…",
+ "runtime-extract": "校验通过,正在解压并安装运行环境…",
+ "nginx-prepare": "已检测到 Nginx,正在配置中转接入…",
+ "certificate-wait": "正在等待证书签发,可能需要几分钟…",
+ "certificate-retry": "暂时连不上证书机构,正在自动重试…",
+ "verify-retry": "暂时还连不上中转,正在重新检查…",
+ "nginx-rollback": "部署未完成,正在恢复原来的 Nginx 配置…"
},
"steps": {
+ "cleanup": "清理原服务器 {{server}}",
"connect": "连接服务器",
- "check": "检查系统和端口",
+ "check": "检查服务器",
"runtime": "安装运行环境",
"upload": "上传中转程序",
"configure": "配置并启动服务",
@@ -5723,16 +5759,68 @@
}
},
"server": {
- "title": "我的服务器中转",
- "version": "中转版本 {{version}}",
- "incomplete": "上次部署没有完成,可以重试或卸载。",
+ "inUse": "正在使用",
"upgrade": "升级到 {{version}}",
- "uninstall": "从服务器卸载",
- "uninstallTitle": "从服务器卸载中转?",
- "uninstallDescription": "服务器上的中转程序和设备档案都会被删除,正在用它的设备会断开。之后重新部署,所有设备都需要重新加入。",
+ "remove": "移除",
+ "removeTitle": "移除服务器中转?",
+ "removeDescription": "会停止并删除服务器上的中转程序和设备档案,正在用它的设备会断开。之后重新部署,所有设备都需要重新加入。",
"forget": "只在本机移除",
"forgetTitle": "只在这台电脑上移除?",
"forgetDescription": "服务器上的中转不会被删除,但这台电脑不再管理它,也不能再为它添加设备。确定不再使用那台服务器时再这样做。"
+ },
+ "route": {
+ "title": "连接线路",
+ "hint": "设备之间的远程控制经由这条线路转发",
+ "kindServer": "我的服务器",
+ "kindJoined": "已加入",
+ "hostTitle": "这台电脑当中转",
+ "hostHint": "其它设备需要能直接访问到这台电脑;电脑休眠或退出 Cindy 时都会断开",
+ "officialHint": "无需设置,所有功能可用",
+ "defaultTag": "默认",
+ "useNamed": "切换到「{{name}}」",
+ "deployingStep": "{{step}}…",
+ "viewProgress": "查看进度",
+ "resume": "继续部署",
+ "statusChecking": "正在检查…",
+ "statusOnline": "在线",
+ "statusOffline": "连不上",
+ "switchTitle": "切换到「{{name}}」?",
+ "switchFromHost": "这台电脑上的中转会停用,已加入它的设备会断开。",
+ "switchFromMember": "这台电脑会退出「{{name}}」,之后要再加入,需要对方重新生成加入链接。",
+ "switchConfirm": "切换",
+ "switchFromOfficial": "设备之间的远程控制会改经「{{name}}」转发。使用自己的中转时,手机系统推送、供应商分享和共享任务暂不可用。"
+ },
+ "dialog": {
+ "steps": {
+ "label": "部署步骤",
+ "form": "选择服务器",
+ "deploy": "部署",
+ "done": "添加设备"
+ },
+ "running": "正在部署到 {{server}}…",
+ "backgroundHint": "关掉窗口不会中断部署",
+ "background": "在后台继续",
+ "doneTitle": "「{{name}}」已部署好",
+ "doneHint": "这台电脑已改用它。用手机扫码,或把链接发给另一台电脑加入。",
+ "doneLater": "之后也可以在「连接线路」里添加设备",
+ "finish": "完成"
+ },
+ "manage": {
+ "check": "检查连接",
+ "offline": "这台电脑现在连不上这个中转。服务器关机、网络变化或安全组改动都会这样,处理后点「检查连接」。",
+ "devices": "已加入设备",
+ "deviceCount_one": "{{count}} 台",
+ "deviceCount_other": "{{count}} 台",
+ "onlineCount_one": "{{count}} 台在线",
+ "onlineCount_other": "{{count}} 台在线",
+ "certificate": "HTTPS 证书",
+ "certificateDays_one": "{{count}} 天后到期",
+ "certificateDays_other": "{{count}} 天后到期",
+ "certificateRenew": "会自动续期",
+ "certificateSite": "沿用网站证书",
+ "version": "中转版本",
+ "latest": "已是最新",
+ "remove": "移除这个中转"
}
},
"title": "远程连接",
@@ -5754,7 +5842,6 @@
"restoreFailed": "恢复失败"
},
"sections": {
- "relay": "中转服务",
"myDevices": "我的设备",
"ssh": "SSH 远程主机",
"hook": "Cindy IM 机器人"
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index 328a3b477d..8311c932b5 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -5570,10 +5570,7 @@
"remoteControl": {
"relay": {
"summary": {
- "official": "Cindy 官方中繼",
- "owner": "這台電腦當中繼",
- "member": "已加入 {{name}}",
- "server": "伺服器中繼「{{name}}」"
+ "official": "Cindy 官方中繼"
},
"description": "裝置之間的遠端控制預設經 Cindy 官方中繼。你也可以把中繼部署到自己的伺服器、讓這台電腦當中繼,或加入你自己另一台電腦上的中繼。登入、模型等其他服務不受影響。",
"current": "目前使用",
@@ -5581,12 +5578,10 @@
"unavailable": "登入 Cindy 帳號,並且系統鑰匙圈可用時,才能使用自己的中繼。",
"limits": "使用自己的中繼時,手機系統推播、供應商分享和共享任務暫不可用。",
"actions": {
- "host": "在這台電腦上開啟",
"join": "加入別的中繼",
"useOfficial": "切回官方中繼",
"editHost": "修改設定",
- "deploy": "部署到我的伺服器",
- "useDeployment": "改用這個中繼"
+ "deploy": "部署到我的伺服器"
},
"host": {
"title": "在這台電腦上開啟中繼",
@@ -5667,13 +5662,16 @@
"START_FAILED": "中繼沒能啟動,可以換一個連接埠再試。",
"EXTERNAL_URL_REQUIRED": "請先填寫其他裝置連線的位址,或把「允許誰連線」改為所有網路。",
"SSH_FAILED": "連不上伺服器。請在「遠端」裡檢查這台伺服器的 SSH 設定。",
+ "SHELL_UNAVAILABLE": "這個 SSH 帳號不能執行指令(例如 Git 服務的 git 帳號),不能用來部署。請選擇一台能登入命令列的伺服器。",
"NEEDS_ROOT": "需要 root 帳號,或這個帳號能免密碼使用 sudo。Cindy 不會索取伺服器密碼。",
"UNSUPPORTED_SYSTEM": "目前只支援含 systemd 的 64 位元 Linux(x64 / arm64),並且需要 curl 或 wget。",
- "PORT_BUSY": "伺服器的 80 或 443 連接埠被其他服務佔用,暫時無法自動接入。現有 Nginx 會自動設定,請檢查佔用連接埠的其他服務。",
+ "PORT_BUSY": "伺服器的 80/443 連接埠正被 {{detail}} 使用。Cindy 不會停掉其他程式,可以換一台伺服器,或停掉它後重新檢查。",
+ "PORT_BUSY_CONTAINER": "伺服器的 80/443 連接埠由 Docker 容器 {{detail}} 使用。Cindy 只能自動設定直接裝在系統裡的 Nginx,改不了容器裡的設定,可以換一台伺服器。",
"NGINX_FAILED": "未能完成 Nginx 設定,部署已停止。請查看詳細原因。",
"DOWNLOAD_FAILED": "伺服器下載執行環境失敗(官方來源和鏡像都沒成功)。請檢查伺服器能否連上外網。",
- "RELAY_MISMATCH": "這台伺服器上已有一個不是這台電腦部署的中繼。可以清除它後重新部署。",
+ "RELAY_MISMATCH": "這台伺服器上的中繼不是這台電腦部署的,Cindy 不會更動它。",
"CERTIFICATE_FAILED": "申請 HTTPS 憑證失敗。通常是雲端主機安全群組沒有放行 80 連接埠,或網域還沒解析到這台伺服器。處理後點重試。",
+ "CA_UNREACHABLE": "伺服器連不上憑證機構 Let's Encrypt,自動重試了幾分鐘仍沒成功。請檢查伺服器能否連上外網,稍後再試。",
"NOT_REACHABLE": "伺服器上的中繼已經執行,但這台電腦連不上它。請在雲端主機安全群組裡放行 443 連接埠。",
"BUNDLE_MISSING": "這個版本的 Cindy 沒有附帶中繼程式,請更新 Cindy。",
"DEPLOY_FAILED": "部署沒有完成。",
@@ -5686,10 +5684,10 @@
},
"deploy": {
"title": "部署到我的伺服器",
- "hint": "把中繼裝到你自己的 Linux 伺服器上,手機和不在同一網路的裝置都能連。Cindy 透過「遠端」裡設定的 SSH 連線安裝,並自動申請 HTTPS 憑證、到期前自動續期。",
- "requirements": "需要:64 位元 Linux(含 systemd)、root 或免密碼 sudo,並在雲端伺服器安全群組或防火牆裡開放 TCP 80 和 443。Cindy 會自動檢查並設定現有的 Nginx。",
+ "hint": "把中繼裝到你自己的 Linux 伺服器上,手機和外網裝置都能連。Cindy 透過「遠端」裡的 SSH 連線安裝,自動申請並續期 HTTPS 憑證。雲端主機需要在安全群組裡開放 TCP 80 和 443。",
"noHosts": "還沒有可用的伺服器。先在「遠端」裡新增 SSH 主機,再回來部署。",
"server": "伺服器",
+ "serverPlaceholder": "選擇伺服器",
"address": "存取位址",
"addressPlaceholder": "公網 IP 或網域,例如 203.0.113.10",
"addressHint": "其他裝置連線中繼用的位址。填公網 IP 會申請 6 天有效、自動續期的 IP 憑證;填網域需要先把網域解析到這台伺服器。",
@@ -5697,22 +5695,60 @@
"defaultName": "我的中繼",
"submit": "開始部署",
"cancel": "取消",
- "detail": "詳細原因:{{detail}}",
"retry": "重試",
- "replace": "清除舊中繼並重新部署",
+ "submitReplace": "清除並部署",
+ "edit": "修改設定",
+ "abandon": "放棄部署",
+ "abandonTitle": "放棄這次部署?",
+ "abandonDescription": "會清理伺服器上已經裝好的部分,並刪除這台電腦上的部署記錄。",
+ "replaceTitle": "清除伺服器上的中繼?",
+ "replaceDescription": "這台伺服器上的中繼不是這台電腦部署的。繼續部署會刪除它和它的裝置檔案,已加入它的裝置需要重新加入。",
+ "incompleteHint": "上次部署沒有完成。可以重試,或修改設定後重新部署。",
+ "showDetails": "查看詳情",
+ "check": {
+ "checking": "正在檢查伺服器…",
+ "ready": "可以部署",
+ "blocked": "無法自動部署",
+ "recheck": "重新檢查",
+ "direct": "80 和 443 連接埠沒有被使用,中繼會直接使用它們。",
+ "nginx": "會接入伺服器上現有的 Nginx,並保留原有網站。",
+ "mine": "伺服器上已有這台電腦部署的中繼,會原地更新,已加入的裝置不受影響。",
+ "other": "伺服器上已有不是這台電腦部署的中繼,繼續部署會清除它,已加入它的裝置需要重新加入。",
+ "cleanup": "會先清理 {{server}} 上沒完成的部署。"
+ },
"running": {
"deploy": "正在部署到伺服器…",
"upgrade": "正在升級伺服器上的中繼…",
- "uninstall": "正在從伺服器解除安裝…"
+ "uninstall": "正在從伺服器移除…"
},
"done": {
"deploy": "部署完成,這台電腦已改用伺服器上的中繼。用「新增裝置」讓手機和其他電腦加入。",
"upgrade": "伺服器上的中繼已升級到 {{version}}。",
- "uninstall": "已從伺服器解除安裝中繼。"
+ "uninstall": "已從伺服器移除中繼"
+ },
+ "failed": {
+ "deploy": "部署未完成",
+ "upgrade": "升級未完成",
+ "uninstall": "移除未完成"
+ },
+ "elapsed": "用時 {{time}}",
+ "logs": "部署日誌",
+ "progress": {
+ "runtime-cached": "執行環境已就緒,無需重新下載。",
+ "runtime-download": "正在下載執行環境,下載速度取決於伺服器網路…",
+ "runtime-fallback": "目前的下載來源無法使用,正在嘗試備用來源…",
+ "runtime-checksum": "下載完成,正在驗證檔案…",
+ "runtime-extract": "驗證通過,正在解壓縮並安裝執行環境…",
+ "nginx-prepare": "已偵測到 Nginx,正在設定中繼接入…",
+ "certificate-wait": "正在等待憑證簽發,可能需要幾分鐘…",
+ "certificate-retry": "暫時連不上憑證機構,正在自動重試…",
+ "verify-retry": "暫時還連不上中繼,正在重新檢查…",
+ "nginx-rollback": "部署未完成,正在還原原本的 Nginx 設定…"
},
"steps": {
+ "cleanup": "清理原伺服器 {{server}}",
"connect": "連線伺服器",
- "check": "檢查系統和連接埠",
+ "check": "檢查伺服器",
"runtime": "安裝執行環境",
"upload": "上傳中繼程式",
"configure": "設定並啟動服務",
@@ -5723,16 +5759,68 @@
}
},
"server": {
- "title": "我的伺服器中繼",
- "version": "中繼版本 {{version}}",
- "incomplete": "上次部署沒有完成,可以重試或解除安裝。",
+ "inUse": "使用中",
"upgrade": "升級到 {{version}}",
- "uninstall": "從伺服器解除安裝",
- "uninstallTitle": "從伺服器解除安裝中繼?",
- "uninstallDescription": "伺服器上的中繼程式和裝置檔案都會被刪除,正在使用它的裝置會斷線。之後重新部署,所有裝置都需要重新加入。",
+ "remove": "移除",
+ "removeTitle": "移除伺服器中繼?",
+ "removeDescription": "會停止並刪除伺服器上的中繼程式和裝置檔案,正在使用它的裝置會斷線。之後重新部署,所有裝置都需要重新加入。",
"forget": "只在本機移除",
"forgetTitle": "只在這台電腦上移除?",
"forgetDescription": "伺服器上的中繼不會被刪除,但這台電腦不再管理它,也不能再為它新增裝置。確定不再使用那台伺服器時再這樣做。"
+ },
+ "route": {
+ "title": "連線路線",
+ "hint": "裝置之間的遠端控制經由這條路線轉送",
+ "kindServer": "我的伺服器",
+ "kindJoined": "已加入",
+ "hostTitle": "這台電腦當中繼",
+ "hostHint": "其他裝置需要能直接連到這台電腦;電腦休眠或結束 Cindy 時都會斷線",
+ "officialHint": "無需設定,所有功能可用",
+ "defaultTag": "預設",
+ "useNamed": "切換到「{{name}}」",
+ "deployingStep": "{{step}}…",
+ "viewProgress": "查看進度",
+ "resume": "繼續部署",
+ "statusChecking": "正在檢查…",
+ "statusOnline": "線上",
+ "statusOffline": "連不上",
+ "switchTitle": "切換到「{{name}}」?",
+ "switchFromHost": "這台電腦上的中繼會停用,已加入它的裝置會斷線。",
+ "switchFromMember": "這台電腦會退出「{{name}}」,之後要再加入,需要對方重新產生加入連結。",
+ "switchConfirm": "切換",
+ "switchFromOfficial": "裝置之間的遠端控制會改經「{{name}}」轉送。使用自己的中繼時,手機系統推播、供應商分享和共享任務暫時無法使用。"
+ },
+ "dialog": {
+ "steps": {
+ "label": "部署步驟",
+ "form": "選擇伺服器",
+ "deploy": "部署",
+ "done": "新增裝置"
+ },
+ "running": "正在部署到 {{server}}…",
+ "backgroundHint": "關閉視窗不會中斷部署",
+ "background": "在背景繼續",
+ "doneTitle": "「{{name}}」已部署完成",
+ "doneHint": "這台電腦已改用它。用手機掃描,或把連結傳給另一台電腦加入。",
+ "doneLater": "之後也可以在「連線路線」裡新增裝置",
+ "finish": "完成"
+ },
+ "manage": {
+ "check": "檢查連線",
+ "offline": "這台電腦現在連不上這個中繼。伺服器關機、網路變動或安全群組變更都會這樣,處理後點「檢查連線」。",
+ "devices": "已加入裝置",
+ "deviceCount_one": "{{count}} 台",
+ "deviceCount_other": "{{count}} 台",
+ "onlineCount_one": "{{count}} 台在線上",
+ "onlineCount_other": "{{count}} 台在線上",
+ "certificate": "HTTPS 憑證",
+ "certificateDays_one": "{{count}} 天後到期",
+ "certificateDays_other": "{{count}} 天後到期",
+ "certificateRenew": "會自動續期",
+ "certificateSite": "沿用網站憑證",
+ "version": "中繼版本",
+ "latest": "已是最新",
+ "remove": "移除這個中繼"
}
},
"title": "遠端連線",
@@ -5754,7 +5842,6 @@
"restoreFailed": "恢復失敗"
},
"sections": {
- "relay": "中繼服務",
"myDevices": "我的裝置",
"ssh": "SSH 遠端主機",
"hook": "Cindy IM 機器人"
diff --git a/apps/desktop/src/shared/selfHostedRelay.ts b/apps/desktop/src/shared/selfHostedRelay.ts
index 1b539d5f5f..df65f9ebde 100644
--- a/apps/desktop/src/shared/selfHostedRelay.ts
+++ b/apps/desktop/src/shared/selfHostedRelay.ts
@@ -37,10 +37,17 @@ export type SelfHostedRelayCommand =
/** 服务器已不可用时,只在本机删掉部署记录。 */
| { type: 'forget-deployment' }
/** 改回使用服务器上的中转(之前切回过官方中转)。 */
- | { type: 'use-deployment' };
+ | { type: 'use-deployment' }
+ /** 只读检查服务器能否部署,不改动服务器;结果在命令返回的 `check` 里。 */
+ | { type: 'check-server'; sshHostId: string }
+ /** 关掉一次没改动过服务器的失败部署(检查阶段就停下的)。 */
+ | { type: 'dismiss-deploy-job' }
+ /** 以主人身份读取服务器中转的状态(在线、设备数、证书到期);结果在 `deploymentStatus` 里。 */
+ | { type: 'deployment-status' };
-/** 部署的步骤(界面逐步展示)。 */
+/** 部署的步骤(界面逐步展示)。`finish` 只出现在日志里。 */
export type RelayDeployStep =
+ | 'cleanup'
| 'connect'
| 'check'
| 'runtime'
@@ -48,28 +55,34 @@ export type RelayDeployStep =
| 'configure'
| 'certificate'
| 'verify'
+ | 'remove'
| 'finish';
+/** 部署与升级界面列出的步骤;换服务器时最前面再加 `cleanup`。 */
export const RELAY_DEPLOY_STEPS: readonly RelayDeployStep[] = [
- 'connect',
'check',
'runtime',
'upload',
'configure',
'certificate',
'verify',
- 'finish',
];
+export const RELAY_UNINSTALL_STEPS: readonly RelayDeployStep[] = ['connect', 'remove'];
+
export type RelayDeployErrorCode =
/** 连不上 SSH 主机(未配置、离线、认证失败)。 */
| 'SSH_FAILED'
+ /** SSH 能连上,但这个账号不能执行命令(例如 Git 服务的 git 账号)。 */
+ | 'SHELL_UNAVAILABLE'
/** 需要 root 或免密 sudo。 */
| 'NEEDS_ROOT'
/** 只支持带 systemd 的 64 位 Linux(x64 / arm64)。 */
| 'UNSUPPORTED_SYSTEM'
- /** 80 或 443 端口被其他程序占用。 */
+ /** 80 或 443 端口被其他程序占用;detail 是程序名。 */
| 'PORT_BUSY'
+ /** 80 或 443 端口由 Docker 容器发布(容器里的配置 Cindy 改不了);detail 是容器名。 */
+ | 'PORT_BUSY_CONTAINER'
| 'NGINX_FAILED'
/** 下载运行环境失败(官方源与国内镜像都失败,或校验不符)。 */
| 'DOWNLOAD_FAILED'
@@ -77,6 +90,8 @@ export type RelayDeployErrorCode =
| 'RELAY_MISMATCH'
/** 证书申请失败(通常是 80 端口没对外开放,或域名没解析到这台服务器)。 */
| 'CERTIFICATE_FAILED'
+ /** 服务器在等待时间内一直连不上证书机构(出网中断、超时、连接被重置)。 */
+ | 'CA_UNREACHABLE'
/** 服务器上中转已运行,但这台电脑访问不到(通常是 443 端口没对外开放)。 */
| 'NOT_REACHABLE'
/** 这个版本的 Cindy 没有带中转程序(开发环境未构建)。 */
@@ -119,6 +134,25 @@ export type SelfHostedRelayJoinView =
| { status: 'joined'; relayName: string }
| { status: 'failed'; error: SelfHostedRelayErrorCode };
+/** 部署日志只传受控事件,不把 SSH 原始输出、证书材料或凭证交给界面。 */
+export type RelayDeployProgressMessage =
+ | 'runtime-cached'
+ | 'runtime-download'
+ | 'runtime-fallback'
+ | 'runtime-checksum'
+ | 'runtime-extract'
+ | 'nginx-prepare'
+ | 'certificate-wait'
+ | 'certificate-retry'
+ | 'verify-retry'
+ | 'nginx-rollback';
+
+export interface RelayDeployLogEntry {
+ at: number;
+ step: RelayDeployStep;
+ message?: RelayDeployProgressMessage;
+}
+
export interface SelfHostedRelayDeployJobView {
action: 'deploy' | 'upgrade' | 'uninstall';
step: RelayDeployStep;
@@ -126,8 +160,30 @@ export interface SelfHostedRelayDeployJobView {
error?: SelfHostedRelayErrorCode;
/** 失败时给用户看的补充信息(端口、服务器返回的原因),不含秘密。 */
detail?: string;
+ /** 可选以兼容旧的状态快照;只保存在当前账号的内存中。 */
+ startedAt?: number;
+ finishedAt?: number;
+ logs?: RelayDeployLogEntry[];
+ /** 这次任务依次要做的步骤(界面照此列出)。 */
+ steps?: RelayDeployStep[];
+ /** 部署的目标。检查通过前还没有部署记录,界面靠它显示服务器和地址,失败后「修改设置」也从这里回填。 */
+ target?: { sshHostId: string; address: string; name: string; baseUrl: string };
+ /** 已经开始改动服务器(部署记录已保存)。为 false 时失败的部署可以直接关掉。 */
+ serverChanged?: boolean;
}
+/** 只读检查的结果:`existing` 说明服务器上已有的中转是不是这台电脑部署的。 */
+export type SelfHostedRelayServerCheck =
+ | {
+ sshHostId: string;
+ ok: true;
+ /** 系统名与架构,例如 `Debian GNU/Linux 13 (trixie) · x86_64`。 */
+ system: string;
+ plan: 'direct' | 'nginx';
+ existing: 'none' | 'mine' | 'other';
+ }
+ | { sshHostId: string; ok: false; error: SelfHostedRelayErrorCode; detail?: string };
+
export interface SelfHostedRelayDeploymentView {
sshHostId: string;
address: string;
@@ -201,7 +257,12 @@ export function parseSelfHostedRelayCommand(raw: unknown): SelfHostedRelayComman
case 'upgrade-deployment':
case 'forget-deployment':
case 'use-deployment':
+ case 'dismiss-deploy-job':
+ case 'deployment-status':
return { type: raw.type };
+ case 'check-server':
+ if (typeof raw.sshHostId !== 'string' || !SSH_HOST_ID_PATTERN.test(raw.sshHostId)) return null;
+ return { type: 'check-server', sshHostId: raw.sshHostId };
case 'enable-host': {
const port = raw.port;
if (typeof port !== 'number' || !Number.isInteger(port) || port < 1024 || port > 65535) return null;
@@ -236,6 +297,21 @@ export function parseSelfHostedRelayCommand(raw: unknown): SelfHostedRelayComman
export interface SelfHostedRelayCommandResult {
state: SelfHostedRelayState;
error?: SelfHostedRelayErrorCode;
+ /** 只有 `check-server` 返回。 */
+ check?: SelfHostedRelayServerCheck;
+ /** 只有 `deployment-status` 返回。 */
+ deploymentStatus?: SelfHostedRelayDeploymentStatus;
+}
+
+/** 服务器中转的实时状态;`online: false` 表示这台电脑现在连不上它(或它不认这台电脑的主人凭证)。 */
+export interface SelfHostedRelayDeploymentStatus {
+ online: boolean;
+ /** 已加入的设备数(含这台电脑)。 */
+ devices?: number;
+ /** 此刻连着中转的设备数。 */
+ onlineDevices?: number;
+ /** 中转自己申请的证书的到期时间;沿用已有网站证书时为 null。 */
+ certificateExpiresAt?: string | null;
}
/** `window.electronAPI.selfHostedRelay`。 */
diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.md
index b07a4faa17..a7fc882518 100644
--- a/docs/dev-rules/protocol-compatibility.md
+++ b/docs/dev-rules/protocol-compatibility.md
@@ -305,6 +305,8 @@ stream 匹配后才处理;信令不进入业务可靠 FIFO,也不走直连
服务器部署的 Nginx 自动接入使用中转 bundle `0.3.0`(`nginx` 为 SSH 部署内部 CLI)。公网仍使用
原有 HTTPS/WSS 地址、`CindyRelay` 认证、媒体签名地址及 v1 设备协议;不新增跨端帧、能力位或权限。
已部署 `0.2.0` 的通信行为继续兼容,需要自动配置 Nginx 时由现有升级入口上传新 bundle。
+证书请求的网络重试与临时失败状态随 bundle `0.3.1` 提供;已部署 `0.3.0` 的服务器通过现有升级入口更新程序。
+新增的证书状态 `transient` 为可选字段,旧客户端忽略;新客户端连接旧中转仍沿用原失败处理,线协议与主人身份不变。
Nginx 后端的 `--trust-proxy` 只对回环连接的单个有效 `X-Forwarded-For` IP 启用配对来源识别,
部署生成的代理配置必须覆盖该头;直连及默认未信任模式继续按 socket 来源限流,协议不变。
Desktop/Mobile 继续共用原客户端,无须更改服务端;验证入口见
diff --git a/docs/self-hosted-relay-plan.md b/docs/self-hosted-relay-plan.md
index cc533e37d9..bc56e6db70 100644
--- a/docs/self-hosted-relay-plan.md
+++ b/docs/self-hosted-relay-plan.md
@@ -555,8 +555,19 @@ App 内不加扫码组件:加一个会改变原生指纹,需要冷更。
- systemd 服务以 `cindy-relay` 用户运行,只放行绑定低端口的权限;`ProtectSystem=strict`,只能写数据目录。
- 主人身份(中转 ID、主人凭证、主人密钥)只在这台电脑生成;服务器只拿到凭证哈希、主人公钥和主人证书。
- 身份在动服务器之前就记进部署记录:中途失败重试,用的还是同一份身份,不会和服务器上已初始化的数据冲突。
+ 记录在检查通过、第一次改动服务器前才写入(2026-10-29):只在连接或检查阶段停下的部署不留记录,界面也不会出现从未装上的中转。
+- 部署界面(2026-10-29 用户反馈后重做):
+ - 表单不预选服务器,用户选中后才做只读检查(`check-server`:只跑探测与检查脚本),说明能否部署、走直连还是已有 Nginx、服务器上已有的中转是不是这台电脑的;不通过时「开始部署」不可点,可直接换服务器或重新检查。下拉显示 `账号@地址`;探测脚本一行都没输出时报 `SHELL_UNAVAILABLE`(例如 Git 服务的 git 账号),不误报为系统不支持。
+ - 证书机构连不上(断网、超时、连接重置、CA 5xx)与 CA 拒绝验证分开:中转的 ACME 请求先短暂重试,仍失败时在 `status.json` 标 `transient` 并按 15 秒起的退避重试;部署方遇到 `transient` 继续等待并显示「正在自动重试」,等待期满仍连不上才报 `CA_UNREACHABLE`。起因是 2026-10-29 国内服务器首次申请 IP 证书时一次 `fetch failed` 就被当作最终失败并回滚。
+ - 端口由 Docker 容器发布时报 `PORT_BUSY_CONTAINER` 并写出容器名:容器里的 Nginx 由它自己的部署配置管理,Cindy 不改。其他程序占用报 `PORT_BUSY` 并写出程序名。
+ - 「连接线路」直接展示在「远程连接」页的「我的设备」下面,不另设入口行或子页(用户 2026-10-29 要求);原独立的「中转服务」折叠分区取消,设置搜索沿用旧别名。
+ - 线路是一个单选列表(官方 / 我的服务器 / 这台电脑当中转 / 已加入的中转):选中的那一行就是正在用的;其他行给切换图标,切换一律先弹确认,说明原线路会怎样(从官方切到自己的中转时说明手机系统推送、供应商分享和共享任务暂不可用)。部署中、未完成、移除中的状态显示在服务器那一行上。右侧只放同样大小的图标并贴右对齐:切换在前,这条线路自己的操作(服务器中转的删除、这台电脑当中转的设置)在后,没有的不占位,只有一个图标时它就在最右边;正在用的线路在名字旁边显示一个绿点(悬停与读屏为「正在使用」),不进图标列(文字和图标混在一列对不齐,用户 2026-10-29 反馈)。「加入别的中转」和这台电脑当中转的设置都用小窗口,不在列表下面展开;这台电脑当中转要先填设置,切换到它就是打开设置窗口。
+ - 部署是三步窗口(选择服务器 → 部署 → 添加设备):关窗口不中断部署;失败的一步下面写原因(技术细节折叠),失败后不再列出没执行的步骤,可重试、修改设置(回第 1 步,可换服务器)或放弃部署(清理服务器后删除记录)。换服务器时先按原身份清理原服务器上没完成的部署。完成页直接生成加入链接与二维码。
+ - 服务器中转的详情并入服务器那一行,且只在正在使用这条线路时显示(没在用时设备数、证书等没有意义,也不去请求):在线状态、已加入/在线设备数、证书剩余天数与版本来自 `deployment-status`(用部署记录里的主人凭证读 `admin/status`,中转 ID 不符按连不上处理),添加设备与升级在详情里,检查连接是状态旁的刷新图标。移除是行尾的图标按钮,先确认;服务器连不上或中转不归这台电脑时才提供「只在本机移除」。
- 已有 Nginx 的自动接入(2026-10-29,服务器 bundle `0.3.0`):
+ - 证书重试修复随 bundle `0.3.1` 提供;已部署 `0.3.0` 的用户通过现有升级入口上传新程序,设备档案与主人身份继续沿用,不改变线协议。
- 沿用同一个部署入口,自动判断 80/443 的占用者;原生 Nginx 自动接入,其他程序不停止、不接管。
+ - 上传暂存程序保留 `.mjs` 后缀(`relay.new.mjs`),Nginx 准备阶段可在正式安装前由 Node 执行;旧的 `relay.mjs.new` 会被 Node 拒绝(`ERR_UNKNOWN_FILE_EXTENSION`)。启动时尚无 CLI JSON 的错误也保留 Node 错误码,避免只显示笼统失败。回归通过 Desktop 部署入口指定的真实文件名调用原生 Node loader,防止 SSH fake 掩盖后缀错误。
- 从运行中的 master 与 `nginx -T` 找到实际配置,不要求用户选安装目录或复制配置。
- 访问地址已有可信 HTTPS 时沿用原证书管理,中转仅在回环地址提供 HTTP;否则中转在回环地址申请、续期证书,Nginx 转发 HTTP-01 验证并提供公网 HTTPS。
- 自动探测空闲回环端口,代理 REST、WebSocket 与媒体流;按访问地址及域名解析结果匹配实际监听 socket,保留无关 IP、原默认网站与域名证书。常见 ACME webroot 的其他验证文件在中转验证服务返回 404 或掉线时均可回退访问。
@@ -573,7 +584,12 @@ App 内不加扫码组件:加一个会改变原生指纹,需要冷更。
**远程管理**(设置 → 远程连接 → 中转服务):
- 部署表单:选择 SSH 主机,访问地址默认取 SSH 主机地址(IP 或域名),可以修改。
-- 部署进度逐步显示。
+- 部署进度逐步显示,当前步骤使用标准加载动画并显示耗时;下载、切换下载源、校验、解压和等待证书时显示实时进展。
+ 可展开带相对时间的部署日志,失败后保留步骤、日志和最终耗时,标题明确显示未完成。
+ 只展示受控的本地化事件,SSH 原始输出和凭证不进入进度日志;应用日志记录操作、步骤和失败码,便于排查。
+ 状态与日志仅在当前账号的内存中保存,日志最多 100 条;账号切换后的迟到进展不能覆盖新账号。
+ 进度事件只用于本机部署界面,不改变中转通信协议,也不要求已部署的中转内核更新。
+ 实现与回归见 `selfHostedRelayDeploy.ts`、`selfHostedRelayRuntime.ts` 及其同名单测;界面场景见 `scripts/fixtures/relay-service/`(均相对 Desktop)。
- 失败时给出原因与处理办法,例如安全组没放行 80 / 443、端口被占、没有 root。
- 可以重试,也可以清掉旧中转重新部署。
- 「我的服务器中转」:
diff --git a/packages/device-link-relay/src/__tests__/acme.test.ts b/packages/device-link-relay/src/__tests__/acme.test.ts
new file mode 100644
index 0000000000..c1223f0203
--- /dev/null
+++ b/packages/device-link-relay/src/__tests__/acme.test.ts
@@ -0,0 +1,56 @@
+/**
+ * 测试价值
+ * - 生产入口:AcmeClient.obtainCertificate;观察申请证书时网络抖动后的结果与错误分类。
+ * - Bug/规则依据:2026-10-29 实机,国内服务器连 Let's Encrypt 偶发失败,一次 `fetch failed` 就让整轮申请失败,
+ * 部署方随即回滚;错误也无法和「CA 拒绝验证」区分。
+ * - 现有覆盖缺口:certificates.test.ts 把 AcmeClient 整个替换掉,没有任何用例经过 ACME 请求本身。
+ * - 最小失败输入:目录请求与一次签名 POST 各断一次网;或 CA 一直连不上。
+ * - tier:unit;CA 为进程内 fetch 桩,重试等待注入为立即返回,无网络、无真实等待。
+ * - 单文件实测:0.50 秒(2 例,测试体 9ms,Windows)。
+ */
+import { expect, it, vi } from 'vitest';
+import { AcmeClient, AcmeError, AcmeNetworkError, createAccountKey } from '../acme';
+
+const CA = 'https://ca.invalid';
+const directory = { newNonce: `${CA}/nonce`, newAccount: `${CA}/account`, newOrder: `${CA}/order` };
+
+function networkError(code: string): TypeError {
+ return Object.assign(new TypeError('fetch failed'), { cause: Object.assign(new Error(code), { code }) });
+}
+
+function client(fetchImpl: typeof fetch, sleep = vi.fn(async () => {})) {
+ return { sleep, acme: new AcmeClient({ directoryUrl: `${CA}/directory`, accountKey: createAccountKey(), fetchImpl, sleep }) };
+}
+
+it('retries network blips and surfaces the certificate authority’s own answer', async () => {
+ const failOnce = new Set([`GET ${CA}/directory`, `POST ${CA}/account`]);
+ const fetchImpl = vi.fn(async (url: string | URL | Request, init?: RequestInit) => {
+ const key = `${init?.method ?? 'GET'} ${String(url)}`;
+ if (failOnce.delete(key)) throw networkError('ECONNRESET');
+ const nonce = { 'Replay-Nonce': 'nonce' };
+ if (key === `GET ${CA}/directory`) return new Response(JSON.stringify(directory));
+ if (key === `HEAD ${CA}/nonce`) return new Response(null, { headers: nonce });
+ if (key === `POST ${CA}/account`) return new Response('{}', { status: 201, headers: { ...nonce, Location: `${CA}/acct/1` } });
+ return new Response(JSON.stringify({ type: 'urn:ietf:params:acme:error:rejectedIdentifier', detail: 'not allowed' }), {
+ status: 400,
+ headers: nonce,
+ });
+ }) as unknown as typeof fetch;
+ const { acme, sleep } = client(fetchImpl);
+ const error = await acme.obtainCertificate({ type: 'ip', value: '203.0.113.10' }, new Map()).catch((e: unknown) => e);
+ expect(error).toBeInstanceOf(AcmeError);
+ expect(error).not.toBeInstanceOf(AcmeNetworkError);
+ expect((error as Error).message).toContain('rejectedIdentifier');
+ expect(sleep).toHaveBeenCalledTimes(2);
+});
+
+it('reports an unreachable certificate authority as a transient error with the network cause', async () => {
+ const fetchImpl = vi.fn(async () => {
+ throw networkError('ETIMEDOUT');
+ }) as unknown as typeof fetch;
+ const { acme } = client(fetchImpl);
+ const error = await acme.obtainCertificate({ type: 'ip', value: '203.0.113.10' }, new Map()).catch((e: unknown) => e);
+ expect(error).toBeInstanceOf(AcmeNetworkError);
+ expect(error).toMatchObject({ transient: true, message: expect.stringContaining('ETIMEDOUT') });
+ expect(fetchImpl).toHaveBeenCalledTimes(3);
+});
diff --git a/packages/device-link-relay/src/__tests__/certificates.test.ts b/packages/device-link-relay/src/__tests__/certificates.test.ts
index f9bfacd3cc..593432922f 100644
--- a/packages/device-link-relay/src/__tests__/certificates.test.ts
+++ b/packages/device-link-relay/src/__tests__/certificates.test.ts
@@ -14,6 +14,8 @@ const h = vi.hoisted(() => ({
files: new Map<string, string>(),
failCommit: false,
issued: { certPem: 'cert-key-one', keyPem: 'key-one', notBefore: 0, notAfter: 100_000 },
+ issueError: null as Error | null,
+ NetworkError: class extends Error {},
}));
vi.mock('node:fs/promises', () => ({
@@ -41,8 +43,12 @@ vi.mock('node:crypto', async importOriginal => ({
vi.mock('../acme', () => ({
AcmeClient: class {
accountUrl = null;
- async obtainCertificate() { return h.issued; }
+ async obtainCertificate() {
+ if (h.issueError) throw h.issueError;
+ return h.issued;
+ }
},
+ AcmeNetworkError: h.NetworkError,
createAccountKey: () => ({ export: () => 'test-account-key' }),
certificateValidity: () => ({ notBefore: 0, notAfter: 100_000 }),
LETS_ENCRYPT_DIRECTORY: 'https://ca.invalid/directory',
@@ -61,6 +67,19 @@ beforeEach(() => {
h.files.clear();
h.failCommit = false;
h.issued = { certPem: 'cert-key-one', keyPem: 'key-one', notBefore: 0, notAfter: 100_000 };
+ h.issueError = null;
+});
+
+// 部署方读 status.json 决定继续等还是报失败:暂时连不上 CA 必须标 transient,CA 拒绝验证不能标。
+it('marks only certificate-authority network failures as transient in the status file', async () => {
+ const status = () => JSON.parse(h.files.get(path.join(dataDir, 'status.json'))!).certificate;
+ h.issueError = new h.NetworkError('could not reach the certificate authority (ECONNRESET)');
+ await expect(manager().obtain()).rejects.toThrow('ECONNRESET');
+ expect(status()).toMatchObject({ state: 'failed', transient: true });
+ h.issueError = new Error('validation failed: connection refused');
+ await expect(manager().obtain()).rejects.toThrow('validation failed');
+ expect(status()).toMatchObject({ state: 'failed' });
+ expect(status().transient).toBeUndefined();
});
it('preserves the previous complete TLS identity when committing a renewal fails', async () => {
diff --git a/packages/device-link-relay/src/acme.ts b/packages/device-link-relay/src/acme.ts
index 2e63ba6c0d..d46a32d726 100644
--- a/packages/device-link-relay/src/acme.ts
+++ b/packages/device-link-relay/src/acme.ts
@@ -13,6 +13,9 @@ export const LETS_ENCRYPT_DIRECTORY = 'https://acme-v02.api.letsencrypt.org/dire
const VALIDATION_TIMEOUT_MS = 3 * 60 * 1000;
const POLL_INTERVAL_MS = 2_000;
+const REQUEST_TIMEOUT_MS = 30_000;
+/** 单个请求遇到网络中断、超时或 CA 临时不可用时,先短暂重试再放弃。 */
+const NETWORK_RETRY_DELAYS_MS = [2_000, 5_000];
export class AcmeError extends Error {
constructor(message: string) {
@@ -21,6 +24,25 @@ export class AcmeError extends Error {
}
}
+/** 连不上证书机构(断网、超时、连接被重置、CA 临时 5xx):稍后可以重试,与 CA 拒绝验证区分开。 */
+export class AcmeNetworkError extends AcmeError {
+ readonly transient = true;
+ constructor(message: string) {
+ super(message);
+ this.name = 'AcmeNetworkError';
+ }
+}
+
+/** fetch 的网络失败只有笼统的 `fetch failed`;取出底层原因(ECONNRESET、ETIMEDOUT…)便于排查。 */
+function networkFailureReason(error: unknown): string | null {
+ if (error instanceof AcmeError || !(error instanceof Error)) return null;
+ if (error.name === 'TimeoutError' || error.name === 'AbortError') return 'timed out';
+ if (!(error instanceof TypeError)) return null;
+ const cause = (error as { cause?: { code?: unknown; message?: unknown } }).cause;
+ const reason = typeof cause?.code === 'string' ? cause.code : typeof cause?.message === 'string' ? cause.message : error.message;
+ return reason.slice(0, 80);
+}
+
interface Directory {
newNonce: string;
newAccount: string;
@@ -107,10 +129,37 @@ export class AcmeClient {
return b64url(createHash('sha256').update(JSON.stringify({ crv, kty, x, y })).digest());
}
+ /** 发一个请求并读完响应体;网络失败与 CA 的 5xx 先重试,仍不行时抛 AcmeNetworkError。 */
+ private async send(url: string, init: RequestInit = {}): Promise<{ res: Response; text: string }> {
+ for (let attempt = 0; ; attempt++) {
+ let reason: string;
+ try {
+ const res = await this.fetchImpl(url, { ...init, signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS) });
+ const text = init.method === 'HEAD' ? '' : await res.text();
+ if (res.status < 500) return { res, text };
+ reason = `HTTP ${res.status}`;
+ } catch (error) {
+ const failure = networkFailureReason(error);
+ if (!failure) throw error;
+ reason = failure;
+ }
+ if (attempt >= NETWORK_RETRY_DELAYS_MS.length) {
+ throw new AcmeNetworkError(`could not reach the certificate authority (${reason})`);
+ }
+ this.log(`certificate authority unreachable (${reason}), retrying`);
+ await this.sleep(NETWORK_RETRY_DELAYS_MS[attempt]);
+ }
+ }
+
private async getDirectory(): Promise<Directory> {
if (this.directory) return this.directory;
- const res = await this.fetchImpl(this.options.directoryUrl);
- const body = (await res.json().catch(() => null)) as Directory | null;
+ const { res, text } = await this.send(this.options.directoryUrl);
+ let body: Directory | null = null;
+ try {
+ body = JSON.parse(text) as Directory;
+ } catch {
+ body = null;
+ }
if (!res.ok || !body?.newNonce || !body.newAccount || !body.newOrder) {
throw new AcmeError(`certificate authority directory unavailable (${res.status})`);
}
@@ -124,7 +173,7 @@ export class AcmeClient {
this.nonce = null;
return nonce;
}
- const res = await this.fetchImpl((await this.getDirectory()).newNonce, { method: 'HEAD' });
+ const { res } = await this.send((await this.getDirectory()).newNonce, { method: 'HEAD' });
const nonce = res.headers.get('replay-nonce');
if (!nonce) throw new AcmeError('certificate authority returned no nonce');
return nonce;
@@ -145,13 +194,13 @@ export class AcmeClient {
key: this.options.accountKey,
dsaEncoding: 'ieee-p1363',
});
- const res = await this.fetchImpl(url, {
+ // 网络重试可能把同一个 nonce 再发一次;CA 已用掉它时回 badNonce,下面换新 nonce 重签。
+ const { res, text } = await this.send(url, {
method: 'POST',
headers: { 'Content-Type': 'application/jose+json', ...(options.accept ? { Accept: options.accept } : {}) },
body: JSON.stringify({ protected: protectedPart, payload: payloadPart, signature: b64url(signature) }),
});
this.nonce = res.headers.get('replay-nonce');
- const text = await res.text();
let body: Record<string, any> | null = null;
try {
body = JSON.parse(text) as Record<string, any>;
diff --git a/packages/device-link-relay/src/certificates.ts b/packages/device-link-relay/src/certificates.ts
index cf6d9a5ea4..20678d0a1c 100644
--- a/packages/device-link-relay/src/certificates.ts
+++ b/packages/device-link-relay/src/certificates.ts
@@ -10,7 +10,14 @@ import { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
import { createServer, type Server } from 'node:http';
import type { AddressInfo } from 'node:net';
import path from 'node:path';
-import { AcmeClient, certificateValidity, createAccountKey, LETS_ENCRYPT_DIRECTORY, type IssuedCertificate } from './acme';
+import {
+ AcmeClient,
+ AcmeNetworkError,
+ certificateValidity,
+ createAccountKey,
+ LETS_ENCRYPT_DIRECTORY,
+ type IssuedCertificate,
+} from './acme';
import type { CertificateIdentifier } from './csr';
import type { RelayLogger } from './logger';
@@ -131,8 +138,10 @@ export class CertificateManager {
return { cert: issued.certPem, key: issued.keyPem, notBefore: issued.notBefore, notAfter: issued.notAfter };
} catch (error) {
const message = error instanceof Error ? error.message : 'unknown error';
- await this.writeStatus('failed', { error: message.slice(0, 500) });
- this.options.logger.error('certificate request failed', { reason: message.slice(0, 500) });
+ // transient:只是暂时连不上 CA,中转稍后自己重试;部署方据此继续等待,不当作验证失败。
+ const transient = error instanceof AcmeNetworkError;
+ await this.writeStatus('failed', { error: message.slice(0, 500), ...(transient ? { transient } : {}) });
+ this.options.logger.error('certificate request failed', { reason: message.slice(0, 500), transient });
throw error;
}
}
@@ -168,7 +177,7 @@ export class CertificateManager {
}
}
- async writeStatus(state: CertificateState, extra: { notAfter?: string; error?: string } = {}): Promise<void> {
+ async writeStatus(state: CertificateState, extra: { notAfter?: string; error?: string; transient?: boolean } = {}): Promise<void> {
const status = {
certificate: { state, identifier: this.options.identifier.value, ...extra, updatedAt: new Date(this.now()).toISOString() },
};
diff --git a/packages/device-link-relay/src/cli.ts b/packages/device-link-relay/src/cli.ts
index 17580bfabf..461e905482 100644
--- a/packages/device-link-relay/src/cli.ts
+++ b/packages/device-link-relay/src/cli.ts
@@ -15,6 +15,7 @@
* stdout 每行一个 JSON 事件(initialized / listening / error),供部署器解析;
* 日志写 stderr,不含凭证、加入码与签名地址。
*/
+import { AcmeNetworkError } from './acme';
import { CertificateManager, startChallengeServer, type TlsMaterial } from './certificates';
import { identifierFor } from './csr';
import { RelayError } from './errors';
@@ -29,6 +30,8 @@ import { isIP } from 'node:net';
const BOOLEAN_FLAGS = new Set(['trust-proxy', 'ipv6', 'existing-certificate']);
/** 首次申请证书失败后的重试间隔(Let's Encrypt 对同一名字每小时只允许几次失败验证)。 */
const ACME_RETRY_DELAYS_MS = [60_000, 5 * 60_000, 15 * 60_000, 30 * 60_000, 60 * 60_000];
+/** 只是连不上 CA(不算失败验证、不占配额)时更快重试,部署等待的几分钟里能多试几次。 */
+const ACME_NETWORK_RETRY_DELAYS_MS = [15_000, 30_000, 60_000, 2 * 60_000, 5 * 60_000];
const RENEWAL_CHECK_MS = 60 * 60 * 1000;
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
@@ -51,12 +54,16 @@ async function prepareAcme(flags: Map<string, string>, dataDir: string, host: st
await startChallengeServer({ host, port: parsePort(flags.get('acme-http-port'), 80, 'acme-http-port'), challenges: manager.challenges });
let material: TlsMaterial | null = await manager.load();
if (material && manager.needsRenewal(material)) material = null;
- for (let attempt = 0; !material; attempt++) {
+ let failures = 0;
+ let networkFailures = 0;
+ while (!material) {
emit({ event: 'certificate', status: 'requesting', identifier: identifier.value });
try {
material = await manager.obtain();
} catch (error) {
- const delay = ACME_RETRY_DELAYS_MS[Math.min(attempt, ACME_RETRY_DELAYS_MS.length - 1)];
+ const delays = error instanceof AcmeNetworkError ? ACME_NETWORK_RETRY_DELAYS_MS : ACME_RETRY_DELAYS_MS;
+ const index = error instanceof AcmeNetworkError ? networkFailures++ : failures++;
+ const delay = delays[Math.min(index, delays.length - 1)];
emit({ event: 'certificate', status: 'failed', retryInMs: delay, message: error instanceof Error ? error.message : 'unknown' });
// 证书还没到手但旧证书仍有效:先用旧的服务,后台继续申请。
const previous = await manager.load();
diff --git a/packages/device-link-relay/src/version.ts b/packages/device-link-relay/src/version.ts
index f7aa455f65..d2ab03b849 100644
--- a/packages/device-link-relay/src/version.ts
+++ b/packages/device-link-relay/src/version.ts
@@ -1,2 +1,2 @@
/** 中转程序版本:主人电脑据此提示升级服务器上的中转。改动 wire 行为时递增。 */
-export const RELAY_VERSION = '0.3.0';
+export const RELAY_VERSION = '0.3.1';