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): 区分远程连接失败与空内容 (#1409)

Dashdd46c45ddb2c
diff --git a/apps/desktop/src/renderer/__tests__/agentCapabilitiesDeviceCache.test.ts b/apps/desktop/src/renderer/__tests__/agentCapabilitiesDeviceCache.test.ts
index f81be6f474..1ba141fb12 100644
--- a/apps/desktop/src/renderer/__tests__/agentCapabilitiesDeviceCache.test.ts
+++ b/apps/desktop/src/renderer/__tests__/agentCapabilitiesDeviceCache.test.ts
@@ -11,13 +11,21 @@ beforeEach(() => {
});
interface Caps {
- availableModels: Array<{ id: string; displayName: string; contextWindow: number }>;
+ availableModels: Array<{
+ id: string;
+ displayName: string;
+ contextWindow: number;
+ efforts: string[];
+ defaultEffort: string | null;
+ }>;
hasFastMode: boolean;
effortLevels: unknown[];
permissionModes: unknown[];
}
const caps = (label: string, ctx = 1): Caps => ({
- availableModels: [{ id: 'm', displayName: label, contextWindow: ctx }],
+ availableModels: [
+ { id: 'm', displayName: label, contextWindow: ctx, efforts: [], defaultEffort: null },
+ ],
hasFastMode: false,
effortLevels: [],
permissionModes: [],
@@ -78,6 +86,102 @@ describe('useAgentCapabilities deviceId-aware cache', () => {
expect(mod.getCachedCapabilities('claude-code')).toBeNull();
});
+ it('非法 capabilities 响应进入 error,不得发布 ready 或落缓存', async () => {
+ const invoke = vi.fn(async () => null);
+ const getCapabilities = vi.fn(async (k: string) => caps(`local:${k}`));
+ vi.stubGlobal('window', {
+ electronAPI: { maker: { getCapabilities }, deviceLink: { invoke } },
+ });
+ const mod = await import('@/hooks/useAgentCapabilities');
+ const listener = vi.fn();
+ mod.subscribeDeviceCapabilities('dev-invalid', 'codex', listener);
+
+ await mod.prefetchDeviceCapabilities('dev-invalid');
+
+ expect(listener).toHaveBeenCalledWith({
+ status: 'error',
+ error: 'Invalid agent capabilities response',
+ });
+ expect(mod.getCachedCapabilities('codex', 'dev-invalid')).toBeNull();
+ });
+
+ it('capabilities 模型数组混入非法元素时整份进入 error,不得部分发布或落缓存', async () => {
+ const invoke = vi.fn(async () => ({
+ ...caps('invalid'),
+ availableModels: [...caps('valid').availableModels, null],
+ }));
+ const getCapabilities = vi.fn(async (k: string) => caps(`local:${k}`));
+ vi.stubGlobal('window', {
+ electronAPI: { maker: { getCapabilities }, deviceLink: { invoke } },
+ });
+ const mod = await import('@/hooks/useAgentCapabilities');
+ const listener = vi.fn();
+ mod.subscribeDeviceCapabilities('dev-invalid-item', 'codex', listener);
+
+ await mod.prefetchDeviceCapabilities('dev-invalid-item');
+
+ expect(listener).toHaveBeenCalledWith({
+ status: 'error',
+ error: 'Invalid agent capabilities response',
+ });
+ expect(mod.getCachedCapabilities('codex', 'dev-invalid-item')).toBeNull();
+ });
+
+ it('模型默认 effort 不在可用列表中时不得落缓存', async () => {
+ const invoke = vi.fn(async () => ({
+ ...caps('invalid-effort'),
+ availableModels: [
+ {
+ id: 'm',
+ displayName: 'Invalid Effort',
+ contextWindow: 1,
+ efforts: ['low'],
+ defaultEffort: 'high',
+ },
+ ],
+ }));
+ const getCapabilities = vi.fn(async (k: string) => caps(`local:${k}`));
+ vi.stubGlobal('window', {
+ electronAPI: { maker: { getCapabilities }, deviceLink: { invoke } },
+ });
+ const mod = await import('@/hooks/useAgentCapabilities');
+ const listener = vi.fn();
+ mod.subscribeDeviceCapabilities('dev-invalid-effort', 'codex', listener);
+
+ await mod.prefetchDeviceCapabilities('dev-invalid-effort');
+
+ expect(listener).toHaveBeenCalledWith({
+ status: 'error',
+ error: 'Invalid agent capabilities response',
+ });
+ expect(mod.getCachedCapabilities('codex', 'dev-invalid-effort')).toBeNull();
+ });
+
+ it.each(['effortLevels', 'permissionModes'] as const)(
+ '%s 混入非法 descriptor 时不得发布 ready',
+ async (field) => {
+ const invoke = vi.fn(async () => ({
+ ...caps('invalid-descriptor'),
+ [field]: [{ id: 'invalid', displayName: null }],
+ }));
+ const getCapabilities = vi.fn(async (k: string) => caps(`local:${k}`));
+ vi.stubGlobal('window', {
+ electronAPI: { maker: { getCapabilities }, deviceLink: { invoke } },
+ });
+ const mod = await import('@/hooks/useAgentCapabilities');
+ const listener = vi.fn();
+ mod.subscribeDeviceCapabilities(`dev-invalid-${field}`, 'codex', listener);
+
+ await mod.prefetchDeviceCapabilities(`dev-invalid-${field}`);
+
+ expect(listener).toHaveBeenCalledWith({
+ status: 'error',
+ error: 'Invalid agent capabilities response',
+ });
+ expect(mod.getCachedCapabilities('codex', `dev-invalid-${field}`)).toBeNull();
+ },
+ );
+
it('key 隔离:local / dev-1 / dev-2 各自独立不串', async () => {
stubElectron();
const mod = await import('@/hooks/useAgentCapabilities');
diff --git a/apps/desktop/src/renderer/__tests__/deviceLinkDeviceListLoading.test.tsx b/apps/desktop/src/renderer/__tests__/deviceLinkDeviceListLoading.test.tsx
index b7320d4c15..6fdb2d4652 100644
--- a/apps/desktop/src/renderer/__tests__/deviceLinkDeviceListLoading.test.tsx
+++ b/apps/desktop/src/renderer/__tests__/deviceLinkDeviceListLoading.test.tsx
@@ -29,6 +29,7 @@ describe('useDeviceLinkDeviceList initial request', () => {
vi.stubGlobal('electronAPI', {
deviceLink: {
listDevices,
+ getState: vi.fn().mockResolvedValue({ linkStatus: 'online' }),
onPresenceChanged: vi.fn(),
onStatusChanged: vi.fn(
(callback: (payload: { status: 'stopped' | 'connecting' | 'online' }) => void) => {
@@ -39,24 +40,46 @@ describe('useDeviceLinkDeviceList initial request', () => {
},
});
- const { useDeviceLinkDeviceList, useDeviceLinkDeviceListSettled } =
- await import('@/features/device-link/useDeviceLinkDeviceList');
+ const {
+ useDeviceLinkDeviceList,
+ useDeviceLinkDeviceListRequestState,
+ useDeviceLinkDeviceListSettled,
+ } = await import('@/features/device-link/useDeviceLinkDeviceList');
const { result } = renderHook(() => ({
devices: useDeviceLinkDeviceList(),
+ request: useDeviceLinkDeviceListRequestState(),
settled: useDeviceLinkDeviceListSettled(),
}));
- expect(result.current).toEqual({ devices: null, settled: false });
- await waitFor(() => expect(result.current.settled).toBe(true));
- expect(result.current.devices).toBeNull();
+ expect(result.current).toEqual({
+ devices: null,
+ request: { status: 'loading', error: null },
+ settled: false,
+ });
+ await waitFor(() => expect(result.current.request.status).toBe('error'));
+ expect(result.current).toEqual({
+ devices: null,
+ request: { status: 'error', error: 'relay unavailable' },
+ settled: true,
+ });
expect(listDevices).toHaveBeenCalledTimes(1);
act(() => statusChanged?.({ status: 'online' }));
expect(listDevices).toHaveBeenCalledTimes(2);
- expect(result.current).toEqual({ devices: null, settled: false });
+ expect(result.current).toEqual({
+ devices: null,
+ request: { status: 'loading', error: null },
+ settled: false,
+ });
await act(async () => resolveRetry?.({ devices: [] }));
- await waitFor(() => expect(result.current).toEqual({ devices: [], settled: true }));
+ await waitFor(() =>
+ expect(result.current).toEqual({
+ devices: [],
+ request: { status: 'ready', error: null },
+ settled: true,
+ }),
+ );
});
// 回归 #797:云端登录 → 登出(relay 'stopped')→ 进入本地模式后不会再有 'online',
@@ -81,6 +104,7 @@ describe('useDeviceLinkDeviceList initial request', () => {
vi.stubGlobal('electronAPI', {
deviceLink: {
listDevices,
+ getState: vi.fn().mockResolvedValue({ linkStatus: 'online' }),
onPresenceChanged: vi.fn(),
onStatusChanged: vi.fn(
(callback: (payload: { status: 'stopped' | 'connecting' | 'online' }) => void) => {
@@ -91,10 +115,14 @@ describe('useDeviceLinkDeviceList initial request', () => {
},
});
- const { useDeviceLinkDeviceList, useDeviceLinkDeviceListSettled } =
- await import('@/features/device-link/useDeviceLinkDeviceList');
- const useProbe = (): { devices: DeviceLinkDeviceView[] | null; settled: boolean } => ({
+ const {
+ useDeviceLinkDeviceList,
+ useDeviceLinkDeviceListRequestState,
+ useDeviceLinkDeviceListSettled,
+ } = await import('@/features/device-link/useDeviceLinkDeviceList');
+ const useProbe = () => ({
devices: useDeviceLinkDeviceList(),
+ request: useDeviceLinkDeviceListRequestState(),
settled: useDeviceLinkDeviceListSettled(),
});
const { result, unmount } = renderHook(useProbe);
@@ -103,13 +131,21 @@ describe('useDeviceLinkDeviceList initial request', () => {
// 登出:清掉上一账号的远程机器(devices 回 null → 切换栏隐藏),但目录仍是终态。
act(() => statusChanged?.({ status: 'stopped' }));
- expect(result.current).toEqual({ devices: null, settled: true });
+ expect(result.current).toEqual({
+ devices: null,
+ request: { status: 'ready', error: null },
+ settled: true,
+ });
expect(listDevices).toHaveBeenCalledTimes(1);
// 本地模式重挂侧栏(共享单例已 started)也不得退回未结算态。
unmount();
const local = renderHook(useProbe);
- expect(local.result.current).toEqual({ devices: null, settled: true });
+ expect(local.result.current).toEqual({
+ devices: null,
+ request: { status: 'ready', error: null },
+ settled: true,
+ });
expect(listDevices).toHaveBeenCalledTimes(1);
});
@@ -120,13 +156,11 @@ describe('useDeviceLinkDeviceList initial request', () => {
const relogin = new Promise<{ devices: DeviceLinkDeviceView[] }>((resolve) => {
resolveRelogin = resolve;
});
- const listDevices = vi
- .fn()
- .mockResolvedValueOnce({ devices: [] })
- .mockReturnValueOnce(relogin);
+ const listDevices = vi.fn().mockResolvedValueOnce({ devices: [] }).mockReturnValueOnce(relogin);
vi.stubGlobal('electronAPI', {
deviceLink: {
listDevices,
+ getState: vi.fn().mockResolvedValue({ linkStatus: 'online' }),
onPresenceChanged: vi.fn(),
onStatusChanged: vi.fn(
(callback: (payload: { status: 'stopped' | 'connecting' | 'online' }) => void) => {
@@ -137,24 +171,263 @@ describe('useDeviceLinkDeviceList initial request', () => {
},
});
- const { useDeviceLinkDeviceList, useDeviceLinkDeviceListSettled } =
- await import('@/features/device-link/useDeviceLinkDeviceList');
+ const {
+ useDeviceLinkDeviceList,
+ useDeviceLinkDeviceListRequestState,
+ useDeviceLinkDeviceListSettled,
+ } = await import('@/features/device-link/useDeviceLinkDeviceList');
const { result } = renderHook(() => ({
devices: useDeviceLinkDeviceList(),
+ request: useDeviceLinkDeviceListRequestState(),
settled: useDeviceLinkDeviceListSettled(),
}));
- await waitFor(() => expect(result.current).toEqual({ devices: [], settled: true }));
+ await waitFor(() =>
+ expect(result.current).toEqual({
+ devices: [],
+ request: { status: 'ready', error: null },
+ settled: true,
+ }),
+ );
act(() => statusChanged?.({ status: 'stopped' }));
- expect(result.current).toEqual({ devices: null, settled: true });
+ expect(result.current).toEqual({
+ devices: null,
+ request: { status: 'ready', error: null },
+ settled: true,
+ });
// 重新登录:relay 'online' 重新拉取,首快照落地前照旧回到 loading。
act(() => statusChanged?.({ status: 'online' }));
expect(listDevices).toHaveBeenCalledTimes(2);
- expect(result.current).toEqual({ devices: null, settled: false });
+ expect(result.current).toEqual({
+ devices: null,
+ request: { status: 'loading', error: null },
+ settled: false,
+ });
await act(async () => resolveRelogin?.({ devices: [] }));
- await waitFor(() => expect(result.current).toEqual({ devices: [], settled: true }));
+ await waitFor(() =>
+ expect(result.current).toEqual({
+ devices: [],
+ request: { status: 'ready', error: null },
+ settled: true,
+ }),
+ );
+ });
+
+ it('manual retry turns an error back into loading and rejects invalid payloads instead of publishing an empty directory', async () => {
+ let resolveRetry: ((value: { devices: DeviceLinkDeviceView[] }) => void) | undefined;
+ const retry = new Promise<{ devices: DeviceLinkDeviceView[] }>((resolve) => {
+ resolveRetry = resolve;
+ });
+ const listDevices = vi.fn().mockResolvedValueOnce(null).mockReturnValueOnce(retry);
+ vi.stubGlobal('electronAPI', {
+ deviceLink: {
+ listDevices,
+ getState: vi.fn().mockResolvedValue({ linkStatus: 'online' }),
+ onPresenceChanged: vi.fn(),
+ onStatusChanged: vi.fn(),
+ onControlTargetChanged: vi.fn(),
+ },
+ });
+
+ const {
+ retryDeviceLinkDeviceList,
+ useDeviceLinkDeviceList,
+ useDeviceLinkDeviceListRequestState,
+ } = await import('@/features/device-link/useDeviceLinkDeviceList');
+ const { result } = renderHook(() => ({
+ devices: useDeviceLinkDeviceList(),
+ request: useDeviceLinkDeviceListRequestState(),
+ }));
+
+ await waitFor(() => expect(result.current.request.status).toBe('error'));
+ expect(result.current.devices).toBeNull();
+
+ act(() => retryDeviceLinkDeviceList());
+ expect(result.current.request).toEqual({ status: 'loading', error: null });
+ await act(async () => resolveRetry?.({ devices: [] }));
+ await waitFor(() => expect(result.current.devices).toEqual([]));
+ expect(result.current.request).toEqual({ status: 'ready', error: null });
+ });
+
+ it('treats an initially stopped link as an inactive remote scope, not a connection failure', async () => {
+ const listDevices = vi.fn();
+ const getState = vi.fn().mockResolvedValue({ linkStatus: 'stopped' });
+ vi.stubGlobal('electronAPI', {
+ deviceLink: {
+ getState,
+ listDevices,
+ onPresenceChanged: vi.fn(),
+ onStatusChanged: vi.fn(),
+ onControlTargetChanged: vi.fn(),
+ },
+ });
+
+ const {
+ useDeviceLinkDeviceList,
+ useDeviceLinkDeviceListRequestState,
+ useDeviceLinkDeviceListSettled,
+ } = await import('@/features/device-link/useDeviceLinkDeviceList');
+ const { result } = renderHook(() => ({
+ devices: useDeviceLinkDeviceList(),
+ request: useDeviceLinkDeviceListRequestState(),
+ settled: useDeviceLinkDeviceListSettled(),
+ }));
+
+ await waitFor(() =>
+ expect(result.current).toEqual({
+ devices: null,
+ request: { status: 'ready', error: null },
+ settled: true,
+ }),
+ );
+ expect(getState).toHaveBeenCalledTimes(1);
+ expect(listDevices).not.toHaveBeenCalled();
+ });
+
+ it('lets a stopped push beat a late online getState snapshot', async () => {
+ let resolveState:
+ ((value: { linkStatus: 'stopped' | 'connecting' | 'online' }) => void) | undefined;
+ const state = new Promise<{ linkStatus: 'stopped' | 'connecting' | 'online' }>((resolve) => {
+ resolveState = resolve;
+ });
+ let statusChanged:
+ ((payload: { status: 'stopped' | 'connecting' | 'online' }) => void) | undefined;
+ const listDevices = vi.fn();
+ vi.stubGlobal('electronAPI', {
+ deviceLink: {
+ getState: vi.fn().mockReturnValue(state),
+ listDevices,
+ onPresenceChanged: vi.fn(),
+ onStatusChanged: vi.fn(
+ (callback: (payload: { status: 'stopped' | 'connecting' | 'online' }) => void) => {
+ statusChanged = callback;
+ },
+ ),
+ onControlTargetChanged: vi.fn(),
+ },
+ });
+
+ const {
+ useDeviceLinkDeviceList,
+ useDeviceLinkDeviceListRequestState,
+ useDeviceLinkDeviceListSettled,
+ } = await import('@/features/device-link/useDeviceLinkDeviceList');
+ const { result } = renderHook(() => ({
+ devices: useDeviceLinkDeviceList(),
+ request: useDeviceLinkDeviceListRequestState(),
+ settled: useDeviceLinkDeviceListSettled(),
+ }));
+
+ act(() => statusChanged?.({ status: 'stopped' }));
+ expect(result.current).toEqual({
+ devices: null,
+ request: { status: 'ready', error: null },
+ settled: true,
+ });
+
+ await act(async () => resolveState?.({ linkStatus: 'online' }));
+ expect(result.current).toEqual({
+ devices: null,
+ request: { status: 'ready', error: null },
+ settled: true,
+ });
+ expect(listDevices).not.toHaveBeenCalled();
+ });
+
+ it('starts loading and fetches the directory when a stopped link becomes online', async () => {
+ let statusChanged:
+ ((payload: { status: 'stopped' | 'connecting' | 'online' }) => void) | undefined;
+ let resolveDevices: ((value: { devices: DeviceLinkDeviceView[] }) => void) | undefined;
+ const response = new Promise<{ devices: DeviceLinkDeviceView[] }>((resolve) => {
+ resolveDevices = resolve;
+ });
+ const listDevices = vi.fn().mockReturnValue(response);
+ vi.stubGlobal('electronAPI', {
+ deviceLink: {
+ getState: vi.fn().mockResolvedValue({ linkStatus: 'stopped' }),
+ listDevices,
+ onPresenceChanged: vi.fn(),
+ onStatusChanged: vi.fn(
+ (callback: (payload: { status: 'stopped' | 'connecting' | 'online' }) => void) => {
+ statusChanged = callback;
+ },
+ ),
+ onControlTargetChanged: vi.fn(),
+ },
+ });
+
+ const {
+ useDeviceLinkDeviceList,
+ useDeviceLinkDeviceListRequestState,
+ useDeviceLinkDeviceListSettled,
+ } = await import('@/features/device-link/useDeviceLinkDeviceList');
+ const { result } = renderHook(() => ({
+ devices: useDeviceLinkDeviceList(),
+ request: useDeviceLinkDeviceListRequestState(),
+ settled: useDeviceLinkDeviceListSettled(),
+ }));
+ await waitFor(() => expect(result.current.request.status).toBe('ready'));
+
+ act(() => statusChanged?.({ status: 'online' }));
+ expect(listDevices).toHaveBeenCalledTimes(1);
+ expect(result.current).toEqual({
+ devices: null,
+ request: { status: 'loading', error: null },
+ settled: false,
+ });
+
+ await act(async () => resolveDevices?.({ devices: [] }));
+ await waitFor(() =>
+ expect(result.current).toEqual({
+ devices: [],
+ request: { status: 'ready', error: null },
+ settled: true,
+ }),
+ );
+ });
+
+ it('re-probes link state on manual retry and does not call listDevices after a missed stop', async () => {
+ const getState = vi
+ .fn()
+ .mockResolvedValueOnce({ linkStatus: 'online' })
+ .mockResolvedValueOnce({ linkStatus: 'stopped' });
+ const listDevices = vi.fn().mockRejectedValueOnce(new Error('relay unavailable'));
+ vi.stubGlobal('electronAPI', {
+ deviceLink: {
+ getState,
+ listDevices,
+ onPresenceChanged: vi.fn(),
+ onStatusChanged: vi.fn(),
+ onControlTargetChanged: vi.fn(),
+ },
+ });
+
+ const {
+ retryDeviceLinkDeviceList,
+ useDeviceLinkDeviceList,
+ useDeviceLinkDeviceListRequestState,
+ useDeviceLinkDeviceListSettled,
+ } = await import('@/features/device-link/useDeviceLinkDeviceList');
+ const { result } = renderHook(() => ({
+ devices: useDeviceLinkDeviceList(),
+ request: useDeviceLinkDeviceListRequestState(),
+ settled: useDeviceLinkDeviceListSettled(),
+ }));
+ await waitFor(() => expect(result.current.request.status).toBe('error'));
+
+ act(() => retryDeviceLinkDeviceList());
+ expect(result.current.request).toEqual({ status: 'loading', error: null });
+ await waitFor(() =>
+ expect(result.current).toEqual({
+ devices: null,
+ request: { status: 'ready', error: null },
+ settled: true,
+ }),
+ );
+ expect(getState).toHaveBeenCalledTimes(2);
+ expect(listDevices).toHaveBeenCalledTimes(1);
});
it('relay stop after selecting a remote device falls back visibly and keeps the local escape action', async () => {
diff --git a/apps/desktop/src/renderer/__tests__/deviceLinkProjectsConcurrency.test.tsx b/apps/desktop/src/renderer/__tests__/deviceLinkProjectsConcurrency.test.tsx
index f03e47e463..180b7e5125 100644
--- a/apps/desktop/src/renderer/__tests__/deviceLinkProjectsConcurrency.test.tsx
+++ b/apps/desktop/src/renderer/__tests__/deviceLinkProjectsConcurrency.test.tsx
@@ -36,11 +36,17 @@ function deferred<T>() {
return { promise, resolve, reject };
}
-const row = (path: string): ExistingRemoteProject => ({ path, name: path.split('/').pop() ?? path });
+const row = (path: string): ExistingRemoteProject => ({
+ path,
+ name: path.split('/').pop() ?? path,
+});
interface Harness {
projects: { path: string; deviceId: string }[];
loading: boolean;
+ status: 'idle' | 'loading' | 'ready' | 'error';
+ error: string | null;
+ retry: () => void;
remove: (path: string, deviceId: string) => Promise<void>;
/** 每一帧渲染看到的选项快照 —— 「切设备那一帧短暂标错归属」只能靠逐帧记录才抓得到。 */
frames: { path: string; deviceId: string }[][];
@@ -48,7 +54,15 @@ interface Harness {
/** 把 hook 的输出暴露给测试,并允许在 render 之外驱动 removeProject / 切设备。 */
function mountHook() {
- const seen: Harness = { projects: [], loading: false, remove: async () => {}, frames: [] };
+ const seen: Harness = {
+ projects: [],
+ loading: false,
+ status: 'idle',
+ error: null,
+ retry: () => {},
+ remove: async () => {},
+ frames: [],
+ };
let setDevice!: (id: string) => void;
let setEnabled!: (v: boolean) => void;
@@ -59,10 +73,20 @@ function mountHook() {
setEnabled = setEnabledState;
// 动态 import 后 hook 已带 mock;放在组件里保证每个用例拿到同一实例。
const { useDeviceLinkProjects } = hookModule;
- const { projects, loading, removeProject } = useDeviceLinkProjects(deviceId, 'Peer', enabled);
- seen.projects = projects.map((p) => ({ path: p.path, deviceId: p.remoteDevice?.deviceId ?? '' }));
+ const { projects, loading, status, error, retry, removeProject } = useDeviceLinkProjects(
+ deviceId,
+ 'Peer',
+ enabled,
+ );
+ seen.projects = projects.map((p) => ({
+ path: p.path,
+ deviceId: p.remoteDevice?.deviceId ?? '',
+ }));
seen.frames.push(seen.projects);
seen.loading = loading;
+ seen.status = status;
+ seen.error = error;
+ seen.retry = retry;
seen.remove = (path, dId) =>
removeProject({ path, name: path, remoteDevice: { deviceId: dId, deviceName: 'Peer' } });
return null;
@@ -104,7 +128,9 @@ describe('useDeviceLinkProjects 取数 / 删除并发', () => {
const aReadback = deferred<ExistingRemoteProject[]>();
// 切到设备 B 的取数(第二次 load)。
const bLoad = deferred<ExistingRemoteProject[]>();
- loadMock.mockImplementationOnce(() => bLoad.promise).mockImplementationOnce(() => aReadback.promise);
+ loadMock
+ .mockImplementationOnce(() => bLoad.promise)
+ .mockImplementationOnce(() => aReadback.promise);
let removePromise!: Promise<void>;
act(() => {
@@ -510,7 +536,9 @@ describe('useDeviceLinkProjects 取数 / 删除并发', () => {
// 两个删除都失败,各自发起回读。
const del1 = deferred<void>();
const del2 = deferred<void>();
- removeMock.mockImplementationOnce(() => del1.promise).mockImplementationOnce(() => del2.promise);
+ removeMock
+ .mockImplementationOnce(() => del1.promise)
+ .mockImplementationOnce(() => del2.promise);
const rb1 = deferred<ExistingRemoteProject[]>();
const rb2 = deferred<ExistingRemoteProject[]>();
loadMock.mockImplementationOnce(() => rb1.promise).mockImplementationOnce(() => rb2.promise);
@@ -653,7 +681,7 @@ describe('useDeviceLinkProjects 取数 / 删除并发', () => {
expect(seen.projects.map((p) => p.path)).toEqual(['/a/two']);
});
- it('首次取数就失败时仍提交空列表(没有可保留的快照,空态里有浏览文件夹兜底)', async () => {
+ it('首次取数失败进入错误态,不把未知结果伪装成权威空列表', async () => {
const first = deferred<ExistingRemoteProject[]>();
loadMock.mockImplementationOnce(() => first.promise);
const { seen } = mountHook();
@@ -662,5 +690,34 @@ describe('useDeviceLinkProjects 取数 / 删除并发', () => {
});
expect(seen.projects).toEqual([]);
expect(seen.loading).toBe(false);
+ expect(seen.status).toBe('error');
+ expect(seen.error).toContain('DEVICE_OFFLINE');
+ });
+
+ it('错误态点击重试后立即回到 loading,成功空数组才进入权威空态', async () => {
+ const first = deferred<ExistingRemoteProject[]>();
+ const retryLoad = deferred<ExistingRemoteProject[]>();
+ loadMock
+ .mockImplementationOnce(() => first.promise)
+ .mockImplementationOnce(() => retryLoad.promise);
+ const { seen } = mountHook();
+
+ await act(async () => {
+ first.reject(new Error('DEVICE_LINK_TIMEOUT'));
+ });
+ expect(seen.status).toBe('error');
+
+ act(() => {
+ seen.retry();
+ });
+ expect(seen.status).toBe('loading');
+ expect(seen.error).toBeNull();
+
+ await act(async () => {
+ retryLoad.resolve([]);
+ });
+ expect(seen.projects).toEqual([]);
+ expect(seen.status).toBe('ready');
+ expect(seen.loading).toBe(false);
});
});
diff --git a/apps/desktop/src/renderer/__tests__/deviceProvidersCache.test.ts b/apps/desktop/src/renderer/__tests__/deviceProvidersCache.test.ts
index 5560196f21..9006d31659 100644
--- a/apps/desktop/src/renderer/__tests__/deviceProvidersCache.test.ts
+++ b/apps/desktop/src/renderer/__tests__/deviceProvidersCache.test.ts
@@ -5,16 +5,48 @@
* 模块级缓存:每个用例 vi.resetModules() + 动态 import 拿干净模块。
*/
import { beforeEach, describe, expect, it, vi } from 'vitest';
+import {
+ connectedProvidersForAgent,
+ visibleModelUnion,
+ type ProviderView,
+} from '@cindy/model-providers';
beforeEach(() => {
vi.resetModules();
});
type Providers = {
- providers: Array<{ id: string }>;
+ providers: ProviderView[];
modelVisibilityOverrides?: Record<string, boolean>;
};
-const result = (deviceId: string): Providers => ({ providers: [{ id: `${deviceId}-xd` }] });
+const provider = (id: string): ProviderView => ({
+ id,
+ name: id,
+ source: 'builtin',
+ agents: ['claude-code'],
+ auth: { method: 'none' },
+ routing: {
+ 'claude-code': { upstream: 'https://example.invalid', authStrategy: 'none' },
+ },
+ models: { 'claude-code': [] },
+ connected: true,
+});
+const result = (deviceId: string): Providers => ({ providers: [provider(`${deviceId}-xd`)] });
+
+const providerWithModel = (id: string) => ({
+ ...provider(id),
+ models: {
+ 'claude-code': [
+ {
+ id: `${id}-model`,
+ name: `${id} Model`,
+ contextWindow: 200_000,
+ efforts: ['medium'],
+ defaultEffort: 'medium',
+ },
+ ],
+ },
+});
/** stub window.electronAPI.deviceLink.invoke,返回 spy。 */
function stubDeviceLink() {
@@ -28,9 +60,217 @@ describe('useDeviceProviders deviceId-aware cache', () => {
const invoke = stubDeviceLink();
const mod = await import('@/hooks/useDeviceProviders');
await mod.prefetchDeviceProviders('dev-1');
- expect(invoke).toHaveBeenCalledWith('dev-1', 'maker:provider:list', [{
- capabilities: ['provider-logo-kinds-v2'],
- }]);
+ expect(invoke).toHaveBeenCalledWith('dev-1', 'maker:provider:list', [
+ {
+ capabilities: ['provider-logo-kinds-v2'],
+ },
+ ]);
+ });
+
+ it('非法 provider 响应进入 error,不得把 null 当成权威空列表', async () => {
+ const invoke = vi.fn(async () => null);
+ vi.stubGlobal('window', { electronAPI: { deviceLink: { invoke } } });
+ const mod = await import('@/hooks/useDeviceProviders');
+ const listener = vi.fn();
+ mod.subscribeDeviceProviders('dev-invalid', listener);
+
+ await mod.prefetchDeviceProviders('dev-invalid');
+
+ expect(listener).toHaveBeenCalledWith({
+ status: 'error',
+ error: 'Invalid provider list response',
+ unsupported: false,
+ });
+ expect(mod.getCachedDeviceProviders('dev-invalid')).toBeNull();
+ });
+
+ it('provider 数组混入非法元素时整份进入 error,不得部分发布或落缓存', async () => {
+ const invoke = vi.fn(async () => ({ providers: [provider('valid'), null] }));
+ vi.stubGlobal('window', { electronAPI: { deviceLink: { invoke } } });
+ const mod = await import('@/hooks/useDeviceProviders');
+ const listener = vi.fn();
+ mod.subscribeDeviceProviders('dev-invalid-item', listener);
+
+ await mod.prefetchDeviceProviders('dev-invalid-item');
+
+ expect(listener).toHaveBeenCalledWith({
+ status: 'error',
+ error: 'Invalid provider list response',
+ unsupported: false,
+ });
+ expect(mod.getCachedDeviceProviders('dev-invalid-item')).toBeNull();
+ });
+
+ it('接受不含执行字段的安全投影 provider', async () => {
+ const projected = {
+ id: 'projected',
+ name: 'Projected',
+ agents: ['claude-code'],
+ models: {
+ 'claude-code': [
+ {
+ id: 'projected-model',
+ name: 'Projected Model',
+ contextWindow: 200_000,
+ efforts: ['medium'],
+ defaultEffort: 'medium',
+ },
+ ],
+ },
+ connected: true,
+ };
+ const invoke = vi.fn(async () => ({ providers: [projected] }));
+ vi.stubGlobal('window', { electronAPI: { deviceLink: { invoke } } });
+ const mod = await import('@/hooks/useDeviceProviders');
+
+ await mod.prefetchDeviceProviders('dev-projected');
+
+ const cached = mod.getCachedDeviceProviders('dev-projected');
+ expect(cached).toEqual({
+ providers: [{ ...projected, routing: { 'claude-code': {} } }],
+ });
+ expect(connectedProvidersForAgent(cached?.providers ?? [], 'claude-code')).toHaveLength(1);
+ expect(
+ visibleModelUnion(cached?.providers ?? [], 'claude-code', () => true).map((m) => m.id),
+ ).toEqual(['projected-model']);
+ });
+
+ it('补齐 agents 声明但缺失的远程 routing entry,保留已有 disabled 标记', async () => {
+ const projected = {
+ ...providerWithModel('partial-routing'),
+ agents: ['claude-code', 'codex'],
+ routing: { codex: { disabled: true } },
+ };
+ const invoke = vi.fn(async () => ({ providers: [projected] }));
+ vi.stubGlobal('window', { electronAPI: { deviceLink: { invoke } } });
+ const mod = await import('@/hooks/useDeviceProviders');
+
+ await mod.prefetchDeviceProviders('dev-partial-routing');
+
+ const cached = mod.getCachedDeviceProviders('dev-partial-routing');
+ expect(cached?.providers[0]?.routing).toEqual({
+ codex: { disabled: true },
+ 'claude-code': {},
+ });
+ expect(connectedProvidersForAgent(cached?.providers ?? [], 'claude-code')).toHaveLength(1);
+ expect(connectedProvidersForAgent(cached?.providers ?? [], 'codex')).toEqual([]);
+ });
+
+ it('嵌套模型损坏时整份 provider 响应失败', async () => {
+ const malformed = {
+ ...provider('malformed-model'),
+ models: { 'claude-code': [null] },
+ };
+ const invoke = vi.fn(async () => ({ providers: [malformed] }));
+ vi.stubGlobal('window', { electronAPI: { deviceLink: { invoke } } });
+ const mod = await import('@/hooks/useDeviceProviders');
+ const listener = vi.fn();
+ mod.subscribeDeviceProviders('dev-malformed-model', listener);
+
+ await mod.prefetchDeviceProviders('dev-malformed-model');
+
+ expect(listener).toHaveBeenCalledWith({
+ status: 'error',
+ error: 'Invalid provider list response',
+ unsupported: false,
+ });
+ expect(mod.getCachedDeviceProviders('dev-malformed-model')).toBeNull();
+ });
+
+ it.each([
+ ['provider.suspended', { ...provider('bad-suspended'), suspended: 'true' }],
+ [
+ 'routing.disabled',
+ {
+ ...provider('bad-route-disabled'),
+ routing: { 'claude-code': { disabled: 'true' } },
+ },
+ ],
+ [
+ 'routing.wireProtocol',
+ {
+ ...provider('bad-wire-protocol'),
+ routing: { 'claude-code': { wireProtocol: 'future-protocol' } },
+ },
+ ],
+ [
+ 'model.disabled',
+ {
+ ...providerWithModel('bad-model-disabled'),
+ models: {
+ 'claude-code': [
+ {
+ ...providerWithModel('bad-model-disabled').models['claude-code'][0],
+ disabled: 'true',
+ },
+ ],
+ },
+ },
+ ],
+ [
+ 'model.supportsFastMode',
+ {
+ ...providerWithModel('bad-fast-mode'),
+ models: {
+ 'claude-code': [
+ {
+ ...providerWithModel('bad-fast-mode').models['claude-code'][0],
+ supportsFastMode: 'true',
+ },
+ ],
+ },
+ },
+ ],
+ [
+ 'model.defaultEnabled',
+ {
+ ...providerWithModel('bad-default-enabled'),
+ models: {
+ 'claude-code': [
+ {
+ ...providerWithModel('bad-default-enabled').models['claude-code'][0],
+ defaultEnabled: 'false',
+ },
+ ],
+ },
+ },
+ ],
+ ])('%s 类型损坏时整份 provider 响应失败', async (field, malformed) => {
+ const deviceId = `dev-invalid-${field}`;
+ const invoke = vi.fn(async () => ({ providers: [malformed] }));
+ vi.stubGlobal('window', { electronAPI: { deviceLink: { invoke } } });
+ const mod = await import('@/hooks/useDeviceProviders');
+ const listener = vi.fn();
+ mod.subscribeDeviceProviders(deviceId, listener);
+
+ await mod.prefetchDeviceProviders(deviceId);
+
+ expect(listener).toHaveBeenCalledWith({
+ status: 'error',
+ error: 'Invalid provider list response',
+ unsupported: false,
+ });
+ expect(mod.getCachedDeviceProviders(deviceId)).toBeNull();
+ });
+
+ it('模型可见性 override 含非布尔值时不得缓存', async () => {
+ const invoke = vi.fn(async () => ({
+ providers: [provider('invalid-override')],
+ modelVisibilityOverrides: { 'claude-code:invalid-override:model': 'hidden' },
+ }));
+ vi.stubGlobal('window', { electronAPI: { deviceLink: { invoke } } });
+ const mod = await import('@/hooks/useDeviceProviders');
+ const listener = vi.fn();
+ mod.subscribeDeviceProviders('dev-invalid-override', listener);
+
+ await mod.prefetchDeviceProviders('dev-invalid-override');
+
+ expect(listener).toHaveBeenCalledWith({
+ status: 'error',
+ error: 'Invalid provider visibility response',
+ unsupported: false,
+ });
+ expect(mod.getCachedDeviceProviders('dev-invalid-override')).toBeNull();
});
it('缓存命中:同设备二次 prefetch 不再发请求', async () => {
@@ -55,12 +295,12 @@ describe('useDeviceProviders deviceId-aware cache', () => {
await mod.prefetchDeviceProviders('dev-1');
expect(mod.getCachedDeviceProviders('dev-1')).toEqual({
- providers: [{ id: 'dev-1-xd' }],
+ providers: [provider('dev-1-xd')],
modelVisibilityOverrides: overrides,
});
expect(listener).toHaveBeenCalledWith({
status: 'ready',
- providers: [{ id: 'dev-1-xd' }],
+ providers: [provider('dev-1-xd')],
modelVisibilityOverrides: overrides,
});
});
@@ -77,12 +317,16 @@ describe('useDeviceProviders deviceId-aware cache', () => {
const mod = await import('@/hooks/useDeviceProviders');
await mod.prefetchDeviceProviders('dev-1');
await mod.prefetchDeviceProviders('dev-2');
- expect(invoke).toHaveBeenCalledWith('dev-1', 'maker:provider:list', [{
- capabilities: ['provider-logo-kinds-v2'],
- }]);
- expect(invoke).toHaveBeenCalledWith('dev-2', 'maker:provider:list', [{
- capabilities: ['provider-logo-kinds-v2'],
- }]);
+ expect(invoke).toHaveBeenCalledWith('dev-1', 'maker:provider:list', [
+ {
+ capabilities: ['provider-logo-kinds-v2'],
+ },
+ ]);
+ expect(invoke).toHaveBeenCalledWith('dev-2', 'maker:provider:list', [
+ {
+ capabilities: ['provider-logo-kinds-v2'],
+ },
+ ]);
expect(invoke).toHaveBeenCalledTimes(2);
// dev-2 已缓存:再 prefetch 不重拉(隔离 + 命中)。
await mod.prefetchDeviceProviders('dev-2');
@@ -123,7 +367,9 @@ describe('useDeviceProviders deviceId-aware cache', () => {
let call = 0;
const invoke = vi.fn(async () => {
call += 1;
- throw new Error("channel 'maker:provider:list' not allowed remotely");
+ throw new Error(
+ "[DEVICE_LINK_CHANNEL_NOT_ALLOWED] channel 'maker:provider:list' not allowed remotely",
+ );
});
vi.stubGlobal('window', { electronAPI: { deviceLink: { invoke } } });
const mod = await import('@/hooks/useDeviceProviders');
@@ -132,6 +378,46 @@ describe('useDeviceProviders deviceId-aware cache', () => {
expect(call).toBe(2);
});
+ it('错误事件区分旧端不支持与真实连接失败', async () => {
+ const unsupported = new Error('[DEVICE_LINK_CHANNEL_NOT_ALLOWED] channel not allowed remotely');
+ const policyFailure = new Error('proxy policy: request not allowed remotely');
+ const invoke = vi
+ .fn()
+ .mockRejectedValueOnce(unsupported)
+ .mockRejectedValueOnce(new Error('[DEVICE_LINK_TIMEOUT] timed out'))
+ .mockRejectedValueOnce(policyFailure);
+ vi.stubGlobal('window', { electronAPI: { deviceLink: { invoke } } });
+ const mod = await import('@/hooks/useDeviceProviders');
+ const oldDeviceListener = vi.fn();
+ const offlineListener = vi.fn();
+ const policyFailureListener = vi.fn();
+ mod.subscribeDeviceProviders('dev-old', oldDeviceListener);
+ mod.subscribeDeviceProviders('dev-offline', offlineListener);
+ mod.subscribeDeviceProviders('dev-policy-failure', policyFailureListener);
+
+ await mod.prefetchDeviceProviders('dev-old');
+ await mod.prefetchDeviceProviders('dev-offline');
+ await mod.prefetchDeviceProviders('dev-policy-failure');
+
+ expect(mod.isDeviceProvidersUnsupportedError(unsupported)).toBe(true);
+ expect(mod.isDeviceProvidersUnsupportedError(policyFailure)).toBe(false);
+ expect(oldDeviceListener).toHaveBeenCalledWith({
+ status: 'error',
+ error: unsupported.message,
+ unsupported: true,
+ });
+ expect(offlineListener).toHaveBeenCalledWith({
+ status: 'error',
+ error: '[DEVICE_LINK_TIMEOUT] timed out',
+ unsupported: false,
+ });
+ expect(policyFailureListener).toHaveBeenCalledWith({
+ status: 'error',
+ error: policyFailure.message,
+ unsupported: false,
+ });
+ });
+
it('新快照只通知对应 deviceId 的已挂载订阅者', async () => {
const invoke = stubDeviceLink();
const mod = await import('@/hooks/useDeviceProviders');
@@ -141,7 +427,10 @@ describe('useDeviceProviders deviceId-aware cache', () => {
const off2 = mod.subscribeDeviceProviders('dev-2', dev2);
await mod.prefetchDeviceProviders('dev-1');
- expect(dev1).toHaveBeenCalledWith({ status: 'ready', providers: [{ id: 'dev-1-xd' }] });
+ expect(dev1).toHaveBeenCalledWith({
+ status: 'ready',
+ providers: [provider('dev-1-xd')],
+ });
expect(dev2).not.toHaveBeenCalled();
off1();
@@ -168,7 +457,7 @@ describe('useDeviceProviders deviceId-aware cache', () => {
expect(listener).toHaveBeenNthCalledWith(1, { status: 'loading' });
expect(listener).toHaveBeenNthCalledWith(2, {
status: 'ready',
- providers: [{ id: 'fresh-xd' }],
+ providers: [provider('fresh-xd')],
});
});
});
diff --git a/apps/desktop/src/renderer/__tests__/dialogueSidebarSection.test.ts b/apps/desktop/src/renderer/__tests__/dialogueSidebarSection.test.ts
index ada7fc19b7..73a5bc12c1 100644
--- a/apps/desktop/src/renderer/__tests__/dialogueSidebarSection.test.ts
+++ b/apps/desktop/src/renderer/__tests__/dialogueSidebarSection.test.ts
@@ -40,6 +40,11 @@ const newMakerDraftRouteSource = readFileSync(
'utf8',
);
+const remoteProjectsHookSource = readFileSync(
+ resolve(__dirname, '..', 'features', 'device-link', 'useDeviceLinkRemoteProjects.ts'),
+ 'utf8',
+);
+
describe('Dialogue sidebar section', () => {
it('is rendered after Projects in project-grouped mode', () => {
const projectsIndex = sidebarSource.indexOf('<ProjectsSection');
@@ -61,11 +66,9 @@ describe('Dialogue sidebar section', () => {
it('shows loading instead of the empty state until the initial session fetch settles', () => {
expect(sidebarSource.match(/isLoading=\{isLoadingSidebarSessions\}/g)).toHaveLength(2);
- expect(sidebarSource).toContain(
- 'useRemoteSessionBootstrapLoading(selectedMachineId)',
- );
- expect(sidebarSource).toContain(
- 'sessionsHook.isLoading || remoteSessionBootstrapLoading',
+ expect(sidebarSource).toContain('useRemoteSessionBootstrapLoading(selectedMachineId)');
+ expect(sidebarSource).toMatch(
+ /sessionsHook\.isLoading\s*\|\|\s*remoteSessionBootstrapLoading\s*\|\|\s*remoteDeviceDirectoryStatus === 'loading'/,
);
expect(dialogueSectionSource).toContain('isLoading: boolean');
expect(dialogueSectionSource).toContain("'ccAgent.sidebar.loadingDialogues'");
@@ -79,6 +82,28 @@ describe('Dialogue sidebar section', () => {
);
});
+ it('shows remote directory/task loading and failures before connecting or authoritative empty states', () => {
+ const failureIndex = sidebarSource.indexOf(
+ 'remoteSessionBootstrapFailures.length > 0 && !hasVisibleSidebarContent',
+ );
+ const connectingIndex = sidebarSource.indexOf('selectedMachineConnecting ?');
+ expect(failureIndex).toBeGreaterThanOrEqual(0);
+ expect(connectingIndex).toBeGreaterThan(failureIndex);
+ expect(sidebarSource).toContain('retryRemoteSessionBootstrap(device.deviceId)');
+ expect(sidebarSource).toContain("'ccAgent.sidebar.machineSwitcher.tasksLoadFailed'");
+ expect(sidebarSource).toContain("'ccAgent.sidebar.machineSwitcher.tasksPartiallyFailed'");
+ expect(sidebarSource).toContain("'ccAgent.sidebar.machineSwitcher.retryTasks'");
+ expect(sidebarSource).toContain("'ccAgent.sidebar.machineSwitcher.tasksLoading'");
+ expect(sidebarSource).toContain("'ccAgent.sidebar.machineSwitcher.devicesLoadFailed'");
+ expect(sidebarSource).toContain("'ccAgent.sidebar.machineSwitcher.devicesLoading'");
+ expect(sidebarSource).toContain('retryDeviceLinkDeviceList');
+ // 即使有旧/空 shard,本轮 gave-up 也必须进 error,不能把缓存伪装成权威结果。
+ expect(remoteProjectsHookSource).toContain("if (result === 'gave-up') {");
+ expect(remoteProjectsHookSource).not.toContain(
+ "result === 'gave-up' && !remoteProjectsStore.hasDevice(deviceId)",
+ );
+ });
+
it('has a Dialogue-owned runtime sort setting instead of using project manual order or renderer storage', () => {
expect(dialogueSectionSource).toContain('DIALOGUE_SORT_OPTIONS');
expect(dialogueSectionSource).not.toMatch(/manualProjectOrder/);
@@ -100,9 +125,15 @@ describe('Dialogue sidebar section', () => {
it('makes the Dialogue title and adjacent hover arrow collapse the section instead of putting collapse in the right tool group', () => {
const titleIndex = dialogueSectionSource.indexOf("t('ccAgent.sidebar.dialogues')");
const titleButtonIndex = dialogueSectionSource.lastIndexOf('<button', titleIndex);
- const titleExpandedIndex = dialogueSectionSource.indexOf('aria-expanded={!collapsed}', titleButtonIndex);
+ const titleExpandedIndex = dialogueSectionSource.indexOf(
+ 'aria-expanded={!collapsed}',
+ titleButtonIndex,
+ );
const hoverToggleIndex = dialogueSectionSource.indexOf('<Tip text={toggleLabel}');
- const hoverToggleExpandedIndex = dialogueSectionSource.indexOf('aria-expanded={!collapsed}', hoverToggleIndex);
+ const hoverToggleExpandedIndex = dialogueSectionSource.indexOf(
+ 'aria-expanded={!collapsed}',
+ hoverToggleIndex,
+ );
const settingsIndex = dialogueSectionSource.indexOf("t('ccAgent.sidebar.dialogueSettings')");
expect(titleIndex).toBeGreaterThanOrEqual(0);
@@ -115,17 +146,27 @@ describe('Dialogue sidebar section', () => {
it('only shows dialogue header actions while hovering or focusing the Dialogue header row', () => {
expect(dialogueSectionSource).toContain('group/sidebar-header flex h-6');
- expect(dialogueSectionSource).toContain('pointer-events-none opacity-0 transition-opacity duration-150');
- expect(dialogueSectionSource).toContain('group-hover/sidebar-header:pointer-events-auto group-hover/sidebar-header:opacity-100');
- expect(dialogueSectionSource).toContain('has-[:focus-visible]:pointer-events-auto has-[:focus-visible]:opacity-100');
- expect(dialogueSectionSource).not.toContain('group-focus-within/sidebar-header:pointer-events-auto');
+ expect(dialogueSectionSource).toContain(
+ 'pointer-events-none opacity-0 transition-opacity duration-150',
+ );
+ expect(dialogueSectionSource).toContain(
+ 'group-hover/sidebar-header:pointer-events-auto group-hover/sidebar-header:opacity-100',
+ );
+ expect(dialogueSectionSource).toContain(
+ 'has-[:focus-visible]:pointer-events-auto has-[:focus-visible]:opacity-100',
+ );
+ expect(dialogueSectionSource).not.toContain(
+ 'group-focus-within/sidebar-header:pointer-events-auto',
+ );
expect(dialogueSectionSource).toContain('className={HEADER_HOVER_ACTION_CLASS}');
expect(dialogueSectionSource).toContain('className={HEADER_ACTIONS_CLASS}');
});
it('creates a standalone dialogue without inheriting a project draft directory', () => {
expect(sidebarSource).toContain('resetDraftWorkspaceTargets();');
- expect(sidebarSource).toMatch(/navigate\(['`]\/cc-agent\/new['`],\s*\{\s*state:\s*makeNewMakerRouteState\('dialogue'\)\s*\}\)/);
+ expect(sidebarSource).toMatch(
+ /navigate\(['`]\/cc-agent\/new['`],\s*\{\s*state:\s*makeNewMakerRouteState\('dialogue'\)\s*\}\)/,
+ );
expect(sidebarSource).toContain('onCreateDialogue={handleCreateDialogue}');
});
@@ -134,6 +175,8 @@ describe('Dialogue sidebar section', () => {
// workingDir。workingDir 为空时直接创建 dialogue,不再强制弹项目 picker。
expect(newMakerDraftRouteSource).not.toContain('selectProjectRequired');
expect(newMakerDraftRouteSource).not.toContain('!selectedWorkingDir');
- expect(newMakerDraftRouteSource).toContain("workspaceKind: workingDir ? 'project' : 'dialogue'");
+ expect(newMakerDraftRouteSource).toContain(
+ "workspaceKind: workingDir ? 'project' : 'dialogue'",
+ );
});
});
diff --git a/apps/desktop/src/renderer/__tests__/machineSwitcher.test.ts b/apps/desktop/src/renderer/__tests__/machineSwitcher.test.ts
index 4b3c53783f..5c463f7ec5 100644
--- a/apps/desktop/src/renderer/__tests__/machineSwitcher.test.ts
+++ b/apps/desktop/src/renderer/__tests__/machineSwitcher.test.ts
@@ -15,6 +15,8 @@ import {
import { remoteProjectsStore } from '@/features/device-link/remoteProjectsStore';
import {
resolveSelectableIdsForNormalize,
+ selectRemoteSessionBootstrapFailures,
+ selectRemoteSessionBootstrapLoadingDevices,
shouldShowMachineSwitcher,
shouldShowSelectedMachineConnectingPlaceholder,
shouldWaitForRemoteSessionBootstrap,
@@ -50,11 +52,7 @@ function mkSession(id: string, deviceLinkDeviceId?: string): Session {
describe('selectVisibleSessions', () => {
const local = [mkSession('l1'), mkSession('l2')];
- const remote = [
- mkSession('r1', 'dev-a'),
- mkSession('r2', 'dev-a'),
- mkSession('r3', 'dev-b'),
- ];
+ const remote = [mkSession('r1', 'dev-a'), mkSession('r2', 'dev-a'), mkSession('r3', 'dev-b')];
it('所有(默认)→ 本机 + 全部远程合并(顺序:本地在前)', () => {
expect(selectVisibleSessions(local, remote, MACHINE_ALL).map((s) => s.id)).toEqual([
@@ -79,9 +77,9 @@ describe('selectVisibleSessions', () => {
});
it('多选:本机 + 某台远程 → 二者并集(本地在前)', () => {
- expect(
- selectVisibleSessions(local, remote, [MACHINE_LOCAL, 'dev-b']).map((s) => s.id),
- ).toEqual(['l1', 'l2', 'r3']);
+ expect(selectVisibleSessions(local, remote, [MACHINE_LOCAL, 'dev-b']).map((s) => s.id)).toEqual(
+ ['l1', 'l2', 'r3'],
+ );
});
it('多选:两台远程 → 按勾选集过滤,排除本地', () => {
@@ -152,9 +150,7 @@ describe('toggleMachineSelection(菜单多选点选)', () => {
it('「所有」下点选一项 → 收窄为只看该项(与旧单选直觉一致)', () => {
expect(toggleMachineSelection(MACHINE_ALL, 'dev-a', selectable)).toEqual(['dev-a']);
- expect(toggleMachineSelection(MACHINE_ALL, MACHINE_LOCAL, selectable)).toEqual([
- MACHINE_LOCAL,
- ]);
+ expect(toggleMachineSelection(MACHINE_ALL, MACHINE_LOCAL, selectable)).toEqual([MACHINE_LOCAL]);
});
it('未勾选 → 追加;已勾选 → 取消', () => {
@@ -167,9 +163,7 @@ describe('toggleMachineSelection(菜单多选点选)', () => {
});
it('勾满本机 + 全部可选设备 → 收敛回「所有」(未来新设备自动包含)', () => {
- expect(
- toggleMachineSelection([MACHINE_LOCAL, 'dev-a'], 'dev-b', selectable),
- ).toBe(MACHINE_ALL);
+ expect(toggleMachineSelection([MACHINE_LOCAL, 'dev-a'], 'dev-b', selectable)).toBe(MACHINE_ALL);
});
it('勾选集规范序:本机在前,设备按 id 字典序', () => {
@@ -186,9 +180,11 @@ describe('toggleMachineSelection(菜单多选点选)', () => {
it('隐藏半保留:勾选集中暂时不可选的设备不因无关点选被冲掉(codex P2)', () => {
// dev-offline 不在可选集(离线/未加载),点选 dev-a 后仍留在勾选集里。
- expect(
- toggleMachineSelection([MACHINE_LOCAL, 'dev-offline'], 'dev-a', selectable),
- ).toEqual([MACHINE_LOCAL, 'dev-a', 'dev-offline']);
+ expect(toggleMachineSelection([MACHINE_LOCAL, 'dev-offline'], 'dev-a', selectable)).toEqual([
+ MACHINE_LOCAL,
+ 'dev-a',
+ 'dev-offline',
+ ]);
// 取消可见项同样不动隐藏半。
expect(
toggleMachineSelection([MACHINE_LOCAL, 'dev-a', 'dev-offline'], 'dev-a', selectable),
@@ -197,9 +193,9 @@ describe('toggleMachineSelection(菜单多选点选)', () => {
it('隐藏半的两个收敛例外:可见半清空 → 回落「所有」;可见半勾满 → 收敛「所有」', () => {
// 可见半只剩 local,取消它 → 视觉上清空 → 回落「所有」(隐藏半一并放下,「所有」已覆盖)。
- expect(
- toggleMachineSelection([MACHINE_LOCAL, 'dev-offline'], MACHINE_LOCAL, selectable),
- ).toBe(MACHINE_ALL);
+ expect(toggleMachineSelection([MACHINE_LOCAL, 'dev-offline'], MACHINE_LOCAL, selectable)).toBe(
+ MACHINE_ALL,
+ );
// 可见半勾满本机 + 全部可选设备 → 收敛「所有」。
expect(
toggleMachineSelection([MACHINE_LOCAL, 'dev-a', 'dev-offline'], 'dev-b', selectable),
@@ -210,9 +206,10 @@ describe('toggleMachineSelection(菜单多选点选)', () => {
describe('机器选择持久化(serialize / parse 往返)', () => {
it('MACHINE_ALL 与勾选集均可往返', () => {
expect(parseMachineSelection(serializeMachineSelection(MACHINE_ALL))).toBe(MACHINE_ALL);
- expect(
- parseMachineSelection(serializeMachineSelection([MACHINE_LOCAL, 'dev-a'])),
- ).toEqual([MACHINE_LOCAL, 'dev-a']);
+ expect(parseMachineSelection(serializeMachineSelection([MACHINE_LOCAL, 'dev-a']))).toEqual([
+ MACHINE_LOCAL,
+ 'dev-a',
+ ]);
});
it('null / 损坏 JSON / 非法形状 → 回落「所有」', () => {
@@ -248,12 +245,10 @@ describe('机器选择持久化(serialize / parse 往返)', () => {
describe('buildSwitcherDevices', () => {
it('已连接(已同步)/ 连接中(在线可控未同步)/ 被拒(已撤销)三态分类', () => {
const result = buildSwitcherDevices({
- fullList: [
- mkDevice('dev-connected'),
- mkDevice('dev-connecting'),
- mkDevice('dev-rejected'),
+ fullList: [mkDevice('dev-connected'), mkDevice('dev-connecting'), mkDevice('dev-rejected')],
+ syncedDevices: [
+ { deviceId: 'dev-connected', deviceName: 'Connected', sessionCount: 1, connected: true },
],
- syncedDevices: [{ deviceId: 'dev-connected', deviceName: 'Connected', sessionCount: 1, connected: true }],
revoked: new Set(['dev-rejected']),
});
const byId = Object.fromEntries(result.map((d) => [d.deviceId, d.status]));
@@ -342,7 +337,9 @@ describe('buildSwitcherDevices', () => {
it('仅有断线缓存的设备仍显示,但状态为 connecting', () => {
const result = buildSwitcherDevices({
fullList: [],
- syncedDevices: [{ deviceId: 'dev-a', deviceName: 'Mac A', sessionCount: 2, connected: false }],
+ syncedDevices: [
+ { deviceId: 'dev-a', deviceName: 'Mac A', sessionCount: 2, connected: false },
+ ],
revoked: new Set(),
});
expect(result).toEqual([{ deviceId: 'dev-a', name: 'Mac A', status: 'connecting' }]);
@@ -375,7 +372,12 @@ describe('compareDevicesByName(切换栏与设置共用,稳定身份排序)'
{ name: 'alpha', deviceId: 'a1' },
{ name: 'Mike', deviceId: 'm' },
];
- expect(arr.slice().sort(compareDevicesByName).map((d) => d.deviceId)).toEqual([
+ expect(
+ arr
+ .slice()
+ .sort(compareDevicesByName)
+ .map((d) => d.deviceId),
+ ).toEqual([
'a1', // alpha + deviceId 兜底(a1 < a2)
'a2',
'm',
@@ -553,6 +555,81 @@ describe('shouldWaitForRemoteSessionBootstrap', () => {
});
});
+describe('selectRemoteSessionBootstrapFailures', () => {
+ const devices = [
+ { deviceId: 'dev-a', name: 'Mac A', status: 'connecting' as const },
+ { deviceId: 'dev-b', name: 'Mac B', status: 'connected' as const },
+ { deviceId: 'dev-c', name: 'Mac C', status: 'rejected' as const },
+ ];
+ const failures = new Set(['dev-a', 'dev-b', 'dev-c']);
+
+ it('所有机器返回全部可见失败设备,但不把已拒绝设备混成读取失败', () => {
+ expect(
+ selectRemoteSessionBootstrapFailures({
+ selectedMachineId: MACHINE_ALL,
+ devices,
+ bootstrapFailedDeviceIds: failures,
+ }).map((device) => device.deviceId),
+ ).toEqual(['dev-a', 'dev-b']);
+ });
+
+ it('显式多选只返回勾选范围内的失败设备;仅本机忽略远端失败', () => {
+ expect(
+ selectRemoteSessionBootstrapFailures({
+ selectedMachineId: ['dev-b'],
+ devices,
+ bootstrapFailedDeviceIds: failures,
+ }).map((device) => device.deviceId),
+ ).toEqual(['dev-b']);
+ expect(
+ selectRemoteSessionBootstrapFailures({
+ selectedMachineId: [MACHINE_LOCAL],
+ devices,
+ bootstrapFailedDeviceIds: failures,
+ }),
+ ).toEqual([]);
+ expect(
+ selectRemoteSessionBootstrapFailures({
+ selectedMachineId: [MACHINE_LOCAL, 'dev-a'],
+ devices,
+ bootstrapFailedDeviceIds: failures,
+ }).map((device) => device.deviceId),
+ ).toEqual(['dev-a']);
+ });
+});
+
+describe('selectRemoteSessionBootstrapLoadingDevices', () => {
+ const devices = [
+ { deviceId: 'dev-a', name: 'Mac A', status: 'connecting' as const },
+ { deviceId: 'dev-b', name: 'Mac B', status: 'connected' as const },
+ ];
+ const loading = new Set(['dev-a', 'dev-b']);
+
+ it('已有 shard 的设备重读时仍属于 loading,并按当前机器范围过滤', () => {
+ expect(
+ selectRemoteSessionBootstrapLoadingDevices({
+ selectedMachineId: MACHINE_ALL,
+ devices,
+ bootstrapLoadingDeviceIds: loading,
+ }).map((device) => device.deviceId),
+ ).toEqual(['dev-a', 'dev-b']);
+ expect(
+ selectRemoteSessionBootstrapLoadingDevices({
+ selectedMachineId: ['dev-b'],
+ devices,
+ bootstrapLoadingDeviceIds: loading,
+ }).map((device) => device.deviceId),
+ ).toEqual(['dev-b']);
+ expect(
+ selectRemoteSessionBootstrapLoadingDevices({
+ selectedMachineId: [MACHINE_LOCAL],
+ devices,
+ bootstrapLoadingDeviceIds: loading,
+ }),
+ ).toEqual([]);
+ });
+});
+
describe('shouldShowSelectedMachineConnectingPlaceholder', () => {
const noBootstrapFailures = new Set<string>();
@@ -593,7 +670,7 @@ describe('shouldShowSelectedMachineConnectingPlaceholder', () => {
).toBe(true);
});
- it('选中设备的 bootstrap 已终态失败 → 停止连接中占位并进入真实空态', () => {
+ it('选中设备的 bootstrap 已终态失败 → 停止连接中占位,交给独立错误态', () => {
expect(
shouldShowSelectedMachineConnectingPlaceholder({
rawSelection: ['dev-a'],
@@ -707,7 +784,11 @@ describe('applyDeviceRename(切换栏全量设备就地改名)', () => {
// buildSwitcherDevices 应立刻吐出新名(此前会停在旧名直到无关 refresh — Codex P2 修复点)。
const fullList = [mkDevice('dev-c', { name: 'Old C' })];
const renamed = applyDeviceRename(fullList, 'dev-c', 'New C') as DeviceLinkDeviceView[];
- const devices = buildSwitcherDevices({ fullList: renamed, syncedDevices: [], revoked: new Set() });
+ const devices = buildSwitcherDevices({
+ fullList: renamed,
+ syncedDevices: [],
+ revoked: new Set(),
+ });
expect(devices).toEqual([{ deviceId: 'dev-c', name: 'New C', status: 'connecting' }]);
});
});
diff --git a/apps/desktop/src/renderer/__tests__/modelSelectorProviderGroups.test.tsx b/apps/desktop/src/renderer/__tests__/modelSelectorProviderGroups.test.tsx
index b468768050..3f138eaef9 100644
--- a/apps/desktop/src/renderer/__tests__/modelSelectorProviderGroups.test.tsx
+++ b/apps/desktop/src/renderer/__tests__/modelSelectorProviderGroups.test.tsx
@@ -78,7 +78,9 @@ vi.mock('@/components/ui/popover', async () => {
vi.mock('@/lib/scrollbarAutoHide', () => ({ flashScrollbar: vi.fn() }));
vi.mock('@/hooks/useAgentCapabilities', () => ({
- useAgentCapabilities: () => ({ capabilities: null }),
+ evictDeviceCapabilities: vi.fn(),
+ prefetchDeviceCapabilities: vi.fn(async () => {}),
+ useAgentCapabilities: () => ({ capabilities: null, loading: false, error: null }),
}));
vi.mock('@/hooks/useApiKey', () => ({
@@ -150,7 +152,14 @@ vi.mock('@/hooks/useProviders', () => ({
}));
vi.mock('@/hooks/useDeviceProviders', () => ({
- useDeviceProviders: () => ({ providers: [], loading: false }),
+ evictDeviceProviders: vi.fn(),
+ prefetchDeviceProviders: vi.fn(async () => {}),
+ useDeviceProviders: () => ({
+ providers: [],
+ loading: false,
+ error: null,
+ unsupported: false,
+ }),
}));
vi.mock('@/lib/providerModels', () => ({
diff --git a/apps/desktop/src/renderer/__tests__/modelSelectorTriggerVariant.test.ts b/apps/desktop/src/renderer/__tests__/modelSelectorTriggerVariant.test.ts
index f6944f37bc..ae825a4ac2 100644
--- a/apps/desktop/src/renderer/__tests__/modelSelectorTriggerVariant.test.ts
+++ b/apps/desktop/src/renderer/__tests__/modelSelectorTriggerVariant.test.ts
@@ -34,6 +34,11 @@ vi.mock('react-i18next', async (importOriginal) => ({
'newChat.modelSelector.trigger.agent.codex': 'Codex',
'newChat.modelSelector.pricing.free': '限时免费',
'newChat.modelSelector.source.disconnected': '已断开',
+ 'newChat.modelSelector.remoteLoading': '正在从远程设备读取模型…',
+ 'newChat.modelSelector.remoteLoadFailed': '无法读取远程设备上的模型。请检查连接后重试。',
+ 'newChat.modelSelector.remoteLoadFailedShort': '模型读取失败',
+ 'newChat.modelSelector.retryRemoteModels': '重新读取模型',
+ 'newChat.modelSelector.search.noResults': '没有匹配的模型',
};
if (key === 'newChat.modelSelector.priceTip') {
return `Input ${options?.input} · Output ${options?.output} per 1M tokens`;
@@ -179,10 +184,21 @@ const agentCapabilitiesRef = vi.hoisted(() => {
effortLevels: [{ id: 'xhigh', displayName: 'X-High' }],
hasFastMode: false,
};
- return { DEFAULT_CAPABILITIES, capabilities: DEFAULT_CAPABILITIES as unknown };
+ return {
+ DEFAULT_CAPABILITIES,
+ capabilities: DEFAULT_CAPABILITIES as unknown,
+ loading: false,
+ error: null as string | null,
+ };
});
vi.mock('@/hooks/useAgentCapabilities', () => ({
- useAgentCapabilities: () => ({ capabilities: agentCapabilitiesRef.capabilities }),
+ evictDeviceCapabilities: vi.fn(),
+ prefetchDeviceCapabilities: vi.fn(async () => {}),
+ useAgentCapabilities: () => ({
+ capabilities: agentCapabilitiesRef.capabilities,
+ loading: agentCapabilitiesRef.loading,
+ error: agentCapabilitiesRef.error,
+ }),
}));
vi.mock('@/hooks/useApiKey', () => ({
@@ -275,9 +291,23 @@ vi.mock('@/hooks/useProviders', () => ({
}),
}));
-const deviceProvidersRef = vi.hoisted(() => ({ providers: [] as unknown[] }));
+const deviceProvidersRef = vi.hoisted(() => ({
+ providers: [] as unknown[],
+ loading: false,
+ error: null as string | null,
+ unsupported: false,
+ prefetch: vi.fn(async () => {}),
+}));
vi.mock('@/hooks/useDeviceProviders', () => ({
- useDeviceProviders: () => ({ providers: deviceProvidersRef.providers, loading: false }),
+ evictDeviceProviders: vi.fn(),
+ prefetchDeviceProviders: (...args: Parameters<typeof deviceProvidersRef.prefetch>) =>
+ deviceProvidersRef.prefetch(...args),
+ useDeviceProviders: () => ({
+ providers: deviceProvidersRef.providers,
+ loading: deviceProvidersRef.loading,
+ error: deviceProvidersRef.error,
+ unsupported: deviceProvidersRef.unsupported,
+ }),
}));
interface VisibleModelFixture {
@@ -372,6 +402,7 @@ import {
ModelSelectorContent,
modelEffortLabel,
modelListMaxHeightForRows,
+ resolveRemoteModelListStatus,
resolveModelSelectorAgentIdentity,
} from '@/components/new-chat/ModelSelector';
import { makerChatStore } from '@/lib/makerChatStore';
@@ -381,11 +412,93 @@ const requestProviderModelsAutoRefresh = vi.fn(async () => ({ ok: true as const
beforeEach(() => {
requestProviderModelsAutoRefresh.mockClear();
providersRef.providerOrder = [];
+ agentCapabilitiesRef.loading = false;
+ agentCapabilitiesRef.error = null;
+ deviceProvidersRef.loading = false;
+ deviceProvidersRef.error = null;
+ deviceProvidersRef.unsupported = false;
+ deviceProvidersRef.prefetch.mockReset();
+ deviceProvidersRef.prefetch.mockResolvedValue(undefined);
(window as unknown as { electronAPI: unknown }).electronAPI = {
maker: { requestProviderModelsAutoRefresh },
};
});
+describe('resolveRemoteModelListStatus', () => {
+ const ready = { capabilities: {}, loading: false, error: null };
+ const pending = { capabilities: null, loading: true, error: null };
+ const failed = { capabilities: null, loading: false, error: 'offline' };
+
+ it('requires the selected agent capability and provider result before declaring ready', () => {
+ expect(
+ resolveRemoteModelListStatus({
+ deviceId: 'dev-a',
+ agentKind: 'claude-code',
+ cc: pending,
+ codex: failed,
+ pi: failed,
+ providers: { loading: false, error: null },
+ }),
+ ).toBe('loading');
+ expect(
+ resolveRemoteModelListStatus({
+ deviceId: 'dev-a',
+ agentKind: 'claude-code',
+ cc: ready,
+ codex: failed,
+ pi: failed,
+ providers: { loading: false, error: null },
+ }),
+ ).toBe('ready');
+ });
+
+ it('reports capability or connection failures instead of authoritative empty', () => {
+ expect(
+ resolveRemoteModelListStatus({
+ deviceId: 'dev-a',
+ agentKind: 'claude-code',
+ cc: failed,
+ codex: ready,
+ pi: ready,
+ providers: { loading: false, error: null },
+ }),
+ ).toBe('error');
+ expect(
+ resolveRemoteModelListStatus({
+ deviceId: 'dev-a',
+ agentKind: null,
+ cc: ready,
+ codex: failed,
+ pi: ready,
+ providers: { loading: false, error: null },
+ }),
+ ).toBe('error');
+ expect(
+ resolveRemoteModelListStatus({
+ deviceId: 'dev-a',
+ agentKind: 'claude-code',
+ cc: ready,
+ codex: ready,
+ pi: ready,
+ providers: { loading: false, error: 'timeout', unsupported: false },
+ }),
+ ).toBe('error');
+ });
+
+ it('only treats an unsupported provider channel as a compatible flat-list fallback', () => {
+ expect(
+ resolveRemoteModelListStatus({
+ deviceId: 'dev-old',
+ agentKind: 'claude-code',
+ cc: ready,
+ codex: ready,
+ pi: ready,
+ providers: { loading: false, error: 'channel not allowed', unsupported: true },
+ }),
+ ).toBe('ready');
+ });
+});
+
describe('ModelSelector trigger variants', () => {
// 打开选择器既发起刷新、又把「发现在途」状态推给内容区(见 useModelDiscoveryPending),
// 所以点击要走 act:那次刷新 resolve 后还有一次 setPending(false) 落在微任务里。
@@ -395,6 +508,79 @@ describe('ModelSelector trigger variants', () => {
});
};
+ it('remote loading replaces the placeholder and no-results empty state', async () => {
+ const originalCapabilities = agentCapabilitiesRef.capabilities;
+ const originalModels = visibleModelsRef.models;
+ agentCapabilitiesRef.capabilities = null;
+ agentCapabilitiesRef.loading = true;
+ deviceProvidersRef.loading = true;
+ visibleModelsRef.models = [];
+ const view = render(
+ React.createElement(ModelSelector, {
+ modelId: 'remote-model',
+ effort: 'medium',
+ onModelChange: vi.fn(),
+ onEffortChange: vi.fn(),
+ vendorKey: 'cc',
+ deviceId: 'dev-a',
+ }),
+ );
+ try {
+ const trigger = screen.getByRole('button', { name: /正在从远程设备读取模型/ });
+ expect(trigger.textContent).toContain('正在从远程设备读取模型…');
+ await act(async () => {
+ fireEvent.click(trigger);
+ });
+ expect(screen.getAllByText('正在从远程设备读取模型…').length).toBeGreaterThan(1);
+ expect(screen.queryByText('没有匹配的模型')).toBeNull();
+ } finally {
+ view.unmount();
+ agentCapabilitiesRef.capabilities = originalCapabilities;
+ agentCapabilitiesRef.loading = false;
+ deviceProvidersRef.loading = false;
+ visibleModelsRef.models = originalModels;
+ }
+ });
+
+ it('remote failures show an explicit retry state instead of no matching models', async () => {
+ const originalCapabilities = agentCapabilitiesRef.capabilities;
+ const originalModels = visibleModelsRef.models;
+ agentCapabilitiesRef.capabilities = null;
+ agentCapabilitiesRef.error = 'offline';
+ visibleModelsRef.models = [];
+ const view = render(
+ React.createElement(ModelSelector, {
+ modelId: 'remote-model',
+ effort: 'medium',
+ onModelChange: vi.fn(),
+ onEffortChange: vi.fn(),
+ vendorKey: 'cc',
+ deviceId: 'dev-a',
+ }),
+ );
+ try {
+ const trigger = screen.getByRole('button', { name: /模型读取失败/ });
+ expect(trigger.textContent).toContain('模型读取失败');
+ await act(async () => {
+ fireEvent.click(trigger);
+ });
+ expect(screen.getByText('无法读取远程设备上的模型。请检查连接后重试。')).toBeTruthy();
+ expect(screen.getByRole('button', { name: '重新读取模型' })).toBeTruthy();
+ expect(screen.queryByText('没有匹配的模型')).toBeNull();
+ deviceProvidersRef.prefetch.mockRejectedValueOnce(new Error('offline'));
+ await act(async () => {
+ fireEvent.click(screen.getByRole('button', { name: '重新读取模型' }));
+ await Promise.resolve();
+ });
+ expect(deviceProvidersRef.prefetch).toHaveBeenCalledWith('dev-a');
+ } finally {
+ view.unmount();
+ agentCapabilitiesRef.capabilities = originalCapabilities;
+ agentCapabilitiesRef.error = null;
+ visibleModelsRef.models = originalModels;
+ }
+ });
+
it('orders local provider sections by the Settings display preference', () => {
providersRef.providers = [
...providersRef.DEFAULT_PROVIDERS,
@@ -881,7 +1067,7 @@ describe('ModelSelector trigger variants', () => {
expect(trigger.querySelector('[data-model-promotion-badge]')).toBeNull();
});
- it('keeps a long subscription-backed field menu bounded and wheel-scrollable', () => {
+ it('keeps a long subscription-backed field menu bounded and wheel-scrollable', async () => {
const models: VisibleModelFixture[] = Array.from({ length: 40 }, (_, index) => ({
id: `subscription-model-${index + 1}`,
displayName: `Subscription Model ${index + 1}`,
@@ -928,7 +1114,9 @@ describe('ModelSelector trigger variants', () => {
}),
);
- fireEvent.click(screen.getByRole('button', { name: /Current: Subscription Model 1/ }));
+ await act(async () => {
+ fireEvent.click(screen.getByRole('button', { name: /Current: Subscription Model 1/ }));
+ });
const list = screen.getByRole('listbox', { name: 'Model list' });
expect(list.className).toContain('max-h-[300px]');
@@ -945,7 +1133,7 @@ describe('ModelSelector trigger variants', () => {
}
});
- it('reuses the parent pricing snapshot when the model content opens', () => {
+ it('reuses the parent pricing snapshot when the model content opens', async () => {
pricingRef.renderCalls = 0;
render(
React.createElement(ModelSelector, {
@@ -959,8 +1147,12 @@ describe('ModelSelector trigger variants', () => {
expect(pricingRef.renderCalls).toBe(1);
pricingRef.renderCalls = 0;
- fireEvent.click(screen.getByRole('button', { name: /Current: Opus 4\.8/ }));
- expect(pricingRef.renderCalls).toBe(1);
+ await act(async () => {
+ fireEvent.click(screen.getByRole('button', { name: /Current: Opus 4\.8/ }));
+ });
+ // Opening and the discovery-pending settle each re-render the parent once. The content must
+ // reuse that parent's pricing snapshot; calling useModelPricing inside it would double this.
+ expect(pricingRef.renderCalls).toBe(2);
});
it('does not show Gateway promotions in the selected-model trigger', () => {
@@ -1041,7 +1233,9 @@ describe('ModelSelector trigger variants', () => {
}),
);
expect(
- within(screen.getByRole('button', { name: /Current: Sonnet 4\.6/ })).queryByText('限时免费'),
+ within(screen.getByRole('button', { name: /Current: Sonnet 4\.6/ })).queryByText(
+ '限时免费',
+ ),
).toBeNull();
} finally {
providersRef.providers = providersRef.DEFAULT_PROVIDERS;
@@ -1181,7 +1375,15 @@ describe('ModelSelector trigger variants', () => {
},
])(
'renders the corrected XD effort defaults without Fast markers for $agentKind',
- ({ agentKind, vendorKey, currentModel, seedEfforts, seedDefaultEffort, seedLabel, glmEfforts }) => {
+ ({
+ agentKind,
+ vendorKey,
+ currentModel,
+ seedEfforts,
+ seedDefaultEffort,
+ seedLabel,
+ glmEfforts,
+ }) => {
const targetModels: VisibleModelFixture[] = [
{
id: 'bytedance-seed/seed-2.1-pro',
@@ -1293,8 +1495,12 @@ describe('ModelSelector trigger variants', () => {
'超高',
);
expect(screen.getByRole('option', { name: /GLM-5\.2/ }).textContent).toContain('Max');
- expect(screen.getByRole('option', { name: /DeepSeek V4 Pro/ }).textContent).toContain('High');
- expect(screen.getByRole('option', { name: /DeepSeek V4 Flash/ }).textContent).toContain('High');
+ expect(screen.getByRole('option', { name: /DeepSeek V4 Pro/ }).textContent).toContain(
+ 'High',
+ );
+ expect(screen.getByRole('option', { name: /DeepSeek V4 Flash/ }).textContent).toContain(
+ 'High',
+ );
expect(screen.queryByLabelText('newChat.modelSelector.meta.fastBadge')).toBeNull();
} finally {
visibleModelsRef.models = null;
@@ -1452,9 +1658,7 @@ describe('ModelSelector trigger variants', () => {
expect(detailText.indexOf('1M context')).toBeLessThan(
detailText.indexOf('Codex compatibility mode'),
);
- expect(compatibilityLabel).not.toBe(
- within(details).getByText(sourceText).parentElement,
- );
+ expect(compatibilityLabel).not.toBe(within(details).getByText(sourceText).parentElement);
expect(compatibilityLabel).not.toBe(
within(details).getByText('1M context').parentElement,
);
@@ -1896,8 +2100,7 @@ describe('ModelSelector trigger variants', () => {
return React.createElement(ModelSelector, {
modelId: selection.modelId,
effort: 'high',
- onModelChange: (modelId: string) =>
- setSelection((current) => ({ ...current, modelId })),
+ onModelChange: (modelId: string) => setSelection((current) => ({ ...current, modelId })),
onEffortChange: vi.fn(),
vendorKey: 'cc',
currentProviderId: selection.providerId,
@@ -1970,12 +2173,8 @@ describe('ModelSelector trigger variants', () => {
expect(searchInput.hasAttribute('disabled')).toBe(true);
expect(searchInput.className).toContain('cursor-not-allowed');
expect(searchInput.className).toContain('text-[var(--text-disabled)]');
- expect(searchInput.className).toContain(
- 'placeholder:text-[var(--text-disabled-tertiary)]',
- );
- expect(searchInput.parentElement?.className).toContain(
- 'bg-[var(--surface-elevated-soft)]',
- );
+ expect(searchInput.className).toContain('placeholder:text-[var(--text-disabled-tertiary)]');
+ expect(searchInput.parentElement?.className).toContain('bg-[var(--surface-elevated-soft)]');
fireEvent.click(opusRow);
fireEvent.pointerEnter(opusRow);
@@ -2071,9 +2270,7 @@ describe('ModelSelector trigger variants', () => {
fireEvent.click(within(options).getByRole('option', { name: 'low' }));
expect(setEffort).toHaveBeenCalledWith('codex', 'zeta-codex', 'gpt-5.5', 'low');
expect(confirmBrowseSwitch).toHaveBeenCalledTimes(1);
- await waitFor(() =>
- expect(onSwitch).toHaveBeenCalledWith('codex', 'gpt-5.5', 'zeta-codex'),
- );
+ await waitFor(() => expect(onSwitch).toHaveBeenCalledWith('codex', 'gpt-5.5', 'zeta-codex'));
expect(onDismiss).not.toHaveBeenCalled();
// 配置点击同时选中目标模型;确认门仍只在 Agent 分段切换。
expect(confirmBrowseSwitch).toHaveBeenCalledTimes(1);
@@ -2089,13 +2286,7 @@ describe('ModelSelector trigger variants', () => {
// 第一笔事务仍在途时,后一次配置也立即交给调用方;调用方会同步登记目标
// session 的 pending token,再由 session 级协调器保证同会话顺序。
expect(onSwitch).toHaveBeenCalledTimes(2);
- expect(setEffort).toHaveBeenNthCalledWith(
- 2,
- 'codex',
- 'zeta-codex',
- 'gpt-5.5',
- 'high',
- );
+ expect(setEffort).toHaveBeenNthCalledWith(2, 'codex', 'zeta-codex', 'gpt-5.5', 'high');
await act(async () => {
releaseFirstSwitch();
diff --git a/apps/desktop/src/renderer/__tests__/newMakerOrcaCreateOrder.test.ts b/apps/desktop/src/renderer/__tests__/newMakerOrcaCreateOrder.test.ts
index 8daf78b77e..53743aca93 100644
--- a/apps/desktop/src/renderer/__tests__/newMakerOrcaCreateOrder.test.ts
+++ b/apps/desktop/src/renderer/__tests__/newMakerOrcaCreateOrder.test.ts
@@ -26,9 +26,18 @@ const remoteCollabHandoffSource = readFileSync(
describe('NewMakerDraftRoute Orca worker create order', () => {
it('delegates worker creation to enableOrca and defers tab reveal until the new route is current', () => {
const collabBranch = source.indexOf('if (shouldEnableCollab)');
- const enableOrca = source.indexOf('const result = await window.electronAPI.maker.enableOrca', collabBranch);
- const revealState = source.indexOf('orcaWorkersRevealState = { focusWorkerSessionId: result.workerSessionId };', enableOrca);
- const navigate = source.indexOf('navigate(orcaNavTarget ?? `/cc-agent/${newSession.id}`', revealState);
+ const enableOrca = source.indexOf(
+ 'const result = await window.electronAPI.maker.enableOrca',
+ collabBranch,
+ );
+ const revealState = source.indexOf(
+ 'orcaWorkersRevealState = { focusWorkerSessionId: result.workerSessionId };',
+ enableOrca,
+ );
+ const navigate = source.indexOf(
+ 'navigate(orcaNavTarget ?? `/cc-agent/${newSession.id}`',
+ revealState,
+ );
expect(collabBranch).toBeGreaterThan(-1);
expect(enableOrca).toBeGreaterThan(collabBranch);
@@ -46,7 +55,10 @@ describe('NewMakerDraftRoute Orca worker create order', () => {
// 本机 / SSH 侧四条草稿起 Worker 路径都走同一个错误映射器:Send 普通、Send worktree、
// 新建目标(2026-07-23 新增 New Goal 路径也 honor 协同,codex P2)、以及 SSH 添加远程
// 项目(2026-07-28 remote 协同接通, codex-connector P2)。
- const mappedFallbacks = source.match(/getCollaborationStartErrorMessage\(err, t, \{ continueAsSingleSession: true \}\)/g) ?? [];
+ const mappedFallbacks =
+ source.match(
+ /getCollaborationStartErrorMessage\(err, t, \{ continueAsSingleSession: true \}\)/g,
+ ) ?? [];
expect(mappedFallbacks).toHaveLength(4);
// device-link 两条(issue #1170)的失败提示已随「等待挪到导航之后」一起搬进
@@ -156,7 +168,7 @@ describe('NewMakerDraftRoute Orca worker create order', () => {
// 本机 / SSH 的四条路径仍按控制端目录收窄,不能被一起改掉。
expect(
collapsed.match(
- /draftEnableOrcaOptions\(effectiveCollab, localProviders, !localProvidersLoading\)/g,
+ /draftEnableOrcaOptions\(\s*effectiveCollab,\s*localProviders,\s*!localProvidersLoading,?\s*\)/g,
) ?? [],
).toHaveLength(4);
});
@@ -184,13 +196,13 @@ describe('NewMakerDraftRoute Orca worker create order', () => {
it('blocks new-goal creation until a selected collaboration policy is available', () => {
const goalHandler = source.slice(source.indexOf('const handleCreateGoal = useCallback('));
- expect(goalHandler).toContain("let policyEnabled = collabPolicy.enabled");
- expect(goalHandler).toContain("if (collabPolicy.loading)");
- expect(goalHandler).toContain("if (collabPolicy.unavailable)");
- expect(goalHandler).toContain("collabPolicy.refresh()");
- expect(goalHandler).toContain("policyEnabled = refreshed.enabled");
- expect(goalHandler).toContain("if (!policyEnabled)");
- expect(goalHandler.indexOf("if (collabPolicy.loading)")).toBeLessThan(
+ expect(goalHandler).toContain('let policyEnabled = collabPolicy.enabled');
+ expect(goalHandler).toContain('if (collabPolicy.loading)');
+ expect(goalHandler).toContain('if (collabPolicy.unavailable)');
+ expect(goalHandler).toContain('collabPolicy.refresh()');
+ expect(goalHandler).toContain('policyEnabled = refreshed.enabled');
+ expect(goalHandler).toContain('if (!policyEnabled)');
+ expect(goalHandler.indexOf('if (collabPolicy.loading)')).toBeLessThan(
goalHandler.indexOf('const newSession = await createSession'),
);
});
@@ -301,7 +313,9 @@ describe('NewMakerDraftRoute Orca worker create order', () => {
// 归属走粘滞解析:非粘滞版在 relay 瞬断窗口会返回 undefined → 跳过订阅,
// 而 goalApiFor 仍按粘滞归属把 setGoal 发到被控端(greptile P1,不变量 #3)。
expect(branch).toContain('const deviceId = getStickySessionDeviceId(sessionId);');
- const awaitCollab = branch.indexOf('await consumePendingRemoteCollab(pendingGoal.remoteCollab');
+ const awaitCollab = branch.indexOf(
+ 'await consumePendingRemoteCollab(pendingGoal.remoteCollab',
+ );
const setGoal = branch.indexOf('await goalApiFor(sessionId).setGoal(');
const forget = branch.indexOf('deliverRecoverableHandoff(sessionId, async () => {');
const unlock = branch.indexOf('setRemoteHandoffPreparing(false)');
diff --git a/apps/desktop/src/renderer/__tests__/newMakerProjectPicker.test.ts b/apps/desktop/src/renderer/__tests__/newMakerProjectPicker.test.ts
index cf8cb200b4..43d1a62009 100644
--- a/apps/desktop/src/renderer/__tests__/newMakerProjectPicker.test.ts
+++ b/apps/desktop/src/renderer/__tests__/newMakerProjectPicker.test.ts
@@ -207,26 +207,16 @@ describe('Shared create project picker', () => {
expect(newMakerDraftRouteSource).toContain(
'deviceLinkReconnectEpoch={remoteDraftRefreshEpoch}',
);
- expect(worktreeChipsSource).toContain(
- "sourceBranch || branches.current || 'HEAD'",
- );
- expect(worktreeChipsSource).not.toContain(
- "sourceBranch || branches.current || 'main'",
- );
+ expect(worktreeChipsSource).toContain("sourceBranch || branches.current || 'HEAD'");
+ expect(worktreeChipsSource).not.toContain("sourceBranch || branches.current || 'main'");
});
it('invalidates worktree probe-derived fields when the selected project changes', () => {
const start = newMakerDraftRouteSource.indexOf('const handleWorkingDirChange');
- const end = newMakerDraftRouteSource.indexOf(
- '// ─── 新草稿入场',
- start,
- );
+ const end = newMakerDraftRouteSource.indexOf('// ─── 新草稿入场', start);
const handler = newMakerDraftRouteSource.slice(start, end);
const actionStart = newMakerDraftRouteSource.indexOf('const applyDraftTarget = useCallback(');
- const actionEnd = newMakerDraftRouteSource.indexOf(
- '// 弹窗确认添加后的落点',
- actionStart,
- );
+ const actionEnd = newMakerDraftRouteSource.indexOf('// 弹窗确认添加后的落点', actionStart);
const action = newMakerDraftRouteSource.slice(actionStart, actionEnd);
expect(handler).toContain('applyDraftTarget({');
@@ -251,6 +241,13 @@ describe('Shared create project picker', () => {
expect(newMakerDraftRouteSource).toContain('deviceScope={folderPickerDeviceScope}');
expect(deviceLinkProjectsHookSource).toContain('loadDeviceLinkExistingProjects(deviceId)');
expect(deviceLinkProjectsHookSource).toContain('removeDeviceLinkExistingProject(');
+ expect(deviceLinkProjectsHookSource).toContain("status: 'error'");
+ expect(deviceLinkProjectsHookSource).toContain('retry: () => void');
+ expect(folderPickerPopoverSource).toContain("deviceScope?.status === 'error'");
+ expect(folderPickerPopoverSource).toContain(
+ "t('newChat.folderPicker.remoteProjectsLoadFailed'",
+ );
+ expect(folderPickerPopoverSource).toContain("t('newChat.folderPicker.retryRemoteProjects')");
// 弹窗统一两类来源:SSH ready hosts + device-link 可控设备(optgroup 区分)。
expect(addRemoteProjectDialogSource).toContain("res.hosts.filter((h) => h.status === 'ready')");
expect(addRemoteProjectDialogSource).toContain('useControllableDevices()');
@@ -273,8 +270,10 @@ describe('Shared create project picker', () => {
// requireAgent 的 not-registered。远程草稿以被控端注册结果为准(hook 传 deviceId 走隧道)。
it('gates the vendor switcher by runtime-registered agents (list-available-agents)', () => {
// hook 用权威的 runtime 注册来源,而非模型目录;远程走 device-link 隧道。
- expect(availableAgentsHookSource).toContain("api.listAvailableAgents()");
- expect(availableAgentsHookSource).toContain("dl.invoke(deviceId, 'maker:list-available-agents', [])");
+ expect(availableAgentsHookSource).toContain('api.listAvailableAgents()');
+ expect(availableAgentsHookSource).toContain(
+ "dl.invoke(deviceId, 'maker:list-available-agents', [])",
+ );
// claude-code → cc 归一,fail-open(未加载不隐藏)。
expect(availableAgentsHookSource).toContain("agent === 'claude-code' ? 'cc' : agent");
// 未加载完成时不隐藏任何入口(loaded 保持 false → 空 hidden)。
@@ -282,10 +281,14 @@ describe('Shared create project picker', () => {
// 开关按 hiddenVendors 过滤 OPTIONS,但保留当前选中段避免"无选中"过渡帧。
expect(vendorSwitcherSource).toContain('hiddenVendors');
- expect(vendorSwitcherSource).toMatch(/opt\.vendor === value \|\| !hiddenVendors\.includes\(opt\.vendor\)/);
+ expect(vendorSwitcherSource).toMatch(
+ /opt\.vendor === value \|\| !hiddenVendors\.includes\(opt\.vendor\)/,
+ );
// 路由:以被控端(deviceId)为准计算 hidden;两处开关都传;选中值被隐藏时 coerce 到首个可用。
- expect(newMakerDraftRouteSource).toContain('useAvailableAgents(effectiveDeviceLinkDeviceId)');
+ expect(newMakerDraftRouteSource).toMatch(
+ /useAvailableAgents\(\s*effectiveDeviceLinkDeviceId,?\s*\)/,
+ );
expect(newMakerDraftRouteSource).toContain('hiddenVendors={hiddenSwitcherVendors}');
expect(newMakerDraftRouteSource).toMatch(/hiddenSwitcherVendors\.includes\(draft\.vendor\)/);
});
@@ -328,15 +331,11 @@ describe('Shared create project picker', () => {
'if (isDeviceLinkDraft && effectiveDeviceLinkDeviceId) {',
);
// 远程纯对话没有 repo:即使 wtEnabled 残留 true 也必须跳过 worktree 分支。
- expect(newMakerDraftRouteSource).toContain(
- '&& wt.supportsRecoveryKeyDiscard === true',
- );
+ expect(newMakerDraftRouteSource).toMatch(/&&\s*wt\.supportsRecoveryKeyDiscard === true/);
expect(newMakerDraftRouteSource).toContain(
'onRecoveryKeyDiscardSupportChange={handleWtRecoveryKeyDiscardSupportChange}',
);
- expect(worktreeChipsSource).toContain(
- 'detect.data.supportsRecoveryKeyDiscard === true',
- );
+ expect(worktreeChipsSource).toContain('detect.data.supportsRecoveryKeyDiscard === true');
});
// #807 review 修复:新建目标必须与普通发送同口径 —— 远程纯对话下不能因为缺 workingDir 就抛错。
@@ -414,8 +413,8 @@ describe('Shared create project picker', () => {
);
// 上层仍要在已选设备时下发 onAddRemoteProject —— 入口 1 与空态入口都靠它,
// 只是那个 Globe 项不再渲染。别顺手把这个 gate 一起收掉。
- expect(newMakerDraftRouteSource).toContain(
- 'hasAnyRemoteTarget || folderPickerDeviceScope ? handleOpenRemoteProject : undefined',
+ expect(newMakerDraftRouteSource).toMatch(
+ /hasAnyRemoteTarget \|\|\s*folderPickerDeviceScope\s*\?\s*handleOpenRemoteProject\s*:\s*undefined/,
);
});
@@ -472,10 +471,12 @@ describe('Shared create project picker', () => {
);
// memo 的归属守卫:这是把 deviceId 绑进状态的唯一目的。
expect(deviceLinkProjectsHookSource).toContain('deviceId && loaded.deviceId === deviceId');
- // 归属没对上时仍算加载中,避免切设备那一帧闪「没有项目」空态。
+ // 请求态也必须绑定归属设备:归属没对上或还没发起时仍算加载中,
+ // 避免切设备那一帧闪「没有项目」空态,也避免上一台的失败串过来。
expect(deviceLinkProjectsHookSource).toContain(
- 'const effectiveLoading = loading || (deviceId != null && loaded.deviceId !== deviceId);',
+ "requestState.deviceId !== deviceId || requestState.status === 'idle'",
);
+ expect(deviceLinkProjectsHookSource).toContain("loading: status === 'loading'");
});
// #807 review 第十四轮:恢复路径不能依赖 React 的调度时机。`setRows(updater)` 的 updater
@@ -630,18 +631,30 @@ describe('Shared create project picker', () => {
);
});
- // #807 review 第十轮:两个创建 guard 必须把 remoteDraftState.loaded 一起看。换设备时我们把它
- // 打回未加载(防上一台默认值串台),而 capabilities/providers 若已缓存则那两个 loading 立刻为
- // false —— 只看它们会在 maker:get-new-maker-defaults 回来前放行,提交 capability 兜底值而不是
- // 该设备保存的草稿值,会话建出来后晚到的响应也修不回去。
- it('waits for remote defaults before allowing send or goal creation', () => {
- const guards =
- newMakerDraftRouteSource.match(
- /capabilitiesLoading \|\| deviceProvidersLoading \|\| !remoteDraftState\.loaded/g,
- ) ?? [];
- expect(guards.length).toBe(2);
- expect(newMakerDraftRouteSource).not.toContain(
- 'if (isDeviceLinkDraft && (capabilitiesLoading || deviceProvidersLoading)) return false;',
+ // 远程模型目录的 loading / error 与草稿默认值都是创建前置条件:任一路径没就绪
+ // 都不能把兜底值提交给对端;真实读取失败还必须告知用户,不能在 loading=false 后放行。
+ it('blocks send and goal creation until remote models/defaults are ready, including terminal errors', () => {
+ expect(newMakerDraftRouteSource).toContain(
+ 'capabilitiesError || (deviceProvidersError && !deviceProvidersUnsupported)',
+ );
+ expect(newMakerDraftRouteSource.match(/remoteModelListStatus !== 'ready'/g)).toHaveLength(2);
+ expect(newMakerDraftRouteSource).toContain(
+ "toast.error(t('newChat.modelSelector.remoteLoadFailed'))",
+ );
+ expect(newMakerDraftRouteSource).toContain(
+ "throw new Error(t('newChat.modelSelector.remoteLoadFailed'))",
+ );
+ expect(newMakerDraftRouteSource).toContain("remoteDraftState.status === 'error'");
+ expect(newMakerDraftRouteSource).toContain(
+ "toast.error(t('ccAgent.draft.remoteDefaultsLoadFailed'))",
+ );
+ expect(newMakerDraftRouteSource).toContain(
+ "throw new Error(t('ccAgent.draft.remoteDefaultsLoadFailed'))",
+ );
+ expect(newMakerDraftRouteSource).toContain('setRemoteDraftRetryEpoch((value) => value + 1)');
+ expect(newMakerDraftRouteSource).toContain("status: unsupported ? 'ready' : 'error'");
+ expect(newMakerDraftRouteSource).toContain(
+ "if (extractIpcError(error)?.code === 'DEVICE_LINK_CHANNEL_NOT_ALLOWED') return null;",
);
});
@@ -717,11 +730,11 @@ describe('Shared create project picker', () => {
newMakerDraftRouteSource.indexOf('const applyDraftTarget = useCallback('),
);
const body = action.slice(0, action.indexOf(' patchDraft({'));
- // 没有 inline 快照(设备 pill / 回落两条路径)且换了设备 → 打回未加载,交给 seed effect。
+ // 没有 inline 快照(设备 pill / 回落两条路径)且换了设备 → 打回 loading,交给 seed effect。
const fallback = body.slice(body.indexOf('} else if (deviceChanged) {'));
expect(fallback).toContain('setDlSel(null);');
expect(fallback).toContain('dlSeedKeyRef.current = null;');
- expect(fallback).toContain('setRemoteDraftState({ loaded: false, value: null });');
+ expect(fallback).toContain("setRemoteDraftState({ status: 'loading', value: null });");
// 有 inline 快照(设备域浏览器)则当场 seed,并置 skip flag 避免 effect 再拉一次覆盖掉。
expect(body).toContain('skipDefaultsRefetchRef.current = true;');
});
@@ -733,8 +746,8 @@ describe('Shared create project picker', () => {
expect(folderPickerPopoverSource).toContain('if (deviceScope) {');
expect(folderPickerPopoverSource).toContain('onAddRemoteProject?.(deviceScope.deviceId);');
// 已选定设备时无条件下发入口(设备离线也要能浏览它)。
- expect(newMakerDraftRouteSource).toContain(
- 'hasAnyRemoteTarget || folderPickerDeviceScope ? handleOpenRemoteProject : undefined',
+ expect(newMakerDraftRouteSource).toMatch(
+ /hasAnyRemoteTarget \|\|\s*folderPickerDeviceScope\s*\?\s*handleOpenRemoteProject\s*:\s*undefined/,
);
});
@@ -787,11 +800,10 @@ describe('Shared create project picker', () => {
// #807 review 第三轮:能力缓存命中时必须清掉上一目标遗留的 loading —— 漏了会让
// capabilitiesLoading 永久为 true,而创建页的 send / goal guard 正是看它。
it('clears inherited loading state when the capability cache hits', () => {
- const cachedBranch = agentCapabilitiesHookSource.slice(
- agentCapabilitiesHookSource.indexOf(
- 'const cached = cache.get(cacheKey(agentKind, deviceId));',
- ),
+ const hookSource = agentCapabilitiesHookSource.slice(
+ agentCapabilitiesHookSource.indexOf('export function useAgentCapabilities('),
);
+ const cachedBranch = hookSource.slice(hookSource.indexOf('const cached = cache.get(key);'));
const untilReturn = cachedBranch.slice(0, cachedBranch.indexOf('return;'));
expect(untilReturn).toContain('setLoading(false);');
expect(untilReturn).toContain('setError(null);');
diff --git a/apps/desktop/src/renderer/__tests__/newMakerWorktreeSend.test.ts b/apps/desktop/src/renderer/__tests__/newMakerWorktreeSend.test.ts
index 871e33d0e3..28da6b5aae 100644
--- a/apps/desktop/src/renderer/__tests__/newMakerWorktreeSend.test.ts
+++ b/apps/desktop/src/renderer/__tests__/newMakerWorktreeSend.test.ts
@@ -16,12 +16,14 @@ const sessionViewSource = readFileSync(
describe('NewMakerDraftRoute worktree send flow', () => {
it('enters a real session before creating the worktree in the background', () => {
// 2026-07-29 状态契约:生效条件 = 勾选 && baseRepo 就绪(不合格静默普通启动)。
- const worktreeBranch = source.indexOf('if (!isRemoteProjectDraft && wt.enabled && wt.baseRepo) {');
+ const worktreeBranch = source.indexOf(
+ 'if (!isRemoteProjectDraft && wt.enabled && wt.baseRepo) {',
+ );
const createSession = source.indexOf('const newSession = await createSession', worktreeBranch);
const touchUserSend = source.indexOf('sessionService.touchUserSend', createSession);
// worktree 创建期的视觉反馈走 worktreeCreationStore(由 CCAgentSessionView 底部
// workingDir chip 行订阅渲染),不再插 chat-stream SystemCard。
- const statusCard = source.indexOf("worktreeCreationStore.set(newSession.id", touchUserSend);
+ const statusCard = source.indexOf('worktreeCreationStore.set(newSession.id', touchUserSend);
const navigate = source.indexOf('navigate(`/cc-agent/$' + '{newSession.id}`', statusCard);
const worktreeCreate = source.indexOf('window.electronAPI.worktreeCreate', navigate);
@@ -57,12 +59,9 @@ describe('NewMakerDraftRoute worktree send flow', () => {
});
it('treats remote session creation as committed before the shared non-blocking handoff', () => {
- const remoteSessionId = source.indexOf('const remoteSessionId = presetSessionId');
+ const remoteSessionId = source.search(/const remoteSessionId\s*=\s*presetSessionId/);
const commitPoint = source.indexOf('remoteSessionId 到手就是**提交点**', remoteSessionId);
- const handoff = source.indexOf(
- 'commitRemoteSessionHandoff({',
- commitPoint,
- );
+ const handoff = source.indexOf('commitRemoteSessionHandoff({', commitPoint);
const pendingHandoff = source.indexOf('setPending(remoteSessionId', handoff);
expect(remoteSessionId).toBeGreaterThan(-1);
@@ -73,9 +72,7 @@ describe('NewMakerDraftRoute worktree send flow', () => {
});
it('settles an older remote cleanup obligation before creating another worktree', () => {
- const remoteBranch = source.indexOf(
- 'if (isDeviceLinkDraft && effectiveDeviceLinkDeviceId) {',
- );
+ const remoteBranch = source.indexOf('if (isDeviceLinkDraft && effectiveDeviceLinkDeviceId) {');
const recovery = source.indexOf(
'await recoverPendingRemotePrecreatedWorktrees({',
remoteBranch,
@@ -99,18 +96,14 @@ describe('NewMakerDraftRoute worktree send flow', () => {
expect(reservationGuard).toBeGreaterThan(retainedGuard);
expect(worktreeCreate).toBeGreaterThan(reservationGuard);
expect(worktreeCreate).toBeGreaterThan(retainedGuard);
- expect(source.slice(worktreeCreate, worktreeCreate + 420)).toContain(
- 'recoveryKey,',
- );
+ expect(source.slice(worktreeCreate, worktreeCreate + 420)).toContain('recoveryKey,');
expect(ledgerRegistration).toBeGreaterThan(worktreeCreate);
- expect(source.slice(ledgerRegistration, ledgerRegistration + 220)).toContain(
- 'deviceId,',
- );
+ expect(source.slice(ledgerRegistration, ledgerRegistration + 220)).toContain('deviceId,');
});
it('fences every remote create side effect by the data-owner generation', () => {
const ownerCapture = source.indexOf('const dataOwnerAtSend = getDataOwnerGeneration();');
- const currentCheck = source.indexOf('const isCurrentDataOwner = () => (', ownerCapture);
+ const currentCheck = source.indexOf('const isCurrentDataOwner = () =>', ownerCapture);
const invokeWrapper = source.indexOf('const invokeRemote = async', currentCheck);
const recoveryFence = source.indexOf('isCurrent: isCurrentDataOwner,', invokeWrapper);
const helperFence = source.indexOf('isCurrent: isCurrentDataOwner,', recoveryFence + 1);
@@ -132,17 +125,9 @@ describe('NewMakerDraftRoute worktree send flow', () => {
});
it('retries remote draft defaults after the relay or selected workstation reconnects', () => {
- const epochHook = source.indexOf(
- 'useDeviceLinkReconnectEpoch(',
- );
- const defaultsFetch = source.indexOf(
- "'maker:get-new-maker-defaults'",
- epochHook,
- );
- const effectDependencies = source.indexOf(
- 'remoteDraftRefreshEpoch,',
- defaultsFetch,
- );
+ const epochHook = source.indexOf('useDeviceLinkReconnectEpoch(');
+ const defaultsFetch = source.indexOf("'maker:get-new-maker-defaults'", epochHook);
+ const effectDependencies = source.indexOf('remoteDraftRefreshEpoch,', defaultsFetch);
const transientPreserve = source.indexOf(
'value: unsupported ? null : previous.value',
defaultsFetch,
@@ -156,7 +141,10 @@ describe('NewMakerDraftRoute worktree send flow', () => {
it('does not auto-send if the prepared session is no longer active', () => {
const worktreeCreate = source.indexOf('window.electronAPI.worktreeCreate');
- const latestSession = source.indexOf('const latestSession = await sessionService.get(newSession.id)', worktreeCreate);
+ const latestSession = source.indexOf(
+ 'const latestSession = await sessionService.get(newSession.id)',
+ worktreeCreate,
+ );
const inactiveGuard = source.indexOf("latestSession?.status !== 'active'", latestSession);
const restoreDraft = source.indexOf('restoreFirstMessageDraft();', inactiveGuard);
const sendMessage = source.indexOf('makerChatStore.sendMessage(', restoreDraft);
@@ -192,7 +180,10 @@ describe('NewMakerDraftRoute worktree send flow', () => {
'if (sessionHandoffPreparing) return false',
preparingMerge,
);
- const overlayLock = sessionViewSource.indexOf('worktreePreparing && smoothedBranchName', sendGuard);
+ const overlayLock = sessionViewSource.indexOf(
+ 'worktreePreparing && smoothedBranchName',
+ sendGuard,
+ );
expect(hookSubscription).toBeGreaterThan(-1);
expect(rawDerive).toBeGreaterThan(hookSubscription);
diff --git a/apps/desktop/src/renderer/__tests__/pinnedProjectSidebarIntegration.test.ts b/apps/desktop/src/renderer/__tests__/pinnedProjectSidebarIntegration.test.ts
index 83f1793ab4..ddf372c25d 100644
--- a/apps/desktop/src/renderer/__tests__/pinnedProjectSidebarIntegration.test.ts
+++ b/apps/desktop/src/renderer/__tests__/pinnedProjectSidebarIntegration.test.ts
@@ -23,15 +23,13 @@ describe('pinned project sidebar integration', () => {
expect(sidebarSource).toContain(
'<RailPanels\n projects={visibleRailProjectsWithVendor}',
);
- expect(sidebarSource).toContain(
- '<ProjectsSection\n unclassified={visibleUnclassified}\n projects={visibleProjectsWithVendor}',
+ expect(sidebarSource).toMatch(
+ /<ProjectsSection\s+unclassified=\{visibleUnclassified\}\s+projects=\{visibleProjectsWithVendor\}/,
);
});
it('keeps all-pinned projects available while omitting their pinned child rows', () => {
- expect(sidebarSource).toContain(
- 'const groupsWithPinnedProjects = useProjectGroups(',
- );
+ expect(sidebarSource).toContain('const groupsWithPinnedProjects = useProjectGroups(');
expect(sidebarSource).toContain(
'if (filter.projectsAsSet === null) return groupsWithPinnedProjects.projects;',
);
diff --git a/apps/desktop/src/renderer/__tests__/refreshRemoteSessionsRetry.test.ts b/apps/desktop/src/renderer/__tests__/refreshRemoteSessionsRetry.test.ts
index 2c2522fa19..fb58cd40c4 100644
--- a/apps/desktop/src/renderer/__tests__/refreshRemoteSessionsRetry.test.ts
+++ b/apps/desktop/src/renderer/__tests__/refreshRemoteSessionsRetry.test.ts
@@ -45,7 +45,44 @@ afterEach(() => {
});
function session(id: string, partial: Partial<Session> = {}): Session {
- return { id, ...partial } as Session;
+ return {
+ id,
+ userId: 'user-1',
+ title: id,
+ workingDir: null,
+ workspaceKind: 'dialogue',
+ model: 'model-1',
+ effort: 'medium',
+ permissionMode: 'default',
+ sdkSessionId: null,
+ totalTokenUsage: 0,
+ totalCostUsd: 0,
+ contextTokens: 0,
+ contextWindow: 0,
+ fastMode: false,
+ clearedAt: null,
+ pinnedAt: null,
+ userSendAt: null,
+ status: 'active',
+ agentKind: 'cc',
+ extraDirs: [],
+ createdAt: '2026-08-02T00:00:00.000Z',
+ updatedAt: '2026-08-02T00:00:00.000Z',
+ ...partial,
+ };
+}
+
+function legacyMinimalSession(id: string) {
+ return {
+ id,
+ title: id,
+ workingDir: null,
+ model: 'model-1',
+ status: 'active',
+ agentKind: 'cc',
+ createdAt: '2026-08-02T00:00:00.000Z',
+ updatedAt: '2026-08-02T00:00:00.000Z',
+ };
}
function deferred<T>() {
@@ -102,6 +139,80 @@ describe('refreshRemoteDeviceSessions retry', () => {
expect(remoteProjectsStore.getMergedRemoteSessions()).toHaveLength(0);
});
+ it('非数组响应不得冒充成功或权威空列表', async () => {
+ const d = did();
+ invoke.mockResolvedValueOnce(null);
+
+ await expect(refreshRemoteDeviceSessions(d, 'Mac B', { sleep: noSleep })).resolves.toBe(
+ 'gave-up',
+ );
+ expect(invoke).toHaveBeenCalledTimes(1);
+ expect(remoteProjectsStore.hasDevice(d)).toBe(false);
+ });
+
+ it('空数组是权威空任务列表并正常发布', async () => {
+ const d = did();
+ invoke.mockResolvedValueOnce([]);
+
+ await expect(refreshRemoteDeviceSessions(d, 'Mac B', { sleep: noSleep })).resolves.toBe('ok');
+
+ expect(remoteProjectsStore.hasDevice(d)).toBe(true);
+ expect(remoteProjectsStore.getDeviceSessions(d)).toEqual([]);
+ });
+
+ it('接受旧端最低任务列表形状,不强制要求新版附加字段', async () => {
+ const d = did();
+ invoke.mockResolvedValueOnce([legacyMinimalSession('legacy')]);
+
+ await expect(refreshRemoteDeviceSessions(d, 'Mac B', { sleep: noSleep })).resolves.toBe('ok');
+
+ expect(remoteProjectsStore.getDeviceSessions(d)).toEqual([
+ expect.objectContaining({ id: 'legacy', title: 'legacy', status: 'active' }),
+ ]);
+ });
+
+ it('数组混入非法会话时整份失败,保留旧 shard 且不部分应用', async () => {
+ const d = did();
+ remoteProjectsStore.setDeviceSessions(d, 'Mac B', [session('existing')]);
+ invoke.mockResolvedValueOnce([session('fresh'), null]);
+
+ await expect(refreshRemoteDeviceSessions(d, 'Mac B', { sleep: noSleep })).resolves.toBe(
+ 'gave-up',
+ );
+ expect(invoke).toHaveBeenCalledTimes(1);
+ expect(remoteProjectsStore.getDeviceSessions(d).map((item) => item.id)).toEqual(['existing']);
+ });
+
+ it('active 列表混入非 active 会话时按协议损坏处理', async () => {
+ const d = did();
+ remoteProjectsStore.setDeviceSessions(d, 'Mac B', [session('existing')]);
+ invoke.mockResolvedValueOnce([session('archived', { status: 'archived' })]);
+
+ await expect(refreshRemoteDeviceSessions(d, 'Mac B', { sleep: noSleep })).resolves.toBe(
+ 'gave-up',
+ );
+ expect(remoteProjectsStore.getDeviceSessions(d).map((item) => item.id)).toEqual(['existing']);
+ });
+
+ it('损坏的满窗口响应不会触发 sessions:get 补查或改写旧 shard', async () => {
+ const d = did();
+ remoteProjectsStore.setDeviceSessions(d, 'Mac B', [session('outside-window')]);
+ const malformed = [
+ ...Array.from({ length: 199 }, (_, index) => session(`recent-${index}`)),
+ null,
+ ];
+ invoke.mockResolvedValueOnce(malformed);
+
+ await expect(refreshRemoteDeviceSessions(d, 'Mac B', { sleep: noSleep })).resolves.toBe(
+ 'gave-up',
+ );
+
+ expect(invoke).toHaveBeenCalledTimes(1);
+ expect(remoteProjectsStore.getDeviceSessions(d).map((item) => item.id)).toEqual([
+ 'outside-window',
+ ]);
+ });
+
it('访问被撤销(DEVICE_LINK_ACCESS_REVOKED)→ 不重试,返回 revoked(调用方据此 handleRevoked)', async () => {
const d = did();
invoke.mockRejectedValue(new Error('[DEVICE_LINK_ACCESS_REVOKED] revoked'));
@@ -170,7 +281,7 @@ describe('refreshRemoteDeviceSessions retry', () => {
it('周期有界快照更新命中行但保留 200 条窗口外的有效会话', async () => {
const d = did();
const recent = Array.from({ length: 200 }, (_, index) =>
- session(`recent-${index}`, { title: index === 0 ? 'new' : undefined }),
+ session(`recent-${index}`, index === 0 ? { title: 'new' } : {}),
);
remoteProjectsStore.setDeviceSessions(d, 'Mac B', [
session('recent-0', { title: 'old' }),
diff --git a/apps/desktop/src/renderer/__tests__/remoteExistingProjects.test.ts b/apps/desktop/src/renderer/__tests__/remoteExistingProjects.test.ts
index 298021a422..05f5f5d631 100644
--- a/apps/desktop/src/renderer/__tests__/remoteExistingProjects.test.ts
+++ b/apps/desktop/src/renderer/__tests__/remoteExistingProjects.test.ts
@@ -120,18 +120,40 @@ describe('loadDeviceLinkExistingProjects', () => {
]);
});
- it('被控端返回 null/undefined → 空数组(不抛)', async () => {
+ it('被控端返回 null/undefined → 协议错误,不能伪装成权威空列表', async () => {
invoke.mockResolvedValue(null);
- expect(await loadDeviceLinkExistingProjects('dev-1')).toEqual([]);
+ await expect(loadDeviceLinkExistingProjects('dev-1')).rejects.toThrow(
+ 'Invalid recent workdirs response',
+ );
+ });
+
+ it.each([
+ ['缺少 path', [{ lastUsedAt: '2026-06-15T00:00:00.000Z' }]],
+ ['空 path', [{ path: '', lastUsedAt: '2026-06-15T00:00:00.000Z' }]],
+ ['lastUsedAt 不是字符串', [{ path: '/remote/app', lastUsedAt: 42 }]],
+ [
+ 'exists 不是布尔值',
+ [{ path: '/remote/app', lastUsedAt: '2026-06-15T00:00:00.000Z', exists: null }],
+ ],
+ [
+ '混入畸形元素',
+ [
+ { path: '/remote/app', lastUsedAt: '2026-06-15T00:00:00.000Z' },
+ { path: '/remote/bad', lastUsedAt: 42 },
+ ],
+ ],
+ ])('数组元素%s → 整份响应进入协议错误', async (_label, rows) => {
+ invoke.mockResolvedValue(rows);
+ await expect(loadDeviceLinkExistingProjects('dev-1')).rejects.toThrow(
+ 'Invalid recent workdirs response',
+ );
});
it('从被控端最近项目列表移除路径,不调用本机 recent-workdirs API', async () => {
invoke.mockResolvedValue({ deleted: true });
await removeDeviceLinkExistingProject('dev-1', '/remote/app');
- expect(invoke).toHaveBeenCalledWith(
- 'dev-1',
- 'local-db:recent-workdirs:remove',
- [{ path: '/remote/app' }],
- );
+ expect(invoke).toHaveBeenCalledWith('dev-1', 'local-db:recent-workdirs:remove', [
+ { path: '/remote/app' },
+ ]);
});
});
diff --git a/apps/desktop/src/renderer/__tests__/remoteModelHooksDeviceOwnership.test.tsx b/apps/desktop/src/renderer/__tests__/remoteModelHooksDeviceOwnership.test.tsx
new file mode 100644
index 0000000000..7718d31d9e
--- /dev/null
+++ b/apps/desktop/src/renderer/__tests__/remoteModelHooksDeviceOwnership.test.tsx
@@ -0,0 +1,151 @@
+// @vitest-environment jsdom
+
+import { act, render, waitFor } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import type { ProviderView } from '@cindy/model-providers';
+
+beforeEach(() => {
+ vi.resetModules();
+});
+
+function setElectronApi(value: unknown): void {
+ Object.defineProperty(window, 'electronAPI', {
+ configurable: true,
+ writable: true,
+ value,
+ });
+}
+
+function capabilities(label: string) {
+ return {
+ availableModels: [
+ {
+ id: `${label}-model`,
+ displayName: label,
+ contextWindow: 1,
+ efforts: [],
+ defaultEffort: null,
+ },
+ ],
+ hasFastMode: false,
+ effortLevels: [],
+ permissionModes: [],
+ };
+}
+
+function provider(id: string): ProviderView {
+ return {
+ id,
+ name: id,
+ source: 'builtin',
+ agents: ['claude-code'],
+ auth: { method: 'none' },
+ routing: {
+ 'claude-code': { upstream: 'https://example.invalid', authStrategy: 'none' },
+ },
+ models: { 'claude-code': [] },
+ connected: true,
+ };
+}
+
+describe('remote model hook device ownership', () => {
+ it('never renders the previous device capabilities under a newly selected device', async () => {
+ const invoke = vi.fn((deviceId: string) => {
+ if (deviceId === 'dev-a') return Promise.resolve(capabilities('Mac A'));
+ return new Promise(() => {});
+ });
+ setElectronApi({ deviceLink: { invoke } });
+ const mod = await import('@/hooks/useAgentCapabilities');
+ await mod.prefetchDeviceCapabilities('dev-a');
+
+ const frames: Array<{ deviceId: string; label: string | null; loading: boolean }> = [];
+ function Probe({ deviceId }: { deviceId: string }) {
+ const state = mod.useAgentCapabilities('codex', deviceId);
+ frames.push({
+ deviceId,
+ label: state.capabilities?.availableModels[0]?.displayName ?? null,
+ loading: state.loading,
+ });
+ return null;
+ }
+
+ const view = render(<Probe deviceId="dev-a" />);
+ await waitFor(() =>
+ expect(frames.at(-1)).toEqual({
+ deviceId: 'dev-a',
+ label: 'Mac A',
+ loading: false,
+ }),
+ );
+
+ frames.length = 0;
+ view.rerender(<Probe deviceId="dev-b" />);
+ expect(frames[0]).toEqual({ deviceId: 'dev-b', label: null, loading: true });
+ });
+
+ it('never renders the previous device providers under a newly selected device', async () => {
+ const invoke = vi.fn((deviceId: string) => {
+ if (deviceId === 'dev-a') {
+ return Promise.resolve({ providers: [provider('provider-a')] });
+ }
+ return new Promise(() => {});
+ });
+ setElectronApi({ deviceLink: { invoke } });
+ const mod = await import('@/hooks/useDeviceProviders');
+ await mod.prefetchDeviceProviders('dev-a');
+
+ const frames: Array<{ deviceId: string; providerIds: string[]; loading: boolean }> = [];
+ function Probe({ deviceId }: { deviceId: string }) {
+ const state = mod.useDeviceProviders(deviceId);
+ frames.push({
+ deviceId,
+ providerIds: state.providers.map((provider) => provider.id),
+ loading: state.loading,
+ });
+ return null;
+ }
+
+ const view = render(<Probe deviceId="dev-a" />);
+ await waitFor(() =>
+ expect(frames.at(-1)).toEqual({
+ deviceId: 'dev-a',
+ providerIds: ['provider-a'],
+ loading: false,
+ }),
+ );
+
+ frames.length = 0;
+ view.rerender(<Probe deviceId="dev-b" />);
+ expect(frames[0]).toEqual({ deviceId: 'dev-b', providerIds: [], loading: true });
+ });
+
+ it('clears a stale provider catalog when an upgraded controller reaches an old unsupported device', async () => {
+ const invoke = vi
+ .fn()
+ .mockResolvedValueOnce({ providers: [provider('stale-provider')] })
+ .mockRejectedValueOnce(
+ new Error('[DEVICE_LINK_CHANNEL_NOT_ALLOWED] channel not allowed remotely'),
+ );
+ setElectronApi({ deviceLink: { invoke } });
+ const mod = await import('@/hooks/useDeviceProviders');
+ await mod.prefetchDeviceProviders('dev-old');
+
+ const frames: Array<ReturnType<typeof mod.useDeviceProviders>> = [];
+ function Probe() {
+ const state = mod.useDeviceProviders('dev-old');
+ frames.push(state);
+ return null;
+ }
+
+ render(<Probe />);
+ await waitFor(() => expect(frames.at(-1)?.providers).toHaveLength(1));
+ await act(async () => {
+ mod.evictDeviceProviders('dev-old');
+ await mod.prefetchDeviceProviders('dev-old');
+ });
+
+ await waitFor(() => expect(frames.at(-1)?.unsupported).toBe(true));
+ expect(frames.at(-1)?.providers).toEqual([]);
+ expect(frames.at(-1)?.error).toContain('CHANNEL_NOT_ALLOWED');
+ });
+});
diff --git a/apps/desktop/src/renderer/__tests__/remoteProjectsStore.test.ts b/apps/desktop/src/renderer/__tests__/remoteProjectsStore.test.ts
index df89521f67..83d36ab6bf 100644
--- a/apps/desktop/src/renderer/__tests__/remoteProjectsStore.test.ts
+++ b/apps/desktop/src/renderer/__tests__/remoteProjectsStore.test.ts
@@ -13,7 +13,9 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import {
remoteProjectsStore,
getSessionDeviceId,
+ retryRemoteSessionBootstrap,
setRemoteReseedImpl,
+ setRemoteSessionBootstrapRetryImpl,
} from '@/features/device-link/remoteProjectsStore';
import type { Session } from '@/lib/ccAgent.types';
@@ -50,12 +52,23 @@ function mk(id: string, partial: Partial<Session> = {}): Session {
describe('remoteProjectsStore', () => {
beforeEach(() => {
setRemoteReseedImpl(null);
+ setRemoteSessionBootstrapRetryImpl(null);
remoteProjectsStore.clear();
remoteProjectsStore.__resetPendingTitlePreviewForTest();
// 钉子刻意不随 clear() 消失(见 pinnedOrigins),所以测试间必须显式清,否则会串用例。
remoteProjectsStore.__resetPinnedOriginsForTest();
});
+ it('把用户的任务重试动作交给 listing tier 注册的 bootstrap 实现', () => {
+ const retry = vi.fn();
+ setRemoteSessionBootstrapRetryImpl(retry);
+
+ retryRemoteSessionBootstrap('dev-B');
+
+ expect(retry).toHaveBeenCalledWith('dev-B');
+ expect(retry).toHaveBeenCalledTimes(1);
+ });
+
describe('origin 钉子(pinSessionOrigin)', () => {
it('远程新建会话后 origin 立刻可判定,即使权威快照还没到', () => {
remoteProjectsStore.pinSessionOrigin('dev-B', 'new-1');
@@ -251,16 +264,26 @@ describe('remoteProjectsStore', () => {
remoteProjectsStore.markDeviceDisconnected('dev-B');
remoteProjectsStore.setDeviceSessions('dev-B', 'B', [mk('s1')]);
- expect(remoteProjectsStore.getMergedRemoteSessions()[0].deviceLinkConnectionStatus).toBe('connected');
+ expect(remoteProjectsStore.getMergedRemoteSessions()[0].deviceLinkConnectionStatus).toBe(
+ 'connected',
+ );
expect(remoteProjectsStore.getDeviceIds()).toEqual(['dev-B']);
expect(remoteProjectsStore.getDeviceList()).toEqual([
{ deviceId: 'dev-B', deviceName: 'B', sessionCount: 1, connected: true },
]);
});
- it('tracks terminal bootstrap failures with stable snapshots and clears them after a successful snapshot', () => {
+ it('tracks loading/error independently from an existing shard and clears both after a successful snapshot', () => {
+ remoteProjectsStore.setDeviceSessions('dev-B', 'B', [mk('old')]);
+ remoteProjectsStore.markBootstrapLoading('dev-B');
+ expect([...remoteProjectsStore.getBootstrapLoadingDeviceIds()]).toEqual(['dev-B']);
+ expect(remoteProjectsStore.getDeviceSessions('dev-B').map((session) => session.id)).toEqual([
+ 'old',
+ ]);
+
const before = remoteProjectsStore.getBootstrapFailedDeviceIds();
remoteProjectsStore.markBootstrapFailed('dev-B');
+ expect(remoteProjectsStore.getBootstrapLoadingDeviceIds().size).toBe(0);
const failed = remoteProjectsStore.getBootstrapFailedDeviceIds();
expect(failed).not.toBe(before);
expect([...failed]).toEqual(['dev-B']);
@@ -269,17 +292,23 @@ describe('remoteProjectsStore', () => {
expect(remoteProjectsStore.getBootstrapFailedDeviceIds()).toBe(failed);
remoteProjectsStore.setDeviceSessions('dev-B', 'B', []);
+ expect(remoteProjectsStore.getBootstrapLoadingDeviceIds().size).toBe(0);
expect(remoteProjectsStore.getBootstrapFailedDeviceIds().size).toBe(0);
});
- it('removeDevice and clear discard bootstrap failure state even before a shard exists', () => {
+ it('disconnect, removeDevice and clear discard bootstrap activity even before a shard exists', () => {
+ remoteProjectsStore.markBootstrapLoading('dev-loading');
+ remoteProjectsStore.markDeviceDisconnected('dev-loading');
+ expect(remoteProjectsStore.getBootstrapLoadingDeviceIds().size).toBe(0);
+
remoteProjectsStore.markBootstrapFailed('dev-A');
remoteProjectsStore.removeDevice('dev-A');
expect(remoteProjectsStore.getBootstrapFailedDeviceIds().size).toBe(0);
- remoteProjectsStore.markBootstrapFailed('dev-A');
+ remoteProjectsStore.markBootstrapLoading('dev-A');
remoteProjectsStore.markBootstrapFailed('dev-B');
remoteProjectsStore.clear();
+ expect(remoteProjectsStore.getBootstrapLoadingDeviceIds().size).toBe(0);
expect(remoteProjectsStore.getBootstrapFailedDeviceIds().size).toBe(0);
});
@@ -316,7 +345,8 @@ describe('remoteProjectsStore', () => {
remoteProjectsStore.renameDevice('dev-B', 'New');
expect(
- remoteProjectsStore.getMergedRemoteSessions().find((x) => x.id === 's1')!.deviceLinkDeviceName,
+ remoteProjectsStore.getMergedRemoteSessions().find((x) => x.id === 's1')!
+ .deviceLinkDeviceName,
).toBe('New');
expect(seen).toEqual([['dev-B', 'New']]);
@@ -396,7 +426,9 @@ describe('remoteProjectsStore pending title preview', () => {
it('treats a user-named "[Fork] ..." session without parentSessionId as manual', () => {
// 与被控端 getOverwritableAutoTitle 同一条判据:没有 parentSessionId 就不是
// fork 占位,是用户自己起的名。
- remoteProjectsStore.setDeviceSessions('dev-B', 'B', [mk('s1', { title: '[Fork] 我自己起的名' })]);
+ remoteProjectsStore.setDeviceSessions('dev-B', 'B', [
+ mk('s1', { title: '[Fork] 我自己起的名' }),
+ ]);
remoteProjectsStore.setPendingTitlePreview('s1', '这个报错怎么修');
@@ -494,9 +526,9 @@ describe('remoteProjectsStore pending title preview', () => {
mk('s2', { title: 'New Maker' }),
]);
- expect(
- remoteProjectsStore.getMergedRemoteSessions().find((s) => s.id === 's1')?.title,
- ).toBe('New Maker');
+ expect(remoteProjectsStore.getMergedRemoteSessions().find((s) => s.id === 's1')?.title).toBe(
+ 'New Maker',
+ );
});
it('keeps overlays for sessions merged back by a partial anti-entropy window', () => {
@@ -509,9 +541,9 @@ describe('remoteProjectsStore pending title preview', () => {
// 半窗口 anti-entropy:s1 不在本次窗口内,但 mergeDeviceSessions 会把它并回来。
remoteProjectsStore.mergeDeviceSessions('dev-B', 'B', [mk('s2', { title: 'New Maker' })]);
- expect(
- remoteProjectsStore.getMergedRemoteSessions().find((s) => s.id === 's1')?.title,
- ).toBe('帮我排查登录失败');
+ expect(remoteProjectsStore.getMergedRemoteSessions().find((s) => s.id === 's1')?.title).toBe(
+ '帮我排查登录失败',
+ );
});
it('clears stale synthesized provenance once a prose preview is confirmed', () => {
diff --git a/apps/desktop/src/renderer/__tests__/remoteWorkerCreationContext.test.ts b/apps/desktop/src/renderer/__tests__/remoteWorkerCreationContext.test.ts
index ee4c9c8cb2..a2f8369162 100644
--- a/apps/desktop/src/renderer/__tests__/remoteWorkerCreationContext.test.ts
+++ b/apps/desktop/src/renderer/__tests__/remoteWorkerCreationContext.test.ts
@@ -13,9 +13,30 @@ describe('remote Orca Worker creation context', () => {
expect(popover).toContain("useAgentCapabilities('claude-code', deviceId)");
expect(popover).toContain("useAgentCapabilities('codex', deviceId)");
expect(popover).toContain('useDeviceProviders(deviceId)');
+ expect(popover).toContain(
+ 'providersUnsupported: deviceId ? remoteProviders.unsupported : false',
+ );
+ expect(popover).toContain('!remoteModelListBlocked');
expect(popover).toContain('deviceId={deviceId}');
});
+ it('blocks existing remote session sends while the model catalog is loading or failed', () => {
+ const chatInput = read('components/new-chat/ChatInput.tsx');
+
+ expect(chatInput).toContain('const remoteModelListStatus = resolveRemoteModelListStatus({');
+ expect(chatInput).toContain("remoteModelListStatus !== 'ready'");
+ expect(chatInput).toContain('if (remoteModelListBlocked) {');
+ expect(chatInput).toContain('remoteModelListBlocked ||');
+
+ const sendPreflightStart = chatInput.indexOf('// 预检(通用、provider-aware)');
+ const sendPreflightEnd = chatInput.indexOf('// 评论截图并入发送附件', sendPreflightStart);
+ expect(sendPreflightStart).toBeGreaterThan(-1);
+ expect(sendPreflightEnd).toBeGreaterThan(sendPreflightStart);
+ expect(chatInput.slice(sendPreflightStart, sendPreflightEnd)).toContain(
+ '!(deviceLinkDeviceId && remoteProviders.unsupported)',
+ );
+ });
+
it('passes the same device context through both Worker creation entry points', () => {
const sessionView = read('features/cc-agent/CCAgentSessionView.tsx');
const workerPanel = read('features/cc-agent/OrcaWorkerPanel.tsx');
@@ -30,11 +51,16 @@ describe('remote Orca Worker creation context', () => {
const selector = read('components/new-chat/ModelSelector.tsx');
// 本地会话仍只按 codex/ + hasSavedKey 准入;SSH 远程额外按订阅直连前缀禁用
- // (不可路由),两者都不得回退到 controller key 判定。
+ // (不可路由)。device-link 远程在目录未就绪或真实读取失败时禁用旧行,
+ // 只有明确判定老被控端不支持 provider:list 时才回退 capabilities flat list;
+ // 任一远程路径都不得回退到 controller key 判定。
expect(selector).toContain('if (!deviceId) {');
expect(selector).toContain('if (subscriptionDirectDisabledReason(id)) return true;');
expect(selector).toContain("return id.startsWith('codex/') && !hasSavedKey;");
- expect(selector).toContain('if (remoteProviders.error) return false;');
+ expect(selector).toContain("if (remoteModelListStatus !== 'ready') return true;");
+ expect(selector).toContain(
+ 'if (remoteProviders.error) return remoteProviders.unsupported ? false : true;',
+ );
expect(selector).toContain('const rowAgentKind = resolveVisibleModelAgentKind({');
expect(selector).toContain('providerOffersModel(provider, id, rowAgentKind)');
});
diff --git a/apps/desktop/src/renderer/__tests__/vendorAuthGateRemoteReadiness.test.ts b/apps/desktop/src/renderer/__tests__/vendorAuthGateRemoteReadiness.test.ts
index 373b6560bc..b4ae699138 100644
--- a/apps/desktop/src/renderer/__tests__/vendorAuthGateRemoteReadiness.test.ts
+++ b/apps/desktop/src/renderer/__tests__/vendorAuthGateRemoteReadiness.test.ts
@@ -14,6 +14,7 @@ import { VOICE_INPUT_ASR_PROFILES } from '../../shared/voiceInputAsrProfiles';
import {
deriveRemoteReadiness,
pickVoiceInputDialogCopy,
+ resolveRemoteProviderProbe,
sourceReadyFromProviderList,
} from '@/hooks/useVendorAuthGate';
import { readinessFromBinaryStatus } from '@/hooks/useVendorReadiness';
@@ -62,7 +63,7 @@ describe('deriveRemoteReadiness(被控端就绪推导)', () => {
).toBe('unauthenticated');
});
- it('全部判定不可用 → ready(控制端不臆断,交给被控端权威校验)', () => {
+ it('两个 channel 都明确 unsupported 的旧端兼容路径 → ready', () => {
expect(
deriveRemoteReadiness('codex', { binaryReady: null, sourceReady: null, authReady: null }),
).toBe('ready');
@@ -104,6 +105,7 @@ describe('sourceReadyFromProviderList(隧道 provider:list 响应解析)', (
name: 'P',
agents: ['codex'],
routing: { codex: {} },
+ models: { codex: [] },
connected: true,
...over,
}) as ProviderView;
@@ -122,6 +124,31 @@ describe('sourceReadyFromProviderList(隧道 provider:list 响应解析)', (
expect(sourceReadyFromProviderList(null, 'codex')).toBe(null);
expect(sourceReadyFromProviderList({}, 'codex')).toBe(null);
expect(sourceReadyFromProviderList({ providers: 'oops' }, 'codex')).toBe(null);
+ expect(sourceReadyFromProviderList({ providers: [{ id: 'broken' }] }, 'codex')).toBe(null);
+ });
+
+ it('只有结构化 channel unsupported 才进入旧端回退,真实失败与畸形响应都 fail closed', () => {
+ expect(
+ resolveRemoteProviderProbe(
+ {
+ status: 'rejected',
+ reason: new Error('[DEVICE_LINK_CHANNEL_NOT_ALLOWED] channel not allowed remotely'),
+ },
+ 'codex',
+ ),
+ ).toEqual({ status: 'unsupported', sourceReady: null });
+ expect(
+ resolveRemoteProviderProbe(
+ {
+ status: 'rejected',
+ reason: new Error('proxy policy: request not allowed remotely'),
+ },
+ 'codex',
+ ),
+ ).toEqual({ status: 'error', sourceReady: null });
+ expect(
+ resolveRemoteProviderProbe({ status: 'fulfilled', value: { providers: [null] } }, 'codex'),
+ ).toEqual({ status: 'error', sourceReady: null });
});
});
diff --git a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
index 6a705c34d3..2f2832c74a 100644
--- a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
+++ b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
@@ -92,6 +92,7 @@ import {
import { subscribeSessionLinkInsert } from '@/lib/composerActionsBus';
import {
ModelSelector,
+ resolveRemoteModelListStatus,
resolveModelSelectorAgentIdentity,
type ModelMemoryAccessors,
} from './ModelSelector';
@@ -1378,11 +1379,25 @@ export function ChatInput({
// 模型选择器 trigger 化成「连接来源」CTA、Send 禁用。useConnectedSource 仅用于
// loading 态判定;实际「有没有可发送来源」独立走 sendProviders(已过滤 SSH remote
// 排除项),两者职责分离以保留 remote guard。
- // providersLoading 期间不判,避免有缓存的老用户首帧闪 CTA / 禁用态(规则 7)。
- const { loading: providersLoading } = useConnectedSource(
+ // 本机沿用 useConnectedSource 的加载态;device-link 必须同时等待被控端 capabilities 与
+ // provider 目录,且真实读取失败时 fail closed。只有结构化 unsupported 才允许旧端回退。
+ const { loading: localProvidersLoading } = useConnectedSource(
currentModelAgentKind,
activeModel,
);
+ const remoteModelListStatus = resolveRemoteModelListStatus({
+ deviceId: deviceLinkDeviceId,
+ agentKind: currentModelAgentKind,
+ cc: ccCaps,
+ codex: codexCaps,
+ pi: piCaps,
+ providers: remoteProviders,
+ });
+ const providersLoading = deviceLinkDeviceId
+ ? remoteModelListStatus === 'loading'
+ : localProvidersLoading;
+ const remoteModelListBlocked =
+ !!deviceLinkDeviceId && remoteModelListStatus !== 'ready';
// chatEligibleSourcesForModel(不是裸 sourcesForModel):非聊天模型即便"存在于某个
// 已连接来源"也不算有可发送来源(issue #882 第 3 点,2026-07 review)——否则 Send
// 会对着一个 image/embedding 端点放行,而不是显示这里的"去连接"空态。已建会话
@@ -1395,7 +1410,14 @@ export function ChatInput({
includeDisabled: !!sessionId,
}).length > 0
: false;
- const noConnectedSource = !!currentModelAgentKind && !providersLoading && !hasConnectedSendSource;
+ const noConnectedSource =
+ !!currentModelAgentKind &&
+ !providersLoading &&
+ !remoteModelListBlocked &&
+ // 老被控端明确不支持 provider:list 时只能依据 capabilities 放行;不能把缺少
+ // provider 镜像误判成权威的「没有已连接来源」。
+ (!deviceLinkDeviceId || !remoteProviders.unsupported) &&
+ !hasConnectedSendSource;
// 会话显式选中的来源已断开(如外部删除订阅 OAuth 凭证):trigger 显示「已断开」错误态 +
// Send 禁用,不再静默回退默认来源图标(否则界面显示 XD、main 懒创建却按 DB 里的来源报
@@ -3576,6 +3598,17 @@ export function ChatInput({
// Allow send if there is text OR attachments(纯引用 / 纯评论无输入也可发送)
if (!text && !hasAttachments) return;
+ // device-link 模型清单未结算或真实读取失败时禁止发送。模型选择器会同步显示
+ // loading / error;这里兜住快捷键、语音等间接派发入口,避免旧快照继续路由。
+ if (remoteModelListBlocked) {
+ if (remoteModelListStatus === 'error') {
+ toast.error(t('newChat.modelSelector.remoteLoadFailed'));
+ } else {
+ toast.warning(t('newChat.modelSelector.remoteLoading'));
+ }
+ return;
+ }
+
// 预检:会话显式选中的来源已断开 → 发送前拦截。main 侧懒创建会从 DB 水合 providerId
// 直接 LAZY_CREATE_FAILED(renderer 的 sendProviderId=null 救不了已建会话),所以这里
// 弹窗给出明确原因 + 去设置入口,而不是让请求出去撞一个原始错误码。
@@ -3601,7 +3634,12 @@ export function ChatInput({
// currentModelAgentKind 解析不出(罕见:capabilities 未就绪)时不拦,交给下游
// 处理,不误伤。用 chatEligibleSourcesForModel 而非裸 sourcesForModel:
// 非聊天来源不该被当成"可以发"放行(issue #882 第 3 点,2026-07 review)。
- if (currentModelAgentKind) {
+ if (
+ currentModelAgentKind &&
+ // 旧被控端明确不支持 provider:list 时,控制端没有可检查的来源镜像;
+ // 与模型列表一致交给 capabilities + 被控端发送链路做兼容回退。
+ !(deviceLinkDeviceId && remoteProviders.unsupported)
+ ) {
// 已建会话按实际路由口径判(includeDisabled,与上方 hasConnectedSendSource
// 同则):运行中会话不因停用打断,最终 preflight 若按准入 rail 判会在全停时
// 弹「去连接来源」把继续发送挡死(PR #744 review 第十八轮)。草稿保持准入口径。
@@ -3725,7 +3763,11 @@ export function ChatInput({
storageKey,
t,
currentModelAgentKind,
+ deviceLinkDeviceId,
providers,
+ remoteProviders.unsupported,
+ remoteModelListBlocked,
+ remoteModelListStatus,
confirmDialog,
navigate,
],
@@ -5106,6 +5148,9 @@ export function ChatInput({
noConnectedSource ||
// 会话显式选中的来源已断开 → Send 禁用(trigger 同步显示「已断开」错误态说明原因)。
selectedSourceDisconnected ||
+ // device-link 模型目录仍在读取或真实失败 → 禁止旧快照继续发送;旧端明确
+ // unsupported 已由 remoteModelListStatus 归并为 ready,不会误伤兼容回退。
+ remoteModelListBlocked ||
// host 尚未完成切换意图登记时不能发送,否则 maker:send 可能先被旧引擎消费。
agentSwitchInFlight ||
sendDispatchInFlight ||
diff --git a/apps/desktop/src/renderer/components/new-chat/FolderPickerPopover.tsx b/apps/desktop/src/renderer/components/new-chat/FolderPickerPopover.tsx
index 1f202a8ee7..e62613537f 100644
--- a/apps/desktop/src/renderer/components/new-chat/FolderPickerPopover.tsx
+++ b/apps/desktop/src/renderer/components/new-chat/FolderPickerPopover.tsx
@@ -1,4 +1,13 @@
-import { Folder, FolderPlus, Globe, MessageCircle, X } from 'lucide-react';
+import {
+ CircleAlert,
+ Folder,
+ FolderPlus,
+ Globe,
+ Loader2,
+ MessageCircle,
+ RefreshCw,
+ X,
+} from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { cn } from '@/lib/utils';
@@ -36,8 +45,10 @@ export interface FolderPickerOption {
export interface FolderPickerDeviceScope {
deviceId: string;
deviceName: string;
- /** 正在经隧道取该设备的最近项目。 */
- loading?: boolean;
+ /** 远程项目读取状态;只有 ready + 空数组才允许渲染权威空态。 */
+ status: 'loading' | 'ready' | 'error';
+ error?: string | null;
+ retry?: () => void;
}
export type FolderPickerSelectSource = 'project' | 'recent' | 'browse' | 'dialogue';
@@ -84,8 +95,9 @@ function handleFolderPickerWheel(e: React.WheelEvent<HTMLElement>) {
const current = e.currentTarget;
const target = e.target instanceof HTMLElement ? e.target : null;
- const scrollRoot = target?.closest<HTMLElement>('[data-folder-picker-scroll="true"]')
- ?? current.querySelector<HTMLElement>('[data-folder-picker-scroll="true"]');
+ const scrollRoot =
+ target?.closest<HTMLElement>('[data-folder-picker-scroll="true"]') ??
+ current.querySelector<HTMLElement>('[data-folder-picker-scroll="true"]');
if (!scrollRoot || scrollRoot.scrollHeight <= scrollRoot.clientHeight) return;
@@ -184,7 +196,10 @@ export function FolderPickerPopover({
>
<Folder
size={20}
- className={cn('shrink-0 text-[var(--folder-item-icon)]', project.missing && 'opacity-50')}
+ className={cn(
+ 'shrink-0 text-[var(--folder-item-icon)]',
+ project.missing && 'opacity-50',
+ )}
/>
<div className="flex min-w-0 flex-1 flex-col items-start">
<span
@@ -304,10 +319,40 @@ export function FolderPickerPopover({
data-folder-picker-scroll="true"
className="pending-queue-scroll -mr-2 max-h-[224px] overflow-x-hidden overflow-y-auto overscroll-contain pr-2"
>
- {deviceScope?.loading ? (
- <div className="px-3 py-[10px] text-sm text-[var(--folder-item-path)]">
- {t('newChat.addRemoteProject.existingLoading')}
+ {deviceScope?.status === 'loading' ? (
+ <div className="flex items-center gap-2 px-3 py-[10px] text-sm text-[var(--folder-item-path)]">
+ <span className="inline-flex shrink-0 animate-spinner motion-reduce:animate-none">
+ <Loader2 size={14} />
+ </span>
+ <span>{t('newChat.addRemoteProject.existingLoading')}</span>
</div>
+ ) : deviceScope?.status === 'error' ? (
+ <>
+ <div
+ role="alert"
+ className="mx-1 flex items-start gap-2 rounded-[8px] border border-[var(--error-border)] bg-[var(--error-bg)] px-3 py-2"
+ >
+ <CircleAlert size={14} className="mt-0.5 shrink-0 text-[var(--error-fg)]" />
+ <div className="min-w-0 flex-1">
+ <p className="text-xs leading-[1.45] text-[var(--error-fg)]">
+ {t('newChat.folderPicker.remoteProjectsLoadFailed', {
+ device: deviceScope.deviceName,
+ })}
+ </p>
+ {deviceScope.retry && (
+ <button
+ type="button"
+ onClick={deviceScope.retry}
+ className="mt-1 inline-flex h-6 items-center gap-1 rounded-full px-2 text-xs font-medium text-[var(--error-fg-strong)] hover:bg-[var(--surface-hover)]"
+ >
+ <RefreshCw size={12} />
+ {t('newChat.folderPicker.retryRemoteProjects')}
+ </button>
+ )}
+ </div>
+ </div>
+ {effectiveProjectOptions.map(renderProject)}
+ </>
) : effectiveProjectOptions.length > 0 ? (
effectiveProjectOptions.map(renderProject)
) : deviceScope && onAddRemoteProject ? (
diff --git a/apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx b/apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx
index bef36fd372..24f8189b47 100644
--- a/apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx
+++ b/apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx
@@ -8,7 +8,18 @@ import {
type PointerEvent as ReactPointerEvent,
type ReactNode,
} from 'react';
-import { Check, ChevronDown, Loader2, PlugZap, Plus, Search, Unplug, Zap } from 'lucide-react';
+import {
+ Check,
+ ChevronDown,
+ CircleAlert,
+ Loader2,
+ PlugZap,
+ Plus,
+ RefreshCw,
+ Search,
+ Unplug,
+ Zap,
+} from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { cn } from '@/lib/utils';
@@ -22,12 +33,21 @@ import { hasProviderLogo, ProviderLogoMark } from '@/components/icons/ProviderLo
import { FastModeToggle } from './FastModeToggle';
import { useModelDiscoveryPending } from './useModelDiscoveryPending';
import { VendorSegmentedSwitcher } from './VendorSegmentedSwitcher';
-import { useAgentCapabilities, type AgentKind } from '@/hooks/useAgentCapabilities';
+import {
+ evictDeviceCapabilities,
+ prefetchDeviceCapabilities,
+ useAgentCapabilities,
+ type AgentKind,
+} from '@/hooks/useAgentCapabilities';
import { useApiKey } from '@/hooks/useApiKey';
import { useConnectedSource } from '@/hooks/useConnectedSource';
import { useModelPricing } from '@/hooks/useModelPricing';
import { useProviders } from '@/hooks/useProviders';
-import { useDeviceProviders } from '@/hooks/useDeviceProviders';
+import {
+ evictDeviceProviders,
+ prefetchDeviceProviders,
+ useDeviceProviders,
+} from '@/hooks/useDeviceProviders';
import {
modelPriceDiscountLabelValues,
modelPriceDetailRows,
@@ -283,6 +303,57 @@ function ModelPromotionBadge({ children }: { children: ReactNode }) {
);
}
+function RemoteModelLoadNotice({
+ status,
+ onRetry,
+ compact = false,
+}: {
+ status: 'loading' | 'error';
+ onRetry: () => void;
+ compact?: boolean;
+}) {
+ const { t } = useTranslation();
+ if (status === 'loading') {
+ return (
+ <div
+ className={cn(
+ 'flex items-center gap-1.5 text-[var(--text-tertiary)]',
+ compact ? 'px-3 pt-0.5 text-12' : 'justify-center px-3 py-6 text-13',
+ )}
+ >
+ <span className="inline-flex shrink-0 animate-spinner motion-reduce:animate-none">
+ <Loader2 size={compact ? 12 : 14} />
+ </span>
+ <span>{t('newChat.modelSelector.remoteLoading')}</span>
+ </div>
+ );
+ }
+ return (
+ <div
+ role="alert"
+ className={cn(
+ 'flex items-start gap-2 border border-[var(--error-border)] bg-[var(--error-bg)] text-[var(--error-fg)]',
+ compact ? 'mx-1 rounded-[8px] px-3 py-2' : 'mx-1 rounded-[8px] px-3 py-3',
+ )}
+ >
+ <CircleAlert size={14} className="mt-0.5 shrink-0" />
+ <div className="min-w-0 flex-1">
+ <p className={cn(compact ? 'text-11 leading-[1.45]' : 'text-xs leading-[1.45]')}>
+ {t('newChat.modelSelector.remoteLoadFailed')}
+ </p>
+ <button
+ type="button"
+ onClick={onRetry}
+ className="mt-1 inline-flex h-6 items-center gap-1 rounded-full px-2 text-xs font-medium text-[var(--error-fg-strong)] hover:bg-[var(--surface-hover)]"
+ >
+ <RefreshCw size={12} />
+ {t('newChat.modelSelector.retryRemoteModels')}
+ </button>
+ </div>
+ </div>
+ );
+}
+
export interface ModelSelectorAgentIdentity {
vendorKey: 'cc' | 'codex' | 'pi';
/**
@@ -518,6 +589,51 @@ function vendorKeyToAgentKind(v?: 'cc' | 'codex' | 'pi'): AgentKind | null {
return null;
}
+export type RemoteModelListStatus = 'idle' | 'loading' | 'ready' | 'error';
+
+interface RemoteCapabilityLoadState {
+ capabilities: unknown | null;
+ loading?: boolean;
+ error?: string | null;
+}
+
+interface RemoteProviderLoadState {
+ loading?: boolean;
+ error?: string | null;
+ unsupported?: boolean;
+}
+
+/**
+ * device-link 模型列表的权威状态:目标 agent 的 capabilities 与 provider 目录必须都结算。
+ * 只有老被控端明确不支持 provider:list 时允许 capabilities-only flat fallback。
+ */
+export function resolveRemoteModelListStatus({
+ deviceId,
+ agentKind,
+ cc,
+ codex,
+ pi,
+ providers,
+}: {
+ deviceId?: string;
+ agentKind: AgentKind | null;
+ cc: RemoteCapabilityLoadState;
+ codex: RemoteCapabilityLoadState;
+ pi: RemoteCapabilityLoadState;
+ providers: RemoteProviderLoadState;
+}): RemoteModelListStatus {
+ if (!deviceId) return 'idle';
+ const required = agentKind
+ ? [agentKind === 'claude-code' ? cc : agentKind === 'codex' ? codex : pi]
+ : [cc, codex, pi];
+ if (required.some((state) => !!state.error)) return 'error';
+ if (providers.error && !providers.unsupported) return 'error';
+ if (providers.loading || required.some((state) => state.loading || state.capabilities == null)) {
+ return 'loading';
+ }
+ return 'ready';
+}
+
export function ModelSelectorContent(props: ModelSelectorContentProps) {
const pricing = useModelPricing();
return <ModelSelectorContentView {...props} pricing={pricing} />;
@@ -610,6 +726,23 @@ function ModelSelectorContentView({
const remoteProviders = useDeviceProviders(deviceId);
const providers = deviceId ? remoteProviders.providers : localProviders.providers;
const providersLoading = deviceId ? remoteProviders.loading : localProviders.loading;
+ const remoteModelListStatus = resolveRemoteModelListStatus({
+ deviceId,
+ agentKind,
+ cc,
+ codex,
+ pi,
+ providers: remoteProviders,
+ });
+ const retryRemoteModels = useCallback(() => {
+ if (!deviceId) return;
+ evictDeviceCapabilities(deviceId);
+ evictDeviceProviders(deviceId);
+ void Promise.allSettled([
+ prefetchDeviceCapabilities(deviceId),
+ prefetchDeviceProviders(deviceId),
+ ]);
+ }, [deviceId]);
const visibilityVersion = useModelVisibilityVersion();
const [query, setQuery] = useState('');
@@ -759,7 +892,7 @@ function ModelSelectorContentView({
? (codex.capabilities?.effortLevels ?? [])
: currentAgentKind === 'pi'
? (pi.capabilities?.effortLevels ?? [])
- : [];
+ : [];
return new Map(levels.map((e) => [e.id, e.displayName]));
}, [currentAgentKind, cc.capabilities, codex.capabilities, pi.capabilities]);
// 档名多语言:i18n 词表(effortLevels.*) → 模型级 effortDisplayNames →
@@ -864,8 +997,8 @@ function ModelSelectorContentView({
if (subscriptionDirectDisabledReason(id)) return true;
return id.startsWith('codex/') && !hasSavedKey;
}
- if (remoteProviders.loading) return true;
- if (remoteProviders.error) return false;
+ if (remoteModelListStatus !== 'ready') return true;
+ if (remoteProviders.error) return remoteProviders.unsupported ? false : true;
const rowAgentKind = resolveVisibleModelAgentKind({
modelId: id,
agentKind,
@@ -914,8 +1047,7 @@ function ModelSelectorContentView({
: applyProviderOrder(sectionProviders, localProviders.providerOrder),
[deviceId, localProviders.providerOrder, sectionProviders],
);
- const suspendedActiveSourceId =
- sectionProviders === connected ? null : activeSourceId;
+ const suspendedActiveSourceId = sectionProviders === connected ? null : activeSourceId;
// biome-ignore lint/correctness/useExhaustiveDependencies: visibilityVersion 是外部可见性偏好的刷新信号,需要强制重算分段列表。
const sections = useMemo(() => {
if (!sourcesEnabled || !currentAgentKind) return null;
@@ -1075,11 +1207,7 @@ function ModelSelectorContentView({
}, [sections, flatModels]);
// ── 行选择 ───────────────────────────────────────────────────────────────
- const handleRowSelect = (
- providerId: string | null,
- id: string,
- dismiss = true,
- ) => {
+ const handleRowSelect = (providerId: string | null, id: string, dismiss = true) => {
if (interactionDisabled) return;
// 浏览目标引擎态:选中模型 = 确认切换引擎(两步式的第二步),走切换事务。
// providerId 一起带上:切换后 sessions.provider_id 直接落用户选的来源,
@@ -1194,7 +1322,14 @@ function ModelSelectorContentView({
editingProviderId ??
resolveCurrentSourceId(providers, currentProviderId, editingModel.id, currentAgentKind);
return providerId ? providers.find((provider) => provider.id === providerId) : undefined;
- }, [editingModel, currentAgentKind, editingProviderId, providers, currentProviderId, resolveCurrentSourceId]);
+ }, [
+ editingModel,
+ currentAgentKind,
+ editingProviderId,
+ providers,
+ currentProviderId,
+ resolveCurrentSourceId,
+ ]);
const editingPricePresentation = editingModel
? pricePresentationOf(editingProvider?.id ?? editingProviderId, editingModel.id)
: null;
@@ -1606,6 +1741,13 @@ function ModelSelectorContentView({
if (emptyState) return emptyState;
const hasAnyModel = sections ? sections.length > 0 : (flatModels?.length ?? 0) > 0;
+ const trimmedQuery = query.trim();
+ const remoteStatusInList =
+ deviceId && (remoteModelListStatus === 'loading' || remoteModelListStatus === 'error')
+ ? remoteModelListStatus
+ : null;
+ const showRemoteStatusFooter =
+ remoteStatusInList !== null && (hasAnyModel || trimmedQuery.length > 0);
// ── 主菜单:固定 320 宽(field 形态改绑 trigger 宽度,见 fluidWidth),选项浮层
// portal 到 body,hover 时主菜单完全不重排 ─────
@@ -1727,9 +1869,15 @@ function ModelSelectorContentView({
{!hasAnyModel ? (
// 发现还在途、且用户没在搜索时不摆「无结果」:那句话和下方的「正在获取」自相矛盾,
// 而用户看到「没有模型」就会走。搜索无命中是本地过滤的确定结论,照常显示。
- discoveringModels && query.trim().length === 0 ? null : (
+ remoteStatusInList && trimmedQuery.length === 0 ? (
+ <RemoteModelLoadNotice status={remoteStatusInList} onRetry={retryRemoteModels} />
+ ) : discoveringModels && trimmedQuery.length === 0 ? null : (
<div className="px-3 py-6 text-center text-13 text-[var(--text-tertiary)]">
- {t('newChat.modelSelector.search.noResults')}
+ {t(
+ deviceId && remoteModelListStatus === 'ready' && trimmedQuery.length === 0
+ ? 'newChat.modelSelector.remoteEmpty'
+ : 'newChat.modelSelector.search.noResults',
+ )}
</div>
)
) : sections ? (
@@ -1737,10 +1885,12 @@ function ModelSelectorContentView({
sections
.filter((sec) => sec.models.length > 0)
.map((sec, index) => (
- <div key={sec.provider.id} role="group" aria-label={providerDisplayName(sec.provider, t)}>
- {index > 0 && (
- <div className="mx-1 my-1 h-px bg-[var(--model-dropdown-border)]" />
- )}
+ <div
+ key={sec.provider.id}
+ role="group"
+ aria-label={providerDisplayName(sec.provider, t)}
+ >
+ {index > 0 && <div className="mx-1 my-1 h-px bg-[var(--model-dropdown-border)]" />}
<div className="truncate px-3 pb-0.5 pt-1 text-11 font-medium text-[var(--text-tertiary)]">
{providerDisplayName(sec.provider, t)}
</div>
@@ -1754,6 +1904,10 @@ function ModelSelectorContentView({
)}
</div>
+ {showRemoteStatusFooter && remoteStatusInList && (
+ <RemoteModelLoadNotice status={remoteStatusInList} onRetry={retryRemoteModels} compact />
+ )}
+
{/* 发现在途提示 —— 追加在列表下方,不接管列表(见 discoveringModels 注释)。
spinner 挂 HTML wrapper + animate-spinner(DESIGN.md §14.4 / 工程规范 §7)。 */}
{discoveringModels && (
@@ -1920,6 +2074,16 @@ export function ModelSelector({
const localProviders = useProviders();
const remoteProviders = useDeviceProviders(deviceId);
const providers = deviceId ? remoteProviders.providers : localProviders.providers;
+ const remoteModelListStatus = resolveRemoteModelListStatus({
+ deviceId,
+ agentKind,
+ cc,
+ codex,
+ pi,
+ providers: remoteProviders,
+ });
+ const remoteModelLoading = !!deviceId && remoteModelListStatus === 'loading';
+ const remoteModelLoadFailed = !!deviceId && remoteModelListStatus === 'error';
const visibleModels = useMemo(
() =>
selectVisibleModels({
@@ -1954,6 +2118,8 @@ export function ModelSelector({
const displayLabel = fallbackOption?.active
? fallbackOption.label
: (currentModel?.displayName ??
+ (remoteModelLoading ? t('newChat.modelSelector.remoteLoading') : null) ??
+ (remoteModelLoadFailed ? t('newChat.modelSelector.remoteLoadFailedShort') : null) ??
(unknownLabel !== '' ? unknownLabel : null) ??
t('newChat.modelSelector.trigger.placeholder'));
const agentName =
@@ -1968,9 +2134,19 @@ export function ModelSelector({
agentName && agentIdentity?.state === 'pending'
? t('newChat.modelSelector.trigger.agent.pending', { agent: agentName })
: agentName;
- const displayIdentityLabel = agentIdentityLabel
+ const baseDisplayIdentityLabel = agentIdentityLabel
? `${agentIdentityLabel} · ${displayLabel}`
: displayLabel;
+ const remoteStatusLabel = currentModel
+ ? remoteModelLoading
+ ? t('newChat.modelSelector.remoteLoading')
+ : remoteModelLoadFailed
+ ? t('newChat.modelSelector.remoteLoadFailedShort')
+ : null
+ : null;
+ const displayIdentityLabel = remoteStatusLabel
+ ? `${baseDisplayIdentityLabel} · ${remoteStatusLabel}`
+ : baseDisplayIdentityLabel;
const efforts = currentModel?.efforts ?? [];
const currentAgentKind: AgentKind | null = useMemo(() => {
@@ -2007,7 +2183,12 @@ export function ModelSelector({
const activeSourceId = useMemo<string | null>(
() =>
currentAgentKind
- ? (actualRoute ? actualSourceIdForModel : effectiveSourceIdForModel)(providers, currentProviderId, modelId, currentAgentKind)
+ ? (actualRoute ? actualSourceIdForModel : effectiveSourceIdForModel)(
+ providers,
+ currentProviderId,
+ modelId,
+ currentAgentKind,
+ )
: null,
[providers, currentAgentKind, currentProviderId, modelId, actualRoute],
);
@@ -2234,6 +2415,14 @@ export function ModelSelector({
</>
) : (
<>
+ {!currentModel && remoteModelLoading && (
+ <span className="inline-flex shrink-0 animate-spinner text-[var(--text-tertiary)] motion-reduce:animate-none">
+ <Loader2 size={dense ? 12 : 13} />
+ </span>
+ )}
+ {!currentModel && remoteModelLoadFailed && (
+ <CircleAlert size={dense ? 12 : 13} className="shrink-0 text-[var(--error-fg)]" />
+ )}
{/* 图标统一规则:模型条目 icon(AI Gateway / 目录设定)优先,缺省回落
当前真正路由的来源标(activeSourceId)——客户端不按 model id 猜厂牌。 */}
{activeSourceId && (
@@ -2319,6 +2508,17 @@ export function ModelSelector({
aria-label={t('newChat.modelSelector.meta.fastBadge')}
/>
)}
+ {currentModel && remoteModelLoading && (
+ <span className="ml-0.5 inline-flex shrink-0 animate-spinner text-[var(--text-tertiary)] motion-reduce:animate-none">
+ <Loader2 size={dense ? 11 : 12} />
+ </span>
+ )}
+ {currentModel && remoteModelLoadFailed && (
+ <CircleAlert
+ size={dense ? 11 : 12}
+ className="ml-0.5 shrink-0 text-[var(--error-fg)]"
+ />
+ )}
</>
)}
<ChevronDown
diff --git a/apps/desktop/src/renderer/components/new-chat/remoteExistingProjects.ts b/apps/desktop/src/renderer/components/new-chat/remoteExistingProjects.ts
index 6dcd0338fc..66be6b6cd9 100644
--- a/apps/desktop/src/renderer/components/new-chat/remoteExistingProjects.ts
+++ b/apps/desktop/src/renderer/components/new-chat/remoteExistingProjects.ts
@@ -46,6 +46,17 @@ interface RecentWorkdirRow {
exists?: boolean;
}
+function isRecentWorkdirRow(value: unknown): value is RecentWorkdirRow {
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return false;
+ const row = value as Record<string, unknown>;
+ return (
+ typeof row.path === 'string' &&
+ row.path.length > 0 &&
+ typeof row.lastUsedAt === 'string' &&
+ (row.exists === undefined || typeof row.exists === 'boolean')
+ );
+}
+
/** device-link:被控端 recent_workdirs → 已有项目列表(保序,handler 已按 lastUsedAt desc 排好)。 */
export function recentWorkdirsToProjects(
rows: readonly RecentWorkdirRow[],
@@ -78,12 +89,17 @@ export function sshExistingProjects(
export async function loadDeviceLinkExistingProjects(
deviceId: string,
): Promise<ExistingRemoteProject[]> {
- const rows = (await window.electronAPI.deviceLink.invoke(
+ const rows: unknown = await window.electronAPI.deviceLink.invoke(
deviceId,
'local-db:recent-workdirs:list',
[],
- )) as RecentWorkdirRow[] | null | undefined;
- return recentWorkdirsToProjects(rows ?? []);
+ );
+ // 只有明确返回数组才是权威结果;null / undefined 是协议或连接异常,不能伪装成
+ // 「对方确实没有项目」的空列表。数组元素也必须完整符合协议,否则整份响应失败。
+ if (!Array.isArray(rows) || !rows.every(isRecentWorkdirRow)) {
+ throw new Error('Invalid recent workdirs response');
+ }
+ return recentWorkdirsToProjects(rows);
}
/** device-link:从被控端最近项目列表移除一条,不删除会话或磁盘目录。 */
@@ -91,9 +107,7 @@ export async function removeDeviceLinkExistingProject(
deviceId: string,
path: string,
): Promise<void> {
- await window.electronAPI.deviceLink.invoke(
- deviceId,
- 'local-db:recent-workdirs:remove',
- [{ path }],
- );
+ await window.electronAPI.deviceLink.invoke(deviceId, 'local-db:recent-workdirs:remove', [
+ { path },
+ ]);
}
diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx
index a69c52840b..f09c859b96 100644
--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx
@@ -16,11 +16,32 @@
* F-PJ-1~7:分组数据来自 useProjectGroups + useCollapsedProjects。
*/
-import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react';
+import {
+ useCallback,
+ useEffect,
+ useLayoutEffect,
+ useMemo,
+ useRef,
+ useState,
+ useSyncExternalStore,
+} from 'react';
import type { ReactNode } from 'react';
import type { SchedulerEvent } from '@cindy/maker-scheduler';
import { createPortal } from 'react-dom';
-import { Archive, ChevronRight, CirclePlus, Folder, Plug, SquarePen, Timer, Trash2, X } from 'lucide-react';
+import {
+ Archive,
+ ChevronRight,
+ CircleAlert,
+ CirclePlus,
+ Folder,
+ Loader2,
+ Plug,
+ RefreshCw,
+ SquarePen,
+ Timer,
+ Trash2,
+ X,
+} from 'lucide-react';
import { useNavigate, useMatch } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { projectDraftSessionTitle } from '@cindy/maker-shared/session-title';
@@ -33,15 +54,15 @@ import { useAppShortcut } from '@/hooks/useAppShortcut';
import { useModifierHold } from '@/hooks/useModifierHold';
import { isSecondaryWindow } from '@/lib/secondaryWindow';
import { getAppShortcutCombos, getAppShortcutPlatform } from '@/lib/appShortcutStore';
-import {
- formatAppShortcutCombo,
- SWITCH_SESSION_SHORTCUT_IDS,
-} from '../../../shared/appShortcuts';
+import { formatAppShortcutCombo, SWITCH_SESSION_SHORTCUT_IDS } from '../../../shared/appShortcuts';
import { setSessionOrdinalBadges } from './sidebar/sessionOrdinalBadges';
import { useSidebarCollapsedState } from '../feature-context';
import { stripTrailingPathSeparators } from '../../../shared/pathText';
import { useRefreshWorktrees } from '@/contexts/WorktreeContext';
-import { SessionAttentionUrgencyProvider, useSessionAttentionUrgencySet } from './contexts/SessionAttentionUrgencyContext';
+import {
+ SessionAttentionUrgencyProvider,
+ useSessionAttentionUrgencySet,
+} from './contexts/SessionAttentionUrgencyContext';
import { ConfirmDialog } from '@/components/ui/confirm-dialog';
import { useConfirmDialog } from '@/components/ui/confirm-dialog-provider';
import {
@@ -110,10 +131,7 @@ import {
import { sessionActivityMs } from './lib/dateSessionGrouping';
import { sortProjectsForSidebar, sortSessionsForSidebar } from './lib/sidebarProjectSorting';
import { isOrcaWorkerSession, resolveSessionRoute } from '@/lib/orcaSessionIdentity';
-import {
- PinnedSection,
- type PinnedSidebarEntry,
-} from './sidebar/sections/PinnedSection';
+import { PinnedSection, type PinnedSidebarEntry } from './sidebar/sections/PinnedSection';
import { ProjectNode as ProjectNodeView } from './sidebar/sections/ProjectNode';
import {
DialogueSection,
@@ -133,7 +151,10 @@ import type {
AutomationScheduleSessionInfo,
AutomationSessionGroup,
} from './lib/automationSidebarGrouping';
-import { getSessionDeviceId } from '@/features/device-link/remoteProjectsStore';
+import {
+ getSessionDeviceId,
+ retryRemoteSessionBootstrap,
+} from '@/features/device-link/remoteProjectsStore';
import {
useRemoteSessionActivity,
useRemoteSessionActivityRevision,
@@ -165,10 +186,7 @@ import {
import { getSessionListCollapseView } from './lib/sessionListCollapse';
import { hasSessionSelectionModifier, type SessionClickModifiers } from './sidebar/SessionItem';
import type { SessionMoveTarget } from './sidebar/sessionMoveTarget';
-import {
- normalizeManualPinnedOrder,
- mergeVisibleReorder,
-} from './hooks/helpers/sidebarFilterCore';
+import { normalizeManualPinnedOrder, mergeVisibleReorder } from './hooks/helpers/sidebarFilterCore';
import {
activePinnedSidebarEntryIds,
pinnedProjectEntryId,
@@ -188,6 +206,7 @@ import {
selectVisibleSessions,
setSelectedMachineIdTransient,
MACHINE_ALL,
+ MACHINE_LOCAL,
} from '@/features/device-link/selectedMachineStore';
import {
isDeviceLinkWriteBlocked,
@@ -195,9 +214,15 @@ import {
} from './lib/remoteSessionWriteGuard';
import {
useEffectiveSelectedMachineId,
+ useRemoteSessionBootstrapFailures,
useRemoteSessionBootstrapLoading,
+ useRemoteSessionBootstrapLoadingDevices,
useSelectedMachineConnecting,
} from '@/features/device-link/useMachineSwitcher';
+import {
+ retryDeviceLinkDeviceList,
+ useDeviceLinkDeviceListRequestState,
+} from '@/features/device-link/useDeviceLinkDeviceList';
import {
useDeleteScheduleWithSessions,
type DeletedScheduleGeneratedSessionResult,
@@ -235,6 +260,81 @@ const DAY_MS = 24 * 60 * 60 * 1000;
type BulkSessionAction = 'archive' | 'delete';
+function RemoteSidebarLoadNotice({
+ kind,
+ status,
+ deviceLabel,
+ partial,
+ onRetry,
+}: {
+ kind: 'tasks' | 'devices';
+ status: 'loading' | 'error';
+ deviceLabel?: string;
+ partial: boolean;
+ onRetry?: () => void;
+}) {
+ const { t } = useTranslation();
+ const isError = status === 'error';
+ const messageKey =
+ kind === 'tasks'
+ ? status === 'loading'
+ ? 'ccAgent.sidebar.machineSwitcher.tasksLoading'
+ : partial
+ ? 'ccAgent.sidebar.machineSwitcher.tasksPartiallyFailed'
+ : 'ccAgent.sidebar.machineSwitcher.tasksLoadFailed'
+ : status === 'loading'
+ ? 'ccAgent.sidebar.machineSwitcher.devicesLoading'
+ : partial
+ ? 'ccAgent.sidebar.machineSwitcher.devicesPartiallyFailed'
+ : 'ccAgent.sidebar.machineSwitcher.devicesLoadFailed';
+ return (
+ <div
+ role={isError ? 'alert' : 'status'}
+ className={cn(
+ 'border',
+ isError
+ ? 'border-[var(--error-border)] bg-[var(--error-bg)] text-[var(--error-fg)]'
+ : 'border-[var(--border-default)] bg-[var(--surface-chip)] text-[var(--text-secondary)]',
+ partial
+ ? 'mx-3 flex items-start gap-2 rounded-[8px] px-3 py-2'
+ : 'mx-3 flex flex-col items-center gap-3 rounded-[12px] px-4 py-8 text-center',
+ )}
+ >
+ {isError ? (
+ <CircleAlert size={partial ? 14 : 20} className="shrink-0" />
+ ) : (
+ <span className="inline-flex shrink-0 animate-spinner motion-reduce:animate-none">
+ <Loader2 size={partial ? 14 : 20} />
+ </span>
+ )}
+ <div className={cn('min-w-0', partial && 'flex-1')}>
+ <p className={cn(partial ? 'text-11 leading-[1.45]' : 'text-xs leading-relaxed')}>
+ {t(messageKey, { device: deviceLabel })}
+ </p>
+ </div>
+ {isError && onRetry && (
+ <button
+ type="button"
+ onClick={onRetry}
+ className={cn(
+ 'inline-flex shrink-0 items-center gap-1 rounded-full font-medium',
+ 'text-[var(--error-fg-strong)] transition-colors hover:bg-[var(--surface-hover)]',
+ 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring-soft)]',
+ partial ? 'h-6 px-2 text-11' : 'h-7 px-3 text-xs',
+ )}
+ >
+ <RefreshCw size={12} />
+ {t(
+ kind === 'tasks'
+ ? 'ccAgent.sidebar.machineSwitcher.retryTasks'
+ : 'ccAgent.sidebar.machineSwitcher.retryDevices',
+ )}
+ </button>
+ )}
+ </div>
+ );
+}
+
function sameStringSet(a: ReadonlySet<string>, b: ReadonlySet<string>): boolean {
if (a.size !== b.size) return false;
for (const value of a) {
@@ -438,122 +538,122 @@ export function CCAgentSidebarUpper() {
// 路过几行热态就丢了,体感退回"每行都要重新等 500ms"(session-git-pr-context)。
<Tooltip.Provider skipDelayDuration={1500}>
<SessionAttentionUrgencyProvider urgentSessionIds={unreadFailedScheduleSessionIds}>
- <div className="relative flex flex-1 flex-col overflow-hidden">
- {/* Expanded — fade out when collapsed.
+ <div className="relative flex flex-1 flex-col overflow-hidden">
+ {/* Expanded — fade out when collapsed.
min-w-0 让内层跟着外层 aside 的实际宽度走,配合 SessionItem 里的
`min-w-0 flex-1 truncate` 才能正确截断。原来写死 min-w-[260px] 是
为了避免 collapse 动画期间 text reflow,但当用户把侧边栏拖到
260 以下时,这个固定宽会让内容超出可视区被 overflow-hidden 砍掉,
表现为 SessionItem 文字被右侧裁切。 */}
- <div
- className={cn(
- 'absolute inset-0 min-w-0 flex flex-col overflow-hidden',
- 'transition-opacity duration-200 ease-in-out',
- isCollapsed ? 'opacity-0 pointer-events-none' : 'opacity-100',
- )}
- >
- {/* SSH remote 会话不再被排除:WorkdirBrowseSidebar 已支持 remoteHostId
+ <div
+ className={cn(
+ 'absolute inset-0 min-w-0 flex flex-col overflow-hidden',
+ 'transition-opacity duration-200 ease-in-out',
+ isCollapsed ? 'opacity-0 pointer-events-none' : 'opacity-100',
+ )}
+ >
+ {/* SSH remote 会话不再被排除:WorkdirBrowseSidebar 已支持 remoteHostId
(P1 解禁),旧门控留着会让 doc 模式对 SSH 会话退回项目列表、无
远端文件树入口。 */}
- {filesSession && filesSession.workingDir ? (
- <WorkdirBrowseSidebar
- sessionId={filesSession.id}
- workdir={filesSession.workingDir}
- remoteHostId={filesSession.remoteHostId ?? null}
- deviceId={getSessionDeviceId(filesSession.id) ?? null}
- displayName={basenameOfPath(filesSession.workingDir)}
- projectKey={filesProjectKey}
- switchProjects={docModeSwitchProjects}
- />
- ) : null}
- {/* ExpandedView 在 doc 模式下也保持挂载(display:none):折叠 rail 的
+ {filesSession && filesSession.workingDir ? (
+ <WorkdirBrowseSidebar
+ sessionId={filesSession.id}
+ workdir={filesSession.workingDir}
+ remoteHostId={filesSession.remoteHostId ?? null}
+ deviceId={getSessionDeviceId(filesSession.id) ?? null}
+ displayName={basenameOfPath(filesSession.workingDir)}
+ projectKey={filesProjectKey}
+ switchProjects={docModeSwitchProjects}
+ />
+ ) : null}
+ {/* ExpandedView 在 doc 模式下也保持挂载(display:none):折叠 rail 的
项目/对话面板(RailPanels)由它渲染且是唯一挂载点,doc 模式卸载会让
files 路由 + 折叠时 rail 入口变成永远弹不出面板的死按钮(codex
review)。面板经 portal 渲染到 body,不受隐藏 wrapper 影响;files
路由下 activeSessionId 为 undefined,ExpandedView 的路由驱动
effects 全部自然停摆,不与 WorkdirBrowseSidebar 抢行为。 */}
+ <div
+ className={cn(
+ 'flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden',
+ filesSession && filesSession.workingDir && 'hidden',
+ )}
+ aria-hidden={filesSession && filesSession.workingDir ? true : undefined}
+ >
+ <ExpandedView
+ sessionsHook={sessionsHook}
+ navigate={navigate}
+ activeSessionId={activeSessionId}
+ // 兜底直接用路由参数而非 filesSession?.id:filesSession 只从本地
+ // 会话表解析,device-link 远程会话的文件视图(WorkdirBrowseRoute
+ // 按远程镜像解析)会解析不到,面板豁免/高亮与重定向判定就会丢
+ // (codex review)。id 相等性语义不需要完整 Session 对象。
+ viewedSessionId={activeSessionId ?? filesSessionId}
+ filter={filter}
+ projectAliases={projectAliases}
+ scheduleSessionIndex={scheduleSessionIndex}
+ />
+ </div>
+ </div>
+
+ {/* Collapsed — fade in when collapsed */}
<div
className={cn(
- 'flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden',
- filesSession && filesSession.workingDir && 'hidden',
+ 'absolute inset-0 flex flex-col overflow-hidden',
+ 'transition-opacity duration-200 ease-in-out',
+ isCollapsed ? 'opacity-100' : 'opacity-0 pointer-events-none',
)}
- aria-hidden={filesSession && filesSession.workingDir ? true : undefined}
>
- <ExpandedView
- sessionsHook={sessionsHook}
+ <CollapsedView
navigate={navigate}
+ onAutomationsContextMenu={handleAutomationsContextMenu}
+ allSearchProjects={searchProjectGroups.projects}
+ sessions={sessionsWithRemote}
activeSessionId={activeSessionId}
- // 兜底直接用路由参数而非 filesSession?.id:filesSession 只从本地
- // 会话表解析,device-link 远程会话的文件视图(WorkdirBrowseRoute
- // 按远程镜像解析)会解析不到,面板豁免/高亮与重定向判定就会丢
- // (codex review)。id 相等性语义不需要完整 Session 对象。
- viewedSessionId={activeSessionId ?? filesSessionId}
- filter={filter}
- projectAliases={projectAliases}
- scheduleSessionIndex={scheduleSessionIndex}
+ notifications={railNotifications}
+ manualPinnedOrder={filter.manualPinnedOrder}
+ onReorderPinned={handleRailPinnedReorder}
/>
</div>
- </div>
-
- {/* Collapsed — fade in when collapsed */}
- <div
- className={cn(
- 'absolute inset-0 flex flex-col overflow-hidden',
- 'transition-opacity duration-200 ease-in-out',
- isCollapsed ? 'opacity-100' : 'opacity-0 pointer-events-none',
- )}
- >
- <CollapsedView
- navigate={navigate}
- onAutomationsContextMenu={handleAutomationsContextMenu}
- allSearchProjects={searchProjectGroups.projects}
- sessions={sessionsWithRemote}
- activeSessionId={activeSessionId}
- notifications={railNotifications}
- manualPinnedOrder={filter.manualPinnedOrder}
- onReorderPinned={handleRailPinnedReorder}
- />
- </div>
- {/* Automations 按钮右键菜单 —— 折叠/展开两份按钮共用此渲染。trigger 跟着 click 坐标定位。 */}
- <DropdownMenu
- open={automationsMenuPos !== null}
- onOpenChange={(open) => {
- if (!open) setAutomationsMenuPos(null);
- }}
- >
- <DropdownMenuTrigger asChild>
- <span
- aria-hidden
- style={{
- position: 'fixed',
- left: automationsMenuPos?.x ?? 0,
- top: automationsMenuPos?.y ?? 0,
- width: 0,
- height: 0,
- pointerEvents: 'none',
- }}
- />
- </DropdownMenuTrigger>
- <DropdownMenuContent
- align="start"
- sideOffset={2}
- className={cn(
- 'min-w-[180px] rounded-xl p-1 overflow-hidden',
- 'bg-[var(--cmd-palette-bg)]',
- 'border border-[var(--cmd-palette-border)]',
- 'shadow-[var(--shadow-menu)]',
- )}
+ {/* Automations 按钮右键菜单 —— 折叠/展开两份按钮共用此渲染。trigger 跟着 click 坐标定位。 */}
+ <DropdownMenu
+ open={automationsMenuPos !== null}
+ onOpenChange={(open) => {
+ if (!open) setAutomationsMenuPos(null);
+ }}
>
- <DropdownMenuItem
- onSelect={() => void handleMarkAllAutomationsRead()}
- className="cursor-pointer text-sm text-[var(--msg-assistant-text)] hover:bg-[var(--cmd-palette-item-hover)]"
+ <DropdownMenuTrigger asChild>
+ <span
+ aria-hidden
+ style={{
+ position: 'fixed',
+ left: automationsMenuPos?.x ?? 0,
+ top: automationsMenuPos?.y ?? 0,
+ width: 0,
+ height: 0,
+ pointerEvents: 'none',
+ }}
+ />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent
+ align="start"
+ sideOffset={2}
+ className={cn(
+ 'min-w-[180px] rounded-xl p-1 overflow-hidden',
+ 'bg-[var(--cmd-palette-bg)]',
+ 'border border-[var(--cmd-palette-border)]',
+ 'shadow-[var(--shadow-menu)]',
+ )}
>
- {t('ccAgent.layout.markAllAsRead')}
- </DropdownMenuItem>
- </DropdownMenuContent>
- </DropdownMenu>
- </div>
+ <DropdownMenuItem
+ onSelect={() => void handleMarkAllAutomationsRead()}
+ className="cursor-pointer text-sm text-[var(--msg-assistant-text)] hover:bg-[var(--cmd-palette-item-hover)]"
+ >
+ {t('ccAgent.layout.markAllAsRead')}
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
</SessionAttentionUrgencyProvider>
</Tooltip.Provider>
);
@@ -607,7 +707,7 @@ function ExpandedView({
projectAliases,
scheduleSessionIndex,
}: ExpandedProps) {
- const { t } = useTranslation();
+ const { t, i18n } = useTranslation();
const { sessions, refreshSessions, patchLocal, effectiveIncludeArchived } = sessionsHook;
const refreshWorktrees = useRefreshWorktrees();
const projectPickerOptions = useProjectPickerOptions();
@@ -701,11 +801,8 @@ function ExpandedView({
const event = raw as SchedulerEvent;
if (done) return;
// 全局事件不含 scheduleId,提前过滤。
- if (
- event.type === 'all-read' ||
- event.type === 'ready' ||
- event.type === 'runtime-state'
- ) return;
+ if (event.type === 'all-read' || event.type === 'ready' || event.type === 'runtime-state')
+ return;
if (event.scheduleId !== scheduleId) return;
if (event.type === 'fired') {
// 捕获本次 run 的 runId,并释放 busy guard(run 已 fire,允许用户再次点击)
@@ -797,38 +894,41 @@ function ExpandedView({
// 是 `[]` 依赖的稳定回调,直接闭包 t 会钉住首次渲染的语言。
const unnamedLabelRef = useRef('');
unnamedLabelRef.current = t('ccAgent.common.unnamedSession');
- const fireSessionNotification = useCallback((sessionId: string, kind: 'done' | 'error' | 'needs-reply') => {
- // 灵动岛启用时,完成提示由灵动岛承载,不再走系统 toast,避免同一事件双重打扰;
- // 灵动岛未启用(或平台不支持)时,继续用系统通知。飞书是独立外发通道,不受影响。
- const islandActive = isAgentIslandSupported() && getAgentIslandEnabled();
- const desktopEnabled = getNotificationsEnabled() && !islandActive;
- const feishuEnabled = getFeishuNotificationsEnabled();
- // 失焦才推 —— 见上注释。
- if (typeof document !== 'undefined' && document.hasFocus()) return;
- const session = sessionsRef.current.find((s) => s.id === sessionId);
- // Orca worker 自身状态翻转不发独立通知 —— 等 lead 接到 worker_report 处理完
- // 再以 lead 名义统一推一条,避免同一事件双重打扰。语义上用户应回到 lead 主对话
- // 查看,而非跳到 worker 实现细节;与 effectiveRunningSessionIds 的角色聚合口径一致。
- if (session && isOrcaWorkerSession(session)) return;
- void window.electronAPI.notificationMarkSessionAttention(sessionId);
- // 哨兵过投影:toast / 飞书 / 手机推送里都不能出现内部哨兵 "New Maker"。
- // (手机推送用的是**桌面侧**语言 —— 标题在 wire payload 里是字面量,让手机按自己
- // locale 投影要改协议,超出本 PR 范围;但无论如何都比露出哨兵好。)
- const title = projectDraftSessionTitle(session?.title, unnamedLabelRef.current);
- // mobile 通道恒开:桌面侧不设第二个开关,是否收到由手机端注册/注销推送 token
- // 决定;发送侧防打扰(远程正在看该会话 / 去重 / relay 能力)在 main 收口。
- // 因此桌面/飞书都关时也要 invoke(不再提前 return)。
- void window.electronAPI.notificationShowSessionEvent({
- sessionId,
- title,
- kind,
- channels: {
- desktop: desktopEnabled,
- feishu: feishuEnabled,
- mobile: true,
- },
- });
- }, []);
+ const fireSessionNotification = useCallback(
+ (sessionId: string, kind: 'done' | 'error' | 'needs-reply') => {
+ // 灵动岛启用时,完成提示由灵动岛承载,不再走系统 toast,避免同一事件双重打扰;
+ // 灵动岛未启用(或平台不支持)时,继续用系统通知。飞书是独立外发通道,不受影响。
+ const islandActive = isAgentIslandSupported() && getAgentIslandEnabled();
+ const desktopEnabled = getNotificationsEnabled() && !islandActive;
+ const feishuEnabled = getFeishuNotificationsEnabled();
+ // 失焦才推 —— 见上注释。
+ if (typeof document !== 'undefined' && document.hasFocus()) return;
+ const session = sessionsRef.current.find((s) => s.id === sessionId);
+ // Orca worker 自身状态翻转不发独立通知 —— 等 lead 接到 worker_report 处理完
+ // 再以 lead 名义统一推一条,避免同一事件双重打扰。语义上用户应回到 lead 主对话
+ // 查看,而非跳到 worker 实现细节;与 effectiveRunningSessionIds 的角色聚合口径一致。
+ if (session && isOrcaWorkerSession(session)) return;
+ void window.electronAPI.notificationMarkSessionAttention(sessionId);
+ // 哨兵过投影:toast / 飞书 / 手机推送里都不能出现内部哨兵 "New Maker"。
+ // (手机推送用的是**桌面侧**语言 —— 标题在 wire payload 里是字面量,让手机按自己
+ // locale 投影要改协议,超出本 PR 范围;但无论如何都比露出哨兵好。)
+ const title = projectDraftSessionTitle(session?.title, unnamedLabelRef.current);
+ // mobile 通道恒开:桌面侧不设第二个开关,是否收到由手机端注册/注销推送 token
+ // 决定;发送侧防打扰(远程正在看该会话 / 去重 / relay 能力)在 main 收口。
+ // 因此桌面/飞书都关时也要 invoke(不再提前 return)。
+ void window.electronAPI.notificationShowSessionEvent({
+ sessionId,
+ title,
+ kind,
+ channels: {
+ desktop: desktopEnabled,
+ feishu: feishuEnabled,
+ mobile: true,
+ },
+ });
+ },
+ [],
+ );
const handleSessionDone = useCallback(
(sessionId: string) => fireSessionNotification(sessionId, 'done'),
[fireSessionNotification],
@@ -938,10 +1038,40 @@ function ExpandedView({
const selectedMachineId = useEffectiveSelectedMachineId();
// 「所有」或含远程设备的作用域还要等 device-link 首次 sessions snapshot;
// 否则本地 sessions 先完成时会把尚未知的远程空数组误报成真实空态。
- const remoteSessionBootstrapLoading =
- useRemoteSessionBootstrapLoading(selectedMachineId);
+ const remoteSessionBootstrapLoading = useRemoteSessionBootstrapLoading(selectedMachineId);
+ const remoteSessionBootstrapLoadingDevices =
+ useRemoteSessionBootstrapLoadingDevices(selectedMachineId);
+ const remoteSessionBootstrapFailures = useRemoteSessionBootstrapFailures(selectedMachineId);
+ const deviceListRequestState = useDeviceLinkDeviceListRequestState();
+ const remoteDeviceDirectoryRelevant =
+ selectedMachineId === MACHINE_ALL ||
+ selectedMachineId.some((deviceId) => deviceId !== MACHINE_LOCAL);
+ const remoteDeviceDirectoryStatus = remoteDeviceDirectoryRelevant
+ ? deviceListRequestState.status
+ : 'ready';
+ const loadingRemoteDeviceLabel = useMemo(
+ () =>
+ new Intl.ListFormat(i18n.language, { style: 'short', type: 'conjunction' }).format(
+ remoteSessionBootstrapLoadingDevices.map((device) => device.name),
+ ),
+ [i18n.language, remoteSessionBootstrapLoadingDevices],
+ );
+ const failedRemoteDeviceLabel = useMemo(
+ () =>
+ new Intl.ListFormat(i18n.language, { style: 'short', type: 'conjunction' }).format(
+ remoteSessionBootstrapFailures.map((device) => device.name),
+ ),
+ [i18n.language, remoteSessionBootstrapFailures],
+ );
+ const handleRetryRemoteTasks = useCallback(() => {
+ for (const device of remoteSessionBootstrapFailures) {
+ retryRemoteSessionBootstrap(device.deviceId);
+ }
+ }, [remoteSessionBootstrapFailures]);
const isLoadingSidebarSessions =
- sessionsHook.isLoading || remoteSessionBootstrapLoading;
+ sessionsHook.isLoading ||
+ remoteSessionBootstrapLoading ||
+ remoteDeviceDirectoryStatus === 'loading';
// 选中的远程机器尚在连接中(会话未同步)→ 用「连接中」占位替换空列表的「暂无对话」。
const selectedMachineConnecting = useSelectedMachineConnecting();
// orca worker + status 过滤(**不含**机器过滤)—— 抽出给「机器过滤后渲染」与「全量项目宇宙」共用。
@@ -1151,12 +1281,7 @@ function ExpandedView({
},
];
});
- }, [
- allProjectGroups.projects,
- pinnedProjectKeys,
- filter.projectsAsSet,
- vendorPredicate,
- ]);
+ }, [allProjectGroups.projects, pinnedProjectKeys, filter.projectsAsSet, vendorPredicate]);
const visiblePinnedEntries = useMemo<PinnedSidebarEntry[]>(() => {
const entries: PinnedSidebarEntry[] = [
@@ -1223,10 +1348,12 @@ function ExpandedView({
? project.sessions.filter(vendorPredicate)
: project.sessions;
if (matchingSessions.length === 0) return [];
- return [{
- ...project,
- sessions: matchingSessions.filter((session) => session.pinnedAt == null),
- }];
+ return [
+ {
+ ...project,
+ sessions: matchingSessions.filter((session) => session.pinnedAt == null),
+ },
+ ];
});
return sortProjectsForSidebar(projects, filter.sortBy, filter.manualProjectOrder);
}, [
@@ -1245,10 +1372,12 @@ function ExpandedView({
? project.sessions.filter(vendorPredicate)
: project.sessions;
if (matchingSessions.length === 0) return [];
- return [{
- ...project,
- sessions: matchingSessions.filter((session) => session.pinnedAt == null),
- }];
+ return [
+ {
+ ...project,
+ sessions: matchingSessions.filter((session) => session.pinnedAt == null),
+ },
+ ];
});
return sortProjectsForSidebar(projects, filter.sortBy, filter.manualProjectOrder);
}, [visibleProjects, vendorPredicate, filter.sortBy, filter.manualProjectOrder]);
@@ -1301,6 +1430,14 @@ function ExpandedView({
});
}, [activityFilteredSessions, vendorPredicate, filter.projectsAsSet, pinnedProjectKeys]);
+ const hasVisibleSidebarContent =
+ visiblePinnedEntries.length > 0 ||
+ (filter.groupBy === 'date'
+ ? visibleDateSessions.length > 0
+ : visibleUnclassified.length > 0 ||
+ visibleProjectsWithVendor.length > 0 ||
+ visibleDialogues.length > 0);
+
const [selectedSessionIds, setSelectedSessionIds] = useState<Set<string>>(() => new Set());
const [selectionAnchorSessionId, setSelectionAnchorSessionId] = useState<string | null>(null);
// 这三个值 handleSessionClick 只在「点击那一刻」读一次。留在它的 deps 里会让
@@ -1434,7 +1571,12 @@ function ExpandedView({
if (!viewedSessionId) return;
markAutomationSessionRunsRead(viewedSessionId);
clearSystemSessionAttention(viewedSessionId);
- }, [viewedSessionId, activeSessionRemoteReceiptKey, activeRemoteAttentionRev, markAutomationSessionRunsRead]);
+ }, [
+ viewedSessionId,
+ activeSessionRemoteReceiptKey,
+ activeRemoteAttentionRev,
+ markAutomationSessionRunsRead,
+ ]);
// 用户从 Dock badge / taskbar flash 点回 app 时,如果 viewedSessionId 没变,
// route-driven effect 不会重跑,系统角标会残留。监听 window focus 兜底清当前
@@ -1528,15 +1670,33 @@ function ExpandedView({
},
[handleSessionClick],
);
- useAppShortcut('switch-session-1', () => handleSwitchSessionSlot(0), { enabled: sessionSwitchEnabled });
- useAppShortcut('switch-session-2', () => handleSwitchSessionSlot(1), { enabled: sessionSwitchEnabled });
- useAppShortcut('switch-session-3', () => handleSwitchSessionSlot(2), { enabled: sessionSwitchEnabled });
- useAppShortcut('switch-session-4', () => handleSwitchSessionSlot(3), { enabled: sessionSwitchEnabled });
- useAppShortcut('switch-session-5', () => handleSwitchSessionSlot(4), { enabled: sessionSwitchEnabled });
- useAppShortcut('switch-session-6', () => handleSwitchSessionSlot(5), { enabled: sessionSwitchEnabled });
- useAppShortcut('switch-session-7', () => handleSwitchSessionSlot(6), { enabled: sessionSwitchEnabled });
- useAppShortcut('switch-session-8', () => handleSwitchSessionSlot(7), { enabled: sessionSwitchEnabled });
- useAppShortcut('switch-session-9', () => handleSwitchSessionSlot(8), { enabled: sessionSwitchEnabled });
+ useAppShortcut('switch-session-1', () => handleSwitchSessionSlot(0), {
+ enabled: sessionSwitchEnabled,
+ });
+ useAppShortcut('switch-session-2', () => handleSwitchSessionSlot(1), {
+ enabled: sessionSwitchEnabled,
+ });
+ useAppShortcut('switch-session-3', () => handleSwitchSessionSlot(2), {
+ enabled: sessionSwitchEnabled,
+ });
+ useAppShortcut('switch-session-4', () => handleSwitchSessionSlot(3), {
+ enabled: sessionSwitchEnabled,
+ });
+ useAppShortcut('switch-session-5', () => handleSwitchSessionSlot(4), {
+ enabled: sessionSwitchEnabled,
+ });
+ useAppShortcut('switch-session-6', () => handleSwitchSessionSlot(5), {
+ enabled: sessionSwitchEnabled,
+ });
+ useAppShortcut('switch-session-7', () => handleSwitchSessionSlot(6), {
+ enabled: sessionSwitchEnabled,
+ });
+ useAppShortcut('switch-session-8', () => handleSwitchSessionSlot(7), {
+ enabled: sessionSwitchEnabled,
+ });
+ useAppShortcut('switch-session-9', () => handleSwitchSessionSlot(8), {
+ enabled: sessionSwitchEnabled,
+ });
// 按住态徽标 map:按当前可见顺序构建,并在按住期间用 MutationObserver 跟随
// 列表变化重建 —— 后台事件(自动化会话冒顶、远程会话上线等)可实时重排列表,
@@ -2040,12 +2200,7 @@ function ExpandedView({
}
await unarchiveSession(sessionId);
},
- [
- runningSessionIds,
- runSessionAction,
- unarchiveSession,
- t,
- ],
+ [runningSessionIds, runSessionAction, unarchiveSession, t],
);
const handleConfirm = useCallback(async () => {
@@ -2063,16 +2218,12 @@ function ExpandedView({
action === 'delete' && sessionId === viewedSessionId
? await resolveSessionRemovalRedirect(new Set([sessionId]), sessionId)
: null;
- await runSessionAction(sessionId, action, { activeSessionId: viewedSessionId, deleteRedirectRoute });
+ await runSessionAction(sessionId, action, {
+ activeSessionId: viewedSessionId,
+ deleteRedirectRoute,
+ });
setConfirm(CONFIRM_INITIAL);
- }, [
- viewedSessionId,
- confirm,
- resolveSessionRemovalRedirect,
- runSessionAction,
- sessionsById,
- t,
- ]);
+ }, [viewedSessionId, confirm, resolveSessionRemovalRedirect, runSessionAction, sessionsById, t]);
const handleCancelConfirm = useCallback(() => {
setConfirm(CONFIRM_INITIAL);
@@ -2573,7 +2724,31 @@ function ExpandedView({
className="flex flex-col gap-2 pt-2 pb-4 overflow-y-auto flex-1"
style={{ scrollbarGutter: 'stable' }}
>
- {selectedMachineConnecting ? (
+ {remoteDeviceDirectoryStatus === 'error' && !hasVisibleSidebarContent ? (
+ <RemoteSidebarLoadNotice
+ kind="devices"
+ status="error"
+ partial={false}
+ onRetry={retryDeviceLinkDeviceList}
+ />
+ ) : remoteSessionBootstrapFailures.length > 0 && !hasVisibleSidebarContent ? (
+ <RemoteSidebarLoadNotice
+ kind="tasks"
+ status="error"
+ deviceLabel={failedRemoteDeviceLabel}
+ partial={false}
+ onRetry={handleRetryRemoteTasks}
+ />
+ ) : remoteDeviceDirectoryStatus === 'loading' && !hasVisibleSidebarContent ? (
+ <RemoteSidebarLoadNotice kind="devices" status="loading" partial={false} />
+ ) : remoteSessionBootstrapLoadingDevices.length > 0 && !hasVisibleSidebarContent ? (
+ <RemoteSidebarLoadNotice
+ kind="tasks"
+ status="loading"
+ deviceLabel={loadingRemoteDeviceLabel}
+ partial={false}
+ />
+ ) : selectedMachineConnecting ? (
// 选中机器连接中:会话还没同步,显示「连接中」而非「暂无对话」。
// 机器切换入口在上方固定行常驻,始终能切回「所有」、不会被困在占位页。
<div className="flex flex-col items-center justify-center px-3 py-12 text-center">
@@ -2583,6 +2758,34 @@ function ExpandedView({
</div>
) : (
<>
+ {remoteDeviceDirectoryStatus === 'error' && (
+ <RemoteSidebarLoadNotice
+ kind="devices"
+ status="error"
+ partial
+ onRetry={retryDeviceLinkDeviceList}
+ />
+ )}
+ {remoteSessionBootstrapFailures.length > 0 && (
+ <RemoteSidebarLoadNotice
+ kind="tasks"
+ status="error"
+ deviceLabel={failedRemoteDeviceLabel}
+ partial
+ onRetry={handleRetryRemoteTasks}
+ />
+ )}
+ {remoteDeviceDirectoryStatus === 'loading' && (
+ <RemoteSidebarLoadNotice kind="devices" status="loading" partial />
+ )}
+ {remoteSessionBootstrapLoadingDevices.length > 0 && (
+ <RemoteSidebarLoadNotice
+ kind="tasks"
+ status="loading"
+ deviceLabel={loadingRemoteDeviceLabel}
+ partial
+ />
+ )}
<PinnedSection
entries={visiblePinnedEntries}
allKnownProjects={projectUniverse.projects}
@@ -2639,84 +2842,84 @@ function ExpandedView({
projectOptions={projectPickerOptions}
onReorder={handlePinnedReorder}
/>
- {filter.groupBy === 'date' ? (
- <DateGroupedSessionsSection
- sessions={visibleDateSessions}
- isLoading={isLoadingSidebarSessions}
- allKnownProjects={projectUniverse.projects}
- filter={filter}
- activeSessionId={activeSessionId}
- runningSessionIds={displayRunningSessionIds}
- attachedSessionIds={attachedSessionIds}
- notifications={sidebarNotifications}
- scheduleSessionIndex={scheduleSessionIndex}
- selectedSessionIds={selectedSessionIds}
- onSessionClick={handleSessionClick}
- onAction={handleActionClick}
- onRename={handleRename}
- onTogglePin={handleTogglePin}
- onMoveSession={handleMoveSession}
- projectOptions={projectPickerOptions}
- onScheduleAction={handleScheduleAction}
- />
- ) : (
- <>
- <ProjectsSection
- unclassified={visibleUnclassified}
- projects={visibleProjectsWithVendor}
- allKnownProjects={projectUniverse.projects}
- filter={filter}
- collapsed={collapse.collapsed}
- isAllCollapsed={collapse.isAllCollapsed}
- activeSessionId={activeSessionId}
- runningSessionIds={displayRunningSessionIds}
- attachedSessionIds={attachedSessionIds}
- notifications={sidebarNotifications}
- scheduleSessionIndex={scheduleSessionIndex}
- selectedSessionIds={selectedSessionIds}
- onSessionClick={handleSessionClick}
- onAction={handleActionClick}
- onRename={handleRename}
- onTogglePin={handleTogglePin}
- onMoveSession={handleMoveSession}
- projectOptions={projectPickerOptions}
- onScheduleAction={handleScheduleAction}
- onToggleProject={collapse.toggle}
- onToggleProjectPin={handleToggleProjectPin}
- onRenameProject={handleProjectAliasChange}
- onCollapseAll={collapse.collapseAll}
- onExpandAll={collapse.expandAll}
- onCreateProject={handleCreateProject}
- onCreateInProject={handleCreateInProject}
- onOpenConversationSearch={handleOpenConversationSearch}
- onOpenInExplorer={handleOpenInExplorer}
- onLinkCodexProject={handleLinkCodexProject}
- linkingCodexProject={linkingCodexProject}
- onBrowseFiles={handleBrowseFiles}
- onArchiveAll={handleArchiveAllInProject}
- />
- <DialogueSection
- sessions={visibleDialogues}
- isLoading={isLoadingSidebarSessions}
- activeSessionId={activeSessionId}
- runningSessionIds={displayRunningSessionIds}
- attachedSessionIds={attachedSessionIds}
- notifications={sidebarNotifications}
- scheduleSessionIndex={scheduleSessionIndex}
- selectedSessionIds={selectedSessionIds}
- onSessionClick={handleSessionClick}
- onAction={handleActionClick}
- onRename={handleRename}
- onTogglePin={handleTogglePin}
- onMoveSession={handleMoveSession}
- projectOptions={projectPickerOptions}
- onScheduleAction={handleScheduleAction}
- onCreateDialogue={handleCreateDialogue}
- sortBy={dialogueSortBy}
- onSortByChange={setDialogueSortBy}
- />
- </>
- )}
+ {filter.groupBy === 'date' ? (
+ <DateGroupedSessionsSection
+ sessions={visibleDateSessions}
+ isLoading={isLoadingSidebarSessions}
+ allKnownProjects={projectUniverse.projects}
+ filter={filter}
+ activeSessionId={activeSessionId}
+ runningSessionIds={displayRunningSessionIds}
+ attachedSessionIds={attachedSessionIds}
+ notifications={sidebarNotifications}
+ scheduleSessionIndex={scheduleSessionIndex}
+ selectedSessionIds={selectedSessionIds}
+ onSessionClick={handleSessionClick}
+ onAction={handleActionClick}
+ onRename={handleRename}
+ onTogglePin={handleTogglePin}
+ onMoveSession={handleMoveSession}
+ projectOptions={projectPickerOptions}
+ onScheduleAction={handleScheduleAction}
+ />
+ ) : (
+ <>
+ <ProjectsSection
+ unclassified={visibleUnclassified}
+ projects={visibleProjectsWithVendor}
+ allKnownProjects={projectUniverse.projects}
+ filter={filter}
+ collapsed={collapse.collapsed}
+ isAllCollapsed={collapse.isAllCollapsed}
+ activeSessionId={activeSessionId}
+ runningSessionIds={displayRunningSessionIds}
+ attachedSessionIds={attachedSessionIds}
+ notifications={sidebarNotifications}
+ scheduleSessionIndex={scheduleSessionIndex}
+ selectedSessionIds={selectedSessionIds}
+ onSessionClick={handleSessionClick}
+ onAction={handleActionClick}
+ onRename={handleRename}
+ onTogglePin={handleTogglePin}
+ onMoveSession={handleMoveSession}
+ projectOptions={projectPickerOptions}
+ onScheduleAction={handleScheduleAction}
+ onToggleProject={collapse.toggle}
+ onToggleProjectPin={handleToggleProjectPin}
+ onRenameProject={handleProjectAliasChange}
+ onCollapseAll={collapse.collapseAll}
+ onExpandAll={collapse.expandAll}
+ onCreateProject={handleCreateProject}
+ onCreateInProject={handleCreateInProject}
+ onOpenConversationSearch={handleOpenConversationSearch}
+ onOpenInExplorer={handleOpenInExplorer}
+ onLinkCodexProject={handleLinkCodexProject}
+ linkingCodexProject={linkingCodexProject}
+ onBrowseFiles={handleBrowseFiles}
+ onArchiveAll={handleArchiveAllInProject}
+ />
+ <DialogueSection
+ sessions={visibleDialogues}
+ isLoading={isLoadingSidebarSessions}
+ activeSessionId={activeSessionId}
+ runningSessionIds={displayRunningSessionIds}
+ attachedSessionIds={attachedSessionIds}
+ notifications={sidebarNotifications}
+ scheduleSessionIndex={scheduleSessionIndex}
+ selectedSessionIds={selectedSessionIds}
+ onSessionClick={handleSessionClick}
+ onAction={handleActionClick}
+ onRename={handleRename}
+ onTogglePin={handleTogglePin}
+ onMoveSession={handleMoveSession}
+ projectOptions={projectPickerOptions}
+ onScheduleAction={handleScheduleAction}
+ onCreateDialogue={handleCreateDialogue}
+ sortBy={dialogueSortBy}
+ onSortByChange={setDialogueSortBy}
+ />
+ </>
+ )}
</>
)}
</div>
@@ -3005,7 +3208,8 @@ function RailPanelShell({
// 落入自身或菜单/对话框浮层才不算——回到一级面板非项目区必须触发
// onLeave 收三级,否则旧项目的三级面板悬留(codex review;项目行经
// mouseenter → openProject 自会接管切换)。
- const keepalive = level === 1 ? RAIL_PANEL_KEEPALIVE_SELECTOR : RAIL_PROJECT_KEEPALIVE_SELECTOR;
+ const keepalive =
+ level === 1 ? RAIL_PANEL_KEEPALIVE_SELECTOR : RAIL_PROJECT_KEEPALIVE_SELECTOR;
if (next?.closest(keepalive)) return;
onLeave();
}}
@@ -3130,7 +3334,13 @@ function RailPanels({
useEffect(() => {
if (!isCollapsed) railPanelStore.closeAll();
}, [isCollapsed]);
- useEffect(() => () => { railPanelStore.closeAll(); railPanelStore.setLampScope(null); }, []);
+ useEffect(
+ () => () => {
+ railPanelStore.closeAll();
+ railPanelStore.setLampScope(null);
+ },
+ [],
+ );
// 灯语取样范围发布:与面板实际展示的过滤后集合一致(项目组 + 未分类 + 对话),
// RailNav 的段灯据此聚合(review P2「灯绕过筛选/截断」两条的根治)。
@@ -3304,7 +3514,13 @@ function RailPanels({
}
if (!notifications.has(s.id)) continue;
const kind = attentionKinds.get(s.id);
- consider(kind === 'error' || urgentSet.has(s.id) ? 'error' : kind === 'awaiting' ? 'awaiting' : 'done');
+ consider(
+ kind === 'error' || urgentSet.has(s.id)
+ ? 'error'
+ : kind === 'awaiting'
+ ? 'awaiting'
+ : 'done',
+ );
}
return { running, dotTone: best };
},
@@ -3367,7 +3583,9 @@ function RailPanels({
const panelHead = (title: string, count: number, action?: ReactNode) => (
<div className="flex items-baseline gap-1.5 px-2.5 pb-1 pt-1.5">
- <span className="min-w-0 flex-1 truncate text-[12.5px] font-extrabold text-foreground">{title}</span>
+ <span className="min-w-0 flex-1 truncate text-[12.5px] font-extrabold text-foreground">
+ {title}
+ </span>
<span className="shrink-0 text-[10px] text-[var(--text-tertiary)]">
{t('ccAgent.sidebar.railNavCount', { count })}
</span>
@@ -3405,7 +3623,7 @@ function RailPanels({
const openProject =
panelState.openSection === 'projects' && panelState.openProjectKey
- ? projects.find((p) => p.projectKey === panelState.openProjectKey) ?? null
+ ? (projects.find((p) => p.projectKey === panelState.openProjectKey) ?? null)
: null;
return (
@@ -3460,7 +3678,10 @@ function RailPanels({
aria-expanded={isOpen}
onMouseEnter={(e) => {
const rect = e.currentTarget.getBoundingClientRect();
- railPanelStore.openProject(p.projectKey, { right: rect.right, top: rect.top });
+ railPanelStore.openProject(p.projectKey, {
+ right: rect.right,
+ top: rect.top,
+ });
}}
// 键盘可达:Tab 聚焦后 Enter/Space(原生 click)走与 hover
// 同一条 openProject 路径,否则三级面板只有鼠标能打开(codex review)。
@@ -3510,7 +3731,9 @@ function RailPanels({
>
{projectDisplayLabel}
</span>
- {agg.dotTone && <AttentionDot size={5} tone={agg.dotTone} className="shrink-0" />}
+ {agg.dotTone && (
+ <AttentionDot size={5} tone={agg.dotTone} className="shrink-0" />
+ )}
<span className="shrink-0 text-[10px] tabular-nums text-[var(--text-tertiary)]">
{p.sessions.length}
</span>
@@ -3623,7 +3846,7 @@ function RailPanels({
// 远程写保护项目:菜单项与展开态同语义禁用(codex review),不触发
// closeAll 丢上下文。
const menuTarget = projectMenu
- ? projects.find((x) => x.projectKey === projectMenu.projectKey) ?? null
+ ? (projects.find((x) => x.projectKey === projectMenu.projectKey) ?? null)
: null;
const menuTargetBlocked = menuTarget != null && isDeviceLinkWriteBlocked(menuTarget);
return (
@@ -3633,10 +3856,7 @@ function RailPanels({
onSelect={() => {
setProjectMenu(null);
if (!menuTarget) return;
- onToggleProjectPin(
- menuTarget,
- pinnedProjectKeys.has(menuTarget.projectKey),
- );
+ onToggleProjectPin(menuTarget, pinnedProjectKeys.has(menuTarget.projectKey));
}}
className="cursor-pointer text-sm text-[var(--msg-assistant-text)] hover:bg-[var(--cmd-palette-item-hover)]"
>
diff --git a/apps/desktop/src/renderer/features/cc-agent/CreateWorkerPopover.tsx b/apps/desktop/src/renderer/features/cc-agent/CreateWorkerPopover.tsx
index 852a1cc220..4addc88b06 100644
--- a/apps/desktop/src/renderer/features/cc-agent/CreateWorkerPopover.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/CreateWorkerPopover.tsx
@@ -169,6 +169,7 @@ export function CreateWorkerPopover({
providers,
providersLoading,
providersError,
+ providersUnsupported: deviceId ? remoteProviders.unsupported : false,
excludeSubscriptionDirect: sshRemote === true,
excludeChatBridgedCodex: sshRemote === true,
isVisible: deviceId
@@ -182,11 +183,18 @@ export function CreateWorkerPopover({
providers,
providersError,
providersLoading,
+ remoteProviders.unsupported,
sshRemote,
visibilityVersion,
]);
const currentModel = activeModels.find((m) => m.id === model);
const modelCatalogLoading = activeCapabilitiesState.loading || providersLoading;
+ const remoteModelListBlocked =
+ !!deviceId &&
+ (activeCapabilitiesState.loading ||
+ activeCapabilitiesState.error !== null ||
+ providersLoading ||
+ (!!providersError && !remoteProviders.unsupported));
// 显式来源仅在「已连接、确实提供该模型、且该 (来源, 模型) 未被**停用**」时有效;
// 其余(断开/下架/停用/换了模型)收窄为 null 交回默认路由解析。停用判据 =
@@ -554,6 +562,7 @@ export function CreateWorkerPopover({
activeRole.length >= 1 &&
activeRole.length <= 32 &&
!customRoleError &&
+ !remoteModelListBlocked &&
!!currentModel;
const resolvedTitle = title ?? t('orca.createWorker.title');
const resolvedSubmitLabel = submitLabel ?? t('orca.createWorker.submit');
diff --git a/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx b/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx
index c22e173220..fc8c9c5ffb 100644
--- a/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx
@@ -105,10 +105,7 @@ import {
} from '@/lib/composerDraftStore';
import type { JSONContent } from '@tiptap/core';
import { base64ToUint8Array } from '@/lib/fileTypeInference';
-import {
- calibrateDraftModel,
- type DraftModelCalibrationResult,
-} from '@/lib/draftModelCalibration';
+import { calibrateDraftModel, type DraftModelCalibrationResult } from '@/lib/draftModelCalibration';
import { showWorktreeError } from '@/lib/worktreeToast';
import type { CreateWorktreeResp } from '@/lib/worktree.types';
import * as sessionService from '@/lib/sessionService';
@@ -146,10 +143,7 @@ import {
} from '@/lib/fileTypes';
import type { PastedTextRange, SlashCommandRange } from '@/lib/imageRef';
import type { AgentInputReference } from '@cindy/maker-shared/agent-input-projection';
-import {
- DEFAULT_DRAFT_SESSION_TITLE,
- normalizeAutoTitle,
-} from '@cindy/maker-shared/session-title';
+import { DEFAULT_DRAFT_SESSION_TITLE, normalizeAutoTitle } from '@cindy/maker-shared/session-title';
import { toast } from '@/lib/toast';
import { cn } from '@/lib/utils';
import { InvisibleWindowDragStrip } from '@/components/layout/windowDrag';
@@ -205,7 +199,15 @@ import {
deriveModelsFromProviders,
filterChatBridgedCodexProviders,
} from '@/lib/providerModels';
-import { effectiveSourceIdForModel, getModel, isModelSelectableForNewRoute, providerOffersModel, sessionModelSupportsFastMode, connectedProvidersForAgent, type ProviderView } from '@cindy/model-providers';
+import {
+ effectiveSourceIdForModel,
+ getModel,
+ isModelSelectableForNewRoute,
+ providerOffersModel,
+ sessionModelSupportsFastMode,
+ connectedProvidersForAgent,
+ type ProviderView,
+} from '@cindy/model-providers';
import { isSubscriptionDirectModel } from '../../../shared/subscriptionModels';
import {
resolveDeviceLinkDraftDefaults,
@@ -316,7 +318,8 @@ function draftEnableOrcaOptions(
if (!providersReady) return preferredAgent;
if (connectedProvidersForAgent(providers, preferredAgent).length > 0) return preferredAgent;
const fallback = (['claude-code', 'codex', 'pi'] as const).find(
- (agent) => agent !== preferredAgent && connectedProvidersForAgent(providers, agent).length > 0,
+ (agent) =>
+ agent !== preferredAgent && connectedProvidersForAgent(providers, agent).length > 0,
);
return fallback ?? preferredAgent;
})();
@@ -522,8 +525,9 @@ export function NewMakerDraftRoute() {
/** createSession 失败 toast:远端路由错误按 code 给可操作文案,其余回退通用文案。 */
const toastCreateSessionFailed = (err?: unknown) => {
- const code = (err as { code?: string } | null | undefined)?.code
- ?? (createSessionError as { code?: string } | null)?.code;
+ const code =
+ (err as { code?: string } | null | undefined)?.code ??
+ (createSessionError as { code?: string } | null)?.code;
const key =
code === 'REMOTE_PROVIDER_UPDATING'
? 'ccAgent.draft.remoteProviderUpdating'
@@ -593,7 +597,9 @@ export function NewMakerDraftRoute() {
const [wtName, setWtName] = useState('');
const [wtSourceBranch, setWtSourceBranch] = useState('');
const [wtBaseRepo, setWtBaseRepo] = useState<string | null>(null);
- const [wtSupportsRecoveryKeyDiscard, setWtSupportsRecoveryKeyDiscard] = useState<boolean | null>(null);
+ const [wtSupportsRecoveryKeyDiscard, setWtSupportsRecoveryKeyDiscard] = useState<boolean | null>(
+ null,
+ );
// F-COLLAB: 协同模式状态(enabled + worker 类型)直接读自 draft store,
// 和 workingDir 走同一份 localStorage,重启 / 切走再回都能恢复。
// 协同与项目/对话形态正交:两种草稿都向 ChatInput 提供入口;项目读项目级策略,
@@ -657,8 +663,9 @@ export function NewMakerDraftRoute() {
// null,agent map 无 pi,但模型目录仍投影 Pi → 需按 maker:list-available-agents 过滤,
// 否则一路创建到 requireAgent 的 not-registered 报错,codex review P2)。远程草稿以被控端
// 的注册结果为准(hook 传 deviceId 走隧道)。未加载完成时不隐藏任何入口(fail-open)。
- const { availableVendors, loaded: availableAgentsLoaded } =
- useAvailableAgents(effectiveDeviceLinkDeviceId);
+ const { availableVendors, loaded: availableAgentsLoaded } = useAvailableAgents(
+ effectiveDeviceLinkDeviceId,
+ );
const hiddenSwitcherVendors = useMemo<MakerVendor[]>(() => {
if (!availableAgentsLoaded) return [];
return (['cc', 'codex', 'pi'] as const).filter((vendor) => !availableVendors.has(vendor));
@@ -784,7 +791,9 @@ export function NewMakerDraftRoute() {
*/
const {
projects: deviceLinkProjects,
- loading: deviceLinkProjectsLoading,
+ status: deviceLinkProjectsStatus,
+ error: deviceLinkProjectsError,
+ retry: retryDeviceLinkProjects,
removeProject: removeRemoteProject,
} = useDeviceLinkProjects(
effectiveDeviceLinkDeviceId ?? null,
@@ -800,10 +809,23 @@ export function NewMakerDraftRoute() {
? {
deviceId: effectiveDeviceLinkDeviceId,
deviceName: effectiveDeviceLinkDeviceName ?? effectiveDeviceLinkDeviceId,
- loading: deviceLinkProjectsLoading,
+ status:
+ deviceLinkProjectsStatus === 'error'
+ ? 'error'
+ : deviceLinkProjectsStatus === 'ready'
+ ? 'ready'
+ : 'loading',
+ error: deviceLinkProjectsError,
+ retry: retryDeviceLinkProjects,
}
: undefined,
- [effectiveDeviceLinkDeviceId, effectiveDeviceLinkDeviceName, deviceLinkProjectsLoading],
+ [
+ effectiveDeviceLinkDeviceId,
+ effectiveDeviceLinkDeviceName,
+ deviceLinkProjectsStatus,
+ deviceLinkProjectsError,
+ retryDeviceLinkProjects,
+ ],
);
const createAgentModeLabel =
getProjectPickerDisplayName(
@@ -871,12 +893,28 @@ export function NewMakerDraftRoute() {
// device-link:在远程设备上新建会话时,能力 / 模型必须来自该被控端(草稿带 deviceLinkDeviceId);
// 本地草稿 effectiveDeviceLinkDeviceId 为 undefined → 走本地能力(行为不变)。
- const { capabilities, loading: capabilitiesLoading } = useAgentCapabilities(capabilityAgentKind, effectiveDeviceLinkDeviceId);
+ const {
+ capabilities,
+ loading: capabilitiesLoading,
+ error: capabilitiesError,
+ } = useAgentCapabilities(capabilityAgentKind, effectiveDeviceLinkDeviceId);
// device-link「以被控端为准」:远程草稿用被控端经隧道带来的 providers(per-provider,含 fast 能力);
// 本地草稿用本机 providers。fast 判定统一交给 resolveFastSupported(不在控制端另写远程逻辑)。
const { providers: localProviders, loading: localProvidersLoading } = useProviders();
- const { providers: deviceProviders, loading: deviceProvidersLoading } = useDeviceProviders(effectiveDeviceLinkDeviceId);
+ const {
+ providers: deviceProviders,
+ loading: deviceProvidersLoading,
+ error: deviceProvidersError,
+ unsupported: deviceProvidersUnsupported,
+ } = useDeviceProviders(effectiveDeviceLinkDeviceId);
const providers = effectiveDeviceLinkDeviceId ? deviceProviders : localProviders;
+ const remoteModelListStatus = !isDeviceLinkDraft
+ ? 'idle'
+ : capabilitiesError || (deviceProvidersError && !deviceProvidersUnsupported)
+ ? 'error'
+ : capabilitiesLoading || deviceProvidersLoading || !capabilities
+ ? 'loading'
+ : 'ready';
// 草稿当前**生效来源 id**(= ModelSelector 高亮 / ChatInput effectiveSourceId 同口径):显式选中且
// 仍可连、并提供当前模型 → 它;否则只在当前模型的可用来源中取原生默认。fast/effort 的
@@ -1039,12 +1077,14 @@ export function NewMakerDraftRoute() {
// 选中模型的 model/effort/fast/permission/source 不取控制端本地(chatPrefs),改经隧道拉被控端
// 当前草稿值(maker:get-new-maker-defaults),按被控端 capabilities 校准后 seed 进一个**临时
// holder(dlSel)**;用户在远程草稿里的修改只写 dlSel,既不污染本地 newMakerDraft、也不回写被控端。
- // 旧版被控端无此 channel / 拉取失败 → remoteDraft=null → 回落被控端 capabilities 默认(绝不回落本地)。
+ // 只有旧版被控端明确不支持此 channel 时才回落 capabilities 默认;超时 / 断链必须保留为
+ // error,不能伪装成「已读取但没有远程偏好」后放行发送。
// 本地草稿(无 deviceId)整段跳过,走下方 chatPrefs 路径(逐字节不变)。
const [remoteDraftState, setRemoteDraftState] = useState<{
- loaded: boolean;
+ status: 'idle' | 'loading' | 'ready' | 'error';
value: RemoteDraftDefaults | null;
- }>({ loaded: false, value: null });
+ }>({ status: 'idle', value: null });
+ const [remoteDraftRetryEpoch, setRemoteDraftRetryEpoch] = useState(0);
const [dlSel, setDlSel] = useState<DeviceLinkDraftSelection | null>(null);
const dlSeedKeyRef = useRef<string | null>(null);
const skipDefaultsRefetchRef = useRef(false);
@@ -1059,7 +1099,7 @@ export function NewMakerDraftRoute() {
useEffect(() => {
if (!isDeviceLinkDraft || !effectiveDeviceLinkDeviceId) {
remoteDraftIdentityRef.current = null;
- setRemoteDraftState({ loaded: false, value: null });
+ setRemoteDraftState({ status: 'idle', value: null });
return;
}
const identity = `${effectiveDeviceLinkDeviceId}:${capabilityAgentKind}`;
@@ -1072,30 +1112,27 @@ export function NewMakerDraftRoute() {
}
let cancelled = false;
const requestRevision = remoteDraftRevisionRef.current;
- setRemoteDraftState((previous) => (
- sameIdentity ? previous : { loaded: false, value: null }
- ));
+ setRemoteDraftState((previous) => ({
+ status: 'loading',
+ value: sameIdentity ? previous.value : null,
+ }));
window.electronAPI.deviceLink
.invoke(effectiveDeviceLinkDeviceId, 'maker:get-new-maker-defaults', [capabilityAgentKind])
.then((v) => {
- if (
- !cancelled
- && remoteDraftRevisionRef.current === requestRevision
- ) {
- setRemoteDraftState({ loaded: true, value: (v as RemoteDraftDefaults | null) ?? null });
+ if (!cancelled && remoteDraftRevisionRef.current === requestRevision) {
+ setRemoteDraftState({
+ status: 'ready',
+ value: (v as RemoteDraftDefaults | null) ?? null,
+ });
}
})
.catch((error) => {
- if (
- cancelled
- || remoteDraftRevisionRef.current !== requestRevision
- ) return;
- const unsupported =
- extractIpcError(error)?.code === 'DEVICE_LINK_CHANNEL_NOT_ALLOWED';
- // 只有确认旧端不支持时回落 capabilities 默认。超时/断链保留同目标旧镜像,
- // remoteDraftRefreshEpoch 会在 relay 或目标设备恢复后触发下一次权威拉取。
+ if (cancelled || remoteDraftRevisionRef.current !== requestRevision) return;
+ const unsupported = extractIpcError(error)?.code === 'DEVICE_LINK_CHANNEL_NOT_ALLOWED';
+ // 只有确认旧端不支持时回落 capabilities 默认。超时/断链保留同目标旧镜像供展示,
+ // 但状态必须是 error,发送 / 新建目标会阻止提交并触发一次显式重试。
setRemoteDraftState((previous) => ({
- loaded: true,
+ status: unsupported ? 'ready' : 'error',
value: unsupported ? null : previous.value,
}));
});
@@ -1107,6 +1144,7 @@ export function NewMakerDraftRoute() {
effectiveDeviceLinkDeviceId,
capabilityAgentKind,
remoteDraftRefreshEpoch,
+ remoteDraftRetryEpoch,
]);
// seed dlSel:等被控端 capabilities + 草稿值都就绪后种一次;按 (deviceId, vendor) 记 seedKey,
@@ -1117,7 +1155,7 @@ export function NewMakerDraftRoute() {
setDlSel(null);
return;
}
- if (!capabilities || !remoteDraftState.loaded) return;
+ if (!capabilities || remoteDraftState.status !== 'ready') return;
const key = `${effectiveDeviceLinkDeviceId}:${capabilityAgentKind}`;
if (dlSeedKeyRef.current === key) return;
dlSeedKeyRef.current = key;
@@ -1158,12 +1196,12 @@ export function NewMakerDraftRoute() {
: null;
// 用被控端快照刷新镜像(初始 pull + 后续 push 都经 remoteDraftState.value 流入)。
- // 仅在 loaded 时刷:重拉期间(loaded=false, value 暂为 null)**保留旧镜像**,避免非选中行闪默认再收敛
+ // 仅在 ready 时刷:重拉 / 失败期间保留旧镜像,避免非选中行闪默认再收敛
// (镜像 scope 按设备、跨 agent 存全量,切 vendor 重拉无需清;真切设备由下方 clearScope effect 处理)。
useEffect(() => {
- if (!mirrorScopeKey || !remoteDraftState.loaded) return;
+ if (!mirrorScopeKey || remoteDraftState.status !== 'ready') return;
replaceScope(mirrorScopeKey, remoteDraftState.value?.providerModelMemory);
- }, [mirrorScopeKey, remoteDraftState.loaded, remoteDraftState.value]);
+ }, [mirrorScopeKey, remoteDraftState.status, remoteDraftState.value]);
// 离开 / 切设备时清掉该 scope 的镜像(避免泄漏);仅随 scopeKey 变化触发,不在每次 push 时清。
useEffect(() => {
@@ -1182,7 +1220,7 @@ export function NewMakerDraftRoute() {
const payload = push.payload as Record<string, RemoteDraftDefaults | undefined> | null;
const next = payload?.[vendorSlot] ?? null;
remoteDraftRevisionRef.current += 1;
- setRemoteDraftState({ loaded: true, value: next });
+ setRemoteDraftState({ status: 'ready', value: next });
// 选中行(dlSel)的 effort/fast 也跟被控端走:按当前 dlSel.model 重解析,但保留控制端的
// permission/source/model 选择(非按模型记 / 控制端 launch 意图)。被控端改选中模型 effort 即时反映。
if (capabilities) {
@@ -1207,7 +1245,7 @@ export function NewMakerDraftRoute() {
// 自动开关;环境合格性只影响 checkbox 禁用态与发送时是否真的走 worktree
// (handleSend 按「勾选 && baseRepo 就绪」静默降级,绝不报错拦截、绝不改记忆)。
const worktreePref = isDeviceLinkDraft
- ? remoteDraftState.loaded && remoteDraftState.value?.worktreeEnabled === true
+ ? remoteDraftState.value?.worktreeEnabled === true
: draft.worktreeEnabled;
useEffect(() => {
setWtEnabled(worktreePref);
@@ -1479,7 +1517,12 @@ export function NewMakerDraftRoute() {
dlSeedKeyRef.current = req.deviceId ? `${req.deviceId}:${capabilityAgentKind}` : null;
if (deviceChanged) {
setDlSel(
- resolveDeviceLinkDraftDefaults(freshCaps, freshDefaults, undefined, capabilityAgentKind),
+ resolveDeviceLinkDraftDefaults(
+ freshCaps,
+ freshDefaults,
+ undefined,
+ capabilityAgentKind,
+ ),
);
// deviceId 变化会让 defaults effect 重跑;我们已经 inline 拉过了,跳过那一次避免覆盖。
skipDefaultsRefetchRef.current = true;
@@ -1511,11 +1554,11 @@ export function NewMakerDraftRoute() {
),
);
}
- setRemoteDraftState({ loaded: true, value: freshDefaults });
+ setRemoteDraftState({ status: 'ready', value: freshDefaults });
} else if (deviceChanged) {
setDlSel(null);
dlSeedKeyRef.current = null;
- setRemoteDraftState({ loaded: false, value: null });
+ setRemoteDraftState({ status: 'loading', value: null });
}
// worktree 三态 = 上一个 repo 的描述:baseRepo 由 detect-cwd 异步回填(远程还要走隧道往返),
@@ -1570,14 +1613,20 @@ export function NewMakerDraftRoute() {
// 验证设备可达:直接 invoke 能力 + 供应商(不走 swallow 的 prefetch)。
// 失败 throw → dialog 留 open,不破坏当前草稿状态。
const [freshCaps] = await Promise.all([
- window.electronAPI.deviceLink.invoke(target.deviceId, 'maker:get-capabilities', [capabilityAgentKind]) as Promise<AgentCapabilities>,
+ window.electronAPI.deviceLink.invoke(target.deviceId, 'maker:get-capabilities', [
+ capabilityAgentKind,
+ ]) as Promise<AgentCapabilities>,
window.electronAPI.deviceLink.invoke(target.deviceId, 'maker:provider:list', []),
]);
- // defaults 允许失败(旧版被控端无此 channel → capabilities 默认 fallback)。
+ // 只有旧版被控端明确不支持 defaults channel 时才回落 capabilities 默认;网络失败
+ // 仍然是连接失败,必须让 dialog 保持打开,不能把 null 当成权威空配置。
const freshDefaults = await window.electronAPI.deviceLink
.invoke(target.deviceId, 'maker:get-new-maker-defaults', [capabilityAgentKind])
.then((v) => (v as RemoteDraftDefaults | null) ?? null)
- .catch(() => null);
+ .catch((error) => {
+ if (extractIpcError(error)?.code === 'DEVICE_LINK_CHANNEL_NOT_ALLOWED') return null;
+ throw error;
+ });
// 设备验证通过(direct invoke 成功)。转移只声明目标 —— 该清什么、该保留什么由
// applyDraftTarget 按「设备变了还是项目变了」推导(它也负责作废该设备的三个无 TTL 快照,
// 所以这一步必须排在下面的 prefetch 之前,否则刚 prefetch 的数据又被 evict 掉)。
@@ -1639,21 +1688,36 @@ export function NewMakerDraftRoute() {
// chatPrefs.providerId(可能是旧的 controller-local 值)。
const rawProviderId = chatInitialProviderId ?? null;
const sshLocalSourceId = effectiveSourceIdForModel(
- localProviders, rawProviderId, sshModel, capabilityAgentKind,
+ localProviders,
+ rawProviderId,
+ sshModel,
+ capabilityAgentKind,
);
// 只有用户显式选中的来源在本地仍可用时才保留;否则 null = 走默认路由。
- const sshProviderId = (rawProviderId && sshLocalSourceId === rawProviderId) ? rawProviderId : null;
+ const sshProviderId =
+ rawProviderId && sshLocalSourceId === rawProviderId ? rawProviderId : null;
// fast mode:来源不支持就关闭;支持时保留用户在 composer 里看到的 effectiveFastMode
// (device-link 草稿活跃时来自 dlSel/deviceLinkInitial,本地草稿来自 per-model 记忆)。
- const sshSourceSupportsFast = sessionModelSupportsFastMode(localProviders, sshProviderId, sshModel, capabilityAgentKind);
+ const sshSourceSupportsFast = sessionModelSupportsFastMode(
+ localProviders,
+ sshProviderId,
+ sshModel,
+ capabilityAgentKind,
+ );
const sshFastMode = sshSourceSupportsFast ? effectiveFastMode : false;
// effort: 用 draftInitialEffort(用户在 composer 里看到的值)作 currentEffort,
// 再由 resolveNewMakerDraftEffort 按本地 SSH model 支持的 levels 做 clamp。
- const sshLocalProvider = sshLocalSourceId ? localProviders.find((p) => p.id === sshLocalSourceId) : undefined;
- const sshLocalModelDesc = sshLocalProvider ? getModel(sshLocalProvider, sshModel, capabilityAgentKind) : undefined;
+ const sshLocalProvider = sshLocalSourceId
+ ? localProviders.find((p) => p.id === sshLocalSourceId)
+ : undefined;
+ const sshLocalModelDesc = sshLocalProvider
+ ? getModel(sshLocalProvider, sshModel, capabilityAgentKind)
+ : undefined;
const sshEffort = resolveNewMakerDraftEffort({
currentEffort: draftInitialEffort,
- presetEffort: sshLocalSourceId ? getProviderModelEffort(capabilityAgentKind, sshLocalSourceId, sshModel) : undefined,
+ presetEffort: sshLocalSourceId
+ ? getProviderModelEffort(capabilityAgentKind, sshLocalSourceId, sshModel)
+ : undefined,
efforts: sshLocalModelDesc?.efforts ?? [],
defaultEffort: sshLocalModelDesc?.defaultEffort ?? null,
});
@@ -1736,16 +1800,33 @@ export function NewMakerDraftRoute() {
}
navigate(`/cc-agent/${newSession.id}`, {
replace: true,
- state: orcaWorkersRevealState
- ? { orcaWorkersReveal: orcaWorkersRevealState }
- : undefined,
+ state: orcaWorkersRevealState ? { orcaWorkersReveal: orcaWorkersRevealState } : undefined,
});
} catch (err) {
log.error('[add remote project]', err);
throw err;
}
},
- [draft.vendor, chatPrefs, chatInitialPermissionMode, chatInitialProviderId, draftInitialModel, draftInitialEffort, effectiveFastMode, effectiveDeviceLinkDeviceId, localProviders, localProvidersLoading, effectiveCollab, capabilityAgentKind, effectivePlanMode, attachmentState, applyDraftTarget, createSession, navigate, t],
+ [
+ draft.vendor,
+ chatPrefs,
+ chatInitialPermissionMode,
+ chatInitialProviderId,
+ draftInitialModel,
+ draftInitialEffort,
+ effectiveFastMode,
+ effectiveDeviceLinkDeviceId,
+ localProviders,
+ localProvidersLoading,
+ effectiveCollab,
+ capabilityAgentKind,
+ effectivePlanMode,
+ attachmentState,
+ applyDraftTarget,
+ createSession,
+ navigate,
+ t,
+ ],
);
// ─── 切 vendor ──────────────────────────────────────────────────────
@@ -1765,9 +1846,17 @@ export function NewMakerDraftRoute() {
useEffect(() => {
if (!availableAgentsLoaded) return;
if (!hiddenSwitcherVendors.includes(draft.vendor)) return;
- const fallback = (['cc', 'codex', 'pi'] as const).find((vendor) => availableVendors.has(vendor));
+ const fallback = (['cc', 'codex', 'pi'] as const).find((vendor) =>
+ availableVendors.has(vendor),
+ );
if (fallback && fallback !== draft.vendor) handleVendorChange(fallback);
- }, [availableAgentsLoaded, hiddenSwitcherVendors, availableVendors, draft.vendor, handleVendorChange]);
+ }, [
+ availableAgentsLoaded,
+ hiddenSwitcherVendors,
+ availableVendors,
+ draft.vendor,
+ handleVendorChange,
+ ]);
// ─── 用户在 ChatInput 改 model/effort/permission 后,落进当前 vendor 的 prefs ──
const patchActivePrefs = useCallback((patch: Partial<VendorPrefs>) => {
@@ -1985,7 +2074,7 @@ export function NewMakerDraftRoute() {
// 与「添加远程项目」那条路径的一点刻意差异:这里**不做**阻塞式 direct invoke 验证 ——
// pill 只让在线设备可选,而它是同步回调,为验证改成异步会让点击后一段时间毫无反馈。
// 快照未就绪期间由 send / goal 的 capabilitiesLoading / deviceProvidersLoading /
- // remoteDraftState.loaded 三重 gate 兜住。也因此不必 prefetch:上面已把「重选同一设备」
+ // remoteDraftState.status 三重 gate 兜住。也因此不必 prefetch:上面已把「重选同一设备」
// 早返回掉,deviceId 必然变化 → hook effect 必然重跑 → evict 后必然 cache miss 并自行 fetch。
applyDraftTarget({ deviceId, deviceName, workingDir: null });
},
@@ -2017,23 +2106,26 @@ export function NewMakerDraftRoute() {
// - source='branch-pick'(分支选择的双向联动)→ 仅本次草稿的 UI 态,不落记忆
// ——分支选择表达"这一次从哪启动",不改全局默认。
// 系统/环境路径没有任何入口能触达这里(不变量)。
- const handleWtEnabledChange = useCallback((enabled: boolean, source: 'chip' | 'branch-pick') => {
- setWtEnabled(enabled);
- if (source !== 'chip') return;
- if (isDeviceLinkDraft && effectiveDeviceLinkDeviceId) {
- remoteDraftRevisionRef.current += 1;
- window.electronAPI.deviceLink
- .invoke(effectiveDeviceLinkDeviceId, 'maker:apply-new-maker-worktree-pref', [
- { worktreeEnabled: enabled },
- ])
- .catch(() => {
- // 旧版被控端无此 channel(CHANNEL_NOT_ALLOWED)/ 隧道瞬断 → 勾选仅本次草稿
- // 生效,不打断用户;被控端后续 push 回流可能把 UI 收敛回旧值,属可接受降级。
- });
- return;
- }
- setWorktreePreference(enabled);
- }, [isDeviceLinkDraft, effectiveDeviceLinkDeviceId]);
+ const handleWtEnabledChange = useCallback(
+ (enabled: boolean, source: 'chip' | 'branch-pick') => {
+ setWtEnabled(enabled);
+ if (source !== 'chip') return;
+ if (isDeviceLinkDraft && effectiveDeviceLinkDeviceId) {
+ remoteDraftRevisionRef.current += 1;
+ window.electronAPI.deviceLink
+ .invoke(effectiveDeviceLinkDeviceId, 'maker:apply-new-maker-worktree-pref', [
+ { worktreeEnabled: enabled },
+ ])
+ .catch(() => {
+ // 旧版被控端无此 channel(CHANNEL_NOT_ALLOWED)/ 隧道瞬断 → 勾选仅本次草稿
+ // 生效,不打断用户;被控端后续 push 回流可能把 UI 收敛回旧值,属可接受降级。
+ });
+ return;
+ }
+ setWorktreePreference(enabled);
+ },
+ [isDeviceLinkDraft, effectiveDeviceLinkDeviceId],
+ );
const handleWtSourceBranchChange = useCallback((sourceBranch: string) => {
setWtSourceBranch(sourceBranch);
}, []);
@@ -2132,19 +2224,29 @@ export function NewMakerDraftRoute() {
);
return false;
}
- const shouldEnableCollab =
- effectiveCollab.enabled && collabPolicyEligible && policyEnabled;
+ const shouldEnableCollab = effectiveCollab.enabled && collabPolicyEligible && policyEnabled;
// device-link 切设备后,capabilities/providers hook 可能还没 re-render 到新设备快照;
// 此时 effectiveFastMode / supportsFastMode / sendProviderId 仍基于旧设备。
- // remoteDraftState.loaded 必须一起看:换设备时我们会把它打回未加载(防上一台的默认值串台),
+ // remoteDraftState 必须一起看:换设备时我们会把它打回 loading(防上一台的默认值串台),
// 而 capabilities / providers 若已缓存则这两个 loading 立刻就是 false —— 只看它们会在
// maker:get-new-maker-defaults 还没回来时放行,于是提交的是 deviceLinkInitial 的 capability
// 兜底值(model / effort / permission / provider),而不是那台设备自己保存的草稿值;
// 会话一旦建出来,晚到的响应也修不回去了。
- if (
- isDeviceLinkDraft &&
- (capabilitiesLoading || deviceProvidersLoading || !remoteDraftState.loaded)
- ) {
+ if (isDeviceLinkDraft && remoteModelListStatus !== 'ready') {
+ if (remoteModelListStatus === 'error') {
+ toast.error(t('newChat.modelSelector.remoteLoadFailed'));
+ } else {
+ toast.warning(t('ccAgent.draft.deviceStillLoading'));
+ }
+ return false;
+ }
+ if (isDeviceLinkDraft && remoteDraftState.status === 'error') {
+ setRemoteDraftRetryEpoch((value) => value + 1);
+ toast.error(t('ccAgent.draft.remoteDefaultsLoadFailed'));
+ return false;
+ }
+ if (isDeviceLinkDraft && remoteDraftState.status !== 'ready') {
+ toast.warning(t('ccAgent.draft.deviceStillLoading'));
return false;
}
// 草稿里选定的来源(供应商):ChatInput 在发送时把"仍连接的显式选择"经 opts 传上来
@@ -2174,10 +2276,9 @@ export function NewMakerDraftRoute() {
// 混合目标创建。这里与 selectedWorkingDir 同步快照,保证整笔创建目标一致。
const selectedWorktree = { ...wtRef.current };
const dataOwnerAtSend = getDataOwnerGeneration();
- const isCurrentDataOwner = () => (
- dataOwnerAtSend.dataOwnerId === dataOwnerId
- && isDataOwnerGenerationCurrent(dataOwnerAtSend)
- );
+ const isCurrentDataOwner = () =>
+ dataOwnerAtSend.dataOwnerId === dataOwnerId &&
+ isDataOwnerGenerationCurrent(dataOwnerAtSend);
markSendInFlight(true);
// 已登记乐观标题预览的会话 id。交接链路(rehomeDraftAttachments / setPending /
@@ -2225,19 +2326,21 @@ export function NewMakerDraftRoute() {
const ownerAtSend = dataOwnerAtSend.dataOwnerId;
let remoteWorkingDir = effectiveWorkingDir?.trim() || undefined;
let presetSessionId: string | undefined;
- let precreatedWorktree: {
- path: string;
- recoveryKey: string;
- createdAt: number;
- } | undefined;
+ let precreatedWorktree:
+ | {
+ path: string;
+ recoveryKey: string;
+ createdAt: number;
+ }
+ | undefined;
// 生效条件 = 勾选 && baseRepo 已就绪 && 被控端明确支持 recoveryKey discard。
// 旧 Desktop 可能接受未知 recoveryKey 却不持久化,不能把它当成支持端发起
// 预创建;能力不合格 / 探测未回时静默按普通方式启动,不报错不改勾选记忆。
if (
- effectiveWorkingDir
- && wt.enabled
- && wt.baseRepo
- && wt.supportsRecoveryKeyDiscard === true
+ effectiveWorkingDir &&
+ wt.enabled &&
+ wt.baseRepo &&
+ wt.supportsRecoveryKeyDiscard === true
) {
// 账本必须绑定发起时的账号/本地数据 owner。账号在后续 await
// 期间切换时,Main 会拒绝把这笔义务落入新 owner 的命名空间。
@@ -2292,18 +2395,15 @@ export function NewMakerDraftRoute() {
}
setWtCreating(true);
try {
- const resp = (await invokeRemote(
- 'worktree:create',
- [
- {
- sessionId: presetSessionId,
- baseRepo,
- name,
- sourceBranch: wt.sourceBranch.trim() || 'HEAD',
- recoveryKey,
- },
- ],
- )) as CreateWorktreeResp | null;
+ const resp = (await invokeRemote('worktree:create', [
+ {
+ sessionId: presetSessionId,
+ baseRepo,
+ name,
+ sourceBranch: wt.sourceBranch.trim() || 'HEAD',
+ recoveryKey,
+ },
+ ])) as CreateWorktreeResp | null;
if (!resp) {
throw new RemotePrecreatedWorktreeCleanupPendingError();
}
@@ -2377,22 +2477,23 @@ export function NewMakerDraftRoute() {
capabilityAgentKind,
});
let created: { sessionId?: string; workDir?: string } | null = null;
- const remoteSessionId = presetSessionId && precreatedWorktree
- ? await createRemoteSessionWithPrecreatedWorktree({
- deviceId,
- sessionId: presetSessionId,
- path: precreatedWorktree.path,
- recoveryKey: precreatedWorktree.recoveryKey,
- ...(ownerAtSend ? { dataOwnerId: ownerAtSend } : {}),
- createdAt: precreatedWorktree.createdAt,
- createArgs: createArgs,
- invoke: invokeRemote,
- isCurrent: isCurrentDataOwner,
- })
- : (created = (await invokeRemote('maker:create-session', [createArgs])) as {
- sessionId?: string;
- workDir?: string;
- } | null)?.sessionId;
+ const remoteSessionId =
+ presetSessionId && precreatedWorktree
+ ? await createRemoteSessionWithPrecreatedWorktree({
+ deviceId,
+ sessionId: presetSessionId,
+ path: precreatedWorktree.path,
+ recoveryKey: precreatedWorktree.recoveryKey,
+ ...(ownerAtSend ? { dataOwnerId: ownerAtSend } : {}),
+ createdAt: precreatedWorktree.createdAt,
+ createArgs: createArgs,
+ invoke: invokeRemote,
+ isCurrent: isCurrentDataOwner,
+ })
+ : (created = (await invokeRemote('maker:create-session', [createArgs])) as {
+ sessionId?: string;
+ workDir?: string;
+ } | null)?.sessionId;
if (presetSessionId && precreatedWorktree) {
created = { sessionId: remoteSessionId, workDir: remoteWorkingDir };
}
@@ -2648,7 +2749,11 @@ export function NewMakerDraftRoute() {
try {
const result = await window.electronAPI.maker.enableOrca(
newSession.id,
- draftEnableOrcaOptions(effectiveCollab, localProviders, !localProvidersLoading),
+ draftEnableOrcaOptions(
+ effectiveCollab,
+ localProviders,
+ !localProvidersLoading,
+ ),
);
// worktree 创建在后台完成,组件可能已经切走;这里读取当前 URL,
// 避免用 render 时捕获的旧路由误判。
@@ -2822,10 +2927,7 @@ export function NewMakerDraftRoute() {
toast.error(
isRemotePrecreatedWorktreeCleanupPendingError(err)
? t('ccAgent.draft.remoteWorktreeCleanupPending')
- : (
- getRemoteWorkingDirErrorMessage(err, t)
- ?? t('ccAgent.draft.createSessionFailed')
- ),
+ : (getRemoteWorkingDirErrorMessage(err, t) ?? t('ccAgent.draft.createSessionFailed')),
);
} finally {
setWtCreating(false);
@@ -2842,8 +2944,8 @@ export function NewMakerDraftRoute() {
effectiveRemoteHostId,
isRemoteProjectDraft,
isDeviceLinkDraft,
- capabilitiesLoading,
- remoteDraftState.loaded,
+ remoteModelListStatus,
+ remoteDraftState.status,
deviceProviders,
deviceProvidersLoading,
effectiveDeviceLinkDeviceId,
@@ -2932,13 +3034,19 @@ export function NewMakerDraftRoute() {
throw new Error(t('newChat.collaboration.disabledHint'));
}
}
- const shouldEnableCollab =
- effectiveCollab.enabled && collabPolicyEligible && policyEnabled;
+ const shouldEnableCollab = effectiveCollab.enabled && collabPolicyEligible && policyEnabled;
// 同 handleSend:remoteDraftState 未就绪时不得放行,否则提交 capability 兜底值而非该设备的
// 草稿值(缓存已热时另两个 loading 会立刻为 false,拦不住)。
+ if (isDeviceLinkDraft && remoteModelListStatus === 'error') {
+ throw new Error(t('newChat.modelSelector.remoteLoadFailed'));
+ }
+ if (isDeviceLinkDraft && remoteDraftState.status === 'error') {
+ setRemoteDraftRetryEpoch((value) => value + 1);
+ throw new Error(t('ccAgent.draft.remoteDefaultsLoadFailed'));
+ }
if (
isDeviceLinkDraft &&
- (capabilitiesLoading || deviceProvidersLoading || !remoteDraftState.loaded)
+ (remoteModelListStatus !== 'ready' || remoteDraftState.status !== 'ready')
) {
throw new Error(t('ccAgent.draft.deviceStillLoading'));
}
@@ -2974,15 +3082,13 @@ export function NewMakerDraftRoute() {
deviceProviders,
capabilityAgentKind,
});
- const createResult = await window.electronAPI.deviceLink.invoke(
- deviceId,
- 'maker:create-session',
- [createArgs],
- ).catch((err) => {
- const remoteWorkdirMessage = getRemoteWorkingDirErrorMessage(err, t);
- if (remoteWorkdirMessage) throw new Error(remoteWorkdirMessage);
- throw err;
- });
+ const createResult = await window.electronAPI.deviceLink
+ .invoke(deviceId, 'maker:create-session', [createArgs])
+ .catch((err) => {
+ const remoteWorkdirMessage = getRemoteWorkingDirErrorMessage(err, t);
+ if (remoteWorkdirMessage) throw new Error(remoteWorkdirMessage);
+ throw err;
+ });
const created = createResult as { sessionId?: string; workDir?: string } | null;
const remoteSessionId = created?.sessionId;
if (!remoteSessionId) {
@@ -3150,7 +3256,9 @@ export function NewMakerDraftRoute() {
orcaWorkersRevealState = { focusWorkerSessionId: result.workerSessionId };
} catch (err) {
log.error('[draft goal] enableOrca failed (continuing as single session)', err);
- toast.error(getCollaborationStartErrorMessage(err, t, { continueAsSingleSession: true }));
+ toast.error(
+ getCollaborationStartErrorMessage(err, t, { continueAsSingleSession: true }),
+ );
}
}
// setGoal 内部 ensureSession(拉起 agent)+ 发首轮(带目标指令)。
@@ -3170,9 +3278,7 @@ export function NewMakerDraftRoute() {
resetDraftWorkspaceAfterSend();
navigate(`/cc-agent/${newSession.id}`, {
replace: true,
- state: orcaWorkersRevealState
- ? { orcaWorkersReveal: orcaWorkersRevealState }
- : undefined,
+ state: orcaWorkersRevealState ? { orcaWorkersReveal: orcaWorkersRevealState } : undefined,
});
} finally {
markSendInFlight(false);
@@ -3181,8 +3287,8 @@ export function NewMakerDraftRoute() {
[
markSendInFlight,
isDeviceLinkDraft,
- capabilitiesLoading,
- remoteDraftState.loaded,
+ remoteModelListStatus,
+ remoteDraftState.status,
deviceProviders,
deviceProvidersLoading,
vendorAuthGate,
@@ -3408,7 +3514,9 @@ export function NewMakerDraftRoute() {
// hasAnyRemoteTarget 影响 —— 它会在该设备离线时变 false,把「浏览文件夹」推回
// 本机原生对话框(见 FolderPickerPopover.handleChooseDifferent 的同款防护)。
onAddRemoteProject={
- hasAnyRemoteTarget || folderPickerDeviceScope ? handleOpenRemoteProject : undefined
+ hasAnyRemoteTarget || folderPickerDeviceScope
+ ? handleOpenRemoteProject
+ : undefined
}
side="bottom"
align="end"
@@ -3426,9 +3534,7 @@ export function NewMakerDraftRoute() {
strokeWidth={2}
className="shrink-0 text-[var(--create-agent-control-icon)]"
/>
- <span className="min-w-0 truncate">
- {createAgentModeLabel}
- </span>
+ <span className="min-w-0 truncate">{createAgentModeLabel}</span>
<ChevronDown
size={12}
strokeWidth={2}
@@ -3463,7 +3569,9 @@ export function NewMakerDraftRoute() {
className={cn('mb-[15px]', isDraftNarrow && 'order-1')}
/>
- <div className={cn('flex w-full flex-col items-start gap-0', isDraftNarrow && 'order-3')}>
+ <div
+ className={cn('flex w-full flex-col items-start gap-0', isDraftNarrow && 'order-3')}
+ >
<div className="w-full">
<ChatInput
onSend={handleSend}
@@ -3534,16 +3642,15 @@ export function NewMakerDraftRoute() {
// unsupported(被控端版本过旧、没有 maker:plugins:get-state)排在
// unavailable 之前:它是确定性的不支持,给「稍后重试」是误导,
// 上面的 onDisabledActivate 也只挂在 unavailable 上。
- disabledReason:
- collabPolicy.loading
- ? t('newChat.collaboration.loadingHint')
- : collabPolicy.unsupported
- ? t('newChat.collaboration.unsupportedRemoteHint')
- : collabPolicy.unavailable
- ? t('newChat.collaboration.unavailableHint')
- : !collabPolicy.enabled
- ? t('newChat.collaboration.disabledHint')
- : undefined,
+ disabledReason: collabPolicy.loading
+ ? t('newChat.collaboration.loadingHint')
+ : collabPolicy.unsupported
+ ? t('newChat.collaboration.unsupportedRemoteHint')
+ : collabPolicy.unavailable
+ ? t('newChat.collaboration.unavailableHint')
+ : !collabPolicy.enabled
+ ? t('newChat.collaboration.disabledHint')
+ : undefined,
}
: undefined
}
@@ -3644,7 +3751,11 @@ export function NewMakerDraftRoute() {
<div
className={cn(
'grid w-full gap-3',
- isDraftNarrow ? 'grid-cols-1' : isDraftMedium ? 'grid-cols-2' : 'grid-cols-4',
+ isDraftNarrow
+ ? 'grid-cols-1'
+ : isDraftMedium
+ ? 'grid-cols-2'
+ : 'grid-cols-4',
)}
>
{createAgentQuickStarts.map(({ key, labelKey, icon: Icon }) => (
diff --git a/apps/desktop/src/renderer/features/cc-agent/__tests__/workerModelAvailability.test.ts b/apps/desktop/src/renderer/features/cc-agent/__tests__/workerModelAvailability.test.ts
index fff29041f6..63ff972aae 100644
--- a/apps/desktop/src/renderer/features/cc-agent/__tests__/workerModelAvailability.test.ts
+++ b/apps/desktop/src/renderer/features/cc-agent/__tests__/workerModelAvailability.test.ts
@@ -135,10 +135,25 @@ describe('selectWorkerModels', () => {
providers: [],
providersLoading: false,
providersError: 'unknown channel',
+ providersUnsupported: true,
}),
).toEqual([standard, budget]);
});
+ it('fails closed when the controlled-device provider list has a real read error', () => {
+ expect(
+ selectWorkerModels({
+ agent: 'codex',
+ capabilities: caps,
+ deviceId: 'offline-device',
+ providers: [provider('openai', true, 'codex', [standard])],
+ providersLoading: false,
+ providersError: 'proxy policy: request not allowed remotely',
+ providersUnsupported: false,
+ }),
+ ).toEqual([]);
+ });
+
it('does not submit a stale selection while a new device provider snapshot is loading', () => {
expect(
selectWorkerModels({
diff --git a/apps/desktop/src/renderer/features/cc-agent/workerModelAvailability.ts b/apps/desktop/src/renderer/features/cc-agent/workerModelAvailability.ts
index a0975f684b..77eb42fb2b 100644
--- a/apps/desktop/src/renderer/features/cc-agent/workerModelAvailability.ts
+++ b/apps/desktop/src/renderer/features/cc-agent/workerModelAvailability.ts
@@ -16,6 +16,8 @@ export interface SelectWorkerModelsOptions {
providers: ProviderView[];
providersLoading: boolean;
providersError: string | null;
+ /** 仅结构化确认旧端没有 provider:list 时允许 capabilities-only 回退。 */
+ providersUnsupported?: boolean;
/** Local-only provider model visibility. Device-link peers own their own visibility choices. */
isVisible?: (providerId: string, model: CatalogModel) => boolean;
/**
@@ -48,6 +50,7 @@ export function selectWorkerModels({
providers,
providersLoading,
providersError,
+ providersUnsupported,
isVisible,
excludeSubscriptionDirect,
excludeChatBridgedCodex,
@@ -74,7 +77,7 @@ export function selectWorkerModels({
: selectable;
}
- if (providersError) return models;
+ if (providersError) return providersUnsupported ? models : [];
if (providersLoading) return [];
const executableIds = new Set(
diff --git a/apps/desktop/src/renderer/features/device-link/refreshRemoteSessions.ts b/apps/desktop/src/renderer/features/device-link/refreshRemoteSessions.ts
index 05863c2c1e..f95b4a801d 100644
--- a/apps/desktop/src/renderer/features/device-link/refreshRemoteSessions.ts
+++ b/apps/desktop/src/renderer/features/device-link/refreshRemoteSessions.ts
@@ -19,6 +19,7 @@ import type { Session } from '@/lib/ccAgent.types';
import { createLogger } from '@/lib/logger';
import { extractIpcError } from '@/utils/ipcError';
import { DEVICE_LINK_RECONCILIATION_PROBE_MARKER } from '@cindy/maker-shared/device-link-contract';
+import type { RemoteSessionListSessionLike } from '@cindy/maker-shared/session-list';
import { remoteProjectsStore } from './remoteProjectsStore';
import { removeRemoteSessionActivityEntry } from './remoteSessionActivityStore';
import type { CachedDeviceSessionsSnapshot } from './mirrorCacheClient';
@@ -82,6 +83,89 @@ export function isTransientRemoteError(message: string): boolean {
return TRANSIENT_MARKERS.some((m) => message.includes(m));
}
+function isNullableString(value: unknown): value is string | null {
+ return value === null || typeof value === 'string';
+}
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return !!value && typeof value === 'object' && !Array.isArray(value);
+}
+
+function hasOptionalNullableString(record: Record<string, unknown>, key: string): boolean {
+ return record[key] === undefined || isNullableString(record[key]);
+}
+
+function hasOptionalBoolean(record: Record<string, unknown>, key: string): boolean {
+ return record[key] === undefined || typeof record[key] === 'boolean';
+}
+
+function hasOptionalFiniteNumber(record: Record<string, unknown>, key: string): boolean {
+ const value = record[key];
+ return (
+ value === undefined || value === null || (typeof value === 'number' && Number.isFinite(value))
+ );
+}
+
+function isRemoteSessionListSession(value: unknown): value is RemoteSessionListSessionLike {
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return false;
+ const session = value as Record<string, unknown>;
+ const count = session._count;
+ return (
+ typeof session.id === 'string' &&
+ session.id.length > 0 &&
+ typeof session.title === 'string' &&
+ isNullableString(session.workingDir) &&
+ typeof session.model === 'string' &&
+ session.status === 'active' &&
+ typeof session.agentKind === 'string' &&
+ typeof session.createdAt === 'string' &&
+ typeof session.updatedAt === 'string' &&
+ (session.userId === undefined || typeof session.userId === 'string') &&
+ hasOptionalNullableString(session, 'workspaceKind') &&
+ hasOptionalNullableString(session, 'effort') &&
+ hasOptionalNullableString(session, 'permissionMode') &&
+ hasOptionalNullableString(session, 'sdkSessionId') &&
+ hasOptionalNullableString(session, 'clearedAt') &&
+ hasOptionalNullableString(session, 'pinnedAt') &&
+ hasOptionalNullableString(session, 'userSendAt') &&
+ hasOptionalNullableString(session, 'source') &&
+ hasOptionalNullableString(session, 'orcaRole') &&
+ hasOptionalNullableString(session, 'providerId') &&
+ hasOptionalNullableString(session, 'parentSessionId') &&
+ hasOptionalNullableString(session, 'forkedAtMessageId') &&
+ hasOptionalNullableString(session, 'worktreePath') &&
+ hasOptionalNullableString(session, 'remoteHostId') &&
+ hasOptionalNullableString(session, 'preview') &&
+ hasOptionalNullableString(session, 'summary') &&
+ hasOptionalBoolean(session, 'fastMode') &&
+ hasOptionalBoolean(session, 'planModeEnabled') &&
+ hasOptionalBoolean(session, 'usedProjectContext') &&
+ hasOptionalFiniteNumber(session, 'totalTokenUsage') &&
+ hasOptionalFiniteNumber(session, 'totalCostUsd') &&
+ hasOptionalFiniteNumber(session, 'contextTokens') &&
+ hasOptionalFiniteNumber(session, 'contextWindow') &&
+ hasOptionalFiniteNumber(session, 'activeTurnStartedAt') &&
+ hasOptionalFiniteNumber(session, 'lastTurnEndedAt') &&
+ (session.extraDirs === undefined ||
+ (Array.isArray(session.extraDirs) &&
+ session.extraDirs.every((dir) => typeof dir === 'string'))) &&
+ (count === undefined ||
+ count === null ||
+ (isRecord(count) &&
+ (count.messages === undefined ||
+ (typeof count.messages === 'number' && Number.isFinite(count.messages)))))
+ );
+}
+
+function parseRemoteSessionList(value: unknown): Session[] {
+ if (!Array.isArray(value) || !value.every(isRemoteSessionListSession)) {
+ throw new Error('Invalid remote sessions response');
+ }
+ // local-db:sessions:list 是跨版本的列表投影;旧端允许缺少新版 Session 的附加字段。
+ // 上面的 guard 锁住列表渲染与分组所需的最低形状,store 继续沿用既有 Session 镜像类型。
+ return value as unknown as Session[];
+}
+
/** 退避:250ms 起指数增长,封顶 3000ms。 */
function backoffMs(attempt: number): number {
return Math.min(250 * 2 ** attempt, 3000);
@@ -278,36 +362,34 @@ async function runRefreshRemoteDeviceSessions(
// 被一次更新的重拉取代(期间又发起了新的 refresh)→ 停手,交给那一次(也避免无谓重试)。
if (!remoteProjectsStore.isLatestSnapshotEpoch(deviceId, epoch)) return 'superseded';
try {
- const list = await window.electronAPI.deviceLink.invoke(deviceId, 'local-db:sessions:list', [
+ const value = await window.electronAPI.deviceLink.invoke(deviceId, 'local-db:sessions:list', [
LIST_LIMIT,
'active',
{ includePinned: true },
]);
// 乱序保护:本次拉取已不是最新一次 → 丢弃,别覆盖更新的结果。
if (!remoteProjectsStore.isLatestSnapshotEpoch(deviceId, epoch)) return 'superseded';
- if (Array.isArray(list)) {
- if ((opts.snapshotMode ?? 'merge') === 'merge') {
- const sessions = list as Session[];
- const incomingIds = new Set(sessions.map((session) => session.id));
- const missingSessionIds = remoteProjectsStore
- .getDeviceSessions(deviceId)
- .filter((session) => !incomingIds.has(session.id))
- .map((session) => session.id);
- // 未满 LIST_LIMIT 证明 active 集合完整,可安全 replace 并清掉缺席的归档/删除行。
- // 满窗口时先 merge,再用既有只读 sessions:get 有界轮询窗口外缓存 id 的终态。
- if (sessions.length < LIST_LIMIT) {
- missingStatusProbeQueues.delete(deviceId);
- remoteProjectsStore.setDeviceSessions(deviceId, deviceName, sessions);
- for (const sessionId of missingSessionIds) {
- removeRemoteSessionActivityEntry(sessionId);
- }
- } else {
- remoteProjectsStore.mergeDeviceSessions(deviceId, deviceName, sessions);
- await probeMissingSessionStatuses(deviceId, epoch, missingSessionIds);
+ const sessions = parseRemoteSessionList(value);
+ if ((opts.snapshotMode ?? 'merge') === 'merge') {
+ const incomingIds = new Set(sessions.map((session) => session.id));
+ const missingSessionIds = remoteProjectsStore
+ .getDeviceSessions(deviceId)
+ .filter((session) => !incomingIds.has(session.id))
+ .map((session) => session.id);
+ // 未满 LIST_LIMIT 证明 active 集合完整,可安全 replace 并清掉缺席的归档/删除行。
+ // 满窗口时先 merge,再用既有只读 sessions:get 有界轮询窗口外缓存 id 的终态。
+ if (sessions.length < LIST_LIMIT) {
+ missingStatusProbeQueues.delete(deviceId);
+ remoteProjectsStore.setDeviceSessions(deviceId, deviceName, sessions);
+ for (const sessionId of missingSessionIds) {
+ removeRemoteSessionActivityEntry(sessionId);
}
} else {
- remoteProjectsStore.setDeviceSessions(deviceId, deviceName, list as Session[]);
+ remoteProjectsStore.mergeDeviceSessions(deviceId, deviceName, sessions);
+ await probeMissingSessionStatuses(deviceId, epoch, missingSessionIds);
}
+ } else {
+ remoteProjectsStore.setDeviceSessions(deviceId, deviceName, sessions);
}
return 'ok'; // 成功
} catch (err) {
diff --git a/apps/desktop/src/renderer/features/device-link/remoteProjectsStore.ts b/apps/desktop/src/renderer/features/device-link/remoteProjectsStore.ts
index bfeb81ee7d..baf66ef3a8 100644
--- a/apps/desktop/src/renderer/features/device-link/remoteProjectsStore.ts
+++ b/apps/desktop/src/renderer/features/device-link/remoteProjectsStore.ts
@@ -50,11 +50,16 @@ interface DeviceShard {
const shards = new Map<string, DeviceShard>();
const subs = new Set<() => void>();
/**
- * 已完成一次 bootstrap、但以永久错误或重试耗尽告终且尚无权威 sessions shard 的设备。
- * 这不是「权威空列表」:仅用于让侧边栏结束无限 loading;下一次 reconnect/bootstrap
- * 开始时会清掉,成功 snapshot 也会清掉。
+ * 正在读取任务快照的设备。它与 shard 是否存在独立:重连或手动重试时可以
+ * 一边保留旧快照、一边明确告知用户「正在重新读取」。
+ */
+let bootstrapLoadingDeviceIds: ReadonlySet<string> = new Set();
+/**
+ * 最新一轮 bootstrap 以永久错误或重试耗尽告终的设备。这不是「权威空列表」;
+ * 即使还保留旧 shard,UI 也必须标明读取失败。下一轮 bootstrap 开始时转 loading,
+ * 成功 snapshot 才回到 ready。
*
- * 用不可变 Set 快照,保证 useSyncExternalStore 在内容不变时引用稳定。
+ * 两个集合都用不可变 Set 快照,保证 useSyncExternalStore 在内容不变时引用稳定。
*/
let bootstrapFailedDeviceIds: ReadonlySet<string> = new Set();
/**
@@ -82,6 +87,12 @@ const snapshotEpoch = new Map<string, number>();
* sessions:created 路由、applyPatch 的 unarchive 兜底)调用,不直接依赖 hook。
*/
let reseedImpl: ((deviceId: string) => void) | null = null;
+/**
+ * 首次 sessions bootstrap 的显式重试实现。与普通 reseed 分开:普通 reseed 只做一次
+ * merge snapshot;用户点击「重新读取任务」必须重新 subscribe,并让失败设备重新进入
+ * bootstrap loading,完整语义由 listing tier 的 subscribeAndBootstrap 承担。
+ */
+let bootstrapRetryImpl: ((deviceId: string) => void) | null = null;
/** 扁平合并快照(缓存引用,变化时才换新)。 */
let mergedSnapshot: Session[] = [];
@@ -204,7 +215,8 @@ const pendingTitlePreview = new Map<string, string>();
/** 该标题是否仍属"系统占位"(可被预览顶替)。 */
function isSystemOwnedTitle(session: Pick<Session, 'id' | 'title' | 'parentSessionId'>): boolean {
if (session.title === DEFAULT_REMOTE_SESSION_TITLE) return true;
- if (session.parentSessionId && session.title.startsWith(FORK_PLACEHOLDER_TITLE_PREFIX)) return true;
+ if (session.parentSessionId && session.title.startsWith(FORK_PLACEHOLDER_TITLE_PREFIX))
+ return true;
return landedSystemTitles.get(session.id) === session.title;
}
@@ -281,14 +293,26 @@ function recompute(): void {
subs.forEach((fn) => fn());
}
-/** 更新 bootstrap 失败快照但不通知;调用方与其它 mutation 合并成一次通知。 */
-function setBootstrapFailed(deviceId: string, failed: boolean): boolean {
- const has = bootstrapFailedDeviceIds.has(deviceId);
- if (has === failed) return false;
- const next = new Set(bootstrapFailedDeviceIds);
- if (failed) next.add(deviceId);
- else next.delete(deviceId);
- bootstrapFailedDeviceIds = next;
+/** 更新 bootstrap 状态但不通知;调用方与其它 mutation 合并成一次通知。 */
+function setBootstrapState(deviceId: string, state: 'idle' | 'loading' | 'failed'): boolean {
+ const wasLoading = bootstrapLoadingDeviceIds.has(deviceId);
+ const wasFailed = bootstrapFailedDeviceIds.has(deviceId);
+ const loading = state === 'loading';
+ const failed = state === 'failed';
+ if (wasLoading === loading && wasFailed === failed) return false;
+
+ if (wasLoading !== loading) {
+ const next = new Set(bootstrapLoadingDeviceIds);
+ if (loading) next.add(deviceId);
+ else next.delete(deviceId);
+ bootstrapLoadingDeviceIds = next;
+ }
+ if (wasFailed !== failed) {
+ const next = new Set(bootstrapFailedDeviceIds);
+ if (failed) next.add(deviceId);
+ else next.delete(deviceId);
+ bootstrapFailedDeviceIds = next;
+ }
return true;
}
@@ -318,14 +342,14 @@ const actions = {
const connectionStatus: DeviceLinkConnectionStatus = 'connected';
const stamped = rawSessions.map((s) => stamp(s, deviceId, deviceName, connectionStatus));
const existing = shards.get(deviceId);
- const failureCleared = setBootstrapFailed(deviceId, false);
+ const bootstrapStateCleared = setBootstrapState(deviceId, 'idle');
if (
existing &&
existing.connectionStatus === connectionStatus &&
JSON.stringify(existing.sessions) === JSON.stringify(stamped)
) {
// 内容不变但设备名可能变了(改名走 renameDevice,不经这里);保持引用不动。
- if (failureCleared) subs.forEach((fn) => fn());
+ if (bootstrapStateCleared) subs.forEach((fn) => fn());
return;
}
// 权威快照会整片替换分片:此前在片里、这次没回来的会话(patch 丢失期间被归档 /
@@ -373,15 +397,24 @@ const actions = {
if (changed) recompute();
},
- /** bootstrap 永久失败 / 重试耗尽且没有 sessions shard:记录终态,避免侧边栏无限 loading。 */
+ /** 新一轮 bootstrap 开始:保留旧 shard,但显式进入读取中。 */
+ markBootstrapLoading(deviceId: string): void {
+ if (!setBootstrapState(deviceId, 'loading')) return;
+ subs.forEach((fn) => fn());
+ },
+
+ /** bootstrap 永久失败 / 重试耗尽:保留旧 shard,但标明它不是本轮权威结果。 */
markBootstrapFailed(deviceId: string): void {
- if (!setBootstrapFailed(deviceId, true)) return;
+ if (!setBootstrapState(deviceId, 'failed')) return;
subs.forEach((fn) => fn());
},
- /** 新一轮 bootstrap 开始或 snapshot 成功:重新进入等待 / 已同步状态。 */
+ /** 只清失败标记的兼容入口;snapshot 成功会由 setDeviceSessions 清掉全部 bootstrap 状态。 */
clearBootstrapFailure(deviceId: string): void {
- if (!setBootstrapFailed(deviceId, false)) return;
+ if (!bootstrapFailedDeviceIds.has(deviceId)) return;
+ const next = new Set(bootstrapFailedDeviceIds);
+ next.delete(deviceId);
+ bootstrapFailedDeviceIds = next;
subs.forEach((fn) => fn());
},
@@ -477,8 +510,12 @@ const actions = {
*/
markDeviceDisconnected(deviceId: string): void {
snapshotEpoch.set(deviceId, (snapshotEpoch.get(deviceId) ?? 0) + 1);
+ const bootstrapStateCleared = setBootstrapState(deviceId, 'idle');
const shard = shards.get(deviceId);
- if (!shard || shard.connectionStatus === 'disconnected') return;
+ if (!shard || shard.connectionStatus === 'disconnected') {
+ if (bootstrapStateCleared) subs.forEach((fn) => fn());
+ return;
+ }
shard.connectionStatus = 'disconnected';
shard.sessions = shard.sessions.map((s) => ({
...s,
@@ -490,18 +527,23 @@ const actions = {
/** 标记全部已缓存远程设备暂不可达,但不清空侧边栏会话快照。 */
markAllDisconnected(): void {
for (const [k, v] of snapshotEpoch) snapshotEpoch.set(k, v + 1);
- let changed = false;
+ const bootstrapStateChanged =
+ bootstrapLoadingDeviceIds.size > 0 || bootstrapFailedDeviceIds.size > 0;
+ if (bootstrapLoadingDeviceIds.size > 0) bootstrapLoadingDeviceIds = new Set();
+ if (bootstrapFailedDeviceIds.size > 0) bootstrapFailedDeviceIds = new Set();
+ let shardChanged = false;
for (const shard of shards.values()) {
if (!snapshotEpoch.has(shard.deviceId)) snapshotEpoch.set(shard.deviceId, 1);
if (shard.connectionStatus === 'disconnected') continue;
- changed = true;
+ shardChanged = true;
shard.connectionStatus = 'disconnected';
shard.sessions = shard.sessions.map((s) => ({
...s,
deviceLinkConnectionStatus: 'disconnected',
}));
}
- if (changed) recompute();
+ if (shardChanged) recompute();
+ else if (bootstrapStateChanged) subs.forEach((fn) => fn());
},
/** 移除某台设备的所有远端会话(访问撤销 / 关被控 / 本机禁用控制 / 删除)。 */
@@ -516,9 +558,9 @@ const actions = {
dropTitleOverlay(session.id);
}
const shardDeleted = shards.delete(deviceId);
- const failureCleared = setBootstrapFailed(deviceId, false);
+ const bootstrapStateCleared = setBootstrapState(deviceId, 'idle');
if (shardDeleted) recompute();
- else if (failureCleared) subs.forEach((fn) => fn());
+ else if (bootstrapStateCleared) subs.forEach((fn) => fn());
},
/** 清空所有远端项目(登出 / device-link stopped / 卸载)。 */
@@ -531,10 +573,12 @@ const actions = {
pendingTitlePreview.clear();
landedSystemTitles.clear();
synthesizedPreviewSessions.clear();
- const failureChanged = bootstrapFailedDeviceIds.size > 0;
- if (failureChanged) bootstrapFailedDeviceIds = new Set();
+ const bootstrapStateChanged =
+ bootstrapLoadingDeviceIds.size > 0 || bootstrapFailedDeviceIds.size > 0;
+ if (bootstrapLoadingDeviceIds.size > 0) bootstrapLoadingDeviceIds = new Set();
+ if (bootstrapFailedDeviceIds.size > 0) bootstrapFailedDeviceIds = new Set();
if (shards.size === 0) {
- if (failureChanged) subs.forEach((fn) => fn());
+ if (bootstrapStateChanged) subs.forEach((fn) => fn());
return;
}
shards.clear();
@@ -656,7 +700,12 @@ const actions = {
return deviceListSnapshot;
},
- /** 机器切换栏 loading 判定用:已终态失败且尚无权威 sessions shard 的设备 id。 */
+ /** 正在读取任务快照的设备 id(可同时保留旧 shard)。 */
+ getBootstrapLoadingDeviceIds(): ReadonlySet<string> {
+ return bootstrapLoadingDeviceIds;
+ },
+
+ /** 最新一轮任务快照已终态失败的设备 id(可同时保留旧 shard)。 */
getBootstrapFailedDeviceIds(): ReadonlySet<string> {
return bootstrapFailedDeviceIds;
},
@@ -694,6 +743,11 @@ export function setRemoteReseedImpl(fn: ((deviceId: string) => void) | null): vo
reseedImpl = fn;
}
+/** listing tier 挂载时注册「重试首次 sessions bootstrap」实现;卸载时传 null 清。 */
+export function setRemoteSessionBootstrapRetryImpl(fn: ((deviceId: string) => void) | null): void {
+ bootstrapRetryImpl = fn;
+}
+
/**
* 请求重拉某被控设备的会话列表(reconcile)。由 push 消费侧调用:
* - `sessions:created`(无 row 数据)→ 重拉该设备;
@@ -704,6 +758,11 @@ export function requestRemoteReseed(deviceId: string): void {
reseedImpl?.(deviceId);
}
+/** 用户可见错误态的重试入口:重新订阅并拉取该设备的首次任务快照。 */
+export function retryRemoteSessionBootstrap(deviceId: string): void {
+ bootstrapRetryImpl?.(deviceId);
+}
+
/** 组件内订阅:返回扁平远端会话快照(喂给 sidebar 合并点)。 */
export function useRemoteProjectSessions(): Session[] {
return useSyncExternalStore(subscribe, actions.getMergedRemoteSessions);
@@ -719,6 +778,11 @@ export function useRemoteBootstrapFailedDeviceIds(): ReadonlySet<string> {
return useSyncExternalStore(subscribe, actions.getBootstrapFailedDeviceIds);
}
+/** 组件内订阅:当前正在重新读取任务快照的设备集合。 */
+export function useRemoteBootstrapLoadingDeviceIds(): ReadonlySet<string> {
+ return useSyncExternalStore(subscribe, actions.getBootstrapLoadingDeviceIds);
+}
+
/** 非组件上下文(presence 订阅器 / 传输层)读写入口。 */
export const remoteProjectsStore = { ...actions, subscribe, subscribeRename };
diff --git a/apps/desktop/src/renderer/features/device-link/useDeviceLinkDeviceList.ts b/apps/desktop/src/renderer/features/device-link/useDeviceLinkDeviceList.ts
index 10f9176cd8..9933298201 100644
--- a/apps/desktop/src/renderer/features/device-link/useDeviceLinkDeviceList.ts
+++ b/apps/desktop/src/renderer/features/device-link/useDeviceLinkDeviceList.ts
@@ -19,9 +19,16 @@ import { useSyncExternalStore } from 'react';
let devices: DeviceLinkDeviceView[] | null = null;
const subs = new Set<() => void>();
let started = false;
+export type DeviceLinkDeviceListStatus = 'loading' | 'ready' | 'error';
+export interface DeviceLinkDeviceListRequestState {
+ status: DeviceLinkDeviceListStatus;
+ error: string | null;
+}
+let requestState: DeviceLinkDeviceListRequestState = { status: 'loading', error: null };
+let refreshImpl: (() => void) | null = null;
/**
* 设备目录是否已进入终态 —— 上层(shouldWaitForRemoteSessionBootstrap)据此决定还要不要等。
- * 两种终态:最新一次 listDevices 已 resolve / reject(见 setDevices / markInitialRequestSettled),
+ * 两种终态:最新一次 listDevices 已 resolve / reject(见 setDevices / markRequestFailed),
* 或 relay 已停(登出 / 本地模式,见 clearDevices)。false 必须意味着「还有结果会来」。
*/
let initialRequestSettled = false;
@@ -36,6 +43,35 @@ let initialRequestSettled = false;
*/
let loadGeneration = 0;
+/** 更新设备目录请求态但不通知,便于与列表快照合并成一次发布。 */
+function setRequestState(status: DeviceLinkDeviceListStatus, error: string | null): boolean {
+ if (requestState.status === status && requestState.error === error) return false;
+ requestState = { status, error };
+ return true;
+}
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return !!value && typeof value === 'object' && !Array.isArray(value);
+}
+
+function isNullableString(value: unknown): value is string | null {
+ return value === null || typeof value === 'string';
+}
+
+function isDeviceLinkDeviceView(value: unknown): value is DeviceLinkDeviceView {
+ if (!isRecord(value)) return false;
+ return (
+ typeof value.deviceId === 'string' &&
+ value.deviceId.length > 0 &&
+ typeof value.name === 'string' &&
+ isNullableString(value.platform) &&
+ typeof value.online === 'boolean' &&
+ typeof value.remoteControlEnabled === 'boolean' &&
+ typeof value.controlEnabled === 'boolean' &&
+ typeof value.isSelf === 'boolean'
+ );
+}
+
/** 仅比较切换栏关心的字段(忽略 busy / lastSeenAt 等高频字段,避免无谓重渲染)。 */
function relevantEqual(a: DeviceLinkDeviceView[] | null, b: DeviceLinkDeviceView[]): boolean {
if (a === null || a.length !== b.length) return false;
@@ -82,7 +118,8 @@ function setDevices(next: DeviceLinkDeviceView[]): void {
const sorted = [...next].sort((a, b) => a.deviceId.localeCompare(b.deviceId));
const devicesChanged = !relevantEqual(devices, sorted);
const settledChanged = !initialRequestSettled;
- if (!devicesChanged && !settledChanged) return;
+ const requestChanged = setRequestState('ready', null);
+ if (!devicesChanged && !settledChanged && !requestChanged) return;
devices = sorted;
initialRequestSettled = true;
subs.forEach((fn) => fn());
@@ -101,15 +138,20 @@ function setDevices(next: DeviceLinkDeviceView[]): void {
*/
function clearDevices(): void {
loadGeneration += 1; // 作废所有在途 listDevices 响应(见 loadGeneration 注释)。
- const changed = devices !== null || !initialRequestSettled;
+ const requestChanged = setRequestState('ready', null);
+ const changed = devices !== null || !initialRequestSettled || requestChanged;
if (!changed) return;
devices = null;
initialRequestSettled = true;
subs.forEach((fn) => fn());
}
-function markInitialRequestSettled(): void {
- if (initialRequestSettled) return;
+function markRequestFailed(error: unknown): void {
+ const requestChanged = setRequestState(
+ 'error',
+ error instanceof Error ? error.message : String(error),
+ );
+ if (initialRequestSettled && !requestChanged) return;
initialRequestSettled = true;
subs.forEach((fn) => fn());
}
@@ -132,36 +174,74 @@ export function renameDeviceLinkDevice(deviceId: string, name: string): void {
function ensureStarted(): void {
if (started) return;
started = true;
- const refresh = (): void => {
- // 上一轮在尚无设备快照时失败只代表「该次请求已结算」。online / push 触发了新的
- // 有意义重试后要重新进入 loading,直到这次请求成功或失败;否则失败后重连期间会
- // 把 devices=null + settled=true 误当成权威空列表。
- if (devices === null && initialRequestSettled) {
- initialRequestSettled = false;
- subs.forEach((fn) => fn());
- }
- loadGeneration += 1; // 本次为最新一次拉取,作废所有更早的在途响应(见 loadGeneration 注释)。
+ let linkStatus: 'stopped' | 'connecting' | 'online' | null = null;
+ let linkStatusRevision = 0;
+
+ const enterLoading = (): void => {
+ // 上一轮在尚无设备快照时失败只代表「该次请求已结算」。新的有效拉取开始后要重新
+ // 进入 loading,直到本轮成功或失败;已有快照则保留,requestState 单独表达正在刷新。
+ const settledChanged = devices === null && initialRequestSettled;
+ if (settledChanged) initialRequestSettled = false;
+ const requestChanged = setRequestState('loading', null);
+ if (settledChanged || requestChanged) subs.forEach((fn) => fn());
+ };
+
+ const runRefresh = async (probeState: boolean): Promise<void> => {
+ // getState 与 listDevices 共用同一个 operation generation。stop、状态 push、手动重试或
+ // 更晚的 refresh 都会令旧操作失效,迟到的状态快照和目录快照都不得落地。
+ loadGeneration += 1;
const gen = loadGeneration;
- window.electronAPI.deviceLink
- .listDevices()
- .then(({ devices: list }) => {
- // 期间发生过清空(stop / 登出)或更晚的 refresh → 本次响应已陈旧,丢弃。
- if (gen !== loadGeneration) return;
- setDevices(list);
- })
- .catch(() => {
- // 只有最新请求的失败才算本轮首拉已经结算;更晚的 refresh 仍在途时继续等待它。
- if (gen !== loadGeneration) return;
- markInitialRequestSettled();
- // 瞬态拉取失败(relay 重连中等)保持当前快照;登出 / relay 停止由下面的 'stopped'
- // 状态事件显式清空,不靠这里的失败兜底(避免一次网络抖动就清掉、闪烁)。但把请求
- // 标成已结算,避免远端 sidebar bootstrap 因 devices 仍为 null 永久显示加载态。
- });
+ const statusRevisionAtStart = linkStatusRevision;
+ enterLoading();
+
+ if (probeState || linkStatus === null) {
+ try {
+ const state = await window.electronAPI.deviceLink.getState();
+ if (gen !== loadGeneration || statusRevisionAtStart !== linkStatusRevision) return;
+ linkStatus = state.linkStatus;
+ } catch {
+ if (gen !== loadGeneration || statusRevisionAtStart !== linkStatusRevision) return;
+ // getState 本身失败时保留既有 status 判断;未知 / 在线态仍尝试目录请求,让真正的
+ // listDevices 结果决定 ready/error。已知 stopped 则不能误打成远程连接失败。
+ }
+ }
+
+ // 未登录 / 本地模式 / Device Link 停服不是「远程目录读取失败」:此刻远端能力
+ // 不在产品作用域内,目录应结算为 ready + null。手动重试也不能把 stopped 重新
+ // 打成 error;只有 online / connecting 下真实发出的 listDevices 失败才是连接错误。
+ if (linkStatus === 'stopped') {
+ clearDevices();
+ return;
+ }
+
+ try {
+ const result = await window.electronAPI.deviceLink.listDevices();
+ // 期间发生过清空(stop / 登出)或更晚的 refresh → 本次响应已陈旧,丢弃。
+ if (gen !== loadGeneration) return;
+ const list = result?.devices;
+ if (!Array.isArray(list) || !list.every(isDeviceLinkDeviceView)) {
+ throw new Error('Invalid device list response');
+ }
+ setDevices(list);
+ } catch (error) {
+ // 只有最新请求的失败才算本轮首拉已经结算;更晚的 refresh 仍在途时继续等待它。
+ if (gen !== loadGeneration) return;
+ markRequestFailed(error);
+ // 瞬态拉取失败(relay 重连中等)保持当前快照;登出 / relay 停止由下面的 'stopped'
+ // 状态事件显式清空,不靠这里的失败兜底(避免一次网络抖动就清掉、闪烁)。但把请求
+ // 标成已结算,避免远端 sidebar bootstrap 因 devices 仍为 null 永久显示加载态。
+ }
+ };
+
+ const refresh = (probeState = false): void => {
+ void runRefresh(probeState);
};
- refresh();
+ refreshImpl = () => refresh(true);
// app 生命周期常驻(侧边栏始终有订阅者),不解绑监听。
window.electronAPI.deviceLink.onPresenceChanged(() => refresh());
window.electronAPI.deviceLink.onStatusChanged((p) => {
+ linkStatusRevision += 1;
+ linkStatus = p.status;
if (p.status === 'stopped') {
// 登出 / relay 停止:清掉缓存设备。否则登出后(或同进程换账号)上一账号的远程机器会
// 一直留在切换栏里被当成可选 / 连接中(listDevices 此时多半失败,catch 又保留旧快照)。
@@ -169,12 +249,17 @@ function ensureStarted(): void {
clearDevices();
return;
}
- // 'online' 重连成功 → 重拉;'connecting' 瞬态保持当前快照(remoteProjectsStore 标记断线,chip 转「连接中」)。
- if (p.status === 'online') refresh();
+ // online / connecting 都是远端目录仍在作用域内的状态:开始新一轮读取。connecting 下
+ // 若 REST 仍可达可直接拿到目录;不可达则明确落 error,而不是误装成空列表。
+ refresh();
});
// 关掉「我控制它」(本地 opt-out)只广播 control-target-changed、不发 presence;listDevices 的
// controlEnabled 已据 disabledControlDeviceIds 计算,故重拉即可让被 opt-out 的设备立刻退出切换栏。
window.electronAPI.deviceLink.onControlTargetChanged(() => refresh());
+
+ // 监听必须先挂,再读初值:否则 hook 挂载前 relay 已 stopped,或 getState 在 push 后迟到,
+ // 都可能把本地/未登录态误报成 listDevices 失败。revision + generation 保证 push 永远胜出。
+ refresh(true);
}
function subscribe(fn: () => void): () => void {
@@ -202,3 +287,21 @@ function getInitialRequestSettledSnapshot(): boolean {
export function useDeviceLinkDeviceListSettled(): boolean {
return useSyncExternalStore(subscribe, getInitialRequestSettledSnapshot);
}
+
+function getRequestStateSnapshot(): DeviceLinkDeviceListRequestState {
+ return requestState;
+}
+
+/** 设备目录的 loading / ready / error 状态;只有 ready + [] 才是权威空目录。 */
+export function useDeviceLinkDeviceListRequestState(): DeviceLinkDeviceListRequestState {
+ return useSyncExternalStore(subscribe, getRequestStateSnapshot);
+}
+
+/** 用户可见错误态的手动重试入口。 */
+export function retryDeviceLinkDeviceList(): void {
+ if (!started) {
+ ensureStarted();
+ return;
+ }
+ refreshImpl?.();
+}
diff --git a/apps/desktop/src/renderer/features/device-link/useDeviceLinkRemoteProjects.ts b/apps/desktop/src/renderer/features/device-link/useDeviceLinkRemoteProjects.ts
index acd64e5c95..832de0a1d0 100644
--- a/apps/desktop/src/renderer/features/device-link/useDeviceLinkRemoteProjects.ts
+++ b/apps/desktop/src/renderer/features/device-link/useDeviceLinkRemoteProjects.ts
@@ -34,7 +34,11 @@
import { useEffect } from 'react';
import { useAuth } from '@/contexts/AuthContext';
import { createLogger } from '@/lib/logger';
-import { remoteProjectsStore, setRemoteReseedImpl } from './remoteProjectsStore';
+import {
+ remoteProjectsStore,
+ setRemoteReseedImpl,
+ setRemoteSessionBootstrapRetryImpl,
+} from './remoteProjectsStore';
import {
clearRemoteSessionActivity,
removeRemoteSessionActivityForDevice,
@@ -164,8 +168,9 @@ export function useDeviceLinkRemoteProjects(): void {
* 任一步返回 ACCESS_REVOKED → 标记已撤销并移除该设备;全程无撤销 → 清掉残留标记(恢复收尾)。
*/
const runSubscribeAndBootstrap = async (deviceId: string, name: string): Promise<void> => {
- // 新一轮 bootstrap 是有意义的重试:恢复 loading,直到本轮落下 snapshot 或再次终态失败。
- remoteProjectsStore.clearBootstrapFailure(deviceId);
+ // 新一轮 bootstrap 是有意义的重试:即使还保留旧 shard 也要显式进入
+ // loading,直到本轮落下 snapshot 或再次终态失败。
+ remoteProjectsStore.markBootstrapLoading(deviceId);
try {
await window.electronAPI.deviceLink.subscribe(deviceId, ['sessions']);
} catch (err) {
@@ -178,9 +183,9 @@ export function useDeviceLinkRemoteProjects(): void {
const result = await refreshRemoteDeviceSessions(deviceId, name);
if (result === 'revoked') return void handleRevoked(deviceId);
if (disposed || !eligible.has(deviceId)) return;
- if (result === 'gave-up' && !remoteProjectsStore.hasDevice(deviceId)) {
+ if (result === 'gave-up') {
// 永久错误(如旧被控端 CHANNEL_NOT_ALLOWED)或瞬态重试耗尽:不是权威空列表,
- // 但本轮 bootstrap 已有终态,不能让「所有」侧边栏永久停在 loading。
+ // 即使还有旧 shard 也必须标明本轮读取失败,不能把缓存伪装成刚返回的结果。
// superseded 表示断连 / 清理使请求失效,必须等重连,不能误记成终态失败。
remoteProjectsStore.markBootstrapFailed(deviceId);
}
@@ -330,6 +335,13 @@ export function useDeviceLinkRemoteProjects(): void {
reseed();
});
+ // 用户点击失败态重试 → 重走 subscribe + bootstrap,恢复 loading 与完整重试语义。
+ setRemoteSessionBootstrapRetryImpl((deviceId) => {
+ const name = eligible.get(deviceId);
+ if (!name || disposed) return;
+ void subscribeAndBootstrap(deviceId, name);
+ });
+
// sessions:created push(无 row 数据)/ applyPatch 的 unarchive 兜底 → 防抖重拉该设备(reconcile)。
setRemoteReseedImpl((deviceId) => {
const name = eligible.get(deviceId);
@@ -473,6 +485,7 @@ export function useDeviceLinkRemoteProjects(): void {
return () => {
disposed = true;
setRemoteReseedImpl(null);
+ setRemoteSessionBootstrapRetryImpl(null);
stopPeriodicReconcile();
for (const t of reseedTimers.values()) clearTimeout(t);
reseedTimers.clear();
diff --git a/apps/desktop/src/renderer/features/device-link/useMachineSwitcher.ts b/apps/desktop/src/renderer/features/device-link/useMachineSwitcher.ts
index 834e1ca6d1..1a394f33fb 100644
--- a/apps/desktop/src/renderer/features/device-link/useMachineSwitcher.ts
+++ b/apps/desktop/src/renderer/features/device-link/useMachineSwitcher.ts
@@ -26,14 +26,12 @@
import { useCallback, useMemo, useSyncExternalStore } from 'react';
import {
useRemoteBootstrapFailedDeviceIds,
+ useRemoteBootstrapLoadingDeviceIds,
useRemoteDevices,
type RemoteDeviceSummary,
} from './remoteProjectsStore';
import { revokedDevicesStore } from './revokedDevicesStore';
-import {
- useDeviceLinkDeviceList,
- useDeviceLinkDeviceListSettled,
-} from './useDeviceLinkDeviceList';
+import { useDeviceLinkDeviceList, useDeviceLinkDeviceListSettled } from './useDeviceLinkDeviceList';
import { buildSwitcherDevices, selectableDeviceIds, type SwitcherDevice } from './switcherDevices';
import {
MACHINE_ALL,
@@ -60,6 +58,58 @@ export interface RemoteSessionBootstrapLoadingInput {
bootstrapFailedDeviceIds: ReadonlySet<string>;
}
+export interface RemoteSessionBootstrapFailuresInput {
+ selectedMachineId: MachineSelection;
+ devices: readonly SwitcherDevice[];
+ bootstrapFailedDeviceIds: ReadonlySet<string>;
+}
+
+export interface RemoteSessionBootstrapLoadingDevicesInput {
+ selectedMachineId: MachineSelection;
+ devices: readonly SwitcherDevice[];
+ bootstrapLoadingDeviceIds: ReadonlySet<string>;
+}
+
+function selectRemoteSessionBootstrapDevices(
+ selectedMachineId: MachineSelection,
+ devices: readonly SwitcherDevice[],
+ deviceIds: ReadonlySet<string>,
+): SwitcherDevice[] {
+ if (deviceIds.size === 0) return [];
+ const selectedRemoteIds =
+ selectedMachineId === MACHINE_ALL
+ ? null
+ : new Set(selectedMachineId.filter((id) => id !== MACHINE_LOCAL));
+ if (selectedRemoteIds?.size === 0) return [];
+ return devices.filter(
+ (device) =>
+ deviceIds.has(device.deviceId) &&
+ device.status !== 'rejected' &&
+ (selectedRemoteIds === null || selectedRemoteIds.has(device.deviceId)),
+ );
+}
+
+/** 返回当前机器作用域里正在读取任务快照的远程设备。 */
+export function selectRemoteSessionBootstrapLoadingDevices({
+ selectedMachineId,
+ devices,
+ bootstrapLoadingDeviceIds,
+}: RemoteSessionBootstrapLoadingDevicesInput): SwitcherDevice[] {
+ return selectRemoteSessionBootstrapDevices(selectedMachineId, devices, bootstrapLoadingDeviceIds);
+}
+
+/**
+ * 返回当前机器作用域里首次任务快照读取失败的远程设备。
+ * 仅本机选择不受远端失败影响;「所有」覆盖全部失败设备;显式多选只看勾选范围。
+ */
+export function selectRemoteSessionBootstrapFailures({
+ selectedMachineId,
+ devices,
+ bootstrapFailedDeviceIds,
+}: RemoteSessionBootstrapFailuresInput): SwitcherDevice[] {
+ return selectRemoteSessionBootstrapDevices(selectedMachineId, devices, bootstrapFailedDeviceIds);
+}
+
/**
* 当前机器作用域是否仍包含尚未完成首次 sessions snapshot 的远程设备。
* syncedDevices 即使 sessionCount=0 也代表 bootstrap 已落过权威空快照;
@@ -208,23 +258,69 @@ export function useSelectedMachineConnecting(): boolean {
* 「所有」作用域包含本机与全部远程源,因此远端设备清单或任一相关首快照未落地时,
* 侧栏继续显示加载态,避免本地 sessions 先完成后短暂误报真实空态。
*/
-export function useRemoteSessionBootstrapLoading(
- selectedMachineId: MachineSelection,
-): boolean {
+export function useRemoteSessionBootstrapLoading(selectedMachineId: MachineSelection): boolean {
const deviceListSettled = useDeviceLinkDeviceListSettled();
const devices = useSwitcherDevices();
const synced = useRemoteDevices();
+ const bootstrapLoadingDeviceIds = useRemoteBootstrapLoadingDeviceIds();
const bootstrapFailedDeviceIds = useRemoteBootstrapFailedDeviceIds();
- return useMemo(
- () =>
+ return useMemo(() => {
+ const explicitlyLoading = selectRemoteSessionBootstrapLoadingDevices({
+ selectedMachineId,
+ devices,
+ bootstrapLoadingDeviceIds,
+ });
+ return (
+ explicitlyLoading.length > 0 ||
shouldWaitForRemoteSessionBootstrap({
selectedMachineId,
deviceListSettled,
devices,
syncedDevices: synced,
bootstrapFailedDeviceIds,
+ })
+ );
+ }, [
+ selectedMachineId,
+ deviceListSettled,
+ devices,
+ synced,
+ bootstrapLoadingDeviceIds,
+ bootstrapFailedDeviceIds,
+ ]);
+}
+
+/** 当前可见机器范围内,正在读取任务快照的远程设备。 */
+export function useRemoteSessionBootstrapLoadingDevices(
+ selectedMachineId: MachineSelection,
+): SwitcherDevice[] {
+ const devices = useSwitcherDevices();
+ const bootstrapLoadingDeviceIds = useRemoteBootstrapLoadingDeviceIds();
+ return useMemo(
+ () =>
+ selectRemoteSessionBootstrapLoadingDevices({
+ selectedMachineId,
+ devices,
+ bootstrapLoadingDeviceIds,
+ }),
+ [selectedMachineId, devices, bootstrapLoadingDeviceIds],
+ );
+}
+
+/** 当前可见机器范围内,首次任务快照已终态失败的远程设备。 */
+export function useRemoteSessionBootstrapFailures(
+ selectedMachineId: MachineSelection,
+): SwitcherDevice[] {
+ const devices = useSwitcherDevices();
+ const bootstrapFailedDeviceIds = useRemoteBootstrapFailedDeviceIds();
+ return useMemo(
+ () =>
+ selectRemoteSessionBootstrapFailures({
+ selectedMachineId,
+ devices,
+ bootstrapFailedDeviceIds,
}),
- [selectedMachineId, deviceListSettled, devices, synced, bootstrapFailedDeviceIds],
+ [selectedMachineId, devices, bootstrapFailedDeviceIds],
);
}
diff --git a/apps/desktop/src/renderer/hooks/useAgentCapabilities.ts b/apps/desktop/src/renderer/hooks/useAgentCapabilities.ts
index 11eb4cb947..4dc60865d2 100644
--- a/apps/desktop/src/renderer/hooks/useAgentCapabilities.ts
+++ b/apps/desktop/src/renderer/hooks/useAgentCapabilities.ts
@@ -106,6 +106,89 @@ export interface AgentCapabilities {
supportsSessionAgentSwitchCas?: boolean;
}
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return !!value && typeof value === 'object' && !Array.isArray(value);
+}
+
+function isStringArray(value: unknown): value is string[] {
+ return Array.isArray(value) && value.every((item) => typeof item === 'string');
+}
+
+function isOptionalString(value: unknown): boolean {
+ return value === undefined || typeof value === 'string';
+}
+
+function isOptionalBoolean(value: unknown): boolean {
+ return value === undefined || typeof value === 'boolean';
+}
+
+function isOptionalFiniteNumber(value: unknown): boolean {
+ return value === undefined || (typeof value === 'number' && Number.isFinite(value));
+}
+
+function isOptionalStringRecord(value: unknown): boolean {
+ return (
+ value === undefined ||
+ (isRecord(value) && Object.values(value).every((label) => typeof label === 'string'))
+ );
+}
+
+function isModelDescriptor(value: unknown): value is ModelDescriptor {
+ if (!isRecord(value)) return false;
+ const efforts = value.efforts;
+ const defaultEffort = value.defaultEffort;
+ return (
+ typeof value.id === 'string' &&
+ value.id.length > 0 &&
+ typeof value.displayName === 'string' &&
+ value.displayName.length > 0 &&
+ typeof value.contextWindow === 'number' &&
+ Number.isFinite(value.contextWindow) &&
+ value.contextWindow > 0 &&
+ isStringArray(efforts) &&
+ (defaultEffort === null ||
+ (typeof defaultEffort === 'string' && efforts.includes(defaultEffort))) &&
+ isOptionalString(value.group) &&
+ isOptionalString(value.mode) &&
+ isOptionalString(value.description) &&
+ isOptionalStringRecord(value.effortDisplayNames) &&
+ isOptionalBoolean(value.supportsFastMode) &&
+ isOptionalFiniteNumber(value.sortOrder) &&
+ isOptionalBoolean(value.defaultEnabled)
+ );
+}
+
+function isNamedDescriptor(value: unknown): boolean {
+ return (
+ isRecord(value) &&
+ typeof value.id === 'string' &&
+ value.id.length > 0 &&
+ typeof value.displayName === 'string' &&
+ value.displayName.length > 0 &&
+ isOptionalString(value.description)
+ );
+}
+
+function parseAgentCapabilities(value: unknown): AgentCapabilities {
+ if (!isRecord(value)) {
+ throw new Error('Invalid agent capabilities response');
+ }
+ if (
+ !Array.isArray(value.availableModels) ||
+ !value.availableModels.every(isModelDescriptor) ||
+ typeof value.hasFastMode !== 'boolean' ||
+ !Array.isArray(value.effortLevels) ||
+ !value.effortLevels.every(isNamedDescriptor) ||
+ !Array.isArray(value.permissionModes) ||
+ !value.permissionModes.every(isNamedDescriptor) ||
+ !isOptionalBoolean(value.supportsSessionAgentSwitch) ||
+ !isOptionalBoolean(value.supportsSessionAgentSwitchCas)
+ ) {
+ throw new Error('Invalid agent capabilities response');
+ }
+ return value as unknown as AgentCapabilities;
+}
+
interface MakerApiShape {
getCapabilities: (agentKind: AgentKind) => Promise<AgentCapabilities>;
}
@@ -214,7 +297,8 @@ async function fetchCapabilities(
raw = api.getCapabilities(agentKind);
}
const p = raw
- .then((caps) => {
+ .then((value) => {
+ const caps = parseAgentCapabilities(value);
// 在途期间设备被驱逐(下线 / 断链)→ 丢弃结果,不回写 cache、不动 inflight。
if (isCurrent()) {
cache.set(key, caps);
@@ -254,33 +338,43 @@ export function useAgentCapabilities(
agentKind: AgentKind | null | undefined,
deviceId?: string,
): UseAgentCapabilitiesResult {
+ const selectedKey = agentKind ? cacheKey(agentKind, deviceId) : null;
+ const initialCapabilities = selectedKey ? cache.get(selectedKey) : undefined;
+ const [ownerKey, setOwnerKey] = useState<CacheKey | null>(
+ initialCapabilities ? selectedKey : null,
+ );
const [capabilities, setCapabilities] = useState<AgentCapabilities | null>(
- agentKind ? (cache.get(cacheKey(agentKind, deviceId)) ?? null) : null,
+ initialCapabilities ?? null,
);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
if (!agentKind) return undefined;
+ const key = cacheKey(agentKind, deviceId);
const applyRemoteEvent = (event: DeviceCapabilitiesEvent): void => {
if (event.status === 'loading') {
// 保留上一份完整快照以避免空白帧,但显式标记为 stale,调用方不得据此改写选择。
+ setOwnerKey(key);
setLoading(true);
setError(null);
return;
}
if (event.status === 'error') {
+ setOwnerKey(key);
setCapabilities(null);
setLoading(false);
setError(event.error);
return;
}
+ setOwnerKey(key);
setCapabilities(event.capabilities);
setLoading(false);
setError(null);
};
if (deviceId) return subscribeDeviceCapabilities(deviceId, agentKind, applyRemoteEvent);
const applySnapshot = (caps: AgentCapabilities): void => {
+ setOwnerKey(key);
setCapabilities(caps);
setLoading(false);
setError(null);
@@ -297,11 +391,16 @@ export function useAgentCapabilities(
useEffect(() => {
if (!agentKind) {
+ setOwnerKey(null);
setCapabilities(null);
+ setLoading(false);
+ setError(null);
return;
}
- const cached = cache.get(cacheKey(agentKind, deviceId));
+ const key = cacheKey(agentKind, deviceId);
+ const cached = cache.get(key);
if (cached) {
+ setOwnerKey(key);
setCapabilities(cached);
// 缓存命中 = 数据已就绪,必须把上一目标遗留的 loading / error 一并清掉。
// 漏了会卡死:从「能力还在加载」的设备切到已缓存的设备时走到这里直接 return,
@@ -314,6 +413,7 @@ export function useAgentCapabilities(
let cancelled = false;
// cache miss:先清掉上一设备 / 会话的能力,避免 fetch 解析前(失败则永远)UI 残留旧设备的
// 模型 / effort 列表 → 远程会话误选目标端不支持的模型。
+ setOwnerKey(key);
setCapabilities(null);
setLoading(true);
setError(null);
@@ -340,7 +440,12 @@ export function useAgentCapabilities(
};
}, [agentKind, deviceId]);
- return { capabilities, loading, error };
+ const ownsSelection = ownerKey === selectedKey;
+ return {
+ capabilities: ownsSelection ? capabilities : null,
+ loading: selectedKey !== null && (!ownsSelection || loading),
+ error: ownsSelection ? error : null,
+ };
}
/**
@@ -360,9 +465,7 @@ export function getCachedCapabilities(
* 模型下拉 / fast / effort 不为空、modelDefinitions 同步层已热。失败 swallow(轮询/打开会话会再取)。
*/
export async function prefetchDeviceCapabilities(deviceId: string): Promise<void> {
- await Promise.allSettled(
- ALL_AGENT_KINDS.map((agent) => fetchCapabilities(agent, deviceId)),
- );
+ await Promise.allSettled(ALL_AGENT_KINDS.map((agent) => fetchCapabilities(agent, deviceId)));
}
/** device-link:被控设备下线 / 断链时驱逐其能力缓存(只清该设备的 key)。 */
@@ -395,9 +498,7 @@ export async function loadLocalCapabilitiesSnapshot(): Promise<LocalCapabilities
const api = getMakerApi();
if (!api) throw new Error('maker IPC not available');
return Promise.all(
- ALL_AGENT_KINDS.map(
- async (agent) => [agent, await api.getCapabilities(agent)] as const,
- ),
+ ALL_AGENT_KINDS.map(async (agent) => [agent, await api.getCapabilities(agent)] as const),
);
}
diff --git a/apps/desktop/src/renderer/hooks/useDeviceLinkProjects.ts b/apps/desktop/src/renderer/hooks/useDeviceLinkProjects.ts
index 2b70039836..502392238c 100644
--- a/apps/desktop/src/renderer/hooks/useDeviceLinkProjects.ts
+++ b/apps/desktop/src/renderer/hooks/useDeviceLinkProjects.ts
@@ -41,6 +41,8 @@ export function toDeviceProjectOptions(
/** 复用的空集合,免得每次取数都新建一个。 */
const EMPTY_PATHS: ReadonlySet<string> = new Set<string>();
+export type DeviceLinkProjectsStatus = 'idle' | 'loading' | 'ready' | 'error';
+
export function useDeviceLinkProjects(
deviceId: string | null,
deviceName: string | null,
@@ -48,6 +50,9 @@ export function useDeviceLinkProjects(
): {
projects: FolderPickerOption[];
loading: boolean;
+ status: DeviceLinkProjectsStatus;
+ error: string | null;
+ retry: () => void;
removeProject: (option: FolderPickerOption) => Promise<void>;
} {
/**
@@ -61,7 +66,12 @@ export function useDeviceLinkProjects(
deviceId: string | null;
rows: ExistingRemoteProject[];
}>({ deviceId: null, rows: [] });
- const [loading, setLoading] = useState(false);
+ const [requestState, setRequestState] = useState<{
+ deviceId: string | null;
+ status: DeviceLinkProjectsStatus;
+ error: string | null;
+ }>({ deviceId: null, status: 'idle', error: null });
+ const [retryNonce, setRetryNonce] = useState(0);
/**
* loaded 的**同步**镜像。setState 的 updater 只在 React 处理这次更新时才跑,而删除失败后的恢复
* 要在两次 await 之间就拿到「被移除的是哪一行、它原来在第几位」—— 从 updater 的副作用里取值会
@@ -168,8 +178,7 @@ export function useDeviceLinkProjects(
if (tomb.size === 0) tombstonesRef.current.delete(ownerDeviceId);
}
const stillTombstoned = tombstonesRef.current.get(ownerDeviceId);
- const drop = (path: string) =>
- hiddenPaths.has(path) || stillTombstoned?.has(path) === true;
+ const drop = (path: string) => hiddenPaths.has(path) || stillTombstoned?.has(path) === true;
commitRows(
ownerDeviceId,
list.some((row) => drop(row.path)) ? list.filter((row) => !drop(row.path)) : [...list],
@@ -184,7 +193,7 @@ export function useDeviceLinkProjects(
// 本机(deviceId=null)不走隧道;picker 没打开时不取数,避免常驻首页时白拉。
if (!enabled || !deviceId) {
commitRows(deviceId, []);
- setLoading(false);
+ setRequestState({ deviceId, status: 'idle', error: null });
return;
}
let cancelled = false;
@@ -195,7 +204,7 @@ export function useDeviceLinkProjects(
// deviceId 已经变成 B 而 rows 还是 A 的,于是加载窗口里会渲染出「标着 B 的 A 的项目」——
// 用户此时选中就把 A 的路径发给 B,撞 path guard 或打开 B 上同名的无关目录。
commitRows(deviceId, []);
- setLoading(true);
+ setRequestState({ deviceId, status: 'loading', error: null });
void loadDeviceLinkExistingProjects(deviceId)
.then((list) => {
if (cancelled || requestIdRef.current !== requestId) return;
@@ -203,138 +212,144 @@ export function useDeviceLinkProjects(
// 点掉的行贴回去。以前靠删除路径自增 requestIdRef 作废取数来避免,但那个共享版本号会
// 顺带把**别的设备**的取数误判成过期(见 requestIdRef 的说明),所以改成在这里过滤。
// 墓碑(已成功删除但快照可能更旧)由 applySnapshot 一并扣掉。
- applySnapshot(deviceId, issueSeq, list, pendingRemovalsRef.current.get(deviceId) ?? EMPTY_PATHS);
- setLoading(false);
+ applySnapshot(
+ deviceId,
+ issueSeq,
+ list,
+ pendingRemovalsRef.current.get(deviceId) ?? EMPTY_PATHS,
+ );
+ setRequestState({ deviceId, status: 'ready', error: null });
})
- .catch(() => {
- // 被控端离线 / 老版本没这个 channel → 空态里仍有「浏览文件夹」兜底。
+ .catch((error: unknown) => {
+ // 被控端离线、超时或老版本没这个 channel 都是读取失败;UI 显示错误与重试,
+ // 不得把它们当成对端权威返回的「没有项目」。
if (cancelled || requestIdRef.current !== requestId) return;
// **刻意不 commitRows([])**(Codex review 第 33 轮 P1)。这个 effect 开头已经把行设成了
- // 「(这台设备, 空)」,所以失败时什么都不做,显示的就已经是空态 —— 再提交一次是冗余的,
+ // 「(这台设备, 空)」,失败由 requestState 单独表达;再提交空行是冗余的,
// 而且会踩掉一个真实窗口:删除失败的兜底回读**在 effect 开头那次清空之后**才 apply,
// 于是「回读刚带回一份好数据」与「本次取数瞬时失败(隧道抖动 / 超时)」可以同时成立。
// 无条件清空会把那份刚被证明存在的列表抹成「没有项目」,直到用户再成功重开一次才恢复。
// 归属正确性不依赖这里:effect 开头的清空已经保证当前行属于这台设备。
- setLoading(false);
+ setRequestState({
+ deviceId,
+ status: 'error',
+ error: error instanceof Error ? error.message : String(error),
+ });
});
return () => {
cancelled = true;
};
- }, [deviceId, enabled]);
+ }, [deviceId, enabled, retryNonce]);
+
+ const removeProject = useCallback(async (option: FolderPickerOption) => {
+ const target = option.remoteDevice;
+ if (!target) return;
- const removeProject = useCallback(
- async (option: FolderPickerOption) => {
- const target = option.remoteDevice;
- if (!target) return;
+ // 刻意**不动** requestIdRef(Greptile review):在途取数不会把刚乐观移除的行贴回来 ——
+ // 它落库前会减去下面这个 pending 集合。作废取数反而会误伤别的设备的取数,见 requestIdRef。
+ const devicePending = pendingRemovalsRef.current.get(target.deviceId) ?? new Set<string>();
+ devicePending.add(option.path);
+ pendingRemovalsRef.current.set(target.deviceId, devicePending);
+ // 记下被移除的行与它原来的位置:两条恢复路径都要用(回读失败时按原序插回)。
+ // 从同步镜像读,不从 setState 的 updater 副作用读 —— 见 loadedRef 的说明。
+ // 归属不符就不动列表:那说明当前显示的已经是别的设备的行,乐观移除会改错列表。
+ const before = loadedRef.current.deviceId === target.deviceId ? loadedRef.current.rows : [];
+ const removedIndex = before.findIndex((row) => row.path === option.path);
+ const removedRow = removedIndex >= 0 ? before[removedIndex] : undefined;
+ if (removedIndex >= 0) {
+ commitRows(target.deviceId, [
+ ...before.slice(0, removedIndex),
+ ...before.slice(removedIndex + 1),
+ ]);
+ }
- // 刻意**不动** requestIdRef(Greptile review):在途取数不会把刚乐观移除的行贴回来 ——
- // 它落库前会减去下面这个 pending 集合。作废取数反而会误伤别的设备的取数,见 requestIdRef。
- const devicePending =
- pendingRemovalsRef.current.get(target.deviceId) ?? new Set<string>();
- devicePending.add(option.path);
- pendingRemovalsRef.current.set(target.deviceId, devicePending);
- // 记下被移除的行与它原来的位置:两条恢复路径都要用(回读失败时按原序插回)。
- // 从同步镜像读,不从 setState 的 updater 副作用读 —— 见 loadedRef 的说明。
- // 归属不符就不动列表:那说明当前显示的已经是别的设备的行,乐观移除会改错列表。
- const before = loadedRef.current.deviceId === target.deviceId ? loadedRef.current.rows : [];
- const removedIndex = before.findIndex((row) => row.path === option.path);
- const removedRow = removedIndex >= 0 ? before[removedIndex] : undefined;
- if (removedIndex >= 0) {
- commitRows(target.deviceId, [
- ...before.slice(0, removedIndex),
- ...before.slice(removedIndex + 1),
- ]);
+ /**
+ * 把乐观移除的那一行按原位插回。
+ *
+ * 「这次删除失败了,所以这一行该在」是一件**与快照版本无关的局部事实**,所以两种情况都用它:
+ * ① 权威回读本身也失败(拿不到任何真相);
+ * ② 回读拿到了快照,但它比已落库的更旧而被丢弃 —— 这一条是 seq gate 的代价:不补的话
+ * 并发失败删除就不再收敛(先回的那份快照隐藏了仍在飞的自己,后回的自己又被丢弃,
+ * 于是自己那一行永远回不来),而「并发失败删除必须各自收敛」是既有不变量。
+ *
+ * 刻意**不按取数版本号一刀切**:期间用户重开 picker / 切回本设备都会推进版本号,按它直接
+ * gate 会把这次恢复跳过,那一行就一直从选择器里消失(而它在对端还在)。自带存在性检查,
+ * 期间真有成功回读把它带回来了也不会插重。
+ *
+ * 但**必须尊重更新快照的否证**(Greptile review):上一轮为保住收敛性而在「回读被 seq gate
+ * 拒绝」时也走这里,那条路径当时只查设备归属与存在性 —— 于是当对端其实已经没有这个项目了
+ * (用户在对端删了 / 删除实际成功只是响应失败),更新的权威快照如实不含它,旧回读却仍能把它
+ * 插回选择器;用户选中就撞 path guard,或打开对端同名但无关的目录。
+ *
+ * 判据用**原始**快照集合而不是落库后的行,见 lastSnapshotPathsRef —— 落库会扣掉仍在飞的
+ * 乐观删除,拿它判会把「对端有、只是被 pending 过滤」也当成否证,直接废掉并发收敛。
+ */
+ const restoreRemovedRow = (readbackSeq?: number) => {
+ const restored = removedRow;
+ if (!restored) return;
+ // 按当前设备 gate:若请求还在飞时用户已切到别的设备,把 A 的行插进 B 的 rows 会被
+ // toDeviceProjectOptions 标成属于 B —— 选中它就把 A 的路径发给 B 了。这与「并发删除不能
+ // 互相取消」不冲突:设备身份只排除「已切走」,不排除同设备内的并发。
+ if (currentDeviceIdRef.current !== target.deviceId) return;
+ if (loadedRef.current.deviceId !== target.deviceId) return;
+ // 已有**更新**的权威快照,且它的原始列表里没有这一行 → 对端确实没有,不恢复。
+ if (readbackSeq !== undefined) {
+ const applied = appliedSeqRef.current.get(target.deviceId) ?? 0;
+ const snapshotPaths = lastSnapshotPathsRef.current.get(target.deviceId);
+ if (applied > readbackSeq && snapshotPaths && !snapshotPaths.has(restored.path)) return;
}
+ // 删除其实已在对端成功过(墓碑)→ 同样不恢复,那一行不该再出现。
+ if (tombstonesRef.current.get(target.deviceId)?.has(restored.path)) return;
+ const current = loadedRef.current.rows;
+ if (current.some((row) => row.path === restored.path)) return;
+ const at =
+ removedIndex >= 0 && removedIndex <= current.length ? removedIndex : current.length;
+ commitRows(target.deviceId, [...current.slice(0, at), restored, ...current.slice(at)]);
+ };
- /**
- * 把乐观移除的那一行按原位插回。
- *
- * 「这次删除失败了,所以这一行该在」是一件**与快照版本无关的局部事实**,所以两种情况都用它:
- * ① 权威回读本身也失败(拿不到任何真相);
- * ② 回读拿到了快照,但它比已落库的更旧而被丢弃 —— 这一条是 seq gate 的代价:不补的话
- * 并发失败删除就不再收敛(先回的那份快照隐藏了仍在飞的自己,后回的自己又被丢弃,
- * 于是自己那一行永远回不来),而「并发失败删除必须各自收敛」是既有不变量。
- *
- * 刻意**不按取数版本号一刀切**:期间用户重开 picker / 切回本设备都会推进版本号,按它直接
- * gate 会把这次恢复跳过,那一行就一直从选择器里消失(而它在对端还在)。自带存在性检查,
- * 期间真有成功回读把它带回来了也不会插重。
- *
- * 但**必须尊重更新快照的否证**(Greptile review):上一轮为保住收敛性而在「回读被 seq gate
- * 拒绝」时也走这里,那条路径当时只查设备归属与存在性 —— 于是当对端其实已经没有这个项目了
- * (用户在对端删了 / 删除实际成功只是响应失败),更新的权威快照如实不含它,旧回读却仍能把它
- * 插回选择器;用户选中就撞 path guard,或打开对端同名但无关的目录。
- *
- * 判据用**原始**快照集合而不是落库后的行,见 lastSnapshotPathsRef —— 落库会扣掉仍在飞的
- * 乐观删除,拿它判会把「对端有、只是被 pending 过滤」也当成否证,直接废掉并发收敛。
- */
- const restoreRemovedRow = (readbackSeq?: number) => {
- const restored = removedRow;
- if (!restored) return;
- // 按当前设备 gate:若请求还在飞时用户已切到别的设备,把 A 的行插进 B 的 rows 会被
- // toDeviceProjectOptions 标成属于 B —— 选中它就把 A 的路径发给 B 了。这与「并发删除不能
- // 互相取消」不冲突:设备身份只排除「已切走」,不排除同设备内的并发。
+ try {
+ await removeDeviceLinkExistingProject(target.deviceId, option.path);
+ // 删成了 → 立墓碑。此刻可能已有一次「A 还在」的旧回读在飞,它落库会把这一行显示回来,
+ // 而成功路径本身不再更新列表(行早就被乐观移除了)—— 墓碑就是那道防线,见 tombstonesRef。
+ const deviceTombstones =
+ tombstonesRef.current.get(target.deviceId) ?? new Map<string, number>();
+ deviceTombstones.set(option.path, fetchSeqRef.current);
+ tombstonesRef.current.set(target.deviceId, deviceTombstones);
+ } catch {
+ // 老被控端可能没有 remove channel。回读一次收敛到被控端真相,
+ // 而不是留下一个「本地看着删了、对端其实还在」的幻影删除。
+ // 同样不动 requestIdRef:晚到的 effect 取数即使覆盖这次回读也无害 —— 两者都是被控端
+ // 真相,且都会减去仍在飞的乐观删除,结果一致。作废它只会误伤新设备的取数。
+ const readbackSeq = ++fetchSeqRef.current;
+ try {
+ const list = await loadDeviceLinkExistingProjects(target.deviceId);
+ // gate 用**设备身份**:只要设备没切走,这份回读就是被控端真相,该应用。不用版本号 ——
+ // 并发删除会互相把对方的回读判成过期,那一行既没在对端删成、又没被恢复,会一直消失。
if (currentDeviceIdRef.current !== target.deviceId) return;
- if (loadedRef.current.deviceId !== target.deviceId) return;
- // 已有**更新**的权威快照,且它的原始列表里没有这一行 → 对端确实没有,不恢复。
- if (readbackSeq !== undefined) {
- const applied = appliedSeqRef.current.get(target.deviceId) ?? 0;
- const snapshotPaths = lastSnapshotPathsRef.current.get(target.deviceId);
- if (applied > readbackSeq && snapshotPaths && !snapshotPaths.has(restored.path)) return;
+ // 只减**这台设备上**其它仍在飞的乐观删除;不含自己 —— 这次删除失败了,真相里有它就该
+ // 显示回来。跨设备的 pending 不参与,否则同名路径会互相误伤。
+ const othersPending = new Set(
+ [...(pendingRemovalsRef.current.get(target.deviceId) ?? [])].filter(
+ (path) => path !== option.path,
+ ),
+ );
+ // 快照比已落库的更旧 → 被丢弃。此时仍要让自己那一行回来,否则并发失败删除不再收敛;
+ // 但要带上 readbackSeq,好让恢复尊重「更新快照已否证这一行」的情形(见 restoreRemovedRow)。
+ if (!applySnapshot(target.deviceId, readbackSeq, list, othersPending)) {
+ restoreRemovedRow(readbackSeq);
}
- // 删除其实已在对端成功过(墓碑)→ 同样不恢复,那一行不该再出现。
- if (tombstonesRef.current.get(target.deviceId)?.has(restored.path)) return;
- const current = loadedRef.current.rows;
- if (current.some((row) => row.path === restored.path)) return;
- const at =
- removedIndex >= 0 && removedIndex <= current.length ? removedIndex : current.length;
- commitRows(target.deviceId, [...current.slice(0, at), restored, ...current.slice(at)]);
- };
-
- try {
- await removeDeviceLinkExistingProject(target.deviceId, option.path);
- // 删成了 → 立墓碑。此刻可能已有一次「A 还在」的旧回读在飞,它落库会把这一行显示回来,
- // 而成功路径本身不再更新列表(行早就被乐观移除了)—— 墓碑就是那道防线,见 tombstonesRef。
- const deviceTombstones =
- tombstonesRef.current.get(target.deviceId) ?? new Map<string, number>();
- deviceTombstones.set(option.path, fetchSeqRef.current);
- tombstonesRef.current.set(target.deviceId, deviceTombstones);
} catch {
- // 老被控端可能没有 remove channel。回读一次收敛到被控端真相,
- // 而不是留下一个「本地看着删了、对端其实还在」的幻影删除。
- // 同样不动 requestIdRef:晚到的 effect 取数即使覆盖这次回读也无害 —— 两者都是被控端
- // 真相,且都会减去仍在飞的乐观删除,结果一致。作废它只会误伤新设备的取数。
- const readbackSeq = ++fetchSeqRef.current;
- try {
- const list = await loadDeviceLinkExistingProjects(target.deviceId);
- // gate 用**设备身份**:只要设备没切走,这份回读就是被控端真相,该应用。不用版本号 ——
- // 并发删除会互相把对方的回读判成过期,那一行既没在对端删成、又没被恢复,会一直消失。
- if (currentDeviceIdRef.current !== target.deviceId) return;
- // 只减**这台设备上**其它仍在飞的乐观删除;不含自己 —— 这次删除失败了,真相里有它就该
- // 显示回来。跨设备的 pending 不参与,否则同名路径会互相误伤。
- const othersPending = new Set(
- [...(pendingRemovalsRef.current.get(target.deviceId) ?? [])].filter(
- (path) => path !== option.path,
- ),
- );
- // 快照比已落库的更旧 → 被丢弃。此时仍要让自己那一行回来,否则并发失败删除不再收敛;
- // 但要带上 readbackSeq,好让恢复尊重「更新快照已否证这一行」的情形(见 restoreRemovedRow)。
- if (!applySnapshot(target.deviceId, readbackSeq, list, othersPending)) {
- restoreRemovedRow(readbackSeq);
- }
- } catch {
- // 回读也失败(对端离线 / 隧道断)。此时**必须把行放回去**:删除既没在对端生效,
- // 权威列表也拿不到,保留乐观移除等于让选择器藏着一个远端仍然存在的项目,而且不给
- // 任何提示 —— 用户只能靠重开 picker 才发现它还在。
- restoreRemovedRow();
- }
- } finally {
- const set = pendingRemovalsRef.current.get(target.deviceId);
- set?.delete(option.path);
- if (set && set.size === 0) pendingRemovalsRef.current.delete(target.deviceId);
+ // 回读也失败(对端离线 / 隧道断)。此时**必须把行放回去**:删除既没在对端生效,
+ // 权威列表也拿不到,保留乐观移除等于让选择器藏着一个远端仍然存在的项目,而且不给
+ // 任何提示 —— 用户只能靠重开 picker 才发现它还在。
+ restoreRemovedRow();
}
- },
- [],
- );
+ } finally {
+ const set = pendingRemovalsRef.current.get(target.deviceId);
+ set?.delete(option.path);
+ if (set && set.size === 0) pendingRemovalsRef.current.delete(target.deviceId);
+ }
+ }, []);
/**
* 归属必须相符才输出选项 —— 这是上面把 deviceId 绑进状态的唯一目的:切设备的那一帧
@@ -348,9 +363,27 @@ export function useDeviceLinkProjects(
[deviceId, deviceName, loaded],
);
- // 归属还没对上就仍算「加载中」:否则切设备那一帧会闪一下「没有项目」的空态
- // (loading 要等 effect 才置 true)。宁可多显示一帧 spinner。
- const effectiveLoading = loading || (deviceId != null && loaded.deviceId !== deviceId);
+ // 归属还没对上 / picker 刚打开、effect 尚未执行时仍算「加载中」:否则切设备或首次打开
+ // 会闪一下「没有项目」的空态。状态与 deviceId 绑定,上一台的 error 也不会串到新设备。
+ const status: DeviceLinkProjectsStatus =
+ !enabled || !deviceId
+ ? 'idle'
+ : requestState.deviceId !== deviceId || requestState.status === 'idle'
+ ? 'loading'
+ : requestState.status;
+ const error = status === 'error' ? requestState.error : null;
+ const retry = useCallback(() => {
+ if (!enabled || !deviceId) return;
+ setRequestState({ deviceId, status: 'loading', error: null });
+ setRetryNonce((value) => value + 1);
+ }, [deviceId, enabled]);
- return { projects, loading: effectiveLoading, removeProject };
+ return {
+ projects,
+ loading: status === 'loading',
+ status,
+ error,
+ retry,
+ removeProject,
+ };
}
diff --git a/apps/desktop/src/renderer/hooks/useDeviceProviders.ts b/apps/desktop/src/renderer/hooks/useDeviceProviders.ts
index c1e4826609..fd748599c0 100644
--- a/apps/desktop/src/renderer/hooks/useDeviceProviders.ts
+++ b/apps/desktop/src/renderer/hooks/useDeviceProviders.ts
@@ -17,6 +17,7 @@ import { CONTROLLER_CAPABILITY_PROVIDER_LOGO_KINDS_V2 } from '@cindy/device-link
import type { ProviderView } from '@cindy/model-providers';
import { createLogger } from '@/lib/logger';
+import { extractIpcError } from '@/utils/ipcError';
const log = createLogger('useDeviceProviders');
@@ -47,9 +48,117 @@ const deviceGen = new Map<string, number>();
export type DeviceProvidersEvent =
| { status: 'loading' }
| ({ status: 'ready' } & DeviceProvidersPayload)
- | { status: 'error'; error: string };
+ | { status: 'error'; error: string; unsupported: boolean };
const listeners = new Map<string, Set<(event: DeviceProvidersEvent) => void>>();
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return !!value && typeof value === 'object' && !Array.isArray(value);
+}
+
+function isOptionalBoolean(value: unknown): boolean {
+ return value === undefined || typeof value === 'boolean';
+}
+
+function isProviderWireProtocol(value: unknown): boolean {
+ return (
+ value === undefined ||
+ value === 'anthropic-messages' ||
+ value === 'openai-responses' ||
+ value === 'openai-chat'
+ );
+}
+
+function isProviderModel(value: unknown): boolean {
+ if (!isRecord(value)) return false;
+ const efforts = value.efforts;
+ const defaultEffort = value.defaultEffort;
+ return (
+ typeof value.id === 'string' &&
+ value.id.length > 0 &&
+ typeof value.name === 'string' &&
+ typeof value.contextWindow === 'number' &&
+ Number.isFinite(value.contextWindow) &&
+ value.contextWindow > 0 &&
+ Array.isArray(efforts) &&
+ efforts.every((effort) => typeof effort === 'string') &&
+ (defaultEffort === null ||
+ (typeof defaultEffort === 'string' && efforts.includes(defaultEffort))) &&
+ isOptionalBoolean(value.disabled) &&
+ isOptionalBoolean(value.supportsFastMode) &&
+ isOptionalBoolean(value.defaultEnabled)
+ );
+}
+
+function isProviderRoute(value: unknown): boolean {
+ return (
+ isRecord(value) &&
+ isOptionalBoolean(value.disabled) &&
+ isProviderWireProtocol(value.wireProtocol)
+ );
+}
+
+function isProviderView(value: unknown): value is ProviderView {
+ if (!isRecord(value)) return false;
+ const routing = value.routing;
+ const models = value.models;
+ return (
+ typeof value.id === 'string' &&
+ value.id.length > 0 &&
+ typeof value.name === 'string' &&
+ Array.isArray(value.agents) &&
+ value.agents.every((agent) => typeof agent === 'string') &&
+ (routing === undefined ||
+ (isRecord(routing) && Object.values(routing).every(isProviderRoute))) &&
+ isRecord(models) &&
+ Object.values(models).every(
+ (entries) => Array.isArray(entries) && entries.every(isProviderModel),
+ ) &&
+ typeof value.connected === 'boolean' &&
+ isOptionalBoolean(value.suspended)
+ );
+}
+
+export function parseDeviceProvidersPayload(value: unknown): DeviceProvidersPayload {
+ if (!isRecord(value)) {
+ throw new Error('Invalid provider list response');
+ }
+ if (!Array.isArray(value.providers) || !value.providers.every(isProviderView)) {
+ throw new Error('Invalid provider list response');
+ }
+ const overrides = value.modelVisibilityOverrides;
+ if (
+ overrides !== undefined &&
+ (!isRecord(overrides) ||
+ Object.values(overrides).some((visible) => typeof visible !== 'boolean'))
+ ) {
+ throw new Error('Invalid provider visibility response');
+ }
+ // device-link 的 provider:list 是只读展示投影;旧/部分被控端可能省略 routing,
+ // 但 model-providers 的 connectedProvidersForAgent 需要每个声明的 agent 有一个
+ // routing entry 才会把供应商视为可用。只在远程解析边界补齐空 entry,不改变本机
+ // registry 对缺失 route 的严格语义,也保留已有 disabled 标记。
+ const providers = value.providers.map((provider) => {
+ const routing = { ...(provider.routing ?? {}) } as ProviderView['routing'];
+ for (const agent of provider.agents) {
+ if (routing[agent as keyof ProviderView['routing']] === undefined) {
+ Object.assign(routing, { [agent]: {} });
+ }
+ }
+ return { ...provider, routing };
+ });
+ return {
+ providers,
+ ...(overrides !== undefined
+ ? { modelVisibilityOverrides: overrides as Record<string, boolean> }
+ : {}),
+ };
+}
+
+/** 旧被控端没有 provider:list 时允许退化到 capabilities flat 列表;其它错误都是真失败。 */
+export function isDeviceProvidersUnsupportedError(error: unknown): boolean {
+ return extractIpcError(error)?.code === 'DEVICE_LINK_CHANNEL_NOT_ALLOWED';
+}
+
function notifyDeviceProviders(deviceId: string, event: DeviceProvidersEvent): void {
for (const listener of listeners.get(deviceId) ?? []) listener(event);
}
@@ -81,17 +190,14 @@ async function fetchDeviceProviders(deviceId: string): Promise<DeviceProvidersPa
const dl = getDeviceLink();
if (!dl) throw new Error('device-link IPC not available');
const p = (
- dl.invoke(deviceId, 'maker:provider:list', [{
- capabilities: [CONTROLLER_CAPABILITY_PROVIDER_LOGO_KINDS_V2],
- }]) as Promise<DeviceProvidersPayload>
+ dl.invoke(deviceId, 'maker:provider:list', [
+ {
+ capabilities: [CONTROLLER_CAPABILITY_PROVIDER_LOGO_KINDS_V2],
+ },
+ ]) as Promise<DeviceProvidersPayload>
)
.then((res) => {
- const payload: DeviceProvidersPayload = {
- providers: res?.providers ?? [],
- ...(res?.modelVisibilityOverrides !== undefined
- ? { modelVisibilityOverrides: res.modelVisibilityOverrides }
- : {}),
- };
+ const payload = parseDeviceProvidersPayload(res);
if (isCurrent()) {
cache.set(deviceId, payload);
inflight.delete(deviceId);
@@ -105,6 +211,7 @@ async function fetchDeviceProviders(deviceId: string): Promise<DeviceProvidersPa
notifyDeviceProviders(deviceId, {
status: 'error',
error: e instanceof Error ? e.message : String(e),
+ unsupported: isDeviceProvidersUnsupportedError(e),
});
}
throw e;
@@ -120,19 +227,27 @@ export interface UseDeviceProvidersResult {
loading: boolean;
/** 非 null = 拉取失败(典型:旧版被控端不识别通道);调用方据此回退扁平列表。 */
error: string | null;
+ /** true 仅表示老被控端没有 provider:list,可安全回退 capabilities-only 列表。 */
+ unsupported: boolean;
}
export function useDeviceProviders(deviceId?: string): UseDeviceProvidersResult {
- const [payload, setPayload] = useState<DeviceProvidersPayload>(
- deviceId ? (cache.get(deviceId) ?? EMPTY_PAYLOAD) : EMPTY_PAYLOAD,
+ const initialPayload = deviceId ? cache.get(deviceId) : undefined;
+ const [ownerDeviceId, setOwnerDeviceId] = useState<string | null>(
+ initialPayload ? (deviceId ?? null) : null,
);
+ const [payload, setPayload] = useState<DeviceProvidersPayload>(initialPayload ?? EMPTY_PAYLOAD);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
+ const [unsupported, setUnsupported] = useState(false);
useEffect(() => {
if (!deviceId) {
+ setOwnerDeviceId(null);
setPayload(EMPTY_PAYLOAD);
+ setLoading(false);
setError(null);
+ setUnsupported(false);
return;
}
let cancelled = false;
@@ -140,15 +255,21 @@ export function useDeviceProviders(deviceId?: string): UseDeviceProvidersResult
if (cancelled) return;
if (event.status === 'loading') {
// 保留上一份完整列表避免视觉跳变,但让模型选择逻辑等待同轮新快照。
+ setOwnerDeviceId(deviceId);
setLoading(true);
setError(null);
+ setUnsupported(false);
return;
}
if (event.status === 'error') {
+ setOwnerDeviceId(deviceId);
+ if (event.unsupported) setPayload(EMPTY_PAYLOAD);
setLoading(false);
setError(event.error);
+ setUnsupported(event.unsupported);
return;
}
+ setOwnerDeviceId(deviceId);
setPayload({
providers: event.providers,
...(event.modelVisibilityOverrides !== undefined
@@ -156,25 +277,33 @@ export function useDeviceProviders(deviceId?: string): UseDeviceProvidersResult
: {}),
});
setError(null);
+ setUnsupported(false);
setLoading(false);
});
const cached = cache.get(deviceId);
if (cached) {
+ setOwnerDeviceId(deviceId);
setPayload(cached);
setError(null);
+ setUnsupported(false);
setLoading(false);
return unsubscribe;
}
// cache miss:先清空,避免 fetch 解析前(失败则永远)残留上一设备的供应商。
+ setOwnerDeviceId(deviceId);
setPayload(EMPTY_PAYLOAD);
setLoading(true);
setError(null);
+ setUnsupported(false);
const remoteGeneration = deviceGen.get(deviceId) ?? 0;
fetchDeviceProviders(deviceId)
.catch((e: unknown) => {
if (cancelled) return;
if ((deviceGen.get(deviceId) ?? 0) !== remoteGeneration) return;
+ const nextUnsupported = isDeviceProvidersUnsupportedError(e);
+ if (nextUnsupported) setPayload(EMPTY_PAYLOAD);
setError(e instanceof Error ? e.message : String(e));
+ setUnsupported(nextUnsupported);
})
.finally(() => {
if (cancelled || (deviceGen.get(deviceId) ?? 0) !== remoteGeneration) return;
@@ -186,13 +315,20 @@ export function useDeviceProviders(deviceId?: string): UseDeviceProvidersResult
};
}, [deviceId]);
+ const ownsSelectedDevice = ownerDeviceId === (deviceId ?? null);
+ const selectedError = ownsSelectedDevice ? error : null;
+ const selectedUnsupported = ownsSelectedDevice ? unsupported : false;
+ const selectedPayload =
+ ownsSelectedDevice && !(selectedError && selectedUnsupported) ? payload : EMPTY_PAYLOAD;
+
return {
- providers: payload.providers,
- ...(payload.modelVisibilityOverrides !== undefined
- ? { modelVisibilityOverrides: payload.modelVisibilityOverrides }
+ providers: selectedPayload.providers,
+ ...(selectedPayload.modelVisibilityOverrides !== undefined
+ ? { modelVisibilityOverrides: selectedPayload.modelVisibilityOverrides }
: {}),
- loading,
- error,
+ loading: !!deviceId && (!ownsSelectedDevice || loading),
+ error: selectedError,
+ unsupported: selectedUnsupported,
};
}
diff --git a/apps/desktop/src/renderer/hooks/useVendorAuthGate.ts b/apps/desktop/src/renderer/hooks/useVendorAuthGate.ts
index f321c65257..174f31eaea 100644
--- a/apps/desktop/src/renderer/hooks/useVendorAuthGate.ts
+++ b/apps/desktop/src/renderer/hooks/useVendorAuthGate.ts
@@ -26,11 +26,14 @@ import { useTranslation } from 'react-i18next';
import {
connectedProvidersForAgent,
type AgentKind as ProviderAgentKind,
- type ProviderView,
} from '@cindy/model-providers';
import { useConfirmDialog } from '@/components/ui/confirm-dialog-provider';
import { useVendorReadiness, type Readiness } from '@/hooks/useVendorReadiness';
+import {
+ isDeviceProvidersUnsupportedError,
+ parseDeviceProvidersPayload,
+} from '@/hooks/useDeviceProviders';
import { remoteProjectsStore } from '@/features/device-link/remoteProjectsStore';
import type { AgentKind } from '@/lib/ccAgent.types';
@@ -133,12 +136,13 @@ function pickCopy(
* OAuth / 网关 key 专属口径,认不出 provider 体系的其他来源(xAI / 通用 OAuth /
* 自定义供应商),会把「没登 Codex 但配了其他 GPT 来源」的被控端误判成未登录。
*
- * 三个输入均可为 null(= 对应查询失败 / 老被控端不支持):
+ * 三个输入均可为 null(= 对应信息在已确认的旧端兼容路径里不可用):
* - binaryReady:codex 的运行时前提,false 优先返回 binary-missing(cc 随包,不参与);
* - sourceReady:provider 维度来源判定,可用时是唯一真相;
* - authReady:老被控端(allowlist 无 maker:provider:list)的回退口径,仅在
* sourceReady 不可用时消费,维持旧行为;
- * - 全部不可用 → ready(控制端不臆断,放行交给被控端 create-session / send 权威校验)。
+ * - 全部不可用 → ready(仅供两个相关 channel 都明确 unsupported 的旧端兼容路径)。
+ * 真正的连接 / 协议失败由调用方在进入本函数前 fail closed,不能折叠成 null。
*/
export function deriveRemoteReadiness(
vendor: AgentKind,
@@ -158,19 +162,44 @@ export function deriveRemoteReadiness(
/**
* device-link:把隧道 `maker:provider:list` 的响应解析成 sourceReady。纯函数,便于单测。
- * 协议异常(providers 字段缺失 / 非数组)返回 null = 判定不可用,走 authReady 回退,
- * 而非把被控端误判成「无来源」。
+ * 协议异常返回 null;resolveRemoteProviderProbe 会把它结算为真实错误。只有
+ * structured DEVICE_LINK_CHANNEL_NOT_ALLOWED 才允许走 authReady 旧端回退。
*/
export function sourceReadyFromProviderList(
value: unknown,
agent: ProviderAgentKind,
opts?: { includeSuspended?: boolean },
): boolean | null {
- const providers = (value as { providers?: ProviderView[] } | null)?.providers;
- if (!Array.isArray(providers)) return null;
- return connectedProvidersForAgent(providers, agent, {
- includeSuspended: opts?.includeSuspended === true,
- }).length > 0;
+ try {
+ const { providers } = parseDeviceProvidersPayload(value);
+ return connectedProvidersForAgent(providers, agent, {
+ includeSuspended: opts?.includeSuspended === true,
+ }).length > 0;
+ } catch {
+ return null;
+ }
+}
+
+export type RemoteProviderProbe =
+ | { status: 'ready'; sourceReady: boolean }
+ | { status: 'unsupported'; sourceReady: null }
+ | { status: 'error'; sourceReady: null };
+
+/** provider:list 探测分类:只有结构化 channel unsupported 可进入旧端回退。 */
+export function resolveRemoteProviderProbe(
+ result: PromiseSettledResult<unknown>,
+ agent: ProviderAgentKind,
+ opts?: { includeSuspended?: boolean },
+): RemoteProviderProbe {
+ if (result.status === 'rejected') {
+ return isDeviceProvidersUnsupportedError(result.reason)
+ ? { status: 'unsupported', sourceReady: null }
+ : { status: 'error', sourceReady: null };
+ }
+ const sourceReady = sourceReadyFromProviderList(result.value, agent, opts);
+ return sourceReady === null
+ ? { status: 'error', sourceReady: null }
+ : { status: 'ready', sourceReady };
}
interface GateResult {
@@ -237,8 +266,8 @@ export function useVendorAuthGate(): UseVendorAuthGateReturn {
// device-link:远程草稿 / 远程会话 → 就绪态以**被控端**为准(控制端本机配置无关)。
// 两条隧道查询并行:provider:list 提供与本地 / 手机同源的来源判定(唯一真相),
// agent:status 提供 codex binary 轴 + 老被控端的 authReady 回退口径。
- // 任一查询失败不在控制端臆断(见 deriveRemoteReadiness 的 null 语义),
- // 全部失败放行交给被控端 create-session / send 做权威校验(host = 单一真相源)。
+ // provider:list 只有结构化 unsupported 才能回退 agent:status。真实网络 / 协议失败
+ // 必须 fail closed,否则模型选择器已经显示读取失败,发送门禁却仍会放行旧快照。
const deviceId = options?.deviceId;
if (deviceId) {
const providerAgent: ProviderAgentKind =
@@ -251,12 +280,29 @@ export function useVendorAuthGate(): UseVendorAuthGateReturn {
statusRes.status === 'fulfilled'
? (statusRes.value as { binaryReady: boolean; authReady: boolean })
: null;
+ const providerProbe = resolveRemoteProviderProbe(providersRes, providerAgent, {
+ includeSuspended: options?.existingSessionRoute === true,
+ });
+ const statusUnsupported =
+ statusRes.status === 'rejected' &&
+ isDeviceProvidersUnsupportedError(statusRes.reason);
+ if (
+ providerProbe.status === 'error' ||
+ (providerProbe.status === 'unsupported' &&
+ statusRes.status === 'rejected' &&
+ !statusUnsupported)
+ ) {
+ await confirm({
+ title: t('newChat.modelSelector.remoteLoadFailedShort'),
+ description: t('newChat.modelSelector.remoteLoadFailed'),
+ confirmText: t('logic.confirm.gotIt'),
+ showCancel: false,
+ autoFocusConfirm: true,
+ });
+ return { proceed: false };
+ }
const sourceReady =
- providersRes.status === 'fulfilled'
- ? sourceReadyFromProviderList(providersRes.value, providerAgent, {
- includeSuspended: options?.existingSessionRoute === true,
- })
- : null;
+ providerProbe.status === 'ready' ? providerProbe.sourceReady : null;
const remoteReadiness = deriveRemoteReadiness(vendor, {
binaryReady: status?.binaryReady ?? null,
sourceReady,
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 420cd87445..8273f672b8 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -4896,6 +4896,11 @@
"generic": "Subscription-direct models are not supported in SSH remote sessions yet"
},
"discovering": "Fetching models…",
+ "remoteLoading": "Loading models from the remote device…",
+ "remoteLoadFailed": "Couldn't load models from the remote device. Check the connection and try again.",
+ "remoteLoadFailedShort": "Model loading failed",
+ "retryRemoteModels": "Reload models",
+ "remoteEmpty": "This device has no available models",
"effortLabel": "Effort level",
"edit": "Edit",
"options": "Options",
@@ -5061,6 +5066,8 @@
"browseProjectFolder": "Choose another project folder",
"dialogue": "Chat",
"dialogueOrSelectProject": "Chat or select project",
+ "remoteProjectsLoadFailed": "Couldn't load projects from {{device}}. Check the connection and try again.",
+ "retryRemoteProjects": "Reload projects",
"removeFromList": "Remove from list",
"missingDir": "Folder not found"
},
@@ -6180,6 +6187,7 @@
"remoteProviderUnsupported": "This provider is not supported in SSH remote sessions — pick another source",
"remoteNativeOauthUnavailable": "Claude.ai subscription is not connected — connect it first or pick a gateway model",
"deviceStillLoading": "Remote device is still loading, please wait",
+ "remoteDefaultsLoadFailed": "Could not load the remote device settings. Check the connection; Cindy is retrying.",
"worktreeMissingRepo": "Can't create a worktree: the current directory's repo root is missing",
"worktreeRepoHint": "Try picking the working directory again, and retry once the folder badge at the bottom right refreshes",
"sessionInactive": "Session is no longer active",
@@ -6195,6 +6203,14 @@
"allMachines": "All",
"localMachine": "This device",
"connecting": "Connecting…",
+ "tasksLoading": "Loading sessions from {{device}}…",
+ "tasksLoadFailed": "Couldn't load sessions from {{device}}. Check the connection and try again.",
+ "tasksPartiallyFailed": "Sessions from {{device}} couldn't be loaded. Showing only content that loaded successfully.",
+ "retryTasks": "Reload sessions",
+ "devicesLoading": "Loading remote devices…",
+ "devicesLoadFailed": "Couldn't load the remote device list. Check the connection and try again.",
+ "devicesPartiallyFailed": "The remote device list couldn't be refreshed. Showing only content that loaded successfully.",
+ "retryDevices": "Reload devices",
"remoteSettings": "Remote connection settings",
"multiSelect": "Multi-select",
"deselect": "Deselect",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 6e7d91114d..a53cbb1863 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -4894,6 +4894,11 @@
"generic": "サブスクリプション直結モデルは SSH リモートセッションに未対応です"
},
"discovering": "モデルを取得中…",
+ "remoteLoading": "リモートデバイスからモデルを読み込み中…",
+ "remoteLoadFailed": "リモートデバイスのモデルを読み込めませんでした。接続を確認して再試行してください。",
+ "remoteLoadFailedShort": "モデルの読み込みに失敗",
+ "retryRemoteModels": "モデルを再読み込み",
+ "remoteEmpty": "このデバイスには利用可能なモデルがありません",
"effortLabel": "推論強度",
"edit": "編集",
"options": "オプション",
@@ -5059,6 +5064,8 @@
"browseProjectFolder": "別のプロジェクトフォルダを選択",
"dialogue": "対話",
"dialogueOrSelectProject": "対話またはプロジェクトを選択",
+ "remoteProjectsLoadFailed": "{{device}} のプロジェクトを読み込めませんでした。接続を確認して再試行してください。",
+ "retryRemoteProjects": "プロジェクトを再読み込み",
"removeFromList": "リストから削除",
"missingDir": "フォルダが見つかりません"
},
@@ -6169,6 +6176,7 @@
"remoteProviderUnsupported": "このプロバイダーは SSH リモートセッションに対応していません。別のソースを選択してください",
"remoteNativeOauthUnavailable": "Claude.ai サブスクリプションが未接続です。先に接続するか、ゲートウェイモデルを選択してください",
"deviceStillLoading": "リモートデバイスの読み込み中です。しばらくお待ちください",
+ "remoteDefaultsLoadFailed": "リモートデバイスの設定を読み込めませんでした。接続を確認してください。Cindy が再試行しています。",
"worktreeMissingRepo": "worktree を作成できません:現在のディレクトリのリポジトリルートが見つかりません",
"worktreeRepoHint": "作業ディレクトリを選び直し、右下のフォルダー表示が更新されてから再試行してください",
"sessionInactive": "セッションはすでにアクティブではありません",
@@ -6184,6 +6192,14 @@
"allMachines": "すべて",
"localMachine": "このデバイス",
"connecting": "接続中…",
+ "tasksLoading": "{{device}} のセッションを読み込み中…",
+ "tasksLoadFailed": "{{device}} のセッションを読み込めませんでした。接続を確認して再試行してください。",
+ "tasksPartiallyFailed": "{{device}} のセッションを読み込めませんでした。読み込み済みの内容のみ表示しています。",
+ "retryTasks": "セッションを再読み込み",
+ "devicesLoading": "リモートデバイスを読み込み中…",
+ "devicesLoadFailed": "リモートデバイスの一覧を読み込めませんでした。接続を確認して再試行してください。",
+ "devicesPartiallyFailed": "リモートデバイスの一覧を更新できませんでした。読み込み済みの内容のみ表示しています。",
+ "retryDevices": "デバイスを再読み込み",
"remoteSettings": "リモート接続設定",
"multiSelect": "複数選択",
"deselect": "選択を解除",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index f93dabdda5..ae883687d6 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -4894,6 +4894,11 @@
"generic": "구독 직결 모델은 SSH 원격 세션을 아직 지원하지 않습니다"
},
"discovering": "모델 가져오는 중…",
+ "remoteLoading": "원격 기기에서 모델을 불러오는 중…",
+ "remoteLoadFailed": "원격 기기의 모델을 불러오지 못했습니다. 연결을 확인한 후 다시 시도하세요.",
+ "remoteLoadFailedShort": "모델 불러오기 실패",
+ "retryRemoteModels": "모델 다시 불러오기",
+ "remoteEmpty": "이 기기에 사용 가능한 모델이 없습니다",
"effortLabel": "추론 강도",
"edit": "편집",
"options": "옵션",
@@ -5059,6 +5064,8 @@
"browseProjectFolder": "다른 프로젝트 폴더 선택",
"dialogue": "대화",
"dialogueOrSelectProject": "대화 또는 프로젝트 선택",
+ "remoteProjectsLoadFailed": "{{device}}의 프로젝트를 불러오지 못했습니다. 연결을 확인한 후 다시 시도하세요.",
+ "retryRemoteProjects": "프로젝트 다시 불러오기",
"removeFromList": "목록에서 제거",
"missingDir": "폴더를 찾을 수 없음"
},
@@ -6169,6 +6176,7 @@
"remoteProviderUnsupported": "이 제공자는 SSH 원격 세션을 지원하지 않습니다. 다른 소스를 선택하세요",
"remoteNativeOauthUnavailable": "Claude.ai 구독이 연결되지 않았습니다. 먼저 연결하거나 게이트웨이 모델을 선택하세요",
"deviceStillLoading": "원격 기기가 아직 로딩 중입니다. 잠시 기다려 주세요",
+ "remoteDefaultsLoadFailed": "원격 기기 설정을 불러오지 못했습니다. 연결을 확인하세요. Cindy가 다시 시도하고 있습니다.",
"worktreeMissingRepo": "worktree를 만들 수 없습니다: 현재 디렉터리의 리포지토리 루트가 없습니다",
"worktreeRepoHint": "작업 디렉터리를 다시 선택한 뒤 오른쪽 아래 폴더 표시가 갱신되면 다시 시도하세요",
"sessionInactive": "세션이 더 이상 활성 상태가 아닙니다",
@@ -6184,6 +6192,14 @@
"allMachines": "전체",
"localMachine": "이 기기",
"connecting": "연결 중…",
+ "tasksLoading": "{{device}}에서 세션을 불러오는 중…",
+ "tasksLoadFailed": "{{device}}의 세션을 불러오지 못했습니다. 연결을 확인한 후 다시 시도하세요.",
+ "tasksPartiallyFailed": "{{device}}의 세션을 불러오지 못했습니다. 불러온 내용만 표시합니다.",
+ "retryTasks": "세션 다시 불러오기",
+ "devicesLoading": "원격 기기를 불러오는 중…",
+ "devicesLoadFailed": "원격 기기 목록을 불러오지 못했습니다. 연결을 확인한 후 다시 시도하세요.",
+ "devicesPartiallyFailed": "원격 기기 목록을 새로 고치지 못했습니다. 불러온 내용만 표시합니다.",
+ "retryDevices": "기기 다시 불러오기",
"remoteSettings": "원격 연결 설정",
"multiSelect": "다중 선택",
"deselect": "선택 해제",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index cc5cc40f30..1c2a094c03 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -4894,6 +4894,11 @@
"generic": "订阅直连模型协议暂不支持 SSH 远程会话"
},
"discovering": "正在获取模型…",
+ "remoteLoading": "正在从远程设备读取模型…",
+ "remoteLoadFailed": "无法读取远程设备上的模型。请检查连接后重试。",
+ "remoteLoadFailedShort": "模型读取失败",
+ "retryRemoteModels": "重新读取模型",
+ "remoteEmpty": "这台设备没有可用模型",
"effortLabel": "推理强度",
"edit": "编辑",
"options": "选项",
@@ -5059,6 +5064,8 @@
"browseProjectFolder": "选择其他项目文件夹",
"dialogue": "对话",
"dialogueOrSelectProject": "对话或选择项目",
+ "remoteProjectsLoadFailed": "无法读取 {{device}} 上的项目。请检查连接后重试。",
+ "retryRemoteProjects": "重新读取项目",
"removeFromList": "从列表中移除",
"missingDir": "目录不存在"
},
@@ -6169,6 +6176,7 @@
"remoteProviderUnsupported": "该供应商不支持 SSH 远程会话,请更换来源",
"remoteNativeOauthUnavailable": "未连接 Claude.ai 订阅,请先连接或选择网关模型",
"deviceStillLoading": "远程设备仍在加载中,请稍候",
+ "remoteDefaultsLoadFailed": "无法读取远程设备配置。请检查连接,Cindy 正在重试。",
"worktreeMissingRepo": "无法开 worktree:缺少当前目录的仓库根",
"worktreeRepoHint": "可尝试重新选一次工作目录,等右下角文件夹标识刷新后再试",
"sessionInactive": "任务已不再处于活跃状态",
@@ -6184,6 +6192,14 @@
"allMachines": "所有",
"localMachine": "本机",
"connecting": "连接中…",
+ "tasksLoading": "正在从 {{device}} 读取任务…",
+ "tasksLoadFailed": "无法读取 {{device}} 上的任务。请检查连接后重试。",
+ "tasksPartiallyFailed": "未能读取 {{device}} 上的任务,当前仅显示已加载的内容。",
+ "retryTasks": "重新读取任务",
+ "devicesLoading": "正在读取远程设备…",
+ "devicesLoadFailed": "无法读取远程设备列表。请检查连接后重试。",
+ "devicesPartiallyFailed": "无法刷新远程设备列表,当前仅显示已加载的内容。",
+ "retryDevices": "重新读取设备",
"remoteSettings": "远程连接设置",
"multiSelect": "多选",
"deselect": "取消勾选",