From 192db98c37dac6e8cb003eb3f1f400a7902096f6 Mon Sep 17 00:00:00 2001 From: kicer Date: Wed, 2 Sep 2026 07:10:11 +0800 Subject: [PATCH] =?UTF-8?q?=E8=AE=BE=E7=BD=AE=E9=A1=B5=E6=94=B9=E5=AF=86?= =?UTF-8?q?=E7=A0=81(prompt=E5=BC=B9=E7=AA=97,=E5=85=8D=E5=8E=9F=E5=AF=86?= =?UTF-8?q?=E7=A0=81,=E7=AB=8B=E5=8D=B3=E7=94=9F=E6=95=88);=E4=B8=8A?= =?UTF-8?q?=E4=BC=A0=E9=99=84=E4=BB=B6=E6=94=B9=E4=B8=BA=E9=9A=8F=E4=B8=8B?= =?UTF-8?q?=E4=B8=80=E6=9D=A1=E6=B6=88=E6=81=AF=E7=BB=9F=E4=B8=80=E5=91=8A?= =?UTF-8?q?=E7=9F=A5AI?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/server/auth.js | 35 ++++++++ app/server/public/css/style.css | 17 ++++ app/server/public/index.html | 14 +-- app/server/public/js/core.js | 5 +- app/server/public/js/settings.js | 30 ++++++- app/server/public/js/tasks.js | 117 ++++++++++++++++++++++--- app/server/routes/files.js | 12 +-- app/server/routes/messages.js | 25 +++++- app/server/templates/system-prompt.txt | 5 ++ app/test/smoke.js | 9 ++ 10 files changed, 235 insertions(+), 34 deletions(-) diff --git a/app/server/auth.js b/app/server/auth.js index 02966b6..9869a2d 100644 --- a/app/server/auth.js +++ b/app/server/auth.js @@ -4,6 +4,7 @@ const express = require('express'); const crypto = require('crypto'); const path = require('path'); +const { readConfigText, applyEditsToText, loadConfigFromText, writeConfigText } = require('./config'); const COOKIE_NAME = 'agent_token'; const DEFAULT_TTL_MS = 30 * 24 * 3600 * 1000; // 30 天 @@ -130,6 +131,40 @@ function createAuth(cfg) { res.json({ ok: true }); }); + // ----- 修改密码(设置页) ----- + // 已登录即可改自己的密码(免输原密码) → 写回 config.yml(保留注释,校验失败不动文件) + // → 同步更新内存(users/validUsers),立即生效无需重启。 + // 已签发的 token 不失效(HMAC 无状态);其他设备下次登录才需新密码。 + // 注:本路由挂在认证中间件之前,需手动验登录态。 + router.post('/api/password', (req, res) => { + try { + const me = sessionUser(req); + if (!me) return res.status(401).json({ error: '未登录' }); + const newP = String((req.body && req.body.new_password == null ? '' : req.body.new_password)); + if (newP.length < 6) return res.status(400).json({ error: '新密码至少 6 位' }); + const idx = users.findIndex(u => String(u.user) === me); + if (idx < 0) return res.status(404).json({ error: '当前用户已不在配置中' }); + if (newP === users[idx].password) return res.status(400).json({ error: '新密码与当前密码相同' }); + const text = readConfigText(cfg); + if (text === null) return res.status(409).json({ error: '配置文件不存在,无法持久化新密码' }); + let nextText; + try { + nextText = applyEditsToText(text, [{ path: ['auth', 'users', String(idx), 'password'], value: newP }]); + loadConfigFromText(nextText, cfg.config_path); + } catch (e) { + return res.status(400).json({ error: '写入配置失败:' + String(e && e.message || e) }); + } + writeConfigText(cfg, nextText); + // 内存同步:users 与 engine.cfg 是同一对象,Basic 认证实时生效;cookie 登录查 validUsers + users[idx].password = newP; + validUsers.set(me, newP); + console.log('[auth] 用户 ' + me + ' 修改了密码'); + res.json({ ok: true }); + } catch (e) { + res.status(500).json({ error: String(e && e.message || e) }); + } + }); + router.get('/api/me', (req, res) => { res.json({ user: sessionUser(req) }); }); diff --git a/app/server/public/css/style.css b/app/server/public/css/style.css index 20ed93a..4a64e5a 100644 --- a/app/server/public/css/style.css +++ b/app/server/public/css/style.css @@ -206,6 +206,23 @@ body { .file-act.del { color: #c33; } .empty-tip { color: #99a; text-align: center; padding: 18px; font-size: 13px; } +/* ---- 待发送附件(随下一条消息统一告知 AI) ---- */ +.attach-row { display: flex; flex-wrap: wrap; gap: 6px; padding: 0 12px 6px; } +.attach-chip { + display: flex; align-items: center; gap: 6px; max-width: 100%; + background: #fff; border: 1px solid #d5deee; border-radius: 14px; + padding: 4px 10px; font-size: 12px; color: #334; +} +.attach-chip .nm { max-width: 140px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.attach-chip .st { color: #2a5299; flex: none; } +.attach-chip.err { border-color: #eac2bd; color: #c0392b; } +.attach-chip.err .st { color: #c0392b; } +.attach-chip .x { color: #99a; background: none; border: none; font-size: 14px; line-height: 1; padding: 0 2px; cursor: pointer; } +.file-upload-btn.uploading svg { display: none; } +.up-pct { font-size: 11px; font-weight: 600; color: #2a5299; } +/* 消息气泡内的附件行 */ +.msg-files { font-size: 12px; opacity: 0.85; margin-bottom: 4px; word-break: break-all; } + /* ---- 输入区 ---- */ .input-area { display: flex; align-items: flex-end; gap: 8px; diff --git a/app/server/public/index.html b/app/server/public/index.html index 02b2fda..68ad38b 100644 --- a/app/server/public/index.html +++ b/app/server/public/index.html @@ -180,10 +180,12 @@
+
-
'; +} + +async function changePassword() { + const btn = $('pwd-btn'); + if (btn) btn.disabled = true; + try { + const newP = await promptModal('修改密码', '新密码,至少 6 位', '', { type: 'password' }); + if (newP == null) return; + if (newP.length < 6) { toast('新密码至少 6 位'); return; } + await req('POST', '/api/password', { new_password: newP }); + toast('密码已修改,立即生效'); + } catch (e) { + toast('修改失败:' + e.message); + } finally { + if (btn) btn.disabled = false; + } +} + function svcCard(st) { let html = '

