Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(desktop): 支持远程任务 GitHub 上下文 (#1773)
Dash214f073a17d8
diff --git a/apps/desktop/src/main/__tests__/gitContextIpcSecurity.test.ts b/apps/desktop/src/main/__tests__/gitContextIpcSecurity.test.tsnew file mode 100644index 0000000000..7f1a46cebe--- /dev/null+++ b/apps/desktop/src/main/__tests__/gitContextIpcSecurity.test.ts@@ -0,0 +1,32 @@+import { readFileSync } from 'node:fs';++import { describe, expect, it } from 'vitest';++const ipcSource = readFileSync(new URL('../git-context/ipc.ts', import.meta.url), 'utf8');++describe('git-context remote IPC security contract', () => {+ it('guards local SSH probes before any session lookup or host connection', () => {+ const guard = ipcSource.indexOf('assertTrustedAppRendererEvent(event);');+ const remoteLookup = ipcSource.indexOf('if (deviceLinkInvoke || requestedRemoteHostId)');++ expect(ipcSource).toContain("if (requestedRemoteHostId !== null && !deviceLinkInvoke)");+ expect(guard).toBeGreaterThanOrEqual(0);+ expect(remoteLookup).toBeGreaterThan(guard);+ });++ it('keeps device-link invokes on their async-context authorization path', () => {+ expect(ipcSource).toContain('if (requestedRemoteHostId !== null && !deviceLinkInvoke)');+ expect(ipcSource).toContain('const deviceLinkInvoke = isDeviceLinkInvoke();');+ });++ it('fails closed when device-link PR refs lookup is unavailable', () => {+ const lookup = ipcSource.indexOf('const refs = await listPrRefs(remoteSessionId);');+ const clear = ipcSource.indexOf('return [];', lookup);+ const statusQuery = ipcSource.indexOf('return prStatusService!.getStatuses(parsed);');++ expect(ipcSource).toContain("log.warn('remote PR refs lookup failed (fail closed)'");+ expect(lookup).toBeGreaterThanOrEqual(0);+ expect(clear).toBeGreaterThan(lookup);+ expect(statusQuery).toBeGreaterThan(clear);+ });+});diff --git a/apps/desktop/src/main/__tests__/gitContextPrStatusService.test.ts b/apps/desktop/src/main/__tests__/gitContextPrStatusService.test.tsindex f00fe169c2..f050f31ac1 100644--- a/apps/desktop/src/main/__tests__/gitContextPrStatusService.test.ts+++ b/apps/desktop/src/main/__tests__/gitContextPrStatusService.test.ts@@ -7,6 +7,7 @@ import { describe, it, expect, vi } from 'vitest';import {PrStatusService,+ filterPrStatusQueriesForRefs,mapRemoteToStatus,type PrRemoteState,} from '../git-context/prStatusService';@@ -33,6 +34,20 @@ describe('mapRemoteToStatus', () => {});});+describe('filterPrStatusQueriesForRefs', () => {+ it('远程查询只保留目标 session 已记录的 PR,owner/repo 大小写不敏感', () => {+ expect(+ filterPrStatusQueriesForRefs(+ [+ { owner: 'MakeCindy', repo: 'Cindy', prNumber: 85 },+ { owner: 'private', repo: 'secret', prNumber: 1 },+ ],+ [{ owner: 'makecindy', repo: 'cindy', prNumber: 85 }],+ ),+ ).toEqual([{ owner: 'MakeCindy', repo: 'Cindy', prNumber: 85 }]);+ });+});+describe('PrStatusService', () => {it('正常查询返回状态与标题', async () => {const svc = new PrStatusService({diff --git a/apps/desktop/src/main/__tests__/gitContextRemoteSessionDirResolver.test.ts b/apps/desktop/src/main/__tests__/gitContextRemoteSessionDirResolver.test.tsnew file mode 100644index 0000000000..c4d1bd2f5a--- /dev/null+++ b/apps/desktop/src/main/__tests__/gitContextRemoteSessionDirResolver.test.ts@@ -0,0 +1,194 @@+import { describe, expect, it, vi } from 'vitest';++import {+ probeRemoteGitDir,+ resolveAuthoritativeSessionGitTarget,+ resolveReadyRemoteGitHost,+ resolveRemoteSessionGitDir,+ type RemoteGitHost,+} from '../git-context/remoteSessionDirResolver';++function makeHost(stdout: string, opts?: { status?: string; reject?: boolean }) {+ const exec = opts?.reject+ ? vi.fn().mockRejectedValue(new Error('disconnected'))+ : vi.fn().mockResolvedValue({ stdout });+ return {+ host: {+ getStatus: () => opts?.status ?? 'ready',+ exec,+ } satisfies RemoteGitHost,+ exec,+ };+}++describe('probeRemoteGitDir', () => {+ it('读取远端分支并限制 probe 的执行预算', async () => {+ const { host, exec } = makeHost('branch:feature/remote\n');++ await expect(probeRemoteGitDir(host, "/srv/O'Reilly/project")).resolves.toEqual({+ kind: 'branch',+ branch: 'feature/remote',+ shortSha: null,+ });+ expect(exec).toHaveBeenCalledWith(+ expect.stringContaining("git -C '/srv/O'\\''Reilly/project'"),+ expect.objectContaining({ timeoutMs: 5_000, label: 'git context probe', maxOutputBytes: 1_024 }),+ );+ });++ it('读取 detached HEAD', async () => {+ const { host } = makeHost('detached:deadbeef\n');+ await expect(probeRemoteGitDir(host, '/srv/project')).resolves.toEqual({+ kind: 'detached',+ branch: null,+ shortSha: 'deadbeef',+ });+ });++ it('远端未连接或执行失败时降级为空', async () => {+ await expect(probeRemoteGitDir(makeHost('', { status: 'disconnected' }).host, '/repo')).resolves.toBeNull();+ await expect(probeRemoteGitDir(makeHost('', { reject: true }).host, '/repo')).resolves.toBeNull();+ });+});++describe('resolveReadyRemoteGitHost', () => {+ it('冷启动时先 hydrate/connect,再返回 ready host', async () => {+ const { host } = makeHost('branch:main\n');+ const ensureReady = vi.fn().mockResolvedValue(undefined);+ const getHost = vi.fn().mockReturnValue(host);++ await expect(resolveReadyRemoteGitHost('ssh-1', { ensureReady, getHost })).resolves.toBe(host);+ expect(ensureReady).toHaveBeenCalledWith('ssh-1');+ expect(getHost).toHaveBeenCalledWith('ssh-1');+ });++ it('连接失败时保持 Git context 静默降级为空', async () => {+ const ensureReady = vi.fn().mockRejectedValue(new Error('auth failed'));+ const getHost = vi.fn();++ await expect(resolveReadyRemoteGitHost('ssh-1', { ensureReady, getHost })).resolves.toBeNull();+ expect(getHost).not.toHaveBeenCalled();+ });++ it('ensure 成功但 host 仍未 ready 时不执行 probe', async () => {+ const { host } = makeHost('', { status: 'reconnecting' });++ await expect(+ resolveReadyRemoteGitHost('ssh-1', {+ ensureReady: vi.fn().mockResolvedValue(undefined),+ getHost: vi.fn().mockReturnValue(host),+ }),+ ).resolves.toBeNull();+ });+});++describe('resolveRemoteSessionGitDir', () => {+ it('按 worktree → workingDir 顺序尝试远端路径,并保留 workingDir 低可信来源', async () => {+ const exec = vi+ .fn()+ .mockResolvedValueOnce({ stdout: '' })+ .mockResolvedValueOnce({ stdout: 'branch:main\n' });+ const host: RemoteGitHost = { getStatus: () => 'ready', exec };++ await expect(+ resolveRemoteSessionGitDir({+ telemetryPath: null,+ fallbackWorktreePath: '/remote/worktree',+ fallbackWorkingDir: '/remote/repo',+ host,+ }),+ ).resolves.toEqual({+ workdir: '/remote/repo',+ head: { kind: 'branch', branch: 'main', shortSha: null },+ source: 'workingDir',+ });+ });++ it('命中远端 worktree 时保留 remote 可信来源', async () => {+ const exec = vi.fn().mockResolvedValue({ stdout: 'branch:feature/remote\n' });+ const host: RemoteGitHost = { getStatus: () => 'ready', exec };++ await expect(+ resolveRemoteSessionGitDir({+ telemetryPath: null,+ fallbackWorktreePath: '/remote/worktree',+ fallbackWorkingDir: '/remote/repo',+ host,+ }),+ ).resolves.toEqual({+ workdir: '/remote/worktree',+ head: { kind: 'branch', branch: 'feature/remote', shortSha: null },+ source: 'remote',+ });+ });++ it('优先尝试最新 telemetry 路径', async () => {+ const exec = vi.fn().mockResolvedValue({ stdout: 'branch:telemetry\n' });+ const host: RemoteGitHost = { getStatus: () => 'ready', exec };++ await expect(+ resolveRemoteSessionGitDir({+ telemetryPath: '/remote/telemetry',+ fallbackWorktreePath: '/remote/worktree',+ fallbackWorkingDir: '/remote/repo',+ host,+ }),+ ).resolves.toMatchObject({ workdir: '/remote/telemetry', source: 'remote' });+ expect(exec).toHaveBeenCalledTimes(1);+ });+});++describe('resolveAuthoritativeSessionGitTarget', () => {+ it('直连 SSH 只使用 main 记录的 host 与远端路径', () => {+ expect(+ resolveAuthoritativeSessionGitTarget({+ stored: {+ workingDir: '/stored/repo',+ worktreePath: '/stored/worktree',+ remoteHostId: 'ssh-1',+ },+ requestedRemoteHostId: 'ssh-1',+ isDeviceLink: false,+ liveLocalWorktreePath: '/local/ignored',+ }),+ ).toEqual({+ workingDir: '/stored/repo',+ worktreePath: '/stored/worktree',+ remoteHostId: 'ssh-1',+ });+ });++ it('直连 renderer 不能把 session 切到另一台 SSH host', () => {+ expect(+ resolveAuthoritativeSessionGitTarget({+ stored: {+ workingDir: '/stored/repo',+ worktreePath: '/stored/worktree',+ remoteHostId: 'ssh-1',+ },+ requestedRemoteHostId: 'ssh-forged',+ isDeviceLink: false,+ liveLocalWorktreePath: null,+ }),+ ).toBeNull();+ });++ it('device-link 忽略控制端投影并按被控端 session 选择 live 本地 worktree', () => {+ expect(+ resolveAuthoritativeSessionGitTarget({+ stored: {+ workingDir: '/controlled/repo',+ worktreePath: '/stale/deleted-worktree',+ remoteHostId: null,+ },+ requestedRemoteHostId: 'ssh-forged',+ isDeviceLink: true,+ liveLocalWorktreePath: '/controlled/live-worktree',+ }),+ ).toEqual({+ workingDir: '/controlled/repo',+ worktreePath: '/controlled/live-worktree',+ remoteHostId: null,+ });+ });+});diff --git a/apps/desktop/src/main/__tests__/gitContextSessionDirResolver.test.ts b/apps/desktop/src/main/__tests__/gitContextSessionDirResolver.test.tsindex 5d7968f1fc..da33dbd705 100644--- a/apps/desktop/src/main/__tests__/gitContextSessionDirResolver.test.ts+++ b/apps/desktop/src/main/__tests__/gitContextSessionDirResolver.test.ts@@ -62,6 +62,15 @@ describe('extractDirCandidate', () => {expect(extractDirCandidate('not json')).toBeNull();expect(extractDirCandidate('{"toolName":"exec"}')).toBeNull();});++ it('远端 POSIX 遥测不按 Windows 控制端转换盘符路径', () => {+ expect(+ extractDirCandidate(toolUse('exec', { command: 'pwd', cwd: '/e/remote/repo' }), 'linux'),+ ).toBe('/e/remote/repo');+ expect(+ extractDirCandidate(toolUse('Edit', { file_path: '/e/remote/repo/src/a.ts' }), 'linux'),+ ).toBe('/e/remote/repo/src');+ });});describe('posixDriveToWin32', () => {diff --git a/apps/desktop/src/main/git-context/ipc.ts b/apps/desktop/src/main/git-context/ipc.tsindex 172b24dfc6..11e308b63c 100644--- a/apps/desktop/src/main/git-context/ipc.ts+++ b/apps/desktop/src/main/git-context/ipc.ts@@ -3,7 +3,7 @@** Channels(invoke):* git-context:get (workdir) → GitContextSnapshot- * git-context:get-for-session ({sessionId,workingDir,worktreePath}) → SessionGitDirResult+ * git-context:get-for-session ({sessionId,workingDir,worktreePath,remoteHostId}) → SessionGitDirResult* git-context:watch (workdir) → void(开始监听 HEAD,refcount)* git-context:unwatch (workdir) → void* git-context:pr-refs:list (sessionId) → SessionPrRef[]@@ -20,14 +20,28 @@import { BrowserWindow, ipcMain } from 'electron';import { GithubClient } from '@cindy/github-client';+import { eq } from 'drizzle-orm';import { createLogger } from '../logger.js';-import { getCurrentDbClientUserId } from '../localDb/client/current';+import { getCurrentDbClientUserId, getDbClient } from '../localDb/client/current';+import { sessions } from '../localDb/schema.js';import { outboundFetch } from '../maker-host/outbound-fetch.js';-import { requireString, throwIpcError } from '../utils/ipcValidate';+import { optionalNullableString, requireString, throwIpcError } from '../utils/ipcValidate';import { getSharedGhCliTokenSource } from './ghCliTokenSource.js';import { GitContextService } from './GitContextService.js';-import { resolveSessionGitDirLive } from './sessionDirResolver.js';+import {+ getSessionGitTelemetryCandidateLive,+ resolveSessionGitDirLive,+} from './sessionDirResolver.js';+import {+ resolveAuthoritativeSessionGitTarget,+ resolveReadyRemoteGitHost,+ resolveRemoteSessionGitDir,+} from './remoteSessionDirResolver.js';+import { ensureRemoteHostReady, getRemoteSshPool } from '../remote-ssh/index.js';+import { isDeviceLinkInvoke } from '../device-link/invoke-context.js';+import { assertTrustedAppRendererEvent } from '../security/trustedAppRenderer.js';+import * as worktreeStore from '../worktree/worktreeStore.js';import {ensurePrRefsBackfill,listAllPrRefs,@@ -35,6 +49,7 @@ import {setPrRefsChangedListener,} from './prRefsStore.js';import {+ filterPrStatusQueriesForRefs,PrStatusService,type PrStatusQuery,type PrRemoteState,@@ -143,17 +158,83 @@ export function registerGitContextIpc(): void {// 按 session 解析「对话真实工作目录」+ 其 HEAD + 来源:从 agent tool-call 遥测// 推断(Codex cwd / cc 编辑路径),拿不到才回退 worktree / working_dir。// renderer 用返回的 workdir 去 watch,用 source 决定分支信任度。- ipcMain.handle(GIT_CONTEXT_INVOKE.GET_FOR_SESSION, async (_e, payload: unknown) => {+ ipcMain.handle(GIT_CONTEXT_INVOKE.GET_FOR_SESSION, async (event, payload: unknown) => {const obj = payload as {sessionId?: unknown;workingDir?: unknown;worktreePath?: unknown;+ remoteHostId?: unknown;};const sessionId = requireString(obj?.sessionId, 'sessionId');- const fallbackWorkingDir =+ let fallbackWorkingDir =typeof obj?.workingDir === 'string' && obj.workingDir !== '' ? obj.workingDir : null;- const fallbackWorktreePath =+ let fallbackWorktreePath =typeof obj?.worktreePath === 'string' && obj.worktreePath !== '' ? obj.worktreePath : null;+ const requestedRemoteHostId = optionalNullableString(obj?.remoteHostId) ?? null;+ let remoteHostId = requestedRemoteHostId;++ // Any remote SSH exec must be anchored to main-owned session state. The+ // renderer cannot choose an arbitrary registered host/path, and a+ // device-link controller cannot override the controlled device's paths or+ // nested SSH host with a stale/forged projection.+ const deviceLinkInvoke = isDeviceLinkInvoke();+ // The SSH branch can hydrate a persisted host and execute a command on it;+ // only Cindy's own top-level renderer may start that privileged path.+ // device-link invokes are authorized by their existing async context.+ if (requestedRemoteHostId !== null && !deviceLinkInvoke) {+ assertTrustedAppRendererEvent(event);+ }+ if (deviceLinkInvoke || requestedRemoteHostId) {+ try {+ const db = getDbClient().drizzle;+ const [row] = await db+ .select({+ workingDir: sessions.workingDir,+ worktreePath: sessions.worktreePath,+ remoteHostId: sessions.remoteHostId,+ })+ .from(sessions)+ .where(eq(sessions.id, sessionId))+ .limit(1);+ if (!row) return { workdir: null, head: null, source: null };+ const target = resolveAuthoritativeSessionGitTarget({+ stored: row,+ requestedRemoteHostId,+ isDeviceLink: deviceLinkInvoke,+ liveLocalWorktreePath: worktreeStore.get(sessionId)?.path ?? null,+ });+ if (!target) return { workdir: null, head: null, source: null };+ fallbackWorkingDir = target.workingDir;+ fallbackWorktreePath = target.worktreePath;+ remoteHostId = target.remoteHostId;+ } catch (err) {+ log.warn('remote git context session lookup failed', {+ sessionId,+ err: err instanceof Error ? err.message : String(err),+ });+ return { workdir: null, head: null, source: null };+ }+ }+ if (remoteHostId) {+ const host = await resolveReadyRemoteGitHost(remoteHostId, {+ ensureReady: ensureRemoteHostReady,+ getHost: (hostId) => getRemoteSshPool().get(hostId),+ });+ if (!host) return { workdir: null, head: null, source: null };+ const telemetryPath = await getSessionGitTelemetryCandidateLive(+ sessionId,+ // SSH sessions run through the bash-based remote runtime; a+ // device-link session without nested SSH probes its controlled+ // Desktop filesystem and must retain that process platform.+ 'linux',+ );+ return resolveRemoteSessionGitDir({+ telemetryPath,+ fallbackWorktreePath,+ fallbackWorkingDir,+ host,+ });+ }return resolveSessionGitDirLive({ sessionId, fallbackWorktreePath, fallbackWorkingDir });});@@ -186,10 +267,17 @@ export function registerGitContextIpc(): void {});ipcMain.handle(GIT_CONTEXT_INVOKE.PR_STATUS, async (_e, queries: unknown) => {- if (!Array.isArray(queries)) {+ let rawQueries: unknown = queries;+ let remoteSessionId: string | null = null;+ if (isDeviceLinkInvoke()) {+ const obj = queries as { sessionId?: unknown; queries?: unknown };+ remoteSessionId = requireString(obj?.sessionId, 'sessionId');+ rawQueries = obj?.queries;+ }+ if (!Array.isArray(rawQueries)) {throwIpcError('INVALID_PARAMS', 'queries 必须是数组');}- const parsed: PrStatusQuery[] = (queries as unknown[]).map((q) => {+ let parsed: PrStatusQuery[] = (rawQueries as unknown[]).map((q) => {const obj = q as { owner?: unknown; repo?: unknown; prNumber?: unknown };const owner = requireString(obj?.owner, 'owner');const repo = requireString(obj?.repo, 'repo');@@ -199,6 +287,25 @@ export function registerGitContextIpc(): void {}return { owner, repo, prNumber };});+ if (remoteSessionId) {+ // A remote controller may only ask for statuses of PRs already extracted+ // from that session's messages. This blocks a bare status-channel call+ // from querying an unrelated private repository with the controlled+ // device's gh token; intentionally mentioning a PR in the task remains+ // part of the existing remote-control product behavior.+ try {+ const refs = await listPrRefs(remoteSessionId);+ parsed = filterPrStatusQueriesForRefs(parsed, refs);+ } catch (err) {+ // DB failures must not turn into an unfiltered token-bearing request;+ // fail closed and let the remote renderer retry on its next refresh.+ log.warn('remote PR refs lookup failed (fail closed)', {+ sessionId: remoteSessionId,+ err: err instanceof Error ? err.message : String(err),+ });+ return [];+ }+ }return prStatusService!.getStatuses(parsed);});}diff --git a/apps/desktop/src/main/git-context/prStatusService.ts b/apps/desktop/src/main/git-context/prStatusService.tsindex d647654c38..1afefb986d 100644--- a/apps/desktop/src/main/git-context/prStatusService.ts+++ b/apps/desktop/src/main/git-context/prStatusService.ts@@ -26,6 +26,19 @@ export interface PrStatusQuery {prNumber: number;}+/** Restrict remote status reads to PRs already attached to the target session. */+export function filterPrStatusQueriesForRefs(+ queries: readonly PrStatusQuery[],+ refs: readonly PrStatusQuery[],+): PrStatusQuery[] {+ const allowed = new Set(+ refs.map((ref) => `${ref.owner.toLowerCase()}/${ref.repo.toLowerCase()}#${ref.prNumber}`),+ );+ return queries.filter((query) =>+ allowed.has(`${query.owner.toLowerCase()}/${query.repo.toLowerCase()}#${query.prNumber}`),+ );+}+export type PrStatusResult =| {ok: true;diff --git a/apps/desktop/src/main/git-context/remoteSessionDirResolver.ts b/apps/desktop/src/main/git-context/remoteSessionDirResolver.tsnew file mode 100644index 0000000000..ec8a74eafd--- /dev/null+++ b/apps/desktop/src/main/git-context/remoteSessionDirResolver.ts@@ -0,0 +1,146 @@+/**+ * Resolve the git context for an SSH-backed session.+ *+ * SSH session paths belong to the remote host, so the local HEAD reader is+ * deliberately not used here. Probe the newest telemetry candidate first,+ * then the remote worktree and session working directory through the existing+ * SSH connection, returning the same small projection consumed by the renderer.+ */++import type { GitHeadInfo } from './headReader.js';+import type { SessionGitDirResult } from './sessionDirResolver.js';++export interface RemoteGitHost {+ getStatus(): string;+ exec(+ command: string,+ options: {+ timeoutMs: number;+ label: string;+ maxOutputBytes: number;+ },+ ): Promise<{ stdout: string }>;+}++/**+ * Rehydrate and connect an SSH host before a remote Git probe.+ *+ * Git context is a best-effort header query: a missing host, expired+ * credentials, or a transient network failure should keep the task usable and+ * return the same empty projection as any other unavailable remote path.+ */+export async function resolveReadyRemoteGitHost(+ remoteHostId: string,+ deps: {+ ensureReady: (hostId: string) => Promise<void>;+ getHost: (hostId: string) => RemoteGitHost | null | undefined;+ },+): Promise<RemoteGitHost | null> {+ try {+ await deps.ensureReady(remoteHostId);+ } catch {+ return null;+ }+ const host = deps.getHost(remoteHostId);+ return host?.getStatus() === 'ready' ? host : null;+}++export interface StoredSessionGitTarget {+ workingDir: string | null;+ worktreePath: string | null;+ remoteHostId: string | null;+}++/**+ * Derive the probe target from main-owned session state.+ *+ * Direct renderer IPC must match the SSH host recorded for the session; a+ * device-link caller is allowed to send stale projection data, but it never+ * gets to override the controlled device's paths or nested SSH host.+ */+export function resolveAuthoritativeSessionGitTarget(input: {+ stored: StoredSessionGitTarget;+ requestedRemoteHostId: string | null;+ isDeviceLink: boolean;+ liveLocalWorktreePath: string | null;+}): StoredSessionGitTarget | null {+ const storedRemoteHostId = input.stored.remoteHostId ?? null;+ if (!input.isDeviceLink && input.requestedRemoteHostId !== storedRemoteHostId) return null;++ return {+ workingDir: input.stored.workingDir ?? null,+ remoteHostId: storedRemoteHostId,+ worktreePath: storedRemoteHostId+ ? input.stored.worktreePath ?? null+ : input.liveLocalWorktreePath,+ };+}++function shellQuote(value: string): string {+ return `'${value.replace(/'/g, `'\\''`)}'`;+}++/**+ * Read a branch or detached HEAD from a remote working directory.+ * The explicit prefix avoids confusing a hexadecimal branch name with a SHA.+ */+export async function probeRemoteGitDir(+ host: RemoteGitHost,+ workdir: string,+): Promise<GitHeadInfo | null> {+ if (!workdir.trim() || host.getStatus() !== 'ready') return null;++ const quoted = shellQuote(workdir);+ const command =+ `if branch=$(git -C ${quoted} symbolic-ref --short HEAD 2>/dev/null); then ` ++ `printf 'branch:%s\\n' "$branch"; ` ++ `elif sha=$(git -C ${quoted} rev-parse --short=8 HEAD 2>/dev/null); then ` ++ `printf 'detached:%s\\n' "$sha"; fi`;++ try {+ const result = await host.exec(command, {+ timeoutMs: 5_000,+ label: 'git context probe',+ maxOutputBytes: 1_024,+ });+ const line = result.stdout.trim().split('\n', 1)[0] ?? '';+ if (line.startsWith('branch:')) {+ const branch = line.slice('branch:'.length).trim();+ return branch ? { kind: 'branch', branch, shortSha: null } : null;+ }+ if (line.startsWith('detached:')) {+ const shortSha = line.slice('detached:'.length).trim();+ return shortSha ? { kind: 'detached', branch: null, shortSha } : null;+ }+ return null;+ } catch {+ // A disconnected host, a missing directory, and a non-git directory all+ // mean the same thing to the badge: no branch context is available yet.+ return null;+ }+}++export async function resolveRemoteSessionGitDir(input: {+ telemetryPath?: string | null;+ fallbackWorktreePath: string | null;+ fallbackWorkingDir: string | null;+ host: RemoteGitHost;+}): Promise<SessionGitDirResult> {+ const candidates = [+ { workdir: input.telemetryPath, source: 'remote' as const },+ { workdir: input.fallbackWorktreePath, source: 'remote' as const },+ // session.workingDir is a shared-checkout snapshot, even when the probe+ // itself runs on the SSH host; keep it low-trust so PR refs can win.+ { workdir: input.fallbackWorkingDir, source: 'workingDir' as const },+ ].filter(+ (candidate): candidate is { workdir: string; source: 'remote' | 'workingDir' } =>+ typeof candidate.workdir === 'string' && candidate.workdir.trim().length > 0,+ );++ for (const { workdir, source } of candidates) {+ const head = await probeRemoteGitDir(input.host, workdir);+ if (head) return { workdir, head, source };+ }++ return { workdir: null, head: null, source: null };+}diff --git a/apps/desktop/src/main/git-context/sessionDirResolver.ts b/apps/desktop/src/main/git-context/sessionDirResolver.tsindex 943b718f4f..6771d44fbf 100644--- a/apps/desktop/src/main/git-context/sessionDirResolver.ts+++ b/apps/desktop/src/main/git-context/sessionDirResolver.ts@@ -61,7 +61,7 @@ const SCAN_LIMIT = 200;export interface SessionGitDirResult {workdir: string | null;head: GitHeadInfo | null;- source: 'telemetry' | 'worktree' | 'workingDir' | null;+ source: 'telemetry' | 'worktree' | 'workingDir' | 'remote' | null;}/**@@ -71,7 +71,10 @@ export interface SessionGitDirResult {* - 其它(Read / 普通 Bash / 脏 JSON / 相对路径)→ null。* 纯函数,不碰 IO。*/-export function extractDirCandidate(content: string): string | null {+export function extractDirCandidate(+ content: string,+ pathPlatform: NodeJS.Platform = process.platform,+): string | null {let obj: unknown;try {obj = JSON.parse(content);@@ -92,14 +95,16 @@ export function extractDirCandidate(content: string): string | null {if (toolName === 'exec') {const cwd = (input as { cwd?: unknown }).cwd;if (typeof cwd === 'string' && cwd.trim() !== '' && path.isAbsolute(cwd)) {- return posixDriveToWin32(cwd);+ return posixDriveToWin32(cwd, pathPlatform);}}// cc 编辑类:先归一 POSIX 盘符路径(Windows 上 cc 常发 `/e/...`)再取 dirname。if (EDIT_TOOL_NAMES.has(toolName)) {const fp = (input as { file_path?: unknown }).file_path;- if (typeof fp === 'string' && path.isAbsolute(fp)) return path.dirname(posixDriveToWin32(fp));+ if (typeof fp === 'string' && path.isAbsolute(fp)) {+ return path.dirname(posixDriveToWin32(fp, pathPlatform));+ }}return null;}@@ -161,7 +166,7 @@ export async function resolveSessionGitDir(}/** 查该 session 可见的 tool-use 消息 content,createdAt 降序、bounded(可见性同 prRefsStore)。 */-async function queryRecentToolUseContents(sessionId: string): Promise<string[]> {+export async function queryRecentToolUseContents(sessionId: string): Promise<string[]> {const db = getDbClient().drizzle;const [sessionRow] = await db.select({ clearedAt: sessions.clearedAt })@@ -186,6 +191,30 @@ async function queryRecentToolUseContents(sessionId: string): Promise<string[]>return rows.map((r) => r.content);}+/**+ * Live wrapper used by remote probes: return only the newest telemetry-derived+ * directory, without touching the local filesystem. The path is meaningful on+ * the SSH host (or on the controlled device), so the caller must probe it there.+ */+export async function getSessionGitTelemetryCandidateLive(+ sessionId: string,+ pathPlatform: NodeJS.Platform = process.platform,+): Promise<string | null> {+ try {+ const contents = await queryRecentToolUseContents(sessionId);+ for (const content of contents) {+ const candidate = extractDirCandidate(content, pathPlatform);+ if (candidate) return candidate;+ }+ } catch (err) {+ log.warn('query remote git telemetry failed (no telemetry)', {+ sessionId,+ err: err instanceof Error ? err.message : String(err),+ });+ }+ return null;+}+/*** live 包装:用真实 DB + readGitHead 解析。DB 未就绪 / 查询失败时视为「无遥测」,* 静默落到 worktree / working_dir 兜底(永不抛错)。diff --git a/apps/desktop/src/main/git-review/scopeResolver.ts b/apps/desktop/src/main/git-review/scopeResolver.tsindex 8f2edae10c..5a0f067d63 100644--- a/apps/desktop/src/main/git-review/scopeResolver.ts+++ b/apps/desktop/src/main/git-review/scopeResolver.ts@@ -126,6 +126,25 @@ 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.+ if (resolved.source === 'remote') {+ return disabledScope(sessionId, {+ workingDir: row.workingDir,+ worktreePath: fallbackWorktreePath,+ disabledReason: 'remote-session',+ disabledMessage: 'Git review for remote sessions is not available yet',+ resolutionChain: [+ {+ source: 'remote',+ path: row.workingDir,+ ok: false,+ reason: row.remoteHostId ?? 'remote-resolver',+ },+ ],+ });+ }const resolutionChain = [{ source: 'telemetry', path: resolved.source === 'telemetry' ? resolved.workdir : null, ok: resolved.source === 'telemetry' },{ source: 'worktree', path: fallbackWorktreePath, ok: resolved.source === 'worktree' },diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.tsindex a5f7d309a7..7b2612195b 100644--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@ -4058,11 +4058,12 @@ contextBridge.exposeInMainWorld('electronAPI', {gitContext: {/** 读 workdir 当前分支(非 git 目录返回 head=null)。 */get: (workdir: string): Promise<unknown> => ipcRenderer.invoke('git-context:get', workdir),- /** 按 session 解析「对话真实工作目录」+ HEAD + 来源(遥测/worktree/working_dir)。 */+ /** 按 session 解析「对话真实工作目录」+ HEAD + 来源(含 SSH 远端)。 */getForSession: (input: {sessionId: string;workingDir: string | null;worktreePath: string | null;+ remoteHostId?: string | null;}): Promise<unknown> => ipcRenderer.invoke('git-context:get-for-session', input),/** 开始监听该 workdir 的 HEAD 变化(refcount;变化经 onChanged 推送)。 */watch: (workdir: string): Promise<void> => ipcRenderer.invoke('git-context:watch', workdir),diff --git a/apps/desktop/src/renderer/__tests__/pickBranchLabel.test.ts b/apps/desktop/src/renderer/__tests__/pickBranchLabel.test.tsindex a46c281891..9cce0cb5a8 100644--- a/apps/desktop/src/renderer/__tests__/pickBranchLabel.test.ts+++ b/apps/desktop/src/renderer/__tests__/pickBranchLabel.test.ts@@ -21,6 +21,12 @@ describe('pickBranchLabel', () => {).toBe('feat/wt');});+ it('remote 来源可信:显示远端分支,即使有 PR 也优先', () => {+ expect(+ pickBranchLabel({ localBranch: 'feat/remote', prBranch: 'pr/remote', branchSource: 'remote', hasPrRefs: true }),+ ).toBe('feat/remote');+ });+it('workingDir + 无 PR 引用:显示 working_dir 分支(最后兜底)', () => {expect(pickBranchLabel({ localBranch: 'main', prBranch: null, branchSource: 'workingDir', hasPrRefs: false }),diff --git a/apps/desktop/src/renderer/features/cc-agent/GitContextBadge.tsx b/apps/desktop/src/renderer/features/cc-agent/GitContextBadge.tsxindex 5946fdc7af..0fa52766f7 100644--- a/apps/desktop/src/renderer/features/cc-agent/GitContextBadge.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/GitContextBadge.tsx@@ -3,7 +3,7 @@** 组成:* - 分支 chip:GitBranch 图标 + 分支名(detached 显示短 sha)。分支按信任度取:- * 遥测/worktree 推断出的真实工作目录 HEAD(可信)→ PR 源分支(head.ref,+ * 遥测/worktree/远端执行端推断出的真实工作目录 HEAD(可信)→ PR 源分支(head.ref,* worktree 已删时兜底)→ working_dir HEAD(低信任,仅在无 PR 时最后兜底)。* HEAD 变化(用户/agent 切分支)由 useSessionGitContext 实时推送刷新。* - PR chip(最多 MAX_STATUS_QUERIES 条,lastSeenAt 最近优先):状态图标 + #号,diff --git a/apps/desktop/src/renderer/features/cc-agent/gitContextPrVisuals.ts b/apps/desktop/src/renderer/features/cc-agent/gitContextPrVisuals.tsindex 3a2176cc53..6356850f8c 100644--- a/apps/desktop/src/renderer/features/cc-agent/gitContextPrVisuals.ts+++ b/apps/desktop/src/renderer/features/cc-agent/gitContextPrVisuals.ts@@ -28,7 +28,8 @@ export function pickBranchLabel(opts: {hasPrRefs: boolean;}): string | null {const { localBranch, prBranch, branchSource, hasPrRefs } = opts;- const trusted = branchSource === 'telemetry' || branchSource === 'worktree';+ const trusted =+ branchSource === 'telemetry' || branchSource === 'worktree' || branchSource === 'remote';if (trusted && localBranch) return localBranch;if (prBranch) return prBranch;if (branchSource === 'workingDir' && !hasPrRefs) return localBranch;diff --git a/apps/desktop/src/renderer/hooks/__tests__/useSessionGitContext.remote.test.ts b/apps/desktop/src/renderer/hooks/__tests__/useSessionGitContext.remote.test.tsnew file mode 100644index 0000000000..24188077af--- /dev/null+++ b/apps/desktop/src/renderer/hooks/__tests__/useSessionGitContext.remote.test.ts@@ -0,0 +1,225 @@+// @vitest-environment jsdom++import { renderHook, waitFor } from '@testing-library/react';+import { afterEach, describe, expect, it, vi } from 'vitest';++import type { Session } from '@/lib/ccAgent.types';++vi.mock('@/contexts/WorktreeContext', () => ({+ useWorktreeForSession: () => null,+}));+vi.mock('@/features/device-link/stickySessionOrigin', () => ({+ getStickySessionDeviceId: () => undefined,+}));++import { useSessionGitContext } from '../useSessionGitContext';++const sessionBase: Session = {+ id: 'session-1',+ userId: 'user-1',+ title: 'Remote task',+ workingDir: '/remote/project',+ workspaceKind: 'project',+ model: 'model',+ effort: 'medium',+ permissionMode: 'default',+ sdkSessionId: null,+ totalTokenUsage: 0,+ totalCostUsd: 0,+ contextTokens: 0,+ contextWindow: 1,+ fastMode: false,+ clearedAt: null,+ pinnedAt: null,+ userSendAt: null,+ status: 'active',+ agentKind: 'codex',+ extraDirs: [],+ remoteHostId: null,+ createdAt: '2026-01-01T00:00:00.000Z',+ updatedAt: '2026-01-01T00:00:00.000Z',+};++function makeGitContext() {+ return {+ getForSession: vi.fn(),+ watch: vi.fn().mockResolvedValue(undefined),+ unwatch: vi.fn().mockResolvedValue(undefined),+ onChanged: vi.fn(() => () => undefined),+ listPrRefs: vi.fn(),+ getPrStatuses: vi.fn(),+ onPrRefsChanged: vi.fn(() => () => undefined),+ };+}++afterEach(() => {+ vi.restoreAllMocks();+});++describe('useSessionGitContext remote routing', () => {+ it('SSH 会话在本机 main 侧解析远端 HEAD,不注册本地 watcher', async () => {+ const gitContext = makeGitContext();+ gitContext.getForSession.mockResolvedValue({+ workdir: '/srv/project',+ head: { kind: 'branch', branch: 'feature/ssh', shortSha: null },+ source: 'remote',+ });+ gitContext.listPrRefs.mockResolvedValue([]);+ gitContext.getPrStatuses.mockResolvedValue([]);+ window.electronAPI = {+ gitContext,+ deviceLink: { invoke: vi.fn() },+ } as never;++ const session = { ...sessionBase, remoteHostId: 'ssh-1' };+ const { result, unmount } = renderHook(() => useSessionGitContext(session));++ await waitFor(() => expect(result.current.head?.branch).toBe('feature/ssh'));+ expect(gitContext.getForSession).toHaveBeenCalledWith({+ sessionId: 'session-1',+ workingDir: '/remote/project',+ worktreePath: null,+ remoteHostId: 'ssh-1',+ });+ expect(gitContext.onChanged).not.toHaveBeenCalled();+ expect(gitContext.watch).not.toHaveBeenCalled();+ expect(gitContext.listPrRefs).toHaveBeenCalledWith('session-1');+ unmount();+ expect(gitContext.unwatch).not.toHaveBeenCalled();+ });++ it('device-link 会话把 HEAD、PR 引用和状态查询全部发往被控端', async () => {+ const gitContext = makeGitContext();+ const invoke = vi.fn(async (_deviceId: string, channel: string) => {+ if (channel === 'git-context:get-for-session') {+ return {+ workdir: '/controlled/repo',+ head: { kind: 'branch', branch: 'feature/device', shortSha: null },+ source: 'remote',+ };+ }+ if (channel === 'git-context:pr-refs:list') {+ return [+ {+ id: 'ref-1',+ sessionId: 'session-1',+ owner: 'octo',+ repo: 'repo',+ prNumber: 42,+ url: 'https://github.com/octo/repo/pull/42',+ firstSeenAt: 1,+ lastSeenAt: 2,+ },+ ];+ }+ return [+ {+ ok: true,+ owner: 'octo',+ repo: 'repo',+ prNumber: 42,+ status: 'open',+ title: 'Remote PR',+ htmlUrl: 'https://github.com/octo/repo/pull/42',+ branch: 'feature/device',+ unresolvedCount: 0,+ },+ ];+ });+ gitContext.getForSession.mockRejectedValue(new Error('must use device-link'));+ gitContext.listPrRefs.mockRejectedValue(new Error('must use device-link'));+ gitContext.getPrStatuses.mockRejectedValue(new Error('must use device-link'));+ window.electronAPI = {+ gitContext,+ deviceLink: { invoke },+ } as never;++ const session = { ...sessionBase, deviceLinkDeviceId: 'device-1', remoteHostId: 'ssh-1' };+ const { result, unmount } = renderHook(() => useSessionGitContext(session));++ await waitFor(() => {+ expect(result.current.head?.branch).toBe('feature/device');+ expect(result.current.prRefs).toHaveLength(1);+ expect(result.current.prStatuses.size).toBe(1);+ });+ expect(invoke).toHaveBeenCalledWith(+ 'device-1',+ 'git-context:get-for-session',+ [expect.objectContaining({ sessionId: 'session-1', remoteHostId: 'ssh-1' })],+ );+ expect(invoke).toHaveBeenCalledWith('device-1', 'git-context:pr-refs:list', ['session-1']);+ expect(invoke).toHaveBeenCalledWith('device-1', 'git-context:pr-status', [+ { sessionId: 'session-1', queries: [{ owner: 'octo', repo: 'repo', prNumber: 42 }] },+ ]);+ expect(gitContext.onChanged).not.toHaveBeenCalled();+ expect(gitContext.onPrRefsChanged).not.toHaveBeenCalled();+ unmount();+ expect(gitContext.watch).not.toHaveBeenCalled();+ expect(gitContext.unwatch).not.toHaveBeenCalled();+ });++ it('切换任务或被控端断链时清掉旧的 Git / PR 展示', async () => {+ let disconnected = false;+ const gitContext = makeGitContext();+ const invoke = vi.fn(async (_deviceId: string, channel: string, args: unknown[]) => {+ if (disconnected) throw new Error('disconnected');+ if (channel === 'git-context:get-for-session') {+ return {+ workdir: '/controlled/repo',+ head: { kind: 'branch', branch: 'feature/device', shortSha: null },+ source: 'remote',+ };+ }+ if (channel === 'git-context:pr-refs:list') {+ return [+ {+ id: 'ref-1',+ sessionId: (args[0] as string) ?? 'session-1',+ owner: 'octo',+ repo: 'repo',+ prNumber: 42,+ url: 'https://github.com/octo/repo/pull/42',+ firstSeenAt: 1,+ lastSeenAt: 2,+ },+ ];+ }+ return [+ {+ ok: true,+ owner: 'octo',+ repo: 'repo',+ prNumber: 42,+ status: 'open',+ title: 'Remote PR',+ htmlUrl: 'https://github.com/octo/repo/pull/42',+ branch: 'feature/device',+ unresolvedCount: 0,+ },+ ];+ });+ window.electronAPI = {+ gitContext,+ deviceLink: { invoke },+ } as never;++ const first = { ...sessionBase, deviceLinkDeviceId: 'device-1' };+ const { result, rerender, unmount } = renderHook(+ ({ session }: { session: Session }) => useSessionGitContext(session),+ { initialProps: { session: first } },+ );+ await waitFor(() => {+ expect(result.current.head?.branch).toBe('feature/device');+ expect(result.current.prRefs).toHaveLength(1);+ });++ disconnected = true;+ rerender({ session: { ...first, id: 'session-2' } });+ await waitFor(() => {+ expect(result.current.head).toBeNull();+ expect(result.current.prRefs).toHaveLength(0);+ expect(result.current.prStatuses.size).toBe(0);+ });+ unmount();+ });+});diff --git a/apps/desktop/src/renderer/hooks/useSessionGitContext.ts b/apps/desktop/src/renderer/hooks/useSessionGitContext.tsindex 80ce41b19b..ac7bba342b 100644--- a/apps/desktop/src/renderer/hooks/useSessionGitContext.ts+++ b/apps/desktop/src/renderer/hooks/useSessionGitContext.ts@@ -6,15 +6,17 @@* 改用 gitContext.getForSession(sessionId) 让 main 从 agent tool-call 遥测* (Codex cwd / cc 编辑路径)推断「对话真实工作目录」+ 其 HEAD + 来源 source。* 拿到 workdir 后 gitContext.watch 开启 HEAD 监听;对话中途换 worktree 靠- * focus + 周期 tick 再解析并切换监听目标。- * - PR 引用:listPrRefs(sessionId) + git-context:pr-refs-changed 推送刷新。+ * focus + 周期 tick 再解析并切换监听目标。SSH / device-link 会话在真实执行端+ * 查询,不在控制端注册本地 watcher,改用 focus + 周期 tick。+ * - PR 引用:listPrRefs(sessionId) + git-context:pr-refs-changed 推送刷新(本机/SSH);+ * device-link 使用被控端查询 + focus/周期 polling,避免把控制端本地事件+ * 错当成被控端事件。* - PR 状态:引用变化后对前 MAX_STATUS_QUERIES 条批量查一次(main 60s TTL 缓存,* 重复查询便宜);未配 PAT 时返回 no-token,UI 显示 PR 号不显示状态。结果含* PR 源分支 branch:遥测拿不到本地目录时,徽标用它兜底显示分支。*- * 约束:dialogue 会话(workspaceKind !== 'project')与远端会话(remoteHostId)- * 不启用——前者 workingDir 是对话自有目录分支语义无意义,后者本地读 .git 没意义,- * 直接返回空态,不发任何 IPC。+ * 约束:dialogue 会话(workspaceKind !== 'project')不启用——workingDir 是对话自有目录,+ * 分支语义无意义。SSH 与 device-link 远程会话则把查询发往真实执行端。*/import { useEffect, useState } from 'react';@@ -24,10 +26,12 @@ import type {GitContextDirSource,GitContextSnapshot,GitHeadInfo,+ SessionGitDirResult,SessionPrRef,PrStatusResult,} from '@/lib/gitContext.types';import { useWorktreeForSession } from '@/contexts/WorktreeContext';+import { getStickySessionDeviceId } from '@/features/device-link/stickySessionOrigin';import { createLogger } from '@/lib/logger';const log = createLogger('useSessionGitContext');@@ -49,10 +53,22 @@ const STATUS_REFRESH_INTERVAL_MS = 90_000;*/const DIR_RERESOLVE_INTERVAL_MS = 60_000;+const GET_FOR_SESSION_CHANNEL = 'git-context:get-for-session';+const PR_REFS_LIST_CHANNEL = 'git-context:pr-refs:list';+const PR_STATUS_CHANNEL = 'git-context:pr-status';++async function invokeRemoteGitContext<T>(+ deviceId: string,+ channel: string,+ args: unknown[],+): Promise<T> {+ return (await window.electronAPI.deviceLink.invoke(deviceId, channel, args)) as T;+}+export interface SessionGitContext {/** 当前分支信息;null = 非 git 目录 / dialogue 会话 / 尚未加载。 */head: GitHeadInfo | null;- /** head 的来源,决定徽标对分支的信任度(telemetry/worktree 可信,workingDir 让位 PR)。 */+ /** head 的来源,决定徽标对分支的信任度(telemetry/worktree/remote 可信,workingDir 让位 PR)。 */branchSource: GitContextDirSource;/** 关联 PR 引用,lastSeenAt 降序。 */prRefs: SessionPrRef[];@@ -73,15 +89,23 @@ const EMPTY: SessionGitContext = {export function useSessionGitContext(session: Session): SessionGitContext {const sessionId = session.id;- // worktree 路径用 WorktreeContext 的 live 元数据,**不读 session.worktreePath**:- // 那是反范式快照,worktree 删除后刻意不清(见 schema.ts),拿快照会把已删- // 路径向上 walk 到主仓 .git,显示主仓分支冒充 worktree 分支(Codex review P2;- // ADR-WT-FE-4:徽标一律按 store 是否存在判定)。它仅作为遥测拿不到时的兜底之一。+ // 本地 worktree 路径用 WorktreeContext 的 live 元数据,**不读 session.worktreePath**:+ // 那是反范式快照,worktree 删除后刻意不清(见 schema.ts),拿快照会把已删路径向上+ // walk 到主仓 .git,显示主仓分支冒充 worktree 分支(Codex review P2;+ // ADR-WT-FE-4)。远程 session 没有控制端 WorktreeContext,其 path 会在真实执行端+ // 重新 probe,因此可以使用远端 session snapshot 作为候选。const worktreeMeta = useWorktreeForSession(sessionId);- // dialogue 会话分支语义无意义;远端会话(remoteHostId)本地读 .git 没意义 → 不启用。- const isProjectLocal = session.workspaceKind === 'project' && !session.remoteHostId;+ const deviceLinkDeviceId =+ session.deviceLinkDeviceId ?? getStickySessionDeviceId(sessionId) ?? null;+ const remoteHostId = session.remoteHostId ?? null;+ const isProjectSession = session.workspaceKind === 'project';+ const isDeviceLinkSession = Boolean(deviceLinkDeviceId);+ const isSshSession = Boolean(remoteHostId) && !isDeviceLinkSession;+ const isLocalSession = !isDeviceLinkSession && !isSshSession;const workingDir = session.workingDir ?? null;- const worktreePath = worktreeMeta?.path ?? null;+ // device-link / SSH 的 path 属于真实执行端,会在那里重新 probe;本地会话仍只使用+ // WorktreeContext 的 live 路径,不信任 session 上的历史快照。+ const worktreePath = isLocalSession ? worktreeMeta?.path ?? null : session.worktreePath ?? null;const [head, setHead] = useState<GitHeadInfo | null>(null);const [branchSource, setBranchSource] = useState<GitContextDirSource>(null);@@ -90,11 +114,16 @@ export function useSessionGitContext(session: Session): SessionGitContext {// ── 分支:getForSession 解析真实工作目录 + 可换目录的 HEAD watch ──useEffect(() => {- if (!isProjectLocal) {+ if (!isProjectSession) {setHead(null);setBranchSource(null);return;}+ // A single header instance can survive session switches. Clear the old+ // task's branch immediately so a failed remote invoke cannot leave stale+ // Git context beside the newly selected title.+ setHead(null);+ setBranchSource(null);let cancelled = false;// 当前监听的(已 resolve 的绝对)目录,cleanup 与目录切换都靠它——// 用 ref 对象而非闭包 let:解析是异步的,cleanup 必须拿到最新值才能 unwatch。@@ -107,30 +136,42 @@ export function useSessionGitContext(session: Session): SessionGitContext {// 退回旧分支,正是本 PR 要修的 bug(Greptile review P2)。let resolveGen = 0;- // 先订阅再解析:在途窗口的推送进 pendingPush 缓冲;match 用 watchedRef.current。- const unsubscribe = window.electronAPI.gitContext.onChanged((snapshot) => {- if (watchedRef.current === null) {- pendingPush.current = snapshot;- return;- }- if (snapshot.workdir === watchedRef.current) {- setHead(snapshot.head);- }- });+ // 只有控制端本地目录能由本机 GitContextService watcher 监听。SSH / device-link+ // 路径属于真实执行端,不能在控制端对同名路径注册 watcher,否则会读错本机 checkout。+ const unsubscribe = isLocalSession+ ? window.electronAPI.gitContext.onChanged((snapshot) => {+ if (watchedRef.current === null) {+ pendingPush.current = snapshot;+ return;+ }+ if (snapshot.workdir === watchedRef.current) {+ setHead(snapshot.head);+ }+ })+ : () => undefined;const resolveAndWatch = async () => {const gen = ++resolveGen;try {- const res = await window.electronAPI.gitContext.getForSession({+ const input = {sessionId,workingDir,worktreePath,- });+ ...(remoteHostId ? { remoteHostId } : {}),+ };+ const res = isDeviceLinkSession+ ? await invokeRemoteGitContext<SessionGitDirResult>(+ deviceLinkDeviceId as string,+ GET_FOR_SESSION_CHANNEL,+ [input],+ )+ : await window.electronAPI.gitContext.getForSession(input);// 被更新的调用超越(或 effect 已 cleanup)→ 丢弃陈旧结果,不碰 watchedRef。if (cancelled || gen !== resolveGen) return;setHead(res.head);setBranchSource(res.source);const next = res.workdir; // 已是 resolve 过的绝对路径或 null+ if (!isLocalSession) return;if (next === watchedRef.current) return; // 目录没变,仅刷新了 headconst prev = watchedRef.current;watchedRef.current = next;@@ -144,6 +185,10 @@ export function useSessionGitContext(session: Session): SessionGitContext {}} catch (err) {log.warn('git context resolve failed', String(err));+ if (!cancelled && gen === resolveGen) {+ setHead(null);+ setBranchSource(null);+ }}};@@ -162,22 +207,46 @@ export function useSessionGitContext(session: Session): SessionGitContext {void window.electronAPI.gitContext.unwatch(watchedRef.current).catch(() => undefined);}};- }, [sessionId, isProjectLocal, workingDir, worktreePath]);+ }, [+ sessionId,+ isProjectSession,+ isLocalSession,+ isSshSession,+ isDeviceLinkSession,+ deviceLinkDeviceId,+ remoteHostId,+ workingDir,+ worktreePath,+ ]);// ── PR 引用 + 状态 ──useEffect(() => {- if (!isProjectLocal) {+ if (!isProjectSession) {setPrRefs([]);setPrStatuses(new Map());return;}+ // The header can remain mounted while the selected task changes. Drop the+ // previous task's PR chips before the new remote read settles.+ setPrRefs([]);+ setPrStatuses(new Map());let cancelled = false;+ let loadGen = 0;const loadRefs = async () => {+ const gen = ++loadGen;+ let refsLoaded = false;try {- const refs = await window.electronAPI.gitContext.listPrRefs(sessionId);- if (cancelled) return;+ const refs = isDeviceLinkSession+ ? await invokeRemoteGitContext<SessionPrRef[]>(+ deviceLinkDeviceId as string,+ PR_REFS_LIST_CHANNEL,+ [sessionId],+ )+ : await window.electronAPI.gitContext.listPrRefs(sessionId);+ if (cancelled || gen !== loadGen) return;setPrRefs(refs);+ refsLoaded = true;const queries = refs.slice(0, MAX_STATUS_QUERIES).map((r) => ({owner: r.owner,repo: r.repo,@@ -187,18 +256,30 @@ export function useSessionGitContext(session: Session): SessionGitContext {setPrStatuses(new Map());return;}- const results = await window.electronAPI.gitContext.getPrStatuses(queries);- if (cancelled) return;+ const results = isDeviceLinkSession+ ? await invokeRemoteGitContext<PrStatusResult[]>(+ deviceLinkDeviceId as string,+ PR_STATUS_CHANNEL,+ [{ sessionId, queries }],+ )+ : await window.electronAPI.gitContext.getPrStatuses(queries);+ if (cancelled || gen !== loadGen) return;setPrStatuses(new Map(results.map((r) => [prStatusKey(r), r])));} catch (err) {log.warn('pr refs load failed', String(err));+ if (!cancelled && gen === loadGen) {+ if (!refsLoaded) setPrRefs([]);+ setPrStatuses(new Map());+ }}};void loadRefs();- const unsubscribe = window.electronAPI.gitContext.onPrRefsChanged((data) => {- if (data.sessionId === sessionId) void loadRefs();- });+ const unsubscribe = isDeviceLinkSession+ ? () => undefined+ : window.electronAPI.gitContext.onPrRefsChanged((data) => {+ if (data.sessionId === sessionId) void loadRefs();+ });// 远端状态变化(merged / closed / review resolve)没有本地事件可订阅,// 用周期 tick + 窗口聚焦兜底刷新;批量上限 3 条 + main 侧缓存,开销可忽略。const interval = setInterval(() => void loadRefs(), STATUS_REFRESH_INTERVAL_MS);@@ -211,8 +292,8 @@ export function useSessionGitContext(session: Session): SessionGitContext {clearInterval(interval);window.removeEventListener('focus', onFocus);};- }, [sessionId, isProjectLocal]);+ }, [sessionId, isProjectSession, isDeviceLinkSession, deviceLinkDeviceId]);- if (!isProjectLocal) return EMPTY;+ if (!isProjectSession) return EMPTY;return { head, branchSource, prRefs, prStatuses };}diff --git a/apps/desktop/src/renderer/lib/gitContext.types.ts b/apps/desktop/src/renderer/lib/gitContext.types.tsindex d16690630a..b32f114e96 100644--- a/apps/desktop/src/renderer/lib/gitContext.types.ts+++ b/apps/desktop/src/renderer/lib/gitContext.types.ts@@ -22,9 +22,10 @@ export interface GitContextSnapshot {* telemetry = 从 agent tool-call(Codex cwd / cc 编辑路径)推出的真实工作目录,可信* worktree = app 托管 worktree 的 live 路径,可信* workingDir = 兜底用 session.working_dir(共享主 checkout,低信任,优先让位 PR 分支)+ * remote = 远端 SSH 主机上直接探测到的目录分支,可信* null = 无可解析目录*/-export type GitContextDirSource = 'telemetry' | 'worktree' | 'workingDir' | null;+export type GitContextDirSource = 'telemetry' | 'worktree' | 'workingDir' | 'remote' | null;/** git-context:get-for-session 的返回:解析出的目录 + 其 HEAD + 来源。 */export interface SessionGitDirResult {diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex 1eed868905..5cd317b12e 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -3673,6 +3673,7 @@ interface ElectronAPI {sessionId: string;workingDir: string | null;worktreePath: string | null;+ remoteHostId?: string | null;}) => Promise<import('@/lib/gitContext.types').SessionGitDirResult>;watch: (workdir: string) => Promise<void>;unwatch: (workdir: string) => Promise<void>;diff --git a/packages/device-link/src/__tests__/allowlist.test.ts b/packages/device-link/src/__tests__/allowlist.test.tsindex bc5b41e8c7..c234bff12e 100644--- a/packages/device-link/src/__tests__/allowlist.test.ts+++ b/packages/device-link/src/__tests__/allowlist.test.ts@@ -44,6 +44,16 @@ describe('REMOTE_INVOKE_ALLOWLIST', () => {}});+ it('允许远程会话读取被控端 Git / GitHub 上下文', () => {+ for (const ch of [+ 'git-context:get-for-session',+ 'git-context:pr-refs:list',+ 'git-context:pr-status',+ ]) {+ expect(REMOTE_INVOKE_ALLOWLIST.has(ch)).toBe(true);+ }+ });+it('放行订阅价值历史汇总只读聚合(远程会话底部 $ chip 的历史初值查被控端)', () => {expect(REMOTE_INVOKE_ALLOWLIST.has('local-db:messages:estimatedSessionValue')).toBe(true);});diff --git a/packages/device-link/src/allowlist.ts b/packages/device-link/src/allowlist.tsindex 71987b6dbf..14a3ca089f 100644--- a/packages/device-link/src/allowlist.ts+++ b/packages/device-link/src/allowlist.ts@@ -228,6 +228,11 @@ const CORE_INVOKE_CHANNELS: readonly string[] = [// Git safety 设置(只读):远程 Codex Rewind 入口必须按被控端是否会创建 safety snapshot// 决定显隐。SET/RESET 不放行,控制端不能改被控端全局偏好。'maker:git-safety:get',+ // 会话标题旁的 Git / GitHub 上下文(分支、PR 引用与实时状态)必须在被控端查询,+ // 因为控制端本地没有远端 session 的 DB、工作目录或 gh 登录态。+ 'git-context:get-for-session',+ 'git-context:pr-refs:list',+ 'git-context:pr-status',// —— 读模型(被控端本地 DB 是数据真相)——'local-db:sessions:list','local-db:sessions:get',