修复模型占用的问题

This commit is contained in:
2026-09-21 11:08:43 +08:00
parent 1fd4fa81a0
commit ae28587c02
5 changed files with 63 additions and 34 deletions
+3
View File
@@ -120,6 +120,9 @@ function initDb(dbPath) {
// 迁移:旧库补 held_at 列(held 保持租约起始时间)
const cols = db.prepare('PRAGMA table_info(sessions)').all();
if (!cols.some(c => c.name === 'held_at')) db.exec('ALTER TABLE sessions ADD COLUMN held_at INTEGER');
// 迁移:model_slot 记会话占用的具体池槽位(「模型id#key下标」,同模型多 key 并行占用),
// model_id 仍存模型 id 供展示/统计(见 engine.bindModel)。
if (!cols.some(c => c.name === 'model_slot')) db.exec('ALTER TABLE sessions ADD COLUMN model_slot TEXT');
// 迁移:last_model_id 记住会话最近用过的模型,释放后新消息优先回绑(见 engine.dispatchQueued)
if (!cols.some(c => c.name === 'last_model_id')) {
db.exec('ALTER TABLE sessions ADD COLUMN last_model_id TEXT');
+33 -17
View File
@@ -157,20 +157,23 @@ function syncModelPool() {
const stmt = db.prepare(
'INSERT INTO model_pool (id, display_name, is_busy, current_session_id) VALUES (?,?,0,NULL) ON CONFLICT(id) DO UPDATE SET display_name=excluded.display_name'
);
// 池槽位按 key 拆分:cfg.models 里同模型每个 key 一条副本,槽位 id = 「模型id#key下标」,
// 一个空闲 key 一个槽位 → 同模型可被多会话并行占用(见 slotBase/freeSlotFor)。
// enable:false 的模型不进池:分配/绑定均按池取模型,天然跳过禁用项(与其他模型配置一致,重启生效)。
const slotId = m => m.id + '#' + m.key_index;
const enabled = cfg.models.filter(m => m.enable !== false);
for (const m of enabled) stmt.run(m.id, m.display_name);
// 清理配置中已删除/已禁用的模型
const ids = enabled.map(m => m.id);
for (const m of enabled) stmt.run(slotId(m), m.display_name);
// 清理配置中已删除/已禁用的模型(含旧版按模型 id 建的行,重启后自动重建为槽位行)
const ids = enabled.map(slotId);
for (const row of db.prepare('SELECT id FROM model_pool').all()) {
if (!ids.includes(row.id)) db.prepare('DELETE FROM model_pool WHERE id = ?').run(row.id);
}
// 进程重启后:释放所有绑定、把 active 会话退回队列;held 会话直接结版(释放)。
// 禁用模型同样走这里收尾:重启后池里已无它,绑过它的会话被退回队列/结版,后续重新分配启用中的模型。
db.prepare('UPDATE model_pool SET is_busy = 0, current_session_id = NULL').run();
db.prepare("UPDATE sessions SET status='completed', completed_at=?, held_at=NULL, model_id=NULL WHERE status='held'").run(now());
db.prepare("UPDATE sessions SET status='completed', completed_at=?, held_at=NULL, model_id=NULL, model_slot=NULL WHERE status='held'").run(now());
for (const s of db.prepare("SELECT id FROM sessions WHERE status = 'active'").all()) {
db.prepare("UPDATE sessions SET status='queued', model_id=NULL, updated_at=? WHERE id=?").run(now(), s.id);
db.prepare("UPDATE sessions SET status='queued', model_id=NULL, model_slot=NULL, updated_at=? WHERE id=?").run(now(), s.id);
enqueue(s.id);
}
// 兑底:queued 会话必须在队列中
@@ -182,6 +185,18 @@ function freeModel() {
return db.prepare('SELECT * FROM model_pool WHERE is_busy = 0 ORDER BY id').get();
}
// 槽位 id(「模型id#key下标」)→ 模型 id(「平台/模型」)。对外一律用模型 id,槽位只在池内/取 key 时用。
function slotBase(id) { return String(id || '').split('#')[0]; }
// 找指定模型(传模型 id 或槽位 id 均可)的任意空闲槽位:同模型多个空闲 key 时任取其一。
// 用范围比较而非 LIKE,避免模型 id 里的 _/% 被当通配符。
function freeSlotFor(modelId) {
const base = slotBase(modelId);
if (!base) return null;
return db.prepare('SELECT * FROM model_pool WHERE id >= ? AND id < ? AND is_busy = 0 ORDER BY id LIMIT 1')
.get(base + '#', base + '#\uffff');
}
// 会话绑定的模型是否支持 vision(图片回传);决定 read_file 读图行为(见 tools/executor.js)。
function modelVision(session) {
const m = session.model_id && (cfg.models || []).find(x => x.id === session.model_id);
@@ -204,14 +219,15 @@ function dequeue(sessionId) {
function bindModel(session, model, status) {
const st = status === 'held' ? 'held' : 'active';
db.prepare('UPDATE model_pool SET is_busy = 1, current_session_id = ? WHERE id = ?').run(session.id, model.id);
// last_model_id 不随释放清除:会话再次需要模型时优先回绑(见 pickModelFor)
db.prepare("UPDATE sessions SET status=?, model_id=?, last_model_id=?, held_at=?, updated_at=? WHERE id=?")
.run(st, model.id, model.id, st === 'held' ? now() : null, now(), session.id);
// model_id/last_model_id 存模型 id(展示/统计/回绑语义不变),model_slot 记绑定的具体 key 槽位;
// last_model_id 不随释放清除:会话再次需要模型时优先回绑同模型的空闲 key(见 pickModelFor)
db.prepare("UPDATE sessions SET status=?, model_id=?, model_slot=?, last_model_id=?, held_at=?, updated_at=? WHERE id=?")
.run(st, slotBase(model.id), model.id, slotBase(model.id), st === 'held' ? now() : null, now(), session.id);
}
function releaseModel(sessionId) {
db.prepare('UPDATE model_pool SET is_busy = 0, current_session_id = NULL WHERE current_session_id = ?').run(sessionId);
db.prepare('UPDATE sessions SET model_id = NULL, updated_at = ? WHERE id = ?').run(now(), sessionId);
db.prepare('UPDATE sessions SET model_id = NULL, model_slot = NULL, updated_at = ? WHERE id = ?').run(now(), sessionId);
}
// 手动为已结版/已终止的会话指定模型:选定的模型必须空闲。
@@ -224,7 +240,8 @@ function bindToSession(sessionId, modelId) {
if (s.status !== 'completed' && s.status !== 'cancelled') {
throw Object.assign(new Error('仅已完成/已终止的会话可手动选择模型'), { status_code: 409 });
}
const model = db.prepare('SELECT * FROM model_pool WHERE id = ? AND is_busy = 0').get(String(modelId || ''));
// 传模型 id:绑到该模型任意一个空闲 key 槽位;全部槽位被占才算「正被占用」
const model = freeSlotFor(String(modelId || ''));
if (!model) throw Object.assign(new Error('模型不存在或正被占用'), { status_code: 409 });
touch(sessionId, { cancelled_at: null, completed_at: null, held_at: null });
const pending = hasPendingUser(sessionId);
@@ -232,7 +249,7 @@ function bindToSession(sessionId, modelId) {
emitStatus(sessionId);
log.info('model', sessionId + ' 手动绑定模型 ' + model.id);
if (pending) runLoop(sessionId);
return { ok: true, model_id: model.id };
return { ok: true, model_id: slotBase(model.id) };
}
// 是否还有待回应的新用户消息(最后一条非 tool 消息是 user)。
@@ -249,7 +266,7 @@ function hasPendingUser(sessionId) {
// 被占用(或从未绑过/已从配置删除)则按 id 序取任意空闲模型。
function pickModelFor(session) {
if (session.last_model_id) {
const pref = db.prepare('SELECT * FROM model_pool WHERE id = ? AND is_busy = 0').get(session.last_model_id);
const pref = freeSlotFor(session.last_model_id);
if (pref) return pref;
}
return freeModel();
@@ -420,7 +437,7 @@ function finalize(sessionId, run) {
function maybeGenerateTitle(sessionId, s) {
try {
if (s.title) return;
const modelId = s.model_id;
const modelId = s.model_slot || s.model_id; // 用绑定槽位精确到 key
if (!modelId || titling.has(sessionId)) return;
titling.add(sessionId);
const messages = titleMessages(loadHistory(sessionId), cfg.agent.language);
@@ -672,7 +689,8 @@ async function streamAssistant(sessionId, run, session, messages, tools) {
const tcDbg = { starts: 0, frags: 0, chars: 0 };
try {
const handleSseMeta = makeSseMetaHandler(sessionId);
const result = await callModel(cfg, session.model_id, messages, tools, {
// 用绑定槽位(含 key 下标)精确取到会话占用的那个 key 的配置
const result = await callModel(cfg, session.model_slot || session.model_id, messages, tools, {
signal: run.abortController.signal,
shouldCancel: () => run.cancelled,
onText: delta => bus.emit(sessionId, 'assistant_delta', { text: delta }),
@@ -793,9 +811,7 @@ function createSession(title, preferModelId, assistantType, user) {
"INSERT INTO sessions (id, title, status, phase, model_id, assistant_type, user, created_at, updated_at) VALUES (?,?,'queued','planning',NULL,?,?,?,?)"
).run(id, title || '', assistantType || 'secretary', user || '', now(), now());
// 指定了模型且它恰好空闲 → 直接绑定,跳过排队;否则回退到 FIFO 队列
const prefer = preferModelId
? db.prepare('SELECT * FROM model_pool WHERE id = ? AND is_busy = 0').get(preferModelId)
: null;
const prefer = preferModelId ? freeSlotFor(preferModelId) : null;
if (prefer) {
// 新建时指定模型 = 仅预留(此时还没有任何消息):先绑成 held 占住模型,
// 用户发首条消息后再转 active 开跑
+4 -2
View File
@@ -340,8 +340,10 @@ async function callModel(cfg, modelId, messages, tools, options) {
if (opts.signal.aborted) controller.abort();
else opts.signal.addEventListener('abort', () => controller.abort());
}
// modelId = 内部唯一键「平台名/模型id」;发给上游的模型名用 mid(原始 id)。
const modelCfg = (cfg.models || []).find(m => m.id === modelId);
// modelId = 池槽位 id「平台名/模型id#key下标」(精确到会话占用的 key);兼容传纯模型 id(取第一个 key 副本)。
// 发给上游的模型名用 mid(原始 id)。
const all = cfg.models || [];
const modelCfg = all.find(m => m.id + '#' + m.key_index === modelId) || all.find(m => m.id === modelId);
if (!modelCfg || !modelCfg.url) throw new Error('模型未在配置中定义或缺少 url: ' + modelId);
const body = {
+11 -14
View File
@@ -433,30 +433,27 @@
}
// 平台颜色盘(循环使用)
const DOT_COLORS = ['#3B82F6','#10B981','#F59E0B','#EF4444','#8B5CF6','#EC4899','#06B6D4','#F97316'];
// 按平台分组;models 全平台共用,一个会话占用一个 key → 平台空闲 key 数 = key_count - 占用模型数
// 按平台分组;/api/models 已按模型聚合槽位:slots_total/slots_busy = 该模型的 key 总数/被占数,
// is_busy 仅在全部 key 被占时为真(同模型还剩空闲 key 就仍可再选)。
const platMap = new Map();
for (const m of rows) {
const pk = m.platform || '';
if (!platMap.has(pk)) {
platMap.set(pk, { name: pk || '未知平台', keyCount: m.key_count || 0, models: [], busyCount: 0 });
platMap.set(pk, { name: pk || '未知平台', keyCount: m.key_count || 0, models: [] });
}
const g = platMap.get(pk);
g.models.push(m);
if (m.is_busy) g.busyCount++;
platMap.get(pk).models.push(m);
}
const groups = [];
for (const g of platMap.values()) {
g.freeKeys = Math.max(0, g.keyCount - g.busyCount);
groups.push(g);
}
// 可选 = 模型自身空闲 且 该平台还有空闲 key;统计可用数供底部提示
const groups = [...platMap.values()];
// 可选 = 模型还有空闲 key 槽位;统计可用数供底部提示
let avail = 0;
for (const g of groups) for (const m of g.models) if (!m.is_busy && g.freeKeys > 0) avail++;
for (const g of groups) for (const m of g.models) if (!m.is_busy) avail++;
list.innerHTML = groups.map((g, gi) => {
const dotColor = DOT_COLORS[gi % DOT_COLORS.length];
const itemHtml = g.models.map(m => {
const disabled = !!m.is_busy || g.freeKeys <= 0;
const title = m.is_busy ? ' 占用中' : (g.freeKeys <= 0 ? ' 无空闲 Key' : '');
const total = m.slots_total || g.keyCount || 1;
const free = total - (m.slots_busy || 0);
const disabled = !!m.is_busy;
const title = m.is_busy ? ' 占用中' : ((m.slots_busy || 0) > 0 ? ' ' + free + '/' + total + ' key 空闲' : '');
return '<div class="msw-item' + (disabled ? ' disabled' : '') + '"' +
(disabled ? '' : ' onclick="bindModel(\'' + esc(m.id) + '\')"') + '>' +
'<div class="msw-radio"></div>' +
+12 -1
View File
@@ -57,7 +57,18 @@ app.use('/api/system', require('./routes/system'));
// model_pool 表只有 id/display_name/占用态,会话页「选择模型」弹窗需要按平台分组展示。
// 配置里新增但重启前未进池的模型不在此返回(池才是运行时真相)。
app.get('/api/models', (req, res) => {
const rows = db.prepare('SELECT id, display_name, is_busy, current_session_id FROM model_pool ORDER BY id').all();
// 池行是按 key 拆分的槽位(id=「模型id#下标」):按模型聚合为一行对外展示,
// is_busy = 全部槽位被占;附 slots_total/slots_busy 供前端显示剩余空闲 key。
const raw = db.prepare('SELECT id, display_name, is_busy, current_session_id FROM model_pool ORDER BY id').all();
const byBase = new Map();
for (const r of raw) {
const base = r.id.split('#')[0];
let g = byBase.get(base);
if (!g) { g = { id: base, display_name: r.display_name, is_busy: 0, slots_total: 0, slots_busy: 0, sessions: [] }; byBase.set(base, g); }
g.slots_total++;
if (r.is_busy) { g.slots_busy++; if (r.current_session_id) g.sessions.push(r.current_session_id); }
}
const rows = [...byBase.values()].map(g => Object.assign(g, { is_busy: g.slots_busy >= g.slots_total ? 1 : 0, current_session_id: g.sessions.join(',') }));
const stats = engine.modelUsageStats();
// 配置视图:模型唯一键 → 平台/原始 id/vision;平台名 → key 数(cfg.models 含 key 副本,不能直接拿来用)
const cfgNow = engine.getConfig();