Skip to content

armgit / cindy

Public Imported from GitHub
0

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

fix(desktop): unblock idle updates for list-only viewers (#663)

cnxpfcv-oss62da746b676c
diff --git a/apps/desktop/src/main/__tests__/deviceLinkDispatch.test.ts b/apps/desktop/src/main/__tests__/deviceLinkDispatch.test.ts
index 37b95eb6cd..e9b4df3df2 100644
--- a/apps/desktop/src/main/__tests__/deviceLinkDispatch.test.ts
+++ b/apps/desktop/src/main/__tests__/deviceLinkDispatch.test.ts
@@ -377,14 +377,16 @@ describe('dispatchLocalInvoke', () => {
import {
wireInboundDispatch,
setControllersChangedListener,
- setSubscribedControllersChangedListener,
+ setRemoteInvokeBusyChangedListener,
setSessionsSubscribedListener,
getActiveControllers,
- getSubscribedControllers,
+ getUpdateRelaunchControllers,
+ hasInFlightRemoteInvokes,
dropAllControllers,
} from '../device-link/dispatch';
import { hasBroadcastTapListener, tapWindowBroadcast } from '../device-link/broadcast-tap';
import { SESSION_ACTIVITY_CHANNEL, type Envelope } from '@cindy/device-link';
+import { DEVICE_LINK_RECONCILIATION_PROBE_MARKER } from '@cindy/maker-shared/device-link-contract';
import { MAKER_PUSH } from '../maker-ipc/channels';
/** 最小 fake client:捕获 onFrame handler,记录出站调用 */
@@ -555,6 +557,157 @@ describe('被控端控制链路生命周期', () => {
expect(getActiveControllers()).toHaveLength(0);
expect(hasBroadcastTapListener()).toBe(false);
});
+
+ it('非订阅 remote invoke 在结果发送前持有更新 busy lease', async () => {
+ remoteControlEnabled = true;
+ let resolveInvoke: ((value: string[]) => void) | undefined;
+ registry.register(
+ 'maker:list-active',
+ () =>
+ new Promise<string[]>((resolve) => {
+ resolveInvoke = resolve;
+ }),
+ );
+ const busyChanges: boolean[] = [];
+ setRemoteInvokeBusyChangedListener((busy) => busyChanges.push(busy));
+ const { client, calls, feed } = makeFakeClient();
+ wireInboundDispatch(client);
+
+ feed({
+ v: 1,
+ kind: 'invoke',
+ id: 'invoke-1',
+ src: 'ctrl-a',
+ payload: { channel: 'maker:list-active', args: [] },
+ });
+
+ expect(hasInFlightRemoteInvokes()).toBe(true);
+ expect(busyChanges).toEqual([true]);
+ resolveInvoke?.(['s1']);
+ await vi.waitFor(() => expect(hasInFlightRemoteInvokes()).toBe(false));
+ expect(busyChanges).toEqual([true, false]);
+ expect(calls.invokeResult).toContainEqual({
+ dst: 'ctrl-a',
+ requestId: 'invoke-1',
+ payload: { ok: true, result: ['s1'] },
+ });
+ });
+
+ it.each([
+ { channel: 'local-db:sessions:list', args: [] },
+ {
+ channel: 'local-db:sessions:get',
+ args: ['s1', DEVICE_LINK_RECONCILIATION_PROBE_MARKER],
+ },
+ ])(
+ '后台 $channel reconciliation 不持有更新 busy lease',
+ async ({ channel, args }) => {
+ remoteControlEnabled = true;
+ registry.register(channel, () => []);
+ const busyChanges: boolean[] = [];
+ setRemoteInvokeBusyChangedListener((busy) => busyChanges.push(busy));
+ const { client, calls, feed } = makeFakeClient();
+ wireInboundDispatch(client);
+
+ feed({
+ v: 1,
+ kind: 'invoke',
+ id: `invoke-${channel}`,
+ src: 'ctrl-a',
+ payload: { channel, args },
+ });
+
+ await vi.waitFor(() =>
+ expect(calls.invokeResult).toContainEqual({
+ dst: 'ctrl-a',
+ requestId: `invoke-${channel}`,
+ payload: { ok: true, result: [] },
+ }),
+ );
+ expect(hasInFlightRemoteInvokes()).toBe(false);
+ expect(busyChanges).toEqual([]);
+ },
+ );
+
+ it('普通 sessions:get 交互读取仍持有更新 busy lease', async () => {
+ remoteControlEnabled = true;
+ let resolveInvoke: ((value: { id: string }) => void) | undefined;
+ registry.register(
+ 'local-db:sessions:get',
+ () =>
+ new Promise<{ id: string }>((resolve) => {
+ resolveInvoke = resolve;
+ }),
+ );
+ const busyChanges: boolean[] = [];
+ setRemoteInvokeBusyChangedListener((busy) => busyChanges.push(busy));
+ const { client, calls, feed } = makeFakeClient();
+ wireInboundDispatch(client);
+
+ feed({
+ v: 1,
+ kind: 'invoke',
+ id: 'invoke-interactive-get',
+ src: 'ctrl-a',
+ payload: { channel: 'local-db:sessions:get', args: ['s1'] },
+ });
+
+ expect(hasInFlightRemoteInvokes()).toBe(true);
+ expect(busyChanges).toEqual([true]);
+ resolveInvoke?.({ id: 's1' });
+ await vi.waitFor(() => expect(hasInFlightRemoteInvokes()).toBe(false));
+ expect(busyChanges).toEqual([true, false]);
+ expect(calls.invokeResult).toContainEqual({
+ dst: 'ctrl-a',
+ requestId: 'invoke-interactive-get',
+ payload: { ok: true, result: { id: 's1' } },
+ });
+ });
+
+ it.each([
+ {
+ name: 'remote control disabled',
+ configure: () => {
+ remoteControlEnabled = false;
+ },
+ payload: { channel: 'maker:list-active', args: [] },
+ },
+ {
+ name: 'revoked controller',
+ configure: () => {
+ revokedControllers = ['ctrl-a'];
+ },
+ payload: { channel: 'maker:list-active', args: [] },
+ },
+ {
+ name: 'non-allowlisted channel',
+ configure: () => undefined,
+ payload: { channel: 'shell:open-path', args: [] },
+ },
+ {
+ name: 'malformed payload',
+ configure: () => undefined,
+ payload: undefined,
+ },
+ ])('被拒绝的 $name 不持有更新 busy lease', async ({ configure, payload }) => {
+ configure();
+ const busyChanges: boolean[] = [];
+ setRemoteInvokeBusyChangedListener((busy) => busyChanges.push(busy));
+ const { client, calls, feed } = makeFakeClient();
+ wireInboundDispatch(client);
+
+ feed({
+ v: 1,
+ kind: 'invoke',
+ id: `invoke-rejected-${calls.invokeResult.length}`,
+ src: 'ctrl-a',
+ payload,
+ });
+
+ await vi.waitFor(() => expect(calls.invokeResult).toHaveLength(1));
+ expect(hasInFlightRemoteInvokes()).toBe(false);
+ expect(busyChanges).toEqual([]);
+ });
});
// ─── 订阅 registry + topic-scoped fan-out + set-* 持久化回流(push 驱动重构)──────
@@ -695,24 +848,140 @@ describe('被控端订阅 registry + topic 转发', () => {
});
});
- it('纯 sessions viewer 也进入无人值守更新的远控 busy 集合并触发变更通知', () => {
+ it('空 subscribe 保留 legacy wildcard,现代有效 subscribe 替换它且重复 open 不恢复', () => {
remoteControlEnabled = true;
- const changes: ActiveController[][] = [];
- setSubscribedControllersChangedListener((controllers) => changes.push(controllers));
+ const { client, calls, feed } = makeFakeClient();
+ wireInboundDispatch(client);
+
+ feed({
+ v: 1,
+ kind: 'link-open',
+ id: 'open-modern',
+ src: 'ctrl-modern',
+ payload: {
+ controllerName: 'Modern',
+ protocolVersion: 1,
+ appVersion: '1.0.0',
+ capabilities: ['provider-logo-kinds-v2'],
+ },
+ });
+ expect(getUpdateRelaunchControllers()).toEqual([
+ { deviceId: 'ctrl-modern', name: 'Modern' },
+ ]);
+
+ feed(subFrame('ctrl-modern', SUB, ['*', 'garbage', 'session:', 'fs-watch:']));
+ expect(getUpdateRelaunchControllers()).toEqual([
+ { deviceId: 'ctrl-modern', name: 'Modern' },
+ ]);
+
+ feed(subFrame('ctrl-modern', SUB, ['sessions'], 'Modern'));
+
+ expect(dispatchTesting.getActiveControllers()).toEqual([]);
+ expect(dispatchTesting.getUpdateRelaunchControllers()).toEqual([]);
+ expect(dispatchTesting.controllerSupports(
+ 'ctrl-modern',
+ 'provider-logo-kinds-v2',
+ )).toBe(true);
+
+ feed({
+ v: 1,
+ kind: 'link-open',
+ id: 'open-modern-again',
+ src: 'ctrl-modern',
+ payload: {
+ controllerName: 'Modern renamed',
+ protocolVersion: 1,
+ appVersion: '1.0.0',
+ capabilities: ['provider-logo-kinds-v2'],
+ },
+ });
+ expect(dispatchTesting.getActiveControllers()).toEqual([]);
+ expect(dispatchTesting.getUpdateRelaunchControllers()).toEqual([]);
+ expect(dispatchTesting.controllerSupports(
+ 'ctrl-modern',
+ 'provider-logo-kinds-v2',
+ )).toBe(true);
+
+ tapWindowBroadcast('local-db:sessions:created', { sessionId: 's1' });
+ tapWindowBroadcast('maker:event', { sessionId: 's1', event: {} });
+ expect(calls.push).toEqual([
+ {
+ dst: 'ctrl-modern',
+ channel: 'local-db:sessions:created',
+ payload: { sessionId: 's1' },
+ },
+ ]);
+
+ feed({
+ v: 1,
+ kind: 'link-close',
+ src: 'ctrl-modern',
+ payload: { reason: 'user' },
+ });
+ feed({
+ v: 1,
+ kind: 'link-open',
+ id: 'open-after-disconnect',
+ src: 'ctrl-modern',
+ payload: {
+ controllerName: 'Modern reconnect',
+ protocolVersion: 1,
+ appVersion: '1.0.0',
+ },
+ });
+ expect(getUpdateRelaunchControllers()).toEqual([
+ { deviceId: 'ctrl-modern', name: 'Modern reconnect' },
+ ]);
+ });
+
+ it('无人值守更新忽略纯 sessions viewer,但保护文件浏览和实际会话控制', () => {
+ remoteControlEnabled = true;
+ const changes: Array<{
+ controlled: ActiveController[];
+ updateBusy: ActiveController[];
+ }> = [];
+ setControllersChangedListener((controlled, updateBusy) =>
+ changes.push({ controlled, updateBusy }),
+ );
const { client, feed } = makeFakeClient();
wireInboundDispatch(client);
feed(subFrame('ctrl-empty', SUB, []));
feed(subFrame('ctrl-invalid', SUB, ['*', 'garbage', 'session:', 'fs-watch:']));
- expect(getSubscribedControllers()).toEqual([]);
+ expect(getActiveControllers()).toEqual([]);
feed(subFrame('ctrl-viewer', SUB, ['sessions'], 'Viewer'));
expect(getActiveControllers()).toEqual([]);
- expect(getSubscribedControllers()).toEqual([
+ expect(getUpdateRelaunchControllers()).toEqual([]);
+ expect(changes.at(-1)).toEqual({ controlled: [], updateBusy: [] });
+
+ feed(subFrame('ctrl-viewer', SUB, ['fs-watch:/repo'], 'Viewer'));
+ expect(getActiveControllers()).toEqual([]);
+ expect(getUpdateRelaunchControllers()).toEqual([
+ { deviceId: 'ctrl-viewer', name: 'Viewer' },
+ ]);
+ expect(changes.at(-1)).toEqual({
+ controlled: [],
+ updateBusy: [{ deviceId: 'ctrl-viewer', name: 'Viewer' }],
+ });
+
+ feed(subFrame('ctrl-viewer', UNSUB, ['fs-watch:/repo']));
+ expect(getActiveControllers()).toEqual([]);
+ expect(getUpdateRelaunchControllers()).toEqual([]);
+ expect(changes.at(-1)).toEqual({ controlled: [], updateBusy: [] });
+
+ feed(subFrame('ctrl-viewer', SUB, ['session:s1'], 'Viewer'));
+ expect(getActiveControllers()).toEqual([
{ deviceId: 'ctrl-viewer', name: 'Viewer' },
]);
- expect(changes.at(-1)).toEqual([{ deviceId: 'ctrl-viewer', name: 'Viewer' }]);
+ expect(getUpdateRelaunchControllers()).toEqual([
+ { deviceId: 'ctrl-viewer', name: 'Viewer' },
+ ]);
+ expect(changes.at(-1)).toEqual({
+ controlled: [{ deviceId: 'ctrl-viewer', name: 'Viewer' }],
+ updateBusy: [{ deviceId: 'ctrl-viewer', name: 'Viewer' }],
+ });
});
it('多控制端:各只收自己订阅 session 的 push', () => {
diff --git a/apps/desktop/src/main/__tests__/deviceLinkSubscriptions.test.ts b/apps/desktop/src/main/__tests__/deviceLinkSubscriptions.test.ts
index 05f6b7715c..a5922eda0f 100644
--- a/apps/desktop/src/main/__tests__/deviceLinkSubscriptions.test.ts
+++ b/apps/desktop/src/main/__tests__/deviceLinkSubscriptions.test.ts
@@ -12,7 +12,6 @@ describe('subscriptions registry', () => {
it('ignores empty subscriptions so they cannot become phantom remote viewers', () => {
subs.subscribe('empty', [], 'Nobody');
expect(subs.getControllerIds()).toEqual([]);
- expect(subs.getSubscribedControllers()).toEqual([]);
});
it('subscribe 累加 topic;getControllersForTopic 命中订阅者', () => {
@@ -30,21 +29,34 @@ describe('subscriptions registry', () => {
expect(subs.getControllersForTopic('session:zzz')).toContain('legacy');
});
- it('横幅控制端 = 持 session:<id> 或 "*";纯 sessions 订阅者不算', () => {
+ it('横幅只认 session / "*";更新 busy 额外保护 fs-watch', () => {
subs.subscribe('observer', ['sessions'], 'Obs');
expect(subs.getControlControllers()).toEqual([]); // 只看列表 → 不亮横幅
- expect(subs.getSubscribedControllers()).toEqual([{ deviceId: 'observer', name: 'Obs' }]);
subs.subscribe('controller', ['session:s1'], 'Ctrl');
expect(subs.getControlControllers()).toEqual([{ deviceId: 'controller', name: 'Ctrl' }]);
+ subs.subscribe('file-browser', ['fs-watch:/repo'], 'Files');
+ expect(subs.getControlControllers()).not.toContainEqual({
+ deviceId: 'file-browser',
+ name: 'Files',
+ });
+ expect(subs.getUpdateRelaunchControllers()).toContainEqual({
+ deviceId: 'file-browser',
+ name: 'Files',
+ });
+
subs.subscribe('legacy', ['*'], 'Old');
- expect(subs.getControlControllers().map((c) => c.deviceId).sort()).toEqual(['controller', 'legacy']);
- expect(subs.getSubscribedControllers().map((c) => c.deviceId).sort()).toEqual([
+ expect(subs.getControlControllers().map((c) => c.deviceId).sort()).toEqual([
+ 'controller',
+ 'legacy',
+ ]);
+ expect(subs.getUpdateRelaunchControllers().map((c) => c.deviceId).sort()).toEqual([
'controller',
+ 'file-browser',
'legacy',
- 'observer',
]);
+ expect(subs.getControllerIds().sort()).toEqual(['controller', 'file-browser', 'legacy', 'observer']);
});
it('unsubscribe 移除指定 topic;清空后整条移除', () => {
diff --git a/apps/desktop/src/main/__tests__/deviceLinkVoiceCredentialBootstrap.test.ts b/apps/desktop/src/main/__tests__/deviceLinkVoiceCredentialBootstrap.test.ts
index 37b40e5a41..4f5e21364b 100644
--- a/apps/desktop/src/main/__tests__/deviceLinkVoiceCredentialBootstrap.test.ts
+++ b/apps/desktop/src/main/__tests__/deviceLinkVoiceCredentialBootstrap.test.ts
@@ -19,17 +19,24 @@ describe('mobile voice credential sync desktop bootstrap path', () => {
const bootstrap = readFileSync(resolve(mainRoot, 'bootstrap-electron.ts'), 'utf8');
expect(bootstrap).toMatch(/import \{[^}]*\binitDeviceLinkService\b[^}]*\} from '\.\/device-link';/);
- expect(bootstrap).toContain('initDeviceLinkService();');
- expect(bootstrap.indexOf('initDeviceLinkService();')).toBeLessThan(
- bootstrap.indexOf('registerDeviceLinkIpc();'),
- );
+ const serviceInit = bootstrap.search(/\binitDeviceLinkService\s*\(\s*\{/);
+ const ipcRegistration = bootstrap.search(/\bregisterDeviceLinkIpc\s*\(\s*\)\s*;/);
+ expect(serviceInit).toBeGreaterThanOrEqual(0);
+ expect(ipcRegistration).toBeGreaterThanOrEqual(0);
+ expect(serviceInit).toBeLessThan(ipcRegistration);
});
it('wires the DeviceLinkClient inbound frames into controlled-desktop dispatch', () => {
const deviceLinkHost = readFileSync(resolve(mainRoot, 'device-link/index.ts'), 'utf8');
expect(deviceLinkHost).toContain('wireInboundDispatch,');
- expect(deviceLinkHost).toContain('wireInboundDispatch(client);');
+ const listenerRegistration = deviceLinkHost.search(
+ /\bsetControllersChangedListener\s*\(\s*\(\s*controllers\s*,\s*updateRelaunchControllers\s*\)\s*=>/,
+ );
+ const inboundWiring = deviceLinkHost.search(/\bwireInboundDispatch\s*\(\s*client\s*\)\s*;/);
+ expect(listenerRegistration).toBeGreaterThanOrEqual(0);
+ expect(inboundWiring).toBeGreaterThanOrEqual(0);
+ expect(listenerRegistration).toBeLessThan(inboundWiring);
});
it('replays desktop subscriptions when a remote device becomes controllable again', () => {
diff --git a/apps/desktop/src/main/__tests__/updateRelaunchSafety.test.ts b/apps/desktop/src/main/__tests__/updateRelaunchSafety.test.ts
index 199ce173ef..b79ec37932 100644
--- a/apps/desktop/src/main/__tests__/updateRelaunchSafety.test.ts
+++ b/apps/desktop/src/main/__tests__/updateRelaunchSafety.test.ts
@@ -3,6 +3,7 @@ import { describe, expect, it, vi } from 'vitest';
import {
MACOS_UPDATE_RELAUNCH_ARG,
createUpdatePresentationRecoveryController,
+ decideUpdateRelaunchBusyTransition,
decideUpdatePresentationRecovery,
hasUpdateRelaunchBusyActivity,
isMacOSUpdateRelaunch,
@@ -78,6 +79,21 @@ describe('update relaunch marker', () => {
});
describe('update relaunch busy probe', () => {
+ it.each([
+ { previousBusy: false, nextBusy: false, shouldNotify: false },
+ { previousBusy: false, nextBusy: true, shouldNotify: true },
+ { previousBusy: true, nextBusy: true, shouldNotify: false },
+ { previousBusy: true, nextBusy: false, shouldNotify: true },
+ ])(
+ 'notifies only on remote busy edges ($previousBusy → $nextBusy)',
+ ({ previousBusy, nextBusy, shouldNotify }) => {
+ expect(decideUpdateRelaunchBusyTransition(previousBusy, nextBusy)).toEqual({
+ nextBusy,
+ shouldNotify,
+ });
+ },
+ );
+
it('treats uninitialized scheduler storage as an idle cold-start state', async () => {
await expect(readUpdateRelaunchScheduleBusy(null)).resolves.toBe(false);
});
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.ts
index 3ab6e34331..b5c7fa88ca 100644
--- a/apps/desktop/src/main/bootstrap-electron.ts
+++ b/apps/desktop/src/main/bootstrap-electron.ts
@@ -144,6 +144,7 @@ import {
} from './updateService';
import {
createUpdatePresentationRecoveryController,
+ decideUpdateRelaunchBusyTransition,
hasUpdateRelaunchBusyActivity,
isMacOSUpdateRelaunch,
readUpdateRelaunchScheduleBusy,
@@ -270,9 +271,9 @@ import { WindowManualDragController } from './windowManualDrag';
// 设备互联(跨设备远程控制): relay 连接 host + 开关/设备列表 IPC
import { initDeviceLinkService, releaseDeviceLinkOwnershipBeforeLogout } from './device-link';
import {
- getSubscribedControllers,
+ getUpdateRelaunchControllers,
+ hasInFlightRemoteInvokes,
setSessionsSubscribedListener,
- setSubscribedControllersChangedListener,
} from './device-link/dispatch';
import {
registerDeviceLinkIpc,
@@ -2392,9 +2393,6 @@ const registerIpcHandlers = () => {
setSessionsSubscribedListener(() => {
getAgentIslandService()?.replaySessionActivity();
});
- setSubscribedControllersChangedListener(() => {
- notifyUpdateAutoRelaunchBusyStateChanged();
- });
// 「在新窗口打开」会话多开 —— 新建一个完整窗口定位到该 session, 初始 bounds 取主窗。
ipcMain.handle(MAKER_IPC_INVOKE.OPEN_SESSION_IN_NEW_WINDOW, (_e, sessionId: unknown) => {
@@ -3544,12 +3542,14 @@ const registerIpcHandlers = () => {
// 由 prepareCodexExtraSpawnConfig 懒启动(幂等);此处不再按全局开关 eager-start。
try {
setUpdateAutoRelaunchBusyProbe(async () => {
- // A remote operator may be reading the UI without an active agent turn.
- // Treat any subscribed view/control session as busy so unattended
- // relaunch cannot cut the only path back into a home-server install.
+ // A remote operator may be viewing a live session or file tree without an agent turn.
+ // Keep those paths alive, but do not let the lightweight `sessions` list subscription
+ // held by every eligible device block updates forever.
return hasUpdateRelaunchBusyActivity({
readSynchronousBusy: () =>
- getSubscribedControllers().length > 0 || anySessionInTurn(getMakerCore()),
+ getUpdateRelaunchControllers().length > 0 ||
+ hasInFlightRemoteInvokes() ||
+ anySessionInTurn(getMakerCore()),
readScheduleBusy: () => readUpdateRelaunchScheduleBusy(getScheduleStorageIfInitialized()),
});
});
@@ -5589,7 +5589,17 @@ app.on('ready', async () => {
// 在线人数心跳:App 启动即上报,内部走 deviceId / userId 兜底,登录前后都活
initHeartbeatService();
// 设备互联(跨设备远程控制):登录后连 relay,登出即断;开关与设备列表 IPC 一并注册
- initDeviceLinkService();
+ let updateRelaunchRemoteBusy = false;
+ initDeviceLinkService({
+ onUpdateRelaunchBusyChanged: (busy) => {
+ const transition = decideUpdateRelaunchBusyTransition(
+ updateRelaunchRemoteBusy,
+ busy,
+ );
+ updateRelaunchRemoteBusy = transition.nextBusy;
+ if (transition.shouldNotify) notifyUpdateAutoRelaunchBusyStateChanged();
+ },
+ });
registerDeviceLinkIpc();
// 注:invoke-capture 自检(assertCaptureHealthy)不在这里——maker:create-session / maker:send
// 由 splash 后的 registerMakerIpcsAfterSplash 延迟注册,此刻尚未注册。自检已挪到该函数末尾
diff --git a/apps/desktop/src/main/device-link/dispatch.ts b/apps/desktop/src/main/device-link/dispatch.ts
index 3a0291dc38..4db7057cf9 100644
--- a/apps/desktop/src/main/device-link/dispatch.ts
+++ b/apps/desktop/src/main/device-link/dispatch.ts
@@ -41,7 +41,10 @@ import {
type LinkOpenPayload,
type Topic,
} from '@cindy/device-link';
-import type { MobileVoiceDictionaryLearningRequest } from '@cindy/maker-shared/device-link-contract';
+import {
+ DEVICE_LINK_RECONCILIATION_PROBE_MARKER,
+ type MobileVoiceDictionaryLearningRequest,
+} from '@cindy/maker-shared/device-link-contract';
import {
resolveProviderLogoKind,
type ProviderLogoKind,
@@ -105,6 +108,11 @@ const REMOTE_TOOL_USE_METADATA_STRING_LIMIT = 1024;
const REMOTE_INVOKE_TRUNCATION_SUFFIX = '\n\n[remote content truncated: payload too large]';
const REMOTE_INVOKE_TRUNCATED_CONTENT = '[remote content truncated: payload too large]';
const REMOTE_INVOKE_FRAME_SAFETY_BYTES = 1024;
+// Remote project viewers reconcile this list on a timer. Treating that background read as
+// interactive activity would refresh the updater quiet period forever for sessions-only viewers.
+const UPDATE_RELAUNCH_NON_BLOCKING_INVOKE_CHANNELS: ReadonlySet<string> = new Set([
+ 'local-db:sessions:list',
+]);
const textEncoder = new TextEncoder();
/** wire 输入 fail-closed:未知形状视为空能力集,并限制数量/长度避免撑大常驻 registry。 */
@@ -327,13 +335,19 @@ function projectInvokeResultForTunnel(
/** 持有 client 的引用(转发 push 用);wireInboundDispatch 接入时设置。 */
let activeClient: DeviceLinkClient | null = null;
-/** 控制端集合变化时通知 host(更新「正在被控」状态条) */
-type ControllersChangedListener = (controllers: ActiveController[]) => void;
+/** 订阅集合变化时一次性通知 host UI 控制态与更新重启安全态。 */
+type ControllersChangedListener = (
+ controllers: ActiveController[],
+ updateRelaunchControllers: ActiveController[],
+) => void;
let onControllersChanged: ControllersChangedListener | null = null;
-/** All remote viewers, including lightweight `sessions` subscriptions. */
-type SubscribedControllersChangedListener = (controllers: ActiveController[]) => void;
-let onSubscribedControllersChanged: SubscribedControllersChangedListener | null = null;
+/** 非订阅类远程 invoke 在途状态;用于给无人值守更新持有短期 busy lease。 */
+type RemoteInvokeBusyChangedListener = (busy: boolean) => void;
+let onRemoteInvokeBusyChanged: RemoteInvokeBusyChangedListener | null = null;
+let inFlightRemoteInvokeCount = 0;
+/** Controllers that have successfully demonstrated topic-subscription support on this link. */
+const topicSubscriptionControllers = new Set<string>();
/** `sessions` 订阅出现时通知 host replay 当前列表级轻量状态。 */
type SessionsSubscribedListener = (controllerDeviceId: string) => void;
@@ -343,10 +357,10 @@ export function setControllersChangedListener(cb: ControllersChangedListener | n
onControllersChanged = cb;
}
-export function setSubscribedControllersChangedListener(
- cb: SubscribedControllersChangedListener | null,
+export function setRemoteInvokeBusyChangedListener(
+ cb: RemoteInvokeBusyChangedListener | null,
): void {
- onSubscribedControllersChanged = cb;
+ onRemoteInvokeBusyChanged = cb;
}
export function setSessionsSubscribedListener(cb: SessionsSubscribedListener | null): void {
@@ -357,8 +371,51 @@ export function getActiveControllers(): ActiveController[] {
return subscriptions.getControlControllers();
}
-export function getSubscribedControllers(): ActiveController[] {
- return subscriptions.getSubscribedControllers();
+export function getUpdateRelaunchControllers(): ActiveController[] {
+ return subscriptions.getUpdateRelaunchControllers();
+}
+
+export function hasInFlightRemoteInvokes(): boolean {
+ return inFlightRemoteInvokeCount > 0;
+}
+
+function notifyRemoteInvokeBusyChanged(busy: boolean): void {
+ try {
+ onRemoteInvokeBusyChanged?.(busy);
+ } catch (err) {
+ log.warn(`remote invoke busy listener failed: ${String(err)}`);
+ }
+}
+
+function acquireRemoteInvokeBusyLease(): () => void {
+ const wasBusy = hasInFlightRemoteInvokes();
+ inFlightRemoteInvokeCount += 1;
+ if (!wasBusy) notifyRemoteInvokeBusyChanged(true);
+
+ let released = false;
+ return () => {
+ if (released) return;
+ released = true;
+ inFlightRemoteInvokeCount = Math.max(0, inFlightRemoteInvokeCount - 1);
+ if (!hasInFlightRemoteInvokes()) notifyRemoteInvokeBusyChanged(false);
+ };
+}
+
+function shouldAcquireRemoteInvokeBusyLease(
+ src: string,
+ payload: InvokePayload | undefined,
+): boolean {
+ if (!payload || typeof payload.channel !== 'string') return false;
+ if (!readDeviceLinkSettings().remoteControlEnabled) return false;
+ if (isControllerRevoked(src)) return false;
+ if (!REMOTE_INVOKE_ALLOWLIST.has(payload.channel)) return false;
+ if (
+ payload.channel === 'local-db:sessions:get' &&
+ payload.args?.[1] === DEVICE_LINK_RECONCILIATION_PROBE_MARKER
+ ) {
+ return false;
+ }
+ return !UPDATE_RELAUNCH_NON_BLOCKING_INVOKE_CHANNELS.has(payload.channel);
}
function notifySessionsSubscribed(controllerDeviceId: string): void {
@@ -512,12 +569,15 @@ function truncateRemoteString(value: string, state: TruncationState): string {
/**
* 同步「转发 tap 开关」与「被控横幅」到当前 registry 状态。任何 registry 变更后调用:
* - registry 非空 → 注册 forwardPush tap(无监听时 broadcast-tap 是 O(1) no-op);空 → 注销。
- * - 横幅控制端集 = 持 session:<id> / legacy '*' 的订阅者。
+ * - UI 活跃控制端集 = 持 session:<id> / legacy '*' 的订阅者。
+ * - 更新重启阻塞集额外包含 fs-watch:<workdir>,但不扩大 UI 被控横幅语义。
*/
function syncForwarding(): void {
setBroadcastTapListener(subscriptions.isEmpty() ? null : forwardPush);
- onControllersChanged?.(subscriptions.getControlControllers());
- onSubscribedControllersChanged?.(subscriptions.getSubscribedControllers());
+ onControllersChanged?.(
+ subscriptions.getControlControllers(),
+ subscriptions.getUpdateRelaunchControllers(),
+ );
}
/** 把所有订阅控制端踢掉(被控开关关闭 / 用户一键断开 / 退出时调用) */
@@ -525,10 +585,15 @@ export function dropAllControllers(
client: DeviceLinkClient,
reason: 'user' | 'toggle-off' | 'shutdown',
): void {
- for (const dst of subscriptions.getControllerIds()) {
+ const controllerIds = new Set([
+ ...subscriptions.getControllerIds(),
+ ...topicSubscriptionControllers,
+ ]);
+ for (const dst of controllerIds) {
client.closeLink(dst, reason);
}
subscriptions.clearAll();
+ topicSubscriptionControllers.clear();
syncForwarding();
}
@@ -538,6 +603,7 @@ export function dropAllControllers(
* 后回收僵尸订阅的兜底信号(正常路径是控制端显式 unsubscribe / link-close)。
*/
export function handleControllerOffline(deviceId: string): void {
+ topicSubscriptionControllers.delete(deviceId);
if (subscriptions.clearController(deviceId)) {
syncForwarding();
}
@@ -565,6 +631,7 @@ async function handleFrame(client: DeviceLinkClient, env: Envelope): Promise<voi
return;
case 'link-close':
if (!src) return;
+ topicSubscriptionControllers.delete(src);
if (subscriptions.clearController(src)) {
syncForwarding();
}
@@ -609,12 +676,13 @@ function handleLinkOpen(
? payload.controllerName.trim().slice(0, MAX_CONTROLLER_NAME_LEN)
: src.slice(0, 8);
// 老控制端无 subscribe 能力:link-open 视作订阅 legacy '*'(全量转发 + 横幅),向后兼容。
- subscriptions.subscribe(
- src,
- [LEGACY_TOPIC],
- name,
- sanitizeControllerCapabilities(payload?.capabilities),
- );
+ // 已在当前 link 上证明支持 topic 的客户端可能重复 open;不能重新装回兼容 wildcard。
+ const capabilities = sanitizeControllerCapabilities(payload?.capabilities);
+ if (topicSubscriptionControllers.has(src)) {
+ subscriptions.updateControllerMetadata(src, name, capabilities);
+ } else {
+ subscriptions.subscribe(src, [LEGACY_TOPIC], name, capabilities);
+ }
syncForwarding();
client.sendLinkAccept(src, requestId, {
appVersion: app.getVersion(),
@@ -635,8 +703,15 @@ async function handleInvoke(
client.sendInvokeResult(src, requestId, handleSubscriptionFrame(src, payload));
return;
}
- const result = await runInvoke(src, payload);
- sendInvokeResultSafe(client, src, requestId, result, payload?.channel, payload?.args);
+ const releaseBusyLease = shouldAcquireRemoteInvokeBusyLease(src, payload)
+ ? acquireRemoteInvokeBusyLease()
+ : () => undefined;
+ try {
+ const result = await runInvoke(src, payload);
+ sendInvokeResultSafe(client, src, requestId, result, payload?.channel, payload?.args);
+ } finally {
+ releaseBusyLease();
+ }
}
/**
@@ -951,7 +1026,16 @@ function handleSubscriptionFrame(src: string, payload: InvokePayload): InvokeRes
: undefined;
const isSub = payload.channel === DL_SUBSCRIBE_CHANNEL;
if (isSub) {
+ // link-open provisionally installs legacy '*' for old clients. A non-empty modern subscribe
+ // proves topic support, so replace that compatibility firehose and remember the capability
+ // until disconnect. Empty/fully-filtered frames leave legacy compatibility intact.
+ // Add the modern topics first so replacing the last legacy topic does not discard the
+ // controller metadata (including negotiated capabilities) with the registry entry.
subscriptions.subscribe(src, topics, name, optionalControllerCapabilities(o));
+ if (topics.length > 0) {
+ topicSubscriptionControllers.add(src);
+ subscriptions.unsubscribe(src, [LEGACY_TOPIC]);
+ }
} else {
subscriptions.unsubscribe(src, topics);
}
@@ -1187,13 +1271,16 @@ export const __testing = {
reset(): void {
subscriptions.__testing.reset();
onControllersChanged = null;
- onSubscribedControllersChanged = null;
+ onRemoteInvokeBusyChanged = null;
+ inFlightRemoteInvokeCount = 0;
+ topicSubscriptionControllers.clear();
onSessionsSubscribed = null;
activeClient = null;
setBroadcastTapListener(null);
},
getActiveControllers,
- getSubscribedControllers,
+ getUpdateRelaunchControllers,
+ hasInFlightRemoteInvokes,
controllerSupports: subscriptions.controllerSupports,
optionalControllerCapabilities,
sendInvokeResultSafe,
diff --git a/apps/desktop/src/main/device-link/index.ts b/apps/desktop/src/main/device-link/index.ts
index c74e2ef902..a724c50bcd 100644
--- a/apps/desktop/src/main/device-link/index.ts
+++ b/apps/desktop/src/main/device-link/index.ts
@@ -51,6 +51,7 @@ import { keepAwakeController } from './power-blocker';
import {
wireInboundDispatch,
setControllersChangedListener,
+ setRemoteInvokeBusyChangedListener,
dropAllControllers,
handleControllerOffline,
} from './dispatch';
@@ -215,7 +216,12 @@ function wsUrl(): string {
return deviceLinkApiBase().replace(/^http/, 'ws') + WS_PATH;
}
-export function initDeviceLinkService(): void {
+/** Host integrations that consume device-link lifecycle state. */
+export interface DeviceLinkServiceOptions {
+ onUpdateRelaunchBusyChanged?: (busy: boolean) => void;
+}
+
+export function initDeviceLinkService(options: DeviceLinkServiceOptions = {}): void {
// 「保持电脑唤醒」按持久化偏好在启动时应用(与登录 / relay 无关,幂等)。
const initialKeepAwake = readDeviceLinkSettings().keepAwake;
keepAwakeController.apply(initialKeepAwake);
@@ -307,13 +313,25 @@ export function initDeviceLinkService(): void {
}
});
- // 被控端:接线入站隧道(link-open / invoke / link-close → 本机 handler dispatch)
- wireInboundDispatch(client);
+ let updateRelaunchControllersBusy = false;
+ let remoteInvokeBusy = false;
+ const notifyUpdateRelaunchBusy = (): void => {
+ options.onUpdateRelaunchBusyChanged?.(updateRelaunchControllersBusy || remoteInvokeBusy);
+ };
- // 被控端可见性:控制端集合变化 → 广播给 renderer 状态条
- setControllersChangedListener((controllers) => {
+ // 先注册远程活动监听,再接线入站帧;否则首个 subscribe / invoke 可能落在空窗期。
+ setControllersChangedListener((controllers, updateRelaunchControllers) => {
broadcast(DEVICE_LINK_PUSH.CONTROLLED_STATE, { controllers });
+ updateRelaunchControllersBusy = updateRelaunchControllers.length > 0;
+ notifyUpdateRelaunchBusy();
});
+ setRemoteInvokeBusyChangedListener((busy) => {
+ remoteInvokeBusy = busy;
+ notifyUpdateRelaunchBusy();
+ });
+
+ // 被控端:接线入站隧道(link-open / invoke / link-close → 本机 handler dispatch)
+ wireInboundDispatch(client);
// busy presence:每 5s 探一次本机是否有 turn 在跑,变化才上报(dedupe by value)
startBusyReporting();
@@ -429,6 +447,7 @@ export function initDeviceLinkService(): void {
// 已由上面 stop() 的 onDemote 执行过一次,linkTornDown 标记拦截重复清理。
teardownActiveLink();
setControllersChangedListener(null);
+ setRemoteInvokeBusyChangedListener(null);
client = null;
});
diff --git a/apps/desktop/src/main/device-link/subscriptions.ts b/apps/desktop/src/main/device-link/subscriptions.ts
index 55bb8a31c7..689e8c8736 100644
--- a/apps/desktop/src/main/device-link/subscriptions.ts
+++ b/apps/desktop/src/main/device-link/subscriptions.ts
@@ -103,8 +103,7 @@ export function subscribe(
name?: string,
capabilities?: readonly string[],
): void {
- // Empty/fully-filtered subscribe frames must not create a registry entry:
- // getSubscribedControllers() treats every entry as update-relaunch busy.
+ // Empty/fully-filtered subscribe frames must not create a phantom remote viewer.
if (topics.length === 0) return;
const e = getOrCreate(deviceId, name);
if (capabilities) {
@@ -115,6 +114,20 @@ export function subscribe(
notifySubscribed(topics);
}
+/** 更新已有控制端元数据;不为尚无 topic 的连接创建 phantom registry entry。 */
+export function updateControllerMetadata(
+ deviceId: string,
+ name: string,
+ capabilities?: readonly string[],
+): void {
+ const e = registry.get(deviceId);
+ if (!e) return;
+ e.name = name;
+ if (capabilities) {
+ e.capabilities = new Set(capabilities.filter((value) => typeof value === 'string'));
+ }
+}
+
/** 取消订阅指定 topics;该控制端 topic 清空后整条移除。空 topics 为 no-op。 */
export function unsubscribe(deviceId: string, topics: readonly string[]): void {
const e = registry.get(deviceId);
@@ -152,14 +165,6 @@ export function getControllerIds(): string[] {
return [...registry.keys()];
}
-/** All subscribed controllers, including lightweight `sessions` viewers. */
-export function getSubscribedControllers(): ActiveController[] {
- return [...registry].map(([deviceId, entry]) => ({
- deviceId,
- name: entry.name,
- }));
-}
-
/** 持有该 topic(或 legacy `'*'`)的控制端 deviceId 列表 —— topic-scoped fan-out 依据。 */
export function getControllersForTopic(topic: Topic): string[] {
const out: string[] = [];
@@ -178,15 +183,11 @@ function isControlTopic(t: StoredTopic): boolean {
return t === LEGACY_TOPIC || t.startsWith('session:');
}
-/**
- * 持有任意 `session:<id>` 或 legacy `'*'` 的控制端 —— 被控横幅展示这些(=活跃控制)。
- * 纯 `sessions`(只看列表)订阅者**不**触发横幅。
- */
-export function getControlControllers(): ActiveController[] {
+function collectControllers(matches: (topic: StoredTopic) => boolean): ActiveController[] {
const out: ActiveController[] = [];
for (const [id, e] of registry) {
for (const t of e.topics) {
- if (isControlTopic(t)) {
+ if (matches(t)) {
out.push({ deviceId: id, name: e.name });
break;
}
@@ -195,6 +196,19 @@ export function getControlControllers(): ActiveController[] {
return out;
}
+/** 持有具体 session 或 legacy `'*'` 的控制端;只用于被控横幅与 `controlledBy`。 */
+export function getControlControllers(): ActiveController[] {
+ return collectControllers(isControlTopic);
+}
+
+/**
+ * 会阻止无人值守更新重启的远程活动。
+ * `fs-watch` 虽不触发被控横幅,但代表有人正在实时浏览文件树,重启仍应延后。
+ */
+export function getUpdateRelaunchControllers(): ActiveController[] {
+ return collectControllers((topic) => isControlTopic(topic) || topic.startsWith('fs-watch:'));
+}
+
export const __testing = {
reset(): void {
registry.clear();
diff --git a/apps/desktop/src/main/updateRelaunchSafety.ts b/apps/desktop/src/main/updateRelaunchSafety.ts
index 4a46e2a8b5..ab65eea15d 100644
--- a/apps/desktop/src/main/updateRelaunchSafety.ts
+++ b/apps/desktop/src/main/updateRelaunchSafety.ts
@@ -16,6 +16,26 @@ export interface UpdateRelaunchScheduleStorage {
hasRunningRuns: () => Promise<boolean>;
}
+export interface UpdateRelaunchBusyTransition {
+ nextBusy: boolean;
+ shouldNotify: boolean;
+}
+
+/**
+ * Collapse controller-list churn into the only edge the update policy needs.
+ * Busy polls refresh the quiet-period timestamp separately; this notification
+ * only wakes the policy when remote activity starts or fully stops.
+ */
+export function decideUpdateRelaunchBusyTransition(
+ previousBusy: boolean,
+ nextBusy: boolean,
+): UpdateRelaunchBusyTransition {
+ return {
+ nextBusy,
+ shouldNotify: previousBusy !== nextBusy,
+ };
+}
+
/**
* Scheduler absence is an expected cold-start state, not a busy-query failure.
* Once storage is initialized, deliberately propagate query failures so the
diff --git a/apps/desktop/src/renderer/__tests__/refreshRemoteSessionsRetry.test.ts b/apps/desktop/src/renderer/__tests__/refreshRemoteSessionsRetry.test.ts
index 4b263c0cd9..2c2522fa19 100644
--- a/apps/desktop/src/renderer/__tests__/refreshRemoteSessionsRetry.test.ts
+++ b/apps/desktop/src/renderer/__tests__/refreshRemoteSessionsRetry.test.ts
@@ -11,6 +11,7 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type { Session } from '@/lib/ccAgent.types';
+import { DEVICE_LINK_RECONCILIATION_PROBE_MARKER } from '@cindy/maker-shared/device-link-contract';
vi.mock('@/lib/logger', () => ({
createLogger: () => ({ debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() }),
@@ -188,7 +189,10 @@ describe('refreshRemoteDeviceSessions retry', () => {
expect(merged).toHaveLength(201);
expect(merged.map((s) => s.id)).toContain('outside-window');
expect(merged[0].title).toBe('new');
- expect(invoke).toHaveBeenNthCalledWith(2, d, 'local-db:sessions:get', ['outside-window']);
+ expect(invoke).toHaveBeenNthCalledWith(2, d, 'local-db:sessions:get', [
+ 'outside-window',
+ DEVICE_LINK_RECONCILIATION_PROBE_MARKER,
+ ]);
});
it('默认事件重拉也按有界快照 merge,保留 200 条窗口外的有效会话', async () => {
diff --git a/apps/desktop/src/renderer/features/device-link/refreshRemoteSessions.ts b/apps/desktop/src/renderer/features/device-link/refreshRemoteSessions.ts
index 75d71237b3..99965f1dc5 100644
--- a/apps/desktop/src/renderer/features/device-link/refreshRemoteSessions.ts
+++ b/apps/desktop/src/renderer/features/device-link/refreshRemoteSessions.ts
@@ -18,6 +18,7 @@
import type { Session } from '@/lib/ccAgent.types';
import { createLogger } from '@/lib/logger';
import { extractIpcError } from '@/utils/ipcError';
+import { DEVICE_LINK_RECONCILIATION_PROBE_MARKER } from '@cindy/maker-shared/device-link-contract';
import { remoteProjectsStore } from './remoteProjectsStore';
import { removeRemoteSessionActivityEntry } from './remoteSessionActivityStore';
@@ -200,7 +201,7 @@ async function probeMissingSessionStatuses(
const value = await window.electronAPI.deviceLink.invoke(
deviceId,
'local-db:sessions:get',
- [sessionId],
+ [sessionId, DEVICE_LINK_RECONCILIATION_PROBE_MARKER],
);
return { sessionId, value };
} catch (error) {
diff --git a/packages/maker-shared/src/deviceLinkContract.ts b/packages/maker-shared/src/deviceLinkContract.ts
index 7ebb80ee34..a1d3e87971 100644
--- a/packages/maker-shared/src/deviceLinkContract.ts
+++ b/packages/maker-shared/src/deviceLinkContract.ts
@@ -2,6 +2,9 @@ import { BRAND_NAME } from './branding.js';
export const DEVICE_LINK_SUBSCRIBE_CHANNEL = 'device-link:subscribe';
export const DEVICE_LINK_UNSUBSCRIBE_CHANNEL = 'device-link:unsubscribe';
+/** Marker passed as sessions:get arg[1] only by background list reconciliation probes. */
+export const DEVICE_LINK_RECONCILIATION_PROBE_MARKER =
+ 'device-link:sessions-reconciliation-probe';
export const DEVICE_LINK_MEDIA_FETCH_CHANNEL = 'device-link:media:fetch';
export const DEVICE_LINK_VOICE_TRANSCRIBE_CHANNEL = 'device-link:voice:transcribe';
export const DEVICE_LINK_VOICE_CREDENTIAL_SYNC_CHANNEL = 'device-link:voice:credential-sync';