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。

feat(mobile): 远程选择项目目录时支持切换 Windows 盘符 (#5058)

Lizia7a584ea200f
diff --git a/apps/desktop/src/main/__tests__/fsBrowse.test.ts b/apps/desktop/src/main/__tests__/fsBrowse.test.ts
index ba9143ec8c..01c42c9428 100644
--- a/apps/desktop/src/main/__tests__/fsBrowse.test.ts
+++ b/apps/desktop/src/main/__tests__/fsBrowse.test.ts
@@ -2,7 +2,8 @@
* fsBrowse.test.ts —— 本机目录浏览纯函数(项目选择器 / device-link 隧道用)。
*
* 覆盖:list-dir 只回目录(含 hidden,对齐 SSH `ls -A`)、每项带 host-native 绝对 path、
- * `~` 展开、parent 计算、根 parent=null;stat 三态;mkdir-p 幂等;错误走 throwIpcError。
+ * `~` 展开、parent 计算、根 parent=null;Windows 追加可选 drives(非 Windows 不枚举、枚举
+ * 为空时省略;超出等待预算时省略 drives 并标 drivesPending);stat 三态;mkdir-p 幂等;错误走 throwIpcError。
* 断言使用 host-native path 语义;mock node:fs / node:os。
*/
import path from 'node:path';
@@ -22,8 +23,12 @@ vi.mock('node:fs', () => ({
promises: { readdir: h.readdir, stat: h.stat, mkdir: h.mkdir },
}));
vi.mock('node:os', () => ({ homedir: h.homedir }));
+vi.mock('../logger.js', () => ({
+ createLogger: () => ({ debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() }),
+}));
import { expandHome, listDir, statPath, mkdirP } from '../fsBrowse/ipc.js';
+import { buildDriveOptions } from '../fsBrowse/windowsDrives.js';
/** 造一个 Dirent-ish。 */
function dirent(name: string, kind: 'dir' | 'file' | 'symlink') {
@@ -84,7 +89,57 @@ describe('listDir', () => {
it('readdir 失败 → throwIpcError(FS_BROWSE_FAILED)', async () => {
h.readdir.mockRejectedValueOnce(new Error('EACCES'));
- await expect(listDir('/root/secret')).rejects.toThrow('[FS_BROWSE_FAILED]');
+ await expect(listDir('/root/secret', { platform: 'darwin' })).rejects.toThrow('[FS_BROWSE_FAILED]');
+ });
+
+ it('Windows:追加 drives(盘符根 + 当前盘标记由 buildDriveOptions 生成)', async () => {
+ h.readdir.mockResolvedValueOnce([]);
+ // 盘符根是 Windows wire 格式(被控端 host-native),固定写反斜杠。resolvedPath 由宿主
+ // path 决定(Windows 开发机上会落在某个盘),当前盘标记的细节见 fsBrowseWindowsDrives.test。
+ const roots = ['C:\\', 'D:\\'];
+ const listDriveRoots = vi.fn().mockResolvedValue(roots);
+ const res = await listDir('~', { platform: 'win32', listDriveRoots });
+ expect(listDriveRoots).toHaveBeenCalledTimes(1);
+ expect(res.drives).toEqual(buildDriveOptions(roots, res.resolvedPath));
+ expect(res.drives?.map((d) => d.path)).toEqual(expect.arrayContaining(roots));
+ expect(res).not.toHaveProperty('drivesPending');
+ });
+
+ it('非 Windows 不枚举盘符,也不带 drives 字段', async () => {
+ h.readdir.mockResolvedValueOnce([]);
+ const listDriveRoots = vi.fn().mockResolvedValue(['C:\\']);
+ const res = await listDir('~', { platform: 'darwin', listDriveRoots });
+ expect(listDriveRoots).not.toHaveBeenCalled();
+ expect(res).not.toHaveProperty('drives');
+ });
+
+ it('Windows 盘符枚举为空 / 失败 → 省略 drives,目录列表照常返回', async () => {
+ h.readdir.mockResolvedValue([dirent('Code', 'dir')]);
+ const empty = await listDir('~', { platform: 'win32', listDriveRoots: async () => [] });
+ expect(empty).not.toHaveProperty('drives');
+ expect(empty).not.toHaveProperty('drivesPending');
+ const failed = await listDir('~', {
+ platform: 'win32',
+ listDriveRoots: () => Promise.reject(new Error('boom')),
+ });
+ expect(failed.entries.map((e) => e.name)).toEqual(['Code']);
+ expect(failed).not.toHaveProperty('drives');
+ expect(failed).not.toHaveProperty('drivesPending');
+ });
+
+ it('Windows 盘符枚举超出等待预算 → 先不带 drives 返回,并标记 pending 供控制端刷新', async () => {
+ vi.useFakeTimers();
+ try {
+ h.readdir.mockResolvedValueOnce([]);
+ const pending = listDir('~', { platform: 'win32', listDriveRoots: () => new Promise<string[]>(() => {}) });
+ await vi.advanceTimersByTimeAsync(1_500);
+ const res = await pending;
+ expect(res.resolvedPath).toBe(HOME);
+ expect(res).not.toHaveProperty('drives');
+ expect(res.drivesPending).toBe(true);
+ } finally {
+ vi.useRealTimers();
+ }
});
});
diff --git a/apps/desktop/src/main/__tests__/fsBrowseWindowsDrives.test.ts b/apps/desktop/src/main/__tests__/fsBrowseWindowsDrives.test.ts
new file mode 100644
index 0000000000..35ccb132ec
--- /dev/null
+++ b/apps/desktop/src/main/__tests__/fsBrowseWindowsDrives.test.ts
@@ -0,0 +1,89 @@
+/**
+ * fsBrowseWindowsDrives.test.ts —— 目录浏览的 Windows 盘符枚举。
+ *
+ * 覆盖:GetLogicalDrives 输出解析、当前盘标记与补全(Windows 路径语义,用 path.win32 固定)、
+ * 缓存 / 过期后先回旧值再后台刷新 / 并发合并、失败降级为空列表。
+ */
+import { describe, it, expect, vi } from 'vitest';
+
+vi.mock('../logger.js', () => ({
+ createLogger: () => ({ debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() }),
+}));
+
+import {
+ buildDriveOptions,
+ createWindowsDriveRootLister,
+ parseLogicalDriveRoots,
+} from '../fsBrowse/windowsDrives.js';
+
+describe('parseLogicalDriveRoots', () => {
+ it('每行一个根,去重、统一大写并排序;忽略空行与非盘符行', () => {
+ expect(parseLogicalDriveRoots('E:\\\r\nc:\\\r\n\r\nD:\\\r\nC:\\\r\nnoise\r\n\\\\srv\\share\\\r\n'))
+ .toEqual(['C:\\', 'D:\\', 'E:\\']);
+ });
+});
+
+describe('buildDriveOptions(Windows 路径语义)', () => {
+ it('标出当前所在盘,盘符大小写不敏感', () => {
+ expect(buildDriveOptions(['C:\\', 'D:\\'], 'd:\\work\\cindy')).toEqual([
+ { name: 'C:', path: 'C:\\', current: false },
+ { name: 'D:', path: 'D:\\', current: true },
+ ]);
+ });
+
+ it('当前盘不在枚举结果里(枚举后新挂载)→ 补进列表并按盘符排序', () => {
+ expect(buildDriveOptions(['C:\\', 'E:\\'], 'D:\\'))
+ .toEqual([
+ { name: 'C:', path: 'C:\\', current: false },
+ { name: 'D:', path: 'D:\\', current: true },
+ { name: 'E:', path: 'E:\\', current: false },
+ ]);
+ });
+
+ it('当前位于 UNC 共享 → 追加该共享根作为当前项', () => {
+ expect(buildDriveOptions(['C:\\'], '\\\\nas\\team\\proj')).toEqual([
+ { name: 'C:', path: 'C:\\', current: false },
+ { name: '\\\\nas\\team', path: '\\\\nas\\team\\', current: true },
+ ]);
+ });
+});
+
+describe('createWindowsDriveRootLister', () => {
+ it('调用 PowerShell 的 GetLogicalDrives,隐藏窗口且带超时', async () => {
+ const run = vi.fn().mockResolvedValue({ stdout: 'C:\\\r\nD:\\\r\n' });
+ const list = createWindowsDriveRootLister({ run });
+ expect(await list()).toEqual(['C:\\', 'D:\\']);
+ const [file, args, options] = run.mock.calls[0]!;
+ expect(file).toMatch(/powershell\.exe$/i);
+ expect(args).toContain('[System.IO.Directory]::GetLogicalDrives()');
+ expect(options).toMatchObject({ windowsHide: true, timeout: expect.any(Number) });
+ });
+
+ it('缓存期内不重复起进程;并发调用合并为一次', async () => {
+ const run = vi.fn().mockResolvedValue({ stdout: 'C:\\\r\n' });
+ const list = createWindowsDriveRootLister({ run, now: () => 0 });
+ await Promise.all([list(), list()]);
+ await list();
+ expect(run).toHaveBeenCalledTimes(1);
+ });
+
+ it('过期后先回旧值,后台刷新完成后返回新值', async () => {
+ let clock = 0;
+ const run = vi.fn()
+ .mockResolvedValueOnce({ stdout: 'C:\\\r\n' })
+ .mockResolvedValueOnce({ stdout: 'C:\\\r\nF:\\\r\n' });
+ const list = createWindowsDriveRootLister({ run, now: () => clock });
+ expect(await list()).toEqual(['C:\\']);
+ clock = 60_000;
+ expect(await list()).toEqual(['C:\\']);
+ expect(run).toHaveBeenCalledTimes(2);
+ await vi.waitFor(async () => expect(await list()).toEqual(['C:\\', 'F:\\']));
+ expect(run).toHaveBeenCalledTimes(2);
+ });
+
+ it('PowerShell 失败 / 超时 → 空列表,不 reject', async () => {
+ const run = vi.fn().mockRejectedValue(Object.assign(new Error('timeout'), { killed: true }));
+ const list = createWindowsDriveRootLister({ run });
+ await expect(list()).resolves.toEqual([]);
+ });
+});
diff --git a/apps/desktop/src/main/fsBrowse/ipc.ts b/apps/desktop/src/main/fsBrowse/ipc.ts
index 9b6a6c5f7f..ce6ce8b819 100644
--- a/apps/desktop/src/main/fsBrowse/ipc.ts
+++ b/apps/desktop/src/main/fsBrowse/ipc.ts
@@ -7,7 +7,10 @@
* 在**被控端**进程执行 —— 被控端 = host,数据真相在它本地 FS。
*
* 能力面(只读 + mkdir -p):
- * - fs:list-dir 列子目录(含 hidden,对齐 SSH `ls -A`;不含文件)
+ * - fs:list-dir 列子目录(含 hidden,对齐 SSH `ls -A`;不含文件)。Windows 被控端额外回
+ * 可选 `drives`(盘符列表 + 当前盘),供控制端切到其它盘;首次枚举超时再回
+ * 可选 `drivesPending`,控制端可刷新。旧被控端不回,控制端不显示切换,
+ * 旧控制端忽略新字段。
* - fs:stat-path 判断路径是 dir / file / missing
* - fs:mkdir-p 幂等创建目录(用户输入一个尚不存在的项目路径时)
* **不**提供文件读/写/删/exec —— 仅项目目录选择所需的最小面(allowlist 注释同款理由)。
@@ -25,6 +28,9 @@ import * as os from 'node:os';
import * as path from 'node:path';
import { throwIpcError, requireObject, requireString } from '../utils/ipcValidate.js';
+import { buildDriveOptions, listWindowsDriveRoots, type FsBrowseDrive } from './windowsDrives.js';
+
+export type { FsBrowseDrive } from './windowsDrives.js';
export interface FsBrowseEntry {
name: string;
@@ -37,6 +43,14 @@ export interface FsListDirResult {
entries: FsBrowseEntry[];
/** host-native 上级目录;已在根则 null。 */
parent: string | null;
+ /** 仅 Windows:本机盘符(含当前盘标记)。盘符枚举失败或超出等待预算时省略。 */
+ drives?: FsBrowseDrive[];
+ /** 仅 Windows:盘符枚举超出等待预算、后台仍在进行。控制端可据此刷新;旧端忽略。 */
+ drivesPending?: boolean;
+}
+export interface FsListDirDeps {
+ platform?: NodeJS.Platform;
+ listDriveRoots?: () => Promise<string[]>;
}
export interface FsStatResult {
kind: 'dir' | 'file' | 'missing';
@@ -66,9 +80,36 @@ export function expandHome(input: string): string {
return path.resolve(home, raw);
}
+/**
+ * 盘符列表最多等这么久:首次枚举要起 PowerShell,不能拖慢目录打开;超时就先不带盘符返回,
+ * 并标 drivesPending,让控制端在当前目录再拉一次。枚举在后台继续写入缓存。
+ */
+const DRIVE_LIST_WAIT_MS = 1_500;
+const DRIVE_WAIT_TIMEOUT = Symbol('drive-wait-timeout');
+
+async function waitForDriveRoots(
+ listDriveRoots: () => Promise<string[]>,
+): Promise<{ roots: string[]; pending: boolean }> {
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ const expired = new Promise<typeof DRIVE_WAIT_TIMEOUT>((resolve) => {
+ timer = setTimeout(() => resolve(DRIVE_WAIT_TIMEOUT), DRIVE_LIST_WAIT_MS);
+ });
+ try {
+ const result = await Promise.race([listDriveRoots().catch(() => [] as string[]), expired]);
+ if (result === DRIVE_WAIT_TIMEOUT) return { roots: [], pending: true };
+ return { roots: result, pending: false };
+ } finally {
+ clearTimeout(timer);
+ }
+}
+
/** 列出目录下的**子目录**(含 hidden,对齐 SSH `ls -A`;文件不列)。每项带 host-native 绝对路径。 */
-export async function listDir(rawPath: string): Promise<FsListDirResult> {
+export async function listDir(rawPath: string, deps: FsListDirDeps = {}): Promise<FsListDirResult> {
const resolvedPath = expandHome(rawPath);
+ // 与 readdir 并行;该 promise 永不 reject,readdir 失败提前抛出也不会留下未处理的拒绝。
+ const driveRoots = (deps.platform ?? process.platform) === 'win32'
+ ? waitForDriveRoots(deps.listDriveRoots ?? listWindowsDriveRoots)
+ : null;
let dirents: Dirent[];
try {
// encoding:'utf8' 固定到 name:string 的重载(否则 readdir 返回 string|Buffer 名联合)。
@@ -93,7 +134,11 @@ export async function listDir(rawPath: string): Promise<FsListDirResult> {
}
entries.sort((a, b) => a.name.localeCompare(b.name));
const parent = path.dirname(resolvedPath);
- return { resolvedPath, entries, parent: parent === resolvedPath ? null : parent };
+ const result: FsListDirResult = { resolvedPath, entries, parent: parent === resolvedPath ? null : parent };
+ const driveWait = driveRoots ? await driveRoots : null;
+ if (driveWait?.roots.length) result.drives = buildDriveOptions(driveWait.roots, resolvedPath);
+ else if (driveWait?.pending) result.drivesPending = true;
+ return result;
}
/** 判断路径状态:dir / file / missing(missing 用于「输入了不存在的新项目目录」分支)。 */
diff --git a/apps/desktop/src/main/fsBrowse/windowsDrives.ts b/apps/desktop/src/main/fsBrowse/windowsDrives.ts
new file mode 100644
index 0000000000..13dd14d3fa
--- /dev/null
+++ b/apps/desktop/src/main/fsBrowse/windowsDrives.ts
@@ -0,0 +1,125 @@
+/**
+ * Windows 盘符枚举 —— 目录浏览(`fs:list-dir`)的「切换盘符」用。
+ *
+ * Windows 没有能导航到其它盘的上级目录:`C:\` 的上级就是它自己,只靠逐级浏览永远到不了
+ * `D:\`。这里列出本机逻辑驱动器,随 list-dir 结果回给控制端直接切换。
+ *
+ * 只读盘符表(Win32 GetLogicalDrives),不访问任何磁盘:断线的网络映射盘、空光驱都不会让
+ * 探测卡住(逐个 stat `A:`~`Z:` 会在断线网络盘上长时间占住 libuv 线程池)。Node 没有该 API,
+ * 借 PowerShell 调 .NET;结果短缓存,失败按空列表降级(控制端不显示盘符切换)。
+ */
+
+import { execFile } from 'node:child_process';
+import path from 'node:path';
+import { promisify } from 'node:util';
+
+import { createLogger } from '../logger.js';
+
+const log = createLogger('fsBrowse/windowsDrives');
+const execFileAsync = promisify(execFile);
+
+export interface FsBrowseDrive {
+ /** 显示名:盘符为 `C:`;UNC 共享为根路径去掉末尾分隔符。 */
+ name: string;
+ /** host-native 根路径(如 `C:\`),控制端直接拿它调 fs:list-dir。 */
+ path: string;
+ /** 当前浏览路径是否位于该根下。 */
+ current: boolean;
+}
+
+type DriveCommand = (
+ file: string,
+ args: string[],
+ options: { encoding: 'utf8'; timeout: number; maxBuffer: number; windowsHide: boolean },
+) => Promise<{ stdout: string }>;
+
+/** 插拔 U 盘等变化不频繁;缓存只为避免逐级浏览时每层都起一次 PowerShell。 */
+const DRIVE_CACHE_TTL_MS = 30_000;
+/** 忙碌主机上 PowerShell 冷启动可能数秒;超时只影响盘符列表,不影响目录列表本身。 */
+const DRIVE_COMMAND_TIMEOUT_MS = 5_000;
+
+/** 解析 GetLogicalDrives 输出(每行一个 `C:\`),去重、统一大写并按盘符排序。 */
+export function parseLogicalDriveRoots(stdout: string): string[] {
+ const roots = new Set<string>();
+ for (const line of stdout.split(/\r?\n/)) {
+ const match = /^([A-Za-z]):\\?$/.exec(line.trim());
+ if (match) roots.add(`${match[1]!.toUpperCase()}:\\`);
+ }
+ return [...roots].sort();
+}
+
+function driveLetterRoot(root: string): string | null {
+ const match = /^([A-Za-z]):[\\/]?$/.exec(root);
+ return match ? `${match[1]!.toUpperCase()}:\\` : null;
+}
+
+/**
+ * 盘符列表 + 标出当前所在盘。当前路径位于未列出的根(枚举后新挂的盘、UNC 共享)时补进去,
+ * 保证控制端总能看到「当前盘」。路径语义固定按 Windows 解析(只在 win32 被控端调用)。
+ */
+export function buildDriveOptions(roots: readonly string[], resolvedPath: string): FsBrowseDrive[] {
+ const currentRoot = path.win32.parse(resolvedPath).root;
+ const currentDrive = driveLetterRoot(currentRoot);
+ const driveRoots = new Set(roots);
+ if (currentDrive) driveRoots.add(currentDrive);
+ const drives: FsBrowseDrive[] = [...driveRoots].sort().map((root) => ({
+ name: root.slice(0, 2),
+ path: root,
+ current: root === currentDrive,
+ }));
+ if (!currentDrive && currentRoot.startsWith('\\\\')) {
+ drives.push({ name: currentRoot.replace(/[\\/]+$/, ''), path: currentRoot, current: true });
+ }
+ return drives;
+}
+
+async function queryLogicalDriveRoots(run: DriveCommand): Promise<string[]> {
+ const powershell = path.win32.join(
+ process.env.SystemRoot ?? 'C:\\Windows',
+ 'System32',
+ 'WindowsPowerShell',
+ 'v1.0',
+ 'powershell.exe',
+ );
+ try {
+ const { stdout } = await run(
+ powershell,
+ ['-NoLogo', '-NoProfile', '-NonInteractive', '-Command', '[System.IO.Directory]::GetLogicalDrives()'],
+ { encoding: 'utf8', timeout: DRIVE_COMMAND_TIMEOUT_MS, maxBuffer: 16 * 1024, windowsHide: true },
+ );
+ return parseLogicalDriveRoots(stdout);
+ } catch (err) {
+ log.warn('list logical drives failed; drive switching hidden', {
+ error: err instanceof Error ? err.message : String(err),
+ });
+ return [];
+ }
+}
+
+/**
+ * 带缓存与并发合并的盘符枚举;永不 reject,失败返回空列表(同样缓存,避免反复起进程)。
+ * 缓存过期后先返回旧值并在后台刷新,只有首次枚举需要等 PowerShell。
+ */
+export function createWindowsDriveRootLister(
+ options: { run?: DriveCommand; now?: () => number } = {},
+): () => Promise<string[]> {
+ const run = options.run ?? execFileAsync;
+ const now = options.now ?? Date.now;
+ let cached: { at: number; roots: string[] } | null = null;
+ let inflight: Promise<string[]> | null = null;
+ return () => {
+ if (!cached || now() - cached.at >= DRIVE_CACHE_TTL_MS) {
+ inflight ??= queryLogicalDriveRoots(run)
+ .then((roots) => {
+ cached = { at: now(), roots };
+ return roots;
+ })
+ .finally(() => {
+ inflight = null;
+ });
+ }
+ return cached ? Promise.resolve(cached.roots) : inflight!;
+ };
+}
+
+export const listWindowsDriveRoots = createWindowsDriveRootLister();
diff --git a/apps/mobile/app/sessions/new.tsx b/apps/mobile/app/sessions/new.tsx
index a6891479d1..750315fa8c 100644
--- a/apps/mobile/app/sessions/new.tsx
+++ b/apps/mobile/app/sessions/new.tsx
@@ -71,6 +71,7 @@ import { useDeviceLink } from '@/device-link/DeviceLinkContext';
import type {
MobileAtResourceItem,
MobileSlashCommand,
+ RemoteDirectoryDrive,
RemoteDirectoryEntry,
} from '@/device-link/mobileMakerTransport';
import { describeAgentAuthError, formatRemoteError, humanizeRemoteError } from '@/device-link/remoteStatus';
@@ -162,6 +163,9 @@ import {
buildRemoteCreateSessionOptions,
buildRecentWorkspaceOptions,
filterRemoteDirectoryEntries,
+ isCurrentRemoteBrowseRequest,
+ normalizeRemoteDirectoryDrives,
+ shouldRetryRemoteBrowseDrives,
normalizeCreateSessionResult,
isNewSessionDraftMissingPayloadOnly,
parseNewSessionDeviceOptions,
@@ -533,6 +537,8 @@ export default function NewRemoteSessionScreen() {
const [browsePath, setBrowsePath] = useState('');
const [browseParent, setBrowseParent] = useState<string | null>(null);
const [browseEntries, setBrowseEntries] = useState<RemoteDirectoryEntry[]>([]);
+ // Windows 被控端的盘符切换项;读取失败时保留上一次的值,切到读不了的盘(空光驱)后还能切回。
+ const [browseDrives, setBrowseDrives] = useState<RemoteDirectoryDrive[]>([]);
const [browseLoading, setBrowseLoading] = useState(false);
const [browseError, setBrowseError] = useState<string | null>(null);
const [showHiddenDirectories, setShowHiddenDirectories] = useState(false);
@@ -838,6 +844,8 @@ export default function NewRemoteSessionScreen() {
setVoiceStartPending(false);
}, []);
const browseSeqRef = useRef(0);
+ const selectedDeviceIdRef = useRef(selectedDeviceId);
+ selectedDeviceIdRef.current = selectedDeviceId;
const capabilitiesSeqRef = useRef(0);
const slashLoadSeqRef = useRef(0);
const atLoadSeqRef = useRef(0);
@@ -1786,6 +1794,8 @@ export default function NewRemoteSessionScreen() {
}
userTouchedDeviceRef.current = true;
explicitProviderModelSelectionRef.current = null;
+ browseSeqRef.current += 1;
+ selectedDeviceIdRef.current = option.deviceId;
setSelectedDeviceId(option.deviceId);
setSelectedDeviceName(option.name || option.deviceId);
void saveNewSessionPreferences({
@@ -1802,6 +1812,8 @@ export default function NewRemoteSessionScreen() {
setBrowsePath('');
setBrowseParent(null);
setBrowseEntries([]);
+ setBrowseDrives([]);
+ setBrowseLoading(false);
setBrowseError(null);
setContextSheetOpen(false);
// 切换电脑丢弃草稿附件前 best-effort 回收已上传的中转对象(codex review #504)。
@@ -2247,26 +2259,43 @@ export default function NewRemoteSessionScreen() {
openLink,
]);
- const loadBrowsePath = useCallback(async (targetPath: string) => {
- if (!selectedDeviceId) return;
- const seq = ++browseSeqRef.current;
- setBrowseLoading(true);
- setBrowseError(null);
+ const loadBrowsePath = useCallback(async (
+ targetPath: string,
+ driveRetryAttempt = 0,
+ reuse?: { seq: number; deviceId: string },
+ ) => {
+ const deviceId = reuse?.deviceId ?? selectedDeviceId;
+ if (!deviceId || selectedDeviceIdRef.current !== deviceId) return;
+ const seq = reuse?.seq ?? ++browseSeqRef.current;
+ const isCurrent = () => isCurrentRemoteBrowseRequest(
+ { seq, deviceId },
+ { seq: browseSeqRef.current, deviceId: selectedDeviceIdRef.current },
+ );
+ if (!reuse) {
+ setBrowseLoading(true);
+ setBrowseError(null);
+ }
try {
const result = await withTransientRemoteRetry(async () => {
- await openLink(selectedDeviceId);
+ await openLink(deviceId);
return maker.fs.listDir(targetPath.trim() || '~');
});
- if (seq !== browseSeqRef.current) return;
+ if (!isCurrent()) return;
setBrowsePath(result.resolvedPath);
setBrowseParent(result.parent);
setBrowseEntries(result.entries);
+ setBrowseDrives(normalizeRemoteDirectoryDrives(result.drives));
+ if (!reuse) setBrowseLoading(false);
+ if (shouldRetryRemoteBrowseDrives(result.drivesPending, driveRetryAttempt)) {
+ void loadBrowsePath(result.resolvedPath, driveRetryAttempt + 1, { seq, deviceId });
+ }
} catch (err) {
- if (seq !== browseSeqRef.current) return;
+ if (!isCurrent()) return;
+ // 盘符补拉失败时保留已画出的目录;只有首次读取失败才清空并报错。
+ if (reuse) return;
setBrowseEntries([]);
setBrowseError(formatRemoteError(err));
- } finally {
- if (seq === browseSeqRef.current) setBrowseLoading(false);
+ setBrowseLoading(false);
}
}, [selectedDeviceId, maker, openLink]);
@@ -5788,6 +5817,40 @@ export default function NewRemoteSessionScreen() {
<Text style={styles.browseActionText}>{t('session.new.useCurrent')}</Text>
</Pressable>
</View>
+ {browseDrives.length > 0 ? (
+ <View style={styles.browseDriveRow} testID="newSession.remoteBrowseDrives">
+ <Text style={styles.browseDriveLabel}>{t('session.new.drive')}</Text>
+ <ScrollView
+ horizontal
+ contentContainerStyle={styles.browseDriveOptions}
+ keyboardShouldPersistTaps="handled"
+ showsHorizontalScrollIndicator={false}
+ >
+ {browseDrives.map((drive) => (
+ <Pressable
+ accessibilityLabel={t('session.new.switchToDrive', { name: drive.name })}
+ accessibilityRole="button"
+ accessibilityState={{ selected: drive.current, disabled: browseLoading || drive.current }}
+ disabled={browseLoading || drive.current}
+ key={drive.path}
+ onPress={() => void loadBrowsePath(drive.path)}
+ style={({ pressed }) => [
+ styles.browseDriveHit,
+ browseLoading && !drive.current && styles.disabled,
+ pressed && styles.pressed,
+ ]}
+ testID="newSession.remoteBrowseDriveOption"
+ >
+ <View style={[styles.browseActionButton, drive.current && styles.browseDriveCurrent]}>
+ <Text style={[styles.browseActionText, drive.current && styles.browseDriveCurrentText]}>
+ {drive.name}
+ </Text>
+ </View>
+ </Pressable>
+ ))}
+ </ScrollView>
+ </View>
+ ) : null}
<Pressable
accessibilityLabel={newSessionText('showHiddenDirectories')}
accessibilityRole="checkbox"
@@ -6182,6 +6245,7 @@ export default function NewRemoteSessionScreen() {
workingDir={draft.workingDir}
path={browsePath}
parent={browseParent}
+ drives={browseDrives}
entries={visibleBrowseEntries}
loading={browseLoading}
error={browseError}
@@ -6829,6 +6893,36 @@ const makeStyles = (colors: ThemeColors) => StyleSheet.create({
fontSize: typeScale.caption,
fontWeight: fontWeight.medium,
},
+ browseDriveRow: {
+ alignItems: 'center',
+ flexDirection: 'row',
+ gap: spacing.sm,
+ },
+ browseDriveLabel: {
+ color: colors.textSecondary,
+ fontSize: typeScale.caption,
+ fontWeight: fontWeight.medium,
+ },
+ browseDriveOptions: {
+ alignItems: 'center',
+ gap: spacing.sm,
+ minHeight: 44,
+ },
+ // 可见 pill 仍是 34pt(与「上级 / 使用当前」同档);不可见外层把热区补到 44pt。
+ browseDriveHit: {
+ alignItems: 'center',
+ justifyContent: 'center',
+ minHeight: 44,
+ minWidth: 44,
+ },
+ // 当前盘用实心 cta 底色(与 browseCheckboxChecked 同色),浅色 / 深色都能一眼认出。
+ browseDriveCurrent: {
+ backgroundColor: colors.cta,
+ borderColor: colors.cta,
+ },
+ browseDriveCurrentText: {
+ color: colors.ctaText,
+ },
browseHiddenToggle: {
alignItems: 'center',
alignSelf: 'flex-start',
diff --git a/apps/mobile/src/__tests__/newSession.test.ts b/apps/mobile/src/__tests__/newSession.test.ts
index debe18fd28..1e9db343da 100644
--- a/apps/mobile/src/__tests__/newSession.test.ts
+++ b/apps/mobile/src/__tests__/newSession.test.ts
@@ -12,6 +12,9 @@ import {
buildRecentWorkspaceOptions,
buildRemoteCreateSessionOptions,
filterRemoteDirectoryEntries,
+ isCurrentRemoteBrowseRequest,
+ normalizeRemoteDirectoryDrives,
+ shouldRetryRemoteBrowseDrives,
defaultPermissionModeForNewSessionAgent,
normalizeCreateSessionResult,
parseNewSessionDeviceOptions,
@@ -1058,6 +1061,68 @@ describe('new session model', () => {
expect(filterRemoteDirectoryEntries(entries, true)).toEqual(entries);
});
+ it('normalizes Windows drive options from fs:list-dir and hides the switch without a second drive', () => {
+ // 盘符根是被控端 host-native 的 Windows wire 格式,固定写反斜杠。
+ expect(normalizeRemoteDirectoryDrives([
+ { name: 'C:', path: 'C:\\', current: false },
+ { name: 'D:', path: 'D:\\', current: true },
+ { path: 'E:\\' },
+ { name: 'dup', path: 'D:\\', current: false },
+ { name: 'bad' },
+ null,
+ ])).toEqual([
+ { name: 'C:', path: 'C:\\', current: false },
+ { name: 'D:', path: 'D:\\', current: true },
+ { name: 'E:\\', path: 'E:\\', current: false },
+ ]);
+ expect(normalizeRemoteDirectoryDrives([{ name: 'C:', path: 'C:\\', current: true }])).toEqual([]);
+ expect(normalizeRemoteDirectoryDrives(undefined)).toEqual([]);
+ expect(normalizeRemoteDirectoryDrives('C:')).toEqual([]);
+ });
+
+ it('drops in-flight remote browse results after switching computers, even if the sequence still matches', () => {
+ expect(isCurrentRemoteBrowseRequest(
+ { seq: 3, deviceId: 'pc-a' },
+ { seq: 3, deviceId: 'pc-b' },
+ )).toBe(false);
+ expect(isCurrentRemoteBrowseRequest(
+ { seq: 3, deviceId: 'pc-a' },
+ { seq: 4, deviceId: 'pc-a' },
+ )).toBe(false);
+ expect(isCurrentRemoteBrowseRequest(
+ { seq: 3, deviceId: 'pc-a' },
+ { seq: 3, deviceId: 'pc-a' },
+ )).toBe(true);
+ expect(isCurrentRemoteBrowseRequest(
+ { seq: 3, deviceId: '' },
+ { seq: 3, deviceId: '' },
+ )).toBe(false);
+
+ const newSource = readTextLf(resolve(process.cwd(), 'app/sessions/new.tsx'), 'utf8');
+ expect(newSource).toContain('browseSeqRef.current += 1');
+ expect(newSource).toContain('selectedDeviceIdRef.current = option.deviceId');
+ expect(newSource).toContain('isCurrentRemoteBrowseRequest');
+ });
+
+ it('retries the current directory when Windows drive enumeration is still pending', () => {
+ expect(shouldRetryRemoteBrowseDrives(true, 0)).toBe(true);
+ expect(shouldRetryRemoteBrowseDrives(true, 2)).toBe(true);
+ expect(shouldRetryRemoteBrowseDrives(true, 3)).toBe(false);
+ expect(shouldRetryRemoteBrowseDrives(false, 0)).toBe(false);
+ expect(shouldRetryRemoteBrowseDrives(undefined, 0)).toBe(false);
+
+ const newSource = readTextLf(resolve(process.cwd(), 'app/sessions/new.tsx'), 'utf8');
+ expect(newSource).toContain('shouldRetryRemoteBrowseDrives');
+ expect(newSource).toContain('result.drivesPending');
+ });
+
+ it('keeps the Android drive pill at 34pt and wraps it in a 44pt hit target', () => {
+ const newSource = readTextLf(resolve(process.cwd(), 'app/sessions/new.tsx'), 'utf8');
+ expect(newSource).toContain('styles.browseDriveHit');
+ expect(newSource).toMatch(/browseDriveHit:\s*\{[^}]*minHeight:\s*44/);
+ expect(newSource).toMatch(/browseDriveHit:\s*\{[^}]*minWidth:\s*44/);
+ });
+
it('builds device-link create-session args with desktop remote-project semantics', () => {
expect(buildRemoteCreateSessionOptions({
...DEFAULT_NEW_SESSION_DRAFT,
diff --git a/apps/mobile/src/device-link/mobileMakerTransport.ts b/apps/mobile/src/device-link/mobileMakerTransport.ts
index 7baa719571..9905961338 100644
--- a/apps/mobile/src/device-link/mobileMakerTransport.ts
+++ b/apps/mobile/src/device-link/mobileMakerTransport.ts
@@ -197,10 +197,21 @@ export interface RemoteDirectoryEntry {
path: string;
}
+/** Windows 被控端的盘符(fs:list-dir 可选回传);path 为 host-native 根路径,直接用于导航。 */
+export interface RemoteDirectoryDrive {
+ name: string;
+ path: string;
+ current: boolean;
+}
+
export interface RemoteDirectoryListResult {
resolvedPath: string;
entries: RemoteDirectoryEntry[];
parent: string | null;
+ /** 仅 Windows 新版被控端回传;旧被控端缺省时不显示盘符切换。 */
+ drives?: RemoteDirectoryDrive[];
+ /** 仅 Windows:盘符枚举仍在后台进行,控制端应再拉一次当前目录。旧端忽略。 */
+ drivesPending?: boolean;
}
export interface RemotePathStatResult {
diff --git a/apps/mobile/src/i18n/locales/en/session.json b/apps/mobile/src/i18n/locales/en/session.json
index 6cbd31e997..5c728b03b4 100644
--- a/apps/mobile/src/i18n/locales/en/session.json
+++ b/apps/mobile/src/i18n/locales/en/session.json
@@ -322,6 +322,8 @@
"readingRemoteDir": "Reading remote directory…",
"goParentDir": "Go to parent directory",
"parentDir": "Parent",
+ "drive": "Drive",
+ "switchToDrive": "Switch to {{name}}",
"useCurrentRemoteDir": "Use current remote directory",
"useCurrent": "Use Current",
"firstMessagePlaceholder": "Enter the first message",
diff --git a/apps/mobile/src/i18n/locales/ja/session.json b/apps/mobile/src/i18n/locales/ja/session.json
index bc788e08b0..bd1364f642 100644
--- a/apps/mobile/src/i18n/locales/ja/session.json
+++ b/apps/mobile/src/i18n/locales/ja/session.json
@@ -322,6 +322,8 @@
"readingRemoteDir": "リモートディレクトリを読み込み中…",
"goParentDir": "上位ディレクトリへ",
"parentDir": "上へ",
+ "drive": "ドライブ",
+ "switchToDrive": "{{name}} に切り替え",
"useCurrentRemoteDir": "現在のリモートディレクトリを使用",
"useCurrent": "現在を使用",
"firstMessagePlaceholder": "最初のメッセージを入力",
diff --git a/apps/mobile/src/i18n/locales/ko/session.json b/apps/mobile/src/i18n/locales/ko/session.json
index 51cc89e5e8..6a5eaf659e 100644
--- a/apps/mobile/src/i18n/locales/ko/session.json
+++ b/apps/mobile/src/i18n/locales/ko/session.json
@@ -318,6 +318,8 @@
"readingRemoteDir": "원격 디렉터리를 읽는 중…",
"goParentDir": "상위 디렉터리로",
"parentDir": "상위",
+ "drive": "드라이브",
+ "switchToDrive": "{{name}}(으)로 전환",
"useCurrentRemoteDir": "현재 원격 디렉터리 사용",
"useCurrent": "현재 사용",
"firstMessagePlaceholder": "첫 메시지 입력",
diff --git a/apps/mobile/src/i18n/locales/zh-CN/session.json b/apps/mobile/src/i18n/locales/zh-CN/session.json
index 75e2a1c01f..ca44c24f07 100644
--- a/apps/mobile/src/i18n/locales/zh-CN/session.json
+++ b/apps/mobile/src/i18n/locales/zh-CN/session.json
@@ -318,6 +318,8 @@
"readingRemoteDir": "正在读取远程目录…",
"goParentDir": "返回上级目录",
"parentDir": "上级",
+ "drive": "盘符",
+ "switchToDrive": "切换到 {{name}}",
"useCurrentRemoteDir": "使用当前远程目录",
"useCurrent": "使用当前",
"firstMessagePlaceholder": "输入首条消息",
diff --git a/apps/mobile/src/i18n/locales/zh-TW/session.json b/apps/mobile/src/i18n/locales/zh-TW/session.json
index be103b3c3c..7e3d2a6662 100644
--- a/apps/mobile/src/i18n/locales/zh-TW/session.json
+++ b/apps/mobile/src/i18n/locales/zh-TW/session.json
@@ -322,6 +322,8 @@
"readingRemoteDir": "正在讀取遠端目錄…",
"goParentDir": "返回上級目錄",
"parentDir": "上級",
+ "drive": "磁碟機",
+ "switchToDrive": "切換到 {{name}}",
"useCurrentRemoteDir": "使用當前遠端目錄",
"useCurrent": "使用當前",
"firstMessagePlaceholder": "輸入首條訊息",
diff --git a/apps/mobile/src/session/NewTaskSelectionSheet.ios.tsx b/apps/mobile/src/session/NewTaskSelectionSheet.ios.tsx
index 65dd599437..9276fcc267 100644
--- a/apps/mobile/src/session/NewTaskSelectionSheet.ios.tsx
+++ b/apps/mobile/src/session/NewTaskSelectionSheet.ios.tsx
@@ -1,5 +1,5 @@
-import { Button, Image, ProgressView, Text, Toggle } from '@expo/ui/swift-ui';
-import { disabled, font, foregroundStyle, frame } from '@expo/ui/swift-ui/modifiers';
+import { Button, Image, Picker, ProgressView, Text, Toggle } from '@expo/ui/swift-ui';
+import { disabled, font, foregroundStyle, frame, pickerStyle, tag } from '@expo/ui/swift-ui/modifiers';
import { useTranslation } from 'react-i18next';
import { iconSize, useTheme } from '@/theme';
import { ComposerSheet } from './ComposerSheet';
@@ -65,6 +65,12 @@ export function NewTaskSelectionSheet(p: NewTaskSelectionSheetProps) {
<ComposerNativeRow title={t('session.new.parentDir')} leading={icon('arrow.up')}
disabled={!p.parent || unavailable} onPress={() => { if (p.parent) p.onEnter(p.parent); }}
testID="newSession.remoteBrowseParentButton" />
+ {p.drives.length ? <Picker label={t('session.new.drive')}
+ selection={p.drives.find(drive => drive.current)?.path ?? ''}
+ onSelectionChange={(next: string) => { if (next && !unavailable) p.onEnter(next); }}
+ modifiers={[pickerStyle('menu'), disabled(unavailable)]} testID="newSession.remoteBrowseDrivePicker">
+ {p.drives.map(drive => <Text key={drive.path} modifiers={[tag(drive.path)]}>{drive.name}</Text>)}
+ </Picker> : null}
<Toggle label={newSessionText('showHiddenDirectories')} isOn={p.showHidden}
onIsOnChange={p.onShowHidden} modifiers={[disabled(p.busy)]} testID="newSession.remoteBrowseShowHidden" />
</Section>
diff --git a/apps/mobile/src/session/NewTaskSelectionSheet.tsx b/apps/mobile/src/session/NewTaskSelectionSheet.tsx
index 4f46dcce95..e453170234 100644
--- a/apps/mobile/src/session/NewTaskSelectionSheet.tsx
+++ b/apps/mobile/src/session/NewTaskSelectionSheet.tsx
@@ -8,6 +8,8 @@ export interface NewTaskSelectionSheetProps {
workingDir: string;
path: string;
parent: string | null;
+ /** Windows 被控端的盘符切换项;少于两个时为空,不显示。 */
+ drives: readonly { name: string; path: string; current: boolean }[];
entries: readonly { name: string; path: string }[];
loading: boolean;
error: string | null;
diff --git a/apps/mobile/src/session/newSession.ts b/apps/mobile/src/session/newSession.ts
index 15d4997ae3..9c18be684b 100644
--- a/apps/mobile/src/session/newSession.ts
+++ b/apps/mobile/src/session/newSession.ts
@@ -5,7 +5,11 @@ import {
deriveOptimisticSessionTitle,
} from '@cindy/maker-shared/session-title';
import { i18n } from '@/i18n';
-import type { CreateSessionOptions, RemoteDirectoryEntry } from '@/device-link/mobileMakerTransport';
+import type {
+ CreateSessionOptions,
+ RemoteDirectoryDrive,
+ RemoteDirectoryEntry,
+} from '@/device-link/mobileMakerTransport';
import type { DeviceProvidersPayload } from '@/device-link/deviceProvidersCache';
import type { MobileModelOption } from './agentCapabilities';
import { effectiveSourceIdForModel } from '@cindy/model-providers/registry';
@@ -282,6 +286,41 @@ export function filterRemoteDirectoryEntries(
return entries.filter((entry) => !entry.name.startsWith('.'));
}
+/**
+ * 远端目录浏览的盘符切换项(Windows 被控端 fs:list-dir 的可选 `drives`)。旧被控端缺省、
+ * 字段畸形或只有一个盘时返回空数组——没有可切换的目标就不显示盘符切换。
+ */
+export function normalizeRemoteDirectoryDrives(value: unknown): RemoteDirectoryDrive[] {
+ if (!Array.isArray(value)) return [];
+ const drives: RemoteDirectoryDrive[] = [];
+ const seen = new Set<string>();
+ for (const item of value) {
+ if (!item || typeof item !== 'object') continue;
+ const { name, path, current } = item as Record<string, unknown>;
+ if (typeof path !== 'string' || !path || seen.has(path)) continue;
+ seen.add(path);
+ drives.push({ name: typeof name === 'string' && name ? name : path, path, current: current === true });
+ }
+ return drives.length > 1 ? drives : [];
+}
+
+/** 目录请求是否仍属于当前被控电脑;切电脑后旧请求即使序号未变也不能写回。 */
+export function isCurrentRemoteBrowseRequest(
+ request: { seq: number; deviceId: string },
+ current: { seq: number; deviceId: string },
+): boolean {
+ return Boolean(request.deviceId)
+ && request.deviceId === current.deviceId
+ && request.seq === current.seq;
+}
+
+/** 首次盘符枚举超时后,最多再拉几次当前目录;超过即停,避免空转。 */
+const REMOTE_BROWSE_DRIVE_RETRY_LIMIT = 3;
+
+export function shouldRetryRemoteBrowseDrives(drivesPending: unknown, attempt: number): boolean {
+ return drivesPending === true && attempt >= 0 && attempt < REMOTE_BROWSE_DRIVE_RETRY_LIMIT;
+}
+
export function buildRecentWorkspaceOptions(
sessions: readonly RemoteSession[],
deviceId?: string,
diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.md
index 142fd94372..5be6e04d01 100644
--- a/docs/dev-rules/protocol-compatibility.md
+++ b/docs/dev-rules/protocol-compatibility.md
@@ -82,6 +82,17 @@ Mobile 未新增卡片入口。服务端无需改动。
不得用旧快照覆盖。旧被控端忽略新参数并返回原数组;手机遇到数组时不根据缺席清除。
旧控制端仍请求、接收原数组。该扩展不修改 relay、授权或持久化格式。
+## 远端目录浏览盘符列表
+
+`fs:list-dir` 响应追加可选 `drives: { name, path, current }[]`,只由 Windows 被控端回传:
+经 PowerShell 读取 `GetLogicalDrives` 盘符表,不访问磁盘,断线网络盘不会卡住探测。结果缓存
+30 秒,过期先回旧值并在后台刷新;首次枚举最多等 1.5 秒,超时、失败或为空时省略 `drives`,目录列表
+照常返回。超时额外回可选 `drivesPending: true`,新版手机据此在当前目录自动再拉,旧控制端忽略。
+`path` 是 host-native 根路径,控制端直接用它再调 `fs:list-dir`,不自行拼路径;当前
+位于未枚举到的盘或 UNC 共享时补为当前项。新版手机在至少两项时于「上级」下显示盘符切换;
+旧被控端不回字段时保留原逐级浏览,旧控制端(含 Desktop 添加远程项目对话框)忽略该字段。
+未新增 channel、relay 类型、allowlist、权限或持久化状态,服务端无需改动。
+
## 自动化检查恢复投影
运行状态和已读回执保留历史事实。当前警告只保留未被**同一自动化**更新成功运行恢复的失败;