Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(desktop): 恢复设置前选中的远程任务并等待冷启动发现

DavidShenbdc314813277
diff --git a/apps/desktop/src/renderer/__tests__/remoteProjectsStartup.test.tsx b/apps/desktop/src/renderer/__tests__/remoteProjectsStartup.test.tsx
index c7aa4c8ce2..0be5290573 100644
--- a/apps/desktop/src/renderer/__tests__/remoteProjectsStartup.test.tsx
+++ b/apps/desktop/src/renderer/__tests__/remoteProjectsStartup.test.tsx
@@ -1,11 +1,17 @@
// @vitest-environment jsdom
-import { act, cleanup, renderHook } from '@testing-library/react';
+import { act, cleanup, render, renderHook } from '@testing-library/react';
import { afterEach, expect, it, vi } from 'vitest';
const state = vi.hoisted(() => ({
refresh: vi.fn(async () => 'ok'),
translate: (key: string) => key,
readCache: vi.fn(async (): Promise<import('@/features/device-link/mirrorCacheClient').CachedDeviceSessionsSnapshot[]> => []),
+ navigate: vi.fn(),
+ localSessions: [{ id: 'local-B', status: 'active', source: 'desktop' }] as import('@/lib/ccAgent.types').Session[],
+}));
+vi.mock('react-router-dom', () => ({ useNavigate: () => state.navigate }));
+vi.mock('@/hooks/useCCSessions', () => ({
+ useCCSessions: () => ({ sessions: state.localSessions, isLoading: false }),
}));
vi.mock('react-i18next', async (importOriginal) => ({
...await importOriginal<typeof import('react-i18next')>(),
@@ -46,18 +52,167 @@ import { clearCachedDevice } from '@/features/device-link/mirrorCacheClient';
import { remoteProjectAliases } from '@/features/device-link/remoteProjectAliases';
import { setDataOwnerGeneration } from '@/contexts/dataOwnerGeneration';
import { resetRemoteDataOwnerPushFence } from '@/lib/remoteDataOwnerPushFence';
+import { CCAgentIndexRedirect } from '@/features/cc-agent/CCAgentIndexRedirect';
+import { clearLastView, saveLastChatView } from '@/features/cc-agent/lib/lastViewStore';
afterEach(() => {
cleanup();
vi.useRealTimers();
- state.refresh.mockClear();
+ state.refresh.mockReset().mockResolvedValue('ok');
state.readCache.mockReset().mockResolvedValue([]);
+ state.navigate.mockReset();
+ clearLastView();
vi.mocked(clearCachedDevice).mockClear();
setDataOwnerGeneration(null, 0);
resetRemoteDataOwnerPushFence();
Reflect.deleteProperty(window, 'electronAPI');
});
+// #7437 / unit: real startup hook + redirect + mirror. Earlier tests seeded
+// bootstrap before mount, missing local-B arriving before cache/device discovery.
+// Deferred IPC replies verify the visible route without network or real waits.
+// Standalone on Windows: 3.38s Vitest / 57ms tests (17 cases, one worker).
+function deferred<T>() {
+ let resolve!: (value: T) => void;
+ let reject!: (reason: Error) => void;
+ const promise = new Promise<T>((done, fail) => { resolve = done; reject = fail; });
+ return { promise, resolve, reject };
+}
+
+function StartupRoute() {
+ useDeviceLinkRemoteProjects();
+ return <CCAgentIndexRedirect />;
+}
+
+function setupStartup() {
+ vi.useFakeTimers();
+ const cache = deferred<Awaited<ReturnType<typeof state.readCache>>>();
+ const link = deferred<{ linkStatus: string }>();
+ const directory = deferred<{ devices: Array<{
+ deviceId: string; name: string; online: boolean; remoteControlEnabled: boolean; isSelf: boolean;
+ }> }>();
+ state.readCache.mockReturnValue(cache.promise);
+ const listen = () => () => {};
+ let onStatus = (_event: { status: string }) => {};
+ Object.defineProperty(window, 'electronAPI', { configurable: true, value: { deviceLink: {
+ getState: () => link.promise,
+ listDevices: () => directory.promise,
+ subscribe: async () => {},
+ unsubscribe: async () => {},
+ onPresenceChanged: listen,
+ onStatusChanged: (callback: typeof onStatus) => { onStatus = callback; return () => {}; },
+ onAccessRevoked: listen,
+ onControlTargetChanged: listen, onRemotePush: listen, onResponsivenessChanged: listen,
+ } } });
+ saveLastChatView({ kind: 'session', sessionId: 'remote-A' });
+ return { cache, link, directory, stop: () => onStatus({ status: 'stopped' }) };
+}
+
+it('waits for late cold cache after device discovery settles', async () => {
+ const { cache, link, directory } = setupStartup();
+ await act(async () => { render(<StartupRoute />); });
+ expect(state.navigate).not.toHaveBeenCalled();
+ await act(async () => {
+ link.resolve({ linkStatus: 'connecting' });
+ directory.resolve({ devices: [{ deviceId: 'peer', name: 'Peer', online: false, remoteControlEnabled: false, isSelf: false }] });
+ });
+ expect(state.navigate).not.toHaveBeenCalled();
+ await act(async () => {
+ cache.resolve([{ deviceId: 'peer', deviceName: 'Peer', sessions: [
+ { id: 'remote-A', status: 'active', source: 'desktop' } as import('@/lib/ccAgent.types').Session,
+ ] }]);
+ });
+ expect(state.navigate).toHaveBeenCalledExactlyOnceWith('/cc-agent/remote-A', { replace: true });
+});
+
+it('waits across delayed getState, device discovery and the first remote snapshot', async () => {
+ const { cache, link, directory } = setupStartup();
+ const snapshot = deferred<string>();
+ state.refresh.mockImplementationOnce(async () => {
+ await snapshot.promise;
+ remoteProjectsStore.setDeviceSessions('peer', 'Peer', [
+ { id: 'remote-A', status: 'active', source: 'desktop' } as import('@/lib/ccAgent.types').Session,
+ ]);
+ return 'ok';
+ });
+ await act(async () => { render(<StartupRoute />); cache.resolve([]); });
+ expect(state.navigate).not.toHaveBeenCalled();
+ await act(async () => { link.resolve({ linkStatus: 'online' }); });
+ expect(state.navigate).not.toHaveBeenCalled();
+ await act(async () => {
+ directory.resolve({ devices: [{ deviceId: 'peer', name: 'Peer', online: true, remoteControlEnabled: true, isSelf: false }] });
+ });
+ expect(state.navigate).not.toHaveBeenCalled();
+ await act(async () => { snapshot.resolve('ok'); });
+ expect(state.navigate).toHaveBeenCalledExactlyOnceWith('/cc-agent/remote-A', { replace: true });
+});
+
+it.each(['empty', 'failed'] as const)('ends the initial wait when discovery is %s', async (outcome) => {
+ const { cache, link, directory } = setupStartup();
+ await act(async () => { render(<StartupRoute />); });
+ expect(state.navigate).not.toHaveBeenCalled();
+ await act(async () => {
+ if (outcome === 'failed') {
+ // The real cache client resolves [] on failure (best-effort contract).
+ cache.resolve([]);
+ link.reject(new Error('state unavailable'));
+ // listDevices is invoked after getState settles; reject once subscribed.
+ await Promise.resolve();
+ await Promise.resolve();
+ directory.reject(new Error('directory unavailable'));
+ } else {
+ cache.resolve([]);
+ link.resolve({ linkStatus: 'connecting' });
+ directory.resolve({ devices: [] });
+ }
+ });
+ expect(state.navigate).toHaveBeenCalledExactlyOnceWith('/cc-agent/local-B', { replace: true });
+});
+
+it('releases the initial wait when Device Link stops, ignoring late completion', async () => {
+ const { cache, link, directory, stop } = setupStartup();
+ await act(async () => { render(<StartupRoute />); });
+ expect(state.navigate).not.toHaveBeenCalled();
+ await act(async () => { stop(); });
+ expect(state.navigate).toHaveBeenCalledExactlyOnceWith('/cc-agent/local-B', { replace: true });
+ await act(async () => {
+ cache.resolve([]);
+ link.resolve({ linkStatus: 'connecting' });
+ directory.resolve({ devices: [] });
+ });
+ expect(state.navigate).toHaveBeenCalledTimes(1);
+});
+
+it('does not let cancelled initialization settle a newly mounted synchronizer', async () => {
+ const old = setupStartup();
+ let view!: ReturnType<typeof render>;
+ await act(async () => { view = render(<StartupRoute />); });
+ view.unmount();
+ expect(remoteProjectsStore.getInitialDiscoverySettled()).toBe(true);
+ const current = setupStartup();
+ await act(async () => { render(<StartupRoute />); });
+ await act(async () => {
+ old.cache.resolve([]);
+ old.link.resolve({ linkStatus: 'connecting' });
+ old.directory.resolve({ devices: [] });
+ });
+ expect(state.navigate).not.toHaveBeenCalled();
+ expect(remoteProjectsStore.getInitialDiscoverySettled()).toBe(false);
+ await act(async () => {
+ current.cache.resolve([]);
+ current.link.resolve({ linkStatus: 'connecting' });
+ current.directory.resolve({ devices: [] });
+ });
+ expect(state.navigate).toHaveBeenCalledExactlyOnceWith('/cc-agent/local-B', { replace: true });
+});
+
+it('restores a known local task while remote initialization is still pending', async () => {
+ setupStartup();
+ saveLastChatView({ kind: 'session', sessionId: 'local-B' });
+ await act(async () => { render(<StartupRoute />); });
+ expect(state.navigate).toHaveBeenCalledExactlyOnceWith('/cc-agent/local-B', { replace: true });
+});
+
it.each(['deleted', 'refused'] as const)('handles confirmed deletion before the old cold cache returns: %s', async (outcome) => {
vi.useFakeTimers();
let finishCache!: (devices: Awaited<ReturnType<typeof state.readCache>>) => void;
diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentIndexRedirect.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentIndexRedirect.tsx
index b5243c845c..0254a1d51f 100644
--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentIndexRedirect.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentIndexRedirect.tsx
@@ -6,44 +6,76 @@
* 启动恢复优先级(lastViewStore.loadLastChatView):
* 1. 上次是 /cc-agent/new 草稿 → 直接回到 /cc-agent/new
* 2. 上次是某个 session:
- * - sessionId 仍在当前 active 列表 → 还原到 /cc-agent/:sessionId
+ * - sessionId 仍在本机或远程 active 列表 → 还原到 /cc-agent/:sessionId
* - sessionId 已删除 / 归档 → 回落到默认逻辑
* 3. 无记录 / 记录失效 → 默认逻辑:
- * - 列表非空 → navigate 到 sessions[0].id(最近更新的)
+ * - 列表非空 → 取首个有效任务(保留本机列表优先,远程补充)
* - 列表为空 → navigate 到 /cc-agent/new
*
* Loading 期间不触发 navigate,显示加载占位。
*/
-import { useEffect, useRef } from 'react';
+import { useEffect, useMemo, useRef } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { CINDY_MAKE_ENABLED, isCindyMakeSource } from '@cindy/maker-shared/cindy-make-feature';
import { useCCSessions } from '@/hooks/useCCSessions';
import {
- isOrcaLeadSession,
- isOrcaWorkerSession,
-} from '@/lib/orcaSessionIdentity';
+ getSessionDeviceId,
+ useRemoteBootstrapLoadingDeviceIds,
+ useRemoteInitialDiscoverySettled,
+ useRemoteProjectSessions,
+} from '@/features/device-link/remoteProjectsStore';
+import { isOrcaLeadSession, isOrcaWorkerSession } from '@/lib/orcaSessionIdentity';
import { orcaWorkflowsFor } from '@/lib/makerTransport';
import { loadLastChatView } from './lib/lastViewStore';
+import { mergeSessionSources } from './lib/mergeSessionSources';
export function CCAgentIndexRedirect() {
const { t } = useTranslation();
- const { sessions, isLoading } = useCCSessions();
+ const { sessions: localSessions, isLoading } = useCCSessions();
+ const remoteSessions = useRemoteProjectSessions();
+ const remoteLoadingDeviceIds = useRemoteBootstrapLoadingDeviceIds();
+ const remoteInitialDiscoverySettled = useRemoteInitialDiscoverySettled();
+ const allSessions = useMemo(
+ () => mergeSessionSources(localSessions, remoteSessions),
+ [localSessions, remoteSessions],
+ );
+ // The mirror also retains archived rows and companion/side-chat detail reads.
+ // Match the ordinary active-task list before restoring or choosing a fallback.
+ const sessions = useMemo(
+ () =>
+ allSessions.filter(
+ (session) =>
+ session.status !== 'archived' &&
+ session.status !== 'deleted' &&
+ session.source !== 'bot' &&
+ session.source !== 'side-chat' &&
+ (CINDY_MAKE_ENABLED || !isCindyMakeSource(session.source)),
+ ),
+ [allSessions],
+ );
const navigate = useNavigate();
const hasRedirected = useRef(false);
useEffect(() => {
if (isLoading || hasRedirected.current) return;
- hasRedirected.current = true;
let cancelled = false;
+ const redirect = (route: string) => {
+ if (cancelled || hasRedirected.current) return;
+ // Lock only once navigation commits: an effect cancelled by a newer
+ // snapshot (or StrictMode) must be allowed to resolve the route again.
+ hasRedirected.current = true;
+ navigate(route, { replace: true });
+ };
void (async () => {
const last = loadLastChatView();
const sessionIdSet = new Set(sessions.map((s) => s.id));
- const routeForSession = async (session: typeof sessions[number]): Promise<string | null> => {
- if (!CINDY_MAKE_ENABLED && isCindyMakeSource(session.source)) return null;
+ const routeForSession = async (
+ session: (typeof sessions)[number],
+ ): Promise<string | null> => {
if (isOrcaLeadSession(session)) return `/cc-agent/${session.id}`;
if (!isOrcaWorkerSession(session)) return `/cc-agent/${session.id}`;
const workflow = await orcaWorkflowsFor(session.id)
@@ -58,35 +90,46 @@ export function CCAgentIndexRedirect() {
};
if (last?.kind === 'new') {
- if (!cancelled) navigate('/cc-agent/new', { replace: true });
+ redirect('/cc-agent/new');
return;
}
if (last?.kind === 'session') {
const lastSession = sessions.find((s) => s.id === last.sessionId);
+ // Missing from an in-flight remote snapshot is not evidence of deletion.
+ // Known archived/hidden rows may fall back immediately. Existing mirrors
+ // remain usable offline; no network request or reconnect is started here.
+ if (!lastSession && !allSessions.some((s) => s.id === last.sessionId)) {
+ if (!remoteInitialDiscoverySettled) return;
+ const deviceId = getSessionDeviceId(last.sessionId);
+ if (deviceId ? remoteLoadingDeviceIds.has(deviceId) : remoteLoadingDeviceIds.size > 0)
+ return;
+ }
const route = lastSession ? await routeForSession(lastSession) : null;
+ if (cancelled) return;
if (route) {
- if (!cancelled) navigate(route, { replace: true });
+ redirect(route);
return;
}
// 失效(删除 / 归档)→ 落到默认逻辑
}
for (const session of sessions) {
+ if (cancelled) return;
const route = await routeForSession(session);
if (route) {
- if (!cancelled) navigate(route, { replace: true });
+ redirect(route);
return;
}
}
// 列表为空 → transient draft route(无后端 session)
- if (!cancelled) navigate('/cc-agent/new', { replace: true });
+ redirect('/cc-agent/new');
})();
return () => {
cancelled = true;
};
- }, [isLoading, sessions, navigate]);
+ }, [isLoading, sessions, allSessions, remoteLoadingDeviceIds, remoteInitialDiscoverySettled, navigate]);
// Loading placeholder while data resolves.
return (
diff --git a/apps/desktop/src/renderer/features/cc-agent/__tests__/CindyMakeIndexRedirect.test.tsx b/apps/desktop/src/renderer/features/cc-agent/__tests__/CindyMakeIndexRedirect.test.tsx
index 9c5d60e250..69090ff1e5 100644
--- a/apps/desktop/src/renderer/features/cc-agent/__tests__/CindyMakeIndexRedirect.test.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/__tests__/CindyMakeIndexRedirect.test.tsx
@@ -1,17 +1,67 @@
// @vitest-environment jsdom
-import { cleanup, render, waitFor } from '@testing-library/react';
+import { StrictMode } from 'react';
+import { act, cleanup, render, waitFor } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type { Session } from '@/lib/ccAgent.types';
import { CCAgentIndexRedirect } from '../CCAgentIndexRedirect';
+import { remoteProjectsStore } from '@/features/device-link/remoteProjectsStore';
+import { clearLastView, saveLastChatView } from '../lib/lastViewStore';
-const state = vi.hoisted(() => ({ sessions: [] as Session[], navigate: vi.fn() }));
-vi.mock('@/hooks/useCCSessions', () => ({ useCCSessions: () => ({ sessions: state.sessions, isLoading: false }) }));
+const state = vi.hoisted(() => ({
+ sessions: [] as Session[],
+ isLoading: false,
+ navigate: vi.fn(),
+ getWorkflow: vi.fn(),
+}));
+vi.mock('@/hooks/useCCSessions', () => ({
+ useCCSessions: () => ({ sessions: state.sessions, isLoading: state.isLoading }),
+}));
vi.mock('react-router-dom', () => ({ useNavigate: () => state.navigate }));
vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
-vi.mock('../lib/lastViewStore', () => ({ loadLastChatView: () => ({ kind: 'session', sessionId: 'make' }) }));
-vi.mock('@/lib/makerTransport', () => ({ getSessionFor: vi.fn(), orcaWorkflowsFor: vi.fn() }));
-afterEach(cleanup);
-beforeEach(() => { state.sessions = []; state.navigate.mockReset(); });
+vi.mock('@/lib/makerTransport', () => ({
+ getSessionFor: vi.fn(),
+ orcaWorkflowsFor: () => ({ getByWorkerSession: state.getWorkflow }),
+}));
+afterEach(() => {
+ cleanup();
+ remoteProjectsStore.clear();
+ clearLastView();
+});
+beforeEach(() => {
+ state.sessions = [];
+ state.isLoading = false;
+ state.navigate.mockReset();
+ state.getWorkflow.mockReset().mockResolvedValue(null);
+ remoteProjectsStore.clear();
+ remoteProjectsStore.__resetPinnedOriginsForTest();
+ clearLastView();
+ saveLastChatView({ kind: 'session', sessionId: 'make' });
+});
+
+/** Minimal active list row; URLs below are router paths, not filesystem paths. */
+function task(id: string, extra: Partial<Session> = {}): Session {
+ return { id, status: 'active', source: 'desktop', ...extra } as Session;
+}
+
+function deferred<T>() {
+ let resolve!: (value: T) => void;
+ const promise = new Promise<T>((done) => {
+ resolve = done;
+ });
+ return { promise, resolve };
+}
+
+async function mount() {
+ let view!: ReturnType<typeof render>;
+ await act(async () => {
+ view = render(<CCAgentIndexRedirect />);
+ });
+ return view;
+}
+
+function expectRoute(route: string) {
+ expect(state.navigate).toHaveBeenCalledExactlyOnceWith(route, { replace: true });
+}
describe('startup after hiding Cindy Make', () => {
it('skips the last Make task and hidden cached rows when restoring a task', async () => {
@@ -21,14 +71,219 @@ describe('startup after hiding Cindy Make', () => {
{ id: 'ordinary', source: 'desktop' },
] as Session[];
render(<CCAgentIndexRedirect />);
- await waitFor(() => expect(state.navigate).toHaveBeenCalledWith('/cc-agent/ordinary', { replace: true }));
+ await waitFor(() =>
+ expect(state.navigate).toHaveBeenCalledWith('/cc-agent/ordinary', { replace: true }),
+ );
expect(state.navigate).toHaveBeenCalledTimes(1);
});
it('opens a draft when all cached tasks belong to Cindy Make', async () => {
state.sessions = [{ id: 'make', source: 'cindy-make' }] as Session[];
render(<CCAgentIndexRedirect />);
- await waitFor(() => expect(state.navigate).toHaveBeenCalledWith('/cc-agent/new', { replace: true }));
+ await waitFor(() =>
+ expect(state.navigate).toHaveBeenCalledWith('/cc-agent/new', { replace: true }),
+ );
expect(state.navigate).toHaveBeenCalledTimes(1);
});
});
+
+/**
+ * #7437 / unit: mount the real redirect with the real remote mirror and last-view
+ * storage, asserting navigation. Existing cases only covered hidden Make rows.
+ * Minimal failure: last=A exists only in the remote mirror, local list=[B].
+ * Deferred workflow reads also expose cancellation during a mirror update.
+ * Standalone run on Windows: 3.4s wall time (Vitest 1.63s, tests 115ms).
+ */
+describe('restoring tasks after Settings', () => {
+ it.each([true, false])('restores remote A with local tasks=%s', async (hasLocal) => {
+ state.sessions = hasLocal ? [task('B')] : [];
+ remoteProjectsStore.setDeviceSessions('host', 'Host', [task('A')]);
+ saveLastChatView({ kind: 'session', sessionId: 'A' });
+ await mount();
+ expectRoute('/cc-agent/A');
+ });
+
+ it('restores an offline remote snapshot instead of selecting a local task', async () => {
+ state.sessions = [task('B')];
+ remoteProjectsStore.hydrateFromCache([
+ { deviceId: 'host', deviceName: 'Host', sessions: [task('A')] },
+ ]);
+ saveLastChatView({ kind: 'session', sessionId: 'A' });
+ await mount();
+ expectRoute('/cc-agent/A');
+ });
+
+ it.each(['archived', 'deleted', 'removed'] as const)(
+ 'falls back when remote A is %s',
+ async (change) => {
+ state.sessions = [task('B')];
+ remoteProjectsStore.setDeviceSessions('host', 'Host', [task('A')]);
+ if (change === 'removed') remoteProjectsStore.removeDevice('host');
+ else remoteProjectsStore.applyPatch('host', 'A', { status: change });
+ saveLastChatView({ kind: 'session', sessionId: 'A' });
+ await mount();
+ expectRoute('/cc-agent/B');
+ },
+ );
+
+ it('excludes archived and non-task remote rows from default selection', async () => {
+ remoteProjectsStore.setDeviceSessions('host', 'Host', [task('archived')], 'archived');
+ remoteProjectsStore.mergeDeviceSessions('host', 'Host', [
+ task('bot', { source: 'bot' }),
+ task('side', { source: 'side-chat' }),
+ task('make', { source: 'cindy-make' }),
+ task('A'),
+ ]);
+ clearLastView();
+ await mount();
+ expectRoute('/cc-agent/A');
+ });
+
+ it.each(['new', 'local'] as const)('keeps the existing %s restoration priority', async (last) => {
+ state.sessions = [task('B')];
+ remoteProjectsStore.setDeviceSessions('host', 'Host', [task('A')]);
+ saveLastChatView(last === 'new' ? { kind: 'new' } : { kind: 'session', sessionId: 'B' });
+ await mount();
+ expectRoute(last === 'new' ? '/cc-agent/new' : '/cc-agent/B');
+ });
+
+ it('waits for local loading before deciding that the last task is missing', async () => {
+ state.isLoading = true;
+ saveLastChatView({ kind: 'session', sessionId: 'B' });
+ const view = await mount();
+ expect(state.navigate).not.toHaveBeenCalled();
+ state.sessions = [task('B')];
+ state.isLoading = false;
+ await act(async () => {
+ view.rerender(<CCAgentIndexRedirect />);
+ });
+ expectRoute('/cc-agent/B');
+ });
+
+ it.each(['arrives', 'missing', 'failed'] as const)(
+ 'waits for an in-flight remote snapshot: %s',
+ async (result) => {
+ state.sessions = [task('B')];
+ remoteProjectsStore.markBootstrapLoading('host');
+ saveLastChatView({ kind: 'session', sessionId: 'A' });
+ await mount();
+ expect(state.navigate).not.toHaveBeenCalled();
+ await act(async () => {
+ if (result === 'failed') remoteProjectsStore.markBootstrapFailed('host');
+ else
+ remoteProjectsStore.setDeviceSessions(
+ 'host',
+ 'Host',
+ result === 'arrives' ? [task('A')] : [],
+ );
+ });
+ expectRoute(result === 'arrives' ? '/cc-agent/A' : '/cc-agent/B');
+ },
+ );
+
+ it('does not wait for another device when the last task is already available', async () => {
+ remoteProjectsStore.setDeviceSessions('host', 'Host', [task('A')]);
+ remoteProjectsStore.markBootstrapLoading('other-host');
+ saveLastChatView({ kind: 'session', sessionId: 'A' });
+ await mount();
+ expectRoute('/cc-agent/A');
+ });
+
+ it('waits only for the known origin, not another device still loading', async () => {
+ state.sessions = [task('B')];
+ remoteProjectsStore.pinSessionOrigin('host', 'A');
+ remoteProjectsStore.markBootstrapLoading('host');
+ remoteProjectsStore.markBootstrapLoading('other-host');
+ saveLastChatView({ kind: 'session', sessionId: 'A' });
+ await mount();
+ expect(state.navigate).not.toHaveBeenCalled();
+ await act(async () => {
+ remoteProjectsStore.setDeviceSessions('host', 'Host', []);
+ });
+ expectRoute('/cc-agent/B');
+ });
+
+ it.each(['active', 'archived', 'missing'] as const)(
+ 'restores a remote Orca worker only with an active lead: %s',
+ async (leadStatus) => {
+ state.sessions = [task('B')];
+ remoteProjectsStore.setDeviceSessions('host', 'Host', [
+ task('worker', { orcaRole: 'worker' }),
+ ]);
+ if (leadStatus !== 'missing')
+ remoteProjectsStore.mergeDeviceSessions(
+ 'host',
+ 'Host',
+ [task('lead', { orcaRole: 'lead', status: leadStatus })],
+ leadStatus,
+ );
+ state.getWorkflow.mockResolvedValue({ leadSessionId: 'lead' });
+ saveLastChatView({ kind: 'session', sessionId: 'worker' });
+ await mount();
+ expectRoute(leadStatus === 'active' ? '/cc-agent/lead?worker=worker' : '/cc-agent/B');
+ },
+ );
+
+ it('restarts a cancelled workflow lookup after a remote update and ignores its late result', async () => {
+ const old = deferred<{ leadSessionId: string }>();
+ remoteProjectsStore.setDeviceSessions('host', 'Host', [
+ task('worker', { orcaRole: 'worker' }),
+ task('lead', { orcaRole: 'lead' }),
+ ]);
+ saveLastChatView({ kind: 'session', sessionId: 'worker' });
+ state.getWorkflow.mockReturnValueOnce(old.promise).mockResolvedValue({ leadSessionId: 'lead' });
+ await mount();
+ expect(state.navigate).not.toHaveBeenCalled();
+ await act(async () => {
+ remoteProjectsStore.applyPatch('host', 'worker', { title: 'Updated' });
+ });
+ expectRoute('/cc-agent/lead?worker=worker');
+ await act(async () => {
+ old.resolve({ leadSessionId: 'lead' });
+ });
+ expectRoute('/cc-agent/lead?worker=worker');
+ });
+
+ it('does not navigate after leaving the entry while a workflow lookup is pending', async () => {
+ const pending = deferred<{ leadSessionId: string }>();
+ state.sessions = [task('worker', { orcaRole: 'worker' }), task('lead', { orcaRole: 'lead' })];
+ saveLastChatView({ kind: 'session', sessionId: 'worker' });
+ state.getWorkflow.mockReturnValue(pending.promise);
+ const view = await mount();
+ view.unmount();
+ await act(async () => {
+ pending.resolve({ leadSessionId: 'lead' });
+ });
+ expect(state.navigate).not.toHaveBeenCalled();
+ });
+
+ it('uses the new local fallback if the last worker disappears during its lookup', async () => {
+ const old = deferred<{ leadSessionId: string }>();
+ state.sessions = [task('worker', { orcaRole: 'worker' }), task('lead', { orcaRole: 'lead' })];
+ saveLastChatView({ kind: 'session', sessionId: 'worker' });
+ state.getWorkflow.mockReturnValue(old.promise);
+ const view = await mount();
+ state.sessions = [task('B')];
+ await act(async () => {
+ view.rerender(<CCAgentIndexRedirect />);
+ });
+ expectRoute('/cc-agent/B');
+ await act(async () => {
+ old.resolve({ leadSessionId: 'lead' });
+ });
+ expectRoute('/cc-agent/B');
+ });
+
+ it('survives StrictMode effect cancellation without getting stuck on loading', async () => {
+ state.sessions = [task('B')];
+ saveLastChatView({ kind: 'session', sessionId: 'B' });
+ await act(async () => {
+ render(
+ <StrictMode>
+ <CCAgentIndexRedirect />
+ </StrictMode>,
+ );
+ });
+ expectRoute('/cc-agent/B');
+ });
+});
diff --git a/apps/desktop/src/renderer/features/device-link/remoteProjectsStore.ts b/apps/desktop/src/renderer/features/device-link/remoteProjectsStore.ts
index ec00d48788..3ca7cf9014 100644
--- a/apps/desktop/src/renderer/features/device-link/remoteProjectsStore.ts
+++ b/apps/desktop/src/renderer/features/device-link/remoteProjectsStore.ts
@@ -70,6 +70,10 @@ function recomputeScheduleIndex(): void {
mergedScheduleIndex = next;
}
const subs = new Set<() => void>();
+// A cold renderer has not read its cache or discovered devices yet. An empty
+// bootstrap set during this phase must not be mistaken for a completed lookup.
+let initialDiscoverySettled = false;
+let initialDiscoveryGeneration = 0;
/**
* 正在读取任务快照的设备。它与 shard 是否存在独立:重连或手动重试时可以
* 一边保留旧快照、一边明确告知用户「正在重新读取」。
@@ -567,6 +571,21 @@ function stamp(
}
const actions = {
+ /** The synchronizer owns initialization; late completion cannot settle a newer run. */
+ beginInitialDiscovery(): () => void {
+ const generation = ++initialDiscoveryGeneration;
+ initialDiscoverySettled = false;
+ subs.forEach((fn) => fn());
+ return () => {
+ if (generation !== initialDiscoveryGeneration || initialDiscoverySettled) return;
+ initialDiscoverySettled = true;
+ subs.forEach((fn) => fn());
+ };
+ },
+
+ getInitialDiscoverySettled(): boolean {
+ return initialDiscoverySettled;
+ },
setDeviceScheduleBindings(deviceId: string, bindings: readonly ScheduleBinding[]): void {
const shard = shards.get(deviceId);
if (!shard) return;
@@ -986,6 +1005,10 @@ const actions = {
/** 清空所有远端项目(登出 / device-link stopped / 卸载)。 */
clear(): void {
+ // Logout, stopped and unmount cancel initialization as well as snapshots.
+ const initialDiscoveryChanged = !initialDiscoverySettled;
+ initialDiscoveryGeneration += 1;
+ initialDiscoverySettled = true;
// 所有设备 epoch 无条件**自增**(不 clear-to-0,见 snapshotEpoch 注释的 ABA):清空时在途
// 首拉立即失效;下一轮 bootstrap 拿到更高 epoch,不会与清空前的 epoch 撞值把陈旧 snapshot 盖回。
for (const [k, v] of snapshotEpoch) snapshotEpoch.set(k, v + 1);
@@ -1007,7 +1030,7 @@ const actions = {
if (bootstrapFailedDeviceIds.size > 0) bootstrapFailedDeviceIds = new Set();
if (archivedFailedDeviceIds.size > 0) archivedFailedDeviceIds = new Set();
if (shards.size === 0) {
- if (bootstrapStateChanged) subs.forEach((fn) => fn());
+ if (bootstrapStateChanged || initialDiscoveryChanged) subs.forEach((fn) => fn());
return;
}
shards.clear();
@@ -1413,6 +1436,11 @@ export function useRemoteProjectSessions(): Session[] {
return useSyncExternalStore(subscribe, actions.getVisibleMergedRemoteSessions);
}
+/** Both initial cache hydration and device discovery have settled (including failure/cancellation). */
+export function useRemoteInitialDiscoverySettled(): boolean {
+ return useSyncExternalStore(subscribe, actions.getInitialDiscoverySettled);
+}
+
/** 组件内订阅:返回当前已连接的被控设备摘要列表(机器切换栏 chips)。 */
export function useRemoteDevices(): RemoteDeviceSummary[] {
return useSyncExternalStore(subscribe, actions.getDeviceList);
diff --git a/apps/desktop/src/renderer/features/device-link/useDeviceLinkRemoteProjects.ts b/apps/desktop/src/renderer/features/device-link/useDeviceLinkRemoteProjects.ts
index 7662e8b8c7..3662d58742 100644
--- a/apps/desktop/src/renderer/features/device-link/useDeviceLinkRemoteProjects.ts
+++ b/apps/desktop/src/renderer/features/device-link/useDeviceLinkRemoteProjects.ts
@@ -423,6 +423,7 @@ export function useDeviceLinkRemoteProjects(
}
let disposed = false;
+ const finishInitialDiscovery = remoteProjectsStore.beginInitialDiscovery();
/**
* 「已明确离场、不许被冷缓存种回来」的设备 id。删除 / 撤销访问 / 关闭被控 / 本机停用控制
* 路径都会往里加 —— 它们清盘是异步的,而 mount 时那次 readCachedSessionList 可能早已
@@ -720,9 +721,9 @@ export function useDeviceLinkRemoteProjects(
};
/** 全量重播(初始 + WS 重连):listDevices 带 isSelf,权威。 */
- const reseed = (): void => {
+ const reseed = (): Promise<void> => {
const generation = directoryGeneration;
- void window.electronAPI.deviceLink
+ return window.electronAPI.deviceLink
.listDevices()
.then(({ devices }) => {
if (disposed || generation !== directoryGeneration) return;
@@ -774,7 +775,7 @@ export function useDeviceLinkRemoteProjects(
// 账号里删掉设备的情形,都靠补这一轮收敛(reseed 末尾还会清掉权威列表中缺席的分片)。
// 仍在 listDevices 里但离线的设备照既有语义保留为 disconnected —— 与「断连保留最近
// 一次快照让 All Sessions 稳定」一致,不是本次引入的行为。
- void readCachedSessionList().then((devices) => {
+ const initialCacheRead = readCachedSessionList().then((devices) => {
if (disposed || devices.length === 0) return;
// 读快照这一跳期间被**明确移除**的设备(撤销访问 / 关闭被控 / 本机停用控制)不许种回来:
// 那些路径已经删了分片并清了盘,而这次种入拿的是它们之前读到的旧快照;紧随的 reseed
@@ -782,8 +783,8 @@ export function useDeviceLinkRemoteProjects(
const usable = devices.filter((device) => !cacheHydrationBlocked.has(device.deviceId));
if (usable.length === 0) return;
remoteProjectsStore.hydrateFromCache(usable);
- reseed();
- });
+ return reseed();
+ }).catch((err) => log.debug('initial remote cache read failed', err));
// 用户点击失败态重试 → 重走 subscribe + bootstrap,恢复 loading 与完整重试语义。
setRemoteSessionBootstrapRetryImpl((deviceId) => {
@@ -879,7 +880,7 @@ export function useDeviceLinkRemoteProjects(
}
});
- void window.electronAPI.deviceLink
+ const initialDirectoryRead = window.electronAPI.deviceLink
.getState()
.then((state) => {
if (disposed) return;
@@ -898,13 +899,18 @@ export function useDeviceLinkRemoteProjects(
unresponsiveDevicesStore.apply(deviceId, true);
}
}
- reseed();
+ return reseed();
})
.catch((err) => {
log.debug('getState before device-link reseed failed', err);
- if (!disposed) reseed();
+ if (!disposed) return reseed();
});
+ // Neither an empty bootstrap set nor the first completed read alone proves
+ // the remembered remote task is absent. Per-device loading takes over once
+ // discovery starts bootstrap; failures and cleanup must release this gate.
+ void Promise.allSettled([initialCacheRead, initialDirectoryRead]).then(finishInitialDiscovery);
+
const offPresence = window.electronAPI.deviceLink.onPresenceChanged((snap) => {
applyDevice({
deviceId: snap.deviceId,