feat(local): 左栏改为图标操作栏,本地端 IDE 式文件树 + 预览

侧栏底部原来的整行用户区换成四个图标:会话 / 文件树 / 预览 / 设置,
当前生效的那一项高亮;设置与预览图标都是开关(再点一次关闭)。
去掉顶部「会话/文件」分段切换,改用底部图标切换互斥面板。

- local-files.js(新增):只读文件树,懒加载单层、展开才请求、忽略大目录,
  点文件进右侧预览;支持在 Finder / 终端中打开
- routes/local.js:新增 /tree(单层、越界双重校验)、/reveal、/terminal
- preview.js:记录最后预览的文件,预览图标可重开上次文件;开合时同步图标高亮
- files.js:底部操作栏接线,设置图标点击切换开合
- settings.js:打开设置不再折叠左栏;图标选中态同步
- 纯前端 + local 路由(AGENT_LOCAL_PICK 门控),服务器/手机形态行为不变
This commit is contained in:
2026-11-11 14:49:57 +08:00
parent 80e9dcb0aa
commit 2d5467203b
8 changed files with 522 additions and 50 deletions
+78 -11
View File
@@ -853,6 +853,82 @@ body.voice-active .scroll-bottom-btn { display: none; }
.search-box input::placeholder { color: var(--gray-light); }
.drawer-list { flex: 1; min-height: 0; overflow-y: auto; padding: 0 8px 12px; }
/* ---------- 抽屉底部图标操作栏(会话/文件树/预览/设置) + 只读文件树 ----------
操作栏替代了原来整行可点的用户区:4 个图标,当前生效的那一项高亮(active)。 */
.drawer-actions {
flex: none; display: flex; align-items: center; justify-content: space-around; gap: 4px;
padding: 6px 10px calc(6px + var(--sab)); border-top: 1px solid var(--border);
background: var(--drawer-bg);
}
.drawer-act {
flex: 1; height: 40px; display: inline-flex; align-items: center; justify-content: center;
border: 0; background: none; border-radius: 10px; color: var(--gray); cursor: pointer;
transition: background .12s, color .12s;
}
.drawer-act:hover { background: var(--surface); color: var(--ink); }
.drawer-act.active { color: var(--active); background: var(--active-soft); }
.drawer-act svg {
width: 20px; height: 20px; fill: none; stroke: currentColor;
stroke-width: 1.8; stroke-linecap: round; stroke-linejoin: round;
}
/* 手机/窄屏没有右侧预览栏(预览走全屏浮层),这个按钮无意义 */
@media (max-width: 959px) { #da-preview { display: none !important; } }
.files-tree { display: none; flex: 1; min-height: 0; flex-direction: column; }
#drawer.drawer-mode-files .drawer-search,
#drawer.drawer-mode-files .drawer-list { display: none; }
#drawer.drawer-mode-files .files-tree { display: flex; }
.tree-head {
flex: none; display: flex; align-items: center; gap: 4px;
padding: 8px 12px 6px; border-bottom: 1px solid var(--border);
}
.tree-title {
flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
font-size: 13px; color: var(--ink);
}
.tree-actions { display: flex; gap: 2px; }
.tree-hbtn {
width: 26px; height: 26px; display: inline-flex; align-items: center; justify-content: center;
border: 0; background: none; border-radius: 8px; color: var(--gray); cursor: pointer;
}
.tree-hbtn:hover { background: var(--surface); color: var(--active); }
.tree-hbtn.active { color: var(--active); background: var(--active-soft); }
.tree-hbtn svg { width: 16px; height: 16px; fill: none; stroke: currentColor; stroke-width: 1.8; stroke-linecap: round; stroke-linejoin: round; }
.tree-body { flex: 1; min-height: 0; overflow: auto; padding: 4px 6px 12px; }
.tree-row {
display: flex; align-items: center; gap: 5px;
padding: 5px 6px; border-radius: 8px; cursor: pointer;
font-size: 13px; color: var(--ink); white-space: nowrap;
}
.tree-row:hover { background: var(--surface); }
.tree-row.is-ignored { color: var(--gray-light); cursor: default; }
.tree-row.is-link { color: var(--gray); }
.tree-caret { flex: none; width: 12px; height: 12px; position: relative; }
.tree-row.is-dir .tree-caret::before {
content: ""; position: absolute; left: 3px; top: 3px;
border-left: 5px solid var(--gray);
border-top: 4px solid transparent; border-bottom: 4px solid transparent;
transition: transform .12s;
}
.tree-row.is-dir.open .tree-caret::before { transform: rotate(90deg); }
.tree-ico { flex: none; width: 16px; height: 16px; display: inline-flex; color: var(--gray); }
.tree-ico svg { width: 16px; height: 16px; fill: none; stroke: currentColor; stroke-width: 1.8; stroke-linecap: round; stroke-linejoin: round; }
.tree-row.is-dir .tree-ico { color: var(--active); }
.tree-name { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; }
.tree-act {
flex: none; width: 20px; height: 20px; display: none; align-items: center; justify-content: center;
border: 0; background: none; color: var(--gray); cursor: pointer; border-radius: 6px;
}
.tree-row:hover .tree-act { display: inline-flex; }
.tree-act:hover { background: var(--border); color: var(--active); }
.tree-act svg { width: 13px; height: 13px; fill: none; stroke: currentColor; stroke-width: 1.8; stroke-linecap: round; stroke-linejoin: round; }
.tree-empty, .tree-loading, .tree-more { padding: 10px 12px; font-size: 12px; color: var(--gray); }
/* 本地模式:隐藏旧的底部「任务文件」浮层入口(它走整棵递归接口,大项目会卡死。改用左栏树) */
body.local-mode #files-btn { display: none !important; }
/* 会话分组表头(按今天/昨天分组):滚动时吸顶,下一个 group-label 滚过来时把它顶走
背景色与抽屉一致,避免 sticky 时下面会话透过看到上一组的尾巴 */
.group-label {
@@ -921,12 +997,7 @@ body.voice-active .scroll-bottom-btn { display: none; }
/* 删除会话 modal 副标题:会话 ID 等二级说明,字号小、灰色 */
.confirm-sub { font-size: 12px; color: var(--gray); margin-top: 6px; }
/* 底部用户区 */
.drawer-user {
flex: none; display: flex; align-items: center; gap: 10px;
padding: 12px 14px calc(12px + var(--sab));
border-top: 1px solid var(--border);
}
/* 底部图标操作栏见上方 .drawer-actions(原用户区整行可点已废弃) */
.avatar {
width: 36px; height: 36px; border-radius: 50%; flex: none;
background: var(--active); /* 真实用户名下的头像:JS 按用户名取色内联覆盖,与设置页 user-card 一致 */
@@ -1124,10 +1195,6 @@ label.icon-btn { cursor: pointer; }
.set-desc { font-size: 12px; color: var(--gray); }
.set-arrow { color: var(--gray-light); }
/* ---------- 抽屉底部用户区:整行可点 ---------- */
.drawer-user { cursor: pointer; }
.drawer-user:active { background: var(--surface); }
/* ---------- 通用白卡与设置表单(搬自 style.css 设置页) ---------- */
.settings-card {
background: var(--page); border: 1px solid var(--border); border-radius: 12px;
@@ -1468,7 +1535,7 @@ label.icon-btn { cursor: pointer; }
z-index: 55;
}
body.pv-open.pv-max #pv-pane { left: 0; width: auto; border-left: none; z-index: 120; }
/* 挤压式分栏:会话列让位;打开右栏时左侧历史栏会自动折叠(若手动再展开则两者同时让位) */
/* 挤压式分栏:打开右栏时会话列让位;左栏不再自动折叠(本地端左栏是文件树,需要与预览并排) */
body.pv-open #app { width: calc(100% - var(--pv-w, min(50vw, 900px))); margin-left: 0; }
body.pv-open.drawer-open #app { width: calc(100% - var(--sidebar-w) - var(--pv-w, min(50vw, 900px))); margin-left: var(--sidebar-w); }
body.pv-open.pv-max #app { width: 100%; margin-left: 0; }
+17 -7
View File
@@ -234,11 +234,20 @@
</div>
</div>
<div class="drawer-list" id="drawer-list"></div>
<div class="drawer-user" id="drawer-user">
<div class="avatar" id="drawer-avatar">A</div>
<div class="user-name" id="drawer-user-name">Agent 用户</div>
<button class="user-more" id="user-more-btn" title="更多设置" aria-label="更多设置">
<svg class="ic sm" viewBox="0 0 24 24"><circle cx="5" cy="12" r="1.4" fill="currentColor" stroke="none"></circle><circle cx="12" cy="12" r="1.4" fill="currentColor" stroke="none"></circle><circle cx="19" cy="12" r="1.4" fill="currentColor" stroke="none"></circle></svg>
<div class="files-tree hidden" id="files-tree"></div>
<!-- 底部图标操作栏:会话 / 文件树 / 预览 / 设置(文件树仅本地模式出现)。选中项高亮。 -->
<div class="drawer-actions" id="drawer-actions">
<button class="drawer-act active" id="da-sessions" type="button" title="会话" aria-label="会话">
<svg viewBox="0 0 24 24"><path d="M21 11.5a8.5 8.5 0 0 1-11.8 7.8L4 21l1.7-5.2A8.5 8.5 0 1 1 21 11.5z"></path></svg>
</button>
<button class="drawer-act hidden" id="da-files" type="button" title="文件树" aria-label="文件树">
<svg viewBox="0 0 24 24"><path d="M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"></path></svg>
</button>
<button class="drawer-act" id="da-preview" type="button" title="预览" aria-label="预览">
<svg viewBox="0 0 24 24"><rect x="3" y="4" width="18" height="16" rx="2"></rect><path d="M14 4v16"></path></svg>
</button>
<button class="drawer-act" id="da-settings" type="button" title="设置" aria-label="设置">
<svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="3.2"></circle><path d="M19.4 13.5a1.7 1.7 0 0 0 .3 1.9l.1.1a2 2 0 1 1-2.8 2.8l-.1-.1a1.7 1.7 0 0 0-1.9-.3 1.7 1.7 0 0 0-1 1.6 2 2 0 1 1-4 0 1.7 1.7 0 0 0-1-1.6 1.7 1.7 0 0 0-1.9.3l-.1.1a2 2 0 1 1-2.8-2.8l.1-.1a1.7 1.7 0 0 0 .3-1.9 1.7 1.7 0 0 0-1.6-1 2 2 0 1 1 0-4 1.7 1.7 0 0 0 1.6-1 1.7 1.7 0 0 0-.3-1.9l-.1-.1a2 2 0 1 1 2.8-2.8l.1.1a1.7 1.7 0 0 0 1.9.3 1.7 1.7 0 0 0 1-1.6 2 2 0 1 1 4 0 1.7 1.7 0 0 0 1 1.6 1.7 1.7 0 0 0 1.9-.3l.1-.1a2 2 0 1 1 2.8 2.8l-.1.1a1.7 1.7 0 0 0-.3 1.9 1.7 1.7 0 0 0 1.6 1 2 2 0 1 1 0 4 1.7 1.7 0 0 0-1.6 1z"></path></svg>
</button>
</div>
</aside>
@@ -548,17 +557,18 @@
<script src="/js/files.js"></script>
<script src="/js/voice.js"></script>
<script src="/js/preview.js"></script>
<script src="/js/local-files.js"></script>
<script src="/js/settings.js"></script>
<script>
// 启动自愈:外部工具改前端文件是非原子写入,极端时机下浏览器可能拿到半截或重复拼接的 HTML
// (脚本缺半 → 白屏裸首页;重复注入 → 每个文件报 duplicate variable 后 JS 全挂)。
// 这里检测关键脚本数量与入口全局,不对就自动整页重载一次(sessionStorage 防循环)。
// 注意:js/ 脚本增减时需同步改这里的期望数 9。
// 注意:js/ 脚本增减时需同步改这里的期望数 10。
(function () {
var ok = false;
try {
var n = document.querySelectorAll('script[src^="/js/"]').length;
ok = n === 9 && typeof state !== 'undefined' &&
ok = n === 10 && typeof state !== 'undefined' &&
typeof openFilePreview === 'function' && typeof restartNow === 'function';
} catch (_) {}
if (ok) { try { sessionStorage.removeItem('boot-heal'); } catch (_) {} return; }
+32 -3
View File
@@ -1096,6 +1096,8 @@
if (delBtn) { e.stopPropagation(); deleteSession(delBtn.dataset.del); return; }
const item = e.target.closest('.conv-item');
if (!item) return;
// 设置页现在保留左栏(可在设置中看会话/文件):点会话即退出设置页回到对话。
if (typeof closeSettings === 'function' && !$('settings-page').classList.contains('hidden')) closeSettings();
openSession(item.dataset.id);
if (!drawerMQ.matches) openDrawer(false); // 桌面端侧栏常驻,选完会话不收起来
});
@@ -1229,9 +1231,36 @@
document.addEventListener('touchcancel', e => endDrag(e, false), { passive: true });
})();
// 抽屉底部用户区:整行点击 → 设置主页(逻辑见文末「设置区」一节)
$('drawer-user').addEventListener('click', () => {
if (!drawerMQ.matches) openDrawer(false); // 桌面端设置页覆盖在会话区上,侧栏保持展开
// 抽屉底部图标操作栏:会话 / 文件树 / 预览 / 设置。
// 会话与文件树是侧栏的两个互斥面板,所以这两个的 active 由 setDrawerPane 维护;
// 预览与设置不占用侧栏(各自是右侧面板/覆盖层),高亮由 preview.js / settings.js 自己同步。
function setDrawerPane(mode) {
const drawer = $('drawer');
const files = mode === 'files';
// 文件树只在本地模式存在;服务器形态下这个按钮是 hidden 的,这里再做一层兜底
if (files && typeof window.showFileTree !== 'function') return;
const changed = drawer.classList.contains('drawer-mode-files') !== files;
drawer.classList.toggle('drawer-mode-files', files);
$('da-sessions').classList.toggle('active', !files);
$('da-files').classList.toggle('active', files);
// 重复点当前项不重干活(不重拉列表/不重渲树),避免白掉请求和滚动位置
if (changed) {
if (files) window.showFileTree();
else loadSessionList();
}
}
$('da-sessions').addEventListener('click', () => setDrawerPane('sessions'));
$('da-files').addEventListener('click', () => setDrawerPane('files'));
// 预览:同一个按钮开/关右侧面板
$('da-preview').addEventListener('click', () => {
if (typeof pvTogglePane === 'function') pvTogglePane();
});
$('da-settings').addEventListener('click', () => {
if (typeof showSettings !== 'function') return;
const page = $('settings-page');
// 再点一次返回(关设置页);否则打开。不看当前在设置栈的第几层,都当"退出设置"
if (page && !page.classList.contains('hidden')) { closeSettings(); return; }
if (!drawerMQ.matches) openDrawer(false); // 移动端设置页整屏,抽屉先收起
showSettings();
});
+238
View File
@@ -0,0 +1,238 @@
// 本地端左栏文件树(只读)。仅在 local 启动器下启用:
// 后端 /api/local/info 拿得到才显示侧栏底部的「文件树」图标与树,服务器/手机形态完全不受影响。
// 设计要点:
// - 目录是用户的真实项目,可能含 node_modules 等大目录,所以「展开才请求、一次一层」;
// - 树只负责看:点文件进右侧既有预览(#pv-pane),不提供删除/新建/重命名;
// - 「在 Finder/终端中打开」走 /api/local/reveal|terminal(后端已做会话目录内校验)。
'use strict';
(function () {
const SVG_FOLDER = '<svg viewBox="0 0 24 24"><path d="M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/></svg>';
const SVG_FILE = '<svg viewBox="0 0 24 24"><path d="M6 3h8l4 4v14H6z"/><path d="M14 3v4h4"/></svg>';
const SVG_LINK = '<svg viewBox="0 0 24 24"><path d="M10 13a5 5 0 0 0 7 0l2-2a5 5 0 0 0-7-7l-1 1"/><path d="M14 11a5 5 0 0 0-7 0l-2 2a5 5 0 0 0 7 7l1-1"/></svg>';
const SVG_REVEAL = '<svg 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 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 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_EYE = '<svg 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>';
let enabled = false;
let showHidden = false;
let expanded = new Set(['']); // 已展开的相对目录('' = 根)
let cache = new Map(); // rel -> /tree 响应
let loading = new Map(); // rel -> Promise(并发去重)
let gen = 0; // 会话切换/刷新时自增,防止旧请求回填到新树的缓存
// 失效缓存。gen 自增让在飞的旧请求回来时不再写缓存(否则切会话会闪旧目录)。
function invalidate(keepExpanded) {
gen++;
cache = new Map();
loading = new Map();
if (!keepExpanded) expanded = new Set(['']);
}
function sid() { return (state && state.sessionId) || ''; }
function tip(parent, text, cls) {
const el = document.createElement('div');
el.className = cls || 'tree-empty';
el.textContent = text;
parent.appendChild(el);
}
function openDir(rel) {
if (cache.has(rel)) return Promise.resolve(cache.get(rel));
if (loading.has(rel)) return loading.get(rel);
if (!sid()) return Promise.resolve(null);
const url = '/api/local/tree?session=' + encodeURIComponent(sid()) +
'&dir=' + encodeURIComponent(rel) + (showHidden ? '&hidden=1' : '');
const myGen = gen;
const p = req('GET', url).then(function (data) {
if (myGen === gen) { cache.set(rel, data); loading.delete(rel); }
return data;
}, function (e) {
if (myGen === gen) loading.delete(rel);
throw e;
});
loading.set(rel, p);
return p;
}
function rowFor(ent, depth) {
const row = document.createElement('div');
row.className = 'tree-row';
row.dataset.rel = ent.rel;
row.dataset.type = ent.type;
row.style.paddingLeft = (6 + depth * 14) + 'px';
row.title = ent.rel;
if (ent.type === 'dir') {
row.classList.add('is-dir');
if (expanded.has(ent.rel)) row.classList.add('open');
}
if (ent.type === 'link') row.classList.add('is-link');
if (ent.ignored) row.classList.add('is-ignored');
const caret = document.createElement('span');
caret.className = 'tree-caret';
row.appendChild(caret);
const ico = document.createElement('span');
ico.className = 'tree-ico';
ico.innerHTML = ent.type === 'dir' ? SVG_FOLDER : (ent.type === 'link' ? SVG_LINK : SVG_FILE);
row.appendChild(ico);
const name = document.createElement('span');
name.className = 'tree-name';
name.textContent = ent.name;
row.appendChild(name);
if (ent.ignored) {
row.title = ent.rel + '(已忽略的大目录/构建产物)';
} else {
const act = document.createElement('button');
act.type = 'button';
act.className = 'tree-act';
act.dataset.act = 'reveal';
act.title = '在 Finder 中显示';
act.innerHTML = SVG_REVEAL;
row.appendChild(act);
}
return row;
}
async function renderDirInto(container, rel, depth) {
container.innerHTML = '';
const data = await openDir(rel);
if (!data) return;
const frag = document.createDocumentFragment();
const list = data.entries || [];
if (!list.length) tip(frag, '(空目录)');
for (const ent of list) {
frag.appendChild(rowFor(ent, depth));
if (ent.type === 'dir' && !ent.ignored && expanded.has(ent.rel)) {
const kids = document.createElement('div');
kids.className = 'tree-children';
frag.appendChild(kids);
renderDirInto(kids, ent.rel, depth + 1).catch(function () {}); // 异步填充子层
}
}
if (data.capped) tip(frag, '仅显示前 ' + list.length + ' 项(共 ' + data.total + ' 项)', 'tree-more');
container.appendChild(frag);
}
async function renderBody() {
const body = $('tree-body');
if (!body) return;
const titleEl = $('tree-title');
if (titleEl) titleEl.textContent = (state && (state.sessionTitle || state.sessionId)) || '文件';
if (!sid()) { body.innerHTML = ''; tip(body, '尚未开始会话'); return; }
const sc = body.scrollTop;
body.innerHTML = '';
const root = document.createElement('div');
body.appendChild(root);
try {
await renderDirInto(root, '', 0);
} catch (e) {
root.innerHTML = '';
tip(root, '加载失败:' + e.message);
}
body.scrollTop = sc;
}
async function localAction(kind, rel) {
if (!sid()) { toast('尚未开始会话'); return; }
try {
await req('POST', '/api/local/' + kind, { session: sid(), path: rel });
} catch (e) {
toast((kind === 'reveal' ? '打开目录失败:' : '打开终端失败:') + e.message);
}
}
async function onTreeClick(e) {
const row = e.target.closest('.tree-row');
if (!row) return;
const act = e.target.closest('[data-act="reveal"]');
if (act) {
e.stopPropagation();
localAction('reveal', row.dataset.rel);
return;
}
const type = row.dataset.type;
const rel = row.dataset.rel;
if (row.classList.contains('is-ignored') || type === 'link') return;
if (type === 'dir') {
if (expanded.has(rel)) expanded.delete(rel); else expanded.add(rel);
await renderBody();
} else if (type === 'file') {
if (typeof openFilePreview === 'function') openFilePreview(rel, '');
}
}
function ensureShell() {
const box = $('files-tree');
if (!box || box.dataset.ready) return;
box.dataset.ready = '1';
box.innerHTML = '';
const head = document.createElement('div');
head.className = 'tree-head';
head.innerHTML =
'<span class="tree-title" id="tree-title">文件</span>' +
'<span class="tree-actions">' +
'<button class="tree-hbtn" type="button" id="tree-hidden" title="显示隐藏文件">' + SVG_EYE + '</button>' +
'<button class="tree-hbtn" type="button" id="tree-refresh" title="刷新">' + SVG_REFRESH + '</button>' +
'<button class="tree-hbtn" type="button" id="tree-reveal" title="在 Finder 中打开">' + SVG_REVEAL + '</button>' +
'<button class="tree-hbtn" type="button" id="tree-terminal" title="在终端中打开">' + SVG_TERM + '</button>' +
'</span>';
const body = document.createElement('div');
body.className = 'tree-body';
body.id = 'tree-body';
box.appendChild(head);
box.appendChild(body);
head.querySelector('#tree-hidden').addEventListener('click', function () {
showHidden = !showHidden;
invalidate(false);
this.classList.toggle('active', showHidden);
renderBody();
});
head.querySelector('#tree-refresh').addEventListener('click', function () {
invalidate(true);
renderBody();
});
head.querySelector('#tree-reveal').addEventListener('click', function () { localAction('reveal', ''); });
head.querySelector('#tree-terminal').addEventListener('click', function () { localAction('terminal', ''); });
body.addEventListener('click', onTreeClick);
}
// 侧栏底部「文件树」图标 → 切到这个面板(由 files.js 的 setDrawerPane 调用)。
// 面板切换本身由 CSS 的 drawer-mode-files 控制,这里只负责首次建壳 + 拉一层目录。
// 只在确认是本地模式后挂到 window 上:files.js 用它是否存在来判断「文件树」按钮可不可用。
function exposeShowFileTree() {
window.showFileTree = function () {
ensureShell();
renderBody();
};
}
// 会话切换后由 sessions.js 调用,避免树停在旧会话。
window.refreshFileTree = function () {
if (!enabled) return;
invalidate(false);
const drawer = $('drawer');
// 只在实际显示「文件」页时才去拉取,避免后台白跑一层目录请求。
if (drawer && drawer.classList.contains('drawer-mode-files')) renderBody();
};
(function init() {
if (!$('drawer-actions')) return;
req('GET', '/api/local/info').then(function (info) {
if (!info || !info.enabled) return;
enabled = true;
document.body.classList.add('local-mode');
$('files-tree').classList.remove('hidden');
$('da-files').classList.remove('hidden'); // 本地才有文件树
exposeShowFileTree();
}).catch(function () { /* 服务器形态:接口 404,保持原样 */ });
})();
})();
+27 -7
View File
@@ -1,7 +1,7 @@
// 通用文档预览窗(桌面右侧 #pv-pane / 移动端全屏 #fs-viewer)
// —— 文件列表的点击一律进预览窗:office 走 /preview 预览网关(固定格式前端自拼);
// md/txt/代码/json/csv 等文本渲染;html/pdf/图片专用渲染;其余类型显示文件信息占位 + 下载。
// 桌面打开时自动折叠左侧历史栏让位,关闭恢复;左右边界可拖拽调宽(记忆在 localStorage)。
// 桌面端与左栏并排(不再自动折叠左栏让位);左右边界可拖拽调宽(记忆在 localStorage)。
// 依赖(core.js/chat.js/stream.js/files.js 顶层声明):state $ esc toast mdHtml decorateCodePre
// rewriteHtmlDocSrcs rewriteMdImageSrcs openFullscreen setFsSource closeFullscreen
// openImageViewer downloadFile openDrawer
@@ -16,7 +16,8 @@ const PV_TEXT = /\.(md|markdown|txt|log|csv|tsv|json|jsonl|xml|yml|yaml|toml|ini
const PV_TEXT_MAX = 512 * 1024; // 文本预览截断阈值(字符),超出提示下载看全文
let pvSeq = 0; // 预览序号:快速连点时旧请求不许再动 DOM
// reload: 当前内容的"重新载入"动作(文本类无 iframe,按名重开);为 null 时回退到 reload iframe
const pvState = { name: null, url: null, blobUrl: null, reload: null, drawerWasOpen: false, mobilePush: false };
// lastName: 最后展示过的文件路径。关窗后 pvState.name 会被清空,靠它支持"再点预览图标重开上次文件"
const pvState = { name: null, url: null, blobUrl: null, reload: null, mobilePush: false, lastName: null };
function pvDesktop() { return window.matchMedia('(min-width: 960px)').matches; }
@@ -79,6 +80,7 @@ function pvToolbar(o) {
// 每次展示内容都过一遍:标题显示相对路径(子目录可见),右上角下载钮随文件走
function pvHeader(name, sizeText) {
pvState.name = name;
if (name) pvState.lastName = name; // 记住最后一份内容,供关窗后重开
const t = document.getElementById('pv-title');
t.value = String(name || '');
t.title = sizeText ? name + ' · ' + sizeText : String(name || '');
@@ -117,11 +119,11 @@ function pvInfoNode(name, sizeText, hint) {
}
function pvOpenPane() {
// 不自动折叠左侧栏:本地端左栏是文件树,打开预览时保持可见(左侧树 + 右侧预览并排)。
if (!document.body.classList.contains('pv-open')) {
pvState.drawerWasOpen = document.getElementById('drawer').classList.contains('open');
if (pvState.drawerWasOpen && typeof openDrawer === 'function') openDrawer(false); // 挤压式分栏:折叠左侧让位
document.body.classList.add('pv-open');
}
pvSyncBtn();
}
function pvCloseDoc() {
@@ -130,9 +132,27 @@ function pvCloseDoc() {
if (typeof pvSetMaxUI === 'function') pvSetMaxUI(false); // 收起时复位放大钮图标(函数声明提升,定义在后亦可)
pvClearBody();
pvState.name = null; pvState.url = null;
if (pvState.drawerWasOpen) {
pvState.drawerWasOpen = false;
if (typeof openDrawer === 'function') openDrawer(true); // 恢复打开预览前的折叠态
pvSyncBtn();
}
// 侧栏底部「预览」图标:开/关右侧预览面板(桌面端)。图标随开合高亮。
function pvSyncBtn() {
const b = document.getElementById('da-preview');
if (b) b.classList.toggle('active', document.body.classList.contains('pv-open'));
}
// 同一个图标开/关预览:已开 → 关;未开 → 优先重开上次看过的文件,没有就开空面板给个提示。
function pvTogglePane() {
if (!pvDesktop()) return; // 移动端预览走全屏 #fs-viewer,不维护右栏
if (document.body.classList.contains('pv-open')) { pvCloseDoc(); return; }
if (pvState.lastName) { openFilePreview(pvState.lastName); return; }
pvOpenPane(); pvClearBody(); pvHeader('', '');
const body = document.getElementById('pv-body');
if (body) {
const tip = document.createElement('div');
tip.className = 'pv-none';
tip.innerHTML = '<div class="hint">点击文件即可在此预览</div>';
body.appendChild(tip);
}
}
+6
View File
@@ -78,6 +78,7 @@
state.sessionId = null;
state.sessionTitle = '';
state.sessionType = 'secretary';
if (window.refreshFileTree) window.refreshFileTree();
state.pendingModel = '';
state.pending = [];
renderSendQueue();
@@ -188,6 +189,8 @@
removeTyping();
setFilesPanel(false); // 会话切换,收起文件面板防旧列表残留
if (typeof pvCloseDoc === 'function') pvCloseDoc(); // 同上:收起文档预览右栏,防旧会话内容残留
// 预览图标会「重开上次看过的文件」,跨会话重开会指向别的会话的路径,逐会话清掉
if (typeof pvState === 'object' && pvState) pvState.lastName = null;
state.sessionId = id;
state.status = '';
state.modelId = '';
@@ -222,6 +225,7 @@
if (state.sessionId !== id) return; // 期间已切到别的会话
renderDetail(detail);
connectStream();
if (window.refreshFileTree) window.refreshFileTree();
} catch (e) {
if (state.sessionId === id) toast('打开会话失败:' + e.message);
}
@@ -236,6 +240,7 @@
state.sessionTitle = (s && s.title) || '';
state.sessionType = (s && s.assistant_type) || state.mode;
state.pendingModel = '';
if (window.refreshFileTree) window.refreshFileTree();
setView('chat');
renderHeader();
updateHeaderActions();
@@ -293,6 +298,7 @@
state.sessionId = null;
state.sessionTitle = '';
state.sessionType = 'secretary';
if (window.refreshFileTree) window.refreshFileTree();
state.status = '';
state.modelId = '';
state.schedule = null;
+7 -22
View File
@@ -130,17 +130,17 @@
function showSettings() {
// 普通用户没有设置主页:直接进账户页(栈里只有一页,返回即退出设置)
SET.stack = [SET.role === 'admin' ? 'home' : 'account']; SET.snaps = {}; setUnderHide();
// 桌面端:打开设置时收起侧边栏让设置页占满窗口,关闭时恢复之前的展开态
if (drawerMQ.matches) { drawerWasOpenBeforeSet = document.body.classList.contains('drawer-open'); openDrawer(false); }
// 桌面端保留左侧栏:设置页是 #app 内的 absolute 覆盖层,自然只占侧栏右侧区域,
// 左栏(会话/文件)保持可见可用。
$('settings-page').classList.remove('hidden'); renderSetPage();
const b = $('da-settings'); if (b) b.classList.add('active'); // 侧栏底部图标同步选中态
}
let drawerWasOpenBeforeSet = false;
function closeSettings() {
SET.stack = []; SET.snaps = {}; setUnderHide();
// 退回会话页才重置模型池状态:平台卡全部折叠、余额清空,下次进入重新自动查
SET.expandedGroups = {}; SET.balanceByGroup = {}; SET.balanceRequested = {};
$('settings-page').classList.add('hidden');
if (drawerMQ.matches && drawerWasOpenBeforeSet) { openDrawer(true); drawerWasOpenBeforeSet = false; }
const b = $('da-settings'); if (b) b.classList.remove('active');
}
// 当前页静态快照(顶栏+正文):右滑返回时垫底,呈现原生导航栈的视差感。
// 快照里的 id 全部剥除,防止重复 id 干扰 $('…') 查找;仅作动画背景,滑完由 renderSetPage 重渲染真页。
@@ -320,23 +320,8 @@
for (const ch of String(name || '')) h = (h * 31 + ch.codePointAt(0)) >>> 0;
return AVATAR_COLORS[h % AVATAR_COLORS.length];
}
// 侧边栏底部用户区:展示真实登录用户名,头像样式与设置页 user-card 一致(按用户名取色+首两字)。
// 启动校验已经拉到登录用户时直接传入,避免同一次加载重复请求 /api/me;未传入时自拉兜底。
async function loadDrawerUser(knownUser) {
const av = $('drawer-avatar'), un = $('drawer-user-name');
if (!av || !un) return;
let name = knownUser ? String(knownUser) : '';
if (!name) {
try {
const r = await req('GET', '/api/me');
name = r && r.user ? String(r.user) : '';
} catch (_) { return; /* 未启用认证时无 /api/me,保留默认占位 */ }
}
if (!name) return; // 未登录态(理论上不会出现,401 已自动跳登录页)
av.textContent = userInitials(name);
av.style.background = avatarColor(name);
un.textContent = name;
}
// 侧栏底部已改成纯图标操作栏,不再展示登录用户名(用户信息仍在设置页「账户」里),
// 所以原来的 loadDrawerUser 已随之删除。
function userCardHtml(me) {
return '<div class="settings-card user-card">' +
'<div class="user-avatar" style="background:' + avatarColor(me) + '">' + esc(userInitials(me)) + '</div>' +
@@ -2079,7 +2064,7 @@
}
} catch (_) { /* 网络错误放过,让后续请求正常走 */ }
loadSessionList();
loadDrawerUser(verifiedUser); // 侧边栏底部展示真实登录用户(未启用鉴权/拉取失败时静默回退默认占位)
// 侧栏底部已是纯图标操作栏(不展示用户信息),不再需要 loadDrawerUser
// 会话深链 /?s=<session_id>:数据页面(/app/{task_id}/...)的「返回会话」FAB 用——
// task_id 即会话 id(engine 里 1:1),启动时消费一次即 replaceState 抹掉参数,
// 避免刷新/分享时被钉回该会话;会话已删则 openSession 自行报错,落在 welcome。
+117
View File
@@ -6,6 +6,8 @@
// 都会卡住,直到用户关掉对话框。用户取消不是错误,回 { path: '' };
// 其它失败(无对话框、权限被拒、超时)要带原因回给前端,别让用户以为是自己取消了。
const express = require('express');
const fs = require('fs');
const path = require('path');
const os = require('os');
const { execFile } = require('child_process');
const engine = require('../engine');
@@ -64,6 +66,121 @@ async function pickDir() {
throw Object.assign(new Error('没有可用的目录选择器(Linux 请安装 zenity 或 kdialog)'), { status_code: 501 });
}
// ---------- 只读文件树 / 原生文件管理器(仅本机会话目录内) ----------
// 目录可能是真实项目,含 node_modules 等大目录:一律「一次只列一层」,客户端展开才请求。
// 绝不能复用 listTaskFiles 的整棵递归——同步递归会卡死单线程 core,连 SSE 一起挂。
const IGNORE_DIRS = new Set([
'node_modules', '.git', 'dist', 'build', 'out', 'target', '.venv', 'venv',
'__pycache__', '.next', '.cache', 'coverage', '.idea', '.vscode',
]);
const TREE_MAX = 500;
function isInside(rootAbs, abs) {
return abs === rootAbs || abs.startsWith(rootAbs + path.sep);
}
// 会话内相对路径 → 绝对路径,双重越界校验(字面 + realpath,防符号链接跳出)。
function resolveInside(sessionId, rel) {
const sid = String(sessionId || '').trim();
if (!sid) throw Object.assign(new Error('缺少 session'), { status_code: 400 });
const session = engine.getSession(sid);
if (!session) throw Object.assign(new Error('会话不存在'), { status_code: 404 });
const rootAbs = path.resolve(engine.taskDirOf(sid));
const p = String(rel || '').replace(/^[\\/]+/, '');
const abs = p ? path.resolve(rootAbs, p) : rootAbs;
if (!isInside(rootAbs, abs)) throw Object.assign(new Error('路径越界'), { status_code: 400 });
let real = abs, rootReal = rootAbs;
try { real = fs.realpathSync(abs); } catch (_) {}
try { rootReal = fs.realpathSync(rootAbs); } catch (_) {}
if (!isInside(rootReal, real)) throw Object.assign(new Error('路径越界'), { status_code: 400 });
return { rootAbs: rootAbs, abs: abs };
}
// 懒加载单层目录。ignored 的目录只回标记、前端灰显且不展开(避免 node_modules 那种灾难)。
router.get('/tree', (req, res) => {
let abs;
try { abs = resolveInside(req.query.session, req.query.dir || '').abs; }
catch (err) { return sendErr(res, err); }
let st;
try { st = fs.statSync(abs); } catch (_) { return res.status(404).json({ error: '目录不存在' }); }
if (!st.isDirectory()) return res.status(400).json({ error: '不是目录' });
const showHidden = req.query.hidden === '1';
const rel = String(req.query.dir || '').replace(/^[\\/]+/, '').replace(/\/+$/, '');
const entries = [];
try {
for (const e of fs.readdirSync(abs, { withFileTypes: true })) {
if (!showHidden && e.name.startsWith('.')) continue;
const childRel = rel ? rel + '/' + e.name : e.name;
if (e.isSymbolicLink()) { entries.push({ name: e.name, rel: childRel, type: 'link' }); continue; }
if (e.isDirectory()) {
entries.push({ name: e.name, rel: childRel, type: 'dir', ignored: IGNORE_DIRS.has(e.name) });
} else if (e.isFile()) {
let size = null;
try { size = fs.statSync(path.join(abs, e.name)).size; } catch (_) {}
entries.push({ name: e.name, rel: childRel, type: 'file', size: size });
}
}
} catch (err) { return sendErr(res, err); }
entries.sort((a, b) =>
(a.ignored ? 1 : 0) - (b.ignored ? 1 : 0) ||
(a.type === 'dir' ? 0 : 1) - (b.type === 'dir' ? 0 : 1) ||
(a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
res.json({
root: path.resolve(engine.taskDirOf(String(req.query.session || ''))),
dir: rel,
total: entries.length,
capped: entries.length > TREE_MAX,
entries: entries.slice(0, TREE_MAX),
});
});
// execFile 异步(同步会阻塞事件循环);open/xdg-open 一般秒回,10s 兜底。
function runOpen(cmd, args) {
return new Promise((resolve, reject) => {
execFile(cmd, args, { timeout: 10000 }, (err) => {
if (!err) return resolve();
if (err.code === 'ENOENT') return reject(Object.assign(new Error('no-cmd'), { no_cmd: true }));
if (err.killed) return reject(Object.assign(new Error('系统调用超时'), { status_code: 504 }));
reject(Object.assign(new Error('打开失败:' + (err.message || err.code)), { status_code: 500 }));
});
});
}
function dirOf(abs) {
try { return fs.statSync(abs).isDirectory() ? abs : path.dirname(abs); } catch (_) { return path.dirname(abs); }
}
// 在系统文件管理器里打开:目录→直接打开;文件→定位所在目录(mac 用 open -R 直接选中该文件)。
router.post('/reveal', (req, res) => {
let target;
try { target = resolveInside(req.body && req.body.session, req.body && req.body.path); }
catch (err) { return sendErr(res, err); }
const abs = target.abs;
let isDir = false;
try { isDir = fs.statSync(abs).isDirectory(); } catch (_) {}
const mac = process.platform === 'darwin';
const cmd = mac ? 'open' : 'xdg-open';
const args = mac && !isDir ? ['-R', abs] : [isDir ? abs : path.dirname(abs)];
runOpen(cmd, args).then(() => res.json({ ok: true })).catch(err => sendErr(res, err));
});
// 在系统终端里打开该目录。mac 用 open -a Terminal;Linux 尽力而为。
router.post('/terminal', (req, res) => {
let target;
try { target = resolveInside(req.body && req.body.session, req.body && req.body.path); }
catch (err) { return sendErr(res, err); }
const dir = dirOf(target.abs);
if (process.platform === 'darwin') {
runOpen('open', ['-a', 'Terminal', dir]).then(() => res.json({ ok: true })).catch(err => sendErr(res, err));
return;
}
runOpen('x-terminal-emulator', ['--working-directory=' + dir])
.then(() => res.json({ ok: true }))
.catch(() => runOpen('gnome-terminal', ['--working-directory=' + dir])
.then(() => res.json({ ok: true }))
.catch(() => sendErr(res, Object.assign(new Error('没有可用的终端程序'), { status_code: 501 }))));
});
// 能力探测:前端凭这个决定是否显示「工作目录」入口(拿不到就整条隐藏)。
router.get('/info', (req, res) => {
res.json({ enabled: true, platform: process.platform, workspace_root: engine.getConfig().workspace_root });