Skip to content

Commit 65b8808

Browse files
committed
feat(web): open commit links in the Diff pane
1 parent 2974a8e commit 65b8808

8 files changed

Lines changed: 320 additions & 38 deletions

File tree

‎apps/server/src/vcs/GitVcsDriverCore.test.ts‎

Lines changed: 29 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1432,21 +1432,46 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => {
14321432
}),
14331433
);
14341434

1435-
it.effect("rejects invalid and stale commit selections", () =>
1435+
it.effect("previews older HEAD ancestors and rejects invalid or stale commit selections", () =>
14361436
Effect.gen(function* () {
14371437
const cwd = yield* makeTmpDir();
14381438
const { initialBranch } = yield* initRepoWithCommit(cwd);
1439-
const initialSha = yield* git(cwd, ["rev-parse", "HEAD"]);
1439+
const rootSha = yield* git(cwd, ["rev-parse", "HEAD"]);
14401440
const driver = yield* GitVcsDriver.GitVcsDriver;
1441+
yield* writeTextFile(cwd, "README.md", "# main commit\n");
1442+
yield* git(cwd, ["add", "README.md"]);
1443+
yield* git(cwd, ["commit", "-m", "main change"]);
1444+
const olderSha = yield* git(cwd, ["rev-parse", "HEAD"]);
14411445
yield* git(cwd, ["checkout", "-b", "feature/stale-preview"]);
14421446
yield* writeTextFile(cwd, "README.md", "# feature\n");
14431447
yield* git(cwd, ["add", "README.md"]);
14441448
yield* git(cwd, ["commit", "-m", "feature"]);
14451449
const featureSha = yield* git(cwd, ["rev-parse", "HEAD"]);
1450+
const list = yield* driver.getReviewBranchCommits({ cwd, baseRef: initialBranch });
1451+
assert.deepStrictEqual(
1452+
list.commits.map((commit) => commit.sha),
1453+
[featureSha],
1454+
);
1455+
const older = yield* driver.getReviewDiffPreview({
1456+
cwd,
1457+
baseRef: initialBranch,
1458+
commitSha: olderSha,
1459+
});
1460+
assert.strictEqual(older.sources[0]?.baseRef, rootSha);
1461+
assert.strictEqual(older.sources[0]?.headRef, olderSha);
1462+
assert.include(older.sources[0]?.diff, "+# main commit");
1463+
const withoutBase = yield* driver.getReviewDiffPreview({
1464+
cwd,
1465+
baseRef: "missing-base",
1466+
commitSha: olderSha,
1467+
});
1468+
assert.strictEqual(withoutBase.sources[0]?.headRef, olderSha);
1469+
const root = yield* driver.getReviewDiffPreview({ cwd, commitSha: rootSha });
1470+
assert.include(root.sources[0]?.diff, "+# test");
14461471
assert.throws(() =>
14471472
decodeReviewDiffPreviewInput({ cwd, baseRef: initialBranch, commitSha: "" }),
14481473
);
1449-
for (const commitSha of ["", "bad-sha", initialSha]) {
1474+
for (const commitSha of ["", "bad-sha", "0".repeat(40)]) {
14501475
const error = yield* driver
14511476
.getReviewDiffPreview({ cwd, baseRef: initialBranch, commitSha })
14521477
.pipe(Effect.flip);
@@ -1461,7 +1486,7 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => {
14611486
.getReviewDiffFileContents(
14621487
makeReviewDiffFileContentsInput(cwd, {
14631488
sourceKind: "commit",
1464-
baseRef: initialSha,
1489+
baseRef: olderSha,
14651490
headRef: featureSha,
14661491
}),
14671492
)

‎apps/server/src/vcs/GitVcsDriverCore.ts‎

Lines changed: 1 addition & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -3085,7 +3085,6 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
30853085
const resolveReviewCommit = Effect.fn("resolveReviewCommit")(function* (
30863086
cwd: string,
30873087
sha: string,
3088-
mergeBase?: string,
30893088
) {
30903089
if (!/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/i.test(sha)) {
30913090
return yield* reviewCommitError(cwd, "Selected commit is invalid or no longer available.");
@@ -3099,23 +3098,6 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
30993098
if (reachable.exitCode !== 0) {
31003099
return yield* reviewCommitError(cwd, "Selected commit is invalid or no longer available.");
31013100
}
3102-
if (mergeBase) {
3103-
const inBase = yield* executeGit(
3104-
"GitVcsDriver.reviewCommit.inBase",
3105-
cwd,
3106-
["merge-base", "--is-ancestor", sha, mergeBase],
3107-
{ allowNonZeroExit: true },
3108-
);
3109-
if (inBase.exitCode === 0) {
3110-
return yield* reviewCommitError(
3111-
cwd,
3112-
"Selected commit is outside the current branch diff range.",
3113-
);
3114-
}
3115-
if (inBase.exitCode !== 1) {
3116-
return yield* reviewCommitError(cwd, "Could not verify the selected commit range.");
3117-
}
3118-
}
31193101
const parents = yield* runGitStdout("GitVcsDriver.reviewCommit.parents", cwd, [
31203102
"rev-list",
31213103
"--parents",
@@ -3246,12 +3228,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
32463228
if (!input.commitSha || (input.file && input.file.sourceKind !== "commit")) {
32473229
return yield* reviewCommitError(cwd, "Selected commit request is invalid.");
32483230
}
3249-
const { mergeBase } = yield* resolveReviewMergeBase(
3250-
cwd,
3251-
repository.currentBranch,
3252-
input.baseRef,
3253-
);
3254-
const commit = yield* resolveReviewCommit(cwd, input.commitSha, mergeBase);
3231+
const commit = yield* resolveReviewCommit(cwd, input.commitSha);
32553232
const diffArgs = [
32563233
...REVIEW_DIFF_ARGS,
32573234
...(input.ignoreWhitespace ? ["--ignore-all-space"] : []),

‎apps/web/src/components/desktop/DesktopWebLinkCoordinator.tsx‎

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime/environment";
22
import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
33
import type { EnvironmentId, ScopedThreadRef } from "@t3tools/contracts";
4-
import { parseChangeRequestUrl } from "@t3tools/shared/changeRequestUrl";
4+
import { parseChangeRequestUrl, parseCommitUrl } from "@t3tools/shared/changeRequestUrl";
55
import { promptLinkAppPath } from "@t3tools/shared/promptLinks";
66
import { useRouter } from "@tanstack/react-router";
77
import * as Effect from "effect/Effect";
@@ -119,9 +119,14 @@ export function DesktopWebLinkCoordinator() {
119119
await router.navigate({ href: appPath });
120120
return;
121121
}
122-
if (openChangeRequest(externalClick, url)) return;
123-
const isFile = url.startsWith("file:");
124122
const routeParams = router.state.matches.at(-1)?.params ?? {};
123+
const routeTarget = resolveThreadRouteTarget(routeParams);
124+
const commitThreadRef =
125+
parseCommitUrl(url) !== null && routeTarget?.kind === "server"
126+
? routeTarget.threadRef
127+
: undefined;
128+
if (openChangeRequest(externalClick, url, commitThreadRef)) return;
129+
const isFile = url.startsWith("file:");
125130
const threadRef =
126131
threadShowingBrowser(
127132
routeParams,
@@ -151,11 +156,11 @@ export function DesktopWebLinkCoordinator() {
151156
});
152157

153158
const receiveLink = useEffectEvent((url: string) => {
154-
// A connected server publishes its config before its project snapshot, so a PR link
155-
// delivered at launch would miss its project and fall through to the browser. Hold PR
156-
// links, and only those, until discovery settles; an ordinary link never waits for it.
159+
// A connected server publishes its config before its project snapshot, so a source control
160+
// link delivered at launch would miss its project and fall through to the browser. Hold
161+
// those links until discovery settles; an ordinary link never waits for it.
157162
const hold =
158-
openPullRequestsInApp && parseChangeRequestUrl(url) !== null
163+
openPullRequestsInApp && (parseChangeRequestUrl(url) !== null || parseCommitUrl(url) !== null)
159164
? projectsSettled()
160165
: Promise.resolve();
161166
void hold.then(() => {
Lines changed: 175 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,175 @@
1+
import { scopeThreadRef } from "@t3tools/client-runtime/environment";
2+
import { EnvironmentId, ProjectId, ThreadId } from "@t3tools/contracts";
3+
import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
4+
5+
const state = vi.hoisted(() => ({
6+
openInApp: true,
7+
threadExists: true,
8+
repositoryKey: "github.com/pingdotgg/t3code",
9+
projectEnvironmentId: "local",
10+
navigate: vi.fn(),
11+
}));
12+
13+
vi.mock("@tanstack/react-router", () => ({ useNavigate: () => state.navigate }));
14+
vi.mock("../hooks/useSettings", () => ({
15+
useClientSettings: (select: (settings: { pullRequestLinksOpenInApp: boolean }) => unknown) =>
16+
select({ pullRequestLinksOpenInApp: state.openInApp }),
17+
}));
18+
vi.mock("../state/environments", () => ({ usePrimaryEnvironmentId: () => "local" }));
19+
vi.mock("../rpc/atomRegistry", () => ({
20+
appAtomRegistry: {
21+
get: () => new Map([["local", { environment: { capabilities: { pullRequests: true } } }]]),
22+
},
23+
}));
24+
vi.mock("../state/server", () => ({ environmentServerConfigsAtom: {}, serverEnvironment: {} }));
25+
vi.mock("../state/entities", () => ({
26+
readThreadShell: (ref: { environmentId: string; threadId: string }) =>
27+
state.threadExists && ref.environmentId === "local" && ref.threadId === "thread"
28+
? { environmentId: "local", projectId: "project" }
29+
: null,
30+
readProject: (ref: { environmentId: string; projectId: string }) =>
31+
ref.environmentId === state.projectEnvironmentId && ref.projectId === "project"
32+
? project()
33+
: null,
34+
readProjects: () => [project()],
35+
}));
36+
37+
import { selectThreadDiffPanelSelection, useDiffPanelStore } from "../diffPanelStore";
38+
import { selectActiveRightPanel, useRightPanelStore } from "../rightPanelStore";
39+
import { useOpenChangeRequestLink } from "./openPullRequestLink";
40+
41+
const ref = scopeThreadRef(EnvironmentId.make("local"), ThreadId.make("thread"));
42+
const sha = "5235a682169a69d18261c8bf4f1017dfb01b28fe";
43+
const commitUrl = `https://github.com/pingdotgg/t3code/pull/19941/commits/${sha}`;
44+
45+
function project() {
46+
return {
47+
id: ProjectId.make("project"),
48+
environmentId: EnvironmentId.make(state.projectEnvironmentId),
49+
repositoryIdentity: {
50+
provider: "github",
51+
canonicalKey: state.repositoryKey,
52+
displayName: state.repositoryKey.split("/").slice(1).join("/"),
53+
locator: { remoteUrl: `https://${state.repositoryKey}.git` },
54+
},
55+
};
56+
}
57+
58+
function click(modifiers = {}) {
59+
return {
60+
metaKey: false,
61+
ctrlKey: false,
62+
button: 0,
63+
defaultPrevented: false,
64+
preventDefault() {
65+
this.defaultPrevented = true;
66+
},
67+
stopPropagation() {},
68+
...modifiers,
69+
};
70+
}
71+
72+
beforeEach(() => {
73+
state.openInApp = true;
74+
state.threadExists = true;
75+
state.repositoryKey = "github.com/pingdotgg/t3code";
76+
state.projectEnvironmentId = "local";
77+
state.navigate.mockReset();
78+
useDiffPanelStore.setState({ byThreadKey: {}, branchBaseRefByThreadKey: {} });
79+
useRightPanelStore.setState({ byThreadKey: {} });
80+
});
81+
82+
describe("commit link opening", () => {
83+
it("opens a port-bearing GitHub Enterprise URL for its normalized repository key", () => {
84+
state.repositoryKey = "github.acme.test/team/repo";
85+
expect(
86+
useOpenChangeRequestLink(ref)(
87+
click(),
88+
`https://github.acme.test:8443/team/repo/commit/${sha}`,
89+
),
90+
).toBe(true);
91+
expect(selectActiveRightPanel(useRightPanelStore.getState().byThreadKey, ref)).toBe("diff");
92+
expect(selectThreadDiffPanelSelection(useDiffPanelStore.getState().byThreadKey, ref)).toEqual({
93+
kind: "commit",
94+
sha,
95+
baseRef: null,
96+
});
97+
});
98+
99+
it.each([commitUrl, `https://github.com/pingdotgg/t3code/commit/${sha}`])(
100+
"opens the Diff panel with the commit and saved base: %s",
101+
(url) => {
102+
useDiffPanelStore.getState().selectBranchBaseRef(ref, "origin/main");
103+
const event = click();
104+
expect(useOpenChangeRequestLink(ref)(event, url)).toBe(true);
105+
expect(event.defaultPrevented).toBe(true);
106+
expect(selectActiveRightPanel(useRightPanelStore.getState().byThreadKey, ref)).toBe("diff");
107+
expect(selectThreadDiffPanelSelection(useDiffPanelStore.getState().byThreadKey, ref)).toEqual(
108+
{
109+
kind: "commit",
110+
sha,
111+
baseRef: "origin/main",
112+
},
113+
);
114+
},
115+
);
116+
117+
it.each([{ metaKey: true }, { ctrlKey: true }, { button: 1 }])(
118+
"leaves modified clicks to the original URL: %s",
119+
(modifiers) => {
120+
const event = click(modifiers);
121+
expect(useOpenChangeRequestLink(ref)(event, commitUrl)).toBe(false);
122+
expect(event.defaultPrevented).toBe(false);
123+
expect(useRightPanelStore.getState().byThreadKey).toEqual({});
124+
expect(useDiffPanelStore.getState().byThreadKey).toEqual({});
125+
},
126+
);
127+
128+
it.each([
129+
"preference off",
130+
"missing thread",
131+
"wrong repository",
132+
"wrong host",
133+
"wrong environment",
134+
])("falls back without changing either panel for %s", (scenario) => {
135+
if (scenario === "preference off") state.openInApp = false;
136+
if (scenario === "missing thread") state.threadExists = false;
137+
if (scenario === "wrong repository") state.repositoryKey = "github.com/pingdotgg/other";
138+
if (scenario === "wrong host") state.repositoryKey = "github.internal/pingdotgg/t3code";
139+
if (scenario === "wrong environment") state.projectEnvironmentId = "remote";
140+
const event = click();
141+
expect(useOpenChangeRequestLink(ref)(event, commitUrl)).toBe(false);
142+
expect(event.defaultPrevented).toBe(false);
143+
expect(useRightPanelStore.getState().byThreadKey).toEqual({});
144+
expect(useDiffPanelStore.getState().byThreadKey).toEqual({});
145+
});
146+
147+
it("does not use a synthetic PR panel or a matching project without a real thread", () => {
148+
const event = click();
149+
expect(useOpenChangeRequestLink(undefined, ref)(event, commitUrl)).toBe(false);
150+
expect(event.defaultPrevented).toBe(false);
151+
expect(useRightPanelStore.getState().byThreadKey).toEqual({});
152+
expect(useDiffPanelStore.getState().byThreadKey).toEqual({});
153+
expect(state.navigate).not.toHaveBeenCalled();
154+
});
155+
156+
it("opens a matching real thread supplied by the desktop link handler", () => {
157+
expect(useOpenChangeRequestLink()(click(), commitUrl, ref)).toBe(true);
158+
expect(selectActiveRightPanel(useRightPanelStore.getState().byThreadKey, ref)).toBe("diff");
159+
expect(selectThreadDiffPanelSelection(useDiffPanelStore.getState().byThreadKey, ref)).toEqual({
160+
kind: "commit",
161+
sha,
162+
baseRef: null,
163+
});
164+
});
165+
166+
it("still opens ordinary PR links in the PR panel", () => {
167+
expect(
168+
useOpenChangeRequestLink(ref)(click(), "https://github.com/pingdotgg/t3code/pull/19941"),
169+
).toBe(true);
170+
expect(selectActiveRightPanel(useRightPanelStore.getState().byThreadKey, ref)).toBe(
171+
"pull-request",
172+
);
173+
expect(useDiffPanelStore.getState().byThreadKey).toEqual({});
174+
});
175+
});

‎apps/web/src/lib/openPullRequestLink.ts‎

Lines changed: 30 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,17 +4,22 @@ import { useNavigate } from "@tanstack/react-router";
44
import { type MouseEvent } from "react";
55

66
import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
7-
import { parseChangeRequestUrl, type ChangeRequestLink } from "@t3tools/shared/changeRequestUrl";
7+
import {
8+
parseChangeRequestUrl,
9+
parseCommitUrl,
10+
type ChangeRequestLink,
11+
} from "@t3tools/shared/changeRequestUrl";
812
import { sourceControlRepositorySelector } from "@t3tools/shared/sourceControl";
913

1014
import { useOpenLink } from "../browser/useOpenLink";
1115
import { useClientSettings } from "../hooks/useSettings";
1216
import { stackedThreadToast, toastManager } from "../components/ui/toast";
1317
import { useRightPanelStore } from "../rightPanelStore";
18+
import { useDiffPanelStore } from "../diffPanelStore";
1419
import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
1520

1621
import { appAtomRegistry } from "../rpc/atomRegistry";
17-
import { readProjects, useProjects } from "../state/entities";
22+
import { readProject, readProjects, readThreadShell, useProjects } from "../state/entities";
1823
import { environmentServerConfigsAtom, serverEnvironment } from "../state/server";
1924
import { usePrimaryEnvironmentId } from "../state/environments";
2025

@@ -110,7 +115,8 @@ export function useOpenChangeRequestLink(
110115
event: Pick<
111116
MouseEvent<HTMLElement>,
112117
"preventDefault" | "stopPropagation" | "metaKey" | "ctrlKey"
113-
>,
118+
> &
119+
Partial<Pick<MouseEvent<HTMLElement>, "button">>,
114120
targetUrl: string,
115121
targetThreadRef?: ScopedThreadRef,
116122
targetEnvironmentId?: EnvironmentId,
@@ -127,6 +133,27 @@ export function useOpenChangeRequestLink(
127133
const allProjects = readProjects();
128134
const resolvedThreadRef = targetThreadRef ?? threadRef;
129135
const resolvedPanelRef = panelRef ?? resolvedThreadRef;
136+
const commit = parseCommitUrl(targetUrl);
137+
if (commit !== null) {
138+
const thread = resolvedThreadRef ? readThreadShell(resolvedThreadRef) : null;
139+
if (!thread || !resolvedThreadRef) return false;
140+
const project = readProject({
141+
environmentId: resolvedThreadRef.environmentId,
142+
projectId: thread.projectId,
143+
});
144+
const identity = project?.repositoryIdentity;
145+
if (
146+
project?.environmentId !== resolvedThreadRef.environmentId ||
147+
identity?.provider !== "github" ||
148+
identity.canonicalKey.toLowerCase() !== `${commit.host}/${commit.repository}`
149+
)
150+
return false;
151+
event.preventDefault();
152+
event.stopPropagation();
153+
useDiffPanelStore.getState().selectCommit(resolvedThreadRef, commit.sha);
154+
useRightPanelStore.getState().open(resolvedThreadRef, "diff");
155+
return true;
156+
}
130157
const parsed = parseChangeRequestUrl(targetUrl);
131158
if (parsed === null) return false;
132159
const reads = (environmentId: string) =>

‎docs/user/source-control.md‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,9 @@ commit at a time. The list shows up to 100 of the newest commits in the current
1515
commit shows its changes against its first parent. If the branch changes, select a commit again to
1616
refresh the view.
1717

18+
GitHub commit links open in the Diff pane when the current thread belongs to the same repository.
19+
Use Command/Ctrl+Click to open the original link in your browser.
20+
1821
## Connect an account
1922

2023
Install Git and configure authentication on the machine running your T3 Code server. For a remote

0 commit comments

Comments
 (0)