feat(ui): 文件树新增 Git 面板(提交历史 / 提交详情 / 未提交改动)

原来想看仓库改了什么只能开终端敲 git,界面里没有入口。复用预览栏做二选一
(body.pv-mode-vcs):打开时占预览的位置,点文件自动切回预览,不再各占一块屏。

三个视图只用一个渲染器:列表 → 点提交进详情,顶部「未提交的改动」进工作区,
两者仅头部信息不同(有无 commit 元信息)。只读,不做 commit / checkout / pull。

不做任何自动刷新:只在打开面板、切视图、点刷新时请求,避免边干活边被打断。

后端 git.js 用 execFile 调 git,加 -c core.quotepath=false 保中文路径不被转义成
八进制;status 用 -z 输出,否则含空格的路径带引号、和 diff 里的裸路径对不上。
patch 按单文件 120KB / 合计 400KB 截断,未跟踪文件用 diff --no-index 现算。
不是仓库或没装 git 返回 HTTP 200 + reason,由界面给空状态。

镜像补装 git,apt 源照 executor/Dockerfile 换成腾讯云镜像(默认源在国内 update 会卡死)。
This commit is contained in:
2026-11-13 11:00:50 +08:00
parent ecf32c0388
commit 43dec0ad0f
8 changed files with 624 additions and 0 deletions
+16
View File
@@ -2,6 +2,22 @@ FROM node:20-slim
ENV TZ=Asia/Shanghai
# git:Git 面板(提交历史 / 未提交改动)要读仓库,本机与容器共用同一条代码路径。
# 国内构建慢:apt 默认源在国外,apt-get update 能卡十几分钟。默认换成腾讯云镜像(与 executor 同源)。
# 境外构建或想换源:docker compose build --build-arg DEBIAN_MIRROR=deb.debian.org
ARG DEBIAN_MIRROR=mirrors.cloud.tencent.com
# 换 apt 源:bookworm 可能是 /etc/apt/sources.list,也可能是 deb822 的 /etc/apt/sources.list.d/*.sources,
# 直接 grep 扫一遍、只替换域名,两种格式都盖住(路径 /debian、/debian-security 保持不变)。
RUN set -eux; \
files="$(grep -rl 'deb.debian.org' /etc/apt/ 2>/dev/null || true)"; \
if [ -n "$files" ]; then sed -i "s|deb.debian.org|${DEBIAN_MIRROR}|g" $files; fi
# 装完清 apt 列表,不给镜像多留几十 MB。
RUN apt-get update \
&& apt-get install -y --no-install-recommends git \
&& rm -rf /var/lib/apt/lists/*
WORKDIR /app
# 国内构建慢:npm 默认源在国外。默认换成腾讯云 npm 镜像(与宿主机 ~/.npmrc 一致)。
+263
View File
@@ -0,0 +1,263 @@
// 只读 git 数据层:仓库探测 / 提交列表 / 提交详情 / 未提交改动详情。
// 一律 execFile + 参数数组(不经 shell),只跑 rev-parse / status / log / show / diff,不碰任何写操作。
// -c core.quotepath=false:中文路径原样返回,不转义成 \346\226\207 那种八进制。
const { execFile } = require('child_process');
const fs = require('fs');
const TIMEOUT = 8000;
const MAX_BUFFER = 8 * 1024 * 1024;
const PATCH_FILE_MAX = 120 * 1024; // 单文件 diff 字符上限
const PATCH_TOTAL_MAX = 400 * 1024; // 整页 diff 字符上限
const UNTRACKED_MAX_BYTES = 512 * 1024; // 未跟踪文件超过此大小不生成 diff
const MAX_FILES = 300; // 一次最多返回的文件数
const BASE = ['-c', 'core.quotepath=false'];
function run(dir, args) {
return new Promise((resolve, reject) => {
// cwd 不存在时 execFile 也报 ENOENT,会和「没装 git」混为一谈,先自己挡掉
let isDir = false;
try { isDir = fs.statSync(dir).isDirectory(); } catch (_) { isDir = false; }
if (!isDir) return reject(Object.assign(new Error('会话目录不存在'), { reason: 'not_repo' }));
execFile('git', BASE.concat(args), { cwd: dir, timeout: TIMEOUT, maxBuffer: MAX_BUFFER }, (err, stdout, stderr) => {
if (!err) return resolve(stdout);
err.stdout = String(stdout || '');
err.stderr = String(stderr || '').trim();
reject(err);
});
});
}
function reasonOf(err) {
if (err && err.code === 'ENOENT') return 'no_git';
if (err && err.code === 'ETIMEDOUT') return 'timeout';
return 'not_repo';
}
// 仓库信息:root 用 --show-toplevel(会话目录可能是仓库子目录);空仓库没有 HEAD,不算错。
async function ensureRepo(dir) {
let root;
try {
root = (await run(dir, ['rev-parse', '--show-toplevel'])).trim();
} catch (err) {
throw Object.assign(new Error(err.code === 'ENOENT' ? '未安装 git' : '当前目录不是 git 仓库'), { reason: reasonOf(err) });
}
if (!root) throw Object.assign(new Error('当前目录不是 git 仓库'), { reason: 'not_repo' });
let branch = '';
let head = '';
try { branch = (await run(root, ['symbolic-ref', '--short', '-q', 'HEAD'])).trim(); } catch (_) { /* detached */ }
try { head = (await run(root, ['rev-parse', '--short', 'HEAD'])).trim(); } catch (_) { /* 空仓库 */ }
return { root, branch: branch || (head ? 'detached' : ''), head };
}
// 把一个整段 diff 按 `diff --git` 切开,键是文件路径。
// 路径优先取 `+++ b/...`(改后),删除文件取 `--- a/...`;都没有就等于没有内容变化(仅 mode 变更)。
function patchPath(body) {
const plus = body.match(/^\+\+\+ b\/(.+)$/m);
if (plus) return plus[1].replace(/\t$/, '');
const minus = body.match(/^--- a\/(.+)$/m);
if (minus) return minus[1].replace(/\t$/, '');
const head = body.match(/^diff --git a\/(.+) b\/(.+)$/m);
return head ? head[2] : null;
}
function splitPatch(text) {
const out = new Map();
if (!text) return out;
const parts = String(text).split(/^diff --git /m);
for (let i = 1; i < parts.length; i++) {
const body = 'diff --git ' + parts[i];
const p = patchPath(body);
if (p) out.set(p, body);
}
return out;
}
function countLines(patch) {
let adds = 0;
let dels = 0;
for (const line of String(patch).split('\n')) {
if (line.charAt(0) === '+' && line.charAt(1) !== '+') adds++;
else if (line.charAt(0) === '-' && line.charAt(1) !== '-') dels++;
}
return { adds, dels };
}
function statusOf(patch, fallback) {
if (/^new file mode /m.test(patch)) return 'A';
if (/^deleted file mode /m.test(patch)) return 'D';
if (/^rename from /m.test(patch) || /^copy from /m.test(patch)) return 'R';
if (/^Binary files .* differ$/m.test(patch) || /^GIT binary patch$/m.test(patch)) return fallback || 'M';
return fallback || 'M';
}
function isBinary(patch) {
return /^Binary files .* differ$/m.test(patch) || /^GIT binary patch$/m.test(patch);
}
// 裁剪 + 汇总。逐文件先裁,再按总量裁(超出的文件保留路径与统计,patch 置空并标 truncated)。
function buildFiles(map, order, extra) {
const files = [];
const byPath = new Map();
let budget = PATCH_TOTAL_MAX;
for (const p of order) {
if (files.length >= MAX_FILES) break;
const raw = map.get(p) || '';
const binary = isBinary(raw);
let patch = raw;
let truncated = false;
if (patch.length > PATCH_FILE_MAX) { patch = patch.slice(0, PATCH_FILE_MAX); truncated = true; }
if (patch.length > budget) { patch = ''; truncated = true; }
budget -= patch.length;
const counts = binary ? { adds: 0, dels: 0 } : countLines(patch);
const item = {
path: p,
status: extra && extra[p] ? extra[p].status : statusOf(raw, extra && extra[p] && extra[p].status),
adds: counts.adds,
dels: counts.dels,
binary: binary,
truncated: truncated,
patch: binary ? '' : patch,
};
if (extra && extra[p] && extra[p].old_path) item.old_path = extra[p].old_path;
files.push(item);
byPath.set(p, item);
}
return files;
}
function summarize(files) {
let adds = 0;
let dels = 0;
for (const f of files) { adds += f.adds; dels += f.dels; }
return { stats: { files: files.length, adds, dels } };
}
// git status --porcelain -z:拿未跟踪文件和状态字母(已跟踪文件的 patch 统一从 `diff HEAD` 拆)
// -z 必须加:不加引号规则下含空格的路径会被写成 "a b.txt",和 diff 里的裸路径对不上,会多出幽灵条目。
// -z 里改名的旧路径是紧随其后的一条 NUL 分隔记录。
function worktreeEntries(out) {
const entries = [];
const parts = String(out || '').split('\0');
for (let i = 0; i < parts.length; i++) {
const line = parts[i];
if (!line || line.length < 4) continue;
const xy = line.slice(0, 2);
const p = line.slice(3);
let oldPath = '';
if (/[RC]/.test(xy)) {
oldPath = parts[i + 1] || '';
i++;
}
let status = 'M';
if (xy === '??') status = 'U';
else if (xy.indexOf('A') >= 0) status = 'A';
else if (xy.indexOf('D') >= 0) status = 'D';
else if (xy.indexOf('R') >= 0) status = 'R';
entries.push({ path: p, old_path: oldPath || undefined, status });
}
return entries;
}
// 未跟踪文件没有 diff:用 --no-index 对 /dev/null 造一个(退出码 1 = 有差异,属正常)
async function untrackedPatch(root, rel) {
const abs = root + '/' + rel;
try {
const st = fs.statSync(abs);
if (!st.isFile() || st.size > UNTRACKED_MAX_BYTES) return { patch: '', binary: st.size > UNTRACKED_MAX_BYTES };
} catch (_) { return { patch: '', binary: false }; }
try {
return { patch: await run(root, ['diff', '--no-index', '--', '/dev/null', rel]), binary: false };
} catch (err) {
if (err.code === 1) return { patch: err.stdout, binary: false };
return { patch: '', binary: false };
}
}
async function worktreeDetail(root) {
let entries = [];
try { entries = worktreeEntries(await run(root, ['status', '--porcelain', '-z'])); }
catch (_) { entries = []; }
let all = '';
try { all = await run(root, ['diff', 'HEAD']); } catch (_) { all = ''; } // 空仓库没有 HEAD
const map = splitPatch(all);
const extra = {};
for (const e of entries) extra[e.path] = e;
const order = [];
for (const e of entries) order.push(e.path);
for (const p of map.keys()) if (!extra[p]) { extra[p] = { status: 'M' }; order.push(p); }
for (const e of entries) {
if (e.status !== 'U' || map.has(e.path)) continue;
const r = await untrackedPatch(root, e.path);
if (r.patch) map.set(e.path, r.patch);
else if (r.binary) extra[e.path].binary = true;
}
const files = buildFiles(map, order, extra);
return { kind: 'worktree', commit: null, files: files, ...summarize(files) };
}
// git log:before 是上一页最后一条的 commit id,用 `<id>^` 翻页(git 天然不含自身)。
async function listCommits(dir, before, limit) {
const repo = await ensureRepo(dir);
const n = Math.max(1, Math.min(100, limit || 30));
const args = ['log', '--max-count=' + (n + 1), '--pretty=format:%H%x1f%h%x1f%an%x1f%aI%x1f%s'];
if (before) args.push(before + '^', '--');
let out = '';
try { out = await run(repo.root, args); } catch (err) {
if (before) return { ok: true, repo, worktree: null, commits: [], next: null }; // 已经翻到底
if (reasonOf(err) === 'no_git') throw err;
return { ok: true, repo, worktree: null, commits: [], next: null }; // 空仓库
}
const rows = out.split('\n').filter(Boolean).map((line) => {
const f = line.split('\x1f');
return { id: f[0], short: f[1], author: f[2], time: f[3], subject: f[4] || '' };
});
const hasMore = rows.length > n;
const commits = hasMore ? rows.slice(0, n) : rows;
const next = hasMore && commits.length ? commits[commits.length - 1].id : null;
let worktree = null;
try {
const st = await run(repo.root, ['status', '--porcelain']);
worktree = { files: st.split('\n').filter(Boolean).length };
} catch (_) { worktree = null; }
return { ok: true, repo, worktree, commits, next };
}
async function commitDetail(dir, rev) {
const repo = await ensureRepo(dir);
if (rev === 'worktree') {
const d = await worktreeDetail(repo.root);
return { ok: true, repo, ...d };
}
let meta;
try {
meta = await run(repo.root, ['show', '-s', '--first-parent', '--format=%H%x1f%h%x1f%an%x1f%ae%x1f%aI%x1f%P%x1f%s%x1f%b', rev]);
} catch (err) {
throw Object.assign(new Error('提交不存在或读取失败'), { reason: 'bad_rev' });
}
const f = meta.split('\x1f');
const commit = {
id: f[0], short: f[1], author: f[2], email: f[3], time: f[4],
parents: String(f[5] || '').split(' ').filter(Boolean),
subject: f[6] || '', body: (f[7] || '').replace(/\s+$/, ''),
};
// --first-parent:合并提交默认不出 patch,跟第一个父提交比才是"这次合并带进来什么"
let all = '';
try { all = await run(repo.root, ['show', '--first-parent', '--format=', '--patch', rev]); } catch (_) { all = ''; }
const map = splitPatch(all);
const order = [...map.keys()];
const files = buildFiles(map, order, null);
return { ok: true, repo, kind: 'commit', commit, files, ...summarize(files) };
}
// 统一入口:ok:false 只用于「不是仓库 / 没装 git / 会话不存在」,前端按 reason 出空状态
async function query(dir, kind, opts) {
try {
if (kind === 'commits') return await listCommits(dir, opts && opts.before, opts && opts.limit);
return await commitDetail(dir, (opts && opts.rev) || '');
} catch (err) {
return { ok: false, reason: (err && err.reason) || 'not_repo', error: String((err && err.message) || err) };
}
}
module.exports = { query };
+67
View File
@@ -1640,6 +1640,73 @@ body.pv-resizing #pv-pane iframe { pointer-events: none; }
.pv-none button { margin-top: 8px; border: 0; background: var(--active); color: #fff; border-radius: 8px; padding: 9px 22px; font-size: 13px; cursor: pointer; }
.pv-none button:hover { opacity: .88; }
/* ---------- Git 面板(复用预览栏:body.pv-mode-vcs。列表 / 提交详情 / 未提交改动)---------- */
/* 文件树头的 Git 钮开启时高亮用通用的 .icon-btn.active(如显示隐藏文件那种),不另造类 */
.vcs-list { padding-bottom: 24px; }
/* 列表顶部的仓库行:会话目录可能只是仓库的某个子目录,所以显式写出 root */
.vcs-repo { padding: 9px 16px; border-bottom: 1px solid var(--border); background: var(--drawer-bg);
font: 11.5px/1.5 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; color: var(--gray);
overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.vcs-empty { padding: 44px 24px; text-align: center; font-size: 13px; color: var(--gray-light); }
.vcs-item { padding: 10px 16px; border-bottom: 1px solid var(--border); cursor: pointer; }
.vcs-item:hover { background: var(--surface); }
.vcs-item .t { font-size: 13.5px; font-weight: 600; color: var(--ink); word-break: break-word; line-height: 1.45; }
.vcs-item .m { margin-top: 3px; font-size: 12px; color: var(--gray); }
.vcs-item .m code { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }
/* 「未提交的改动」入口:列表顶部单独一行,与提交行区分 */
.vcs-item.wt { background: var(--active-light); }
.vcs-item.wt:hover { background: #e3ecfe; }
.vcs-more { display: block; margin: 14px auto 0; padding: 7px 18px; font-size: 12.5px; color: var(--ink);
background: var(--page); border: 1px solid var(--border); border-radius: 8px; cursor: pointer; }
.vcs-more:hover { background: var(--surface); }
.vcs-back { display: flex; align-items: center; gap: 6px; padding: 8px 14px; font-size: 12.5px; color: var(--active);
background: var(--page); border-bottom: 1px solid var(--border); cursor: pointer; position: sticky; top: 0; z-index: 2; }
.vcs-back:hover { background: var(--surface); }
.vcs-commit { padding: 12px 16px 14px; border-bottom: 1px solid var(--border); background: var(--drawer-bg); }
.vcs-subject { font-size: 14px; font-weight: 700; line-height: 1.5; word-break: break-word; }
.vcs-meta { margin-top: 6px; display: flex; flex-wrap: wrap; align-items: center; gap: 6px; font-size: 12px; color: var(--gray); }
.vcs-meta code { padding: 1px 6px; border-radius: 5px; background: var(--surface); font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }
.vcs-meta .vcs-hash { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; color: var(--active); }
.vcs-err-t { max-width: 420px; }
.vcs-msg { margin: 8px 0 0; font: 12.5px/1.6 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; white-space: pre-wrap; color: #444; }
.vcs-sum { display: flex; align-items: center; gap: 10px; padding: 8px 16px; font-size: 12px; color: var(--gray); border-bottom: 1px solid var(--border); }
.vcs-sum b.a { color: #1a7f37; }
.vcs-sum b.d { color: #cf222e; }
.vcs-file { border-bottom: 1px solid var(--border); }
.vcs-fh { display: flex; align-items: center; gap: 8px; padding: 8px 12px; font-size: 12.5px; cursor: pointer; user-select: none; }
.vcs-fh:hover { background: var(--surface); }
.vcs-caret { flex: none; width: 10px; color: var(--gray); transition: transform .12s ease; }
.vcs-file.open .vcs-caret { transform: rotate(90deg); }
.vcs-path { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; color: var(--ink); }
.vcs-badge { flex: none; padding: 0 5px; border-radius: 4px; font-size: 11px; line-height: 17px; background: var(--surface); color: var(--gray); }
.vcs-badge.m { color: #9a6700; background: #fff8c5; }
.vcs-badge.a { color: #1a7f37; background: #dafbe1; }
.vcs-badge.d { color: #cf222e; background: #ffebe9; }
.vcs-badge.r { color: #0550ae; background: #ddf4ff; }
.vcs-badge.u { color: #6639ba; background: #f3e8ff; }
.vcs-stat { flex: none; font-size: 11.5px; font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }
.vcs-stat .a { color: #1a7f37; }
.vcs-stat .d { color: #cf222e; }
.vcs-fb { display: none; border-top: 1px solid var(--border); overflow-x: auto; background: #fff; }
.vcs-file.open .vcs-fb { display: block; }
/* 行:旧号 / 新号 / 代码三列。代码不换行,横向滚动(diff 语义上就该逐行对齐) */
.vcs-line { display: grid; grid-template-columns: 44px 44px minmax(0, 1fr);
font: 12px/1.6 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }
.vcs-line .n { padding: 0 6px; text-align: right; color: #b0b6bd; user-select: none;
background: #fafbfc; border-right: 1px solid rgba(0,0,0,.04); }
.vcs-line .c { padding: 0 8px; white-space: pre; color: var(--ink); }
.vcs-line.a { background: #e6ffec; }
.vcs-line.a .n { background: #ccffd8; }
.vcs-line.d { background: #ffebe9; }
.vcs-line.d .n { background: #ffd7d5; }
.vcs-line.h { background: #ddf4ff; }
.vcs-line.h .c { color: #0550ae; }
.vcs-line.h .n { background: #ddf4ff; }
.vcs-line.meta .c { color: var(--gray); font-style: italic; }
.vcs-nodiff { padding: 12px 16px; font-size: 12px; color: var(--gray); }
.vcs-note { padding: 8px 16px; font-size: 12px; color: var(--gray); background: var(--drawer-bg); }
/* 通用 UI 卡片:SSE ui_card → 聊天流可点卡片(动作注册表驱动,见 preview.js) */
.ui-card { display: flex; align-items: center; gap: 10px; max-width: 420px; margin: 8px 0; padding: 10px 14px;
border: 1px solid var(--border); border-radius: 12px; background: var(--page); cursor: pointer; }
+1
View File
@@ -553,6 +553,7 @@
<script src="/js/files.js"></script>
<script src="/js/voice.js"></script>
<script src="/js/preview.js"></script>
<script src="/js/vcs.js"></script>
<script src="/js/files-tree.js"></script>
<script src="/js/settings.js"></script>
<script>
+5
View File
@@ -14,6 +14,7 @@
const SVG_REVEAL = '<svg class="ic sm" viewBox="0 0 24 24"><path d="M14 4h6v6"/><path d="M20 4l-9 9"/><path d="M19 14v5a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V6a1 1 0 0 1 1-1h5"/></svg>';
const SVG_REFRESH = '<svg class="ic sm" viewBox="0 0 24 24"><path d="M20 12a8 8 0 1 1-2.3-5.7"/><path d="M20 4v5h-5"/></svg>';
const SVG_TERM = '<svg class="ic sm" viewBox="0 0 24 24"><rect x="3" y="4" width="18" height="16" rx="2"/><path d="M7 9l3 3-3 3"/><path d="M13 15h4"/></svg>';
const SVG_VCS = '<svg class="ic sm" viewBox="0 0 24 24"><circle cx="6" cy="5" r="2"/><circle cx="6" cy="19" r="2"/><circle cx="18" cy="7" r="2"/><path d="M6 7v10"/><path d="M18 9v1a4 4 0 0 1-4 4H9"/></svg>';
const SVG_EYE = '<svg class="ic sm" viewBox="0 0 24 24"><path d="M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7S2 12 2 12z"/><circle cx="12" cy="12" r="2.6"/></svg>';
const SVG_DL = '<svg viewBox="0 0 24 24"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>';
const SVG_DEL = '<svg viewBox="0 0 24 24"><polyline points="3 6 5 6 21 6"/><path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"/><line x1="10" y1="11" x2="10" y2="17"/><line x1="14" y1="11" x2="14" y2="17"/></svg>';
@@ -408,6 +409,7 @@
'<span class="pv-actions">' +
'<button class="icon-btn" type="button" id="tree-hidden" title="显示隐藏文件" aria-label="显示隐藏文件">' + SVG_EYE + '</button>' +
'<button class="icon-btn" type="button" id="tree-refresh" title="刷新" aria-label="刷新">' + SVG_REFRESH + '</button>' +
'<button class="icon-btn" type="button" id="tree-vcs" title="Git 改动与历史" aria-label="Git 改动与历史">' + SVG_VCS + '</button>' +
'<button class="icon-btn hidden" type="button" id="tree-reveal" title="在 Finder 中打开" aria-label="在 Finder 中打开">' + SVG_REVEAL + '</button>' +
'<button class="icon-btn hidden" type="button" id="tree-terminal" title="在终端中打开" aria-label="在终端中打开">' + SVG_TERM + '</button>' +
'</span>';
@@ -441,6 +443,9 @@
});
head.querySelector('#tree-reveal').addEventListener('click', function () { localAction('reveal', ''); });
head.querySelector('#tree-terminal').addEventListener('click', function () { localAction('terminal', ''); });
head.querySelector('#tree-vcs').addEventListener('click', function () {
if (typeof window.openVcsPane === 'function') window.openVcsPane();
});
foot.querySelector('#tree-check-all').addEventListener('click', toggleSelAll);
foot.querySelector('#tree-bulk-download').addEventListener('click', bulkDownload);
foot.querySelector('#tree-bulk-delete').addEventListener('click', bulkDelete);
+2
View File
@@ -130,6 +130,7 @@ function pvOpenPane() {
function pvCloseDoc() {
if (!document.body.classList.contains('pv-open')) return;
document.body.classList.remove('pv-open', 'pv-max');
if (typeof vcsSetMode === 'function') vcsSetMode(false); // 关面板即离开 Git 模式
if (typeof pvSetMaxUI === 'function') pvSetMaxUI(false); // 收起时复位放大钮图标(函数声明提升,定义在后亦可)
pvClearBody();
pvState.name = null; pvState.url = null;
@@ -206,6 +207,7 @@ async function pvOpenOffice(name, sizeText) {
// ---------- 统一入口:所有文件点击都走这 ----------
async function openFilePreview(name, sizeText) {
if (!state.sessionId) return;
if (typeof vcsSetMode === 'function') vcsSetMode(false); // 点文件即离开 Git 面板(预览/Git 二选一)
if (PV_OFFICE.test(name)) { try { await pvOpenOffice(name, sizeText); } catch (e) { toast('预览失败:' + e.message); } return; }
let kind = pvKind(name);
if (kind === 'pdf' && !navigator.pdfViewerEnabled) kind = 'none'; // WebView 内嵌不了 PDF:给占位卡,不再自动下载
+243
View File
@@ -0,0 +1,243 @@
// Git 面板(复用 #pv-pane:预览 / Git 二选一,由 body.pv-mode-vcs 切换)。
// 三个视图:list(提交历史 + 未提交入口)/ detail(提交详情)/ worktree(未提交改动)。
// 后两者共用一个渲染器,区别只在头部有没有 commit 信息。
// 不做自动刷新:打开、切视图、点刷新时才请求。
// 依赖(全局):state esc toast req pvOpenPane pvHeader pvToolbar pvClearBody pvState pvDesktop openFilePreview
'use strict';
(function () {
const PAGE = 30;
// view: list | detail | worktree;cur: 当前详情响应;lastPreview: 进 Git 前预览的文件(切回用)
const st = { view: 'list', sid: '', repo: null, commits: [], next: null, cur: null, lastPreview: null, seq: 0 };
function bodyEl() { return document.getElementById('pv-body'); }
function sid() { return (state && state.sessionId) || ''; }
function api(p) {
return req('GET', '/api/sessions/' + encodeURIComponent(sid()) + p);
}
// 仓库路径显示在地址条上(地址条是现成的路径位,不另开头部)
function setAddr(repo) {
const t = document.getElementById('pv-title');
if (!t || !repo) return;
t.value = repo.root || '';
t.title = (repo.root || '') + (repo.branch ? ' · ' + repo.branch : '');
}
function fmtTime(iso) {
const d = new Date(iso);
if (isNaN(d.getTime())) return String(iso || '');
const p = (n) => (n < 10 ? '0' + n : '' + n);
return d.getFullYear() + '-' + p(d.getMonth() + 1) + '-' + p(d.getDate()) + ' ' + p(d.getHours()) + ':' + p(d.getMinutes());
}
const BADGE = { A: '新增', D: '删除', R: '改名', M: '修改', U: '未跟踪' };
function errBox(text, retry) {
bodyEl().innerHTML =
'<div class="pv-err"><div class="vcs-err-t"></div>' + (retry ? '<button type="button" class="vcs-retry">重试</button>' : '') + '</div>';
bodyEl().querySelector('.vcs-err-t').textContent = text;
const b = bodyEl().querySelector('.vcs-retry');
if (b) b.addEventListener('click', retry);
}
function reasonText(reason) {
if (reason === 'no_git') return '这个环境没有 git 命令(服务器镜像未装 git)。';
if (reason === 'bad_rev') return '提交不存在,可能已被改写或清理。';
if (reason === 'timeout') return 'git 执行超时,仓库可能过大。';
if (reason === 'not_repo') return '当前会话目录不是 git 仓库。';
return '读取失败:' + (reason || '未知错误');
}
// ---------- 列表 ----------
function renderList() {
const parts = [];
parts.push('<div class="vcs-list">');
if (st.repo) {
parts.push('<div class="vcs-repo">' + esc(st.repo.root) + (st.repo.branch ? ' · ' + esc(st.repo.branch) : '') + '</div>');
}
if (st.worktree && st.worktree.files) {
parts.push('<div class="vcs-item wt" data-act="worktree">' +
'<div class="t">未提交的改动</div>' +
'<div class="m">' + st.worktree.files + ' 个文件有变动</div></div>');
}
for (const c of st.commits) {
parts.push('<div class="vcs-item" data-act="commit" data-id="' + esc(c.id) + '">' +
'<div class="t">' + esc(c.subject) + '</div>' +
'<div class="m">' + esc(c.author) + ' · ' + esc(fmtTime(c.time)) + ' · ' + esc(c.short) + '</div></div>');
}
if (!st.commits.length && !(st.worktree && st.worktree.files)) {
parts.push('<div class="vcs-empty">还没有提交记录</div>');
}
if (st.next) parts.push('<button type="button" class="vcs-more" data-act="more">加载更多</button>');
parts.push('</div>');
bodyEl().innerHTML = parts.join('');
}
// ---------- 详情(提交 / 未提交共用)----------
function lineHtml(cls, oldNo, newNo, text) {
return '<div class="vcs-line' + (cls ? ' ' + cls : '') + '"><span class="n">' + (oldNo == null ? '' : oldNo) +
'</span><span class="n">' + (newNo == null ? '' : newNo) + '</span><span class="c">' + esc(text) + '</span></div>';
}
// 行号自己推:@@ -a,b +c,d @@ 之后的上下文/+/- 分别推进两个计数器
function patchHtml(f) {
if (f.binary) return '<div class="vcs-nodiff">二进制文件,不显示差异</div>';
if (!f.patch) return '<div class="vcs-nodiff">没有可显示的差异</div>';
const out = [];
const lines = String(f.patch).split('\n');
let oldNo = 0, newNo = 0, inHunk = false, rows = 0;
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
if (i === lines.length - 1 && line === '') break; // 末尾换行不算内容行
if (line.slice(0, 2) === '@@') {
const m = /^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/.exec(line);
if (m) { oldNo = Number(m[1]); newNo = Number(m[2]); inHunk = true; }
out.push('<div class="vcs-line h"><span class="n"></span><span class="n"></span><span class="c">' + esc(line) + '</span></div>');
continue;
}
if (!inHunk) continue; // 文件头(diff --git / index / --- / +++)由文件行本身表达,不重复渲染
if (line.charAt(0) === '\\') { out.push('<div class="vcs-line meta"><span class="n"></span><span class="n"></span><span class="c">' + esc(line) + '</span></div>'); continue; }
const c = line.charAt(0);
if (c === '+') out.push(lineHtml('a', null, newNo++, line.slice(1)));
else if (c === '-') out.push(lineHtml('d', oldNo++, null, line.slice(1)));
else out.push(lineHtml('', oldNo++, newNo++, line.slice(1)));
if (++rows > 3000) { out.push('<div class="vcs-nodiff">行数过多,剩余部分已隐藏</div>'); break; }
}
return out.join('') || '<div class="vcs-nodiff">仅改名或模式变更,没有内容差异</div>';
}
function fileHtml(f, idx, openAll) {
const open = openAll ? ' open' : '';
return '<div class="vcs-file' + open + '" data-i="' + idx + '">' +
'<div class="vcs-fh">' +
'<span class="vcs-caret"></span>' +
'<span class="vcs-path">' + esc(f.path) + '</span>' +
'<span class="vcs-badge ' + esc(String(f.status || '').toLowerCase()) + '">' + esc(BADGE[f.status] || f.status) + '</span>' +
'<span class="vcs-stat"><b class="a">+' + f.adds + '</b><b class="d">-' + f.dels + '</b></span>' +
'</div>' +
'<div class="vcs-fb">' + patchHtml(f) + (f.truncated ? '<div class="vcs-nodiff">差异过大,已截断</div>' : '') + '</div>' +
'</div>';
}
function renderDetail(d) {
st.cur = d;
const openAll = d.files.length <= 3; // 少量文件默认展开,多文件默认折叠
const parts = [];
parts.push('<div class="vcs-detail">');
parts.push('<button type="button" class="vcs-back" data-act="back">返回提交列表</button>');
if (d.commit) {
parts.push('<div class="vcs-commit">' +
'<div class="vcs-subject">' + esc(d.commit.subject) + '</div>' +
'<div class="vcs-meta"><span>' + esc(d.commit.author) + '</span><span>' + esc(fmtTime(d.commit.time)) + '</span>' +
'<span class="vcs-hash">' + esc(d.commit.short) + '</span>' +
(d.commit.parents && d.commit.parents.length > 1 ? '<span>合并提交</span>' : '') + '</div>' +
(d.commit.body ? '<pre class="vcs-msg">' + esc(d.commit.body) + '</pre>' : '') +
'</div>');
} else {
parts.push('<div class="vcs-commit"><div class="vcs-subject">未提交的改动</div>' +
'<div class="vcs-meta"><span>' + esc(d.repo.branch || 'HEAD') + '</span><span>' + esc(d.repo.root) + '</span></div></div>');
}
parts.push('<div class="vcs-sum">' + d.stats.files + ' 个文件 · <b class="a">+' + d.stats.adds + '</b> <b class="d">-' + d.stats.dels + '</b></div>');
d.files.forEach(function (f, i) { parts.push(fileHtml(f, i, openAll)); });
if (!d.files.length) parts.push('<div class="vcs-empty">没有文件变动</div>');
parts.push('</div>');
bodyEl().innerHTML = parts.join('');
}
// ---------- 数据加载 ----------
async function loadList(more) {
const seq = ++st.seq;
const keepTop = more ? bodyEl().scrollTop : 0; // 加载更多是整体重绘,得自己把滚动位置补回去
st.view = 'list';
st.sid = sid();
if (!more) { st.commits = []; st.next = null; bodyEl().innerHTML = '<div class="pv-loading"></div>'; }
const q = '?limit=' + PAGE + (more && st.next ? '&before=' + encodeURIComponent(st.next) : '');
let d;
try { d = await api('/git/commits' + q); }
catch (e) { if (seq === st.seq) errBox('请求失败:' + (e.message || e), function () { loadList(false); }); return; }
if (seq !== st.seq) return;
if (!d || !d.ok) { errBox(reasonText(d && d.reason), function () { loadList(false); }); return; }
st.repo = d.repo;
st.worktree = d.worktree;
st.commits = more ? st.commits.concat(d.commits) : d.commits;
st.next = d.next;
setAddr(d.repo);
renderList();
if (more) bodyEl().scrollTop = keepTop;
}
async function loadDetail(rev) {
const seq = ++st.seq;
st.view = rev === 'worktree' ? 'worktree' : 'detail';
st.sid = sid();
bodyEl().innerHTML = '<div class="pv-loading"></div>';
let d;
try { d = await api('/git/commit/' + encodeURIComponent(rev)); }
catch (e) {
if (seq === st.seq) errBox('请求失败:' + (e.message || e), function () { loadDetail(rev); });
return;
}
if (seq !== st.seq) return;
if (!d || !d.ok) { errBox(reasonText(d && d.reason), function () { loadDetail(rev); }); return; }
renderDetail(d);
}
function refresh() {
if (st.view === 'list') return loadList(false);
if (st.view === 'worktree') return loadDetail('worktree');
if (st.cur && st.cur.commit) return loadDetail(st.cur.commit.id);
return loadList(false);
}
// ---------- 面板开关 ----------
function syncBtn() {
const b = document.getElementById('tree-vcs');
if (b) b.classList.toggle('active', document.body.classList.contains('pv-mode-vcs'));
}
function setMode(on) {
document.body.classList.toggle('pv-mode-vcs', !!on);
syncBtn();
}
function openPane() {
if (!sid()) { toast('请先打开一个会话'); return; }
if (typeof pvDesktop === 'function' && !pvDesktop()) { toast('Git 面板仅在桌面端可用'); return; }
const on = document.body.classList.contains('pv-mode-vcs');
if (on && st.sid === sid()) { // 再点一次:有上次预览就切回预览,否则关面板
setMode(false);
if (st.lastPreview) { openFilePreview(st.lastPreview); return; }
document.getElementById('pv-close').click();
return;
}
if (!on) st.lastPreview = (typeof pvState === 'object' && pvState && pvState.name) || null;
if (typeof pvOpenPane === 'function') pvOpenPane();
setMode(true);
pvClearBody();
pvHeader(null); // 清掉预览的文件名与下载钮;地址条下面再写仓库路径
pvToolbar({ refresh: true, popup: false, reload: refresh });
loadList(false);
}
// 事件委托:pv-body 的内容每次整体重建,逐元素绑定没必要
document.getElementById('pv-body').addEventListener('click', function (e) {
if (!document.body.classList.contains('pv-mode-vcs')) return;
const it = e.target.closest('.vcs-item');
if (it) {
if (it.dataset.act === 'worktree') loadDetail('worktree');
else if (it.dataset.act === 'commit') loadDetail(it.dataset.id);
return;
}
const more = e.target.closest('.vcs-more');
if (more) { loadList(true); return; }
const back = e.target.closest('.vcs-back');
if (back) { loadList(false); return; }
const fh = e.target.closest('.vcs-fh');
if (fh) { fh.parentNode.classList.toggle('open'); return; }
});
window.openVcsPane = openPane;
window.vcsSetMode = setMode;
window.vcsRefresh = refresh;
})();
+27
View File
@@ -9,6 +9,7 @@ const { listTaskFiles } = require('./sessions');
const { resolveInTask } = require('../tools/executor');
const downloadToken = require('../download-token');
const log = require('../log');
const git = require('../git');
const router = express.Router();
@@ -142,6 +143,32 @@ router.get('/:id/tree', function (req, res) {
});
});
// ---------- Git 面板(只读):提交列表 / 提交详情 ----------
// rev=worktree 是「未提交的改动」,与提交详情返回同一副骨架(commit=null),前端共用一个渲染器。
// 不是仓库 / 没装 git 不算错误:HTTP 200 + { ok:false, reason },由界面显示空状态。
function gitDir(req) { return engine.taskDirOf(req.params.id); }
router.get('/:id/git/commits', async function (req, res) {
const session = engine.getSession(req.params.id);
if (!session) return res.status(404).json({ error: '会话不存在' });
const limit = Math.min(Math.max(parseInt(req.query.limit, 10) || 30, 1), 100);
const before = String(req.query.before || '');
// before 只接受完整/短 hash:它会拼进 git 参数,绝不能是任意表达式
const out = await git.query(gitDir(req), 'commits', {
before: /^[0-9a-f]{7,40}$/i.test(before) ? before : '',
limit,
});
res.json(out);
});
router.get('/:id/git/commit/:rev', async function (req, res) {
const session = engine.getSession(req.params.id);
if (!session) return res.status(404).json({ error: '会话不存在' });
const rev = String(req.params.rev || '');
if (rev !== 'worktree' && !/^[0-9a-f]{4,40}$/i.test(rev)) return res.status(400).json({ error: '非法的提交编号' });
res.json(await git.query(gitDir(req), 'commit', { rev }));
});
router.get('/:id/files', function (req, res) {
try {
const session = engine.getSession(req.params.id);