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(desktop): 支持 SSH 远程工作区审查 (#2381)

DavidShenXDea293be27f60
diff --git a/apps/desktop/src/main/git-review/__tests__/deviceOp.test.ts b/apps/desktop/src/main/git-review/__tests__/deviceOp.test.ts
index 31e1455e11..edcd4ad2b6 100644
--- a/apps/desktop/src/main/git-review/__tests__/deviceOp.test.ts
+++ b/apps/desktop/src/main/git-review/__tests__/deviceOp.test.ts
@@ -22,12 +22,17 @@ const readReviewBranchDiffMock = vi.fn();
const readReviewFileDiffMock = vi.fn();
const readReviewImagePreviewMock = vi.fn();
const readReviewMarkdownPreviewMock = vi.fn();
+const withSessionReviewExecutionMock = vi.hoisted(() => vi.fn());
vi.mock('electron', () => ({
ipcMain: { handle: vi.fn() },
shell: { openPath: vi.fn() },
}));
+vi.mock('../sshReviewBackend.js', () => ({
+ withSessionReviewExecution: withSessionReviewExecutionMock,
+}));
+
vi.mock('../ipc.js', async (importOriginal) => {
const actual = await importOriginal<typeof import('../ipc.js')>();
return {
@@ -49,6 +54,9 @@ const { handleRemoteOp, GIT_REVIEW_MAX_JSON_BYTES } = __gitReviewDeviceOpTesting
beforeEach(() => {
vi.clearAllMocks();
+ withSessionReviewExecutionMock.mockImplementation(
+ (_sessionId: string, task: () => Promise<unknown>) => task(),
+ );
});
describe('git-review device-op', () => {
@@ -117,6 +125,17 @@ describe('git-review device-op', () => {
expect(await handleRemoteOp({ op: 'get', payload: { sessionId: 's1' } })).toEqual({ ok: false, message: 'boom' });
});
+ it('does not expose controlled-device SSH setup details', async () => {
+ withSessionReviewExecutionMock.mockRejectedValue(
+ new Error('[SSH_AUTH_FAILED] Identity file C:\\Users\\alice\\.ssh\\id_ed25519'),
+ );
+
+ expect(await handleRemoteOp({ op: 'get', payload: { sessionId: 's1' } })).toEqual({
+ ok: false,
+ message: 'SSH workspace review is unavailable on the controlled device',
+ });
+ });
+
it('gzips large compressible results and round-trips through resultGz', async () => {
const result = { diff: 'context line\n'.repeat(300_000) }; // ~3.9MB JSON,高度可压缩
readReviewDataMock.mockResolvedValue(result);
diff --git a/apps/desktop/src/main/git-review/__tests__/fsPathGuard.test.ts b/apps/desktop/src/main/git-review/__tests__/fsPathGuard.test.ts
new file mode 100644
index 0000000000..cb912cac90
--- /dev/null
+++ b/apps/desktop/src/main/git-review/__tests__/fsPathGuard.test.ts
@@ -0,0 +1,11 @@
+import { describe, expect, it } from 'vitest';
+
+import { isPathInside, repoRelativeFsPath } from '../fsPathGuard';
+
+describe('git-review filesystem path guards', () => {
+ it('keeps remote POSIX paths stable on a Windows controller', () => {
+ expect(repoRelativeFsPath('/srv/repo', 'docs/readme.md')).toBe('/srv/repo/docs/readme.md');
+ expect(isPathInside('/srv/repo', '/srv/repo/docs/readme.md')).toBe(true);
+ expect(isPathInside('/srv/repo', '/srv/secret.txt')).toBe(false);
+ });
+});
diff --git a/apps/desktop/src/main/git-review/__tests__/gitRunner.test.ts b/apps/desktop/src/main/git-review/__tests__/gitRunner.test.ts
index 2d578981f8..2483dbca1a 100644
--- a/apps/desktop/src/main/git-review/__tests__/gitRunner.test.ts
+++ b/apps/desktop/src/main/git-review/__tests__/gitRunner.test.ts
@@ -3,7 +3,7 @@ import { EventEmitter } from 'node:events';
import { beforeEach, describe, expect, it, vi } from 'vitest';
-import { GitRunError, runGit, runGitBuffer } from '../gitRunner';
+import { GitRunError, runGit, runGitBuffer, withGitExecutionBackend } from '../gitRunner';
vi.mock('node:child_process', () => ({
spawn: vi.fn(),
@@ -72,4 +72,20 @@ describe('git-review gitRunner', () => {
expect(spawnedArgs()).toEqual([['cat-file', 'blob', 'HEAD:file.txt']]);
expect(spawnedArgs().some((args) => args.includes('--global') || args.includes('safe.directory'))).toBe(false);
});
+
+ it('isolates request-scoped execution backends from the local runner', async () => {
+ const backend = {
+ run: vi.fn().mockResolvedValue({ stdout: 'remote', stderr: '', exitCode: 0 }),
+ runBuffer: vi.fn().mockResolvedValue({ stdout: Buffer.from([0, 255]), stderr: '', exitCode: 0 }),
+ };
+
+ await expect(withGitExecutionBackend(backend, () => runGit(['status'], { cwd: '/remote/repo' })))
+ .resolves.toMatchObject({ stdout: 'remote' });
+ await expect(withGitExecutionBackend(backend, () => runGitBuffer(['cat-file', 'blob', 'abc'], { cwd: '/remote/repo' })))
+ .resolves.toMatchObject({ stdout: Buffer.from([0, 255]) });
+
+ expect(backend.run).toHaveBeenCalledWith(['status'], { cwd: '/remote/repo' });
+ expect(backend.runBuffer).toHaveBeenCalledOnce();
+ expect(spawn).not.toHaveBeenCalled();
+ });
});
diff --git a/apps/desktop/src/main/git-review/__tests__/ipc.test.ts b/apps/desktop/src/main/git-review/__tests__/ipc.test.ts
index 51aa6886c7..b28e8dd41f 100644
--- a/apps/desktop/src/main/git-review/__tests__/ipc.test.ts
+++ b/apps/desktop/src/main/git-review/__tests__/ipc.test.ts
@@ -7,6 +7,7 @@ import {
parseMarkdownPreviewPayload,
parseOpenFilePayload,
parseTarget,
+ openReviewFile,
readReviewData,
runReviewFileStageOperation,
} from '../ipc';
@@ -168,6 +169,36 @@ describe('git-review write busy gate', () => {
], deps)).rejects.toMatchObject({ code: 'SESSION_RUNNING' });
expect(deps.resolveScope).not.toHaveBeenCalled();
});
+
+ it('rejects SSH workspace writes before reading status or mutating Git', async () => {
+ const deps: GitReviewDeps = {
+ resolveScope: vi.fn().mockResolvedValue({
+ disabledReason: null,
+ repoRoot: '/remote/repo',
+ source: 'remote',
+ } as ReviewScope),
+ readStatus: vi.fn(),
+ readDiffs: vi.fn(),
+ };
+
+ await expect(runReviewFileStageOperation('s1', 'stage', [
+ { source: 'unstaged', path: 'file.txt', oldPath: null },
+ ], deps)).rejects.toMatchObject({ code: 'PRECONDITION_FAILED' });
+ expect(deps.readStatus).not.toHaveBeenCalled();
+ });
+
+ it('rejects opening a controlled-side file with the local shell', async () => {
+ const openPath = vi.fn();
+ const resolveScope = vi.fn().mockResolvedValue({
+ disabledReason: null,
+ repoRoot: '/remote/repo',
+ source: 'remote',
+ } as ReviewScope);
+
+ await expect(openReviewFile('s1', 'file.txt', { resolveScope }, openPath))
+ .rejects.toMatchObject({ code: 'PRECONDITION_FAILED' });
+ expect(openPath).not.toHaveBeenCalled();
+ });
});
describe('git-review hunk IPC serialization', () => {
diff --git a/apps/desktop/src/main/git-review/__tests__/scopeResolver.test.ts b/apps/desktop/src/main/git-review/__tests__/scopeResolver.test.ts
index 809778836d..3af1d3ad60 100644
--- a/apps/desktop/src/main/git-review/__tests__/scopeResolver.test.ts
+++ b/apps/desktop/src/main/git-review/__tests__/scopeResolver.test.ts
@@ -2,8 +2,13 @@ import path from 'node:path';
import { describe, expect, it, vi } from 'vitest';
-import { resolveReviewScope, type ScopeResolverDeps } from '../scopeResolver';
-import type { GitRunResult } from '../gitRunner';
+import {
+ defaultScopeResolverDeps,
+ resolveReviewScope,
+ type ScopeResolverDeps,
+ withSessionReviewRowSnapshot,
+} from '../scopeResolver';
+import { GitRunError, type GitRunResult } from '../gitRunner';
function deps(patch: Partial<ScopeResolverDeps> = {}): ScopeResolverDeps {
return {
@@ -47,22 +52,112 @@ describe('git-review scopeResolver', () => {
});
});
- it('returns a remote-session disabled scope before probing local paths', async () => {
+ it('resolves an SSH session with remote POSIX paths without probing local paths', async () => {
const d = deps({
getSessionRow: vi.fn().mockResolvedValue({
id: 's1',
- workingDir: '/remote/repo',
+ workingDir: '/remote/project/subdir',
worktreePath: null,
remoteHostId: 'host-1',
}),
+ git: vi.fn().mockImplementation(async (args: readonly string[]): Promise<GitRunResult> => {
+ if (args.includes('--show-toplevel')) return { stdout: '/remote/project\n', stderr: '', exitCode: 0 };
+ if (args.includes('--verify')) return { stdout: '0123456789abcdef\n', stderr: '', exitCode: 0 };
+ if (args[0] === 'symbolic-ref') return { stdout: 'feature/ssh-review\n', stderr: '', exitCode: 0 };
+ return { stdout: '', stderr: '', exitCode: 0 };
+ }),
});
const scope = await resolveReviewScope('s1', d);
- expect(scope.disabledReason).toBe('remote-session');
+ expect(scope).toMatchObject({
+ workdir: '/remote/project/subdir',
+ repoRoot: '/remote/project',
+ source: 'remote',
+ branch: 'feature/ssh-review',
+ headOid: '0123456789abcdef',
+ isDetached: false,
+ disabledReason: null,
+ });
expect(d.resolveSessionDir).not.toHaveBeenCalled();
});
+ it('marks a remote HEAD without a symbolic branch as detached', async () => {
+ const d = deps({
+ getSessionRow: vi.fn().mockResolvedValue({
+ id: 's1',
+ workingDir: '/remote/project',
+ worktreePath: null,
+ remoteHostId: 'host-1',
+ }),
+ git: vi.fn().mockImplementation(async (args: readonly string[]): Promise<GitRunResult> => {
+ if (args.includes('--show-toplevel')) return { stdout: '/remote/project\n', stderr: '', exitCode: 0 };
+ if (args.includes('--verify')) return { stdout: '0123456789abcdef\n', stderr: '', exitCode: 0 };
+ throw new GitRunError({ args, cwd: '/remote/project', exitCode: 1, stdout: '', stderr: '' });
+ }),
+ });
+
+ await expect(resolveReviewScope('s1', d)).resolves.toMatchObject({
+ branch: null,
+ headOid: '0123456789abcdef',
+ isDetached: true,
+ });
+ });
+
+ it('reuses the request session-row snapshot instead of querying a second routing identity', async () => {
+ const snapshot = {
+ id: 's1',
+ workingDir: '/remote/project',
+ worktreePath: null,
+ remoteHostId: 'host-1',
+ };
+
+ const row = await withSessionReviewRowSnapshot(
+ snapshot,
+ () => defaultScopeResolverDeps().getSessionRow('s1'),
+ );
+
+ expect(row).toEqual(snapshot);
+ });
+
+ it('distinguishes missing Git on the SSH host from a non-Git directory', async () => {
+ const d = deps({
+ getSessionRow: vi.fn().mockResolvedValue({
+ id: 's1',
+ workingDir: '/remote/project',
+ worktreePath: null,
+ remoteHostId: 'host-1',
+ }),
+ git: vi.fn().mockRejectedValue(new GitRunError({
+ args: ['rev-parse'],
+ cwd: '/remote/project',
+ exitCode: 127,
+ stdout: '',
+ stderr: 'git: command not found',
+ })),
+ });
+
+ const scope = await resolveReviewScope('s1', d);
+
+ expect(scope.disabledReason).toBe('git-unavailable');
+ expect(scope.disabledMessage).toBe('Git is not available on the SSH host');
+ });
+
+ it('propagates SSH transport failures during the remote repository probe', async () => {
+ const failure = new Error('SSH channel closed while probing Git');
+ const d = deps({
+ getSessionRow: vi.fn().mockResolvedValue({
+ id: 's1',
+ workingDir: '/remote/project',
+ worktreePath: null,
+ remoteHostId: 'host-1',
+ }),
+ git: vi.fn().mockRejectedValue(failure),
+ });
+
+ await expect(resolveReviewScope('s1', d)).rejects.toBe(failure);
+ });
+
it('falls back to non-git disabled scope when no workdir resolves', async () => {
const d = deps({
resolveSessionDir: vi.fn().mockResolvedValue({ workdir: null, head: null, source: null }),
diff --git a/apps/desktop/src/main/git-review/__tests__/sshReviewBackend.test.ts b/apps/desktop/src/main/git-review/__tests__/sshReviewBackend.test.ts
new file mode 100644
index 0000000000..71b8a96d0e
--- /dev/null
+++ b/apps/desktop/src/main/git-review/__tests__/sshReviewBackend.test.ts
@@ -0,0 +1,369 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { runGit as runScopedGit, runGitBuffer as runScopedGitBuffer } from '../gitRunner';
+import {
+ lstatReviewWorktreePath,
+ readReviewWorktreeFile,
+ readReviewWorktreePrefix,
+} from '../reviewFileRunner';
+import {
+ __sshReviewBackendTesting,
+ assertReadOnlyRemoteGitArgs,
+ buildRemoteGitCommand,
+ createSshPreviewReaderDeps,
+ type SshReviewBackendDeps,
+ type SshReviewHost,
+ withSessionReviewExecution,
+} from '../sshReviewBackend';
+import { defaultScopeResolverDeps } from '../scopeResolver';
+import type { ReviewScope } from '../types';
+
+function remoteDeps(
+ host: SshReviewHost,
+ fileBrowser: SshReviewBackendDeps['getFileBrowser'] extends () => infer T ? T : never = {
+ request: vi.fn(),
+ },
+ patch: Partial<SshReviewBackendDeps> = {},
+): SshReviewBackendDeps {
+ return {
+ getSessionRow: vi.fn().mockResolvedValue({
+ id: 's1',
+ workingDir: '/srv/project',
+ worktreePath: null,
+ remoteHostId: 'host-1',
+ }),
+ ensureHostReady: vi.fn().mockResolvedValue(undefined),
+ getHost: vi.fn().mockReturnValue(host),
+ getFileBrowser: vi.fn().mockReturnValue(fileBrowser),
+ ...patch,
+ };
+}
+
+function execResult(
+ bytes: Buffer | string,
+ patch: Partial<Awaited<ReturnType<SshReviewHost['exec']>>> = {},
+) {
+ const buffer = typeof bytes === 'string' ? Buffer.from(bytes, 'utf8') : bytes;
+ return {
+ stdout: buffer.toString('base64'),
+ stderr: '',
+ exitCode: 0,
+ signal: null,
+ ...patch,
+ };
+}
+
+describe('SSH git-review backend', () => {
+ it('pins local session routing for the complete review request too', async () => {
+ const row = {
+ id: 'local-1',
+ workingDir: 'C:\\repo',
+ worktreePath: null,
+ remoteHostId: null,
+ };
+ const deps = remoteDeps(
+ { exec: vi.fn() },
+ { request: vi.fn() },
+ { getSessionRow: vi.fn().mockResolvedValue(row) },
+ );
+
+ const resolved = await withSessionReviewExecution(
+ 'local-1',
+ () => defaultScopeResolverDeps().getSessionRow('local-1'),
+ deps,
+ );
+
+ expect(resolved).toEqual(row);
+ expect(deps.ensureHostReady).not.toHaveBeenCalled();
+ });
+
+ it('keeps the remote cwd and Git args out of shell syntax', () => {
+ const cwd = "/srv/a repo/with ' quote";
+ const gitArg = "file with ' quote.txt";
+ const command = buildRemoteGitCommand(cwd, ['diff', '--', gitArg]);
+
+ expect(command).toContain("bash -c '");
+ expect(command).not.toContain(cwd);
+ expect(command).not.toContain(gitArg);
+ expect(command).toContain(Buffer.from(cwd).toString('base64'));
+ expect(command).toContain(Buffer.from(gitArg).toString('base64'));
+ });
+
+ it('runs Git on the authoritative SSH host and preserves binary stdout', async () => {
+ const raw = Buffer.from([0, 1, 2, 0, 255]);
+ const host: SshReviewHost = {
+ exec: vi.fn().mockResolvedValue(execResult(raw)),
+ };
+ const deps = remoteDeps(host);
+
+ const result = await withSessionReviewExecution(
+ 's1',
+ () => runScopedGitBuffer(['cat-file', 'blob', 'abc1234'], { cwd: '/srv/project' }),
+ deps,
+ );
+
+ expect(result.stdout).toEqual(raw);
+ expect(deps.ensureHostReady).toHaveBeenCalledWith('host-1');
+ expect(deps.getHost).toHaveBeenCalledWith('host-1');
+ expect(host.exec).toHaveBeenCalledOnce();
+ const [command, options] = vi.mocked(host.exec).mock.calls[0];
+ expect(command).not.toContain('/srv/project');
+ expect(options).toMatchObject({ label: 'git-review-read', timeoutMs: 30_000 });
+ });
+
+ it('rejects mutating commands and unsafe diff options before opening an SSH channel', async () => {
+ const host: SshReviewHost = { exec: vi.fn() };
+ const deps = remoteDeps(host);
+
+ await expect(
+ withSessionReviewExecution(
+ 's1',
+ () => runScopedGit(['add', 'file.txt'], { cwd: '/srv/project' }),
+ deps,
+ ),
+ ).rejects.toThrow(/read-only Git operations/);
+ expect(() =>
+ assertReadOnlyRemoteGitArgs(['diff', '--output=/tmp/leak'], { cwd: '/srv/project' }),
+ ).toThrow(/external side effects/);
+ expect(() =>
+ assertReadOnlyRemoteGitArgs(['cat-file', '--filters', 'HEAD:file.txt'], {
+ cwd: '/srv/project',
+ }),
+ ).toThrow(/external side effects/);
+ expect(host.exec).not.toHaveBeenCalled();
+ });
+
+ it('forces repository-configured diff helpers off on the controlled side', () => {
+ expect(__sshReviewBackendTesting.hardenedRemoteGitArgs(['diff', '--numstat']))
+ .toEqual(['diff', '--no-ext-diff', '--no-textconv', '--numstat']);
+ expect(__sshReviewBackendTesting.hardenedRemoteGitArgs(['log', '--format=%H']))
+ .toEqual(['log', '--no-ext-diff', '--no-textconv', '--format=%H']);
+ });
+
+ it('redacts the remote workspace path from command failures', async () => {
+ const host: SshReviewHost = {
+ exec: vi.fn().mockResolvedValue(
+ execResult('', {
+ stderr: "fatal: unsafe repository at '/srv/project'",
+ exitCode: 128,
+ }),
+ ),
+ };
+
+ await expect(
+ withSessionReviewExecution(
+ 's1',
+ () => runScopedGit(['status'], { cwd: '/srv/project' }),
+ remoteDeps(host),
+ ),
+ ).rejects.toSatisfy((err: Error) => {
+ expect(err.message).toContain('<workspace>');
+ expect(err.message).not.toContain('/srv/project');
+ return true;
+ });
+ });
+
+ it('redacts an ancestor repo root when the remote workspace is a subdirectory', async () => {
+ const host: SshReviewHost = {
+ exec: vi.fn().mockResolvedValue(
+ execResult('', {
+ stderr: "fatal: unsafe repository at '/Users/david/project'; cwd '/Users/david/project/subdir'",
+ exitCode: 128,
+ }),
+ ),
+ };
+ const deps = remoteDeps(
+ host,
+ { request: vi.fn() },
+ {
+ getSessionRow: vi.fn().mockResolvedValue({
+ id: 's1',
+ workingDir: '/Users/david/project/subdir',
+ worktreePath: null,
+ remoteHostId: 'host-1',
+ }),
+ },
+ );
+
+ await expect(
+ withSessionReviewExecution(
+ 's1',
+ () => runScopedGit(['rev-parse', '--show-toplevel'], {
+ cwd: '/Users/david/project/subdir',
+ }),
+ deps,
+ ),
+ ).rejects.toSatisfy((err: Error) => {
+ expect(err.message).toContain('<workspace>');
+ expect(err.message).not.toContain('/Users/david/project');
+ expect(err.message).not.toContain('/Users/david/project/subdir');
+ return true;
+ });
+ });
+
+ it('keeps concurrent SSH review requests isolated by session', async () => {
+ const makeDeps = (sessionId: string, hostId: string, output: string): SshReviewBackendDeps => {
+ const host: SshReviewHost = {
+ exec: vi.fn(async () => {
+ await new Promise((resolve) => setImmediate(resolve));
+ return execResult(output);
+ }),
+ };
+ return remoteDeps(
+ host,
+ { request: vi.fn() },
+ {
+ getSessionRow: vi.fn().mockResolvedValue({
+ id: sessionId,
+ workingDir: `/srv/${sessionId}`,
+ worktreePath: null,
+ remoteHostId: hostId,
+ }),
+ },
+ );
+ };
+
+ const [one, two] = await Promise.all([
+ withSessionReviewExecution(
+ 's1',
+ () => runScopedGit(['status'], { cwd: '/srv/s1' }),
+ makeDeps('s1', 'h1', 'one'),
+ ),
+ withSessionReviewExecution(
+ 's2',
+ () => runScopedGit(['status'], { cwd: '/srv/s2' }),
+ makeDeps('s2', 'h2', 'two'),
+ ),
+ ]);
+
+ expect(one.stdout).toBe('one');
+ expect(two.stdout).toBe('two');
+ });
+
+ it('reads guarded worktree previews through the controlled-side file service', async () => {
+ const bytes = Buffer.from('remote markdown', 'utf8');
+ const request = vi.fn(
+ async (_hostId: string, method: string, params: Record<string, unknown>) => {
+ expect(params).toMatchObject({ workdir: '/srv/project', relPath: 'docs/readme.md' });
+ if (method === 'stat') return { type: 'file', size: bytes.length, mtimeMs: 123 };
+ return {
+ dataBase64: bytes.toString('base64'),
+ eof: true,
+ size: bytes.length,
+ mtimeMs: 123,
+ };
+ },
+ );
+ const scope = {
+ sessionId: 's1',
+ workingDir: '/srv/project',
+ repoRoot: '/srv/project',
+ source: 'remote',
+ } as ReviewScope;
+ const deps = remoteDeps({ exec: vi.fn() }, { request });
+
+ const result = await withSessionReviewExecution(
+ 's1',
+ async () => {
+ const preview = createSshPreviewReaderDeps(scope);
+ const stat = await preview.stat('/srv/project/docs/readme.md');
+ const content = await preview.readFile('/srv/project/docs/readme.md');
+ return { stat, content };
+ },
+ deps,
+ );
+
+ expect(result.stat.isFile()).toBe(true);
+ expect(result.content).toEqual(bytes);
+ expect(request).toHaveBeenCalledTimes(2);
+ });
+
+ it('routes ordinary diff metadata and content reads through the controlled-side file service', async () => {
+ const bytes = Buffer.from('line one\nline two\n', 'utf8');
+ const request = vi.fn(
+ async (_hostId: string, method: string, params: Record<string, unknown>) => {
+ expect(params).toMatchObject({ workdir: '/srv/project', relPath: 'new.txt' });
+ if (method === 'stat') return { type: 'file', size: bytes.length, mtimeMs: 123 };
+ const length = params.length as number;
+ return {
+ dataBase64: bytes.subarray(0, length).toString('base64'),
+ eof: length >= bytes.length,
+ size: bytes.length,
+ mtimeMs: 123,
+ };
+ },
+ );
+
+ const result = await withSessionReviewExecution(
+ 's1',
+ async () => ({
+ stat: await lstatReviewWorktreePath('/srv/project', 'new.txt'),
+ prefix: await readReviewWorktreePrefix('/srv/project', 'new.txt', 8),
+ content: await readReviewWorktreeFile('/srv/project', 'new.txt', 1024),
+ }),
+ remoteDeps({ exec: vi.fn() }, { request }),
+ );
+
+ expect(result.stat).toEqual({ size: bytes.length, isSymlink: false });
+ expect(result.prefix).toEqual(bytes.subarray(0, 8));
+ expect(result.content).toEqual(bytes);
+ expect(request).toHaveBeenCalledTimes(3);
+ });
+
+ it('rejects oversized decoded chunks even when the controlled side claims eof', async () => {
+ const oversized = Buffer.alloc(9, 1);
+ const request = vi.fn().mockResolvedValue({
+ dataBase64: oversized.toString('base64'),
+ eof: true,
+ size: 1,
+ mtimeMs: 123,
+ });
+
+ await expect(
+ withSessionReviewExecution(
+ 's1',
+ () => readReviewWorktreeFile('/srv/project', 'new.txt', 8),
+ remoteDeps({ exec: vi.fn() }, { request }),
+ ),
+ ).rejects.toThrow(/oversized/);
+ });
+
+ it('rejects oversized prefix responses before returning them to preview readers', async () => {
+ const oversized = Buffer.alloc(9, 1);
+ const request = vi.fn().mockResolvedValue({
+ dataBase64: oversized.toString('base64'),
+ eof: true,
+ size: oversized.length,
+ mtimeMs: 123,
+ });
+
+ await expect(
+ withSessionReviewExecution(
+ 's1',
+ () => readReviewWorktreePrefix('/srv/project', 'new.txt', 8),
+ remoteDeps({ exec: vi.fn() }, { request }),
+ ),
+ ).rejects.toThrow(/oversized/);
+ });
+
+ it('redacts SSH setup details before review errors leave Main', async () => {
+ const deps = remoteDeps(
+ { exec: vi.fn() },
+ { request: vi.fn() },
+ {
+ ensureHostReady: vi.fn().mockRejectedValue(
+ new Error('[SSH_AUTH_FAILED] Identity file C:\\Users\\alice\\.ssh\\id_ed25519'),
+ ),
+ },
+ );
+
+ await expect(withSessionReviewExecution('s1', async () => null, deps))
+ .rejects.toThrow('[SSH_AUTH_FAILED] SSH workspace review could not connect to the remote host');
+ });
+
+ it('rejects remote preview traversal before calling the file service', () => {
+ expect(() =>
+ __sshReviewBackendTesting.remoteRelativePath('/srv/project', '/srv/secret.txt'),
+ ).toThrow(/outside the repository/);
+ });
+});
diff --git a/apps/desktop/src/main/git-review/__tests__/statusReader.test.ts b/apps/desktop/src/main/git-review/__tests__/statusReader.test.ts
index 6befade8ca..073fd1205f 100644
--- a/apps/desktop/src/main/git-review/__tests__/statusReader.test.ts
+++ b/apps/desktop/src/main/git-review/__tests__/statusReader.test.ts
@@ -73,6 +73,12 @@ describe('git-review statusReader', () => {
expect(status.writeDisabledReasons).toContain('unmerged');
});
+ it('marks SSH workspace status as view-only', () => {
+ const status = parsePorcelainV2Status('# branch.head main\0', { ...scope, source: 'remote' });
+
+ expect(status.writeDisabledReasons).toContain('remote-ssh');
+ });
+
it('guards git status stdout collection with the large diff stdout limit', async () => {
runGitMock.mockImplementation(async (args: readonly string[]) => {
if (args[0] === 'status') {
diff --git a/apps/desktop/src/main/git-review/device-op.ts b/apps/desktop/src/main/git-review/device-op.ts
index 5fa790e0be..56eb8ccc89 100644
--- a/apps/desktop/src/main/git-review/device-op.ts
+++ b/apps/desktop/src/main/git-review/device-op.ts
@@ -12,8 +12,8 @@
* 一律不实现,未知 op 确定性回 `{ok:false}`。
* - 入参只有 sessionId + 结构化查询字段(复用本机 IPC 的 parse* 校验),不接受
* 任何客户端路径:workdir 由被控端 resolveReviewScope 从自己的 session 记录
- * 解析;SSH 远程会话由 scope 层返回 remote-session 禁用态(不二跳,对齐
- * 本机审查面板现状)。
+ * 解析;若被控端任务本身是 SSH 工作区,同样由被控端 Main 在目标 SSH 主机
+ * 上执行只读 Git,控制端仍看不到主机凭据或任意命令能力。
*
* oversize:响应序列化超 relay 帧限(MAX_FRAME_BYTES=2MiB)前主动预判——先
* gzip(diff 文本压缩率高),仍超回结构化 `{ ok:false, code:'OVERSIZE' }`,
@@ -45,6 +45,7 @@ import {
readReviewMarkdownPreview,
readReviewSummary,
} from './ipc.js';
+import { withSessionReviewExecution } from './sshReviewBackend.js';
const log = createLogger('git-review/device-op');
@@ -92,33 +93,35 @@ async function dispatchRemoteOp(op: string, payload: unknown): Promise<unknown>
switch (op) {
case 'get': {
const { sessionId, options } = parseReviewDataPayload(payload);
- return readReviewData(sessionId, options);
+ return withSessionReviewExecution(sessionId, () => readReviewData(sessionId, options));
+ }
+ case 'summary': {
+ const sessionId = parseSessionId(payload);
+ return withSessionReviewExecution(sessionId, () => readReviewSummary(sessionId));
}
- case 'summary':
- return readReviewSummary(parseSessionId(payload));
case 'commits': {
const { sessionId, baseRef } = parseCommitsPayload(payload);
- return readReviewCommits(sessionId, baseRef);
+ return withSessionReviewExecution(sessionId, () => readReviewCommits(sessionId, baseRef));
}
case 'commit-diff': {
const { sessionId, oid, options } = parseCommitDiffPayload(payload);
- return readReviewCommitDiff(sessionId, oid, options);
+ return withSessionReviewExecution(sessionId, () => readReviewCommitDiff(sessionId, oid, options));
}
case 'branch-diff': {
const { sessionId, baseRef, options } = parseBranchDiffPayload(payload);
- return readReviewBranchDiff(sessionId, baseRef, options);
+ return withSessionReviewExecution(sessionId, () => readReviewBranchDiff(sessionId, baseRef, options));
}
case 'file-diff': {
const { sessionId, request } = parseFileDiffPayload(payload);
- return readReviewFileDiff(sessionId, request);
+ return withSessionReviewExecution(sessionId, () => readReviewFileDiff(sessionId, request));
}
case 'image-preview': {
const { sessionId, request } = parseImagePreviewPayload(payload);
- return readReviewImagePreview(sessionId, request);
+ return withSessionReviewExecution(sessionId, () => readReviewImagePreview(sessionId, request));
}
case 'markdown-preview': {
const { sessionId, request } = parseMarkdownPreviewPayload(payload);
- return readReviewMarkdownPreview(sessionId, request);
+ return withSessionReviewExecution(sessionId, () => readReviewMarkdownPreview(sessionId, request));
}
default:
return null;
@@ -153,6 +156,10 @@ async function handleRemoteOp(args: GitReviewRemoteOpArgs): Promise<GitReviewRem
// 避免把内部堆栈带回控制端。
if (err instanceof Error && /\[(INVALID_PARAMS|PRECONDITION_FAILED)\]/.test(err.message)) throw err;
const message = err instanceof Error ? err.message : String(err);
+ if (/\[SSH_[A-Z_]+\]/.test(message)) {
+ log.warn('git-review remote-op SSH backend unavailable', { op: args.op });
+ return bad('SSH workspace review is unavailable on the controlled device');
+ }
log.warn('git-review remote-op failed', { op: args.op, message });
return bad(message);
}
diff --git a/apps/desktop/src/main/git-review/diffReader.ts b/apps/desktop/src/main/git-review/diffReader.ts
index 48da46fab7..676defb1bb 100644
--- a/apps/desktop/src/main/git-review/diffReader.ts
+++ b/apps/desktop/src/main/git-review/diffReader.ts
@@ -5,12 +5,13 @@
* or partially selected by later M2 operations.
*/
-import { promises as fs } from 'node:fs';
-import path from 'node:path';
-
import { runGit, GitRunError } from './gitRunner.js';
import { parseGitDiff, parseGitDiffs } from './diffParser.js';
-import { resolveRepoContainedRealPath } from './fsPathGuard.js';
+import {
+ lstatReviewWorktreePath,
+ readReviewWorktreeFile,
+ readReviewWorktreePrefix,
+} from './reviewFileRunner.js';
import {
buildCappedDiffData,
createDiffSummaryEntry,
@@ -35,14 +36,9 @@ function literalPathspec(gitPath: string): string {
return `:(top,literal)${gitPath}`;
}
-function toFsPath(repoRoot: string, gitPath: string): string {
- return path.join(repoRoot, ...gitPath.split('/'));
-}
-
async function lstatWorktreePath(repoRoot: string, gitPath: string): Promise<{ size: number | null; isSymlink: boolean }> {
try {
- const stat = await fs.lstat(toFsPath(repoRoot, gitPath));
- return { size: stat.size, isSymlink: stat.isSymbolicLink() };
+ return await lstatReviewWorktreePath(repoRoot, gitPath);
} catch {
return { size: null, isSymlink: false };
}
@@ -55,15 +51,7 @@ async function statSize(repoRoot: string, gitPath: string): Promise<number | nul
async function hasNulByte(repoRoot: string, gitPath: string): Promise<boolean> {
try {
if ((await lstatWorktreePath(repoRoot, gitPath)).isSymlink) return false;
- const { targetReal } = await resolveRepoContainedRealPath(repoRoot, gitPath);
- const fh = await fs.open(targetReal, 'r');
- try {
- const buf = Buffer.alloc(8192);
- const { bytesRead } = await fh.read(buf, 0, buf.length, 0);
- return buf.subarray(0, bytesRead).includes(0);
- } finally {
- await fh.close();
- }
+ return (await readReviewWorktreePrefix(repoRoot, gitPath, 8192)).includes(0);
} catch {
return false;
}
@@ -268,8 +256,7 @@ async function countUntrackedTextLines(repoRoot: string, gitPath: string, size:
if (size === null || size > 3 * 1024 * 1024) return 0;
try {
if ((await lstatWorktreePath(repoRoot, gitPath)).isSymlink) return 0;
- const { targetReal } = await resolveRepoContainedRealPath(repoRoot, gitPath);
- const content = await fs.readFile(targetReal);
+ const content = await readReviewWorktreeFile(repoRoot, gitPath, 3 * 1024 * 1024);
if (content.includes(0)) return 0;
if (content.length === 0) return 0;
let lines = 0;
diff --git a/apps/desktop/src/main/git-review/fsPathGuard.ts b/apps/desktop/src/main/git-review/fsPathGuard.ts
index 77f17e58f2..51563063e6 100644
--- a/apps/desktop/src/main/git-review/fsPathGuard.ts
+++ b/apps/desktop/src/main/git-review/fsPathGuard.ts
@@ -31,12 +31,14 @@ const defaultDeps: RepoContainedPathDeps = {
};
export function repoRelativeFsPath(repoRoot: string, gitPath: string): string {
- return path.join(repoRoot, ...gitPath.split('/'));
+ const pathApi = path.posix.isAbsolute(repoRoot) ? path.posix : path;
+ return pathApi.join(repoRoot, ...gitPath.split('/'));
}
export function isPathInside(parent: string, child: string): boolean {
- const relative = path.relative(parent, child);
- return relative === '' || (!relative.startsWith('..') && !path.isAbsolute(relative));
+ const pathApi = path.posix.isAbsolute(parent) ? path.posix : path;
+ const relative = pathApi.relative(parent, child);
+ return relative === '' || (!relative.startsWith('..') && !pathApi.isAbsolute(relative));
}
export async function resolveRepoContainedRealPath(
diff --git a/apps/desktop/src/main/git-review/gitRunner.ts b/apps/desktop/src/main/git-review/gitRunner.ts
index 0b873c0e24..4516be7c20 100644
--- a/apps/desktop/src/main/git-review/gitRunner.ts
+++ b/apps/desktop/src/main/git-review/gitRunner.ts
@@ -5,6 +5,7 @@
* non-zero exit codes, and explicit stdout guards for large diff reads.
*/
+import { AsyncLocalStorage } from 'node:async_hooks';
import { spawn } from 'node:child_process';
export interface GitRunResult {
@@ -66,6 +67,23 @@ export interface GitRunBufferOptions extends GitRunOptions {
maxStdoutBytes?: number;
}
+/**
+ * Request-scoped Git execution surface. SSH review installs one of these for
+ * the lifetime of an IPC request, while local review keeps using spawn below.
+ * AsyncLocalStorage prevents concurrent local/remote review panes from sharing
+ * a host or working directory.
+ */
+export interface GitExecutionBackend {
+ run(args: readonly string[], opts?: GitRunOptions): Promise<GitRunResult>;
+ runBuffer(args: readonly string[], opts?: GitRunBufferOptions): Promise<GitRunBufferResult>;
+}
+
+const executionBackend = new AsyncLocalStorage<GitExecutionBackend>();
+
+export function withGitExecutionBackend<T>(backend: GitExecutionBackend, task: () => Promise<T>): Promise<T> {
+ return executionBackend.run(backend, task);
+}
+
const DEFAULT_TIMEOUT_MS = 30_000;
function buildEnv(extraEnv?: Record<string, string | undefined>): NodeJS.ProcessEnv {
@@ -340,9 +358,11 @@ async function runGitBufferOnce(args: readonly string[], opts: GitRunBufferOptio
}
export async function runGit(args: readonly string[], opts: GitRunOptions = {}): Promise<GitRunResult> {
- return runGitOnce(args, opts);
+ const backend = executionBackend.getStore();
+ return backend ? backend.run(args, opts) : runGitOnce(args, opts);
}
export async function runGitBuffer(args: readonly string[], opts: GitRunBufferOptions = {}): Promise<GitRunBufferResult> {
- return runGitBufferOnce(args, opts);
+ const backend = executionBackend.getStore();
+ return backend ? backend.runBuffer(args, opts) : runGitBufferOnce(args, opts);
}
diff --git a/apps/desktop/src/main/git-review/ipc.ts b/apps/desktop/src/main/git-review/ipc.ts
index 59165323c7..528092938c 100644
--- a/apps/desktop/src/main/git-review/ipc.ts
+++ b/apps/desktop/src/main/git-review/ipc.ts
@@ -21,6 +21,7 @@ import { readImagePreview } from './imageReader.js';
import { readMarkdownPreview } from './markdownReader.js';
import { GitReviewPushError, pushBranch } from './pushOps.js';
import { resolveReviewScope } from './scopeResolver.js';
+import { createSshPreviewReaderDeps, withSessionReviewExecution } from './sshReviewBackend.js';
import { readStatus } from './statusReader.js';
import { applyFileBatch, applyHunkSelection, GitReviewStageError } from './stageOps.js';
import type {
@@ -245,6 +246,9 @@ export async function openReviewFile(
if (scope.disabledReason || !scope.repoRoot) {
throwIpcError('PRECONDITION_FAILED', 'No git repository is available for this session');
}
+ if (scope.source === 'remote') {
+ throwIpcError('PRECONDITION_FAILED', 'Opening files is unavailable for SSH workspace review');
+ }
let targetReal: string;
try {
targetReal = (await resolveRepoContainedRealPath(scope.repoRoot, gitPath)).targetReal;
@@ -269,7 +273,7 @@ export async function readReviewImagePreview(
if (scope.disabledReason || !scope.repoRoot) {
throwIpcError('PRECONDITION_FAILED', scope.disabledMessage ?? 'git review is unavailable');
}
- return readImagePreview(scope, request);
+ return readImagePreview(scope, request, scope.source === 'remote' ? createSshPreviewReaderDeps(scope) : {});
}
export async function readReviewMarkdownPreview(
@@ -281,7 +285,16 @@ export async function readReviewMarkdownPreview(
if (scope.disabledReason || !scope.repoRoot) {
throwIpcError('PRECONDITION_FAILED', scope.disabledMessage ?? 'git review is unavailable');
}
- return readMarkdownPreview(scope, request);
+ const preview = await readMarkdownPreview(
+ scope,
+ request,
+ scope.source === 'remote' ? createSshPreviewReaderDeps(scope) : {},
+ );
+ // Repository Markdown is rendered with privileged links disabled in the
+ // renderer. Clearing a controlled-side baseDir is an additional boundary:
+ // future renderer changes cannot reinterpret an SSH path as a controller
+ // local file origin.
+ return scope.source === 'remote' ? { ...preview, baseDir: null } : preview;
}
async function runQueuedWrite<T>(
@@ -294,6 +307,9 @@ async function runQueuedWrite<T>(
if (scope.disabledReason || !scope.repoRoot) {
throwIpcError('PRECONDITION_FAILED', scope.disabledMessage ?? 'git review is unavailable');
}
+ if (scope.source === 'remote') {
+ throwIpcError('PRECONDITION_FAILED', 'SSH workspace review is view-only');
+ }
return enqueueGitRepoWrite(scope.repoRoot, async () => {
await assertSessionWriteAllowed(sessionId, deps);
return task();
@@ -320,7 +336,16 @@ function mapWriteError(err: unknown): never {
}
throwIpcError('PRECONDITION_FAILED', message);
}
- if (err instanceof Error && /\[(INVALID_PARAMS|PRECONDITION_FAILED|STALE_DIFF|PUSH_LEASE_EXPIRED|PUSH_NO_REMOTE|SESSION_RUNNING)\]/.test(err.message)) throw err;
+ if (isForwardableReviewIpcError(err)) throw err;
+ throwIpcError('INTERNAL', err instanceof Error ? err.message : String(err));
+}
+
+function isForwardableReviewIpcError(err: unknown): err is Error {
+ return err instanceof Error && /\[(INVALID_PARAMS|PRECONDITION_FAILED|STALE_DIFF|PUSH_LEASE_EXPIRED|PUSH_NO_REMOTE|SESSION_RUNNING|SSH_[A-Z_]+)\]/.test(err.message);
+}
+
+function rethrowReviewIpcError(err: unknown): never {
+ if (isForwardableReviewIpcError(err)) throw err;
throwIpcError('INTERNAL', err instanceof Error ? err.message : String(err));
}
@@ -675,144 +700,136 @@ export function registerGitReviewIpc(options: GitReviewIpcOptions = {}): void {
ipcMain.handle(GIT_REVIEW_INVOKE.GET, async (_event, payload: unknown) => {
try {
const { sessionId, options } = parseReviewDataPayload(payload);
- return await readReviewData(sessionId, options);
+ return await withSessionReviewExecution(sessionId, () => readReviewData(sessionId, options));
} catch (err) {
- if (err instanceof Error && /\[INVALID_PARAMS\]/.test(err.message)) throw err;
- throwIpcError('INTERNAL', err instanceof Error ? err.message : String(err));
+ rethrowReviewIpcError(err);
}
});
ipcMain.handle(GIT_REVIEW_INVOKE.SUMMARY, async (_event, payload: unknown) => {
try {
- return await readReviewSummary(parseSessionId(payload));
+ const sessionId = parseSessionId(payload);
+ return await withSessionReviewExecution(sessionId, () => readReviewSummary(sessionId));
} catch (err) {
- if (err instanceof Error && /\[INVALID_PARAMS\]/.test(err.message)) throw err;
- throwIpcError('INTERNAL', err instanceof Error ? err.message : String(err));
+ rethrowReviewIpcError(err);
}
});
ipcMain.handle(GIT_REVIEW_INVOKE.COMMITS, async (_event, payload: unknown) => {
try {
const { sessionId, baseRef } = parseCommitsPayload(payload);
- return await readReviewCommits(sessionId, baseRef);
+ return await withSessionReviewExecution(sessionId, () => readReviewCommits(sessionId, baseRef));
} catch (err) {
- if (err instanceof Error && /\[INVALID_PARAMS\]/.test(err.message)) throw err;
- throwIpcError('INTERNAL', err instanceof Error ? err.message : String(err));
+ rethrowReviewIpcError(err);
}
});
ipcMain.handle(GIT_REVIEW_INVOKE.COMMIT_DIFF, async (_event, payload: unknown) => {
try {
const { sessionId, oid, options } = parseCommitDiffPayload(payload);
- return await readReviewCommitDiff(sessionId, oid, options);
+ return await withSessionReviewExecution(sessionId, () => readReviewCommitDiff(sessionId, oid, options));
} catch (err) {
- if (err instanceof Error && /\[INVALID_PARAMS\]/.test(err.message)) throw err;
- throwIpcError('INTERNAL', err instanceof Error ? err.message : String(err));
+ rethrowReviewIpcError(err);
}
});
ipcMain.handle(GIT_REVIEW_INVOKE.BRANCH_DIFF, async (_event, payload: unknown) => {
try {
const { sessionId, baseRef, options } = parseBranchDiffPayload(payload);
- return await readReviewBranchDiff(sessionId, baseRef, options);
+ return await withSessionReviewExecution(sessionId, () => readReviewBranchDiff(sessionId, baseRef, options));
} catch (err) {
- if (err instanceof Error && /\[INVALID_PARAMS\]/.test(err.message)) throw err;
- throwIpcError('INTERNAL', err instanceof Error ? err.message : String(err));
+ rethrowReviewIpcError(err);
}
});
ipcMain.handle(GIT_REVIEW_INVOKE.FILE_DIFF, async (_event, payload: unknown) => {
try {
const { sessionId, request } = parseFileDiffPayload(payload);
- return await readReviewFileDiff(sessionId, request);
+ return await withSessionReviewExecution(sessionId, () => readReviewFileDiff(sessionId, request));
} catch (err) {
- if (err instanceof Error && /\[(INVALID_PARAMS|PRECONDITION_FAILED)\]/.test(err.message)) throw err;
- throwIpcError('INTERNAL', err instanceof Error ? err.message : String(err));
+ rethrowReviewIpcError(err);
}
});
ipcMain.handle(GIT_REVIEW_INVOKE.IMAGE_PREVIEW, async (_event, payload: unknown) => {
try {
const { sessionId, request } = parseImagePreviewPayload(payload);
- return await readReviewImagePreview(sessionId, request);
+ return await withSessionReviewExecution(sessionId, () => readReviewImagePreview(sessionId, request));
} catch (err) {
- if (err instanceof Error && /\[(INVALID_PARAMS|PRECONDITION_FAILED)\]/.test(err.message)) throw err;
- throwIpcError('INTERNAL', err instanceof Error ? err.message : String(err));
+ rethrowReviewIpcError(err);
}
});
ipcMain.handle(GIT_REVIEW_INVOKE.MARKDOWN_PREVIEW, async (_event, payload: unknown) => {
try {
const { sessionId, request } = parseMarkdownPreviewPayload(payload);
- return await readReviewMarkdownPreview(sessionId, request);
+ return await withSessionReviewExecution(sessionId, () => readReviewMarkdownPreview(sessionId, request));
} catch (err) {
- if (err instanceof Error && /\[(INVALID_PARAMS|PRECONDITION_FAILED)\]/.test(err.message)) throw err;
- throwIpcError('INTERNAL', err instanceof Error ? err.message : String(err));
+ rethrowReviewIpcError(err);
}
});
ipcMain.handle(GIT_REVIEW_INVOKE.OPEN_FILE, async (_event, payload: unknown) => {
try {
const { sessionId, path: gitPath } = parseOpenFilePayload(payload);
- await openReviewFile(sessionId, gitPath);
+ await withSessionReviewExecution(sessionId, () => openReviewFile(sessionId, gitPath));
} catch (err) {
- if (err instanceof Error && /\[(INVALID_PARAMS|PRECONDITION_FAILED|INTERNAL)\]/.test(err.message)) throw err;
- throwIpcError('INTERNAL', err instanceof Error ? err.message : String(err));
+ rethrowReviewIpcError(err);
}
});
ipcMain.handle(GIT_REVIEW_INVOKE.STAGE_FILE, async (_event, payload: unknown) => {
const { sessionId, targets } = parseTargets(payload);
- return runReviewFileStageOperation(sessionId, 'stage', targets.slice(0, 1), writeDeps);
+ return withSessionReviewExecution(sessionId, () => runReviewFileStageOperation(sessionId, 'stage', targets.slice(0, 1), writeDeps));
});
ipcMain.handle(GIT_REVIEW_INVOKE.UNSTAGE_FILE, async (_event, payload: unknown) => {
const { sessionId, targets } = parseTargets(payload);
- return runReviewFileStageOperation(sessionId, 'unstage', targets.slice(0, 1), writeDeps);
+ return withSessionReviewExecution(sessionId, () => runReviewFileStageOperation(sessionId, 'unstage', targets.slice(0, 1), writeDeps));
});
ipcMain.handle(GIT_REVIEW_INVOKE.DISCARD_FILE, async (_event, payload: unknown) => {
const { sessionId, targets } = parseTargets(payload);
- return runReviewFileStageOperation(sessionId, 'discard', targets.slice(0, 1), writeDeps);
+ return withSessionReviewExecution(sessionId, () => runReviewFileStageOperation(sessionId, 'discard', targets.slice(0, 1), writeDeps));
});
ipcMain.handle(GIT_REVIEW_INVOKE.STAGE_ALL, async (_event, payload: unknown) => {
const { sessionId, targets } = parseTargets(payload);
- return runReviewFileStageOperation(sessionId, 'stage', targets, writeDeps);
+ return withSessionReviewExecution(sessionId, () => runReviewFileStageOperation(sessionId, 'stage', targets, writeDeps));
});
ipcMain.handle(GIT_REVIEW_INVOKE.UNSTAGE_ALL, async (_event, payload: unknown) => {
const { sessionId, targets } = parseTargets(payload);
- return runReviewFileStageOperation(sessionId, 'unstage', targets, writeDeps);
+ return withSessionReviewExecution(sessionId, () => runReviewFileStageOperation(sessionId, 'unstage', targets, writeDeps));
});
ipcMain.handle(GIT_REVIEW_INVOKE.DISCARD_ALL, async (_event, payload: unknown) => {
const { sessionId, targets } = parseTargets(payload);
- return runReviewFileStageOperation(sessionId, 'discard', targets, writeDeps);
+ return withSessionReviewExecution(sessionId, () => runReviewFileStageOperation(sessionId, 'discard', targets, writeDeps));
});
ipcMain.handle(GIT_REVIEW_INVOKE.STAGE_HUNK, async (_event, payload: unknown) => {
const { sessionId, diff, hunkIndex, options } = parseHunkPayload(payload);
- return runReviewHunkStageOperation(sessionId, 'stage', diff, hunkIndex, options, writeDeps);
+ return withSessionReviewExecution(sessionId, () => runReviewHunkStageOperation(sessionId, 'stage', diff, hunkIndex, options, writeDeps));
});
ipcMain.handle(GIT_REVIEW_INVOKE.UNSTAGE_HUNK, async (_event, payload: unknown) => {
const { sessionId, diff, hunkIndex, options } = parseHunkPayload(payload);
- return runReviewHunkStageOperation(sessionId, 'unstage', diff, hunkIndex, options, writeDeps);
+ return withSessionReviewExecution(sessionId, () => runReviewHunkStageOperation(sessionId, 'unstage', diff, hunkIndex, options, writeDeps));
});
ipcMain.handle(GIT_REVIEW_INVOKE.DISCARD_HUNK, async (_event, payload: unknown) => {
const { sessionId, diff, hunkIndex, options } = parseHunkPayload(payload);
- return runReviewHunkStageOperation(sessionId, 'discard', diff, hunkIndex, options, writeDeps);
+ return withSessionReviewExecution(sessionId, () => runReviewHunkStageOperation(sessionId, 'discard', diff, hunkIndex, options, writeDeps));
});
ipcMain.handle(GIT_REVIEW_INVOKE.COMMIT, async (_event, payload: unknown) => {
const { sessionId, message, includeUnstaged } = parseCommitPayload(payload);
- return runReviewCommit(sessionId, message, includeUnstaged, writeDeps);
+ return withSessionReviewExecution(sessionId, () => runReviewCommit(sessionId, message, includeUnstaged, writeDeps));
});
ipcMain.handle(GIT_REVIEW_INVOKE.PUSH, async (_event, payload: unknown) => {
const { sessionId, confirmForce } = parsePushPayload(payload);
- return runReviewPush(sessionId, confirmForce, writeDeps);
+ return withSessionReviewExecution(sessionId, () => runReviewPush(sessionId, confirmForce, writeDeps));
});
}
diff --git a/apps/desktop/src/main/git-review/markdownReader.ts b/apps/desktop/src/main/git-review/markdownReader.ts
index 50d11b45b0..107cca4d8c 100644
--- a/apps/desktop/src/main/git-review/markdownReader.ts
+++ b/apps/desktop/src/main/git-review/markdownReader.ts
@@ -55,7 +55,8 @@ function toFsPath(repoRoot: string, gitPath: string): string {
}
function baseDirForGitPath(repoRoot: string, gitPath: string): string {
- return path.dirname(toFsPath(repoRoot, gitPath));
+ const pathApi = path.posix.isAbsolute(repoRoot) ? path.posix : path;
+ return pathApi.dirname(toFsPath(repoRoot, gitPath));
}
function errorMessage(err: unknown): string {
diff --git a/apps/desktop/src/main/git-review/reviewFileRunner.ts b/apps/desktop/src/main/git-review/reviewFileRunner.ts
new file mode 100644
index 0000000000..2981743a54
--- /dev/null
+++ b/apps/desktop/src/main/git-review/reviewFileRunner.ts
@@ -0,0 +1,83 @@
+/**
+ * Request-scoped worktree file reads for git-review.
+ *
+ * Local review uses the controller filesystem. SSH review installs a backend
+ * backed by the controlled-side file service, so a remote POSIX path is never
+ * handed to the controller's node:fs APIs.
+ */
+
+import { AsyncLocalStorage } from 'node:async_hooks';
+import { promises as fs } from 'node:fs';
+
+import {
+ isPathInside,
+ repoRelativeFsPath,
+ resolveRepoContainedRealPath,
+} from './fsPathGuard.js';
+
+export interface ReviewWorktreePathStat {
+ size: number;
+ isSymlink: boolean;
+}
+
+export interface ReviewFileExecutionBackend {
+ lstat(repoRoot: string, gitPath: string): Promise<ReviewWorktreePathStat>;
+ readFile(repoRoot: string, gitPath: string, maxBytes: number): Promise<Buffer>;
+ readPrefix(repoRoot: string, gitPath: string, maxBytes: number): Promise<Buffer>;
+}
+
+const executionBackend = new AsyncLocalStorage<ReviewFileExecutionBackend>();
+
+export function withReviewFileExecutionBackend<T>(
+ backend: ReviewFileExecutionBackend,
+ task: () => Promise<T>,
+): Promise<T> {
+ return executionBackend.run(backend, task);
+}
+
+function lexicalWorktreePath(repoRoot: string, gitPath: string): string {
+ const candidate = repoRelativeFsPath(repoRoot, gitPath);
+ if (!isPathInside(repoRoot, candidate)) throw new Error('Review path is outside the repository');
+ return candidate;
+}
+
+export async function lstatReviewWorktreePath(
+ repoRoot: string,
+ gitPath: string,
+): Promise<ReviewWorktreePathStat> {
+ const backend = executionBackend.getStore();
+ if (backend) return backend.lstat(repoRoot, gitPath);
+ const stat = await fs.lstat(lexicalWorktreePath(repoRoot, gitPath));
+ return { size: stat.size, isSymlink: stat.isSymbolicLink() };
+}
+
+export async function readReviewWorktreeFile(
+ repoRoot: string,
+ gitPath: string,
+ maxBytes: number,
+): Promise<Buffer> {
+ const backend = executionBackend.getStore();
+ if (backend) return backend.readFile(repoRoot, gitPath, maxBytes);
+ const { targetReal } = await resolveRepoContainedRealPath(repoRoot, gitPath);
+ const stat = await fs.stat(targetReal);
+ if (stat.size > maxBytes) throw new Error('Review file exceeds the read limit');
+ return fs.readFile(targetReal);
+}
+
+export async function readReviewWorktreePrefix(
+ repoRoot: string,
+ gitPath: string,
+ maxBytes: number,
+): Promise<Buffer> {
+ const backend = executionBackend.getStore();
+ if (backend) return backend.readPrefix(repoRoot, gitPath, maxBytes);
+ const { targetReal } = await resolveRepoContainedRealPath(repoRoot, gitPath);
+ const handle = await fs.open(targetReal, 'r');
+ try {
+ const buffer = Buffer.alloc(maxBytes);
+ const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0);
+ return buffer.subarray(0, bytesRead);
+ } finally {
+ await handle.close();
+ }
+}
diff --git a/apps/desktop/src/main/git-review/scopeResolver.ts b/apps/desktop/src/main/git-review/scopeResolver.ts
index 5a0f067d63..bcdf97153d 100644
--- a/apps/desktop/src/main/git-review/scopeResolver.ts
+++ b/apps/desktop/src/main/git-review/scopeResolver.ts
@@ -1,11 +1,12 @@
/**
- * Resolve a session into the local git workdir used by the review panel.
+ * Resolve a session into the authoritative git workdir used by the review panel.
*
* Renderer never supplies cwd directly. The main process reads the session row
* and managed worktree store, then delegates telemetry/worktree fallback logic
* to sessionDirResolver.
*/
+import { AsyncLocalStorage } from 'node:async_hooks';
import path from 'node:path';
import { eq } from 'drizzle-orm';
@@ -14,7 +15,7 @@ import { resolveSessionGitDirLive } from '../git-context/sessionDirResolver.js';
import { getDbClient } from '../localDb/client/current.js';
import { sessions } from '../localDb/schema.js';
import * as worktreeStore from '../worktree/worktreeStore.js';
-import { runGit } from './gitRunner.js';
+import { GitRunError, runGit } from './gitRunner.js';
import type { ReviewScope } from './types.js';
export interface SessionReviewRow {
@@ -24,6 +25,15 @@ export interface SessionReviewRow {
remoteHostId: string | null;
}
+const sessionRowSnapshot = new AsyncLocalStorage<SessionReviewRow>();
+
+export function withSessionReviewRowSnapshot<T>(
+ row: SessionReviewRow,
+ task: () => Promise<T>,
+): Promise<T> {
+ return sessionRowSnapshot.run(row, task);
+}
+
export interface ScopeResolverDeps {
getSessionRow: (sessionId: string) => Promise<SessionReviewRow | null>;
getManagedWorktreePath: (sessionId: string) => string | null;
@@ -34,6 +44,8 @@ export interface ScopeResolverDeps {
export function defaultScopeResolverDeps(): ScopeResolverDeps {
return {
getSessionRow: async (sessionId) => {
+ const snapshot = sessionRowSnapshot.getStore();
+ if (snapshot?.id === sessionId) return snapshot;
const db = getDbClient().drizzle;
const rows = await db
.select({
@@ -77,13 +89,36 @@ function disabledScope(
};
}
-async function readRepoRoot(workdir: string, git: typeof runGit): Promise<string | null> {
+interface RepoRootProbe {
+ repoRoot: string | null;
+ disabledReason: 'non-git' | 'git-unavailable' | null;
+}
+
+function isGitUnavailable(err: unknown): boolean {
+ return err instanceof GitRunError && (
+ err.exitCode === 127 ||
+ (err.exitCode === null && (err.cause as NodeJS.ErrnoException | undefined)?.code === 'ENOENT')
+ );
+}
+
+async function readRepoRoot(workdir: string, git: typeof runGit, remote = false): Promise<RepoRootProbe> {
try {
const { stdout } = await git(['rev-parse', '--show-toplevel'], { cwd: workdir });
const root = stdout.trim();
- return root ? path.resolve(root) : null;
- } catch {
- return null;
+ if (!root) return { repoRoot: null, disabledReason: 'non-git' };
+ if (remote) {
+ return path.posix.isAbsolute(root)
+ ? { repoRoot: path.posix.normalize(root), disabledReason: null }
+ : { repoRoot: null, disabledReason: 'non-git' };
+ }
+ return { repoRoot: path.resolve(root), disabledReason: null };
+ } catch (err) {
+ // A remote Git probe can fail before Git runs (SSH channel closure,
+ // timeout, or remote service failure). Preserve that transport error so
+ // the caller can surface a retryable connection failure instead of
+ // misreporting the workspace as a non-Git directory.
+ if (remote && !(err instanceof GitRunError)) throw err;
+ return { repoRoot: null, disabledReason: isGitUnavailable(err) ? 'git-unavailable' : 'non-git' };
}
}
@@ -96,6 +131,21 @@ async function readHeadOid(workdir: string, git: typeof runGit): Promise<string
}
}
+async function readRemoteHeadState(
+ repoRoot: string,
+ git: typeof runGit,
+): Promise<{ branch: string | null; headOid: string | null; isDetached: boolean }> {
+ const headOid = await readHeadOid(repoRoot, git);
+ try {
+ const { stdout } = await git(['symbolic-ref', '--quiet', '--short', 'HEAD'], {
+ cwd: repoRoot,
+ });
+ return { branch: stdout.trim() || null, headOid, isDetached: false };
+ } catch {
+ return { branch: null, headOid, isDetached: headOid !== null };
+ }
+}
+
export async function resolveReviewScope(
sessionId: string,
deps: ScopeResolverDeps = defaultScopeResolverDeps(),
@@ -110,13 +160,58 @@ export async function resolveReviewScope(
}
if (row.remoteHostId) {
- return disabledScope(sessionId, {
- workingDir: row.workingDir,
+ const resolutionChain = [{ source: 'remote', path: row.workingDir, ok: Boolean(row.workingDir) }];
+ if (!row.workingDir) {
+ return disabledScope(sessionId, {
+ worktreePath: row.worktreePath,
+ disabledReason: 'no-workdir',
+ disabledMessage: 'This SSH session has no remote workdir',
+ resolutionChain,
+ });
+ }
+ if (!path.posix.isAbsolute(row.workingDir)) {
+ return disabledScope(sessionId, {
+ workingDir: row.workingDir,
+ worktreePath: row.worktreePath,
+ source: 'remote',
+ disabledReason: 'invalid-worktree',
+ disabledMessage: 'The SSH workspace path is invalid',
+ resolutionChain: [{ ...resolutionChain[0], ok: false, reason: 'not-absolute' }],
+ });
+ }
+ const workdir = path.posix.normalize(row.workingDir);
+ const probe = await readRepoRoot(workdir, deps.git, true);
+ if (!probe.repoRoot) {
+ const unavailable = probe.disabledReason === 'git-unavailable';
+ return disabledScope(sessionId, {
+ workdir,
+ workingDir: row.workingDir,
+ worktreePath: row.worktreePath,
+ source: 'remote',
+ disabledReason: unavailable ? 'git-unavailable' : 'non-git',
+ disabledMessage: unavailable
+ ? 'Git is not available on the SSH host'
+ : 'No git repository found in the SSH workspace',
+ resolutionChain: [{ ...resolutionChain[0], ok: false, reason: unavailable ? 'git-unavailable' : 'non-git' }],
+ });
+ }
+ const head = await readRemoteHeadState(probe.repoRoot, deps.git);
+ return {
+ sessionId,
+ workdir,
worktreePath: row.worktreePath,
- disabledReason: 'remote-session',
- disabledMessage: 'Git review for remote sessions is not available yet',
- resolutionChain: [{ source: 'remote', path: row.workingDir, ok: false, reason: row.remoteHostId }],
- });
+ workingDir: row.workingDir,
+ repoRoot: probe.repoRoot,
+ branch: head.branch,
+ headOid: head.headOid,
+ isDetached: head.isDetached,
+ isUnborn: head.headOid === null,
+ source: 'remote',
+ aheadBehind: { ahead: 0, behind: 0, upstream: null, stale: true },
+ disabledReason: null,
+ disabledMessage: null,
+ resolutionChain,
+ };
}
const managedWorktreePath = deps.getManagedWorktreePath(sessionId);
@@ -126,9 +221,8 @@ export async function resolveReviewScope(
fallbackWorktreePath,
fallbackWorkingDir: row.workingDir,
});
- // The review panel is intentionally local-only. Keep this guard explicit so
- // the shared session resolver can also represent SSH probes without widening
- // ReviewScope's local source contract.
+ // A remote row is handled above through the request-scoped SSH Git backend.
+ // A remote result here would lack the authoritative host id, so fail closed.
if (resolved.source === 'remote') {
return disabledScope(sessionId, {
workingDir: row.workingDir,
@@ -161,19 +255,22 @@ export async function resolveReviewScope(
});
}
- const repoRoot = await readRepoRoot(resolved.workdir, deps.git);
- if (!repoRoot) {
+ const probe = await readRepoRoot(resolved.workdir, deps.git);
+ if (!probe.repoRoot) {
return disabledScope(sessionId, {
workdir: path.resolve(resolved.workdir),
workingDir: row.workingDir,
worktreePath: fallbackWorktreePath,
source: resolved.source,
- disabledReason: 'non-git',
- disabledMessage: 'No git repository found for this session',
+ disabledReason: probe.disabledReason ?? 'non-git',
+ disabledMessage: probe.disabledReason === 'git-unavailable'
+ ? 'Git is not available on this computer'
+ : 'No git repository found for this session',
resolutionChain,
});
}
+ const repoRoot = probe.repoRoot;
const headOid = await readHeadOid(repoRoot, deps.git);
const isDetached = resolved.head?.kind === 'detached';
return {
diff --git a/apps/desktop/src/main/git-review/sshReviewBackend.ts b/apps/desktop/src/main/git-review/sshReviewBackend.ts
new file mode 100644
index 0000000000..8244f1907e
--- /dev/null
+++ b/apps/desktop/src/main/git-review/sshReviewBackend.ts
@@ -0,0 +1,556 @@
+/**
+ * SSH execution backend for the workspace review panel.
+ *
+ * The renderer continues to send only a session id and structured review
+ * requests. Main resolves the authoritative host/workdir from the session row,
+ * then runs a fixed, read-only Git wrapper on that host. Paths and Git args are
+ * base64-encoded positional data, never interpolated as shell syntax.
+ */
+
+import { AsyncLocalStorage } from 'node:async_hooks';
+import type { Stats } from 'node:fs';
+import path from 'node:path';
+
+import type { ExecOpts, ExecResult } from '@cindy/maker-remote-ssh';
+
+import { getRemoteFileBrowser } from '../file-browser/remote-deps.js';
+import { ensureRemoteHostReady, getRemoteSshPool } from '../remote-ssh/index.js';
+import {
+ GitRunError,
+ type GitExecutionBackend,
+ type GitRunBufferOptions,
+ type GitRunBufferResult,
+ type GitRunOptions,
+ type GitRunResult,
+ withGitExecutionBackend,
+} from './gitRunner.js';
+import { repoRelativeFsPath } from './fsPathGuard.js';
+import { ImagePreviewDataUrlCache, type ImagePreviewReaderDeps } from './imageReader.js';
+import type { MarkdownPreviewReaderDeps } from './markdownReader.js';
+import {
+ type ReviewFileExecutionBackend,
+ withReviewFileExecutionBackend,
+} from './reviewFileRunner.js';
+import {
+ defaultScopeResolverDeps,
+ type SessionReviewRow,
+ withSessionReviewRowSnapshot,
+} from './scopeResolver.js';
+import type { ReviewScope } from './types.js';
+
+const DEFAULT_REMOTE_STDOUT_BYTES = 64 * 1024 * 1024;
+const REMOTE_PREVIEW_CHUNK_BYTES = 1024 * 1024;
+const REMOTE_PREVIEW_MAX_BYTES = 5 * 1024 * 1024;
+
+const READ_ONLY_GIT_COMMANDS = new Set([
+ 'cat-file',
+ 'check-attr',
+ 'check-ref-format',
+ 'config',
+ 'diff',
+ 'diff-tree',
+ 'for-each-ref',
+ 'log',
+ 'ls-files',
+ 'merge-base',
+ 'rev-list',
+ 'rev-parse',
+ 'status',
+ 'symbolic-ref',
+]);
+
+const REMOTE_GIT_SCRIPT = [
+ 'set -o pipefail',
+ 'decode() { if printf %s "$1" | base64 --decode 2>/dev/null; then return 0; fi; printf %s "$1" | base64 -D; }',
+ 'cwd=$(decode "$1") || exit 125',
+ 'shift',
+ 'argv=()',
+ 'for item in "$@"; do argv+=("$(decode "$item")") || exit 125; done',
+ 'cd -- "$cwd" || exit 126',
+ 'export GIT_TERMINAL_PROMPT=0 GIT_ASKPASS= SSH_ASKPASS= GIT_PAGER=cat GIT_EXTERNAL_DIFF= GIT_OPTIONAL_LOCKS=0 LC_ALL=C',
+ 'git -c core.fsmonitor=false "${argv[@]}" | base64 | tr -d "\\r\\n"',
+].join('; ');
+
+export interface SshReviewHost {
+ exec(command: string, options?: ExecOpts): Promise<ExecResult>;
+}
+
+interface RemoteFileBrowser {
+ request(
+ hostId: string,
+ method: 'stat' | 'readFileChunk',
+ params: Record<string, unknown>,
+ ): Promise<unknown>;
+}
+
+export interface SshReviewBackendDeps {
+ getSessionRow(sessionId: string): Promise<SessionReviewRow | null>;
+ ensureHostReady(hostId: string): Promise<void>;
+ getHost(hostId: string): SshReviewHost;
+ getFileBrowser(): RemoteFileBrowser;
+}
+
+interface SshReviewContext {
+ hostId: string;
+ workdir: string;
+ host: SshReviewHost;
+ fileBrowser: RemoteFileBrowser;
+ imageCache: ImagePreviewDataUrlCache;
+}
+
+const sshReviewContext = new AsyncLocalStorage<SshReviewContext>();
+
+function defaultDeps(): SshReviewBackendDeps {
+ return {
+ getSessionRow: defaultScopeResolverDeps().getSessionRow,
+ ensureHostReady: ensureRemoteHostReady,
+ getHost: (hostId) => {
+ const host = getRemoteSshPool().get(hostId);
+ if (!host) throw new Error('SSH review host is not available');
+ return host;
+ },
+ getFileBrowser: () => getRemoteFileBrowser() as RemoteFileBrowser,
+ };
+}
+
+function encodeArg(value: string): string {
+ return Buffer.from(value, 'utf8').toString('base64');
+}
+
+function shellQuoteBase64(value: string): string {
+ // Base64 cannot contain a single quote, but keep the assertion close to the
+ // command boundary so future encoding changes fail closed.
+ if (!/^[A-Za-z0-9+/]*={0,2}$/.test(value)) throw new Error('invalid encoded SSH review argument');
+ return `'${value}'`;
+}
+
+export function buildRemoteGitCommand(cwd: string, args: readonly string[]): string {
+ const encoded = [cwd, ...args].map((value) => shellQuoteBase64(encodeArg(value)));
+ return `bash -c '${REMOTE_GIT_SCRIPT}' -- ${encoded.join(' ')}`;
+}
+
+export function assertReadOnlyRemoteGitArgs(
+ args: readonly string[],
+ opts: GitRunOptions = {},
+): void {
+ const command = args[0] ?? '';
+ if (!READ_ONLY_GIT_COMMANDS.has(command)) {
+ throw new GitRunError({
+ args,
+ cwd: opts.cwd,
+ exitCode: null,
+ stdout: '',
+ stderr: '',
+ message: 'SSH workspace review only supports read-only Git operations',
+ });
+ }
+ if (command === 'config' && args[1] !== '--get') {
+ throw new GitRunError({
+ args,
+ cwd: opts.cwd,
+ exitCode: null,
+ stdout: '',
+ stderr: '',
+ message: 'SSH workspace review only supports read-only Git config queries',
+ });
+ }
+ if (command === 'symbolic-ref' && args.some((arg) => arg === '--delete' || arg === '-d')) {
+ throw new GitRunError({
+ args,
+ cwd: opts.cwd,
+ exitCode: null,
+ stdout: '',
+ stderr: '',
+ message: 'SSH workspace review only supports read-only Git operations',
+ });
+ }
+ if (
+ args.some(
+ (arg) =>
+ arg === '--ext-diff' ||
+ arg === '--filters' ||
+ arg === '--textconv' ||
+ arg === '--output' ||
+ arg.startsWith('--output='),
+ )
+ ) {
+ throw new GitRunError({
+ args,
+ cwd: opts.cwd,
+ exitCode: null,
+ stdout: '',
+ stderr: '',
+ message: 'SSH workspace review rejected a Git option with external side effects',
+ });
+ }
+ if (opts.extraEnv && Object.keys(opts.extraEnv).length > 0) {
+ throw new GitRunError({
+ args,
+ cwd: opts.cwd,
+ exitCode: null,
+ stdout: '',
+ stderr: '',
+ message: 'SSH workspace review does not accept custom Git environment variables',
+ });
+ }
+}
+
+function hardenedRemoteGitArgs(args: readonly string[]): readonly string[] {
+ if (args[0] === 'diff' || args[0] === 'diff-tree' || args[0] === 'log') {
+ // Porcelain diff/log can enable repository-configured textconv or external
+ // diff helpers. Force both off on the controlled side even when callers do
+ // not request those flags explicitly.
+ return [args[0], '--no-ext-diff', '--no-textconv', ...args.slice(1)];
+ }
+ return args;
+}
+
+function escapeRegExp(value: string): string {
+ return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+}
+
+function remoteWorkspacePathPrefixes(cwd: string): string[] {
+ const normalized = path.posix.normalize(cwd);
+ const prefixes: string[] = [];
+ let candidate = normalized;
+ while (candidate !== '/') {
+ // Avoid redacting generic mount roots such as `/Users` or `/srv`, which
+ // could hide unrelated paths in an otherwise ordinary Git diagnostic.
+ if (candidate.split('/').filter(Boolean).length >= 2) prefixes.push(candidate);
+ const parent = path.posix.dirname(candidate);
+ if (parent === candidate) break;
+ candidate = parent;
+ }
+ return prefixes;
+}
+
+function sanitizeRemoteStderr(stderr: string, cwd: string): string {
+ const redacted = remoteWorkspacePathPrefixes(cwd).reduce(
+ (message, prefix) =>
+ message.replace(
+ new RegExp(`${escapeRegExp(prefix)}(?=$|[/\\s'\"\\)\\]\\},:;])`, 'g'),
+ '<workspace>',
+ ),
+ stderr,
+ );
+ return redacted.length <= 4_096 ? redacted : `${redacted.slice(0, 4_096)}…`;
+}
+
+function decodedOutput(
+ result: ExecResult,
+ maxStdoutBytes: number,
+ args: readonly string[],
+ cwd: string,
+): Buffer {
+ if (result.truncated) {
+ throw new GitRunError({
+ args,
+ cwd,
+ exitCode: result.exitCode,
+ stdout: '',
+ stderr: sanitizeRemoteStderr(result.stderr, cwd),
+ message: `Remote Git output exceeded the ${maxStdoutBytes}-byte review limit`,
+ });
+ }
+ const encoded = result.stdout.trim();
+ if (encoded && !/^[A-Za-z0-9+/]*={0,2}$/.test(encoded)) {
+ throw new GitRunError({
+ args,
+ cwd,
+ exitCode: result.exitCode,
+ stdout: '',
+ stderr: sanitizeRemoteStderr(result.stderr, cwd),
+ message: 'Remote Git returned an invalid binary response',
+ });
+ }
+ const stdout = Buffer.from(encoded, 'base64');
+ if (stdout.length > maxStdoutBytes) {
+ throw new GitRunError({
+ args,
+ cwd,
+ exitCode: result.exitCode,
+ stdout: stdout.subarray(0, maxStdoutBytes).toString('utf8'),
+ stderr: sanitizeRemoteStderr(result.stderr, cwd),
+ message: `Remote Git output exceeded the ${maxStdoutBytes}-byte review limit`,
+ });
+ }
+ return stdout;
+}
+
+function createGitBackend(host: SshReviewHost): GitExecutionBackend {
+ const execute = async (
+ args: readonly string[],
+ opts: GitRunOptions,
+ ): Promise<{ stdout: Buffer; stderr: string; exitCode: number }> => {
+ assertReadOnlyRemoteGitArgs(args, opts);
+ const cwd = opts.cwd;
+ if (!cwd || !path.posix.isAbsolute(cwd)) {
+ throw new GitRunError({
+ args,
+ cwd,
+ exitCode: null,
+ stdout: '',
+ stderr: '',
+ message: 'SSH workspace review requires an absolute remote working directory',
+ });
+ }
+ if (opts.signal?.aborted) {
+ throw new GitRunError({
+ args,
+ cwd,
+ exitCode: null,
+ stdout: '',
+ stderr: '',
+ message: 'Remote Git review request was cancelled',
+ });
+ }
+ const safeArgs = hardenedRemoteGitArgs(args);
+ const maxStdoutBytes = opts.maxStdoutBytes ?? DEFAULT_REMOTE_STDOUT_BYTES;
+ const encodedLimit = Math.ceil(maxStdoutBytes / 3) * 4 + 4_096;
+ const result = await host.exec(buildRemoteGitCommand(cwd, safeArgs), {
+ input: opts.stdin,
+ timeoutMs: opts.timeoutMs ?? 30_000,
+ maxOutputBytes: encodedLimit,
+ label: 'git-review-read',
+ });
+ if (opts.signal?.aborted) {
+ throw new GitRunError({
+ args,
+ cwd,
+ exitCode: result.exitCode,
+ stdout: '',
+ stderr: '',
+ message: 'Remote Git review request was cancelled',
+ });
+ }
+ const exitCode = result.exitCode ?? 128;
+ const stderr = sanitizeRemoteStderr(result.stderr, cwd);
+ const stdout = decodedOutput(result, maxStdoutBytes, args, cwd);
+ const allowed = new Set(opts.allowedExitCodes ?? [0]);
+ if (!allowed.has(exitCode)) {
+ throw new GitRunError({
+ args,
+ cwd,
+ exitCode,
+ stdout: stdout.toString('utf8'),
+ stderr,
+ message: `Remote Git command failed with exit code ${exitCode}${stderr.trim() ? `: ${stderr.trim()}` : ''}`,
+ });
+ }
+ return { stdout, stderr, exitCode };
+ };
+
+ return {
+ async run(args: readonly string[], opts: GitRunOptions = {}): Promise<GitRunResult> {
+ const result = await execute(args, opts);
+ return { ...result, stdout: result.stdout.toString('utf8') };
+ },
+ async runBuffer(
+ args: readonly string[],
+ opts: GitRunBufferOptions = {},
+ ): Promise<GitRunBufferResult> {
+ return execute(args, opts);
+ },
+ };
+}
+
+/** Run one complete review request against the session's authoritative backend. */
+export async function withSessionReviewExecution<T>(
+ sessionId: string,
+ task: () => Promise<T>,
+ deps: SshReviewBackendDeps = defaultDeps(),
+): Promise<T> {
+ const row = await deps.getSessionRow(sessionId);
+ if (!row) return task();
+ if (!row.remoteHostId || !row.workingDir) {
+ return withSessionReviewRowSnapshot(row, task);
+ }
+ try {
+ await deps.ensureHostReady(row.remoteHostId);
+ } catch (err) {
+ const message = err instanceof Error ? err.message : String(err);
+ const code = /\[(SSH_[A-Z_]+)\]/.exec(message)?.[1] ?? 'SSH_CONNECT_FAILED';
+ throw new Error(`[${code}] SSH workspace review could not connect to the remote host`);
+ }
+ const context: SshReviewContext = {
+ hostId: row.remoteHostId,
+ workdir: row.workingDir,
+ host: deps.getHost(row.remoteHostId),
+ fileBrowser: deps.getFileBrowser(),
+ imageCache: new ImagePreviewDataUrlCache(),
+ };
+ return withSessionReviewRowSnapshot(row, () =>
+ sshReviewContext.run(context, () =>
+ withGitExecutionBackend(createGitBackend(context.host), () =>
+ withReviewFileExecutionBackend(createFileBackend(context), task)),
+ ),
+ );
+}
+
+function currentRemoteContext(scope: ReviewScope): SshReviewContext {
+ const context = sshReviewContext.getStore();
+ if (
+ !context ||
+ scope.source !== 'remote' ||
+ scope.workingDir !== context.workdir
+ )
+ throw new Error('SSH review execution context is unavailable');
+ return context;
+}
+
+function remoteRelativePath(repoRoot: string, filePath: string): string {
+ const relative = path.posix.relative(repoRoot, filePath);
+ if (!relative || relative.startsWith('..') || path.posix.isAbsolute(relative)) {
+ throw new Error('Remote preview path is outside the repository');
+ }
+ return relative;
+}
+
+function statsLike(type: 'file' | 'directory', size: number, mtimeMs: number): Stats {
+ return {
+ size,
+ mtimeMs,
+ isFile: () => type === 'file',
+ isDirectory: () => type === 'directory',
+ // The remote file service follows symlinks only after enforcing realpath
+ // containment, so presenting the contained target as non-symlink is safe.
+ isSymbolicLink: () => false,
+ } as Stats;
+}
+
+type RemoteStatResult = { type: 'file' | 'directory'; size: number; mtimeMs: number };
+type RemoteChunkResult = { dataBase64: string; eof: boolean; size: number; mtimeMs: number };
+
+function decodeRemoteChunk(result: RemoteChunkResult, maxChunkBytes: number): Buffer {
+ if (!Number.isSafeInteger(maxChunkBytes) || maxChunkBytes < 0) {
+ throw new Error('Remote review requested an invalid file chunk length');
+ }
+ if (typeof result.dataBase64 !== 'string') {
+ throw new Error('Remote review file service returned an invalid chunk');
+ }
+ // Check the encoded response before decoding so a compromised or broken
+ // controlled side cannot force Main to allocate an arbitrarily large Buffer.
+ const maxEncodedChars = Math.ceil(maxChunkBytes / 3) * 4;
+ if (
+ result.dataBase64.length > maxEncodedChars ||
+ !/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(
+ result.dataBase64,
+ )
+ ) {
+ throw new Error('Remote review file service returned an oversized or invalid chunk');
+ }
+ const chunk = Buffer.from(result.dataBase64, 'base64');
+ if (chunk.length > maxChunkBytes) {
+ throw new Error('Remote review file service returned an oversized chunk');
+ }
+ return chunk;
+}
+
+async function readRemoteStat(
+ context: SshReviewContext,
+ repoRoot: string,
+ filePath: string,
+): Promise<Stats> {
+ const result = (await context.fileBrowser.request(context.hostId, 'stat', {
+ workdir: repoRoot,
+ relPath: remoteRelativePath(repoRoot, filePath),
+ })) as RemoteStatResult;
+ return statsLike(result.type, result.size, result.mtimeMs);
+}
+
+async function readRemoteFile(
+ context: SshReviewContext,
+ repoRoot: string,
+ filePath: string,
+ maxBytes: number,
+): Promise<Buffer> {
+ const relPath = remoteRelativePath(repoRoot, filePath);
+ const chunks: Buffer[] = [];
+ let offset = 0;
+ while (true) {
+ const requestedLength = Math.min(REMOTE_PREVIEW_CHUNK_BYTES, Math.max(0, maxBytes - offset));
+ const result = (await context.fileBrowser.request(context.hostId, 'readFileChunk', {
+ workdir: repoRoot,
+ relPath,
+ offset,
+ length: requestedLength,
+ })) as RemoteChunkResult;
+ if (result.size > maxBytes) throw new Error('Remote review file exceeds the read limit');
+ const chunk = decodeRemoteChunk(result, requestedLength);
+ if (offset + chunk.length > maxBytes) {
+ throw new Error('Remote review file exceeds the read limit');
+ }
+ chunks.push(chunk);
+ offset += chunk.length;
+ if (result.eof) break;
+ if (chunk.length === 0 || offset >= maxBytes) {
+ throw new Error('Remote review file changed while it was being read');
+ }
+ }
+ return Buffer.concat(chunks);
+}
+
+async function readRemotePrefix(
+ context: SshReviewContext,
+ repoRoot: string,
+ filePath: string,
+ maxBytes: number,
+): Promise<Buffer> {
+ const requestedLength = Math.min(maxBytes, REMOTE_PREVIEW_CHUNK_BYTES);
+ const result = (await context.fileBrowser.request(context.hostId, 'readFileChunk', {
+ workdir: repoRoot,
+ relPath: remoteRelativePath(repoRoot, filePath),
+ offset: 0,
+ length: requestedLength,
+ })) as RemoteChunkResult;
+ return decodeRemoteChunk(result, requestedLength);
+}
+
+function createFileBackend(context: SshReviewContext): ReviewFileExecutionBackend {
+ const absolutePath = (repoRoot: string, gitPath: string) =>
+ repoRelativeFsPath(repoRoot, gitPath);
+ return {
+ async lstat(repoRoot, gitPath) {
+ const stat = await readRemoteStat(context, repoRoot, absolutePath(repoRoot, gitPath));
+ return { size: stat.size, isSymlink: false };
+ },
+ readFile: (repoRoot, gitPath, maxBytes) =>
+ readRemoteFile(context, repoRoot, absolutePath(repoRoot, gitPath), maxBytes),
+ readPrefix: (repoRoot, gitPath, maxBytes) =>
+ readRemotePrefix(context, repoRoot, absolutePath(repoRoot, gitPath), maxBytes),
+ };
+}
+
+export type SshPreviewReaderDeps = Pick<
+ ImagePreviewReaderDeps & MarkdownPreviewReaderDeps,
+ 'lstat' | 'realpath' | 'stat' | 'readFile'
+> &
+ Pick<ImagePreviewReaderDeps, 'cache'>;
+
+/** Remote worktree reader used only for image/Markdown rich previews. */
+export function createSshPreviewReaderDeps(scope: ReviewScope): SshPreviewReaderDeps {
+ const context = currentRemoteContext(scope);
+ const repoRoot = scope.repoRoot;
+ if (!repoRoot) throw new Error('SSH review repository is unavailable');
+ return {
+ lstat: (filePath) => readRemoteStat(context, repoRoot, filePath),
+ // The daemon's stat/read calls perform canonical realpath containment on
+ // the controlled side. Identity here prevents local fs.realpath from ever
+ // touching a POSIX path that belongs to the SSH host.
+ realpath: async (filePath) => filePath,
+ stat: (filePath) => readRemoteStat(context, repoRoot, filePath),
+ readFile: (filePath) => readRemoteFile(
+ context,
+ repoRoot,
+ filePath,
+ REMOTE_PREVIEW_MAX_BYTES,
+ ),
+ cache: context.imageCache,
+ };
+}
+
+export const __sshReviewBackendTesting = {
+ createGitBackend,
+ hardenedRemoteGitArgs,
+ remoteRelativePath,
+};
diff --git a/apps/desktop/src/main/git-review/statusReader.ts b/apps/desktop/src/main/git-review/statusReader.ts
index 4d37a4c9eb..92dea919f1 100644
--- a/apps/desktop/src/main/git-review/statusReader.ts
+++ b/apps/desktop/src/main/git-review/statusReader.ts
@@ -201,6 +201,7 @@ export function parsePorcelainV2Status(stdout: string, baseScope: ReviewScope):
if (scope.isDetached) writeDisabledReasons.push('detached');
if (scope.isUnborn) writeDisabledReasons.push('unborn');
if (unmergedCount > 0) writeDisabledReasons.push('unmerged');
+ if (scope.source === 'remote') writeDisabledReasons.push('remote-ssh');
return {
scope,
@@ -275,7 +276,9 @@ export async function readStatus(scope: ReviewScope): Promise<ReviewStatus> {
maxStdoutBytes: STATUS_MAX_STDOUT_BYTES,
});
const status = parsePorcelainV2Status(stdout, scope);
- status.inProgress = await readInProgressState(scope.repoRoot);
+ // SSH review is read-only regardless of merge/rebase markers. Never probe a
+ // controlled-side path with the controller's local fs APIs.
+ status.inProgress = scope.source === 'remote' ? [] : await readInProgressState(scope.repoRoot);
if (status.inProgress.length > 0) status.writeDisabledReasons.push('in-progress');
return status;
}
diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator-artifact.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator-artifact.test.ts
index 08b634982d..98b7f6170e 100644
--- a/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator-artifact.test.ts
+++ b/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator-artifact.test.ts
@@ -310,17 +310,18 @@ describe('packaged iOS Simulator sidecar artifact verification', () => {
await symlink(targetPath, fixture.executablePath);
const commandRunner = createCommandRunner(fixture);
- await expect(
- verifyIOSSimulatorPackagedSidecarArtifact({
- resourcesPath: fixture.resourcesPath,
- version: VERSION,
- architecture: 'arm64',
- platform: 'darwin',
- commandRunner,
- }),
- ).rejects.toThrow('verification failed');
- expect(commandRunner).not.toHaveBeenCalled();
- });
+ await expect(
+ verifyIOSSimulatorPackagedSidecarArtifact({
+ resourcesPath: fixture.resourcesPath,
+ version: VERSION,
+ architecture: 'arm64',
+ platform: 'darwin',
+ commandRunner,
+ }),
+ ).rejects.toThrow('verification failed');
+ expect(commandRunner).not.toHaveBeenCalled();
+ },
+ );
it('fails a final pre-spawn check after the verified executable changes', async () => {
const fixture = await createFixture();
diff --git a/apps/desktop/src/renderer/__tests__/markdownImagePathEncoding.test.ts b/apps/desktop/src/renderer/__tests__/markdownImagePathEncoding.test.ts
index c9a5da0890..45d34a7f9c 100644
--- a/apps/desktop/src/renderer/__tests__/markdownImagePathEncoding.test.ts
+++ b/apps/desktop/src/renderer/__tests__/markdownImagePathEncoding.test.ts
@@ -99,7 +99,15 @@ describe('Markdown local image path encoding', () => {
});
it('blocks privileged local paths in untrusted Markdown previews', () => {
- expect(normalizeMarkdownImageSrc('/tmp/private.png', '/repo', false)).toBeUndefined();
+ for (const src of [
+ '/tmp/private.png',
+ 'C:\\Users\\alice\\private.png',
+ 'relative/private.png',
+ 'file:///tmp/private.png',
+ 'xdt-file://local/?path=%2Ftmp%2Fprivate.png',
+ ]) {
+ expect(normalizeMarkdownImageSrc(src, '/repo', false)).toBeUndefined();
+ }
expect(normalizeMarkdownImageSrc('https://example.com/public.png', '/repo', false)).toBe(
'https://example.com/public.png',
);
diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/review/ReviewTabBody.tsx b/apps/desktop/src/renderer/features/right-sidebar/plugins/review/ReviewTabBody.tsx
index 68f11c0f87..8e7035f84e 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/plugins/review/ReviewTabBody.tsx
+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/review/ReviewTabBody.tsx
@@ -163,6 +163,10 @@ export function shouldShowBranchBaseLabel(rowWidth: number, hasBranchBaseControl
return hasBranchBaseControl && Number.isFinite(rowWidth) && rowWidth >= REVIEW_BRANCH_BASE_LABEL_MIN_WIDTH_PX;
}
+export function shouldOfferReviewOpenFile(remoteHostId: string | null, deviceLinkDeviceId: string | null): boolean {
+ return remoteHostId === null && deviceLinkDeviceId === null;
+}
+
export type ReviewCommitActionDisabledReason =
| 'no-message'
| 'write-disabled'
@@ -775,8 +779,8 @@ function GitReviewTabBody({ state, ctx, source, setSource, selectedCommitOid, se
toast.error(t('rightSidebar.review.openFileFailed', { error: message }));
});
}, [sessionId, t]);
- // device-link 远程会话没有本机文件可打开:传 undefined 让「打开文件」入口整体不渲染。
- const openFileHandler = deviceLinkDeviceId ? undefined : openReviewFile;
+ // device-link 与 SSH 工作区都没有可由控制端 shell 打开的本机文件。
+ const openFileHandler = shouldOfferReviewOpenFile(ctx.remoteHostId, deviceLinkDeviceId) ? openReviewFile : undefined;
// 次级视图(提交 / 分支 / 单文件)错误串的 OVERSIZE 标记 → 可读文案;其余原样。
const localizeReviewError = useCallback(<T extends string | null>(message: T): T | string => {
if (message && isReviewRemoteOversizeError(message)) return t('rightSidebar.review.remote.oversizeDesc');
diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/review/__tests__/ReviewTabBody.helpers.test.ts b/apps/desktop/src/renderer/features/right-sidebar/plugins/review/__tests__/ReviewTabBody.helpers.test.ts
index ea29f3b91e..8b0c434fdf 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/plugins/review/__tests__/ReviewTabBody.helpers.test.ts
+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/review/__tests__/ReviewTabBody.helpers.test.ts
@@ -44,6 +44,7 @@ import {
reviewActionRevealClass,
scrollElementIntoContainerView,
shouldShowBranchBaseLabel,
+ shouldOfferReviewOpenFile,
shouldFallbackFromMissingSelectedCommit,
shouldHideWhitespaceOnlyDiff,
summaryEntryToPlaceholderDiff,
@@ -91,6 +92,12 @@ function branchDiffData(baseRef: string): ReviewBranchDiffData {
}
describe('ReviewTabBody Last turn actions', () => {
+ it('offers local file opening only when neither SSH nor device-link controls the task', () => {
+ expect(shouldOfferReviewOpenFile(null, null)).toBe(true);
+ expect(shouldOfferReviewOpenFile('ssh-host', null)).toBe(false);
+ expect(shouldOfferReviewOpenFile(null, 'device-id')).toBe(false);
+ });
+
it('keeps Last turn as a read-only source while other sources retain file actions', () => {
expect(actionForReviewDiff('unstaged', diff('unstaged', 'a.ts'))).toBe('stage');
expect(actionForReviewDiff('staged', diff('staged', 'b.ts'))).toBe('unstage');
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 2735d92b23..7387dafd3b 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -4826,7 +4826,8 @@
"in-progress": "git operation in progress",
"agent-running": "agent is running",
"disabled": "review unavailable",
- "remote-device": "remote device sessions are view-only"
+ "remote-device": "remote device sessions are view-only",
+ "remote-ssh": "SSH workspace review is view-only"
},
"remote": {
"deviceTooOldTitle": "Device version too old",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 572c9f02dd..36c1cb13a2 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -4824,7 +4824,8 @@
"in-progress": "git 操作が進行中です",
"agent-running": "エージェントが実行中です",
"disabled": "レビューを利用できません",
- "remote-device": "リモートデバイスのセッションは閲覧のみです"
+ "remote-device": "リモートデバイスのセッションは閲覧のみです",
+ "remote-ssh": "SSH ワークスペースのレビューは表示専用です"
},
"remote": {
"deviceTooOldTitle": "相手デバイスのバージョンが古すぎます",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index e8d0b719f6..18d721d438 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -4824,7 +4824,8 @@
"in-progress": "git 작업 진행 중",
"agent-running": "에이전트 실행 중",
"disabled": "리뷰를 사용할 수 없음",
- "remote-device": "원격 기기 세션은 보기 전용입니다"
+ "remote-device": "원격 기기 세션은 보기 전용입니다",
+ "remote-ssh": "SSH 워크스페이스 검토는 보기 전용입니다"
},
"remote": {
"deviceTooOldTitle": "상대 기기 버전이 너무 오래되었습니다",
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 68eb04443f..4dc0d50b34 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -4820,7 +4820,8 @@
"in-progress": "git 操作进行中",
"agent-running": "Agent 正在运行",
"disabled": "审查不可用",
- "remote-device": "远程设备任务仅支持查看"
+ "remote-device": "远程设备任务仅支持查看",
+ "remote-ssh": "SSH 工作区审查仅支持查看"
},
"remote": {
"deviceTooOldTitle": "对方设备版本过旧",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index c17f512159..09e6980589 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -4823,7 +4823,8 @@
"in-progress": "git 操作進行中",
"agent-running": "Agent 正在執行",
"disabled": "審查不可用",
- "remote-device": "遠端設備任務僅支援檢視"
+ "remote-device": "遠端設備任務僅支援檢視",
+ "remote-ssh": "SSH 工作區審查僅支援檢視"
},
"remote": {
"deviceTooOldTitle": "對方設備版本過舊",
diff --git a/apps/desktop/src/shared/gitReviewWire.ts b/apps/desktop/src/shared/gitReviewWire.ts
index f24ac5f612..207d244f93 100644
--- a/apps/desktop/src/shared/gitReviewWire.ts
+++ b/apps/desktop/src/shared/gitReviewWire.ts
@@ -33,7 +33,7 @@ export interface ReviewScope {
headOid: string | null;
isDetached: boolean;
isUnborn: boolean;
- source: 'telemetry' | 'worktree' | 'workingDir' | null;
+ source: 'telemetry' | 'worktree' | 'workingDir' | 'remote' | null;
aheadBehind: AheadBehind;
disabledReason: ReviewDisableReason | null;
disabledMessage: string | null;
diff --git a/packages/maker-cc-manager/__tests__/remote-claude-env.test.ts b/packages/maker-cc-manager/__tests__/remote-claude-env.test.ts
new file mode 100644
index 0000000000..2a5fb01a94
--- /dev/null
+++ b/packages/maker-cc-manager/__tests__/remote-claude-env.test.ts
@@ -0,0 +1,29 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ prepareRemoteClaudeEnv,
+ resolveRemoteClaudeConfigDir,
+} from '../src/remote-claude-env.js';
+
+describe('remote Claude environment', () => {
+ it('resolves the Cindy-managed config directory under the remote POSIX home', () => {
+ expect(resolveRemoteClaudeConfigDir('/Users/david')).toBe(
+ '/Users/david/.xdt-server/v1/claude-home',
+ );
+ });
+
+ it('replaces a Windows controller path without mutating the input env', () => {
+ const controllerEnv = {
+ ANTHROPIC_API_KEY: 'sk-gw',
+ CLAUDE_CONFIG_DIR: 'C:\\Users\\Admin\\AppData\\Roaming\\Cindy-dev2\\claude-home',
+ };
+
+ const remoteEnv = prepareRemoteClaudeEnv(controllerEnv, '/Users/david');
+
+ expect(remoteEnv).toEqual({
+ ANTHROPIC_API_KEY: 'sk-gw',
+ CLAUDE_CONFIG_DIR: '/Users/david/.xdt-server/v1/claude-home',
+ });
+ expect(controllerEnv.CLAUDE_CONFIG_DIR).toContain('C:\\Users\\Admin');
+ });
+});
diff --git a/packages/maker-cc-manager/__tests__/sdk-handlers.test.ts b/packages/maker-cc-manager/__tests__/sdk-handlers.test.ts
index 452e1e8755..f321aa1ef5 100644
--- a/packages/maker-cc-manager/__tests__/sdk-handlers.test.ts
+++ b/packages/maker-cc-manager/__tests__/sdk-handlers.test.ts
@@ -152,6 +152,23 @@ async function waitFor(
}
describe('sdk-handlers end-to-end', () => {
+ it('rewrites controller-local Claude config paths at the remote RPC boundary', async () => {
+ await ctx!.client.request('query/start', {
+ sessionId: 'remote-env',
+ cwd: '/Users/david/repo',
+ model: 'm',
+ env: {
+ ANTHROPIC_API_KEY: 'sk-gw',
+ CLAUDE_CONFIG_DIR: 'C:\\Users\\Admin\\AppData\\Roaming\\Cindy-dev2\\claude-home',
+ },
+ });
+
+ expect(latestFactoryOptions?.env).toEqual({
+ ANTHROPIC_API_KEY: 'sk-gw',
+ CLAUDE_CONFIG_DIR: expect.stringMatching(/\/.xdt-server\/v1\/claude-home$/),
+ });
+ });
+
it('query/start returns sessionId + emits init notification', async () => {
const result = await ctx!.client.request<{ sessionId: string }>('query/start', {
sessionId: 'sess-1',
diff --git a/packages/maker-cc-manager/src/bin/cc-mgr.ts b/packages/maker-cc-manager/src/bin/cc-mgr.ts
index b65ba39457..1872ff5e13 100644
--- a/packages/maker-cc-manager/src/bin/cc-mgr.ts
+++ b/packages/maker-cc-manager/src/bin/cc-mgr.ts
@@ -20,6 +20,7 @@ import path from 'node:path';
import { ManagerServer } from '../server.js';
import { SessionRegistry, type SdkQueryFactoryOptions, type SdkQueryLike } from '../session-registry.js';
import { wireSdkHandlers } from '../sdk-handlers.js';
+import { ensureRemoteClaudeConfigDir } from '../remote-claude-env.js';
import { CC_MGR_BUNDLE_VERSION, PROTOCOL_VERSION, SERVER_METHODS, type ApprovalRequestParams, type ApprovalRequestResult, type OAuthRefreshParams, type OAuthRefreshResult } from '../protocol.js';
const MANAGER_VERSION = CC_MGR_BUNDLE_VERSION;
@@ -294,6 +295,10 @@ async function runDaemon(socketPath: string): Promise<void> {
if (stripped.length > 0) {
console.error('[cc-mgr] stripped sensitive env keys at boot:', stripped.join(', '));
}
+ // Keep all Cindy-managed Claude state outside the user's repository and
+ // outside the host's global ~/.claude directory. query/start independently
+ // overwrites the per-session env with the same daemon-owned path.
+ process.env.CLAUDE_CONFIG_DIR = ensureRemoteClaudeConfigDir();
// Lazy import the SDK so --version doesn't pay the SDK load cost.
const sdkModule = await import('@anthropic-ai/claude-agent-sdk');
diff --git a/packages/maker-cc-manager/src/protocol.ts b/packages/maker-cc-manager/src/protocol.ts
index e0a0587d40..22ec3580d4 100644
--- a/packages/maker-cc-manager/src/protocol.ts
+++ b/packages/maker-cc-manager/src/protocol.ts
@@ -40,7 +40,7 @@ export const PROTOCOL_VERSION = 3 as const;
* 无关依赖变化而变。desktop 用这个(而非 bundle sha256)判断远端 daemon
* 是否需要 upgrade,避免无关的 pnpm install 触发全量远端重装。
*/
-export const CC_MGR_BUNDLE_VERSION = '0.0.7' as const;
+export const CC_MGR_BUNDLE_VERSION = '0.0.8' as const;
export type RpcId = number;
diff --git a/packages/maker-cc-manager/src/remote-claude-env.ts b/packages/maker-cc-manager/src/remote-claude-env.ts
new file mode 100644
index 0000000000..1a68d2f082
--- /dev/null
+++ b/packages/maker-cc-manager/src/remote-claude-env.ts
@@ -0,0 +1,42 @@
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+
+const REMOTE_CLAUDE_CONFIG_SEGMENTS = ['.xdt-server', 'v1', 'claude-home'] as const;
+
+/** Resolve the Cindy-managed Claude config directory on the remote POSIX host. */
+export function resolveRemoteClaudeConfigDir(remoteHomeDir: string = os.homedir()): string {
+ // cc-manager only runs on bash-capable SSH hosts. Normalize separators so
+ // Windows unit tests can inject a POSIX home without changing production
+ // path semantics.
+ const normalizedHome = remoteHomeDir.replaceAll('\\', '/').replace(/\/+$/, '');
+ if (!normalizedHome) {
+ throw new Error('remote home directory is empty');
+ }
+ return path.posix.join(normalizedHome, ...REMOTE_CLAUDE_CONFIG_SEGMENTS);
+}
+
+/**
+ * Override controller-supplied path values before they reach the remote SDK.
+ *
+ * CLAUDE_CONFIG_DIR is intentionally daemon-owned: a controller path is not
+ * meaningful on another machine and may otherwise become a repository-local
+ * relative directory on POSIX.
+ */
+export function prepareRemoteClaudeEnv(
+ env: Readonly<Record<string, string>>,
+ remoteHomeDir: string = os.homedir(),
+): Record<string, string> {
+ return {
+ ...env,
+ CLAUDE_CONFIG_DIR: resolveRemoteClaudeConfigDir(remoteHomeDir),
+ };
+}
+
+/** Create the daemon-owned directory with private permissions before SDK use. */
+export function ensureRemoteClaudeConfigDir(remoteHomeDir: string = os.homedir()): string {
+ const configDir = resolveRemoteClaudeConfigDir(remoteHomeDir);
+ fs.mkdirSync(configDir, { recursive: true, mode: 0o700 });
+ fs.chmodSync(configDir, 0o700);
+ return configDir;
+}
diff --git a/packages/maker-cc-manager/src/sdk-handlers.ts b/packages/maker-cc-manager/src/sdk-handlers.ts
index 11a815a9c5..11d9f97759 100644
--- a/packages/maker-cc-manager/src/sdk-handlers.ts
+++ b/packages/maker-cc-manager/src/sdk-handlers.ts
@@ -40,6 +40,7 @@ import {
type AttachedNotify,
} from './session-registry.js';
import { encodeMessage } from './codec.js';
+import { prepareRemoteClaudeEnv } from './remote-claude-env.js';
/**
@@ -132,7 +133,7 @@ export function wireSdkHandlers(server: ManagerServer, registry: SessionRegistry
sessionId: p.sessionId!,
cwd: p.cwd!,
model: p.model!,
- env: p.env as Record<string, string>,
+ env: prepareRemoteClaudeEnv(p.env as Record<string, string>),
...(p.mcpServers ? { mcpServers: p.mcpServers } : {}),
...(p.permissionMode ? { permissionMode: p.permissionMode } : {}),
...(p.systemPrompt !== undefined ? { systemPrompt: p.systemPrompt } : {}),
diff --git a/packages/maker-core/src/agents/claude-code/__tests__/env-builder.test.ts b/packages/maker-core/src/agents/claude-code/__tests__/env-builder.test.ts
index f15f240486..d3101168fd 100644
--- a/packages/maker-core/src/agents/claude-code/__tests__/env-builder.test.ts
+++ b/packages/maker-core/src/agents/claude-code/__tests__/env-builder.test.ts
@@ -104,6 +104,20 @@ describe('buildClaudeEnv', () => {
});
});
+ it('does not forward a controller-local CLAUDE_CONFIG_DIR to a remote host', async () => {
+ const env = await buildClaudeEnv(
+ createAuthAdapter({
+ ANTHROPIC_API_KEY: 'sk-gw',
+ CLAUDE_CONFIG_DIR: 'C:\\Users\\Admin\\AppData\\Roaming\\Cindy-dev2\\claude-home',
+ }),
+ {},
+ { credentialMode: 'gateway-key', mode: 'remote' },
+ );
+
+ expect(env.ANTHROPIC_API_KEY).toBe('sk-gw');
+ expect(env.CLAUDE_CONFIG_DIR).toBeUndefined();
+ });
+
it('lets behaviorFlags override an inherited CLAUDE_CODE_ATTRIBUTION_HEADER from the host env', async () => {
// local spawn 继承宿主 process.env:宿主 shell export 过 =0 时,flags 缺席压不住
// 继承值 —— 保留归因必须显式 '1'(desktop issue #758 的环境继承回归面)。
diff --git a/packages/maker-core/src/agents/claude-code/env-builder.ts b/packages/maker-core/src/agents/claude-code/env-builder.ts
index 99f0a2f5af..35ffdf15d3 100644
--- a/packages/maker-core/src/agents/claude-code/env-builder.ts
+++ b/packages/maker-core/src/agents/claude-code/env-builder.ts
@@ -307,7 +307,17 @@ export async function buildClaudeEnv(
const authOptions = options.credentialMode
? { credentialMode: options.credentialMode }
: undefined;
- Object.assign(env, await auth.getAuthEnv(authOptions));
+ const authEnv = { ...(await auth.getAuthEnv(authOptions)) };
+ if (mode === 'remote') {
+ // CLAUDE_CONFIG_DIR is a host-local path. Desktop dev sandboxes inject a
+ // Windows/macOS userData path through the auth adapter; forwarding that
+ // literal path to a different POSIX host makes Claude resolve it relative
+ // to the remote cwd and write configuration data into the repository.
+ // The remote cc-manager owns this path and replaces it with its isolated
+ // ~/.xdt-server/v1/claude-home directory at the RPC boundary.
+ delete authEnv.CLAUDE_CONFIG_DIR;
+ }
+ Object.assign(env, authEnv);
// Claude Code's documented child-agent model override.
//
diff --git a/packages/maker-core/src/agents/shared/review-read-scope.test.ts b/packages/maker-core/src/agents/shared/review-read-scope.test.ts
index d282849fe3..ee478cc170 100644
--- a/packages/maker-core/src/agents/shared/review-read-scope.test.ts
+++ b/packages/maker-core/src/agents/shared/review-read-scope.test.ts
@@ -118,17 +118,30 @@ describe("review read scope", () => {
it.skipIf(!canLink)("resolves symlinks before checking both scope and credential policy", async () => {
const root = await makeTempDir();
const workspace = path.join(root, "workspace");
- const outside = path.join(root, "outside.txt");
- const outsideLink = path.join(workspace, "outside-link.txt");
+ const outsideDir = path.join(root, "outside");
+ const outside = path.join(outsideDir, "outside.txt");
const keyDir = path.join(root, ".ssh");
const key = path.join(keyDir, "id_ed25519");
- const keyLink = path.join(workspace, "key.png");
await fs.mkdir(workspace);
+ await fs.mkdir(outsideDir);
await fs.mkdir(keyDir);
await fs.writeFile(outside, "outside");
await fs.writeFile(key, "private-key");
- await fs.symlink(outside, outsideLink);
- await fs.symlink(key, keyLink);
+ let outsideLink: string;
+ let keyLink: string;
+ if (process.platform === "win32") {
+ const outsideJunction = path.join(workspace, "outside-link");
+ const keyJunction = path.join(workspace, "key-link");
+ await fs.symlink(outsideDir, outsideJunction, "junction");
+ await fs.symlink(keyDir, keyJunction, "junction");
+ outsideLink = path.join(outsideJunction, path.basename(outside));
+ keyLink = path.join(keyJunction, path.basename(key));
+ } else {
+ outsideLink = path.join(workspace, "outside-link.txt");
+ keyLink = path.join(workspace, "key.png");
+ await fs.symlink(outside, outsideLink);
+ await fs.symlink(key, keyLink);
+ }
const grants = await buildReviewReadGrants(workspace, []);
expect(