The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 22, 12:00 UTC
feat(web): review local commits in the Diff pane (#19941)
Co-authored-by: Julius Marminge <julius0216@outlook.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Bilal Bakr committed
Oct 30, 2026 at 11:00 UTC
5ef56853ef1854da50bc1909c6c0a32700f2cb13
33 files changed
+1375
-162
apps/mobile/src/features/review/reviewModel.ts
+16
-11
@@ -534,17 +534,22 @@ export function buildReviewSectionItems(input: {
534
},
535
);
536
537
- const gitItems = input.gitSections.map<ReviewSectionItem>((section) => ({
538
- id: `git:${section.kind}`,
539
- kind: section.kind,
540
- title: section.title,
541
- subtitle: gitSubtitle(section),
542
- diff: section.diff,
543
- source: section,
544
- ...(section.files ? { files: section.files } : {}),
545
- truncated: section.truncated,
546
- isLoading: false,
547
- }));
537
+ const gitItems = input.gitSections
538
+ .filter(
539
+ (section): section is typeof section & { kind: ReviewSectionKind } =>
540
+ section.kind !== "commit",
541
+ )
542
+ .map<ReviewSectionItem>((section) => ({
543
+ id: `git:${section.kind}`,
544
+ kind: section.kind,
545
+ title: section.title,
546
+ subtitle: gitSubtitle(section),
547
+ diff: section.diff,
548
+ source: section,
549
+ ...(section.files ? { files: section.files } : {}),
550
+ truncated: section.truncated,
551
+ isLoading: false,
552
+ }));
553
const hasChangesItem = gitItems.some((item) => item.id === CHANGES_SECTION_ID);
554
const visibleGitItems =
555
input.loadingGitSections && !hasChangesItem
apps/server/src/auth/RpcAuthorization.ts
+1
@@ -170,6 +170,7 @@ export const RPC_REQUIRED_SCOPES = {
170
[WS_METHODS.vcsRefreshStatus]: AuthOrchestrationReadScope,
171
[WS_METHODS.gitResolvePullRequest]: AuthOrchestrationReadScope,
172
[WS_METHODS.vcsListRefs]: AuthOrchestrationReadScope,
173
+ [WS_METHODS.reviewGetBranchCommits]: AuthFilesystemReadScope,
174
[WS_METHODS.reviewGetDiffPreview]: AuthFilesystemReadScope,
175
[WS_METHODS.reviewGetDiffFileContents]: AuthFilesystemReadScope,
176
[WS_METHODS.terminalOpen]: AuthTerminalOperateScope,
apps/server/src/observability/RpcInstrumentation.ts
+1
@@ -181,6 +181,7 @@ const RPC_AGGREGATES = {
181
[WS_METHODS.vcsCreateRef]: "vcs",
182
[WS_METHODS.vcsSwitchRef]: "vcs",
183
[WS_METHODS.vcsInit]: "vcs",
184
+ [WS_METHODS.reviewGetBranchCommits]: "review",
185
[WS_METHODS.reviewGetDiffPreview]: "review",
186
[WS_METHODS.reviewGetDiffFileContents]: "review",
187
[WS_METHODS.terminalOpen]: "terminal",
apps/server/src/review/ReviewService.ts
+31
-5
@@ -8,6 +8,8 @@ import * as Path from "effect/Path";
8
import {
9
VcsRepositoryDetectionError,
10
VcsUnsupportedOperationError,
11
+ type ReviewBranchCommitsInput,
12
+ type ReviewBranchCommitsResult,
13
type ReviewDiffFileContentsInput,
14
type ReviewDiffFileContentsResult,
15
type ReviewDiffPreviewError,
@@ -20,9 +22,18 @@ import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
22
import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
23
import * as KnownWorkspaces from "../workspace/KnownWorkspaces.ts";
24
25
+const WORKSPACE_BOUND_SUBJECTS = {
26
+ "ReviewService.getBranchCommits": "commit list",
27
+ "ReviewService.getDiffPreview": "diff preview",
28
+ "ReviewService.getDiffFileContents": "diff file contents",
29
+} as const;
30
+
31
export class ReviewService extends Context.Service<
32
ReviewService,
33
{
34
+ readonly getBranchCommits: (
35
+ input: ReviewBranchCommitsInput,
36
+ ) => Effect.Effect<ReviewBranchCommitsResult, ReviewDiffPreviewError>;
37
readonly getDiffPreview: (
38
input: ReviewDiffPreviewInput,
39
) => Effect.Effect<ReviewDiffPreviewResult, ReviewDiffPreviewError>;
@@ -61,7 +72,7 @@ export const make = Effect.gen(function* () {
72
};
73
74
const assertWorkspaceBoundCwd = Effect.fn("ReviewService.assertWorkspaceBoundCwd")(function* (
64
- operation: "ReviewService.getDiffPreview" | "ReviewService.getDiffFileContents",
75
+ operation: keyof typeof WORKSPACE_BOUND_SUBJECTS,
76
cwd: string,
77
) {
78
const [candidate, workspaceRoot] = yield* Effect.all([
@@ -78,13 +89,27 @@ export const make = Effect.gen(function* () {
89
return yield* new VcsRepositoryDetectionError({
90
operation,
91
cwd,
81
- detail:
82
- operation === "ReviewService.getDiffPreview"
83
- ? "Review diff preview cwd must stay within the configured workspace root."
84
- : "Review diff file contents cwd must stay within the configured workspace root.",
92
+ detail: `Review ${WORKSPACE_BOUND_SUBJECTS[operation]} cwd must stay within the configured workspace root.`,
93
});
94
});
95
96
+ const getBranchCommits: ReviewService["Service"]["getBranchCommits"] = Effect.fn(
97
+ "ReviewService.getBranchCommits",
98
+ )(function* (input) {
99
+ yield* assertWorkspaceBoundCwd("ReviewService.getBranchCommits", input.cwd);
100
+
101
+ const handle = yield* vcsRegistry.detect({ cwd: input.cwd, requestedKind: "auto" });
102
+ if (!handle) return { commits: [], truncated: false };
103
+ if (handle.kind !== "git") {
104
+ return yield* new VcsUnsupportedOperationError({
105
+ operation: "ReviewService.getBranchCommits",
106
+ kind: handle.kind,
107
+ detail: "Review commit lists require a Git repository.",
108
+ });
109
+ }
110
+ return yield* git.getReviewBranchCommits(input);
111
+ });
112
+
113
const getDiffPreview: ReviewService["Service"]["getDiffPreview"] = Effect.fn(
114
"ReviewService.getDiffPreview",
115
)(function* (input) {
@@ -120,6 +145,7 @@ export const make = Effect.gen(function* () {
145
});
146
147
return ReviewService.of({
148
+ getBranchCommits,
149
getDiffPreview,
150
getDiffFileContents,
151
});
apps/server/src/vcs/GitVcsDriver.ts
+5
@@ -20,6 +20,8 @@ import {
20
type VcsCreateRefResult,
21
type VcsCreateWorktreeInput,
22
type VcsCreateWorktreeResult,
23
+ type ReviewBranchCommitsInput,
24
+ type ReviewBranchCommitsResult,
25
type ReviewDiffPreviewInput,
26
type ReviewDiffPreviewResult,
27
type ReviewDiffFileContentsInput,
@@ -328,6 +330,9 @@ export class GitVcsDriver extends Context.Service<
330
cwd: string,
331
baseRef: string,
332
) => Effect.Effect<GitRangeContext, GitCommandError>;
333
+ readonly getReviewBranchCommits: (
334
+ input: ReviewBranchCommitsInput,
335
+ ) => Effect.Effect<ReviewBranchCommitsResult, GitCommandError>;
336
readonly getReviewDiffPreview: (
337
input: ReviewDiffPreviewInput,
338
) => Effect.Effect<ReviewDiffPreviewResult, GitCommandError>;
apps/server/src/vcs/GitVcsDriverCore.test.ts
+136
@@ -1,5 +1,7 @@
1
// @effect-diagnostics nodeBuiltinImport:off - realpathSync.native resolves Windows 8.3 short names, which the Effect realPath does not.
2
import * as NodeFS from "node:fs";
3
+import * as NodeOS from "node:os";
4
+import * as NodeURL from "node:url";
5
import * as NodeServices from "@effect/platform-node/NodeServices";
6
import * as HostProcess from "@t3tools/shared/HostProcess";
7
import { assert, it, describe } from "@effect/vitest";
@@ -1466,6 +1468,140 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => {
1468
});
1469
1470
describe("review diff previews", () => {
1471
+ it.effect("diffs a root commit against the empty tree but rejects a shallow boundary", () =>
1472
+ Effect.gen(function* () {
1473
+ const upstream = yield* makeTmpDir();
1474
+ yield* initRepoWithCommit(upstream);
1475
+ const driver = yield* GitVcsDriver.GitVcsDriver;
1476
+ const emptyTree = yield* git(upstream, ["hash-object", "-t", "tree", NodeOS.devNull]);
1477
+ const root = yield* git(upstream, ["rev-parse", "HEAD"]);
1478
+ const rootSource = (yield* driver.getReviewDiffPreview({ cwd: upstream, commitSha: root }))
1479
+ .sources[0]!;
1480
+ assert.equal(rootSource.baseRef, emptyTree);
1481
+ assert.include(rootSource.diff, "+# test");
1482
+
1483
+ yield* writeTextFile(upstream, "README.md", "# boundary\n");
1484
+ yield* git(upstream, ["commit", "-am", "boundary"]);
1485
+ const sha = yield* git(upstream, ["rev-parse", "HEAD"]);
1486
+ const cwd = yield* makeTmpDir();
1487
+ yield* git(upstream, ["clone", "--depth=1", NodeURL.pathToFileURL(upstream).href, cwd], {
1488
+ GIT_CONFIG_GLOBAL: NodeOS.devNull,
1489
+ GIT_CONFIG_NOSYSTEM: "1",
1490
+ });
1491
+ assert.equal(yield* git(cwd, ["rev-parse", "--is-shallow-repository"]), "true");
1492
+ for (const request of [
1493
+ driver.getReviewDiffPreview({ cwd, commitSha: sha }),
1494
+ driver.getReviewDiffFileContents(
1495
+ makeReviewDiffFileContentsInput(cwd, {
1496
+ sourceKind: "commit",
1497
+ changeType: "new",
1498
+ headRef: sha,
1499
+ baseRef: emptyTree,
1500
+ }),
1501
+ ),
1502
+ ]) {
1503
+ const error = yield* Effect.asVoid<unknown, GitCommandError, never>(request).pipe(
1504
+ Effect.flip,
1505
+ );
1506
+ assert.include(error.detail, "parent");
1507
+ }
1508
+ }),
1509
+ );
1510
+
1511
+ it.effect("lists the branch's commits newest first, at most 100, and flags the rest", () =>
1512
+ Effect.gen(function* () {
1513
+ const cwd = yield* makeTmpDir();
1514
+ const { initialBranch } = yield* initRepoWithCommit(cwd);
1515
+ const driver = yield* GitVcsDriver.GitVcsDriver;
1516
+ yield* git(cwd, ["checkout", "-b", "feature/commits"]);
1517
+ for (let index = 0; index < 102; index++) {
1518
+ yield* git(cwd, ["commit", "--allow-empty", "-m", `feature ${index}`]);
1519
+ }
1520
+
1521
+ const result = yield* driver.getReviewBranchCommits({ cwd, baseRef: initialBranch });
1522
+ assert.strictEqual(result.truncated, true);
1523
+ assert.strictEqual(result.commits.length, 100);
1524
+ assert.strictEqual(result.commits[0]?.sha, yield* git(cwd, ["rev-parse", "HEAD"]));
1525
+ assert.deepStrictEqual(
1526
+ [result.commits[0]?.subject, result.commits[99]?.subject],
1527
+ ["feature 101", "feature 2"],
1528
+ );
1529
+ }),
1530
+ );
1531
+
1532
+ it.effect("previews one selected commit, a merge against its first parent", () =>
1533
+ Effect.gen(function* () {
1534
+ const cwd = yield* makeTmpDir();
1535
+ const { initialBranch } = yield* initRepoWithCommit(cwd);
1536
+ const driver = yield* GitVcsDriver.GitVcsDriver;
1537
+ yield* git(cwd, ["checkout", "-b", "feature/merge-preview"]);
1538
+ yield* git(cwd, ["checkout", "-b", "feature/side"]);
1539
+ yield* writeTextFile(cwd, "README.md", "# side commit\n");
1540
+ yield* git(cwd, ["add", "README.md"]);
1541
+ yield* git(cwd, ["commit", "-m", "side change"]);
1542
+ yield* git(cwd, ["checkout", "feature/merge-preview"]);
1543
+ yield* writeTextFile(cwd, "feature.txt", "feature commit\n");
1544
+ yield* git(cwd, ["add", "feature.txt"]);
1545
+ yield* git(cwd, ["commit", "-m", "feature change"]);
1546
+ const firstParent = yield* git(cwd, ["rev-parse", "HEAD"]);
1547
+ yield* git(cwd, ["merge", "--no-ff", "--no-edit", "feature/side"]);
1548
+ const mergeSha = yield* git(cwd, ["rev-parse", "HEAD"]);
1549
+ yield* git(cwd, ["checkout", "-b", "feature/elsewhere", initialBranch]);
1550
+ yield* writeTextFile(cwd, "elsewhere.txt", "elsewhere\n");
1551
+ yield* git(cwd, ["add", "elsewhere.txt"]);
1552
+ yield* git(cwd, ["commit", "-m", "elsewhere change"]);
1553
+ const elsewhereSha = yield* git(cwd, ["rev-parse", "HEAD"]);
1554
+ yield* git(cwd, ["checkout", "feature/merge-preview"]);
1555
+ yield* writeTextFile(cwd, "README.md", "# dirty tree\n");
1556
+
1557
+ const elsewhere = yield* driver.getReviewDiffPreview({ cwd, commitSha: elsewhereSha });
1558
+ assert.deepStrictEqual(
1559
+ elsewhere.sources
1560
+ .find((candidate) => candidate.kind === "commit")
1561
+ ?.files?.map((file) => file.path),
1562
+ ["elsewhere.txt"],
1563
+ );
1564
+
1565
+ const preview = yield* driver.getReviewDiffPreview({
1566
+ cwd,
1567
+ baseRef: initialBranch,
1568
+ commitSha: mergeSha,
1569
+ });
1570
+ const source = preview.sources.find((candidate) => candidate.kind === "commit")!;
1571
+ assert.strictEqual(source.baseRef, firstParent);
1572
+ assert.strictEqual(source.headRef, mergeSha);
1573
+ assert.deepStrictEqual(
1574
+ source.files?.map((file) => file.path),
1575
+ ["README.md"],
1576
+ );
1577
+ assert.include(source.diff, "+# side commit");
1578
+ assert.notInclude(source.diff, "dirty tree");
1579
+ assert.notInclude(source.diff, "feature.txt");
1580
+
1581
+ const patch = yield* driver.getReviewDiffPreview({
1582
+ cwd,
1583
+ baseRef: initialBranch,
1584
+ commitSha: mergeSha,
1585
+ file: { path: "README.md", previousPath: null, sourceKind: "commit" },
1586
+ });
1587
+ assert.include(
1588
+ patch.sources.find((candidate) => candidate.kind === "commit")!.diff,
1589
+ "+# side commit",
1590
+ );
1591
+ const contents = yield* driver.getReviewDiffFileContents(
1592
+ makeReviewDiffFileContentsInput(cwd, {
1593
+ sourceKind: "commit",
1594
+ baseRef: source.baseRef,
1595
+ headRef: source.headRef,
1596
+ }),
1597
+ );
1598
+ assert.deepStrictEqual(contents, {
1599
+ oldContents: "# test\n",
1600
+ newContents: "# side commit\n",
1601
+ });
1602
+ }),
1603
+ );
1604
+
1605
it.effect("loads repository-relative files from a nested project directory", () =>
1606
Effect.gen(function* () {
1607
const cwd = yield* makeTmpDir();
apps/server/src/vcs/GitVcsDriverCore.ts
+222
-14
@@ -26,6 +26,7 @@ import {
26
GitCommandError,
27
type GitCommandFailureReason,
28
T3_PROJECT_FILE_NAME,
29
+ type ReviewBranchCommitsInput,
30
type ReviewDiffFileContentsInput,
31
type ReviewDiffPreviewInput,
32
type ReviewDiffFileStat,
@@ -74,6 +75,9 @@ const REVIEW_METADATA_MAX_OUTPUT_BYTES = 16 * 1024 * 1024;
75
// Temporary-index git add scales poorly (50k files took ~30 s); report incomplete totals above this cap.
76
const REVIEW_UNTRACKED_MAX_FILES = 5_000;
77
const REVIEW_DIFF_FILE_MAX_OUTPUT_BYTES = 1024 * 1024;
78
+const REVIEW_BRANCH_COMMIT_LIMIT = 100;
79
+const REVIEW_BRANCH_SUBJECT_LIMIT = 300;
80
+const REVIEW_BRANCH_COMMIT_MAX_OUTPUT_BYTES = 128 * 1024;
81
// Client patch parsers require a/ and b/ prefixes; override user diff prefix settings.
82
export const PATCH_RENDER_PREFIX_ARGS = ["--src-prefix=a/", "--dst-prefix=b/"] as const;
83
const REVIEW_DIFF_ARGS = [
@@ -3115,6 +3119,141 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
3119
return { baseRef, insertions, deletions };
3120
}, Effect.scoped);
3121
3122
+ const reviewCommitError = (cwd: string, detail: string) =>
3123
+ new GitCommandError({
3124
+ operation: "GitVcsDriver.reviewCommit",
3125
+ command: "git cat-file",
3126
+ cwd,
3127
+ detail,
3128
+ });
3129
+
3130
+ const resolveReviewCommit = Effect.fn("resolveReviewCommit")(function* (
3131
+ cwd: string,
3132
+ sha: string,
3133
+ ) {
3134
+ if (!/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/i.test(sha)) {
3135
+ return yield* reviewCommitError(cwd, "Selected commit is invalid or no longer available.");
3136
+ }
3137
+ const present = yield* executeGit(
3138
+ "GitVcsDriver.reviewCommit.present",
3139
+ cwd,
3140
+ ["cat-file", "-e", `${sha}^{commit}`],
3141
+ { allowNonZeroExit: true, env: { GIT_NO_LAZY_FETCH: "1" } },
3142
+ );
3143
+ if (present.exitCode !== 0) {
3144
+ return yield* reviewCommitError(cwd, "Selected commit is invalid or no longer available.");
3145
+ }
3146
+ // The raw object keeps the parents a shallow clone grafts away, so a boundary is not a root.
3147
+ const object = yield* runGitStdout("GitVcsDriver.reviewCommit.parents", cwd, [
3148
+ "cat-file",
3149
+ "commit",
3150
+ sha,
3151
+ ]);
3152
+ const secondLine = object.split("\n", 2)[1];
3153
+ const firstParent = secondLine?.startsWith("parent ") ? secondLine.slice(7) : undefined;
3154
+ if (firstParent !== undefined) {
3155
+ const parent = yield* executeGit(
3156
+ "GitVcsDriver.reviewCommit.parent",
3157
+ cwd,
3158
+ ["cat-file", "-e", `${firstParent}^{commit}`],
3159
+ { allowNonZeroExit: true, env: { GIT_NO_LAZY_FETCH: "1" } },
3160
+ );
3161
+ if (parent.exitCode !== 0) {
3162
+ return yield* reviewCommitError(cwd, "Selected commit's parent is not available locally.");
3163
+ }
3164
+ }
3165
+ return { sha: sha.toLowerCase(), parent: firstParent ?? (yield* readEmptyTreeHash(cwd)) };
3166
+ });
3167
+
3168
+ const readReviewCommitMessage = Effect.fn("GitVcsDriver.readReviewCommitMessage")(function* (
3169
+ cwd: string,
3170
+ sha: string,
3171
+ ) {
3172
+ const result = yield* executeGit(
3173
+ "GitVcsDriver.readReviewCommitMessage",
3174
+ cwd,
3175
+ ["show", "-s", "--no-notes", "--no-show-signature", "--format=%B", sha],
3176
+ { maxOutputBytes: 8_192, appendTruncationMarker: true },
3177
+ );
3178
+ const endOfSubject = result.stdout.indexOf("\n");
3179
+ return {
3180
+ subject: result.stdout.slice(0, endOfSubject < 0 ? undefined : endOfSubject).slice(0, 300),
3181
+ };
3182
+ });
3183
+
3184
+ const getReviewBranchCommits = Effect.fn("getReviewBranchCommits")(function* (
3185
+ input: ReviewBranchCommitsInput,
3186
+ ) {
3187
+ const repository = yield* resolveRepositoryPathsUncached(input.cwd);
3188
+ if (!repository?.worktreeRoot) return { commits: [], truncated: false };
3189
+ const cwd = repository.worktreeRoot;
3190
+ const head = yield* executeGit(
3191
+ "GitVcsDriver.getReviewBranchCommits.head",
3192
+ cwd,
3193
+ ["rev-parse", "--verify", "--quiet", "HEAD"],
3194
+ { allowNonZeroExit: true },
3195
+ );
3196
+ if (head.exitCode !== 0) {
3197
+ if (head.exitCode === 1 && head.stderr.trim() === "") {
3198
+ return { commits: [], truncated: false };
3199
+ }
3200
+ return yield* reviewCommitError(cwd, "Could not resolve the current branch commit.");
3201
+ }
3202
+ const { mergeBase } = yield* resolveReviewMergeBase(
3203
+ cwd,
3204
+ repository.currentBranch,
3205
+ input.baseRef,
3206
+ );
3207
+ const result = yield* executeGit(
3208
+ "GitVcsDriver.getReviewBranchCommits",
3209
+ cwd,
3210
+ [
3211
+ "log",
3212
+ "-z",
3213
+ "--no-notes",
3214
+ "--no-show-signature",
3215
+ "--format=%H%x00%s%x00%cI",
3216
+ `--max-count=${REVIEW_BRANCH_COMMIT_LIMIT + 1}`,
3217
+ `${mergeBase}..HEAD`,
3218
+ ],
3219
+ {
3220
+ maxOutputBytes: REVIEW_BRANCH_COMMIT_MAX_OUTPUT_BYTES,
3221
+ appendTruncationMarker: true,
3222
+ },
3223
+ );
3224
+ if (!result.stdoutTruncated && result.stdout.length > 0 && !result.stdout.endsWith("\0")) {
3225
+ return yield* reviewCommitError(cwd, "Could not read branch commit metadata.");
3226
+ }
3227
+ const fields = result.stdout.split("\0");
3228
+ const completeFieldCount = fields.length - 1;
3229
+ const commits: Array<{ sha: string; subject: string; committedAt: string }> = [];
3230
+ for (
3231
+ let index = 0;
3232
+ index + 2 < completeFieldCount && commits.length <= REVIEW_BRANCH_COMMIT_LIMIT;
3233
+ index += 3
3234
+ ) {
3235
+ const sha = fields[index];
3236
+ const subject = fields[index + 1];
3237
+ const committedAt = fields[index + 2];
3238
+ if (
3239
+ !sha ||
3240
+ subject === undefined ||
3241
+ !committedAt ||
3242
+ !/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/i.test(sha)
3243
+ ) {
3244
+ return yield* reviewCommitError(cwd, "Could not read branch commit metadata.");
3245
+ }
3246
+ commits.push({ sha, subject: subject.slice(0, REVIEW_BRANCH_SUBJECT_LIMIT), committedAt });
3247
+ }
3248
+ if (result.stdoutTruncated && commits.length === 0) {
3249
+ return yield* reviewCommitError(cwd, "Branch commit metadata exceeds the response limit.");
3250
+ }
3251
+ return {
3252
+ commits: commits.slice(0, REVIEW_BRANCH_COMMIT_LIMIT),
3253
+ truncated: result.stdoutTruncated || commits.length > REVIEW_BRANCH_COMMIT_LIMIT,
3254
+ };
3255
+ });
3256
+
3257
const getReviewDiffPreview = Effect.fn("getReviewDiffPreview")(function* (
3258
input: ReviewDiffPreviewInput,
3259
) {
@@ -3141,6 +3280,64 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
3280
}
3281
3282
const cwd = repository.worktreeRoot;
3283
+ const hashDiff = (diff: string, files: ReadonlyArray<ReviewDiffFileStat>) =>
3284
+ crypto.digest("SHA-256", new TextEncoder().encode(JSON.stringify([diff, files]))).pipe(
3285
+ Effect.map(Hex.encode),
3286
+ Effect.mapError(
3287
+ (cause) =>
3288
+ new GitCommandError({
3289
+ operation: "GitVcsDriver.getReviewDiffPreview.hash",
3290
+ command: "crypto.digest SHA-256",
3291
+ cwd,
3292
+ detail: "Failed to hash review diff.",
3293
+ cause,
3294
+ }),
3295
+ ),
3296
+ );
3297
+ if (input.commitSha !== undefined || input.file?.sourceKind === "commit") {
3298
+ if (!input.commitSha || (input.file && input.file.sourceKind !== "commit")) {
3299
+ return yield* reviewCommitError(cwd, "Selected commit request is invalid.");
3300
+ }
3301
+ const commit = yield* resolveReviewCommit(cwd, input.commitSha);
3302
+ const { subject } = yield* readReviewCommitMessage(cwd, commit.sha);
3303
+ const diffArgs = [
3304
+ ...REVIEW_DIFF_ARGS,
3305
+ ...(input.ignoreWhitespace ? ["--ignore-all-space"] : []),
3306
+ ];
3307
+ const stat = yield* executeGit(
3308
+ "GitVcsDriver.getReviewDiffPreview.commitStat",
3309
+ cwd,
3310
+ [...diffArgs, "--numstat", "-z", commit.parent, commit.sha, "--", ...pathArgs],
3311
+ { maxOutputBytes: REVIEW_METADATA_MAX_OUTPUT_BYTES },
3312
+ );
3313
+ const files = parseReviewNumstat(stat.stdout);
3314
+ const patch = yield* executeGit(
3315
+ "GitVcsDriver.getReviewDiffPreview.commitPatch",
3316
+ cwd,
3317
+ [...diffArgs, "--patch", commit.parent, commit.sha, "--", ...pathArgs],
3318
+ { maxOutputBytes: patchLimit, appendTruncationMarker: true },
3319
+ );
3320
+ const diffHash = yield* hashDiff(patch.stdout, files);
3321
+ return {
3322
+ cwd: input.cwd,
3323
+ generatedAt: yield* DateTime.now,
3324
+ sources: [
3325
+ {
3326
+ id: commit.sha,
3327
+ kind: "commit" as const,
3328
+ title: `Commit ${commit.sha.slice(0, 7)}`,
3329
+ ...(subject.trim() ? { commitSubject: subject.trim() } : {}),
3330
+ baseRef: commit.parent,
3331
+ headRef: commit.sha,
3332
+ diff: patch.stdout,
3333
+ files,
3334
+ diffHash,
3335
+ truncated: patch.stdoutTruncated,
3336
+ },
3337
+ ],
3338
+ };
3339
+ }
3340
+
3341
const dirtyRef = input.file?.sourceKind === "branch-range" ? null : "HEAD";
3342
const review =
3343
input.file?.sourceKind === "working-tree"
@@ -3220,20 +3417,6 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
3417
const baseFiles = baseResult.files;
3418
const dirtyDiff = dirtyTrackedResult.stdout;
3419
const baseDiff = baseResult.stdout;
3223
- const hashDiff = (diff: string, files: ReadonlyArray<ReviewDiffFileStat>) =>
3224
- crypto.digest("SHA-256", new TextEncoder().encode(JSON.stringify([diff, files]))).pipe(
3225
- Effect.map(Hex.encode),
3226
- Effect.mapError(
3227
- (cause) =>
3228
- new GitCommandError({
3229
- operation: "GitVcsDriver.getReviewDiffPreview.hash",
3230
- command: "crypto.digest SHA-256",
3231
- cwd,
3232
- detail: "Failed to hash review diff.",
3233
- cause,
3234
- }),
3235
- ),
3236
- );
3420
const [dirtyDiffHash, baseDiffHash] = yield* Effect.all([
3421
hashDiff(dirtyDiff, dirtyFiles ?? []),
3422
hashDiff(baseDiff, baseFiles ?? []),
@@ -3385,6 +3568,30 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
3568
if (repositoryRoot.length === 0) {
3569
return yield* reviewDiffFileError(input, "Could not resolve the Git repository root.");
3570
}
3571
+ if (input.sourceKind === "commit") {
3572
+ if (!input.headRef) {
3573
+ return yield* reviewDiffFileError(input, "Selected commit is no longer available.");
3574
+ }
3575
+ const commit = yield* resolveReviewCommit(input.cwd, input.headRef);
3576
+ if (input.baseRef !== commit.parent) {
3577
+ return yield* reviewDiffFileError(
3578
+ input,
3579
+ "Selected commit changed. Refresh the comparison.",
3580
+ );
3581
+ }
3582
+ const [oldContents, newContents] = yield* Effect.all(
3583
+ [
3584
+ input.changeType === "new"
3585
+ ? Effect.succeed("")
3586
+ : readReviewFileAtRevision(input, commit.parent, input.oldPath),
3587
+ input.changeType === "deleted"
3588
+ ? Effect.succeed("")
3589
+ : readReviewFileAtRevision(input, commit.sha, input.newPath),
3590
+ ],
3591
+ { concurrency: 2 },
3592
+ );
3593
+ return { oldContents, newContents };
3594
+ }
3595
const oldRevision =
3596
input.sourceKind === "working-tree"
3597
? (input.baseRef ?? "HEAD")
@@ -4649,6 +4856,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
4856
return yield* withListRefsInvalidation(cwd, pullCurrentBranch(cwd));
4857
}),
4858
readRangeContext,
4859
+ getReviewBranchCommits,
4860
getReviewDiffPreview,
4861
getReviewDiffFileContents,
4862
readConfigValue,
apps/server/src/ws.ts
+1
@@ -3001,6 +3001,7 @@ export const layerWsRpc = (
3001
gitWorkflow.switchRef(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))),
3002
[WS_METHODS.vcsInit]: (input) =>
3003
vcsProvisioning.initRepository(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))),
3004
+ [WS_METHODS.reviewGetBranchCommits]: (input) => review.getBranchCommits(input),
3005
[WS_METHODS.reviewGetDiffPreview]: (input) => review.getDiffPreview(input),
3006
[WS_METHODS.reviewGetDiffFileContents]: (input) => review.getDiffFileContents(input),
3007
[WS_METHODS.terminalOpen]: (input) => terminalManager.open(input),
apps/web/src/browser/browserLinkTarget.ts
+11
-2
@@ -1,6 +1,11 @@
1
-import type { BrowserLinkTarget, ScopedThreadRef } from "@t3tools/contracts";
1
+import {
2
+ AuthPreviewOperateScope,
3
+ type BrowserLinkTarget,
4
+ type ScopedThreadRef,
5
+} from "@t3tools/contracts";
6
7
import { ensureClientSettingsHydrated, getClientSettings } from "~/hooks/useSettings";
8
+import { readEnvironmentScope } from "~/state/session";
9
import { isPreviewAvailableFor } from "./previewRuntime";
10
11
export interface ResolveLinkTargetInput {
@@ -38,5 +43,9 @@ export async function resolveBrowserLinkTargetPreference(): Promise<BrowserLinkT
43
}
44
45
export function canOpenLinksInApp(threadRef: ScopedThreadRef | null | undefined): boolean {
41
- return threadRef != null && isPreviewAvailableFor(threadRef.environmentId);
46
+ return (
47
+ threadRef != null &&
48
+ readEnvironmentScope(threadRef.environmentId, AuthPreviewOperateScope) &&
49
+ isPreviewAvailableFor(threadRef.environmentId)
50
+ );
51
}
apps/web/src/browser/useOpenLink.ts
+2
-6
@@ -1,4 +1,4 @@
1
-import { AuthPreviewOperateScope, type ScopedThreadRef } from "@t3tools/contracts";
1
+import type { ScopedThreadRef } from "@t3tools/contracts";
2
import {
3
isAtomCommandInterrupted,
4
squashAtomCommandFailure,
@@ -6,7 +6,6 @@ import {
6
import { recordVisitForThread } from "~/browserHistoryStore";
7
import { readLocalApi } from "~/localApi";
8
import { previewEnvironment } from "~/state/preview";
9
-import { readEnvironmentScope } from "~/state/session";
9
import { useAtomCommand } from "~/state/use-atom-command";
10
11
import {
@@ -37,10 +36,7 @@ export function useOpenLink(threadRef: ScopedThreadRef | null | undefined): (
36
url,
37
event: options.event ?? NO_MODIFIER,
38
preference: await resolveBrowserLinkTargetPreference(),
40
- canOpenInApp:
41
- targetThreadRef != null &&
42
- readEnvironmentScope(targetThreadRef.environmentId, AuthPreviewOperateScope) &&
43
- canOpenLinksInApp(targetThreadRef),
39
+ canOpenInApp: canOpenLinksInApp(targetThreadRef),
40
});
41
if (target === "app" && targetThreadRef) {
42
const result = await openUrlInPreview({ threadRef: targetThreadRef, url, openPreview });
apps/web/src/components/ChatView.tsx
+6
-1
@@ -1010,7 +1010,12 @@ export default function ChatView(props: ChatViewProps) {
1010
useLayoutEffect(() => {
1011
const explicitThreadRef = explicitDiffOpenRef.current;
1012
explicitDiffOpenRef.current = null;
1013
- if (diffOpen && activeThreadRef && explicitThreadRef !== activeThreadRef) {
1013
+ if (
1014
+ diffOpen &&
1015
+ activeThreadRef &&
1016
+ explicitThreadRef !== activeThreadRef &&
1017
+ !useDiffPanelStore.getState().consumeKeepSelectionOnOpen(activeThreadRef)
1018
+ ) {
1019
useDiffPanelStore.getState().selectGitScope(activeThreadRef, "branch");
1020
}
1021
}, [activeThreadRef, diffOpen]);
apps/web/src/components/DiffPanel.tsx
+223
-29
@@ -6,7 +6,7 @@ import {
6
squashAtomCommandFailure,
7
} from "@t3tools/client-runtime/state/runtime";
8
import { safeErrorLogAttributes } from "@t3tools/client-runtime/errors";
9
-import type { ScopedThreadRef, RunId } from "@t3tools/contracts";
9
+import type { ReviewBranchCommitsResult, ScopedThreadRef, RunId } from "@t3tools/contracts";
10
import {
11
ArrowRightIcon,
12
CheckIcon,
@@ -20,7 +20,7 @@ import {
20
} from "lucide-react";
21
import { ChevronDown, ChevronRight, ChevronsDownUp, ChevronsUpDown } from "lucide";
22
import * as Schema from "effect/Schema";
23
-import { useEffect, useRef, useState } from "react";
23
+import { type MouseEvent, useEffect, useRef, useState } from "react";
24
import { useCodeViewFileReveal } from "./diffs/useCodeViewFileReveal";
25
import { useFilesystemReadAccess } from "~/state/filesystem";
26
import { useOpenInPreferredEditor } from "../editorPreferences";
@@ -33,6 +33,7 @@ import { revisionedQuery } from "~/state/revisionedQuery";
33
import { cn } from "~/lib/utils";
34
import {
35
resolveToolCallDiffTarget,
36
+ selectThreadBranchBaseRef,
37
selectThreadDiffPanelSelection,
38
useDiffPanelSessionStore,
39
useDiffPanelStore,
@@ -60,7 +61,7 @@ import {
61
useQuietThreadVisibleTurnItems,
62
} from "../state/entities";
63
import { useClientSettings, updateClientSettings } from "../hooks/useSettings";
63
-import { formatShortTimestamp } from "../timestampFormat";
64
+import { formatRelativeTimeLabel, formatShortTimestamp } from "../timestampFormat";
65
import { DiffFilePathCopyButton } from "./DiffFilePathCopyButton";
66
import { DiffPanelLoadingState, DiffPanelShell, type DiffPanelMode } from "./DiffPanelShell";
67
import { DiffStatLabel } from "./chat/DiffStatLabel";
@@ -83,6 +84,7 @@ import {
84
import {
85
DropdownMenu,
86
DropdownMenuContent,
87
+ DropdownMenuItem,
88
DropdownMenuRadioGroup,
89
DropdownMenuRadioItem,
90
DropdownMenuSub,
@@ -103,6 +105,8 @@ import { useReviewFilePatches } from "./diffs/useReviewFilePatches";
105
import { DiffFileLoadingBoundary } from "./diffs/DiffFileLoadingBoundary";
106
import { DiffFileStatus } from "./diffs/DiffFileStatus";
107
import { useThreadRouteRef } from "../hooks/useThreadRouteTarget";
108
+import { projectCommitUrl } from "@t3tools/client-runtime/change-request-links";
109
+import { useOpenLink } from "../browser/useOpenLink";
110
111
type DiffThemeType = "light" | "dark";
112
const AUTOMATIC_BASE_REF = "__automatic_base_ref__";
@@ -223,6 +227,8 @@ export default function DiffPanel({
227
);
228
const [hideTestFiles, setHideTestFiles] = useHideTestFiles();
229
const [baseRefQuery, setBaseRefQuery] = useState("");
230
+ // The open commit menu keeps the list it opened with, so rows do not move under the pointer.
231
+ const [openCommitMenu, setOpenCommitMenu] = useState<ReviewBranchCommitsResult | null>(null);
232
const [codeViewRevision, setCodeViewRevision] = useState(0);
233
234
const routeThreadRef = useThreadRouteRef();
@@ -263,8 +269,14 @@ export default function DiffPanel({
269
const diffSelection = useDiffPanelStore((state) =>
270
selectThreadDiffPanelSelection(state.byThreadKey, routeThreadRef),
271
);
272
+ const rememberedBaseRef = useDiffPanelStore((state) =>
273
+ selectThreadBranchBaseRef(state, routeThreadRef),
274
+ );
275
const toolCallSelection = diffSelection.kind === "tool-call" ? diffSelection : null;
267
- const isGitSelection = diffSelection.kind === "branch" || diffSelection.kind === "unstaged";
276
+ const isGitSelection =
277
+ diffSelection.kind === "branch" ||
278
+ diffSelection.kind === "unstaged" ||
279
+ diffSelection.kind === "commit";
280
const toolCallItems = useQuietThreadVisibleTurnItems(toolCallSelection ? routeThreadRef : null);
281
const toolCallDetail = useTurnItemDetail(
282
toolCallSelection && routeThreadRef
@@ -294,8 +306,15 @@ export default function DiffPanel({
306
}, [diffSelection, orderedTurnDiffSummaries, routeThreadRef]);
307
308
const selectedRunId = diffSelection.kind === "turn" ? diffSelection.turnId : null;
297
- const selectedGitScope = diffSelection.kind === "unstaged" ? "unstaged" : "branch";
298
- const selectedBaseRef = diffSelection.kind === "branch" ? diffSelection.baseRef : null;
309
+ const selectedGitScope =
310
+ diffSelection.kind === "unstaged" || diffSelection.kind === "commit"
311
+ ? diffSelection.kind
312
+ : "branch";
313
+ const selectedCommitSha = diffSelection.kind === "commit" ? diffSelection.sha : null;
314
+ const selectedBaseRef =
315
+ diffSelection.kind === "branch" || diffSelection.kind === "commit"
316
+ ? diffSelection.baseRef
317
+ : null;
318
const selectedFilePath = diffSelection.kind === "turn" ? diffSelection.filePath : null;
319
const selectedFileRevealRequestId =
320
diffSelection.kind === "turn" ? diffSelection.revealRequestId : 0;
@@ -306,31 +325,17 @@ export default function DiffPanel({
325
orderedTurnDiffSummaries[0]);
326
const selectedCheckpointTurnCount = selectedTurn?.checkpointTurnCount;
327
const latestTurn = orderedTurnDiffSummaries[0];
309
- const selectedScopeLabel = toolCallSelection
310
- ? "Tool call"
311
- : selectedRunId === null
312
- ? selectedGitScope === "unstaged"
313
- ? "Uncommitted"
314
- : "Changes"
315
- : selectedTurn?.runId === latestTurn?.runId
316
- ? "Latest turn"
317
- : `Turn ${selectedCheckpointTurnCount ?? "?"}`;
328
const reviewSectionId = toolCallSelection
329
? `tool-call:${toolCallSelection.threadId}:${toolCallSelection.itemId}`
330
: selectedTurn
331
? `turn:${selectedTurn.runId}`
322
- : selectedGitScope;
332
+ : selectedCommitSha !== null
333
+ ? `commit:${selectedCommitSha}`
334
+ : selectedGitScope;
335
const collapseScopeKey = routeThreadRef
336
? `${routeThreadRef.environmentId}:${routeThreadRef.threadId}:${reviewSectionId}`
337
: null;
338
const codeViewMountKey = `${collapseScopeKey ?? reviewSectionId}:${codeViewRevision}`;
327
- const reviewSectionTitle = toolCallSelection
328
- ? "Tool call"
329
- : selectedTurn
330
- ? `Turn ${selectedCheckpointTurnCount ?? "?"}`
331
- : selectedGitScope === "unstaged"
332
- ? "Uncommitted"
333
- : "Changes";
339
const selectedCheckpointRange =
340
typeof selectedCheckpointTurnCount === "number"
341
? {
@@ -354,6 +359,7 @@ export default function DiffPanel({
359
? {
360
cwd: activeCwd,
361
...(selectedBaseRef ? { baseRef: selectedBaseRef } : {}),
362
+ ...(selectedCommitSha !== null ? { commitSha: selectedCommitSha } : {}),
363
ignoreWhitespace: diffIgnoreWhitespace,
364
}
365
: undefined;
@@ -372,13 +378,69 @@ export default function DiffPanel({
378
)
379
: null,
380
);
381
+ const branchCommitsQuery = useEnvironmentQuery(
382
+ visible && isGitRepo && canReadFiles && activeThread && activeCwd
383
+ ? reviewEnvironment.branchCommits({
384
+ environmentId: activeThread.environmentId,
385
+ input: {
386
+ cwd: activeCwd,
387
+ ...(rememberedBaseRef ? { baseRef: rememberedBaseRef } : {}),
388
+ },
389
+ })
390
+ : null,
391
+ );
392
+ const branchCommits = openCommitMenu ?? branchCommitsQuery.data;
393
const activeThreadRefreshKey = routeThreadRef
394
? `${routeThreadRef.environmentId}:${routeThreadRef.threadId}`
395
: null;
396
397
const selectedGitSource = branchDiffPreview.data?.sources.find(
380
- (source) => source.kind === (selectedGitScope === "unstaged" ? "working-tree" : "branch-range"),
398
+ (source) =>
399
+ source.kind ===
400
+ (selectedGitScope === "unstaged"
401
+ ? "working-tree"
402
+ : selectedGitScope === "commit"
403
+ ? "commit"
404
+ : "branch-range"),
405
);
406
+ const selectedCommitSubject =
407
+ selectedCommitSha !== null && selectedGitSource?.headRef === selectedCommitSha
408
+ ? selectedGitSource.commitSubject
409
+ : undefined;
410
+ const selectedGitScopeLabel =
411
+ selectedCommitSha !== null
412
+ ? (selectedCommitSubject ?? `Commit ${selectedCommitSha.slice(0, 7)}`)
413
+ : selectedGitScope === "unstaged"
414
+ ? "Uncommitted"
415
+ : "Changes";
416
+ const selectedScopeLabel = toolCallSelection
417
+ ? "Tool call"
418
+ : selectedRunId === null
419
+ ? selectedCommitSha !== null
420
+ ? (selectedCommitSubject ?? "Commit")
421
+ : selectedGitScopeLabel
422
+ : selectedTurn?.runId === latestTurn?.runId
423
+ ? "Latest turn"
424
+ : `Turn ${selectedCheckpointTurnCount ?? "?"}`;
425
+ const reviewSectionTitle = toolCallSelection
426
+ ? "Tool call"
427
+ : selectedTurn
428
+ ? `Turn ${selectedCheckpointTurnCount ?? "?"}`
429
+ : selectedGitScopeLabel;
430
+ const headerCommitSha = selectedRunId === null ? selectedCommitSha : null;
431
+ const selectedCommitUrl =
432
+ headerCommitSha !== null
433
+ ? projectCommitUrl(activeProject?.repositoryIdentity, headerCommitSha)
434
+ : null;
435
+ const openLink = useOpenLink(routeThreadRef);
436
+ // A SHA link goes to the code host; it must not route back into this pane's commit selection.
437
+ const openCommitUrl = (event: MouseEvent<HTMLElement>, url: string) => {
438
+ event.stopPropagation();
439
+ if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey || event.button === 1)
440
+ return;
441
+ event.preventDefault();
442
+ void openLink(url, { event });
443
+ };
444
const refreshPreviewQuery = branchDiffPreview.refresh;
445
const refreshDiffFromUserAction = refreshPreviewQuery;
446
@@ -512,7 +574,8 @@ export default function DiffPanel({
574
environmentId: activeThread?.environmentId,
575
cwd: branchDiffPreview.data?.cwd,
576
source: lazySource,
515
- baseRef: lazySource?.baseRef ?? selectedBaseRef,
577
+ baseRef:
578
+ selectedCommitSha !== null ? selectedBaseRef : (lazySource?.baseRef ?? selectedBaseRef),
579
ignoreWhitespace: diffIgnoreWhitespace,
580
theme: resolvedTheme,
581
previewInput: branchDiffPreviewInput,
@@ -693,16 +756,23 @@ export default function DiffPanel({
756
useDiffPanelStore.getState().selectBranchBaseRef(routeThreadRef, baseRef);
757
};
758
const selectedTurnValue = selectedTurn ? `turn:${selectedTurn.runId}` : "";
759
+ const selectedCommitValue = selectedCommitSha !== null ? `commit:${selectedCommitSha}` : "";
760
const selectedScopeValue = toolCallSelection
761
? ""
762
: selectedRunId === null
699
- ? selectedGitScope
763
+ ? selectedCommitValue || selectedGitScope
764
: selectedTurn?.runId === latestTurn?.runId
765
? "latest"
766
: selectedTurnValue;
767
const selectScopeValue = (value: string) => {
768
if (value === "unstaged" || value === "branch") {
769
selectGitScope(value);
770
+ } else if (value === selectedCommitValue) {
771
+ selectGitScope("branch");
772
+ } else if (value.startsWith("commit:")) {
773
+ if (routeThreadRef) {
774
+ useDiffPanelStore.getState().selectCommit(routeThreadRef, value.slice("commit:".length));
775
+ }
776
} else if (value === "latest") {
777
if (latestTurn) selectTurn(latestTurn.runId);
778
} else {
@@ -717,13 +787,37 @@ export default function DiffPanel({
787
<DropdownMenu>
788
<DropdownMenuTrigger
789
render={<Button size="xs" variant="secondary" />}
720
- className="max-w-full"
790
+ className={cn("max-w-full", headerCommitSha !== null && "min-w-0 shrink")}
791
aria-label={`Diff scope: ${selectedScopeLabel}`}
792
data-workspace-focus-default
793
>
794
<span className="truncate">{selectedScopeLabel}</span>
795
<ChevronDownIcon className="size-3.5 shrink-0 opacity-70" />
796
</DropdownMenuTrigger>
797
+ {headerCommitSha !== null ? (
798
+ selectedCommitUrl ? (
799
+ <Tooltip>
800
+ <TooltipTrigger
801
+ render={
802
+ <a
803
+ href={selectedCommitUrl}
804
+ target="_blank"
805
+ rel="noopener noreferrer"
806
+ className="shrink-0 font-mono text-xs text-muted-foreground underline underline-offset-4"
807
+ onClick={(event) => openCommitUrl(event, selectedCommitUrl)}
808
+ />
809
+ }
810
+ >
811
+ {headerCommitSha.slice(0, 7)}
812
+ </TooltipTrigger>
813
+ <TooltipPopup side="top">{selectedCommitUrl}</TooltipPopup>
814
+ </Tooltip>
815
+ ) : (
816
+ <span className="shrink-0 font-mono text-xs text-muted-foreground">
817
+ {headerCommitSha.slice(0, 7)}
818
+ </span>
819
+ )
820
+ ) : null}
821
<DropdownMenuContent align="start">
822
<DropdownMenuRadioGroup value={selectedScopeValue} onValueChange={selectScopeValue}>
823
<DropdownMenuRadioItem value="branch" closeOnClick>
@@ -760,6 +854,99 @@ export default function DiffPanel({
854
</DropdownMenuRadioGroup>
855
</DropdownMenuSubContent>
856
</DropdownMenuSub>
857
+ <DropdownMenuSub
858
+ onOpenChange={(open) => {
859
+ setOpenCommitMenu(open ? (branchCommitsQuery.data ?? null) : null);
860
+ if (!open) return;
861
+ // The menu keeps the list it opened with; the refreshed one shows next time.
862
+ branchCommitsQuery.refresh();
863
+ }}
864
+ >
865
+ <DropdownMenuSubTrigger>Commits</DropdownMenuSubTrigger>
866
+ <DropdownMenuSubContent className="max-h-80 max-w-96">
867
+ <DropdownMenuRadioGroup
868
+ value={selectedCommitValue}
869
+ onValueChange={selectScopeValue}
870
+ >
871
+ {branchCommits?.commits.map((commit) => {
872
+ const commitUrl = projectCommitUrl(
873
+ activeProject?.repositoryIdentity,
874
+ commit.sha,
875
+ );
876
+ return (
877
+ <div
878
+ key={commit.sha}
879
+ className={cn(
880
+ "flex items-center rounded-sm hover:bg-accent has-data-highlighted:bg-accent has-focus-visible:bg-accent [&_[data-checked]]:bg-transparent [&_[data-highlighted]]:bg-transparent",
881
+ selectedCommitSha === commit.sha && "bg-foreground/[0.08]",
882
+ )}
883
+ >
884
+ <Tooltip>
885
+ <TooltipTrigger
886
+ render={
887
+ <DropdownMenuRadioItem
888
+ className="min-w-0 flex-1"
889
+ value={`commit:${commit.sha}`}
890
+ closeOnClick
891
+ />
892
+ }
893
+ >
894
+ <span className="flex items-center gap-3">
895
+ <span className="min-w-0 flex-1 truncate">{commit.subject}</span>
896
+ <span className="shrink-0 text-xs tabular-nums text-muted-foreground">
897
+ {formatRelativeTimeLabel(commit.committedAt)}
898
+ </span>
899
+ </span>
900
+ </TooltipTrigger>
901
+ <TooltipPopup side="right" className="max-w-80">
902
+ {commit.subject}
903
+ </TooltipPopup>
904
+ </Tooltip>
905
+ {commitUrl ? (
906
+ <DropdownMenuItem
907
+ className="shrink-0"
908
+ render={
909
+ <a
910
+ href={commitUrl}
911
+ target="_blank"
912
+ rel="noopener noreferrer"
913
+ aria-label={`Open commit ${commit.sha.slice(0, 7)}`}
914
+ />
915
+ }
916
+ onClick={(event) => openCommitUrl(event, commitUrl)}
917
+ >
918
+ <span className="font-mono text-xs text-muted-foreground underline underline-offset-4">
919
+ {commit.sha.slice(0, 7)}
920
+ </span>
921
+ </DropdownMenuItem>
922
+ ) : (
923
+ <span className="shrink-0 px-2 font-mono text-xs text-muted-foreground">
924
+ {commit.sha.slice(0, 7)}
925
+ </span>
926
+ )}
927
+ </div>
928
+ );
929
+ })}
930
+ </DropdownMenuRadioGroup>
931
+ {branchCommitsQuery.error ? (
932
+ <DropdownMenuItem disabled>{branchCommitsQuery.error}</DropdownMenuItem>
933
+ ) : !canReadFiles ? (
934
+ <DropdownMenuItem disabled>
935
+ {fileAccess.isPending
936
+ ? "Checking file access..."
937
+ : (fileAccess.error ?? "This connection cannot read local diffs.")}
938
+ </DropdownMenuItem>
939
+ ) : branchCommits === null ? (
940
+ <DropdownMenuItem disabled>Loading commits...</DropdownMenuItem>
941
+ ) : branchCommits.commits.length === 0 ? (
942
+ <DropdownMenuItem disabled>No commits on this branch.</DropdownMenuItem>
943
+ ) : branchCommits.truncated ? (
944
+ <DropdownMenuItem disabled>
945
+ {`Showing latest ${branchCommits.commits.length} commits`}
946
+ </DropdownMenuItem>
947
+ ) : null}
948
+ </DropdownMenuSubContent>
949
+ </DropdownMenuSub>
950
</DropdownMenuContent>
951
</DropdownMenu>
952
{isGitSelection && selectedGitScope === "branch" && selectedGitSource?.baseRef && (
@@ -894,7 +1081,12 @@ export default function DiffPanel({
1081
</div>
1082
)}
1083
</div>
897
- <div className="flex shrink-0 items-center gap-1 [-webkit-app-region:no-drag]">
1084
+ <div
1085
+ className={cn(
1086
+ "flex shrink-0 items-center gap-1 [-webkit-app-region:no-drag]",
1087
+ headerCommitSha !== null && "gap-0",
1088
+ )}
1089
+ >
1090
{codeViewFiles.length > 0 || (isGitSelection && selectedGitSource?.files?.length) ? (
1091
<DiffStatLabel
1092
additions={diffLineStat.additions}
@@ -1124,7 +1316,9 @@ export default function DiffPanel({
1316
? "Loading checkpoint diff..."
1317
: selectedGitScope === "unstaged"
1318
? "Loading uncommitted changes..."
1127
- : "Loading changes..."
1319
+ : selectedGitScope === "commit"
1320
+ ? "Loading commit..."
1321
+ : "Loading changes..."
1322
}
1323
/>
1324
) : (
apps/web/src/components/desktop/DesktopWebLinkCoordinator.browser.test.tsx
+111
-6
@@ -1,11 +1,16 @@
1
-import { EnvironmentId, ProjectId } from "@t3tools/contracts";
2
-import type { Atom } from "effect/reactivity";
1
+import { EnvironmentId, ProjectId, ThreadId } from "@t3tools/contracts";
2
+import { scopeThreadRef } from "@t3tools/client-runtime/environment";
3
+import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
4
+import { AsyncResult, type Atom } from "effect/reactivity";
5
import { expect, it, vi } from "vite-plus/test";
6
7
import { act, render, stubGlobal } from "../../../test/render";
8
9
const state = vi.hoisted(() => ({
8
- projects: [] as never[],
10
+ projects: [] as EnvironmentProject[],
11
+ routeParams: {} as Record<string, string>,
12
+ preview: vi.fn(),
13
+ openLink: vi.fn(async () => undefined),
14
navigate: vi.fn(async (): Promise<void> => undefined),
15
openScratchProject: vi.fn(async () => null),
16
confirm: vi.fn(async (_message: string) => true),
@@ -18,7 +23,10 @@ const state = vi.hoisted(() => ({
23
vi.mock(import("@tanstack/react-router"), async (original) => ({
24
...(await original()),
25
useNavigate: (() => state.navigate) as never,
21
- useRouter: (() => ({ navigate: state.navigate, state: { matches: [] } })) as never,
26
+ useRouter: (() => ({
27
+ navigate: state.navigate,
28
+ state: { matches: [{ params: state.routeParams }] },
29
+ })) as never,
30
}));
31
vi.mock(import("../../state/environments"), async (original) => ({
32
...(await original()),
@@ -47,11 +55,17 @@ vi.mock(import("../../state/server"), async (original) => {
55
});
56
vi.mock(import("../../state/shell"), async (original) => {
57
const { Atom } = await import("effect/reactivity");
50
- return { ...(await original()), allReachableShellsLiveAtom: Atom.make(false) };
58
+ return {
59
+ ...(await original()),
60
+ allReachableShellsLiveAtom: Atom.make(false).pipe(Atom.keepAlive),
61
+ };
62
});
63
vi.mock(import("../../state/entities"), async (original) => ({
64
...(await original()),
65
readProjects: () => state.projects,
66
+ readThreadShell: (ref: { threadId: string }) =>
67
+ ref.threadId === "thread" ? ({ projectId: "effect", worktreePath: null } as never) : null,
68
+ readProject: () => state.projects[0] ?? null,
69
}));
70
vi.mock(import("../../hooks/useScratchProject"), async (original) => ({
71
...(await original()),
@@ -61,6 +75,10 @@ vi.mock(import("../../hooks/useScratchProject"), async (original) => ({
75
})) as never,
76
}));
77
78
+vi.mock("../../state/use-atom-query-runner", () => ({
79
+ useAtomQueryRunner: () => state.preview,
80
+}));
81
+vi.mock("../../browser/useOpenLink", () => ({ useOpenLink: () => state.openLink }));
82
vi.mock(import("../../confirmDialog"), async (original) => ({
83
...(await original()),
84
requestConfirmDialog: state.confirm,
@@ -82,6 +100,12 @@ vi.mock(import("../../state/use-atom-command"), async (original) => {
100
101
import { AppAtomRegistryProvider, appAtomRegistry } from "../../rpc/atomRegistry";
102
import { allReachableShellsLiveAtom } from "../../state/shell";
103
+import { selectThreadDiffPanelSelection, useDiffPanelStore } from "../../diffPanelStore";
104
+import {
105
+ selectActiveRightPanel,
106
+ selectActiveRightPanelSurface,
107
+ useRightPanelStore,
108
+} from "../../rightPanelStore";
109
import { DesktopWebLinkCoordinator } from "./DesktopWebLinkCoordinator";
110
111
const discoverySettled = allReachableShellsLiveAtom as Atom.Writable<boolean>;
@@ -89,6 +113,7 @@ const environmentId = EnvironmentId.make("local");
113
const projectId = ProjectId.make("effect");
114
const project = {
115
id: projectId,
116
+ workspaceRoot: "/workspace/effect",
117
environmentId,
118
repositoryIdentity: {
119
provider: "github",
@@ -100,7 +125,7 @@ const project = {
125
remoteUrl: "https://github.com/Effect-TS/effect.git",
126
},
127
},
103
-} as never;
128
+} as EnvironmentProject;
129
const pullRequestUrl = "https://github.com/Effect-TS/effect/pull/9339";
130
const pullRequestView = {
131
to: "/pull-requests",
@@ -123,6 +148,12 @@ function setup() {
148
state.confirm.mockResolvedValue(true);
149
state.localEnvironmentDisabled = false;
150
state.projects = [];
151
+ state.routeParams = {};
152
+ state.preview
153
+ .mockReset()
154
+ .mockResolvedValue(AsyncResult.success({ sources: [{ kind: "commit", headRef: sha }] }));
155
+ useDiffPanelStore.setState({ byThreadKey: {}, branchBaseRefByThreadKey: {} });
156
+ useRightPanelStore.setState({ byThreadKey: {}, userActionRevisionByThreadKey: {} });
157
appAtomRegistry.set(discoverySettled, false);
158
}
159
@@ -172,6 +203,80 @@ it("holds a launch PR link until project discovery settles, then opens the PR vi
203
expect(state.openScratchProject).not.toHaveBeenCalled();
204
});
205
206
+const sha = "a".repeat(40);
207
+const commitUrl = `https://github.com/Effect-TS/effect/pull/9339/commits/${sha}`;
208
+const threadRef = scopeThreadRef(environmentId, ThreadId.make("thread"));
209
+
210
+it.each([
211
+ ["github.com", "pull/9339/commits"],
212
+ ["code.example.com:8443", "commit"],
213
+])("opens a %s/%s commit in the active thread's Diff pane after discovery", async (host, path) => {
214
+ setup();
215
+ state.routeParams = { environmentId: "local", threadId: "thread" };
216
+ await using _coordinator = await mount(`https://${host}/Effect-TS/effect/${path}/${sha}`);
217
+ expect(state.preview).not.toHaveBeenCalled();
218
+
219
+ state.projects = [
220
+ {
221
+ ...project,
222
+ repositoryIdentity: {
223
+ ...project.repositoryIdentity,
224
+ canonicalKey: `${host}/effect-ts/effect`,
225
+ locator: {
226
+ ...project.repositoryIdentity?.locator,
227
+ remoteUrl: `https://${host}/Effect-TS/effect.git`,
228
+ },
229
+ },
230
+ } as EnvironmentProject,
231
+ ];
232
+ await act(async () => appAtomRegistry.set(discoverySettled, true));
233
+ await vi.waitFor(() => {
234
+ expect(selectActiveRightPanel(useRightPanelStore.getState().byThreadKey, threadRef)).toBe(
235
+ "diff",
236
+ );
237
+ });
238
+ expect(
239
+ selectThreadDiffPanelSelection(useDiffPanelStore.getState().byThreadKey, threadRef),
240
+ ).toMatchObject({ kind: "commit", sha });
241
+ expect(state.preview).toHaveBeenCalledExactlyOnceWith({
242
+ environmentId,
243
+ input: expect.objectContaining({ cwd: "/workspace/effect", commitSha: sha }),
244
+ });
245
+ expect(state.navigate).not.toHaveBeenCalled();
246
+ expect(state.openLink).not.toHaveBeenCalled();
247
+});
248
+
249
+it("opens a PR commit the workspace lacks in the thread's PR panel", async () => {
250
+ setup();
251
+ state.routeParams = { environmentId: "local", threadId: "thread" };
252
+ state.projects = [project];
253
+ state.preview.mockResolvedValueOnce(AsyncResult.success({ sources: [] }));
254
+ appAtomRegistry.set(discoverySettled, true);
255
+ await using _coordinator = await mount(commitUrl);
256
+ await vi.waitFor(() =>
257
+ expect(
258
+ selectActiveRightPanelSurface(useRightPanelStore.getState().byThreadKey, threadRef),
259
+ ).toMatchObject({ kind: "pull-request", repository: "effect-ts/effect", number: 9339 }),
260
+ );
261
+ expect(useDiffPanelStore.getState().byThreadKey).toEqual({});
262
+ expect(state.openLink).not.toHaveBeenCalled();
263
+});
264
+
265
+it("opens a plain commit the workspace lacks like any other delivered link", async () => {
266
+ setup();
267
+ state.routeParams = { environmentId: "local", threadId: "thread" };
268
+ state.projects = [project];
269
+ state.preview.mockResolvedValueOnce(AsyncResult.success({ sources: [] }));
270
+ appAtomRegistry.set(discoverySettled, true);
271
+ const plainCommitUrl = `https://github.com/Effect-TS/effect/commit/${sha}`;
272
+ await using _coordinator = await mount(plainCommitUrl);
273
+ await vi.waitFor(() => expect(state.openScratchProject).toHaveBeenCalledOnce());
274
+ // Handing it to the OS browser would loop when T3 Code is the default browser.
275
+ expect(state.openLink).not.toHaveBeenCalled();
276
+ expect(useDiffPanelStore.getState().byThreadKey).toEqual({});
277
+ expect(useRightPanelStore.getState().byThreadKey).toEqual({});
278
+});
279
+
280
it("adds the backend from a pairing link after the user confirms its host", async () => {
281
setup();
282
await using _coordinator = await mount(pairLink);
apps/web/src/components/desktop/DesktopWebLinkCoordinator.tsx
+41
-17
@@ -27,6 +27,7 @@ import { selectActiveRightPanelSurface, useRightPanelStore } from "../../rightPa
27
import { appAtomRegistry } from "../../rpc/atomRegistry";
28
import { resolveThreadRouteTarget } from "../../threadRoutes";
29
import { assetEnvironment } from "../../state/assets";
30
+import { readProject, readThreadShell } from "../../state/entities";
31
import { useEnvironmentHttpBaseUrl, usePrimaryEnvironment } from "../../state/environments";
32
import { previewEnvironment } from "../../state/preview";
33
import { allReachableShellsLiveAtom } from "../../state/shell";
@@ -163,25 +164,14 @@ export function DesktopWebLinkCoordinator() {
164
return threadRef;
165
};
166
166
- const openLink = useEffectEvent(async (url: string) => {
167
- const pairingUrl = readPairingAppLink(url);
168
- if (pairingUrl !== null) {
169
- await pairFromLink(pairingUrl);
170
- return;
171
- }
172
- const appPath = promptLinkAppPath(url);
173
- if (appPath !== null) {
174
- await router.navigate({ href: appPath });
175
- return;
176
- }
177
- if (openChangeRequest(externalClick, url)) return;
167
+ const openInBrowser = useEffectEvent(async (url: string) => {
168
+ const routeParams = router.state.matches.at(-1)?.params ?? {};
169
const isFile = url.startsWith("file:");
170
// Only this machine's environment serves files, so fail before starting a thread.
171
if (isFile && httpBaseUrl === null) {
172
reportFailure(url);
173
return;
174
}
184
- const routeParams = router.state.matches.at(-1)?.params ?? {};
175
const threadRef =
176
threadShowingBrowser(
177
routeParams,
@@ -210,15 +200,49 @@ export function DesktopWebLinkCoordinator() {
200
}
201
});
202
203
+ const openLink = useEffectEvent(async (url: string) => {
204
+ const pairingUrl = readPairingAppLink(url);
205
+ if (pairingUrl !== null) {
206
+ await pairFromLink(pairingUrl);
207
+ return;
208
+ }
209
+ const appPath = promptLinkAppPath(url);
210
+ if (appPath !== null) {
211
+ await router.navigate({ href: appPath });
212
+ return;
213
+ }
214
+ const routeParams = router.state.matches.at(-1)?.params ?? {};
215
+ const routeTarget = resolveThreadRouteTarget(routeParams);
216
+ const activeThreadRef = routeTarget?.kind === "server" ? routeTarget.threadRef : undefined;
217
+ const activeThread = activeThreadRef ? readThreadShell(activeThreadRef) : null;
218
+ const activeProject =
219
+ activeThread && activeThreadRef
220
+ ? readProject(scopeProjectRef(activeThreadRef.environmentId, activeThread.projectId))
221
+ : null;
222
+ const commitThreadRef =
223
+ activeThread &&
224
+ sourceControlClients.parseCommitUrl(url, activeProject?.repositoryIdentity?.provider) !== null
225
+ ? activeThreadRef
226
+ : undefined;
227
+ // A commit the thread's workspace lacks continues here, after its lookup.
228
+ const openUnavailableCommit = () => {
229
+ queueRef.current = queueRef.current.then(() => openInBrowser(url)).catch(() => undefined);
230
+ };
231
+ if (openChangeRequest(externalClick, url, commitThreadRef, undefined, openUnavailableCommit))
232
+ return;
233
+ await openInBrowser(url);
234
+ });
235
+
236
const receiveLink = useEffectEvent((url: string) => {
214
- // A connected server publishes its config before its project snapshot, so a PR link
215
- // delivered at launch would miss its project and fall through to the browser. Hold PR
216
- // links, and only those, until discovery settles; an ordinary link never waits for it.
237
+ // A connected server publishes its config before its project snapshot, so a source control
238
+ // link delivered at launch would miss its project and fall through to the browser. Hold
239
+ // those links until discovery settles; an ordinary link never waits for it.
240
// Discovery never settles without the local environment, so those links do not wait.
241
const hold =
242
openPullRequestsInApp &&
243
!localEnvironmentDisabled &&
221
- sourceControlClients.parseChangeRequestUrl(url) !== null
244
+ (sourceControlClients.parseChangeRequestUrl(url) !== null ||
245
+ sourceControlClients.parseCommitUrl(url) !== null)
246
? projectsSettled()
247
: Promise.resolve();
248
void hold.then(() => {
apps/web/src/components/diffs/useReviewFilePatches.ts
+1
@@ -193,6 +193,7 @@ function reviewFileQueries({
193
request: {
194
cwd,
195
...(baseRef ? { baseRef } : {}),
196
+ ...(source.kind === "commit" ? { commitSha: source.id } : {}),
197
ignoreWhitespace,
198
file: {
199
path: file.path,
apps/web/src/components/settings/settingsSearch.ts
+1
-1
@@ -923,7 +923,7 @@ export const SETTINGS_SEARCH_ITEMS = [
923
title: "Open pull requests in T3 Code",
924
to: "/settings/diffs",
925
searchTerms: [
926
- `pr links ${SOURCE_CONTROL_HOST_LABELS} browser external click default pull request view panel`,
926
+ `pr commit links ${SOURCE_CONTROL_HOST_LABELS} browser external click default pull request view panel`,
927
],
928
},
929
{
apps/web/src/diffPanelStore.ts
+46
-6
@@ -17,6 +17,7 @@ export type DiffPanelSelection =
17
| ({ kind: "tool-call" } & ToolCallDiffTarget)
18
| { kind: "branch"; baseRef: string | null }
19
| { kind: "unstaged" }
20
+ | { kind: "commit"; sha: string; baseRef: string | null }
21
| { kind: "turn"; turnId: RunId; filePath: string | null; revealRequestId: number };
22
23
const DEFAULT_SELECTION: DiffPanelSelection = { kind: "branch", baseRef: null };
@@ -24,10 +25,14 @@ const DEFAULT_SELECTION: DiffPanelSelection = { kind: "branch", baseRef: null };
25
interface DiffPanelStoreState {
26
byThreadKey: Record<string, DiffPanelSelection>;
27
branchBaseRefByThreadKey: Record<string, string | null>;
28
+ /** A link that selected a commit before opening the closed pane; opening keeps that selection. */
29
+ keepSelectionOnOpenThreadKey: string | null;
30
selectGitScope: (ref: ScopedThreadRef, scope: "branch" | "unstaged") => void;
31
selectBranchBaseRef: (ref: ScopedThreadRef, baseRef: string | null) => void;
32
selectToolCall: (ref: ScopedThreadRef, target: ToolCallDiffTarget) => void;
33
selectTurn: (ref: ScopedThreadRef, turnId: RunId, filePath?: string) => void;
34
+ selectCommit: (ref: ScopedThreadRef, sha: string, keepOnOpen?: boolean) => void;
35
+ consumeKeepSelectionOnOpen: (ref: ScopedThreadRef) => boolean;
36
reconcileTurnSelection: (ref: ScopedThreadRef, availableTurnIds: ReadonlyArray<RunId>) => void;
37
removeThread: (ref: ScopedThreadRef) => void;
38
}
@@ -37,19 +42,27 @@ function normalizeBaseRef(baseRef: string | null): string | null {
42
return normalized ? normalized : null;
43
}
44
45
+function branchBaseRef(
46
+ state: Pick<DiffPanelStoreState, "byThreadKey" | "branchBaseRefByThreadKey">,
47
+ threadKey: string,
48
+): string | null {
49
+ const previous = state.byThreadKey[threadKey];
50
+ return previous?.kind === "branch" || previous?.kind === "commit"
51
+ ? previous.baseRef
52
+ : (state.branchBaseRefByThreadKey[threadKey] ?? null);
53
+}
54
+
55
export const useDiffPanelStore = create<DiffPanelStoreState>()(
56
persist(
42
- (set) => ({
57
+ (set, get) => ({
58
byThreadKey: {},
59
branchBaseRefByThreadKey: {},
60
+ keepSelectionOnOpenThreadKey: null,
61
selectGitScope: (ref, scope) =>
62
set((state) => {
63
const threadKey = scopedThreadKey(ref);
64
const previous = state.byThreadKey[threadKey];
49
- const previousBaseRef =
50
- previous?.kind === "branch"
51
- ? previous.baseRef
52
- : (state.branchBaseRefByThreadKey[threadKey] ?? null);
65
+ const previousBaseRef = branchBaseRef(state, threadKey);
66
return {
67
byThreadKey: {
68
...state.byThreadKey,
@@ -59,7 +72,7 @@ export const useDiffPanelStore = create<DiffPanelStoreState>()(
72
: { kind: "unstaged" },
73
},
74
branchBaseRefByThreadKey:
62
- previous?.kind === "branch"
75
+ previous?.kind === "branch" || previous?.kind === "commit"
76
? { ...state.branchBaseRefByThreadKey, [threadKey]: previous.baseRef }
77
: state.branchBaseRefByThreadKey,
78
};
@@ -102,6 +115,26 @@ export const useDiffPanelStore = create<DiffPanelStoreState>()(
115
},
116
};
117
}),
118
+ selectCommit: (ref, sha, keepOnOpen = false) =>
119
+ set((state) => {
120
+ const threadKey = scopedThreadKey(ref);
121
+ const baseRef = branchBaseRef(state, threadKey);
122
+ return {
123
+ byThreadKey: {
124
+ ...state.byThreadKey,
125
+ [threadKey]: { kind: "commit", sha, baseRef },
126
+ },
127
+ branchBaseRefByThreadKey: { ...state.branchBaseRefByThreadKey, [threadKey]: baseRef },
128
+ keepSelectionOnOpenThreadKey: keepOnOpen
129
+ ? threadKey
130
+ : state.keepSelectionOnOpenThreadKey,
131
+ };
132
+ }),
133
+ consumeKeepSelectionOnOpen: (ref) => {
134
+ if (get().keepSelectionOnOpenThreadKey !== scopedThreadKey(ref)) return false;
135
+ set({ keepSelectionOnOpenThreadKey: null });
136
+ return true;
137
+ },
138
reconcileTurnSelection: (ref, availableTurnIds) =>
139
set((state) => {
140
const threadKey = scopedThreadKey(ref);
@@ -178,6 +211,13 @@ export function selectThreadDiffPanelSelection(
211
return byThreadKey[scopedThreadKey(ref)] ?? DEFAULT_SELECTION;
212
}
213
214
+export function selectThreadBranchBaseRef(
215
+ state: Pick<DiffPanelStoreState, "byThreadKey" | "branchBaseRefByThreadKey">,
216
+ ref: ScopedThreadRef | null | undefined,
217
+): string | null {
218
+ return ref ? branchBaseRef(state, scopedThreadKey(ref)) : null;
219
+}
220
+
221
export function resolveToolCallDiffTarget(
222
target: ToolCallDiffTarget,
223
items: ReadonlyArray<ThreadStructureVisibleTurnItem>,
apps/web/src/lib/openPullRequestLink.browser.test.tsx
new
+160
@@ -0,0 +1,160 @@
1
+import { EnvironmentId, ThreadId } from "@t3tools/contracts";
2
+import { scopeThreadRef, scopedThreadKey } from "@t3tools/client-runtime/environment";
3
+import { AsyncResult } from "effect/reactivity";
4
+import { expect, it, vi } from "vite-plus/test";
5
+import { page } from "vite-plus/test/browser";
6
+
7
+import { act, render, stubGlobal } from "../../test/render";
8
+
9
+const state = vi.hoisted(() => ({ preview: vi.fn(), openLink: vi.fn() }));
10
+vi.mock("../state/use-atom-query-runner", () => ({ useAtomQueryRunner: () => state.preview }));
11
+vi.mock("../browser/useOpenLink", () => ({ useOpenLink: () => state.openLink }));
12
+vi.mock(import("../state/environments"), async (original) => ({
13
+ ...(await original()),
14
+ usePrimaryEnvironmentId: () => EnvironmentId.make("local"),
15
+}));
16
+vi.mock("../state/entities", async (original) => ({
17
+ ...(await original<typeof import("../state/entities")>()),
18
+ readProjects: () => [project],
19
+ useProjects: () => [project],
20
+ readProject: () => project,
21
+ readThreadShell: () => ({ projectId: "project", worktreePath: null }),
22
+}));
23
+vi.mock("../state/server", async (original) => {
24
+ const { Atom } = await import("effect/reactivity");
25
+ return {
26
+ ...(await original<typeof import("../state/server")>()),
27
+ environmentServerConfigsAtom: Atom.make(new Map([["local", {}]])),
28
+ };
29
+});
30
+
31
+import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts/settings";
32
+import { __setClientSettingsForTests } from "../hooks/useSettings";
33
+import { ToastProvider } from "../components/ui/toast";
34
+import { AppAtomRegistryProvider } from "../rpc/atomRegistry";
35
+import { useRightPanelStore } from "../rightPanelStore";
36
+import { useDiffPanelStore } from "../diffPanelStore";
37
+import { useOpenChangeRequestLink } from "./openPullRequestLink";
38
+
39
+const environmentId = EnvironmentId.make("local");
40
+const threadRef = scopeThreadRef(environmentId, ThreadId.make("thread"));
41
+const project = {
42
+ id: "project",
43
+ environmentId,
44
+ workspaceRoot: "/repo",
45
+ repositoryIdentity: {
46
+ provider: "github",
47
+ canonicalKey: "github.com/effect-ts/effect",
48
+ displayName: "Effect-TS/effect",
49
+ locator: {
50
+ source: "git-remote",
51
+ remoteName: "origin",
52
+ remoteUrl: "https://github.com/Effect-TS/effect.git",
53
+ },
54
+ },
55
+};
56
+const commitUrl = `https://github.com/Effect-TS/effect/commit/${"a".repeat(40)}?plain=1#diff-original`;
57
+const pullRequestCommitUrl = `https://github.com/Effect-TS/effect/pull/1/commits/${"a".repeat(40)}`;
58
+
59
+function CommitLink({ url = commitUrl }: { url?: string }) {
60
+ const open = useOpenChangeRequestLink(threadRef);
61
+ return (
62
+ <a href={url} onClick={(event) => open(event, url)}>
63
+ Commit
64
+ </a>
65
+ );
66
+}
67
+
68
+function setup() {
69
+ state.preview.mockReset().mockResolvedValue(AsyncResult.success({ sources: [] }));
70
+ state.openLink.mockReset().mockResolvedValue(undefined);
71
+ __setClientSettingsForTests({
72
+ ...DEFAULT_CLIENT_SETTINGS,
73
+ pullRequestLinksOpenInApp: true,
74
+ browserLinkTarget: "system",
75
+ });
76
+ useDiffPanelStore.setState({
77
+ byThreadKey: {},
78
+ branchBaseRefByThreadKey: {},
79
+ keepSelectionOnOpenThreadKey: null,
80
+ });
81
+ useRightPanelStore.setState({ byThreadKey: {}, userActionRevisionByThreadKey: {} });
82
+}
83
+
84
+it.each([
85
+ ["shiftKey", commitUrl],
86
+ ["altKey", commitUrl],
87
+ ["shiftKey", pullRequestCommitUrl],
88
+] as const)("keeps %s clicks on %s native", async (modifier, url) => {
89
+ setup();
90
+ await using screen = await render(
91
+ <AppAtomRegistryProvider>
92
+ <CommitLink url={url} />
93
+ </AppAtomRegistryProvider>,
94
+ );
95
+ const event = new MouseEvent("click", { bubbles: true, cancelable: true, [modifier]: true });
96
+ const defaults: boolean[] = [];
97
+ screen.container.addEventListener(
98
+ "click",
99
+ (nativeEvent) => {
100
+ defaults.push(nativeEvent.defaultPrevented);
101
+ nativeEvent.preventDefault();
102
+ },
103
+ { once: true },
104
+ );
105
+ await act(() => screen.getByRole("link", { name: "Commit" }).element().dispatchEvent(event));
106
+ expect(defaults).toEqual([false]);
107
+ expect(state.preview).not.toHaveBeenCalled();
108
+ expect(useRightPanelStore.getState().byThreadKey).toEqual({});
109
+});
110
+
111
+it.each(["system", "app"] as const)(
112
+ "offers the original unavailable commit URL when web popups are blocked (%s)",
113
+ async (browserLinkTarget) => {
114
+ setup();
115
+ // Without preview access, the "app" preference opens a popup too.
116
+ __setClientSettingsForTests({
117
+ ...DEFAULT_CLIENT_SETTINGS,
118
+ pullRequestLinksOpenInApp: true,
119
+ browserLinkTarget,
120
+ });
121
+ using _desktop = stubGlobal("desktopBridge", undefined);
122
+ await using screen = await render(
123
+ <AppAtomRegistryProvider>
124
+ <ToastProvider>
125
+ <CommitLink />
126
+ </ToastProvider>
127
+ </AppAtomRegistryProvider>,
128
+ );
129
+ using open = vi.spyOn(window, "open").mockReturnValue(null);
130
+ await screen.getByRole("link", { name: "Commit" }).click();
131
+ await expect
132
+ .element(page.getByRole("button", { name: "Open link", exact: true }))
133
+ .toBeVisible();
134
+ expect(open).not.toHaveBeenCalled();
135
+ await page.getByRole("button", { name: "Open link", exact: true }).click();
136
+ expect(open).toHaveBeenCalledExactlyOnceWith(commitUrl, "_blank", "noopener,noreferrer");
137
+ expect(state.openLink).not.toHaveBeenCalled();
138
+ },
139
+);
140
+
141
+it("opens an available commit in the closed Diff pane without the pane resetting it", async () => {
142
+ setup();
143
+ const sha = "a".repeat(40);
144
+ state.preview.mockResolvedValue(
145
+ AsyncResult.success({ sources: [{ kind: "commit", headRef: sha }] }),
146
+ );
147
+ await using screen = await render(
148
+ <AppAtomRegistryProvider>
149
+ <CommitLink />
150
+ </AppAtomRegistryProvider>,
151
+ );
152
+ await screen.getByRole("link", { name: "Commit" }).click();
153
+ await vi.waitFor(() =>
154
+ expect(useDiffPanelStore.getState().byThreadKey).toEqual({
155
+ [scopedThreadKey(threadRef)]: { kind: "commit", sha, baseRef: null },
156
+ }),
157
+ );
158
+ // ChatView resets a pane opened without an explicit request to Changes unless this is set.
159
+ expect(useDiffPanelStore.getState().consumeKeepSelectionOnOpen(threadRef)).toBe(true);
160
+});
apps/web/src/lib/openPullRequestLink.ts
+168
-51
@@ -8,15 +8,25 @@ import {
8
resolvePullRequestPreviewTarget,
9
} from "@t3tools/client-runtime/change-request-links";
10
11
+import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
12
+
13
+import { canOpenLinksInApp } from "../browser/browserLinkTarget";
14
import { useOpenLink } from "../browser/useOpenLink";
15
import { useClientSettings } from "../hooks/useSettings";
16
import { stackedThreadToast, toastManager } from "../components/ui/toast";
14
-import { useRightPanelStore } from "../rightPanelStore";
17
+import { selectActiveRightPanel, useRightPanelStore } from "../rightPanelStore";
18
+import {
19
+ selectThreadBranchBaseRef,
20
+ selectThreadDiffPanelSelection,
21
+ useDiffPanelStore,
22
+} from "../diffPanelStore";
23
24
import { appAtomRegistry } from "../rpc/atomRegistry";
17
-import { readProjects, useProjects } from "../state/entities";
25
+import { readProject, readProjects, readThreadShell, useProjects } from "../state/entities";
26
import { environmentServerConfigsAtom, serverEnvironment } from "../state/server";
27
import { usePrimaryEnvironmentId } from "../state/environments";
28
+import { reviewEnvironment } from "../state/review";
29
+import { useAtomQueryRunner } from "../state/use-atom-query-runner";
30
31
export function usePullRequestPreviewTarget(environmentId: EnvironmentId | null, url: string) {
32
const projects = useProjects();
@@ -43,71 +53,178 @@ export function useOpenChangeRequestLink(
53
event: Pick<
54
MouseEvent<HTMLElement>,
55
"preventDefault" | "stopPropagation" | "metaKey" | "ctrlKey"
46
- >,
56
+ > &
57
+ Partial<Pick<MouseEvent<HTMLElement>, "button" | "shiftKey" | "altKey">>,
58
targetUrl: string,
59
targetThreadRef?: ScopedThreadRef,
60
targetEnvironmentId?: EnvironmentId,
61
+ onCommitUnavailable?: () => void,
62
) => boolean {
63
const navigate = useNavigate();
64
const primaryEnvironmentId = usePrimaryEnvironmentId();
65
const openInApp = useClientSettings((settings) => settings.pullRequestLinksOpenInApp);
54
- return (event, targetUrl, targetThreadRef, targetEnvironmentId) => {
66
+ const ignoreWhitespace = useClientSettings((settings) => settings.diffIgnoreWhitespace);
67
+ const browserLinkTarget = useClientSettings((settings) => settings.browserLinkTarget);
68
+ const readDiffPreview = useAtomQueryRunner(reviewEnvironment.diffPreview, {
69
+ reportFailure: false,
70
+ refresh: true,
71
+ });
72
+ const openLink = useOpenLink(threadRef);
73
+ return (event, targetUrl, targetThreadRef, targetEnvironmentId, onCommitUnavailable) => {
74
if (!openInApp || shouldOpenPullRequestExternally(event)) return false;
56
- // Read at click time: every provider status push replaces the config map, and
57
- // subscribing would hand every rendered link a new handler. Projects likewise, so a
58
- // link can resolve against a snapshot that arrived after this handler was built.
59
- const serverConfigs = appAtomRegistry.get(environmentServerConfigsAtom);
75
const resolvedThreadRef = targetThreadRef ?? threadRef;
76
const resolvedPanelRef = panelRef ?? resolvedThreadRef;
62
- const target = resolveChangeRequestLinkTarget({
63
- url: targetUrl,
64
- projects: readProjects(),
65
- configLoaded: (environmentId) => serverConfigs.has(environmentId),
66
- environmentId: resolvedThreadRef?.environmentId ?? targetEnvironmentId,
67
- primaryEnvironmentId,
68
- lendHostProject: resolvedPanelRef !== undefined,
69
- });
70
- if (target === null) return false;
71
- const { project, repository, number, host } = target;
72
- event.preventDefault();
73
- event.stopPropagation();
74
- const pullRequestsSearch = {
75
- repository,
76
- number,
77
- ...(host === undefined ? {} : { selectedHost: host }),
78
- selectedProjectId: project.id,
79
- selectedEnvironmentId: project.environmentId,
80
- };
81
- if (resolvedPanelRef) {
82
- useRightPanelStore.getState().openPullRequest(resolvedPanelRef, {
83
- // The standalone PR panel has a synthetic ref; each tab keeps its real environment.
84
- ...(resolvedPanelRef.environmentId === project.environmentId
85
- ? {}
86
- : { environmentId: project.environmentId }),
87
- projectId: project.id,
88
- ...(host === undefined ? {} : { host }),
89
- repository,
77
+ const openPullRequest = () => {
78
+ // Read at click time: every provider status push replaces the config map, and
79
+ // subscribing would hand every rendered link a new handler. Projects likewise, so a
80
+ // link can resolve against a snapshot that arrived after this handler was built.
81
+ const serverConfigs = appAtomRegistry.get(environmentServerConfigsAtom);
82
+ const target = resolveChangeRequestLinkTarget({
83
url: targetUrl,
91
- number,
84
+ projects: readProjects(),
85
+ configLoaded: (environmentId) => serverConfigs.has(environmentId),
86
+ environmentId: resolvedThreadRef?.environmentId ?? targetEnvironmentId,
87
+ primaryEnvironmentId,
88
+ lendHostProject: resolvedPanelRef !== undefined,
89
});
93
- if (!resolvedThreadRef) {
94
- void navigate({
95
- to: "/pull-requests",
96
- search: (previous) => ({
97
- ...previous,
98
- involvement: previous.involvement ?? "all",
99
- state: previous.state ?? "all",
100
- ...pullRequestsSearch,
101
- }),
102
- replace: true,
90
+ if (target === null) return false;
91
+ const { project, repository, number, host } = target;
92
+ const pullRequestsSearch = {
93
+ repository,
94
+ number,
95
+ ...(host === undefined ? {} : { selectedHost: host }),
96
+ selectedProjectId: project.id,
97
+ selectedEnvironmentId: project.environmentId,
98
+ };
99
+ if (resolvedPanelRef) {
100
+ useRightPanelStore.getState().openPullRequest(resolvedPanelRef, {
101
+ // The standalone PR panel has a synthetic ref; each tab keeps its real environment.
102
+ ...(resolvedPanelRef.environmentId === project.environmentId
103
+ ? {}
104
+ : { environmentId: project.environmentId }),
105
+ projectId: project.id,
106
+ ...(host === undefined ? {} : { host }),
107
+ repository,
108
+ url: targetUrl,
109
+ number,
110
});
111
+ if (!resolvedThreadRef) {
112
+ void navigate({
113
+ to: "/pull-requests",
114
+ search: (previous) => ({
115
+ ...previous,
116
+ involvement: previous.involvement ?? "all",
117
+ state: previous.state ?? "all",
118
+ ...pullRequestsSearch,
119
+ }),
120
+ replace: true,
121
+ });
122
+ }
123
+ return true;
124
}
125
+ void navigate({
126
+ to: "/pull-requests",
127
+ search: { involvement: "all", state: "all", ...pullRequestsSearch },
128
+ });
129
+ return true;
130
+ };
131
+ const commitThread = resolvedThreadRef ? readThreadShell(resolvedThreadRef) : null;
132
+ const commitProject =
133
+ commitThread && resolvedThreadRef
134
+ ? readProject({
135
+ environmentId: resolvedThreadRef.environmentId,
136
+ projectId: commitThread.projectId,
137
+ })
138
+ : null;
139
+ const identity = commitProject?.repositoryIdentity;
140
+ const parsedCommit = sourceControlClients.parseCommitUrl(targetUrl, identity?.provider);
141
+ // Shift and Alt keep their browser meaning (new window, download) on commit links.
142
+ if (parsedCommit !== null && (event.shiftKey || event.altKey)) return false;
143
+ if (
144
+ parsedCommit !== null &&
145
+ commitThread &&
146
+ resolvedThreadRef &&
147
+ commitProject?.environmentId === resolvedThreadRef.environmentId &&
148
+ identity &&
149
+ identity.provider === parsedCommit.definition.kind &&
150
+ parsedCommit.definition.isChangeRequestInRepository(identity, parsedCommit.link)
151
+ ) {
152
+ const commit = parsedCommit.link;
153
+ event.preventDefault();
154
+ event.stopPropagation();
155
+ const userActionRevision = useRightPanelStore.getState().markUserAction(resolvedThreadRef);
156
+ const baseRef = selectThreadBranchBaseRef(useDiffPanelStore.getState(), resolvedThreadRef);
157
+ const selection = selectThreadDiffPanelSelection(
158
+ useDiffPanelStore.getState().byThreadKey,
159
+ resolvedThreadRef,
160
+ );
161
+ void readDiffPreview({
162
+ environmentId: resolvedThreadRef.environmentId,
163
+ input: {
164
+ cwd: commitThread.worktreePath ?? commitProject.workspaceRoot,
165
+ ...(baseRef ? { baseRef } : {}),
166
+ commitSha: commit.sha,
167
+ ignoreWhitespace,
168
+ },
169
+ })
170
+ .then((result) => {
171
+ if (
172
+ useRightPanelStore.getState().getUserActionRevision(resolvedThreadRef) !==
173
+ userActionRevision ||
174
+ selectThreadDiffPanelSelection(
175
+ useDiffPanelStore.getState().byThreadKey,
176
+ resolvedThreadRef,
177
+ ) !== selection
178
+ )
179
+ return;
180
+ if (
181
+ result._tag === "Success" &&
182
+ result.value.sources.some(
183
+ (source) => source.kind === "commit" && source.headRef === commit.sha,
184
+ )
185
+ ) {
186
+ const diffOpen =
187
+ selectActiveRightPanel(
188
+ useRightPanelStore.getState().byThreadKey,
189
+ resolvedThreadRef,
190
+ ) === "diff";
191
+ useDiffPanelStore.getState().selectCommit(resolvedThreadRef, commit.sha, !diffOpen);
192
+ useRightPanelStore.getState().open(resolvedThreadRef, "diff");
193
+ return;
194
+ }
195
+ if (openPullRequest()) return;
196
+ if (onCommitUnavailable) return onCommitUnavailable();
197
+ // A popup opened after the lookup has lost the click's activation, so browsers block it.
198
+ if (
199
+ window.desktopBridge === undefined &&
200
+ (browserLinkTarget !== "app" || !canOpenLinksInApp(resolvedThreadRef))
201
+ ) {
202
+ const toastId = toastManager.add(
203
+ stackedThreadToast({
204
+ type: "info",
205
+ title: "This commit is not in the thread's workspace",
206
+ actionProps: {
207
+ children: "Open link",
208
+ onClick: () => {
209
+ toastManager.close(toastId);
210
+ window.open(targetUrl, "_blank", "noopener,noreferrer");
211
+ },
212
+ },
213
+ }),
214
+ );
215
+ return;
216
+ }
217
+ return openLink(targetUrl, {
218
+ event: { metaKey: event.metaKey, ctrlKey: event.ctrlKey, button: event.button },
219
+ threadRef: resolvedThreadRef,
220
+ });
221
+ })
222
+ .catch((error: unknown) => console.error(error));
223
return true;
224
}
107
- void navigate({
108
- to: "/pull-requests",
109
- search: { involvement: "all", state: "all", ...pullRequestsSearch },
110
- });
225
+ if (!openPullRequest()) return false;
226
+ event.preventDefault();
227
+ event.stopPropagation();
228
return true;
229
};
230
}
apps/web/src/rightPanelStore.ts
+11
@@ -109,6 +109,7 @@ interface RightPanelStoreState {
109
userActionRevisionByThreadKey: Record<string, number>;
110
closeRevisionByThreadKey: Record<string, number>;
111
getUserActionRevision: (ref: ScopedThreadRef) => number;
112
+ markUserAction: (ref: ScopedThreadRef) => number;
113
/** Refused if the user chose a panel after expectedUserActionRevision was read. */
114
openProactive: (
115
ref: ScopedThreadRef,
@@ -598,6 +599,16 @@ export const useRightPanelStore = create<RightPanelStoreState>()(
599
closeRevisionByThreadKey: {},
600
getUserActionRevision: (ref) =>
601
get().userActionRevisionByThreadKey[scopedThreadKey(ref)] ?? 0,
602
+ markUserAction: (ref) => {
603
+ const revision = get().getUserActionRevision(ref) + 1;
604
+ set((state) => ({
605
+ userActionRevisionByThreadKey: {
606
+ ...state.userActionRevisionByThreadKey,
607
+ [scopedThreadKey(ref)]: revision,
608
+ },
609
+ }));
610
+ return revision;
611
+ },
612
openProactive: (ref, request, expectedUserActionRevision, activateExisting = false) => {
613
let opened = false;
614
set((state) => {
docs/user/source-control.md
+10
@@ -10,6 +10,16 @@ rebases, the files Git brought in are left out. A file stays in the list when th
10
committed it, or fixed a conflict in it. Use the branch comparison to review everything that changed
11
against your base branch. Restore still returns the complete saved workspace.
12
13
+On web and desktop, open the Diff pane source picker and choose **Commits** to review one local
14
+commit at a time. The list shows the newest 100 commits in the branch comparison. A merge commit
15
+shows its changes against its first parent.
16
+
17
+A commit link from a supported code host opens in the Diff pane when the thread's repository has
18
+that commit locally, on any branch. Otherwise a pull request commit link opens the pull request. Other
19
+commit links follow your **Open links in** setting; on web, when that opens a new tab, T3 Code first
20
+shows an **Open link** button. Command/Ctrl+Click always opens the link in your browser. Commit links follow the **Open pull requests in T3 Code**
21
+setting in **Settings → Diffs**.
22
+
23
## Connect an account
24
25
Install Git and configure authentication on the machine running your T3 Code server. For a remote
packages/client-runtime/src/changeRequestLinks.ts
+18
@@ -150,3 +150,21 @@ export function projectChangeRequestUrl(
150
...(ownRepository && identity.webUrl !== undefined ? { webUrl: identity.webUrl } : {}),
151
});
152
}
153
+
154
+export function projectCommitUrl(
155
+ identity: RepositoryIdentity | null | undefined,
156
+ sha: string,
157
+): string | null {
158
+ if (identity?.provider === undefined) return null;
159
+ const [host, ...path] = identity.canonicalKey.split("/");
160
+ if (!host) return null;
161
+ return (
162
+ sourceControlClients.get(identity.provider).commitUrl?.({
163
+ host,
164
+ repository: path.join("/"),
165
+ sha,
166
+ remoteUrl: identity.locator.remoteUrl.trim(),
167
+ ...(identity.webUrl !== undefined ? { webUrl: identity.webUrl } : {}),
168
+ }) ?? null
169
+ );
170
+}
packages/client-runtime/src/state/review.ts
+5
@@ -51,6 +51,11 @@ export function createReviewEnvironmentAtoms<R, E>(
51
});
52
});
53
return {
54
+ branchCommits: createEnvironmentRpcQueryAtomFamily(runtime, {
55
+ label: "environment-data:review:branch-commits",
56
+ tag: WS_METHODS.reviewGetBranchCommits,
57
+ staleTimeMs: 5_000,
58
+ }),
59
diffPreview,
60
diffFilePatch: createEnvironmentQueryAtomFamily(runtime, {
61
label: "environment-data:review:diff-file-patch",
packages/contracts/src/review.ts
+26
-2
@@ -6,18 +6,41 @@ import { VcsError } from "./vcs.ts";
6
export const ReviewDiffPreviewInput = Schema.Struct({
7
cwd: TrimmedNonEmptyString,
8
baseRef: Schema.optional(TrimmedNonEmptyString),
9
+ commitSha: Schema.optional(TrimmedNonEmptyString),
10
ignoreWhitespace: Schema.optionalKey(Schema.Boolean),
11
file: Schema.optionalKey(
12
Schema.Struct({
13
path: Schema.NonEmptyString,
14
previousPath: Schema.NullOr(Schema.NonEmptyString),
14
- sourceKind: Schema.Literals(["working-tree", "branch-range"]),
15
+ sourceKind: Schema.Literals(["working-tree", "branch-range", "commit"]),
16
}),
17
),
18
});
19
export type ReviewDiffPreviewInput = typeof ReviewDiffPreviewInput.Type;
20
20
-export const ReviewDiffPreviewSourceKind = Schema.Literals(["working-tree", "branch-range"]);
21
+export const ReviewBranchCommitsInput = Schema.Struct({
22
+ cwd: TrimmedNonEmptyString,
23
+ baseRef: Schema.optional(TrimmedNonEmptyString),
24
+});
25
+export type ReviewBranchCommitsInput = typeof ReviewBranchCommitsInput.Type;
26
+
27
+export const ReviewBranchCommitsResult = Schema.Struct({
28
+ commits: Schema.Array(
29
+ Schema.Struct({
30
+ sha: Schema.String,
31
+ subject: Schema.String,
32
+ committedAt: Schema.String,
33
+ }),
34
+ ),
35
+ truncated: Schema.Boolean,
36
+});
37
+export type ReviewBranchCommitsResult = typeof ReviewBranchCommitsResult.Type;
38
+
39
+export const ReviewDiffPreviewSourceKind = Schema.Literals([
40
+ "working-tree",
41
+ "branch-range",
42
+ "commit",
43
+]);
44
export type ReviewDiffPreviewSourceKind = typeof ReviewDiffPreviewSourceKind.Type;
45
46
export const ReviewDiffFileStat = Schema.Struct({
@@ -32,6 +55,7 @@ export const ReviewDiffPreviewSource = Schema.Struct({
55
id: TrimmedNonEmptyString,
56
kind: ReviewDiffPreviewSourceKind,
57
title: TrimmedNonEmptyString,
58
+ commitSubject: Schema.optionalKey(TrimmedNonEmptyString),
59
baseRef: Schema.NullOr(TrimmedNonEmptyString),
60
headRef: Schema.NullOr(TrimmedNonEmptyString),
61
diff: Schema.String,
packages/contracts/src/rpc.ts
+10
@@ -149,6 +149,8 @@ import {
149
VcsStatusStreamEvent,
150
} from "./git.ts";
151
import {
152
+ ReviewBranchCommitsInput,
153
+ ReviewBranchCommitsResult,
154
ReviewDiffFileContentsInput,
155
ReviewDiffFileContentsResult,
156
ReviewDiffPreviewError,
@@ -455,6 +457,7 @@ export const WS_METHODS = {
457
gitResolvePullRequest: "git.resolvePullRequest",
458
gitPreparePullRequestThread: "git.preparePullRequestThread",
459
460
+ reviewGetBranchCommits: "review.getBranchCommits",
461
reviewGetDiffPreview: "review.getDiffPreview",
462
reviewGetDiffFileContents: "review.getDiffFileContents",
463
@@ -1500,6 +1503,12 @@ const WsVcsInitRpc = Rpc.make(WS_METHODS.vcsInit, {
1503
error: Schema.Union([VcsError, EnvironmentAuthorizationError]),
1504
});
1505
1506
+const WsReviewGetBranchCommitsRpc = Rpc.make(WS_METHODS.reviewGetBranchCommits, {
1507
+ payload: ReviewBranchCommitsInput,
1508
+ success: ReviewBranchCommitsResult,
1509
+ error: Schema.Union([ReviewDiffPreviewError, EnvironmentAuthorizationError]),
1510
+});
1511
+
1512
const WsReviewGetDiffPreviewRpc = Rpc.make(WS_METHODS.reviewGetDiffPreview, {
1513
payload: ReviewDiffPreviewInput,
1514
success: ReviewDiffPreviewResult,
@@ -2092,6 +2101,7 @@ export const WsRpcGroup = RpcGroup.make(
2101
WsVcsCreateRefRpc,
2102
WsVcsSwitchRefRpc,
2103
WsVcsInitRpc,
2104
+ WsReviewGetBranchCommitsRpc,
2105
WsReviewGetDiffPreviewRpc,
2106
WsReviewGetDiffFileContentsRpc,
2107
WsTerminalOpenRpc,
packages/source-control-azure-devops/src/shared/definition.ts
+9
@@ -1,15 +1,18 @@
1
import { SourceControlProviderKind } from "@t3tools/contracts";
2
import {
3
+ buildCommitUrl,
4
changeRequestUrlBelow,
5
defineSourceControl,
6
isChangeRequestAuthorityOfProject,
7
parseChangeRequestPath,
8
+ parseCommitPath,
9
remoteWebOrigin,
10
} from "@t3tools/source-control-core/shared/definition";
11
import { icon } from "./icon.ts";
12
13
// Azure DevOps Server runs on any hostname; its `_git` route identifies it.
14
const CHANGE_REQUEST_PATH = /^\/((?:[^/]+\/)*_git\/[^/]+)\/pullrequest\/(\d+)(?:\/|$)/u;
15
+const COMMIT_PATH = /^\/((?:[^/]+\/)*_git\/[^/]+)\/commit\/([0-9a-f]+)\/?$/iu;
16
const CHECKOUT_COMMAND = /^az\s+repos\s+pr\s+checkout\s+(.+)$/i;
17
const CHANGE_REQUEST_REFERENCE =
18
/^https:\/\/(?:dev\.azure\.com\/[^/\s]+\/[^/\s]+|[^/\s]+\.visualstudio\.com\/[^/\s]+)\/_git\/[^/\s]+\/pullrequest\/(\d+)(?:[/?#].*)?$/i;
@@ -88,6 +91,12 @@ export const definition = defineSourceControl({
91
const [canonicalHost = host, ...path] = (canonicalRepositoryKey(key) ?? key).split("/");
92
return `${remoteWebOrigin(canonicalHost, remoteUrl)}/${path.join("/")}/pullrequest/${number}`;
93
},
94
+ commitUrl: (input) => {
95
+ const key = `${input.host}/${input.repository}`.toLowerCase();
96
+ const [host = input.host, ...path] = (canonicalRepositoryKey(key) ?? key).split("/");
97
+ return buildCommitUrl({ ...input, host, repository: path.join("/") }, "commit");
98
+ },
99
+ parseCommitUrl: (url) => parseCommitPath(url, COMMIT_PATH),
100
// Servers on different ports are different servers, so a port stays in the link.
101
parseChangeRequestUrl: (url) => {
102
const link = parseChangeRequestPath(url, CHANGE_REQUEST_PATH);
packages/source-control-bitbucket/src/shared/definition.ts
+6
@@ -6,11 +6,13 @@ import {
6
import * as Effect from "effect/Effect";
7
import * as Schema from "effect/Schema";
8
import {
9
+ buildCommitUrl,
10
changeRequestUrlBelow,
11
defineSourceControl,
12
isChangeRequestInProjectRepository,
13
isChangeRequestOnProjectHost,
14
parseChangeRequestPath,
15
+ parseCommitPath,
16
projectChangeRequestHost,
17
} from "@t3tools/source-control-core/shared/definition";
18
import { icon } from "./icon.ts";
@@ -19,6 +21,7 @@ const safeShellArgument = /^[A-Za-z0-9._/@+=,-]+$/;
21
const repositoryName = /^[A-Za-z0-9._-]+\/[A-Za-z0-9._-]+$/;
22
23
const CHANGE_REQUEST_PATH = /^\/([^/]+\/[^/]+)\/pull-requests\/(\d+)(?:\/|$)/u;
24
+const COMMIT_PATH = /^\/([^/]+\/[^/]+)\/commits\/([0-9a-f]+)\/?$/iu;
25
26
const KIND = SourceControlProviderKind.make("bitbucket");
27
@@ -87,6 +90,9 @@ export const definition = defineSourceControl({
90
: `https://${host}/${repository}/pull-requests/${number}`,
91
parseChangeRequestUrl: (url) =>
92
isBitbucketHost(url.hostname) ? parseChangeRequestPath(url, CHANGE_REQUEST_PATH) : null,
93
+ commitUrl: (input) => buildCommitUrl(input, "commits"),
94
+ parseCommitUrl: (url) =>
95
+ isBitbucketHost(url.hostname) ? parseCommitPath(url, COMMIT_PATH) : null,
96
changeRequestUrlFromReferenceAutolink: () => null,
97
// No endpoint reopens a declined pull request, and nothing documented moves one in or out of
98
// draft, so neither is offered rather than failing when pressed.
packages/source-control-core/src/shared/definition.ts
+70
-4
@@ -30,6 +30,17 @@ export interface ParsedChangeRequestUrl extends ChangeRequestLink {
30
readonly repositoryUrl: string;
31
}
32
33
+export interface CommitLink {
34
+ readonly host: string;
35
+ readonly repository: string;
36
+ readonly sha: string;
37
+ readonly authority?: string;
38
+}
39
+
40
+export interface CommitUrlInput extends Omit<ChangeRequestUrlInput, "number"> {
41
+ readonly sha: string;
42
+}
43
+
44
export interface ChangeRequestTerminology {
45
readonly shortLabel: string;
46
/** Spelled out because the article follows how the label is said: "an MR". */
@@ -238,6 +249,9 @@ export interface SourceControlDefinition {
249
readonly newRepositoryOwner: (account: string | null) => { readonly owner: string | null } | null;
250
readonly defaultCloneTransport: "https" | "ssh";
251
readonly changeRequestUrl: (input: ChangeRequestUrlInput) => string | null;
252
+ readonly commitUrl?: (input: CommitUrlInput) => string | null;
253
+ /** `known` is set when the caller already knows this host serves the URL's repository. */
254
+ readonly parseCommitUrl?: (url: URL, known: boolean) => CommitLink | null;
255
/** Null when the URL is not one of this host's change requests. */
256
readonly parseChangeRequestUrl: (url: URL) => ParsedChangeRequestUrl | null;
257
/**
@@ -290,7 +304,7 @@ export interface SourceControlDefinition {
304
readonly isChangeRequestReference: (url: string) => boolean;
305
readonly isChangeRequestInRepository: (
306
identity: ChangeRequestProjectIdentity,
293
- link: ChangeRequestLink,
307
+ link: ChangeRequestLink | CommitLink,
308
) => boolean;
309
readonly canReadChangeRequestOnHost: (
310
identity: ChangeRequestProjectIdentity,
@@ -335,6 +349,42 @@ export type SourceControlHostSettingsSchema = {
349
readonly fields: Readonly<Record<string, Schema.Top>>;
350
} & Schema.Decoder<object>;
351
352
+const FULL_COMMIT_SHA = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/iu;
353
+
354
+export function parseCommitPath(url: URL, route: RegExp): CommitLink | null {
355
+ if (url.protocol !== "https:" && url.protocol !== "http:") return null;
356
+ const match = route.exec(url.pathname);
357
+ const repository = match?.[1];
358
+ const sha = match?.[2];
359
+ return repository && sha && FULL_COMMIT_SHA.test(sha)
360
+ ? {
361
+ host: url.hostname.toLowerCase(),
362
+ repository: repository.toLowerCase(),
363
+ sha: sha.toLowerCase(),
364
+ ...(url.port ? { authority: url.host.toLowerCase() } : {}),
365
+ }
366
+ : null;
367
+}
368
+
369
+export function buildCommitUrl(
370
+ { host, repository, sha, remoteUrl, webUrl }: CommitUrlInput,
371
+ route: string,
372
+): string | null {
373
+ if (!repository || !FULL_COMMIT_SHA.test(sha)) return null;
374
+ try {
375
+ const url = new URL(webUrl || `${remoteWebOrigin(host, remoteUrl)}/${repository}`);
376
+ if (url.protocol !== "http:" && url.protocol !== "https:") return null;
377
+ url.pathname = changeRequestUrlBelow(url.pathname, `${route}/${sha.toLowerCase()}`);
378
+ url.username = "";
379
+ url.password = "";
380
+ url.search = "";
381
+ url.hash = "";
382
+ return url.toString();
383
+ } catch {
384
+ return null;
385
+ }
386
+}
387
+
388
/**
389
* Reads a change request from `url` with `route`, whose first group is the repository path and
390
* second the number.
@@ -383,7 +433,7 @@ export function defineSourceControl<const Definition extends SourceControlDefini
433
434
export function isChangeRequestAuthorityOfProject(
435
identity: ChangeRequestProjectIdentity,
386
- link: ChangeRequestLink,
436
+ link: ChangeRequestLink | CommitLink,
437
): boolean {
438
if (link.authority === undefined) return true;
439
try {
@@ -410,7 +460,7 @@ export function projectChangeRequestHost<const Kind extends string | undefined>(
460
export function isChangeRequestOnProjectHost(
461
projectHost: string,
462
identity: ChangeRequestProjectIdentity,
413
- link: ChangeRequestLink,
463
+ link: ChangeRequestLink | CommitLink,
464
): boolean {
465
if (!isChangeRequestAuthorityOfProject(identity, link)) return false;
466
return projectHost === link.host.toLowerCase() || projectHost === link.authority;
@@ -426,7 +476,7 @@ function projectRepositoryPath(identity: ChangeRequestProjectIdentity): string |
476
export function isChangeRequestInProjectRepository(
477
projectHost: string,
478
identity: ChangeRequestProjectIdentity,
429
- link: ChangeRequestLink,
479
+ link: ChangeRequestLink | CommitLink,
480
): boolean {
481
const repository = projectRepositoryPath(identity);
482
return (
@@ -533,6 +583,11 @@ export interface ParsedChangeRequest {
583
readonly link: ParsedChangeRequestUrl;
584
}
585
586
+export interface ParsedCommit {
587
+ readonly definition: SourceControlDefinition;
588
+ readonly link: CommitLink;
589
+}
590
+
591
export interface SourceControlMedia extends SourceControlMediaUrl {
592
readonly definition: SourceControlDefinition;
593
}
@@ -549,6 +604,7 @@ export interface SourceControlDefinitionRegistry {
604
readonly findByPublicDomain: (hostname: string) => SourceControlDefinition | undefined;
605
/** The first host, in registry order, that reads `url` as one of its change requests. */
606
readonly parseChangeRequestUrl: (url: string) => ParsedChangeRequest | null;
607
+ readonly parseCommitUrl: (url: string, kind?: SourceControlProviderKind) => ParsedCommit | null;
608
readonly findByChangeRequestUrl: (url: string) => SourceControlDefinition | undefined;
609
readonly hostLabelForChangeRequestUrl: (url: string) => string;
610
readonly isSameChangeRequest: (left: string, right: string) => boolean;
@@ -648,6 +704,16 @@ export function makeSourceControlDefinitionRegistry(
704
);
705
},
706
parseChangeRequestUrl,
707
+ parseCommitUrl: (value, kind) => {
708
+ const url = httpUrl(value);
709
+ if (url === null) return null;
710
+ const preferred = kind === undefined ? undefined : byKind.get(kind);
711
+ for (const definition of kind === undefined ? claimOrder : preferred ? [preferred] : []) {
712
+ const link = definition.parseCommitUrl?.(url, preferred !== undefined);
713
+ if (link != null) return { definition, link };
714
+ }
715
+ return null;
716
+ },
717
findByChangeRequestUrl: (url) => parseChangeRequestUrl(url)?.definition,
718
hostLabelForChangeRequestUrl: (url) =>
719
parseChangeRequestUrl(url)?.definition.label ?? "the host",
packages/source-control-definitions/src/registry.ts
+1
-1
@@ -23,7 +23,7 @@ export const builtInSourceControlDefinitions = makeSourceControlDefinitionRegist
23
AzureDevOps.definition,
24
],
25
{
26
- claimChangeRequestUrlsFirst: [GitCafe.definition.kind],
26
+ claimChangeRequestUrlsFirst: [GitCafe.definition.kind, AzureDevOps.definition.kind],
27
recognizeRemotesIn: [
28
GitCafe.definition.kind,
29
Forgejo.definition.kind,
packages/source-control-forgejo/src/shared/definition.ts
+5
@@ -1,5 +1,6 @@
1
import { SourceControlProviderKind } from "@t3tools/contracts";
2
import {
3
+ buildCommitUrl,
4
changeRequestUrlBelow,
5
type ChangeRequestHostIdentity,
6
type ChangeRequestProjectIdentity,
@@ -8,6 +9,7 @@ import {
9
isChangeRequestInProjectRepository,
10
isChangeRequestOnProjectHost,
11
parseChangeRequestPath,
12
+ parseCommitPath,
13
projectChangeRequestHost,
14
remoteWebOrigin,
15
} from "@t3tools/source-control-core/shared/definition";
@@ -19,6 +21,7 @@ const CHANGE_REQUEST_REFERENCE =
21
22
// Forgejo and Gitea run on any hostname, possibly mounted below a path.
23
const CHANGE_REQUEST_PATH = /^\/([^/]+(?:\/[^/]+)+)\/pulls\/(\d+)(?:\/|$)/u;
24
+const COMMIT_PATH = /^\/([^/]+(?:\/[^/]+)+)\/commit\/([0-9a-f]+)\/?$/iu;
25
26
const KIND = SourceControlProviderKind.make("forgejo");
27
@@ -82,6 +85,8 @@ export const definition = defineSourceControl({
85
return link === null ? null : { ...link, authority: url.host.toLowerCase() };
86
},
87
changeRequestUrlFromReferenceAutolink: () => null,
88
+ commitUrl: (input) => buildCommitUrl(input, "commit"),
89
+ parseCommitUrl: (url) => parseCommitPath(url, COMMIT_PATH),
90
changeRequestActions: new Set(["merge", "close", "reopen", "update-branch"] as const),
91
// Neither `fj` nor `tea` checks out by number.
92
checkoutCommand: ({ number, repositoryUrl }) =>
packages/source-control-gitcafe/src/shared/definition.ts
+6
@@ -7,11 +7,13 @@ import {
7
import * as Effect from "effect/Effect";
8
import * as Schema from "effect/Schema";
9
import {
10
+ buildCommitUrl,
11
changeRequestUrlBelow,
12
defineSourceControl,
13
isChangeRequestInProjectRepository,
14
isChangeRequestOnProjectHost,
15
parseChangeRequestPath,
16
+ parseCommitPath,
17
projectChangeRequestHost,
18
} from "@t3tools/source-control-core/shared/definition";
19
import { icon } from "./icon.ts";
@@ -21,6 +23,7 @@ const GITCAFE_HOSTS = new Set(["git.cafe", "staging.git.cafe"]);
23
24
/** GitCafe serves pull requests at `/pull/<n>` and redirects the older `/pulls/<n>` there. */
25
const CHANGE_REQUEST_PATH = /^\/([^/]+\/[^/]+)\/pulls?\/(\d+)(?:\/|$)/u;
26
+const COMMIT_PATH = /^\/([^/]+\/[^/]+)\/commit\/([0-9a-f]+)\/?$/iu;
27
28
function parseChangeRequestUrl(url: URL) {
29
return GITCAFE_HOSTS.has(url.hostname.toLowerCase())
@@ -68,6 +71,9 @@ export const definition = defineSourceControl({
71
// `/pull/` and `/pulls/` are GitHub's and Forgejo's shapes too, so only GitCafe's own hosts
72
// claim them.
73
parseChangeRequestUrl,
74
+ commitUrl: (input) => buildCommitUrl(input, "commit"),
75
+ parseCommitUrl: (url) =>
76
+ GITCAFE_HOSTS.has(url.hostname.toLowerCase()) ? parseCommitPath(url, COMMIT_PATH) : null,
77
changeRequestUrlFromReferenceAutolink: () => null,
78
changeRequestActions: new Set([
79
"ready",
packages/source-control-github/src/shared/definition.ts
+10
-6
@@ -1,11 +1,13 @@
1
import { makeProviderSettingsSchema, SourceControlProviderKind } from "@t3tools/contracts";
2
import {
3
+ buildCommitUrl,
4
changeRequestUrlBelow,
5
defineSourceControl,
6
hostCredentialSettingsFields,
7
isChangeRequestInProjectRepository,
8
isChangeRequestOnProjectHost,
9
parseChangeRequestPath,
10
+ parseCommitPath,
11
projectChangeRequestHost,
12
remoteWebOrigin,
13
type SourceControlAppSignIn,
@@ -22,15 +24,14 @@ const CHANGE_REQUEST_REFERENCE =
24
// GitHub Enterprise Server runs on any hostname, so the `<owner>/<repo>/pull/<n>` route alone
25
// identifies a GitHub pull request.
26
const CHANGE_REQUEST_PATH = /^\/([^/]+\/[^/]+)\/pull\/(\d+)(?:\/|$)/u;
27
+const COMMIT_PATH = /^\/([^/]+\/[^/]+)\/(?:commit|pull\/\d+\/commits)\/([0-9a-f]+)\/?$/iu;
28
const ISSUE_PATH = /^\/([^/]+\/[^/]+)\/issues\/(\d+)(?:\/|$)/u;
29
30
const KIND = SourceControlProviderKind.make("github");
31
32
function isGitHubHost(hostname: string): boolean {
33
const host = hostname.toLowerCase();
31
- return (
32
- host === "github.com" || host.endsWith(".github.com") || host.split(".").includes("github")
33
- );
34
+ return host === "github.com" || host.endsWith(".ghe.com") || host.split(".").includes("github");
35
}
36
37
function isRepositoryPath(repository: string): boolean {
@@ -91,6 +92,11 @@ export const definition = defineSourceControl({
92
return null;
93
}
94
},
95
+ commitUrl: (input) =>
96
+ isRepositoryPath(input.repository) ? buildCommitUrl(input, "commit") : null,
97
+ // A known project's host can be any GitHub Enterprise Server name.
98
+ parseCommitUrl: (url, known) =>
99
+ known || isGitHubHost(url.hostname) ? parseCommitPath(url, COMMIT_PATH) : null,
100
parseChangeRequestUrl: (url) => parseChangeRequestPath(url, CHANGE_REQUEST_PATH),
101
// GitHub writes every bare reference through `/issues/`, including pull requests.
102
changeRequestUrlFromReferenceAutolink: (url) => {
@@ -133,9 +139,7 @@ export const definition = defineSourceControl({
139
changeRequestHeadRef: (number) => `refs/pull/${number}/head`,
140
// `*.ghe.com` is GitHub Enterprise Cloud with data residency, one subdomain per enterprise.
141
recognizeRemote: ({ host, hostname }) =>
136
- hostname === "github.com" ||
137
- hostname.endsWith(".ghe.com") ||
138
- hostname.split(".").includes("github")
142
+ isGitHubHost(hostname)
143
? {
144
kind: KIND,
145
name: hostname === "github.com" ? "GitHub" : "GitHub Self-Hosted",
packages/source-control-gitlab/src/shared/definition.ts
+5
@@ -1,10 +1,12 @@
1
import { SourceControlProviderKind } from "@t3tools/contracts";
2
import {
3
+ buildCommitUrl,
4
changeRequestUrlBelow,
5
defineSourceControl,
6
isChangeRequestInProjectRepository,
7
isChangeRequestOnProjectHost,
8
parseChangeRequestPath,
9
+ parseCommitPath,
10
projectChangeRequestHost,
11
} from "@t3tools/source-control-core/shared/definition";
12
import { icon } from "./icon.ts";
@@ -15,6 +17,7 @@ const CHANGE_REQUEST_REFERENCE =
17
18
// Self-managed GitLab runs on any hostname and nests projects in groups.
19
const CHANGE_REQUEST_PATH = /^\/([^/]+(?:\/[^/]+)+)\/-\/merge_requests\/(\d+)(?:\/|$)/u;
20
+const COMMIT_PATH = /^\/([^/]+(?:\/[^/]+)+)\/-\/commit\/([0-9a-f]+)\/?$/iu;
21
22
const KIND = SourceControlProviderKind.make("gitlab");
23
@@ -40,6 +43,8 @@ export const definition = defineSourceControl({
43
? changeRequestUrlBelow(webUrl, `-/merge_requests/${number}`)
44
: `https://${host}/${repository}/-/merge_requests/${number}`,
45
parseChangeRequestUrl: (url) => parseChangeRequestPath(url, CHANGE_REQUEST_PATH),
46
+ commitUrl: (input) => buildCommitUrl(input, "-/commit"),
47
+ parseCommitUrl: (url) => parseCommitPath(url, COMMIT_PATH),
48
changeRequestUrlFromReferenceAutolink: () => null,
49
changeRequestActions: new Set([
50
"merge",