Files
ST-Amily2-Chat-Optimisation/glossary/GT_bindings.js
Jenkins CI 0d7e3b799e release: v2.2.6 [2026-06-13 01:02:05]
### 新功能
- **翰林院向量化质量升级**:
  - **边界感知切块**:替换四个来源(聊天记录/小说/世界书/手动)的纯字符硬切——优先在段落边界断开,其次句末标点(含中文引号闭合),极端长串才硬切;句子/对话不再被拦腰截断,embedding 质量同步受益。仅影响新录入,已有向量无需重建
  - **注入时序重排**:检索结果注入提示词前按时序重排(聊天记录按楼层、小说按卷/章/节——中文数字章节号可解析),rerank 只决定"选哪些块",不再决定呈现顺序;修复"不打不相识的剧情之后紧跟关系亲密"这类因按相关度排序导致的认知时间错乱
  - **断层提示**:聊天记录相邻块楼层跳跃时自动插入"与上文相隔约 N 楼,并非连续发生"提示行,消除中间剧情缺失造成的割裂感
  - **时间标识**:新录入的聊天记录块在来源标识中带上消息发送时间(ST 向量存储不持久化元数据,时间必须写入块文本才能在检索后取回;旧格式块兼容解析)
- **记忆块工作流(memory-blocks)**:剧情优化新增"自定义记忆块"体系——占位符驱动的并发工作流框架
  - 在剧情优化面板「匹配替换 (sulv)」下方可增删自定义块:每个块定义一个占位符,执行剧情优化时主/拦截提示词中的占位符会被块的产出替换
  - **静态块**:直接输出固定内容;**AI 调用块**:用所选 API 功能槽独立请求一次,把回复(或其中指定 `<标签>` 的内容)作为替换值
  - 原有 sulv1-4 速率占位符迁入同一框架,行为与旧版逐字节一致
  - 块定义为纯 JSON、随设置持久化,为后续导入导出与战斗系统接入预留扩展点
  - 框架层新增**顺序拼接式 Chain**(`composeChain`):与占位符替换并列的第二种组合范式——同链的块并发执行后按 `order` 排序、以 `separator` 拼接并可选 `header/footer` 包裹,产出一个完整注入块;为记忆注入合成块与战斗系统"底部战报块"预留的承载结构,本版本暂无 UI 入口
- **API 连接配置**:
  - 角色世界书(cwb)与一键生卡(autoCharCard)纳入旧配置自动迁移:老用户首次加载会把旧 URL / Key / 模型自动迁移为连接配置并分配槽位(一键生卡仅在规划者与执行者配置一致或规划者为空时迁移,避免悄悄改变行为)
  - **profile 已分配时参数控件 informational 化**:主面板 / 并发剧情优化 / 角色世界书 / 术语表的温度、maxTokens 控件在槽位分配 profile 后自动禁用并显示"由连接配置控制"提示,消除"改了没效果"的用户陷阱
  - **profile 状态卡新增"本设备无 Key"警示**:API Key 仅保存在最初填写它的设备/浏览器上(安全设计,不随云端设置同步),换设备后状态卡会直接亮出警示徽标,不必等到调用报错才发现
### 修复
- **独立聊天记忆从摆设变真功能(原作遗留坑)**:此前向量数据"随卡不随聊天"——开启"独立聊天记忆"后录入仍存进角色库、查询却去查一个从未被写入过的聊天集合、计数恒为 0,整体静默失效。现已重构为聊天级分桶:
  - 独立模式下,聊天记录类向量按当前聊天隔离存储与检索,同一张卡开多个聊天(不同剧情线)的记忆互不污染
  - 小说 / 世界书 / 手动录入属于"知识",仍随角色卡跨聊天共享;全局库不受影响
  - 知识管理列表为聊天专属库显示"聊天级"徽标;聊天级库禁止移动到全局
  - 统一模式(默认关闭独立记忆)的存量数据与行为完全不变
  - 已知限制:聊天专属记忆跟随聊天文件,重命名聊天文件会使其失联(与 ST 官方向量扩展同等限制)
