diff --git a/app/server/public/index.html b/app/server/public/index.html index 9dc2c26..8d4889b 100644 --- a/app/server/public/index.html +++ b/app/server/public/index.html @@ -56,16 +56,29 @@ .stop-link.icon-only.icon-primary:hover { color: #2854d6; } /* 推到 phase-bar 最右侧(独立动作,与左侧状态/选择模型区分) */ .phase-bar .phase-bar-right { margin-left: auto; } - /* 定时任务状态条:整条可点,弹详情窗(看/改提示词、删除;创建走 AI 的 schedule_task 工具),淡黄底区别于状态栏 */ + /* 定时任务状态条:整条可点,弹详情窗(改频次/提示词、删除;创建走 AI 的 schedule_task 工具),淡黄底区别于状态栏。 + 高度与 phase-bar 对齐:同 6px 上下内边距,sched-text 用与 stop-link 同构的 12px 字 + 4px 上下 padding(天然同 line-box),eye 同 icon-only 钮 */ .schedule-bar { flex: none; display: flex; align-items: center; gap: 8px; - padding: 5px 12px; font-size: 12px; color: #8a6400; cursor: pointer; + padding: 6px 12px; font-size: 12px; color: #8a6400; cursor: pointer; background: #fffdf2; border-bottom: 1px solid #f0e6c8; } .schedule-bar:active { opacity: 0.75; } - .schedule-bar .sched-text { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } - .schedule-bar .sched-eye { margin-left: auto; flex: none; display: inline-flex; align-items: center; } - .schedule-bar .sched-eye svg { width: 15px; height: 15px; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; } + .schedule-bar .sched-text { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; padding: 4px 0; } + /* eye 图标与 phase-bar 右侧 icon-only 钮垂直对齐:同 6px 上下内边距、同 0 8px 水平、同 18px 图标 */ + .schedule-bar .sched-eye { margin-left: auto; flex: none; padding: 0 8px; line-height: 0; } + .schedule-bar .sched-eye .ic { width: 18px; height: 18px; vertical-align: middle; } + /* schedule 弹窗控件(.modal select/input 的 100% 宽会撑满整行,这里收窄成本行内样式) */ + #schedule-modal .sched-row { display: flex; align-items: center; gap: 6px; margin-bottom: 10px; font-size: 14px; color: var(--ink); flex-wrap: wrap; } + #schedule-modal .sched-row select, + #schedule-modal .sched-row input { + width: auto; margin: 0; padding: 7px 8px; font-size: 14px; + border: 1px solid #dde1ea; border-radius: 8px; background: #fff; color: var(--ink); + } + #schedule-modal .sched-row select { appearance: none; -webkit-appearance: none; } + #schedule-modal .sched-row .sched-num { width: 52px; text-align: center; } + #schedule-modal .sched-row .sched-grow { flex: 1; min-width: 130px; font-family: monospace; } + #schedule-modal .sched-meta { font-size: 12.5px; color: var(--gray); margin-bottom: 10px; white-space: pre-wrap; } /* schedule 弹窗内的提示词编辑区(.modal input 不覆盖 textarea,单独给样式) */ #schedule-modal textarea { width: 100%; box-sizing: border-box; display: block; @@ -307,7 +320,7 @@ -
@@ -1398,7 +1428,7 @@ } } - // ---------- 定时任务状态条(整条可点→详情弹窗;创建只走 AI 工具,频次暂不可改,提示词可在弹窗内更新) ---------- + // ---------- 定时任务状态条(整条可点→详情弹窗;创建只走 AI 工具,频次/提示词可在弹窗内改) ---------- const CRON_DOW = ['日', '一', '二', '三', '四', '五', '六']; // cron 人类可读化:只覆盖常见形态(每天/每周几几点、每 N 小时),其余原样显示表达式 function cronText(expr) { @@ -1427,37 +1457,88 @@ else if (sc.last_status === 'error') last = '上次 error' + (sc.last_note ? ': ' + sc.last_note : ''); else if (sc.last_status === 'skipped') last = '上次 跳过' + (sc.last_note ? ':' + sc.last_note : ''); else last = '下次 ' + fmtTime(sc.next_run_at); - bar.innerHTML = '⏰ ' + esc(cronText(sc.cron_expr)) + ' · ' + esc(last) + '' - + ''; + bar.innerHTML = '' + esc(cronText(sc.cron_expr)) + ' · ' + esc(last) + '' + + ''; bar.classList.remove('hidden'); } + // 频次控件显隐:每天=[时分] 每周=[天][时分] 每隔=[N][小时] 自定义=[cron 文本框] + function schedFreqUi() { + const f = $('sched-freq').value; + const hm = f === 'daily' || f === 'weekly'; + $('sched-dow').classList.toggle('hidden', f !== 'weekly'); + $('sched-hh').classList.toggle('hidden', !hm); + $('sched-colon').classList.toggle('hidden', !hm); + $('sched-mm').classList.toggle('hidden', !hm); + $('sched-nh').classList.toggle('hidden', f !== 'everyN'); + $('sched-nh-unit').classList.toggle('hidden', f !== 'everyN'); + $('sched-cron').classList.toggle('hidden', f !== 'custom'); + } + // 既有 cron → 控件:只认每天/每周几/每 N 小时三形态(与 cronText 覆盖一致),其余落入自定义 + function schedFillFromCron(expr) { + const f = $('sched-freq'); + const p = String(expr || '').trim().split(/\s+/); + f.value = 'custom'; + if (p.length === 5 && p[2] === '*' && p[3] === '*' && /^\d+$/.test(p[0]) && /^\d+$/.test(p[1])) { + if (p[4] === '*') f.value = 'daily'; + else if (/^[0-6]$/.test(p[4])) { f.value = 'weekly'; $('sched-dow').value = p[4]; } + if (f.value !== 'custom') { $('sched-hh').value = +p[1]; $('sched-mm').value = +p[0]; } + } else if (p.length === 5 && p[0] === '0' && /^\*\/\d+$/.test(p[1]) && p[2] === '*' && p[3] === '*' && p[4] === '*') { + f.value = 'everyN'; + $('sched-nh').value = p[1].slice(2); + } + if (f.value === 'custom') $('sched-cron').value = String(expr || ''); + schedFreqUi(); + } + // 控件 → cron 表达式;非法输入抛中文 Error(后端 validateCron 再兜底:可解析 + 间隔 ≥1h) + function schedComposeCron() { + const f = $('sched-freq').value; + if (f === 'custom') { + const c = $('sched-cron').value.trim(); + if (!c) throw new Error('请输入 cron 表达式'); + return c; + } + if (f === 'everyN') { + const n = parseInt($('sched-nh').value, 10); + if (!(n >= 1 && n <= 23)) throw new Error('间隔需为 1-23 的整小时数'); + return '0 */' + n + ' * * *'; + } + const hh = parseInt($('sched-hh').value, 10); + const mm = parseInt($('sched-mm').value, 10); + if (!(hh >= 0 && hh <= 23)) throw new Error('小时需为 0-23'); + if (!(mm >= 0 && mm <= 59)) throw new Error('分钟需为 0-59'); + return mm + ' ' + hh + ' * * ' + (f === 'weekly' ? $('sched-dow').value : '*'); + } function openScheduleModal() { const sc = state.schedule; if (!sc || state.view !== 'chat') return; - let time = '⏰ ' + cronText(sc.cron_expr) + '(' + sc.cron_expr + ')'; - if (sc.next_run_at) time += '\n下次执行 ' + fmtTime(sc.next_run_at); - if (sc.last_run_at) time += '\n上次执行 ' + fmtTime(sc.last_run_at) + (sc.last_status ? ' · ' + sc.last_status : ''); - $('sched-modal-time').textContent = time; + schedFillFromCron(sc.cron_expr); + let meta = sc.next_run_at ? '下次执行 ' + fmtTime(sc.next_run_at) : ''; + if (sc.last_run_at) meta += (meta ? '\n' : '') + '上次执行 ' + fmtTime(sc.last_run_at) + (sc.last_status ? ' · ' + sc.last_status : ''); + $('sched-modal-meta').textContent = meta; $('sched-modal-prompt').value = sc.prompt || ''; $('schedule-modal').classList.remove('hidden'); } function closeScheduleModal() { $('schedule-modal').classList.add('hidden'); } - async function saveSchedulePrompt() { + async function saveSchedule() { const id = state.sessionId; if (!id || !state.schedule) return; const prompt = $('sched-modal-prompt').value.trim(); if (!prompt) { toast('提示词不能为空'); return; } + let cron; + try { cron = schedComposeCron(); } catch (e) { toast(e.message); return; } try { - await req('PATCH', '/api/sessions/' + id + '/schedule', { prompt }); - state.schedule.prompt = prompt; // 本地同步,免重拉详情 + await req('PATCH', '/api/sessions/' + id + '/schedule', { prompt: prompt, cron_expr: cron }); toast('定时任务已更新'); closeScheduleModal(); + // 频次变了 next_run_at 由后端重算,重拉详情同步状态条(与删除后同一套刷新路径) + const detail = await req('GET', '/api/sessions/' + id + '?limit=' + Math.max(CHAT_PAGE_SIZE, state.chatLoadedCount)); + if (state.sessionId === id) { renderDetail(detail); connectStream(); } } catch (e) { toast('更新失败:' + e.message); } } async function deleteSchedule() { if (!state.sessionId) return; const id = state.sessionId; - if (!await confirmModal('删除定时任务', '删除后本会话不再定时执行。要改频次,先删除再让 AI 重新创建。', '删除', true)) return; + if (!await confirmModal('删除定时任务', '删除后本会话不再定时执行。', '删除', true)) return; try { await req('DELETE', '/api/sessions/' + id + '/schedule'); toast('定时任务已删除'); diff --git a/app/server/routes/sessions.js b/app/server/routes/sessions.js index 58f15ed..95a5d09 100644 --- a/app/server/routes/sessions.js +++ b/app/server/routes/sessions.js @@ -3,6 +3,7 @@ const express = require('express'); const fs = require('fs'); const path = require('path'); const engine = require('../engine'); +const scheduler = require('../scheduler'); // 复用 validateCron(cron 可解析 + 间隔 ≥1h);scheduler 顶层不 require 路由,无循环引用 const log = require('../log'); const router = express.Router(); @@ -235,21 +236,36 @@ router.delete('/:id', wrap((req, res) => { res.json(engine.deleteSession(req.params.id, delDir)); })); -// 手动修改定时任务提示词(会话详情 schedule 弹窗入口)。 -// 只改 prompt,不动 next_run_at/cron;不插通知消息——每次触发前历史会被存档, +// 手动修改定时任务(会话详情 schedule 弹窗入口):提示词 + 频次(前端预设控件组合出的 cron,兼容自定义表达式)。 +// cron 变化才重算 next_run_at(同样以 now 为基准);不插通知消息——每次触发前历史会被存档, // AI 只看到投递的 prompt 本身,改完下次触发自然生效。 router.patch('/:id/schedule', wrap((req, res) => { const db = engine.getDb(); - const prompt = String((req.body && req.body.prompt) || '').trim(); + const body = req.body || {}; + const prompt = String(body.prompt || '').trim(); if (!prompt) throw Object.assign(new Error('提示词不能为空'), { status_code: 400 }); if (prompt.length > 20000) throw Object.assign(new Error('提示词过长(上限 20000 字符)'), { status_code: 400 }); - const r = db.prepare('UPDATE scheduled_tasks SET prompt = ? WHERE session_id = ?').run(prompt, req.params.id); - if (!r.changes) throw Object.assign(new Error('本会话没有定时任务'), { status_code: 404 }); - log.info('scheduler', req.params.id + ' 更新定时任务提示词'); + const t = db.prepare('SELECT cron_expr FROM scheduled_tasks WHERE session_id = ?').get(req.params.id); + if (!t) throw Object.assign(new Error('本会话没有定时任务'), { status_code: 404 }); + const cron = String(body.cron_expr || '').trim(); + if (cron && cron !== t.cron_expr) { + let nextAt; + try { + nextAt = scheduler.validateCron(cron); + } catch (e) { + throw Object.assign(new Error(e.message), { status_code: 400 }); + } + db.prepare('UPDATE scheduled_tasks SET prompt = ?, cron_expr = ?, next_run_at = ? WHERE session_id = ?') + .run(prompt, cron, nextAt, req.params.id); + log.info('scheduler', req.params.id + ' 定时任务改为 ' + cron + '(原 ' + t.cron_expr + ')'); + } else { + db.prepare('UPDATE scheduled_tasks SET prompt = ? WHERE session_id = ?').run(prompt, req.params.id); + log.info('scheduler', req.params.id + ' 更新定时任务提示词'); + } res.json({ ok: true }); })); -// 手动删除定时任务(创建只经 AI 工具;频次暂不可改,内容可在弹窗内更新)。 +// 手动删除定时任务(创建只经 AI 工具;频次/提示词可在弹窗内改)。 // 通知消息只 saveMessage 落库,不走 postUserMessage:不触发 AI 运行。 // 删会话无需此处:scheduled_tasks 随 sessions 行 ON DELETE CASCADE 自动清理。 router.delete('/:id/schedule', wrap((req, res) => { diff --git a/app/server/scheduler.js b/app/server/scheduler.js index 1673a84..04f79f6 100644 --- a/app/server/scheduler.js +++ b/app/server/scheduler.js @@ -30,10 +30,10 @@ function computeNext(cronExpr) { } // ---------- schedule_task 工具实现(tools/executor.js 调) ---------- -// sessionId 由调用方从工具 ctx 取(AI 无法指定别的会话)。校验顺序: -// cron 可解析 → 连续两次 next() 间隔 ≥ 1h → 本会话尚无任务 → INSERT(主键冲突兜底)。 -// 失败抛中文 Error,由 engine 工具执行路径转成 'Error: ...' 回执原样回给 AI。 -function createTask(db, sessionId, cronExpr, prompt) { +// cron 校验:可解析 + 连续两次 next() 间隔 ≥ 1h(防分钟级任务反复烧模型池); +// 返回下次到期时间(以 now 为基准)。创建(createTask)与会话详情弹窗改频次(PATCH /:id/schedule)共用。 +// 失败抛中文 Error:工具路径由 engine 转 'Error: ...' 回给 AI,HTTP 路径由 wrap 转 4xx/500 给前端 toast。 +function validateCron(cronExpr) { let first; let second; try { @@ -44,6 +44,13 @@ function createTask(db, sessionId, cronExpr, prompt) { throw new Error('cron 表达式无效: ' + (e && e.message || e)); } if (second - first < MIN_INTERVAL_MS) throw new Error('定时任务间隔不能小于 1 小时'); + return first; +} + +// sessionId 由调用方从工具 ctx 取(AI 无法指定别的会话)。校验顺序: +// validateCron → 本会话尚无任务 → INSERT(主键冲突兜底)。 +function createTask(db, sessionId, cronExpr, prompt) { + const first = validateCron(cronExpr); const exist = db.prepare('SELECT cron_expr FROM scheduled_tasks WHERE session_id = ?').get(sessionId); if (exist) throw new Error('本会话已有定时任务(' + exist.cron_expr + '),请先在会话页删除'); try { @@ -143,4 +150,4 @@ function start(engine) { if (timer.unref) timer.unref(); // 不阻止进程退出 } -module.exports = { start, createTask, computeNext }; +module.exports = { start, createTask, computeNext, validateCron }; diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 4dd8825..08a3029 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -191,8 +191,8 @@ scheduled_tasks session_id PK (FK sessions, ON DELETE CASCADE) / cron_expr / prompt / next_run_at / last_run_at / last_status (ok|error|skipped|running) / last_note (给人看的中文说明,UI 原样展示) / created_at # 定时任务:每会话至多一个(session_id 主键兼防重),按 next_run_at 索引; - # 创建只经 AI 工具 schedule_task;提示词可在会话详情弹窗改(PATCH /:id/schedule), - # cron 暂不可改(改=删后让 AI 重建);删除走 CASCADE 或 DELETE /:id/schedule(见 §5.12) + # 创建只经 AI 工具 schedule_task;频次/提示词可在会话详情弹窗改(PATCH /:id/schedule, + # 改频次后端重校验并重算 next_run_at);删除走 CASCADE 或 DELETE /:id/schedule(见 §5.12) ``` **session.status 状态机**(`engine.js`): @@ -415,7 +415,7 @@ AI 通过 `schedule_task` 工具为所在会话建周期性任务(`scheduled_t | 路径前缀 | 文件 | 主要端点 | |---|---|---| -| `/api/sessions` | `routes/sessions.js` | `POST /` 创建、`GET /` 列表(分页 + 搜索 + user 隔离)、`GET /:id` 详情(含 `schedule` 字段,列表接口不带以免 N+1)、`PATCH /:id` 改名、`DELETE /:id?delete_dir=...`、`POST /:id/bind`、`DELETE /:id/schedule`(删定时任务,只落 `scheduler_note` 通知消息不触发 AI)、`PATCH /:id/schedule`(改提示词,不动 cron/next_run_at) | +| `/api/sessions` | `routes/sessions.js` | `POST /` 创建、`GET /` 列表(分页 + 搜索 + user 隔离)、`GET /:id` 详情(含 `schedule` 字段,列表接口不带以免 N+1)、`PATCH /:id` 改名、`DELETE /:id?delete_dir=...`、`POST /:id/bind`、`DELETE /:id/schedule`(删定时任务,只落 `scheduler_note` 通知消息不触发 AI)、`PATCH /:id/schedule`(改提示词/频次,cron 经 validateCron 重校验并重算 next_run_at) | | `/api/sessions/:id/messages` | `routes/messages.js` | `POST /` 发消息(`delivered:'live'\|'queued'`)、`POST /start` "开始执行" 模板消息、`POST /stop`、`POST /release`(held→completed)、`DELETE /messages`(清空 + ?keep=summary)、`POST /summarize`(压缩)、`DELETE /messages/:mid`、`GET /stream` SSE 事件流 | | `/api/sessions/:id/files` | `routes/files.js` | `POST /` 上传(multer,50MB/文件,文件名清洗 sanitizeName)、`GET /` 列表(递归)、`GET /download[-name/...]` 签名下载(5 分钟 TTL)、`GET /zip-token` + `GET /zip[-name/...]` 选中项(含文件夹)打包 zip 流式下载(纯 Node STORE,两遍读:先 CRC 后磁盘流发送)、`DELETE /` 删文件(目录递归删) | | `/api/skills` | `routes/skills.js` | 技能列表/创建/重命名/删除 + 技能内文件 CRUD + 上传(`?overwrite=true` 覆盖) |