会话阶段状态机advising/executing(单会话单问题:先聊清再干活):新建会话与「清空」落advising——resolveProfileName两档化(phase=advising强制命中内置advising组合,否则随模型配置profile,tools_allow只留read_file/fetch/write_file、不带skill故模板无技能清单段,配advising-system.txt:问答判意图引导澄清、每轮至多1-2问防过度追问);唯一出口是任务书正门——runLoopInner工具批跑完后,advising回合内write_file/edit_file成功落任务目录根task.md(argsHitTaskBrief,上传同名与terminal间接创建不算;批量末尾统一切,防父assistant先存档后落库回执成孤儿行被上游拒收)即enterExecuting:全史标archived+插type=task_brief磁盘快照行作执行阶段唯一上下文起点+phase翻转与SSE phase广播,下一迭代重读历史重解profile天然切默认组合、同回合开工(幂等:执行中再改task.md只是普通编辑);回头路只有清空(archiveTaskBrief把旧task.md mv进.task-history/task-<ts>.md防污染新规划,点目录沿用.imgcache隐式约定);压缩对phase中性(压完回原模式,task_brief不豁免存档,漂移可控因压缩本就用户主导);定时投递前强制executing(无人值守不能被顾问话术卡住);db迁移存量phase回填executing零打扰、sessions.profile列废弃不读写;运行期手动切profile全拆(消息级参数/bind的profile分支/setSessionProfile与hasModelProfile/status的model_profiles名单/bind弹窗模式区),头部徽标机位复用为阶段徽标(仅advising显灯泡,SSE phase驱动,转执行toast反馈)

