Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(device-link): validate new task directories on the SSH host
DavidShenea58829e7eb6
diff --git a/apps/desktop/src/main/__tests__/deviceLinkHostDispatch.test.ts b/apps/desktop/src/main/__tests__/deviceLinkHostDispatch.test.tsindex 9721143eed..e4d2e271e3 100644--- a/apps/desktop/src/main/__tests__/deviceLinkHostDispatch.test.ts+++ b/apps/desktop/src/main/__tests__/deviceLinkHostDispatch.test.ts@@ -3,7 +3,7 @@* ---------------------------------------------------------------------------* 把过去要真机验证的**被控端那一半**变成 CI 可跑:驱动**真实** runInvoke(dispatch.ts),* 串起真实双层门禁(remoteControlEnabled + allowlist)+ **真实 workingDir guard**- * (`checkRemoteWorkingDir` 跑真实异步 fs 探测)+ * (`createRemoteWorkingDirGuard` 解析 SSH 归属,本地目录跑真实异步 fs 探测)* + dispatchLocalInvoke 路由到本机 handler + set-* 回流 + throwIpcError `[CODE]` 透传。** 真实 vs 忠实替身的边界(诚实声明):@@ -58,7 +58,8 @@ import {setRemoteSettingsPersist,__testing as dispatchTesting,} from '../device-link/dispatch';-import { checkRemoteWorkingDir } from '../device-link/remote-workdir-guard';+import { createRemoteWorkingDirGuard } from '../device-link/remote-workdir-guard';+import { createIpcError } from '../../shared/ipc-errors';import { __testing as registry } from '../device-link/invoke-registry';import type { InvokeResultPayload } from '@cindy/device-link';@@ -66,16 +67,14 @@ const SRC = 'controller-device';const TMP_DIR = os.tmpdir(); // 真实存在的目录(模拟"浏览到/新建的远程目录")let managedWorktreeTestRoot = '';let managedWorktreeDir = '';+const localStat = vi.fn((dir: string) => stat(dir));+const findSshHosts = vi.fn<(dir: string) => Promise<readonly string[]>>();+const probeSshWorkingDirectory = vi.fn<(hostId: string, dir: string) => Promise<string>>();beforeAll(() => {managedWorktreeTestRoot = mkdtempSync(path.join(os.tmpdir(), 'device-link-worktree-'));managedWorktreeDir = path.join(managedWorktreeTestRoot, '.cindy-worktrees', 'auto-test');mkdirSync(managedWorktreeDir, { recursive: true });-- // 接入与生产相同的结构化 guard。- // 此集成测试在纯 Node 中运行,显式注入真实异步 stat;utilityProcess 的- // 并发、超时与回收由 workdir-probe-host 专属测试覆盖。- setRemoteWorkingDirGuard((dir) => checkRemoteWorkingDir(dir, { stat }));});afterAll(() => {@@ -88,6 +87,15 @@ beforeEach(() => {registry.reset();h.settings.remoteControlEnabled = true;h.settings.revokedControllers = [];+ findSshHosts.mockReset().mockResolvedValue([]);+ probeSshWorkingDirectory.mockReset().mockImplementation(async (_hostId, dir) => dir);+ localStat.mockClear();+ // 与生产相同的端点解析 + 结构化 guard;仅 SSH/DB 注入内存依赖。+ // 本地目录使用真实异步 stat,utilityProcess 的调度由其专属测试覆盖。+ setRemoteWorkingDirGuard(createRemoteWorkingDirGuard({+ findSshHosts,+ probeSshWorkingDirectory,+ }, { stat: localStat }));persistSpy = vi.fn();setRemoteSettingsPersist(persistSpy);});@@ -106,6 +114,120 @@ function registerHandler(channel: string, impl: (...args: unknown[]) => unknown)}describe('device-link host dispatch (runInvoke) — real gate + async fs guard + routing', () => {+ // #7117:生产 runInvoke 必须把 SSH 的 POSIX 路径交给对应主机,而非 Windows fs。+ // 既有覆盖只有本机路径;最小失败输入为不存在于本机的路径 + remoteHostId。+ // tier:unit,SSH/数据库用内存依赖,dispatch 与目录守卫使用真实生产入口。+ // 单文件实测(2026-10-25,Windows):38.38s,其中收集38.00s、用例37ms。+ // 超预算来自既有 dispatch 静态依赖图;复用本文件,不新增同模块加载或真实等待。+ it('#7117:SSH 新建任务保留主机归属,不被本机目录探测拦截', async () => {+ registerHandler('maker:create-session', (opts: unknown) => opts);+ const opts = { workingDir: '/home/user/project', remoteHostId: 'wsl-host' };+ const res = await runInvoke(SRC, { channel: 'maker:create-session', args: [opts] });+ expect(res).toEqual({ ok: true, result: opts });+ expect(localStat).not.toHaveBeenCalled();+ expect(findSshHosts).not.toHaveBeenCalled();+ expect(probeSshWorkingDirectory).toHaveBeenCalledWith('wsl-host', opts.workingDir);+ });++ it('#7117:旧控制端缺主机时将唯一 SSH 归属和远端规范化目录传给创建 handler', async () => {+ findSshHosts.mockResolvedValue(['wsl-host']);+ probeSshWorkingDirectory.mockResolvedValue('/home/user/canonical-project');+ registerHandler('maker:create-session', (opts: unknown) => opts);+ const opts = { id: 'new-task', workingDir: '/home/user/project' };+ expect(await runInvoke(SRC, { channel: 'maker:create-session', args: [opts] })).toEqual({+ ok: true,+ result: { ...opts, remoteHostId: 'wsl-host', workingDir: '/home/user/canonical-project' },+ });+ expect(opts).toEqual({ id: 'new-task', workingDir: '/home/user/project' });+ });++ it.each([+ { name: '本地目录与 SSH 同时命中', workingDir: TMP_DIR, hosts: ['wsl-host'] },+ { name: '多个 SSH 主机有同路径', workingDir: '/home/user/project', hosts: ['wsl-host', 'another-host'] },+ ])('#7117:$name 时拒绝猜测执行位置', async ({ workingDir, hosts }) => {+ findSshHosts.mockResolvedValue(hosts);+ const handler = registerHandler('maker:create-session', () => 'must not create');+ expect(await runInvoke(SRC, { channel: 'maker:create-session', args: [{ workingDir }] })).toEqual({+ ok: false,+ error: { code: 'IPC_ERROR', message: expect.stringContaining('[REMOTE_WORKDIR_INVALID]') },+ });+ expect(handler).not.toHaveBeenCalled();+ expect(probeSshWorkingDirectory).not.toHaveBeenCalled();+ });++ it.each([{ remoteHostId: null }, { agentDeviceId: 'agent-device' }])(+ '#7117:显式本地/另一电脑 Agent 的任务保留本地文件归属 %j', async (route) => {+ findSshHosts.mockResolvedValue(['wsl-host']);+ registerHandler('maker:create-session', (opts: unknown) => opts);+ const opts = { workingDir: TMP_DIR, ...route };+ expect(await runInvoke(SRC, { channel: 'maker:create-session', args: [opts] })).toEqual({ ok: true, result: opts });+ expect(findSshHosts).not.toHaveBeenCalled();+ expect(probeSshWorkingDirectory).not.toHaveBeenCalled();+ },+ );++ it.each([+ { error: createIpcError('SSH_HOST_NOT_FOUND', 'Unknown SSH host'), code: 'SSH_HOST_NOT_FOUND' },+ { error: createIpcError('SSH_CONNECT_FAILED', 'SSH connection failed'), code: 'SSH_CONNECT_FAILED' },+ { error: new Error('remote stderr with private/path'), code: 'REMOTE_WORKDIR_UNAVAILABLE' },+ ])('#7117:SSH 探测失败返回 $code,不回落本机创建', async ({ error, code }) => {+ probeSshWorkingDirectory.mockRejectedValue(error);+ const handler = registerHandler('maker:create-session', () => 'must not create');+ const res = await runInvoke(SRC, {+ channel: 'maker:create-session',+ args: [{ workingDir: '/home/user/project', remoteHostId: 'wsl-host' }],+ });+ expect(res).toEqual({ ok: false, error: { code: 'IPC_ERROR', message: expect.stringContaining(`[${code}]`) } });+ expect(JSON.stringify(res)).not.toContain('private/path');+ expect(handler).not.toHaveBeenCalled();+ expect(localStat).not.toHaveBeenCalled();+ });++ it.each([+ { remoteHostId: '' },+ { remoteHostId: 123 },+ { remoteHostId: 'wsl-host', agentDeviceId: 'agent-device' },+ ])('#7117:非法或冲突的执行端参数在连接 SSH 前拒绝 %j', async (route) => {+ const handler = registerHandler('maker:create-session', () => 'must not create');+ expect(await runInvoke(SRC, {+ channel: 'maker:create-session', args: [{ workingDir: TMP_DIR, ...route }],+ })).toEqual({ ok: false, error: { code: 'IPC_ERROR', message: expect.stringContaining('[REMOTE_WORKDIR_INVALID]') } });+ expect(handler).not.toHaveBeenCalled();+ expect(probeSshWorkingDirectory).not.toHaveBeenCalled();+ });++ it('#7117:归属查询失败不猜测端点或泄露数据库错误', async () => {+ findSshHosts.mockRejectedValue(new Error('private database path'));+ const handler = registerHandler('maker:create-session', () => 'must not create');+ const res = await runInvoke(SRC, { channel: 'maker:create-session', args: [{ workingDir: TMP_DIR }] });+ expect(res).toEqual({ ok: false, error: { code: 'IPC_ERROR', message: expect.stringContaining('[REMOTE_WORKDIR_UNAVAILABLE]') } });+ expect(JSON.stringify(res)).not.toContain('private database path');+ expect(handler).not.toHaveBeenCalled();+ });++ it('#7117:探测期间撤回远控授权后不再创建任务', async () => {+ probeSshWorkingDirectory.mockImplementation(async (_hostId, dir) => {+ h.settings.remoteControlEnabled = false;+ return dir;+ });+ const handler = registerHandler('maker:create-session', () => 'must not create');+ expect(await runInvoke(SRC, {+ channel: 'maker:create-session', args: [{ workingDir: '/home/user/project', remoteHostId: 'wsl-host' }],+ })).toEqual({ ok: false, error: { code: 'ACCESS_REVOKED', message: expect.any(String) } });+ expect(handler).not.toHaveBeenCalled();+ });++ it('#7117:worktree:create 不能借 SSH 参数绕过本地目录检查', async () => {+ findSshHosts.mockResolvedValue(['wsl-host']);+ const handler = registerHandler('worktree:create', () => 'must not create');+ expect(await runInvoke(SRC, {+ channel: 'worktree:create', args: [{ baseRepo: '/home/user/project', remoteHostId: 'wsl-host' }],+ })).toEqual({ ok: false, error: { code: 'IPC_ERROR', message: expect.stringContaining('[REMOTE_WORKDIR_NOT_FOUND]') } });+ expect(handler).not.toHaveBeenCalled();+ expect(findSshHosts).not.toHaveBeenCalled();+ expect(probeSshWorkingDirectory).not.toHaveBeenCalled();+ });+it('Bug1:create-session 的 workingDir 是真实存在的新目录 → 放行到 handler', async () => {const handler = registerHandler('maker:create-session', () => ({ sessionId: 's-new' }));const res = (await runInvoke(SRC, {diff --git a/apps/desktop/src/main/__tests__/remoteWorkdirGuard.test.ts b/apps/desktop/src/main/__tests__/remoteWorkdirGuard.test.tsindex bc3668beb8..7aee6e367b 100644--- a/apps/desktop/src/main/__tests__/remoteWorkdirGuard.test.ts+++ b/apps/desktop/src/main/__tests__/remoteWorkdirGuard.test.ts@@ -4,8 +4,9 @@* dispatch 把控制端 args 原样喂本机 handler;create-session 的 workingDir 决定 agent 在哪起* 进程(可读写/执行)。allowlist 只挡 channel 不挡 args,故必须对 workingDir 收敛。* 所有本地路径都必须通过当前文件系统探测,历史 recent/session 记录不能替代可访问性。- * SSH workdir 的端点识别由 file-browser 独立处理,不能放宽 create-session、worktree:create- * 或远程 /cmd 共用的本地目录安全闸。这里锁住:目录放行、文件/不存在路径拒、空路径拒、+ * checkRemoteWorkingDir 始终只探测本地;新建任务的 SSH 端点解析与远端实时探测由+ * createRemoteWorkingDirGuard 包装,不能放宽 worktree:create 或远程 /cmd 的本地目录安全闸。+ * 这里锁住:目录放行、文件/不存在路径拒、空路径拒、* 断线探测不阻塞事件循环且在业务超时内收敛。*/import { describe, it, expect, vi, beforeEach } from 'vitest';diff --git a/apps/desktop/src/main/device-link/dispatch.ts b/apps/desktop/src/main/device-link/dispatch.tsindex 7baebfc7e1..b187bb754b 100644--- a/apps/desktop/src/main/device-link/dispatch.ts+++ b/apps/desktop/src/main/device-link/dispatch.ts@@ -161,7 +161,7 @@ import {} from '../cindy-brain/ghostSetupInteractionBridge.js';import {remoteWorkingDirRejectionToIpcError,- type RemoteWorkingDirCheckResult,+ type RemoteWorkingDirGuard,} from './remote-workdir-guard';const log = createLogger('device-link-dispatch');@@ -358,19 +358,17 @@ const PATH_GUARDED_CHANNELS: ReadonlyMap<string, 'workingDir' | 'baseRepo'> = ne['worktree:create', 'baseRepo'],]);-type RemoteWorkingDirGuardValue = boolean | RemoteWorkingDirCheckResult;-/** host 注入的 workingDir 校验器(null = 未注入,放行;布尔返回值仅作旧测试兼容) */-let workingDirGuard: ((dir: string) => RemoteWorkingDirGuardValue | Promise<RemoteWorkingDirGuardValue>) | null = null;+let workingDirGuard: RemoteWorkingDirGuard | null = null;type RemoteReviewInputGuard = (sessionId: string) => void | Promise<void>;/** Main injects the DB-backed sessions.source authorization check once ready. */let remoteReviewInputGuard: RemoteReviewInputGuard | null = null;-/** 注入远程 create-session/worktree:create 的本地目录校验器(register.ts 在 maker 就绪后接入)。 */+/** 注入执行端点感知的目录校验器(register.ts 在 maker 就绪后接入)。 */export function setRemoteWorkingDirGuard(- guard: ((dir: string) => RemoteWorkingDirGuardValue | Promise<RemoteWorkingDirGuardValue>) | null,+ guard: RemoteWorkingDirGuard | null,): void {workingDirGuard = guard;}@@ -4754,40 +4752,52 @@ async function executeRemoteInvoke(src: string, payload: InvokePayload | undefin}}- // 参数级收敛:create-session 的 workingDir / worktree:create 的 baseRepo 决定 agent- // 在哪个目录起进程或跑 git,allowlist 只挡 channel 不挡 args。路径必须在被控端- // 当前可访问且确为目录,历史记录不能替代实时探测。- const guardedField = PATH_GUARDED_CHANNELS.get(payload.channel);- if (guardedField && workingDirGuard) {- const dir = extractGuardedPath(payload.args ?? [], guardedField);- const guardResult = dir ? await workingDirGuard(dir) : true;- if (guardResult === false) {- log.warn(`blocked remote ${payload.channel} to unknown ${guardedField} from ${shortId(src)}: ${dir}`);- return {- ok: false,- error: {- code: 'CHANNEL_NOT_ALLOWED',- message: `${guardedField} not allowed for remote ${payload.channel}`,- },- };- }- if (guardResult !== true && !guardResult.allowed) {- const rejection = remoteWorkingDirRejectionToIpcError(guardResult.reason);- log.warn(`blocked remote ${payload.channel} for ${guardedField} reason ${guardResult.reason} from ${shortId(src)}`);- return {- ok: false,- error: {- code: 'IPC_ERROR',- message: `[${rejection.code}] ${rejection.message}`,- },- };- }- }-let handlerCompleted = false;try {- const args = payload.args ?? [];+ let args = payload.args ?? [];const invocationOwner = broadcastTap.captureDataOwnerBroadcastScope();+ // 参数级收敛:新建任务按实际执行端探测目录;worktree 等其它入口仍只接受本地目录。+ // SSH 历史记录只能解析端点,不能替代实时探测;解析结果必须传入真正的创建 handler。+ const guardedField = PATH_GUARDED_CHANNELS.get(payload.channel);+ if (guardedField && workingDirGuard) {+ const dir = extractGuardedPath(args, guardedField);+ const options = args[0] as Record<string, unknown> | undefined;+ const guardResult = dir ? await workingDirGuard(dir, {+ channel: payload.channel,+ remoteHostId: options?.remoteHostId,+ agentDeviceId: options?.agentDeviceId,+ }) : true;+ if (guardResult === false) {+ log.warn(`blocked remote ${payload.channel} to unknown ${guardedField} from ${shortId(src)}: ${dir}`);+ return {+ ok: false,+ error: {+ code: 'CHANNEL_NOT_ALLOWED',+ message: `${guardedField} not allowed for remote ${payload.channel}`,+ },+ };+ }+ if (guardResult !== true && !guardResult.allowed) {+ const rejection = remoteWorkingDirRejectionToIpcError(guardResult.reason);+ log.warn(`blocked remote ${payload.channel} for ${guardedField} reason ${guardResult.reason} from ${shortId(src)}`);+ return {+ ok: false,+ error: {+ code: 'IPC_ERROR',+ message: `[${rejection.code}] ${rejection.message}`,+ },+ };+ }+ if (guardResult !== true && guardResult.allowed && guardResult.source === 'ssh'+ && payload.channel === 'maker:create-session') {+ args = [{ ...options, remoteHostId: guardResult.remoteHostId, workingDir: guardResult.workingDir }, ...args.slice(1)];+ }+ if (!broadcastTap.isDataOwnerBroadcastScopeCurrent(invocationOwner)+ || !readDeviceLinkSettings().remoteControlEnabled || isControllerRevoked(src)) {+ return { ok: false, error: { code: 'ACCESS_REVOKED', message: 'Remote control is no longer allowed' } };+ }+ }+const historyView = (payload.channel === 'local-db:messages:view' || payload.channel === 'local-db:messages:view-intent')&& typeof args[0] === 'string' ? subscriptions.prepareHistoryView(src, args[0]) : undefined;if (hasRemoteBotSessionLookup()) await timing.measure('authorizeBefore', () => assertRemoteBotInvocationAllowed(args, payload.channel));diff --git a/apps/desktop/src/main/device-link/remote-workdir-guard.ts b/apps/desktop/src/main/device-link/remote-workdir-guard.tsindex 819caf588a..ca3b100c22 100644--- a/apps/desktop/src/main/device-link/remote-workdir-guard.ts+++ b/apps/desktop/src/main/device-link/remote-workdir-guard.ts@@ -1,12 +1,13 @@/*** remote-workdir-guard —— 远程新建会话的 workingDir 收敛(被控端)。*- * 背景(安全):dispatch 把控制端传来的 `args` 原样喂给本机 handler;+ * 背景(安全):dispatch 把控制端请求交给本机 handler;* `maker:create-session` 的 `workingDir` 决定 agent 在哪个目录起进程(可读写 / 执行 shell)。* allowlist 只挡 channel、不挡 args,故此处对 workingDir 收敛,挡掉「不存在 / 非目录」的* 伪造或笔误路径。*- * 放行判据:路径必须**当前在被控端真实存在、且是一个目录**。+ * 放行判据:路径必须在实际执行端当前存在且是目录。本地路径由+ * checkRemoteWorkingDir 检查;新建 SSH 任务由 createRemoteWorkingDirGuard 解析端点并探测。** 本地目录探测是必须的:本版本开放了远程文件浏览(AddRemoteProjectDialog + fs:* 隧道),* 控制端可浏览 / 新建被控端任意目录并在其下建首个会话,但目录的历史记录不能证明它@@ -15,12 +16,12 @@* 任意目录,故「限定到已存在目录」是此处剩余的、成本极低的越权兜底(挡掉不存在路径 /* 把文件当目录),并非完全放开。*- * 路径比较复用 normalizeWorkingDirForStorage,只做路径形态归一。SSH endpoint 的- * 归属由 file-browser 在本地探测后单独解析;create-session / worktree:create / 远程- * `/cmd` 不得借 SSH 会话记录绕过本地目录校验。空 / 非法 / 不存在 / 非目录路径仍拒绝。+ * 路径比较复用 normalizeWorkingDirForStorage,只做路径形态归一。+ * 新建任务可用历史会话解析唯一 SSH 归属,但记录不能替代远端实时探测。+ * worktree:create / 远程 `/cmd` 仍只接受本地目录。空 / 非法 / 不存在 / 非目录路径仍拒绝。*/-import type { IpcErrorCode } from '../../shared/ipc-errors';+import { isIpcError, type IpcErrorCode } from '../../shared/ipc-errors';import { normalizeWorkingDirForStorage } from '../../shared/workingDir';import { workdirProbeHostClient } from '../workdir-probe-host/index.js';@@ -35,7 +36,7 @@ interface DirectoryStatLike {export type RemoteDirectoryStat = (dir: string) => Promise<DirectoryStatLike>;export type RemoteWorkingDirRejectionReason =- 'invalid' | 'not-found' | 'not-directory' | 'unavailable' | 'timeout';+ 'invalid' | 'not-found' | 'not-directory' | 'unavailable' | 'timeout' | 'ambiguous';export type RemoteWorkingDirCheckResult =| { allowed: true; source: 'filesystem' }@@ -46,6 +47,73 @@ export interface RemoteDirectoryProbeOptions {timeoutMs?: number;}+export interface RemoteWorkingDirGuardContext {+ channel: string;+ remoteHostId?: unknown;+ agentDeviceId?: unknown;+}++export type RemoteWorkingDirGuardValue = boolean | RemoteWorkingDirCheckResult | {+ allowed: true;+ source: 'ssh';+ remoteHostId: string;+ workingDir: string;+};++export type RemoteWorkingDirGuard = (+ dir: string,+ context?: RemoteWorkingDirGuardContext,+) => RemoteWorkingDirGuardValue | Promise<RemoteWorkingDirGuardValue>;++/** Only create-session can resolve an SSH endpoint; other guarded channels stay local. */+export function createRemoteWorkingDirGuard(+ deps: {+ findSshHosts(dir: string): Promise<readonly string[]>;+ probeSshWorkingDirectory(hostId: string, dir: string): Promise<string>;+ },+ probeOptions: RemoteDirectoryProbeOptions = {},+): RemoteWorkingDirGuard {+ return async (dir, context) => {+ if (context?.channel !== 'maker:create-session') return checkRemoteWorkingDir(dir, probeOptions);+ const normalized = normalizeWorkingDirForStorage(dir);+ if (!normalized) return { allowed: false, reason: 'invalid' };+ const explicitHost = context.remoteHostId;+ if (explicitHost != null && (typeof explicitHost !== 'string' || !explicitHost.trim())) {+ return { allowed: false, reason: 'invalid' };+ }+ const checkSsh = async (hostId: string): Promise<RemoteWorkingDirGuardValue> => {+ if (context.agentDeviceId != null || /[\r\n\0]/.test(dir)) {+ return { allowed: false, reason: 'invalid' };+ }+ try {+ const workingDir = await deps.probeSshWorkingDirectory(hostId, dir);+ return { allowed: true, source: 'ssh', remoteHostId: hostId, workingDir };+ } catch (error) {+ // SSH readiness errors already use the public IPC protocol and redact local paths.+ if (isIpcError(error) && error.code.startsWith('SSH_')) throw error;+ return { allowed: false, reason: 'unavailable' };+ }+ };+ if (typeof explicitHost === 'string') return checkSsh(explicitHost);+ const local = await checkRemoteWorkingDir(dir, probeOptions);+ // null explicitly selects local; an Agent on another device still uses this host's files.+ if (explicitHost === null || context.agentDeviceId != null || (!local.allowed && local.reason === 'invalid')) {+ return local;+ }+ let hosts: string[];+ try {+ hosts = [...new Set(await deps.findSshHosts(normalized))];+ } catch {+ // Without the lookup we cannot tell a local path from an ambiguous SSH workspace.+ return { allowed: false, reason: 'unavailable' };+ }+ if (hosts.length > 1 || (hosts.length > 0 && local.allowed)) {+ return { allowed: false, reason: 'ambiguous' };+ }+ return hosts.length === 1 ? checkSsh(hosts[0]) : local;+ };+}+function classifyStatError(err: unknown): RemoteWorkingDirRejectionReason {const code =err && typeof err === 'object' && typeof (err as { code?: unknown }).code === 'string'@@ -132,6 +200,11 @@ export function remoteWorkingDirRejectionToIpcError(reason: RemoteWorkingDirRejemessage: string;} {switch (reason) {+ case 'ambiguous':+ return {+ code: 'REMOTE_WORKDIR_INVALID',+ message: 'Working directory belongs to multiple execution environments. Select a host explicitly.',+ };case 'invalid':return { code: 'REMOTE_WORKDIR_INVALID', message: 'Remote working directory is invalid.' };case 'not-found':diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex 92f7b2a3a1..ff0159e2c8 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -1396,7 +1396,7 @@ import {assertResolveInteractionOrigin,isPluginSetupInteractionDecision,} from './interactionResolveOrigin.js';-import { checkRemoteWorkingDir } from '../device-link/remote-workdir-guard.js';+import { createRemoteWorkingDirGuard } from '../device-link/remote-workdir-guard.js';import { assertReviewSessionExternalInputAllowed } from '../reviewer/reviewSessionInputPolicy.js';import { createWorkerTurnStartSequencer } from './workerTurnStartSequencer.js';import { createBusinessSessionId } from '../sessionIds.js';@@ -6528,9 +6528,18 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)// 它每 5s 取一次、翻转才上报,让控制端设备列表显示 busy 三态(规则 2:回调注入解耦)。setDeviceLinkBusyProbe(() => anySessionInTurn(maker));- // device-link 参数级收敛:远程 create-session 的 workingDir / worktree:create 的 baseRepo- // 必须是本机当前可访问的目录,挡掉控制端用任意路径越权起进程或执行 git。- setDeviceLinkRemoteWorkingDirGuard(checkRemoteWorkingDir);+ // 新建任务先解析实际执行端;旧控制端缺 SSH host 时仅补全唯一、无本地冲突的归属。+ // 历史记录不证明目录仍存在:SSH 使用已有远端探测,其它入口保留本地异步探测。+ setDeviceLinkRemoteWorkingDirGuard(createRemoteWorkingDirGuard({+ findSshHosts: async (dir) => {+ const rows = await getDbClient().drizzle+ .selectDistinct({ remoteHostId: sessions.remoteHostId })+ .from(sessions)+ .where(eq(sessions.workingDir, dir));+ return rows.map((row) => row.remoteHostId).filter((id): id is string => !!id);+ },+ probeSshWorkingDirectory: probeRemoteWorkingDirectory,+ }));setDeviceLinkRemoteReviewInputGuard(assertReviewExternalInputAllowed);// 远程 xAI 订阅余量只读:该 channel 的 ipcMain handler 挂 assertTrustedSender,// device-link 由 dispatch 拦截直读注入的 reader(见 dispatch.ts 同名 setter 注释)。diff --git a/docs/dev-rules/remote-and-mobile-adaptation.md b/docs/dev-rules/remote-and-mobile-adaptation.mdindex 3de73ad311..d3ea48699f 100644--- a/docs/dev-rules/remote-and-mobile-adaptation.md+++ b/docs/dev-rules/remote-and-mobile-adaptation.md@@ -40,6 +40,20 @@ Cindy 的产品形态不止本地桌面单机。同一个功能可能运行在同步 topic 路由;不登记,手机/远程控制端就永远调不通。3. 手机版需不需要对应的入口/UI/交互?+## 远程新建 SSH 项目的目录归属(#7117)++`maker:create-session` 的路径守卫先按执行端点识别目录:显式 `remoteHostId` 经既有+SSH 就绪与目录探测后,将主机和规范化路径一同交给创建处理器,不用本机文件系统探测+SSH 路径。旧控制端省略主机时,按当前账号的 session 记录查找唯一 SSH 归属;本地目录+与 SSH 同时命中、或多个 SSH 主机命中时拒绝猜测。记录只能解析归属,不能替代实时探测。+显式 `remoteHostId: null` 选择本地;`agentDeviceId` 指定另一电脑运行 Agent 时,文件仍属+被控电脑,不反查 SSH。探测失败不降级到本机创建,探测期间撤权或切账号也不能继续创建。++`worktree:create` 等其它入口保留本地目录与网络盘超时检查。此修复不改变 wire 字段、+allowlist、重试或 relay 生命周期;手机端完整保留“主机 + 路径”的选择与记忆仍需单独适配。+实现与回归:`device-link/remote-workdir-guard.ts`、`device-link/dispatch.ts`、+`maker-ipc/register.ts` 与 `__tests__/deviceLinkHostDispatch.test.ts`(均相对 Desktop main)。+## 远程任务存档的即时反馈桌面与手机的远程任务列表在点击存档后立即乐观移走任务行,不能等待远程预检或写入