Skip to content

Commit 00955e3

Browse files
committed
feat(web,server): add VS Code-style Git Graph panel with per-thread repo browser and commit diff viewer
1 parent 8213d1d commit 00955e3

11 files changed

Lines changed: 2247 additions & 8 deletions

File tree

‎apps/server/src/auth/RpcAuthorization.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ import {
2323
AuthPreviewOperateScope,
2424
AuthRelayReadScope,
2525
AuthRelayWriteScope,
26+
AuthSourceControlWriteScope,
2627
AuthTerminalOperateScope,
2728
ORCHESTRATION_V2_WS_METHODS,
2829
type OrchestrationV2Command,
@@ -215,6 +216,10 @@ export const RPC_REQUIRED_SCOPES = {
215216
[WS_METHODS.vcsRefreshStatus]: AuthOrchestrationReadScope,
216217
[WS_METHODS.gitResolvePullRequest]: AuthOrchestrationReadScope,
217218
[WS_METHODS.vcsListRefs]: AuthOrchestrationReadScope,
219+
[WS_METHODS.vcsListHistory]: AuthOrchestrationReadScope,
220+
[WS_METHODS.vcsCommitFileDiff]: AuthOrchestrationReadScope,
221+
[WS_METHODS.vcsCommitFiles]: AuthOrchestrationReadScope,
222+
[WS_METHODS.vcsHistoryAction]: AuthSourceControlWriteScope,
218223
[WS_METHODS.reviewGetBranchCommits]: AuthFilesystemReadScope,
219224
[WS_METHODS.reviewGetDiffPreview]: AuthFilesystemReadScope,
220225
[WS_METHODS.reviewGetDiffFileContents]: AuthFilesystemReadScope,

‎apps/server/src/git/gitHistory.ts‎

Lines changed: 326 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,326 @@
1+
import { execFile } from "node:child_process";
2+
import * as Effect from "effect/Effect";
3+
import {
4+
GitCommandError,
5+
type VcsCommitFileDiffInput,
6+
type VcsCommitFileDiffResult,
7+
type VcsCommitFilesInput,
8+
type VcsCommitFilesResult,
9+
type VcsHistoryActionInput,
10+
type VcsHistoryActionResult,
11+
type VcsHistoryCommit,
12+
type VcsHistoryCommitRef,
13+
type VcsListHistoryInput,
14+
type VcsListHistoryResult,
15+
} from "@t3tools/contracts";
16+
17+
function runGit(cwd: string, args: ReadonlyArray<string>): Promise<string> {
18+
return new Promise((resolve, reject) => {
19+
execFile(
20+
"git",
21+
args,
22+
{ cwd, maxBuffer: 16 * 1024 * 1024 },
23+
(error, stdout, stderr) => {
24+
if (error) {
25+
reject(new Error(stderr.trim() || error.message));
26+
return;
27+
}
28+
resolve(stdout);
29+
},
30+
);
31+
});
32+
}
33+
34+
function parseDecorations(raw: string): {
35+
refs: VcsHistoryCommitRef[];
36+
headRefName: string | null;
37+
} {
38+
const refs: VcsHistoryCommitRef[] = [];
39+
let headRefName: string | null = null;
40+
if (!raw.trim()) return { refs, headRefName };
41+
42+
for (const part of raw.split(",")) {
43+
const token = part.trim();
44+
if (!token) continue;
45+
if (token.startsWith("HEAD -> ")) {
46+
const name = token.slice("HEAD -> ".length).trim();
47+
if (name) {
48+
headRefName = name;
49+
refs.push({ id: `refs/heads/${name}`, name, isRemote: false, isHead: true });
50+
}
51+
continue;
52+
}
53+
if (token === "HEAD" || token.includes(" -> ")) continue;
54+
if (token.startsWith("tag: ")) {
55+
const name = token.slice("tag: ".length).trim();
56+
if (name) refs.push({ id: `refs/tags/${name}`, name, isRemote: false, isHead: false });
57+
continue;
58+
}
59+
if (token.startsWith("origin/") || token.includes("/")) {
60+
const isRemote = token.startsWith("origin/") || token.startsWith("upstream/");
61+
refs.push({
62+
id: isRemote ? `refs/remotes/${token}` : `refs/heads/${token}`,
63+
name: token,
64+
isRemote,
65+
isHead: false,
66+
});
67+
continue;
68+
}
69+
refs.push({ id: `refs/heads/${token}`, name: token, isRemote: false, isHead: false });
70+
}
71+
return { refs, headRefName };
72+
}
73+
74+
function parseNumstat(raw: string): {
75+
filesChanged: number;
76+
insertions: number;
77+
deletions: number;
78+
files: Array<{ path: string; status: string }>;
79+
} {
80+
let insertions = 0;
81+
let deletions = 0;
82+
const files: Array<{ path: string; status: string }> = [];
83+
84+
for (const rawLine of raw.split(/\r?\n/)) {
85+
const line = rawLine.trim();
86+
if (!line) continue;
87+
const parts = rawLine.split("\t");
88+
if (parts.length >= 3) {
89+
const ins = parts[0] === "-" ? 0 : Number(parts[0]) || 0;
90+
const del = parts[1] === "-" ? 0 : Number(parts[1]) || 0;
91+
const filePath = parts.slice(2).join("\t").trim();
92+
insertions += ins;
93+
deletions += del;
94+
if (filePath) {
95+
const status = ins > 0 && del === 0 ? "A" : del > 0 && ins === 0 ? "D" : "M";
96+
files.push({ path: filePath, status });
97+
}
98+
}
99+
}
100+
101+
return {
102+
filesChanged: files.length,
103+
insertions,
104+
deletions,
105+
files,
106+
};
107+
}
108+
109+
export function listVcsHistory(
110+
input: VcsListHistoryInput,
111+
): Effect.Effect<VcsListHistoryResult, GitCommandError> {
112+
return Effect.tryPromise({
113+
try: async (): Promise<VcsListHistoryResult> => {
114+
const limit = input.limit ?? 60;
115+
const skip = input.skip ?? 0;
116+
const refArgs =
117+
input.refs && input.refs.length > 0
118+
? [...input.refs]
119+
: input.allRefs
120+
? ["--branches", "--remotes", "--tags"]
121+
: [];
122+
123+
const args = [
124+
"log",
125+
"--topo-order",
126+
...refArgs,
127+
`--skip=${skip}`,
128+
"-n",
129+
String(limit + 1),
130+
"--pretty=format:%x1e%H%x1f%h%x1f%P%x1f%D%x1f%an%x1f%ar%x1f%s%x1f%b",
131+
];
132+
133+
let stdout: string;
134+
try {
135+
stdout = await runGit(input.cwd, args);
136+
} catch (err) {
137+
const msg = err instanceof Error ? err.message : String(err);
138+
if (msg.includes("not a git repository") || msg.includes("does not have any commits")) {
139+
return {
140+
isRepo: false,
141+
headRevision: null,
142+
headRefName: null,
143+
upstreamRefName: null,
144+
aheadCount: 0,
145+
behindCount: 0,
146+
hasMore: false,
147+
commits: [],
148+
};
149+
}
150+
throw err;
151+
}
152+
153+
const [headRevision, headBranch, upstreamRefName] = await Promise.all([
154+
runGit(input.cwd, ["rev-parse", "HEAD"])
155+
.then((s) => s.trim() || null)
156+
.catch(() => null),
157+
runGit(input.cwd, ["symbolic-ref", "--short", "HEAD"])
158+
.then((s) => s.trim() || null)
159+
.catch(() => null),
160+
runGit(input.cwd, ["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{u}"])
161+
.then((s) => s.trim() || null)
162+
.catch(() => null),
163+
]);
164+
165+
let aheadCount = 0;
166+
let behindCount = 0;
167+
if (upstreamRefName) {
168+
const countsRaw = await runGit(input.cwd, [
169+
"rev-list",
170+
"--left-right",
171+
"--count",
172+
`HEAD...${upstreamRefName}`,
173+
]).catch(() => "");
174+
const [a, b] = countsRaw.trim().split(/\s+/);
175+
aheadCount = Number(a) || 0;
176+
behindCount = Number(b) || 0;
177+
}
178+
179+
let headRefName: string | null = headBranch;
180+
const commits: VcsHistoryCommit[] = [];
181+
182+
for (const record of stdout.split("\x1e")) {
183+
if (!record.trim()) continue;
184+
const fields = record.split("\x1f");
185+
if (fields.length < 8) continue;
186+
187+
const id = fields[0]?.trim() ?? "";
188+
const displayId = fields[1]?.trim() ?? "";
189+
const parentsRaw = fields[2]?.trim() ?? "";
190+
const refsRaw = fields[3]?.trim() ?? "";
191+
const author = fields[4]?.trim() ?? "";
192+
const relativeDate = fields[5]?.trim() ?? "";
193+
const subject = fields[6]?.trim() ?? "";
194+
const body = fields[7]?.trim() ?? "";
195+
const statRaw = fields[8]?.trim() ?? "";
196+
197+
if (!id || !displayId) continue;
198+
199+
const { refs, headRefName: parsedHead } = parseDecorations(refsRaw);
200+
if (parsedHead) headRefName = parsedHead;
201+
202+
commits.push({
203+
id,
204+
displayId,
205+
parentIds: parentsRaw ? parentsRaw.split(/\s+/).filter(Boolean) : [],
206+
subject,
207+
body,
208+
author,
209+
relativeDate,
210+
filesChanged: 0,
211+
insertions: 0,
212+
deletions: 0,
213+
references: refs,
214+
});
215+
}
216+
217+
const hasMore = commits.length > limit;
218+
if (hasMore) commits.length = limit;
219+
220+
return {
221+
isRepo: true,
222+
headRevision,
223+
headRefName,
224+
upstreamRefName,
225+
aheadCount,
226+
behindCount,
227+
hasMore,
228+
commits,
229+
};
230+
},
231+
catch: (cause) =>
232+
new GitCommandError({
233+
operation: "listVcsHistory",
234+
command: "git log",
235+
cwd: input.cwd,
236+
detail: cause instanceof Error ? cause.message : String(cause),
237+
}),
238+
});
239+
}
240+
241+
export function getVcsCommitFiles(
242+
input: VcsCommitFilesInput,
243+
): Effect.Effect<VcsCommitFilesResult, GitCommandError> {
244+
return Effect.tryPromise({
245+
try: async (): Promise<VcsCommitFilesResult> => {
246+
const stdout = await runGit(input.cwd, ["show", "--format=", "--numstat", input.commitId]);
247+
return parseNumstat(stdout);
248+
},
249+
catch: (cause) =>
250+
new GitCommandError({
251+
operation: "getVcsCommitFiles",
252+
command: "git show --numstat",
253+
cwd: input.cwd,
254+
detail: cause instanceof Error ? cause.message : String(cause),
255+
}),
256+
});
257+
}
258+
259+
export function getVcsCommitFileDiff(
260+
input: VcsCommitFileDiffInput,
261+
): Effect.Effect<VcsCommitFileDiffResult, GitCommandError> {
262+
return Effect.tryPromise({
263+
try: async (): Promise<VcsCommitFileDiffResult> => {
264+
const diff = await runGit(input.cwd, [
265+
"show",
266+
"--format=",
267+
"--patch",
268+
input.commitId,
269+
"--",
270+
input.filePath,
271+
]);
272+
return { diff };
273+
},
274+
catch: (cause) =>
275+
new GitCommandError({
276+
operation: "getVcsCommitFileDiff",
277+
command: "git show",
278+
cwd: input.cwd,
279+
detail: cause instanceof Error ? cause.message : String(cause),
280+
}),
281+
});
282+
}
283+
284+
export function runVcsHistoryAction(
285+
input: VcsHistoryActionInput,
286+
): Effect.Effect<VcsHistoryActionResult, GitCommandError> {
287+
return Effect.tryPromise({
288+
try: async (): Promise<VcsHistoryActionResult> => {
289+
switch (input.action) {
290+
case "fetch": {
291+
await runGit(input.cwd, ["fetch", "--all", "--prune"]);
292+
return { message: "Fetched all remotes" };
293+
}
294+
case "checkout": {
295+
if (!input.target) throw new Error("Missing target revision");
296+
await runGit(input.cwd, ["checkout", input.target]);
297+
return { message: `Checked out ${input.target}` };
298+
}
299+
case "cherry-pick": {
300+
if (!input.target) throw new Error("Missing target commit");
301+
await runGit(input.cwd, ["cherry-pick", input.target]);
302+
return { message: `Cherry-picked ${input.target}` };
303+
}
304+
case "revert": {
305+
if (!input.target) throw new Error("Missing target commit");
306+
await runGit(input.cwd, ["revert", "--no-edit", input.target]);
307+
return { message: `Reverted ${input.target}` };
308+
}
309+
case "create-branch": {
310+
if (!input.branchName || !input.target) {
311+
throw new Error("Missing branch name or target commit");
312+
}
313+
await runGit(input.cwd, ["checkout", "-b", input.branchName, input.target]);
314+
return { message: `Created branch ${input.branchName}` };
315+
}
316+
}
317+
},
318+
catch: (cause) =>
319+
new GitCommandError({
320+
operation: `runVcsHistoryAction:${input.action}`,
321+
command: `git ${input.action}`,
322+
cwd: input.cwd,
323+
detail: cause instanceof Error ? cause.message : String(cause),
324+
}),
325+
});
326+
}

‎apps/server/src/observability/RpcInstrumentation.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -232,6 +232,10 @@ const RPC_AGGREGATES = {
232232
[WS_METHODS.gitResolvePullRequest]: "git",
233233
[WS_METHODS.gitPreparePullRequestThread]: "git",
234234
[WS_METHODS.vcsListRefs]: "vcs",
235+
[WS_METHODS.vcsListHistory]: "vcs",
236+
[WS_METHODS.vcsCommitFileDiff]: "vcs",
237+
[WS_METHODS.vcsCommitFiles]: "vcs",
238+
[WS_METHODS.vcsHistoryAction]: "vcs",
235239
[WS_METHODS.vcsCreateWorktree]: "vcs",
236240
[WS_METHODS.vcsRemoveWorktree]: "vcs",
237241
[WS_METHODS.vcsCreateRef]: "vcs",

‎apps/server/src/ws.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -234,6 +234,12 @@ import { readWorkflowScript } from "./orchestration-v2/workflowScriptQuery.ts";
234234
import * as WorkspacePaths from "./workspace/WorkspacePaths.ts";
235235
import * as VcsStatusBroadcaster from "./vcs/VcsStatusBroadcaster.ts";
236236
import * as VcsProvisioningService from "./vcs/VcsProvisioningService.ts";
237+
import {
238+
getVcsCommitFileDiff,
239+
getVcsCommitFiles,
240+
listVcsHistory,
241+
runVcsHistoryAction,
242+
} from "./git/gitHistory.ts";
237243
import * as GitWorkflowService from "./git/GitWorkflowService.ts";
238244
import { assertCheckoutIdle } from "./git/sharedCheckoutGuard.ts";
239245
import { refreshPushedPullRequests } from "./git/refreshPushedPullRequests.ts";
@@ -3386,6 +3392,10 @@ export const layerWsRpc = (
33863392
Effect.tap(() => refreshGitStatus(input.cwd)),
33873393
),
33883394
[WS_METHODS.vcsListRefs]: (input) => gitWorkflow.listRefs(input),
3395+
[WS_METHODS.vcsListHistory]: (input) => listVcsHistory(input),
3396+
[WS_METHODS.vcsCommitFileDiff]: (input) => getVcsCommitFileDiff(input),
3397+
[WS_METHODS.vcsCommitFiles]: (input) => getVcsCommitFiles(input),
3398+
[WS_METHODS.vcsHistoryAction]: (input) => runVcsHistoryAction(input),
33893399
[WS_METHODS.vcsCreateWorktree]: (input) =>
33903400
// A project that tracks repositories gets a task folder, as its new worktree threads do.
33913401
taskFolders.createForProjectFolder(input, { projectCommands }).pipe(

0 commit comments

Comments
 (0)