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(device-link): 限制远程请求并发并区分繁忙错误

Dashc10f6d2d146e
diff --git a/apps/desktop/src/main/__tests__/deviceLinkDispatch.test.ts b/apps/desktop/src/main/__tests__/deviceLinkDispatch.test.ts
index a89a87c72b..face32a7e6 100644
--- a/apps/desktop/src/main/__tests__/deviceLinkDispatch.test.ts
+++ b/apps/desktop/src/main/__tests__/deviceLinkDispatch.test.ts
@@ -9,9 +9,8 @@ let revokedControllers: string[] = [];
vi.mock('../device-link/settings-store', () => ({
readDeviceLinkSettings: () => ({ remoteControlEnabled, revokedControllers }),
}));
-vi.mock('../logger', () => ({
- createLogger: () => ({ debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() }),
-}));
+const diagnosticLog = vi.hoisted(() => ({ debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() }));
+vi.mock('../logger', () => ({ createLogger: () => diagnosticLog }));
vi.mock('electron', () => ({
ipcMain: { handle: vi.fn(), removeHandler: vi.fn() },
app: { getVersion: () => '1.0.0' },
@@ -1234,6 +1233,10 @@ describe('被控端控制链路生命周期', () => {
},
},
}));
+ expect(diagnosticLog.debug).toHaveBeenCalledWith('remote invoke admission busy', expect.objectContaining({
+ executing: limit, pendingResults: 0, controllerAtLimit: true, globalAtLimit: false,
+ channels: { 'local-db:sessions:list': limit },
+ }));
resolveList?.([{ id: 's1' }]);
await vi.waitFor(() => {
expect(calls.invokeResult.filter((call) => call.payload && (call.payload as { ok?: boolean }).ok === true))
diff --git a/apps/desktop/src/main/__tests__/deviceLinkIpc.test.ts b/apps/desktop/src/main/__tests__/deviceLinkIpc.test.ts
index d92da7d7cd..36b7d143bb 100644
--- a/apps/desktop/src/main/__tests__/deviceLinkIpc.test.ts
+++ b/apps/desktop/src/main/__tests__/deviceLinkIpc.test.ts
@@ -900,15 +900,25 @@ describe('device-link controller handlers', () => {
);
});
- it('invoke:本地传输背压 → DEVICE_LINK_NOT_CONNECTED', async () => {
+ it('invoke:本地传输背压 → DEVICE_LINK_BUSY', async () => {
const deps = makeDeps({
invoke: vi.fn().mockRejectedValue(new DeviceLinkError('BACKPRESSURE', 'buffer full')),
});
await expect(handleInvoke(deps, 'dev-2', 'maker:send', [])).rejects.toThrowError(
- /\[DEVICE_LINK_NOT_CONNECTED\]/,
+ /\[DEVICE_LINK_BUSY\]/,
);
});
+ it('invoke: remote admission backpressure remains busy rather than disconnected', async () => {
+ const deps = makeDeps({
+ invoke: vi.fn().mockResolvedValue({
+ ok: false, error: { code: 'BACKPRESSURE', message: 'remote invoke execution queue is full' },
+ }),
+ });
+ await expect(handleInvoke(deps, 'dev-2', 'local-db:task-tags:execute', []))
+ .rejects.toMatchObject({ code: 'DEVICE_LINK_BUSY' });
+ });
+
it('invoke: a second peer reset stops retrying and becomes a disconnected IPC error', async () => {
const reset = new DeviceLinkError('PEER_RESET', 'peer reset during read');
reset.inFlight = true;
@@ -1062,7 +1072,7 @@ describe('device-link controller handlers', () => {
});
await handleSubscribe(deps, 'dev-2', ['sessions'], 1);
await expect(handleUnsubscribe(deps, 'dev-2', ['sessions'], 1)).rejects.toThrowError(
- /\[DEVICE_LINK_NOT_CONNECTED\]/,
+ /\[DEVICE_LINK_BUSY\]/,
);
await expect(handleUnsubscribe(deps, 'dev-2', ['sessions'], 1)).resolves.toEqual({ ok: true });
expect(deps.unsubscribe).toHaveBeenCalledTimes(2);
diff --git a/apps/desktop/src/main/device-link/dispatch.ts b/apps/desktop/src/main/device-link/dispatch.ts
index 6b8696e9f9..188aaa04d8 100644
--- a/apps/desktop/src/main/device-link/dispatch.ts
+++ b/apps/desktop/src/main/device-link/dispatch.ts
@@ -782,6 +782,7 @@ interface CachedRemoteInvokeResult {
const completedRemoteInvokeResults = new Map<string, CachedRemoteInvokeResult>();
let completedRemoteInvokeResultBytes = 0;
interface InFlightRemoteInvoke {
+ channel?: string;
promise: Promise<InvokeResultPayload>;
bytes: number;
fingerprint: string;
@@ -2642,6 +2643,30 @@ async function handleInvoke(
> REMOTE_INVOKE_IN_FLIGHT_BYTES
);
if (controllerAtLimit || globalAtLimit) {
+ const channels: Record<string, number> = {};
+ let executing = 0;
+ let pendingResults = 0;
+ const countChannel = (channel?: string) => {
+ const name = channel && REMOTE_INVOKE_ALLOWLIST.has(channel) ? channel : 'unknown';
+ channels[name] = (channels[name] ?? 0) + 1;
+ };
+ for (const [key, entry] of inFlightRemoteInvokeResults) {
+ if (!key.startsWith(`${src}\u0000`)) continue;
+ executing++;
+ countChannel(entry.channel);
+ }
+ for (const entry of remoteInvokeResultOutbox.values()) {
+ if (entry.src !== src) continue;
+ pendingResults++;
+ countChannel(entry.channel);
+ }
+ log.debug('remote invoke admission busy', {
+ from: shortId(src), controllerAtLimit, globalAtLimit, executing, pendingResults,
+ controllerBytes: controllerAdmission.bytes,
+ globalExecuting: inFlightRemoteInvokeResults.size,
+ globalPendingResults: remoteInvokeResultOutbox.size,
+ channels: Object.fromEntries(Object.entries(channels).sort((a, b) => b[1] - a[1]).slice(0, 8)),
+ });
const result: InvokeResultPayload = {
ok: false,
error: {
@@ -2665,6 +2690,7 @@ async function handleInvoke(
if (joiningExisting && existingListing) {
const waiterEntry = {
+ channel: payload?.channel,
promise: existingListing.promise,
bytes: invokeBytes,
fingerprint,
@@ -2723,6 +2749,7 @@ async function handleInvoke(
payload?.channel,
).finally(releaseBusyLease);
const inFlightEntry = {
+ channel: payload?.channel,
promise: resultPromise,
bytes: invokeBytes,
fingerprint,
diff --git a/apps/desktop/src/main/device-link/ipc.ts b/apps/desktop/src/main/device-link/ipc.ts
index bc618a586f..be1b6d99fe 100644
--- a/apps/desktop/src/main/device-link/ipc.ts
+++ b/apps/desktop/src/main/device-link/ipc.ts
@@ -221,7 +221,7 @@ const DEVICE_LINK_CODE_MAP: Record<string, IpcErrorCode> = {
NOT_CONNECTED: 'DEVICE_LINK_NOT_CONNECTED',
LINK_NOT_OPEN: 'DEVICE_LINK_NOT_CONNECTED',
PEER_RESET: 'DEVICE_LINK_NOT_CONNECTED',
- BACKPRESSURE: 'DEVICE_LINK_NOT_CONNECTED',
+ BACKPRESSURE: 'DEVICE_LINK_BUSY',
};
/**
diff --git a/apps/desktop/src/renderer/__tests__/prRefsGranularity.test.tsx b/apps/desktop/src/renderer/__tests__/prRefsGranularity.test.tsx
index f4c84c289f..36afbfdd5c 100644
--- a/apps/desktop/src/renderer/__tests__/prRefsGranularity.test.tsx
+++ b/apps/desktop/src/renderer/__tests__/prRefsGranularity.test.tsx
@@ -84,6 +84,30 @@ const wrapper = ({ children }: { children: ReactNode }) =>
createElement(PrRefsProvider, null, children);
describe('PrRefsProvider 订阅粒度(真实 Provider)', () => {
+ it('coalesces repeated focus and registration while remote PR reads are queued or running', async () => {
+ const api = installElectronApi();
+ let finishRefs!: (refs: SessionPrRef[]) => void;
+ let finishStatuses!: (statuses: unknown[]) => void;
+ api.invoke.mockImplementation((_device, channel) => new Promise((resolve) => {
+ if (channel === 'git-context:pr-refs:list') finishRefs = resolve as typeof finishRefs;
+ else finishStatuses = resolve as typeof finishStatuses;
+ }));
+ const focus = vi.spyOn(document, 'hasFocus').mockReturnValue(true);
+ const { result, unmount } = renderHook(() => usePrActions(), { wrapper });
+ try {
+ act(() => { result.current.registerPrConsumer('session-r', 'device-1'); });
+ for (let n = 0; n < 5; n++) act(() => {
+ result.current.registerPrConsumer('session-r', 'device-1');
+ window.dispatchEvent(new Event('focus'));
+ });
+ expect(api.invoke).toHaveBeenCalledTimes(1);
+ await act(async () => { finishRefs([makeRef('session-r', 42)]); });
+ expect(api.invoke).toHaveBeenCalledTimes(2);
+ for (let n = 0; n < 5; n++) act(() => { window.dispatchEvent(new Event('focus')); });
+ expect(api.invoke).toHaveBeenCalledTimes(2);
+ await act(async () => { finishStatuses([]); });
+ } finally { unmount(); focus.mockRestore(); }
+ });
it('某会话 refs 更新只重渲染该会话的订阅行,其它行不醒', async () => {
const api = installElectronApi();
api.gitContext.listPrRefs.mockImplementation(async (sessionId: string) =>
diff --git a/apps/desktop/src/renderer/components/chat/__tests__/ErrorLocalization.test.tsx b/apps/desktop/src/renderer/components/chat/__tests__/ErrorLocalization.test.tsx
index d3d76f5848..b8f99540f8 100644
--- a/apps/desktop/src/renderer/components/chat/__tests__/ErrorLocalization.test.tsx
+++ b/apps/desktop/src/renderer/components/chat/__tests__/ErrorLocalization.test.tsx
@@ -37,7 +37,7 @@ describe.each(SUPPORTED_LOCALES)('error presentation in %s', locale => {
expect(screen.queryByText(locales[locale].chat.errorBanner.networkShowRaw)).toBeNull();
});
- it.each(['REMOTE_LOCAL_ONLY_PROVIDER', 'DEVICE_LINK_MEDIA_TRANSFER_FAILED', 'MCP_APPROVAL_CONFIRMATION_TIMEOUT'])('preserves curated %s guidance and follows language changes', async code => {
+ it.each(['REMOTE_LOCAL_ONLY_PROVIDER', 'DEVICE_LINK_MEDIA_TRANSFER_FAILED', 'DEVICE_LINK_BUSY', 'MCP_APPROVAL_CONFIRMATION_TIMEOUT'])('preserves curated %s guidance and follows language changes', async code => {
const i18n = createInstance();
await i18n.init({ lng: locale, fallbackLng: 'en', resources: Object.fromEntries(Object.entries(locales).map(([lng, common]) => [lng, { translation: common }])) });
const message = `Error invoking remote method device-link:invoke: Error: [${code}] upstream fallback api_key=private-test-value`;
diff --git a/apps/desktop/src/renderer/features/task-tags/TaskTags.tsx b/apps/desktop/src/renderer/features/task-tags/TaskTags.tsx
index 33213534dc..f4944193a2 100644
--- a/apps/desktop/src/renderer/features/task-tags/TaskTags.tsx
+++ b/apps/desktop/src/renderer/features/task-tags/TaskTags.tsx
@@ -255,7 +255,7 @@ export function TaskTagMenuSection({ session, onMore }: { session: Session; onMo
{error && (
<p className="max-w-64 text-xs text-[var(--text-secondary)]" role="status">
{t(`taskTags.${error}`)}
- {error === 'loadFailed' && (
+ {(error === 'loadFailed' || error === 'remoteBusy') && (
<button
type="button"
className={button}
@@ -902,7 +902,7 @@ export function TaskTagEditor({ session, onClose }: { session: Session; onClose:
role="alert"
>
{t(`taskTags.${blocked ? 'offline' : error}`)}
- {!blocked && error === 'loadFailed' && (
+ {!blocked && (error === 'loadFailed' || error === 'remoteBusy') && (
<button
type="button"
className={button}
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index d05c009027..44535bce64 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -334,6 +334,7 @@
"credentialRequired": "Complete Mac password verification. If unavailable, update Cindy on both computers."
},
"ipcError": {
+ "DEVICE_LINK_BUSY": "The remote computer is busy. Please try again shortly.",
"INVALID_PARAMS": "Invalid input. Please check and try again.",
"PRECONDITION_FAILED": "This action is unavailable in the current state. Please try again.",
"MODEL_CONTEXT_USAGE_UNKNOWN": "Model not switched: Cindy can’t verify how much context this task uses. Keep the current model or start a new task.",
@@ -10115,6 +10116,7 @@
"daemonNotReady": "{{manager}} upgraded, but the remote daemon hasn't started yet — please resend your message manually"
},
"remoteError": {
+ "DEVICE_LINK_BUSY": "The remote computer is busy. Please try again shortly.",
"REMOTE_DAEMON_CLOSED": "The remote connection dropped, possibly during an update. This turn has ended. Send the message again.",
"REMOTE_LOCAL_ATTACHMENT_UNSUPPORTED": "Local file/image attachments aren't accessible in remote sessions. Paste the content directly instead.",
"AUTO_REVIEW_UNAVAILABLE": "Auto-review could not reach a decision, so actions that need review now need your confirmation. Switch this task to Full access if you would rather not be interrupted. That mode is higher risk.",
@@ -14227,6 +14229,7 @@
}
},
"taskTags": {
+ "remoteBusy": "The remote computer is busy. Please try again shortly.",
"loadFailed": "Could not load tags. Try again.",
"retry": "Retry",
"editLabel": "Edit “{{name}}”",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 6aba0141b1..b187137c6e 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -334,6 +334,7 @@
"credentialRequired": "Mac のパスワードを確認してください。確認できない場合は両方のパソコンで Cindy を更新してください。"
},
"ipcError": {
+ "DEVICE_LINK_BUSY": "接続先のコンピュータが混み合っています。しばらくしてから再試行してください。",
"INVALID_PARAMS": "パラメータが無効です。確認して再試行してください。",
"PRECONDITION_FAILED": "現在の状態ではこの操作を実行できません。しばらくしてから再試行してください。",
"MODEL_CONTEXT_USAGE_UNKNOWN": "モデルは切り替わっていません。現在のタスクで使用中のコンテキスト量を確認できません。現在のモデルを維持するか、新しいタスクを作成してください。",
@@ -10109,6 +10110,7 @@
"daemonNotReady": "{{manager}} のアップグレードは完了しましたが、リモート daemon がまだ起動していません — メッセージを手動で再送信してください"
},
"remoteError": {
+ "DEVICE_LINK_BUSY": "接続先のコンピュータが混み合っています。しばらくしてから再試行してください。",
"REMOTE_DAEMON_CLOSED": "リモート接続が切れました。更新中の可能性があります。このターンは終了したので、もう一度送信してください。",
"REMOTE_LOCAL_ATTACHMENT_UNSUPPORTED": "リモートセッションではローカルのファイル/画像の添付にアクセスできません。内容を直接貼り付けてください。",
"AUTO_REVIEW_UNAVAILABLE": "自動レビューが判断できませんでした。レビューが必要な操作は、ご自身で確認する形に切り替わりました。中断を減らしたい場合は、このタスクを「フルアクセス」に切り替えてください。リスクはより高くなります。",
@@ -14208,6 +14210,7 @@
}
},
"taskTags": {
+ "remoteBusy": "接続先のコンピュータが混み合っています。しばらくしてから再試行してください。",
"loadFailed": "タグを読み込めませんでした。もう一度お試しください。",
"retry": "再試行",
"editLabel": "「{{name}}」を編集",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 7a19826c93..6b3d1d63c1 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -334,6 +334,7 @@
"credentialRequired": "Mac 암호를 확인하세요. 확인할 수 없으면 두 컴퓨터에서 Cindy를 업데이트하세요."
},
"ipcError": {
+ "DEVICE_LINK_BUSY": "원격 컴퓨터가 사용 중입니다. 잠시 후 다시 시도해 주세요.",
"INVALID_PARAMS": "매개변수가 잘못되었습니다. 확인 후 다시 시도하세요.",
"PRECONDITION_FAILED": "현재 상태에서는 이 작업을 수행할 수 없습니다. 잠시 후 다시 시도하세요.",
"MODEL_CONTEXT_USAGE_UNKNOWN": "모델이 전환되지 않았습니다. 현재 작업에서 사용한 컨텍스트 양을 확인할 수 없습니다. 현재 모델을 유지하거나 새 작업을 만드세요.",
@@ -10109,6 +10110,7 @@
"daemonNotReady": "{{manager}} 업그레이드가 완료되었지만 원격 daemon이 아직 시작되지 않았습니다 — 메시지를 수동으로 다시 전송하세요"
},
"remoteError": {
+ "DEVICE_LINK_BUSY": "원격 컴퓨터가 사용 중입니다. 잠시 후 다시 시도해 주세요.",
"REMOTE_DAEMON_CLOSED": "원격 연결이 끊겼습니다. 업데이트 중일 수 있습니다. 이번 차례는 끝났으니 다시 보내 주세요.",
"REMOTE_LOCAL_ATTACHMENT_UNSUPPORTED": "원격 세션에서는 로컬 파일/이미지 첨부에 접근할 수 없습니다. 내용을 직접 붙여넣으세요.",
"AUTO_REVIEW_UNAVAILABLE": "자동 리뷰가 판단을 내리지 못했습니다. 검토가 필요한 작업은 직접 확인하도록 바뀌었습니다. 중단을 줄이려면 이 작업을 전체 접근으로 전환하세요. 위험도는 더 높습니다.",
@@ -14208,6 +14210,7 @@
}
},
"taskTags": {
+ "remoteBusy": "원격 컴퓨터가 사용 중입니다. 잠시 후 다시 시도해 주세요.",
"loadFailed": "태그를 불러오지 못했습니다. 다시 시도해 주세요.",
"retry": "다시 시도",
"editLabel": "“{{name}}” 편집",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index 91402d750d..13934cdbe2 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -334,6 +334,7 @@
"credentialRequired": "请完成 Mac 密码验证。如果无法验证,请更新两台电脑上的 Cindy。"
},
"ipcError": {
+ "DEVICE_LINK_BUSY": "远端繁忙,请稍后重试。",
"INVALID_PARAMS": "参数无效,请检查后重试。",
"PRECONDITION_FAILED": "当前状态下无法执行此操作,请稍后重试。",
"MODEL_CONTEXT_USAGE_UNKNOWN": "模型未切换:无法确认当前任务已使用的上下文。请保留当前模型,或新建任务后再选择",
@@ -10109,6 +10110,7 @@
"daemonNotReady": "{{manager}} 升级完成,但远端 daemon 暂未启动 — 请手动重新发送消息"
},
"remoteError": {
+ "DEVICE_LINK_BUSY": "远端繁忙,请稍后重试。",
"REMOTE_DAEMON_CLOSED": "远端连接中断了,可能正在更新。这一轮已经结束,请重新发送。",
"REMOTE_LOCAL_ATTACHMENT_UNSUPPORTED": "远端任务无法访问本地文件/图片附件。请直接粘贴内容。",
"AUTO_REVIEW_UNAVAILABLE": "自动审批暂时无法给出判断,需要审批的操作已改为由你确认。想少被打断,可以把任务切到「完全访问」,但风险更高。",
@@ -14208,6 +14210,7 @@
}
},
"taskTags": {
+ "remoteBusy": "远端繁忙,请稍后重试。",
"loadFailed": "标签加载失败,请重试。",
"retry": "重试",
"editLabel": "编辑“{{name}}”",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index a9d4f19981..755a7e5b4a 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -334,6 +334,7 @@
"credentialRequired": "請完成 Mac 密碼驗證。如果無法驗證,請更新兩台電腦上的 Cindy。"
},
"ipcError": {
+ "DEVICE_LINK_BUSY": "遠端忙碌中,請稍後再試。",
"INVALID_PARAMS": "引數無效,請檢查後重試。",
"PRECONDITION_FAILED": "目前狀態下無法執行此操作,請稍後再試。",
"MODEL_CONTEXT_USAGE_UNKNOWN": "模型未切換:無法確認目前任務已使用的上下文。請保留目前模型,或新增任務後再選擇",
@@ -10108,6 +10109,7 @@
"daemonNotReady": "{{manager}} 升級完成,但遠端 daemon 暫未啟動 — 請手動重新傳送訊息"
},
"remoteError": {
+ "DEVICE_LINK_BUSY": "遠端忙碌中,請稍後再試。",
"REMOTE_DAEMON_CLOSED": "遠端連線中斷了,可能正在更新。這一輪已經結束,請重新傳送。",
"REMOTE_LOCAL_ATTACHMENT_UNSUPPORTED": "遠端任務無法訪問本地檔案/圖片附件。請直接貼上內容。",
"AUTO_REVIEW_UNAVAILABLE": "自動審批暫時無法給出判斷,需要審批的操作已改為由你確認。想少被打斷,可以把任務切到「完全訪問」,但風險更高。",
@@ -14208,6 +14210,7 @@
}
},
"taskTags": {
+ "remoteBusy": "遠端忙碌中,請稍後再試。",
"loadFailed": "標籤載入失敗,請重試。",
"retry": "重試",
"editLabel": "編輯「{{name}}」",
diff --git a/apps/desktop/src/shared/ipc-errors.ts b/apps/desktop/src/shared/ipc-errors.ts
index c8861b9f65..333204dd9b 100644
--- a/apps/desktop/src/shared/ipc-errors.ts
+++ b/apps/desktop/src/shared/ipc-errors.ts
@@ -207,6 +207,7 @@ export type IpcErrorCode =
// device-link(跨设备远程控制)
| 'DEVICE_LINK_UNAVAILABLE' // relay 不可达 / server 未启用该功能
| 'DEVICE_LINK_NOT_CONNECTED' // 本机尚未连上 relay(未登录 / 断线中)
+ | 'DEVICE_LINK_BUSY' // 请求队列繁忙,连接仍可能正常
| 'DEVICE_LINK_STANDBY' // 本实例处于单持有者仲裁的被动态(同机另一实例持有 relay 连接)
| 'DEVICE_LINK_DEVICE_OFFLINE' // 目标设备离线
| 'DEVICE_LINK_REMOTE_DISABLED' // 目标设备「允许被控」开关关闭
@@ -447,6 +448,7 @@ const IPC_ERROR_CODES: ReadonlySet<IpcErrorCode> = new Set<IpcErrorCode>([
'FS_BROWSE_FAILED',
'DEVICE_LINK_UNAVAILABLE',
'DEVICE_LINK_NOT_CONNECTED',
+ 'DEVICE_LINK_BUSY',
'DEVICE_LINK_STANDBY',
'DEVICE_LINK_DEVICE_OFFLINE',
'DEVICE_LINK_REMOTE_DISABLED',
diff --git a/apps/mobile/src/__tests__/taskTagsRecovery.test.tsx b/apps/mobile/src/__tests__/taskTagsRecovery.test.tsx
index 0854793927..3dabd0e81b 100644
--- a/apps/mobile/src/__tests__/taskTagsRecovery.test.tsx
+++ b/apps/mobile/src/__tests__/taskTagsRecovery.test.tsx
@@ -190,6 +190,17 @@ beforeEach(() => {
root = createRoot(node);
});
afterEach(() => act(() => root.unmount()));
+it("shows busy without marking the host offline and retries only when requested", async () => {
+ h.invoke.mockRejectedValueOnce(Object.assign(new Error('queue full'), { code: 'BACKPRESSURE' }));
+ await render();
+ expect(h.compact.message).toBe('taskTags.remoteBusy');
+ expect(h.compact.disabled).toBe(false);
+ expect(h.compact.canRetry).toBe(true);
+ expect(h.invoke).toHaveBeenCalledTimes(1);
+ await act(async () => h.compact.onRetry());
+ expect(h.invoke).toHaveBeenCalledTimes(2);
+ expect(h.compact.message).toBeUndefined();
+});
it.each(["other", "host", "account"])(
"scopes in-flight catalog invalidation to %s",
async (scope) => {
diff --git a/apps/mobile/src/i18n/locales/en/taskTags.json b/apps/mobile/src/i18n/locales/en/taskTags.json
index db9529427f..abe3a50c2d 100644
--- a/apps/mobile/src/i18n/locales/en/taskTags.json
+++ b/apps/mobile/src/i18n/locales/en/taskTags.json
@@ -1,4 +1,5 @@
{
+ "remoteBusy": "The remote computer is busy. Please try again shortly.",
"title": "Tags",
"more": "More tags",
"settings": "Tag settings",
diff --git a/apps/mobile/src/i18n/locales/ja/taskTags.json b/apps/mobile/src/i18n/locales/ja/taskTags.json
index 20a9f34524..d5491691ec 100644
--- a/apps/mobile/src/i18n/locales/ja/taskTags.json
+++ b/apps/mobile/src/i18n/locales/ja/taskTags.json
@@ -1,4 +1,5 @@
{
+ "remoteBusy": "接続先のコンピュータが混み合っています。しばらくしてから再試行してください。",
"title": "タグ",
"more": "その他のタグ",
"settings": "タグ設定",
diff --git a/apps/mobile/src/i18n/locales/ko/taskTags.json b/apps/mobile/src/i18n/locales/ko/taskTags.json
index 781178db2b..d6d648b544 100644
--- a/apps/mobile/src/i18n/locales/ko/taskTags.json
+++ b/apps/mobile/src/i18n/locales/ko/taskTags.json
@@ -1,4 +1,5 @@
{
+ "remoteBusy": "원격 컴퓨터가 사용 중입니다. 잠시 후 다시 시도해 주세요.",
"title": "태그",
"more": "태그 더 보기",
"settings": "태그 설정",
diff --git a/apps/mobile/src/i18n/locales/zh-CN/taskTags.json b/apps/mobile/src/i18n/locales/zh-CN/taskTags.json
index 084ffcf5b5..4a77dbafb0 100644
--- a/apps/mobile/src/i18n/locales/zh-CN/taskTags.json
+++ b/apps/mobile/src/i18n/locales/zh-CN/taskTags.json
@@ -1,4 +1,5 @@
{
+ "remoteBusy": "远端繁忙,请稍后重试。",
"title": "标签",
"more": "更多标签",
"settings": "标签设置",
diff --git a/apps/mobile/src/i18n/locales/zh-TW/taskTags.json b/apps/mobile/src/i18n/locales/zh-TW/taskTags.json
index 0669a7fe6e..d7d6f0f02b 100644
--- a/apps/mobile/src/i18n/locales/zh-TW/taskTags.json
+++ b/apps/mobile/src/i18n/locales/zh-TW/taskTags.json
@@ -1,4 +1,5 @@
{
+ "remoteBusy": "遠端忙碌中,請稍後再試。",
"title": "標籤",
"more": "更多標籤",
"settings": "標籤設定",
diff --git a/apps/mobile/src/session/TaskTags.tsx b/apps/mobile/src/session/TaskTags.tsx
index c215426c12..3730a716eb 100644
--- a/apps/mobile/src/session/TaskTags.tsx
+++ b/apps/mobile/src/session/TaskTags.tsx
@@ -743,7 +743,7 @@ export function TaskTagsPanel({
{t('taskTags.title')}
</Text>
<Text
- accessibilityRole={reason === 'loadFailed' ? 'alert' : 'text'}
+ accessibilityRole={reason === 'loadFailed' || reason === 'remoteBusy' ? 'alert' : 'text'}
style={{
color: colors.textSecondary,
fontSize: typeScale.caption,
@@ -1350,7 +1350,7 @@ export function TaskTagsPanel({
{t(`taskTags.${blocked ? 'offline' : error}`)}
</Text>
)}
- {!blocked && error === 'loadFailed' && (
+ {!blocked && (error === 'loadFailed' || error === 'remoteBusy') && (
<Pressable
accessibilityRole="button"
disabled={busy}
diff --git a/docs/dev-rules/remote-and-mobile-adaptation.md b/docs/dev-rules/remote-and-mobile-adaptation.md
index 2c3b4a6e55..93b1cc6dfd 100644
--- a/docs/dev-rules/remote-and-mobile-adaptation.md
+++ b/docs/dev-rules/remote-and-mobile-adaptation.md
@@ -70,6 +70,18 @@ relay 以 close 1013 `inbound backpressure` 主动断连,此时任何「立即
## 共享恢复与请求策略
+普通出站 invoke 在共享 `InvokeScheduler` 中按目标设备排队:每台最多 8 个在途,
+其中 PR 引用/状态、任务列表、定时任务侧栏和用量同步等后台查询最多 2 个。
+前台请求优先于尚未发送的后台请求;不同设备独立推进。PR 的重复聚焦/注册沿用
+`PrRefsContext` 的单任务在途合并,不额外重试或保存结果。握手、订阅控制与远控心跳
+不占业务队列,避免业务拥堵阻断连接或 lease 维护。
+每设备最多等待 128 条,后台最多占前 96 个等待位置;排队预算不超过 30 秒,
+排队过期返回 BACKPRESSURE,发送后仍保留原通道执行预算。断连/停止时取消未发送项,
+在途项仍由既有 transport 结算,不能把取消或超时当成远端操作未执行。
+Desktop 将 BACKPRESSURE 映射为 DEVICE_LINK_BUSY;桌面和手机标签入口显示繁忙与手动重试。
+被控端拒收时 Debug 日志记录在途数、待回包数、配额范围和前八个通道计数,
+不记录参数/标签/消息内容。原被控端准入上限及 wire 格式不变,可独立升级控制端。
+
Desktop 和 Mobile 的按设备排队、并发上限、退避、取消代次由
`packages/device-link/src/peerRecoveryScheduler.ts` 统一维护。Desktop 的订阅快照与
在线判断、Mobile 的后台生命周期与页面恢复仍由各端适配器负责。同一设备取消后重新
diff --git a/packages/device-link/src/__tests__/client.test.ts b/packages/device-link/src/__tests__/client.test.ts
index 51e9c878a9..25e59c3f56 100644
--- a/packages/device-link/src/__tests__/client.test.ts
+++ b/packages/device-link/src/__tests__/client.test.ts
@@ -125,6 +125,36 @@ function makeHarness(opts?: {
const tick = (ms = 0): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms));
+describe('outbound invoke admission', () => {
+ it('batches PR refreshes, admits interactive work and keeps control traffic and other peers moving', async () => {
+ vi.useFakeTimers();
+ const h = makeHarness({ timing: { pingIntervalMs: 60_000, requestTimeoutMs: 30_000 } });
+ const calls: Promise<unknown>[] = [];
+ try {
+ h.client.start(); await vi.advanceTimersByTimeAsync(1); h.current().ack();
+ for (let i = 0; i < 30; i++) calls.push(h.client.invoke('a', {
+ channel: 'git-context:pr-refs:list', args: [`session-${i}`],
+ }).catch(e => e));
+ for (let i = 0; i < 8; i++) calls.push(h.client.invoke('a', {
+ channel: 'local-db:task-tags:execute', args: [{ action: 'get', sessionIds: [`session-${i}`] }],
+ }).catch(e => e));
+ const sent = () => h.current().sent.filter(e => e.kind === 'invoke');
+ expect(sent()).toHaveLength(8);
+ expect(sent().filter(e => (e.payload as { channel: string }).channel === 'git-context:pr-refs:list')).toHaveLength(2);
+ calls.push(h.client.invoke('a', { channel: 'device-link:subscribe', args: [] }).catch(e => e));
+ calls.push(h.client.invoke('b', { channel: 'local-db:task-tags:execute', args: [] }).catch(e => e));
+ expect(sent()).toHaveLength(10);
+ const first = sent()[0];
+ h.current().push({ v: PROTOCOL_VERSION, kind: 'invoke-result', src: 'a', id: first.id, payload: { ok: true, result: [] } });
+ await vi.advanceTimersByTimeAsync(1);
+ expect(sent()).toHaveLength(11);
+ expect(sent().at(-1)?.payload).toMatchObject({ channel: 'local-db:task-tags:execute' });
+ } finally {
+ h.client.stop(); await Promise.all(calls); vi.useRealTimers();
+ }
+ });
+});
+
describe('verified outbound stream notification', () => {
it('notifies before business delivery and keeps two peers independent across restart', async () => {
const h = makeHarness({ timing: { pingIntervalMs: 60_000 } });
@@ -9202,7 +9232,8 @@ describe('confirmed duplicate-open gap repair', () => {
await pump(); await p;
};
await open(phone); await open(healthy);
- for (let i = 0; i < 10; i++) relay.dropNext((sender, env) => sender === 'desktop' && env.dst === 'phone' && env.kind === 'invoke-result');
+ // Eight requests are sent; two remain locally queued and must be cancelled on reconnect.
+ for (let i = 0; i < 8; i++) relay.dropNext((sender, env) => sender === 'desktop' && env.dst === 'phone' && env.kind === 'invoke-result');
const old = Promise.all(Array.from({ length: 10 }, () => phone.invoke('desktop', { channel: 'maker:provider:list', args: [] }, 60000).catch(e => e)));
await pump(); await vi.advanceTimersByTimeAsync(1000);
phone.restartConnection('phone-only-reconnect');
@@ -9215,7 +9246,12 @@ describe('confirmed duplicate-open gap repair', () => {
expect(host.isLinkReady('healthy')).toBe(true);
expect(sockets.mock.calls.filter(x => x[0] === 'desktop')).toHaveLength(1);
expect(sockets.mock.calls.filter(x => x[0] === 'healthy')).toHaveLength(1);
- expect(await old).toEqual(Array.from({ length: 10 }, () => ({ ok: true, result: 'x'.repeat(100000) })));
+ const oldResults = await old;
+ expect(oldResults.slice(0, 8)).toEqual(Array.from({ length: 8 }, () => ({ ok: true, result: 'x'.repeat(100000) })));
+ for (const result of oldResults.slice(8)) {
+ expect(result).toMatchObject({ code: 'NOT_CONNECTED' });
+ expect(result.inFlight).not.toBe(true);
+ }
} finally { off(); for (const c of [host, phone, healthy]) c.stop(); sockets.mockRestore(); vi.useRealTimers(); }
});
diff --git a/packages/device-link/src/__tests__/invokeScheduler.test.ts b/packages/device-link/src/__tests__/invokeScheduler.test.ts
new file mode 100644
index 0000000000..68a511c9e7
--- /dev/null
+++ b/packages/device-link/src/__tests__/invokeScheduler.test.ts
@@ -0,0 +1,175 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { InvokeScheduler } from "../invokeScheduler.js";
+import { DeviceLinkError } from "../protocol.js";
+import { isBackgroundInvoke, bypassInvokeScheduling } from "../invokePolicy.js";
+
+function deferred() {
+ let resolve!: () => void;
+ const promise = new Promise<void>((done) => {
+ resolve = done;
+ });
+ return { promise, resolve };
+}
+const flush = async () => {
+ for (let n = 0; n < 8; n++) await Promise.resolve();
+};
+afterEach(() => vi.useRealTimers());
+
+describe("invoke admission", () => {
+ it("runs a 32-request burst in bounded batches and prioritizes current work", async () => {
+ const scheduler = new InvokeScheduler();
+ const started: string[] = [];
+ const pending = Array.from({ length: 32 }, deferred);
+ const results = pending.map((job, index) =>
+ scheduler.run("a", true, 30_000, () => {
+ started.push(`background-${index}`);
+ return job.promise;
+ }),
+ );
+ const foreground = Array.from({ length: 8 }, deferred);
+ const foregroundResults = foreground.map((job, index) =>
+ scheduler.run("a", false, 30_000, () => {
+ started.push(`foreground-${index}`);
+ return job.promise;
+ }),
+ );
+ expect(started).toEqual([
+ "background-0",
+ "background-1",
+ ...Array.from({ length: 6 }, (_, i) => `foreground-${i}`),
+ ]);
+ pending[0].resolve();
+ await flush();
+ expect(started.at(-1)).toBe("foreground-6");
+ pending[1].resolve();
+ await flush();
+ expect(started.at(-1)).toBe("foreground-7");
+ for (const job of foreground) job.resolve();
+ await flush();
+ expect(started.slice(-2)).toEqual(["background-2", "background-3"]);
+ for (const job of pending) job.resolve();
+ await Promise.all([...results, ...foregroundResults]);
+ expect(started).toHaveLength(40);
+ });
+
+ it("keeps two peers independent and never sends cancelled queued writes after reconnect", async () => {
+ const scheduler = new InvokeScheduler();
+ const active = deferred();
+ const running = Array.from({ length: 8 }, () =>
+ scheduler.run("a", false, 30_000, () => active.promise),
+ );
+ const write = vi.fn(async () => {});
+ const queued = scheduler.run("a", false, 30_000, write);
+ const rejected = expect(queued).rejects.toMatchObject({
+ code: "NOT_CONNECTED",
+ inFlight: undefined,
+ });
+ const error = new DeviceLinkError("NOT_CONNECTED", "disconnected");
+ scheduler.cancel("a", error);
+ error.inFlight = true;
+ await rejected;
+ await expect(
+ scheduler.run("b", false, 30_000, async () => 42),
+ ).resolves.toBe(42);
+ const fresh = vi.fn(async () => {});
+ const next = scheduler.run("a", false, 30_000, fresh);
+ expect(fresh).not.toHaveBeenCalled();
+ active.resolve();
+ await Promise.all([...running, next]);
+ expect(fresh).toHaveBeenCalledOnce();
+ expect(write).not.toHaveBeenCalled();
+ });
+
+ it("expires unsent calls without retrying, and bounds queued calls", async () => {
+ vi.useFakeTimers();
+ const scheduler = new InvokeScheduler();
+ const active = deferred();
+ const running = Array.from({ length: 8 }, () =>
+ scheduler.run("a", false, 30_000, () => active.promise),
+ );
+ const send = vi.fn(async () => {});
+ const queued = Array.from({ length: 128 }, () =>
+ scheduler
+ .run("a", false, 1000, send)
+ .catch((error: DeviceLinkError) => error.code),
+ );
+ await expect(scheduler.run("a", false, 1000, send)).rejects.toMatchObject({
+ code: "BACKPRESSURE",
+ });
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(await Promise.all(queued)).toEqual(Array(128).fill("BACKPRESSURE"));
+ active.resolve();
+ await Promise.all(running);
+ expect(send).not.toHaveBeenCalled();
+ });
+
+ it("checks elapsed queue time before dispatch when timer callbacks have not resumed", async () => {
+ vi.useFakeTimers();
+ const scheduler = new InvokeScheduler();
+ const active = deferred();
+ const running = Array.from({ length: 8 }, () =>
+ scheduler.run("a", false, 30_000, () => active.promise),
+ );
+ const send = vi.fn(async () => {});
+ const next = scheduler
+ .run("a", false, 1000, send)
+ .catch((error: DeviceLinkError) => error.code);
+ vi.setSystemTime(Date.now() + 2000);
+ active.resolve();
+ await Promise.all(running);
+ expect(await next).toBe("BACKPRESSURE");
+ expect(send).not.toHaveBeenCalled();
+ });
+
+ it("releases slots after rejection and synchronous throw without retrying", async () => {
+ const scheduler = new InvokeScheduler();
+ await expect(
+ scheduler.run("a", true, 1000, () => {
+ throw new Error("sync");
+ }),
+ ).rejects.toThrow("sync");
+ await expect(
+ scheduler.run("a", true, 1000, async () => {
+ throw new Error("async");
+ }),
+ ).rejects.toThrow("async");
+ await expect(
+ scheduler.run("a", true, 1000, async () => "ok"),
+ ).resolves.toBe("ok");
+ });
+
+ it("reserves waiting positions for user actions when background refreshes fill their queue", async () => {
+ const scheduler = new InvokeScheduler();
+ const active = deferred();
+ const pending = Array.from({ length: 98 }, () =>
+ scheduler.run("a", true, 30_000, () => active.promise).catch((e) => e),
+ );
+ await expect(
+ scheduler.run("a", true, 30_000, async () => {}),
+ ).rejects.toMatchObject({ code: "BACKPRESSURE" });
+ await expect(
+ scheduler.run("a", false, 30_000, async () => "tag"),
+ ).resolves.toBe("tag");
+ scheduler.clear(new DeviceLinkError("NOT_CONNECTED", "stop"));
+ active.resolve();
+ await Promise.all(pending);
+ });
+
+ it("classifies PR reads as background and keeps control/lease maintenance outside the queue", () => {
+ expect(isBackgroundInvoke("git-context:pr-refs:list")).toBe(true);
+ expect(isBackgroundInvoke("git-context:pr-status")).toBe(true);
+ expect(isBackgroundInvoke("local-db:task-tags:execute")).toBe(false);
+ expect(
+ bypassInvokeScheduling({ channel: "device-link:subscribe", args: [] }),
+ ).toBe(true);
+ expect(
+ bypassInvokeScheduling({
+ channel: "device-link:remote-desktop:v1",
+ args: [{ op: "heartbeat" }],
+ }),
+ ).toBe(true);
+ expect(bypassInvokeScheduling({ channel: "maker:send", args: [] })).toBe(
+ false,
+ );
+ });
+});
diff --git a/packages/device-link/src/client.ts b/packages/device-link/src/client.ts
index 2656c3f23e..bbbe201a2e 100644
--- a/packages/device-link/src/client.ts
+++ b/packages/device-link/src/client.ts
@@ -1,4 +1,5 @@
-import { isPeerResetRetryableReadChannel } from './invokePolicy.js';
+import { isPeerResetRetryableReadChannel, isBackgroundInvoke, bypassInvokeScheduling } from './invokePolicy.js';
+import { InvokeScheduler } from './invokeScheduler.js';
import { encodeSharedTaskEnvelope, decodeSharedTaskEnvelope } from './sharedTaskEnvelope.js';
import { isSharedTaskPeer } from './sharedTaskPeer.js';
import { SHARED_TASK_RELAY_CAPABILITY } from '@cindy/device-link-protocol';
@@ -670,6 +671,7 @@ interface ReceiveStreamState {
// ─── 客户端实现 ───────────────────────────────────────────────────────────────
export class DeviceLinkClient {
+ private readonly invokeScheduler = new InvokeScheduler();
private readonly opts: DeviceLinkClientOptions;
private readonly timing: DeviceLinkTiming;
private readonly log: DeviceLinkLogger;
@@ -1341,11 +1343,15 @@ export class DeviceLinkClient {
/** 控制端:远程 invoke,等待 invoke-result */
async invoke(dst: string, payload: InvokePayload, timeoutMs?: number): Promise<InvokeResultPayload> {
- const env = await this.request(
+ if (this.status !== 'online') throw new DeviceLinkError('NOT_CONNECTED', 'not connected to relay');
+ const send = () => this.request(
{ v: PROTOCOL_VERSION, kind: 'invoke', dst, payload: requestSessionTagCatalog(payload) },
'invoke-result',
timeoutMs,
);
+ const env = await (bypassInvokeScheduling(payload) ? send() : this.invokeScheduler.run(
+ dst, isBackgroundInvoke(payload.channel), Math.min(timeoutMs ?? this.timing.requestTimeoutMs, 30_000), send,
+ ));
const result = env.payload as InvokeResultPayload;
return result.ok
? {
@@ -1648,6 +1654,7 @@ export class DeviceLinkClient {
}
private failAllPending(err: DeviceLinkError): void {
+ this.invokeScheduler.clear(err);
// pending 里的请求全部已经 sendEnvelope 成功(in-flight):打上标记,
// 让控制端的重试逻辑知道「请求可能已送达对端,只是响应丢了」,
// 与发送前本地拒绝的 NOT_CONNECTED 区分开。
@@ -1657,6 +1664,7 @@ export class DeviceLinkClient {
}
private failNonReliablePending(err: DeviceLinkError): void {
+ this.invokeScheduler.clear(err);
err.inFlight = true;
for (const [id, pending] of this.pending) {
if (pending.reliableDst) continue;
@@ -4614,6 +4622,7 @@ export class DeviceLinkClient {
}
private abandonReliablePending(dst: string, message: string): void {
+ this.invokeScheduler.cancel(dst, new DeviceLinkError('NOT_CONNECTED', message));
const peer = this.peerTransport.get(dst);
if (peer) {
if (peer.retryTimer) {
diff --git a/packages/device-link/src/invokePolicy.ts b/packages/device-link/src/invokePolicy.ts
index f2aac76408..fe18268382 100644
--- a/packages/device-link/src/invokePolicy.ts
+++ b/packages/device-link/src/invokePolicy.ts
@@ -2,6 +2,27 @@ import { INVOKE_TIMEOUT_OVERRIDES_MS } from './allowlist.js';
import { TASK_MIGRATION_CHANNEL } from './taskMigration.js';
import type { InvokePayload } from './protocol.js';
+/** These reads may wait behind current-task work. Not a retry or authorization policy. */
+const BACKGROUND_INVOKE_CHANNELS = new Set([
+ 'git-context:pr-refs:list',
+ 'git-context:pr-status',
+ 'local-db:sessions:list',
+ 'maker:schedule:list-sidebar-index-runs',
+ 'maker:usage:device-rows',
+]);
+
+export function isBackgroundInvoke(channel: string): boolean {
+ return BACKGROUND_INVOKE_CHANNELS.has(channel);
+}
+
+/** Control traffic must not wait behind business operations to maintain a link/lease. */
+export function bypassInvokeScheduling(payload: InvokePayload): boolean {
+ if (payload.channel === 'device-link:subscribe' || payload.channel === 'device-link:unsubscribe') return true;
+ const request = payload.args?.[0];
+ return payload.channel === 'device-link:remote-desktop:v1' && !!request &&
+ typeof request === 'object' && 'op' in request && request.op === 'heartbeat';
+}
+
/**
* mobile 侧 invoke 超时解析(优先级:mobile 精确表 → schedule 前缀规则 →
* 协议契约表 → undefined = client 默认 15s)。
diff --git a/packages/device-link/src/invokeScheduler.ts b/packages/device-link/src/invokeScheduler.ts
new file mode 100644
index 0000000000..2bac202f37
--- /dev/null
+++ b/packages/device-link/src/invokeScheduler.ts
@@ -0,0 +1,124 @@
+import { DeviceLinkError } from "./protocol.js";
+
+const MAX_ACTIVE = 8;
+const MAX_BACKGROUND_ACTIVE = 2;
+const MAX_QUEUED = 128;
+// Background refreshes cannot consume the last waiting positions for user actions.
+const MAX_BACKGROUND_QUEUED = 96;
+
+interface Job {
+ background: boolean;
+ start(): void;
+ cancel(error: DeviceLinkError): void;
+}
+interface PeerQueue {
+ active: number;
+ background: number;
+ jobs: Job[];
+}
+
+/** Local admission only: never retries or cancels an operation already sent. */
+export class InvokeScheduler {
+ private readonly peers = new Map<string, PeerQueue>();
+
+ run<T>(
+ deviceId: string,
+ background: boolean,
+ waitMs: number,
+ run: () => Promise<T>,
+ ): Promise<T> {
+ let peer = this.peers.get(deviceId);
+ if (!peer) {
+ peer = { active: 0, background: 0, jobs: [] };
+ this.peers.set(deviceId, peer);
+ }
+ const state = peer;
+ if (
+ state.jobs.length >= (background ? MAX_BACKGROUND_QUEUED : MAX_QUEUED)
+ ) {
+ return Promise.reject(
+ new DeviceLinkError(
+ "BACKPRESSURE",
+ "local remote invoke queue is full",
+ ),
+ );
+ }
+ return new Promise<T>((resolve, reject) => {
+ const queuedAt = Date.now();
+ const job: Job = {
+ background,
+ cancel: (error) => {
+ clearTimeout(timer);
+ reject(error);
+ },
+ start: () => {
+ clearTimeout(timer);
+ // A suspended app may resume before its expired timers run. Never send stale work.
+ if (Date.now() - queuedAt >= waitMs) {
+ reject(
+ new DeviceLinkError(
+ "BACKPRESSURE",
+ "remote invoke expired before dispatch",
+ ),
+ );
+ return;
+ }
+ state.active++;
+ if (background) state.background++;
+ let result: Promise<T>;
+ try {
+ result = run();
+ } catch (error) {
+ result = Promise.reject(error);
+ }
+ void result.then(resolve, reject).finally(() => {
+ state.active--;
+ if (background) state.background--;
+ this.drain(deviceId, state);
+ });
+ },
+ };
+ const timer = setTimeout(() => {
+ const index = state.jobs.indexOf(job);
+ if (index < 0) return;
+ state.jobs.splice(index, 1);
+ job.cancel(
+ new DeviceLinkError(
+ "BACKPRESSURE",
+ "remote invoke expired before dispatch",
+ ),
+ );
+ this.drain(deviceId, state);
+ }, waitMs);
+ state.jobs.push(job);
+ this.drain(deviceId, state);
+ });
+ }
+
+ /** Keep active slots until their promises settle, including across reconnects. */
+ cancel(deviceId: string, error: DeviceLinkError): void {
+ const state = this.peers.get(deviceId);
+ if (!state) return;
+ for (const job of state.jobs.splice(0)) {
+ // The transport may mark its error inFlight later; queued calls were never sent.
+ job.cancel(new DeviceLinkError(error.code, error.message));
+ }
+ this.drain(deviceId, state);
+ }
+
+ clear(error: DeviceLinkError): void {
+ for (const deviceId of this.peers.keys()) this.cancel(deviceId, error);
+ }
+
+ private drain(deviceId: string, state: PeerQueue): void {
+ while (state.active < MAX_ACTIVE && state.jobs.length) {
+ let index = state.jobs.findIndex((job) => !job.background);
+ if (index < 0) {
+ if (state.background >= MAX_BACKGROUND_ACTIVE) break;
+ index = 0;
+ }
+ state.jobs.splice(index, 1)[0].start();
+ }
+ if (!state.active && !state.jobs.length) this.peers.delete(deviceId);
+ }
+}
diff --git a/packages/maker-shared/src/__tests__/deviceLinkContract.test.ts b/packages/maker-shared/src/__tests__/deviceLinkContract.test.ts
index c72ce51731..8f95533819 100644
--- a/packages/maker-shared/src/__tests__/deviceLinkContract.test.ts
+++ b/packages/maker-shared/src/__tests__/deviceLinkContract.test.ts
@@ -160,6 +160,7 @@ describe('device-link shared contract', () => {
expect(isTransientRemoteError(Object.assign(new Error('buffer is full'), { code: 'BACKPRESSURE' }))).toBe(true);
expect(isTransientRemoteError(Object.assign(new Error('target offline'), { code: 'DEVICE_OFFLINE' }))).toBe(true);
expect(isTransientRemoteError('[DEVICE_LINK_TIMEOUT] no result')).toBe(true);
+ expect(isTransientRemoteError('[DEVICE_LINK_BUSY] queue full')).toBe(true);
// HTTP 层弱网错误(超时 / 离线 / RN 原生 fetch 原文)同属瞬时,必须可重试
expect(isTransientRemoteError(Object.assign(new Error('请求超时,请稍后重试'), { code: 'REQUEST_TIMEOUT' }))).toBe(true);
expect(isTransientRemoteError(Object.assign(new Error('网络连接不可用'), { code: 'NETWORK_UNAVAILABLE' }))).toBe(true);
diff --git a/packages/maker-shared/src/deviceLinkContract.ts b/packages/maker-shared/src/deviceLinkContract.ts
index 242fb7880a..7d93c82a01 100644
--- a/packages/maker-shared/src/deviceLinkContract.ts
+++ b/packages/maker-shared/src/deviceLinkContract.ts
@@ -439,6 +439,7 @@ const TRANSIENT_REMOTE_ERROR_MARKERS = [
'NOT_CONNECTED',
'LINK_NOT_OPEN',
'BACKPRESSURE',
+ 'DEVICE_LINK_BUSY',
'DEVICE_OFFLINE',
'DEVICE_LINK_TIMEOUT',
'INVOKE_TIMEOUT',
@@ -584,6 +585,9 @@ export function describeRemoteError(error: string | null): string | null {
if (error.includes('OFFER_EXPIRED')) return 'Codex 重置凭证已失效,请刷新额度后重新确认。';
return '操作条件已变化,请刷新后重新确认。';
}
+ if (error.includes('BACKPRESSURE') || error.includes('DEVICE_LINK_BUSY')) {
+ return '远端繁忙,请稍后重试。';
+ }
if (TRANSIENT_REMOTE_ERROR_MARKERS.some((marker) => error.includes(marker))) {
return '网络或被控端暂时不可用,可以稍后重新同步。';
}
diff --git a/packages/maker-shared/src/errorRedaction.test.ts b/packages/maker-shared/src/errorRedaction.test.ts
index f9011b57b0..22960d319f 100644
--- a/packages/maker-shared/src/errorRedaction.test.ts
+++ b/packages/maker-shared/src/errorRedaction.test.ts
@@ -260,7 +260,7 @@ describe('isGatewayProxyTokenInvalidError', () => {
describe('agent error envelopes shared by desktop and mobile', () => {
- it.each(['REMOTE_LOCAL_ONLY_PROVIDER', 'DEVICE_LINK_MEDIA_TRANSFER_FAILED', 'MCP_APPROVAL_CONFIRMATION_TIMEOUT', 'AUTO_REVIEW_UNAVAILABLE'])(
+ it.each(['REMOTE_LOCAL_ONLY_PROVIDER', 'DEVICE_LINK_MEDIA_TRANSFER_FAILED', 'DEVICE_LINK_BUSY', 'MCP_APPROVAL_CONFIRMATION_TIMEOUT', 'AUTO_REVIEW_UNAVAILABLE'])(
'parses %s directly and inside an IPC error', code => {
for (const prefix of ['', "Error invoking remote method 'maker:send': Error: "]) {
expect(parseAgentErrorCode(`${prefix}[${code}] first line\nsecond line`)).toEqual({ code, fallback: 'first line\nsecond line' });
diff --git a/packages/maker-shared/src/errorRedaction.ts b/packages/maker-shared/src/errorRedaction.ts
index 7f62c264f4..8efac54c9e 100644
--- a/packages/maker-shared/src/errorRedaction.ts
+++ b/packages/maker-shared/src/errorRedaction.ts
@@ -203,6 +203,7 @@ export function isResponsesLiteParallelToolCallsError(message: string): boolean
}
const AGENT_CHAT_ERROR_CODES: ReadonlySet<string> = new Set([
+ 'DEVICE_LINK_BUSY',
'DEVICE_LINK_CONTROL_DISABLED',
'DEVICE_LINK_MEDIA_TRANSFER_FAILED',
'AUTO_REVIEW_UNAVAILABLE',
diff --git a/packages/maker-shared/src/taskTags.test.ts b/packages/maker-shared/src/taskTags.test.ts
index 470b94eb24..a181582c53 100644
--- a/packages/maker-shared/src/taskTags.test.ts
+++ b/packages/maker-shared/src/taskTags.test.ts
@@ -4,6 +4,7 @@ import {
reconcileTaskTags,
taskTagEditRevision,
taskTagNameKey,
+ taskTagErrorKey,
TASK_TAG_PRESETS,
type TaskTag,
} from './taskTags';
@@ -13,6 +14,16 @@ const tag = (
favoriteOrder: number | null = null,
): TaskTag => ({ id, name: id, color, favoriteOrder, revision: 1 });
+it.each([
+ { code: 'BACKPRESSURE', message: 'queue full' },
+ { error: { code: 'BACKPRESSURE', message: 'queue full' } },
+ new Error("Error invoking remote method 'device-link:invoke': Error: [DEVICE_LINK_BUSY] queue full"),
+])('distinguishes busy from offline for reads and edits', (error) => {
+ expect(taskTagErrorKey(error, 'get')).toBe('remoteBusy');
+ expect(taskTagErrorKey(error, 'attach')).toBe('remoteBusy');
+ expect(taskTagErrorKey({ code: 'NOT_CONNECTED' }, 'get')).toBe('offline');
+});
+
it('keeps default names localized after recoloring without translating custom names', () => {
for (const color of ['red', 'orange', 'yellow', 'green', 'blue', 'purple', 'gray']) {
const original = {
diff --git a/packages/maker-shared/src/taskTags.ts b/packages/maker-shared/src/taskTags.ts
index a044be117d..acfbc097ad 100644
--- a/packages/maker-shared/src/taskTags.ts
+++ b/packages/maker-shared/src/taskTags.ts
@@ -164,6 +164,8 @@ export function taskTagErrorKey(error: unknown, action: TaskTagRequest['action']
value && typeof value === 'object'
? String(value.message ?? value.error?.message ?? error)
: String(error);
+ if (['BACKPRESSURE', 'DEVICE_LINK_BUSY'].includes(code) ||
+ /\[(?:BACKPRESSURE|DEVICE_LINK_BUSY)\]/.test(message)) return 'remoteBusy';
if (
['CHANNEL_NOT_ALLOWED', 'UNKNOWN_CHANNEL', 'UNSUPPORTED_CHANNEL', 'METHOD_NOT_FOUND'].includes(
code,