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
66 changes: 66 additions & 0 deletions client/src/changelens/BranchNotice.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
// Where HEAD stands against the default branch, drawn at the start of the
// status row when HEAD is off it (or behind it). A time window also gets a
// toggle between HEAD's history and the default branch's.

import { For, Show } from "solid-js";
import { GitBranch } from "lucide-solid";
import type { LensBranch, LensHistory, LensSelection } from "./types";
import type { LensState } from "./urlState";

/** HEAD is on another branch, or on the default branch but behind its newest ref. */
export const isOffMain = (b: LensBranch | null): b is LensBranch => !!b && (!b.onDefault || b.behind > 0);

/** History picks the ref of a time window; branch and revision windows name their own. */
export const historyApplies = (s: Pick<LensState, "window" | "base" | "head">) => s.window === "24h" || s.window === "7d" || (s.window === "custom" && !s.base && !s.head);

const fmt = (n: number) => n.toLocaleString("en-US");

export default function BranchNotice(props: { selection: LensSelection; toggle: boolean; onHistory: (h: LensHistory) => void }) {
const b = () => props.selection.branch as LensBranch;
const name = () => b().name ?? "Detached HEAD";
const counts = () => {
const parts = [];
if (b().behind) parts.push(`${fmt(b().behind)} behind`);
if (b().ahead) parts.push(`${fmt(b().ahead)} ahead of`);
return parts.length ? `${parts.join(", ")} ${b().defaultRef}` : `level with ${b().defaultRef}`;
};
const options = (): { id: LensHistory; label: string; title: string }[] => [
{ id: "head", label: "Branch", title: `Read the commits on ${name()}` },
{ id: "main", label: b().defaultRef, title: `Read the commits on ${b().defaultRef}, without checking anything out` },
];
return (
<span class="flex min-w-0 shrink items-center gap-1.5" data-lens-branch data-lens-history={props.selection.history}>
<GitBranch size={12} class="shrink-0 text-[var(--plc-warning)]" aria-hidden="true" />
<span class="plc-data-sm min-w-0 max-w-[20rem] truncate text-[12px] text-[var(--plc-on-surface)]" title={name()}>
{name()}
</span>
<span class="shrink-0 tabular-nums" data-lens-behind={b().behind}>
{counts()}
</span>
<Show when={props.toggle}>
<span class="ml-1 shrink-0 text-[var(--plc-on-subtle)]">History</span>
<span role="radiogroup" aria-label="History" class="flex h-[22px] shrink-0 rounded border border-[var(--plc-border)] bg-[var(--plc-surface-muted)]">
<For each={options()}>
{(o) => (
<button
type="button"
role="radio"
aria-checked={props.selection.history === o.id}
title={o.title}
data-lens-history-option={o.id}
class="plc-data-sm max-w-[12rem] truncate rounded-[3px] px-1.5 text-[12px] transition-colors duration-150"
classList={{
"bg-[var(--plc-surface)] text-[var(--plc-on-surface)] shadow-sm": props.selection.history === o.id,
"text-[var(--plc-on-muted)] hover:text-[var(--plc-on-surface)]": props.selection.history !== o.id,
}}
onClick={() => props.selection.history !== o.id && props.onHistory(o.id)}
>
{o.label}
</button>
)}
</For>
</span>
</Show>
</span>
);
}
29 changes: 27 additions & 2 deletions client/src/changelens/ChangeLensView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { atFromTreePath, baseName, splitAt } from "../navigation/location";
import { go, location } from "../navigation/store";
import { ViewTools } from "../viz/viewToolbar";
import { fetchChangeLens, fetchHunk, LensError, type LensQuery } from "./api";
import BranchNotice, { historyApplies, isOffMain } from "./BranchNotice";
import { plural, timeLimits } from "./labels";
import { inScope, type RepoNode } from "./layout";
import Legend from "./Legend";
Expand Down Expand Up @@ -81,7 +82,7 @@ export default function ChangeLensView(props: {
const query = createMemo<LensQuery | null>(
() => {
const s = lens();
return props.rootPath ? { path: props.rootPath, window: s.window, mode: s.mode, base: s.base, head: s.head, since: s.since, until: s.until } : null;
return props.rootPath ? { path: props.rootPath, window: s.window, mode: s.mode, base: s.base, head: s.head, since: s.since, until: s.until, history: historyApplies(s) ? s.history : null } : null;
},
null,
{ equals: (a, b) => JSON.stringify(a) === JSON.stringify(b) }
Expand Down Expand Up @@ -225,6 +226,17 @@ export default function ChangeLensView(props: {
onCleanup(() => observer.disconnect());
});

/** For an empty window off main: the button that reads main's history instead, when main has commits there. */
const mainOffer = createMemo(() => {
const p = payload();
const b = p?.selection.branch ?? null;
if (!p || p.chunks.length || !isOffMain(b) || p.selection.history !== "head" || !b.defaultCommits) return null;
const commits = plural(b.defaultCommits, "commit");
return p.selection.window === "branch"
? { label: `Show ${b.defaultRef}'s last 7 days (${commits})`, patch: { window: "7d" as const, history: "main" as const, commit: null } }
: { label: `Show ${b.defaultRef}'s history (${commits})`, patch: { history: "main" as const, commit: null } };
});

const state = () => (error() ? (error()!.status === 409 ? "not-git" : "error") : !payload() ? "loading" : !payload()!.chunks.length ? "empty" : loading() ? "refreshing" : "ready");

/** Root › scope › the selected chunk's folders, file and name. Every folder and file zooms. */
Expand All @@ -248,10 +260,13 @@ export default function ChangeLensView(props: {
</ViewTools>

{/* What the window resolved to. One fixed-height row at rest; notes wrap under it. */}
<div class="relative flex min-h-[28px] shrink-0 flex-wrap items-center gap-x-3 gap-y-0.5 border-b border-[var(--plc-border)] px-3 py-1 text-[12px] text-[var(--plc-on-muted)]" data-lens-status>
<div class="relative flex min-h-[28px] shrink-0 flex-wrap items-center gap-x-3 gap-y-0.5 border-b border-[var(--plc-border)] px-3 py-0.5 text-[12px] text-[var(--plc-on-muted)]" data-lens-status>
<Show when={payload()} fallback={<span class="text-[var(--plc-on-subtle)]">{loading() ? "Reading the history of this window…" : " "}</span>}>
{(p) => (
<>
<Show when={isOffMain(p().selection.branch)}>
<BranchNotice selection={p().selection} toggle={historyApplies(lens())} onHistory={(history) => setLens({ history, commit: null })} />
</Show>
<span class="plc-data-sm flex shrink-0 items-center gap-1.5 text-[12px] font-semibold text-[var(--plc-on-surface)]" title={`${p().selection.base.ref} → ${p().selection.head.ref}, history of ${p().selection.ref}`}>
{p().selection.base.label}
<ArrowRight size={12} class="text-[var(--plc-on-subtle)]" aria-label="to" />
Expand Down Expand Up @@ -297,6 +312,16 @@ export default function ChangeLensView(props: {
<Show when={state() === "empty"}>
<Message state="empty" title="No edits in this window">
<For each={payload()!.selection.notes}>{(note) => <p>{note}</p>}</For>
<Show when={mainOffer()}>
{(offer) => (
<>
<p class="mt-1">This checkout is not on {payload()!.selection.branch!.default}, so its own history misses the work that landed there.</p>
<Button class="mt-2" variant="primary" data-lens-main-offer onClick={() => setLens(offer().patch)}>
{offer().label}
</Button>
</>
)}
</Show>
<p class="mt-1">Pick another window in the toolbar: 7 days reaches further back, and Custom takes any two revisions.</p>
</Message>
</Show>
Expand Down
5 changes: 4 additions & 1 deletion client/src/changelens/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,9 @@
// The view never sends `ref` or `worktree`: it reads the checked-out branch
// (HEAD) and includes uncommitted edits, which is what "after a coding
// session" means. Custom windows pick other revisions through base and head.
// `history: main` makes a time window read the default branch instead of HEAD.

import type { ChangeLensPayload, LensHunkDiff, LensMode, LensWindow } from "./types";
import type { ChangeLensPayload, LensHistory, LensHunkDiff, LensMode, LensWindow } from "./types";

export interface LensQuery {
/** Absolute path of the scan root. */
Expand All @@ -15,6 +16,7 @@ export interface LensQuery {
head?: string;
since?: string;
until?: string;
history?: LensHistory | null;
}

/** A failed request. Status 409 means the folder is not a git repo. */
Expand All @@ -28,6 +30,7 @@ export class LensError extends Error {

function params(q: LensQuery): URLSearchParams {
const p = new URLSearchParams({ path: q.path, window: q.window, mode: q.mode });
if (q.history) p.set("history", q.history);
if (q.window === "custom") {
if (q.base) p.set("base", q.base);
if (q.head) p.set("head", q.head);
Expand Down
10 changes: 10 additions & 0 deletions client/src/changelens/fixture.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,16 @@
"window": "branch",
"mode": "touched",
"ref": "HEAD",
"history": "head",
"branch": {
"name": "feature",
"default": "main",
"defaultRef": "main",
"onDefault": false,
"ahead": 10,
"behind": 0,
"defaultCommits": null
},
"base": {
"ref": "merge-base(main, feature)",
"sha": "97e5cf7df943e4232f3d2efcdd499dd7d0a70d63",
Expand Down
10 changes: 10 additions & 0 deletions client/src/changelens/fixture.net.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,16 @@
"window": "branch",
"mode": "net",
"ref": "HEAD",
"history": "head",
"branch": {
"name": "feature",
"default": "main",
"defaultRef": "main",
"onDefault": false,
"ahead": 10,
"behind": 0,
"defaultCommits": null
},
"base": {
"ref": "merge-base(main, feature)",
"sha": "97e5cf7df943e4232f3d2efcdd499dd7d0a70d63",
Expand Down
2 changes: 2 additions & 0 deletions client/src/changelens/panel/sample.ts
Original file line number Diff line number Diff line change
Expand Up @@ -391,6 +391,8 @@ export const samplePayload: ChangeLensPayload = {
window: "branch",
mode: "touched",
ref: "HEAD",
history: "head",
branch: null,
base: { ref: "merge-base(main, HEAD)", sha: sha("3f9a"), label: "main @ 3f9a3f9", date: "2026-11-17T14:02:00Z" },
head: { ref: WORKTREE, sha: null, label: "Working tree", date: null },
since: null,
Expand Down
23 changes: 23 additions & 0 deletions client/src/changelens/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
export type LensWindow = "branch" | "24h" | "7d" | "custom";
/** touched: union of chunks changed by the window's commits. net: base snapshot against head snapshot. */
export type LensMode = "touched" | "net";
/** Whose history a time window reads: the checked-out HEAD or the default branch. */
export type LensHistory = "head" | "main";

/** The literal head and commit id of uncommitted work. */
export const WORKTREE = "WORKTREE";
Expand All @@ -21,11 +23,32 @@ export interface LensEndpoint {
date: string | null;
}

/** Where HEAD stands against the default branch. */
export interface LensBranch {
/** The checked-out branch; null for a detached HEAD. */
name: string | null;
/** The default branch's name, e.g. `main`. */
default: string;
/** What main history reads: `origin/main` unless local `main` is ahead of it. */
defaultRef: string;
onDefault: boolean;
/** Commits on HEAD that `defaultRef` does not hold. */
ahead: number;
/** Commits on `defaultRef` that HEAD does not hold. */
behind: number;
/** Only for an empty HEAD window off the default branch: commits on `defaultRef` in the same time span (the last 7 days for the branch window). */
defaultCommits: number | null;
}

export interface LensSelection {
window: LensWindow;
mode: LensMode;
/** The branch or revision whose first-parent history was read. */
ref: string;
/** `main` when a time window read the default branch instead of HEAD: asked for, or HEAD had no commits in it. */
history: LensHistory;
/** Null when no default branch was found. */
branch: LensBranch | null;
base: LensEndpoint;
head: LensEndpoint;
/** Time limits of a time window (ISO 8601); null for `branch` and for ref-only custom ranges. */
Expand Down
8 changes: 7 additions & 1 deletion client/src/changelens/urlState.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,11 @@
// cs selected chunk id
// cbase, chead, csince, cuntil the custom window
// clens color: `<metric id>.now` or `<metric id>.delta`
// chist history of a time window: head | main (unset: the server picks)

import { createMemo } from "solid-js";
import { go, location, replace } from "../navigation/store";
import type { LensMode, LensWindow } from "./types";
import type { LensHistory, LensMode, LensWindow } from "./types";

export type LensLayout = "edits" | "repo";
export type ColorMode = "now" | "delta";
Expand All @@ -28,6 +29,8 @@ export interface LensState {
until: string;
metric: string;
color: ColorMode;
/** Null: HEAD, or main when HEAD is off it and empty in the window. */
history: LensHistory | null;
}

export const DEFAULT_LENS: LensState = {
Expand All @@ -42,6 +45,7 @@ export const DEFAULT_LENS: LensState = {
until: "",
metric: "complexity",
color: "delta",
history: null,
};

const WINDOWS: readonly LensWindow[] = ["branch", "24h", "7d", "custom"];
Expand All @@ -65,6 +69,7 @@ export function parseLens(changes: string | undefined): LensState {
until: custom ? (p.get("cuntil") ?? "") : "",
metric: dot > 0 ? lens.slice(0, dot) : DEFAULT_LENS.metric,
color: dot > 0 && (color === "now" || color === "delta") ? color : DEFAULT_LENS.color,
history: p.get("chist") === "head" ? "head" : p.get("chist") === "main" ? "main" : null,
};
}

Expand All @@ -82,6 +87,7 @@ export function serializeLens(s: LensState): string {
if (s.since) p.set("csince", s.since);
if (s.until) p.set("cuntil", s.until);
}
if (s.history) p.set("chist", s.history);
if (s.metric !== DEFAULT_LENS.metric || s.color !== DEFAULT_LENS.color) p.set("clens", `${s.metric}.${s.color}`);
return p.toString();
}
Expand Down
2 changes: 1 addition & 1 deletion client/src/navigation/location.ts
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ const LINKS_PARAM = "links";
const SYMBOLS_PARAM = "symbols";
const TO_PARAM = "to";
/** The Changes view's parameters, in the order `changes` keeps them. */
export const CHANGES_PARAMS = ["cw", "cm", "cl", "cc", "cs", "cbase", "chead", "csince", "cuntil", "clens"] as const;
export const CHANGES_PARAMS = ["cw", "cm", "cl", "cc", "cs", "cbase", "chead", "csince", "cuntil", "clens", "chist"] as const;
/** Pre-location graph focus parameter. Read as an alias of `at` + graph view. */
const LEGACY_FOCUS_PARAM = "depFocus";

Expand Down
5 changes: 3 additions & 2 deletions docs/CODE_MAP.md
Original file line number Diff line number Diff line change
Expand Up @@ -209,14 +209,15 @@ Which code chunks a branch or a time window edited. User guide: `site/src/docs/p
| Feature | Where |
| --- | --- |
| `srcly changes [path]` (Markdown, `--json`) | `server/app/run.py` → `server/app/services/changelens/service.py` (`build_payload`, `render_markdown`) |
| Window resolution: first-parent history of `ref`, branch base (merge base, or the upstream tip on the default branch), 24h/7d/custom, 200-commit cap, shallow clones, working tree entry, the scan root's `scope` inside the repo | `server/app/services/changelens/window.py` (`resolve`) |
| Window resolution: first-parent history of `ref`, branch base (merge base, or the upstream tip on the default branch), 24h/7d/custom, 200-commit cap, shallow clones, working tree entry, the scan root's `scope` inside the repo; off the default branch: ahead/behind and main history for time windows (`history`, `Branch`) | `server/app/services/changelens/window.py` (`resolve`, `_branch`) |
| 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`) |
| 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`, custom refs), selection kept across results, repo ↔ scan paths | `client/src/changelens/ChangeLensView.tsx`, `api.ts`, `urlState.ts` |
| 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` |
| Off-main notice in the status row: branch, behind/ahead of the default ref, Branch/origin/main history toggle (`chist`) | `client/src/changelens/BranchNotice.tsx` |
| Maps: Only edits packing (floored area, pooled small chunks, collapse), In repo bands, tile states and the delta scale, legend | `client/src/changelens/LensMap.tsx`, `layout.ts`, `colors.ts`, `labels.ts`, `Legend.tsx` |
| Review panel (props only): `ReviewBuckets`, `ChunkInspector`, `HunkDiff`, `CommitRail`; dev harness `client/panel-harness.html` | `client/src/changelens/panel/` |
| Browser smoke on the acceptance repo | `client/e2e/changes.spec.ts` |
Expand Down
9 changes: 6 additions & 3 deletions server/app/routers/changelens.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,9 @@ def _params(
since: Optional[str] = None,
until: Optional[str] = None,
worktree: Optional[bool] = None,
history: Optional[Literal["head", "main"]] = None,
) -> Params:
return Params(window, mode, ref, base or None, head or None, since or None, until or None, worktree)
return Params(window, mode, ref, base or None, head or None, since or None, until or None, worktree, history)


def _folder(path: str) -> Path:
Expand All @@ -50,9 +51,10 @@ def get_change_lens(
since: Optional[str] = None,
until: Optional[str] = None,
worktree: Optional[bool] = None,
history: Optional[Literal["head", "main"]] = None,
):
try:
return service.build_payload(_folder(path), _params(window, mode, ref, base, head, since, until, worktree))
return service.build_payload(_folder(path), _params(window, mode, ref, base, head, since, until, worktree, history))
except LensError as exc:
raise HTTPException(status_code=exc.status, detail=str(exc)) from exc

Expand All @@ -70,10 +72,11 @@ def get_change_lens_hunk(
since: Optional[str] = None,
until: Optional[str] = None,
worktree: Optional[bool] = None,
history: Optional[Literal["head", "main"]] = None,
):
try:
return service.hunk_diff(
_folder(path), _params(window, mode, ref, base, head, since, until, worktree), chunk, commit or None
_folder(path), _params(window, mode, ref, base, head, since, until, worktree, history), chunk, commit or None
)
except LensError as exc:
raise HTTPException(status_code=exc.status, detail=str(exc)) from exc
13 changes: 13 additions & 0 deletions server/app/services/changelens/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

LensWindow = Literal["branch", "24h", "7d", "custom"]
LensMode = Literal["touched", "net"]
LensHistory = Literal["head", "main"]
ChunkKind = Literal["function", "class", "heading", "file", "range"]
ChunkStatus = Literal["modified", "added", "deleted", "moved", "reverted"]
ChunkMatch = Literal["exact", "renamed-file", "moved", "uncertain", "none"]
Expand Down Expand Up @@ -45,10 +46,22 @@ class LensEndpoint(LensModel):
date: Optional[str]


class LensBranch(LensModel):
name: Optional[str]
default: str
default_ref: str
on_default: bool
ahead: int
behind: int
default_commits: Optional[int]


class LensSelection(LensModel):
window: LensWindow
mode: LensMode
ref: str
history: LensHistory
branch: Optional[LensBranch]
base: LensEndpoint
head: LensEndpoint
since: Optional[str]
Expand Down
Loading
Loading