Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): fence quota ownership and replay after peer recovery
qianboa36cc82119c8
diff --git a/apps/desktop/src/main/device-link/__tests__/transportTimeoutReopen.test.ts b/apps/desktop/src/main/device-link/__tests__/transportTimeoutReopen.test.tsindex 525c14069a..8e2fb0affe 100644--- a/apps/desktop/src/main/device-link/__tests__/transportTimeoutReopen.test.ts+++ b/apps/desktop/src/main/device-link/__tests__/transportTimeoutReopen.test.ts@@ -298,3 +298,28 @@ describe('createTransportTimeoutReopenLoop', () => {expect(loop.isActive('dev-d')).toBe(false);});});++describe('successful recovery notifications', () => {+ beforeEach(() => vi.useFakeTimers());+ afterEach(() => vi.useRealTimers());+ it('notifies only the recovered peer after a failed first attempt', async () => {+ const onReopened = vi.fn();+ const reopen = vi.fn().mockRejectedValueOnce(new Error('busy')).mockResolvedValue(undefined);+ const loop = createTransportTimeoutReopenLoop({ reopen, onReopened, shouldAbort: () => false, baseDelayMs: 10 });+ loop.trigger('a');+ await vi.advanceTimersByTimeAsync(0);+ expect(onReopened).not.toHaveBeenCalled();+ await vi.advanceTimersByTimeAsync(10);+ expect(onReopened.mock.calls).toEqual([['a']]);+ expect(loop.isActive('a')).toBe(false);+ expect(loop.isActive('b')).toBe(false);+ });+ it('ignores success from a cancelled generation', async () => {+ let resolve!: () => void;+ const onReopened = vi.fn();+ const loop = createTransportTimeoutReopenLoop({ reopen: () => new Promise<void>(r => { resolve = r; }), onReopened, shouldAbort: () => false });+ loop.trigger('a'); loop.cancel('a');+ resolve(); await vi.advanceTimersByTimeAsync(0);+ expect(onReopened).not.toHaveBeenCalled();+ });+});diff --git a/apps/desktop/src/main/device-link/index.ts b/apps/desktop/src/main/device-link/index.tsindex bc8a9c79a7..edb311512e 100644--- a/apps/desktop/src/main/device-link/index.ts+++ b/apps/desktop/src/main/device-link/index.ts@@ -388,6 +388,7 @@ let sharedHostSourceEpoch = 0;const transportTimeoutReopen = createTransportTimeoutReopenLoop({// Local Main→Renderer projection only; the relay and neighboring peers remain online.onReset: (deviceId) => broadcast(DEVICE_LINK_PUSH.PEER_LINK_RESET, { deviceId }),+ onReopened: (deviceId) => broadcast(DEVICE_LINK_PUSH.PEER_LINK_REOPENED, { deviceId }),reopen: async (deviceId) => {await openRemoteLink(deviceId);// link 重建成功后定向补一次订阅重放:transport-timeout 场景被控端保留了diff --git a/apps/desktop/src/main/device-link/transportTimeoutReopen.ts b/apps/desktop/src/main/device-link/transportTimeoutReopen.tsindex 1f727c9438..55bb6283eb 100644--- a/apps/desktop/src/main/device-link/transportTimeoutReopen.ts+++ b/apps/desktop/src/main/device-link/transportTimeoutReopen.ts@@ -17,6 +17,8 @@ type Timer = ReturnType<typeof setTimeout>;export interface TransportTimeoutReopenDeps {/** Local view invalidation, including another reset while reopen is already pending. */onReset?(deviceId: string): void;+ /** Notify only a still-current, authorized successful recovery. */+ onReopened?(deviceId: string): void;/** 重开链路(通常是 openRemoteLink;自带同 device in-flight 去重)。 */reopen(deviceId: string): Promise<unknown>;/** 返回 true 则终止该设备的循环(撤权 / client 不在 / 待命态 / relay 离线)。 */@@ -155,7 +157,9 @@ export function createTransportTimeoutReopenLoop(// link-accept 已达成:被控端 sendLinkAccept 会清扫陈旧前缀并重放 live// pending,双向续传由传输层接管,循环使命完成。仅限本代:晚到的// 旧代成功不得关掉新一代正在进行的恢复。+ if (!isCurrent(deviceId, entry)) return;finishEntry(deviceId, entry);+ if (!deps.shouldAbort(deviceId)) deps.onReopened?.(deviceId);},(err) => {if (!isCurrent(deviceId, entry)) return; // 被 cancel/dispose 或已换代diff --git a/apps/desktop/src/main/model-access/index.ts b/apps/desktop/src/main/model-access/index.tsindex f740d59547..f7a3a3cac4 100644--- a/apps/desktop/src/main/model-access/index.ts+++ b/apps/desktop/src/main/model-access/index.ts@@ -1,4 +1,4 @@-import { noteQuotaCredentialStatus } from './quotaCredentialState.js';+import { cloudQuotaOwnerKey, noteQuotaCredentialStatus } from './quotaCredentialState.js';import { createByokCache } from './byokCache.js';import { byokSnapshotSecretIo } from '../secrets/providerSecretStore.js';import { registerByokIpc } from './byokIpc.js';@@ -408,7 +408,7 @@ function getSync(): CredentialsSync {onStatusChange: (status) => {const auth = authManager.getAuthState();noteQuotaCredentialStatus(- auth.mode === 'cloud' && auth.dataOwnerId ? `cloud:${auth.dataOwnerId}` : null,+ cloudQuotaOwnerKey(auth),status,);if (['failed', 'disabled', 'unsupported', 'idle'].includes(status.state)) {diff --git a/apps/desktop/src/main/model-access/quotaCredentialState.ts b/apps/desktop/src/main/model-access/quotaCredentialState.tsindex f8d3fad6bc..6b8b90d44c 100644--- a/apps/desktop/src/main/model-access/quotaCredentialState.ts+++ b/apps/desktop/src/main/model-access/quotaCredentialState.ts@@ -1,3 +1,4 @@+import type { AuthState } from '../authManager.js';import type { ModelAccessStatus } from '../../shared/modelAccess.js';// Process-local readiness only: persisted credentials never count as a successful@@ -30,3 +31,9 @@ export function onQuotaCredentialSourceChanged(listener: (ownerKey: string | nullisteners.add(listener);return () => { listeners.delete(listener); };}++/** Owner generation also fences same-membership realm switches and repairs. */+export function cloudQuotaOwnerKey(auth: Pick<AuthState, 'mode' | 'dataOwnerId' | 'ownerGeneration'>): string | null {+ return auth.mode === 'cloud' && auth.dataOwnerId+ ? `cloud:${auth.dataOwnerId}:${auth.ownerGeneration}` : null;+}diff --git a/apps/desktop/src/main/usage/__tests__/organizationQuotaRefresh.test.ts b/apps/desktop/src/main/usage/__tests__/organizationQuotaRefresh.test.tsindex 87e260241a..55a861073d 100644--- a/apps/desktop/src/main/usage/__tests__/organizationQuotaRefresh.test.ts+++ b/apps/desktop/src/main/usage/__tests__/organizationQuotaRefresh.test.ts@@ -1,6 +1,6 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';const mocks = vi.hoisted(() => ({- auth: { mode: 'cloud', dataOwnerId: 'owner-a', user: { id: 'member-a', membershipKind: 'org' } },+ auth: { mode: 'cloud', ownerGeneration: 1, dataOwnerId: 'owner-a', user: { id: 'member-a', membershipKind: 'org' } },endpoint: 'https://gateway.example.test',managed: vi.fn(), outbound: vi.fn(), broadcast: vi.fn(),}));@@ -17,10 +17,10 @@ vi.mock('../organizationAccountUsage.js', () => ({ readOrganizationAccountUsage:const quota = { spend: 12, maxBudget: 100, currency: 'CNY', todaySpend: null, fetchedAt: 1 };beforeEach(async () => {vi.resetModules(); vi.useFakeTimers(); vi.clearAllMocks();- mocks.auth = { mode: 'cloud', dataOwnerId: 'owner-a', user: { id: 'member-a', membershipKind: 'org' } };+ mocks.auth = { mode: 'cloud', ownerGeneration: 1, dataOwnerId: 'owner-a', user: { id: 'member-a', membershipKind: 'org' } };mocks.endpoint = 'https://gateway.example.test';const state = await import('../../model-access/quotaCredentialState');- state.noteQuotaCredentialStatus('cloud:owner-a', { state: 'ok', source: 'server', endpoint: mocks.endpoint, accountTier: null });+ state.noteQuotaCredentialStatus('cloud:owner-a:1', { state: 'ok', source: 'server', endpoint: mocks.endpoint, accountTier: null });mocks.managed.mockResolvedValue(quota);mocks.outbound.mockResolvedValue({ ok: true, json: async () => ({ spend: 2, max_budget: 20, results: [] }) });});@@ -55,6 +55,21 @@ describe('Cindy AI enterprise quota refresh', () => {resolve(quota); await pending;expect(api.readClaudeAccountUsageSnapshot()).toBeNull();});+ it('rejects an old realm response with the same membership and endpoint after sync fails', async () => {+ let resolve!: (value: unknown) => void;+ mocks.managed.mockImplementationOnce(() => new Promise(r => { resolve = r; }));+ const api = await import('../claudeAccountUsage');+ const pending = api.triggerClaudeAccountUsageRefresh(true);+ mocks.auth.ownerGeneration++;+ const state = await import('../../model-access/quotaCredentialState');+ state.noteQuotaCredentialStatus('cloud:owner-a:2', { state: 'failed', source: 'server', endpoint: mocks.endpoint, accountTier: null });+ mocks.managed.mockResolvedValue(null);+ resolve(quota); await pending;+ await vi.advanceTimersByTimeAsync(0);+ expect(api.readClaudeAccountUsageSnapshot()).toBeNull();+ expect(api.readClaudeAccountQuotaClear()).toEqual({ quotaState: 'invalidated' });+ expect(state.quotaCredentialsReady('cloud:owner-a:2', mocks.endpoint)).toBe(false);+ });it('clears and broadcasts an unlimited result after a finite quota was cached', async () => {const api = await import('../claudeAccountUsage');await api.triggerClaudeAccountUsageRefresh(true);@@ -83,19 +98,19 @@ describe('Cindy AI enterprise quota refresh', () => {describe('quota gateway migration boundary', () => {it('blocks persisted legacy credentials before this process completes credential sync', async () => {const state = await import('../../model-access/quotaCredentialState');- state.noteQuotaCredentialStatus('cloud:owner-a', { state: 'idle', source: 'server', endpoint: mocks.endpoint, accountTier: null });+ state.noteQuotaCredentialStatus('cloud:owner-a:1', { state: 'idle', source: 'server', endpoint: mocks.endpoint, accountTier: null });mocks.managed.mockResolvedValue(undefined);const api = await import('../claudeAccountUsage');await api.triggerClaudeAccountUsageRefresh(true);expect(mocks.outbound).not.toHaveBeenCalled();expect(api.readClaudeAccountUsageSnapshot()).toBeNull();- state.noteQuotaCredentialStatus('cloud:owner-a', { state: 'ok', source: 'server', endpoint: mocks.endpoint, accountTier: null });+ state.noteQuotaCredentialStatus('cloud:owner-a:1', { state: 'ok', source: 'server', endpoint: mocks.endpoint, accountTier: null });await vi.waitFor(() => expect(api.readClaudeAccountUsageSnapshot()?.maxBudget).toBe(20));});it('reads managed quota before credential sync without contacting the persisted gateway', async () => {const state = await import('../../model-access/quotaCredentialState');- state.noteQuotaCredentialStatus('cloud:owner-a', { state: 'idle', source: 'server', endpoint: mocks.endpoint, accountTier: null });+ state.noteQuotaCredentialStatus('cloud:owner-a:1', { state: 'idle', source: 'server', endpoint: mocks.endpoint, accountTier: null });const api = await import('../claudeAccountUsage');await api.triggerClaudeAccountUsageRefresh(true);expect(api.readClaudeAccountUsageSnapshot()).toEqual(quota);@@ -110,7 +125,7 @@ describe('quota gateway migration boundary', () => {mocks.managed.mockResolvedValue(null);mocks.endpoint = 'https://new-gateway.example.test';const state = await import('../../model-access/quotaCredentialState');- state.noteQuotaCredentialStatus('cloud:owner-a', { state: 'ok', source: 'server', endpoint: mocks.endpoint, accountTier: null });+ state.noteQuotaCredentialStatus('cloud:owner-a:1', { state: 'ok', source: 'server', endpoint: mocks.endpoint, accountTier: null });expect(api.readClaudeAccountUsageSnapshot()).toBeNull();expect(api.readClaudeAccountQuotaClear()).toEqual({ quotaState: 'invalidated' });expect(mocks.broadcast).toHaveBeenLastCalledWith('usage:claude-account-changed', null);@@ -128,7 +143,7 @@ describe('quota gateway migration boundary', () => {mocks.managed.mockResolvedValue(null);mocks.endpoint = 'https://new-gateway.example.test';const state = await import('../../model-access/quotaCredentialState');- state.noteQuotaCredentialStatus('cloud:owner-a', { state: 'ok', source: 'server', endpoint: mocks.endpoint, accountTier: null });+ state.noteQuotaCredentialStatus('cloud:owner-a:1', { state: 'ok', source: 'server', endpoint: mocks.endpoint, accountTier: null });complete({ ok: true, json: async () => ({ spend: 99, max_budget: 100 }) });await pending;expect(api.readClaudeAccountUsageSnapshot()).toBeNull();diff --git a/apps/desktop/src/main/usage/claudeAccountUsage.ts b/apps/desktop/src/main/usage/claudeAccountUsage.tsindex 02024554ed..d0daf992b6 100644--- a/apps/desktop/src/main/usage/claudeAccountUsage.ts+++ b/apps/desktop/src/main/usage/claudeAccountUsage.ts@@ -1,4 +1,4 @@-import { quotaCredentialsReady, quotaCredentialGeneration, onQuotaCredentialSourceChanged } from '../model-access/quotaCredentialState.js';+import { cloudQuotaOwnerKey, quotaCredentialsReady, quotaCredentialGeneration, onQuotaCredentialSourceChanged } from '../model-access/quotaCredentialState.js';import type { ClaudeQuotaClear } from '../../shared/claudeQuotaState.js';import { readOrganizationAccountUsage } from './organizationAccountUsage.js';/**@@ -125,7 +125,7 @@ function currentQuotaOwner(): QuotaOwner | null {const auth = getAuthState();if (auth.mode === 'cloud') {if (auth.user?.membershipKind !== 'org' || !auth.dataOwnerId) return null;- return { key: `cloud:${auth.dataOwnerId}`, authenticatedUserId: auth.user.id };+ return { key: cloudQuotaOwnerKey(auth)!, authenticatedUserId: auth.user.id };}if (auth.mode === 'local' && auth.dataOwnerId) {return { key: `local:${auth.dataOwnerId}` };diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.tsindex a02d4208a2..47f262f91d 100644--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@ -851,6 +851,7 @@ const fanOutProviderShareOpenManage = createIpcFanOut(PROVIDER_SHARE_IPC.OPEN_MAconst fanOutDeviceLinkOwnershipChanged = createIpcFanOut('device-link:ownership-changed');// 控制端:目标设备「无响应」熔断状态翻转(payload = { deviceId, unresponsive })const fanOutDeviceLinkResponsivenessChanged = createIpcFanOut('device-link:responsiveness-changed');+const fanOutDeviceLinkPeerLinkReopened = createIpcFanOut(DEVICE_LINK_PUSH.PEER_LINK_REOPENED);const fanOutDeviceLinkPeerLinkReset = createIpcFanOut(DEVICE_LINK_PUSH.PEER_LINK_RESET);// device-link 模型列表写穿:被控端本地 main → 自身 renderer,把控制端写穿的草稿 / 会话 pref@@ -4676,6 +4677,7 @@ contextBridge.exposeInMainWorld('electronAPI', {/** 控制端:目标设备「无响应」熔断状态翻转,payload: { deviceId, unresponsive } */onResponsivenessChanged: fanOutDeviceLinkResponsivenessChanged,onPeerLinkReset: fanOutDeviceLinkPeerLinkReset,+ onPeerLinkReopened: fanOutDeviceLinkPeerLinkReopened,/*** 控制端:远程会话镜像的本地冷缓存(main 落 userData,见 main/device-link/mirrorCacheStore.ts)。* 只做首屏加速,非权威;fresh 数据一到由 renderer 整体接管。diff --git a/apps/desktop/src/preload/sidebarWindowPreload.ts b/apps/desktop/src/preload/sidebarWindowPreload.tsindex fdc43286c1..eb2578aefb 100644--- a/apps/desktop/src/preload/sidebarWindowPreload.ts+++ b/apps/desktop/src/preload/sidebarWindowPreload.ts@@ -157,6 +157,8 @@ contextBridge.exposeInMainWorld('electronAPI', {onPayload(DEVICE_LINK_PUSH.CONTROL_TARGET_CHANGED, cb),onResponsivenessChanged: (cb: (payload: unknown) => void): (() => void) =>onPayload(DEVICE_LINK_PUSH.RESPONSIVENESS_CHANGED, cb),+ onPeerLinkReopened: (cb: (payload: unknown) => void): (() => void) =>+ onPayload(DEVICE_LINK_PUSH.PEER_LINK_REOPENED, cb),onPeerLinkReset: (cb: (payload: unknown) => void): (() => void) =>onPayload(DEVICE_LINK_PUSH.PEER_LINK_RESET, cb),mirrorCache: {diff --git a/apps/desktop/src/renderer/__tests__/useRemoteDeviceUsage.test.ts b/apps/desktop/src/renderer/__tests__/useRemoteDeviceUsage.test.tsindex 53bd995089..63718be247 100644--- a/apps/desktop/src/renderer/__tests__/useRemoteDeviceUsage.test.ts+++ b/apps/desktop/src/renderer/__tests__/useRemoteDeviceUsage.test.ts@@ -36,6 +36,7 @@ type PushListener = (const mocks = vi.hoisted(() => ({invoke: vi.fn<(deviceId: string, channel: string, args: unknown[]) => Promise<unknown>>(),pushListeners: [] as PushListener[],+ reopenedListeners: [] as Array<(value: { deviceId: string }) => void>,peerResetListeners: [] as Array<(value: { deviceId: string }) => void>,statusListeners: [] as Array<(value: { status: 'online' | 'connecting' | 'stopped' }) => void>,presenceListeners: [] as Array<(value: { deviceId: string; online: boolean }) => void>,@@ -63,11 +64,16 @@ beforeEach(() => {mocks.presenceListeners.length = 0;mocks.statusListeners.length = 0;mocks.peerResetListeners.length = 0;+ mocks.reopenedListeners.length = 0;Object.defineProperty(window, 'electronAPI', {configurable: true,value: {deviceLink: {invoke: mocks.invoke,+ onPeerLinkReopened: (listener: (value: { deviceId: string }) => void) => {+ mocks.reopenedListeners.push(listener);+ return () => { mocks.reopenedListeners = mocks.reopenedListeners.filter(item => item !== listener); };+ },onPeerLinkReset: (listener: (value: { deviceId: string }) => void) => {mocks.peerResetListeners.push(listener);return () => { mocks.peerResetListeners = mocks.peerResetListeners.filter(item => item !== listener); };@@ -463,3 +469,25 @@ it('rereads only the reset peer without needing relay or presence changes', asynb.unmount();expect(mocks.peerResetListeners).toHaveLength(0);});++it('rereads the recovered peer after the initial reset read failed, leaving its neighbor untouched', async () => {+ const finite = { spend: 1, maxBudget: 10, currency: 'CNY', fetchedAt: 1 };+ mocks.invoke.mockResolvedValue(finite);+ const a = renderHook(() => useRemoteClaudeAccountUsage('retry-a'));+ const b = renderHook(() => useRemoteClaudeAccountUsage('retry-b'));+ await flushMicrotasks();+ mocks.invoke.mockRejectedValueOnce(new Error('first open failed'));+ act(() => mocks.peerResetListeners.forEach(cb => cb({ deviceId: 'retry-a' })));+ await flushMicrotasks();+ expect(a.result.current).toEqual(finite);+ mocks.invoke.mockClear();+ mocks.invoke.mockResolvedValue({ quotaState: 'invalidated' });+ act(() => mocks.reopenedListeners.forEach(cb => cb({ deviceId: 'retry-a' })));+ await flushMicrotasks();+ expect(a.result.current).toBeNull();+ expect(b.result.current).toEqual(finite);+ expect(mocks.invoke).toHaveBeenCalledTimes(1);+ expect(mocks.invoke.mock.calls[0]?.[0]).toBe('retry-a');+ a.unmount(); b.unmount();+ expect(mocks.reopenedListeners).toHaveLength(0);+});diff --git a/apps/desktop/src/renderer/features/device-link/useDeviceLinkReconnectEpoch.ts b/apps/desktop/src/renderer/features/device-link/useDeviceLinkReconnectEpoch.tsindex cd2e74bdcd..83af65d1eb 100644--- a/apps/desktop/src/renderer/features/device-link/useDeviceLinkReconnectEpoch.ts+++ b/apps/desktop/src/renderer/features/device-link/useDeviceLinkReconnectEpoch.ts@@ -36,10 +36,15 @@ export function useDeviceLinkReconnectEpoch(deviceId: string | undefined): numbeif (event.deviceId === deviceId) bump();});+ const offReopened = window.electronAPI.deviceLink.onPeerLinkReopened?.((event) => {+ if (event.deviceId === deviceId) bump();+ });+return () => {offPresence();offStatus();offPeerReset?.();+ offReopened?.();};}, [deviceId]);diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex e2e99b8b24..20156e115a 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -4061,6 +4061,7 @@ interface ElectronAPI {/** 「保持电脑唤醒」在其它共享 userData 实例被翻转后推送 */onKeepAwakeChanged: (cb: (payload: { keepAwake: boolean }) => void) => () => void;/** Main 本地投影:单个 peer 的恢复作废旧内容就绪证据,不代表 relay 离线。 */+ onPeerLinkReopened?: (cb: (payload: { deviceId: string }) => void) => () => void;onPeerLinkReset?: (cb: (payload: { deviceId: string }) => void) => () => void;/** 控制端:目标设备「无响应」熔断状态翻转(弱网 / 对端卡死;presence 可能仍在线) */onResponsivenessChanged: (diff --git a/apps/desktop/src/shared/deviceLinkIpc.ts b/apps/desktop/src/shared/deviceLinkIpc.tsindex d6b3bfda02..425bebd4cf 100644--- a/apps/desktop/src/shared/deviceLinkIpc.ts+++ b/apps/desktop/src/shared/deviceLinkIpc.ts@@ -61,6 +61,8 @@ export const DEVICE_LINK_INVOKE = {export const DEVICE_LINK_PUSH = {/** Local peer recovery invalidates content readiness; payload: { deviceId }. Not a wire push. */PEER_LINK_RESET: 'device-link:peer-link-reset',+ /** Local recovery succeeded; payload: { deviceId }. Not a wire push. */+ PEER_LINK_REOPENED: 'device-link:peer-link-reopened',/** 同账号某设备 presence 变化(上线/下线/开关/busy),payload: PresenceSnapshot */PRESENCE_CHANGED: 'device-link:presence-changed',/** 本机 relay 连接状态变化,payload: { status: 'stopped'|'connecting'|'online' } */diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.mdindex ed4886b129..4eb8b3ad26 100644--- a/docs/dev-rules/protocol-compatibility.md+++ b/docs/dev-rules/protocol-compatibility.md@@ -1769,3 +1769,6 @@ PC 同源 ghostPermissionItems 声明摘要投影并排除 tool,以请求 loca`maker:usage:account('claude-code', 'cindy-quota-state-v1')` 为可选读取能力:有限额度保持原快照,权威不限额返回 `{ quotaState: 'unlimited' }`,暂无当前账号快照返回 null。无该能力参数的旧消费者仍只收到快照/null;旧主机忽略该参数,新消费者对其 null 保留旧缓存。本地重新挂载和远程读取均查询该状态,避免错过 clear 推送;仅权威 clear 可淘汰同账号缓存。企业凭据迁移:`/quota` 查询不依赖本地推理凭据;仅在当前进程、当前账号已成功同步服务端凭据,且实际 endpoint 与本次同步一致时,允许 404/明确 501 后的旧直连回退。持久化凭据不能作为本轮同步成功的证明。网关 endpoint 或身份代次变化时,失效当前账号额度并丢弃旧代次在途结果;失效结果通过既有 null push 通知,可选状态读取返回 `{ quotaState: 'invalidated' }`,与 unavailable null 区分。新本地/远程消费者将 invalidated 和 unlimited 都作为权威清缓存;未携带能力参数的旧消费者保持 snapshot/null 返回。此处不变更凭据存储、推理回退或额度计算口径。++额度身份隔离使用主进程 `ownerGeneration` 与 `dataOwnerId`,覆盖同 membership 跨认证 realm 切换及同账号修复;凭据状态与额度快照使用同一身份键。+远程 transport-timeout 退避重连成功后,Main 通过本地 `device-link:peer-link-reopened` 推送 `{ deviceId }`,preload 暴露可选 `onPeerLinkReopened`,仅目标设备触发排队补读。被取消的重连代次不发通知。该事件不进入 relay wire、不增加远端 IPC allowlist,也不改变 Mobile/旧消费者的请求协议。