- **超级排序截断顺序修正**:开启"超级排序"时,时序重排发生在 top_n 截断之前,导致保留的是"时序最早"而非"最相关"的块,检索结果长期偏向最旧的聊天记录。现改为先按相关度截取 top_n、再做时序排序
- **翰林院向量化失败("向量化块数量不识别"反馈)**:
  - 一次性清洗 profile-sync 历史污染:`retrieval/rerank.apiKey` 中的掩码占位符在持久层根治(此前仅读取侧防御);`apiEndpoint` / `rerank.apiMode` 的非法值(如被旧版写入的空字符串)归一化为 `custom`
  - 修复 `apiEndpoint` 为空/非法时请求被硬定向到 `api.openai.com`、无视用户自定义 URL 的问题(CSP 拦截 / 401 的元凶)
  - 修复**本地代理(LM Studio/Ollama)模式**自始就缺少 URL 分支、同样被错误定向到 openai.com 的问题
  - API 模式下拉补全 `OpenAI 官方` / `Azure` 选项;默认 API 模式改为 `custom`(与默认 URL 配套),新用户不再因选项缺失导致首次保存写入空值
  - profile-sync 给下拉框赋不存在选项值的污染源头修复(影响所有模块面板,不止翰林院)
- **Rerank "API Key 未提供"报错升级**:当原因是"连接配置在本设备没有可用 Key"时,报错会直接说明 Key 的设备本地性并指引到 API 连接配置重新填写(向量化 Google 直连、获取模型列表同步处理)
- **旧配置迁移**:一键生卡迁移时排除掩码占位符,避免把历史污染的假 Key 迁入新连接配置
- **超级记忆稳定性专项**(针对"工作不大稳定"反馈,4 处根因一次修复):
  - **切聊天竞态污染**:CHAT_CHANGED 时超级记忆立即全量同步,而表格系统延迟 100ms 才加载新聊天的表格,导致【旧聊天】的表格内容被写进【新角色】的记忆世界书;两边表名不同时旧表条目无 GC 兜底会**永久残留**("记忆串台"元凶)。现 CHAT_CHANGED 只确保世界书存在,新状态同步交由 `loadTables()` 完成后的自动推送,单次且时序正确
  - **死代码双轨存储拆除**:`saveStateToMetadata` / `tryRestoreStateFromMetadata` 把表格状态写到 `msg.metadata`——该字段非 ST 持久化位(同 v2.2.5 二次填表修过的坑),写入即蒸发、恢复永远为空,且每次同步还白调一次 `saveChat()`。整条链路删除,表格状态唯一信源为表格系统的 `msg.extra.amily2_tables_data`
  - **`awaitSync()` 穿透**:同步队列正忙时 `pushUpdate` 会用一个立即 resolve 的空 Promise 覆盖 `_syncPromise`,Pipeline Stage 4 等待形同虚设、后续阶段在同步未完成时被放行。现忙时不覆盖,正在运行的 drain 循环自然吃掉新入队项
  - **开关打开不生效**:启动时若总开关为关,初始化早退且不注册监听器;此后在 UI 勾选开关只写设置,超级记忆直到刷新页面前都是死的。现勾选即触发初始化(幂等)
  - 附带:`forceSyncAll` 的表格角色推断改为复用 `events-schema.inferTableRole`,消除两处重复逻辑漂移风险;每次切聊天的双倍全量同步(restore 路径一次 + 显式一次)随死代码移除归一
### 重构
- 表格核心 `manager.js` 瘦身(约 1050 → 600 行):19 个 UI 突变操作拆分至 `actions/ui-mutations.js`,SuperMemory 事件分发拆分至 `events-dispatch.js`;全部经 re-export 保持兼容,外部调用路径零改动
- 角色世界书最后 2 处散乱的厂商 URL 判断迁移至 `detectVendor` 统一入口,业务路径上不再有硬编码的 URL substring 判断
2026-06-13 01:02:05 +08:00

