feat(git): commit graph in history view and cross-spawn everywhere

- render a VSCode-style commit graph in the source control history:
  lane-assignment algorithm, SVG strip with colored rails, merge and
  branch curves, commit dots, and branch/tag badges per commit
- /commits returns parents and ref decorations across all branches
  (--branches --remotes --tags --topo-order) using unit-separator
  fields so pipes in commit subjects can't break parsing
- collect stats via a single --shortstat pass instead of one
  `git show --stat` call per commit; raise the history limit to 50
- replace child_process spawn with cross-spawn in all runtimes,
  routes, and services: it resolves .cmd shims and PATHEXT on
  Windows (fixing taskmaster's npx invocations) and delegates to
  native spawn elsewhere, removing the per-file win32 ternaries
- unit tests for the log parser and lane assignment
This commit is contained in:
Haileyesus
2026-07-06 16:09:39 +03:00
parent 09a21b3754
commit 6daae87443
22 changed files with 525 additions and 65 deletions

View File

@@ -1,5 +1,3 @@
import { spawn } from 'child_process';
import crossSpawn from 'cross-spawn';
import { appendImagesInputTag } from './shared/image-attachments.js';
@@ -9,8 +7,9 @@ import { providerAuthService } from './modules/providers/services/provider-auth.
import { providerModelsService } from './modules/providers/services/provider-models.service.js';
import { createCompleteMessage, createNormalizedMessage, flattenPromptForWindowsShell } from './shared/utils.js';
// Use cross-spawn on Windows for better command execution
const spawnFunction = process.platform === 'win32' ? crossSpawn : spawn;
// cross-spawn resolves .cmd shims/PATHEXT on Windows and delegates to
// child_process.spawn everywhere else.
const spawnFunction = crossSpawn;
let activeCursorProcesses = new Map(); // Track active processes by session ID

View File

@@ -1,4 +1,3 @@
import { spawn } from 'child_process';
import { promises as fs } from 'fs';
import os from 'os';
import path from 'path';
@@ -13,8 +12,9 @@ import { providerAuthService } from './modules/providers/services/provider-auth.
import { providerModelsService } from './modules/providers/services/provider-models.service.js';
import { createCompleteMessage, createNormalizedMessage, flattenPromptForWindowsShell } from './shared/utils.js';
// Use cross-spawn on Windows for correct .cmd resolution (same pattern as cursor-cli.js)
const spawnFunction = process.platform === 'win32' ? crossSpawn : spawn;
// cross-spawn resolves .cmd shims/PATHEXT on Windows and delegates to
// child_process.spawn everywhere else.
const spawnFunction = crossSpawn;
let activeGeminiProcesses = new Map(); // Track active processes by session ID

View File

@@ -5,8 +5,10 @@ import fs, { promises as fsPromises } from 'fs';
import path from 'path';
import os from 'os';
import http from 'http';
import { spawn } from 'child_process';
// cross-spawn is a drop-in for child_process.spawn that resolves .cmd
// shims/PATHEXT on Windows and delegates to the native spawn elsewhere.
import spawn from 'cross-spawn';
import express from 'express';
import cors from 'cors';
import mime from 'mime-types';

View File

@@ -1,10 +1,12 @@
import { createRequire } from 'node:module';
import { randomBytes, randomUUID } from 'node:crypto';
import { spawn } from 'node:child_process';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
// cross-spawn: drop-in spawn with Windows .cmd/PATHEXT resolution.
import spawn from 'cross-spawn';
import { appConfigDb } from '@/modules/database/index.js';
import { providerMcpService } from '@/modules/providers/index.js';
import { getModuleDir } from '@/utils/runtime-paths.js';
@@ -270,8 +272,10 @@ function runCommand(command: string, args: string[]): Promise<void> {
}, INSTALL_COMMAND_TIMEOUT_MS);
timer.unref?.();
child.stdout.on('data', (chunk) => output.push(String(chunk)));
child.stderr.on('data', (chunk) => output.push(String(chunk)));
// stdio config above guarantees the pipes exist; cross-spawn's types
// just don't narrow them the way node's spawn overloads do.
child.stdout?.on('data', (chunk) => output.push(String(chunk)));
child.stderr?.on('data', (chunk) => output.push(String(chunk)));
child.on('error', (error) => finish(() => reject(error)));
child.on('close', (code) => finish(() => {
if (code === 0) {

View File

@@ -1,7 +1,9 @@
import { spawn } from 'node:child_process';
import { access, mkdir, rm } from 'node:fs/promises';
import path from 'node:path';
// cross-spawn: drop-in spawn with Windows .cmd/PATHEXT resolution.
import spawn from 'cross-spawn';
import { githubTokensDb } from '@/modules/database/index.js';
import { createProject } from '@/modules/projects/services/project-management.service.js';
import type { WorkspacePathValidationResult } from '@/shared/types.js';

View File

@@ -1,7 +1,6 @@
import { access, readdir } from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import { spawn } from 'node:child_process';
import crossSpawn from 'cross-spawn';
@@ -589,7 +588,9 @@ type CursorModelRow = {
const CURSOR_MODELS_TIMEOUT_MS = 10_000;
const CURSOR_CHATS_ROOT = path.join(os.homedir(), '.cursor', 'chats');
const spawnFunction = process.platform === 'win32' ? crossSpawn : spawn;
// cross-spawn resolves .cmd shims/PATHEXT on Windows and delegates to
// child_process.spawn everywhere else.
const spawnFunction = crossSpawn;
const ANSI_PATTERN = new RegExp(
// eslint-disable-next-line no-control-regex
'[\\u001B\\u009B][[\\]()#;?]*(?:'

View File

@@ -1,5 +1,3 @@
import { spawn } from 'node:child_process';
import Database from 'better-sqlite3';
import crossSpawn from 'cross-spawn';
@@ -67,7 +65,9 @@ export const OPENCODE_FALLBACK_MODELS: ProviderModelsDefinition = {
const OPEN_CODE_MODELS_TIMEOUT_MS = 20_000;
const MODEL_ID_LINE = /^[a-z0-9][a-z0-9._-]*\/[a-z0-9][a-z0-9._-]*$/i;
const spawnFunction = process.platform === 'win32' ? crossSpawn : spawn;
// cross-spawn resolves .cmd shims/PATHEXT on Windows and delegates to
// child_process.spawn everywhere else.
const spawnFunction = crossSpawn;
const DATE_TOKEN = /^\d{8}$/;
const SIMPLE_NUMBER_TOKEN = /^\d$/;
const VERSION_TOKEN = /^[a-z]\d+$/i;

View File

@@ -1,4 +1,3 @@
import { spawn } from 'child_process';
import fsSync from 'node:fs';
import crossSpawn from 'cross-spawn';
@@ -11,7 +10,9 @@ import { providerModelsService } from './modules/providers/services/provider-mod
import { notifyRunFailed, notifyRunStopped } from './services/notification-orchestrator.js';
import { createCompleteMessage, createNormalizedMessage, flattenPromptForWindowsShell, getOpenCodeDatabasePath } from './shared/utils.js';
const spawnFunction = process.platform === 'win32' ? crossSpawn : spawn;
// cross-spawn resolves .cmd shims/PATHEXT on Windows and delegates to
// child_process.spawn everywhere else.
const spawnFunction = crossSpawn;
const activeOpenCodeProcesses = new Map();

View File

@@ -1,5 +1,6 @@
import express from 'express';
import { spawn } from 'child_process';
// cross-spawn: drop-in spawn with Windows .cmd/PATHEXT resolution.
import spawn from 'cross-spawn';
import path from 'path';
import os from 'os';
import { promises as fs } from 'fs';

View File

@@ -1,5 +1,6 @@
import express from 'express';
import { spawn } from 'child_process';
// cross-spawn: drop-in spawn with Windows .cmd/PATHEXT resolution.
import spawn from 'cross-spawn';
import path from 'path';
import { promises as fs } from 'fs';
import { projectsDb } from '../modules/database/index.js';
@@ -861,10 +862,57 @@ router.post('/delete-branch', async (req, res) => {
}
});
// Get recent commits
// Fields are joined with the ASCII unit separator so pipes (or anything else
// typed into a commit subject) cannot break parsing.
const GIT_LOG_FIELD_SEPARATOR = '\u001f';
const GIT_LOG_PRETTY_FORMAT = '%H%x1f%P%x1f%D%x1f%an%x1f%ae%x1f%ad%x1f%s';
/**
* Parses `git log --shortstat` output produced with GIT_LOG_PRETTY_FORMAT.
*
* Each commit is one format line (hash, parent hashes, ref decorations,
* author, email, date, subject) optionally followed by its `--shortstat`
* summary line ("N files changed, ..."). Parents and refs feed the commit
* graph rendered by the History view; merge commits carry no shortstat line,
* so their `stats` stays empty.
*
* Exported for tests.
*/
export function parseGitLogWithStats(stdout) {
const commits = [];
for (const rawLine of stdout.split('\n')) {
const line = rawLine.trimEnd();
if (!line.trim()) continue;
if (line.includes(GIT_LOG_FIELD_SEPARATOR)) {
const [hash, parents, refs, author, email, date, ...messageParts] = line.split(GIT_LOG_FIELD_SEPARATOR);
commits.push({
hash,
parents: parents ? parents.split(' ').filter(Boolean) : [],
// `%D` decorations, e.g. "HEAD -> main", "origin/main", "tag: v1.0".
refs: refs ? refs.split(', ').filter(Boolean) : [],
author,
email,
date,
message: messageParts.join(GIT_LOG_FIELD_SEPARATOR),
stats: ''
});
continue;
}
if (commits.length > 0 && /files? changed/.test(line)) {
commits[commits.length - 1].stats = line.trim();
}
}
return commits;
}
// Get recent commits (across all branches, in graph order)
router.get('/commits', async (req, res) => {
const { project, limit = 10 } = req.query;
if (!project) {
return res.status(400).json({ error: 'Project id is required' });
}
@@ -876,42 +924,28 @@ router.get('/commits', async (req, res) => {
const safeLimit = Number.isFinite(parsedLimit) && parsedLimit > 0
? Math.min(parsedLimit, 100)
: 10;
// Get commit log with stats
// Branches/remotes/tags (not --all, which would drag in refs/stash) with
// `--topo-order` guarantee children appear before their parents across
// every branch, which the frontend lane-assignment relies on.
// `--shortstat` replaces the previous per-commit `git show --stat` calls.
const { stdout } = await spawnAsync(
'git',
['log', '--pretty=format:%H|%an|%ae|%ad|%s', '--date=iso-strict', '-n', String(safeLimit)],
[
'log',
'--branches',
'--remotes',
'--tags',
'--topo-order',
'--shortstat',
`--pretty=format:${GIT_LOG_PRETTY_FORMAT}`,
'--date=iso-strict',
'-n', String(safeLimit)
],
{ cwd: projectPath },
);
const commits = stdout
.split('\n')
.filter(line => line.trim())
.map(line => {
const [hash, author, email, date, ...messageParts] = line.split('|');
return {
hash,
author,
email,
date,
message: messageParts.join('|')
};
});
// Get stats for each commit
for (const commit of commits) {
try {
const { stdout: stats } = await spawnAsync(
'git', ['show', '--stat', '--format=', commit.hash],
{ cwd: projectPath }
);
commit.stats = stats.trim().split('\n').pop(); // Get the summary line
} catch (error) {
commit.stats = '';
}
}
res.json({ commits });
res.json({ commits: parseGitLogWithStats(stdout) });
} catch (error) {
console.error('Git commits error:', error);
res.json({ error: error.message });

View File

@@ -1,7 +1,7 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { parseGitStatusOutput } from './git.js';
import { parseGitLogWithStats, parseGitStatusOutput } from './git.js';
// Builds `git status --porcelain=v1 -z` output: NUL-separated entries with a
// trailing NUL, exactly as git emits it.
@@ -66,3 +66,41 @@ test('parseGitStatusOutput handles empty output', () => {
staged: [],
});
});
// Builds one `git log --pretty=format:%H%x1f%P%x1f%D%x1f%an%x1f%ae%x1f%ad%x1f%s` line.
const US = '';
const logLine = (hash, parents, refs, subject) =>
[hash, parents, refs, 'Alice', 'a@x.com', '2026-07-06T10:00:00+03:00', subject].join(US);
test('parseGitLogWithStats parses commits with parents, refs, and shortstat lines', () => {
const output = [
logLine('c3', 'c2', 'HEAD -> main, origin/main, tag: v1.0', 'feat: add | pipes | to subject'),
' 3 files changed, 10 insertions(+), 2 deletions(-)',
'',
logLine('c2', 'c1 c0', '', 'Merge branch feature'),
'',
logLine('c0', '', '', 'initial commit'),
' 1 file changed, 1 insertion(+)',
].join('\n');
const commits = parseGitLogWithStats(output);
assert.equal(commits.length, 3);
assert.deepEqual(commits[0].parents, ['c2']);
assert.deepEqual(commits[0].refs, ['HEAD -> main', 'origin/main', 'tag: v1.0']);
// Pipes in the subject survive because fields are joined with .
assert.equal(commits[0].message, 'feat: add | pipes | to subject');
assert.equal(commits[0].stats, '3 files changed, 10 insertions(+), 2 deletions(-)');
// Merge commit: two parents, no shortstat line.
assert.deepEqual(commits[1].parents, ['c1', 'c0']);
assert.equal(commits[1].stats, '');
// Root commit: no parents.
assert.deepEqual(commits[2].parents, []);
assert.equal(commits[2].stats, '1 file changed, 1 insertion(+)');
});
test('parseGitLogWithStats handles empty output', () => {
assert.deepEqual(parseGitLogWithStats(''), []);
});

View File

@@ -12,7 +12,9 @@ import express from 'express';
import fs from 'fs';
import path from 'path';
import { promises as fsPromises } from 'fs';
import { spawn } from 'child_process';
// cross-spawn: drop-in spawn with Windows .cmd/PATHEXT resolution — required
// here since task-master/npx are .cmd shims on Windows.
import spawn from 'cross-spawn';
import { projectsDb } from '../modules/database/index.js';
import { detectTaskMasterMCPServer } from '../utils/mcp-detector.js';
import { broadcastTaskMasterProjectUpdate, broadcastTaskMasterTasksUpdate } from '../utils/taskmaster-websocket.js';

View File

@@ -1,8 +1,9 @@
import express from 'express';
// cross-spawn: drop-in spawn with Windows .cmd/PATHEXT resolution.
import spawn from 'cross-spawn';
import { userDb } from '../modules/database/index.js';
import { authenticateToken } from '../middleware/auth.js';
import { getSystemGitConfig } from '../utils/gitConfig.js';
import { spawn } from 'child_process';
const router = express.Router();

View File

@@ -1,4 +1,5 @@
import { spawn } from 'child_process';
// cross-spawn: drop-in spawn with Windows .cmd/PATHEXT resolution.
import spawn from 'cross-spawn';
function spawnAsync(command, args) {
return new Promise((resolve, reject) => {

View File

@@ -1,5 +1,7 @@
import { spawn } from 'child_process';
import path from 'path';
// cross-spawn: drop-in spawn with Windows .cmd/PATHEXT resolution.
import spawn from 'cross-spawn';
import { scanPlugins, getPluginsConfig, getPluginDir } from './plugin-loader.js';
// Map<pluginName, { process, port }>