Skip to content
refs
History
144 lines · 8.0 KBRaw
1import { COMMITS_PER_PAGE, MAX_TITLE_LENGTH, repoLink, splatSegments, type CommitSummary } from "@refs/backend/contract";
2import { AgentAvatar, Ago, Avatar, Empty, LayerCard, Pagination, TabCount, Tabs } from "@refs/design-system";
3import { GitCommitIcon, PathIcon } from "@refs/design-system/icons";
4import { parseDecisions } from "@refs/protocol";
5import { Link, data, redirect, useNavigate } from "react-router";
6import type { Route } from "./+types/repo-commits";
7import { BranchPicker } from "@refs/design-system";
8import { formatDate } from "@refs/design-system";
9import { failed, formText, found, refs, signedIn, fullName, nowSeconds } from "../lib/session";
10import { HistoryReasoning, decisionsOf } from "../components/history-reasoning";
11import { AppLink } from "../components/link";
12
13export const meta: Route.MetaFunction = ({ params }) => [{ title: `History · ${fullName(params)} · refs` }];
14
15export async function loader({ request, params, context }: Route.LoaderArgs) {
16 const segments = splatSegments(params["*"]);
17 if (!segments) throw data(null, { status: 404 });
18 const query = new URL(request.url).searchParams;
19 const page = Math.max(1, Number(query.get("page")) || 1);
20 const tab = query.get("tab") === "reasoning" ? "reasoning" : "commits";
21 const viewer = refs(context);
22 const repo = await found(viewer.repo(fullName(params)));
23 const [history, refList] = await found(Promise.all([repo.history(segments, { cursor: String(page) }), repo.refs()]));
24 return {
25 repo: repo.summary.name,
26 refs: refList,
27 ref: history.location.ref,
28 page,
29 tab,
30 canRevisit: viewer.viewer.agent === null && repo.summary.can.write,
31 now: nowSeconds(),
32 commits: history.page.items,
33 hasOlder: history.page.next !== null,
34 };
35}
36
37export async function action({ request, params, context }: Route.ActionArgs) {
38 const form = await request.formData();
39 if (formText(form, "intent") !== "revisit") throw data(null, { status: 400 });
40 const name = fullName(params);
41 const repo = await found(signedIn(context).repo(name));
42 const ref = formText(form, "ref");
43 const commit = await found(repo.commit(formText(form, "commit")));
44 const record = parseDecisions(commit.message, commit.hash).decisions.find((candidate) => candidate.decisionId === formText(form, "decision"));
45 if (!record) return { error: "This decision is no longer in that commit. Reload and try again." };
46 const hash = commit.hash.slice(0, 7);
47 const body = [
48 `Revisit decision ${record.decisionId} from ${hash} "${commit.message.split("\n")[0]}" on ${ref}:`,
49 `> ${record.decision}`,
50 formText(form, "body").trim(),
51 `Start from the head of ${ref}, not from ${hash}. Review every commit after ${hash} that builds on this decision, and change them so the new direction holds throughout. Record a decision that supersedes ${record.decisionId}.`,
52 ].join("\n\n");
53 const outcome = await signedIn(context).createTask({ title: `Revisit: ${record.decision}`.slice(0, MAX_TITLE_LENGTH), body, repo: name, assignee: null, labels: [] });
54 return outcome.ok ? redirect(`/${name}/tasks/${outcome.value.number}`) : failed(outcome.problem, {});
55}
56
57function groupByDay(commits: readonly CommitSummary[]): [string, CommitSummary[]][] {
58 const days = new Map<string, CommitSummary[]>();
59 for (const commit of commits) {
60 const day = formatDate(commit.committedAt);
61 days.set(day, [...(days.get(day) ?? []), commit]);
62 }
63 return [...days];
64}
65
66export default function RepoCommits({ loaderData }: Route.ComponentProps) {
67 const { repo, refs: refList, ref, page, tab, canRevisit, commits, hasOlder, now: current } = loaderData;
68 const navigate = useNavigate();
69 const base = repoLink(repo, "commits", ref);
70 const href = (view: string, at = 1) => `${base}?${new URLSearchParams({ ...(view === "reasoning" && { tab: view }), ...(at > 1 && { page: String(at) }) })}`.replace(/\?$/, "");
71 const decisions = decisionsOf(commits).length;
72 const tabLink = (value: string, icon: React.ReactNode, label: string, count: number) => ({
73 value,
74 label: (
75 <span className="flex items-center gap-2">
76 {icon}
77 {label}
78 <TabCount>{count}</TabCount>
79 </span>
80 ),
81 nativeButton: false,
82 render: (props: React.AnchorHTMLAttributes<HTMLAnchorElement>) => <AppLink {...props} href={href(value, page)} />,
83 });
84 return (
85 <div className="flex flex-col gap-5">
86 <div className="flex flex-wrap items-center justify-between gap-3">
87 <h1 className="m-0 text-heading leading-tight font-semibold">History</h1>
88 <BranchPicker repo={repo} refs={refList} current={ref} />
89 </div>
90 <Tabs variant="underline" value={tab} tabs={[tabLink("commits", <GitCommitIcon size={16} />, "Commits", commits.length), tabLink("reasoning", <PathIcon size={16} />, "Reasoning", decisions)]} />
91 {tab === "reasoning" ? (
92 <HistoryReasoning commits={commits} refName={ref} repo={repo} now={current} canRevisit={canRevisit} />
93 ) : commits.length === 0 ? (
94 <Empty icon={<GitCommitIcon size={40} />} title="No commits" description="There are no commits on this ref." />
95 ) : (
96 groupByDay(commits).map(([day, dayCommits]) => (
97 <section key={day} className="flex flex-col gap-2">
98 <h2 className="caption m-0 text-faint">{day}</h2>
99 <LayerCard>
100 <ul className="m-0 list-none p-0">
101 {dayCommits.map((commit) => {
102 const count = parseDecisions(commit.message ?? "", commit.hash).decisions.length;
103 const agent = commit.pushedBy?.actor.kind === "agent";
104 return (
105 <li key={commit.hash} className="group/commit relative flex items-center justify-between gap-4 py-2.5 pr-4 pl-12 transition-colors duration-150 hover:bg-hover">
106 <span aria-hidden className="absolute top-0 bottom-0 left-[22px] w-0.5 bg-porcelain/45 group-first/commit:top-1/2 group-last/commit:bottom-1/2" />
107 <span
108 aria-hidden
109 className={`absolute top-1/2 left-[23px] flex -translate-x-1/2 -translate-y-1/2 items-center justify-center rounded-full font-semibold tabular-nums size-5 text-[0.7143rem] ${agent ? "bg-panel text-ink shadow-[inset_0_0_0_2px_var(--porcelain)]" : "bg-accent text-on-accent"}`}
110 >
111 {count > 0 ? count : null}
112 </span>
113 <div className="flex min-w-0 flex-1 flex-col">
114 <Link to={`/${repo}/commit/${commit.hash}`} className="truncate font-medium text-ink hover:text-accent-text">
115 {commit.title}
116 </Link>
117 <span className="flex items-center gap-1.5 text-compact text-muted">
118 <span className="text-ink">{commit.author}</span> committed <Ago at={commit.committedAt} now={current} />
119 </span>
120 </div>
121 <div className="flex shrink-0 items-center gap-3 text-compact text-muted">
122 {count > 0 && (
123 <Link to={`${base}?tab=reasoning`} className="hidden items-center gap-1 tabular-nums hover:text-accent-text sm:flex">
124 <PathIcon size={14} /> {count} {count === 1 ? "decision" : "decisions"}
125 </Link>
126 )}
127 <Link to={`/${repo}/commit/${commit.hash}`} className="rounded-chip bg-sunken px-1.5 py-0.5 shadow-[inset_0_0_0_1px_var(--hairline)] font-mono text-xs text-ink hover:text-accent-text">
128 {commit.hash.slice(0, 7)}
129 </Link>
130 </div>
131 </li>
132 );
133 })}
134 </ul>
135 </LayerCard>
136 </section>
137 ))
138 )}
139 {(page > 1 || hasOlder) && (
140 <Pagination page={page} perPage={COMMITS_PER_PAGE} hasNextPage={hasOlder} controls="simple" setPage={(next) => navigate(href(tab, next))} />
141 )}
142 </div>
143 );
144}