Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(provider-group): 为转分享同步增加离线退避并抑制重复重试
DavidShenc50f46fea234
diff --git a/apps/desktop/src/main/provider-group/__tests__/reshare.test.ts b/apps/desktop/src/main/provider-group/__tests__/reshare.test.tsindex 9956d7c0eb..58135fe4c3 100644--- a/apps/desktop/src/main/provider-group/__tests__/reshare.test.ts+++ b/apps/desktop/src/main/provider-group/__tests__/reshare.test.ts@@ -63,6 +63,7 @@ function setup(options: {let states = { ...(options.states ?? {}) };const responses: unknown[] = [];const cleanups: Record<string, string> = {};+ const availability = new Map<string, 'unknown' | 'online' | 'offline' | 'paused' | 'removed'>();let cleanupSeq = 0;const invoke = vi.fn(async (_agentDeviceId: string, request: unknown) => {const input = request as { entries: Array<{ key: string }>; batch?: { id: string; index: number; count: number } };@@ -75,7 +76,7 @@ function setup(options: {responses.push(response);return response;});- const readCaps = vi.fn(async () => options.caps ?? CAPS);+ const readCaps = vi.fn<(agentDeviceId: string) => Promise<RemoteAgentCaps>>(async () => options.caps ?? CAPS);const changed = vi.fn();const completeCleanup = vi.fn(async (device: string, token: string) => {if (cleanups[device] === token) delete cleanups[device];@@ -84,12 +85,13 @@ function setup(options: {listGroups: () => groups,ownedShares: () => shares,pendingCleanups: () => cleanups,+ shareAvailability: (device: string) => availability.get(device) ?? 'unknown',completeCleanup,readCaps,invoke,changed,now: () => now,- log: { warn: vi.fn() },+ log: { info: vi.fn(), debug: vi.fn(), warn: vi.fn() },};let reshare = createProviderGroupReshare(deps);instances.push(reshare);@@ -101,6 +103,8 @@ function setup(options: {changed,completeCleanup,cleanups,+ availability,+ log: deps.log,setGroups: (next: Record<string, ProviderGroupConfig>) => {// 生产中由 writeProviderGroup 与移出组同一事务持久记下(真实落盘回归在 stores.test.ts)。const shared = (configs: Record<string, ProviderGroupConfig>) => new Set(Object.values(configs)@@ -126,6 +130,149 @@ afterEach(() => {});describe('provider group reshare (group computer side)', () => {+ // #6961 / unit: exercise the real scheduler with an unreachable peer and fake time.+ // Existing tests cover only one failure, not repeated refreshes, backoff, recovery or log volume.+ // Observable results: outgoing caps/reshare requests, retained cleanup barriers and diagnostic logs.+ // Standalone vitest run on Windows: under 5s; see the verification report for the final timing.+ it.each(['report', 'cleanup'] as const)('backs off repeated %s failures and resets after success', async (kind) => {+ vi.useFakeTimers();+ const env = setup();+ if (kind === 'cleanup') env.setGroups({});+ env.readCaps.mockRejectedValue(new Error('offline'));+ await env.reshare.sync('startup');+ // First two failures wait a minute; then 5, 10, 20 and at most 30 minutes.+ for (const minutes of [1, 1, 5, 10, 20, 30, 30]) {+ const before = env.readCaps.mock.calls.length;+ env.advance(minutes * 60_000 - 1);+ await vi.advanceTimersByTimeAsync(minutes * 60_000 - 1);+ await env.reshare.sync('received');+ expect(env.readCaps).toHaveBeenCalledTimes(before);+ env.advance(1);+ await vi.advanceTimersByTimeAsync(1);+ expect(env.readCaps).toHaveBeenCalledTimes(before + 1);+ }+ expect(env.log.info).toHaveBeenCalledTimes(1);+ expect(env.log.debug).toHaveBeenCalledTimes(7);+ env.readCaps.mockResolvedValue(CAPS);+ env.advance(30 * 60_000);+ await vi.advanceTimersByTimeAsync(30 * 60_000);+ expect(env.log.info).toHaveBeenLastCalledWith('provider group: reshare sync recovered', expect.any(Object));+ if (kind === 'cleanup') {+ expect(env.cleanups).toEqual({});+ expect(vi.getTimerCount()).toBe(0);+ } else {+ env.readCaps.mockRejectedValue(new Error('offline'));+ await env.reshare.sync('manual', { force: true });+ const before = env.readCaps.mock.calls.length;+ env.advance(60_000);+ await vi.advanceTimersByTimeAsync(60_000);+ expect(env.readCaps).toHaveBeenCalledTimes(before + 1);+ }+ });++ it('does not let failure-triggered refreshes or view reads bypass backoff, but sends a changed list once', async () => {+ vi.useFakeTimers();+ const env = setup();+ env.readCaps.mockImplementation(async () => {+ // remoteBackgroundInvoke refreshes received shares after a link-open failure.+ env.reshare.kick('received');+ throw new Error('offline');+ });+ await env.reshare.sync('startup');+ env.advance(1_000);+ await vi.advanceTimersByTimeAsync(1_000);+ expect(env.readCaps).toHaveBeenCalledTimes(1);+ env.advance(15_000);+ await vi.advanceTimersByTimeAsync(15_000);+ env.reshare.refreshIfStale();+ await env.reshare.sync('settled');+ expect(env.readCaps).toHaveBeenCalledTimes(1);+ env.setShares([owned([{ memberId: 'carol', displayName: 'Carol' }])]);+ env.reshare.kick('owned');+ env.advance(1_000);+ await vi.advanceTimersByTimeAsync(1_000);+ expect(env.readCaps).toHaveBeenCalledTimes(2);+ env.advance(1_000);+ await vi.advanceTimersByTimeAsync(1_000);+ expect(env.readCaps).toHaveBeenCalledTimes(2);+ });++ it.each(['offline', 'paused'] as const)('wakes only the recovered peer after %s and retains cleanup across restart', async (status) => {+ vi.useFakeTimers();+ const env = setup({ groups: { anthropic: { strategy: 'least', autoSwitch: true,+ members: [FRIEND, member('share:a2:anthropic', 'share', 'share:a2')] } } });+ env.availability.set('share:a1', status);+ env.availability.set('share:a2', 'offline');+ env.readCaps.mockRejectedValue(new Error('offline'));+ await env.reshare.sync('startup');+ env.setGroups({});+ await env.reshare.sync('removed');+ env.restart();+ await env.reshare.sync('restart');+ expect(Object.keys(env.cleanups).sort()).toEqual(['share:a1', 'share:a2']);+ const before = env.readCaps.mock.calls.length;+ env.availability.set('share:a1', 'online');+ env.readCaps.mockResolvedValue(CAPS);+ await env.reshare.sync('received');+ expect(env.readCaps.mock.calls.slice(before)).toEqual([['share:a1']]);+ expect(env.invoke).toHaveBeenLastCalledWith('share:a1', { op: 'reshare', entries: [] });+ expect(Object.keys(env.cleanups)).toEqual(['share:a2']);+ });++ it('stops network polling for a confirmed removed share without acknowledging its pending cleanup', async () => {+ vi.useFakeTimers();+ const env = setup({ states: { [CAROL]: 'approved' } });+ await env.reshare.sync('startup');+ env.setGroups({});+ env.availability.set('share:a1', 'removed');+ await env.reshare.sync('received');+ env.restart();+ await env.reshare.sync('restart');+ env.advance(60 * 60_000);+ await vi.advanceTimersByTimeAsync(60 * 60_000);+ expect(env.readCaps).toHaveBeenCalledTimes(1);+ expect(env.cleanups['share:a1']).toBeDefined();+ expect(env.completeCleanup).not.toHaveBeenCalled();+ expect(env.reshare.allows('share:a1', CAROL)).toBe(false);+ expect(vi.getTimerCount()).toBe(0);+ });++ it('logs a changed failure reason once and does not treat ACCESS_REVOKED as permanent removal', async () => {+ const env = setup();+ env.readCaps.mockRejectedValue(Object.assign(new Error('unavailable'), { code: 'DEVICE_OFFLINE' }));+ await env.reshare.sync('startup');+ env.readCaps.mockRejectedValue(Object.assign(new Error('unavailable'), { code: 'ACCESS_REVOKED' }));+ await env.reshare.sync('manual', { force: true });+ await env.reshare.sync('manual', { force: true });+ expect(env.log.info).toHaveBeenCalledTimes(2);+ expect(env.log.debug).toHaveBeenCalledTimes(1);+ env.readCaps.mockResolvedValue(CAPS);+ env.advance(5 * 60_000);+ await env.reshare.sync('poll');+ expect(env.reshare.summary('anthropic', 'share:a1')?.support).toBe('supported');+ });++ it('rechecks a denied peer and stale healthy views without waking another failing peer', async () => {+ const env = setup({ states: { [CAROL]: 'approved' },+ groups: { anthropic: { strategy: 'least', autoSwitch: true,+ members: [FRIEND, member('share:a2:anthropic', 'share', 'share:a2')] } } });+ env.readCaps.mockImplementation(async (device) => {+ if (device === 'share:a2') throw new Error('offline');+ return CAPS;+ });+ await env.reshare.sync('startup');+ env.setStates({ [CAROL]: 'rejected' });+ env.reshare.noteDenied('share:a1', CAROL);+ expect(env.reshare.allows('share:a1', CAROL)).toBe(false);+ await env.reshare.sync('settled');+ expect(env.readCaps.mock.calls.slice(2)).toEqual([['share:a1']]);+ expect(env.reshare.summary('anthropic', 'share:a1')?.guests[0]?.state).toBe('rejected');+ env.advance(15_000);+ env.reshare.refreshIfStale();+ await env.reshare.sync('settled');+ expect(env.readCaps.mock.calls.slice(3)).toEqual([['share:a1']]);+ });+it('reports the people this computer shares the group with only to shared-in computers, and follows their answers', async () => {const env = setup({ states: { [CAROL]: 'approved', [DAVE]: 'pending' } });// 没问到之前一律当作没同意。diff --git a/apps/desktop/src/main/provider-group/reshare.ts b/apps/desktop/src/main/provider-group/reshare.tsindex 173d94f70c..a05ffd8d1b 100644--- a/apps/desktop/src/main/provider-group/reshare.ts+++ b/apps/desktop/src/main/provider-group/reshare.ts@@ -5,10 +5,10 @@* 主人逐人同意。这里按本机的组设置与本机分享出去的人,算出每台分享来的电脑该报上哪些人,经远程 Agent 的* op `reshare` 整体报给那台(本机是那台的受邀者),记下每个人此刻的结果;给受邀者选电脑时只选同意过这个人的那台。*- * 结果只在内存里,以那台电脑为准:组或分享的人变化后马上报一次;还有人等着、或那台读不到时每分钟再问一次,+ * 结果只在内存里,以那台电脑为准:组或分享的人变化后马上报一次;还有人等着时每分钟再问一次,失败逐步退避,* 其余每 10 分钟核对一次;那台拒绝了某个人的任务时马上重问。没问到之前一律当作没同意(不分给那台)。* 本机分享出去的人还没读到时不报:整体替换会把那台上已有的同意清掉。- * 移出全部组的清理与组设置一起持久保存,空名单确认后才删除;离线每分钟重试,重启与重新加入都先完成清理。+ * 移出全部组的清理与组设置一起持久保存,空名单确认后才删除;离线同样退避,重启与重新加入都先完成清理。*/import { randomUUID } from 'node:crypto';@@ -25,8 +25,9 @@ import {import type { ProviderGroupConfig, ProviderGroupReshareGuest, ProviderGroupReshareSummary } from '../../shared/providerGroup.js';import { reshareKeyFor } from '../remote-agent/host/groupRelay.js';-/** 还有人等着同意、或那台读不到时,多久再问一次。 */+/** 还有人等着同意、或前两次失败时,多久再问一次。 */export const PROVIDER_GROUP_RESHARE_PENDING_POLL_MS = 60_000;+const RETRY_DELAYS_MS = [60_000, 60_000, 5 * 60_000, 10 * 60_000, 20 * 60_000, 30 * 60_000];/** 都有结果时多久核对一次(主人可能撤回)。 */export const PROVIDER_GROUP_RESHARE_IDLE_POLL_MS = 10 * 60_000;/** 变化后合并成一次报告的等待。 */@@ -40,6 +41,8 @@ export interface ProviderGroupReshareDeps {ownedShares(): readonly ProviderShareOwned[] | null;/** 与移出组一起持久保存的清理代次;重新加入也须先清空旧同意。 */pendingCleanups(): Readonly<Record<string, string>>;+ /** removed 只能来自完整可信的分享名单;offline / paused 不是永久删除。 */+ shareAvailability?(agentDeviceId: string): ShareAvailability;completeCleanup(agentDeviceId: string, token: string): Promise<void>;readCaps(agentDeviceId: string): Promise<RemoteAgentCaps>;/** 经远程 Agent 通道发给那台电脑(本机是那台的受邀者),返回回包;失败抛错。 */@@ -47,18 +50,29 @@ export interface ProviderGroupReshareDeps {/** 结果有变化(设置页重读)。 */changed?(): void;now(): number;- log: { info?(message: string, meta?: Record<string, unknown>): void; warn(message: string, meta?: Record<string, unknown>): void };+ log: {+ info?(message: string, meta?: Record<string, unknown>): void;+ debug?(message: string, meta?: Record<string, unknown>): void;+ warn(message: string, meta?: Record<string, unknown>): void;+ };}type DeviceSupport = 'supported' | 'needs-update' | 'unknown';+type ShareAvailability = 'unknown' | 'online' | 'offline' | 'paused' | 'removed';interface DeviceState {support: DeviceSupport;states: Map<string, ProviderGroupReshareGuest['state']>;- /** 上次成功报上去的内容;变了才需要立即再报。 */+ /** 上次成功报上去的内容;只有确认空名单后才能停止轮询。 */sentSignature: string | null;+ /** 尝试过不代表成功;同一份失败的名单不能被普通刷新立即重发。 */+ attemptedSignature: string | null;checkedAt: number;failed: boolean;+ failureCount: number;+ retryAt: number;+ lastError?: string;+ availability: ShareAvailability;cleanupToken?: string;}@@ -100,8 +114,43 @@ export function createProviderGroupReshare(deps: ProviderGroupReshareDeps): Provlet running: Promise<void> | null = null;let again = false;let againForce = false;+ const forcedDevices = new Set<string>();let stopped = false;+ function stateFor(agentDeviceId: string): DeviceState {+ let state = devices.get(agentDeviceId);+ if (!state) {+ state = {+ support: 'unknown', states: new Map(), sentSignature: null, attemptedSignature: null,+ checkedAt: 0, failed: false, failureCount: 0, retryAt: 0, availability: 'unknown',+ };+ devices.set(agentDeviceId, state);+ }+ return state;+ }++ function canSync(agentDeviceId: string): boolean {+ const state = stateFor(agentDeviceId);+ const availability = deps.shareAvailability?.(agentDeviceId) ?? 'unknown';+ if (availability === 'online' && state.availability !== 'online' && state.availability !== 'unknown') {+ // 只在这台恢复时提前唤醒;收到同一在线快照不能反复清掉退避。+ state.failureCount = 0;+ state.retryAt = 0;+ state.attemptedSignature = null;+ state.checkedAt = 0;+ }+ state.availability = availability;+ return availability !== 'removed' && availability !== 'paused';+ }++ function recovered(agentDeviceId: string, state: DeviceState): void {+ if (state.lastError !== undefined) deps.log.info?.('provider group: reshare sync recovered', { device: agentDeviceId });+ state.failed = false;+ state.failureCount = 0;+ state.retryAt = 0;+ state.lastError = undefined;+ }+/** 每台分享来的电脑该报上的人(按转分享键去重);本机分享出去的人还没读到时为 null。 */function desired(): Map<string, Map<string, DesiredGuest>> | null {const owned = deps.ownedShares();@@ -132,13 +181,12 @@ export function createProviderGroupReshare(deps: ProviderGroupReshareDeps): Prov}async function syncDevice(agentDeviceId: string, entries: RemoteAgentReshareEntry[], cleanupToken?: string): Promise<boolean> {- const state: DeviceState = devices.get(agentDeviceId) ?? {- support: 'unknown', states: new Map(), sentSignature: null, checkedAt: 0, failed: false,- } satisfies DeviceState;- devices.set(agentDeviceId, state);+ const state = stateFor(agentDeviceId);const before = JSON.stringify([state.support, [...state.states]]);const signature = signatureOf(entries);+ state.attemptedSignature = signature;if (cleanupToken) {+ if (state.cleanupToken !== cleanupToken) state.failureCount = 0;state.cleanupToken = cleanupToken;state.states.clear();state.sentSignature = null;@@ -191,6 +239,7 @@ export function createProviderGroupReshare(deps: ProviderGroupReshareDeps): Provif (cleanupToken) {await deps.completeCleanup(agentDeviceId, cleanupToken);if (stopped) return false;+ recovered(agentDeviceId, state);devices.delete(agentDeviceId);return true;}@@ -202,24 +251,33 @@ export function createProviderGroupReshare(deps: ProviderGroupReshareDeps): Provstate.states = new Map(result.entries.map((entry) => [entry.key, entry.state]));}state.sentSignature = signature;- state.failed = false;+ recovered(agentDeviceId, state);} catch (error) {+ if (stopped) return false;// 读不到(离线、分享暂停等):保留上次的结果(那台本来也选不上),稍后再问。state.failed = true;- deps.log.info?.('provider group: reshare sync failed', {+ state.failureCount = Math.min(state.failureCount + 1, RETRY_DELAYS_MS.length);+ state.retryAt = deps.now() + RETRY_DELAYS_MS[state.failureCount - 1];+ const message = error instanceof Error ? error.message : String(error);+ const code = error && typeof error === 'object' && 'code' in error ? String(error.code) : '';+ const errorKey = JSON.stringify([code, message]);+ const meta = {device: agentDeviceId,- error: error instanceof Error ? error.message : String(error),- });+ error: message, code, retryInMs: state.retryAt - deps.now(),+ };+ if (state.lastError !== errorKey) deps.log.info?.('provider group: reshare sync failed', meta);+ else deps.log.debug?.('provider group: reshare sync failed', meta);+ state.lastError = errorKey;}state.checkedAt = deps.now();if (!devices.has(agentDeviceId)) return false;return JSON.stringify([state.support, [...state.states]]) !== before;}- /** 这台多久再问一次:还有人等着、或上次读不到时每分钟,其余每 10 分钟。 */+ /** 成功后:还有人等着时每分钟,其余每 10 分钟;失败另走 retryAt。 */function intervalFor(agentDeviceId: string, guests: ReadonlyMap<string, DesiredGuest>): number {const state = devices.get(agentDeviceId);- if (!state || state.failed) return PROVIDER_GROUP_RESHARE_PENDING_POLL_MS;+ if (!state) return PROVIDER_GROUP_RESHARE_PENDING_POLL_MS;if (state.support === 'supported') {for (const key of guests.keys()) {const value = state.states.get(key);@@ -234,17 +292,20 @@ export function createProviderGroupReshare(deps: ProviderGroupReshareDeps): Provconst cleanups = deps.pendingCleanups();for (const [agentDeviceId, token] of Object.entries(cleanups)) {const state = devices.get(agentDeviceId);+ if (state?.availability === 'removed' || state?.availability === 'paused') continue;const elapsed = state?.cleanupToken === token ? deps.now() - state.checkedAt : Infinity;- const remaining = Math.max(0, PROVIDER_GROUP_RESHARE_PENDING_POLL_MS - elapsed);+ const remaining = Math.max(0, state?.cleanupToken === token && state.failed+ ? state.retryAt - deps.now() : PROVIDER_GROUP_RESHARE_PENDING_POLL_MS - elapsed);delay = delay === null ? remaining : Math.min(delay, remaining);}for (const [agentDeviceId, guests] of want ?? []) {if (cleanups[agentDeviceId]) continue;const state = devices.get(agentDeviceId);- // 空名单已确认后无须轮询;失败的空名单仍按一分钟重试。+ if (state?.availability === 'removed' || state?.availability === 'paused') continue;+ // 空名单已确认后无须轮询;失败的空名单仍按退避重试。if (guests.size === 0 && state?.sentSignature === signatureOf([]) && !state.failed) continue;const elapsed = state ? deps.now() - state.checkedAt : Infinity;- const remaining = Math.max(0, intervalFor(agentDeviceId, guests) - elapsed);+ const remaining = Math.max(0, state?.failed ? state.retryAt - deps.now() : intervalFor(agentDeviceId, guests) - elapsed);delay = delay === null ? remaining : Math.min(delay, remaining);}return delay;@@ -261,16 +322,18 @@ export function createProviderGroupReshare(deps: ProviderGroupReshareDeps): Prov(timer as { unref?: () => void }).unref?.();}- /** force:每台都现问(设置页打开、那台刚拒绝了人);否则只问报上的人变了的、或到了核对时间的。 */- async function runOnce(force: boolean): Promise<void> {+ /** force 全量现问;forceDevices 只唤醒指定设备,其余遵守名单变化和核对时间。 */+ async function runOnce(force: boolean, forceDevices: ReadonlySet<string>): Promise<void> {let changed = false;// 清理先于重新报人;即使分享名单尚未读到,也能继续已持久保存的清理。const cleanups = Object.entries(deps.pendingCleanups());if (cleanups.length > 0) {await Promise.all(cleanups.map(async ([agentDeviceId, token]) => {+ if (!canSync(agentDeviceId)) return;const state = devices.get(agentDeviceId);- if (!force && state?.cleanupToken === token- && deps.now() - state.checkedAt < PROVIDER_GROUP_RESHARE_PENDING_POLL_MS) return;+ if (!force && !forceDevices.has(agentDeviceId) && state?.cleanupToken === token+ && (state.failed ? deps.now() < state.retryAt+ : deps.now() - state.checkedAt < PROVIDER_GROUP_RESHARE_PENDING_POLL_MS)) return;if (await syncDevice(agentDeviceId, [], token)) changed = true;}));}@@ -289,13 +352,15 @@ export function createProviderGroupReshare(deps: ProviderGroupReshareDeps): Prov}await Promise.all([...want].map(async ([agentDeviceId, guests]) => {if (deps.pendingCleanups()[agentDeviceId]) return;+ if (!canSync(agentDeviceId)) return;const entries = [...guests.values()].map((guest) => guest.entry);const state = devices.get(agentDeviceId);const signature = signatureOf(entries);// 没有分享给任何人、空名单也已报过:没有要问的。- if (!force && entries.length === 0 && state?.sentSignature === signature && !state.failed) return;- const due = force || !state || state.sentSignature !== signature- || deps.now() - state.checkedAt >= intervalFor(agentDeviceId, guests);+ const forceDevice = force || forceDevices.has(agentDeviceId);+ if (!forceDevice && entries.length === 0 && state?.sentSignature === signature && !state.failed) return;+ const due = forceDevice || !state || state.attemptedSignature !== signature+ || (state.failed ? deps.now() >= state.retryAt : deps.now() - state.checkedAt >= intervalFor(agentDeviceId, guests));if (!due) return;if (await syncDevice(agentDeviceId, entries)) changed = true;}));@@ -304,8 +369,9 @@ export function createProviderGroupReshare(deps: ProviderGroupReshareDeps): Provschedule(nextDelay(desired()));}- async function sync(reason: string, options: { force?: boolean } = {}): Promise<void> {+ async function sync(reason: string, options: { force?: boolean; forceDevices?: string[] } = {}): Promise<void> {if (stopped) return;+ for (const device of options.forceDevices ?? []) forcedDevices.add(device);if (running) {again = true;againForce ||= options.force === true;@@ -317,7 +383,9 @@ export function createProviderGroupReshare(deps: ProviderGroupReshareDeps): Provdo {again = false;againForce = false;- await runOnce(force);+ const forceDevices = new Set(forcedDevices);+ forcedDevices.clear();+ await runOnce(force, forceDevices);force = againForce;} while (again && !stopped);} catch (error) {@@ -368,9 +436,10 @@ export function createProviderGroupReshare(deps: ProviderGroupReshareDeps): Prov},refreshIfStale() {const now = deps.now();- const stale = [...devices.values()].some((state) => now - state.checkedAt >= PROVIDER_GROUP_RESHARE_VIEW_REFRESH_MS);- if (stale) void sync('view', { force: true });- else if (devices.size === 0) void sync('view');+ // 这是读取组详情的公共路径,也会被后台调用;失败设备仍遵守退避。+ const stale = [...devices].filter(([, state]) => !state.failed+ && now - state.checkedAt >= PROVIDER_GROUP_RESHARE_VIEW_REFRESH_MS).map(([device]) => device);+ void sync('view', { forceDevices: stale });},noteDenied(agentDeviceId, reshareKey) {const state = devices.get(agentDeviceId);@@ -378,7 +447,7 @@ export function createProviderGroupReshare(deps: ProviderGroupReshareDeps): Provstate.states.delete(reshareKey);deps.changed?.();}- void sync('denied', { force: true });+ void sync('denied', { forceDevices: [agentDeviceId] });},sync,stop() {@@ -388,6 +457,7 @@ export function createProviderGroupReshare(deps: ProviderGroupReshareDeps): Provtimer = null;kickTimer = null;devices.clear();+ forcedDevices.clear();},};}diff --git a/apps/desktop/src/main/provider-group/reshareRuntime.ts b/apps/desktop/src/main/provider-group/reshareRuntime.tsindex 9b402a7c15..18a7141440 100644--- a/apps/desktop/src/main/provider-group/reshareRuntime.ts+++ b/apps/desktop/src/main/provider-group/reshareRuntime.ts@@ -9,6 +9,7 @@ import { REMOTE_AGENT_CHANNEL, parseRemoteAgentCaps } from '@cindy/device-link';import { activeOwnerScopeKey } from '../appSessionState.js';import { PROVIDER_GROUP_IPC } from '../../shared/providerGroup.js';+import { PROVIDER_SHARE_AGENT_DEVICE_PREFIX } from '../../shared/providerShare.js';import { tapWindowBroadcast } from '../device-link/broadcast-tap.js';import { broadcast, remoteBackgroundInvoke } from '../device-link/index.js';import {@@ -45,13 +46,21 @@ function reshareForActiveOwner(): ProviderGroupReshare {if (!isCurrent()) throw new Error('The account changed');const reply = await remoteBackgroundInvoke(agentDeviceId, REMOTE_AGENT_CHANNEL, [request]);if (!isCurrent()) throw new Error('The account changed');- if (!reply.ok) throw new Error(reply.error.message || reply.error.code);+ if (!reply.ok) throw Object.assign(new Error(reply.error.message || reply.error.code), { code: reply.error.code });return reply.result;};const reshare = createProviderGroupReshare({listGroups: () => (isCurrent() ? listProviderGroups() : {}),ownedShares: () => (isCurrent() ? getProviderShareHostLoadedSnapshot() : null),pendingCleanups: () => (isCurrent() ? listProviderGroupReshareCleanups() : {}),+ shareAvailability: (agentDeviceId) => {+ if (!isCurrent() || !agentDeviceId.startsWith(PROVIDER_SHARE_AGENT_DEVICE_PREFIX)) return 'unknown';+ const shareId = agentDeviceId.slice(PROVIDER_SHARE_AGENT_DEVICE_PREFIX.length);+ const share = getReceivedShares().find((item) => item.shareId === shareId);+ if (share) return share.status === 'paused' ? 'paused' : share.hostOnline ? 'online' : 'offline';+ const confirmed = getConfirmedReceivedShareIds();+ return confirmed && !confirmed.has(shareId) ? 'removed' : 'unknown';+ },completeCleanup: async (agentDeviceId, token) => {if (!isCurrent()) throw new Error('The account changed');await completeProviderGroupReshareCleanup(agentDeviceId, token);diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.mdindex d80175a6a1..b40832b08b 100644--- a/docs/dev-rules/protocol-compatibility.md+++ b/docs/dev-rules/protocol-compatibility.md@@ -1981,7 +1981,9 @@ G 与 O 之间不变。受邀者能调用的 channel 不变(仍是 `maker:remote没带(旧 O)回已有的 `REMOTE_AGENT_PROVIDER_NOT_ALLOWED`,旧 O 照常换组里下一台、转给 G 时统一成「暂时不可用」。主人撤回同意时 M 立即结束这个人经组转来的任务;M 在所有异步查询结束后、登记任务前再次核对同意,核对与登记之间不等待。O 收到 `REMOTE_AGENT_RESHARE_NOT_ALLOWED` 时重新核对同意情况,之后不再选它。-- O 移出最后一个组引用时,在本机组设置里原子记下待清空代次;`reshare` 空名单得到有效回包后才删除该代次,失败每分钟重试,+- O 移出最后一个组引用时,在本机组设置里原子记下待清空代次;`reshare` 空名单得到有效回包后才删除该代次,失败与普通同步一起按+ 1、1、5、10、20、30 分钟退避(上限 30 分钟),重复快照和组详情读取不能穿透;成功重置,观察到对端恢复在线只唤醒那台。+ 暂停分享或完整可信名单确认分享已删除时不发同步,未确认的清理代次仍保留;`ACCESS_REVOKED` 本身不是永久删除证据。重启后继续。重新加入时先清空再报人;迟到的确认不能吞掉再次移出的新代次。不新增 wire 字段,沿用整体替换的幂等语义。- O 给 G 的匿名组状态(`groupStatus`)里,没同意过 G 的分享来的电脑显示 `unavailable`(那台给不出同意时 `needs-update`),与实际分配一致;`groupSize` 不变。diff --git a/docs/product-rules/provider-groups.md b/docs/product-rules/provider-groups.mdindex e2279fb320..cf40c955b6 100644--- a/docs/product-rules/provider-groups.md+++ b/docs/product-rules/provider-groups.md@@ -152,11 +152,14 @@这个受邀者**(2026-10-15,[供应商分享](provider-sharing.md) §4.3);同账号电脑要声明能按受邀者隔离(`guestRelay`),不声明的旧版本一阵子(10 分钟)不再给它受邀者的任务,但不冷却它,组所在电脑自己的任务照常分过去。- **转分享的同意**:组所在电脑自动把分享出去的人(按账号)报给组里每台分享来的电脑,由那台的主人逐人同意;结果只在组所在- 电脑内存里,以那台为准(组或分享的人变化后马上报,还有人等着时每分钟再问,其余每 10 分钟核对,设置页打开时 15 秒内现问),+ 电脑内存里,以那台为准(组或分享的人变化后马上报,还有人等着时每分钟再问,其余每 10 分钟核对,设置页读取距上次成功核对超过 15 秒时再问),没问到之前一律当作没同意。中转到分享来的电脑时带上这个人的转分享键,那台再核对一次,没同意就拒绝(换组里下一台,不冷却);主人撤回时那台立即结束这个人的任务;查询供应商、续接归属等等待结束后,登记任务前再次核对,同一步登记,中间不再等待。每次向分享来的电脑打开任务(含已有绑定的续接)都现查 `reshareConsent` 能力;降级的旧端不能沿用缓存同意接任务。- 分享来的电脑离开全部组时,移出组与待清空记录同一次原子写入;空名单被确认后才删除,失败每分钟重试,重启后继续。重新加入+ 同步和清理连续失败后按 1、1、5、10、20、30 分钟退避,之后最多每 30 分钟一次;成功清零。重复分享快照与设置页读取不穿透退避,+ 真正变化的名单可立即尝试一次;分享名单观察到那台从离线或暂停恢复在线时只唤醒那台。同类失败只在首次或原因变化时记 info,其余记 debug。+ 分享暂停时不发同步;完整可信名单确认分享已删除或退出时停止该分享的网络轮询,但保留未确认的清理记录,不把暂停或 `ACCESS_REVOKED` 当作删除。+ 分享来的电脑离开全部组时,移出组与待清空记录同一次原子写入;空名单被确认后才删除,失败按上述间隔退避,重启后继续。重新加入也先清空旧同意,再重新报人;已确认的空名单不再定时轮询。实现与回归见 `provider-group/store.ts`、`reshare.ts` 及对应测试。名单超过 256 人时由支持 `reshareBatch` 的新版电脑按批次分片,每片回报当前片状态,接收端收齐后才整体替换;批次数不设固定人数上限,接收端以字节预算保护内存;已完成片段重发仍幂等。旧版不能安全接收大名单时显示需要更新,不发送部分名单。