From 6ffc0111370b6e472cd0721ba6333aa8001ec0f9 Mon Sep 17 00:00:00 2001 From: Byron Wall Date: Sat, 21 Nov 2026 23:12:32 -0500 Subject: [PATCH 1/3] feat(changelens): read main history for time windows off the default branch Selection now carries where HEAD stands against the default branch (ahead, behind, origin/main or local main) and which history a time window read. A time window on a branch with no commits in it reads the default branch instead. history=head|main picks one explicitly. Co-Authored-By: Claude Opus 5.5 --- client/src/changelens/fixture.json | 10 +++ client/src/changelens/fixture.net.json | 10 +++ client/src/changelens/types.ts | 23 +++++ server/app/routers/changelens.py | 9 +- server/app/services/changelens/models.py | 13 +++ server/app/services/changelens/service.py | 5 +- server/app/services/changelens/window.py | 100 ++++++++++++++++++++-- server/tests/test_change_lens.py | 39 +++++++++ 8 files changed, 197 insertions(+), 12 deletions(-) diff --git a/client/src/changelens/fixture.json b/client/src/changelens/fixture.json index 33e97398..495fde09 100644 --- a/client/src/changelens/fixture.json +++ b/client/src/changelens/fixture.json @@ -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", diff --git a/client/src/changelens/fixture.net.json b/client/src/changelens/fixture.net.json index bba40107..b340411b 100644 --- a/client/src/changelens/fixture.net.json +++ b/client/src/changelens/fixture.net.json @@ -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", diff --git a/client/src/changelens/types.ts b/client/src/changelens/types.ts index 90d7219e..af29c6f6 100644 --- a/client/src/changelens/types.ts +++ b/client/src/changelens/types.ts @@ -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"; @@ -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. */ diff --git a/server/app/routers/changelens.py b/server/app/routers/changelens.py index 8706f0ae..b1e6994a 100644 --- a/server/app/routers/changelens.py +++ b/server/app/routers/changelens.py @@ -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: @@ -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 @@ -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 diff --git a/server/app/services/changelens/models.py b/server/app/services/changelens/models.py index 4e732dc8..728f78b3 100644 --- a/server/app/services/changelens/models.py +++ b/server/app/services/changelens/models.py @@ -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"] @@ -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] diff --git a/server/app/services/changelens/service.py b/server/app/services/changelens/service.py index 4d97d87f..2d19a873 100644 --- a/server/app/services/changelens/service.py +++ b/server/app/services/changelens/service.py @@ -15,6 +15,7 @@ from app.services.changelens.models import ( WORKTREE, ChangeLensPayload, + LensBranch, LensEndpoint, LensHunkDiff, LensSelection, @@ -114,7 +115,9 @@ def build_payload(path: Path, params: Params) -> dict: selection = LensSelection( window=params.window, mode=params.mode, - ref=params.ref, + ref=window.branch.default_ref if window.history == "main" and window.branch else params.ref, + history=window.history, + branch=LensBranch(**vars(window.branch)) if window.branch else None, base=LensEndpoint(ref=base.ref, sha=base.sha, label=base.label, date=iso(base.ts)), head=_head_endpoint(built), since=iso(window.since), diff --git a/server/app/services/changelens/window.py b/server/app/services/changelens/window.py index bb70544c..7e5daaa3 100644 --- a/server/app/services/changelens/window.py +++ b/server/app/services/changelens/window.py @@ -51,6 +51,9 @@ class Params: since: Optional[str] = None until: Optional[str] = None worktree: Optional[bool] = None + history: Optional[str] = None + """Whose history a time window reads: ``head`` or ``main`` (the default branch). None: HEAD, or the + default branch when HEAD is off it and has no commits in the window.""" @dataclass @@ -73,6 +76,30 @@ class Endpoint: ts: Optional[int] +@dataclass +class Branch: + """Where HEAD stands against the default branch.""" + + name: Optional[str] + """The checked-out branch; None for a detached HEAD.""" + default: str + """The default branch's name (``main``).""" + default_ref: str + """What main history reads: ``origin/main`` when it exists and is not behind local ``main``.""" + on_default: bool + ahead: int + """Commits on HEAD that the default ref does not hold.""" + behind: int + """Commits on the default ref that HEAD does not hold.""" + default_commits: Optional[int] = None + """Set only for an empty HEAD window off the default branch: commits on the default ref in the + window's time span (the last 7 days for the branch window).""" + + @property + def off(self) -> bool: + return not self.on_default or self.behind > 0 + + @dataclass class Window: repo: Path @@ -89,6 +116,9 @@ class Window: notes: list[str] = field(default_factory=list) upstream_tree: Optional[str] = None """The base with the window's upstream merges applied, when it holds any: what "before" is read from.""" + history: str = "head" + """``main`` when the window read the default branch's history instead of HEAD's.""" + branch: Optional[Branch] = None @property def base_tree(self) -> str: @@ -183,6 +213,31 @@ def _label(name: str, sha: str) -> str: return sha[:7] if sha.startswith(name) and len(name) >= 7 else f"{name} @ {sha[:7]}" +def _default_ref(repo: Path, default: str) -> Optional[str]: + """``origin/main`` unless local ``main`` is ahead of it; local ``main`` when there is no remote.""" + name = default.removeprefix("origin/") + local, remote = _try_sha(repo, name), _try_sha(repo, f"origin/{name}") + if remote and not (local and local != remote and _is_ancestor(repo, remote, local)): + return f"origin/{name}" + return name if local else None + + +def _branch(repo: Path, default: Optional[str]) -> Optional[Branch]: + if default is None: + return None + ref = _default_ref(repo, default) + if ref is None: + return None + name = branch_of(repo, "HEAD") + ahead, behind = (int(n) for n in _git(repo, "rev-list", "--left-right", "--count", f"HEAD...{ref}").split()) + short = default.removeprefix("origin/") + return Branch(name, short, ref, name == short, ahead, behind) + + +def _count_since(repo: Path, ref: str, since: int, until: int) -> int: + return int(_git(repo, "rev-list", "--count", "--first-parent", f"--since={since}", f"--until={until}", ref).strip()) + + def resolve(path: Path, params: Params) -> Window: try: repo = repo_root(path) @@ -191,13 +246,44 @@ def resolve(path: Path, params: Params) -> Window: head_commit = _try_sha(repo, "HEAD") if head_commit is None: raise LensError(f"{repo.name} has no commits yet", status=409) + if params.history not in (None, "head", "main"): + raise LensError(f"Unknown history: {params.history}") start = (path if path.is_dir() else path.parent).resolve() scope = "" if start == repo else start.relative_to(repo).as_posix() + try: + default = default_branch(repo) + except GitError: + default = None + branch = _branch(repo, default) + + # History picks the ref of a time window. Branch and revision windows name their own refs. + timed = params.window in WINDOW_SPANS or (params.window == "custom" and not params.base and not params.head) + can_switch = timed and params.ref == "HEAD" and branch is not None and params.history != "head" + if can_switch and params.history == "main": + window = _resolve_on(repo, scope, params, head_commit, default, branch, branch.default_ref) + else: + window = _resolve_on(repo, scope, params, head_commit, default, branch, None) + if can_switch and not window.commits and branch.off: + window = _resolve_on(repo, scope, params, head_commit, default, branch, branch.default_ref) + window.notes.insert(0, f"{branch.name or 'HEAD'} has no commits in this window, so it reads {branch.default_ref}'s history.") + window.branch = branch + if branch and branch.off and window.history == "head" and not window.commits: + if timed and window.since is not None and window.until is not None: + branch.default_commits = _count_since(repo, branch.default_ref, window.since, window.until) + elif params.window == "branch": + now = int(time.time()) + branch.default_commits = _count_since(repo, branch.default_ref, now - int(WINDOW_SPANS["7d"].total_seconds()), now) + return window + +def _resolve_on( + repo: Path, scope: str, params: Params, head_commit: str, default: Optional[str], branch: Optional[Branch], main_ref: Optional[str] +) -> Window: + """The window on HEAD's history, or on ``main_ref``'s when it is set.""" notes: list[str] = [] - tip_ref = params.head if params.window == "custom" and params.head else params.ref + tip_ref = main_ref or (params.head if params.window == "custom" and params.head else params.ref) tip_sha = _sha(repo, tip_ref) - tip_name = branch_of(repo, tip_ref) or tip_ref + tip_name = main_ref or branch_of(repo, tip_ref) or tip_ref tip = Endpoint(tip_ref, tip_sha, _label(tip_name, tip_sha), _commit_ts(repo, tip_sha)) wants_worktree = params.worktree if params.worktree is not None else tip_sha == head_commit @@ -206,17 +292,14 @@ def resolve(path: Path, params: Params) -> Window: notes.append(f"The working tree is left out: {tip_ref} is not the checked-out commit.") window = Window(repo, scope, params, base=tip, tip=tip, commits=[], wants_worktree=wants_worktree, notes=notes) + if main_ref: + window.history = "main" if scope: notes.append(f"Only files under {scope}/ are read.") boundary = _shallow_boundary(repo) if boundary: notes.append("This clone is shallow: history before its oldest commits is not available.") - try: - default = default_branch(repo) - except GitError: - default = None - if params.window == "branch": _branch_window(window, default) elif params.window in WINDOW_SPANS: @@ -243,7 +326,8 @@ def resolve(path: Path, params: Params) -> Window: raise LensError(f"Unknown window: {params.window}") _trim(window, boundary) - _mark_upstream_merges(window, default) + # Merges of the newest default ref are upstream work; a stale local main would miss some. + _mark_upstream_merges(window, branch.default_ref if branch else default) return window diff --git a/server/tests/test_change_lens.py b/server/tests/test_change_lens.py index 1d0f2d23..0f7f57f5 100644 --- a/server/tests/test_change_lens.py +++ b/server/tests/test_change_lens.py @@ -3,6 +3,7 @@ from __future__ import annotations import subprocess +from datetime import datetime, timezone import pytest from fastapi.testclient import TestClient @@ -243,6 +244,44 @@ def test_pr_merges_count_on_a_default_branch_ahead_of_its_upstream(tmp_path): assert not any("upstream" in note for note in payload["selection"]["notes"]) +def _stale_feature(tmp_path) -> tuple[Mini, dict]: + """HEAD on `feature`, one commit behind origin/main; local main is older still. The window holds main's edit only.""" + repo = Mini(tmp_path / "r") + first = repo.commit("base", {"a.ts": fn("a", 1), "b.ts": fn("b", 1)}) + repo.git("checkout", "--quiet", "-b", "feature") + repo.commit("feature edits a", {"a.ts": fn("a", 2)}) + since = int(repo.git("log", "-1", "--format=%ct")) + 60 + repo.git("checkout", "--quiet", "main") + repo.commit("main edits b", {"b.ts": fn("b", 7)}) + repo.git("update-ref", "refs/remotes/origin/main", "HEAD") + repo.git("checkout", "--quiet", "feature") + repo.git("branch", "--force", "main", first) + after = {"window": "custom", "since": datetime.fromtimestamp(since, timezone.utc).isoformat(), "until": "2026-03-30T00:00:00+00:00"} + return repo, after + + +def test_a_time_window_off_main_reads_main_history_when_head_has_none(tmp_path): + repo, after = _stale_feature(tmp_path) + payload = repo.lens(**after) + sel = payload["selection"] + assert sel["history"] == "main" and sel["ref"] == "origin/main" + assert sel["branch"] == { + "name": "feature", "default": "main", "defaultRef": "origin/main", "onDefault": False, + "ahead": 1, "behind": 1, "defaultCommits": None, + } + assert set(by_id(payload)) == {"b.ts::b"} + assert not sel["includesWorktree"] + # The branch window keeps meaning this branch against its merge-base. + assert set(by_id(repo.lens())) == {"a.ts::a"} + + +def test_head_history_off_main_is_empty_and_counts_main_commits(tmp_path): + repo, after = _stale_feature(tmp_path) + payload = repo.lens(history="head", **after) + assert payload["chunks"] == [] and payload["selection"]["history"] == "head" + assert payload["selection"]["branch"]["defaultCommits"] == 1 + + def test_same_named_scopes_pair_by_body_and_anonymous_objects_are_no_chunks(tmp_path): load = "def load(x):\n if x:\n return 1\n return 0\n" config = 'register({\n name: "a",\n retries: 1,\n});\n' From 889807313bb484a62948eafcd4866c0552392358 Mon Sep 17 00:00:00 2001 From: Byron Wall Date: Sat, 21 Nov 2026 23:14:58 -0500 Subject: [PATCH 2/3] feat(client): branch notice and main-history toggle in Change Lens The status row names the checked-out branch and how far it is behind the default branch when HEAD is off it. Time windows get a History toggle between the branch and origin/main. An empty window offers main's history when main has commits there. Co-Authored-By: Claude Opus 5.5 --- client/src/changelens/BranchNotice.tsx | 66 ++++++++++++++++++++++++ client/src/changelens/ChangeLensView.tsx | 29 ++++++++++- client/src/changelens/api.ts | 5 +- client/src/changelens/panel/sample.ts | 2 + client/src/changelens/urlState.ts | 8 ++- 5 files changed, 106 insertions(+), 4 deletions(-) create mode 100644 client/src/changelens/BranchNotice.tsx diff --git a/client/src/changelens/BranchNotice.tsx b/client/src/changelens/BranchNotice.tsx new file mode 100644 index 00000000..0ccb2163 --- /dev/null +++ b/client/src/changelens/BranchNotice.tsx @@ -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) => 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: b().name ?? "HEAD", title: `Read the commits on ${name()}` }, + { id: "main", label: b().defaultRef, title: `Read the commits on ${b().defaultRef}, without checking anything out` }, + ]; + return ( + + + ); +} diff --git a/client/src/changelens/ChangeLensView.tsx b/client/src/changelens/ChangeLensView.tsx index dc73f9bb..db8430e8 100644 --- a/client/src/changelens/ChangeLensView.tsx +++ b/client/src/changelens/ChangeLensView.tsx @@ -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"; @@ -81,7 +82,7 @@ export default function ChangeLensView(props: { const query = createMemo( () => { 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) } @@ -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. */ @@ -248,10 +260,13 @@ export default function ChangeLensView(props: { {/* What the window resolved to. One fixed-height row at rest; notes wrap under it. */} -
+
{loading() ? "Reading the history of this window…" : " "}}> {(p) => ( <> + + setLens({ history, commit: null })} /> + {p().selection.base.label} @@ -297,6 +312,16 @@ export default function ChangeLensView(props: { {(note) =>

{note}

}
+ + {(offer) => ( + <> +

This checkout is not on {payload()!.selection.branch!.default}, so its own history misses the work that landed there.

+ + + )} +

Pick another window in the toolbar: 7 days reaches further back, and Custom takes any two revisions.

diff --git a/client/src/changelens/api.ts b/client/src/changelens/api.ts index 4fa44aac..4da8086f 100644 --- a/client/src/changelens/api.ts +++ b/client/src/changelens/api.ts @@ -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. */ @@ -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. */ @@ -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); diff --git a/client/src/changelens/panel/sample.ts b/client/src/changelens/panel/sample.ts index 5bb79516..27df8ee4 100644 --- a/client/src/changelens/panel/sample.ts +++ b/client/src/changelens/panel/sample.ts @@ -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, diff --git a/client/src/changelens/urlState.ts b/client/src/changelens/urlState.ts index c0668f75..2bc46c9a 100644 --- a/client/src/changelens/urlState.ts +++ b/client/src/changelens/urlState.ts @@ -8,10 +8,11 @@ // cs selected chunk id // cbase, chead, csince, cuntil the custom window // clens color: `.now` or `.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"; @@ -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 = { @@ -42,6 +45,7 @@ export const DEFAULT_LENS: LensState = { until: "", metric: "complexity", color: "delta", + history: null, }; const WINDOWS: readonly LensWindow[] = ["branch", "24h", "7d", "custom"]; @@ -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, }; } @@ -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(); } From 07af435edae6a9aff55d31574a2246dd10993d4b Mon Sep 17 00:00:00 2001 From: Byron Wall Date: Sat, 21 Nov 2026 23:22:19 -0500 Subject: [PATCH 3/3] feat(changelens): chist in the URL, shorter labels, docs Co-Authored-By: Claude Opus 5.5 --- client/src/changelens/BranchNotice.tsx | 2 +- client/src/navigation/location.ts | 2 +- docs/CODE_MAP.md | 5 +++-- server/app/services/changelens/window.py | 2 +- site/src/docs/pages/changes.md | 6 ++++++ 5 files changed, 12 insertions(+), 5 deletions(-) diff --git a/client/src/changelens/BranchNotice.tsx b/client/src/changelens/BranchNotice.tsx index 0ccb2163..7e32873f 100644 --- a/client/src/changelens/BranchNotice.tsx +++ b/client/src/changelens/BranchNotice.tsx @@ -25,7 +25,7 @@ export default function BranchNotice(props: { selection: LensSelection; toggle: return parts.length ? `${parts.join(", ")} ${b().defaultRef}` : `level with ${b().defaultRef}`; }; const options = (): { id: LensHistory; label: string; title: string }[] => [ - { id: "head", label: b().name ?? "HEAD", title: `Read the commits on ${name()}` }, + { 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 ( diff --git a/client/src/navigation/location.ts b/client/src/navigation/location.ts index 47caec9b..86060923 100644 --- a/client/src/navigation/location.ts +++ b/client/src/navigation/location.ts @@ -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"; diff --git a/docs/CODE_MAP.md b/docs/CODE_MAP.md index 494c7a67..f9014958 100644 --- a/docs/CODE_MAP.md +++ b/docs/CODE_MAP.md @@ -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` | diff --git a/server/app/services/changelens/window.py b/server/app/services/changelens/window.py index 7e5daaa3..476b699b 100644 --- a/server/app/services/changelens/window.py +++ b/server/app/services/changelens/window.py @@ -265,7 +265,7 @@ def resolve(path: Path, params: Params) -> Window: window = _resolve_on(repo, scope, params, head_commit, default, branch, None) if can_switch and not window.commits and branch.off: window = _resolve_on(repo, scope, params, head_commit, default, branch, branch.default_ref) - window.notes.insert(0, f"{branch.name or 'HEAD'} has no commits in this window, so it reads {branch.default_ref}'s history.") + window.notes.insert(0, f"This branch has no commits in this window, so this shows {branch.default_ref}'s history.") window.branch = branch if branch and branch.off and window.history == "head" and not window.commits: if timed and window.since is not None and window.until is not None: diff --git a/site/src/docs/pages/changes.md b/site/src/docs/pages/changes.md index 20d7ab24..296ec579 100644 --- a/site/src/docs/pages/changes.md +++ b/site/src/docs/pages/changes.md @@ -19,6 +19,12 @@ The view reads the checked-out branch. Staged and unstaged edits are included as - **This branch** compares the branch with the commit where it left the default branch (the merge base). On the default branch itself, the base is the upstream tip. When the two are equal, the window is empty and a note says so. - **24 hours** and **7 days** read the commits whose committer date falls in that time, counted back from now. The base is the first parent of the oldest commit in the window. + +### Off the default branch + +When the checkout is on another branch, or on the default branch but behind its upstream, the status row names the branch and how far it is behind and ahead of the default branch (`origin/main` when it exists and is not behind local `main`). A time window then gets a **History** toggle: **Branch** reads the checked-out branch, and **origin/main** reads the default branch's commits. Srcly reads Git objects only. It never checks out a branch or touches the working tree, so main history leaves out uncommitted edits. + +When the branch has no commits in a time window, the window reads the default branch and a note says so. Pick **Branch** to go back. When a window on the branch is empty and the default branch has commits in the same time (the last 7 days for **This branch**), the empty view offers a button that shows them. **This branch** always compares the branch with its merge base. - **Custom** takes two revisions, a time range, or both. Srcly reads one history: the first-parent log of the branch. A merge commit counts once, as its diff against its first parent, so merged work is never counted twice and other branches never mix in. A merge of the default branch into your branch is listed but not read, because those are upstream changes. A note names it. When the base is older than such a merge, "before" is the base with that merge's changes applied, so upstream work never reads as yours. If the merge overlaps your own earlier edits, the base stays as it is and a note says so. On the default branch itself, no merge is an upstream merge.