This commit is contained in:
2026-09-25 11:54:20 +08:00
parent a70e5d267b
commit 7f8cf64e88
15 changed files with 245 additions and 157 deletions
+4
View File
@@ -9,7 +9,11 @@ platforms: []
tools_deny: [lab]
# 模型 profile:prompt + tools 名单组合,模型用 profile: <名> 引用(不配 = 全量)。
# 内置 advising 不靠引用:会话处于 advising 阶段(顾问澄清需求/规划)时强制命中,见 server/engine.js resolveProfileName。
model_profiles:
advising: # 顾问阶段:只留问答/调研/写任务书工具,配专属提示词
tools_allow: [read_file, fetch, write_file]
system_prompt_file: advising-system.txt
lab: # 统一入口自测:tools 只有 lab,其余能力经 lab(help) 现场发现
tools_allow: [lab]
tools_deny: [] # 必须显式清空全局黑名单,否则 lab 自己也被 deny → 零工具
+3
View File
@@ -96,6 +96,9 @@ const DEFAULTS = {
tools_deny: ['lab'],
// 模型 profile(prompt + tools 名单组合):platforms 里的模型用 profile: <名> 引用。
model_profiles: {
// advising:顾问阶段(sessions.phase)专用组合——不由模型配置引用,而是 resolveProfileName 在
// advising 时强制命中:只留问答/调研/写任务书所需工具(terminal 不进名单),配专用顾问提示词模板。
advising: { tools_allow: ['read_file', 'fetch', 'write_file'], system_prompt_file: 'advising-system.txt' },
// lab:统一入口元工具自测组合——tools 收缩到 1 个,其余能力经 lab(help) 现场发现。
// tools_deny 必须显式清空:不配 = 继承全局 ['lab'],deny 后叠加会把 lab 自己禁掉 → 零工具。
lab: { tools_allow: ['lab'], tools_deny: [], system_prompt_file: 'lab-system.txt' },
+8 -3
View File
@@ -14,7 +14,7 @@ function initDb(dbPath) {
id TEXT PRIMARY KEY,
title TEXT DEFAULT '',
status TEXT NOT NULL,
phase TEXT NOT NULL DEFAULT 'planning',
phase TEXT NOT NULL DEFAULT 'advising',
model_id TEXT,
last_model_id TEXT,
assistant_type TEXT DEFAULT 'secretary',
@@ -143,11 +143,16 @@ function initDb(dbPath) {
if (!cols.some(c => c.name === 'user')) {
db.exec("ALTER TABLE sessions ADD COLUMN user TEXT DEFAULT ''");
}
// 迁移:profile 记会话绑定的 prompt+tools 组合名(config.yml 顶层 model_profiles;''=随模型配置)。
// 选取优先级见 engine.resolveProfileName,切换入口见 routes/sessions.js bind 路由(弹窗「模式」区)。
// 迁移:profile 曾记会话绑定的 prompt+tools 组合名(bind 弹窗「模式」区)。已废弃:
// 前端手动切换模式全部移除,profile 选取收敛为「phase 强制 + 模型配置默认」两档(见 engine.resolveProfileName);
// 列保留(SQLite 删列不值得),代码不再读写。
if (!cols.some(c => c.name === 'profile')) {
db.exec("ALTER TABLE sessions ADD COLUMN profile TEXT DEFAULT ''");
}
// 迁移:phase 语义重定义为 advising(顾问:澄清需求/规划)/ executing(执行)。
// 存量会话(旧值 planning/NULL)统一回填 executing——它们都有历史,行为与改造前一致、零打扰;
// 只有新建会话进 advising(createSession 显式写入)。幂等,每次启动一条廉价 UPDATE。
db.exec("UPDATE sessions SET phase='executing' WHERE phase IS NULL OR phase NOT IN ('advising','executing')");
return db;
}
+98 -33
View File
@@ -241,15 +241,13 @@ function registerProfilePrompts() {
setProfilePrompts(map);
}
// 本轮生效的 profile 名:每消息参数(run.profile,与 deepThink 同约定:每轮迭代取最新值)
// > 会话绑定(sessions.profile,弹窗「模式」区写入,跨回合/刷新持久)> 模型配置默认(cfg.models[].profile)
// > ''(默认全量)。保留值 'default' 归一为 ''(显式摆脱模型默认组合;无 profile 模型下二者等效)。
function resolveProfileName(session, run) {
const manual = run && String(run.profile || '').trim();
if (manual) return manual === 'default' ? '' : manual;
const bound = String((session && session.profile) || '').trim();
if (bound) return bound === 'default' ? '' : bound;
const m = session.model_id && (cfg.models || []).find(x => x.id === session.model_id);
// 本轮生效的 profile 名(两档):advising 阶段强制命中内置 'advising' 组合(顾问只该看到顾问的工具);
// 否则 = 模型配置默认(cfg.models[].profile)> ''(默认全量)。
// 运行期手动切换已全部移除(消息级 profile 参数、sessions.profile 会话绑定均已废弃),
// 顾问/执行的节奏由 sessions.phase 单一状态机控制,见 enterExecuting / archiveTaskBrief。
function resolveProfileName(session) {
if (session && session.phase === 'advising') return 'advising';
const m = session && session.model_id && (cfg.models || []).find(x => x.id === session.model_id);
return m && m.profile ? String(m.profile) : '';
}
@@ -274,8 +272,75 @@ function effectiveTools(profileName) {
return out;
}
function hasModelProfile(name) {
return !!(name && cfg.model_profiles && cfg.model_profiles[String(name)]);
// ---------- 阶段(sessions.phase:advising 顾问 / executing 执行) ----------
// advising:新建会话与「清空」的落点。profile 被 resolveProfileName 强制为 'advising',
// 只问答/判意图/引导澄清;唯一出口是 write_file/edit_file 把任务书 task.md 落在任务目录根(正门判定)。
// executing:一路走到底,只有清空才回 advising;压缩不碰 phase(压完仍回原模式)。
// 写类工具(write_file/edit_file)的参数是否恰好落在任务目录根的 task.md——阶段切换的正门判定。
// resolveInTask 统一解相对/绝对路径并拦越界;子目录 task.md 不算。
// 不扫文件存在性:用户随时上传同名素材不算承诺,只有 AI 亲自写一次才算(上传也永远覆盖不了
// task.md:files.js 同名自动加后缀)。
function argsHitTaskBrief(taskDir, args) {
try {
const abs = path.resolve(resolveInTask(taskDir, String((args && args.path) || '')));
return abs === path.resolve(taskDir, 'task.md');
} catch (_) { return false; }
}
// advising → executing:任务书落地,当场重建上下文——
// 全部历史标 archived(UI 照常展示、不再发模型,与压缩/定时投递同机制),
// 插一条 type='task_brief' 的 user 行(内容 = 此刻 task.md 磁盘快照,非引用:后续文件怎么改都不动锚点)
// 作为执行阶段唯一上下文起点;runLoopInner 下一迭代重读历史 + 重解 profile,天然已在执行态,AI 同回合开工。
// 幂等:phase 已是 executing 直接返回(执行中再改 task.md 只是普通文件编辑,不重存档、不重插快照)。
function enterExecuting(sessionId) {
const session = getSession(sessionId);
if (!session || session.phase !== 'advising') return;
const briefPath = path.join(taskDirOf(sessionId), 'task.md');
let snapshot;
try {
snapshot = fs.readFileSync(briefPath, 'utf8');
} catch (e) {
log.warn('engine', sessionId + ' 阶段切换放弃:读不回 task.md — ' + (e && e.message || e));
return;
}
if (!snapshot.trim()) return; // 空任务书不构成承诺,继续留在顾问模式
const n = db.prepare(
"UPDATE messages SET type = 'archived' WHERE session_id = ? AND (type IS NULL OR type != 'archived')"
).run(sessionId).changes;
saveMessage(sessionId, {
role: 'user', type: 'task_brief',
content: '【任务书】需求澄清完毕,会话已进入执行模式。以下任务书快照(task.md)是唯一目标依据;'
+ '之前的顾问对话已存档、不再发送。执行中可修订 task.md(以文件现状为准);'
+ '上一轮任务书归档在 .task-history/,仅限用户明确要求时查阅。\n\n' + snapshot,
});
db.prepare("UPDATE sessions SET phase='executing', updated_at=? WHERE id=?").run(now(), sessionId);
bus.emit(sessionId, 'phase', { phase: 'executing' });
emitStatus(sessionId);
log.info('engine', sessionId + ' advising → executing:task.md 落地,存档 ' + n + ' 条消息,上下文重建为任务书快照');
}
// 清空即回 advising:上一轮任务书 mv 进 .task-history/(带时间戳名,撞名再加 -N,同上传风格),
// 防旧约定污染新一轮规划。点前缀目录在文件列表默认隐藏(同 .imgcache 约定),AI/用户显式请求可查;
// 同步清掉 files 元数据表的 task.md 行(列表读磁盘不读表,清行只为不留孤儿记录)。
function archiveTaskBrief(sessionId) {
try {
const dir = taskDirOf(sessionId);
const src = path.join(dir, 'task.md');
if (!fs.existsSync(src)) return;
const hist = path.join(dir, '.task-history');
fs.mkdirSync(hist, { recursive: true });
const d = new Date();
const pad = x => String(x).padStart(2, '0');
const stamp = d.getFullYear() + pad(d.getMonth() + 1) + pad(d.getDate()) + '-' + pad(d.getHours()) + pad(d.getMinutes()) + pad(d.getSeconds());
let dest = path.join(hist, 'task-' + stamp + '.md');
for (let i = 1; fs.existsSync(dest); i++) dest = path.join(hist, 'task-' + stamp + '-' + i + '.md');
fs.renameSync(src, dest);
db.prepare("DELETE FROM files WHERE session_id = ? AND filename = 'task.md'").run(sessionId);
log.info('task', sessionId + ' 旧任务书归档 → ' + path.relative(dir, dest));
} catch (e) {
log.warn('task', sessionId + ' 旧任务书归档失败:' + (e && e.message || e));
}
}
function enqueue(sessionId) {
@@ -330,17 +395,7 @@ function bindToSession(sessionId, modelId) {
return { ok: true, model_id: want };
}
// 会话级 profile 绑定(bind 弹窗「模式」区):''=解绑回随模型配置;保留值 'default' 归一为 ''。
// 不设会话状态门槛——模式是每轮选择,切换下一轮迭代/下条消息即生效;不碰模型槽位占用。
// 名字存在性由路由校验(hasModelProfile,与 messages 路由同款 400),这里只管落库。
function setSessionProfile(sessionId, profile) {
const s = getSession(sessionId);
if (!s) throw Object.assign(new Error('会话不存在'), { status_code: 404 });
const name = profile === 'default' ? '' : String(profile || '').trim();
db.prepare('UPDATE sessions SET profile = ?, updated_at = ? WHERE id = ?').run(name, now(), sessionId);
log.info('model', sessionId + ' 会话模式绑定 → ' + (name || '默认(随模型配置)'));
return name;
}
// 是否还有待回应的新用户消息(最后一条非 tool 消息是 user)。
function hasPendingUser(sessionId) {
@@ -593,7 +648,7 @@ async function runLoopInner(sessionId, run) {
const compressing = !!run.summarizing;
// profile(prompt+tools 组合):每迭代现解,前端切模式后下一个请求即生效;
// 压缩回合同样跟随(小模型会话点「压缩」若回退默认大模板,当场撑爆)。
const profileName = resolveProfileName(session, run);
const profileName = resolveProfileName(session);
const messages = compressing
? compressMessages(session, (cfg.agent || {}).language, mintImageUrl, profileName)
: buildMessages(session, (cfg.agent || {}).language, mintImageUrl, profileName);
@@ -703,6 +758,7 @@ async function runLoopInner(sessionId, run) {
// 执行工具
const vision = modelVision(session);
let taskBriefWritten = false; // 本批工具里是否有「正门落 task.md」(批量跑完统一切换,见循环尾注释)
for (const tc of msgRow.tool_calls) {
if (run.cancelled) break;
const id = tc.id;
@@ -755,7 +811,15 @@ async function runLoopInner(sessionId, run) {
image_url: imageRel ? '/api/sessions/' + encodeURIComponent(sessionId) + '/files/download?path=' + encodeURIComponent(imageRel) : undefined,
msg_id: toolMsgId,
});
// 阶段切换正门:advising 回合里 write_file/edit_file 成功且路径恰为根 task.md → 标记待切换。
// 不在这里就地切:同批可能还有其它 tool_calls,其父 assistant 行若先被存档、
// 后落库的回执就成了无主孤儿行(上游拒收)——整批跑完再统一重建上下文。
if (!isError && (tc.function.name === 'write_file' || tc.function.name === 'edit_file')
&& argsHitTaskBrief(taskDirOf(sessionId), chk.args)) {
taskBriefWritten = true;
}
}
if (taskBriefWritten) enterExecuting(sessionId);
iter++;
}
if (iter >= maxIter && !run.cancelled) {
@@ -927,8 +991,9 @@ function createSession(title, preferModelId, assistantType, user) {
const dir = taskDirOf(id);
fs.mkdirSync(dir, { recursive: true });
db.prepare(
"INSERT INTO sessions (id, title, status, phase, model_id, assistant_type, user, created_at, updated_at) VALUES (?,?,'queued','planning',NULL,?,?,?,?)"
"INSERT INTO sessions (id, title, status, phase, model_id, assistant_type, user, created_at, updated_at) VALUES (?,?,'queued','advising',NULL,?,?,?,?)"
).run(id, title || '', assistantType || 'secretary', user || '', now(), now());
// 新会话一律落 advising(顾问模式):先聊天判意图,任务书 task.md 落地才转 executing(见 enterExecuting)
// 指定了模型且其平台恰好有空闲 key → 直接绑定,跳过排队;否则回退到 FIFO 队列
const prefer = preferModelId && platformModels(platformOf(preferModelId)).includes(preferModelId)
? freeKeyOf(platformOf(preferModelId))
@@ -947,18 +1012,16 @@ function createSession(title, preferModelId, assistantType, user) {
return session;
}
// 用户消息(或“开始执行”的模板消息)入口。
// opts.deepThink: true 时启用深度思考;opts.profile: 本轮 prompt+tools 组合名(model_profiles,
// 空 = 随模型配置,'default' = 显式全量);参数都记在会话 run 上,
// 正在跑的回合下一轮迭代会取到最新值。新建会话需在 runLoop 之前先预建 run 以携带该值。
// 用户消息入口。
// opts.deepThink: true 时启用模型该「深度思考」参数(记在会话 run 上,正在跑的回合下一轮迭代会取到最新值)。
// 新建会话需在 runLoop 之前先预建 run 以携带该值。
function postUserMessage(sessionId, content, opts) {
const session = getSession(sessionId);
if (!session) throw Object.assign(new Error('会话不存在'), { status_code: 404 });
const messageId = saveMessage(sessionId, { role: 'user', content });
// 预建/更新 run 记录,记下本轮的 deepThink/profile(被 runLoop / callModel 读取)
// 预建/更新 run 记录,记下本轮的 deepThink(被 runLoop / callModel 读取)
const run = getRun(sessionId, true);
run.deepThink = !!(opts && opts.deepThink);
run.profile = String((opts && opts.profile) || '').trim();
// 真实用户消息到达:若还有个「已排队但尚未开跑」的压缩回合(见 summarizeContext),
// 让它作废,避免新消息被误当成压缩回合处理;已在跑(looping)的不动,
// 由其收尾时自行清空 summarizing。
@@ -1142,6 +1205,8 @@ function maybeAutoCompress(sessionId, run, wasCompressTurn) {
// 清空会话的对话内容:删除该会话的全部消息记录,但保留会话本身与任务目录文件。
// 状态收尾为 completed(释放模型占用、移出等待队列);此后再次发言从零开始,
// 不再携带旧历史。执行中的会话不允许清空,需先「终止」。
// 阶段语义:清空是 executing 唯一回头路——回到 advising 重新规划(单会话只解决一个问题),
// 旧任务书 mv 进 .task-history/ 防污染(archiveTaskBrief);压缩不碰 phase,不在此列。
function clearSessionMessages(sessionId) {
const session = getSession(sessionId);
if (!session) throw Object.assign(new Error('会话不存在'), { status_code: 404 });
@@ -1158,12 +1223,14 @@ function clearSessionMessages(sessionId) {
dequeue(sessionId);
releaseModel(sessionId);
db.prepare('DELETE FROM messages WHERE session_id = ?').run(sessionId);
archiveTaskBrief(sessionId); // 旧任务书先归档(mv),新一轮 advising 不会被上一问题的约定污染
autoCompressProposed.delete(sessionId); // 历史清零,恢复自动压缩提议额度
// 标题随历史一并清零:旧标题描述的是已删除的对话,留着会让新对话文不对题;
// 新一轮交互结束后 maybeGenerateTitle 见 title 为空会自动重新生成。
touch(sessionId, { status: 'completed', completed_at: now(), cancelled_at: null, held_at: null, title: null });
touch(sessionId, { status: 'completed', completed_at: now(), cancelled_at: null, held_at: null, title: null, phase: 'advising' });
bus.emit(sessionId, 'done', { status: 'completed' });
bus.emit(sessionId, 'title', { title: null }); // 供其他打开同一会话的窗口同步清掉旧标题
bus.emit(sessionId, 'phase', { phase: 'advising' });
emitStatus(sessionId);
dispatchQueued();
return { ok: true };
@@ -1249,8 +1316,6 @@ module.exports = {
modelUsageStats,
dispatchQueued,
bindToSession,
setSessionProfile,
TOOL_DEFINITIONS,
effectiveTools,
hasModelProfile,
};
+6 -12
View File
@@ -54,7 +54,7 @@
/* 状态栏「压缩」图标按钮:主操作色(蓝色),与其他 stop-link 区分(终止/选择模型是灰) */
.stop-link.icon-only.icon-primary { color: var(--active); }
.stop-link.icon-only.icon-primary:hover { color: #2854d6; }
/* 推到 phase-bar 最右侧(独立动作,与左侧状态区分;「选择模型/模式」与压缩同列右靠) */
/* 推到 phase-bar 最右侧(独立动作,与左侧状态区分;「选择模型」与压缩同列右靠) */
.phase-bar .phase-bar-right { margin-left: auto; }
/* 定时任务状态条:整条可点,弹详情窗(改频次/提示词、删除;创建走 AI 的 schedule 工具),紫色调区别于状态栏;
左侧 3px 竖条与侧边栏定时任务会话的紫色标记同一语义。
@@ -88,16 +88,10 @@
margin-bottom: 10px; background: #fff; color: var(--ink); resize: vertical;
}
#schedule-modal textarea:focus { border-color: var(--active); }
/* 会话模式徽标(profile 绑定时的标题小图标;尺寸显式定,不依赖 .ic 默认值) */
/* 会话阶段徽标(advising 顾问态的标题小图标;executing 不显;尺寸显式定,不依赖 .ic 默认值) */
.prof-badge { display: inline-flex; align-items: center; margin-right: 4px; opacity: .62; flex: none; }
.prof-badge .ic { width: 13px; height: 13px; }
/* 模式徽标统一用主题蓝(lab/zero 同色,靠形状区分) */
.prof-badge.prof-lab .ic, .prof-badge.prof-zero .ic { color: var(--active); }
/* 弹窗模式行:下拉选中(取代纵向选项组,省垂直空间) */
.msw-prof { display: flex; align-items: center; gap: 6px; padding: 10px 12px; font-size: 13px; color: var(--ink); border-top: 1px solid #dde1ea; }
.msw-prof-label { flex: none; line-height: 30px; }
.msw-prof select { flex: 1; min-width: 0; height: 30px; box-sizing: border-box; border: 1px solid #dde1ea; border-radius: 8px; padding: 0 8px; font-size: 13px; line-height: 28px; background: #fff; color: var(--ink); }
/* welcome 头像兼做「选择模型/模式」入口(与聊天态的「选择模型」同一弹窗) */
.prof-badge .ic { width: 13px; height: 13px; color: var(--active); }
/* welcome 头像兼做「选择模型」入口(与聊天态的「选择模型」同一弹窗) */
.logo-badge { cursor: pointer; }
</style>
<script>
@@ -129,7 +123,7 @@
<div id="phase-bar" class="phase-bar hidden">
<span class="status-pill" id="status-pill">--</span>
<button class="stop-link hidden" id="stop-btn" onclick="stopSession()">终止</button>
<button class="stop-link hidden phase-bar-right" id="model-switch-btn" onclick="openModelSwitch()">选择模型/模式</button>
<button class="stop-link hidden phase-bar-right" id="model-switch-btn" onclick="openModelSwitch()">选择模型</button>
<button class="stop-link icon-only icon-primary phase-bar-right hidden" id="compress-btn" title="压缩上下文" aria-label="压缩上下文" onclick="summarizeChat()">
<svg class="ic" viewBox="0 0 24 24"><ellipse cx="12" cy="5" rx="8" ry="2.5" fill="none" stroke="currentColor" stroke-width="1.6"></ellipse><path fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" d="M4 5v6c0 1.4 3.6 2.5 8 2.5s8-1.1 8-2.5V5"></path><path fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" d="M4 11v6c0 1.4 3.6 2.5 8 2.5s8-1.1 8-2.5v-6"></path></svg>
</button>
@@ -142,7 +136,7 @@
<!-- ================= 未对话状态:欢迎页 ================= -->
<section id="welcome-view">
<div class="welcome-head">
<div class="logo-badge" onclick="openModelSwitch()" title="选择模型/模式" role="button" aria-label="选择模型与模式">
<div class="logo-badge" onclick="openModelSwitch()" title="选择模型" role="button" aria-label="选择模型">
<svg class="ic" viewBox="0 0 24 24"><rect x="4" y="8" width="16" height="12" rx="3"></rect><line x1="12" y1="4" x2="12" y2="8"></line><circle cx="12" cy="3" r="1.4"></circle><circle cx="9" cy="13.5" r="1" fill="currentColor" stroke="none"></circle><circle cx="15" cy="13.5" r="1" fill="currentColor" stroke="none"></circle><line x1="9.5" y1="17" x2="14.5" y2="17"></line></svg>
</div>
<div class="welcome-slogan">随时开始吧</div>
+1 -1
View File
@@ -329,7 +329,7 @@
const s = detail.session;
state.sessionTitle = (s && s.title) || '';
state.sessionType = (s && s.assistant_type) || 'secretary'; // 顶部 icon 跟随会话类型
state.profile = (s && s.profile) || ''; // 会话绑定模式(头部徽标/弹窗当前态同源)
state.phase = s && s.phase || ''; // 会话阶段(advising/executing):头部徽标与 SSE status/phase 事件同源
state.status = (s && s.status) || '';
state.schedule = detail.schedule || null; // 定时任务状态条数据(随 updatePhaseBar 一并渲染)
state.toolCards = {};
+15 -14
View File
@@ -157,9 +157,8 @@
mode: 'secretary', // 新建会话默认助手类型(欢迎页已去掉模式切换,不再可变)
sessionType: 'secretary', // 当前会话的助手类型(建档时锁定,后续不随模式切换变更)
deepThink: false, // 深度思考开关(仅本地视觉状态,无后端参数)
profile: '', // 当前会话绑定模式(sessions.profile;''=默认随模型;弹窗「模式」区切换)
phase: '', // 当前会话阶段(sessions.phase: advising=顾问 / executing=执行;徽标据此渲染)
pendingModel: '', // welcome 预选模型(ensureSession 建档时透传 model_id)
pendingProfile: '', // welcome 预选模式(ensureSession 建会话后立即 bind)
sessionId: null, // 当前会话
sessionTitle: '', // 当前会话标题
status: '', // 当前会话状态(SSE 更新)
@@ -198,29 +197,31 @@
updateScrollBottomBtn();
}
// ---------- 会话模式徽标 ----------
// 会话绑定 profile 时仅头部标题前显示小图标(抽屉列表不显,避免画蛇添足):''=默认不显示;
// 颜色统一 --active(CSS .prof-*),靠形状区分;未知名兑底圆点;tooltip 提示当前模式,不另显文字。
const PROFILE_BADGES = {
lab: '<svg viewBox="0 0 24 24" class="ic"><path fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" d="M10 2v6.6L4.8 18.5a1.8 1.8 0 0 0 1.6 2.7h11.2a1.8 1.8 0 0 0 1.6-2.7L14 8.6V2"/><line x1="8.5" y1="2" x2="15.5" y2="2"/></svg>',
zero: '<svg viewBox="0 0 24 24" class="ic"><circle fill="none" stroke="currentColor" stroke-width="1.8" cx="12" cy="12" r="9"/><line stroke="currentColor" stroke-width="1.8" stroke-linecap="round" x1="8" y1="12" x2="16" y2="12"/></svg>',
// ---------- 会话阶段徽标 ----------
// 头部标题前小图标:advising(顾问:澄清需求/规划)才显示(tooltip 说明),
// executing 是主干状态不显示、减噪。原 profile 模式徽标机位改造而来(手动切换模式已移除)。
const PHASE_BADGES = {
advising: {
label: '顾问模式:澄清需求、规划任务;写定任务书后自动开始执行',
icon: '<svg viewBox="0 0 24 24" class="ic" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M9 18h6"/><path d="M10 21h4"/><path d="M12 3a6 6 0 0 0-3.6 10.8c.7.6 1.1 1.4 1.1 2.2h5c0-.8.4-1.6 1.1-2.2A6 6 0 0 0 12 3z"/></svg>',
},
};
function profileBadgeHtml(p) {
if (!p) return '';
return '<span class="prof-badge prof-' + esc(p) + '" title="当前模式:' + esc(p) + '">' +
(PROFILE_BADGES[p] || '<svg viewBox="0 0 24 24" class="ic"><circle cx="12" cy="12" r="4.5" fill="none" stroke="currentColor" stroke-width="2"/></svg>') + '</span>';
function phaseBadgeHtml(p) {
const b = PHASE_BADGES[p];
if (!b) return '';
return '<span class="prof-badge phase-' + esc(p) + '" title="' + esc(b.label) + '">' + b.icon + '</span>';
}
function renderHeader() {
const c = $('header-center');
// welcome(含刚 newChat)一律清空:newChat 会停在 welcome,不重刷会残留旧会话标题
if (state.view !== 'chat' || !state.sessionId) { c.innerHTML = ''; return; }
// 顶部只显会话模式徽标(助手类型 icon 退位;''=默认不显),颜色按模式区分,tooltip 提示当前模式
// 顶部只显会话阶段徽标(advising 才显)+ 标题;助手类型 icon 早已退位
const title = document.createElement('div');
title.className = 'header-title';
title.style.cursor = 'pointer';
title.title = '点击重命名';
title.innerHTML = profileBadgeHtml(state.profile) +
title.innerHTML = phaseBadgeHtml(state.phase) +
'<span class="header-title-text">' + esc(state.sessionTitle || state.sessionId) + '</span>';
title.addEventListener('click', renameSession); // 点标题重命名(同步 index)
c.innerHTML = '';
+6 -53
View File
@@ -78,9 +78,8 @@
state.sessionId = null;
state.sessionTitle = '';
state.sessionType = 'secretary';
state.profile = '';
state.phase = '';
state.pendingModel = '';
state.pendingProfile = '';
state.streamEl = null;
state.streamText = '';
state.toolCards = {};
@@ -162,7 +161,7 @@
// 先从抽屉列表缓存取会话类型,让顶部 icon 立即正确;详情回来后由 renderDetail 纠正
const cached = (state.sessions || []).find(x => x.id === id);
state.sessionType = (cached && cached.assistant_type) || 'secretary';
state.profile = (cached && cached.profile) || ''; // 先从列表缓存取模式徽标,renderDetail 回来后纠正
state.phase = (cached && cached.phase) || ''; // 先从列表缓存取阶段徽标,renderDetail 回来后纠正
state.streamEl = null;
state.streamText = '';
state.streamWrap = null;
@@ -191,20 +190,14 @@
}
// 确保存在当前会话:首条消息自动建档(POST /api/sessions);助手类型此时锁定,后续不可变更。
// welcome 经弹窗预选的模型/模式在这里兑现:model_id 建档透传,pendingProfile 建完会话立即 bind(早于首条消息)。
// welcome 经弹窗预选的模型在这里兑现:model_id 建档透传。
async function ensureSession() {
if (state.sessionId) return state.sessionId;
const s = await req('POST', '/api/sessions', { title: '', model_id: state.pendingModel || '', assistant_type: state.mode });
state.sessionId = s.id;
state.sessionTitle = (s && s.title) || '';
state.sessionType = (s && s.assistant_type) || state.mode;
if (state.pendingProfile) {
try {
await req('POST', '/api/sessions/' + s.id + '/bind', { profile: state.pendingProfile });
} catch (e) { toast('模式绑定失败:' + e.message); state.profile = ''; }
}
state.pendingModel = '';
state.pendingProfile = '';
setView('chat');
renderHeader();
updatePhaseBar();
@@ -221,9 +214,8 @@
state.sessionType = 'secretary';
state.status = '';
state.schedule = null;
state.profile = '';
state.phase = '';
state.pendingModel = '';
state.pendingProfile = '';
state.attachments = [];
state.streamEl = null;
state.streamText = '';
@@ -431,7 +423,7 @@
} catch (e) { toast((held ? '断开失败:' : '终止失败:') + e.message); }
}
async function openModelSwitch() {
// welcome(无会话)也可开:模型/模式选择记为预选项,ensureSession 建档时兑现。有会话则即点即绑,行为与原逻辑一致。
// welcome(无会话)也可开:模型选择记为预选项,ensureSession 建档时兑现。有会话则即点即绑,行为与原逻辑一致。
const list = $('bind-model-list');
const sub = $('bind-model-sub');
list.innerHTML = '<div class="empty-tip">加载中…</div>';
@@ -497,58 +489,19 @@
} catch (e) {
modelsHtml = '<div class="empty-tip">读取模型列表失败:' + e.message + '</div>';
}
// ---------- 模式行:下拉选中(名单来自 /api/system/status;拉不到 = 整行隐藏,不影响选模型) ----------
let profHtml = '';
const names = await loadProfileNames();
if (names.length) {
const cur = state.sessionId ? state.profile : state.pendingProfile;
const opts = [''].concat(names).map(p =>
'<option value="' + esc(p) + '"' + (p === cur ? ' selected' : '') + '>' + (p ? esc(p) : '默认(随模型配置)') + '</option>').join('');
profHtml = '<div class="msw-prof"><span class="msw-prof-label">模式:</span>' +
'<select id="bind-prof-select" onchange="chooseProfile(this.value)">' + opts + '</select></div>';
}
// 空闲数并进顶部提示句(原 footer「共 X 个模型可用」不再单独占行)
if (sub) sub.textContent = (state.sessionId ? '选择一个模型继续当前会话' : '选择一个模型用于新会话')
+ (avail ? '(共 ' + avail + ' 个空闲)' : '');
list.innerHTML = modelsHtml + profHtml;
list.innerHTML = modelsHtml;
}
function closeModelSwitch() { $('bind-model-modal').classList.add('hidden'); }
// profile 组合名单缓存(组合列表改动需重启才生效,会话级缓存足够);status 拉失败 = 空名单 → 模式区隐藏。
let PROFILE_NAMES = null;
async function loadProfileNames() {
if (PROFILE_NAMES) return PROFILE_NAMES;
try {
const s = await req('GET', '/api/system/status');
PROFILE_NAMES = Array.isArray(s && s.model_profiles) ? s.model_profiles.slice() : [];
} catch (_) { PROFILE_NAMES = []; }
return PROFILE_NAMES;
}
function choosePendingModel(modelId) { // welcome 无会话:记预选,ensureSession 建档时透传;选完即关窗 + toast,重开弹窗时该行带「预选」标记
state.pendingModel = modelId;
closeModelSwitch();
toast('新会话将用 ' + modelId);
}
async function chooseProfile(name) { // 下拉选中即绑/即预选;无 toast(头部/抽屉徽标即时变化即反馈),失败回退选项并报错
if (state.sessionId) {
try {
await req('POST', '/api/sessions/' + state.sessionId + '/bind', { profile: name });
} catch (e) {
const sel = $('bind-prof-select');
if (sel) sel.value = state.profile; // 失败回退选项,下拉不谎报
return toast('切换失败:' + e.message);
}
state.profile = name;
const row = (state.sessions || []).find(x => x.id === state.sessionId); // 只同步本地缓存保数据一致(抽屉不显模式徽标,无需重画)
if (row) row.profile = name;
} else {
state.pendingProfile = name;
state.profile = name;
}
renderHeader(); // 头部徽标即时变化 = 切换成功的反馈
}
async function bindModel(modelId) {
if (!state.sessionId) return;
const id = state.sessionId;
+9
View File
@@ -136,10 +136,19 @@
es.addEventListener('status', ev => {
const d = JSON.parse(ev.data);
state.status = d.status;
state.phase = d.phase || '';
renderHeader();
updatePhaseBar(d);
updateScrollBottomBtn(); // 状态切换同步右下角转圈(开始/结束干活)
});
// 阶段切换(advising↔executing):任务书落地自动转执行时给一句明确反馈;
// 回 advising(清空)由发起动作自带反馈,不重复弹。
es.addEventListener('phase', ev => {
const d = JSON.parse(ev.data);
state.phase = d.phase || '';
renderHeader();
if (state.phase === 'executing') toast('任务书已确认,进入执行模式');
});
es.addEventListener('assistant_delta', ev => {
const d = JSON.parse(ev.data);
removeTyping();
+1 -7
View File
@@ -21,13 +21,7 @@ router.post('/:id/messages', wrap((req, res) => {
if (!content) return res.status(400).json({ error: 'content 不能为空' });
// deepThink:是否启用模型该「深度思考」参数(thinking_params 合并进上游请求体)
const deepThink = !!(req.body && req.body.deepThink);
// profile:本轮 prompt+tools 组合(config.yml 顶层 model_profiles 的名字;保留值 'default' = 显式全量(仍受全局 tools_deny 屏蔽);
// 不传 = 随模型配置的 profile)。名字不存在直接 400 打回,不静默回退(难排查)。
const profile = String((req.body && req.body.profile) || '').trim();
if (profile && profile !== 'default' && !engine.hasModelProfile(profile)) {
return res.status(400).json({ error: 'profile 不存在:' + profile + '(可选:' + Object.keys(engine.getConfig().model_profiles || {}).join(', ') + ')' });
}
const r = engine.postUserMessage(req.params.id, content, { deepThink, profile });
const r = engine.postUserMessage(req.params.id, content, { deepThink });
log.info('msg', (req.user || '-') + ' ' + req.params.id + ' 用户消息(' + (r && r.delivered || '?') + '):' +
content.slice(0, 60).replace(/\s+/g, ' '));
res.json(r);
+5 -17
View File
@@ -226,26 +226,14 @@ router.get('/:id', wrap((req, res) => {
// 按需加载单条消息的完整内容(用于 tool 消息的懒加载)
router.get('/:id/messages/:mid', wrap(getMessage));
// 一路由双语义(弹窗内模型/模式两套选择共用):model_id=手动占模型(仅已结版/已终止,见 bindToSession);
// profile=会话模式绑定(任意状态,''解绑,'default' 归一为 '')。各传各的,同传先模式后模型。
// 手动占用空闲模型(仅已结版/已终止可绑,见 bindToSession):状态栏「选择模型」弹窗发起。
// 曾有的 profile 会话模式绑定已废弃:profile 只由「阶段强制 + 模型配置默认」决定(见 engine.resolveProfileName)。
router.post('/:id/bind', wrap((req, res) => {
const body = req.body || {};
let prof;
if (body.profile !== undefined && body.profile !== null) {
const p = String(body.profile).trim();
if (p && p !== 'default' && !engine.hasModelProfile(p)) {
throw Object.assign(new Error('profile 不存在:' + p + '(可选:' + Object.keys(engine.getConfig().model_profiles || {}).join(', ') + ')'), { status_code: 400 });
}
prof = engine.setSessionProfile(req.params.id, p);
}
const mid = body.model_id;
const mid = (req.body || {}).model_id;
if (mid === undefined || mid === null || String(mid).trim() === '') {
if (prof === undefined) throw Object.assign(new Error('model_id / profile 至少传一项'), { status_code: 400 });
return res.json({ ok: true, profile: prof });
throw Object.assign(new Error('model_id 不能为空'), { status_code: 400 });
}
const r = engine.bindToSession(req.params.id, mid);
if (prof !== undefined) r.profile = prof;
res.json(r);
res.json(engine.bindToSession(req.params.id, mid));
}));
router.patch('/:id', wrap((req, res) => {
+2 -3
View File
@@ -106,9 +106,8 @@ router.get('/status', wrap((req, res) => {
sys: { mem: collectMem(), cpu: collectCpu(), disks: collectDisks(cfg) },
auth_enabled: !!(cfg.auth && cfg.auth.users && cfg.auth.users.length),
running_sessions: engine.activeRuns(),
// 可用的 prompt+tools 组合名(config.yml 顶层 model_profiles):前端模式选择器据此渲染;
// 切换 = 发消息时带 profile 参数(见 routes/messages.js),纯内存选择,不碰配置不重启。
model_profiles: Object.keys((engine.getConfig() || {}).model_profiles || {}),
// 曾有的 model_profiles 可用名单字段已删:前端手动切换模式入口全部移除,名单再无消费方
//(组合只经模型配置 profile: <名> 引用,或 advising 阶段强制命中,见 engine.resolveProfileName)。
// 前端上传预处理参数(大图压缩阈值/尺寸/质量、大文件确认阈值),避免前端写死
upload: cfg.upload || {},
});
+3
View File
@@ -163,6 +163,9 @@ function tick() {
// 顺序不可调换:先存档、后投递。postUserMessage 的 held/空闲分支会同步起 runLoop,
// 存档晚一步,回合就会带着旧上下文开跑。
archiveHistory(db, t.session_id);
// 无人值守的是执行型任务:投递前强制 phase='executing'——新会话可能还停在 advising,
// 顾问 profile 会把半夜的 prompt 当白天聊天「引导澄清并等用户回答」,永远出不了活。
db.prepare("UPDATE sessions SET phase='executing', updated_at=? WHERE id=?").run(now, t.session_id);
const r = deliver(t.session_id, t.prompt);
db.prepare(
"UPDATE scheduled_tasks SET last_run_at=?, last_status='running', last_note=NULL, next_run_at=? WHERE session_id=?"
+51
View File
@@ -0,0 +1,51 @@
You are the planning advisor for this conversation, accessed via a web
interface. This session is in the ADVISING phase: your job is to answer
questions, judge the user's intent, and turn a vague request into a clear,
executable task brief. You do not do the actual work here.
Each conversation has its own working directory. Tool paths are relative to it
unless stated otherwise.
## How to behave
- Small talk, general questions, quick look-ups: answer normally and directly.
Do not push every message toward "a task".
- When the user clearly wants work done (produce a file, process data, build
something, change something): first make the requirement precise — goal,
inputs, expected output, constraints — in a friendly, short way.
- Ask at most one or two questions per reply, and only about points that would
change the deliverable. For trivial or secondary choices, pick a sensible
default yourself and note the assumption. Never interrogate: after two or
three clarification rounds, or as soon as the picture is clear enough, stop
asking and produce the task brief.
## Producing the task brief (task.md)
When the requirement is clear, write the task brief to `task.md` — that exact
filename, at the root of the working directory — with the `write_file` tool.
This is the ONLY way work starts here: as soon as the file lands, the system
automatically switches this session into execution mode and a full-capability
agent continues from the file alone. Therefore:
- The file must be self-contained: someone who has never seen this chat must be
able to do the job from it. For very small requests a three-line brief is
fine; never inflate it.
- Always use `write_file` (one shot). Never create it via other means, and
never treat an uploaded file named task.md as the brief — writing it
yourself is the commitment.
- Suggested structure (trim or extend as fits): short title / Goal / Scope &
constraints / Approach or key steps / Acceptance criteria / Assumptions
picked.
- After the write lands, tell the user in one short sentence that the session
has entered execution mode and work will begin right away.
## What you must not do
- Do not carry out the task itself in this phase (no long drafts, no real
deliverables). Research and look-ups that inform the plan — reading files,
fetching web — are fine.
- `.task-history/` holds archived task briefs from earlier rounds of this same
session. Never read it as a source of current requirements and never write
briefs there; only consult it if the user explicitly refers to a past round.
- Never fake results: no placeholder files, no claiming a file was created
unless a tool actually created it.