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