Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(mobile): batch off-list companion reads and scope live state
Chris57e0da56ca56
diff --git a/apps/mobile/src/__tests__/CompanionMessageCard.test.tsx b/apps/mobile/src/__tests__/CompanionMessageCard.test.tsxindex e237a46564..18b7bd587d 100644--- a/apps/mobile/src/__tests__/CompanionMessageCard.test.tsx+++ b/apps/mobile/src/__tests__/CompanionMessageCard.test.tsx@@ -130,6 +130,16 @@ let node: HTMLDivElement;const render = async () => {await act(async () => root.render(createElement(CompanionMessageCard, { deviceId: 'home', message })));};+const renderTasks = async (ids: string[]) => {+ await act(async () => root.render(ids.map((id, index) => createElement(CompanionMessageCard, {+ key: index, deviceId: 'home', message: {+ ...message,+ companion: { ...message.companion, meta: {+ ...message.companion!.meta, delegationId: `job-${id}`, childSessionId: id,+ } },+ } as NormalizedRemoteMessage,+ }))));+};beforeEach(() => {(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;node = document.createElement('div');@@ -239,8 +249,8 @@ it('opens the task from the whole card and keeps stop as a small action while itit('refreshes an off-list task title and follows the list when a completed task runs again', async () => {vi.useFakeTimers();let title = 'Updated task title';- h.invoke.mockImplementation(async (_device, channel) => channel === 'local-db:sessions:get'- ? { id: 'child', title }+ h.invoke.mockImplementation(async (_device, channel) => channel === 'local-db:sessions:get-many'+ ? [{ id: 'child', title }]: { ok: true, delegations: [{ id: 'job', childSessionId: 'child', status: 'completed', title: 'Old title' }] });await render();expect(node.textContent).toContain('Updated task title');@@ -255,13 +265,102 @@ it('refreshes an off-list task title and follows the list when a completed task});expect(node.textContent).toContain('devices.companions.status.running');expect(node.textContent).not.toContain('devices.companions.status.completed');- const taskReads = () => h.invoke.mock.calls.filter((call) => call[1] === 'local-db:sessions:get').length;+ const taskReads = () => h.invoke.mock.calls.filter((call) => call[1] === 'local-db:sessions:get-many').length;const reads = taskReads();await act(async () => { await vi.advanceTimersByTimeAsync(30_000); });expect(taskReads()).toBe(reads);expect(node.textContent).toContain('Updated task title');});+// Unit: mounted production cards must coalesce different IDs, not just duplicate+// bindings. Nine unique tasks cross the eight-ID boundary without concurrent fanout.+it('batches off-list cards and shares their polling wave', async () => {+ vi.useFakeTimers();+ const ids = Array.from({ length: 9 }, (_, i) => `child-${i}`);+ let active = 0;+ let peak = 0;+ h.invoke.mockImplementation(async (_device, channel, args) => {+ if (channel !== 'local-db:sessions:get-many') return { ok: true, delegations: [] };+ peak = Math.max(peak, ++active);+ await Promise.resolve();+ active--;+ return args[0].map((id: string) => ({ id, title: `Task ${id}` }));+ });+ await renderTasks([...ids, ids[0]!]);+ const batches = () => h.invoke.mock.calls.filter((call) => call[1] === 'local-db:sessions:get-many');+ expect(batches().map((call) => call[2][0])).toEqual([ids.slice(0, 8), ids.slice(8)]);+ ids.forEach((id) => expect(node.textContent).toContain(`Task ${id}`));+ await act(async () => { await vi.advanceTimersByTimeAsync(30_000); });+ expect(batches().map((call) => call[2][0])).toEqual([+ ids.slice(0, 8), ids.slice(8), ids.slice(0, 8), ids.slice(8),+ ]);+ expect(peak).toBe(1);+ expect(h.invoke.mock.calls.some((call) => call[1] === 'local-db:sessions:get')).toBe(false);+});++it.each(['[CHANNEL_NOT_ALLOWED] old host', '[PRECONDITION_FAILED] REMOTE_SESSION_BATCH_TOO_LARGE'])(+ 'uses serial single reads only for batch compatibility failure %s', async (error) => {+ let active = 0;+ let peak = 0;+ h.invoke.mockImplementation(async (_device, channel, args) => {+ if (channel === 'local-db:sessions:get-many') throw new Error(error);+ if (channel !== 'local-db:sessions:get') return { ok: true, delegations: [] };+ peak = Math.max(peak, ++active);+ await Promise.resolve();+ active--;+ return { id: args[0], title: `Task ${args[0]}` };+ });+ await renderTasks(['one', 'two']);+ expect(node.textContent).toContain('Task one');+ expect(node.textContent).toContain('Task two');+ expect(h.invoke.mock.calls.filter((call) => call[1] === 'local-db:sessions:get')).toHaveLength(2);+ expect(peak).toBe(1);+ },+);++it.each(['INVOKE_TIMEOUT', 'ACCESS_REVOKED', 'malformed'])(+ 'does not multiply a failed batch into single reads: %s', async (failure) => {+ h.invoke.mockImplementation(async (_device, channel) => {+ if (channel !== 'local-db:sessions:get-many') return { ok: true, delegations: [] };+ if (failure === 'malformed') return [{ id: 'unrequested', title: 'Wrong task' }];+ throw Object.assign(new Error(failure), { code: failure });+ });+ await renderTasks(['one', 'two']);+ expect(node.textContent).not.toContain('Wrong task');+ expect(h.invoke.mock.calls.filter((call) => call[1] === 'local-db:sessions:get-many')).toHaveLength(1);+ expect(h.invoke.mock.calls.some((call) => call[1] === 'local-db:sessions:get')).toBe(false);+ },+);++it('drops queued batch reads and late titles after account change', async () => {+ let finish!: (value: unknown) => void;+ h.invoke.mockImplementation((_device, channel) => channel === 'local-db:sessions:get-many'+ ? new Promise((resolve) => { finish = resolve; }) : Promise.resolve({ ok: true, delegations: [] }));+ const ids = Array.from({ length: 9 }, (_, i) => `child-${i}`);+ await renderTasks(ids);+ h.accountGeneration++;+ h.status = 'offline';+ await renderTasks(ids);+ await act(async () => finish(ids.slice(0, 8).map((id) => ({ id, title: 'Old private title' }))));+ expect(node.textContent).not.toContain('Old private title');+ expect(h.invoke.mock.calls.filter((call) => call[1] === 'local-db:sessions:get-many')).toHaveLength(1);+});++it.each(['activity', 'interaction'])('filters another host\'s off-list %s even after it is removed', async (kind) => {+ const push = (device: string) => kind === 'activity'+ ? remoteSessionStore.applySessionActivity(device, { sessionId: 'child', phase: 'running' })+ : remoteSessionStore.applyRemotePush(device, 'maker:interaction-request', {+ sessionId: 'child', request: { kind: 'permission', requestId: 'permission-1' },+ });+ push('other');+ remoteSessionStore.removeDevice('other');+ h.invoke.mockRejectedValue(new Error('read failed'));+ await render();+ expect(node.textContent).toContain('devices.companions.status.unknown');+ await act(async () => push('home'));+ expect(node.textContent).toContain(`devices.companions.status.${kind === 'activity' ? 'running' : 'waiting'}`);+});+it('does not borrow another computer\'s task identity or activity for the same id', async () => {remoteSessionStore.setDeviceSessions('other', 'Other Mac', [{ id: 'child', title: 'Unrelated task', status: 'active' } as RemoteSession]);remoteSessionStore.applyRemotePush('other', SESSION_ACTIVITY_CHANNEL, { sessionId: 'child', phase: 'running' });@@ -551,7 +650,7 @@ it('refreshes associated PR state only while mounted and never replays task actiexpect(node.querySelector('[data-testid="merged-pr"]')).not.toBeNull();expect(h.invoke.mock.calls.every((c) =>- ['maker:bot-delegations:list', 'local-db:sessions:get', 'git-context:pr-refs:list', 'git-context:pr-status'].includes(+ ['maker:bot-delegations:list', 'local-db:sessions:get-many', 'git-context:pr-refs:list', 'git-context:pr-status'].includes(c[1],),),diff --git a/apps/mobile/src/session/companionTaskReads.ts b/apps/mobile/src/session/companionTaskReads.tsnew file mode 100644index 0000000000..8396be4772--- /dev/null+++ b/apps/mobile/src/session/companionTaskReads.ts@@ -0,0 +1,111 @@+import type { RemoteInvoke } from '@/device-link/mobileMakerTransport';++type Read = {+ id: string;+ current(): boolean;+ resolve(value: unknown): void;+ reject(error: unknown): void;+};+const queues = new Map<string, Read[]>();+const refreshes = new Map<string, { listeners: Set<() => void>; timer: ReturnType<typeof setInterval> }>();++function permitsSingleRead(error: unknown): boolean {+ const record = error && typeof error === 'object' ? error as { code?: unknown; message?: unknown } : {};+ const message = typeof record.message === 'string' ? record.message : String(error);+ const code = typeof record.code === 'string' && record.code !== 'IPC_ERROR'+ ? record.code : /^\[([^\]]+)\]/.exec(message)?.[1];+ return code === 'CHANNEL_NOT_ALLOWED' || code === 'DEVICE_LINK_CHANNEL_NOT_ALLOWED'+ || (code === 'PRECONDITION_FAILED' && message.replace(/^\[[^\]]+\]\s*/, '') === 'REMOTE_SESSION_BATCH_TOO_LARGE');+}++function isTask(value: unknown): value is { id: string; title: string } {+ return !!value && typeof value === 'object' && !Array.isArray(value)+ && typeof (value as { id?: unknown }).id === 'string'+ && typeof (value as { title?: unknown }).title === 'string';+}++async function readChunk(reads: Read[], deviceId: string, invoke: RemoteInvoke): Promise<void> {+ const ids = [...new Set(reads.map((read) => read.id))];+ try {+ let value: unknown;+ try {+ value = await invoke(deviceId, 'local-db:sessions:get-many', [ids]);+ } catch (error) {+ if (!permitsSingleRead(error)) throw error;+ // Old hosts / oversized batch replies only. Keep fallback serial, and do+ // not issue queued reads after focus, account or connection has changed.+ for (const id of ids) {+ const consumers = reads.filter((read) => read.id === id);+ if (!consumers.some((read) => read.current())) {+ consumers.forEach((read) => read.resolve(null));+ continue;+ }+ try {+ const row = await invoke(deviceId, 'local-db:sessions:get', [id]);+ if (row !== null && (!isTask(row) || row.id !== id)) throw new Error('Invalid task reply');+ consumers.forEach((read) => read.resolve(row));+ } catch (error) {+ consumers.forEach((read) => read.reject(error));+ }+ }+ return;+ }+ if (!Array.isArray(value) || value.some((row) => !isTask(row) || !ids.includes(row.id))+ || new Set(value.map((row) => row.id)).size !== value.length) throw new Error('Invalid task batch reply');+ const rows = new Map(value.map((row) => [row.id, row]));+ reads.forEach((read) => read.resolve(rows.get(read.id) ?? null));+ } catch (error) {+ // Timeout, revocation and malformed replies never multiply into single GETs.+ reads.forEach((read) => read.reject(error));+ }+}++/** One in-flight batch per account/connection/host; no completed-result cache. */+export function readCompanionTask(+ scope: string, deviceId: string, id: string, invoke: RemoteInvoke, current: () => boolean,+): Promise<unknown> {+ return new Promise((resolve, reject) => {+ let queue = queues.get(scope);+ if (!queue) {+ queue = [];+ queues.set(scope, queue);+ const captured = queue;+ // Let cards mounted in the same render register before selecting a batch.+ void Promise.resolve().then(async () => {+ try {+ while (captured.length) {+ const reads = captured.splice(0, 8).filter((read) => {+ if (read.current()) return true;+ read.resolve(null);+ return false;+ });+ if (reads.length) await readChunk(reads, deviceId, invoke);+ }+ } finally {+ if (queues.get(scope) === captured) queues.delete(scope);+ }+ });+ }+ queue.push({ id, current, resolve, reject });+ });+}++/** Poll together so differently mounted cards do not create separate read waves. */+export function subscribeCompanionTaskRefresh(scope: string, intervalMs: number, load: () => void): () => void {+ const key = JSON.stringify([scope, intervalMs]);+ let entry = refreshes.get(key);+ if (!entry) {+ const listeners = new Set<() => void>();+ entry = { listeners, timer: setInterval(() => listeners.forEach((listener) => listener()), intervalMs) };+ refreshes.set(key, entry);+ }+ const captured = entry;+ captured.listeners.add(load);+ return () => {+ captured.listeners.delete(load);+ if (captured.listeners.size === 0) {+ clearInterval(captured.timer);+ refreshes.delete(key);+ }+ };+}diff --git a/apps/mobile/src/session/remoteSessionStore.ts b/apps/mobile/src/session/remoteSessionStore.tsindex 3aecfe733e..5db904ebb1 100644--- a/apps/mobile/src/session/remoteSessionStore.ts+++ b/apps/mobile/src/session/remoteSessionStore.ts@@ -1085,6 +1085,13 @@ function sessionStateWriteAllowed(sessionId: string, deviceId?: string): boolean|| mergedSessionById.get(sessionId)?.canonicalDeviceId === deviceId;}+function sessionStateReadAllowed(sessionId: string, deviceId: string | undefined, sources: Map<string, string>): boolean {+ if (!deviceId) return true;+ if (!sessionStateWriteAllowed(sessionId, deviceId)) return false;+ const source = sources.get(sessionId);+ return !source || source === deviceId || (sessionDeviceIndex.has(sessionId) && sessionStateWriteAllowed(sessionId, source));+}+function clearSourcedSessionState(sessionId: string, sources: Map<string, string>): void {sources.delete(sessionId);if (sources === sessionInteractionSources) {@@ -5635,7 +5642,8 @@ export const remoteSessionStore = {return newMakerWorktreeBranchPreferences.get(deviceId)?.get(baseRepo.trim()) ?? null;},- getPendingInteractions(sessionId: string): PendingInteraction[] {+ getPendingInteractions(sessionId: string, deviceId?: string): PendingInteraction[] {+ if (!sessionStateReadAllowed(sessionId, deviceId, sessionInteractionSources)) return emptyPendingInteractions;return pendingInteractions.get(sessionId) ?? emptyPendingInteractions;},@@ -5686,12 +5694,13 @@ export const remoteSessionStore = {return inputProjections.get(sessionId) ?? EMPTY_INPUT_PROJECTION;},- getSessionLiveActivity(sessionId: string): RemoteSessionLiveActivity | null {+ getSessionLiveActivity(sessionId: string, deviceId?: string): RemoteSessionLiveActivity | null {+ if (!sessionStateReadAllowed(sessionId, deviceId, sessionRuntimeSources)) return null;return sessionLiveActivity.get(sessionId) ?? null;},- isSessionRunning(sessionId: string): boolean {- return sessionRunning.get(sessionId) === true;+ isSessionRunning(sessionId: string, deviceId?: string): boolean {+ return sessionStateReadAllowed(sessionId, deviceId, sessionRuntimeSources) && sessionRunning.get(sessionId) === true;},getSessionRunStatus(sessionId: string): RemoteSessionRunStatus {diff --git a/apps/mobile/src/session/useCompanionTaskSession.ts b/apps/mobile/src/session/useCompanionTaskSession.tsindex 8b6c041e16..2ec7169b61 100644--- a/apps/mobile/src/session/useCompanionTaskSession.ts+++ b/apps/mobile/src/session/useCompanionTaskSession.ts@@ -25,13 +25,13 @@ export function useCompanionTaskSession(deviceId: string, sessionId: string | nu? cached ?? (query.value?.id === sessionId ? query.value : null): null;const activity = useSyncExternalStore(remoteSessionStore.subscribeHomeStatus, () =>- readable ? remoteSessionStore.getSessionLiveActivity(sessionId!) : null,+ readable ? remoteSessionStore.getSessionLiveActivity(sessionId!, deviceId) : null,);const running = useSyncExternalStore(remoteSessionStore.subscribeHomeStatus, () =>- readable && remoteSessionStore.isSessionRunning(sessionId!),+ readable && remoteSessionStore.isSessionRunning(sessionId!, deviceId),);const waiting = useSyncExternalStore(remoteSessionStore.subscribeHomeStatus, () =>- readable && remoteSessionStore.getPendingInteractions(sessionId!).length > 0,+ readable && remoteSessionStore.getPendingInteractions(sessionId!, deviceId).length > 0,);return { session, activity, running, waiting, originConflict, refresh: query.refresh };}diff --git a/apps/mobile/src/session/useRemoteCompanionQuery.ts b/apps/mobile/src/session/useRemoteCompanionQuery.tsindex a1e126ac3d..4387e4b0a0 100644--- a/apps/mobile/src/session/useRemoteCompanionQuery.ts+++ b/apps/mobile/src/session/useRemoteCompanionQuery.ts@@ -4,8 +4,9 @@ import { AppState } from 'react-native';import { useFocusEffect } from 'expo-router';import { useAuth } from '@/auth/AuthContext';import { subscribeRemoteBotChanges, useDeviceLink } from '@/device-link/DeviceLinkContext';+import { readCompanionTask, subscribeCompanionTaskRefresh } from './companionTaskReads';-const pending = new Map<string, { promise: Promise<unknown>; invalidated: boolean }>();+const pending = new Map<string, { promise: Promise<unknown>; invalidated: boolean; consumers: Set<() => boolean> }>();/** Share concurrent list reads between cards; responses never outlive their account/link. */export function useRemoteCompanionQuery<T>(@@ -21,6 +22,7 @@ export function useRemoteCompanionQuery<T>(const link = useDeviceLink();const { accountGeneration } = useAuth();const argsKey = JSON.stringify(args);+ const taskReadScope = JSON.stringify([accountGeneration, link.connectionEpoch, deviceId]);const identity = JSON.stringify([accountGeneration, deviceId, channel, argsKey]);const binding = JSON.stringify([accountGeneration,@@ -67,9 +69,14 @@ export function useRemoteCompanionQuery<T>(return;}if (!entry) {+ const consumers = new Set<() => boolean>();entry = {- promise: link.invoke(deviceId, channel, JSON.parse(argsKey)),+ promise: channel === 'local-db:sessions:get'+ ? readCompanionTask(taskReadScope, deviceId, JSON.parse(argsKey)[0], link.invoke,+ () => [...consumers].some((current) => current()))+ : link.invoke(deviceId, channel, JSON.parse(argsKey)),invalidated: false,+ consumers,};pending.set(binding, entry);const captured = entry;@@ -79,6 +86,7 @@ export function useRemoteCompanionQuery<T>(}).catch(() => undefined);}+ entry.consumers.add(() => !disposed && currentBinding.current === binding && AppState.currentState === 'active');void entry.promise.then((value) => {if (!disposed && generation === expected && currentBinding.current === binding) {@@ -125,7 +133,10 @@ export function useRemoteCompanionQuery<T>(});};load();- const interval = options.refreshIntervalMs+ const taskRefresh = channel === 'local-db:sessions:get' && options.refreshIntervalMs+ ? subscribeCompanionTaskRefresh(taskReadScope, options.refreshIntervalMs, load)+ : undefined;+ const interval = !taskRefresh && options.refreshIntervalMs? setInterval(load, options.refreshIntervalMs): undefined;const unsubscribe = subscribeRemoteBotChanges((source, changedChannel, payload) => {@@ -160,9 +171,11 @@ export function useRemoteCompanionQuery<T>(appState.remove();if (timer) clearTimeout(timer);if (interval) clearInterval(interval);+ taskRefresh?.();};}, [argsKey,+ taskReadScope,binding,channel,deviceId,diff --git a/docs/dev-rules/remote-and-mobile-adaptation.md b/docs/dev-rules/remote-and-mobile-adaptation.mdindex 91a9192990..2c8bdce09e 100644--- a/docs/dev-rules/remote-and-mobile-adaptation.md+++ b/docs/dev-rules/remote-and-mobile-adaptation.md@@ -427,6 +427,10 @@ Desktop 的同账号远程 Cindy Make 任务同样消费该投影:准备与测旧被控端不支持或批量回复超帧预算时回退到原有有界 GET;超时、撤权、损坏回复不触发成倍重试,迟到回复不能覆盖更新的 push。+Mobile 伙伴任务卡的列表外补读由 `companionTaskReads.ts` 按账号、连接代次和电脑聚合,+每批最多 8 个、批次串行;同组共享刷新时钟,旧端单条回退同样串行。焦点或账号切换后+不发送已失效的排队读取,不缓存已完成批次;卡片优先使用普通任务列表中的更新结果。+Debug 日志区分两层耗时:- `remote invoke slow execution`(至少 1 秒)包含 `stagesMs`:调用前授权、业务 handler、