Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(device-link): 暴露待命状态并诊断不稳定连接 (#1611)
Dashffc90023d34c
diff --git a/apps/desktop/src/main/__tests__/deviceLinkIpc.test.ts b/apps/desktop/src/main/__tests__/deviceLinkIpc.test.tsindex e73b93fb8c..199b3c6976 100644--- a/apps/desktop/src/main/__tests__/deviceLinkIpc.test.ts+++ b/apps/desktop/src/main/__tests__/deviceLinkIpc.test.ts@@ -102,6 +102,7 @@ function makeDeps(overrides?: Partial<DeviceLinkIpcDeps>): DeviceLinkIpcDeps {keepAwake: false,linkStatus: 'online',connectionIssue: null,+ standby: false,controlledBy: [],revokedControllers: [],disabledControlDeviceIds: [],@@ -139,6 +140,7 @@ describe('device-link IPC handlers', () => {keepAwake: false,linkStatus: 'online',connectionIssue: null,+ standby: false,controlledBy: [],revokedControllers: [],disabledControlDeviceIds: [],@@ -146,6 +148,23 @@ describe('device-link IPC handlers', () => {});});+ it('getState 透传待命状态', () => {+ const deps = makeDeps({+ getState: () => ({+ remoteControlEnabled: true,+ keepAwake: false,+ linkStatus: 'stopped',+ connectionIssue: null,+ standby: true,+ controlledBy: [],+ revokedControllers: [],+ disabledControlDeviceIds: [],+ unresponsiveDeviceIds: [],+ }),+ });+ expect(handleGetState(deps).standby).toBe(true);+ });+it('getState: local/signed-out sessions only expose keepAwake', () => {capabilities.canUseDeviceLink = false;const deps = makeDeps({@@ -159,6 +178,7 @@ describe('device-link IPC handlers', () => {detail: 'account state',at: 123,},+ standby: false,controlledBy: [{ deviceId: 'controller-1', name: 'Other device' }],revokedControllers: ['revoked-1'],disabledControlDeviceIds: ['disabled-1'],@@ -171,6 +191,7 @@ describe('device-link IPC handlers', () => {keepAwake: true,linkStatus: 'stopped',connectionIssue: null,+ standby: false,controlledBy: [],revokedControllers: [],disabledControlDeviceIds: [],@@ -335,6 +356,7 @@ describe('device-link IPC handlers', () => {keepAwake: false,linkStatus: 'online',connectionIssue: null,+ standby: false,controlledBy: [],revokedControllers: [],disabledControlDeviceIds: ['dev-1'],@@ -431,6 +453,7 @@ describe('device-link controller handlers', () => {keepAwake: false,linkStatus: 'online',connectionIssue: null,+ standby: false,controlledBy: [],revokedControllers: [],disabledControlDeviceIds: ['dev-2'],@@ -536,6 +559,7 @@ describe('device-link controller handlers', () => {keepAwake: false,linkStatus: 'online',connectionIssue: null,+ standby: false,controlledBy: [],revokedControllers: [],disabledControlDeviceIds: disabled ? ['dev-2'] : [],diff --git a/apps/desktop/src/main/__tests__/safeStorageCodexRestart.test.ts b/apps/desktop/src/main/__tests__/safeStorageCodexRestart.test.tsindex 69590bc841..541f57f900 100644--- a/apps/desktop/src/main/__tests__/safeStorageCodexRestart.test.ts+++ b/apps/desktop/src/main/__tests__/safeStorageCodexRestart.test.ts@@ -55,4 +55,21 @@ describe('safe storage Codex restart invariants', () => {expect(src.slice(start, end)).toContain('isValidRendererKey(key)');}});++ it('keeps safe-storage-read fail-closed and downgrades expected permission denials', () => {+ const src = source();+ const start = src.indexOf("'safe-storage-read'");+ const end = src.indexOf("'safe-storage-remove'", start);+ expect(start).toBeGreaterThan(-1);+ expect(end).toBeGreaterThan(start);+ const body = src.slice(start, end);+ expect(body).toContain('assertTrustedAppRendererEvent(event);');+ expect(body.indexOf('assertTrustedAppRendererEvent(event);')).toBeLessThan(+ body.indexOf('resolveSafeStorageFilepath(key)'),+ );+ expect(body).toContain("isIpcError(err) && err.code === 'PERMISSION_DENIED'");+ expect(body).toContain("safeStorageReadLog.debug('read denied for untrusted renderer')");+ expect(body).toContain("safeStorageReadLog.error('read failed'");+ expect(body).not.toContain("console.error('[safe-storage-read]', err)");+ });});diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.tsindex c665d9e0ab..3ae15f2740 100644--- a/apps/desktop/src/main/bootstrap-electron.ts+++ b/apps/desktop/src/main/bootstrap-electron.ts@@ -293,6 +293,7 @@ import {markAppContentWindow,} from './windowFocusClassifier.js';import { assertTrustedAppRendererEvent } from './security/trustedAppRenderer.js';+import { isIpcError } from '../shared/ipc-errors';import { readFileBytesForPreview } from './fileReadBytes.js';import { initHeartbeatService } from './heartbeatService';import { initAnalyticsSettingsService, noteAuthColdStartState } from './analyticsSettingsService';@@ -911,6 +912,7 @@ const dbClientLog = createLogger('DbClient');const authBoundaryLog = createLogger('auth-boundary');// 主窗 renderer 加载失败可观测性 + dev 启动看门狗(见 renderer-boot-guard.ts 顶部注释)。const rendererGuardLog = createLogger('renderer-guard');+const safeStorageReadLog = createLogger('safe-storage:read');const updatePresentationLog = createLogger('update-presentation');const voicePowerBroadcastLog = createLogger('voice-input-power');let rendererBootGuard: RendererBootGuard | null = null;@@ -3587,7 +3589,16 @@ const registerIpcHandlers = () => {const buffer = Buffer.from(content, 'base64');return safeStorage.decryptString(buffer);} catch (err) {- console.error('[safe-storage-read]', err);+ // 非可信 auxiliary/WebView renderer 触发的拒绝是预期安全结果,降为 debug;+ // guard、allowlist、路径和明文返回边界保持不变。其它异常仍可见,但只记录+ // 安全的类型/code,绝不落原始 message、路径、sender 或密文。+ if (isIpcError(err) && err.code === 'PERMISSION_DENIED') {+ safeStorageReadLog.debug('read denied for untrusted renderer');+ } else {+ safeStorageReadLog.error('read failed', {+ error: isIpcError(err) ? err.code : err instanceof Error ? err.name : 'unknown',+ });+ }return null;}},diff --git a/apps/desktop/src/main/device-link/__tests__/ownership.test.ts b/apps/desktop/src/main/device-link/__tests__/ownership.test.tsindex 0b8b007a02..616330d7dd 100644--- a/apps/desktop/src/main/device-link/__tests__/ownership.test.ts+++ b/apps/desktop/src/main/device-link/__tests__/ownership.test.ts@@ -81,18 +81,20 @@ function memoryStore(): OwnershipStore & {function makeArbiter(opts: { store: OwnershipStore | null; id?: string; now: () => number }) {const onAcquire = vi.fn();const onDemote = vi.fn();+ const onStandbyChanged = vi.fn();const arbiter = new DeviceLinkOwnershipArbiter({getStore: () => opts.store,instance: { ownerPid: 100, ownerLabel: 'test' },newOwnerId: () => opts.id ?? 'self',onAcquire,onDemote,+ onStandbyChanged,heartbeatMs: 5_000,staleMs: 15_000,now: opts.now,});// 测试直接手动驱动 tick,不调 start()(避免 start 的后台首 tick 与手动 tick 竞争防重入锁)- return { arbiter, onAcquire, onDemote };+ return { arbiter, onAcquire, onDemote, onStandbyChanged };}describe('DeviceLinkOwnershipArbiter', () => {@@ -458,6 +460,127 @@ describe('DeviceLinkOwnershipArbiter', () => {}),).toThrow(/staleMs/);});++ describe('待命状态通知(onStandbyChanged)', () => {+ it('外部持有者心跳新鲜 → 通知待命并去重', async () => {+ const store = memoryStore();+ store.set({ ownerId: 'other', ownerPid: 200, heartbeatAt: clock - 5_000 });+ const { arbiter, onStandbyChanged } = makeArbiter({ store, now });+ await arbiter.tick();+ expect(arbiter.isStandby()).toBe(true);+ expect(onStandbyChanged).toHaveBeenCalledWith(true);+ store.set({ ownerId: 'other', ownerPid: 200, heartbeatAt: clock });+ await arbiter.tick();+ expect(onStandbyChanged).toHaveBeenCalledTimes(1);+ });++ it('过期持有者直接接管,不先闪一次待命', async () => {+ const store = memoryStore();+ store.set({ ownerId: 'other', ownerPid: 200, heartbeatAt: clock - 16_000 });+ const { arbiter, onStandbyChanged } = makeArbiter({ store, now });+ await arbiter.tick();+ expect(arbiter.isOwner()).toBe(true);+ expect(arbiter.isStandby()).toBe(false);+ expect(onStandbyChanged).not.toHaveBeenCalled();+ });++ it('失去持有权、接管和 stop 都会翻转待命状态', async () => {+ const store = memoryStore();+ const { arbiter, onStandbyChanged } = makeArbiter({ store, now });+ await arbiter.tick();+ store.set({ ownerId: 'usurper', ownerPid: 300, heartbeatAt: clock });+ clock += 5_000;+ await arbiter.tick();+ expect(arbiter.isStandby()).toBe(true);+ expect(onStandbyChanged).toHaveBeenLastCalledWith(true);+ clock += 16_000;+ await arbiter.tick();+ expect(arbiter.isOwner()).toBe(true);+ expect(onStandbyChanged).toHaveBeenLastCalledWith(false);+ await arbiter.stop();+ expect(arbiter.isStandby()).toBe(false);+ });++ it('ownership store 短暂不可用时保留最近一次已确认的待命状态', async () => {+ const base = memoryStore();+ base.set({ ownerId: 'other', ownerPid: 200, heartbeatAt: clock - 5_000 });+ let store: OwnershipStore | null = base;+ const onStandbyChanged = vi.fn();+ const arbiter = new DeviceLinkOwnershipArbiter({+ getStore: () => store,+ instance: { ownerPid: 100, ownerLabel: 'test' },+ newOwnerId: () => 'self',+ onAcquire: vi.fn(),+ onDemote: vi.fn(),+ onStandbyChanged,+ heartbeatMs: 5_000,+ staleMs: 15_000,+ now,+ });++ await arbiter.tick();+ expect(arbiter.isStandby()).toBe(true);++ store = {+ ...base,+ read: async () => {+ throw new Error('temporary ownership store failure');+ },+ };+ await arbiter.tick();+ expect(arbiter.isStandby()).toBe(true);++ store = null;+ await arbiter.tick();+ expect(arbiter.isStandby()).toBe(true);+ expect(onStandbyChanged).toHaveBeenCalledTimes(1);+ });++ it('ownership read 本地超时时保留待命,直到明确结果推进状态', async () => {+ vi.useFakeTimers();+ try {+ const base = memoryStore();+ base.set({ ownerId: 'other', ownerPid: 200, heartbeatAt: clock - 5_000 });+ let readHangs = false;+ const store: OwnershipStore = {+ ...base,+ read: () => (readHangs ? new Promise<never>(() => {}) : base.read()),+ };+ const onStandbyChanged = vi.fn();+ const arbiter = new DeviceLinkOwnershipArbiter({+ getStore: () => store,+ instance: { ownerPid: 100, ownerLabel: 'test' },+ newOwnerId: () => 'self',+ onAcquire: vi.fn(),+ onDemote: vi.fn(),+ onStandbyChanged,+ heartbeatMs: 5_000,+ staleMs: 15_000,+ opTimeoutMs: 100,+ now,+ });++ await arbiter.tick();+ expect(arbiter.isStandby()).toBe(true);++ readHangs = true;+ const timedOutTick = arbiter.tick();+ await vi.advanceTimersByTimeAsync(100);+ await timedOutTick;+ expect(arbiter.isStandby()).toBe(true);+ expect(onStandbyChanged).toHaveBeenCalledTimes(1);++ readHangs = false;+ base.set(null);+ await arbiter.tick();+ expect(arbiter.isOwner()).toBe(true);+ expect(arbiter.isStandby()).toBe(false);+ expect(onStandbyChanged).toHaveBeenLastCalledWith(false);+ } finally {+ vi.useRealTimers();+ }+ });+ });});describe('createDbClientOwnershipStore(真 SQLite CAS 语义,DbClient 接口适配)', () => {diff --git a/apps/desktop/src/main/device-link/index.ts b/apps/desktop/src/main/device-link/index.tsindex 46661a9feb..84724e1c70 100644--- a/apps/desktop/src/main/device-link/index.ts+++ b/apps/desktop/src/main/device-link/index.ts@@ -717,6 +717,11 @@ export function initDeviceLinkService(options: DeviceLinkServiceOptions = {}): vappliedSettingsSnapshot = null;teardownActiveLink();},+ // 待命状态推给 renderer:待命实例不连 relay,远程设备会全部显示离线、远程调用一律+ // DEVICE_LINK_STANDBY。不广播的话这段时间界面上没有任何解释(用户只能以为功能坏了)。+ onStandbyChanged: (standby) => {+ broadcast(DEVICE_LINK_PUSH.OWNERSHIP_CHANGED, { standby });+ },});// 登录态驱动仲裁:已登录即参与认领(控制端列表/被控端可达都依赖这条 WS)@@ -1057,6 +1062,14 @@ export function getDeviceLinkConnectionIssue(): DeviceLinkConnectionIssue | nullreturn client?.getConnectionIssue() ?? null;}+/**+ * 本机另一个实例正持有 device-link(本实例待命)。仲裁器缺失时按 false ——+ * 未登录 / 服务未初始化不是“被占用”,不能让 UI 显示一条无从处理的占用提示。+ */+export function isDeviceLinkStandby(): boolean {+ return arbiter?.isStandby() ?? false;+}+/** 切换「允许被控」开关:落盘 + 在线时即时 presence-set 广播;关闭时踢掉所有控制端 */export async function setRemoteControlEnabled(enabled: boolean): Promise<void> {// 先消化并 enforce 盘上的外部变化(另一实例可能刚改过授权),再应用本地修改;diff --git a/apps/desktop/src/main/device-link/ipc.ts b/apps/desktop/src/main/device-link/ipc.tsindex 94b3415098..fce29aa781 100644--- a/apps/desktop/src/main/device-link/ipc.ts+++ b/apps/desktop/src/main/device-link/ipc.ts@@ -25,6 +25,7 @@ import {import {getDeviceLinkStatus,getDeviceLinkConnectionIssue,+ isDeviceLinkStandby,getUnresponsiveDeviceIds,clearDeviceResponsiveness,setRemoteControlEnabled,@@ -122,6 +123,7 @@ export function defaultDeps(): DeviceLinkIpcDeps {keepAwake: s.keepAwake,linkStatus: getDeviceLinkStatus(),connectionIssue: getDeviceLinkConnectionIssue(),+ standby: isDeviceLinkStandby(),controlledBy: getActiveControllers(),revokedControllers: s.revokedControllers,disabledControlDeviceIds: s.disabledControlDeviceIds,@@ -229,6 +231,8 @@ export function handleGetState(deps: DeviceLinkIpcDeps): DeviceLinkState {keepAwake: state.keepAwake,linkStatus: 'stopped',connectionIssue: null,+ // 无 device-link 能力(未登录 / 本地会话)不是“被本机另一实例占用”,按 false 上报。+ standby: false,controlledBy: [],revokedControllers: [],disabledControlDeviceIds: [],diff --git a/apps/desktop/src/main/device-link/ownership.ts b/apps/desktop/src/main/device-link/ownership.tsindex 4c81bcf0b9..8d8024c44e 100644--- a/apps/desktop/src/main/device-link/ownership.ts+++ b/apps/desktop/src/main/device-link/ownership.ts@@ -80,6 +80,8 @@ export interface OwnershipArbiterOptions {onAcquire: () => void;/** 失去持有权(续期 CAS 失败,行被他人接管)→ 宿主停止 relay 连接 */onDemote: () => void;+ /** 本机另一个实例持有连接时通知宿主;仅在状态变化时调用。 */+ onStandbyChanged?: (standby: boolean) => void;/** 持有者续期间隔,默认 5s */heartbeatMs?: number;/** 心跳超过该时长未续视为持有者失效,默认 15s(须 > 2×heartbeatMs 留余量) */@@ -149,6 +151,8 @@ export class DeviceLinkOwnershipArbiter {private lastRenewOkAt = 0;/** 已记录过日志的外部持有者,变化才再记(避免被动态每 5s 刷一行) */private loggedForeignOwnerId: string | null = null;+ /** 是否确知本机另一个实例正持有 device-link。 */+ private standby = false;constructor(options: OwnershipArbiterOptions) {const heartbeatMs = options.heartbeatMs ?? DEFAULT_HEARTBEAT_MS;@@ -175,6 +179,10 @@ export class DeviceLinkOwnershipArbiter {return this.owner;}+ isStandby(): boolean {+ return this.standby;+ }+start(): void {if (this.timer) return;this.identity = this.buildIdentity(); // 轮换 ownerId,见字段注释@@ -202,6 +210,7 @@ export class DeviceLinkOwnershipArbiter {clearInterval(this.timer);this.timer = null;}+ this.setStandby(false);this.clearStoreRetry();let released: Promise<void> = Promise.resolve();{@@ -243,7 +252,9 @@ export class DeviceLinkOwnershipArbiter {// 回到 4409 互踢。超过自我降级期限(< staleMs)先停 client 保安全。this.maybeSelfDemoteForRenewFailure((this.opts.now ?? Date.now)());} else {- // DB 未就绪:排一次快速重试,把冷启动首连延迟从一整拍收敛到亚秒级+ // DB 未就绪时保留最近一次已确认的 standby 事实,避免短暂故障把“另一实例占用”+ // 错误地洗成普通离线;DB 恢复后的明确 ownership 结果再推进状态。+ // 同时排一次快速重试,把冷启动首连延迟从一整拍收敛到亚秒级。this.scheduleStoreRetry();}return;@@ -294,6 +305,7 @@ export class DeviceLinkOwnershipArbiter {return;}if (!row) {+ this.setStandby(false);const insertPromise = store.tryInsert(id, now);const inserted = await this.raceOpTimeout(insertPromise);if (inserted === OP_TIMEOUT) {@@ -359,7 +371,8 @@ export class DeviceLinkOwnershipArbiter {if (taken) this.promote(`takeover-stale(prev pid=${row.ownerPid})`);return;}- // 持有者心跳新鲜 → 保持被动,不抢+ // 持有者心跳新鲜 → 保持被动,不抢。过期行会直接尝试接管,不先闪一次待命提示。+ this.setStandby(true);} catch (err) {log.warn('ownership tick failed (will retry next tick)', err);// 持有者续期持续抛错(如 DbClient worker 崩溃):与 store 不可用同栏,@@ -458,6 +471,7 @@ export class DeviceLinkOwnershipArbiter {private promote(reason: string): void {this.owner = true;this.lastRenewOkAt = (this.opts.now ?? Date.now)();+ this.setStandby(false);log.info(`became device-link owner (${reason})`);try {this.opts.onAcquire();@@ -468,6 +482,7 @@ export class DeviceLinkOwnershipArbiter {private demote(reason: string): void {this.owner = false;+ this.setStandby(reason === 'superseded');log.info(`no longer device-link owner (${reason})`);try {this.opts.onDemote();@@ -475,6 +490,16 @@ export class DeviceLinkOwnershipArbiter {log.error('onDemote callback failed', err);}}++ private setStandby(next: boolean): void {+ if (this.standby === next) return;+ this.standby = next;+ try {+ this.opts.onStandbyChanged?.(next);+ } catch (err) {+ log.error('onStandbyChanged callback failed', err);+ }+ }}// ─── DbClient store 实现 ──────────────────────────────────────────────────────diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.tsindex e8a70c2a00..095f8032f3 100644--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@ -541,6 +541,7 @@ const fanOutDeviceLinkControlledState = createIpcFanOut('device-link:controlled-const fanOutDeviceLinkAccessRevoked = createIpcFanOut('device-link:access-revoked');const fanOutDeviceLinkControlTargetChanged = createIpcFanOut('device-link:control-target-changed');const fanOutDeviceLinkKeepAwakeChanged = createIpcFanOut('device-link:keep-awake-changed');+const fanOutDeviceLinkOwnershipChanged = createIpcFanOut('device-link:ownership-changed');// 控制端:目标设备「无响应」熔断状态翻转(payload = { deviceId, unresponsive })const fanOutDeviceLinkResponsivenessChanged = createIpcFanOut('device-link:responsiveness-changed');@@ -3296,11 +3297,12 @@ contextBridge.exposeInMainWorld('electronAPI', {keepAwake: boolean;linkStatus: 'stopped' | 'connecting' | 'online';connectionIssue: {- kind: 'auth-failed' | 'replaced' | 'too-many-connections' | 'version-mismatch';+ kind: 'auth-failed' | 'replaced' | 'too-many-connections' | 'version-mismatch' | 'unstable';closeCode?: number;detail?: string;at: number;} | null;+ standby: boolean;controlledBy: Array<{ deviceId: string; name: string }>;revokedControllers: string[];disabledControlDeviceIds: string[];@@ -3376,6 +3378,8 @@ contextBridge.exposeInMainWorld('electronAPI', {onControlTargetChanged: fanOutDeviceLinkControlTargetChanged,/** 「保持电脑唤醒」在其它共享 userData 实例被翻转后推送,payload: { keepAwake: boolean } */onKeepAwakeChanged: fanOutDeviceLinkKeepAwakeChanged,+ /** 同机单持有者仲裁角色变化,payload: { standby: boolean }。 */+ onOwnershipChanged: fanOutDeviceLinkOwnershipChanged,/** 控制端:目标设备「无响应」熔断状态翻转,payload: { deviceId, unresponsive } */onResponsivenessChanged: fanOutDeviceLinkResponsivenessChanged,/**diff --git a/apps/desktop/src/renderer/__tests__/mobileDownloadDialog.test.tsx b/apps/desktop/src/renderer/__tests__/mobileDownloadDialog.test.tsxindex 69e80d28d5..c8f6219a7c 100644--- a/apps/desktop/src/renderer/__tests__/mobileDownloadDialog.test.tsx+++ b/apps/desktop/src/renderer/__tests__/mobileDownloadDialog.test.tsx@@ -42,6 +42,7 @@ const getState = vi.fn<() => Promise<DeviceLinkState>>(async () => ({keepAwake: false,linkStatus: 'online',connectionIssue: null,+ standby: false,controlledBy: [],revokedControllers: [],disabledControlDeviceIds: [],@@ -463,6 +464,7 @@ describe('MobileDownloadDialog', () => {keepAwake: false,linkStatus: 'connecting' as const,connectionIssue: null,+ standby: false,controlledBy: [],revokedControllers: [],disabledControlDeviceIds: [],diff --git a/apps/desktop/src/renderer/__tests__/myDevicesModel.test.ts b/apps/desktop/src/renderer/__tests__/myDevicesModel.test.tsindex c05c377ce8..53c6dad1cd 100644--- a/apps/desktop/src/renderer/__tests__/myDevicesModel.test.ts+++ b/apps/desktop/src/renderer/__tests__/myDevicesModel.test.ts@@ -4,6 +4,7 @@ import {canBeControlledPlatform,controlToggleState,inboundToggleState,+ resolveActiveConnectionIssue,} from '@/components/settings/myDevicesModel';describe('canBeControlledPlatform(手机不展示「我控制它」)', () => {@@ -61,3 +62,13 @@ describe('inboundToggleState(允许它控制本机)', () => {expect(inboundToggleState(false, true)).toEqual({ checked: false, disabled: true });});});++describe('resolveActiveConnectionIssue(本机卡片的原因行)', () => {+ it('普通 issue 在 online 后隐藏,unstable 即使 online 仍显示', () => {+ const authFailed = { kind: 'auth-failed' as const };+ const unstable = { kind: 'unstable' as const };+ expect(resolveActiveConnectionIssue('connecting', authFailed)).toBe(authFailed);+ expect(resolveActiveConnectionIssue('online', authFailed)).toBeNull();+ expect(resolveActiveConnectionIssue('online', unstable)).toBe(unstable);+ });+});diff --git a/apps/desktop/src/renderer/__tests__/remoteHistoryOriginReconcile.test.ts b/apps/desktop/src/renderer/__tests__/remoteHistoryOriginReconcile.test.tsindex 1cf255c982..6d18a9921f 100644--- a/apps/desktop/src/renderer/__tests__/remoteHistoryOriginReconcile.test.ts+++ b/apps/desktop/src/renderer/__tests__/remoteHistoryOriginReconcile.test.ts@@ -34,6 +34,7 @@ vi.mock('@/lib/sessionService', () => ({import { makerChatStore } from '@/lib/makerChatStore';import * as messageService from '@/lib/messageService';+import * as sessionService from '@/lib/sessionService';import { remoteProjectsStore } from '@/features/device-link/remoteProjectsStore';const DEVICE_ID = 'dev-A';@@ -177,6 +178,41 @@ describe('makerChatStore.reconcileOpenSessionOrigins (device-link 历史竞速)'expect(makerChatStore.getSnapshot(s).messages).toHaveLength(1);});+ it('来源漂移后丢弃旧 sessions:get 响应,避免本机 metadata 覆盖远程状态', async () => {+ const s = sid();+ let resolveStaleMetadata!: (session: unknown) => void;+ vi.mocked(sessionService.get).mockReturnValueOnce(+ new Promise((resolve) => {+ resolveStaleMetadata = resolve;+ }) as never,+ );++ // 首拉先按本机来源完成,metadata 请求故意留在途。+ makerChatStore.ensureInitialMessages(s);+ await flush();+ expect(makerChatStore.getSnapshot(s).historyLoaded).toBe(true);++ // 来源解析后触发新一轮远程首拉,旧 metadata Promise 必须失效。+ remoteHistory = [dbMessage(s, 'r1', 'remote')];+ seedRemote(s);+ makerChatStore.reconcileOpenSessionOrigins();+ await flush();++ resolveStaleMetadata({+ agentKind: 'codex',+ remoteHostId: null,+ sdkSessionId: 'stale-local-session',+ fastMode: false,+ contextTokens: 0,+ contextWindow: 0,+ totalCostUsd: 0,+ });+ await flush();++ expect(makerChatStore.getSnapshot(s).agentKind).toBe('claude-code');+ expect(makerChatStore.getSnapshot(s).sdkSessionId).toBeNull();+ });+it('purge 后丢弃此前发起的旧投影查询', async () => {const s = sid();let resolveLocalProjection!: (projection: unknown) => void;diff --git a/apps/desktop/src/renderer/__tests__/remoteMirrorCache.test.ts b/apps/desktop/src/renderer/__tests__/remoteMirrorCache.test.tsindex 5bfdc51b6c..0600166c9a 100644--- a/apps/desktop/src/renderer/__tests__/remoteMirrorCache.test.ts+++ b/apps/desktop/src/renderer/__tests__/remoteMirrorCache.test.ts@@ -727,6 +727,39 @@ describe('在途最新页遇上权威作废', () => {});});+describe('首拉在途遇上消息代际失效', () => {+ it('messages:deleted 作废首拉后自动重拉当前代,不让 historyLoaded 永久卡 false', async () => {+ const s = sid();+ registerRemote(s);+ let resolveInitial: (rows: Message[]) => void = () => {};+ remoteListPromise = new Promise<Message[]>((resolve) => {+ resolveInitial = resolve;+ });++ makerChatStore.ensureInitialMessages(s);+ await flush();+ expect(+ invoke.mock.calls.filter(([, channel]) => channel === 'local-db:messages:list'),+ ).toHaveLength(1);++ // messages:deleted 与其它 renderer 删除入口共用 removeMessagesByClientIds,+ // 即使当前窗口没有这条消息也会 bump epoch 作废在途首拉。+ makerChatStore.removeMessagesByClientIds(s, ['client-deleted']);+ remoteListPromise = Promise.resolve([+ dbMessage(s, 'fresh', '当前代的消息', '2026-01-02T00:00:00.000Z'),+ ]);+ resolveInitial([dbMessage(s, 'stale', '上一代的迟到消息', '2026-01-01T00:00:00.000Z')]);+ await flush(40);++ expect(+ invoke.mock.calls.filter(([, channel]) => channel === 'local-db:messages:list'),+ ).toHaveLength(2);+ const snapshot = makerChatStore.getSnapshot(s);+ expect(snapshot.historyLoaded).toBe(true);+ expect(snapshot.messages.map((message) => message.clientId)).toEqual(['client-fresh']);+ });+});+describe('作废式重载 → 缓存一起清', () => {// review(codex P1):粘滞抑制标记只活在本进程里。rewind 后权威首拉失败、用户直接退出 app,// 重启后标记没了而盘上那份还是 rewind 之前的窗口 —— 照样 hydrate 出已被软删的消息。diff --git a/apps/desktop/src/renderer/components/settings/MyDevicesPanel.tsx b/apps/desktop/src/renderer/components/settings/MyDevicesPanel.tsxindex 1be2278821..0c0888a895 100644--- a/apps/desktop/src/renderer/components/settings/MyDevicesPanel.tsx+++ b/apps/desktop/src/renderer/components/settings/MyDevicesPanel.tsx@@ -22,7 +22,12 @@ import { Switch } from '@/components/ui/switch';import type { DeviceLinkSettings } from '@/hooks/useDeviceLinkSettings';import { revokedDevicesStore } from '@/features/device-link/revokedDevicesStore';import { compareDevicesByName } from '@/features/device-link/deviceSort';-import { canBeControlledPlatform, controlToggleState, inboundToggleState } from './myDevicesModel';+import {+ canBeControlledPlatform,+ controlToggleState,+ inboundToggleState,+ resolveActiveConnectionIssue,+} from './myDevicesModel';function platformLabel(platform: string | null): string {switch (platform) {@@ -147,13 +152,13 @@ export function MyDevicesPanel({const revokedControllers = new Set(s.revokedControllers);const controlling = new Set(s.controlledBy.map((c) => c.deviceId));- // 连接问题(鉴权失效/被顶号/超限/版本不符)时不再显示笼统的 connecting 黄点,- // 直接给断开色 + 下方原因行,让「一直连不上」可解释、可行动。- const activeConnectionIssue = s.linkStatus !== 'online' ? s.connectionIssue : null;- const linkStatusColor =- s.linkStatus === 'online'+ // 连接问题(鉴权失效/被顶号/超限/版本不符/反复掉线)时不再显示笼统的 connecting 黄点。+ const activeConnectionIssue = resolveActiveConnectionIssue(s.linkStatus, s.connectionIssue);+ const linkStatusColor = activeConnectionIssue+ ? 'var(--remote-status-disconnected)'+ : s.linkStatus === 'online'? 'var(--remote-status-ready)'- : s.linkStatus === 'connecting' && !activeConnectionIssue+ : s.linkStatus === 'connecting'? 'var(--remote-status-progress)': 'var(--remote-status-disconnected)';@@ -266,6 +271,11 @@ export function MyDevicesPanel({{t(`settings.devices.connectionIssue.${activeConnectionIssue.kind}`)}</span>) : null}+ {s.standby ? (+ <span className="text-11 text-[var(--text-tertiary)]">+ {t('settings.devices.standbyHint')}+ </span>+ ) : null}</div>{self && editingId !== self.deviceId ? (<buttondiff --git a/apps/desktop/src/renderer/components/settings/myDevicesModel.ts b/apps/desktop/src/renderer/components/settings/myDevicesModel.tsindex 0fda736ef9..9791163f01 100644--- a/apps/desktop/src/renderer/components/settings/myDevicesModel.ts+++ b/apps/desktop/src/renderer/components/settings/myDevicesModel.ts@@ -46,3 +46,13 @@ export function inboundToggleState(): { checked: boolean; disabled: boolean } {return { checked: !isRevokedController, disabled: !masterEnabled };}++/** 连接问题原因行的显示规则。unstable 描述跨连接抖动,即使当前短暂 online 也保留。 */+export function resolveActiveConnectionIssue<T extends { kind: string }>(+ linkStatus: 'stopped' | 'connecting' | 'online',+ issue: T | null,+): T | null {+ if (!issue) return null;+ if (issue.kind === 'unstable') return issue;+ return linkStatus === 'online' ? null : issue;+}diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsxindex e62ccc5284..e19b0dad8b 100644--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx@@ -3232,7 +3232,7 @@ export function CCAgentSessionView({{/* device-link 远程会话状态 banner:断链重连 / 被控离线 / 通路不稳定(degraded,弱网熔断)时提示 + 重新同步(以被控端为准重拉对账)。suspect-stall(链路在线但本轮久未更新且核实不到被控端)优先 —— 它可能在 connected 时触发,额外给「结束本轮」手动收尾。- connected / local 且无 stall 时不渲染。 */}+ unstable 描述跨连接抖动,即使此刻 online 也要展示。connected / local 且无 stall 时不渲染。 */}{remoteSync.suspectStall ? (<RemoteSessionBannerstatus="suspect-stall"@@ -3241,9 +3241,18 @@ export function CCAgentSessionView({/>) : remoteConn === 'reconnecting' ||remoteConn === 'host-offline' ||- remoteConn === 'degraded' ? (+ remoteConn === 'degraded' ||+ remoteLinkIssue?.kind === 'unstable' ? (<RemoteSessionBanner- status={remoteConn}+ status={+ remoteLinkIssue?.kind === 'unstable'+ ? 'reconnecting'+ : remoteConn === 'host-offline'+ ? 'host-offline'+ : remoteConn === 'degraded'+ ? 'degraded'+ : 'reconnecting'+ }issue={remoteLinkIssue}onResync={remoteSync.resync}/>diff --git a/apps/desktop/src/renderer/hooks/__tests__/useDeviceLinkSettings.test.tsx b/apps/desktop/src/renderer/hooks/__tests__/useDeviceLinkSettings.test.tsxnew file mode 100644index 0000000000..8ead399d63--- /dev/null+++ b/apps/desktop/src/renderer/hooks/__tests__/useDeviceLinkSettings.test.tsx@@ -0,0 +1,86 @@+// @vitest-environment jsdom++import { act, renderHook } from '@testing-library/react';+import { afterEach, describe, expect, it, vi } from 'vitest';++import { useDeviceLinkSettings } from '../useDeviceLinkSettings';++const translate = vi.hoisted(() => (key: string) => key);++vi.mock('react-i18next', () => ({+ useTranslation: () => ({ t: translate }),+}));++vi.mock('@/lib/logger', () => ({+ createLogger: () => ({+ error: vi.fn(),+ warn: vi.fn(),+ info: vi.fn(),+ debug: vi.fn(),+ }),+}));++function deferred<T>() {+ let resolve!: (value: T) => void;+ const promise = new Promise<T>((next) => {+ resolve = next;+ });+ return { promise, resolve };+}++afterEach(() => {+ delete (window as unknown as { electronAPI?: unknown }).electronAPI;+ vi.clearAllMocks();+});++describe('useDeviceLinkSettings ownership state', () => {+ it('keeps a newer ownership push when the initial getState snapshot resolves late', async () => {+ type State = Awaited<ReturnType<typeof window.electronAPI.deviceLink.getState>>;+ const state = deferred<State>();+ let ownershipChanged: ((payload: { standby: boolean }) => void) | undefined;+ const off = vi.fn();+ const subscribe = vi.fn(() => off);+ const api = {+ getState: vi.fn(() => state.promise),+ listDevices: vi.fn(async () => ({ devices: [] })),+ onOwnershipChanged: vi.fn((callback: (payload: { standby: boolean }) => void) => {+ ownershipChanged = callback;+ return off;+ }),+ onPresenceChanged: subscribe,+ onStatusChanged: subscribe,+ onConnectionIssue: subscribe,+ onControlledState: subscribe,+ onControlTargetChanged: subscribe,+ };+ (window as unknown as { electronAPI: { deviceLink: typeof api } }).electronAPI = {+ deviceLink: api,+ };++ const { result, unmount } = renderHook(() => useDeviceLinkSettings());++ expect(api.onOwnershipChanged.mock.invocationCallOrder[0]).toBeLessThan(+ api.getState.mock.invocationCallOrder[0],+ );+ act(() => ownershipChanged?.({ standby: true }));+ expect(result.current.standby).toBe(true);++ await act(async () => {+ state.resolve({+ remoteControlEnabled: true,+ keepAwake: false,+ linkStatus: 'online',+ connectionIssue: null,+ standby: false,+ controlledBy: [],+ revokedControllers: [],+ disabledControlDeviceIds: [],+ unresponsiveDeviceIds: [],+ });+ await state.promise;+ });++ expect(result.current.standby).toBe(true);+ unmount();+ });+});diff --git a/apps/desktop/src/renderer/hooks/useDeviceLinkSettings.ts b/apps/desktop/src/renderer/hooks/useDeviceLinkSettings.tsindex ec721e6274..3f8bbff680 100644--- a/apps/desktop/src/renderer/hooks/useDeviceLinkSettings.ts+++ b/apps/desktop/src/renderer/hooks/useDeviceLinkSettings.ts@@ -34,8 +34,10 @@ export interface DeviceLinkSettings {enabled: boolean;/** 本机 relay 连接状态。 */linkStatus: DeviceLinkLinkStatus;- /** 本机 relay 连接问题(鉴权失效/被顶号/超限/版本不符;null = 无异常)。 */+ /** 本机 relay 连接问题(鉴权失效/被顶号/超限/版本不符/反复掉线;null = 无异常)。 */connectionIssue: DeviceLinkConnectionIssuePayload | null;+ /** 本机另一个 Cindy 实例正持有 device-link 连接,本实例处于待命。 */+ standby: boolean;/** 同账号设备列表(含本机 isSelf);null = 尚未加载。 */devices: DeviceLinkDeviceView[] | null;/** 当前正在控制本机的控制端。 */@@ -68,6 +70,7 @@ export function useDeviceLinkSettings(active = true): DeviceLinkSettings {const [enabled, setEnabledState] = useState(false);const [linkStatus, setLinkStatus] = useState<DeviceLinkLinkStatus>('stopped');const [connectionIssue, setConnectionIssue] = useState<DeviceLinkConnectionIssuePayload | null>(null);+ const [standby, setStandby] = useState(false);const [devices, setDevices] = useState<DeviceLinkDeviceView[] | null>(null);const [controlledBy, setControlledBy] = useState<ActiveController[]>([]);const [revokedControllers, setRevokedControllers] = useState<string[]>([]);@@ -76,6 +79,8 @@ export function useDeviceLinkSettings(active = true): DeviceLinkSettings {const [refreshing, setRefreshing] = useState(false);const mounted = useRef(true);const disabledControlDeviceIdsRef = useRef<string[]>([]);+ // getState() 与 ownership push 可能乱序返回;事件版本推进后,旧快照不得覆盖新事实。+ const ownershipEventVersion = useRef(0);const applyDisabledControlDeviceIds = useCallback((ids: string[]) => {disabledControlDeviceIdsRef.current = ids;@@ -122,6 +127,11 @@ export function useDeviceLinkSettings(active = true): DeviceLinkSettings {mounted.current = false;};}+ const offOwnership = window.electronAPI.deviceLink.onOwnershipChanged((p) => {+ ownershipEventVersion.current += 1;+ setStandby(p.standby === true);+ });+ const ownershipVersionAtGetState = ownershipEventVersion.current;void window.electronAPI.deviceLink.getState().then((s) => {@@ -129,6 +139,9 @@ export function useDeviceLinkSettings(active = true): DeviceLinkSettings {setEnabledState(s.remoteControlEnabled);setLinkStatus(s.linkStatus);setConnectionIssue(s.connectionIssue ?? null);+ if (ownershipEventVersion.current === ownershipVersionAtGetState) {+ setStandby(s.standby === true);+ }setControlledBy(s.controlledBy ?? []);setRevokedControllers(s.revokedControllers ?? []);applyDisabledControlDeviceIds(s.disabledControlDeviceIds ?? []);@@ -158,6 +171,7 @@ export function useDeviceLinkSettings(active = true): DeviceLinkSettings {offPresence();offStatus();offIssue();+ offOwnership();offControlled();offControlTarget();clearInterval(timer);@@ -300,6 +314,7 @@ export function useDeviceLinkSettings(active = true): DeviceLinkSettings {enabled,linkStatus,connectionIssue,+ standby,devices,controlledBy,revokedControllers,diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex ffb10a75d0..feb0953e60 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -2940,7 +2940,8 @@"auth-failed": "Sign-in expired — please sign in again","replaced": "Connection replaced by another instance of this device","too-many-connections": "Connection limit reached for this account",- "version-mismatch": "Protocol version mismatch — please update the app"+ "version-mismatch": "Protocol version mismatch — please update the app",+ "unstable": "Connection keeps dropping and reconnecting — check the network, or restart Cindy if it persists"},"refresh": "Refresh","empty": "No other devices yet. Sign in to {{appName}} with the same account on another computer and it will show up here.",@@ -2981,7 +2982,8 @@"disconnectFailed": "Failed to disconnect remote connection","remoteSessionEnded": "The remote device ended this session"},- "control": "Control"+ "control": "Control",+ "standbyHint": "Another Cindy instance on this computer is using the remote connection. Close it and this instance takes over automatically."},"imBot": {"beta": "Beta",@@ -6189,7 +6191,8 @@"auth-failed": "Sign-in has expired — sign in again to restore the remote connection","replaced": "This connection was replaced by another instance of the same device — reconnecting…","too-many-connections": "Too many devices online for this account — the server refused the connection",- "version-mismatch": "Protocol version doesn't match the server — update the app and retry"+ "version-mismatch": "Protocol version doesn't match the server — update the app and retry",+ "unstable": "This computer keeps losing and re-establishing its connection, so remote actions may keep timing out — check the network, or restart Cindy and retry"}},"common": {diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 330d59cd68..244a521421 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -2939,7 +2939,8 @@"auth-failed": "ログインが無効になりました。再ログインしてください","replaced": "同じデバイスの別の接続に置き換えられました","too-many-connections": "このアカウントの同時接続数が上限に達しました",- "version-mismatch": "プロトコルバージョンが一致しません。アプリを更新してください"+ "version-mismatch": "プロトコルバージョンが一致しません。アプリを更新してください",+ "unstable": "接続が切断と再接続を繰り返しています。ネットワークを確認し、続く場合は Cindy を再起動してください"},"refresh": "更新","empty": "他のデバイスはまだありません。別のパソコンで同じアカウントで {{appName}} にログインすると、ここに表示されます。",@@ -2980,7 +2981,8 @@"disconnectFailed": "リモート接続の切断に失敗しました","remoteSessionEnded": "リモートデバイスがこのセッションを終了しました"},- "control": "操作"+ "control": "操作",+ "standbyHint": "このパソコンの別の Cindy インスタンスがリモート接続を使用しています。それを閉じると、このインスタンスが自動的に引き継ぎます。"},"imBot": {"beta": "Beta",@@ -6178,7 +6180,8 @@"auth-failed": "ログインの有効期限が切れました。再ログインするとリモート接続が復旧します","replaced": "同じデバイスの別の接続に置き換えられました。再接続しています…","too-many-connections": "このアカウントの同時オンライン台数が多すぎるため、サーバーに接続を拒否されました",- "version-mismatch": "サーバーとプロトコルバージョンが一致しません。アプリを更新してから再試行してください"+ "version-mismatch": "サーバーとプロトコルバージョンが一致しません。アプリを更新してから再試行してください",+ "unstable": "このパソコンの接続が切断と再接続を繰り返しているため、リモート操作がタイムアウトし続ける可能性があります。ネットワークを確認するか、Cindy を再起動して再試行してください"}},"common": {diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 48b14ecb52..dce27608f5 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -2939,7 +2939,8 @@"auth-failed": "로그인이 만료되었습니다. 다시 로그인해 주세요","replaced": "동일한 기기의 다른 연결로 대체되었습니다","too-many-connections": "이 계정의 동시 연결 수가 상한에 도달했습니다",- "version-mismatch": "프로토콜 버전이 일치하지 않습니다. 앱을 업데이트해 주세요"+ "version-mismatch": "프로토콜 버전이 일치하지 않습니다. 앱을 업데이트해 주세요",+ "unstable": "연결이 끊김과 재연결을 반복하고 있습니다. 네트워크를 확인하고, 계속되면 Cindy를 다시 시작해 주세요"},"refresh": "새로고침","empty": "아직 다른 기기가 없습니다. 다른 컴퓨터에서 같은 계정으로 {{appName}}에 로그인하면 여기에 표시됩니다.",@@ -2980,7 +2981,8 @@"disconnectFailed": "원격 연결 끊기에 실패했습니다","remoteSessionEnded": "원격 기기가 이 세션을 종료했습니다"},- "control": "제어"+ "control": "제어",+ "standbyHint": "이 컴퓨터의 다른 Cindy 인스턴스가 원격 연결을 사용하고 있습니다. 그것을 닫으면 이 인스턴스가 자동으로 이어받습니다."},"imBot": {"beta": "Beta",@@ -6178,7 +6180,8 @@"auth-failed": "로그인이 만료되었습니다. 다시 로그인하면 원격 연결이 복구됩니다","replaced": "동일한 기기의 다른 연결로 대체되었습니다. 다시 연결하는 중…","too-many-connections": "이 계정의 동시 접속 기기가 너무 많아 서버가 연결을 거부했습니다",- "version-mismatch": "서버와 프로토콜 버전이 일치하지 않습니다. 앱을 업데이트한 뒤 다시 시도해 주세요"+ "version-mismatch": "서버와 프로토콜 버전이 일치하지 않습니다. 앱을 업데이트한 뒤 다시 시도해 주세요",+ "unstable": "이 컴퓨터의 연결이 끊김과 재연결을 반복하고 있어 원격 작업이 계속 시간 초과될 수 있습니다. 네트워크를 확인하거나 Cindy를 다시 시작한 뒤 다시 시도해 주세요"}},"common": {diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex d5935944cd..93655a46e8 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -2939,7 +2939,8 @@"auth-failed": "登录已失效,请重新登录","replaced": "连接被另一处相同设备顶替","too-many-connections": "同账号连接数已达上限",- "version-mismatch": "协议版本不一致,请升级应用"+ "version-mismatch": "协议版本不一致,请升级应用",+ "unstable": "连接反复断开又重连,请检查网络;若持续如此,重启 Cindy"},"refresh": "刷新","empty": "暂无其它设备。在另一台电脑上用同一账号登录 {{appName}} 后,这里会显示该设备。",@@ -2980,7 +2981,8 @@"disconnectFailed": "断开远程连接失败","remoteSessionEnded": "被控设备已结束该远程任务"},- "control": "控制"+ "control": "控制",+ "standbyHint": "本机另一 Cindy 实例正在使用远程连接。关闭它后,本实例会自动接管。"},"imBot": {"beta": "Beta",@@ -6178,7 +6180,8 @@"auth-failed": "登录已失效,重新登录后才能恢复远程连接","replaced": "本机连接被另一处相同设备顶替,正在重新连接…","too-many-connections": "同账号在线设备过多,连接被服务端拒绝",- "version-mismatch": "与服务端协议版本不一致,请升级应用后重试"+ "version-mismatch": "与服务端协议版本不一致,请升级应用后重试",+ "unstable": "本机连接反复断开又重连,远程操作可能一直超时;请检查网络,或重启 Cindy 后重试"}},"common": {diff --git a/apps/desktop/src/renderer/index.tsx b/apps/desktop/src/renderer/index.tsxindex d55619d2f0..ca83043e96 100644--- a/apps/desktop/src/renderer/index.tsx+++ b/apps/desktop/src/renderer/index.tsx@@ -14,7 +14,6 @@ import '@google/model-viewer';import '@/i18n';import './themes/colors';-import { App } from './App';import { TopLevelErrorBoundary } from './components/error/TopLevelErrorBoundary';import { initTapdb } from './analytics/tapdbClient';import { installScrollbarAutoHide } from './lib/scrollbarAutoHide';@@ -213,6 +212,9 @@ void (async () => {// 顶层 boundary:App 内 RouterProvider 之上的 provider 链渲染崩溃时兜底// (路由子树的崩溃仍由 router.tsx 的 errorElement 就近接住)。+ // App 必须延迟到辅助窗口分流之后再加载:完整 App 的 useApiKey 等模块会在+ // ghost/secondary renderer 启动时触发 safe-storage-read,被 main 正确拒绝并制造噪声。+ const { App } = await import('./App');root.render(<TopLevelErrorBoundary><App />diff --git a/apps/desktop/src/renderer/lib/makerChatStore.ts b/apps/desktop/src/renderer/lib/makerChatStore.tsindex aed13f3aab..16aa936e5d 100644--- a/apps/desktop/src/renderer/lib/makerChatStore.ts+++ b/apps/desktop/src/renderer/lib/makerChatStore.ts@@ -105,6 +105,7 @@ import {emitPatch,} from '@/lib/sessionsBus';import { createLogger } from '@/lib/logger';+import { extractIpcError } from '@/utils/ipcError';import { tryBeginAgentSendDispatch } from '@/lib/agentSwitchCoordinator';import { getUserPrompt } from '@/lib/userPromptStore';import { getMakerMemoryEnabled } from '@/lib/memorySettingsStore';@@ -1423,6 +1424,9 @@ function _purgeSession(sessionId: string): void {lightSnapshotCache.delete(sessionId);titleUpdateCallbacks.delete(sessionId);_historyFetchInFlight.delete(sessionId);+ // 会话已被永久移出缓存:在途请求由 sessions.has(sessionId) 守卫作废,token 条目无需+ // 留作墓碑;新建同 id 会用全局递增 token,不会重新放行旧响应。+ _historyFetchToken.delete(sessionId);_historyLoadOrigin.delete(sessionId);// 冷缓存 hydrate 的两个守卫随会话一起收掉(会话都没了,守卫留着只是无用条目)。_cacheHydrateStarted.delete(sessionId);@@ -5526,6 +5530,13 @@ function reconcilePendingInteractions(sessionId: string): Promise<number> {*/// Guard set to prevent concurrent fetches (historyLoaded stays false until data arrives)const _historyFetchInFlight = new Set<string>();+/** 首拉请求 token:origin 变化 / reload / purge 时作废旧 Promise,防本机竞态响应回写远程会话。 */+const _historyFetchToken = new Map<string, number>();+let _nextHistoryFetchToken = 0;++function invalidateHistoryFetch(sessionId: string): void {+ _historyFetchToken.set(sessionId, ++_nextHistoryFetchToken);+}/*** device-link:记录每个 session 的历史「按哪个 origin(deviceId)加载」。@@ -5725,6 +5736,52 @@ function bumpMessagesEpoch(sessionId: string): void {_messagesEpoch.set(sessionId, (_messagesEpoch.get(sessionId) ?? 0) + 1);}+function isCurrentHistoryFetch(+ sessionId: string,+ token: number,+ origin: string | undefined,+ epoch: number,+): boolean {+ return (+ sessions.has(sessionId) &&+ _historyFetchToken.get(sessionId) === token &&+ (_messagesEpoch.get(sessionId) ?? 0) === epoch &&+ remoteProjectsStore.getSessionDeviceId(sessionId) === origin+ );+}++/** 只释放仍属于这次请求的首拉占用,不误伤 reload 后已经接管的新请求。 */+function releaseHistoryFetchIfCurrent(sessionId: string, token: number): void {+ if (_historyFetchToken.get(sessionId) === token) {+ _historyFetchInFlight.delete(sessionId);+ }+}++/**+ * 释放一条被代际作废的首拉,并在没有新请求接管时补发当前代的首拉。+ *+ * 消息删除 / clear / trim 等路径会 bump `_messagesEpoch` 令在途响应失效,但它们+ * 不一定会主动重载。若这里仅释放 in-flight 占用,会留下 historyLoaded=false 的+ * 会话,而挂载中的视图不会再次触发 ensureInitialMessages。只有这次请求仍持有+ * token、代际确实变化、会话仍存在且没有其它请求接管时才重试,避免与 reload / purge+ * 或新一轮首拉重复发起。+ */+function retryInvalidatedInitialHistoryFetchIfNeeded(+ sessionId: string,+ token: number,+ origin: string | undefined,+ epoch: number,+): void {+ const ownsFetch = _historyFetchToken.get(sessionId) === token;+ const epochChanged = (_messagesEpoch.get(sessionId) ?? 0) !== epoch;+ const originUnchanged = remoteProjectsStore.getSessionDeviceId(sessionId) === origin;+ releaseHistoryFetchIfCurrent(sessionId, token);+ if (!ownsFetch || !epochChanged || !originUnchanged || !sessions.has(sessionId)) return;+ const state = sessions.get(sessionId);+ if (!state || state.historyLoaded || _historyFetchInFlight.has(sessionId)) return;+ ensureInitialMessages(sessionId);+}+/*** DB sessions.agent_kind('cc' / 'codex' / 'pi')→ maker-core AgentKind 的唯一映射点。* 缺失 / 异常值走 fallback(默认 'claude-code',老 row 兼容)。所有从 session@@ -5858,9 +5915,13 @@ function ensureInitialMessages(sessionId: string): void {// Mark in-flight to prevent concurrent callers from double-fetching.// historyLoaded stays false until data actually arrives._historyFetchInFlight.add(sessionId);+ const historyFetchToken = ++_nextHistoryFetchToken;+ _historyFetchToken.set(sessionId, historyFetchToken);+ const historyEpochAtStart = _messagesEpoch.get(sessionId) ?? 0;+ const historyOriginAtStart = remoteProjectsStore.getSessionDeviceId(sessionId);// 记录本次加载所依据的 origin(可能 undefined)。remote-projects 注入该会话来源后,// reconcileOpenSessionOrigins 比对此值发现漂移 → 重载(见上方说明)。- _historyLoadOrigin.set(sessionId, remoteProjectsStore.getSessionDeviceId(sessionId));+ _historyLoadOrigin.set(sessionId, historyOriginAtStart);// 远程会话:与 fresh 首拉**并行**从冷缓存乐观 hydrate,让冷启动 / 被控端离线时// 立刻看到上次看到的最近一页(而不是空白 + spinner)。不设 historyLoaded ——@@ -5871,6 +5932,12 @@ function ensureInitialMessages(sessionId: string): void {// device-link 远程 session 经隧道读被控端 row(本地 DB 没有,直接 get 会 404)。getSessionFor(sessionId).then((session) => {+ if (!isCurrentHistoryFetch(sessionId, historyFetchToken, historyOriginAtStart, historyEpochAtStart)) {+ // The history list owns the shared in-flight guard and will settle the+ // invalidated generation. Do not release it while that request is still+ // pending, otherwise a caller could start a second initial fetch beside it.+ return;+ }setState(sessionId, (s) => {const updates: Partial<SessionChatState> = {};// agentKind 是真实 reducer 路由,始终跟随 DB;乐观切换展示单独放在@@ -5920,11 +5987,41 @@ function ensureInitialMessages(sessionId: string): void {return Object.keys(updates).length > 0 ? { ...s, ...updates } : s;});})- .catch((err) => log.warn('Failed to fetch session for sdkSessionId:', err));+ .catch((err) => {+ if (!isCurrentHistoryFetch(sessionId, historyFetchToken, historyOriginAtStart, historyEpochAtStart)) {+ // See the resolve branch above: let listMessagesFor settle the shared+ // initial-fetch guard and decide whether the current generation retries.+ return;+ }+ const ipcError = extractIpcError(err);+ if (ipcError?.code === 'NOT_FOUND') {+ log.debug('session metadata unavailable during initial routing', ipcError.code);+ } else {+ log.warn('Failed to fetch session for sdkSessionId:', err);+ }+ });listMessagesFor(sessionId).then(async (existing) => {+ if (!isCurrentHistoryFetch(sessionId, historyFetchToken, historyOriginAtStart, historyEpochAtStart)) {+ retryInvalidatedInitialHistoryFetchIfNeeded(+ sessionId,+ historyFetchToken,+ historyOriginAtStart,+ historyEpochAtStart,+ );+ return;+ }if (existing.length === 0) {+ if (!isCurrentHistoryFetch(sessionId, historyFetchToken, historyOriginAtStart, historyEpochAtStart)) {+ retryInvalidatedInitialHistoryFetchIfNeeded(+ sessionId,+ historyFetchToken,+ historyOriginAtStart,+ historyEpochAtStart,+ );+ return;+ }// 权威侧确认这个会话没有可见消息(被控端 /clear、rewind 到头、消息被删干净)。// 冷缓存 hydrate 出来的行必须在这里一并抹掉,否则控制端会一直显示被清掉的正文。// 盘上那份不用在这里单独删:listMessagesFor 的写点收到空页时就把缓存清了。@@ -5963,6 +6060,15 @@ function ensureInitialMessages(sessionId: string): void {let merged: Message[] = existing;let oldestRow = oldestMessageRow(merged, 'newest-first');if (!oldestRow) {+ if (!isCurrentHistoryFetch(sessionId, historyFetchToken, historyOriginAtStart, historyEpochAtStart)) {+ retryInvalidatedInitialHistoryFetchIfNeeded(+ sessionId,+ historyFetchToken,+ historyOriginAtStart,+ historyEpochAtStart,+ );+ return;+ }setState(sessionId, (s) => ({...s,historyLoaded: true,@@ -5998,6 +6104,15 @@ function ensureInitialMessages(sessionId: string): void {limit: 50,before: oldestRow.id,});+ if (!isCurrentHistoryFetch(sessionId, historyFetchToken, historyOriginAtStart, historyEpochAtStart)) {+ retryInvalidatedInitialHistoryFetchIfNeeded(+ sessionId,+ historyFetchToken,+ historyOriginAtStart,+ historyEpochAtStart,+ );+ return;+ }if (older.length === 0) {hasMore = false;break;@@ -6014,6 +6129,15 @@ function ensureInitialMessages(sessionId: string): void {// perf/session-switch 探针纯诊断:整段测量走 import.meta.env.DEV,生产// 构建里 Vite 把常量折成 false 后 dead-code 消除,零开销。const ingestStartMs = import.meta.env.DEV ? performance.now() : 0;+ if (!isCurrentHistoryFetch(sessionId, historyFetchToken, historyOriginAtStart, historyEpochAtStart)) {+ retryInvalidatedInitialHistoryFetchIfNeeded(+ sessionId,+ historyFetchToken,+ historyOriginAtStart,+ historyEpochAtStart,+ );+ return;+ }const mapped = mapServerMessages(merged);const oldestId = oldestRow.id;settleCacheHydration(sessionId);@@ -6070,6 +6194,15 @@ function ensureInitialMessages(sessionId: string): void {reconcilePendingInteractions(sessionId);}).catch(() => {+ if (!isCurrentHistoryFetch(sessionId, historyFetchToken, historyOriginAtStart, historyEpochAtStart)) {+ retryInvalidatedInitialHistoryFetchIfNeeded(+ sessionId,+ historyFetchToken,+ historyOriginAtStart,+ historyEpochAtStart,+ );+ return;+ }// Allow retry on next mount_historyFetchInFlight.delete(sessionId);// 首拉失败(典型:被控端离线)→ 放开「本轮已发起」的守卫以便下次重试,但**不解除**@@ -6091,6 +6224,7 @@ function reloadMessages(sessionId: string, opts?: { allowCacheHydrate?: booleandiscardPendingTextDelta(sessionId);// 代际递增:作废 in-flight 的 loadOlderMessages 追页窗口(见 _messagesEpoch 注释)。bumpMessagesEpoch(sessionId);+ invalidateHistoryFetch(sessionId);// Drop the in-flight guard so ensureInitialMessages can run again._historyFetchInFlight.delete(sessionId);// 默认**不借**冷缓存:rewind 截断这类重载的起因恰恰意味着盘上那份缓存已经过期,diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex 6a6a42274c..8ed949b0ea 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -95,7 +95,7 @@ interface DeviceLinkDeviceView {/** 设备互联:relay 连接问题(镜像 @cindy/device-link 的 DeviceLinkConnectionIssue) */interface DeviceLinkConnectionIssuePayload {- kind: 'auth-failed' | 'replaced' | 'too-many-connections' | 'version-mismatch';+ kind: 'auth-failed' | 'replaced' | 'too-many-connections' | 'version-mismatch' | 'unstable';closeCode?: number;detail?: string;at: number;@@ -3104,6 +3104,7 @@ interface ElectronAPI {keepAwake: boolean;linkStatus: 'stopped' | 'connecting' | 'online';connectionIssue: DeviceLinkConnectionIssuePayload | null;+ standby: boolean;controlledBy: Array<{ deviceId: string; name: string }>;revokedControllers: string[];disabledControlDeviceIds: string[];@@ -3143,6 +3144,8 @@ interface ElectronAPI {onConnectionIssue: (cb: (payload: { issue: DeviceLinkConnectionIssuePayload | null }) => void,) => () => void;+ /** 同机单持有者仲裁角色变化。 */+ onOwnershipChanged: (cb: (payload: { standby: boolean }) => void) => () => void;/** 控制端:被控端转发回来的 renderer 广播事件 */onRemotePush: (cb: (payload: { deviceId: string; channel: string; payload: unknown }) => void,diff --git a/apps/desktop/src/shared/deviceLinkIpc.ts b/apps/desktop/src/shared/deviceLinkIpc.tsindex 2f78b27ddc..5a6d1987bf 100644--- a/apps/desktop/src/shared/deviceLinkIpc.ts+++ b/apps/desktop/src/shared/deviceLinkIpc.ts@@ -94,6 +94,8 @@ export const DEVICE_LINK_PUSH = {* payload: { keepAwake: boolean } —— renderer 据此同步开关显示状态。*/KEEP_AWAKE_CHANGED: 'device-link:keep-awake-changed',+ /** 同机单持有者仲裁角色变化。payload: { standby: boolean }。 */+ OWNERSHIP_CHANGED: 'device-link:ownership-changed',/*** 控制端:某目标设备的「无响应」熔断状态翻转(连续 invoke 超时判定,弱网 / 对端* 卡死;presence 可能仍显示在线)。payload: { deviceId, unresponsive: boolean }。@@ -116,7 +118,9 @@ export type DeviceLinkConnectionIssueKind =| 'auth-failed'| 'replaced'| 'too-many-connections'- | 'version-mismatch';+ | 'version-mismatch'+ /** 连续多次握手成功后仍在稳定期内断开。 */+ | 'unstable';/** 连接问题(同 @cindy/device-link 的 DeviceLinkConnectionIssue) */export interface DeviceLinkConnectionIssue {@@ -145,6 +149,8 @@ export interface DeviceLinkState {linkStatus: DeviceLinkStatus;/** 当前连接问题(null = 无;变化走 CONNECTION_ISSUE push) */connectionIssue: DeviceLinkConnectionIssue | null;+ /** 本机另一个 Cindy 实例持有 device-link,当前实例处于待命。 */+ standby: boolean;/** 当前正在控制本机的控制端(被控端可见性初值;后续变化走 CONTROLLED_STATE push) */controlledBy: ControlledByDevice[];/** 被撤销访问权限的控制端 deviceId 列表(逐设备黑名单,被控端 UI 渲染「已撤销」用) */diff --git a/apps/mobile/app/devices/index.tsx b/apps/mobile/app/devices/index.tsxindex 09b62f0551..0781d11177 100644--- a/apps/mobile/app/devices/index.tsx+++ b/apps/mobile/app/devices/index.tsx@@ -894,9 +894,9 @@ export default function HomeScreen() {setRestoredDeviceName(null);void saveHomeViewPreferences({ selectedDevice: null });}, [home.deviceFilters, home.selectedDeviceId, initialHomeSettled, selectedDeviceId]);- // 连接层失败原因(鉴权失效/被顶号/超限/版本不符)比请求级 error 更根因:非 online 时优先展示。- const activeConnectionIssue = status !== 'online' ? connectionIssue : null;- const showConnectionRow = !!connectionError || status !== 'online';+ // 连接层失败原因比请求级 error 更根因:unstable 在 online 时也需保持可见。+ const activeConnectionIssue = status !== 'online' || connectionIssue?.kind === 'unstable' ? connectionIssue : null;+ const showConnectionRow = !!connectionError || status !== 'online' || connectionIssue?.kind === 'unstable';const connectionTone = activeConnectionIssue? 'off': connectionError ? 'muted' : status === 'online' ? 'ready' : status === 'connecting' ? 'busy' : 'off';diff --git a/apps/mobile/src/__tests__/connectionBannerVisibility.test.ts b/apps/mobile/src/__tests__/connectionBannerVisibility.test.tsindex 64e8e2c2a7..72c39651de 100644--- a/apps/mobile/src/__tests__/connectionBannerVisibility.test.ts+++ b/apps/mobile/src/__tests__/connectionBannerVisibility.test.ts@@ -9,6 +9,7 @@ const base = {offlineLongEnough: false,hasError: false,hasIssue: false,+ hasUnstableIssue: false,deviceUnresponsive: false,};@@ -35,6 +36,10 @@ describe('resolveConnectionBannerVisibility', () => {it('可分类连接问题(鉴权失效 / 被顶号等)在断线时立即显示,不等防闪窗口', () => {expect(resolveConnectionBannerVisibility({ ...base, offline: true, hasIssue: true })).toBe(true);});++ it('unstable 即使 relay 瞬时 online 也保持可见', () => {+ expect(resolveConnectionBannerVisibility({ ...base, hasUnstableIssue: true })).toBe(true);+ });});describe('resolveEffectiveConnectionError', () => {diff --git a/apps/mobile/src/__tests__/homeDesktopFirst.test.ts b/apps/mobile/src/__tests__/homeDesktopFirst.test.tsindex b3b399af88..329f23a0bd 100644--- a/apps/mobile/src/__tests__/homeDesktopFirst.test.ts+++ b/apps/mobile/src/__tests__/homeDesktopFirst.test.ts@@ -251,7 +251,9 @@ describe('mobile home desktop-first surface', () => {expect(source).toContain("updateDeviceConnectionState(device.deviceId, 'syncing');");expect(source).toContain("updateDeviceConnectionState(device.deviceId, 'failed');");expect(source).toContain("updateDeviceConnectionState(device.deviceId, 'idle');");- expect(source).toContain("const showConnectionRow = !!connectionError || status !== 'online';");+ expect(source).toContain(+ "const showConnectionRow = !!connectionError || status !== 'online' || connectionIssue?.kind === 'unstable';",+ );expect(source).toContain("connectionStates={deviceConnectionStates}");expect(source).toContain('function DeviceMenuItem');expect(source).toContain("tone={status === 'online' ? 'ready' : 'off'}");diff --git a/apps/mobile/src/__tests__/remoteStatus.test.ts b/apps/mobile/src/__tests__/remoteStatus.test.tsindex 025020b533..b5bc91293b 100644--- a/apps/mobile/src/__tests__/remoteStatus.test.ts+++ b/apps/mobile/src/__tests__/remoteStatus.test.ts@@ -1,11 +1,14 @@import { describe, expect, it } from 'vitest';import { DeviceLinkError } from '@cindy/device-link';import {+ connectionIssueHint,+ connectionIssueTitle,describeRemoteError,formatRemoteError,relayStatusHint,relayStatusLabel,} from '@/device-link/remoteStatus';+import { i18n } from '@/i18n';describe('remoteStatus', () => {it('labels relay status', () => {@@ -37,4 +40,18 @@ describe('remoteStatus', () => {);expect(formatRemoteError(new Error('[NOT_CONNECTED] offline'))).toBe('[NOT_CONNECTED] offline');});++ it('localizes every connection issue kind', async () => {+ const previousLanguage = i18n.language;+ try {+ await i18n.changeLanguage('en');+ expect(connectionIssueTitle('auth-failed')).toBe('Sign-in expired');+ expect(connectionIssueHint('replaced')).toContain('replaced elsewhere');+ expect(connectionIssueTitle('too-many-connections')).toBe('Too many connections');+ expect(connectionIssueHint('version-mismatch')).toContain('Update to the latest version');+ expect(connectionIssueTitle('unstable')).toBe('Connection keeps dropping');+ } finally {+ await i18n.changeLanguage(previousLanguage);+ }+ });});diff --git a/apps/mobile/src/components/ConnectionBanner.tsx b/apps/mobile/src/components/ConnectionBanner.tsxindex 776bb0850b..39295de193 100644--- a/apps/mobile/src/components/ConnectionBanner.tsx+++ b/apps/mobile/src/components/ConnectionBanner.tsx@@ -53,6 +53,7 @@ export function useShowConnectionBanner(// 否则恢复后 banner 会带着"自动重试中"文案常驻到用户手动同步。hasError: Boolean(resolveEffectiveConnectionError(error, deviceUnresponsive)),hasIssue: issue !== null,+ hasUnstableIssue: issue?.kind === 'unstable',deviceUnresponsive,});}@@ -82,9 +83,9 @@ export function ConnectionBanner({}) {const styles = useThemedStyles(makeStyles);const { t } = useTranslation();- // 链路已 online 说明 issue 已过期(client 侧 online 会清除,这里兜底不展示)。+ // 链路已 online 说明普通 issue 已过期;unstable 描述跨连接抖动,online 时仍展示。// issue 优先于请求级 error:链路断因明确时,invoke 失败都是它的下游症状(NOT_CONNECTED)。- const activeIssue = status !== 'online' ? issue : null;+ const activeIssue = status !== 'online' || issue?.kind === 'unstable' ? issue : null;// 熔断 open 优先于请求级 error:open 期间的请求失败绝大多数就是熔断快速失败本身,// 状态级提示(未响应 + 自动重试中)比单次请求的错误原文更能解释现状。const showUnresponsive = !activeIssue && deviceUnresponsive;@@ -99,12 +100,16 @@ export function ConnectionBanner({: friendlyError ? 'muted' : status === 'online' ? 'ready' : status === 'connecting' ? 'busy' : 'off';const compact = density === 'compact';const title = activeIssue- ? connectionIssueTitle(activeIssue.kind)+ ? activeIssue.kind === 'unstable'+ ? t('deviceLink.unstableTitle')+ : connectionIssueTitle(activeIssue.kind): showUnresponsive? t('deviceLink.deviceUnresponsiveTitle'): friendlyError ? t('deviceLink.syncFailed') : relayStatusLabel(status);const copy = activeIssue- ? connectionIssueHint(activeIssue.kind)+ ? activeIssue.kind === 'unstable'+ ? t('deviceLink.unstableHint')+ : connectionIssueHint(activeIssue.kind): showUnresponsive? t('deviceLink.deviceUnresponsiveHint'): friendlyError ?? relayStatusHint(status, lastSyncedAt);diff --git a/apps/mobile/src/components/connectionBannerVisibility.ts b/apps/mobile/src/components/connectionBannerVisibility.tsindex 99ea33a7c8..891557ca53 100644--- a/apps/mobile/src/components/connectionBannerVisibility.ts+++ b/apps/mobile/src/components/connectionBannerVisibility.ts@@ -13,10 +13,12 @@ export function resolveConnectionBannerVisibility(input: {offlineLongEnough: boolean;hasError: boolean;hasIssue: boolean;+ hasUnstableIssue: boolean;deviceUnresponsive: boolean;}): boolean {return input.hasError|| input.deviceUnresponsive+ || input.hasUnstableIssue|| (input.offline && (input.hasIssue || input.offlineLongEnough));}diff --git a/apps/mobile/src/device-link/remoteStatus.ts b/apps/mobile/src/device-link/remoteStatus.tsindex 3b1bfe178d..a9c92628b2 100644--- a/apps/mobile/src/device-link/remoteStatus.ts+++ b/apps/mobile/src/device-link/remoteStatus.ts@@ -3,11 +3,10 @@ import {humanizeRemoteError as humanizeRemoteErrorShared,isDeviceUnresponsiveRemoteError,} from '@cindy/maker-shared/device-link-contract';+import type { DeviceLinkConnectionIssueKind } from '@cindy/device-link';import { i18n } from '@/i18n';export {- connectionIssueHint,- connectionIssueTitle,describeAgentAuthError,formatRemoteError,isPreconditionFailedRemoteError,@@ -15,6 +14,32 @@ export {relayStatusLabel,} from '@cindy/maker-shared/device-link-contract';+const CONNECTION_ISSUE_COPY_KEYS: Record<+ DeviceLinkConnectionIssueKind,+ { title: string; hint: string }+> = {+ 'auth-failed': { title: 'deviceLink.authFailedTitle', hint: 'deviceLink.authFailedHint' },+ replaced: { title: 'deviceLink.replacedTitle', hint: 'deviceLink.replacedHint' },+ 'too-many-connections': {+ title: 'deviceLink.tooManyConnectionsTitle',+ hint: 'deviceLink.tooManyConnectionsHint',+ },+ 'version-mismatch': {+ title: 'deviceLink.versionMismatchTitle',+ hint: 'deviceLink.versionMismatchHint',+ },+ unstable: { title: 'deviceLink.unstableTitle', hint: 'deviceLink.unstableHint' },+};++/** Mobile 连接问题标题/提示统一走 i18n,避免同一 banner 混用本地化与中文硬编码。 */+export function connectionIssueTitle(kind: DeviceLinkConnectionIssueKind): string {+ return i18n.t(CONNECTION_ISSUE_COPY_KEYS[kind].title);+}++export function connectionIssueHint(kind: DeviceLinkConnectionIssueKind): string {+ return i18n.t(CONNECTION_ISSUE_COPY_KEYS[kind].hint);+}+/*** mobile 侧的 humanizeRemoteError / describeRemoteError:熔断快速失败* (DEVICE_UNRESPONSIVE)先走四语言 i18n(与 ConnectionBanner 同一组文案),diff --git a/apps/mobile/src/i18n/locales/en/deviceLink.json b/apps/mobile/src/i18n/locales/en/deviceLink.jsonindex 1391a2e899..b7ca856b3a 100644--- a/apps/mobile/src/i18n/locales/en/deviceLink.json+++ b/apps/mobile/src/i18n/locales/en/deviceLink.json@@ -16,5 +16,15 @@"sectionRemoteDisabled": "On Your Computer","sectionAccessRevoked": "Approve Access Again","retryAccess": "Retry Access",- "recheck": "Check Again"+ "recheck": "Check Again",+ "authFailedTitle": "Sign-in expired",+ "authFailedHint": "Your sign-in has expired. Sign out and sign in again.",+ "replacedTitle": "Connection replaced",+ "replacedHint": "This device connection was replaced elsewhere. Reconnecting now.",+ "tooManyConnectionsTitle": "Too many connections",+ "tooManyConnectionsHint": "Too many devices are online for this account. Disconnect another device and try again.",+ "versionMismatchTitle": "Version mismatch",+ "versionMismatchHint": "This app version is incompatible with the service. Update to the latest version and try again.",+ "unstableTitle": "Connection keeps dropping",+ "unstableHint": "Connection keeps dropping and reconnecting — check the network, or restart the app if it persists."}diff --git a/apps/mobile/src/i18n/locales/ja/deviceLink.json b/apps/mobile/src/i18n/locales/ja/deviceLink.jsonindex 42b8a06b37..3a4ab65bb4 100644--- a/apps/mobile/src/i18n/locales/ja/deviceLink.json+++ b/apps/mobile/src/i18n/locales/ja/deviceLink.json@@ -16,5 +16,15 @@"sectionRemoteDisabled": "パソコンで操作","sectionAccessRevoked": "再度の許可が必要","retryAccess": "アクセスを再試行",- "recheck": "再確認"+ "recheck": "再確認",+ "authFailedTitle": "ログインの有効期限が切れました",+ "authFailedHint": "ログインの有効期限が切れています。ログアウトして、もう一度ログインしてください。",+ "replacedTitle": "接続が置き換えられました",+ "replacedHint": "このデバイスの接続は別の場所で置き換えられました。再接続しています。",+ "tooManyConnectionsTitle": "接続数の上限に達しました",+ "tooManyConnectionsHint": "このアカウントでオンラインのデバイスが多すぎます。別のデバイスを切断して再試行してください。",+ "versionMismatchTitle": "バージョンが一致しません",+ "versionMismatchHint": "このアプリのバージョンはサービスと互換性がありません。最新版に更新して再試行してください。",+ "unstableTitle": "接続が繰り返し切断されています",+ "unstableHint": "接続が切断と再接続を繰り返しています。ネットワークを確認し、続く場合はアプリを再起動してください。"}diff --git a/apps/mobile/src/i18n/locales/ko/deviceLink.json b/apps/mobile/src/i18n/locales/ko/deviceLink.jsonindex 829a13afe4..1fbb08a88f 100644--- a/apps/mobile/src/i18n/locales/ko/deviceLink.json+++ b/apps/mobile/src/i18n/locales/ko/deviceLink.json@@ -16,5 +16,15 @@"sectionRemoteDisabled": "컴퓨터에서 조작","sectionAccessRevoked": "다시 허용 필요","retryAccess": "액세스 재시도",- "recheck": "다시 확인"+ "recheck": "다시 확인",+ "authFailedTitle": "로그인이 만료되었습니다",+ "authFailedHint": "로그인이 만료되었습니다. 로그아웃한 후 다시 로그인해 주세요.",+ "replacedTitle": "연결이 다른 곳에서 대체되었습니다",+ "replacedHint": "이 기기의 연결이 다른 곳에서 대체되었습니다. 다시 연결하는 중입니다.",+ "tooManyConnectionsTitle": "연결 수 한도에 도달했습니다",+ "tooManyConnectionsHint": "이 계정에 온라인 상태인 기기가 너무 많습니다. 다른 기기의 연결을 끊고 다시 시도해 주세요.",+ "versionMismatchTitle": "버전이 일치하지 않습니다",+ "versionMismatchHint": "이 앱 버전은 서비스와 호환되지 않습니다. 최신 버전으로 업데이트한 후 다시 시도해 주세요.",+ "unstableTitle": "연결이 반복적으로 끊깁니다",+ "unstableHint": "연결이 끊김과 재연결을 반복하고 있습니다. 네트워크를 확인하고, 계속되면 앱을 다시 시작해 주세요."}diff --git a/apps/mobile/src/i18n/locales/zh-CN/deviceLink.json b/apps/mobile/src/i18n/locales/zh-CN/deviceLink.jsonindex cabfc85eb6..8f2c6840eb 100644--- a/apps/mobile/src/i18n/locales/zh-CN/deviceLink.json+++ b/apps/mobile/src/i18n/locales/zh-CN/deviceLink.json@@ -16,5 +16,15 @@"sectionRemoteDisabled": "在电脑上操作","sectionAccessRevoked": "需要重新允许","retryAccess": "重试访问",- "recheck": "重新检查"+ "recheck": "重新检查",+ "authFailedTitle": "登录已失效",+ "authFailedHint": "登录状态已过期,请退出后重新登录。",+ "replacedTitle": "连接被顶替",+ "replacedHint": "本设备的连接被另一处相同设备顶替,正在重新连接。",+ "tooManyConnectionsTitle": "连接数已达上限",+ "tooManyConnectionsHint": "当前账号同时在线的设备过多,请断开其它设备后重试。",+ "versionMismatchTitle": "版本不匹配",+ "versionMismatchHint": "当前 App 版本与服务端协议不一致,请升级到最新版本。",+ "unstableTitle": "连接反复断开",+ "unstableHint": "本机连接反复断开又重连,远程操作可能一直超时。请检查网络;若持续如此,重启 App 后重试。"}diff --git a/packages/device-link/src/__tests__/client.test.ts b/packages/device-link/src/__tests__/client.test.tsindex 43b93dbf48..6009207425 100644--- a/packages/device-link/src/__tests__/client.test.ts+++ b/packages/device-link/src/__tests__/client.test.ts@@ -3465,6 +3465,67 @@ describe('DeviceLinkClient', () => {expect(issues).toHaveLength(2);expect(issues[1]).toBeNull();});++ describe('unstable(反复连上又掉)', () => {+ const flappy = () =>+ makeHarness({ timing: { reconnectStableResetMs: 60, pingIntervalMs: 10_000 } });++ async function flap(h: Harness, first = false): Promise<void> {+ if (first) h.client.start();+ await tick(first ? 0 : 45);+ h.current().ack();+ h.current().emit('close', 1006);+ }++ it('前两次短命不打扰用户,第三次连续才判 unstable', async () => {+ const h = flappy();+ await flap(h, true);+ expect(h.client.getConnectionIssue()).toBeNull();+ await flap(h);+ expect(h.client.getConnectionIssue()).toBeNull();+ await flap(h);+ expect(h.client.getConnectionIssue()).toMatchObject({ kind: 'unstable' });+ h.client.stop();+ });++ it('hello-ack 不会立即清除 unstable,稳定在线满一个周期后才清除', async () => {+ const h = flappy();+ await flap(h, true);+ await flap(h);+ await flap(h);+ expect(h.client.getConnectionIssue()).toMatchObject({ kind: 'unstable' });+ await tick(45);+ h.current().ack();+ expect(h.client.getConnectionIssue()).toMatchObject({ kind: 'unstable' });+ await tick(80);+ expect(h.client.getConnectionIssue()).toBeNull();+ h.current().emit('close', 1006);+ expect(h.client.getConnectionIssue()).toBeNull();+ h.client.stop();+ });++ it('具体的 4409 replaced 优先于 unstable,主动 stop 不计入', async () => {+ const h = flappy();+ h.client.start();+ await tick();+ for (let i = 0; i < 3; i++) {+ if (i > 0) await tick(45);+ h.current().ack();+ h.current().emit('close', 4409, 'replaced by new connection');+ }+ expect(h.client.getConnectionIssue()).toMatchObject({ kind: 'replaced', closeCode: 4409 });+ h.client.stop();++ const stopped = flappy();+ for (let i = 0; i < 3; i++) {+ stopped.client.start();+ await tick();+ stopped.current().ack();+ stopped.client.stop();+ }+ expect(stopped.client.getConnectionIssue()).toBeNull();+ });+ });});describe('客户端主动重建(connect 重入丢弃在用 socket)', () => {@@ -3485,7 +3546,7 @@ describe('DeviceLinkClient', () => {// 静默重建此前没有任何日志痕迹(旧 socket close 被 epoch 守卫屏蔽),这条 INFO// 是排障时区分「客户端主动重建」与「真实断连重连」的唯一锚点。expect(info).toHaveBeenCalledWith(- expect.stringContaining('discarding live socket for reconnect (reason=appstate-active, pending=0)'),+ expect.stringContaining('discarding live socket for reconnect (reason=appstate-active, pending=0'),);h.current().ack();expect(h.client.getStatus()).toBe('online');diff --git a/packages/device-link/src/client.ts b/packages/device-link/src/client.tsindex 2789e9772c..bfe542166b 100644--- a/packages/device-link/src/client.ts+++ b/packages/device-link/src/client.ts@@ -47,6 +47,8 @@ const HANDSHAKE_TIMEOUT_WIDEN_AFTER = 2;/** 「link 未就绪收到可靠帧」通知的 per-peer 节流(见 onReliableFrameBeforeLink)。 */const STALE_LINK_NOTIFY_THROTTLE_MS = 30_000;const SLOW_REQUEST_WARN_MS = 1_000;+/** 连续三次握手成功后仍没撑过稳定期,才把普通抖动升级为可见问题。 */+const SHORT_LIVED_STREAK_LIMIT = 3;const MAX_LEGACY_INBOUND_FRAMES = 128;const MAX_LEGACY_INBOUND_BYTES = 16 * 1024 * 1024;const MAX_PENDING_INBOUND_LINK_OFFERS = 64;@@ -209,7 +211,9 @@ export type DeviceLinkConnectionIssueKind =/** 4429:同账号连接数超限 */| 'too-many-connections'/** 协议版本不一致(server 4400 拒绝 / 客户端 hello-ack 校验) */- | 'version-mismatch';+ | 'version-mismatch'+ /** 连续多次握手成功后又在稳定期内断开。 */+ | 'unstable';export interface DeviceLinkConnectionIssue {kind: DeviceLinkConnectionIssueKind;@@ -368,6 +372,10 @@ export class DeviceLinkClient {private lastSocketErrorMessage: string | null = null;/** 最近一次分类出的连接问题;online 清除,普通断线保留(重连中 banner 不闪) */private connectionIssue: DeviceLinkConnectionIssue | null = null;+ /** 当前连接第一次进入 online 的时刻;用于断开诊断和短命连接判定。 */+ private onlineSinceAt: number | null = null;+ /** 连续「握手成功但没撑过稳定期」次数;稳定在线后清零。 */+ private shortLivedStreak = 0;/** 最近一次 hello-ack 声明的 server 能力集(老 server 无该字段 = 空集) */private serverCapabilities: readonly string[] = [];/** 最近一次 hello-ack 回的本设备 deviceId(深链等场景需要自我标识) */@@ -532,6 +540,13 @@ export class DeviceLinkClient {ws.terminate?.();}}+ this.log.info(+ `device-link stopped by host (onlineForMs=${+ this.onlineSinceAt === null ? 'never-online' : Math.max(0, Date.now() - this.onlineSinceAt)+ })`,+ );+ this.onlineSinceAt = null;+ this.shortLivedStreak = 0;// 主动停止(登出 / 退后台)清掉遗留 issue,避免下次启动前 UI 挂着过期原因this.setConnectionIssue(null);this.setStatus('stopped');@@ -1029,8 +1044,11 @@ export class DeviceLinkClient {// 立刻 fail(带 inFlight 标记),让上层快速重试。这条 INFO 同时是排障锚点:// 此路径此前没有任何日志痕迹,连接翻覆时无法与「真实断连重连」区分。this.log.info(- `discarding live socket for reconnect (reason=${reason}, pending=${this.pending.size})`,+ `discarding live socket for reconnect (reason=${reason}, pending=${this.pending.size}, onlineForMs=${+ this.onlineSinceAt === null ? 'never-online' : Math.max(0, Date.now() - this.onlineSinceAt)+ })`,);+ this.onlineSinceAt = null;try {prev.close(1000, 'reconnecting');} catch {@@ -1113,7 +1131,6 @@ export class DeviceLinkClient {ws.on('close', (code, reason) => {if (epoch !== this.connEpoch) return;const reasonText = closeReasonToString(reason);- this.log.info(`relay connection closed (code=${code}${reasonText ? ` reason=${reasonText}` : ''})`);this.handleDisconnect(code, reasonText);});@@ -1149,6 +1166,15 @@ export class DeviceLinkClient {}private handleDisconnect(code?: number, reason?: string): void {+ const onlineForMs =+ this.onlineSinceAt === null ? null : Math.max(0, Date.now() - this.onlineSinceAt);+ this.log.info(+ `device-link disconnected (code=${code ?? 'n/a'}, reason=${reason || 'n/a'}, onlineForMs=${+ onlineForMs ?? 'never-online'+ })`,+ );+ this.trackShortLivedConnection(onlineForMs, code, reason);+ this.onlineSinceAt = null;this.clearTimers();this.ws = null;this.resetLinkStateForReconnect();@@ -1447,7 +1473,9 @@ export class DeviceLinkClient {this.ws?.close(4400, 'protocol version mismatch');return true; // close 事件经 epoch 校验后走 handleDisconnect → 退避重连}- this.setConnectionIssue(null);+ // unstable 描述的是跨连接的抖动模式,不能在每次短暂握手成功时清掉;+ // 只有稳定在线满一个稳定期才算恢复。+ if (this.connectionIssue?.kind !== 'unstable') this.setConnectionIssue(null);this.serverCapabilities = Array.isArray(ack?.capabilities)? ack.capabilities.filter((c): c is string => typeof c === 'string'): [];@@ -1461,6 +1489,7 @@ export class DeviceLinkClient {this.handshakeTimeoutStreak = 0;const wasOnline = this.status === 'online';this.setStatus('online');+ if (!wasOnline) this.onlineSinceAt = Date.now();this.armReconnectStableReset();this.startHeartbeat();// 重复 hello-ack(已在线还收到 ack)单独判别:这不是新连接,而是 relay 在同一条@@ -2715,11 +2744,45 @@ export class DeviceLinkClient {}}+ /**+ * 普通网络切换不应打扰用户;连续多次「连上就掉」才暴露 unstable。+ * 主动 stop 不经过这里,具体的鉴权/顶号/版本问题会在调用方随后覆盖本分类。+ */+ private trackShortLivedConnection(+ onlineForMs: number | null,+ code?: number,+ reason?: string,+ ): void {+ if (this.stopped || onlineForMs === null) return;+ if (onlineForMs >= this.timing.reconnectStableResetMs) {+ this.shortLivedStreak = 0;+ return;+ }+ this.shortLivedStreak++;+ if (this.shortLivedStreak < SHORT_LIVED_STREAK_LIMIT) return;+ this.log.warn(+ `device-link keeps dropping after handshake (${this.shortLivedStreak} in a row, lastOnlineForMs=${onlineForMs}, code=${+ code ?? 'n/a'+ })`,+ );+ this.setConnectionIssue({+ kind: 'unstable',+ closeCode: code,+ detail: `${this.shortLivedStreak} short-lived connections; last ${onlineForMs}ms${+ reason ? ` (${reason})` : ''+ }`,+ at: Date.now(),+ });+ }+private armReconnectStableReset(): void {if (this.reconnectStableTimer) clearTimeout(this.reconnectStableTimer);this.reconnectStableTimer = setTimeout(() => {this.reconnectStableTimer = null;- if (!this.stopped && this.status === 'online') this.reconnectAttempt = 0;+ if (this.stopped || this.status !== 'online') return;+ this.reconnectAttempt = 0;+ this.shortLivedStreak = 0;+ if (this.connectionIssue?.kind === 'unstable') this.setConnectionIssue(null);}, this.timing.reconnectStableResetMs);}}diff --git a/packages/maker-shared/src/__tests__/deviceLinkContract.test.ts b/packages/maker-shared/src/__tests__/deviceLinkContract.test.tsindex 9dd4f8f3ec..b4e8fb164b 100644--- a/packages/maker-shared/src/__tests__/deviceLinkContract.test.ts+++ b/packages/maker-shared/src/__tests__/deviceLinkContract.test.ts@@ -117,6 +117,8 @@ describe('device-link shared contract', () => {expect(connectionIssueTitle('replaced')).toContain('顶替');expect(connectionIssueHint('too-many-connections')).toContain('断开其它设备');expect(connectionIssueHint('version-mismatch')).toContain('升级到最新版本');+ expect(connectionIssueTitle('unstable')).toContain('反复断开');+ expect(connectionIssueHint('unstable')).toContain('本机');});it('preserves structured remote error codes and access revoked classification', () => {diff --git a/packages/maker-shared/src/deviceLinkContract.ts b/packages/maker-shared/src/deviceLinkContract.tsindex 5b91eeb210..541689d931 100644--- a/packages/maker-shared/src/deviceLinkContract.ts+++ b/packages/maker-shared/src/deviceLinkContract.ts@@ -445,7 +445,8 @@ export type DeviceLinkConnectionIssueKind =| 'auth-failed'| 'replaced'| 'too-many-connections'- | 'version-mismatch';+ | 'version-mismatch'+ | 'unstable';/** 连接问题标题(手机端直出文案;桌面端走 i18n,不用这组)。 */export function connectionIssueTitle(kind: DeviceLinkConnectionIssueKind): string {@@ -458,6 +459,8 @@ export function connectionIssueTitle(kind: DeviceLinkConnectionIssueKind): strinreturn '连接数已达上限';case 'version-mismatch':return '版本不匹配';+ case 'unstable':+ return '连接反复断开';}}@@ -472,6 +475,8 @@ export function connectionIssueHint(kind: DeviceLinkConnectionIssueKind): stringreturn '当前账号同时在线的设备过多,请断开其它设备后重试。';case 'version-mismatch':return '当前 App 版本与服务端协议不一致,请升级到最新版本。';+ case 'unstable':+ return '本机连接反复断开又重连,远程操作可能一直超时。请检查网络;若持续如此,重启 App 后重试。';}}