Skip to content

Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active

7.6 KB
Raw Blame
import { memo } from 'react';
import { cn } from '@librechat/client';
import type { ReactNode } from 'react';

const HUNK_HEADER = /^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/;

export interface DiffLine {
  type: 'add' | 'del' | 'context' | 'hunk';
  text: string;
  oldLine?: number;
  newLine?: number;
}

export interface ParsedDiff {
  lines: DiffLine[];
  additions: number;
  deletions: number;
  hasLineNumbers: boolean;
}

/**
 * Parses REAL unified-diff text (a tool's own output) into typed lines with
 * old/new line numbers when the hunk headers carry them. File headers and
 * `\ No newline` markers are dropped, since the window header already names
 * the file.
 *
 * Deliberately knows nothing about the args preview. That preview is built
 * from structured edits by `buildEditPreviewDiff`, so it never round-trips
 * through diff text: there are no synthetic separators to recognize, and
 * therefore no byte sequence a real changed line could be mistaken for. An
 * earlier version emitted `--- old_text` / `+++ new_text` separators and tried
 * to spot them here, which could not be made safe, because replacing a source
 * line `-- old_text` with `++ new_text` produces exactly those strings.
 */
export function parseUnifiedDiff(diff: string): ParsedDiff {
  const lines: DiffLine[] = [];
  let additions = 0;
  let deletions = 0;
  let hasLineNumbers = false;
  let oldLine: number | undefined;
  let newLine: number | undefined;
  let inHunk = false;

  for (const raw of diff.replace(/\n$/, '').split('\n')) {
    if (!inHunk && (raw.startsWith('--- ') || raw.startsWith('+++ '))) {
      continue;
    }
    if (raw.startsWith('\\')) {
      continue;
    }
    const hunk = HUNK_HEADER.exec(raw);
    if (hunk) {
      inHunk = true;
      oldLine = Number(hunk[1]);
      newLine = Number(hunk[2]);
      hasLineNumbers = true;
      lines.push({ type: 'hunk', text: raw });
      continue;
    }
    if (raw === '@@') {
      inHunk = true;
      oldLine = undefined;
      newLine = undefined;
      lines.push({ type: 'hunk', text: '' });
      continue;
    }
    if (raw.startsWith('+')) {
      additions += 1;
      lines.push({ type: 'add', text: raw.slice(1), newLine });
      newLine = newLine == null ? undefined : newLine + 1;
      continue;
    }
    if (raw.startsWith('-')) {
      deletions += 1;
      lines.push({ type: 'del', text: raw.slice(1), oldLine });
      oldLine = oldLine == null ? undefined : oldLine + 1;
      continue;
    }
    lines.push({
      type: 'context',
      text: raw.startsWith(' ') ? raw.slice(1) : raw,
      oldLine,
      newLine,
    });
    oldLine = oldLine == null ? undefined : oldLine + 1;
    newLine = newLine == null ? undefined : newLine + 1;
  }

  return { lines, additions, deletions, hasLineNumbers };
}

export interface TextEditPreview {
  oldText: string;
  newText: string;
}

/**
 * Rows one side of an edit contributes. An empty side means "nothing here",
 * not one blank line, and a trailing newline terminates the last line rather
 * than starting an empty one: plain `split('\n')` would render a blank row and
 * count it as a change, so a pure deletion (`new_text: ""`) claimed one
 * addition.
 */
const previewRows = (text: string): string[] => (text ? text.replace(/\n$/, '').split('\n') : []);

/**
 * Builds the diff for an `edit_file` args preview straight from the structured
 * edits, instead of formatting them into diff text for `parseUnifiedDiff` to
 * read back.
 *
 * That round trip is what made batched previews ambiguous: the separators it
 * needed between edits were byte-identical to a real changed line, since
 * deleting a source line `-- old_text` prefixes to exactly `--- old_text`. No
 * parser can tell those apart from position or bytes alone. Built here, each
 * edit boundary is structural and no separator is ever emitted.
 *
 * A boundary between edits becomes an empty `hunk` line, which `DiffView`
 * renders as its divider rule. There are no line numbers: args previews carry
 * the replacement text, never its position in the file.
 */
