Skip to content

armgit / cindy

Public Imported from GitHub
0

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

feat(relay): manage multiple deployments without automatic switching

Liziec973dd0310a
diff --git a/apps/desktop/scripts/fixtures/relay-service/fixture.tsx b/apps/desktop/scripts/fixtures/relay-service/fixture.tsx
index 2f3d55802c..c86b0cc038 100644
--- a/apps/desktop/scripts/fixtures/relay-service/fixture.tsx
+++ b/apps/desktop/scripts/fixtures/relay-service/fixture.tsx
@@ -1,23 +1,43 @@
import { RelayServicePanel, useSelfHostedRelayState } from '../../../src/renderer/components/settings/RelayServicePanel';
-import type { SelfHostedRelayCommand, SelfHostedRelayState } from '../../../src/shared/selfHostedRelay';
-import { forbid, mountPage, subscription } from '../../ui-page/harness';
+import type {
+ RelayDeployProgressMessage,
+ RelayDeployStep,
+ SelfHostedRelayCommand,
+ SelfHostedRelayDeploymentView,
+ SelfHostedRelayState,
+} from '../../../src/shared/selfHostedRelay';
+import { forbid, mountPage } from '../../ui-page/harness';
-const deployment = {
+const deployment: SelfHostedRelayDeploymentView = {
+ relayId: '11111111-1111-4111-8111-111111111111',
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,
};
+/** multi:第二台服务器上的中转。 */
+const backup: SelfHostedRelayDeploymentView = {
+ relayId: '22222222-2222-4222-8222-222222222222',
+ sshHostId: 'backup-server', address: '198.51.100.20', baseUrl: 'https://198.51.100.20', name: 'Backup',
+ relayVersion: '0.3.1', deployedAt: '2026-10-30T00:00:00Z', active: false, upgradeAvailable: false,
+};
+
+const serverRelay = (record: SelfHostedRelayDeploymentView) => ({ name: record.name, baseUrl: record.baseUrl, role: 'owner' as const, origin: 'server' as const });
-/** default:官方在用、服务器中转已部署未使用;server:正在用服务器中转;host:这台电脑当中转在用。 */
+/**
+ * default:官方在用、服务器中转已部署未使用;server:正在用服务器中转;host:这台电脑当中转在用;
+ * multi:两台服务器,正在用第一台;retry-*:一次失败的部署;deploy-steady:从头部署一台。
+ */
function initialState(name: string): SelfHostedRelayState {
- const server = name === 'server';
+ const server = name === 'server' || name === 'multi';
const host = name === 'host';
- const recovering = name.startsWith('retry-') || name === 'join-error';
+ const recovering = name.startsWith('retry-');
+ const fresh = name === 'deploy-steady';
const finishedAt = Date.now();
+ const first = { ...deployment, active: server, ...(recovering ? { relayVersion: '' } : {}) };
return {
available: true,
mode: server || host ? 'self-hosted' : 'official',
relay: server
- ? { name: 'Test', baseUrl: deployment.baseUrl, role: 'owner', origin: 'server' }
+ ? serverRelay(deployment)
: host
? { name: 'This computer', baseUrl: 'http://127.0.0.1:47820', role: 'owner', origin: 'host' }
: null,
@@ -26,10 +46,10 @@ function initialState(name: string): SelfHostedRelayState {
enabled: host, running: host, error: null, port: 47820, listenAll: host, externalUrl: null,
suggestedUrls: ['http://192.168.1.20:47820'],
},
- deployment: { ...deployment, active: server, ...(recovering ? { relayVersion: '' } : {}) },
+ deployments: fresh ? [] : name === 'multi' ? [first, backup] : [first],
deployJob: recovering ? {
action: 'deploy', status: 'failed', step: 'runtime', error: 'DOWNLOAD_FAILED',
- startedAt: finishedAt - 15_000, finishedAt, serverChanged: true,
+ startedAt: finishedAt - 15_000, finishedAt, serverChanged: true, relayId: deployment.relayId,
target: { sshHostId: deployment.sshHostId, address: deployment.address, name: deployment.name, baseUrl: deployment.baseUrl },
logs: [{ at: finishedAt - 15_000, step: 'check' }, { at: finishedAt - 14_000, step: 'runtime' }],
} : null,
@@ -48,7 +68,31 @@ function Page() {
void mountPage({
host: ctx => {
let state = initialState(ctx.case);
- const recovering = ctx.case.startsWith('retry-') || ctx.case === 'join-error';
+ const recovering = ctx.case.startsWith('retry-');
+ const listeners = new Set<(next: SelfHostedRelayState) => void>();
+ const publish = (next: SelfHostedRelayState) => {
+ state = next;
+ for (const listener of listeners) listener(state);
+ };
+ // 部署完成只保存记录,不切换线路(与 main 一致)。
+ const finishDeploy = () => {
+ const job = state.deployJob!;
+ const record = { ...deployment, ...job.target!, relayId: job.relayId!, relayVersion: '0.3.1', active: false };
+ publish({
+ ...state,
+ deployments: [...state.deployments.filter((item) => item.relayId !== record.relayId), record],
+ deployJob: { ...job, step: 'finish', status: 'done', finishedAt: Date.now() },
+ });
+ };
+ // deploy-steady:场景逐步推进部署任务,轮询与推送读到的是同一份状态。
+ Object.assign(window, {
+ __relayDeployAdvance: (step: RelayDeployStep, message?: RelayDeployProgressMessage) => {
+ const job = state.deployJob!;
+ const logs = [...(job.logs ?? []), { at: (job.startedAt ?? 0) + (job.logs?.length ?? 0) * 1_000, step, ...(message ? { message } : {}) }];
+ publish({ ...state, deployJob: { ...job, step, logs } });
+ },
+ __relayDeployFinish: finishDeploy,
+ });
return {
selfHostedRelay: {
command: async (command: SelfHostedRelayCommand) => {
@@ -64,21 +108,60 @@ void mountPage({
}
if (recovering && command.type === 'deploy') {
if (command.replaceExisting !== (ctx.case === 'retry-replace')) return forbid('unexpected relay replacement')();
+ finishDeploy();
+ return { state };
+ }
+ if (ctx.case === 'deploy-steady' && command.type === 'check-server') {
+ // 检查要花一点时间:场景据此确认「检查中」和「可以部署」占同样的高度。
+ await new Promise((resolve) => setTimeout(resolve, 400));
+ return { state, check: { sshHostId: command.sshHostId, ok: true, system: 'Debian GNU/Linux 13 (trixie) · x86_64', plan: 'nginx', existing: 'none' } };
+ }
+ if (ctx.case === 'deploy-steady' && command.type === 'deploy') {
+ const startedAt = Date.now();
state = {
- ...state, mode: 'self-hosted',
- relay: { name: deployment.name, baseUrl: deployment.baseUrl, role: 'owner', origin: 'server' },
- deployment: { ...deployment, active: true },
- deployJob: { ...state.deployJob!, step: 'finish', status: 'done' },
+ ...state,
+ deployJob: {
+ action: 'deploy', status: 'running', step: 'check', startedAt, serverChanged: false,
+ relayId: '33333333-3333-4333-8333-333333333333',
+ target: { sshHostId: command.sshHostId, address: command.address, name: command.name, baseUrl: deployment.baseUrl },
+ logs: [{ at: startedAt, step: 'check' }],
+ },
+ };
+ return { state };
+ }
+ if (command.type === 'dismiss-deploy-job') {
+ state = { ...state, deployJob: state.deployJob?.status === 'running' ? state.deployJob : null };
+ return { state };
+ }
+ if (command.type === 'use-deployment') {
+ const record = state.deployments.find((item) => item.relayId === command.relayId)!;
+ state = {
+ ...state, mode: 'self-hosted', relay: serverRelay(record),
+ deployments: state.deployments.map((item) => ({ ...item, active: item.relayId === command.relayId })),
+ };
+ return { state };
+ }
+ if (ctx.case === 'multi' && command.type === 'rename-deployment') {
+ state = {
+ ...state,
+ deployments: state.deployments.map((item) => (item.relayId === command.relayId ? { ...item, name: command.name } : item)),
};
return { state };
}
- if (recovering && command.type === 'create-join-link') return { state, ...(ctx.case === 'join-error' ? { error: 'FAILED' } : {}) };
return forbid(`selfHostedRelay.command:${command.type}`)();
},
- onChanged: subscription('relayChanged'),
+ onChanged: (listener: (next: SelfHostedRelayState) => void) => {
+ listeners.add(listener);
+ return () => listeners.delete(listener);
+ },
},
remoteSsh: {
- list: async () => ({ hosts: [{ config: { id: 'demo-server', displayName: 'demo-server', hostname: '203.0.113.10', user: 'root' } }] }),
+ list: async () => ({
+ hosts: [
+ { config: { id: 'demo-server', displayName: 'demo-server', hostname: '203.0.113.10', user: 'root' } },
+ { config: { id: 'backup-server', displayName: 'backup-server', hostname: '198.51.100.20', user: 'root' } },
+ ],
+ }),
},
};
},
diff --git a/apps/desktop/scripts/fixtures/relay-service/ui-page.mjs b/apps/desktop/scripts/fixtures/relay-service/ui-page.mjs
index 8fbc205832..9e3ad2c809 100644
--- a/apps/desktop/scripts/fixtures/relay-service/ui-page.mjs
+++ b/apps/desktop/scripts/fixtures/relay-service/ui-page.mjs
@@ -4,7 +4,7 @@ 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',
+ real: 'RelayServicePanel and useSelfHostedRelayState: route list with one row per server, icon-only switch/rename/remove actions, server details, deploy, rename, 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' },
@@ -13,7 +13,8 @@ export default {
'retry-replace': { about: 'A failed replacement rechecks the server and asks again before clearing its relay' },
'retry-own': { about: 'A failed deployment retains its elapsed time and retries its own relay without clearing it' },
'retry-check-error': { about: 'A failed retry check stays in the deployment dialog with a visible error' },
- 'join-error': { about: 'The completed deployment shows join-link failures inside the open dialog' },
+ 'deploy-steady': { about: 'Choosing a server, its check, each deployment step and the finished page keep the dialog and form fields in place' },
+ multi: { about: 'Two server relays, one in use; renaming the other and deploying again stay available' },
},
async check(page, ui) {
const route = 'settings.remoteControl.relay.route';
@@ -22,7 +23,7 @@ export default {
const serverRow = page.getByRole('listitem').filter({ hasText: 'Test' });
const serverButtons = serverRow.getByRole('button');
// #7921 review:真实组件回归替换重试、失败用时和弹窗内错误;旧场景只有成功状态。
- if (ui.case.startsWith('retry-') || ui.case === 'join-error') {
+ if (ui.case.startsWith('retry-')) {
const deploy = `${relay}.deploy`;
await page.getByRole('button', { name: await ui.t(`${route}.resume`), exact: true }).click();
const dialog = page.getByRole('dialog', { name: await ui.t(`${deploy}.title`), exact: true });
@@ -47,18 +48,96 @@ export default {
assert.ok(await dialog.getByRole('button', { name: await ui.t(`${deploy}.retry`), exact: true }).isVisible());
await ui.capture('retry-check-error');
} else {
+ // 用户 2026-10-30:部署完成不自动切换。完成页给「使用这条线路」,切换照常先确认。
await dialog.getByText(await ui.t(`${relay}.dialog.doneTitle`, { name: 'Test' }), { exact: true }).waitFor({ timeout: 3_000 });
- if (ui.case === 'join-error') {
- await dialog.getByRole('alert').filter({ hasText: await ui.t(`${relay}.errors.FAILED`) }).waitFor({ timeout: 3_000 });
- await ui.capture('join-link-error');
+ // 窗口打开时列表对读屏隐藏,这里按 DOM 查:服务器那一行没有被选中。
+ const inUseRow = page.locator('li[aria-current="true"]');
+ assert.equal(await inUseRow.filter({ hasText: 'Test' }).count(), 0);
+ const use = dialog.getByRole('button', { name: await ui.t(`${relay}.dialog.use`), exact: true });
+ await ui.capture('done');
+ if (ui.case === 'retry-own') {
+ await use.click();
+ const confirmation = page.getByRole('alertdialog', { name: await ui.t(`${route}.switchTitle`, { name: 'Test' }), exact: true });
+ await confirmation.getByRole('button', { name: await ui.t(`${route}.switchConfirm`), exact: true }).click();
+ await inUseRow.filter({ hasText: 'Test' }).waitFor({ timeout: 3_000 });
+ } else {
+ await dialog.getByRole('button', { name: await ui.t(`${relay}.dialog.finish`), exact: true }).click();
+ await dialog.waitFor({ state: 'detached' });
+ assert.equal(await page.getByRole('listitem').first().getAttribute('aria-current'), 'true');
}
}
+ } else if (ui.case === 'deploy-steady') {
+ // 用户 2026-10-30 反馈部署过程中窗口高度来回跳:选服务器、检查出结果、开始部署、
+ // 每一步推进时,窗口位置和大小都不变,表单的输入框和步骤列表也不被推动。
+ const deploy = `${relay}.deploy`;
+ await page.getByRole('button', { name: await ui.t(`${relay}.actions.deploy`), exact: true }).click();
+ const dialog = page.getByRole('dialog', { name: await ui.t(`${deploy}.title`), exact: true });
+ await dialog.waitFor();
+ const frame = await dialog.boundingBox();
+ const assertFrame = async (moment) => {
+ const box = await dialog.boundingBox();
+ assert.deepEqual([box.y, box.height], [frame.y, frame.height], `deploy dialog moved or resized: ${moment}`);
+ };
+ const address = dialog.getByRole('textbox', { name: await ui.t(`${deploy}.address`), exact: true });
+ const addressY = (await address.boundingBox()).y;
+ const assertForm = async (moment) => {
+ await assertFrame(moment);
+ assert.equal((await address.boundingBox()).y, addressY, `address field moved: ${moment} (${(await address.boundingBox()).y} vs ${addressY})`);
+ };
+ await ui.capture('form-idle');
+ await dialog.getByRole('combobox', { name: await ui.t(`${deploy}.serverPlaceholder`) }).click();
+ await page.getByRole('option').first().click();
+ await dialog.getByText(await ui.t(`${deploy}.check.checking`), { exact: true }).waitFor();
+ await assertForm('checking');
+ await ui.capture('form-checking');
+ await dialog.getByRole('status').filter({ hasText: await ui.t(`${deploy}.check.ready`) }).waitFor({ timeout: 3_000 });
+ await assertForm('ready');
+ await ui.capture('form-ready');
+ await dialog.getByRole('button', { name: await ui.t(`${deploy}.submit`), exact: true }).click();
+ await dialog.getByRole('progressbar').waitFor();
+ await assertFrame('progress');
+ const steps = dialog.getByRole('list').last().getByRole('listitem');
+ const stepY = () => steps.evaluateAll((items) => items.map((item) => item.getBoundingClientRect().y));
+ const initialStepY = await stepY();
+ const progress = [['runtime'], ['runtime', 'runtime-download'], ['runtime', 'runtime-extract'], ['upload'], ['configure', 'nginx-prepare'], ['certificate', 'certificate-wait']];
+ for (const [step, message] of progress) {
+ await page.evaluate(([s, m]) => globalThis.__relayDeployAdvance(s, m), [step, message]);
+ await dialog.locator('[aria-current="step"]').filter({ hasText: await ui.t(`${deploy}.steps.${step}`) }).waitFor();
+ const moment = `${step} ${message ?? ''}`;
+ await assertFrame(moment);
+ assert.deepEqual(await stepY(), initialStepY, `steps moved: ${moment}`);
+ }
+ await ui.capture('progress-certificate');
+ await page.evaluate(() => globalThis.__relayDeployFinish());
+ await dialog.getByText(await ui.t(`${relay}.dialog.doneTitle`, { name: await ui.t(`${deploy}.defaultName`) }), { exact: true }).waitFor();
+ await assertFrame('done');
+ assert.ok(await dialog.getByRole('button', { name: await ui.t(`${relay}.dialog.use`), exact: true }).isVisible());
+ await ui.capture('done');
+ } else if (ui.case === 'multi') {
+ // 用户 2026-10-30:能部署多台服务器,部署完能改名。每台一行;没在用的那台可以切换、改名、移除。
+ const backupRow = page.getByRole('listitem').filter({ hasText: 'Backup' });
+ assert.equal(await serverRow.getAttribute('aria-current'), 'true');
+ assert.ok(await serverRow.getByText(await ui.t(`${relay}.manage.deviceCount`, { count: 3 }), { exact: true }).isVisible());
+ assert.deepEqual(
+ await backupRow.getByRole('button').evaluateAll((buttons) => buttons.map((button) => button.getAttribute('aria-label'))),
+ [await ui.t(`${route}.useNamed`, { name: 'Backup' }), await ui.t(`${route}.rename`), removeLabel],
+ );
+ assert.ok(await page.getByRole('button', { name: await ui.t(`${relay}.actions.deploy`), exact: true }).isEnabled());
+ await backupRow.getByRole('button', { name: await ui.t(`${route}.rename`), exact: true }).click();
+ const dialog = page.getByRole('dialog', { name: await ui.t(`${route}.rename`), exact: true });
+ const input = dialog.getByRole('textbox', { name: await ui.t(`${relay}.deploy.name`), exact: true });
+ await input.fill('Office');
+ await ui.capture('rename-dialog');
+ await input.press('Enter');
+ await dialog.waitFor({ state: 'detached' });
+ await page.getByRole('listitem').filter({ hasText: 'Office' }).waitFor({ timeout: 3_000 });
} else if (ui.case === 'default') {
- // 切换在前、删除在后,都只有图标。
+ // 切换在前、改名和删除在后,都只有图标。
const switchLabel = await ui.t(`${route}.useNamed`, { name: 'Test' });
- assert.equal(await serverButtons.count(), 2);
+ assert.equal(await serverButtons.count(), 3);
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(1).getAttribute('aria-label'), await ui.t(`${route}.rename`));
+ assert.equal(await serverButtons.nth(2).getAttribute('aria-label'), removeLabel);
assert.equal((await serverButtons.nth(0).innerText()).trim(), '');
// 右侧只放图标、贴右对齐:只有一个图标的行它就在最右边;正在使用的绿点在线路名旁边,
// 不挤进图标列(用户 2026-10-29 反馈没对齐、单个切换图标要靠右)。
@@ -67,9 +146,11 @@ export default {
.getByRole('listitem')
.filter({ hasText: hostTitle })
.getByRole('button', { name: await ui.t(`${route}.useNamed`, { name: hostTitle }), exact: true });
+ // 新部署随时可以开始,不因为已有一台服务器而隐藏。
+ assert.ok(await page.getByRole('button', { name: await ui.t(`${relay}.actions.deploy`), exact: true }).isEnabled());
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()),
+ [serverButtons.nth(0), serverButtons.nth(2), hostSwitch, inUse].map((locator) => locator.boundingBox()),
);
assert.equal(hostSwitchBox.x + hostSwitchBox.width, removeBox.x + removeBox.width);
assert.ok(removeBox.x >= serverSwitchBox.x + serverSwitchBox.width);
diff --git a/apps/desktop/src/main/device-link/__tests__/selfHostedRelayConfig.test.ts b/apps/desktop/src/main/device-link/__tests__/selfHostedRelayConfig.test.ts
new file mode 100644
index 0000000000..0786868544
--- /dev/null
+++ b/apps/desktop/src/main/device-link/__tests__/selfHostedRelayConfig.test.ts
@@ -0,0 +1,76 @@
+/**
+ * 测试价值
+ * - 生产入口与可观察结果:readRelayConfig / writeRelayConfig 读写账号目录下的 config.json;
+ * 升级后旧版本写的单条部署记录仍在列表里,新版本写出的文件里旧字段 `deployment` 仍有一条,装回旧版本不丢失。
+ * - Bug/规则依据:用户 2026-10-30 要求能部署多台服务器,部署记录由单个 `deployment` 改为 `deployments` 列表
+ * (docs/self-hosted-relay-plan.md §15.5);格式变化不能让已部署用户的记录消失。
+ * - 现有覆盖缺口:selfHostedRelayRuntime.test.ts 把本模块整个替换成内存 fake,没有经过真实的解析与写入。
+ * - 最小失败输入:只有旧字段 `deployment` 的 config.json;写入两条记录且第二条正在使用。
+ * - tier:unit;fs 与 Electron 为进程内 fake,无磁盘与钥匙串。单独成文件:运行时测试 mock 了本模块,不能共用。
+ * - 实测耗时:0.86 秒(1 例,测试体 3ms,Windows)。
+ */
+import { beforeEach, expect, it, vi } from 'vitest';
+
+const files = vi.hoisted(() => new Map<string, string>());
+
+vi.mock('node:fs', () => ({
+ default: {
+ readFileSync: (file: string) => {
+ const content = files.get(file);
+ if (content === undefined) throw Object.assign(new Error('missing'), { code: 'ENOENT' });
+ return content;
+ },
+ writeFileSync: (file: string, content: string) => { files.set(file, content); },
+ renameSync: (from: string, to: string) => { files.set(to, files.get(from)!); files.delete(from); },
+ mkdirSync: vi.fn(),
+ rmSync: (file: string) => { files.delete(file); },
+ },
+}));
+vi.mock('electron', () => ({ safeStorage: { isEncryptionAvailable: () => true } }));
+vi.mock('../../appSessionState.js', () => ({
+ activeOwnerScopeKey: () => 'account-a',
+ getActiveAppSession: () => ({ dataOwnerId: 'account-a' }),
+ ownerScopedUserDataPath: (...parts: string[]) => parts.join('/'),
+}));
+vi.mock('../../logger.js', () => ({ createLogger: () => ({ info: vi.fn(), warn: vi.fn(), error: vi.fn() }) }));
+vi.mock('../../plugin-oauth/identityStore.js', () => ({ oauthSecureStorageAvailable: () => true }));
+vi.mock('../selfHostedRelayRouting.js', () => ({ setSelfHostedRelaySource: vi.fn() }));
+
+import { invalidateRelayConfigCache, readRelayConfig, writeRelayConfig, type RelayDeployment } from '../selfHostedRelayConfig';
+
+const CONFIG = 'device-link-relay/config.json';
+const KEY = 'A'.repeat(43);
+
+function deployment(index: number): RelayDeployment {
+ return {
+ sshHostId: `server-${index}`, address: `203.0.113.${index}`, baseUrl: `https://203.0.113.${index}`,
+ relayId: `0000000${index}-0000-4000-8000-000000000000`, name: `Relay ${index}`, ownerPublicKey: KEY,
+ relayVersion: '0.3.1', deployedAt: '2026-10-29T00:00:00.000Z', complete: true,
+ };
+}
+
+const host = { enabled: false, port: 47820, listenAll: false, externalUrl: null, relayId: null };
+
+beforeEach(() => {
+ files.clear();
+ invalidateRelayConfigCache();
+});
+
+it('reads a legacy single deployment and writes the list with a legacy copy older versions can read', () => {
+ files.set(CONFIG, JSON.stringify({ version: 2, active: null, host, deployment: deployment(1) }));
+ expect(readRelayConfig().deployments).toEqual([deployment(1)]);
+
+ const second = deployment(2);
+ writeRelayConfig({
+ version: 2,
+ host,
+ active: { relayId: second.relayId, name: second.name, baseUrl: second.baseUrl, role: 'owner', origin: 'server', deviceId: 'device', ownerPublicKey: KEY },
+ // 同一台服务器重复的记录只留第一条。
+ deployments: [deployment(1), second, { ...deployment(3), sshHostId: 'server-1' }],
+ });
+ const written = JSON.parse(files.get(CONFIG)!);
+ // 旧版本只认 `deployment`:写正在用的那一条。
+ expect(written.deployment).toEqual(second);
+ invalidateRelayConfigCache();
+ expect(readRelayConfig().deployments).toEqual([deployment(1), second]);
+});
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 472233b132..d36d9ca123 100644
--- a/apps/desktop/src/main/device-link/__tests__/selfHostedRelayRuntime.test.ts
+++ b/apps/desktop/src/main/device-link/__tests__/selfHostedRelayRuntime.test.ts
@@ -1,18 +1,19 @@
/**
* 测试价值
- * - 生产入口与可观察结果:注册后的 self-hosted-relay:command IPC;部署完成会保存并切换中转,
- * 账号切换后的迟到部署/退出响应不能改写新账号配置或覆盖新部署进度。
+ * - 生产入口与可观察结果:注册后的 self-hosted-relay:command IPC;部署完成只保存记录、不切换线路,
+ * 多台服务器各留一条记录,改名只改本机记录;账号切换后的迟到部署/退出响应不能改写新账号配置或覆盖新部署进度。
* - Bug/规则依据:appSessionState.activeOwnerScopeKey 的异步账号边界;原部署回调跨 await 读取当前账号,
* 会将旧账号的部署记录写入新账号,切换中转在等待退出旧中转时也有同样问题。
* - 现有覆盖缺口:部署器测试只验证 SSH 步骤,没有经过运行时 IPC 与账号切换,故单独覆盖该模块。
* - 最小失败输入:挂起一次部署或退出请求,换账号,再让原请求完成。
* - tier:unit;SSH、存储和 Electron 为进程内 fake,无网络、磁盘或真实等待。
- * - 单文件实测:1.08 秒(9 例,测试体 41ms,Windows)。
+ * - 单文件实测:1.32 秒(15 例,测试体 44ms,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';
+import { RELAY_DEPLOY_STEPS } from '../../../shared/selfHostedRelay';
const h = vi.hoisted(() => ({
owner: 'account-a',
@@ -86,7 +87,7 @@ vi.mock('../selfHostedRelayConfig.js', () => ({
import { getState, registerSelfHostedRelayIpc } from '../selfHostedRelayRuntime';
function emptyConfig(): RelayConfig {
- return { version: 2, active: null, host: { enabled: false, port: 47820, listenAll: false, externalUrl: null, relayId: null }, deployment: null };
+ return { version: 2, active: null, host: { enabled: false, port: 47820, listenAll: false, externalUrl: null, relayId: null }, deployments: [] };
}
function deferred<T>() {
@@ -121,27 +122,88 @@ beforeEach(async () => {
afterEach(() => { vi.useRealTimers(); vi.unstubAllGlobals(); });
-it('records a completed deployment and activates it for the account that started it', async () => {
+const deploymentOf = (owner = 'account-a', sshHostId = 'test-server') =>
+ h.config.get(owner)!.deployments.find((deployment) => deployment.sshHostId === sshHostId);
+
+// 用户 2026-10-30:部署是部署,切换要让用户自己切。原实现部署完成就改用新中转。
+// 最小输入:官方线路上部署一次,再显式 use-deployment。tier: unit。
+it('records a completed deployment without switching, and switches only when asked', async () => {
h.deploy.mockResolvedValue({ relayVersion: '0.2.0' });
await command(deployCommand);
await vi.runAllTimersAsync();
- expect(h.config.get('account-a')?.deployment?.complete).toBe(true);
- expect(h.config.get('account-a')?.active?.origin).toBe('server');
- expect(getState().deployJob?.status).toBe('done');
+ expect(deploymentOf()?.complete).toBe(true);
+ expect(h.config.get('account-a')?.active).toBeNull();
+ expect(getState().deployJob).toMatchObject({ status: 'done', relayId: deploymentOf()!.relayId });
+ expect(getState().deployments[0]).toMatchObject({ active: false, relayVersion: '0.2.0' });
+ expect(h.restart).not.toHaveBeenCalled();
+ await command({ type: 'use-deployment', relayId: deploymentOf()!.relayId });
+ expect(h.config.get('account-a')?.active).toMatchObject({ origin: 'server', relayId: deploymentOf()!.relayId });
expect(h.restart).toHaveBeenCalledOnce();
});
+// 用户 2026-10-30:部署了一个就不能再部署。最小输入:两台服务器各部署一次,第二台部署时第一台正在使用。
+// 第一台的记录、身份与正在用的线路都不受影响;同一台再部署沿用原身份。tier: unit。
+it('keeps one relay per server and deploys to another server alongside the one in use', async () => {
+ h.deploy.mockResolvedValue({ relayVersion: '0.2.0' });
+ await command(deployCommand);
+ await vi.runAllTimersAsync();
+ const first = deploymentOf()!;
+ await command({ type: 'use-deployment', relayId: first.relayId });
+ h.restart.mockClear();
+ h.deploy.mockImplementationOnce(async (params: DeployParams) => {
+ params.onServerChange?.();
+ return { relayVersion: '0.2.0' };
+ });
+ await command({ ...deployCommand, sshHostId: 'other-server', address: '203.0.113.20', name: 'Second relay' });
+ await vi.runAllTimersAsync();
+ const config = h.config.get('account-a')!;
+ expect(config.deployments.map((deployment) => deployment.sshHostId)).toEqual(['test-server', 'other-server']);
+ expect(config.active?.relayId).toBe(first.relayId);
+ expect(h.deleteSecrets).not.toHaveBeenCalled();
+ expect(h.uninstall).not.toHaveBeenCalled();
+ expect(h.restart).not.toHaveBeenCalled();
+ h.deploy.mockResolvedValueOnce({ relayVersion: '0.2.0' });
+ await command(deployCommand);
+ await vi.runAllTimersAsync();
+ expect(h.deploy.mock.calls.at(-1)![0].init.relayId).toBe(first.relayId);
+ expect(h.config.get('account-a')!.deployments).toHaveLength(2);
+});
+
+// 用户 2026-10-30:部署完要能改名字。只改本机记录;正在用时当前线路名同步,部署中改名不被完成覆盖。tier: unit。
+it('renames a deployment locally, including the route in use and a deployment still running', async () => {
+ h.deploy.mockResolvedValueOnce({ relayVersion: '0.2.0' });
+ await command(deployCommand);
+ await vi.runAllTimersAsync();
+ const relayId = deploymentOf()!.relayId;
+ await command({ type: 'use-deployment', relayId });
+ h.restart.mockClear();
+ expect((await command({ type: 'rename-deployment', relayId, name: 'Office relay' })).error).toBeUndefined();
+ expect(deploymentOf()?.name).toBe('Office relay');
+ expect(h.config.get('account-a')?.active?.name).toBe('Office relay');
+ expect(h.restart).not.toHaveBeenCalled();
+ const upgrading = deferred<{ relayVersion: string }>();
+ h.deploy.mockReturnValueOnce(upgrading.promise);
+ await command({ type: 'upgrade-deployment', relayId });
+ await command({ type: 'rename-deployment', relayId, name: 'Home relay' });
+ upgrading.resolve({ relayVersion: '0.2.1' });
+ await vi.runAllTimersAsync();
+ expect(deploymentOf()).toMatchObject({ name: 'Home relay', relayVersion: '0.2.1' });
+ expect(h.config.get('account-a')?.active?.name).toBe('Home relay');
+ expect(h.restart).toHaveBeenCalledOnce();
+ expect((await command({ type: 'rename-deployment', relayId: '00000000-0000-4000-8000-000000000000', name: 'X' })).error).toBe('NO_DEPLOYMENT');
+});
+
// 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);
+ expect((await command({ type: 'state' })).state.deployments[0]?.upgradeAvailable).toBe(true);
h.deploy.mockResolvedValueOnce({ relayVersion: RELAY_VERSION });
- await command({ type: 'upgrade-deployment' });
+ await command({ type: 'upgrade-deployment', relayId: deploymentOf()!.relayId });
await vi.runAllTimersAsync();
- expect((await command({ type: 'state' })).state.deployment).toMatchObject({
+ expect((await command({ type: 'state' })).state.deployments[0]).toMatchObject({
relayVersion: RELAY_VERSION, upgradeAvailable: false,
});
});
@@ -152,19 +214,19 @@ it('reads the deployed relay status with the owner credential and rejects anothe
h.deploy.mockResolvedValue({ relayVersion: '0.2.0' });
await command(deployCommand);
await vi.runAllTimersAsync();
- const relayId = h.config.get('account-a')!.deployment!.relayId;
+ const relayId = deploymentOf()!.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' });
+ const status = await command({ type: 'deployment-status', relayId });
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 });
+ expect((await command({ type: 'deployment-status', relayId })).deploymentStatus).toEqual({ online: false });
});
// 2026-10-29:部署期间看不出进展;原测试只看终态,未覆盖 SSH 尚未结束时的状态推送。
@@ -201,29 +263,29 @@ it('keeps no deployment record when deployment stops before changing the server'
h.deploy.mockRejectedValueOnce(new Error('ports busy'));
await command(deployCommand);
await vi.runAllTimersAsync();
- expect(h.config.get('account-a')!.deployment).toBeNull();
+ expect(h.config.get('account-a')!.deployments).toEqual([]);
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 () => {
+// 没完成的部署不影响部署到另一台服务器:原服务器那条记录与身份留着,之后可以继续或放弃。tier: unit。
+it('keeps an unfinished deployment when deploying to another server', async () => {
h.deploy.mockImplementationOnce(failAfterServerChange);
await command(deployCommand);
await vi.runAllTimersAsync();
- const previous = structuredClone(h.config.get('account-a')!.deployment!);
- h.uninstall.mockResolvedValueOnce(undefined);
+ const previous = structuredClone(deploymentOf()!);
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 });
+ expect(getState().deployJob).toMatchObject({ status: 'done', steps: [...RELAY_DEPLOY_STEPS] });
+ expect(h.uninstall).not.toHaveBeenCalled();
+ expect(h.deleteSecrets).not.toHaveBeenCalled();
+ expect(deploymentOf()).toEqual(previous);
+ expect(deploymentOf('account-a', 'other-server')).toMatchObject({ complete: true });
});
// Bug:重启后进度对象不存在,持久部署记录仍须能继续,并保留已写入服务器的主人身份。tier: unit。
@@ -231,16 +293,16 @@ it('resumes an incomplete persisted deployment with the same relay identity', as
h.deploy.mockImplementationOnce(failAfterServerChange);
await command(deployCommand);
await vi.runAllTimersAsync();
- const previous = structuredClone(h.config.get('account-a')!.deployment!);
+ const previous = structuredClone(deploymentOf()!);
await switchOwner('account-b');
await switchOwner('account-a');
expect(getState().deployJob).toBeNull();
- expect(getState().deployment?.relayVersion).toBe('');
+ expect(getState().deployments[0]?.relayVersion).toBe('');
h.deploy.mockResolvedValueOnce({ relayVersion: '0.2.0' });
await command(deployCommand);
await vi.runAllTimersAsync();
expect(h.deploy.mock.calls.at(-1)![0].init.relayId).toBe(previous.relayId);
- expect(h.config.get('account-a')!.deployment?.complete).toBe(true);
+ expect(deploymentOf()?.complete).toBe(true);
});
it.each(['resolve', 'reject'] as const)('ignores an old deployment that later %s after a new account starts its own', async (outcome) => {
@@ -332,7 +394,7 @@ it('does not remove another account’s deployment after a delayed uninstall', a
await vi.runAllTimersAsync();
const uninstall = deferred<void>();
h.uninstall.mockReturnValueOnce(uninstall.promise);
- await command({ type: 'uninstall-deployment', removeData: true });
+ await command({ type: 'uninstall-deployment', relayId: deploymentOf()!.relayId, removeData: true });
await switchOwner('account-b');
h.write.mockClear();
h.deleteSecrets.mockClear();
diff --git a/apps/desktop/src/main/device-link/selfHostedRelayConfig.ts b/apps/desktop/src/main/device-link/selfHostedRelayConfig.ts
index fac87d5d09..415da600d0 100644
--- a/apps/desktop/src/main/device-link/selfHostedRelayConfig.ts
+++ b/apps/desktop/src/main/device-link/selfHostedRelayConfig.ts
@@ -1,7 +1,8 @@
/**
* 自建中转的本机配置与秘密(按当前账号隔离)。
*
- * - `config.json`:当前用哪个中转(官方 / 自建)、本机中转的开启设置、部署到服务器的中转记录。不含秘密。
+ * - `config.json`:当前用哪个中转(官方 / 自建)、本机中转的开启设置、部署到服务器的中转记录(一台服务器一条)。
+ * 不含秘密。记录列表存在 `deployments`;同时把其中一条写进旧字段 `deployment`,装回旧版本时仍能看到它。
* - `secrets/<中转ID>.enc`:本机在这个中转上的设备凭证与签名私钥,经 Electron safeStorage
* (钥匙串 / DPAPI)加密。Linux 只有明文后端(basic_text)时不保存,直接报不可用。
* 主人(本机中转 / 部署的服务器中转)与成员(加入的中转)都按中转 ID 各存一份:切走再切回不用重新加入。
@@ -70,7 +71,8 @@ export interface RelayConfig {
/** null = 使用 Cindy 官方中转。 */
active: ActiveRelay | null;
host: RelayHostSettings;
- deployment: RelayDeployment | null;
+ /** 部署到服务器的中转,按部署顺序;中转 ID 与 SSH 主机都不重复。 */
+ deployments: RelayDeployment[];
}
/** 本机在某个中转上的秘密。 */
@@ -84,7 +86,7 @@ const DEFAULT_CONFIG: RelayConfig = {
version: CONFIG_VERSION,
active: null,
host: { enabled: false, port: DEFAULT_RELAY_PORT, listenAll: false, externalUrl: null, relayId: null },
- deployment: null,
+ deployments: [],
};
interface Cache {
@@ -167,6 +169,19 @@ function parseDeployment(raw: unknown): RelayDeployment | null {
};
}
+/** 新版本存 `deployments`;只有旧字段 `deployment` 时(旧版本写的)按一条读入。重复的中转或服务器只留第一条。 */
+function parseDeployments(value: Record<string, unknown>): RelayDeployment[] {
+ const raw = Array.isArray(value.deployments) ? value.deployments : [value.deployment];
+ const result: RelayDeployment[] = [];
+ for (const item of raw) {
+ const deployment = parseDeployment(item);
+ if (deployment && !result.some((d) => d.relayId === deployment.relayId || d.sshHostId === deployment.sshHostId)) {
+ result.push(deployment);
+ }
+ }
+ return result;
+}
+
function parseConfig(raw: unknown): RelayConfig {
if (!raw || typeof raw !== 'object') return structuredClone(DEFAULT_CONFIG);
const value = raw as Record<string, unknown>;
@@ -183,10 +198,15 @@ function parseConfig(raw: unknown): RelayConfig {
externalUrl: typeof host.externalUrl === 'string' && host.externalUrl ? host.externalUrl : null,
relayId: current && isString(host.relayId) && RELAY_ID_PATTERN.test(host.relayId) ? host.relayId : null,
},
- deployment: current ? parseDeployment(value.deployment) : null,
+ deployments: current ? parseDeployments(value) : [],
};
}
+/** 写给旧版本看的那一条:正在用的优先,否则第一条。 */
+function legacyDeployment(config: RelayConfig): RelayDeployment | null {
+ return config.deployments.find((d) => d.relayId === config.active?.relayId) ?? config.deployments[0] ?? null;
+}
+
function secretsFile(relayId: string): string {
return relayDataPath('secrets', `${relayId}.enc`);
}
@@ -296,7 +316,7 @@ function requireSignedIn(): void {
export function writeRelayConfig(next: RelayConfig): void {
requireSignedIn();
const state = load();
- writeAtomically(relayDataPath('config.json'), JSON.stringify(next, null, 2));
+ writeAtomically(relayDataPath('config.json'), JSON.stringify({ ...next, deployment: legacyDeployment(next) }, null, 2));
state.config = structuredClone(next);
}
diff --git a/apps/desktop/src/main/device-link/selfHostedRelayRuntime.ts b/apps/desktop/src/main/device-link/selfHostedRelayRuntime.ts
index 23ef2fd864..f548a6a6a4 100644
--- a/apps/desktop/src/main/device-link/selfHostedRelayRuntime.ts
+++ b/apps/desktop/src/main/device-link/selfHostedRelayRuntime.ts
@@ -4,7 +4,8 @@
* - 在这台电脑上开启中转(方式 B):Cindy 主进程内运行 `@cindy/device-link-relay`,本机作为主人设备
* 连 `http://127.0.0.1:<端口>`;别的设备怎么访问到这台电脑由用户保证,Cindy 只列出本机地址。
* - 部署到自己的服务器(方式 C):经已配置的 SSH 主机安装同一个中转内核,自动申请证书;本机是主人,
- * 远程生成加入链接、审批设备、升级与卸载(selfHostedRelayDeploy.ts)。
+ * 远程生成加入链接、审批设备、升级与卸载(selfHostedRelayDeploy.ts)。可以部署到多台服务器(一台一个);
+ * 部署完成只保存记录,改用哪条线路由用户自己切换。
* - 加入别的中转:粘贴主人电脑给出的加入链接 → 申请 → 主人同意 → 保存中转凭证与签名密钥并切换。
* - 设备签名(§16):主人密钥只在主人电脑;同意加入时主人核对配对证明后签发设备证书。
*
@@ -164,7 +165,6 @@ export function getState(): SelfHostedRelayState {
const issue = relay ? getDeviceLinkConnectionIssue() : null;
if (joinLink && joinLink.expiresAt < Date.now()) joinLink = null;
const bundled = bundledRelayVersion();
- const deployment = config.deployment;
return {
available: authManager.getAuthState().isAuthenticated && secureStorageAvailable(),
mode: relay ? 'self-hosted' : 'official',
@@ -179,18 +179,17 @@ export function getState(): SelfHostedRelayState {
externalUrl: config.host.externalUrl,
suggestedUrls: suggestedUrls(config),
},
- deployment: deployment
- ? {
- sshHostId: deployment.sshHostId,
- address: deployment.address,
- baseUrl: deployment.baseUrl,
- name: deployment.name,
- relayVersion: deployment.complete ? deployment.relayVersion : '',
- deployedAt: deployment.deployedAt,
- active: relay?.relayId === deployment.relayId,
- upgradeAvailable: Boolean(bundled && deployment.complete && bundled !== deployment.relayVersion),
- }
- : null,
+ deployments: config.deployments.map((deployment) => ({
+ relayId: deployment.relayId,
+ sshHostId: deployment.sshHostId,
+ address: deployment.address,
+ baseUrl: deployment.baseUrl,
+ name: deployment.name,
+ relayVersion: deployment.complete ? deployment.relayVersion : '',
+ deployedAt: deployment.deployedAt,
+ active: relay?.relayId === deployment.relayId,
+ upgradeAvailable: Boolean(bundled && deployment.complete && bundled !== deployment.relayVersion),
+ })),
deployJob,
bundledRelayVersion: bundled,
joinLink: joinLink ? { link: joinLink.link, expiresAt: new Date(joinLink.expiresAt).toISOString() } : null,
@@ -701,7 +700,19 @@ function deploymentActive(deployment: RelayDeployment): RelayConfig['active'] {
};
}
-type DeployJobPlan = Pick<SelfHostedRelayDeployJobView, 'action' | 'target' | 'serverChanged'> & { steps: RelayDeployStep[] };
+type DeployJobPlan = Pick<SelfHostedRelayDeployJobView, 'action' | 'target' | 'serverChanged' | 'relayId'> & { steps: RelayDeployStep[] };
+
+function findDeployment(config: RelayConfig, relayId: string): RelayDeployment | null {
+ return config.deployments.find((deployment) => deployment.relayId === relayId) ?? null;
+}
+
+/** 写入一条部署记录:同一个中转或同一台服务器的旧记录原位替换(一台服务器一个中转),否则加在最后。 */
+function withDeployment(deployments: RelayDeployment[], record: RelayDeployment): RelayDeployment[] {
+ const same = (deployment: RelayDeployment) => deployment.relayId === record.relayId || deployment.sshHostId === record.sshHostId;
+ const index = deployments.findIndex(same);
+ if (index < 0) return [...deployments, record];
+ return deployments.flatMap((deployment, i) => (i === index ? [record] : same(deployment) ? [] : [deployment]));
+}
function runDeployJob(plan: DeployJobPlan, work: (onStep: (step: SelfHostedRelayDeployJobView['step']) => void, assertOwner: () => void, onProgress: (message: RelayDeployProgressMessage) => void) => Promise<void>): void {
const { action } = plan;
@@ -750,16 +761,17 @@ function runDeployJob(plan: DeployJobPlan, work: (onStep: (step: SelfHostedRelay
}
/**
- * 部署或升级。身份(中转 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 previous = readRelayConfig().deployment;
- const reuse = previous && previous.sshHostId === input.sshHostId && !input.replaceExisting ? readRelaySecrets(previous.relayId) : null;
+ const previous = readRelayConfig().deployments.find((deployment) => deployment.sshHostId === input.sshHostId) ?? null;
+ const reuse = previous && !input.replaceExisting ? readRelaySecrets(previous.relayId) : null;
const relayId = reuse && previous ? previous.relayId : randomUUID();
const secrets = reuse ?? generateOwnerSecrets();
const init = ownerInitArgs(relayId, secrets, input.name);
@@ -775,14 +787,12 @@ function deploy(input: { sshHostId: string; address: string; name: string; repla
deployedAt: new Date().toISOString(),
complete: false,
};
- // 没完成的部署换了服务器:原服务器上可能装了一半,先清理掉再部署到新服务器。
- const cleanup = previous && !previous.complete && previous.sshHostId !== input.sshHostId ? previous : null;
const persist = () => {
const config = readRelayConfig();
- const old = config.deployment;
+ const old = config.deployments.find((deployment) => deployment.sshHostId === input.sshHostId) ?? null;
let replacedActive = false;
if (old && old.relayId !== relayId) {
- // 换了一台服务器(或清掉重来):旧身份作废。正在用旧中转时先切回官方,不留下指向已删秘密的配置。
+ // 清掉这台服务器上原来的中转重来:旧身份作废。正在用它时先切回官方,不留下指向已删秘密的配置。
replacedActive = config.active?.relayId === old.relayId;
if (replacedActive) {
stopPairing();
@@ -791,24 +801,19 @@ function deploy(input: { sshHostId: string; address: string; name: string; repla
deleteRelaySecrets(old.relayId);
}
if (!reuse) writeRelaySecrets(relayId, secrets);
- // 升级沿用原记录:失败时服务器上仍是这一份中转,卡片照常显示,可以重试。
- if (!(action === 'upgrade' && old?.relayId === relayId)) writeRelayConfig({ ...config, deployment: record });
+ // 升级沿用原记录:失败时服务器上仍是这一份中转,那一行照常显示,可以重试。
+ if (!(action === 'upgrade' && old?.relayId === relayId)) writeRelayConfig({ ...config, deployments: withDeployment(config.deployments, record) });
if (deployJob) deployJob = { ...deployJob, serverChanged: true };
if (replacedActive) restartDeviceLinkForRelayChange();
};
const plan: DeployJobPlan = {
action,
- steps: cleanup ? ['cleanup', ...RELAY_DEPLOY_STEPS] : [...RELAY_DEPLOY_STEPS],
+ steps: [...RELAY_DEPLOY_STEPS],
target: { sshHostId: input.sshHostId, address: input.address, name: input.name, baseUrl },
+ relayId,
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,
@@ -825,35 +830,35 @@ function deploy(input: { sshHostId: string; address: string; name: string; repla
},
});
onStep('finish');
- const done: RelayDeployment = { ...record, relayVersion, deployedAt: new Date().toISOString(), complete: true };
- // 改用服务器上的中转:本机中转停掉,加入的中转退出。
- const before = readRelayConfig();
- if (activeRelayOrigin() !== 'server' || activeSelfHostedRelay()?.relayId !== relayId) {
- if (before.host.enabled) await stopHost(false);
- assertOwner();
- await leaveCurrent();
- assertOwner();
- }
- writeRelayConfig({ ...readRelayConfig(), deployment: done, active: deploymentActive(done), host: { ...before.host, enabled: false } });
- restartDeviceLinkForRelayChange();
+ const config = readRelayConfig();
+ // 部署期间改过名字时保留新名字。
+ const name = findDeployment(config, relayId)?.name ?? record.name;
+ const done: RelayDeployment = { ...record, name, relayVersion, deployedAt: new Date().toISOString(), complete: true };
+ const inUse = config.active?.relayId === relayId;
+ writeRelayConfig({
+ ...config,
+ deployments: withDeployment(config.deployments, done),
+ ...(inUse ? { active: deploymentActive(done) } : {}),
+ });
+ if (inUse) restartDeviceLinkForRelayChange();
});
return { state: getState() };
}
-function upgradeDeployment(): CommandResult {
- const deployment = readRelayConfig().deployment;
+function upgradeDeployment(relayId: string): CommandResult {
+ const deployment = findDeployment(readRelayConfig(), relayId);
if (!deployment) return { state: getState(), error: 'NO_DEPLOYMENT' };
return deploy({ sshHostId: deployment.sshHostId, address: deployment.address, name: deployment.name, replaceExisting: false }, 'upgrade');
}
-function uninstallDeployment(removeData: boolean): CommandResult {
+function uninstallDeployment(relayId: string, removeData: boolean): CommandResult {
const notReady = requireReady();
if (notReady) return { state: getState(), error: notReady };
if (deployJob?.status === 'running') return { state: getState(), error: 'BUSY' };
- const deployment = readRelayConfig().deployment;
+ const deployment = findDeployment(readRelayConfig(), relayId);
if (!deployment) return { state: getState(), error: 'NO_DEPLOYMENT' };
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) => {
+ runDeployJob({ action: 'uninstall', steps: [...RELAY_UNINSTALL_STEPS], target, relayId, serverChanged: true }, async (onStep, assertOwner) => {
await uninstallRelayFromServer(deployment.sshHostId, deployment, removeData, onStep, assertOwner);
onStep('finish');
forgetDeploymentLocally(deployment, removeData);
@@ -870,18 +875,30 @@ function forgetDeploymentLocally(deployment: RelayDeployment, removeIdentity: bo
writeRelayConfig({
...config,
active: wasActive ? null : config.active,
- deployment: removeIdentity ? null : { ...deployment, complete: false },
+ deployments: removeIdentity
+ ? config.deployments.filter((item) => item.relayId !== deployment.relayId)
+ : config.deployments.map((item) => (item.relayId === deployment.relayId ? { ...item, complete: false } : item)),
});
if (wasActive) restartDeviceLinkForRelayChange();
}
-async function useDeployment(): Promise<CommandResult> {
+function forgetDeployment(relayId: string): CommandResult {
+ const deployment = findDeployment(readRelayConfig(), relayId);
+ if (!deployment) return { state: getState(), error: 'NO_DEPLOYMENT' };
+ if (deployJob?.status === 'running') return { state: getState(), error: 'BUSY' };
+ forgetDeploymentLocally(deployment, true);
+ if (deployJob?.relayId === relayId) deployJob = null;
+ return { state: getState() };
+}
+
+async function useDeployment(relayId: string): Promise<CommandResult> {
const assertOwner = captureOwner();
const notReady = requireReady();
if (notReady) return { state: getState(), error: notReady };
const config = readRelayConfig();
- const deployment = config.deployment;
+ const deployment = findDeployment(config, relayId);
if (!deployment?.complete || !readRelaySecrets(deployment.relayId)) return { state: getState(), error: 'NO_DEPLOYMENT' };
+ if (config.active?.relayId === relayId) return { state: getState() };
if (config.host.enabled) await stopHost(false);
assertOwner();
await leaveCurrent();
@@ -891,13 +908,27 @@ async function useDeployment(): Promise<CommandResult> {
return { state: getState() };
}
+/** 只改本机显示的名字:线路列表、切换确认与正在用的线路都用新名字;服务器上的名字不变。 */
+function renameDeployment(relayId: string, name: string): CommandResult {
+ const notReady = requireReady();
+ if (notReady) return { state: getState(), error: notReady };
+ const config = readRelayConfig();
+ if (!findDeployment(config, relayId)) return { state: getState(), error: 'NO_DEPLOYMENT' };
+ writeRelayConfig({
+ ...config,
+ active: config.active?.relayId === relayId ? { ...config.active, name } : config.active,
+ deployments: config.deployments.map((deployment) => (deployment.relayId === relayId ? { ...deployment, name } : deployment)),
+ });
+ if (deployJob?.relayId === relayId && deployJob.target) deployJob = { ...deployJob, target: { ...deployJob.target, name } };
+ 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;
+ const identity = readRelayConfig().deployments.find((deployment) => deployment.sshHostId === sshHostId) ?? null;
let check: SelfHostedRelayServerCheck;
try {
check = { sshHostId, ok: true, ...(await checkRelayServer(sshHostId, identity, assertOwner)) };
@@ -918,11 +949,11 @@ const countOf = (value: unknown) => (typeof value === 'number' && Number.isInteg
* 用部署记录里的主人凭证读服务器中转的管理状态;没在用它时也能看到在线、设备数与证书到期。
* 返回的中转 ID 不是这份部署时按连不上处理,不把别的中转的数字当成自己的。
*/
-async function deploymentStatus(): Promise<CommandResult> {
+async function deploymentStatus(relayId: string): Promise<CommandResult> {
const notReady = requireReady();
if (notReady) return { state: getState(), error: notReady };
const assertOwner = captureOwner();
- const deployment = readRelayConfig().deployment;
+ const deployment = findDeployment(readRelayConfig(), relayId);
if (!deployment?.complete) return { state: getState(), error: 'NO_DEPLOYMENT' };
const secrets = readRelaySecrets(deployment.relayId);
if (!secrets) return { state: getState(), deploymentStatus: { online: false } };
@@ -970,26 +1001,22 @@ async function execute(command: SelfHostedRelayCommand): Promise<CommandResult>
case 'deploy':
return deploy(command, 'deploy');
case 'upgrade-deployment':
- return upgradeDeployment();
+ return upgradeDeployment(command.relayId);
case 'uninstall-deployment':
- return uninstallDeployment(command.removeData);
- case 'forget-deployment': {
- const deployment = readRelayConfig().deployment;
- if (!deployment) return { state: getState(), error: 'NO_DEPLOYMENT' };
- if (deployJob?.status === 'running') return { state: getState(), error: 'BUSY' };
- forgetDeploymentLocally(deployment, true);
- deployJob = null;
- return { state: getState() };
- }
+ return uninstallDeployment(command.relayId, command.removeData);
+ case 'forget-deployment':
+ return forgetDeployment(command.relayId);
case 'use-deployment':
- return useDeployment();
+ return useDeployment(command.relayId);
+ case 'rename-deployment':
+ return renameDeployment(command.relayId, command.name);
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();
+ return deploymentStatus(command.relayId);
}
}
diff --git a/apps/desktop/src/renderer/components/settings/RelayServicePanel.tsx b/apps/desktop/src/renderer/components/settings/RelayServicePanel.tsx
index 1725edb753..807e42c878 100644
--- a/apps/desktop/src/renderer/components/settings/RelayServicePanel.tsx
+++ b/apps/desktop/src/renderer/components/settings/RelayServicePanel.tsx
@@ -2,8 +2,9 @@
* 「远程连接 → 连接线路」:设备之间经 Cindy 官方中转,还是用户自己的中转
* (部署到自己的服务器 / 这台电脑当中转 / 加入别的中转)。方案见 docs/self-hosted-relay-plan.md。
*
- * 紧跟在「我的设备」下面直接展示:单选的线路列表(选中的那条就是正在用的)、服务器中转的管理,
- * 以及三步部署窗口(选择服务器 → 部署 → 添加设备)。
+ * 紧跟在「我的设备」下面直接展示:单选的线路列表(选中的那条就是正在用的)、服务器中转的管理
+ * (可以部署到多台服务器,每台一行),以及三步部署窗口(选择服务器 → 部署 → 完成)。
+ * 部署完成不切换线路,改用哪条由用户自己切换。
*
* 状态以 main 为准(`window.electronAPI.selfHostedRelay`):命令返回最新状态,另有 CHANGED 推送;
* 连接问题(被移出中转)来自 device-link 链路,低频轮询兜底。
@@ -21,6 +22,7 @@ import {
Info,
Link2,
Monitor,
+ Pencil,
Plus,
RefreshCw,
Server,
@@ -42,12 +44,15 @@ import { cn } from '@/lib/utils';
import {
DEFAULT_RELAY_PORT,
normalizeRelayAddress,
+ normalizeRelayName,
RELAY_DEPLOY_STEPS,
+ RELAY_NAME_MAX_LENGTH,
RELAY_UNINSTALL_STEPS,
type SelfHostedRelayCommand,
type SelfHostedRelayCommandResult,
type SelfHostedRelayDeployJobView,
type SelfHostedRelayDeploymentStatus,
+ type SelfHostedRelayDeploymentView,
type SelfHostedRelayErrorCode,
type SelfHostedRelayServerCheck,
type SelfHostedRelayState,
@@ -296,26 +301,16 @@ 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) {
@@ -515,7 +510,8 @@ function useSshHosts(enabled: boolean, refreshKey: unknown): SshHostOption[] | n
return hosts;
}
-type DeployTarget = { sshHostId: string; address: string; name: string };
+/** 部署表单的初始值;`relayId` 是继续或修改的那条部署记录。 */
+type DeployTarget = { sshHostId: string; address: string; name: string; relayId?: string };
const DEPLOY = 'settings.remoteControl.relay.deploy';
const SERVER = 'settings.remoteControl.relay.server';
@@ -638,12 +634,15 @@ function Actions({ start, children }: { start?: React.ReactNode; children?: Reac
);
}
-function stepLabel(t: (key: string, options?: Record<string, unknown>) => string, step: RelayDeployLogEntry['step'], cleanupServer: string) {
- return t(`${DEPLOY}.steps.${step}`, { server: cleanupServer });
+function stepLabel(t: (key: string) => string, step: RelayDeployLogEntry['step']) {
+ return t(`${DEPLOY}.steps.${step}`);
}
-/** 依次列出这次任务的步骤:进行中的一步下面写实时进展,失败的一步下面写原因,失败后不再列出没执行的步骤。 */
-function JobSteps({ job, cleanupServer }: { job: SelfHostedRelayDeployJobView; cleanupServer: string }) {
+/**
+ * 依次列出这次任务的步骤:进行中的一步下面写实时进展(liveDetail=false 时由调用方放在固定位置),
+ * 失败的一步下面写原因,失败后不再列出没执行的步骤。
+ */
+function JobSteps({ job, liveDetail = true }: { job: SelfHostedRelayDeployJobView; liveDetail?: boolean }) {
const { t } = useTranslation();
const steps = job.steps ?? (job.action === 'uninstall' ? RELAY_UNINSTALL_STEPS : RELAY_DEPLOY_STEPS);
const found = steps.indexOf(job.step);
@@ -666,9 +665,9 @@ function JobSteps({ job, cleanupServer }: { job: SelfHostedRelayDeployJobView; c
(tone === 'progress' || tone === 'failed') && 'font-medium',
)}
>
- {stepLabel(t, step, cleanupServer)}
+ {stepLabel(t, step)}
</span>
- {tone === 'progress' && latest?.message && latest.step === step ? (
+ {liveDetail && 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>
@@ -682,7 +681,7 @@ function JobSteps({ job, cleanupServer }: { job: SelfHostedRelayDeployJobView; c
);
}
-function JobLog({ job, cleanupServer }: { job: SelfHostedRelayDeployJobView; cleanupServer: string }) {
+function JobLog({ job }: { job: SelfHostedRelayDeployJobView }) {
const { t } = useTranslation();
const logs = job.logs ?? [];
if (logs.length === 0) return null;
@@ -695,7 +694,7 @@ function JobLog({ job, cleanupServer }: { job: SelfHostedRelayDeployJobView; cle
{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)}
+ {entry.message ? t(`${DEPLOY}.progress.${entry.message}`) : stepLabel(t, entry.step)}
</span>
</li>
))}
@@ -705,7 +704,7 @@ function JobLog({ job, cleanupServer }: { job: SelfHostedRelayDeployJobView; cle
}
/** 移除失败(服务器连不上、上面的中转不归这台电脑管)时的退路。 */
-function RemovalFallback({ controller }: { controller: SelfHostedRelayController }) {
+function RemovalFallback({ controller, relayId }: { controller: SelfHostedRelayController; relayId: string }) {
const { t } = useTranslation();
const confirm = useConfirm();
return (
@@ -717,7 +716,7 @@ function RemovalFallback({ controller }: { controller: SelfHostedRelayController
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' });
+ if (ok) void controller.run({ type: 'forget-deployment', relayId });
});
}}
>
@@ -725,7 +724,7 @@ function RemovalFallback({ controller }: { controller: SelfHostedRelayController
</Button>
}
>
- <Button size="sm" disabled={controller.busy} onClick={() => void controller.run({ type: 'uninstall-deployment', removeData: true })}>
+ <Button size="sm" disabled={controller.busy} onClick={() => void controller.run({ type: 'uninstall-deployment', relayId, removeData: true })}>
{t(`${DEPLOY}.retry`)}
</Button>
</Actions>
@@ -762,14 +761,14 @@ function useServerCheck(sshHostId: string) {
}
function ServerCheckLine({
+ idle,
check,
checking,
- cleanupServer,
onRecheck,
}: {
+ idle: boolean;
check: SelfHostedRelayServerCheck | null;
checking: boolean;
- cleanupServer: string | null;
onRecheck: () => void;
}) {
const { t } = useTranslation();
@@ -777,8 +776,12 @@ function ServerCheckLine({
let tone: LineTone = 'progress';
let title = t(`${k}.checking`);
let meta: string | null = null;
- let body: React.ReactNode = null;
- if (!checking && check && !check.ok) {
+ let body: React.ReactNode = <p className="text-12 leading-[1.6] text-[var(--text-tertiary)]">{t(`${k}.checkingHint`)}</p>;
+ if (idle) {
+ tone = 'pending';
+ title = t(`${k}.idle`);
+ body = null;
+ } else if (!checking && check && !check.ok) {
tone = 'failed';
title = t(`${k}.blocked`);
body = <FailureReason error={check.error} detail={check.detail} />;
@@ -788,18 +791,19 @@ function ServerCheckLine({
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)]">
+ <p className={cn('text-13 leading-5', idle ? 'text-[var(--text-tertiary)]' : 'text-[var(--text-primary)]')}>
{title}
- {meta ? <span className="ml-2 text-12 text-[var(--text-tertiary)]">{meta}</span> : null}
+ {/* 行高收紧:小一号的字放在同一行里不把这一行撑高,检查结果出来时下面的表单不动。 */}
+ {meta ? <span className="ml-2 text-12 leading-none text-[var(--text-tertiary)]">{meta}</span> : null}
</p>
- {body}
+ {/* 未选、检查中、检查通过都先占两行说明的高度,结果出来时下面的表单不被推动。 */}
+ <div className="min-h-[3.2em] text-12">{body}</div>
</div>
{tone === 'failed' ? (
<Button variant="secondary" size="xs" compact onClick={onRecheck}>
@@ -827,14 +831,15 @@ const DIALOG = 'settings.remoteControl.relay.dialog';
const MANAGE = 'settings.remoteControl.relay.manage';
/**
- * 线路行右侧只放同样大小的图标,贴右对齐:切换在前,这条线路自己的操作(删除、设置)在后;
+ * 线路行右侧只放同样大小的图标,贴右对齐:切换在前,这条线路自己的操作(改名、删除、设置)在后;
* 没有的不占位,只有一个图标时它就在最右边。正在用的线路用名字旁边的绿点表示,不进这一列。
*/
-function RouteSide({ switchAction, action }: { switchAction?: React.ReactNode; action?: React.ReactNode }) {
+function RouteSide({ switchAction, actions = [] }: { switchAction?: React.ReactNode; actions?: 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}
+ {[switchAction, ...actions].map((item, index) =>
+ item ? <span key={index} className="flex w-7 shrink-0 justify-center">{item}</span> : null,
+ )}
</>
);
}
@@ -902,6 +907,18 @@ function DeployProgressBar({ job }: { job: SelfHostedRelayDeployJobView }) {
);
}
+/** 当前这一步的实时进展:固定在进度条下面占一行,内容变了只换文字,不推动下面的步骤列表。 */
+function LiveProgress({ job }: { job: SelfHostedRelayDeployJobView }) {
+ const { t } = useTranslation();
+ const latest = job.logs?.at(-1);
+ const text = latest?.message && latest.step === job.step ? t(`${DEPLOY}.progress.${latest.message}`) : '';
+ return (
+ <p role="status" title={text || undefined} className="min-h-[1.5em] truncate text-12 leading-[1.5] text-[var(--text-secondary)]">
+ {text}
+ </p>
+ );
+}
+
/** 第 1 步:选服务器后自动只读检查,检查通过才能开始。 */
function DeployFormStep({
state,
@@ -933,10 +950,6 @@ function DeployFormStep({
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 ready = Boolean(!checking && check?.ok && check.sshHostId === hostId);
// 服务器上的中转不归这台电脑:检查结果里已用警示写明后果,按钮也直接叫「清除并部署」。
@@ -956,7 +969,7 @@ function DeployFormStep({
return (
<>
- <div className="flex flex-col gap-4 overflow-y-auto px-4 pb-4">
+ <div className="flex min-h-0 flex-1 flex-col gap-4 overflow-y-auto px-4 pb-4">
{hosts && hosts.length === 0 ? (
<Hint>{t(`${DEPLOY}.noHosts`)}</Hint>
) : (
@@ -976,11 +989,9 @@ function DeployFormStep({
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 className="rounded-lg border border-[var(--border-default)] px-3 py-2.5">
+ <ServerCheckLine idle={!hostId} check={check} checking={checking} onRecheck={recheck} />
+ </div>
</div>
<FieldRow label={t(`${DEPLOY}.address`)} hint={<Hint>{t(`${DEPLOY}.addressHint`)}</Hint>}>
<Input
@@ -1025,7 +1036,7 @@ function DeployFormStep({
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">
+ <div className="flex shrink-0 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>
@@ -1033,8 +1044,9 @@ function DialogFooter({ start, children }: { start?: React.ReactNode; children?:
}
/**
- * 部署窗口:选择服务器 → 部署 → 添加设备。关掉窗口部署照样在后台继续,线路列表里那一行显示进度;
+ * 部署窗口:选择服务器 → 部署 → 完成。关掉窗口部署照样在后台继续,线路列表里那一行显示进度;
* 失败时原因写在出错的那一步下面,可以重试、回到表单修改或放弃(清理服务器)。
+ * 部署完成不切换线路:完成页给「使用这条线路」,切换照常先确认。
*/
function DeployDialog({
open,
@@ -1043,6 +1055,9 @@ function DeployDialog({
controller,
hosts,
initial,
+ startInForm,
+ openKey,
+ onUse,
}: {
open: boolean;
onOpenChange: (open: boolean) => void;
@@ -1050,33 +1065,54 @@ function DeployDialog({
controller: SelfHostedRelayController;
hosts: SshHostOption[] | null;
initial: DeployTarget | null;
+ /** 打开时直接显示表单(新部署、继续某条记录),不显示上一次任务的进度。 */
+ startInForm: boolean;
+ /** 列表每次打开窗口都换一个值;窗口为确认框临时关闭再打开时不变,不会退回表单。 */
+ openKey: number;
+ /** 完成页的「使用这条线路」:由列表弹切换确认。 */
+ onUse: (relayId: string) => void;
}) {
const { t } = useTranslation();
const confirm = useConfirm();
- // undefined:跟着部署任务显示;DeployTarget / null:回到表单(null 为空表单)。
+ // undefined:跟着部署任务显示;DeployTarget / null:显示表单(null 为空表单)。
const [editing, setEditing] = useState<DeployTarget | null | undefined>(undefined);
+ // 从任务的「修改设置」进来的表单,取消时回到任务;新开的表单取消就关窗口。
+ const [backToJob, setBackToJob] = useState(false);
const job = state.deployJob?.action === 'deploy' ? state.deployJob : null;
const elapsed = useElapsed(job);
useEffect(() => {
- if (open) setEditing(undefined);
- }, [open]);
+ setEditing(startInForm ? initial : undefined);
+ setBackToJob(false);
+ // 只跟着列表的打开动作重置(initial / startInForm 与 openKey 同时更新)。
+ }, [openKey]);
const view = editing !== undefined ? 'form' : job?.status === 'done' ? 'done' : job ? 'progress' : 'form';
- const deployment = state.deployment;
- const incomplete = Boolean(deployment && !deployment.relayVersion);
- const target = job?.target ?? deployment;
+ // 这次窗口对应的部署记录:修改中的、任务的、或打开时指定继续的那一条。
+ const recordId = view === 'form' ? (editing ?? initial)?.relayId : job?.relayId;
+ const record = state.deployments.find((deployment) => deployment.relayId === recordId) ?? null;
+ const incomplete = Boolean(record && !record.relayVersion);
+ const target = job?.target ?? record;
const close = () => onOpenChange(false);
// 确认框与本窗口同层,先关窗口再确认,确认框才不会被盖住。
const abandon = () => {
+ if (!record) return;
+ const relayId = record.relayId;
close();
void confirm(t(`${DEPLOY}.abandonTitle`), t(`${DEPLOY}.abandonDescription`), t(`${DEPLOY}.abandon`)).then((ok) => {
- if (ok) void controller.run({ type: 'uninstall-deployment', removeData: true });
+ if (ok) void controller.run({ type: 'uninstall-deployment', relayId, removeData: true });
});
};
const finish = () => {
close();
void controller.run({ type: 'dismiss-deploy-job' });
};
+ const done = view === 'done' && record?.relayVersion ? record : null;
+ const canUse = Boolean(done && !done.active);
+ const use = () => {
+ if (!done) return;
+ finish();
+ onUse(done.relayId);
+ };
const retry = async () => {
if (!target) return;
const retryTarget = { sshHostId: target.sshHostId, address: target.address, name: target.name };
@@ -1095,7 +1131,7 @@ function DeployDialog({
const description =
view === 'form'
? t(`${DEPLOY}.hint`)
- : view === 'done'
+ : view === 'done' && canUse
? t(`${DIALOG}.doneHint`)
: target
? `${hostLabel(hosts, target.sshHostId)} · ${target.baseUrl}`
@@ -1107,20 +1143,21 @@ function DeployDialog({
<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"
+ className="modal-panel fixed left-1/2 top-1/2 z-[10001] flex h-[min(560px,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">
+ {/* 三步共用一个固定高度:内容在中间区域滚动,换步骤、步骤推进时窗口不变高也不重新居中。 */}
+ <div className="flex shrink-0 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>
{controller.error ? (
- <div className="px-4 pb-3">
+ <div className="shrink-0 px-4 pb-3">
<CommandError error={controller.error} port={state.host.port} detail={controller.errorDetail} />
</div>
) : null}
{view === 'form' ? (
<>
- <Dialog.Description className="px-4 pb-4 text-12 leading-[1.5] text-[var(--text-tertiary)]">
+ <Dialog.Description className="shrink-0 px-4 pb-4 text-12 leading-[1.5] text-[var(--text-tertiary)]">
{description}
</Dialog.Description>
<DeployFormStep
@@ -1128,14 +1165,14 @@ function DeployDialog({
controller={controller}
hosts={hosts}
initial={editing !== undefined ? editing : initial}
- onCancel={() => (editing !== undefined && job ? setEditing(undefined) : close())}
+ onCancel={() => (backToJob && 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 min-h-0 flex-1 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)]">
@@ -1150,10 +1187,15 @@ function DeployDialog({
) : null}
</div>
<Dialog.Description className="truncate text-12 text-[var(--text-tertiary)]">{description}</Dialog.Description>
- {job.status === 'running' ? <DeployProgressBar job={job} /> : null}
+ {job.status === 'running' ? (
+ <>
+ <DeployProgressBar job={job} />
+ <LiveProgress job={job} />
+ </>
+ ) : null}
</div>
- <JobSteps job={job} cleanupServer={deployment ? hostLabel(hosts, deployment.sshHostId) : ''} />
- <JobLog job={job} cleanupServer={deployment ? hostLabel(hosts, deployment.sshHostId) : ''} />
+ <JobSteps job={job} liveDetail={false} />
+ <JobLog job={job} />
</div>
{job.status === 'running' ? (
<DialogFooter start={<span className="text-12 text-[var(--text-tertiary)]">{t(`${DIALOG}.backgroundHint`)}</span>}>
@@ -1164,7 +1206,7 @@ function DeployDialog({
) : (
<DialogFooter
start={
- deployment ? (
+ record ? (
<Button variant="secondary" size="sm" disabled={controller.busy} onClick={abandon}>
{t(`${DEPLOY}.abandon`)}
</Button>
@@ -1179,7 +1221,11 @@ function DeployDialog({
variant="secondary"
size="sm"
disabled={controller.busy || !target}
- onClick={() => target && setEditing({ sshHostId: target.sshHostId, address: target.address, name: target.name })}
+ onClick={() => {
+ if (!target) return;
+ setBackToJob(true);
+ setEditing({ sshHostId: target.sshHostId, address: target.address, name: target.name, relayId: job.relayId });
+ }}
>
{t(`${DEPLOY}.edit`)}
</Button>
@@ -1196,7 +1242,7 @@ function DeployDialog({
</>
) : (
<>
- <div className="flex flex-col gap-4 overflow-y-auto px-4 pb-4">
+ <div className="flex min-h-0 flex-1 flex-col gap-4 overflow-y-auto px-4 pb-4">
<div className="flex items-center gap-3">
<span
aria-hidden
@@ -1206,21 +1252,37 @@ function DeployDialog({
</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 ?? '' })}
+ {t(`${DIALOG}.doneTitle`, { name: done?.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>
+ {done ? (
+ <dl className="flex flex-col divide-y divide-[var(--border-default)] rounded-lg border border-[var(--border-default)]">
+ {[
+ [t(`${DEPLOY}.server`), hostLabel(hosts, done.sshHostId)],
+ [t(`${DEPLOY}.address`), done.baseUrl],
+ [t(`${MANAGE}.version`), done.relayVersion],
+ ].map(([label, value]) => (
+ <div key={label} className="flex items-center justify-between gap-4 px-3 py-2.5 text-12">
+ <dt className="shrink-0 text-[var(--text-tertiary)]">{label}</dt>
+ <dd className="min-w-0 truncate font-mono text-[var(--text-primary)]">{value}</dd>
+ </div>
+ ))}
+ </dl>
+ ) : null}
</div>
- <DialogFooter start={<span className="text-12 text-[var(--text-tertiary)]">{t(`${DIALOG}.doneLater`)}</span>}>
- <Button variant="cta" size="sm" onClick={finish}>
+ <DialogFooter start={canUse ? <span className="text-12 text-[var(--text-tertiary)]">{t(`${DIALOG}.doneLater`)}</span> : null}>
+ <Button variant={canUse ? 'secondary' : 'cta'} size="sm" onClick={finish}>
{t(`${DIALOG}.finish`)}
</Button>
+ {canUse ? (
+ <Button variant="cta" size="sm" disabled={controller.busy} onClick={use}>
+ {t(`${DIALOG}.use`)}
+ </Button>
+ ) : null}
</DialogFooter>
</>
)}
@@ -1230,24 +1292,75 @@ function DeployDialog({
);
}
+/** 改服务器中转在本机显示的名字。 */
+function RenameForm({
+ deployment,
+ controller,
+ onClose,
+}: {
+ deployment: SelfHostedRelayDeploymentView;
+ controller: SelfHostedRelayController;
+ onClose: () => void;
+}) {
+ const { t } = useTranslation();
+ const [name, setName] = useState(deployment.name);
+ const normalized = normalizeRelayName(name);
+ const canSave = Boolean(normalized && normalized !== deployment.name) && !controller.busy;
+ const save = async () => {
+ if (!normalized) return;
+ if (await controller.run({ type: 'rename-deployment', relayId: deployment.relayId, name: normalized })) onClose();
+ };
+ return (
+ <form
+ className="flex min-h-0 flex-col"
+ onSubmit={(event) => {
+ event.preventDefault();
+ if (canSave) void save();
+ }}
+ >
+ <div className="flex flex-col gap-3 px-4 pb-4">
+ <Input
+ value={name}
+ onChange={setName}
+ size="sm"
+ maxLength={RELAY_NAME_MAX_LENGTH}
+ autoFocus
+ error={!normalized}
+ ariaLabel={t(`${DEPLOY}.name`)}
+ />
+ <CommandError error={controller.error} port={0} detail={controller.errorDetail} />
+ </div>
+ <DialogFooter>
+ <Button type="button" variant="secondary" size="sm" disabled={controller.busy} onClick={onClose}>
+ {t(`${ROUTE}.renameCancel`)}
+ </Button>
+ <Button type="submit" variant="cta" size="sm" disabled={!canSave}>
+ {t(`${ROUTE}.renameSave`)}
+ </Button>
+ </DialogFooter>
+ </form>
+ );
+}
+
/**
* 服务器中转的实时状态:进入页面时读一次,之后每分钟刷新;刷新时保留上一次结果,不闪空。
* 查询本身失败(例如主进程还是旧版本)不等于服务器连不上:这时不下结论,不显示状态。
*/
-function useDeploymentStatus(enabled: boolean) {
+function useDeploymentStatus(relayId: string | null) {
const [status, setStatus] = useState<SelfHostedRelayDeploymentStatus | null>(null);
const [checking, setChecking] = useState(false);
const [attempt, setAttempt] = useState(0);
+ // 换了一个中转才清空;同一个中转定时刷新时保留上一次结果。
+ useEffect(() => {
+ setStatus(null);
+ }, [relayId]);
useEffect(() => {
const api = window.electronAPI?.selfHostedRelay;
- if (!enabled || !api) {
- setStatus(null);
- return;
- }
+ if (!relayId || !api) return;
let active = true;
setChecking(true);
void api
- .command({ type: 'deployment-status' })
+ .command({ type: 'deployment-status', relayId })
.then((res) => {
if (active && res.deploymentStatus) setStatus(res.deploymentStatus);
})
@@ -1258,12 +1371,12 @@ function useDeploymentStatus(enabled: boolean) {
return () => {
active = false;
};
- }, [enabled, attempt]);
+ }, [relayId, attempt]);
useEffect(() => {
- if (!enabled) return;
+ if (!relayId) return;
const timer = setInterval(() => setAttempt((value) => value + 1), DEPLOYMENT_STATUS_POLL_MS);
return () => clearInterval(timer);
- }, [enabled]);
+ }, [relayId]);
return { status, checking, refresh: () => setAttempt((value) => value + 1) };
}
@@ -1351,13 +1464,13 @@ function TaskPanel({ job, controller }: { job: SelfHostedRelayDeployJobView; con
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} />
+ <JobSteps job={job} />
+ <JobLog job={job} />
+ {running || !job.relayId ? null : job.action === 'uninstall' ? (
+ <RemovalFallback controller={controller} relayId={job.relayId} />
) : (
<Actions>
- <Button size="sm" disabled={controller.busy} onClick={() => void controller.run({ type: 'upgrade-deployment' })}>
+ <Button size="sm" disabled={controller.busy} onClick={() => void controller.run({ type: 'upgrade-deployment', relayId: job.relayId! })}>
{t(`${DEPLOY}.retry`)}
</Button>
</Actions>
@@ -1410,17 +1523,18 @@ function IconAction({
/** 正在用的服务器中转的详情:状态用数字说话(设备、证书、版本),下面就是添加设备。 */
function ServerDetails({
state,
+ deployment,
controller,
status,
}: {
state: SelfHostedRelayState;
+ deployment: SelfHostedRelayDeploymentView;
controller: SelfHostedRelayController;
status: SelfHostedRelayDeploymentStatus | null;
}) {
const { t } = useTranslation();
- const deployment = state.deployment!;
const job = state.deployJob;
- const task = job && job.action !== 'deploy' && job.status !== 'done' ? job : null;
+ const task = job && job.relayId === deployment.relayId && 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;
@@ -1459,7 +1573,7 @@ function ServerDetails({
compact
className="mt-1"
disabled={busy}
- onClick={() => void controller.run({ type: 'upgrade-deployment' })}
+ onClick={() => void controller.run({ type: 'upgrade-deployment', relayId: deployment.relayId })}
>
{t(`${SERVER}.upgrade`, { version: state.bundledRelayVersion ?? '' })}
</Button>
@@ -1479,6 +1593,7 @@ function ServerDetails({
/**
* 「连接线路」:所有线路是一个单选列表,选中的那条就是正在用的。切换线路都先确认;
* 正在用的那条在自己那一行里展开详情(服务器中转的设备数、证书、添加设备;这台电脑当中转的加入链接)。
+ * 部署到服务器的中转每台一行,各自可以切换、改名、移除;随时可以再部署到另一台服务器。
*/
export function RelayServicePanel({ controller }: { controller: SelfHostedRelayController }) {
const { t } = useTranslation();
@@ -1487,14 +1602,17 @@ export function RelayServicePanel({ controller }: { controller: SelfHostedRelayC
const [form, setForm] = useState<'none' | 'host' | 'join'>('none');
const [deployOpen, setDeployOpen] = useState(false);
const [deployInitial, setDeployInitial] = useState<DeployTarget | null>(null);
+ const [deployInForm, setDeployInForm] = useState(false);
+ const [deployOpenKey, setDeployOpenKey] = useState(0);
+ const [renaming, setRenaming] = useState<SelfHostedRelayDeploymentView | 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));
+ // 详情只给正在用的那个服务器中转:没在用时设备数、证书等没有意义,也不去请求。
+ const activeServer = state?.deployments.find((deployment) => deployment.active && deployment.relayVersion) ?? null;
+ const deploymentStatus = useDeploymentStatus(state?.available ? activeServer?.relayId ?? null : null);
// 移除完成后这一行随之消失,用一条提示说明结果。
useEffect(() => {
@@ -1519,13 +1637,9 @@ 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 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 busy = controller.busy || job?.status === 'running';
@@ -1541,9 +1655,8 @@ export function RelayServicePanel({ controller }: { controller: SelfHostedRelayC
await controller.run({ type: 'use-official' });
}
};
- // 切换到服务器中转前先确认,并说清楚原线路会怎样。
- const switchToDeployment = async () => {
- if (!deployment) return;
+ // 切换到服务器中转前先确认,并说清楚原线路会怎样(从另一个服务器中转切过来时原中转继续运行)。
+ const switchToDeployment = async (deployment: SelfHostedRelayDeploymentView) => {
const ok = !confirmDialog || (await confirmDialog.confirm({
title: t(`${ROUTE}.switchTitle`, { name: deployment.name }),
description: t(
@@ -1555,17 +1668,24 @@ export function RelayServicePanel({ controller }: { controller: SelfHostedRelayC
}));
if (!ok) return;
setForm('none');
- await controller.run({ type: 'use-deployment' });
+ await controller.run({ type: 'use-deployment', relayId: deployment.relayId });
};
- const removeDeployment = () => {
+ const switchToDeploymentById = (relayId: string) => {
+ const deployment = state.deployments.find((item) => item.relayId === relayId);
+ if (deployment) void switchToDeployment(deployment);
+ };
+ const removeDeployment = (relayId: string) => {
void confirm(t(`${SERVER}.removeTitle`), t(`${SERVER}.removeDescription`), t(`${SERVER}.remove`)).then((ok) => {
- if (ok) void controller.run({ type: 'uninstall-deployment', removeData: true });
+ if (ok) void controller.run({ type: 'uninstall-deployment', relayId, removeData: true });
});
};
- const openDeploy = (initial: DeployTarget | null) => {
+ /** `inForm`:直接显示表单(新部署、继续某条记录);否则跟着当前部署任务显示进度。 */
+ const openDeploy = (initial: DeployTarget | null, inForm: boolean) => {
controller.clearError();
setForm('none');
setDeployInitial(initial);
+ setDeployInForm(inForm);
+ setDeployOpenKey((value) => value + 1);
setDeployOpen(true);
};
const openForm = (next: 'host' | 'join') => {
@@ -1576,6 +1696,14 @@ export function RelayServicePanel({ controller }: { controller: SelfHostedRelayC
controller.clearError();
setForm('none');
};
+ const openRename = (deployment: SelfHostedRelayDeploymentView) => {
+ controller.clearError();
+ setRenaming(deployment);
+ };
+ const closeRename = () => {
+ controller.clearError();
+ setRenaming(null);
+ };
// 等待主人同意时关窗口,就撤回这次加入申请。
const closeJoin = () => {
if (state.join.status === 'connecting' || state.join.status === 'waiting') void controller.run({ type: 'cancel-join' });
@@ -1586,63 +1714,100 @@ export function RelayServicePanel({ controller }: { controller: SelfHostedRelayC
<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 ? (
+ const runningHint = (text: string) => (
<span className="inline-flex items-center gap-1.5">
<Spinner size={12} />
- {t(`${DEPLOY}.running.uninstall`)}
+ {text}
</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;
+
+ const serverRow = (deployment: SelfHostedRelayDeploymentView) => {
+ const rowJob = job?.relayId === deployment.relayId ? job : null;
+ const running = rowJob?.status === 'running';
+ const deploying = running && rowJob.action === 'deploy';
+ const removing = running && rowJob.action === 'uninstall';
+ const complete = Boolean(deployment.relayVersion);
+ const inUse = Boolean(isServer && deployment.active);
+ const showStatus = inUse && complete && (deploymentStatus.status || deploymentStatus.checking);
+ const hint = deploying ? (
+ runningHint(t(`${ROUTE}.deployingStep`, { step: stepLabel(t, rowJob.step) }))
+ ) : removing ? (
+ runningHint(t(`${DEPLOY}.running.uninstall`))
+ ) : !complete ? (
+ t(`${DEPLOY}.failed.deploy`)
+ ) : (
+ <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>
+ {showStatus ? (
+ <>
+ <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>
+ );
+ const side = deploying ? (
+ <Button variant="secondary" size="sm" onClick={() => openDeploy(null, false)}>
+ {t(`${ROUTE}.viewProgress`)}
+ </Button>
+ ) : removing ? null : !complete ? (
+ <Button
+ variant="secondary"
+ size="sm"
+ disabled={busy}
+ onClick={() =>
+ // 这一条刚失败过:回到它的进度看原因、重试;否则用记录里的设置打开表单。
+ rowJob?.action === 'deploy'
+ ? openDeploy(null, false)
+ : openDeploy({ sshHostId: deployment.sshHostId, address: deployment.address, name: deployment.name, relayId: deployment.relayId }, true)
+ }
+ >
+ {t(`${ROUTE}.resume`)}
+ </Button>
+ ) : (
+ <RouteSide
+ switchAction={deployment.active ? null : switchAction(deployment.name, () => void switchToDeployment(deployment))}
+ actions={[
+ <IconAction key="rename" label={t(`${ROUTE}.rename`)} disabled={busy} onClick={() => openRename(deployment)}>
+ <Pencil aria-hidden size={14} />
+ </IconAction>,
+ <IconAction key="remove" label={t(`${MANAGE}.remove`)} disabled={busy} onClick={() => removeDeployment(deployment.relayId)}>
+ <Trash2 aria-hidden size={14} />
+ </IconAction>,
+ ]}
+ />
+ );
+ const failedTask = rowJob && rowJob.action !== 'deploy' && rowJob.status === 'failed' ? rowJob : null;
+ return (
+ <RouteRow
+ key={deployment.relayId}
+ selected={inUse}
+ icon={<Server size={15} />}
+ title={deploying && rowJob.target ? rowJob.target.name : deployment.name}
+ tag={t(`${ROUTE}.kindServer`)}
+ hint={hint}
+ side={side}
+ >
+ {inUse && complete && !removing ? (
+ <ServerDetails state={state} deployment={deployment} controller={controller} status={deploymentStatus.status} />
+ ) : failedTask ? (
+ <div className="rounded-lg border border-[var(--border-default)] px-3 py-3">
+ <TaskPanel job={failedTask} controller={controller} />
+ </div>
+ ) : null}
+ </RouteRow>
+ );
+ };
+ // 检查通过前停下或还在进行的部署还没有记录:用任务里的目标单独占一行。
+ const pendingDeploy =
+ job?.action === 'deploy' && job.status !== 'done' && !state.deployments.some((deployment) => deployment.relayId === job.relayId)
+ ? job
+ : null;
return (
<div className="flex flex-col gap-4">
@@ -1656,23 +1821,24 @@ export function RelayServicePanel({ controller }: { controller: SelfHostedRelayC
hint={t(`${ROUTE}.officialHint`)}
side={<RouteSide switchAction={relay ? switchAction(t(`${k}.summary.official`), () => void switchToOfficial()) : null} />}
/>
- {deployment || deploying || deployFailed ? (
+ {state.deployments.map(serverRow)}
+ {pendingDeploy ? (
<RouteRow
- selected={Boolean(isServer && deployment?.active)}
+ selected={false}
icon={<Server size={15} />}
- title={serverTitle}
+ title={pendingDeploy.target?.name ?? ''}
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>
+ hint={
+ pendingDeploy.status === 'running'
+ ? runningHint(t(`${ROUTE}.deployingStep`, { step: stepLabel(t, pendingDeploy.step) }))
+ : t(`${DEPLOY}.failed.deploy`)
+ }
+ side={
+ <Button variant="secondary" size="sm" onClick={() => openDeploy(null, false)}>
+ {t(pendingDeploy.status === 'running' ? `${ROUTE}.viewProgress` : `${ROUTE}.resume`)}
+ </Button>
+ }
+ />
) : null}
<RouteRow
selected={isHost}
@@ -1689,13 +1855,13 @@ export function RelayServicePanel({ controller }: { controller: SelfHostedRelayC
<RouteSide
// 这台电脑当中转要先填端口等设置,切换就是打开设置窗口,在窗口里点「开启」。
switchAction={isHost ? null : switchAction(t(`${ROUTE}.hostTitle`), () => openForm('host'))}
- action={
+ actions={[
isHost ? (
- <IconAction label={t(`${k}.actions.editHost`)} onClick={() => openForm('host')}>
+ <IconAction key="settings" label={t(`${k}.actions.editHost`)} onClick={() => openForm('host')}>
<Settings2 aria-hidden size={14} />
</IconAction>
- ) : null
- }
+ ) : null,
+ ]}
/>
}
>
@@ -1715,31 +1881,27 @@ export function RelayServicePanel({ controller }: { controller: SelfHostedRelayC
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}
+ <li className="px-4 py-2">
+ <div className="-mx-3 flex flex-wrap items-center gap-1">
+ <Button
+ variant="secondary"
+ size="sm"
+ tone="quiet"
+ compact
+ disabled={!state.bundledRelayVersion || busy}
+ onClick={() => openDeploy(null, true)}
+ >
+ <Plus aria-hidden size={13} />
+ {t(`${k}.actions.deploy`)}
+ </Button>
+ {!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>
</ul>
{state.issue ? (
<ErrorText>
@@ -1755,7 +1917,7 @@ export function RelayServicePanel({ controller }: { controller: SelfHostedRelayC
</p>
</div>
{/* 窗口里的命令失败写在窗口里,这里只显示列表上的操作(切换、移除等)出的错。 */}
- {!deployOpen && form === 'none' && error && error !== 'CANCELLED' ? (
+ {!deployOpen && form === 'none' && !renaming && error && error !== 'CANCELLED' ? (
<CommandError error={error} port={state.host.port} detail={controller.errorDetail} />
) : null}
<FormDialog
@@ -1774,6 +1936,9 @@ export function RelayServicePanel({ controller }: { controller: SelfHostedRelayC
<FormDialog open={form === 'join'} onClose={closeJoin} title={t(`${k}.join.title`)} description={t(`${k}.join.hint`)}>
<JoinForm state={state} controller={controller} onClose={closeJoin} />
</FormDialog>
+ <FormDialog open={Boolean(renaming)} onClose={closeRename} title={t(`${ROUTE}.rename`)} description={t(`${ROUTE}.renameHint`)}>
+ {renaming ? <RenameForm key={renaming.relayId} deployment={renaming} controller={controller} onClose={closeRename} /> : null}
+ </FormDialog>
<DeployDialog
open={deployOpen}
onOpenChange={setDeployOpen}
@@ -1781,6 +1946,9 @@ export function RelayServicePanel({ controller }: { controller: SelfHostedRelayC
controller={controller}
hosts={hosts}
initial={deployInitial}
+ startInForm={deployInForm}
+ openKey={deployOpenKey}
+ onUse={switchToDeploymentById}
/>
</div>
);
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 1bb96cd5c6..5940d1a48c 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -5739,14 +5739,15 @@
"showDetails": "Show Details",
"check": {
"checking": "Checking the server…",
+ "checkingHint": "Connecting to the server to check its system, ports and existing services.",
+ "idle": "After you choose a server, Cindy checks whether it can be deployed to.",
"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."
+ "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."
},
"running": {
"deploy": "Deploying to your server…",
@@ -5754,7 +5755,7 @@
"uninstall": "Removing the relay from your server…"
},
"done": {
- "deploy": "Deployed. This computer now uses the relay on your server. Use Add device to bring in your phone and other computers.",
+ "deploy": "Deployed. Switch to it under Connection Route, then you can add devices.",
"upgrade": "The relay on your server is now version {{version}}.",
"uninstall": "Relay removed from your server"
},
@@ -5778,7 +5779,6 @@
"nginx-rollback": "Deployment did not complete. Restoring the previous Nginx configuration…"
},
"steps": {
- "cleanup": "Clean up {{server}}",
"connect": "Connect to the server",
"check": "Check the server",
"runtime": "Install the runtime",
@@ -5813,6 +5813,10 @@
"deployingStep": "{{step}}…",
"viewProgress": "View Progress",
"resume": "Resume Deployment",
+ "rename": "Rename",
+ "renameHint": "Only changes the name shown on this computer. The server and joined devices keep the original name.",
+ "renameSave": "Save",
+ "renameCancel": "Cancel",
"statusChecking": "Checking…",
"statusOnline": "Online",
"statusOffline": "Unreachable",
@@ -5827,14 +5831,15 @@
"label": "Deployment steps",
"form": "Choose Server",
"deploy": "Deploy",
- "done": "Add Devices"
+ "done": "Done"
},
"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",
+ "doneHint": "This computer is still on its current route. Choose Use This Route to switch, then add your phone and other computers.",
+ "doneLater": "You can also switch later under Connection Route",
+ "use": "Use This Route",
"finish": "Done"
},
"manage": {
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index c404924534..0f8b057339 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -5707,14 +5707,15 @@
"showDetails": "詳細を表示",
"check": {
"checking": "サーバーを確認しています…",
+ "checkingHint": "サーバーに接続して、システム、ポート、既存のサービスを確認しています。",
+ "idle": "サーバーを選ぶと、デプロイできるかを先に確認します。",
"ready": "デプロイできます",
"blocked": "自動ではデプロイできません",
"recheck": "再確認",
"direct": "ポート 80 と 443 が空いているため、リレーが直接使用します。",
"nginx": "サーバーの既存の Nginx 経由で接続し、既存のサイトはそのまま残します。",
"mine": "このコンピュータからデプロイしたリレーがすでにあります。その場で更新し、参加済みのデバイスには影響しません。",
- "other": "このコンピュータ以外からデプロイされたリレーがあります。デプロイすると削除され、そのリレーに参加していたデバイスは再参加が必要です。",
- "cleanup": "先に {{server}} の未完了のデプロイを片付けます。"
+ "other": "このコンピュータ以外からデプロイされたリレーがあります。デプロイすると削除され、そのリレーに参加していたデバイスは再参加が必要です。"
},
"running": {
"deploy": "サーバーにデプロイしています…",
@@ -5722,7 +5723,7 @@
"uninstall": "サーバーから削除しています…"
},
"done": {
- "deploy": "デプロイが完了し、このコンピュータはサーバーのリレーを使うようになりました。「デバイスを追加」でスマホや他のコンピュータを参加させてください。",
+ "deploy": "デプロイが完了しました。「接続経路」で切り替えると、デバイスを追加できます。",
"upgrade": "サーバーのリレーを {{version}} に更新しました。",
"uninstall": "サーバーからリレーを削除しました"
},
@@ -5746,7 +5747,6 @@
"nginx-rollback": "デプロイが完了しませんでした。元の Nginx 設定を復元中…"
},
"steps": {
- "cleanup": "{{server}} を片付け",
"connect": "サーバーに接続",
"check": "サーバーを確認",
"runtime": "実行環境をインストール",
@@ -5781,6 +5781,10 @@
"deployingStep": "{{step}}…",
"viewProgress": "進行状況を見る",
"resume": "デプロイを続ける",
+ "rename": "名前を変更",
+ "renameHint": "このコンピュータでの表示名だけを変更します。サーバーと参加済みのデバイスでは元の名前のままです。",
+ "renameSave": "保存",
+ "renameCancel": "キャンセル",
"statusChecking": "確認しています…",
"statusOnline": "オンライン",
"statusOffline": "接続できません",
@@ -5795,14 +5799,15 @@
"label": "デプロイの手順",
"form": "サーバーを選択",
"deploy": "デプロイ",
- "done": "デバイスを追加"
+ "done": "完了"
},
"running": "{{server}} にデプロイしています…",
"backgroundHint": "ウィンドウを閉じてもデプロイは続きます",
"background": "バックグラウンドで続ける",
"doneTitle": "「{{name}}」のデプロイが完了しました",
- "doneHint": "このコンピュータはこのリレーを使うようになりました。スマホでスキャンするか、リンクを別のコンピュータに送って参加させてください。",
- "doneLater": "あとから「接続経路」でもデバイスを追加できます",
+ "doneHint": "このコンピュータは今の経路のままです。「この経路を使う」で切り替えてから、スマホや他のコンピュータを追加してください。",
+ "doneLater": "あとから「接続経路」でも切り替えられます",
+ "use": "この経路を使う",
"finish": "完了"
},
"manage": {
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 6d2416733b..af156effbe 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -5707,14 +5707,15 @@
"showDetails": "자세히 보기",
"check": {
"checking": "서버를 확인하는 중…",
+ "checkingHint": "서버에 연결해 시스템, 포트, 기존 서비스를 확인하는 중입니다.",
+ "idle": "서버를 선택하면 배포할 수 있는지 먼저 확인합니다.",
"ready": "배포할 수 있습니다",
"blocked": "자동으로 배포할 수 없습니다",
"recheck": "다시 확인",
"direct": "80·443 포트가 비어 있어 중계가 직접 사용합니다.",
"nginx": "서버의 기존 Nginx를 통해 연결하고, 기존 사이트는 그대로 둡니다.",
"mine": "이 컴퓨터에서 배포한 중계가 이미 있습니다. 그대로 업데이트하며, 참여한 기기에는 영향이 없습니다.",
- "other": "이 컴퓨터가 배포하지 않은 중계가 있습니다. 배포하면 삭제되고, 그 중계에 참여한 기기는 다시 참여해야 합니다.",
- "cleanup": "먼저 {{server}}의 끝나지 않은 배포를 정리합니다."
+ "other": "이 컴퓨터가 배포하지 않은 중계가 있습니다. 배포하면 삭제되고, 그 중계에 참여한 기기는 다시 참여해야 합니다."
},
"running": {
"deploy": "서버에 배포하는 중…",
@@ -5722,7 +5723,7 @@
"uninstall": "서버에서 제거하는 중…"
},
"done": {
- "deploy": "배포를 마쳤습니다. 이제 이 컴퓨터는 서버의 중계를 사용합니다. 기기 추가로 휴대폰과 다른 컴퓨터를 참여시키세요.",
+ "deploy": "배포를 마쳤습니다. 연결 경로에서 전환하면 기기를 추가할 수 있습니다.",
"upgrade": "서버의 중계를 {{version}}(으)로 업그레이드했습니다.",
"uninstall": "서버에서 중계를 제거했습니다"
},
@@ -5746,7 +5747,6 @@
"nginx-rollback": "배포를 완료하지 못했습니다. 이전 Nginx 설정을 복원하고 있습니다…"
},
"steps": {
- "cleanup": "기존 서버 {{server}} 정리",
"connect": "서버에 연결",
"check": "서버 확인",
"runtime": "실행 환경 설치",
@@ -5781,6 +5781,10 @@
"deployingStep": "{{step}}…",
"viewProgress": "진행 상황 보기",
"resume": "배포 계속",
+ "rename": "이름 변경",
+ "renameHint": "이 컴퓨터에 표시되는 이름만 바뀝니다. 서버와 참여한 기기에는 원래 이름이 그대로 표시됩니다.",
+ "renameSave": "저장",
+ "renameCancel": "취소",
"statusChecking": "확인하는 중…",
"statusOnline": "온라인",
"statusOffline": "연결 안 됨",
@@ -5795,14 +5799,15 @@
"label": "배포 단계",
"form": "서버 선택",
"deploy": "배포",
- "done": "기기 추가"
+ "done": "완료"
},
"running": "{{server}}에 배포하는 중…",
"backgroundHint": "창을 닫아도 배포는 계속됩니다",
"background": "백그라운드에서 계속",
"doneTitle": "{{name}} 배포를 마쳤습니다",
- "doneHint": "이제 이 컴퓨터는 이 중계를 사용합니다. 휴대폰으로 스캔하거나, 링크를 다른 컴퓨터에 보내 참여시키세요.",
- "doneLater": "나중에 연결 경로에서도 기기를 추가할 수 있습니다",
+ "doneHint": "이 컴퓨터는 아직 현재 경로를 사용합니다. 이 경로 사용을 눌러 전환한 뒤 휴대폰과 다른 컴퓨터를 추가하세요.",
+ "doneLater": "나중에 연결 경로에서도 전환할 수 있습니다",
+ "use": "이 경로 사용",
"finish": "완료"
},
"manage": {
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 073684884a..56a9c33438 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -5707,14 +5707,15 @@
"showDetails": "查看详情",
"check": {
"checking": "正在检查服务器…",
+ "checkingHint": "正在连接服务器,确认系统、端口和已有服务。",
+ "idle": "选择服务器后,会先检查它能否部署。",
"ready": "可以部署",
"blocked": "不能自动部署",
"recheck": "重新检查",
"direct": "80 和 443 端口空闲,中转会直接使用它们。",
"nginx": "会接入服务器上已有的 Nginx,并保留原有网站。",
"mine": "服务器上已有这台电脑部署的中转,会原地更新,已加入的设备不受影响。",
- "other": "服务器上已有不是这台电脑部署的中转,继续部署会清除它,已加入它的设备需要重新加入。",
- "cleanup": "会先清理 {{server}} 上没完成的部署。"
+ "other": "服务器上已有不是这台电脑部署的中转,继续部署会清除它,已加入它的设备需要重新加入。"
},
"running": {
"deploy": "正在部署到服务器…",
@@ -5722,7 +5723,7 @@
"uninstall": "正在从服务器移除…"
},
"done": {
- "deploy": "部署完成,这台电脑已改用服务器上的中转。用「添加设备」让手机和其他电脑加入。",
+ "deploy": "部署完成。在「连接线路」里切换到它之后,就可以添加设备。",
"upgrade": "服务器上的中转已升级到 {{version}}。",
"uninstall": "已从服务器移除中转"
},
@@ -5746,7 +5747,6 @@
"nginx-rollback": "部署未完成,正在恢复原来的 Nginx 配置…"
},
"steps": {
- "cleanup": "清理原服务器 {{server}}",
"connect": "连接服务器",
"check": "检查服务器",
"runtime": "安装运行环境",
@@ -5781,6 +5781,10 @@
"deployingStep": "{{step}}…",
"viewProgress": "查看进度",
"resume": "继续部署",
+ "rename": "改名",
+ "renameHint": "只改这台电脑上显示的名字,服务器和已加入的设备看到的名字不变。",
+ "renameSave": "保存",
+ "renameCancel": "取消",
"statusChecking": "正在检查…",
"statusOnline": "在线",
"statusOffline": "连不上",
@@ -5795,14 +5799,15 @@
"label": "部署步骤",
"form": "选择服务器",
"deploy": "部署",
- "done": "添加设备"
+ "done": "完成"
},
"running": "正在部署到 {{server}}…",
"backgroundHint": "关掉窗口不会中断部署",
"background": "在后台继续",
"doneTitle": "「{{name}}」已部署好",
- "doneHint": "这台电脑已改用它。用手机扫码,或把链接发给另一台电脑加入。",
- "doneLater": "之后也可以在「连接线路」里添加设备",
+ "doneHint": "这台电脑还在用原来的线路。点「使用这条线路」改用它,之后再添加手机和其他电脑。",
+ "doneLater": "之后也可以在「连接线路」里切换",
+ "use": "使用这条线路",
"finish": "完成"
},
"manage": {
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 8311c932b5..e910649054 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -5707,14 +5707,15 @@
"showDetails": "查看詳情",
"check": {
"checking": "正在檢查伺服器…",
+ "checkingHint": "正在連線伺服器,確認系統、連接埠和現有服務。",
+ "idle": "選擇伺服器後,會先檢查它能否部署。",
"ready": "可以部署",
"blocked": "無法自動部署",
"recheck": "重新檢查",
"direct": "80 和 443 連接埠沒有被使用,中繼會直接使用它們。",
"nginx": "會接入伺服器上現有的 Nginx,並保留原有網站。",
"mine": "伺服器上已有這台電腦部署的中繼,會原地更新,已加入的裝置不受影響。",
- "other": "伺服器上已有不是這台電腦部署的中繼,繼續部署會清除它,已加入它的裝置需要重新加入。",
- "cleanup": "會先清理 {{server}} 上沒完成的部署。"
+ "other": "伺服器上已有不是這台電腦部署的中繼,繼續部署會清除它,已加入它的裝置需要重新加入。"
},
"running": {
"deploy": "正在部署到伺服器…",
@@ -5722,7 +5723,7 @@
"uninstall": "正在從伺服器移除…"
},
"done": {
- "deploy": "部署完成,這台電腦已改用伺服器上的中繼。用「新增裝置」讓手機和其他電腦加入。",
+ "deploy": "部署完成。在「連線路線」裡切換到它之後,就可以新增裝置。",
"upgrade": "伺服器上的中繼已升級到 {{version}}。",
"uninstall": "已從伺服器移除中繼"
},
@@ -5746,7 +5747,6 @@
"nginx-rollback": "部署未完成,正在還原原本的 Nginx 設定…"
},
"steps": {
- "cleanup": "清理原伺服器 {{server}}",
"connect": "連線伺服器",
"check": "檢查伺服器",
"runtime": "安裝執行環境",
@@ -5781,6 +5781,10 @@
"deployingStep": "{{step}}…",
"viewProgress": "查看進度",
"resume": "繼續部署",
+ "rename": "改名",
+ "renameHint": "只改這台電腦上顯示的名稱,伺服器和已加入的裝置看到的名稱不變。",
+ "renameSave": "儲存",
+ "renameCancel": "取消",
"statusChecking": "正在檢查…",
"statusOnline": "線上",
"statusOffline": "連不上",
@@ -5795,14 +5799,15 @@
"label": "部署步驟",
"form": "選擇伺服器",
"deploy": "部署",
- "done": "新增裝置"
+ "done": "完成"
},
"running": "正在部署到 {{server}}…",
"backgroundHint": "關閉視窗不會中斷部署",
"background": "在背景繼續",
"doneTitle": "「{{name}}」已部署完成",
- "doneHint": "這台電腦已改用它。用手機掃描,或把連結傳給另一台電腦加入。",
- "doneLater": "之後也可以在「連線路線」裡新增裝置",
+ "doneHint": "這台電腦還在用原來的路線。點「使用這條路線」改用它,之後再新增手機和其他電腦。",
+ "doneLater": "之後也可以在「連線路線」裡切換",
+ "use": "使用這條路線",
"finish": "完成"
},
"manage": {
diff --git a/apps/desktop/src/shared/selfHostedRelay.ts b/apps/desktop/src/shared/selfHostedRelay.ts
index df65f9ebde..2a7d67f9b9 100644
--- a/apps/desktop/src/shared/selfHostedRelay.ts
+++ b/apps/desktop/src/shared/selfHostedRelay.ts
@@ -27,27 +27,30 @@ export type SelfHostedRelayCommand =
| { type: 'use-official' }
/**
* 部署到自己的服务器(经已配置的 SSH 主机)。`address` 是其他设备访问用的域名或公网 IP,证书签给它。
+ * 一台服务器只有一个中转:部署到已有记录的服务器就是重新部署那一个。部署完成不切换线路。
* `replaceExisting`:服务器上已有不属于这台电脑的中转时,清掉它重新部署。
*/
| { type: 'deploy'; sshHostId: string; address: string; name: string; replaceExisting: boolean }
+ /** 下面这些都针对某一个服务器中转,用部署记录的 `relayId` 指定。 */
/** 把服务器上的中转升级到这个版本 Cindy 自带的版本(保留已加入的设备)。 */
- | { type: 'upgrade-deployment' }
+ | { type: 'upgrade-deployment'; relayId: string }
/** 从服务器卸载中转;`removeData` 同时删除设备档案(已加入的设备需要重新加入)。 */
- | { type: 'uninstall-deployment'; removeData: boolean }
+ | { type: 'uninstall-deployment'; relayId: string; removeData: boolean }
/** 服务器已不可用时,只在本机删掉部署记录。 */
- | { type: 'forget-deployment' }
- /** 改回使用服务器上的中转(之前切回过官方中转)。 */
- | { type: 'use-deployment' }
+ | { type: 'forget-deployment'; relayId: string }
+ /** 改用服务器上的这个中转。 */
+ | { type: 'use-deployment'; relayId: string }
+ /** 改这个中转在本机显示的名字(不改服务器上的名字)。 */
+ | { type: 'rename-deployment'; relayId: string; name: string }
/** 只读检查服务器能否部署,不改动服务器;结果在命令返回的 `check` 里。 */
| { type: 'check-server'; sshHostId: string }
/** 关掉一次没改动过服务器的失败部署(检查阶段就停下的)。 */
| { type: 'dismiss-deploy-job' }
/** 以主人身份读取服务器中转的状态(在线、设备数、证书到期);结果在 `deploymentStatus` 里。 */
- | { type: 'deployment-status' };
+ | { type: 'deployment-status'; relayId: string };
/** 部署的步骤(界面逐步展示)。`finish` 只出现在日志里。 */
export type RelayDeployStep =
- | 'cleanup'
| 'connect'
| 'check'
| 'runtime'
@@ -58,7 +61,7 @@ export type RelayDeployStep =
| 'remove'
| 'finish';
-/** 部署与升级界面列出的步骤;换服务器时最前面再加 `cleanup`。 */
+/** 部署与升级界面列出的步骤。 */
export const RELAY_DEPLOY_STEPS: readonly RelayDeployStep[] = [
'check',
'runtime',
@@ -168,6 +171,8 @@ export interface SelfHostedRelayDeployJobView {
steps?: RelayDeployStep[];
/** 部署的目标。检查通过前还没有部署记录,界面靠它显示服务器和地址,失败后「修改设置」也从这里回填。 */
target?: { sshHostId: string; address: string; name: string; baseUrl: string };
+ /** 这次任务对应的服务器中转(部署记录的 `relayId`;检查通过前还没有记录)。 */
+ relayId?: string;
/** 已经开始改动服务器(部署记录已保存)。为 false 时失败的部署可以直接关掉。 */
serverChanged?: boolean;
}
@@ -185,6 +190,7 @@ export type SelfHostedRelayServerCheck =
| { sshHostId: string; ok: false; error: SelfHostedRelayErrorCode; detail?: string };
export interface SelfHostedRelayDeploymentView {
+ relayId: string;
sshHostId: string;
address: string;
baseUrl: string;
@@ -214,7 +220,8 @@ export interface SelfHostedRelayState {
/** 本机局域网地址(含端口),用于填写对外地址。 */
suggestedUrls: string[];
};
- deployment: SelfHostedRelayDeploymentView | null;
+ /** 部署到服务器的中转,一台服务器一个,按部署顺序。 */
+ deployments: SelfHostedRelayDeploymentView[];
deployJob: SelfHostedRelayDeployJobView | null;
/** 这个版本 Cindy 自带的中转版本;null = 没带(开发环境未构建)。 */
bundledRelayVersion: string | null;
@@ -228,6 +235,19 @@ function isRecord(value: unknown): value is Record<string, unknown> {
}
const SSH_HOST_ID_PATTERN = /^[A-Za-z0-9._@:-]{1,128}$/;
+const RELAY_ID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
+export const RELAY_NAME_MAX_LENGTH = 64;
+
+function relayIdOf(raw: Record<string, unknown>): string | null {
+ return typeof raw.relayId === 'string' && RELAY_ID_PATTERN.test(raw.relayId) ? raw.relayId : null;
+}
+
+/** 中转名字:去掉首尾空白,1–64 个字符。 */
+export function normalizeRelayName(value: unknown): string | null {
+ if (typeof value !== 'string') return null;
+ const name = value.trim();
+ return name && name.length <= RELAY_NAME_MAX_LENGTH ? name : null;
+}
/** 访问地址:域名或 IP(不带协议、端口、路径)。 */
export function normalizeRelayAddress(value: string): string | null {
@@ -254,12 +274,20 @@ export function parseSelfHostedRelayCommand(raw: unknown): SelfHostedRelayComman
case 'create-join-link':
case 'cancel-join':
case 'use-official':
+ case 'dismiss-deploy-job':
+ return { type: raw.type };
case 'upgrade-deployment':
case 'forget-deployment':
case 'use-deployment':
- case 'dismiss-deploy-job':
- case 'deployment-status':
- return { type: raw.type };
+ case 'deployment-status': {
+ const relayId = relayIdOf(raw);
+ return relayId ? { type: raw.type, relayId } : null;
+ }
+ case 'rename-deployment': {
+ const relayId = relayIdOf(raw);
+ const name = normalizeRelayName(raw.name);
+ return relayId && name ? { type: 'rename-deployment', relayId, name } : null;
+ }
case 'check-server':
if (typeof raw.sshHostId !== 'string' || !SSH_HOST_ID_PATTERN.test(raw.sshHostId)) return null;
return { type: 'check-server', sshHostId: raw.sshHostId };
@@ -280,15 +308,17 @@ export function parseSelfHostedRelayCommand(raw: unknown): SelfHostedRelayComman
return { type: 'join', link: raw.link };
case 'deploy': {
if (typeof raw.sshHostId !== 'string' || !SSH_HOST_ID_PATTERN.test(raw.sshHostId)) return null;
- if (typeof raw.address !== 'string' || typeof raw.name !== 'string' || typeof raw.replaceExisting !== 'boolean') return null;
+ if (typeof raw.address !== 'string' || typeof raw.replaceExisting !== 'boolean') return null;
const address = normalizeRelayAddress(raw.address);
- const name = raw.name.trim();
- if (!address || !name || name.length > 64) return null;
+ const name = normalizeRelayName(raw.name);
+ if (!address || !name) return null;
return { type: 'deploy', sshHostId: raw.sshHostId, address, name, replaceExisting: raw.replaceExisting };
}
- case 'uninstall-deployment':
- if (typeof raw.removeData !== 'boolean') return null;
- return { type: 'uninstall-deployment', removeData: raw.removeData };
+ case 'uninstall-deployment': {
+ const relayId = relayIdOf(raw);
+ if (!relayId || typeof raw.removeData !== 'boolean') return null;
+ return { type: 'uninstall-deployment', relayId, removeData: raw.removeData };
+ }
default:
return null;
}
diff --git a/docs/self-hosted-relay-plan.md b/docs/self-hosted-relay-plan.md
index b5b2df060d..55dd8aa193 100644
--- a/docs/self-hosted-relay-plan.md
+++ b/docs/self-hosted-relay-plan.md
@@ -125,7 +125,8 @@ IP 证书的注意点:
1. 去云服务器控制台的安全组放行 TCP 443。
2. 检查服务器上的防火墙。
3. 端口被占用时,改用前置代理方式。
-9. 完成,显示加入二维码。主人电脑自动切换到这个中转。
+9. 完成,显示部署结果,**不切换线路**:是否改用这个中转由用户决定(完成页的「使用这条线路」或线路列表里的切换,都先确认);切换后再添加设备。
+ 可以部署到多台服务器,一台服务器一个中转;部署到已有记录的服务器就是重新部署那一个(2026-10-30,见 §15.5)。
**权限**:
@@ -429,6 +430,7 @@ App 内不加扫码组件:加一个会改变原生指纹,需要冷更。
- 多台主人电脑。
- 中转自带 TURN。
- 可选的官方推送转发。
+- 自建模式下的供应商分享与共享任务(用户 2026-10-30 提出):卡住它们的不是官方证书,而是它们跨账号,成员关系和转发校验都在官方 device-link 服务端(`provider-sharing-contract.md` §2、§3),受邀者也连在官方中转上。可行做法是自建模式下这台电脑另外保持一条到官方的连接,只走带 `providerShare` / `sharedTask` 范围的帧,自己设备之间仍走自建中转;要改 device-link 的连接管理,单独设计。手机系统推送需要官方 App 的推送凭据,不在此列。
- 公司内网场景:内网服务器 + 公司自己签发的证书。
## 15. 实施记录
@@ -561,8 +563,8 @@ App 内不加扫码组件:加一个会改变原生指纹,需要冷更。
- 证书机构连不上(断网、超时、连接重置、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 步,可换服务器)或放弃部署(清理服务器后删除记录)。换服务器时先按原身份清理原服务器上没完成的部署。完成页直接生成加入链接与二维码。
+ - 线路是一个单选列表(官方 / 我的服务器(每台服务器一行,2026-10-30 起)/ 这台电脑当中转 / 已加入的中转):选中的那一行就是正在用的;其他行给切换图标,切换一律先弹确认,说明原线路会怎样(从官方切到自己的中转时说明手机系统推送、供应商分享和共享任务暂不可用)。部署中、未完成、移除中的状态显示在服务器那一行上。右侧只放同样大小的图标并贴右对齐:切换在前,这条线路自己的操作(服务器中转的删除、这台电脑当中转的设置)在后,没有的不占位,只有一个图标时它就在最右边;正在用的线路在名字旁边显示一个绿点(悬停与读屏为「正在使用」),不进图标列(文字和图标混在一列对不齐,用户 2026-10-29 反馈)。「加入别的中转」和这台电脑当中转的设置都用小窗口,不在列表下面展开;这台电脑当中转要先填设置,切换到它就是打开设置窗口。
+ - 部署是三步窗口(选择服务器 → 部署 → 完成,2026-10-30 起第 3 步不再是添加设备):关窗口不中断部署;失败的一步下面写原因(技术细节折叠),失败后不再列出没执行的步骤,可重试、修改设置(回第 1 步,可换服务器)或放弃部署(清理服务器后删除记录)。完成页只显示结果和「使用这条线路」,不自动切换、不生成加入链接;换到另一台服务器部署时,原服务器上没完成的那条记录保留,可以继续或放弃(见 §15.5)。
- 服务器中转的详情并入服务器那一行,且只在正在使用这条线路时显示(没在用时设备数、证书等没有意义,也不去请求):在线状态、已加入/在线设备数、证书剩余天数与版本来自 `deployment-status`(用部署记录里的主人凭证读 `admin/status`,中转 ID 不符按连不上处理),添加设备与升级在详情里,检查连接是状态旁的刷新图标。移除是行尾的图标按钮,先确认;服务器连不上或中转不归这台电脑时才提供「只在本机移除」。
- 已有 Nginx 的自动接入(2026-10-29,服务器 bundle `0.3.0`):
- 证书重试修复随 bundle `0.3.1` 提供;已部署 `0.3.0` 的用户通过现有升级入口上传新程序,设备档案与主人身份继续沿用,不改变线协议。
@@ -598,6 +600,7 @@ App 内不加扫码组件:加一个会改变原生指纹,需要冷更。
- 升级(Cindy 带的中转版本不同时);
- 从服务器卸载(连同设备档案);
- 只在本机移除;
+ - 改名(只改本机显示的名字,服务器和已加入的设备看到的仍是部署时的名字);
- 改用这个中转。
- 作为服务器中转的主人时,「添加设备」与审批直接对 `https://<地址>` 调管理接口,与本机中转共用同一套界面。
- 切回官方中转时,服务器上的中转继续运行,可以随时改回来。
@@ -654,12 +657,25 @@ App 内不加扫码组件:加一个会改变原生指纹,需要冷更。
1. 使用含本次代码的桌面开发版,在「设置 → 远程」配置自己的 Linux SSH 主机。
2. 打开「设置 → 远程连接 → 中转服务 → 部署到我的服务器」,选主机、核对访问地址,开始部署。
主机需支持 systemd,并具备 root 或免密 sudo;80/443 端口需空闲或由原生 Nginx 使用,部署时自动接入 Nginx,云安全组需放行这两个端口。
-3. 等待部署完成并自动切换后,点击「添加设备」。另一台新版电脑粘贴链接,手机用含本次 JS 改动的开发版扫码。
+3. 等待部署完成,点「使用这条线路」并确认(2026-10-30 起不再自动切换),再点击「添加设备」。另一台新版电脑粘贴链接,手机用含本次 JS 改动的开发版扫码。
在主人电脑核对配对码并同意,再测试设备列表、远程消息、图片和断线重连。
4. 切回官方中转,核对原有连接恢复,服务器中转仍继续运行;可以再点击「改用这个中转」。
真实云服务器部署、生产 CA 签发与续期、手机真机仍待体验验证;本轮未操作用户的云服务器,也未提交或发布。
+### 15.5 多台服务器、部署后手动切换、改名与部署窗口高度(2026-10-30)
+
+用户反馈:部署过程中窗口高度来回跳;部署了一台就不能再部署;部署完不该马上切换;部署完要能改名。
+
+- **窗口高度**:部署窗口三步共用固定高度 `min(560px, 88vh)`,内容在中间区域滚动,底部按钮不动;服务器检查卡片在未选、检查中、检查通过时都先占两行说明的高度;部署中的实时进展固定在进度条下面的一行,不再插在当前步骤下面推动列表。
+- **多台服务器**:本机配置 `config.json` 的部署记录从单个 `deployment` 改为 `deployments` 列表,一台服务器(SSH 主机)一条,中转 ID 不重复;配置版本仍是 2。读取时没有 `deployments` 就把旧字段 `deployment` 读成一条;写入时同时把正在用的(或第一条)写进旧字段,装回旧版本仍能看到它(旧版本再写回会丢掉其余几条的本机记录,服务器上的中转与秘密文件不受影响)。
+- **命令**:`upgrade-deployment`、`uninstall-deployment`、`forget-deployment`、`use-deployment`、`deployment-status` 都带 `relayId`;新增 `rename-deployment`。部署任务带 `relayId`,界面据此把进度显示在对应那一行;同时仍只允许一个部署任务。IPC 只在本机窗口与主进程之间,随同一版本发布,不涉及手机或中转协议。
+- **不自动切换**:部署完成只保存记录;正在用的就是这个中转时(升级、重新部署)才按新记录重连。完成页给「使用这条线路」,与列表里的切换一样先确认。
+- **不再清理其他服务器**:原先换服务器部署前会先清理上一台没完成的部署(`cleanup` 步骤),现在那条记录留在列表里,由用户继续或放弃。
+- **改名**:只改本机记录与正在用的线路名,不连服务器;部署或升级进行中改名,完成时不被覆盖。服务器上没有改名接口,新设备加入时等待页显示的仍是部署时的名字。
+- **实现**:`apps/desktop/src/shared/selfHostedRelay.ts`、`src/main/device-link/selfHostedRelayConfig.ts`、`selfHostedRelayRuntime.ts`、`src/renderer/components/settings/RelayServicePanel.tsx`。
+- **回归**:`selfHostedRelayRuntime.test.ts`(部署不切换、两台服务器并存、改名、没完成的记录保留)、`selfHostedRelayConfig.test.ts`(旧格式读取与旧字段写回);单页场景 `relay-service` 新增 `deploy-steady`(每一步窗口位置与大小、表单输入框和步骤列表都不动)与 `multi`(两台服务器、改名)。
+
## 16. 设备签名:中转无法冒充你的设备
### 16.1 要防什么