Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 57 additions & 0 deletions client/e2e/changes.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,4 +61,61 @@ test.describe("Changes view on the acceptance repo", () => {
await page.screenshot({ path: path.join(SHOTS, "changes-net.png") });
expect(errors).toEqual([]);
});

test("deleted code opens at the base revision without disturbing its diff", async ({ page }) => {
const base = execFileSync("git", ["rev-parse", "main"], { cwd: repo, encoding: "utf8" }).trim();
const id = "src/worker.ts::legacyCleanup";
await page.goto(`/?${new URLSearchParams({ repo, view: "changes" })}`);
await lensReady(page);
await chunk(page, id).click();
const inspector = page.locator(`[data-chunk-inspector="${id}"]`);
await inspector.locator('[data-action="open-diff"]').click();
const diff = page.locator("[data-hunk-diff]");
await expect(diff).toContainText("legacyCleanup");

const fetched = page.waitForRequest((r) => {
const url = new URL(r.url());
return url.pathname === "/api/files/content" && url.searchParams.get("ref") === base;
});
await inspector.locator('[data-action="open-code"]').click();
expect(new URL((await fetched).url()).searchParams.get("path")).toBe(path.join(repo, "src/worker.ts"));
const code = page.getByRole("dialog");
await expect(code.locator('[data-source-side="base"]')).toHaveAttribute("title", base);
await expect(code.locator(".code-modal-content")).toContainText("export function legacyCleanup");
await expect(code.getByRole("link", { name: "Open in VS Code" })).toHaveCount(0);
await page.keyboard.press("Escape");
await expect(code).toHaveCount(0);
await expect(chunk(page, id)).toHaveAttribute("data-selected", "");
await expect(diff).toContainText("legacyCleanup");

// An unavailable Git object must not fall back to the checked-out file.
const requests: string[] = [];
await page.route("**/api/files/content?**", async (route) => {
requests.push(new URL(route.request().url()).searchParams.get("ref") ?? "disk");
await route.fulfill({ status: 404, body: "Missing Git object" });
});
await inspector.locator('[data-action="open-code"]').click();
await expect(code).toContainText(`Source unavailable at base ${base.slice(0, 7)}`);
await expect(code.locator(".code-modal-content")).toHaveCount(0);
expect(requests).toEqual([base]);
});

test("Open code follows a commit diff opened from the chunk's touch strip", async ({ page }) => {
const git = (...args: string[]) => execFileSync("git", args, { cwd: repo, encoding: "utf8" }).trim();
const removedAt = git("log", "-1", "--format=%H", "--grep=worker: remove legacyCleanup");
const previous = git("rev-parse", `${removedAt}^`);
expect(previous).not.toBe(git("rev-parse", "main"));
const id = "src/worker.ts::legacyCleanup";
await page.goto(`/?${new URLSearchParams({ repo, view: "changes" })}`);
await lensReady(page);
await chunk(page, id).click();
const inspector = page.locator(`[data-chunk-inspector="${id}"]`);
await inspector.locator(`[data-touch="${removedAt}"]`).click();
const diff = page.locator("[data-hunk-diff]");
await expect(diff).toContainText(removedAt.slice(0, 7));
await inspector.locator('[data-action="open-code"]').click();
const code = page.getByRole("dialog");
await expect(code.locator('[data-source-side="base"]')).toHaveAttribute("title", previous);
await expect(code.locator(".code-modal-content")).toContainText("export function legacyCleanup");
});
});
62 changes: 56 additions & 6 deletions client/src/changelens/ChangeLensView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,12 @@
// It owns the fetches and the URL state; the map and the panel pieces get
// everything through props.

import { createEffect, createMemo, createSignal, For, on, onCleanup, onMount, Show, untrack, type JSX } from "solid-js";
import { createEffect, createMemo, createSignal, For, lazy, on, onCleanup, onMount, Show, untrack, type JSX } from "solid-js";
import { ArrowRight } from "lucide-solid";
import { Button } from "../components/ui/Button";
import { atFromTreePath, baseName, splitAt } from "../navigation/location";
import { go, location } from "../navigation/store";
import { findTreeNodeByPath } from "../utils/dataProcessing";
import { ViewTools } from "../viz/viewToolbar";
import { fetchChangeLens, fetchHunk, LensError, type LensQuery } from "./api";
import BranchNotice, { historyApplies, isOffMain } from "./BranchNotice";
Expand All @@ -15,12 +16,13 @@ import { inScope, type RepoNode } from "./layout";
import Legend from "./Legend";
import LensMap from "./LensMap";
import { ChunkInspector, CommitRail, HunkDiff, ReviewBuckets } from "./panel";
import type { ChangeLensPayload, LensChunk, LensHunkDiff } from "./types";
import type { ChangeLensPayload, LensChunk, LensHunkDiff, LensSourceLocation } from "./types";
import { lens, setLens } from "./urlState";
import WindowBar from "./WindowBar";

