Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(device-link): 事件触发的目录读取不复用旧列表,后台不补读
david741800e362c5
diff --git a/apps/desktop/src/main/device-link/__tests__/sharedTaskApi.test.ts b/apps/desktop/src/main/device-link/__tests__/sharedTaskApi.test.tsindex dcafb58ad9..a9d3c6eefb 100644--- a/apps/desktop/src/main/device-link/__tests__/sharedTaskApi.test.ts+++ b/apps/desktop/src/main/device-link/__tests__/sharedTaskApi.test.ts@@ -7,7 +7,7 @@ vi.mock('../../authManager.js', () => ({ getAuthState: () => ({ isAuthenticated:getCurrentUserId: () => state.accountId, getActiveAuthRealm: () => state.region, getAccessToken: () => state.token }));vi.mock('../../clientEndpointsService.js', () => ({ getClientEndpoint: () => state.endpoint }));vi.mock('../../serverApiClient.js', () => ({ serverApiFetch: http }));-import { captureSharedTaskBoundaryClose, sharedTaskApi } from '../sharedTaskApi.js';+import { captureSharedTaskBoundaryClose, forgetSharedTaskList, sharedTaskApi } from '../sharedTaskApi.js';beforeEach(() => {state.key = 'account:1'; state.endpoint = 'https://relay.example.test'; state.authenticated = true; state.boundary = false;@@ -141,6 +141,15 @@ describe('sharedTask Main list reuse', () => {await expect(sharedTaskApi.list()).resolves.toHaveLength(1);expect(listCalls()).toBe(4);});+ it('makes a real request after an external event forgets the recent list', async () => {+ state.key = 'list-reuse:6';+ http.mockResolvedValue(listed('a'));+ await sharedTaskApi.list();+ forgetSharedTaskList();+ await sharedTaskApi.list();+ await sharedTaskApi.list();+ expect(listCalls()).toBe(2);+ });it('treats a cached list as stale after the clock moves backwards', async () => {state.key = 'list-reuse:5';http.mockResolvedValue(listed('a'));diff --git a/apps/desktop/src/main/device-link/__tests__/sharedTaskIpc.test.ts b/apps/desktop/src/main/device-link/__tests__/sharedTaskIpc.test.tsindex 5529eed25d..6a9e1061d2 100644--- a/apps/desktop/src/main/device-link/__tests__/sharedTaskIpc.test.ts+++ b/apps/desktop/src/main/device-link/__tests__/sharedTaskIpc.test.ts@@ -8,6 +8,7 @@ const h = vi.hoisted(() => ({trusted: vi.fn(),list: vi.fn(),close: vi.fn(),+ forget: vi.fn(),host: { activeSharedTaskIds: vi.fn(() => []), open: vi.fn(), close: vi.fn() },}));vi.mock('electron', () => ({ ipcMain: { handle: (channel: string, handler: (event: unknown, raw: unknown) => Promise<unknown>) => h.handlers.set(channel, handler) } }));@@ -15,7 +16,7 @@ vi.mock('../../authManager.js', () => ({ getCurrentUserId: () => 'owner' }));vi.mock('../../security/trustedAppRenderer.js', () => ({ assertTrustedAppRendererEvent: h.trusted }));vi.mock('../invoke-context.js', () => ({ getDeviceLinkInvokeContext: () => h.context }));vi.mock('../sharedTaskRuntime.js', () => ({ requireSharedTaskHost: () => h.host }));-vi.mock('../sharedTaskApi.js', () => ({ sharedTaskApi: { list: h.list, close: h.close } }));+vi.mock('../sharedTaskApi.js', () => ({ sharedTaskApi: { list: h.list, close: h.close }, forgetSharedTaskList: h.forget }));const invoke = (channel: string, command: unknown) => h.handlers.get(channel)!({}, command);const commands = [@@ -64,6 +65,16 @@ describe('shared-task IPC availability', () => {expect(h.list).toHaveBeenCalledTimes(1);});+ // Reconnect / revocation refreshes must read the server, not a list cached before the event.+ it('drops the cached directory only for an event-driven fresh read', async () => {+ registerSharedTaskIpc(() => true, () => true);+ await invoke(SHARED_TASK_ACCOUNT_CHANNEL, { action: 'list' });+ expect(h.forget).not.toHaveBeenCalled();+ await invoke(SHARED_TASK_ACCOUNT_CHANNEL, { action: 'list', fresh: true });+ expect(h.forget).toHaveBeenCalledOnce();+ expect(h.list).toHaveBeenCalledTimes(2);+ });+it('retains the guest and tunneled-account permission guards before availability', async () => {registerSharedTaskIpc(() => false, () => false);h.context = { sharedTask: {} };diff --git a/apps/desktop/src/main/device-link/__tests__/sharedTaskRuntime.test.ts b/apps/desktop/src/main/device-link/__tests__/sharedTaskRuntime.test.tsindex 0d5275ff7b..56cffec30b 100644--- a/apps/desktop/src/main/device-link/__tests__/sharedTaskRuntime.test.ts+++ b/apps/desktop/src/main/device-link/__tests__/sharedTaskRuntime.test.ts@@ -12,7 +12,7 @@ const state = vi.hoisted(() => ({accountId: 'owner', region: 'global', authenticated: true,session: { mode: 'cloud', dataOwnerId: 'owner', generation: 1 }, boundary: false,db: { client: { query: vi.fn(), exec: vi.fn() }, clientEpoch: 1 },- hosts: [] as HostRecord[], dispatch: vi.fn(),+ hosts: [] as HostRecord[], dispatch: vi.fn(), forgetList: vi.fn(),captureClose: vi.fn(), close: vi.fn(), journalClose: vi.fn(), journalPrepare: vi.fn(), journalRollback: vi.fn(), journalFinalize: vi.fn(),}));vi.mock('../../localDb/client/current.js', () => ({ getCurrentDbClientSnapshot: () => state.db }));@@ -32,7 +32,7 @@ vi.mock('../../authManager.js', () => ({getDeviceId: () => 'host-device', getActiveAuthRealm: () => state.region,}));vi.mock('../../logger.js', () => ({ createLogger: () => ({ warn: vi.fn(), debug: vi.fn() }) }));-vi.mock('../sharedTaskApi.js', () => ({ sharedTaskApi: {}, captureSharedTaskBoundaryClose: state.captureClose }));+vi.mock('../sharedTaskApi.js', () => ({ sharedTaskApi: {}, captureSharedTaskBoundaryClose: state.captureClose, forgetSharedTaskList: state.forgetList }));vi.mock('../sharedTaskDispatch.js', () => ({ setSharedTaskDispatchHost: state.dispatch }));vi.mock('../sharedTaskHost.js', () => ({SharedTaskHost: class {@@ -151,8 +151,11 @@ describe('shared runtime stable owner recommit', () => {// A reconnect that finished between ticks is never observed offline.relay.getConnectionEpoch = () => 2;host.restore.mockRejectedValueOnce(new Error('offline'));+ state.forgetList.mockClear();await vi.advanceTimersByTimeAsync(5_000);expect(serverReads()).toBe(4);+ // The reconnect sync must not reuse a list cached before the reconnect.+ expect(state.forgetList).toHaveBeenCalledOnce();// A failed sync retries after the server interval, not on every local tick.await vi.advanceTimersByTimeAsync(25_000);expect(serverReads()).toBe(4);diff --git a/apps/desktop/src/main/device-link/sharedTaskApi.ts b/apps/desktop/src/main/device-link/sharedTaskApi.tsindex 411f95946a..1cef9d01d3 100644--- a/apps/desktop/src/main/device-link/sharedTaskApi.ts+++ b/apps/desktop/src/main/device-link/sharedTaskApi.ts@@ -17,6 +17,11 @@ function trackListWrite<T>(method: string, work: () => Promise<T>): Promise<T> {return work().finally(() => { listWrites++; });}+/** The next list() is a real request: an external event (reconnect, revocation) may postdate the cache. */+export function forgetSharedTaskList(): void {+ listCache = null;+}+/** Main-owned adapter. Tokens remain inside the existing authenticated HTTP client. */const accountApi = createSharedTaskApi({captureScope() {diff --git a/apps/desktop/src/main/device-link/sharedTaskIpc.ts b/apps/desktop/src/main/device-link/sharedTaskIpc.tsindex c9720e417b..463e6bcd20 100644--- a/apps/desktop/src/main/device-link/sharedTaskIpc.ts+++ b/apps/desktop/src/main/device-link/sharedTaskIpc.ts@@ -5,7 +5,7 @@ import { assertTrustedAppRendererEvent } from '../security/trustedAppRenderer.jsimport { throwIpcError } from '../utils/ipcValidate.js';import { getDeviceLinkInvokeContext } from './invoke-context.js';import { requireSharedTaskHost } from './sharedTaskRuntime.js';-import { sharedTaskApi } from './sharedTaskApi.js';+import { forgetSharedTaskList, sharedTaskApi } from './sharedTaskApi.js';import { executeSharedTaskAccountCommand, executeSharedTaskHostCommand } from './sharedTaskCommands.js';/** Narrow Renderer adapter; account operations cannot be tunneled on somebody else's login. */@@ -25,6 +25,8 @@ export function registerSharedTaskIpc(available: () => boolean, relayOnline: ()if (getDeviceLinkInvokeContext()) throwIpcError('PERMISSION_DENIED', 'SharedTask account operations are local only');assertTrustedAppRendererEvent(event);if (!availableOnline()) throwIpcError('UNSUPPORTED_CAPABILITY', 'SharedTask mode requires updated clients and server');+ // Event-driven directory reads must not reuse a list cached before the event.+ if (raw && typeof raw === 'object' && (raw as { fresh?: unknown }).fresh === true) forgetSharedTaskList();return executeSharedTaskAccountCommand(raw, sharedTaskApi, getCurrentUserId() ?? undefined, {hostedIds: () => { try { return requireSharedTaskHost().activeSharedTaskIds(); } catch { return []; } },closeHosted: (sharedTaskId) => requireSharedTaskHost().close(sharedTaskId),diff --git a/apps/desktop/src/main/device-link/sharedTaskRuntime.ts b/apps/desktop/src/main/device-link/sharedTaskRuntime.tsindex 36b66a917a..38643bc0c8 100644--- a/apps/desktop/src/main/device-link/sharedTaskRuntime.ts+++ b/apps/desktop/src/main/device-link/sharedTaskRuntime.ts@@ -12,7 +12,7 @@ import { activeOwnerScopeKey, getActiveAppSession, isAppSessionBoundaryPending }import { getAuthState, getCurrentUserId, getDeviceId, getActiveAuthRealm } from '../authManager.js';import { createLogger } from '../logger.js';import { throwIpcError } from '../utils/ipcValidate.js';-import { captureSharedTaskBoundaryClose, sharedTaskApi } from './sharedTaskApi.js';+import { captureSharedTaskBoundaryClose, forgetSharedTaskList, sharedTaskApi } from './sharedTaskApi.js';import { SharedTaskHost, type SharedTaskCreationState } from './sharedTaskHost.js';import { setSharedTaskDispatchHost } from './sharedTaskDispatch.js';@@ -110,6 +110,8 @@ export function startSharedTaskRuntime(options: {seenConnectionEpoch = connectionEpoch;syncRequested = true;lastServerReadAt = undefined;+ // A list cached before the reconnect cannot reflect changes made while offline.+ forgetSharedTaskList();}const allowNetwork = online && serverReadDue() && (syncRequested || host.needsAuthorityRefresh());try {diff --git a/apps/desktop/src/renderer/features/device-link/__tests__/useSharedTaskTasks.test.tsx b/apps/desktop/src/renderer/features/device-link/__tests__/useSharedTaskTasks.test.tsxindex efe17f104f..6b302d614f 100644--- a/apps/desktop/src/renderer/features/device-link/__tests__/useSharedTaskTasks.test.tsx+++ b/apps/desktop/src/renderer/features/device-link/__tests__/useSharedTaskTasks.test.tsx@@ -139,6 +139,9 @@ it('rereads the guest directory on join, reconnect and return instead of a fixedexpect(lists()).toBe(2);await act(async () => { state.status?.({ status: 'online' }); });expect(lists()).toBe(3);+ // Event-driven reads ask Main to skip its short list reuse; timed reads do not.+ expect(state.account.mock.calls.filter(([command]) => command.action === 'list').map(([command]) => command.fresh))+ .toEqual([undefined, true, true]);Object.defineProperty(document, 'visibilityState', { configurable: true, get: () => 'hidden' });await act(async () => { document.dispatchEvent(new Event('visibilitychange')); });await act(async () => vi.advanceTimersByTimeAsync(10 * 60_000));diff --git a/apps/desktop/src/renderer/features/device-link/useSharedTaskTasks.ts b/apps/desktop/src/renderer/features/device-link/useSharedTaskTasks.tsindex 6fba0cca6f..899993e341 100644--- a/apps/desktop/src/renderer/features/device-link/useSharedTaskTasks.ts+++ b/apps/desktop/src/renderer/features/device-link/useSharedTaskTasks.ts@@ -27,10 +27,11 @@ export function useSharedTaskTasks(): void {const owner = getDataOwnerGeneration();const currentOwner = () => !disposed && isDataOwnerGenerationCurrent(owner);const linked = new Map<string, string>();- const poll = async (): Promise<number | null> => {+ const poll = async ({ fresh }: { fresh: boolean }): Promise<number | null> => {if (!currentOwner()) return null;try {- const sharedTasks = await window.electronAPI.sharedTask.account({ action: 'list' }) as SharedTaskListItem[];+ // Event-driven reads bypass Main's short list reuse.+ const sharedTasks = await window.electronAPI.sharedTask.account({ action: 'list', ...(fresh ? { fresh: true } : {}) }) as SharedTaskListItem[];if (!currentOwner()) return null;const current = new Set(sharedTasks.map((sharedTask) => sharedTaskHostPeer(sharedTask.sharedTaskId, sharedTask.hostDeviceId)));for (const id of remoteProjectsStore.getAllDeviceIds()) {diff --git a/apps/mobile/app/shared-session.tsx b/apps/mobile/app/shared-session.tsxindex 0475753f04..d1a78d114a 100644--- a/apps/mobile/app/shared-session.tsx+++ b/apps/mobile/app/shared-session.tsx@@ -398,7 +398,7 @@ export default function SharedSessionScreen() {<Text style={styles.intro}>{t('sharedTask.startIntro')}</Text>{taskCard}<View style={styles.noticeBox}><Users size={iconSize.sm} color={colors.textTertiary} /><Text style={[styles.smallMuted, styles.grow]}>{t('sharedTask.inviteNotice')}</Text></View><Text style={styles.smallMuted}>{t('sharedTask.offlineAutoClose')}</Text>- <View style={styles.footer}><SharedTaskAction grow action={{ label: t('sharedTask.open'), tone: 'primary', busy, onPress: () => void run(async () => { await host({ action: 'open', sessionId: sessionId! }); }) }} /></View>+ <View style={styles.footer}><SharedTaskAction grow action={{ label: t('sharedTask.open'), tone: 'primary', busy, onPress: () => void run(async () => { await host({ action: 'open', sessionId: sessionId! }); notifySharedTaskMembershipChanged(); }) }} /></View></> : <><Text style={styles.caption}>{title}</Text><View style={styles.copyBox}><Link size={iconSize.md} color={colors.textTertiary} /><View style={styles.grow}><Text style={styles.smallMuted}>{t('sharedTask.inviteBoxTitle')}</Text><Text style={styles.smallMuted}>{t('sharedTask.inviteBoxHint')}</Text></View>@@ -419,6 +419,7 @@ export default function SharedSessionScreen() {<View style={styles.noticeBox}><Clock size={iconSize.sm} color={colors.textTertiary} /><Text style={[styles.smallMuted, styles.grow]}>{t('sharedTask.remoteHostOfflineNote')}</Text></View><View style={styles.footer}><SharedTaskAction grow action={{ label: t('sharedTask.closeCurrent'), tone: 'danger', disabled: busy, onPress: () => confirm(t('sharedTask.closeOneTitle'), t('sharedTask.closeOneBody'), t('sharedTask.closeAllKeep'), t('sharedTask.close'), async current => {await host({ action: 'close', sharedTaskId: detail.sharedTaskId });+ notifySharedTaskMembershipChanged();if (current() && mode === 'detail') goBackGuarded(router, { pathname: '/shared-session', params: { mode: 'manage' } });}) }} /></View></> : <>diff --git a/docs/product-rules/shared-task-mode.md b/docs/product-rules/shared-task-mode.mdindex a63ff6f51c..10dae8783c 100644--- a/docs/product-rules/shared-task-mode.md+++ b/docs/product-rules/shared-task-mode.md@@ -64,7 +64,7 @@- 服务端是成员关系权威;主机保存恢复与关闭记录。迟到响应、旧快照、缓存和重连不能恢复已撤销访问。- 访客断线保留成员关系,重连后可继续访问仍有效的共享;不能影响其他访客或同账号远控。- 正常断开触发关闭;relay 崩溃、路由过期或关闭落库失败由服务端每 30 秒扫描补偿。服务端授权在关闭提交后立即失效。-- 共享目录轮询(2026-10-22 起,降低空闲请求):Desktop 与 Mobile 的共享目录在窗口隐藏或 App 退到后台时暂停;目录为空时约 60 秒、有共享时约 30 秒读取一次;本机加入或退出共享、回到前台(距上次读取满 10 秒)、重新连上服务器时立即读取,Mobile 在本机批量关闭共享后、Desktop 在访问被结束时也立即读取。Desktop 只看窗口是否可见,不因窗口获得焦点而读取。另一台设备上加入的共享最长约 60 秒后出现;任务内容仍由房主实时推送,不受此间隔影响。Desktop 主进程内同时或 5 秒内的目录读取合并为一次;本机发出的共享写请求(开启、加入、退出、移除、关闭)会使之前的结果失效,其他设备的写入不在此列;缓存按账号、区域与服务端地址隔离,系统时间回拨时视为过期。+- 共享目录轮询(2026-10-22 起,降低空闲请求):Desktop 与 Mobile 的共享目录在窗口隐藏或 App 退到后台时暂停;目录为空时约 60 秒、有共享时约 30 秒读取一次;本机加入或退出共享、回到前台(距上次读取满 10 秒)、重新连上服务器时立即读取,Mobile 在本机开启或关闭共享后、Desktop 在访问被结束时也立即读取。这些事件发生在读取途中或后台时,补读留到当前读取结束且回到前台后进行,后台不发起读取。Desktop 只看窗口是否可见,不因窗口获得焦点而读取。另一台设备上加入的共享最长约 60 秒后出现;任务内容仍由房主实时推送,不受此间隔影响。Desktop 主进程内同时或 5 秒内的目录读取合并为一次;本机发出的共享写请求(开启、加入、退出、移除、关闭)会使之前的结果失效,其他设备的写入不在此列;由事件触发的读取(加入、退出、重连、访问被结束)和发起方的重连同步不复用此前的结果;缓存按账号、区域与服务端地址隔离,系统时间回拨时视为过期。- 不承诺撤回访客已经看到或下载的内容。## 实现约束diff --git a/packages/device-link/src/__tests__/sharedTaskListPoller.test.ts b/packages/device-link/src/__tests__/sharedTaskListPoller.test.tsindex 6b8b413cb4..7e1ece6795 100644--- a/packages/device-link/src/__tests__/sharedTaskListPoller.test.ts+++ b/packages/device-link/src/__tests__/sharedTaskListPoller.test.ts@@ -4,7 +4,7 @@ import { startSharedTaskListPoller } from '../sharedTaskListPoller.js';// Guards the request budget of the guest directory that every signed-in// Desktop and phone runs; a 5 s fixed poll here overloaded auth on 2026-10-22.let visible: boolean;-let poll: ReturnType<typeof vi.fn<() => Promise<number | null>>>;+let poll: ReturnType<typeof vi.fn<(read: { fresh: boolean }) => Promise<number | null>>>;const reads = () => poll.mock.calls.length;beforeEach(() => {vi.useFakeTimers();@@ -80,7 +80,24 @@ it('runs a refresh requested during a read once more after it, never concurrentlfinish(0);await vi.advanceTimersByTimeAsync(0);expect(reads()).toBe(2);+ expect(poll.mock.calls.map(([read]) => read.fresh)).toEqual([false, true]);await vi.advanceTimersByTimeAsync(59_999);expect(reads()).toBe(2);poller.dispose();});++it('defers a refresh owed by an in-flight read until the app returns to the foreground', async () => {+ let finish!: (count: number) => void;+ poll.mockImplementationOnce(() => new Promise(resolve => { finish = resolve; }));+ const poller = startSharedTaskListPoller({ poll, isVisible: () => visible });+ poller.refresh();+ visible = false; poller.visibilityChanged();+ finish(0);+ await vi.advanceTimersByTimeAsync(10 * 60_000);+ expect(reads()).toBe(1);+ visible = true; poller.visibilityChanged();+ await vi.advanceTimersByTimeAsync(0);+ expect(reads()).toBe(2);+ expect(poll.mock.calls[1][0]).toEqual({ fresh: true });+ poller.dispose();+});diff --git a/packages/device-link/src/sharedTaskApi.ts b/packages/device-link/src/sharedTaskApi.tsindex 2865cf70b4..c98983057e 100644--- a/packages/device-link/src/sharedTaskApi.ts+++ b/packages/device-link/src/sharedTaskApi.ts@@ -8,7 +8,8 @@ export type SharedTaskHostCommand =| { action: 'invite' | 'close'; sharedTaskId: string }| { action: 'remove'; sharedTaskId: string; memberId: string };export type SharedTaskAccountCommand =- | { action: 'list' }+ /** `fresh`: Desktop-local hint to skip Main's short list reuse after an external event. */+ | { action: 'list'; fresh?: true }| { action: 'owned' }| { action: 'close'; sharedTaskId?: string; all?: true }| { action: 'get' | 'leave'; sharedTaskId: string }diff --git a/packages/device-link/src/sharedTaskListPoller.ts b/packages/device-link/src/sharedTaskListPoller.tsindex 071773015c..3b33397e21 100644--- a/packages/device-link/src/sharedTaskListPoller.ts+++ b/packages/device-link/src/sharedTaskListPoller.ts@@ -17,13 +17,19 @@ export interface SharedTaskListPoller {}export function startSharedTaskListPoller(options: {- /** Resolves to the number of listed shared tasks, or null when the read failed. */- poll(): Promise<number | null>;+ /**+ * Resolves to the number of listed shared tasks, or null when the read failed.+ * `fresh` marks a read owed to an explicit refresh event; it must not reuse+ * a list cached before that event.+ */+ poll(read: { fresh: boolean }): Promise<number | null>;isVisible(): boolean;}): SharedTaskListPoller {let disposed = false;let busy = false;- let again = false;+ // An explicit refresh is owed. It survives an in-flight read (e.g. a join+ // mid-read) and a background period, and is paid by the next visible read.+ let refreshPending = false;let timer: ReturnType<typeof setTimeout> | undefined;let delay = SHARED_TASK_LIST_IDLE_MS;let lastReadAt = Number.NEGATIVE_INFINITY;@@ -34,32 +40,32 @@ export function startSharedTaskListPoller(options: {timer = setTimeout(() => { void run(); }, delay);};const run = async () => {- if (disposed) return;- // A refresh requested mid-read (e.g. a join) must not be lost to that read.- if (busy) { again = true; return; }+ if (disposed || busy) return;cancel();busy = true;try {do {- again = false;+ const fresh = refreshPending;+ refreshPending = false;lastReadAt = Date.now();- const count = await options.poll().catch(() => null);+ const count = await options.poll({ fresh }).catch(() => null);if (count !== null) delay = count > 0 ? SHARED_TASK_LIST_ACTIVE_MS : SHARED_TASK_LIST_IDLE_MS;- } while (again && !disposed);+ // Never start the owed read in the background; it runs on return.+ } while (refreshPending && !disposed && options.isVisible());} finally { busy = false; }schedule();};if (options.isVisible()) void run();return {refresh() {+ refreshPending = true;if (options.isVisible()) void run();- else lastReadAt = Number.NEGATIVE_INFINITY;},visibilityChanged() {if (!options.isVisible()) { cancel(); return; }const elapsed = Date.now() - lastReadAt;// A negative interval means the clock moved backwards; read rather than trust it.- if (elapsed < 0 || elapsed >= SHARED_TASK_LIST_RESUME_MIN_MS) void run();+ if (refreshPending || elapsed < 0 || elapsed >= SHARED_TASK_LIST_RESUME_MIN_MS) void run();else schedule();},dispose() { disposed = true; cancel(); },