4 Commits
Author SHA1 Message Date
kicer a2bedbf0d7 feat(ui): 文件树头部操作钮分左右两组
五个图标钮原来全挤在右端(显示隐藏文件 / 刷新 / Git / Finder / 终端),
一排点下来容易点到隔壁,刷新和 Git 面板尤其挨得近。

现在左边一组是树内只读操作(显示隐藏文件、刷新、Git),右边一组是拉到外部
打开(Finder、终端,仅本地模式出现),两端由 space-between 拉开,组内间距仍按
侧栏收紧成 4px。没动机器行为,只多包一层 span 加两条覆盖规则。
2026-11-13 11:25:55 +08:00
kicer 3d5c8a80f1 feat(ui): 预览栏新增查看源码按钮
手机端 #fs-viewer 早有眼睛钮,桌面端预览栏只有下载和刷新:md / html / svg
这类渲染过的内容想看原文只能去终端开文件。

做法是渲染时把原文挂到节点的 __src,show() 带进 pvToolbar 的 o.source;
只有带 source 的类型才显示 #pv-src,点了在 #pv-body 里挂一个 pre 并隐藏预览
节点,再点移除。只做查看不做复制——桌面端选中即可复制,多一个按钮只是噪声。
超过 2MB 截断显示,避免大文件塞 pre 把面板卡住。

html/svg 顺手用同一份文本:r 只能读一次,svg 改为先取文本再自己包 blob。
代码类预览本身就是 .pv-pre,源码面板加 pv-src-pre 以便区分两套节点。
2026-11-13 11:25:52 +08:00
kicer 6eca2dd215 feat(ui): 会话流里的本机链接直接在预览窗打开
点 /app/task-x/daily.html 这类站内地址原来是浏览器默认的新标签,
预览窗只认 sessionId + 相对文件名,同一个地址没第二条进窗口的路。
现在 #chat-view 上加委托监听,命中本机 host 的链接就交给 pvOpenUrl:
桌面进右侧分栏,窄屏(含手机)进 #fs-viewer 全屏浮层,系统返回键可收起。

「本机」= 完全同源,或两端都是 localhost/127.0.0.1/[::1]/0.0.0.0 别名(端口不究),
部署在公网域名时同源自然命中。外链、//host、锚点、mailto、相对路径不拦;
Ctrl/Cmd 点击与中键放行,保留「我就是要开新标签」这个出口。

pvOpenUrl 走 iframe 直挂,不经过文件读取链路,sandbox 沿用现有 HTML 预览的
allow-same-origin allow-scripts——data-page 页面要靠脚本渲染表格。URL 模式下
隐藏下载钮(不是文件,按名下载会拼错路径),刷新钮重建 iframe,新窗口钮开原地址,
地址条回填完整 URL 方便复制。窄屏不传 source,源码/复制钮自动隐藏。

