Selaa lähdekoodia

fix: preserve session diff paths and rename metrics

hetaoBackend 2 kuukautta sitten
vanhempi
sitoutus
0e91cd785f

+ 72 - 71
packages/local-runtime/src/turns/diff-api.ts

@@ -11,6 +11,16 @@ import { json } from '../api/host-helpers.js';
 import { applyLocalTurnDiffSnapshotMutation } from './file-changes.js';
 
 const execFile = promisify(execFileCallback);
+// Read paths and metrics as NUL records; patch headers are presentation only.
+const WORKSPACE_DIFF_ARGS = [
+  '--raw',
+  '--numstat',
+  '-z',
+  '--patch',
+  '--no-color',
+  '--no-ext-diff',
+  '--no-textconv',
+];
 
 export interface LocalDiffSession {
   readonly sessionId: string;
@@ -238,22 +248,19 @@ async function readWorkspaceDiff(
   workspaceDir: string,
 ): Promise<{ fileChanges: LocalFileDiff[]; rawDiff?: string }> {
   try {
-    const [nameStatus, numstat, rawDiff] = await Promise.all([
-      execGit(['diff', 'HEAD', '--name-status', '--'], workspaceDir),
-      execGit(['diff', 'HEAD', '--numstat', '--'], workspaceDir),
-      execGit(['diff', 'HEAD', '--'], workspaceDir),
-    ]);
+    const result = await execGit(['diff', 'HEAD', ...WORKSPACE_DIFF_ARGS, '--'], workspaceDir);
+    const trackedDiffs = parseGitDiffSummary(result.stdout);
     const untracked = await readUntrackedFiles(workspaceDir);
     const untrackedDiffs = await Promise.all(
       untracked.map((file) => readUntrackedFileDiff(workspaceDir, file)),
     );
-    const raw = [rawDiff.stdout, ...untrackedDiffs.flatMap((item) => item.rawDiff ?? [])]
+    const raw = [
+      ...trackedDiffs.flatMap((item) => item.diff ?? []),
+      ...untrackedDiffs.flatMap((item) => item.rawDiff ?? []),
+    ]
       .filter(Boolean)
       .join('\n');
-    const fileChanges = [
-      ...parseGitDiffSummary(nameStatus.stdout, numstat.stdout, rawDiff.stdout),
-      ...untrackedDiffs.map((item) => item.fileChange),
-    ];
+    const fileChanges = [...trackedDiffs, ...untrackedDiffs.map((item) => item.fileChange)];
     return { fileChanges, ...(raw ? { rawDiff: raw } : {}) };
   } catch {
     return { fileChanges: [] };
@@ -268,48 +275,59 @@ async function execGit(args: string[], cwd: string): Promise<{ stdout: string; s
   });
 }
 
-function parseGitDiffSummary(
-  nameStatus: string,
-  numstat: string,
-  rawDiff: string,
-): LocalFileDiff[] {
+function parseGitDiffSummary(output: string): LocalFileDiff[] {
+  if (!output) return [];
+  // --raw --numstat -z --patch emits raw records, then numstat records,
+  // then an extra NUL before the patches. Git uses the same order for raw
+  // records and patch blocks, including rename-only and binary changes.
+  const boundary = output.indexOf('\0\0');
+  if (boundary < 0) throw new Error('Git diff is missing its patch boundary');
+  const records = output.slice(0, boundary).split('\0');
+  const files: Array<{ file: string; status: string }> = [];
+  let index = 0;
+  while (records[index]?.startsWith(':')) {
+    const status = records[index++]!.split(' ').at(-1)!;
+    const source = records[index++];
+    const file = /^[RC]/u.test(status) ? records[index++] : source;
+    if (!file) throw new Error('Git diff is missing a raw path');
+    files.push({ file, status: mapGitStatus(status) });
+  }
   const stats = new Map<string, { additions: number; deletions: number }>();
-  for (const line of numstat.split('\n')) {
-    if (!line.trim()) continue;
-    const [additions, deletions, ...pathParts] = line.split('\t');
-    const file = pathParts.join('\t');
-    if (!file) continue;
+  while (index < records.length) {
+    const [additions, deletions, ...pathParts] = records[index++]!.split('\t');
+    let file = pathParts.join('\t');
+    // Renames/copies have an empty numstat path followed by old and new paths.
+    if (!file) {
+      index += 1;
+      file = records[index++] ?? '';
+    }
+    if (!file) throw new Error('Git diff is missing a numstat path');
     stats.set(file, {
       additions: numericDiffStat(additions),
       deletions: numericDiffStat(deletions),
     });
   }
-  const patches = splitPatchByFile(rawDiff);
-  const out: LocalFileDiff[] = [];
-  for (const line of nameStatus.split('\n')) {
-    if (!line.trim()) continue;
-    const [statusToken, ...pathParts] = line.split('\t');
-    const file = pathParts[pathParts.length - 1];
-    if (!file) continue;
-    const stat = stats.get(file) ?? { additions: 0, deletions: 0 };
-    out.push({
-      file,
-      additions: stat.additions,
-      deletions: stat.deletions,
-      status: mapGitStatus(statusToken),
-      ...(patches.get(file) ? { diff: patches.get(file) } : {}),
-    });
+  const patches = output
+    .slice(boundary + 2)
+    .split(/(?=^diff --git )/mu)
+    .filter(Boolean);
+  if (files.length !== patches.length) {
+    throw new Error('Git diff raw paths and patch blocks do not match');
   }
-  return out;
+  return files.map(({ file, status }, position) => {
+    const stat = stats.get(file);
+    if (!stat) throw new Error('Git diff is missing file metrics');
+    return { file, status, ...stat, diff: patches[position] };
+  });
 }
 
 async function readUntrackedFiles(workspaceDir: string): Promise<string[]> {
   try {
-    const result = await execGit(['ls-files', '--others', '--exclude-standard'], workspaceDir);
-    return result.stdout
-      .split('\n')
-      .map((line) => line.trim())
-      .filter(Boolean);
+    const result = await execGit(
+      ['ls-files', '--others', '--exclude-standard', '-z'],
+      workspaceDir,
+    );
+    return result.stdout.split('\0').filter(Boolean);
   } catch {
     return [];
   }
@@ -320,28 +338,24 @@ async function readUntrackedFileDiff(
   file: string,
 ): Promise<{ fileChange: LocalFileDiff; rawDiff?: string }> {
   try {
-    const rawDiff = await execFile('git', ['diff', '--no-index', '--', '/dev/null', file], {
-      cwd: workspaceDir,
-      env: cleanGitEnv(),
-      maxBuffer: 10 * 1024 * 1024,
-    }).catch((err: unknown) => {
+    const rawDiff = await execFile(
+      'git',
+      ['diff', '--no-index', ...WORKSPACE_DIFF_ARGS, '--', '/dev/null', file],
+      {
+        cwd: workspaceDir,
+        env: cleanGitEnv(),
+        maxBuffer: 10 * 1024 * 1024,
+      },
+    ).catch((err: unknown) => {
       const error = err as { stdout?: string; code?: number };
       if (error.code === 1 && typeof error.stdout === 'string') return { stdout: error.stdout };
       throw err;
     });
-    const text = rawDiff.stdout;
-    const additions = text
-      .split('\n')
-      .filter((line) => line.startsWith('+') && !line.startsWith('+++')).length;
+    const parsed = parseGitDiffSummary(rawDiff.stdout)[0];
+    if (!parsed) throw new Error('Git diff is missing an untracked file');
     return {
-      fileChange: {
-        file,
-        additions,
-        deletions: 0,
-        status: 'added',
-        ...(text ? { diff: text } : {}),
-      },
-      ...(text ? { rawDiff: text } : {}),
+      fileChange: { ...parsed, file, status: 'added' },
+      ...(parsed.diff ? { rawDiff: parsed.diff } : {}),
     };
   } catch {
     return {
@@ -355,19 +369,6 @@ async function readUntrackedFileDiff(
   }
 }
 
-function splitPatchByFile(rawDiff: string): Map<string, string> {
-  const patches = new Map<string, string>();
-  const chunks = rawDiff.split(/^diff --git /m);
-  for (const chunk of chunks) {
-    if (!chunk.trim()) continue;
-    const text = `diff --git ${chunk}`;
-    const match = /^diff --git a\/(.+?) b\/(.+)$/m.exec(text);
-    const file = match?.[2];
-    if (file) patches.set(file, text);
-  }
-  return patches;
-}
-
 function mapGitStatus(status: string | undefined): string {
   const code = status?.[0];
   if (code === 'A') return 'added';

+ 303 - 0
packages/local-runtime/test/unit/session-diff-fallback.test.ts

@@ -0,0 +1,303 @@
+import { execFileSync } from 'node:child_process';
+import { mkdtemp, mkdir, writeFile, appendFile, rm } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { closeLocalRuntimeDb } from '../../src/persistence/db.js';
+import { SqliteLocalTurnDiffStore } from '../../src/persistence/sqlite-persistence.js';
+import { readLocalSessionDiff } from '../../src/turns/diff-api.js';
+
+let root: string;
+let workspaceDir: string;
+let dataDir: string;
+let diffStore: SqliteLocalTurnDiffStore;
+
+function git(...args: string[]): string {
+  return execFileSync('git', args, { cwd: workspaceDir, encoding: 'utf8' });
+}
+
+async function write(file: string, content: string | Buffer): Promise<void> {
+  await mkdir(path.dirname(path.join(workspaceDir, file)), { recursive: true });
+  await writeFile(path.join(workspaceDir, file), content);
+}
+
+function commit(): void {
+  git('add', '--all');
+  git('commit', '-qm', 'Synthetic baseline');
+}
+
+async function read(messageId?: string) {
+  return readLocalSessionDiff({
+    diffStore,
+    session: { sessionId: 'test-session', workspaceDir },
+    messageId,
+  });
+}
+
+beforeEach(async () => {
+  root = await mkdtemp(path.join(tmpdir(), 'session-diff-'));
+  workspaceDir = path.join(root, 'workspace');
+  dataDir = path.join(root, 'data');
+  await mkdir(workspaceDir);
+  // Keep user hooks, attributes, diff drivers and quoting defaults out of fixtures.
+  vi.stubEnv('GIT_CONFIG_NOSYSTEM', '1');
+  vi.stubEnv('GIT_CONFIG_GLOBAL', path.join(root, 'no-global-config'));
+  for (const key of ['GIT_DIR', 'GIT_WORK_TREE', 'GIT_INDEX_FILE', 'GIT_PREFIX']) {
+    vi.stubEnv(key, undefined);
+  }
+  git('init', '-q');
+  git('config', 'user.name', 'Diff Test');
+  git('config', 'user.email', 'diff-test@example.com');
+  git('config', 'core.autocrlf', 'false');
+  git('config', 'diff.renames', 'true');
+  await write('baseline.txt', 'unchanged\n');
+  commit();
+  diffStore = new SqliteLocalTurnDiffStore(dataDir);
+});
+
+afterEach(async () => {
+  closeLocalRuntimeDb(dataDir);
+  vi.unstubAllEnvs();
+  await rm(root, { recursive: true, force: true });
+});
+
+const portableNames = ['中文.txt', 'with spaces.txt', 'dir/{before after}.txt'];
+const posixNames = [
+  'tab\tname.txt',
+  'line\nname.txt',
+  'literal => arrow.txt',
+  ' quote"slash\\.txt',
+  ' trailing.txt ',
+];
+
+describe.each(['true', 'false'])('session diff fallback with core.quotePath=%s', (quotePath) => {
+  beforeEach(() => {
+    git('config', 'core.quotePath', quotePath);
+  });
+
+  it('preserves Unicode paths and attaches each tracked patch through the public API', async () => {
+    for (const file of portableNames) await write(file, 'first\n');
+    commit();
+    for (const [index, file] of portableNames.entries()) {
+      await appendFile(path.join(workspaceDir, file), `added-${index}\n`);
+    }
+    const result = await read();
+    expect(result.diffs).toHaveLength(portableNames.length);
+    for (const [index, file] of portableNames.entries()) {
+      expect(result.diffs.find((entry) => entry.file === file)).toMatchObject({
+        file,
+        additions: 1,
+        deletions: 0,
+        status: 'modified',
+        diff: expect.stringContaining(`+added-${index}\n`),
+      });
+    }
+  });
+
+  it('reports rename edits against the destination path', async () => {
+    await write('before.txt', 'a\nb\nc\nd\ne\nf\n');
+    commit();
+    git('mv', 'before.txt', 'after.txt');
+    await appendFile(path.join(workspaceDir, 'after.txt'), 'added\n');
+    expect((await read('missing-message')).diffs).toEqual([
+      {
+        file: 'after.txt',
+        additions: 1,
+        deletions: 0,
+        status: 'renamed',
+        diff: expect.stringContaining('+added\n'),
+      },
+    ]);
+  });
+
+  it('keeps additions, deletions, binary changes and untracked paths distinct', async () => {
+    await write('deleted 中文.txt', 'remove\n');
+    await write('binary.bin', Buffer.from([0, 1, 2]));
+    commit();
+    await rm(path.join(workspaceDir, 'deleted 中文.txt'));
+    await write('binary.bin', Buffer.from([0, 3, 4]));
+    await write('staged 中文.txt', 'staged\n');
+    git('add', '--', 'staged 中文.txt');
+    for (const file of portableNames) await write(file, 'untracked\n++content\n');
+    await write('untracked.bin', Buffer.from([0, 5, 6]));
+    await write('empty.txt', '');
+    const { diffs } = await read();
+    expect(diffs).toHaveLength(portableNames.length + 5);
+    expect(diffs.find((entry) => entry.file === 'deleted 中文.txt')).toMatchObject({
+      additions: 0,
+      deletions: 1,
+      status: 'deleted',
+      diff: expect.stringContaining('-remove\n'),
+    });
+    expect(diffs.find((entry) => entry.file === 'staged 中文.txt')).toMatchObject({
+      additions: 1,
+      deletions: 0,
+      status: 'added',
+      diff: expect.stringContaining('+staged\n'),
+    });
+    for (const file of ['binary.bin', 'untracked.bin']) {
+      expect(diffs.find((entry) => entry.file === file)).toMatchObject({
+        additions: 0,
+        deletions: 0,
+        diff: expect.stringContaining('Binary files '),
+      });
+    }
+    for (const file of portableNames) {
+      expect(diffs.find((entry) => entry.file === file)).toMatchObject({
+        additions: 2,
+        deletions: 0,
+        status: 'added',
+        diff: expect.stringContaining('+++content\n'),
+      });
+    }
+    expect(diffs.find((entry) => entry.file === 'empty.txt')).toMatchObject({
+      additions: 0,
+      deletions: 0,
+      status: 'added',
+    });
+  });
+
+  it.skipIf(process.platform === 'win32')(
+    'preserves POSIX whitespace, escape and arrow names for tracked and untracked files',
+    async () => {
+      for (const file of posixNames) await write(file, 'first\n');
+      commit();
+      for (const [index, file] of posixNames.entries()) {
+        await appendFile(path.join(workspaceDir, file), `tracked-${index}\n`);
+        await write(`untracked/${file}`, `untracked-${index}\n`);
+      }
+      const { diffs } = await read();
+      expect(diffs).toHaveLength(posixNames.length * 2);
+      for (const [index, file] of posixNames.entries()) {
+        expect(diffs.find((entry) => entry.file === file)).toMatchObject({
+          additions: 1,
+          deletions: 0,
+          diff: expect.stringContaining(`+tracked-${index}\n`),
+        });
+        expect(diffs.find((entry) => entry.file === `untracked/${file}`)).toMatchObject({
+          additions: 1,
+          deletions: 0,
+          diff: expect.stringContaining(`+untracked-${index}\n`),
+        });
+      }
+    },
+  );
+
+  it('retains a rename-only patch with zero line changes', async () => {
+    await write('old 中文.txt', 'same\n');
+    commit();
+    git('mv', 'old 中文.txt', 'new 中文.txt');
+    expect((await read()).diffs).toEqual([
+      {
+        file: 'new 中文.txt',
+        additions: 0,
+        deletions: 0,
+        status: 'renamed',
+        diff: expect.stringContaining('similarity index 100%'),
+      },
+    ]);
+  });
+
+  it.skipIf(process.platform === 'win32')(
+    'consumes both rename paths without splitting tabs or literal arrows',
+    async () => {
+      const source = 'dir/old\tline\n{left => right}.txt';
+      const destination = 'dir/new\tline\n{right => left}.txt';
+      await write(source, 'a\nb\nc\nd\ne\nf\n');
+      commit();
+      git('mv', source, destination);
+      await appendFile(path.join(workspaceDir, destination), 'renamed\n');
+      expect((await read()).diffs).toEqual([
+        {
+          file: destination,
+          additions: 1,
+          deletions: 0,
+          status: 'renamed',
+          diff: expect.stringContaining('+renamed\n'),
+        },
+      ]);
+    },
+  );
+
+  it('handles brace-compressed renames and copies with destination stats and patches', async () => {
+    await write('dir/old 中文.txt', 'a\nb\nc\nd\ne\nf\n');
+    await write('copy-source.txt', 'unique\ncopy\nsource\nlines\nhere\nend\n');
+    commit();
+    git('mv', 'dir/old 中文.txt', 'dir/new 中文.txt');
+    await appendFile(path.join(workspaceDir, 'dir/new 中文.txt'), 'renamed\n');
+    await appendFile(path.join(workspaceDir, 'copy-source.txt'), 'source-edit\n');
+    await write('copy 中文.txt', 'unique\ncopy\nsource\nlines\nhere\nend\ncopied\n');
+    git('add', '--', 'copy 中文.txt');
+    git('config', 'diff.renames', 'copies');
+    const { diffs } = await read();
+    expect(diffs).toHaveLength(3);
+    expect(diffs.find((entry) => entry.file === 'dir/new 中文.txt')).toMatchObject({
+      additions: 1,
+      deletions: 0,
+      status: 'renamed',
+      diff: expect.stringContaining('+renamed\n'),
+    });
+    expect(diffs.find((entry) => entry.file === 'copy 中文.txt')).toMatchObject({
+      additions: 1,
+      deletions: 0,
+      status: 'copied',
+      diff: expect.stringContaining('+copied\n'),
+    });
+    expect(diffs.find((entry) => entry.file === 'copy-source.txt')).toMatchObject({
+      additions: 1,
+      deletions: 0,
+      status: 'modified',
+      diff: expect.stringContaining('+source-edit\n'),
+    });
+  });
+});
+
+it('returns an empty diff for a clean workspace', async () => {
+  expect(await read()).toEqual({ diffs: [] });
+});
+
+it('prefers stored session/message diffs and falls back only when the selected record is absent', async () => {
+  await write('live.txt', 'live\n');
+  const fileChanges = [{ file: 'stored.txt', additions: 7, deletions: 2, diff: 'stored patch' }];
+  await diffStore.upsert({
+    sessionId: 'test-session',
+    turnId: 'test-turn',
+    changeSetId: 'test-change',
+    assistantMessageId: 'test-message',
+    workspaceDir,
+    capturedAtMs: Date.now(),
+    status: 'active',
+    fileChanges,
+  });
+  for (const messageId of [undefined, 'test-message']) {
+    expect(await read(messageId)).toEqual({ diffs: fileChanges, changeSetId: 'test-change' });
+  }
+  expect((await read('absent-message')).diffs).toEqual([
+    {
+      file: 'live.txt',
+      additions: 1,
+      deletions: 0,
+      status: 'added',
+      diff: expect.stringContaining('+live\n'),
+    },
+  ]);
+});
+
+it('associates patches without relying on color or path prefixes', async () => {
+  await write('中文.txt', 'first\n');
+  commit();
+  await appendFile(path.join(workspaceDir, '中文.txt'), 'added\n');
+  git('config', 'color.ui', 'always');
+  git('config', 'diff.noprefix', 'true');
+  expect((await read()).diffs).toEqual([
+    {
+      file: '中文.txt',
+      additions: 1,
+      deletions: 0,
+      status: 'modified',
+      diff: expect.stringContaining('+added\n'),
+    },
+  ]);
+});

+ 1 - 0
release/public-source.json

@@ -2637,6 +2637,7 @@
     "packages/local-runtime/test/unit/local-thread-goal-store.test.ts",
     "packages/local-runtime/test/unit/local-thread-goal-wiring.test.ts",
     "packages/local-runtime/test/unit/metrics-telemetry-privacy.test.ts",
+    "packages/local-runtime/test/unit/session-diff-fallback.test.ts",
     "packages/local-runtime/test/unit/thread-goal-kickoff-host.test.ts",
     "packages/local-runtime/test/unit/thread-goal-verifier-contract.test.ts",
     "packages/local-runtime/test/unit/thread-goal/contract.test.ts",

+ 2 - 1
test/vitest-suites.json

@@ -138,7 +138,8 @@
       "packages/tui/test/unit/tui/features/settings/hotkeys-picker.test.ts",
       "packages/tui/test/unit/incident-reporter-privacy.test.ts",
       "packages/config/test/config-file-permissions.test.ts",
-      "packages/agent-modules/context-manager/test/compaction-usage.test.ts"
+      "packages/agent-modules/context-manager/test/compaction-usage.test.ts",
+      "packages/local-runtime/test/unit/session-diff-fallback.test.ts"
     ],
     "status-contract": [
       "packages/tui/test/unit/tui-build-mode-contract.test.ts"