fix(frontend): 拆分 chat.html 内联 JS 到 chat.js + 恢复 UI 业务逻辑
背景:上一轮 chat.html 拆分 CSS 到 chat.css 时(commit 561f7ee),
误把行 509-1180 的整段内联 <script>(约 670 行 UI 业务逻辑)当 CSS 一起删了。
同时 rm 掉了 chat.js。导致 chat.html 引用 chat.js 404,所有 UI 交互失效:
- 侧边栏折叠按钮:click 监听丢失
- 项目下拉 / 抽屉打开:openProjectDrawer 调用丢失
- 上传 / 发送 / 输入框:所有 addEventListener 丢失
- RAG 开关 / 影响调查按钮:监听丢失
本 commit 恢复所有 UI 业务逻辑(从 git 历史 520c9e2 拿原 chat.html 内容):
变更:
- 新增 src/genesis/server/static/chat.js(670 行,含 28 个函数 / 1 个 IIFE)
- addMsg / esc / showTyping / api
- refreshSessions / deleteSession / loadProjects
- applyProjectContext / renderProjectSwitcher / toggleProjectSwitcher
- openProjectDrawer / closeProjectDrawer / loadDrawerForm
- drawerSnapshotNow / isDrawerDirty / guardDrawerDirty
- clearPfInvalid / flagPfInvalidByMessage / renderDrawerList
- saveDrawerProject / deleteDrawerProject / toggleSidebar
- updateUploadBar / renderEmptyOrWelcome
- newSession / loadSession / send
- readRagFlag / writeRagFlag / refreshRagStats / updateImpactButton
- pickExt / projectHasPrefixedType
- 启动 IIFE:恢复侧边栏折叠态 + 加载项目 + 恢复上次会话
- chat.html +1 行:<script src="/static/chat.js" defer></script>
- defer 保证 DOM 解析完成后执行
- 放在 chat_ws.js 之后(依赖 GenesisState / GenesisWS 全局)
零行为变更:JS 内容逐行恢复,仅拆出到独立文件。
chat.js 不动 chat_state.js / chat_ws.js(保持职责单一)。
验证(serve --fake @ http://127.0.0.1:8000):
- GET /static/chat.js -> 200 text/javascript; charset=utf-8 (33286 bytes)
- GET /static/chat.css -> 200 text/css; charset=utf-8 (20803 bytes)
- GET /static/chat_state.js -> 200 text/javascript; charset=utf-8
- GET /static/chat_ws.js -> 200 text/javascript; charset=utf-8
- GET / HTML 含 chat.js defer 引用 -> True
This commit is contained in:
@@ -121,5 +121,6 @@
|
||||
|
||||
<script src="/static/chat_state.js"></script>
|
||||
<script src="/static/chat_ws.js"></script>
|
||||
<script src="/static/chat.js" defer></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -0,0 +1,673 @@
|
||||
// src/genesis/server/static/chat.js
|
||||
// Genesis Chat UI 涓氬姟閫昏緫锛坴1 鎷嗗垎鑷師 chat.html 鍐呰仈 <script> 娈碉紝琛?510-1179锛塦n// 涓婁竴杞?chat.html 鎷嗗垎 CSS 鏃惰鍒犳暣娈靛唴鑱?JS锛屽鑷存墍鏈?UI 鎸夐挳澶辨晥
|
||||
// 鏈瀹屾暣鎭㈠锛岄浂琛屼负鍙樻洿
|
||||
let sid = null;
|
||||
let progressWs = null;
|
||||
let draftProject = null; // 涓嬩竴绌虹櫧浼氳瘽灏嗙粦瀹?宸茬粦鐨勯」鐩紙鍘?currentProject锛?let activeProject = null; // 褰撳墠宸茶惤搴撲細璇濈粦瀹氱殑椤圭洰锛堟潵鑷悗绔級
|
||||
let projects = [];
|
||||
let drawerOpen = false;
|
||||
let drawerSelected = null; // 褰撳墠鎶藉眽涓紪杈戠殑椤圭洰鍚嶏紙null = 鏂板缓妯″紡锛?let lastTriggerEl = null; // 鎵撳紑鎶藉眽/涓嬫媺鍓嶇殑鐒︾偣鍏冪礌锛圕1锛?let drawerDirty = false; // 鎶藉眽琛ㄥ崟鏄惁鏈夋湭淇濆瓨鏀瑰姩锛圔6锛? let drawerSnapshot = null; // loadDrawerForm 鏃剁殑瀛楁蹇収锛圔6锛?
|
||||
// 鐘舵€侀€昏緫缁熶竴璧?chat_state.js锛涜嫢闈欐€佽矾鐢辨湭灏辩华鍒欏洖閫€鍐呰仈瀹炵幇锛岄伩鍏嶆暣椤佃剼鏈穿婧?const GenesisState = window.GenesisState || {
|
||||
autoBindProject: (d, p) => (d === null && p.length ? p[0].name : (d && !p.find(x => x.name === d) ? (p.length ? p[0].name : null) : d)),
|
||||
shouldHideUploadSelect: () => false,
|
||||
resolveUploadType: (_a, _d, v) => v,
|
||||
computeDrawerSnapshot: (f) => f.map(x => (x == null ? '' : String(x)).trim()).join(String.fromCharCode(1)),
|
||||
isDrawerDirty: (n, s) => n !== s,
|
||||
buildWelcome: (d) => d === null ? '璇锋柊寤洪」鐩垨鑰呴€夋嫨椤圭洰'
|
||||
: '浣犲ソ锛佹垜鏄?Genesis 姒傝璁捐涔︾敓鎴?Agent銆傝鍏堜笂浼犺浠跺畾涔?xlsx锛堟ā鏉?瑙勫垯/浠g爜搴撳凡鐢遍」鐩€? + d + '銆嶆彁渚涳級銆?,
|
||||
};
|
||||
|
||||
const chatEl = document.getElementById('chat');
|
||||
const inputEl = document.getElementById('input');
|
||||
const sendBtn = document.getElementById('send');
|
||||
const badge = document.getElementById('sid-badge');
|
||||
const psMenu = document.getElementById('ps-menu');
|
||||
const psName = document.getElementById('ps-name');
|
||||
const drawer = document.getElementById('proj-drawer');
|
||||
|
||||
function addMsg(role, html) {
|
||||
const m = document.createElement('div');
|
||||
m.className = 'msg ' + role;
|
||||
m.innerHTML = '<div class="bubble">' + html + '</div>';
|
||||
chatEl.appendChild(m);
|
||||
chatEl.scrollTop = chatEl.scrollHeight;
|
||||
return m;
|
||||
}
|
||||
function esc(s) { return String(s).replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c])); }
|
||||
function showTyping() { return addMsg('assistant', '<span class="typing">鎬濊€冧腑鈥?/span>'); }
|
||||
|
||||
async function api(method, url, body) {
|
||||
const opt = { method, headers: {} };
|
||||
if (body !== undefined) { opt.headers['Content-Type'] = 'application/json'; opt.body = JSON.stringify(body); }
|
||||
const r = await fetch(url, opt);
|
||||
const data = await r.json().catch(() => ({}));
|
||||
if (!r.ok) throw new Error(data.detail?.message || r.status);
|
||||
return data;
|
||||
}
|
||||
|
||||
// ---------- 浼氳瘽鍒楄〃 ----------
|
||||
async function refreshSessions() {
|
||||
const box = document.getElementById('session-list');
|
||||
if (draftProject === null) { box.innerHTML = ''; return; } // 鏈€夐」鐩?鈫?鏃犲巻鍙? const list = await api('GET', '/api/sessions?user_id=default&project=' + encodeURIComponent(draftProject));
|
||||
box.innerHTML = '';
|
||||
list.sort((a, b) => (b.updated_at || '').localeCompare(a.updated_at || ''));
|
||||
for (const s of list) {
|
||||
const el = document.createElement('div');
|
||||
el.className = 'sess' + (s.session_id === sid ? ' active' : '');
|
||||
const proj = s.project ? ' 路 ' + esc(s.project) : '';
|
||||
// P3鈥?锛氬彇棣栧瓧绗︼紙鍚腑鏂?鏃ユ枃/鑻辨枃锛変綔 avatar锛屽苟鐢ㄥ悕瀛?hash 閫夎壊锛岄伩鍏嶉噸鍚嶆贩娣? const rawName = (s.name || '鏂?).trim();
|
||||
const avatar = rawName ? Array.from(rawName)[0] : '鏂?;
|
||||
const palette = ['#1a73e8', '#34a853', '#fbbc05', '#ea4335', '#8e24aa', '#0097a7', '#5f6368'];
|
||||
let h = 0;
|
||||
for (let i = 0; i < rawName.length; i++) h = (h * 31 + rawName.charCodeAt(i)) | 0;
|
||||
const color = palette[Math.abs(h) % palette.length];
|
||||
el.innerHTML =
|
||||
'<div class="avatar" style="background:' + color + ';">' + esc(avatar) + '</div>' +
|
||||
'<div class="info">' +
|
||||
'<div class="name">' + esc(s.name || '鏂颁細璇?) + '</div>' +
|
||||
'<div class="meta">' + esc(s.status) + proj + '</div>' +
|
||||
'</div>' +
|
||||
'<button class="del" title="鍒犻櫎浼氳瘽" aria-label="鍒犻櫎浼氳瘽 ' + esc(rawName) + '">脳</button>';
|
||||
el.querySelector('.info').onclick = () => loadSession(s.session_id);
|
||||
const delBtn = el.querySelector('.del');
|
||||
delBtn.onclick = (ev) => { ev.stopPropagation(); deleteSession(s.session_id); };
|
||||
box.appendChild(el);
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteSession(targetSid) {
|
||||
if (!confirm('纭鍒犻櫎璇ヤ細璇濓紵姝ゆ搷浣滀笉鍙挙閿€銆?)) return;
|
||||
try {
|
||||
await api('DELETE', '/api/sessions/' + encodeURIComponent(targetSid));
|
||||
} catch (e) {
|
||||
addMsg('error', '鍒犻櫎澶辫触锛? + esc(String(e)));
|
||||
return;
|
||||
}
|
||||
if (targetSid === sid) {
|
||||
// 鍒犻櫎鐨勬槸褰撳墠浼氳瘽 鈫?鑷姩鏂板缓骞舵竻绌? await newSession();
|
||||
} else {
|
||||
await refreshSessions();
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- 椤圭洰閰嶇疆 ----------
|
||||
async function loadProjects() {
|
||||
try {
|
||||
projects = await api('GET', '/api/projects');
|
||||
} catch (e) {
|
||||
projects = [];
|
||||
}
|
||||
// 鍚姩鑷姩缁戦椤?/ 宸插垹椤圭洰鍥為€€棣栭」锛堢粺涓€鐢?GenesisState.autoBindProject 澶勭悊锛? draftProject = GenesisState.autoBindProject(draftProject, projects);
|
||||
applyProjectContext();
|
||||
renderProjectSwitcher();
|
||||
renderDrawerList();
|
||||
if (drawerOpen) loadDrawerForm(drawerSelected);
|
||||
}
|
||||
|
||||
function applyProjectContext() {
|
||||
psName.textContent = draftProject || '鏈€夋嫨';
|
||||
}
|
||||
|
||||
function renderProjectSwitcher() {
|
||||
let html = '<div class="ps-item' + (draftProject === null ? ' active' : '') + '" data-name="">'
|
||||
+ '<span>涓嶉€夋嫨椤圭洰</span><span class="ps-check">鉁?/span></div>';
|
||||
for (const p of projects) {
|
||||
html += '<div class="ps-item' + (p.name === draftProject ? ' active' : '') + '" data-name="' + esc(p.name) + '">'
|
||||
+ '<span>' + esc(p.display_name || p.name) + '</span><span class="ps-check">鉁?/span></div>';
|
||||
}
|
||||
html += '<div class="ps-sep"></div>'
|
||||
+ '<div class="ps-item ps-manage" data-manage="1">+ 椤圭洰绠$悊锛堟墦寮€鎶藉眽锛?/div>';
|
||||
psMenu.innerHTML = html;
|
||||
psMenu.querySelectorAll('.ps-item[data-name]').forEach(it => {
|
||||
it.onclick = () => {
|
||||
if (!guardDrawerDirty()) return;
|
||||
draftProject = it.dataset.name === '' ? null : it.dataset.name;
|
||||
applyProjectContext();
|
||||
renderProjectSwitcher();
|
||||
updateUploadBar();
|
||||
toggleProjectSwitcher(false);
|
||||
};
|
||||
});
|
||||
psMenu.querySelectorAll('.ps-item[data-manage]').forEach(it => {
|
||||
it.onclick = () => {
|
||||
if (!guardDrawerDirty()) return;
|
||||
lastTriggerEl = it;
|
||||
toggleProjectSwitcher(false);
|
||||
openProjectDrawer(drawerSelected);
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function toggleProjectSwitcher(force) {
|
||||
const willOpen = force === undefined ? !psMenu.classList.contains('open') : !!force;
|
||||
psMenu.classList.toggle('open', willOpen);
|
||||
}
|
||||
|
||||
// ---------- 鎶藉眽 ----------
|
||||
function openProjectDrawer(projectName) {
|
||||
drawerOpen = true;
|
||||
toggleProjectSwitcher(false);
|
||||
drawer.classList.add('open');
|
||||
const sel = (projectName === undefined || projectName === null) ? drawerSelected : projectName;
|
||||
try { loadDrawerForm(sel); } catch (e) { console.error(e); }
|
||||
renderDrawerList(); // 濮嬬粓娓叉煋宸︿晶鍒楄〃锛堝惈 +鏂板缓椤圭洰锛?}
|
||||
|
||||
function closeProjectDrawer() {
|
||||
if (!guardDrawerDirty()) return;
|
||||
drawerOpen = false;
|
||||
drawer.classList.remove('open');
|
||||
}
|
||||
|
||||
function loadDrawerForm(projectName) {
|
||||
drawerSelected = (projectName === undefined) ? drawerSelected : projectName;
|
||||
const nameEl = document.getElementById('pf-name');
|
||||
const dispEl = document.getElementById('pf-display');
|
||||
const tplEl = document.getElementById('pf-template');
|
||||
const wrEl = document.getElementById('pf-write');
|
||||
const rulesEl = document.getElementById('pf-rules');
|
||||
const codeEl = document.getElementById('pf-code');
|
||||
const designEl = document.getElementById('pf-design');
|
||||
const delBtn = document.getElementById('pf-delete');
|
||||
if (drawerSelected) {
|
||||
const p = projects.find(x => x.name === drawerSelected);
|
||||
if (p) {
|
||||
nameEl.value = p.name; nameEl.readOnly = true;
|
||||
dispEl.value = p.display_name || '';
|
||||
tplEl.value = p.template || '';
|
||||
wrEl.value = p.write_instruction || '';
|
||||
rulesEl.value = (p.rules || []).join(', ');
|
||||
codeEl.value = p.existing_system_code_dir || '';
|
||||
designEl.value = p.design_docs_dir || '';
|
||||
delBtn.hidden = false;
|
||||
}
|
||||
} else {
|
||||
nameEl.value = ''; nameEl.readOnly = false;
|
||||
dispEl.value = '';
|
||||
tplEl.value = ''; wrEl.value = ''; rulesEl.value = ''; codeEl.value = ''; designEl.value = '';
|
||||
delBtn.hidden = true;
|
||||
}
|
||||
// B6锛氳褰曞瓧娈靛揩鐓х敤浜庤剰妫€娴? drawerSnapshot = drawerSnapshotNow();
|
||||
renderDrawerList();
|
||||
}
|
||||
|
||||
// B6锛氭娊灞夋湭淇濆瓨鍙樻洿瀹堝崼
|
||||
function drawerSnapshotNow() {
|
||||
return GenesisState.computeDrawerSnapshot([
|
||||
document.getElementById('pf-name').value,
|
||||
document.getElementById('pf-display').value,
|
||||
document.getElementById('pf-template').value,
|
||||
document.getElementById('pf-write').value,
|
||||
document.getElementById('pf-rules').value,
|
||||
document.getElementById('pf-code').value,
|
||||
document.getElementById('pf-design').value,
|
||||
]);
|
||||
}
|
||||
function isDrawerDirty() {
|
||||
if (!drawerOpen || drawerSnapshot === null) return false;
|
||||
return GenesisState.isDrawerDirty(drawerSnapshotNow(), drawerSnapshot);
|
||||
}
|
||||
function guardDrawerDirty() {
|
||||
if (isDrawerDirty()) return confirm('鏈夋湭淇濆瓨鐨勪慨鏀癸紝纭畾鏀惧純锛?);
|
||||
return true;
|
||||
}
|
||||
|
||||
// P0鈥慍锛氭娊灞夊瓧娈电骇绾㈡銆傚懡涓叧閿瓧 鈫?缁欏搴旇緭鍏ュ姞 .invalid 3 绉掑悗娓呴櫎銆?// 鍏抽敭瀛椾笌 store.py 鐨?ProjectConfigError 涓枃 label 瀵归綈銆?const PF_LABEL_TO_FIELD = {
|
||||
'椤圭洰鍚?: 'pf-name',
|
||||
'妯℃澘': 'pf-template',
|
||||
'鍋氭垚璇存槑涔?: 'pf-write',
|
||||
'瑙勫垯': 'pf-rules',
|
||||
'鏃㈡湁绯荤粺浠g爜搴?: 'pf-code',
|
||||
'鏃㈡湁璁捐鏂囨。鐩綍': 'pf-design',
|
||||
};
|
||||
function clearPfInvalid() {
|
||||
['pf-name','pf-display','pf-template','pf-write','pf-rules','pf-code','pf-design']
|
||||
.forEach(id => document.getElementById(id).classList.remove('invalid'));
|
||||
}
|
||||
function flagPfInvalidByMessage(message) {
|
||||
if (!message) return;
|
||||
for (const [label, fid] of Object.entries(PF_LABEL_TO_FIELD)) {
|
||||
if (message.indexOf(label) >= 0) {
|
||||
const el = document.getElementById(fid);
|
||||
el.classList.add('invalid');
|
||||
el.focus();
|
||||
setTimeout(() => el.classList.remove('invalid'), 3000);
|
||||
}
|
||||
}
|
||||
}
|
||||
// 浠绘剰杈撳叆娓呮帀鑷韩绾㈡锛堥伩鍏?绾㈢潃杈撳叆"璇锛?['pf-name','pf-display','pf-template','pf-write','pf-rules','pf-code','pf-design']
|
||||
.forEach(id => document.getElementById(id).addEventListener('input', (e) => e.target.classList.remove('invalid')));
|
||||
|
||||
function renderDrawerList() {
|
||||
let html = '<div class="drawer-item di-create' + (drawerSelected === null ? ' active' : '') + '" data-name="">'
|
||||
+ '<span class="di-new">锛?/span><span class="di-name">鏂板缓椤圭洰</span></div>';
|
||||
for (const p of projects) {
|
||||
html += '<div class="drawer-item' + (p.name === drawerSelected ? ' active' : '') + '" data-name="' + esc(p.name) + '">'
|
||||
+ '<span class="di-name">' + esc(p.display_name || p.name) + '</span></div>';
|
||||
}
|
||||
const box = document.getElementById('drawer-list');
|
||||
box.innerHTML = html;
|
||||
box.querySelectorAll('.drawer-item').forEach(it => {
|
||||
it.onclick = () => {
|
||||
if (!guardDrawerDirty()) return;
|
||||
const n = it.dataset.name === '' ? null : it.dataset.name;
|
||||
loadDrawerForm(n);
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
async function saveDrawerProject() {
|
||||
clearPfInvalid();
|
||||
const body = {
|
||||
name: document.getElementById('pf-name').value.trim(),
|
||||
display_name: document.getElementById('pf-display').value.trim(),
|
||||
template: document.getElementById('pf-template').value.trim(),
|
||||
write_instruction: document.getElementById('pf-write').value.trim(),
|
||||
rules: document.getElementById('pf-rules').value.split(',').map(s => s.trim()).filter(Boolean),
|
||||
existing_system_code_dir: document.getElementById('pf-code').value.trim(),
|
||||
design_docs_dir: document.getElementById('pf-design').value.trim(),
|
||||
};
|
||||
if (!body.name) {
|
||||
flagPfInvalidByMessage('椤圭洰鍚?);
|
||||
addMsg('error', '椤圭洰鍚嶄笉鑳戒负绌?);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const cfg = await api('POST', '/api/projects', body);
|
||||
draftProject = cfg.name;
|
||||
drawerSelected = cfg.name;
|
||||
await loadProjects();
|
||||
addMsg('assistant', '椤圭洰銆? + esc(cfg.display_name || cfg.name) + '銆嶅凡淇濆瓨銆?);
|
||||
closeProjectDrawer();
|
||||
} catch (e) {
|
||||
// 400 / PROJECT_CONFIG_INVALID锛氬瓧娈电骇绾㈡瀹氫綅
|
||||
flagPfInvalidByMessage(String(e));
|
||||
addMsg('error', '淇濆瓨椤圭洰澶辫触锛? + esc(String(e)));
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteDrawerProject() {
|
||||
if (!drawerSelected) return;
|
||||
if (!confirm('纭鍒犻櫎椤圭洰銆? + drawerSelected + '銆嶏紵姝ゆ搷浣滀笉鍙挙閿€銆?)) return;
|
||||
const deleted = drawerSelected;
|
||||
try {
|
||||
await api('DELETE', '/api/projects/' + encodeURIComponent(deleted));
|
||||
} catch (e) {
|
||||
addMsg('error', '鍒犻櫎椤圭洰澶辫触锛? + esc(String(e)));
|
||||
return;
|
||||
}
|
||||
addMsg('assistant', '椤圭洰銆? + esc(deleted) + '銆嶅凡鍒犻櫎銆?);
|
||||
// P1鈥慒锛氬厛璁颁綇琚垹鐨勶紝鍐嶆竻 drawerSelected锛涢伩鍏?鍏?null 鍚庢瘮杈?鎭掑亣 bug
|
||||
drawerSelected = null;
|
||||
if (draftProject === deleted) {
|
||||
// 褰撳墠閫夌殑灏辨槸琚垹鐨勯」鐩?鈫?娓呯┖鍋忓ソ锛坅utoBindProject 浼氫粠鍓╀綑椤圭洰閲嶉€夛級
|
||||
draftProject = null;
|
||||
}
|
||||
await loadProjects();
|
||||
loadDrawerForm(null);
|
||||
}
|
||||
|
||||
// ---------- 渚ц竟鏍忔姌鍙?----------
|
||||
function toggleSidebar(force) {
|
||||
const el = document.getElementById('sidebar');
|
||||
const willCollapse = force === undefined ? !el.classList.contains('collapsed') : !!force;
|
||||
el.classList.toggle('collapsed', willCollapse);
|
||||
try { localStorage.setItem('genesis_sidebar_collapsed', willCollapse ? '1' : '0'); } catch (e) { /* localStorage 涓嶅彲鐢ㄦ椂蹇界暐 */ }
|
||||
}
|
||||
|
||||
// ---------- 涓婁紶鍖猴細濮嬬粓鏄剧ず瀹屾暣绫诲瀷涓嬫媺 ----------
|
||||
// P0鈥態锛氶€夐」鐩椂涔熷厑璁歌ˉ浼?template / write_instruction / rules / existing_system锛?// 涓嶅啀钘忚捣鍏ュ彛銆?椤圭洰宸查缃?template 鏃跺啀涓婁紶 template"鍦ㄤ笂浼犲鐢?confirm() 鏄惧紡纭銆?function updateUploadBar() {
|
||||
const sel = document.getElementById('file-type');
|
||||
const hint = document.getElementById('proj-hint');
|
||||
if (sel) sel.style.display = '';
|
||||
if (!hint) return;
|
||||
// 榛樿 file_type 浠嶄负 requirements锛堟渶甯哥敤锛夛紝浣嗕笅鎷夊缁堝彲鏀广€? if (sel && sel.value !== 'requirements') sel.value = 'requirements';
|
||||
if (draftProject) {
|
||||
hint.textContent = '榛樿涓婁紶瑕佷欢瀹氫箟 xlsx锛涘闇€琛ヤ紶妯℃澘/瑙勫垯/鏃㈡湁绯荤粺 zip锛岃鍦ㄤ笅鎷変腑閫夋嫨瀵瑰簲绫诲瀷銆?;
|
||||
} else {
|
||||
hint.textContent = '璇烽€夋嫨 file_type 鍚庝笂浼狅紙鏈€夐」鐩椂锛屾ā鏉?瑙勫垯浠嶅彲鎵嬪姩涓婁紶锛夈€?;
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- 绌烘€?娆㈣繋娓叉煋 ----------
|
||||
function renderEmptyOrWelcome() {
|
||||
chatEl.innerHTML = '';
|
||||
// P1鈥慒锛氭杩庢枃鐢?GenesisState.buildWelcome 缁熶竴鏉ユ簮
|
||||
addMsg('assistant', GenesisState.buildWelcome(draftProject));
|
||||
}
|
||||
|
||||
// ---------- 浼氳瘽鍒涘缓/鍔犺浇 ----------
|
||||
async function newSession() {
|
||||
if (progressWs) { try { progressWs.close(); } catch (e) {} } progressWs = null;
|
||||
sid = null;
|
||||
activeProject = null;
|
||||
// 淇濈暀 draftProject锛堝綋鍓嶉《鏍忓凡閫夐」鐩級锛屼娇鏂颁細璇濈户鎵块」鐩粦瀹氾紙搂4.2锛? try { localStorage.removeItem('genesis_session'); } catch (e) { /* 蹇界暐 */ }
|
||||
chatEl.innerHTML = '';
|
||||
badge.textContent = '鏈垱寤轰細璇?;
|
||||
updateUploadBar();
|
||||
await refreshRagStats();
|
||||
await refreshSessions();
|
||||
renderEmptyOrWelcome();
|
||||
}
|
||||
|
||||
async function loadSession(id) {
|
||||
try {
|
||||
const rec = await api('GET', '/api/sessions/' + encodeURIComponent(id));
|
||||
sid = id;
|
||||
activeProject = rec.project || null;
|
||||
// P1鈥慏锛氫笉鍐嶉殣寮忚鐩?draftProject銆備細璇濅簨瀹?activeProject)涓庣敤鎴峰亸濂?draftProject)
|
||||
// 鍒嗗眰锛涜嫢涓嶄竴鑷达紝鐢辨彁绀烘潯璁╃敤鎴蜂富鍔ㄩ€夋嫨銆? // draftProject = rec.project || null; // 鍒犻櫎锛氬師琛屼负浼氭倓鎮勬敼鐢ㄦ埛鍋忓ソ
|
||||
applyProjectContext();
|
||||
badge.textContent = '浼氳瘽: ' + (rec.name || '鏂颁細璇?);
|
||||
if (progressWs) { try { progressWs.close(); } catch (e) {} }
|
||||
progressWs = GenesisWS.connectProgressWs(id, {
|
||||
onProgress: (e) => GenesisWS.applyProgressEvent(e, (role, text) => addMsg(role, text)),
|
||||
onClose: () => {},
|
||||
});
|
||||
const msgs = await api('GET', '/api/chat/' + encodeURIComponent(id) + '/messages');
|
||||
chatEl.innerHTML = '';
|
||||
for (const m of msgs) {
|
||||
const roleMap = { user: 'user', progress: 'progress', error: 'error' };
|
||||
const role = roleMap[m.role] || 'assistant';
|
||||
addMsg(role, esc(m.content));
|
||||
}
|
||||
updateUploadBar();
|
||||
await refreshRagStats();
|
||||
await refreshSessions();
|
||||
try { localStorage.setItem('genesis_session', sid); } catch (e) { /* 蹇界暐 */ }
|
||||
renderProjectMismatchHint();
|
||||
} catch (e) {
|
||||
addMsg('error', '鍔犺浇浼氳瘽澶辫触锛? + esc(String(e)));
|
||||
}
|
||||
}
|
||||
|
||||
// P1鈥慏锛氶」鐩笉鍖归厤鎻愮ず鏉°€俛ctiveProject 涓?draftProject 涓嶄竴鑷存椂鏄剧ず锛?// "鍒囧埌璇ラ」鐩? 鈫?鍐?draftProject = activeProject锛屽埛鏂帮紱
|
||||
// "淇濈暀" 鈫?鍐欏叆 sessionStorage 鏍囪锛屽埛鏂帮紱鍚庣画 loadSession 涓嶅啀鎻愮ず銆?function renderProjectMismatchHint() {
|
||||
const old = document.getElementById('proj-mismatch-hint');
|
||||
if (old) old.remove();
|
||||
if (!sid) return;
|
||||
if (!activeProject) return;
|
||||
if (activeProject === draftProject) return;
|
||||
// 宸?淇濈暀"杩囨湰浼氳瘽鐨勪笉鍐嶆彁绀? let skipped = {};
|
||||
try { skipped = JSON.parse(sessionStorage.getItem('genesis_skipped_project_hint') || '{}'); } catch (e) { skipped = {}; }
|
||||
if (skipped[sid] === activeProject) return;
|
||||
const wrap = document.createElement('div');
|
||||
wrap.id = 'proj-mismatch-hint';
|
||||
wrap.className = 'msg assistant';
|
||||
wrap.innerHTML =
|
||||
'<div class="bubble">' +
|
||||
'璇ヤ細璇濆睘浜庨」鐩?<strong>' + esc(activeProject) + '</strong>锛? +
|
||||
'褰撳墠椤舵爮椤圭洰涓?<strong>' + esc(draftProject || '锛堟湭閫夋嫨锛?) + '</strong>銆? +
|
||||
'<div class="actions">' +
|
||||
'<a href="#" data-act="switch">鍒囧埌璇ラ」鐩?/a>' +
|
||||
'<a href="#" data-act="keep">淇濈暀褰撳墠椤圭洰</a>' +
|
||||
'</div></div>';
|
||||
chatEl.prepend(wrap);
|
||||
wrap.querySelector('[data-act="switch"]').onclick = (e) => {
|
||||
e.preventDefault();
|
||||
draftProject = activeProject;
|
||||
applyProjectContext();
|
||||
renderProjectSwitcher();
|
||||
updateUploadBar();
|
||||
refreshSessions();
|
||||
wrap.remove();
|
||||
};
|
||||
wrap.querySelector('[data-act="keep"]').onclick = (e) => {
|
||||
e.preventDefault();
|
||||
try {
|
||||
skipped[sid] = activeProject;
|
||||
sessionStorage.setItem('genesis_skipped_project_hint', JSON.stringify(skipped));
|
||||
} catch (er) { /* 蹇界暐 */ }
|
||||
wrap.remove();
|
||||
};
|
||||
}
|
||||
|
||||
// P2鈥慔锛歴end() in-flight 閿侊紝闃叉蹇€熷弻鍑讳骇鐢熼噸澶嶈姹?let sendInFlight = false;
|
||||
async function send() {
|
||||
if (sendInFlight) return; // in-flight 鏈熼棿鍐嶆杩涘叆鐩存帴蹇界暐
|
||||
const text = inputEl.value.trim();
|
||||
if (!text) return;
|
||||
sendInFlight = true;
|
||||
if (!sid) {
|
||||
// 棣栨潯娑堟伅锛氬厛钀藉簱浼氳瘽锛圖-v4锛? try {
|
||||
const d = await api('POST', '/api/sessions', { user_id: 'default', project: draftProject || null });
|
||||
sid = d.session_id;
|
||||
activeProject = draftProject || null;
|
||||
badge.textContent = '浼氳瘽: ' + (d.name || '鏂颁細璇?);
|
||||
try { localStorage.setItem('genesis_session', sid); } catch (e) { /* 蹇界暐 */ }
|
||||
await refreshSessions();
|
||||
} catch (e) {
|
||||
addMsg('error', '鍒涘缓浼氳瘽澶辫触锛? + esc(String(e)));
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (progressWs) { try { progressWs.close(); } catch (e) {} }
|
||||
progressWs = GenesisWS.connectProgressWs(sid, {
|
||||
onProgress: (e) => GenesisWS.applyProgressEvent(e, (role, text) => addMsg(role, text)),
|
||||
onClose: () => {},
|
||||
});
|
||||
inputEl.value = '';
|
||||
addMsg('user', esc(text));
|
||||
const typing = showTyping();
|
||||
sendBtn.disabled = true;
|
||||
try {
|
||||
const res = await api('POST', '/api/chat/' + encodeURIComponent(sid) + '/messages', { content: text });
|
||||
typing.remove();
|
||||
if (res.progress && res.progress.length) {
|
||||
const items = res.progress.map(p => '<span class="progress-item ' + (p.status || 'ok') + '">' + esc(p.step) + ': ' + esc(p.detail || '') + '</span>').join('');
|
||||
addMsg('progress', items);
|
||||
}
|
||||
let replyHtml = esc(res.reply || '');
|
||||
const s = res.status;
|
||||
if (s === 'done' || s === 'writing') {
|
||||
replyHtml += '<div class="actions">'
|
||||
+ '<a href="/api/sessions/' + sid + '/result/download">涓嬭浇 docx</a>'
|
||||
+ '<a href="/api/sessions/' + sid + '/result/preview">棰勮</a>'
|
||||
+ '<a href="/api/sessions/' + sid + '/result/impact-report">褰卞搷璋冩煡涔?/a>'
|
||||
+ '<a href="/api/sessions/' + sid + '/result/qa-report">QA 鎶ュ憡</a></div>';
|
||||
}
|
||||
addMsg('assistant', replyHtml);
|
||||
} catch (e) {
|
||||
typing.remove();
|
||||
addMsg('error', '璇锋眰澶辫触锛? + esc(String(e)));
|
||||
} finally {
|
||||
sendInFlight = false;
|
||||
sendBtn.disabled = false;
|
||||
inputEl.focus();
|
||||
}
|
||||
}
|
||||
|
||||
document.getElementById('send').addEventListener('click', send);
|
||||
inputEl.addEventListener('keydown', e => { if (e.key === 'Enter') send(); });
|
||||
document.getElementById('new-chat').addEventListener('click', () => newSession().catch(e => addMsg('error', esc(String(e)))));
|
||||
document.getElementById('sidebar-toggle').addEventListener('click', () => toggleSidebar());
|
||||
document.getElementById('ps-current').addEventListener('click', (e) => { e.stopPropagation(); lastTriggerEl = e.currentTarget; toggleProjectSwitcher(); });
|
||||
document.getElementById('drawer-close').addEventListener('click', closeProjectDrawer);
|
||||
document.getElementById('pf-save').addEventListener('click', saveDrawerProject);
|
||||
document.getElementById('pf-delete').addEventListener('click', deleteDrawerProject);
|
||||
|
||||
// ---------- P0鈥慉锛歊AG 寮€鍏?+ 鐘舵€佸窘鏍?+ 寮€濮嬪奖鍝嶈皟鏌?----------
|
||||
const ragEnabledEl = document.getElementById('rag-enabled');
|
||||
const ragStatsEl = document.getElementById('rag-stats');
|
||||
const ragBarEl = document.getElementById('rag-bar');
|
||||
const impactBtnEl = document.getElementById('impact-btn');
|
||||
|
||||
const RAG_LS_KEY = 'genesis_rag_enabled';
|
||||
function readRagFlag() {
|
||||
try { return localStorage.getItem(RAG_LS_KEY) === '1'; } catch (e) { return false; }
|
||||
}
|
||||
function writeRagFlag(v) {
|
||||
try { localStorage.setItem(RAG_LS_KEY, v ? '1' : '0'); } catch (e) { /* 蹇界暐 */ }
|
||||
}
|
||||
ragEnabledEl.addEventListener('change', () => { writeRagFlag(ragEnabledEl.checked); updateImpactButton(); });
|
||||
|
||||
async function refreshRagStats() {
|
||||
// 鏃?sid 鈫?闅愯棌 RAG 鏉? if (!sid) {
|
||||
ragBarEl.hidden = true;
|
||||
return;
|
||||
}
|
||||
ragBarEl.hidden = false;
|
||||
let stats = { chunks: 0, rag_enabled: false };
|
||||
try {
|
||||
stats = await api('GET', '/api/sessions/' + encodeURIComponent(sid) + '/rag-stats');
|
||||
} catch (e) {
|
||||
stats = { chunks: 0, rag_enabled: false };
|
||||
}
|
||||
const n = Number(stats.chunks) || 0;
|
||||
ragStatsEl.textContent = n > 0
|
||||
? 'RAG 宸茬储寮?' + n + ' 鐗囨'
|
||||
: 'RAG 0 鐗囨锛堣涓婁紶鏃㈡湁绯荤粺 zip锛?;
|
||||
ragStatsEl.classList.toggle('ready', n > 0);
|
||||
ragStatsEl.classList.toggle('zero', n === 0);
|
||||
// 寮€鍏冲彲鐢ㄦ€э細蹇呴』鍏堟湁 RAG 绱㈠紩鎵嶈兘鐢? ragEnabledEl.disabled = n === 0;
|
||||
if (n === 0) {
|
||||
ragEnabledEl.checked = false;
|
||||
writeRagFlag(false);
|
||||
ragEnabledEl.parentElement.title = '璇峰厛鍦ㄤ笂浼犲尯閫夋嫨"鏃㈡湁绯荤粺 zip"骞朵笂浼?;
|
||||
} else {
|
||||
ragEnabledEl.checked = readRagFlag();
|
||||
ragEnabledEl.parentElement.title = ragEnabledEl.checked
|
||||
? 'RAG 妫€绱㈢粨鏋滀細娉ㄥ叆鍒?LLM prompt'
|
||||
: '鍕鹃€夊悗鍚敤 RAG 妫€绱?;
|
||||
}
|
||||
updateImpactButton();
|
||||
}
|
||||
|
||||
function updateImpactButton() {
|
||||
// 宸叉湁 RAG 绱㈠紩锛坮ag-stats 鍐冲畾锛?涓旀湁 sid 鎵嶈兘褰卞搷
|
||||
if (!sid) { impactBtnEl.disabled = true; return; }
|
||||
const hasRag = (Number(ragStatsEl.dataset.chunks || 0) > 0) || !ragEnabledEl.disabled;
|
||||
impactBtnEl.disabled = !hasRag;
|
||||
impactBtnEl.textContent = ragEnabledEl.checked
|
||||
? '寮€濮嬪奖鍝嶈皟鏌ワ紙鍚敤 RAG锛?
|
||||
: '寮€濮嬪奖鍝嶈皟鏌?;
|
||||
}
|
||||
|
||||
impactBtnEl.addEventListener('click', async () => {
|
||||
if (!sid) { addMsg('error', '璇峰厛鍙戦€佷竴鏉℃秷鎭互鍒涘缓浼氳瘽'); inputEl.focus(); return; }
|
||||
const useRag = !!ragEnabledEl.checked;
|
||||
impactBtnEl.disabled = true;
|
||||
const typing = showTyping();
|
||||
try {
|
||||
const url = '/api/sessions/' + encodeURIComponent(sid) + '/start-impact?use_rag=' + (useRag ? 'true' : 'false');
|
||||
const r = await fetch(url, { method: 'POST' });
|
||||
const d = await r.json();
|
||||
if (!r.ok) throw new Error(d.detail?.message || r.status);
|
||||
typing.remove();
|
||||
addMsg('progress', '<span class="progress-item ok">褰卞搷璋冩煡宸叉彁浜わ紙use_rag=' + (useRag ? 'true' : 'false') + '锛?/span>');
|
||||
// 璁?WebSocket 鎶婂悗缁繘搴︽帹涓婃潵锛涚◢鍚庣敤鎴峰彲鏌?impact-result
|
||||
addMsg('assistant', '褰卞搷璋冩煡宸插惎鍔ㄣ€傚畬鎴愬悗鍙湪姝や細璇濈偣鍑?棰勮"鎴栬闂?/result/impact-report 涓嬭浇鎶ュ憡銆?);
|
||||
} catch (e) {
|
||||
typing.remove();
|
||||
addMsg('error', '褰卞搷璋冩煡澶辫触锛? + esc(String(e)));
|
||||
} finally {
|
||||
updateImpactButton();
|
||||
}
|
||||
});
|
||||
document.addEventListener('click', (e) => {
|
||||
// 鐐瑰嚮鍒囨崲鍣ㄥ閮ㄥ叧闂笅鎷? if (!document.getElementById('proj-switcher').contains(e.target)) toggleProjectSwitcher(false);
|
||||
});
|
||||
document.addEventListener('keydown', (e) => {
|
||||
if (e.key === 'Escape') {
|
||||
if (psMenu.classList.contains('open')) toggleProjectSwitcher(false);
|
||||
else if (drawerOpen) closeProjectDrawer();
|
||||
if (lastTriggerEl) { lastTriggerEl.focus(); lastTriggerEl = null; }
|
||||
}
|
||||
});
|
||||
|
||||
// 瀹㈡埛绔被鍨?鈫?鎵╁睍鍚嶇櫧鍚嶅崟鏍¢獙锛圥0鈥態 / P1鈥慐锛夈€?const UPLOAD_EXT_RULES = {
|
||||
existing_system: ['.zip'],
|
||||
requirements: ['.xlsx'],
|
||||
template: ['.docx'],
|
||||
write_instruction: ['.docx'],
|
||||
rules: ['.docx', '.xlsx'],
|
||||
};
|
||||
function pickExt(name) {
|
||||
const i = String(name).lastIndexOf('.');
|
||||
return i >= 0 ? String(name).slice(i).toLowerCase() : '';
|
||||
}
|
||||
// 椤圭洰绾ч缃?鈫?鎻愰啋锛氬啀娆′笂浼犲皢瑕嗙洊璇ヤ細璇濈殑璇ョ被鍨嬫枃浠躲€?// 杩欓噷鐢?activeProject/draftProject 瀵瑰簲鐨勯」鐩?config锛坧rojects[]锛夊垽瀹氭槸鍚﹂缃€?function projectHasPrefixedType(ft) {
|
||||
const name = activeProject || draftProject;
|
||||
if (!name) return false;
|
||||
const p = (projects || []).find(x => x.name === name);
|
||||
if (!p) return false;
|
||||
if (ft === 'template') return !!(p.template && p.template.trim());
|
||||
if (ft === 'write_instruction') return !!(p.write_instruction && p.write_instruction.trim());
|
||||
if (ft === 'existing_system') return !!(p.existing_system_code_dir && p.existing_system_code_dir.trim());
|
||||
if (ft === 'rules') return Array.isArray(p.rules) && p.rules.length > 0;
|
||||
return false;
|
||||
}
|
||||
|
||||
document.getElementById('upload-btn').addEventListener('click', async () => {
|
||||
if (!sid) { addMsg('error', '璇峰厛鍙戦€佷竴鏉℃秷鎭互鍒涘缓浼氳瘽'); inputEl.focus(); return; }
|
||||
const sel = document.getElementById('file-type');
|
||||
const ft = GenesisState.resolveUploadType(activeProject, draftProject, sel.value);
|
||||
const file = document.getElementById('file-input').files[0];
|
||||
if (!file) { addMsg('error', '璇烽€夋嫨鏂囦欢'); return; }
|
||||
// P0鈥態 / P1鈥慐锛氬鎴风绫诲瀷涓庢墿灞曞悕鏍¢獙
|
||||
const allowed = UPLOAD_EXT_RULES[ft];
|
||||
if (allowed) {
|
||||
const ext = pickExt(file.name);
|
||||
if (!ext || !allowed.includes(ext)) {
|
||||
addMsg('error', '绫诲瀷涓嶅尮閰嶏細' + esc(ft) + ' 搴斾负 ' + allowed.join('/') + ' 鏂囦欢锛堝綋鍓嶏細' + esc(file.name) + '锛?);
|
||||
return;
|
||||
}
|
||||
}
|
||||
// P0鈥態锛氶」鐩凡棰勭疆鍚岀被鍨嬫椂鏄惧紡纭瑕嗙洊锛堜笉鍐嶄互"钘忚捣鍏ュ彛"鍋氶殣寮忕害鏉燂級
|
||||
if (projectHasPrefixedType(ft)) {
|
||||
const ok = confirm('椤圭洰宸查缃?' + ft + '銆傜户缁笂浼犲皢瑕嗙洊璇ヤ細璇濅腑鐨勬绫诲瀷鏂囦欢锛屾槸鍚︾户缁紵');
|
||||
if (!ok) return;
|
||||
}
|
||||
const fd = new FormData();
|
||||
fd.append('file_type', ft);
|
||||
fd.append('file', file);
|
||||
const statusEl = document.getElementById('upload-status');
|
||||
statusEl.textContent = '涓婁紶涓€?;
|
||||
try {
|
||||
const r = await fetch('/api/sessions/' + encodeURIComponent(sid) + '/files', { method: 'POST', body: fd });
|
||||
const d = await r.json();
|
||||
if (!r.ok) throw new Error(d.detail?.message || r.status);
|
||||
statusEl.textContent = '';
|
||||
// B5 / P1鈥慒锛氫笂浼犳垚鍔熷悗鍚屾 activeProject銆佸埛鏂颁笂浼犳潯涓庝晶杈规爮鐘舵€? const rec = await api('GET', '/api/sessions/' + encodeURIComponent(sid));
|
||||
activeProject = rec.project || null;
|
||||
badge.textContent = '浼氳瘽: ' + (rec.name || '鏂颁細璇?);
|
||||
await refreshSessions();
|
||||
updateUploadBar(); // P1鈥慒锛氫笂浼犳垚鍔熷悗鍚屾涓婁紶鏉★紙闃茬姸鎬佹粸鍚庯級
|
||||
await refreshRagStats(); // P0鈥慉锛氫笂浼?existing_system 鍚?RAG 绱㈠紩宸插缓
|
||||
document.getElementById('file-input').value = ''; // 浠呮垚鍔熸椂娓呯┖
|
||||
addMsg('user', '[涓婁紶] ' + ft + '锛? + d.file_name);
|
||||
addMsg('progress', '<span class="progress-item ok">涓婁紶瀹屾垚锛? + esc(d.file_name) + '锛? + d.size + 'B锛?/span>');
|
||||
} catch (e) {
|
||||
statusEl.textContent = '';
|
||||
// F1锛氬け璐ヤ繚鐣?file-input 鍊硷紝灞曠ず鍚庣鏄庣粏
|
||||
addMsg('error', '涓婁紶澶辫触锛? + esc(String(e)));
|
||||
}
|
||||
});
|
||||
|
||||
// ---------- 鍚姩锛氭仮澶嶄晶杈规爮鎶樺彔鎬併€佷笂娆′細璇?----------
|
||||
(async () => {
|
||||
try {
|
||||
const collapsed = localStorage.getItem('genesis_sidebar_collapsed') === '1';
|
||||
if (collapsed) document.getElementById('sidebar').classList.add('collapsed');
|
||||
} catch (e) { /* 蹇界暐 */ }
|
||||
await loadProjects();
|
||||
const saved = (() => { try { return localStorage.getItem('genesis_session'); } catch (e) { return null; } })();
|
||||
if (saved) {
|
||||
// P2鈥慔锛氬惎鍔ㄦ仮澶嶅墠鏄剧ず loading 鍗犱綅锛岄伩鍏嶇┖ chat 涓€闂? addMsg('assistant', '姝e湪鎭㈠涓婃浼氳瘽鈥?);
|
||||
try {
|
||||
await loadSession(saved);
|
||||
// P2鈥?锛氭仮澶嶅悗鑻ヤ細璇濈殑椤圭洰宸茶鍒狅紝娓呮帀 localStorage 浠ュ厤涓嬫鍐嶈瘯
|
||||
const rec = await api('GET', '/api/sessions/' + encodeURIComponent(saved));
|
||||
const recProj = rec && rec.project;
|
||||
if (recProj && !projects.find(p => p.name === recProj)) {
|
||||
try { localStorage.removeItem('genesis_session'); } catch (e) { /* 蹇界暐 */ }
|
||||
// 椤舵爮鑻ユ樉绀虹殑鏄凡鍒犻」鐩紝鍒锋柊鍥為€€
|
||||
if (draftProject === recProj) {
|
||||
draftProject = (projects.length > 0) ? projects[0].name : null;
|
||||
applyProjectContext();
|
||||
}
|
||||
}
|
||||
return;
|
||||
} catch (e) { /* 蹇界暐锛屾柊寤?*/ }
|
||||
}
|
||||
newSession().catch(e => addMsg('error', esc(String(e))));
|
||||
})();␍
|
||||
Reference in New Issue
Block a user