地址条回车顺带认站内绝对路径:/app/... 原来当相对文件名去 fetch,注定 404,
现在同样进预览窗。移动端 popstate 的判定从 [src^=/preview/] 放宽到 .fs-html-frame,
URL 预览也能被返回键收起。
2026-11-13 11:07:51 +08:00
kicer 43dec0ad0f 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 会卡死)。
2026-11-13 11:00:50 +08:00
9 changed files with 764 additions and 11 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 };
+70 -1
View File
@@ -884,7 +884,9 @@ body.voice-active .scroll-bottom-btn { display: none; }
/* 左栏树头部复用预览栏的 .pv-head / .pv-actions / .icon-btn:
它俩在桌面上左右并排,高一点点或图标小一号都会明显错位。
不放地址条:侧栏只有 280px,路径必然被截断,没有信息量。 */
.tree-head .pv-actions { gap: 4px; margin-left: auto; } /* 靠右,与预览栏的操作钮同一侧 */
/* 操作钮分两组分居两端:左边是树内只读操作(显示隐藏文件/刷新/Git),右边是外部打开 */
.tree-head { justify-content: space-between; }
.tree-head .pv-actions { gap: 4px; margin-left: 0; } /* 组内间距按侧栏收紧;两端由 space-between 拉开 */
/* 头部图标的「开启中」态(如显示隐藏文件) */
.pv-actions .icon-btn.active { color: var(--active); background: var(--active-soft); }
@@ -1640,6 +1642,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; }
+5
View File
@@ -503,6 +503,10 @@
</button>
</span>
<span class="pv-actions">
<!-- 源码钮:只在当前内容有源文本时出现(md/文本/代码/html/svg),点了在预览与原文间切换 -->
<button class="icon-btn hidden" id="pv-src" title="查看源码" aria-label="查看源码">
<svg class="ic sm" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"></path><circle cx="12" cy="12" r="3"></circle></svg>
</button>
<button class="icon-btn hidden" id="pv-download" title="下载文件" aria-label="下载文件">
<svg class="ic sm" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path><polyline points="7 10 12 15 17 10"></polyline><line x1="12" y1="15" x2="12" y2="3"></line></svg>
</button>
@@ -553,6 +557,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>
+11 -2
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>';
@@ -401,13 +402,18 @@
// 头部直接复用预览栏的 .pv-head / .pv-actions / .icon-btn:
// 两者在桌面上左右并排,尺寸/描边/内边距必须一模一样,否则一眼就看出错位。
// 不放地址条(路径在 280px 里必然截断,没有信息量),所以只剩右侧操作钮。
// 不放地址条(路径在 280px 里必然截断,没有信息量)。
// 操作钮按用途分两组:左边是树内的只读操作(显示隐藏文件 / 刷新 / Git 面板),
// 右边是拉到外部打开(Finder / 终端,仅本地模式出现)。两组分居两端,连点不易误触。
const head = document.createElement('header');
head.className = 'pv-head tree-head';
head.innerHTML =
'<span class="pv-actions">' +
'<span class="pv-actions tree-actions-main">' +
'<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>' +
'</span>' +
'<span class="pv-actions tree-actions-ext">' +
'<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 +447,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);
+114 -8
View File
@@ -15,9 +15,11 @@ const PV_PLAIN = /\.(txt|log)$/i;
// 常见代码/配置/数据文本扩展名;无扩展名的文件(Dockerfile/LICENSE 等)也按文本尝试,二进制嗅探兜底
const PV_TEXT = /\.(md|markdown|txt|log|csv|tsv|json|jsonl|xml|yml|yaml|toml|ini|conf|cfg|properties|env|py|pyw|js|mjs|cjs|ts|tsx|jsx|java|kt|c|h|cpp|hpp|cc|cs|go|rs|rb|php|swift|sh|bash|zsh|bat|ps1|sql|lua|r|dart|vue|css|less|scss|srt|vtt)$/i;
const PV_TEXT_MAX = 512 * 1024; // 文本预览截断阈值(字符),超出提示下载看全文
const PV_SRC_MAX = 2 * 1024 * 1024; // 源码面板的显示上限,超过就只给前 2MB(大文件塞 pre 会卡)
let pvSeq = 0; // 预览序号:快速连点时旧请求不许再动 DOM
// reload: 当前内容的"重新载入"动作(文本类无 iframe,按名重开);为 null 时回退到 reload iframe
const pvState = { name: null, url: null, blobUrl: null, reload: null, mobilePush: false };
const pvState = { name: null, url: null, blobUrl: null, reload: null, mobilePush: false,
source: null, srcOn: false, bodyNode: null, srcPre: null };
function pvDesktop() { return window.matchMedia('(min-width: 960px)').matches; }
@@ -75,6 +77,40 @@ function pvToolbar(o) {
document.getElementById('pv-popup').classList.toggle('hidden', !o.popup);
pvState.reload = typeof o.reload === 'function' ? o.reload : null;
pvState.url = o.url === undefined ? null : o.url;
// 源码钮:o.source 是原文(已渲染过的内容才有),没传就藏起来并回到预览态
pvState.source = o.source == null || o.source === '' ? null : String(o.source);
pvState.srcOn = false;
pvState.srcPre = null;
const sb = document.getElementById('pv-src');
sb.classList.toggle('hidden', pvState.source == null);
sb.classList.remove('active');
sb.title = '查看源码';
sb.setAttribute('aria-label', '查看源码');
}
// 预览 ↔ 源码互切:不重建预览节点,只把它 display:none 再挂一个等宽 pre,来回切代价很低
function pvToggleSrc() {
const btn = document.getElementById('pv-src');
if (!btn || pvState.source == null || !pvState.bodyNode) return;
pvState.srcOn = !pvState.srcOn;
if (pvState.srcOn) {
let text = pvState.source;
if (text.length > PV_SRC_MAX) text = text.slice(0, PV_SRC_MAX) + '\n\n…(源码较大,仅显示前 ' + Math.round(PV_SRC_MAX / 1024) + ' KB)';
const pre = document.createElement('pre');
pre.className = 'pv-pre pv-src-pre'; // 代码类预览本身也是 .pv-pre,多一个类便于区分/定位
pre.textContent = text; // 不用 innerHTML:源码里的标签必须当文本
pvState.srcPre = pre;
document.getElementById('pv-body').appendChild(pre);
pvState.bodyNode.style.display = 'none';
} else {
if (pvState.srcPre && pvState.srcPre.parentNode) pvState.srcPre.parentNode.removeChild(pvState.srcPre);
pvState.srcPre = null;
pvState.bodyNode.style.display = '';
}
btn.classList.toggle('active', pvState.srcOn);
const lbl = pvState.srcOn ? '返回预览' : '查看源码';
btn.title = lbl;
btn.setAttribute('aria-label', lbl);
}
// 每次展示内容都过一遍:标题显示相对路径(子目录可见),右上角下载钮随文件走
@@ -90,6 +126,11 @@ function pvClearBody() {
document.getElementById('pv-body').innerHTML = '';
pvState.reload = null; // 换内容/关窗后旧的刷新动作立即失效
pvState.url = null; // 新窗口地址同理:不清会残留上一份内容的 blob/网关 URL
pvState.source = null; // 源码同样跟内容走,不然会把上一个文件的原文留在按钮里
pvState.srcOn = false;
pvState.bodyNode = null;
pvState.srcPre = null;
document.getElementById('pv-src').classList.add('hidden');
if (pvState.blobUrl) { try { URL.revokeObjectURL(pvState.blobUrl); } catch (_) {} pvState.blobUrl = null; }
}
@@ -130,6 +171,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;
@@ -203,9 +245,56 @@ async function pvOpenOffice(name, sizeText) {
pvState.url = url;
}
// ---------- 站内地址预览:会话流里的链接 / 地址条回车 → 直接挂进预览窗 ----------
// 「本机」判定:完全同源,或两端都是本机别名(localhost/127.0.0.1/[::1]/0.0.0.0,端口不究)。
// 外链、锚点、mailto、相对路径都不算,调用方自行放行。
function pvLocalHost(h) { return h === 'localhost' || h === '127.0.0.1' || h === '::1' || h === '[::1]' || h === '0.0.0.0'; }
function pvSameHost(target) {
let u;
try { u = new URL(target, location.href); } catch (_) { return null; }
if (u.origin === location.origin) return u;
if (pvLocalHost(u.hostname) && pvLocalHost(location.hostname)) return u;
return null;
}
function pvUrlTitle(url) {
try {
const u = new URL(url, location.href);
return decodeURIComponent(u.pathname.split('/').filter(Boolean).pop() || '') || u.host;
} catch (_) { return String(url); }
}
// iframe 直挂,不走文件读取链路:桌面进右侧分栏,窄屏进全屏浮层。
// sandbox 与现有 HTML 预览一致——data-page 页面要靠脚本渲染表格。
function pvOpenUrl(url, title) {
const desk = pvDesktop();
const name = title || pvUrlTitle(url);
++pvSeq; // 在途的文件预览请求就此作废,别回来抢 DOM
const mkFrame = () => {
const fr = document.createElement('iframe');
fr.className = desk ? 'pv-frame' : 'fs-html-frame';
fr.title = name;
fr.setAttribute('sandbox', 'allow-same-origin allow-scripts');
fr.src = url;
return fr;
};
if (desk) {
pvOpenPane(); pvClearBody();
pvHeader(name, '');
pvState.name = null; // 不是文件:下载钮收起(按名下载会拼错路径)
document.getElementById('pv-download').classList.add('hidden');
pvToolbar({ refresh: true, popup: true, reload: () => pvOpenUrl(url, title), url });
const t = document.getElementById('pv-title'); // 地址条显示完整地址,可选中复制
t.value = url; t.title = url;
document.getElementById('pv-body').appendChild(mkFrame());
} else {
pvOverlayShow(mkFrame(), { bar: true, name });
if (!pvState.mobilePush) { try { history.pushState({ pvOffice: 1 }, ''); pvState.mobilePush = true; } catch (_) {} }
}
}
// ---------- 统一入口:所有文件点击都走这 ----------
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:给占位卡,不再自动下载
@@ -224,9 +313,12 @@ async function openFilePreview(name, sizeText) {
}
const show = (node, tb) => {
if (my !== pvSeq) return;
// 节点上挂了 __src(原文)就带进工具条:预览栏据此显示源码钮。手机端的源码钮走 fs-viewer,不掺和。
if (node && node.__src != null) { tb = Object.assign({}, tb || tbAll, { source: node.__src }); delete node.__src; }
if (desk) {
pvClearBody(); pvHeader(name, sizeText);
document.getElementById('pv-body').appendChild(node);
pvState.bodyNode = node;
pvToolbar(tb || tbAll);
} else pvOverlayShow(node, { bar: true, name: name });
};
@@ -289,11 +381,13 @@ async function openFilePreview(name, sizeText) {
// 统一等 show() 之后登记,陈旧序号则立即撤销防泄漏。
let newBlobUrl = null;
if (kind === 'html') {
const src = rewriteHtmlDocSrcs(await r.text(), name); // 相对资源改写,否则 about:srcdoc/blob 基准下全 404
const raw = await r.text(); // 原文留着做源码面板,改写只用于内嵌显示
const src = rewriteHtmlDocSrcs(raw, name); // 相对资源改写,否则 about:srcdoc/blob 基准下全 404
const fr = document.createElement('iframe');
fr.className = 'pv-frame';
fr.setAttribute('sandbox', 'allow-same-origin allow-scripts');
fr.srcdoc = src;
fr.__src = raw;
newBlobUrl = URL.createObjectURL(new Blob([src], { type: 'text/html;charset=utf-8' }));
tb = Object.assign({}, tbAll, { url: newBlobUrl }); // 新窗口=改写后的页面(与面板里同一份)
node = fr;
@@ -304,10 +398,14 @@ async function openFilePreview(name, sizeText) {
fr.className = 'pv-frame'; fr.title = String(name); fr.src = u; // 不加 sandbox:内建查看器插件需要 unrestricted 帧
node = fr; tb = Object.assign({}, tbAll, { url: u });
} else if (kind === 'img') {
const u = URL.createObjectURL(await r.blob());
// r 只能读一次:svg 先取文本再自己包 blob(也顺便拿到源码面板要的原文)
const isSvg = /\.svg$/i.test(name);
const svgText = isSvg ? await r.text() : null;
const u = URL.createObjectURL(isSvg ? new Blob([svgText], { type: 'image/svg+xml;charset=utf-8' }) : await r.blob());
newBlobUrl = u;
const im = document.createElement('img');
im.className = 'pv-img'; im.src = u; im.alt = String(name);
if (isSvg) im.__src = svgText;
const g = pvImgGroup(name);
im.addEventListener('click', () => openImageViewer(u, String(name).split('/').pop(), g && g.list, g && g.at));
node = im; tb = Object.assign({}, tbAll, { url: u });
@@ -367,13 +465,14 @@ async function pvTextNode(name, sizeText, r) {
n.__tb = q.fmt
? { popup: true, url: URL.createObjectURL(new Blob([pvMdDoc(html, name)], { type: 'text/html;charset=utf-8' })) }
: { popup: true, url: pvTextUrl(text) };
n.__src = text;
return n;
}
if (PV_PLAIN.test(low)) {
const wrap = document.createElement('div');
wrap.className = 'msg other';
wrap.innerHTML = '<div class="bubble-ai pv-doc">' + esc(text) + '</div>';
const n = wrap.firstChild; n.__tb = { popup: true, url: pvTextUrl(text) };
const n = wrap.firstChild; n.__tb = { popup: true, url: pvTextUrl(text) }; n.__src = text;
return n;
}
const frag = document.createDocumentFragment();
@@ -393,6 +492,7 @@ async function pvTextNode(name, sizeText, r) {
holder.className = 'pv-plain';
holder.appendChild(frag);
holder.__tb = { popup: true, url: pvTextUrl(text) }; // 新窗口用全文,不受面板截断影响
holder.__src = text; // 源码面板同样给全文
return holder;
}
@@ -468,6 +568,7 @@ document.getElementById('pv-max').addEventListener('click', () => {
const max = document.body.classList.toggle('pv-max');
pvSetMaxUI(max);
});
document.getElementById('pv-src').addEventListener('click', pvToggleSrc);
document.getElementById('pv-refresh').addEventListener('click', () => {
if (typeof pvState.reload === 'function') { pvState.reload(); return; }
const f = document.getElementById('pv-body').querySelector('iframe');
@@ -479,11 +580,16 @@ document.getElementById('pv-popup').addEventListener('click', () => {
});
// 地址条:点击/聚焦全选——长路径被截断时可选中看全文、直接 Ctrl+C 复制
document.getElementById('pv-title').addEventListener('focus', (e) => e.target.select());
// 地址条回车跳转:http(s) 网址新标签打开,其余按任务目录相对路径进预览
// 地址条回车跳转:本机地址(含 /app/... 这类站内绝对路径)进预览窗,外部网址新开标签,
// 其余按任务目录相对路径当文件预览。
function pvClean(s) { return String(s || '').trim().replace(/^["']+|["']+$/g, ''); }
function pvAddrGo(v) {
if (/^https?:\/\//i.test(v)) { window.open(v, '_blank', 'noopener'); return; }
if (/^https?:\/\//i.test(v)) {
if (pvSameHost(v)) { document.getElementById('pv-title').blur(); pvOpenUrl(v); return; }
window.open(v, '_blank', 'noopener'); return;
}
document.getElementById('pv-title').blur();
if (v.charAt(0) === '/' && v.charAt(1) !== '/') { pvOpenUrl(v); return; }
openFilePreview(v);
}
// ---------- 地址条文件名补全:候选取自 files.js 缓存的目录树(filesNodeAt),零请求 ----------
@@ -568,11 +674,11 @@ document.getElementById('pv-pane').addEventListener('click', (e) => {
const b = e.target.closest('.act-copy');
if (b && typeof onCopyClick === 'function') onCopyClick(e);
});
// 移动端系统返回键:先收起 office 全屏预览
// 移动端系统返回键:先收起 iframe 类全屏预览(office 网关 / 站内地址)
window.addEventListener('popstate', () => {
pvState.mobilePush = false;
const fs = document.getElementById('fs-viewer');
if (!fs.classList.contains('hidden') && fs.querySelector('.fs-html-frame[src^="/preview/"]')) closeFullscreen();
if (!fs.classList.contains('hidden') && fs.querySelector('.fs-html-frame')) closeFullscreen();
});
// Esc 关闭预览分栏(未开全屏查看器时)
window.addEventListener('keydown', (e) => {
+15
View File
@@ -705,6 +705,21 @@
$('chat-view').addEventListener('click', imgViewerDelegate);
$('fs-viewer').addEventListener('click', imgViewerDelegate);
// ---------- 会话流里的本机链接:进预览窗 ----------
// 只拦本机 host(同源 / localhost 别名);外链、锚点、mailto、相对路径维持浏览器默认。
// 修饰键与中键放行,留着「我就是要新开一个标签页」这个出口。
function linkPreviewDelegate(e) {
if (e.button !== 0 || e.ctrlKey || e.metaKey || e.shiftKey || e.altKey) return;
const a = e.target.closest('a[href]');
if (!a) return;
const href = a.getAttribute('href') || '';
if (!/^(https?:\/\/|\/(?!\/))/i.test(href) || !pvSameHost(href)) return;
e.preventDefault();
const txt = (a.textContent || '').trim();
pvOpenUrl(href, txt && txt.length <= 40 ? txt : null);
}
$('chat-view').addEventListener('click', linkPreviewDelegate);
// 图片全屏查看器:transform 缩放+平移。双指捻合缩放(1~6x)、放大后单指/鼠标拖动、双击切 2.5x。
// 第 3 参 list([{src,alt}] 或 [src]) 传入「同组图片」时开启左右滑动切换;第 4 参 at 指定起始下标。
// 切图用双层 img 做真正的分页位移(旧图跟手滑出、新图同步滑入),并在开图时预取相邻图,
+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);