export function buildEditPreviewDiff(edits: TextEditPreview[]): ParsedDiff {
  const lines: DiffLine[] = [];
  let additions = 0;
  let deletions = 0;

  edits.forEach((edit, index) => {
    if (index > 0) {
      lines.push({ type: 'hunk', text: '' });
    }
    for (const text of previewRows(edit.oldText)) {
      deletions += 1;
      lines.push({ type: 'del', text });
    }
    for (const text of previewRows(edit.newText)) {
      additions += 1;
      lines.push({ type: 'add', text });
    }
  });

  return { lines, additions, deletions, hasLineNumbers: false };
}

/** One-way serialization for the copy button. Never parsed back, so it is free
 *  to be lossy about hunk boundaries. */
export function diffPreviewText(parsed: ParsedDiff): string {
  return parsed.lines
    .map((line) => (line.type === 'hunk' ? '' : `${LINE_MARKERS[line.type]}${line.text}`))
    .join('\n');
}

const LINE_MARKERS: Record<DiffLine['type'], string> = {
  add: '+',
  del: '-',
  context: '',
  hunk: '',
};

/** One number per row keeps the gutter compact: the old line for removals
 *  (it no longer exists in the new file) and the new line otherwise. */
function lineNumber(line: DiffLine): number | undefined {
  return line.type === 'del' ? line.oldLine : (line.newLine ?? line.oldLine);
}

interface DiffRowProps {
  type: DiffLine['type'];
  text: string;
  num?: number;
  hasLineNumbers: boolean;
}

/** Primitive props only: `parseUnifiedDiff` rebuilds every line object on each
 *  streamed delta, so memo has to compare values, not object identity. */
const DiffRow = memo(function DiffRow({ type, text, num, hasLineNumbers }: DiffRowProps) {
  if (type === 'hunk') {
    if (!text) {
      return <div className="border-border-light mx-3 my-1.5 border-t" />;
    }
    return <div className="text-text-tertiary text-2xs px-3 py-0.5 select-none">{text}</div>;
  }
  return (
    <div
      className={cn(
        'flex',
        type === 'add' && 'bg-status-success-subtle',
        type === 'del' && 'bg-status-error-subtle',
      )}
    >
      {hasLineNumbers && (
        <span className="text-text-tertiary text-2xs w-9 shrink-0 pe-1 text-end select-none">
          {num ?? ''}
        </span>
      )}
      <span
        className={cn(
          'shrink-0 text-center font-semibold select-none',
          hasLineNumbers ? 'w-5' : 'w-6',
          type === 'add' && 'text-status-success',
          type === 'del' && 'text-status-error',
        )}
      >
        {LINE_MARKERS[type]}
      </span>
      <span className="text-text-primary min-w-0 flex-1 pe-3 break-words whitespace-pre-wrap">
        {text || ' '}
      </span>
    </div>
  );
});

/** Index keys are safe: the parser walks the text top to bottom and the stream
 *  only appends, so a row's index, type and line numbers are stable once
 *  emitted. Only the trailing, still-growing line changes, and its props do too. */
export default function DiffView({ parsed }: { parsed: ParsedDiff }): ReactNode {
  const { lines, hasLineNumbers } = parsed;
  const firstContentIndex = lines.findIndex((line) => line.type !== 'hunk');

  return (
    <div
      data-testid="diff-view"
      dir="ltr"
      className="bg-surface-code max-h-[300px] overflow-y-auto py-2 font-mono text-xs leading-5"
    >
      {lines.map((line, index) => {
        if (line.type === 'hunk' && (index < firstContentIndex || firstContentIndex === -1)) {
          return null;
        }
        return (
          <DiffRow
            key={index}
            type={line.type}
            text={line.text}
            num={lineNumber(line)}
            hasLineNumbers={hasLineNumbers}
          />
        );
      })}
    </div>
  );
}