服务状态' + (pendingKeys.size ? ' 待重启生效' : '') + '

'; @@ -103,12 +127,13 @@ async function loadSettings() { if (!el) return; el.innerHTML = '
加载中…
'; try { - const [st, cg] = await Promise.all([ + const [st, cg, me] = await Promise.all([ req('GET', '/api/system/status'), req('GET', '/api/config'), + req('GET', '/api/me').catch(function () { return { user: null }; }), // 未启用认证时无此路由 ]); effCfg = cg.effective || {}; - el.innerHTML = svcCard(st) + formCard(); + el.innerHTML = (st.auth_enabled && me && me.user ? accountCard(me.user) : '') + svcCard(st) + formCard(); } catch (e) { el.innerHTML = '
加载失败:' + esc(e.message) + '
'; } @@ -238,6 +263,7 @@ async function closeCfgEditor() { window.cfgUI = { saveForm: saveForm, + changePassword: changePassword, restart: restart, open: openCfgEditor, save: saveCfgEditor, diff --git a/app/server/public/js/tasks.js b/app/server/public/js/tasks.js index 618b8ae..6ea2755 100644 --- a/app/server/public/js/tasks.js +++ b/app/server/public/js/tasks.js @@ -152,6 +152,91 @@ async function doSearch() { } catch (e) { toast('搜索失败:' + e.message); } } +// ---------- 待发送附件 ---------- +// 选定文件后立即传到任务目录,但**不通知 AI**;下一条用户消息发送时, +// 由服务端在正文前拼【系统通知】一并送达(见 routes/messages.js)。 +let pendingFiles = []; // { name, size, pct, status: 'up'|'ok'|'err', xhr? } + +function renderAttach() { + const row = $('attach-row'); + if (!row) return; + row.classList.toggle('hidden', !pendingFiles.length); + row.innerHTML = pendingFiles.map(function (f, i) { + const st = f.status === 'up' ? (f.pct + '%') : f.status === 'ok' ? '✓' : '失败'; + return '' + + '' + esc(f.name) + '' + st + '' + + ''; + }).join(''); + // 输入框里的回形针图标在上传中换成总进度百分比 + const lb = document.getElementById('attach-btn'); + const pctEl = $('up-pct'); + if (lb && pctEl) { + const ups = pendingFiles.filter(function (f) { return f.status === 'up'; }); + lb.classList.toggle('uploading', ups.length > 0); + if (ups.length) { + let done = 0, tot = 0; + for (const f of pendingFiles) { if (f.status === 'err') continue; done += f.size * f.pct / 100; tot += f.size; } + pctEl.textContent = (tot ? Math.round(done / tot * 100) : 0) + '%'; + } + } +} + +function startUpload(file) { + if (!state.sessionId) return; + const item = { name: file.name, size: file.size, pct: 0, status: 'up' }; + pendingFiles.push(item); + renderAttach(); + const fd = new FormData(); + fd.append('files', file); + const xhr = new XMLHttpRequest(); + item.xhr = xhr; + xhr.open('POST', '/api/sessions/' + state.sessionId + '/files'); + xhr.upload.onprogress = function (e) { + if (e.lengthComputable) { item.pct = Math.min(99, Math.round(e.loaded / e.total * 100)); renderAttach(); } + }; + xhr.onload = function () { + let r = {}; + try { r = JSON.parse(xhr.responseText); } catch (_) {} + if (xhr.status === 200 && r.uploaded && r.uploaded[0]) { + item.name = r.uploaded[0].filename; // 以服务端清洗/重命名后的文件名为准 + item.size = r.uploaded[0].size; + item.pct = 100; + item.status = 'ok'; + } else { + item.status = 'err'; + toast('上传失败:' + (r.error || xhr.status)); + } + item.xhr = null; + renderAttach(); + }; + xhr.onerror = function () { item.status = 'err'; item.xhr = null; renderAttach(); toast('上传失败:网络错误'); }; + xhr.send(fd); +} + +function removeAttach(i) { + const f = pendingFiles[i]; + if (!f) return; + if (f.xhr) { try { f.xhr.abort(); } catch (_) {} } + else if (f.status === 'ok' && state.sessionId) { + // 已传完成的附件被移除:连带删掉已落盘的文件,避免任务目录里残留孤儿文件 + req('DELETE', '/api/sessions/' + state.sessionId + '/files?path=' + encodeURIComponent(f.name)).catch(function () {}); + } + pendingFiles.splice(i, 1); + renderAttach(); +} + +// 历史消息里的【系统通知】行:展示层拆成附件胶囊行 + 用户原文 +function parseUploadNotice(content) { + const m = /^【系统通知】用户上传了文件:([^\n]*)(?:\n([\s\S]*))?$/.exec(content || ''); + if (!m) return { text: content || '', files: null }; + const files = m[1].split('、').map(function (s) { return s.replace(/(大小[^)]*)$/, '').trim(); }).filter(Boolean); + return { text: m[2] || '', files: files }; +} + +function attachBubbleLine(names) { + return names && names.length ? '
📎 ' + names.map(esc).join(' ') + '
' : ''; +} + // ---------- 消息渲染 ---------- function md(text) { if (typeof marked === 'undefined') return esc(text); @@ -189,9 +274,11 @@ function msgNode(m, cardMap) { } const wrap = document.createElement('div'); if (m.role === 'user') { + const p = parseUploadNotice(m.content); wrap.className = 'msg me'; wrap.innerHTML = '
我
' + - '
' + esc(m.content) + '
' + + '
' + attachBubbleLine(p.files) + esc(p.text) + '
'; + } else if (m.role === 'assistant' && (m.content || !m.tool_calls)) { '
' + fmtTime(m.created_at) + '
'; return wrap; } @@ -457,6 +544,9 @@ const ui = { }, async openSession(id) { state.sessionId = id; + // 待发送附件属于上一个会话的语境,切会话时清空展示(文件已落盘,可在文件面板查看) + pendingFiles = []; + renderAttach(); showChat(); try { const detail = await req('GET', '/api/sessions/' + id); @@ -474,19 +564,27 @@ const ui = { async send() { const ta = $('msg-input'); const content = ta.value.trim(); - if (!content || !state.sessionId) return; + if (!state.sessionId) return; + if (pendingFiles.some(f => f.status === 'up')) { toast('附件上传中,请稍候'); return; } + const atts = pendingFiles.filter(f => f.status === 'ok').map(f => ({ name: f.name, size: f.size })); + if (!content && !atts.length) return; ta.value = ''; ta.style.height = 'auto'; const box = $('messages'); const tip = box.querySelector('.empty-tip'); if (tip) tip.remove(); try { - const r = await req('POST', '/api/sessions/' + state.sessionId + '/messages', { content }); + const body = { content }; + if (atts.length) body.attachments = atts; + const r = await req('POST', '/api/sessions/' + state.sessionId + '/messages', body); const wrap = document.createElement('div'); wrap.className = 'msg me'; wrap.innerHTML = '
我' + (r.delivered === 'queued' ? '(排队中,暂存)' : '') + '
' + - '
' + esc(content) + '
'; + '
' + attachBubbleLine(atts.map(a => a.name)) + esc(content) + '
'; box.appendChild(wrap); + // 发送成功后附件已随消息告知 AI;失败的保留,由用户决定重试或移除 + pendingFiles = pendingFiles.filter(f => f.status === 'err'); + renderAttach(); // 立即给出回馈:占位气泡 + 等待计时,首个增量/回复到达时移除并填充内容 if (r.delivered !== 'queued') addPendingBubble(); scrollBottom(); @@ -515,16 +613,11 @@ const ui = { async uploadFiles(ev) { const input = ev.target; const files = input.files; - if (!files || !files.length || !state.sessionId) return; - const fd = new FormData(); - for (const f of files) fd.append('files', f); input.value = ''; - try { - const r = await req('POST', '/api/sessions/' + state.sessionId + '/files', fd, true); - toast('已上传 ' + r.uploaded.length + ' 个文件'); - loadFiles(); - } catch (e) { toast('上传失败:' + e.message); } + if (!files || !files.length || !state.sessionId) return; + for (const f of files) startUpload(f); // 多个文件并行上传,进度在回形针图标上汇总 }, + removeAttach(i) { removeAttach(i); }, async deleteFile(name) { if (!await confirmModal('删除文件', '删除文件 ' + name + ' ?', '删除', true)) return; try { diff --git a/app/server/routes/files.js b/app/server/routes/files.js index d759663..e5b8dcf 100644 --- a/app/server/routes/files.js +++ b/app/server/routes/files.js @@ -63,17 +63,7 @@ router.post('/:id/files', upload.array('files', 10), function (req, res) { db.prepare('INSERT INTO files (session_id, filename, size, created_at) VALUES (?,?,?,?)') .run(req.params.id, f.filename, f.size, Date.now()); } - // 主动告知 AI:文件名、大小以单行随上传送达会话(live/held/queued 都能送达)。 - // 附任务目录绝对路径、明确无需列目录验证与确认回复,减少 AI 多余探索;通知失败不影响上传本身。 - if (uploaded.length) { - try { - const dir = engine.taskDirOf(req.params.id); - const list = uploaded.map(f => f.filename + '(' + f.size + ' 字节)').join(';'); - engine.postUserMessage(req.params.id, - '【系统通知】用户刚通过页面上传了 ' + uploaded.length + ' 个文件,已存在于任务目录 ' + dir + ' 中:' + list + - '。文件已确认存在,无需再列目录或读取验证;无需为确认收到而回复,除非用户另有诉求。'); - } catch (e) { console.warn('[files] 上传通知 AI 失败:', e && e.message || e); } - } + // 不再自动通知 AI:附件随用户下一条消息统一告知(见 routes/messages.js 的 attachments) res.json({ uploaded }); } catch (err) { res.status(500).json({ error: String(err && err.message || err) }); diff --git a/app/server/routes/messages.js b/app/server/routes/messages.js index f51ff06..670e270 100644 --- a/app/server/routes/messages.js +++ b/app/server/routes/messages.js @@ -14,8 +14,31 @@ function wrap(fn) { }; } +// 附件提示词:用户带附件发消息时,服务端在正文前拼一行系统通知, +// 与消息一并落库(历史重建时 AI 能看到)。格式: +// 【系统通知】用户上传了文件:a.png(大小 1.2 MB)、b.txt(大小 3 KB) +// <用户原文> +function fmtSize(n) { + n = Number(n) || 0; + if (n < 1024) return n + ' B'; + if (n < 1024 * 1024) return (n / 1024).toFixed(1) + ' KB'; + if (n < 1024 * 1024 * 1024) return (n / 1024 / 1024).toFixed(1) + ' MB'; + return (n / 1024 / 1024 / 1024).toFixed(2) + ' GB'; +} +function composeWithAttachments(content, attachments) { + if (!Array.isArray(attachments) || !attachments.length) return content; + const list = attachments.slice(0, 20).map(a => + String(a && a.name || 'file').slice(0, 200) + '(大小 ' + fmtSize(a && a.size) + ')' + ).join('、'); + const notice = '【系统通知】用户上传了文件:' + list; + return content ? notice + '\n' + content : notice; +} + router.post('/:id/messages', wrap((req, res) => { - const content = String((req.body && req.body.content) || '').trim(); + const content = composeWithAttachments( + String((req.body && req.body.content) || '').trim(), + req.body && req.body.attachments + ); if (!content) return res.status(400).json({ error: 'content 不能为空' }); const r = engine.postUserMessage(req.params.id, content); res.json(r); diff --git a/app/server/templates/system-prompt.txt b/app/server/templates/system-prompt.txt index b8bbd89..fb6d7bf 100644 --- a/app/server/templates/system-prompt.txt +++ b/app/server/templates/system-prompt.txt @@ -38,6 +38,11 @@ Skipping this step may lead to duplicated work and inefficient solutions. - Work inside the working directory. Use clear file names. - Uploaded files appear in the working directory; check with `list_directory` if needed. +## User Uploads + +- User-uploaded files are announced by a 「【系统通知】用户上传了文件:…」 line at the start of a user message, followed by the user's own text. +- Understand the user's intent before touching uploaded files: an upload may only be stored or referenced for later. Do not open, analyze, or convert uploaded files unless the request clearly requires it — do not process files just for the sake of processing them. + ## External Services - Use `fetch` or `web_search` when the task requires web data. diff --git a/app/test/smoke.js b/app/test/smoke.js index 9676260..df2556b 100644 --- a/app/test/smoke.js +++ b/app/test/smoke.js @@ -245,6 +245,15 @@ async function main() { ok(qc.some(x => x.id === fs9.id), 'q= 按消息内容命中'); const qnone = await api('GET', '/api/sessions?q=绝无此内容xyzzy-9x7'); ok(Array.isArray(qnone) && qnone.length === 0, 'q= 无命中返回空'); + // 附件消息:服务端在正文前拼【系统通知】行,与消息一并落库 + await api('POST', '/api/sessions/' + fs9.id + '/messages', { content: '', attachments: [{ name: 'a.png', size: 1536 }, { name: 'b.txt', size: 20 }] }); + const noticePrefix = '【系统通知】用户上传了文件:a.png(大小 1.5 KB)、b.txt(大小 20 B)'; + let attOk = false; + try { + await waitSession(fs9.id, x => x.messages.some(m => m.role === 'user' && m.content.indexOf(noticePrefix) === 0), 6000, '附件通知落库'); + attOk = true; + } catch (_) {} + ok(attOk, '附件提示词按格式拼接(文件名+大小)'); // token 用量:model_usage 由 mock 上游的 usage 帧驱动,输入/输出分开统计 const usagePool = await api('GET', '/api/models'); const sumP = usagePool.reduce(function (n, m) { return n + (m.today_prompt || 0); }, 0);