/** Below this width the panel moves under the map. */
const NARROW_PX = 900;
const CodeModal = lazy(() => import("../components/CodeModal/CodeModal"));

interface ScanNode {
name: string;
Expand Down Expand Up @@ -76,8 +78,6 @@ export default function ChangeLensView(props: {
data: ScanNode | null;
/** Absolute path of the scan root. */
rootPath: string;
/** Open a file or scope in the code viewer. */
onOpenAt: (at: string, line?: number) => void;
}) {
const query = createMemo<LensQuery | null>(
() => {
Expand Down Expand Up @@ -188,6 +188,35 @@ export default function ChangeLensView(props: {
);
/** The selected commit's step when that commit changed the chunk, else the whole window. */
const stepOf = (chunk: string) => (commit()?.chunkIds.includes(chunk) ? commit()!.sha : undefined);
const [source, setSource] = createSignal<LensSourceLocation | null>(null);
const [sourceError, setSourceError] = createSignal<string>();
const [sourceLoading, setSourceLoading] = createSignal(false);
let sourceRequest = 0;
createEffect(on([query, selected, commit, hunk], () => {
sourceRequest++;
setSource(null);
setSourceError(undefined);
setSourceLoading(false);
}));
const openCode = async (chunk: LensChunk) => {
const q = query();
if (!q || loading()) return;
const id = ++sourceRequest;
setSourceError(undefined);
setSourceLoading(true);
try {
const active = hunk();
const step = active?.chunk === chunk.id ? active.commit : stepOf(chunk.id);
const target = (await fetchHunk(q, chunk.id, step)).source;
if (id !== sourceRequest) return;
if (target) setSource(target);
else setSourceError("No source is available for this chunk at the selected revisions.");
} catch (e) {
if (id === sourceRequest) setSourceError(e instanceof Error ? e.message : String(e));
} finally {
if (id === sourceRequest) setSourceLoading(false);
}
};
const openHunk = (chunk: string, sha?: string) => {
setHunk({ chunk, commit: sha ?? stepOf(chunk) });
if (lens().chunk !== chunk) setLens({ chunk });
Expand Down Expand Up @@ -401,7 +430,7 @@ export default function ChangeLensView(props: {
<Legend lens={{ metric: lens().metric, color: lens().color }} layout={lens().layout} />
<Show when={hunk()}>
<div class="h-[50%] min-h-[220px] shrink-0 border-t border-[var(--plc-border)]" data-lens-hunk>
<HunkDiff diff={diff()} loading={diffLoading()} error={diffError()} onClose={() => setHunk(null)} />
<HunkDiff diff={diff()} loading={diffLoading()} error={diffError()} ignoreEscape={Boolean(source())} onClose={() => setHunk(null)} />
</div>
</Show>
</div>
Expand All @@ -414,12 +443,33 @@ export default function ChangeLensView(props: {
<ReviewBuckets payload={p()} selected={lens().chunk} onSelect={(chunk) => setLens({ chunk })} />
</div>
<div class="min-h-0 flex-1 overflow-auto">
<ChunkInspector payload={p()} chunk={selected()} onOpenHunk={openHunk} onOpenCode={(chunk) => props.onOpenAt(scanPath(base(), chunk.path), chunk.startLine)} />
<ChunkInspector payload={p()} chunk={selected()} onOpenHunk={openHunk} onOpenCode={openCode} sourceBusy={sourceLoading() || loading()} />
<Show when={sourceError()}>
<p role="alert" class="px-3 pb-3 text-[12px] text-[var(--plc-warning)]">{sourceError()}</p>
</Show>
</div>
</aside>
</div>
)}
</Show>
<Show when={source()} keyed>
{(target) => {
const filePath = `${target.repoRoot.replace(/\/$/, "")}/${target.path}`;
return (
<CodeModal
isOpen={true}
filePath={filePath}
rootPath={target.revision ? target.repoRoot : props.rootPath}
gitRef={target.revision}
revisionSide={target.side}
startLine={target.startLine}
endLine={target.endLine}
fileNode={target.revision ? null : findTreeNodeByPath(props.data, filePath)}
onClose={() => setSource(null)}
/>
);
}}
</Show>
</div>
);
}
3 changes: 2 additions & 1 deletion client/src/changelens/panel/ChunkInspector.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,7 @@ export function ChunkInspector(props: {
chunk: LensChunk | null;
onOpenHunk: (chunkId: string, commit?: string) => void;
onOpenCode: (chunk: LensChunk) => void;
sourceBusy?: boolean;
}) {
// Bars scale against the largest |Δ| of each metric across the window.
const maxAbs = createMemo(() => {
Expand Down Expand Up @@ -193,7 +194,7 @@ export function ChunkInspector(props: {
<Button size="sm" data-action="open-diff" onClick={() => props.onOpenHunk(c().id)}>
Open diff
</Button>
<Button size="sm" data-action="open-code" onClick={() => props.onOpenCode(c())}>
<Button size="sm" data-action="open-code" disabled={props.sourceBusy} onClick={() => props.onOpenCode(c())}>
Open code
</Button>
</div>
Expand Down
4 changes: 2 additions & 2 deletions client/src/changelens/panel/HunkDiff.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ function Line(props: { line: DiffLine }) {
}

/** The diff text behind one chunk, with line numbers and word highlights. Esc closes it. */
export function HunkDiff(props: { diff: LensHunkDiff | null; loading: boolean; error?: string; onClose: () => void }) {
export function HunkDiff(props: { diff: LensHunkDiff | null; loading: boolean; error?: string; ignoreEscape?: boolean; onClose: () => void }) {
const hunks = createMemo(() => (props.diff ? parseUnifiedDiff(props.diff.diff) : []));
const counts = createMemo(() => {
let added = 0;
Expand All @@ -68,7 +68,7 @@ export function HunkDiff(props: { diff: LensHunkDiff | null; loading: boolean; e

onMount(() => {
const onKey = (e: KeyboardEvent) => {
if (e.key === "Escape" && !e.defaultPrevented) props.onClose();
if (e.key === "Escape" && !e.defaultPrevented && !props.ignoreEscape) props.onClose();
};
window.addEventListener("keydown", onKey);
onCleanup(() => window.removeEventListener("keydown", onKey));
Expand Down
12 changes: 12 additions & 0 deletions client/src/changelens/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,16 @@ export interface ChangeLensPayload {
}

/** `GET /api/change-lens/hunk`: the diff text behind one chunk. */
export interface LensSourceLocation {
repoRoot: string;
path: string;
side: "base" | "head";
/** Null only for a working-tree file. */
revision: string | null;
startLine: number;
endLine: number;
}

export interface LensHunkDiff {
chunkId: string;
path: string;
Expand All @@ -216,4 +226,6 @@ export interface LensHunkDiff {
diff: string;
/** Set when the diff was clipped. */
truncated: boolean;
/** The side containing the chunk, or null when neither side has source. */
source?: LensSourceLocation | null;
}
16 changes: 13 additions & 3 deletions client/src/components/CodeModal/CodeModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,10 @@ interface CodeModalProps {
onClose: () => void;
fileNode?: any;
scopeNode?: any;
/** Read the file from this git commit (compare mode) instead of the disk. */
/** Read the file from this Git revision instead of the disk. */
gitRef?: string | null;
/** The side selected in Changes, shown beside the source path. */
revisionSide?: "base" | "head";
/** The scanned root, so the header can show a repo-relative path. */
rootPath?: string;
}
Expand Down Expand Up @@ -124,7 +126,7 @@ export default function CodeModal(props: CodeModalProps) {
eLine >= sLine;
setLineFilterEnabled(hasRange);

if (guessLangFromPath(props.filePath) === "md") {
if (guessLangFromPath(props.filePath) === "md" && !props.revisionSide) {
setViewMode("preview");
} else {
setViewMode("code");
Expand Down Expand Up @@ -427,6 +429,8 @@ export default function CodeModal(props: CodeModalProps) {
filePath={props.filePath!}
rootPath={props.rootPath}
baseName={baseName()}
gitRef={props.gitRef}
revisionSide={props.revisionSide}
onClose={props.onClose}
rawCode={rawCode}
hasLineRange={hasLineRange}
Expand Down Expand Up @@ -501,7 +505,13 @@ export default function CodeModal(props: CodeModalProps) {
fallback={
<CodePane
loading={loading}
error={() => error() ?? highlightError()}
error={() => {
const failure = error();
if (failure && props.gitRef && props.revisionSide) {
return `Source unavailable at ${props.revisionSide} ${props.gitRef.slice(0, 7)}. ${failure}`;
}
return failure ?? highlightError();
}}
highlightedHtml={highlightedHtml}
filePath={() => props.filePath}
baseName={baseName()}
Expand Down
11 changes: 11 additions & 0 deletions client/src/components/CodeModal/CodeModalHeader.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,8 @@ export function CodeModalHeader(props: {
/** The scanned root; the path shows relative to it. */
rootPath?: string;
baseName: string;
gitRef?: string | null;
revisionSide?: "base" | "head";
onClose: () => void;
rawCode: () => string;

Expand Down Expand Up @@ -100,6 +102,13 @@ export function CodeModalHeader(props: {
>
<span dir="ltr">{dir()}</span>
</span>
<Show when={props.revisionSide}>
{(side) => (
<span class="shrink-0 rounded bg-[var(--plc-surface-muted)] px-1.5 text-[11px]" data-source-side={side()} title={props.gitRef ?? "Working tree"}>
{side() === "base" ? "Base" : "Head"} · {props.gitRef?.slice(0, 7) ?? "Working tree"}
</span>
)}
</Show>
</div>

<Show when={props.isMarkdown()}>
Expand Down Expand Up @@ -184,6 +193,7 @@ export function CodeModalHeader(props: {
icon={<Copy size={15} aria-hidden="true" />}
onClick={() => navigator.clipboard.writeText(props.rawCode())}
/>
<Show when={!props.gitRef}>
<a
href={`vscode://file/${props.filePath}`}
target="_blank"
Expand All @@ -193,6 +203,7 @@ export function CodeModalHeader(props: {
>
<ExternalLink size={15} aria-hidden="true" />
</a>
</Show>
<IconButton label="Close (Esc)" onClick={props.onClose}>
<X size={16} aria-hidden="true" />
</IconButton>
Expand Down
2 changes: 1 addition & 1 deletion client/src/components/CodeModal/MetricsSidebar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ export function MetricsSidebar(props: {
fallback={
<EmptyState
title="No metrics available"
description="This file does not have metrics to inspect."
description={props.gitRef ? "Current-tree metrics and flow analysis are not shown for historical source." : "This file does not have metrics to inspect."}
class="h-auto py-6 text-xs"
/>
}
Expand Down
2 changes: 1 addition & 1 deletion client/src/components/Treemap.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -269,7 +269,7 @@ export default function Treemap(props: TreemapProps) {
/>
</Show>
<Show when={showChanges()}>
<ChangeLensView data={props.data} rootPath={props.rootPath} onOpenAt={props.onOpenAt} />
<ChangeLensView data={props.data} rootPath={props.rootPath} />
</Show>
</Suspense>
<Show when={!covered() && layoutRoot()}>
Expand Down
2 changes: 1 addition & 1 deletion docs/CODE_MAP.md
Original file line number Diff line number Diff line change
Expand Up @@ -213,7 +213,7 @@ Which code chunks a branch or a time window edited. User guide: `site/src/docs/p
| Hunks per commit and base → head (`git diff -U0`), renames | `server/app/services/changelens/hunks.py` |
| Blob parsing with the scan's analyzers (one parse per side, by blob sha), Markdown headings, generated/vendored files | `server/app/services/changelens/blobs.py` |
| Chunks: hunk → innermost named scope, file/heading/range chunks, base ↔ head pairing (exact, renamed-file, moved, uncertain), touches, reverted, metrics before → after, review buckets (`COMPLEX_AT`) | `server/app/services/changelens/chunks.py` |
| Chunk-limited unified diff for one chunk | `server/app/services/changelens/textdiff.py`, `service.py` (`hunk_diff`) |
| Chunk-limited unified diff and revision-bound source location for one chunk | `server/app/services/changelens/textdiff.py`, `service.py` (`hunk_diff`); `client/src/changelens/ChangeLensView.tsx` opens that side in `CodeModal` |
| Acceptance repo (every case of the issue) and the client's fixture payloads | `server/tests/fixtures/change_lens_repo.py` (`--write-payloads` writes `client/src/changelens/fixture*.json`), `server/tests/test_change_lens.py` |
| The view: fetches, URL state (`cw`, `cm`, `cl`, `cc`, `cs`, `clens`, `chist`, custom refs), selection kept across results, repo ↔ scan paths | `client/src/changelens/ChangeLensView.tsx`, `api.ts`, `urlState.ts` |
| Toolbar: window presets and Custom form, Touched/Net, Only edits/In repo, color metric with Now/Δ | `client/src/changelens/WindowBar.tsx` |
Expand Down
10 changes: 10 additions & 0 deletions server/app/services/changelens/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,15 @@ class ChangeLensPayload(LensModel):
metric_ids: list[str]


class LensSourceLocation(LensModel):
repo_root: str
path: str
side: Literal["base", "head"]
revision: Optional[str] # null only for a working-tree file
start_line: int
end_line: int


class LensHunkDiff(LensModel):
chunk_id: str
path: str
Expand All @@ -170,6 +179,7 @@ class LensHunkDiff(LensModel):
to: str
diff: str
truncated: bool
source: Optional[LensSourceLocation] = None

model_config = ConfigDict(
alias_generator=lambda name: "from" if name == "from_" else to_camel(name), populate_by_name=True
Expand Down
Loading
Loading