优化welcome页文件上传相关逻辑

This commit is contained in:
2026-09-21 20:54:18 +08:00
parent 33d9f4b834
commit 011c3ac436
6 changed files with 99 additions and 69 deletions
+2
View File
@@ -92,10 +92,12 @@ agent:
# 大图上传预处理:图片超过 threshold_kb(默认 1.5M)时,浏览器端询问是否压缩; # 大图上传预处理:图片超过 threshold_kb(默认 1.5M)时,浏览器端询问是否压缩;
# 同意后在用户本地 canvas 压缩(长边 ≤ image_max_dim,JPEG image_quality)再上传。 # 同意后在用户本地 canvas 压缩(长边 ≤ image_max_dim,JPEG image_quality)再上传。
# confirm_size_mb:任意文件最终体积超过该值时再弹一次「继续上传」确认(multer 硬限 50M 不变)。
upload: upload:
image_compress_threshold_kb: 1536 image_compress_threshold_kb: 1536
image_max_dim: 2000 image_max_dim: 2000
image_quality: 0.85 image_quality: 0.85
confirm_size_mb: 10
# 模型保持占用(held)租约:AI 答完后不立即释放模型,用户追问可直接复用。 # 模型保持占用(held)租约:AI 答完后不立即释放模型,用户追问可直接复用。
# 页面无人观看超过 idle_release_ms 释放;有人观看最长保持 active_max_ms;sweep_ms 巡检间隔。 # 页面无人观看超过 idle_release_ms 释放;有人观看最长保持 active_max_ms;sweep_ms 巡检间隔。
+4 -2
View File
@@ -34,8 +34,10 @@ const DEFAULTS = {
// 改后重启生效。 // 改后重启生效。
agent: { temperature: 1.0, max_tool_iterations: 50, max_retries: 2, language: 'Simplified Chinese', auto_compress_tokens: 60000 }, agent: { temperature: 1.0, max_tool_iterations: 50, max_retries: 2, language: 'Simplified Chinese', auto_compress_tokens: 60000 },
// 大图上传预处理:图片文件超过 threshold_kb 时,浏览器端询问用户后用 canvas 压缩 // 大图上传预处理:图片文件超过 threshold_kb 时,浏览器端询问用户后用 canvas 压缩
// (长边 ≤ max_dim,JPEG quality)再上传,减轻服务器带宽与存储压力。参数经 /api/system/status 下发给前端。 // (长边 ≤ max_dim,JPEG quality)再上传,减轻服务器带宽与存储压力。
upload: { image_compress_threshold_kb: 1536, image_max_dim: 2000, image_quality: 0.85 }, // confirm_size_mb:任意文件最终体积超过该值(默认 10M)时再弹一次「继续上传」确认。
// 参数经 /api/system/status 下发给前端。
upload: { image_compress_threshold_kb: 1536, image_max_dim: 2000, image_quality: 0.85, confirm_size_mb: 10 },
// 技能(Skill Manager):skills_root 为技能根目录,所有任务/会话共享(容器内挂我 ./skills → /workspace/skills); // 技能(Skill Manager):skills_root 为技能根目录,所有任务/会话共享(容器内挂我 ./skills → /workspace/skills);
// 缺省取 workspace_root 的同级目录 skills(如 /workspace/tasks → /workspace/skills)。timeout_ms 为单个技能执行超时,默认 120000。 // 缺省取 workspace_root 的同级目录 skills(如 /workspace/tasks → /workspace/skills)。timeout_ms 为单个技能执行超时,默认 120000。
skills: { skills_root: '', timeout_ms: 120000 }, skills: { skills_root: '', timeout_ms: 120000 },
+6 -3
View File
@@ -342,14 +342,17 @@
</div> </div>
</div> </div>
<!-- 全局确认弹窗(替代原生 confirm;搬自 index) --> <!-- 全局确认弹窗(替代原生 confirm;搬自 index)。resolve: true=确定 / false=取消 / null=右上 X 或点遮罩关闭 -->
<div id="confirm-modal" class="modal-overlay hidden" onclick="if(event.target===this)confirmClose(false)"> <div id="confirm-modal" class="modal-overlay hidden" onclick="if(event.target===this)confirmClose(null)">
<div class="modal"> <div class="modal">
<button class="modal-close-btn" onclick="confirmClose(null)" aria-label="关闭">
<svg viewBox="0 0 24 24"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>
</button>
<h3 id="confirm-title">请确认</h3> <h3 id="confirm-title">请确认</h3>
<div class="modal-text" id="confirm-text"></div> <div class="modal-text" id="confirm-text"></div>
<label class="del-dir hidden" id="confirm-check-wrap"><input type="checkbox" id="confirm-check"> <span id="confirm-check-label"></span></label> <label class="del-dir hidden" id="confirm-check-wrap"><input type="checkbox" id="confirm-check"> <span id="confirm-check-label"></span></label>
<div class="btn-row"> <div class="btn-row">
<button class="ghost-btn" onclick="confirmClose(false)">取消</button> <button class="ghost-btn" id="confirm-cancel-btn" onclick="confirmClose(false)">取消</button>
<button class="primary-btn" id="confirm-ok-btn" onclick="confirmClose(true)">确定</button> <button class="primary-btn" id="confirm-ok-btn" onclick="confirmClose(true)">确定</button>
</div> </div>
</div> </div>
+80 -62
View File
@@ -52,42 +52,20 @@
$('files-mask').classList.toggle('show', open); $('files-mask').classList.toggle('show', open);
$('files-btn').classList.toggle('active', open); $('files-btn').classList.toggle('active', open);
} }
let ensuringSessionForFiles = false; // 防止建会话请求发出前重复点击按钮导致连建两个会话
async function toggleFilesPanel() { async function toggleFilesPanel() {
const panel = $('files-panel'); const panel = $('files-panel');
const open = !panel.classList.contains('open'); const open = !panel.classList.contains('open');
if (open && !state.sessionId) { if (open && !state.sessionId) {
// 新建会话页直接管理文件:自动建档会话再弹面板;建会话失败(如无可用模型)给出提示 // 新建会话页不再静默建档:没有会话就没有任务目录,无从查看文件,只轻提示一下
if (ensuringSessionForFiles) return; toast('尚未开始会话,暂无任务文件可查看');
ensuringSessionForFiles = true; return;
try {
await ensureSession();
} catch (e) {
toast('创建会话失败:' + e.message);
return;
} finally {
ensuringSessionForFiles = false;
}
} }
setFilesPanel(open); setFilesPanel(open);
} }
$('files-btn').addEventListener('click', toggleFilesPanel); $('files-btn').addEventListener('click', toggleFilesPanel);
// 附件(回形针)按钮:直接唤起文件选择写入当前会话任务目录;无会话时先建会话再弹选择器, // 附件(回形针)按钮:只弹文件选择器,不预建会话;选中文件后由 change 处理器
// 避免选完文件后因无会话被丢弃(与面板同策略)。 // 写入当前会话任务目录(无会话时先建档再传,见下方);取消选择则什么都不发生。
let ensuringSessionForUpload = false; $('attach-btn').addEventListener('click', () => {
$('attach-btn').addEventListener('click', async () => {
if (!state.sessionId) {
if (ensuringSessionForUpload) return;
ensuringSessionForUpload = true;
try {
await ensureSession();
} catch (e) {
toast('创建会话失败:' + e.message);
return;
} finally {
ensuringSessionForUpload = false;
}
}
$('file-input').click(); $('file-input').click();
}); });
$('files-mask').addEventListener('click', () => setFilesPanel(false)); // 点遮罩收起 $('files-mask').addEventListener('click', () => setFilesPanel(false)); // 点遮罩收起
@@ -690,7 +668,9 @@
if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); toggleSelectAll(); } if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); toggleSelectAll(); }
}); });
// ---------- 大图上传前压缩(同步 v1:阈值/参数由 /api/system/status 透出) ---------- // ---------- 大图上传前压缩(同步 v1:阈值/参数由 /api/system/status 透出) ----------
const DEFAULT_UPLOAD_CFG = { image_compress_threshold_kb: 1536, image_max_dim: 2000, image_quality: 0.85 }; const DEFAULT_UPLOAD_CFG = { image_compress_threshold_kb: 1536, image_max_dim: 2000, image_quality: 0.85, confirm_size_mb: 10 };
// 后端 multer 单文件硬限(routes/files.js limits.filesize),前端预检对齐它,超了直接拒掉不发起上传
const UPLOAD_HARD_LIMIT = 50 * 1024 * 1024;
let uploadCfgCache = null; let uploadCfgCache = null;
async function getUploadCfg() { async function getUploadCfg() {
if (!uploadCfgCache) { if (!uploadCfgCache) {
@@ -715,42 +695,67 @@
fr.readAsDataURL(file); fr.readAsDataURL(file);
}); });
} }
// 返回待上传的 File:需要时询问并压缩;取消/失败/无收益都按原文件上传 // 上传前逐文件预处理(串行,模态弹窗不能并行),返回待上传 File 或 null(用户放弃该文件):
async function maybeCompressImage(file) { // 1) 大图(>image_compress_threshold_kb):三选一——「压缩」本地压后传 / 「直接上传」原样传 /
// 右上 X、点遮罩关闭 = 放弃该文件(不上传,也就不触发建会话);
// 2) 最终体积 >50M(后端 multer 硬限):直接拒掉,不发起上传;
// 3) 预处理后仍 >confirm_size_mb(默认 10M,不限类型):二次确认「继续上传」,
// 取消/X/遮罩一律放弃。
// 压缩失败/无收益按原文件继续后续流程。
async function prepareUploadFile(file) {
const cfg = await getUploadCfg(); const cfg = await getUploadCfg();
const isImg = /^image\//.test(file.type || '') || /\.(png|jpe?g|gif|bmp|webp)$/i.test(file.name || ''); const isImg = /^image\//.test(file.type || '') || /\.(png|jpe?g|gif|bmp|webp)$/i.test(file.name || '');
const threshold = Number(cfg.image_compress_threshold_kb || 1536) * 1024; const threshold = Number(cfg.image_compress_threshold_kb || 1536) * 1024;
if (!isImg || file.size <= threshold) return file;
const maxDim = Number(cfg.image_max_dim || 2000); const maxDim = Number(cfg.image_max_dim || 2000);
const quality = Number(cfg.image_quality || 0.85); const quality = Number(cfg.image_quality || 0.85);
const ok = await confirmModal('图片文件过大', if (isImg && file.size > threshold) {
'「' + file.name + '」有 ' + fmtSize(file.size) + ',超过 ' + fmtSize(threshold) + // confirmModal resolve: true=压缩 / false=直接上传 / null=X或遮罩=放弃
'。建议在浏览器本地压缩为 JPEG(长边≤' + maxDim + 'px)后再上传。是否压缩?', '压缩后上传'); const ans = await confirmModal('图片文件过大',
if (!ok) return file; '「' + file.name + '」有 ' + fmtSize(file.size) + ',超过 ' + fmtSize(threshold) +
try { '。建议在浏览器本地压缩为 JPEG(长边≤' + maxDim + 'px)后再上传;也可原样直接上传。',
const img = await loadImageEl(file); '压缩', false, { cancelText: '直接上传' });
const iw = img.naturalWidth || img.width, ih = img.naturalHeight || img.height; if (ans === null) return null;
if (!iw || !ih) throw new Error('无法读取图片尺寸'); if (ans) {
const scale = Math.min(1, maxDim / Math.max(iw, ih)); try {
const w = Math.max(1, Math.round(iw * scale)), h = Math.max(1, Math.round(ih * scale)); const img = await loadImageEl(file);
const canvas = document.createElement('canvas'); const iw = img.naturalWidth || img.width, ih = img.naturalHeight || img.height;
canvas.width = w; canvas.height = h; if (!iw || !ih) throw new Error('无法读取图片尺寸');
const ctx = canvas.getContext('2d'); const scale = Math.min(1, maxDim / Math.max(iw, ih));
// 透明底(PNG)转 JPEG 前先铺白,避免变黑 const w = Math.max(1, Math.round(iw * scale)), h = Math.max(1, Math.round(ih * scale));
ctx.fillStyle = '#fff'; ctx.fillRect(0, 0, w, h); const canvas = document.createElement('canvas');
ctx.drawImage(img, 0, 0, w, h); canvas.width = w; canvas.height = h;
const blob = await new Promise(function (res) { canvas.toBlob(function (b) { res(b); }, 'image/jpeg', quality); }); const ctx = canvas.getContext('2d');
if (!blob || blob.size >= file.size) { // 透明底(PNG)转 JPEG 前先铺白,避免变黑
toast('压缩无收益,已按原文件上传'); ctx.fillStyle = '#fff'; ctx.fillRect(0, 0, w, h);
return file; ctx.drawImage(img, 0, 0, w, h);
const blob = await new Promise(function (res) { canvas.toBlob(function (b) { res(b); }, 'image/jpeg', quality); });
if (!blob || blob.size >= file.size) {
toast('压缩无收益,按原文件上传');
} else {
const newName = String(file.name || 'image').replace(/\.[^.]+$/, '') + '.jpg';
toast('已压缩 ' + fmtSize(file.size) + ' → ' + fmtSize(blob.size));
file = new File([blob], newName, { type: 'image/jpeg' });
}
} catch (e) {
toast('压缩失败(' + (e && e.message || e) + '),按原文件上传');
}
} }
const newName = String(file.name || 'image').replace(/\.[^.]+$/, '') + '.jpg';
toast('已压缩 ' + fmtSize(file.size) + ' → ' + fmtSize(blob.size));
return new File([blob], newName, { type: 'image/jpeg' });
} catch (e) {
toast('压缩失败(' + (e && e.message || e) + '),按原文件上传');
return file;
} }
// 后端 multer 单文件硬限 50M:压缩后仍超限、或选了「直接上传」的超限大图、非图片超限文件,
// 都在这里拒掉(返回 null,与其他「放弃」同一条路径),免得传完一个 500 才知道原因
if (file.size > UPLOAD_HARD_LIMIT) {
toast('「' + file.name + '」有 ' + fmtSize(file.size) + ',超过 50M 上限,无法上传' + (isImg ? ',可尝试选「压缩」后上传' : ''));
return null;
}
// 最终体积仍超大盘阈值的文件(含非图片、含压缩后仍超限):用户确认后才传
const bigLimit = Number(cfg.confirm_size_mb || 10) * 1024 * 1024;
if (file.size > bigLimit) {
const go = await confirmModal('文件过大',
'「' + file.name + '」有 ' + fmtSize(file.size) + ',超过 ' + fmtSize(bigLimit) + '。确认继续上传?',
'继续上传');
if (go !== true) return null; // 取消/X/遮罩:不传该文件
}
return file;
} }
// ---------- 上传文件卡片(嵌在输入框内部顶端,随卡片数撑高输入框;新卡插最前,图标 + 文件名/类型大小,逐卡上传进度遮罩;过多横向滚动) ---------- // ---------- 上传文件卡片(嵌在输入框内部顶端,随卡片数撑高输入框;新卡插最前,图标 + 文件名/类型大小,逐卡上传进度遮罩;过多横向滚动) ----------
@@ -816,16 +821,29 @@
row.classList.add('hidden'); row.classList.add('hidden');
} }
// 面板内上传:直接写入当前会话任务目录(>阈值的图片逐个询问压缩;多文件并行上传+总进度条+逐卡进度) // 文件选择统一入口:先逐文件预处理(大图压缩询问/大文件确认,X或遮罩=放弃该文件),
// 只要还剩至少一个待传文件才自动建档(welcome 无会话时)并走即传路径(多文件并行上传+总进度条+逐卡进度);
// 全部放弃或取消选择都不上传、不新建会话。
$('file-input').addEventListener('change', async e => { $('file-input').addEventListener('change', async e => {
const input = e.target; const input = e.target;
const files = Array.prototype.slice.call(input.files || []); // 先快照再清空,FileList 是实时的 const files = Array.prototype.slice.call(input.files || []); // 先快照再清空,FileList 是实时的
input.value = ''; input.value = '';
if (!files.length) return; if (!files.length) return;
if (!state.sessionId) { toast('先发送一条消息创建会话'); return; } // 逐个串行预处理(模态弹窗不能并行)
// 大图逐个串行询问压缩(模态弹窗不能并行)
const ready = []; const ready = [];
for (const f of files) ready.push(await maybeCompressImage(f)); for (const f of files) {
const r = await prepareUploadFile(f);
if (r) ready.push(r);
}
if (!ready.length) return; // 用户全放弃了:不上传也不建档
if (!state.sessionId) {
try {
await ensureSession();
} catch (er) {
toast('创建会话失败:' + er.message);
return;
}
}
// 每张卡对应一个文件的上传进度(输入区上方;面板内总进度条保留不变) // 每张卡对应一个文件的上传进度(输入区上方;面板内总进度条保留不变)
const cards = ready.map(f => addUploadCard(f)); const cards = ready.map(f => addUploadCard(f));
// ---- 并行上传 + 实时进度 ---- // ---- 并行上传 + 实时进度 ----
+6 -1
View File
@@ -66,9 +66,12 @@
} }
// confirmModal(title, text, okText, danger, opts?) // confirmModal(title, text, okText, danger, opts?)
// opts.checkbox = {label, default=true} 可选:展示一个默认勾选状态可改的复选框 // opts.checkbox = {label, default=true} 可选:展示一个默认勾选状态可改的复选框
// opts.cancelText 可选:改左键文案(如「直接上传」),缺省「取消」
// resolve: true=确定 / false=取消 / null=右上 X 或点遮罩关闭(对只认布尔的旧调用方等同取消)
// 确认/取消后在 state._confirmChecked 读出勾选状态(不破坏现有调用方签名) // 确认/取消后在 state._confirmChecked 读出勾选状态(不破坏现有调用方签名)
function confirmModal(title, text, okText, danger, opts) { function confirmModal(title, text, okText, danger, opts) {
state._confirmChecked = !!(opts && opts.checkbox); // 未传 opts 时 reset 为 false state._confirmChecked = !!(opts && opts.checkbox); // 未传 opts 时 reset 为 false
$('confirm-cancel-btn').textContent = (opts && opts.cancelText) || '取消';
const wrap = $('confirm-check-wrap'); const wrap = $('confirm-check-wrap');
if (opts && opts.checkbox) { if (opts && opts.checkbox) {
$('confirm-check-label').textContent = opts.checkbox.label; $('confirm-check-label').textContent = opts.checkbox.label;
@@ -92,6 +95,7 @@
$('confirm-modal').classList.remove('hidden'); $('confirm-modal').classList.remove('hidden');
}); });
} }
// 调用方语义见 confirmModal:true=确定 / false=取消 / null=X、遮罩
function confirmClose(v) { _dlgSettle(v); } function confirmClose(v) { _dlgSettle(v); }
function promptModal(title, placeholder, initial, opts) { function promptModal(title, placeholder, initial, opts) {
return new Promise(resolve => { return new Promise(resolve => {
@@ -377,10 +381,11 @@
{ group: '技能', items: [ { group: '技能', items: [
{ path: 'skills.timeout_ms', label: '技能执行超时(ms)', type: 'int' }, { path: 'skills.timeout_ms', label: '技能执行超时(ms)', type: 'int' },
] }, ] },
{ group: '图片上传压缩(浏览器端)', items: [ { group: '上传预处理(浏览器端)', items: [
{ path: 'upload.image_compress_threshold_kb', label: '大图阈值(KB)', type: 'int' }, { path: 'upload.image_compress_threshold_kb', label: '大图阈值(KB)', type: 'int' },
{ path: 'upload.image_max_dim', label: '压缩后长边上限(px)', type: 'int' }, { path: 'upload.image_max_dim', label: '压缩后长边上限(px)', type: 'int' },
{ path: 'upload.image_quality', label: 'JPEG 质量(0~1)', type: 'float' }, { path: 'upload.image_quality', label: 'JPEG 质量(0~1)', type: 'float' },
{ path: 'upload.confirm_size_mb', label: '大文件确认阈值(MB)', type: 'int' },
] }, ] },
{ group: '模型租约(会话结束后的保持)', items: [ { group: '模型租约(会话结束后的保持)', items: [
{ path: 'model_hold.idle_release_ms', label: '无人观看释放(ms)', type: 'int' }, { path: 'model_hold.idle_release_ms', label: '无人观看释放(ms)', type: 'int' },
+1 -1
View File
@@ -47,7 +47,7 @@ router.get('/status', wrap((req, res) => {
port: cfg.port, port: cfg.port,
auth_enabled: !!(cfg.auth && cfg.auth.users && cfg.auth.users.length), auth_enabled: !!(cfg.auth && cfg.auth.users && cfg.auth.users.length),
running_sessions: engine.activeRuns(), running_sessions: engine.activeRuns(),
// 前端上传前的大图压缩参数(阈值/尺寸/质量),避免前端写死 // 前端上传预处理参数(大图压缩阈值/尺寸/质量、大文件确认阈值),避免前端写死
upload: cfg.upload || {}, upload: cfg.upload || {},
}); });
})); }));