725 lines
29 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { extension_settings, getContext } from "/scripts/extensions.js";
import { saveSettingsDebounced, eventSource, event_types } from "/script.js";
import { extensionName } from "../utils/settings.js";
import { configManager } from '../utils/config/ConfigManager.js';
import { SENSITIVE_KEYS } from '../utils/config/sensitive-keys.js';
import { safeLorebooks, safeLorebookEntries, safeUpdateLorebookEntries } from '../core/tavernhelper-compatibility.js';
import { testSybdApiConnection, fetchSybdModels } from '../core/api/SybdApi.js';
import { handleFileUpload, processNovel } from './index.js';
import { reorganizeEntriesByHeadings, loadDatabaseFiles } from './executor.js';
import { SETTINGS_KEY as PRESET_SETTINGS_KEY } from '../PresetSettings/config.js';
import { escapeHTML } from '../utils/utils.js';
import { watchProfileSliderGuard } from '../ui/profile-slider-guard.js';
const moduleState = {
selectedWorldBook: '',
};
function updateAndSaveSetting(key, value) {
if (!extension_settings[extensionName]) {
extension_settings[extensionName] = {};
}
extension_settings[extensionName][key] = value;
saveSettingsDebounced();
console.log(`[Amily2-术语表] 设置项 '${key}' 已更新为: ${JSON.stringify(value)}`);
}
function loadSettingsToUI() {
const settings = extension_settings[extensionName] || {};
const container = document.getElementById('amily2_glossary_panel');
if (!container) return;
const inputs = container.querySelectorAll('[data-setting-key]');
inputs.forEach(target => {
const key = target.dataset.settingKey;
// 敏感字段从 configManagerlocalStorage读取其余从 extension_settings 读取
const value = SENSITIVE_KEYS.has(key) ? configManager.get(key) : settings[key];
if (value === undefined || value === null || value === '') {
if (!SENSITIVE_KEYS.has(key)) {
let defaultValue;
if (target.type === 'checkbox') {
defaultValue = target.checked;
} else if (target.type === 'range') {
defaultValue = target.dataset.type === 'float' ? parseFloat(target.value) : parseInt(target.value, 10);
} else {
defaultValue = target.value;
}
updateAndSaveSetting(key, defaultValue);
}
return;
};
if (target.type === 'checkbox') {
target.checked = value;
} else if (target.type === 'range') {
target.value = value;
const valueDisplay = document.getElementById(`${target.id}_value`);
if (valueDisplay) valueDisplay.textContent = value;
}
else {
target.value = value;
}
});
const sybdContent = document.getElementById('amily2_sybd_content');
if (sybdContent) {
sybdContent.classList.remove('amily2-content-hidden');
}
const apiModeSelect = document.getElementById('amily2_sybd_api_mode');
if (apiModeSelect) {
updateConfigVisibility(apiModeSelect.value);
}
}
function bindAutoSaveEvents() {
const container = document.getElementById('amily2_glossary_panel');
if (!container) return;
const handler = (event) => {
const target = event.target;
const key = target.dataset.settingKey;
if (!key) return;
let value;
const type = target.dataset.type || 'string';
if (target.type === 'checkbox') {
value = target.checked;
} else {
value = target.value;
}
switch (type) {
case 'integer': value = parseInt(value, 10); break;
case 'float': value = parseFloat(value); break;
case 'boolean': value = (typeof value === 'boolean') ? value : (value === 'true'); break;
}
// 敏感字段API Key经 configManager 写入 localStorage
if (SENSITIVE_KEYS.has(key)) {
configManager.set(key, value);
} else {
updateAndSaveSetting(key, value);
}
if (key === 'sybdApiMode') {
updateConfigVisibility(value);
}
if (target.type === 'range') {
document.getElementById(`${target.id}_value`).textContent = value;
}
};
container.addEventListener('change', handler);
container.addEventListener('input', (event) => {
if (event.target.type === 'range') handler(event);
});
}
function updateConfigVisibility(mode) {
const compatibleConfig = document.getElementById('amily2_sybd_compatible_config');
const presetConfig = document.getElementById('amily2_sybd_preset_config');
if (mode === 'sillytavern_preset') {
compatibleConfig.style.display = 'none';
presetConfig.style.display = 'block';
loadTavernPresets();
} else {
compatibleConfig.style.display = 'block';
presetConfig.style.display = 'none';
}
}
async function loadTavernPresets() {
const select = document.getElementById('amily2_sybd_tavern_profile');
if (!select) return;
const currentValue = extension_settings[extensionName]?.sybdTavernProfile || '';
select.innerHTML = '<option value="">-- 加载中 --</option>';
try {
const context = getContext();
const tavernProfiles = context.extensionSettings?.connectionManager?.profiles || [];
select.innerHTML = '<option value="">-- 请选择预设 --</option>';
if (tavernProfiles.length > 0) {
tavernProfiles.forEach(profile => {
if (profile.api && profile.preset) {
const option = new Option(profile.name || profile.id, profile.id);
select.add(option);
}
});
select.value = currentValue;
} else {
select.innerHTML = '<option value="">未找到可用预设</option>';
}
} catch (error) {
console.error('[Amily2-术语表] 加载SillyTavern预设失败:', error);
select.innerHTML = '<option value="">加载失败</option>';
}
}
function bindManualActionEvents() {
const testBtn = document.getElementById('amily2_sybd_test_connection');
if (testBtn) {
testBtn.addEventListener('click', async () => {
const originalHtml = testBtn.innerHTML;
testBtn.disabled = true;
testBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 测试中';
await testSybdApiConnection();
testBtn.disabled = false;
testBtn.innerHTML = originalHtml;
});
}
const fetchBtn = document.getElementById('amily2_sybd_fetch_models');
const modelSelect = document.getElementById('amily2_sybd_model_select');
const modelInput = document.getElementById('amily2_sybd_model');
if (fetchBtn && modelSelect && modelInput) {
fetchBtn.addEventListener('click', async () => {
const originalHtml = fetchBtn.innerHTML;
fetchBtn.disabled = true;
fetchBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 获取中';
try {
const models = await fetchSybdModels();
if (models && models.length > 0) {
modelSelect.innerHTML = '<option value="">-- 请选择模型 --</option>';
models.forEach(model => {
const option = new Option(model.name || model.id, model.id);
modelSelect.add(option);
});
modelSelect.style.display = 'block';
modelInput.style.display = 'none';
toastr.success(`成功获取 ${models.length} 个模型`);
} else {
toastr.warning('未获取到任何模型');
}
} catch (error) {
toastr.error(`获取模型失败: ${error.message}`);
} finally {
fetchBtn.disabled = false;
fetchBtn.innerHTML = originalHtml;
}
});
modelSelect.addEventListener('change', () => {
const selectedModel = modelSelect.value;
if (selectedModel) {
modelInput.value = selectedModel;
modelInput.dispatchEvent(new Event('change', { bubbles: true }));
}
});
}
}
async function renderWorldBookEntries() {
const container = document.getElementById('world-book-entries-display');
if (!container) return;
const selectedBook = moduleState.selectedWorldBook;
if (!selectedBook) {
container.innerHTML = '<p style="text-align:center;">请先在“小说处理”标签页中选择一个世界书。</p>';
return;
}
container.innerHTML = '<p style="text-align:center;"><i class="fas fa-spinner fa-spin"></i> 正在加载条目...</p>';
try {
const allEntries = await safeLorebookEntries(selectedBook);
let managedEntries = allEntries.filter(e => e.comment?.startsWith('[Amily2小说处理]'));
if (managedEntries.length === 0) {
container.innerHTML = '<p style="text-align:center;">未找到由小说处理功能生成的条目。</p>';
return;
}
container.innerHTML = '';
const summaryEntries = managedEntries.filter(e => e.comment.replace('[Amily2小说处理]', '').trim().startsWith('章节内容概述'));
const otherEntries = managedEntries.filter(e => !e.comment.replace('[Amily2小说处理]', '').trim().startsWith('章节内容概述'));
const sortedEntries = otherEntries.concat(summaryEntries);
sortedEntries.forEach(entry => {
const entryElement = document.createElement('div');
entryElement.className = 'world-book-entry-item';
entryElement.dataset.entryId = entry.uid;
const title = entry.comment.replace('[Amily2小说处理]', '').trim();
const renderContent = (content) => {
const trimmedContent = content.trim();
if (trimmedContent.startsWith('graph') || trimmedContent.startsWith('flowchart')) {
try {
const lines = trimmedContent.split('\n').map(l => l.trim()).filter(l => l.includes('-->') || l.includes('--'));
let body = '';
lines.forEach(line => {
if (line.startsWith('flowchart')) return;
let source = '', rel = '', target = '';
let match = line.match(/(.+?)\s*--\s*"(.*?)"\s*-->(.+)/);
if (match) {
[source, rel, target] = [match[1], match[2], match[3]];
} else {
match = line.match(/(.+?)\s*-->\s*\|(.*?)\|(.+)/);
if (match) {
[source, rel, target] = [match[1], match[2], match[3]];
} else {
match = line.match(/(.+?)\s*-->(.+)/);
if (match) {
[source, target] = [match[1], match[2]];
rel = '<i>(直接关联)</i>';
}
}
}
if (source && target) {
body += `<tr><td>${escapeHTML(source.trim())}</td><td>${escapeHTML(rel.trim())}</td><td>${escapeHTML(target.trim().replace(';',''))}</td></tr>`;
}
});
return `<table class="table-render"><thead><tr><th>源头</th><th>关系</th><th>目标</th></tr></thead><tbody>${body}</tbody></table>`;
} catch {
return `<pre>${escapeHTML(content)}</pre>`;
}
}
if (trimmedContent.includes('|') && trimmedContent.includes('\n')) {
try {
const rows = trimmedContent.split('\n').filter(row => row.trim() && row.includes('|'));
let header = '';
let body = '';
let isHeaderRow = true;
rows.forEach(rowStr => {
if (rowStr.includes('---')) return;
const cells = rowStr.split('|').filter(c => c.trim()).map(cell => `<td>${escapeHTML(cell.trim())}</td>`).join('');
if (isHeaderRow) {
header += `<tr>${cells.replace(/<td>/g, '<th>').replace(/<\/td>/g, '</th>')}</tr>`;
isHeaderRow = false;
} else {
body += `<tr>${cells}</tr>`;
}
});
return `<table class="table-render"><thead>${header}</thead><tbody>${body}</tbody></table>`;
} catch {
return `<pre>${escapeHTML(content)}</pre>`;
}
}
return `<pre>${escapeHTML(content)}</pre>`;
};
entryElement.innerHTML = `
<div class="entry-header">
<strong class="entry-title">${escapeHTML(title)}</strong>
<div class="entry-actions">
<button class="menu_button primary small_button save-entry-btn" style="display: none;"><i class="fas fa-save"></i> 保存</button>
<button class="menu_button danger small_button cancel-entry-btn" style="display: none;"><i class="fas fa-times"></i> 取消</button>
<button class="menu_button secondary small_button edit-entry-btn"><i class="fas fa-edit"></i> 编辑</button>
</div>
</div>
<div class="entry-content-display">${renderContent(entry.content)}</div>
<div class="entry-content-editor" style="display: none;">
<textarea class="text_pole" style="width: 98%; min-height: 150px;">${escapeHTML(entry.content || '')}</textarea>
</div>
`;
const editBtn = entryElement.querySelector('.edit-entry-btn');
const saveBtn = entryElement.querySelector('.save-entry-btn');
const cancelBtn = entryElement.querySelector('.cancel-entry-btn');
const displayDiv = entryElement.querySelector('.entry-content-display');
const editorDiv = entryElement.querySelector('.entry-content-editor');
const textarea = editorDiv.querySelector('textarea');
const originalContent = entry.content;
editBtn.addEventListener('click', () => {
displayDiv.style.display = 'none';
editorDiv.style.display = 'block';
saveBtn.style.display = 'inline-block';
cancelBtn.style.display = 'inline-block';
editBtn.style.display = 'none';
});
const hideEditor = () => {
displayDiv.style.display = 'block';
editorDiv.style.display = 'none';
saveBtn.style.display = 'none';
cancelBtn.style.display = 'none';
editBtn.style.display = 'inline-block';
};
cancelBtn.addEventListener('click', () => {
textarea.value = originalContent;
hideEditor();
});
saveBtn.addEventListener('click', async () => {
const newContent = textarea.value;
displayDiv.innerHTML = renderContent(newContent);
hideEditor();
try {
const entryToUpdate = { uid: entry.uid, content: newContent };
await safeUpdateLorebookEntries(selectedBook, [entryToUpdate]);
toastr.success(`条目 "${title}" 已保存。`);
entry.content = newContent;
} catch (error) {
displayDiv.innerHTML = renderContent(originalContent);
console.error('保存世界书条目失败:', error);
toastr.error(`保存失败: ${error.message}`);
}
});
container.appendChild(entryElement);
});
} catch (error) {
console.error('加载世界书条目失败:', error);
const p = document.createElement('p');
p.style.textAlign = 'center';
p.style.color = '#ff8a8a';
p.textContent = `加载失败: ${error?.message ?? '未知错误'}`;
container.innerHTML = '';
container.appendChild(p);
}
}
function bindTabEvents() {
const tabs = document.querySelectorAll('.glossary-tab');
const contents = document.querySelectorAll('.glossary-content');
tabs.forEach(tab => {
tab.addEventListener('click', () => {
const tabId = tab.dataset.tab;
tabs.forEach(t => t.classList.remove('active'));
tab.classList.add('active');
contents.forEach(content => {
if (content.id === `glossary-content-${tabId}`) {
content.classList.add('active');
} else {
content.classList.remove('active');
}
});
if (tabId === 'context') {
renderWorldBookEntries();
} else if (tabId === 'tools') {
const statusEl = document.getElementById('reorganize-status');
if (statusEl) {
if (moduleState.selectedWorldBook) {
statusEl.textContent = `当前已选择世界书: "${moduleState.selectedWorldBook}"。可以开始重组。`;
statusEl.style.color = '';
} else {
statusEl.textContent = '请先在“小说处理”标签页中选择一个世界书。';
statusEl.style.color = '#ffdb58'; // Warning color
}
}
}
});
});
}
function bindReorganizeEvents() {
const reorganizeBtn = document.getElementById('reorganize-entries-by-heading');
const statusEl = document.getElementById('reorganize-status');
const headingsListEl = document.getElementById('reorganize-headings-list');
if (!reorganizeBtn || !statusEl || !headingsListEl) return;
const updateStatusCallback = (message, type = 'info') => {
statusEl.textContent = message;
statusEl.style.color = type === 'error' ? '#ff8a8a' : (type === 'success' ? '#8aff8a' : '');
};
reorganizeBtn.addEventListener('click', async () => {
const headingsToProcess = headingsListEl.value.split('\n').map(h => h.trim()).filter(Boolean);
if (headingsToProcess.length === 0) {
updateStatusCallback('错误:请在文本框中输入至少一个要重组的标题。', 'error');
return;
}
const bookName = moduleState.selectedWorldBook;
if (!bookName) {
updateStatusCallback('错误:请先在“小说处理”标签页中选择一个世界书。', 'error');
return;
}
const originalHtml = reorganizeBtn.innerHTML;
reorganizeBtn.disabled = true;
reorganizeBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 正在重组...';
try {
await reorganizeEntriesByHeadings(bookName, headingsToProcess, updateStatusCallback);
if (document.querySelector('.glossary-tab[data-tab="context"].active')) {
renderWorldBookEntries();
}
} catch (error) {
console.error('An error occurred during reorganization:', error);
} finally {
reorganizeBtn.disabled = false;
reorganizeBtn.innerHTML = originalHtml;
}
});
}
function bindNovelProcessEvents() {
const fileInput = document.getElementById('novel-file-input');
const fileLabel = document.querySelector('label[for="novel-file-input"]');
const dbSelectBtn = document.getElementById('select-from-database-button');
const processBtn = document.getElementById('novel-confirm-and-process');
const chunkSizeInput = document.getElementById('novel-chunk-size');
const chunkCountEl = document.getElementById('novel-chunk-count');
const chunkPreviewEl = document.getElementById('novel-chunk-preview');
let fileContent = '';
let processingState = {
chunks: [],
batchSize: 1,
forceNew: false,
selectedWorldBook: '',
currentIndex: 0,
isAborted: false,
isRunning: false,
lastStatus: 'idle',
};
function updateChunks() {
if (!fileContent) return;
const chunkSize = parseInt(chunkSizeInput.value, 10) || 5000;
const newChunks = [];
for (let i = 0; i < fileContent.length; i += chunkSize) {
newChunks.push({ title: `Part ${i/chunkSize + 1}`, content: fileContent.substring(i, i + chunkSize) });
}
processingState.chunks = newChunks;
chunkCountEl.textContent = newChunks.length;
chunkPreviewEl.innerHTML = newChunks.map((chunk, index) =>
`<div class="chunk-preview-item"><b>块 ${index + 1}:</b> ${escapeHTML(chunk.content.substring(0, 100))}...</div>`
).join('');
resetProcessing();
}
function resetProcessing() {
processingState.currentIndex = 0;
processingState.isAborted = false;
processingState.isRunning = false;
processingState.lastStatus = 'idle';
updateButtonUI();
}
function updateButtonUI() {
if (processingState.isRunning) {
processBtn.disabled = false;
processBtn.innerHTML = '<i class="fas fa-stop-circle"></i> 请求中止';
processBtn.classList.add('danger');
} else {
processBtn.classList.remove('danger');
switch (processingState.lastStatus) {
case 'paused':
processBtn.innerHTML = '<i class="fas fa-play"></i> 继续处理';
processBtn.disabled = false;
break;
case 'failed':
processBtn.innerHTML = '<i class="fas fa-redo"></i> 重试处理';
processBtn.disabled = false;
break;
case 'success':
processBtn.innerHTML = '<i class="fas fa-check"></i> 处理完成';
processBtn.disabled = true;
break;
case 'idle':
default:
processBtn.innerHTML = '确认并开始处理';
processBtn.disabled = processingState.chunks.length === 0;
break;
}
}
}
async function startOrResumeProcessing() {
if (processingState.isRunning) return;
processingState.isRunning = true;
processingState.isAborted = false;
updateButtonUI();
processingState.forceNew = document.getElementById('novel-force-new').checked;
processingState.batchSize = 1;
processingState.selectedWorldBook = moduleState.selectedWorldBook;
try {
const result = await processNovel(processingState);
if (result === 'paused') {
processingState.lastStatus = 'paused';
} else if (result === 'success') {
processingState.lastStatus = 'success';
processingState.currentIndex = 0;
}
} catch (error) {
processingState.lastStatus = 'failed';
processingState.isAborted = true;
} finally {
processingState.isRunning = false;
updateButtonUI();
}
}
if (fileLabel && fileInput) {
fileLabel.addEventListener('click', (event) => {
event.preventDefault();
fileInput.click();
});
fileInput.addEventListener('change', (event) => {
const file = event.target.files[0];
if (!file) return;
fileLabel.innerHTML = `<i class="fas fa-check"></i> 已选择: ${escapeHTML(file.name)}`;
handleFileUpload(file, (content) => {
fileContent = content;
updateChunks();
});
});
}
if (dbSelectBtn) {
dbSelectBtn.addEventListener('click', () => {
loadDatabaseFiles();
});
}
document.addEventListener('novel-file-loaded', (event) => {
const { content, fileName } = event.detail;
fileContent = content;
updateChunks();
if (fileLabel) {
fileLabel.innerHTML = `<i class="fas fa-upload"></i> 2a. 上传本地文件 (.txt)`;
}
});
if (chunkSizeInput) {
chunkSizeInput.addEventListener('input', updateChunks);
}
if (processBtn) {
processBtn.addEventListener('click', async () => {
if (processingState.isRunning) {
processingState.isAborted = true;
processBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 正在中止...';
processBtn.disabled = true;
} else {
if (processingState.lastStatus !== 'paused') {
const startBatchInput = document.getElementById('novel-start-batch-index');
let startBatch = parseInt(startBatchInput.value, 10);
if (isNaN(startBatch) || startBatch < 1) {
startBatch = 1;
if (startBatchInput) startBatchInput.value = 1;
}
processingState.currentIndex = (startBatch - 1);
}
startOrResumeProcessing();
}
});
}
}
async function loadWorldBooks() {
const select = document.getElementById('novel-world-book-select');
if (!select) return;
const savedBook = extension_settings[extensionName]?.selectedWorldBook;
moduleState.selectedWorldBook = savedBook || '';
try {
const allBooks = await safeLorebooks();
select.innerHTML = '<option value="">-- 请选择世界书 --</option>';
if (allBooks && allBooks.length > 0) {
allBooks.forEach(bookName => {
const option = new Option(bookName, bookName);
select.add(option);
});
if (savedBook && allBooks.includes(savedBook)) {
select.value = savedBook;
}
} else {
select.innerHTML = '<option value="">未找到世界书</option>';
}
} catch (error) {
console.error('[Amily2-术语表] 加载世界书失败:', error);
select.innerHTML = '<option value="">加载失败</option>';
}
}
export function bindGlossaryEvents() {
const panel = document.getElementById('amily2_glossary_panel');
if (!panel || panel.dataset.eventsBound) {
return;
}
console.log('[Amily2-术语表] 开始绑定UI事件 (最终重构版)...');
loadSettingsToUI();
bindAutoSaveEvents();
// sybd 槽分配 profile 后,温度/maxTokens 由 profile 权威控制T-006 informational 化)
watchProfileSliderGuard('sybd', ['#amily2_sybd_max_tokens', '#amily2_sybd_temperature']);
bindManualActionEvents();
bindTabEvents();
bindNovelProcessEvents();
bindReorganizeEvents();
loadWorldBooks();
// 监听我们自己的世界书创建事件,而不是监听全局的角色加载事件,避免冲突
document.addEventListener('amily-lorebook-created', (event) => {
console.log(`[Amily2-术语表] 检测到新世界书《${event.detail.bookName}》创建,重新加载列表以确保同步。`);
loadWorldBooks();
});
const worldBookSelect = document.getElementById('novel-world-book-select');
if (worldBookSelect) {
const updateOnBookSelect = (selectedValue) => {
updateAndSaveSetting('selectedWorldBook', selectedValue);
moduleState.selectedWorldBook = selectedValue;
const contextTab = document.querySelector('.glossary-tab[data-tab="context"]');
if (contextTab && contextTab.classList.contains('active')) {
renderWorldBookEntries();
}
const toolsTab = document.querySelector('.glossary-tab[data-tab="tools"]');
if (toolsTab && toolsTab.classList.contains('active')) {
const statusEl = document.getElementById('reorganize-status');
if (statusEl) {
if (selectedValue) {
statusEl.textContent = `当前已选择世界书: "${selectedValue}"。可以开始重组。`;
statusEl.style.color = '';
} else {
statusEl.textContent = '请先在“小说处理”标签页中选择一个世界书。';
statusEl.style.color = '#ffdb58';
}
}
}
};
worldBookSelect.addEventListener('change', () => {
updateOnBookSelect(worldBookSelect.value);
});
if (moduleState.selectedWorldBook) {
updateOnBookSelect(moduleState.selectedWorldBook);
}
}
panel.dataset.eventsBound = 'true';
console.log('[Amily2-术语表] UI事件绑定完成 (最终重构版)。');
}