Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(tasks): preserve cloud Cindy selection and publish ordinary rows first
zqchris2ff99f1fbda0
diff --git a/apps/desktop/scripts/fixtures/teammate-task-filter/fixture.tsx b/apps/desktop/scripts/fixtures/teammate-task-filter/fixture.tsxindex a0fbcae7c9..a210098e45 100644--- a/apps/desktop/scripts/fixtures/teammate-task-filter/fixture.tsx+++ b/apps/desktop/scripts/fixtures/teammate-task-filter/fixture.tsx@@ -5,6 +5,7 @@ import { persistCreators } from '../../../src/renderer/features/cc-agent/hooks/himport { useSidebarFilter } from '../../../src/renderer/features/cc-agent/hooks/useSidebarFilter';import { BotFollowMark, useSessionFollowers } from '../../../src/renderer/features/bots/BotFollowMark';import { matchesTaskCreators, useTaskCreatorIndex, useTaskCreatorOptions } from '../../../src/renderer/features/bots/botFollowScopes';+import { resetCompanionCloudStoreForTests } from '../../../src/renderer/features/bots/companionCloudStore';import { setDataOwnerGeneration } from '../../../src/renderer/contexts/dataOwnerGeneration';import type { Session } from '../../../src/renderer/lib/ccAgent.types';@@ -25,7 +26,7 @@ function TaskRow({ task }: { task: Session }) {</div>;}function Fixture() {- useState(() => { persistCreators(['["laptop","remote-cindy"]'], 'fixture'); return true; });+ useState(() => { persistCreators(['["companion","remote-cindy"]'], 'fixture'); return true; });const options = useTaskCreatorOptions();const hidden = useMemo(() => new Set<string>(), []);const filter = useSidebarFilter(hidden, snapshot, options);@@ -41,6 +42,8 @@ function Fixture() {mountPage({host: () => {setDataOwnerGeneration('fixture', 1);+ resetCompanionCloudStoreForTests({ enabled: true, selfDeviceId: 'desktop', humanActorId: 'human', demotedBotIds: [],+ actors: [{ id: 'actor', externalId: 'remote-cindy', name: 'Cindy', avatar: null, homeDeviceId: 'laptop' }] });return {authHasPersistedSessionHintSync: () => false,appearanceSettings: undefined,diff --git a/apps/desktop/scripts/fixtures/teammate-task-filter/ui-page.mjs b/apps/desktop/scripts/fixtures/teammate-task-filter/ui-page.mjsindex 77fb0d59fc..0ccc094635 100644--- a/apps/desktop/scripts/fixtures/teammate-task-filter/ui-page.mjs+++ b/apps/desktop/scripts/fixtures/teammate-task-filter/ui-page.mjs@@ -5,7 +5,7 @@ export default {notCovered: 'Live cross-device transport and host database reads; task/roster snapshots are fixture data. Pinned exemptions remain in the full sidebar.',stubs: {'src/renderer/features/bots/botStore': `const bots = [{id:'cindy-default',name:'Cindy',avatar:'',avatarColor:'blue',enabled:true,status:'active'}, { id:'dash',name:'Dash',avatar:'',avatarColor:'blue',enabled:true,status:'active' }]; export const useBotProfiles=()=>bots; export const hasLoadedBotProfiles=()=>true; export const ensureBotProfilesLoaded=async()=>bots;`,- 'src/renderer/features/bots/useRemoteBots': `const bots = [{id:'remote-cindy',templateId:'cindy',name:'Cindy',avatar:'',avatarColor:'blue',deviceId:'laptop',deviceName:'MacBook Pro',delegatedSessionIds:['cindy-remote']},{id:'lizi',name:'Lizi',avatar:'',avatarColor:'green',deviceId:'laptop',deviceName:'MacBook Pro',followingSessionIds:[],delegatedSessionIds:['remote']}]; export const useRemoteBots=()=>bots;`,+ 'src/renderer/features/bots/useRemoteBots': `const bots = [{id:'remote-cindy',templateId:'cindy',name:'Cindy',avatar:'',avatarColor:'blue',deviceId:'laptop',deviceName:'MacBook Pro',delegatedSessionIds:['cindy-remote']},{id:'lizi',name:'Lizi',avatar:'',avatarColor:'green',deviceId:'laptop',deviceName:'MacBook Pro',followingSessionIds:[],delegatedSessionIds:['remote']}]; export const useRemoteBots=()=>bots; const ids = new Set(['remote-cindy']); export const useRemoteCindyIds=()=>ids;`,'src/renderer/features/device-link/useMachineSwitcher': `export const useEffectiveSelectedMachineId=()=> 'all';`,'src/renderer/features/cc-agent/hooks/useRemoteHostProjectOrders': `export const useLocalHostProjectOrder=()=>({snapshot:undefined}); export const useRemoteHostProjectOrders=()=>({orders:new Map()}); export const projectOrderWriteScopeForSelection=()=>({kind:'viewer'}); export const controllerManualOrderForDevice=()=>[];`,},diff --git a/apps/desktop/src/renderer/__tests__/refreshRemoteSessionsRetry.test.ts b/apps/desktop/src/renderer/__tests__/refreshRemoteSessionsRetry.test.tsindex e492fedb13..78eb73f687 100644--- a/apps/desktop/src/renderer/__tests__/refreshRemoteSessionsRetry.test.ts+++ b/apps/desktop/src/renderer/__tests__/refreshRemoteSessionsRetry.test.ts@@ -1322,3 +1322,18 @@ it('does not resurrect teammate task discovery after its device snapshot is invaexpect(await refresh).toBe('superseded');expect(remoteProjectsStore.getDeviceSessions(device)).toEqual([]);});++// Unit / review4390134794: a blocked optional history read must not hide the+// already successful ordinary snapshot; existing tests only observe completion.+it('publishes ordinary tasks before legacy teammate discovery finishes', async () => {+ const device = did();+ const pending = deferred<{ ok: boolean; sessions: Session[]; hasMore: boolean }>();+ invoke.mockResolvedValue([session('ready')]);+ historyInvoke.mockReturnValue(pending.promise);+ const refresh = refreshRemoteDeviceSessions(device);+ await Promise.resolve(); await Promise.resolve();+ const earlyIds = remoteProjectsStore.getDeviceSessions(device).map(row => row.id);+ pending.resolve({ ok: true, sessions: [], hasMore: false });+ await expect(refresh).resolves.toBe('ok');+ expect(earlyIds).toContain('ready');+});diff --git a/apps/desktop/src/renderer/features/bots/__tests__/botFollowMark.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/botFollowMark.test.tsxindex e068e4fbae..84c6a676b0 100644--- a/apps/desktop/src/renderer/features/bots/__tests__/botFollowMark.test.tsx+++ b/apps/desktop/src/renderer/features/bots/__tests__/botFollowMark.test.tsx@@ -8,6 +8,7 @@ import type { Session } from '@/lib/ccAgent.types';const h = vi.hoisted(() => ({profiles: [] as Array<Record<string, unknown>>,remote: [] as Array<Record<string, unknown>>,+ cindyIds: new Set<string>(),}));vi.mock('react-i18next', () => ({@@ -22,7 +23,7 @@ vi.mock('../botStore', () => ({ensureBotProfilesLoaded: vi.fn(async () => h.profiles),}));-vi.mock('../useRemoteBots', () => ({ useRemoteBots: () => h.remote }));+vi.mock('../useRemoteBots', () => ({ useRemoteBots: () => h.remote, useRemoteCindyIds: () => h.cindyIds }));import { BotFollowMark, useSessionFollowers } from '../BotFollowMark';import { __testing, useSessionDelegatingBot, useTaskCreatorIndex, useTaskCreatorOptions, matchesTaskCreators, taskBotKey } from '../botFollowScopes';@@ -48,6 +49,7 @@ beforeEach(() => {__testing.reset();resetCompanionCloudStoreForTests();h.remote = [];+ h.cindyIds = new Set();h.profiles = [bot('bot-1', 'Dash'), bot('bot-2', 'Lizi')];followScopes.mockClear();(window as unknown as { electronAPI: unknown }).electronAPI = {@@ -283,3 +285,26 @@ it.each(['routine', 'channel'])('uses exact local/remote ownership for %s avatarexpect(matchesTaskCreators(remote, [remoteKey], result.current)).toBe(true);expect(matchesTaskCreators(local, [localKey, remoteKey], result.current)).toBe(true);});++// Unit / review4390134785: existing coverage starts with a real roster, missing+// the cloud-only -> known-Cindy -> online transition and saved companion alias.+it('keeps a cloud-only Cindy selection valid when identity and its home roster arrive', async () => {+ resetCompanionCloudStoreForTests({ enabled: true, selfDeviceId: 'desktop', humanActorId: 'human', demotedBotIds: [],+ actors: [{ id: 'actor', externalId: 'cloud-cindy', name: 'Cindy', avatar: null, homeDeviceId: 'laptop' }] });+ const { normalizeTaskCreators } = await import('../../cc-agent/hooks/helpers/sidebarFilterCore');+ const { result, rerender } = renderHook(() => ({ options: useTaskCreatorOptions(), index: useTaskCreatorIndex() }));+ const old = [JSON.stringify(['companion', 'cloud-cindy'])];+ expect(result.current.options.find(b => b.id === 'cloud-cindy')?.filterKey).toBe(old[0]);+ h.cindyIds = new Set(['cloud-cindy']);+ rerender();+ const known = result.current.options.find(b => b.id === 'cloud-cindy')!;+ const cindyKey = JSON.stringify(['teammate', 'cindy']);+ expect(known.filterKey).toBe(cindyKey);+ expect(known.deviceName).toBeUndefined();+ expect(normalizeTaskCreators(old, result.current.options)).toEqual([cindyKey]);+ h.remote = [{ ...bot('cloud-cindy', 'Renamed', { templateId: 'cindy' }), deviceId: 'laptop', delegatedSessionIds: ['child'] }];+ rerender();+ const selected = normalizeTaskCreators(old, result.current.options);+ expect(matchesTaskCreators(session({ id: 'child', deviceLinkDeviceId: 'laptop' }), selected, result.current.index)).toBe(true);+ expect(normalizeTaskCreators([...old, cindyKey], result.current.options)).toEqual([cindyKey]);+});diff --git a/apps/desktop/src/renderer/features/bots/__tests__/remoteBots.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/remoteBots.test.tsxindex 6f06bd921d..502a361e7b 100644--- a/apps/desktop/src/renderer/features/bots/__tests__/remoteBots.test.tsx+++ b/apps/desktop/src/renderer/features/bots/__tests__/remoteBots.test.tsx@@ -21,7 +21,7 @@ vi.mock('@/features/device-link/useDeviceLinkDeviceList', () => ({useDeviceLinkDeviceList: () => h.devices,}));vi.mock('@/lib/remoteDataOwnerPushFence', () => ({ isDeviceLinkRemotePushCurrent: () => true }));-import { useRemoteBotSync, useRemoteBots, markRemoteBotRead } from '../useRemoteBots';+import { useRemoteBotSync, useRemoteBots, useRemoteCindyIds, markRemoteBotRead } from '../useRemoteBots';import { parseRemoteCollectionListRequest, REMOTE_RESOURCE_LIST_CHANNEL, REMOTE_RESOURCE_CHANGED_CHANNEL } from '@cindy/device-link';import { parseRemoteBots, remoteBotKey, isRemoteBotUnread } from '../remoteBotRoster';const host = (deviceId: string, online = true) => ({@@ -267,3 +267,21 @@ it('applies cloud Cindy identity regardless of roster arrival order and rejectsawait act(async () => oldFinish([{ botId: 'same-bot' }]));expect(result.current.every(bot => bot.templateId === undefined)).toBe(true);});++// Unit / review4390134785: identity must be available without any roster rows;+// previous arrival-order coverage only read templateId on already listed rows.+it('exposes known Cindy IDs before an offline home provides its roster and clears on owner switch', async () => {+ h.devices = [];+ h.cloudEnabled = true;+ h.copies.mockResolvedValue([{ botId: 'same-bot' }]);+ const { result, rerender } = renderHook(() => {+ useRemoteBotSync();+ return { rows: useRemoteBots(), ids: useRemoteCindyIds() };+ });+ await waitFor(() => expect(result.current.ids.has('same-bot')).toBe(true));+ expect(result.current.rows).toEqual([]);+ h.owner = 'new-empty-owner';+ h.cloudEnabled = false;+ rerender();+ expect(result.current.ids.size).toBe(0);+});diff --git a/apps/desktop/src/renderer/features/bots/botFollowScopes.ts b/apps/desktop/src/renderer/features/bots/botFollowScopes.tsindex 695cee2bac..5ca12160e9 100644--- a/apps/desktop/src/renderer/features/bots/botFollowScopes.ts+++ b/apps/desktop/src/renderer/features/bots/botFollowScopes.ts@@ -9,7 +9,7 @@ import { createLogger } from '@/lib/logger';import { isTeammateTaskSession } from '../../../shared/sessionSource';import { isWorkbenchTaskSource } from '../../../shared/botWorkbench';-import { useRemoteBots } from './useRemoteBots';+import { useRemoteBots, useRemoteCindyIds } from './useRemoteBots';import { useCompanionCloud } from './companionCloudStore';import { cloudRemoteBots, withoutShadowedBots } from './companionCloudPresentation';import { taskCreatorFilterKey } from './cindyDeviceRoster';@@ -143,7 +143,7 @@ export type TaskBotIdentity = Pick<BotProfile, 'id' | 'name' | 'avatar' | 'avatataskRelation?: 'created' | 'owned';templateId?: string;filterKey?: string;- /** Previous per-computer selection keys, used to preserve existing filter choices. */+ /** Previous per-computer/cloud selection keys, preserving existing filter choices. */filterMemberKeys?: readonly string[];};@@ -151,27 +151,32 @@ export function useTaskCreatorOptions(): TaskBotIdentity[] {const profiles = useBotProfiles();const remote = useRemoteBots();const cloud = useCompanionCloud();+ const cindyIds = useRemoteCindyIds();return useMemo(() => {const grouped = new Map<string, TaskBotIdentity>();- for (const bot of [...withoutShadowedBots(profiles, cloud).filter(bot => !bot.hiddenAt && bot.status !== 'deleting'), ...cloudRemoteBots(cloud, remote)]) {+ for (const source of [...withoutShadowedBots(profiles, cloud).filter(bot => !bot.hiddenAt && bot.status !== 'deleting'), ...cloudRemoteBots(cloud, remote)]) {+ const bot = cindyIds.has(source.id) ? { ...source, templateId: 'cindy' } : source;const key = taskCreatorFilterKey(bot, cloud);+ const memberKeys = [taskBotKey(bot), ...(cloud.enabled && cloud.actors.some(actor => actor.externalId === bot.id)+ ? [JSON.stringify(['companion', bot.id])] : [])];const existing = grouped.get(key);if (existing) {- existing.filterMemberKeys = [...(existing.filterMemberKeys ?? []), taskBotKey(bot)];+ existing.filterMemberKeys = [...new Set([...(existing.filterMemberKeys ?? []), ...memberKeys])];} else {// Keep the original device ID for avatar resolution; the merged choice has no device subtitle.grouped.set(key, { ...bot, filterKey: key, deviceName: key === taskBotKey(bot) && 'deviceName' in bot ? bot.deviceName : undefined,- filterMemberKeys: [taskBotKey(bot)] });+ filterMemberKeys: memberKeys });}}// Old per-computer choices follow the same cloud companion after it moves home.- for (const bot of [...profiles, ...remote]) {+ for (const source of [...profiles, ...remote]) {+ const bot = cindyIds.has(source.id) ? { ...source, templateId: 'cindy' } : source;const option = grouped.get(taskCreatorFilterKey(bot, cloud));const member = taskBotKey(bot);if (option && !option.filterMemberKeys?.includes(member)) option.filterMemberKeys = [...(option.filterMemberKeys ?? []), member];}return [...grouped.values()].sort((a, b) => a.name.localeCompare(b.name));- }, [profiles, remote, cloud]);+ }, [profiles, remote, cloud, cindyIds]);}/** Indexed once for the sidebar, so selecting multiple creators does not scan every Bot per row. */@@ -180,24 +185,27 @@ export function useTaskCreatorIndex(): ReadonlyMap<string, ReadonlySet<string>>const profiles = useBotProfiles();const remote = useRemoteBots();const cloud = useCompanionCloud();+ const cindyIds = useRemoteCindyIds();return useMemo(() => {const index = new Map<string, Set<string>>();+ const filterKey = (bot: Pick<TaskBotIdentity, 'id' | 'deviceId' | 'templateId'>) =>+ taskCreatorFilterKey(cindyIds.has(bot.id) ? { ...bot, templateId: 'cindy' } : bot, cloud);const add = (bot: Pick<TaskBotIdentity, 'id' | 'deviceId' | 'templateId'>, ids: readonly string[] | undefined) => {for (const id of ids ?? []) {const key = taskCreatorSessionKey(id, bot.deviceId);const creators = index.get(key) ?? new Set<string>();- creators.add(taskCreatorFilterKey(bot, cloud));+ creators.add(filterKey(bot));index.set(key, creators);}};for (const bot of [...profiles, ...remote]) {- index.set(`creator:${taskBotKey(bot)}`, new Set([taskCreatorFilterKey(bot, cloud)]));+ index.set(`creator:${taskBotKey(bot)}`, new Set([filterKey(bot)]));}const localById = new Map(profiles.map(bot => [bot.id, bot]));for (const scope of scopes) add(localById.get(scope.botId) ?? { id: scope.botId }, scope.delegatedSessionIds);for (const bot of remote) add(bot, bot.delegatedSessionIds);return index;- }, [scopes, profiles, remote, cloud]);+ }, [scopes, profiles, remote, cloud, cindyIds]);}function taskCreatorSessionKey(id: string, deviceId?: string): string {diff --git a/apps/desktop/src/renderer/features/bots/useRemoteBots.ts b/apps/desktop/src/renderer/features/bots/useRemoteBots.tsindex afd4fd896f..beb4ad66d5 100644--- a/apps/desktop/src/renderer/features/bots/useRemoteBots.ts+++ b/apps/desktop/src/renderer/features/bots/useRemoteBots.ts@@ -45,6 +45,14 @@ export function useRemoteBots(): readonly RemoteBot[] {return isAuthenticated && owner === dataOwnerId ? rows : empty;}+/** Identity discovery is independent of a home computer's roster being online. */+export function useRemoteCindyIds(): ReadonlySet<string> {+ const { dataOwnerId, isAuthenticated } = useAuth();+ const ids = useSyncExternalStore(subscribe, () => cindyIds);+ return isAuthenticated && owner === dataOwnerId ? ids : EMPTY_CINDY_IDS;+}+const EMPTY_CINDY_IDS: ReadonlySet<string> = new Set();+/** One subscription owner in the main window; a failed host cannot erase another host. */export function useRemoteBotSync(): void {const { dataOwnerId, isAuthenticated } = useAuth();diff --git a/apps/desktop/src/renderer/features/cc-agent/hooks/helpers/sidebarFilterCore.ts b/apps/desktop/src/renderer/features/cc-agent/hooks/helpers/sidebarFilterCore.tsindex df029a5bb3..848bbdad0b 100644--- a/apps/desktop/src/renderer/features/cc-agent/hooks/helpers/sidebarFilterCore.ts+++ b/apps/desktop/src/renderer/features/cc-agent/hooks/helpers/sidebarFilterCore.ts@@ -161,6 +161,18 @@ export function persistCreators(value: FilterCreators, ownerId: string | null):writeSidebarOwnerStorage(CREATORS_KEY, ownerId, JSON.stringify(value));}+/** Canonicalize both per-device and older cloud-companion selections after discovery. */+export function normalizeTaskCreators(+ selected: FilterCreators,+ options: readonly { filterKey?: string; filterMemberKeys?: readonly string[] }[],+): FilterCreators {+ if (selected === 'all') return selected;+ const aliases = new Map(options.flatMap(bot => bot.filterKey+ ? (bot.filterMemberKeys ?? []).map(member => [member, bot.filterKey!] as const) : []));+ const next = [...new Set(selected.map(key => aliases.get(key) ?? key))];+ return next.length === selected.length && next.every((key, i) => key === selected[i]) ? selected : next;+}+export function nextCreatorsAfterToggle(previous: FilterCreators, key: string): FilterCreators {if (previous === 'all') return [key];const next = previous.includes(key) ? previous.filter(value => value !== key) : [...previous, key];diff --git a/apps/desktop/src/renderer/features/cc-agent/hooks/useSidebarFilter.ts b/apps/desktop/src/renderer/features/cc-agent/hooks/useSidebarFilter.tsindex 2edd08ea25..15e9a54dc1 100644--- a/apps/desktop/src/renderer/features/cc-agent/hooks/useSidebarFilter.ts+++ b/apps/desktop/src/renderer/features/cc-agent/hooks/useSidebarFilter.ts@@ -45,7 +45,6 @@import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';-import { taskCreatorFilterKey } from '@/features/bots/cindyDeviceRoster';import type { TaskBotIdentity } from '@/features/bots/botFollowScopes';import { createLogger } from '@/lib/logger';import { isDataOwnerPushStampCurrent } from '@/contexts/dataOwnerGeneration';@@ -60,6 +59,7 @@ import {loadCreators,persistCreators,nextCreatorsAfterToggle,+ normalizeTaskCreators,type FilterCreators,loadStatus,loadProjects,@@ -238,13 +238,8 @@ export function useSidebarFilter(const [status, setStatusState] = useState<FilterStatus>(() => loadStatus());const [projects, setProjectsState] = useState<FilterProjects>(() => loadProjects(ownerId));const [storedCreators, setCreators] = useState<FilterCreators>(() => loadCreators(ownerId));- const normalizeCreators = useCallback((selected: FilterCreators): FilterCreators => {- if (selected === 'all') return selected;- const aliases = new Map(creatorOptions.flatMap(bot => (bot.filterMemberKeys ?? [])- .map(member => [member, taskCreatorFilterKey(bot)] as const)));- const next = [...new Set(selected.map(key => aliases.get(key) ?? key))];- return next.length === selected.length && next.every((key, i) => key === selected[i]) ? selected : next;- }, [creatorOptions]);+ const normalizeCreators = useCallback((selected: FilterCreators): FilterCreators =>+ normalizeTaskCreators(selected, creatorOptions), [creatorOptions]);const creators = useMemo(() => normalizeCreators(storedCreators), [normalizeCreators, storedCreators]);useEffect(() => {if (creators === storedCreators) return;diff --git a/apps/desktop/src/renderer/features/device-link/refreshRemoteSessions.ts b/apps/desktop/src/renderer/features/device-link/refreshRemoteSessions.tsindex e94abcb223..6ababcb35d 100644--- a/apps/desktop/src/renderer/features/device-link/refreshRemoteSessions.ts+++ b/apps/desktop/src/renderer/features/device-link/refreshRemoteSessions.ts@@ -407,6 +407,9 @@ async function runRefreshRemoteDeviceSessions(if (!remoteProjectsStore.isLatestSnapshotEpoch(deviceId, epoch, status))return 'superseded';const ordinary = parseRemoteSessionList(value, status);+ // Optional old-host history may span many pages. Publish the successful+ // ordinary read now; reconcile removals only after discovery completes.+ remoteProjectsStore.mergeDeviceSessions(deviceId, deviceName, ordinary, status);const teammateTasks = await readRemoteTeammateTasks(deviceId, status, listLimit,() => remoteProjectsStore.isLatestSnapshotEpoch(deviceId, epoch, status));if (!remoteProjectsStore.isLatestSnapshotEpoch(deviceId, epoch, status)) return 'superseded';diff --git a/apps/mobile/app/devices/[deviceId].tsx b/apps/mobile/app/devices/[deviceId].tsxindex eb738f095f..4902e095db 100644--- a/apps/mobile/app/devices/[deviceId].tsx+++ b/apps/mobile/app/devices/[deviceId].tsx@@ -349,6 +349,11 @@ function DeviceDetailScreenContent() {return readTeammateTasks({ invoke, deviceId, deviceName, scope: JSON.stringify([owner, deviceId, listQueryScope]),sessions: Array.isArray(sessions) ? sessions : [], previous: remoteSessionStore.getHomeSessions(),status: requestedListFilter, limit: LIST_LIMIT, current: isCurrentQuery,+ publishInitial: rows => {+ if (isCurrentQuery() && remoteSessionStore.isDeviceSessionListMutationEpochCurrent(deviceId, mutationEpoch)) {+ remoteSessionStore.setDeviceSessions(deviceId, deviceName, rows);+ }+ },});});if (!isCurrentQuery()) return;diff --git a/apps/mobile/src/__tests__/readTeammateTasks.test.ts b/apps/mobile/src/__tests__/readTeammateTasks.test.tsindex f1322f7894..54238ff975 100644--- a/apps/mobile/src/__tests__/readTeammateTasks.test.ts+++ b/apps/mobile/src/__tests__/readTeammateTasks.test.ts@@ -79,3 +79,21 @@ describe('mobile teammate task list', () => {expect(taskTeammateOptions(rows, cloud, 'en', cindyIds)[0].key).toBe(JSON.stringify(['teammate', 'cindy']));});});++// Unit / review4390134794: one ordinary task + a cached channel + a pending+// history response. The production callback must publish without awaiting it.+it('publishes ordinary rows and cached lane ownership before optional history completes', async () => {+ let finish!: (value: unknown) => void;+ const pending = new Promise(resolve => { finish = resolve; });+ const lane = task('lane', { deviceLinkDeviceId: 'mac', source: 'bot', companion: { id: 'cindy-default', role: 'channel' } });+ const owned = task('ordinary', { deviceLinkDeviceId: 'mac', taskTeammate: { id: 'cindy-default', name: 'Cindy' } });+ const publishInitial = vi.fn();+ const invoke = vi.fn(async (_device: string, api: string) => api === 'local-db:history:query'+ ? pending : { collectionId: 'teammates', items: [] });+ const reading = readTeammateTasks({ ...input, invoke: invoke as RemoteInvoke, sessions: [task('ordinary')], previous: [owned, lane], publishInitial });+ const initial = publishInitial.mock.calls[0]?.[0];+ finish({ ok: true, sessions: [] });+ await reading;+ expect(initial?.map((row: RemoteSession) => row.id)).toEqual(['ordinary', 'lane']);+ expect(initial?.[0].taskTeammate?.id).toBe('cindy-default');+});diff --git a/apps/mobile/src/session/HomeSurface.tsx b/apps/mobile/src/session/HomeSurface.tsxindex ec12a542a1..48f41083b2 100644--- a/apps/mobile/src/session/HomeSurface.tsx+++ b/apps/mobile/src/session/HomeSurface.tsx@@ -984,6 +984,12 @@ function HomeScreenContent({ active = true, width, newSessionInSystemBar = falsescope: JSON.stringify([expectedAccountGeneration, expectedHomeSyncGeneration, device.deviceId]),sessions: Array.isArray(list) ? list : [], previous: remoteSessionStore.getHomeSessions(),status: requestedListFilter, limit: LIST_LIMIT,+ publishInitial: rows => {+ assertCurrentScope();+ if (remoteSessionStore.isDeviceSessionListMutationEpochCurrent(device.deviceId, epoch)) {+ remoteSessionStore.setDeviceSessions(device.deviceId, device.name, rows);+ }+ },current: () => homeAccountGenerationRef.current === expectedAccountGeneration&& isCurrentHomeSyncTarget(device.deviceId, expectedHomeSyncGeneration),});diff --git a/apps/mobile/src/session/readTeammateTasks.ts b/apps/mobile/src/session/readTeammateTasks.tsindex 59f05b334b..4beae4d273 100644--- a/apps/mobile/src/session/readTeammateTasks.ts+++ b/apps/mobile/src/session/readTeammateTasks.ts@@ -12,11 +12,22 @@ export async function readTeammateTasks(input: {invoke: RemoteInvoke; deviceId: string; deviceName: string; scope: string;sessions: readonly RemoteSession[]; previous?: readonly RemoteSession[];status: string; limit: number; current(): boolean;+ /** Publish the ordinary snapshot before optional history/roster reads finish. */+ publishInitial?(sessions: RemoteSession[]): void;}): Promise<RemoteSession[]> {const { invoke, deviceId, current, status, limit } = input;const matches = (s: RemoteSession) => s.status !== 'deleted' && (status === 'all' || s.status === status || !!s.pinnedAt);const rows = new Map(input.sessions.map(row => [row.id, row]));const previous = new Map((input.previous ?? []).filter(row => row.deviceLinkDeviceId === deviceId).map(row => [row.id, row]));+ if (!current()) return [];+ if (input.publishInitial) {+ const initial = new Map<string, RemoteSession>();+ for (const row of rows.values()) if (row.source !== 'bot' || isTeammateTask(row)) {+ initial.set(row.id, { ...row, taskTeammate: row.taskTeammate ?? previous.get(row.id)?.taskTeammate });+ }+ for (const row of previous.values()) if (!initial.has(row.id) && isTeammateTask(row) && matches(row)) initial.set(row.id, row);+ input.publishInitial([...initial.values()]);+ }// Independent from roster support: old hosts' history carries the exact lane owner.try {const links = new Map<string, NonNullable<RemoteSession['companion']>>();