Spaces:
Sleeping
Sleeping
File size: 67,566 Bytes
8f4045a 115b94d 8f4045a 115b94d 8f4045a 115b94d 8f4045a 115b94d 8f4045a 115b94d 8f4045a 115b94d 8f4045a 115b94d 8f4045a 115b94d 8f4045a 115b94d 8f4045a 115b94d 8f4045a 115b94d 8f4045a 115b94d 8f4045a 115b94d 8f4045a 115b94d 8f4045a 115b94d 8f4045a 115b94d 8f4045a 115b94d 8f4045a 115b94d 8f4045a 115b94d 8f4045a 115b94d 8f4045a 115b94d 8f4045a 115b94d 8f4045a 115b94d 8f4045a 115b94d 8f4045a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 | import * as runtime from './runtime.js';
import { USERS, uid, loadState, saveState, putHandle, getHandle, deleteHandle } from './local-store.js';
import { icon, mountIcons } from './icons.js';
const $ = id => document.getElementById(id);
const esc = value => String(value ?? '').replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
const MODELS = [{ id: 'auto', name: '自动选择' }];
const BASES = [{ id: 'java', name: 'Java 编码规约', description: '企业规范与工程约定' }, {id:'java-basics',name:'Java 基础知识',description:'Java 语言、十进制计算与标准库资料'}, {id:'java-integration',name:'Java 集成知识',description:'文件解析、依赖与接口集成资料'}, { id: 'erp', name: 'ERP 订单知识库', description: '本地演示采购订单、收货与付款数据' }, { id: 'wms', name: 'WMS 库存知识库', description: '本地演示库存、出入库与数量规则' }, { id: 'equipment', name: '设备工单知识库', description: '本地演示工单、处理流程与状态规则' }, { id: 'sap', name: 'SAP 接口参考', description: '接口说明与测试约定' }];
let state = loadState();
for(const savedChat of state.chats) for(const message of savedChat.messages||[]) {
message.scopeBusy=false;
for(const slot of ['actionState','resetState']) if(message[slot]?.status==='submitting') Object.assign(message[slot],{status:'unknown',error:'上次请求结果尚待核对。再次点击会用同一请求号核对,不重复执行。'});
}
let currentChatId = null;
let draftProjectId = null;
let prefs = { model: 'auto', skill: false, bases: [] };
let attachments = [];
let pending = null;
let drawer = null;
let toastTimer;
let menuActions = [];
let menuAnchor = null;
let projectDraft = null;
let deleteTarget = null;
let folderTarget = 'message';
let folderEpoch = 0;
let switchingUser = false;
const budgetInFlight=new Set();
const user = () => USERS.find(u => u.id === state.currentUser);
const projects = () => state.projects.filter(p => p.owner === user().id);
const chats = () => state.chats.filter(c => c.owner === user().id).sort((a, b) => b.updated - a.updated);
const chat = () => chats().find(c => c.id === currentChatId) || null;
const selectedProjectId = () => chat()?.projectId || draftProjectId;
const project = id => projects().find(p => p.id === id) || null;
const selectedProject = () => project(selectedProjectId());
function toast(message) { clearTimeout(toastTimer); $('toast').textContent = message; toastTimer = setTimeout(() => { $('toast').textContent = ''; }, 4200); }
function persist() {
state.views ||= {};
state.views[user().id] = { chatId: chat()?.id || null, projectId: project(selectedProjectId())?.id || null, model: prefs.model, skill: prefs.skill, bases: [...prefs.bases] };
if (!saveState(state)) toast('浏览器存储不可用,当前修改仅在本次页面中保留。');
}
function restoreView() {
const view = state.views?.[user().id];
const c = chats().find(x => x.id === view?.chatId);
currentChatId = c?.id || null; draftProjectId = project(c?.projectId || view?.projectId)?.id || null;
const source = c || view;
prefs = { model: typeof source?.model === 'string' && /^[a-z0-9.-]{2,80}$/.test(source.model) ? source.model : 'auto', skill: source?.skill === true ? 'erp' : (typeof source?.skill === 'string' ? source.skill : false), bases: Array.isArray(source?.bases) ? source.bases.filter(id => BASES.some(b => b.id === id)) : [] };
}
function log(action, detail = '') {
state.logs.unshift({ id: uid(), owner: user().id, at: Date.now(), action, detail });
state.logs = state.logs.slice(0, 180);
persist();
if (drawer === 'logs') renderLogs();
}
function closeMobile() { $('shell').classList.remove('sidebar-open'); $('mobileScrim').hidden = true; }
function chatActivity(c){
const message=c.messages?.findLast(m=>m.job),job=message?.job;
if(pending?.chatId===c.id&&!pending.stopped&&pending.kind!=='java')return '<span class="execution-pulse chat-task-spinner" role="status" aria-label="此对话请求正在进行" title="此对话请求正在进行"></span>';
if(['waiting_budget','waiting_limit'].includes(job?.status))return '<span class="chat-task-state" role="status" title="任务已暂停,查看本轮预算或资源申请">待确认</span>';
if(job?.status==='unknown')return '<span class="chat-task-state" role="status" title="结果未知,保留预留且不自动重放">待核对</span>';
if(job?.status==='failed')return '<span class="chat-task-state" role="status" title="任务失败,打开对话查看原因和下一步">失败</span>';
if(['queued','working'].includes(job?.status)){
if(Date.now()-Number(job.observed_at||0)>12000)return '<span class="chat-task-state" role="status" title="状态尚未刷新,正在核对同一任务">待核对</span>';
return '<span class="execution-pulse chat-task-spinner" role="status" aria-label="此对话任务正在执行" title="此对话任务正在执行"></span>';
}
return pending?.chatId===c.id&&!pending.stopped?'<span class="execution-pulse chat-task-spinner" role="status" aria-label="此对话请求正在进行" title="此对话请求正在进行"></span>':'';
}
function renderSidebar() {
$('shell').classList.toggle('collapsed', !!state.collapsed);
$('collapseSidebar').setAttribute('aria-expanded', String(!state.collapsed));
$('collapseSidebar').setAttribute('aria-label', state.collapsed ? '展开侧栏' : '折叠侧栏');
$('collapseSidebar').title = state.collapsed ? '展开侧栏' : '折叠侧栏';
$('projectsNav').setAttribute('aria-expanded', String(state.projectsExpanded));
$('projectSection').hidden = !state.projectsExpanded;
$('profileName').textContent = user().name;
$('profileRole').textContent = user().role;
$('avatar').textContent = user().initial;
$('profileSwitch').title = `${user().name} · ${user().role},点击切换人员`;
$('projectList').innerHTML = projects().map(p => {
const items = chats().filter(c => c.projectId === p.id).slice(0, 5);
return `<div class="project-row${selectedProjectId() === p.id ? ' active' : ''}"><button class="project-open" data-project="${esc(p.id)}" title="${esc(p.name)}" aria-expanded="${p.expanded}">${icon('folder')}<span class="project-title">${esc(p.name)}</span></button><button class="icon-button project-options" data-project-menu="${esc(p.id)}" title="${esc(p.name)}选项" aria-label="${esc(p.name)}选项">${icon('more')}</button></div>${p.expanded ? `<div class="project-conversations">${items.map(c => `<button data-chat="${esc(c.id)}" title="${esc(c.title)}"><span class="chat-task-title">${esc(c.title)}</span>${chatActivity(c)}</button>`).join('')}<button class="project-new-chat" data-project-chat="${esc(p.id)}">${icon('plus')}新对话</button></div>` : ''}`;
}).join('');
$('spaceList').innerHTML = chats().map(c => `<div class="chat-row${currentChatId === c.id ? ' active' : ''}"><button class="space" data-chat="${esc(c.id)}" title="${esc(c.title)}">${icon('chat')}<span>${esc(c.title)}</span>${chatActivity(c)}</button><button class="icon-button chat-options" data-chat-menu="${esc(c.id)}" title="对话选项:${esc(c.title)}" aria-label="对话选项:${esc(c.title)}">${icon('more')}</button></div>`).join('') || '<div class="menu-empty">从一条新对话开始。</div>';
}
function renderContext() {
const p = selectedProject();
$('composerProject').textContent = p?.name || '选择项目';
$('projectPicker').title = p ? `当前项目:${p.name},点击切换` : '选择项目,或保持独立对话';
$('directoryCount').textContent = p?.folders.length ? `${p.folders.length} 个目录` : '';
$('headerProject').hidden = !p || !chat();
$('headerProject').textContent = p?.name || '';
$('matterTitle').textContent = chat()?.title || '新对话';
$('welcomeDescription').textContent = p ? `在「${p.name}」中开始。` : '一个想法,一段对话。';
$('modelLabel').textContent = prefs.model==='auto' ? '自动选择模型' : prefs.model;
$('skillLabel').textContent = prefs.skill ? `Skill · ${runtime.skillOptions().find(s => s.id === prefs.skill)?.name || 'Java ERP'}` : 'Skill';
const coding=prefs.skill&&runtime.skillOptions().find(s=>s.id===prefs.skill)?.kind!=='business'&&runtime.session?.capabilities?.automatic_recovery;
const note=document.querySelector('.compose-note');
note.innerHTML=coding?'Enter 发送<span>·</span>自动诊断修复,必要时续修1轮<span>·</span>Shift + Enter 换行':'Enter 发送<span>·</span>Shift + Enter 换行<span>·</span>对话与项目保存在此浏览器';
note.title=coding?'每任务最多6次调用、120000 Token、2次诊断修复;额外自动续修最多1轮。两轮合计最多12次调用、240000 Token,仍受服务端配额限制。':'';
if(coding&&runtime.session?.budget_policy?.mode==='one-call-overdraft-v1'){note.innerHTML='Enter 发送<span>·</span>额度不足先行一步并申请追加<span>·</span>Shift + Enter 换行';note.title='初始任务额度不变;额度不足时允许先行一次请求并申请追加12000 Token,未决定前不叠加模型调用,拒绝会中断后续。';}
if(coding&&runtime.session?.budget_policy?.mode==='unlimited-usage-v1'){note.innerHTML='Enter 发送<span>·</span>本地新任务不限用量<span>·</span>Shift + Enter 换行';note.title='不设平台任务 Token、模型调用次数或累计执行时间额度。实际用量显示在下方;供应商限制、未知结果和故障仍如实停止。';}
if(prefs.skill&&runtime.session?.resource_limits){const r=runtime.session.resource_limits;note.textContent=`内网轻量模式 · 每阶段最多 ${r.max_model_calls} 次调用、${r.max_tokens} Token、${r.max_repairs} 轮修复;确认范围后开始`;note.title='所有重试共用任务账本;超限暂停,不另开自动续修预算。';}
$('chooseSkills').classList.toggle('selected-choice', prefs.skill);
$('knowledgeLabel').textContent = prefs.bases.length ? `知识库 · ${prefs.bases.length}` : '知识库';
$('chooseBases').classList.toggle('selected-choice', !!prefs.bases.length);
$('attachmentChips').innerHTML = attachments.map((f, i) => `<span class="chip">${icon(f.type === 'directory' ? 'folder' : 'file')}<span title="${esc(f.name)}">${esc(f.name)}${f.type === 'directory' ? '/' : ''}</span><button type="button" data-remove-attachment="${i}" aria-label="移除${esc(f.name)}">${icon('close')}</button></span>`).join('');
updateSend();
}
function renderMessages() {
renderTokenMeter();
const c = chat();
if(pending&&!pending.startedAt)pending.startedAt=Date.now();
const waitingMessage=pending&&c?.messages.findLast(m=>m.job?.id===pending.runId);
const openDetails=[...document.querySelectorAll('.development-result details[open][data-detail]')].map(el=>[el.closest('.development-result').dataset.runId,el.dataset.detail]);
$('welcome').hidden = !!c?.messages.length;
$('messages').innerHTML = (c?.messages || []).map((m, i) => `<article class="message ${m.role === 'user' ? 'user' : 'assistant'}">${m.role === 'assistant' ? '<div class="message-head"><span class="assistant-mark"></></span>Vibe Coding</div>' : ''}${m.attachments?.length ? `<div class="message-attachments">${m.attachments.map(f => `<span>${esc(f.name)}${f.type === 'directory' ? '/' : ''}</span>`).join('')}</div>` : ''}<div class="message-body">${m.scope ? '旧范围裁剪方案已撤回;历史记录保留。可直接提交完整原需求,按原流程执行。' : m.business ? runtime.renderBusinessMessage(m.business,i,m.actionState,m.resetState) : m.job ? runtime.renderJobMessage(m.job,i,m.jobError,m.repairConfirmation) : esc(m.content)}</div>${m.role === 'assistant' ? `<div class="message-meta">${m.preview ? '<span>前端交互示例</span>' : ''}<button class="icon-button message-copy" data-copy-message="${i}" aria-label="复制回复" title="复制回复">${icon('copy')}</button></div>` : ''}</article>`).join('') + (pending && c && pending.chatId === c.id ? runtime.renderPendingMessage(waitingMessage?.job,pending,waitingMessage?.jobError) : '');
const approvals=(c?.messages||[]).map((m,i)=>m.scope?'':hasBudgetDecision(m.job)?`<section class="development-result" data-run-id="${esc(m.job.id)}">${runtime.renderBudgetApproval({...m.job,jobError:m.jobError},i,false,budgetInFlight.has(m.job.id))}</section>`:'').filter(Boolean);
if(approvals.length)$('messages').insertAdjacentHTML('beforeend',`<article class="message assistant approval-latest" aria-label="最新待确认事项"><div class="message-head"><span class="assistant-mark"></></span>Vibe Coding · 等待你的确认</div><div class="message-body">${approvals.join('')}<p>追加申请可在此决定;先行请求已发出时可能产生费用。未决定前不叠加模型请求,拒绝会中断后续;刷新后仍可查看。</p></div></article>`);
for(const [runId,key] of openDetails){const section=[...document.querySelectorAll('.development-result')].find(el=>el.dataset.runId===runId);const detail=section?.querySelector(`details[data-detail="${key}"]`);if(detail)detail.open=true;}
document.querySelectorAll('[data-job-budget],[data-job-followup],[data-job-repair],[data-job-refresh],.development-result button[data-runtime]').forEach(button=>{button.disabled=!!switchingUser||budgetInFlight.has(button.closest('.development-result')?.dataset.runId);});
document.querySelectorAll('.development-result a').forEach(link=>{link.inert=!!switchingUser;});
runtime.tickJobClocks();
syncBudgetDialog();
}
function renderTokenMeter(){
const meter=$('taskTokenMeter');if(!meter)return;
const jobs=[...new Map((chat()?.messages||[]).filter(m=>m.job).map(m=>[m.job.id,m.job])).values()];
const tokens=jobs.reduce((sum,job)=>sum+(job.usage?.settled_tokens??(job.model_calls||[]).reduce((n,c)=>n+(c.charged||0),0)),0);
const pending=jobs.some(job=>job.usage?.unknown_calls||job.usage?.pending_calls||(job.model_calls||[]).some(c=>['reserved','unknown'].includes(c.state)));
meter.textContent=`本对话已用 ${Number(tokens).toLocaleString('zh-CN')} Token${pending?' · 本次调用用量待回执':''}`;
meter.title=jobs.length?'本对话各编程任务已结算的输入和输出累计,同一任务只计一次,包含关联续修。预留不算实际消耗,回执返回后更新。':'当前对话尚无编程任务。';
}
function hasBudgetDecision(job){return !!(job?.budget_request?.mode==='overdraft'||['waiting_budget','waiting_limit'].includes(job?.status));}
function budgetDismissKey(job){return `${user().id}:${job.id}`;}
function closeBudgetDialog(){
const dialog=$('budgetDialog');
if(dialog.dataset.runId&&dialog.dataset.digest){
state.budgetDismissed||={};state.budgetDismissed[`${user().id}:${dialog.dataset.runId}`]=dialog.dataset.digest;saveState(state);
}
dialog.close();
document.querySelector(`.approval-latest [data-run-id="${dialog.dataset.runId}"] [data-budget-card]`)?.scrollIntoView({block:'start'});
}
function syncBudgetDialog(forceIndex=null){
const dialog=$('budgetDialog'),messages=chat()?.messages||[];
const index=forceIndex??messages.findLastIndex(m=>hasBudgetDecision(m.job)&&(m.job.budget_request||m.job.limit_request));
const message=messages[index],job=message?.job,b=job?.budget_request||job?.limit_request;
if(switchingUser||!job||!hasBudgetDecision(job)||!b){if(dialog.open)dialog.close();return;}
const dismissed=state.budgetDismissed?.[budgetDismissKey(job)]===b.digest||b.deferred;
if(forceIndex===null&&dismissed&&!dialog.open)return;
const stamp=[job.id,b.digest,budgetInFlight.has(job.id),message.jobError||''].join(':');
if(dialog.dataset.stamp!==stamp){
$('budgetDialogBody').innerHTML=runtime.renderBudgetApproval({...job,jobError:message.jobError},index,true,budgetInFlight.has(job.id));
dialog.dataset.stamp=stamp;dialog.dataset.runId=job.id;dialog.dataset.digest=b.digest;
}
if(!dialog.open)dialog.showModal();
}
$('budgetDialog').addEventListener('cancel',event=>{event.preventDefault();closeBudgetDialog();});
function render() { renderSidebar(); renderContext(); renderMessages(); if (drawer === 'folders') renderFolders(); }
function bottom() { requestAnimationFrame(() => {
const approval=document.querySelector('.approval-latest');
if(approval)approval.scrollIntoView({block:'start'});
else $('chatScroll').scrollTop = $('chatScroll').scrollHeight;
}); }
function updateSend() {
const isPending = pending?.chatId === currentChatId && !!currentChatId;
$('send').disabled = switchingUser || (!isPending && !$('prompt').value.trim());
for(const id of ['profileSwitch','runtimeNav','modelPicker'])$(id).disabled=!!switchingUser;
$('send').innerHTML = icon(isPending ? 'stop' : 'arrowUp');
$('send').title = isPending ? '停止等待 / 取消任务' : '发送消息';
$('send').setAttribute('aria-label', isPending ? '停止等待 / 取消任务' : '发送消息');
}
function resetDraft(projectId = null) {
closeMenu();
currentChatId = null;
draftProjectId = project(projectId) ? projectId : null;
attachments = [];
prefs = { model: 'auto', skill: false, bases: [] };
$('prompt').value = '';
$('prompt').style.height = '';
render(); persist(); closeMobile(); $('prompt').focus();
}
function openChat(id) {
const c = chats().find(x => x.id === id);
if (!c) return;
closeMenu(); currentChatId = c.id; draftProjectId = c.projectId;
prefs = { model: c.model || 'auto', skill: c.skill === true ? 'erp' : c.skill, bases: [...(c.bases || [])] };
attachments = []; $('prompt').value = ''; $('prompt').style.height = '';
render(); bottom(); closeMobile();
log('打开对话', c.projectId ? '已恢复项目与绑定目录引用' : '独立对话');
resumeVisibleJob();
}
function updatePrefs() { const c = chat(); if (c) Object.assign(c, { model: prefs.model, skill: prefs.skill, bases: [...prefs.bases] }); persist(); renderContext(); }
function closeMenu(restoreFocus = false) {
$('popover').hidden = true;
menuAnchor?.setAttribute('aria-expanded', 'false');
if (restoreFocus && menuAnchor?.isConnected) menuAnchor.focus();
menuActions = [];
}
function menu(anchor, entries, title = '') {
closeMenu(); menuAnchor = anchor;
$('popover').classList.toggle('skill-picker',entries.some(e=>e.card));
menuActions = entries.filter(e => !e.separator);
let i = 0;
$('popover').innerHTML = (title ? `<div class="popover-heading">${esc(title)}</div>` : '') + entries.map(e => {
if (e.separator) return '<div class="menu-separator" role="separator"></div>';
return `<button class="menu-item${e.card?' skill-card-choice':''}${e.selected ? ' selected' : ''}${e.danger ? ' danger' : ''}" role="menuitem" data-menu-index="${i++}" ${e.card?`data-product-skill="${esc(e.card.id)}"`:''} ${e.disabled?'disabled':''}>${e.card?`<span class="product-skill-icon ${esc(e.card.icon)}">${runtime.skillIcon(e.card.icon)}</span>`:icon(e.icon || 'file')}<span class="menu-copy"><strong>${esc(e.label)}</strong>${e.description ? `<small>${esc(e.description)}</small>` : ''}${e.card?`<small>工作流 · ${e.card.node_count}节点 · r${e.card.revision}</small>`:''}</span>${e.selected ? `<span class="check-icon">${icon('check')}</span>` : ''}</button>`;
}).join('');
$('popover').hidden = false;
anchor.setAttribute('aria-expanded', 'true');
const r = anchor.getBoundingClientRect(), box = $('popover').getBoundingClientRect();
let left = r.left, top = r.bottom + 6;
if (state.collapsed && anchor.closest('.sidebar')) { left = r.right + 14; top = r.top; }
if (top + box.height > innerHeight - 12) top = Math.max(10, r.top - box.height - 7);
$('popover').style.left = `${Math.max(10, Math.min(left, innerWidth - box.width - 10))}px`;
$('popover').style.top = `${top}px`;
}
function newChatMenu(anchor) {
menu(anchor, [
{ label: '独立对话', description: '不绑定项目,直接开始', icon: 'chat', action: () => resetDraft() },
{ label: '项目对话', description: '选择项目,继承目录上下文', icon: 'folder', action: () => { resetDraft(); projectMenu($('projectPicker')); } }
], '创建新对话');
}
function chooseProject(id) {
if (chat() && chat().projectId !== id) { resetDraft(id); toast('已切换到新对话,原对话保留。'); }
else { draftProjectId = id; renderSidebar(); renderContext(); }
log('选择项目', id ? project(id)?.name || '' : '独立对话');
}
function projectMenu(anchor) {
menu(anchor, [
{ label: '独立对话', icon: 'chat', selected: !selectedProjectId(), action: () => chooseProject(null) },
...projects().map(p => ({ label: p.name, description: p.folders.length ? `${p.folders.length} 个本地目录` : '尚未绑定目录', icon: 'folder', selected: selectedProjectId() === p.id, action: () => chooseProject(p.id) })),
{ separator: true }, { label: '新建项目', icon: 'plus', action: () => openProjectDialog() }
], '选择项目');
}
function projectOptions(id, anchor) {
const p = project(id); if (!p) return;
menu(anchor, [
{ label: '新建项目对话', icon: 'new', action: () => resetDraft(id) },
{ label: '项目与目录', icon: 'folder', action: () => { chooseProject(id); showDrawer('folders'); } },
{ label: '编辑项目', icon: 'file', action: () => openProjectDialog(id) },
{ separator: true }, { label: '删除项目', icon: 'trash', danger: true, action: () => confirmProjectDelete(id) }
], p.name);
}
function skillMenu(anchor) {
menu(anchor,[...runtime.productSkills.map(s=>({label:s.name,description:s.description,card:s,selected:prefs.skill===s.id,action:()=>selectSkill(s.id)})),{separator:true},{label:'普通对话',description:'不使用编程工作流',icon:'chat',action:()=>{prefs.skill=false;prefs.bases=[];updatePrefs();}}],'选择 Skill · 3 个编程工作流');
}
function knowledgeMenu(anchor) {
menu(anchor, BASES.map(b => ({ label: b.name, description: b.description, icon: 'book', selected: prefs.bases.includes(b.id), action: () => selectKnowledge(b.id) })), '选择知识库');
}
function closeDrawer() { drawer=null;++folderEpoch;runtime.dismiss();$('drawer').hidden=true; }
function injectBusiness(scenario,prompt) {
const preset=runtime.businessPresets.find(p=>p.scenario===scenario);if(!preset)return;
closeMenu();closeDrawer();closeMobile();
prefs.skill=preset.id;prefs.bases=[preset.base];
$('prompt').value=prompt??preset.prompt;
$('prompt').dispatchEvent(new Event('input'));updatePrefs();$('prompt').focus();
}
function injectDevelopment(scenario) {
const spec=runtime.scenarios.find(s=>s.id===scenario),brief=runtime.javaDevelopmentPrompt(scenario);
if(!spec||!brief){toast('当前用户尚无该开发场景的完整需求或项目权限,请刷新后查看。');return;}
syncServerProjects();
const target=projects().find(p=>p.id===`${user().id}:${spec.project_id}`)||projects().find(p=>p.serverId===spec.project_id);
if(!target){toast('此开发场景的项目权限不可用。');return;}
const chosenModel=prefs.model;
closeDrawer();resetDraft(target.id);
prefs.model=chosenModel;
prefs.skill=scenario;prefs.bases=[runtime.developmentPresets.find(p=>p.id===scenario)?.knowledge||'java'];
$('prompt').value=brief;$('prompt').dispatchEvent(new Event('input'));updatePrefs();$('prompt').focus();
toast('已填入完整开发需求;确认后发送,开始真实编码与验证。');
}
function selectSkill(id) {
if(runtime.productSkills.some(s=>s.id===id)){
const current=$('prompt').value.trim(),isBrief=runtime.scenarios.some(s=>s.requirement.trim()===current);
injectDevelopment(id);
if(current&&!isBrief){$('prompt').value=current;$('prompt').dispatchEvent(new Event('input'));}
return;
}
const preset=runtime.businessPresets.find(p=>p.id===id);
if(preset){injectBusiness(preset.scenario,$('prompt').value.trim()||preset.prompt);return;}
prefs.skill=id;closeDrawer();updatePrefs();$('prompt').focus();
}
function selectKnowledge(id) {
const preset=runtime.businessPresets.find(p=>p.base===id);
if(preset){injectBusiness(preset.scenario,$('prompt').value.trim()||preset.prompt);return;}
if(runtime.businessPresets.some(p=>p.id===prefs.skill)){prefs.skill=false;prefs.bases=[];}
prefs.bases=prefs.bases.includes(id)?prefs.bases.filter(x=>x!==id):[...prefs.bases,id];
closeDrawer();updatePrefs();$('prompt').focus();
}
async function modelMenu(anchor) {
const entries=[{label:'自动选择',description:'由服务端按任务阶段选择模型',icon:'skill',selected:prefs.model==='auto',action:()=>{prefs.model='auto';updatePrefs();}}];
try {
const routes=await runtime.refreshModels();
const codingModel=routes.effective_policy?.['java-code'];
if(routes.models.some(m=>m.provider==='openai'&&m.model===codingModel))entries[0].description=`默认 ${routes.effective_policy?.design||codingModel} · medium(中等)`;
const roles={chat:'普通对话',design:'技术设计',diagnose:'故障定位',code:'网页与Java编码',repair:'错误修复'};
for(const m of routes.models.filter(m=>m.selectable).sort((a,b)=>Number(b.provider==='openai')-Number(a.provider==='openai'))){
const available=m.health.status==='healthy';
entries.push({label:m.model,description:(available?'API 已验证 · ':'当前不可选 · ')+(m.reasoning_effort?`${m.reasoning_effort}(中等) · `:'')+m.roles.map(r=>roles[r]||r).join(' · '),
icon:'skill',selected:prefs.model===m.model,disabled:!available,
action:()=>{prefs.model=m.model;updatePrefs();}});
}
} catch {entries.push({label:'读取任务模型记录',description:'实际选模与用量随任务保存,可在任务详情核对',action:()=>openRuntime('jobs')});}
menu(anchor,entries,'选择大模型');
}
async function switchUser(id) {
if (switchingUser||!USERS.some(u => u.id === id)) return;
persist();
switchingUser=true;
if(pending){pending.stopped=true;pending=null;}
try { await runtime.authenticate(id); } finally { switchingUser=false; }
// Switching a view does not cancel another actor's server task.
pending = null; state.currentUser = id; drawer = null; $('drawer').hidden = true;
syncServerProjects();
attachments = []; $('prompt').value = ''; closeMenu(); closeMobile(); restoreView(); render(); persist();
log('切换登录用户', user().role); toast(`已登录:${user().name} · ${user().role}`);
resumeVisibleJob();
}
function syncServerProjects() {
for(const p of projects()) if(p.id === 'example-java-erp') p.serverId = 'erp-demo';
for (const p of runtime.session.projects) {
const id = `${user().id}:${p.id}`;
if (!state.projects.some(x => x.id === id)) state.projects.push({id,owner:user().id,name:p.name,serverId:p.id,folders:[],expanded:false});
}
}
function openRuntime(view) { if(runtime.businessPresets.some(p=>p.scenario===view)){injectBusiness(view);return;} closeMenu(); drawer = 'runtime'; $('drawer').hidden = false; closeMobile(); runtime.show(view); }
function openProjectDialog(id = null) {
const p = project(id);
projectDraft = { id: p?.id || null, owner: user().id, folders: (p?.folders || []).map(f => ({ ...f })), newHandles: new Map() };
$('projectName').value = p?.name || '';
$('projectDialogTitle').textContent = p ? '编辑项目' : '创建项目';
$('saveProject').textContent = p ? '保存项目' : '创建项目';
$('projectError').textContent = '';
$('folderHelp').textContent = 'showDirectoryPicker' in window ? '重新打开项目时保留目录引用;浏览器可能需要再次授权。' : '此浏览器使用目录选择兼容模式:仅记住目录名,刷新后请重新选择以恢复访问。';
renderProjectFolders(); $('projectDialog').showModal();
requestAnimationFrame(() => $('projectName').focus());
}
function folderStatus(f) { return f.mode === 'handle' ? '本地目录引用 · 访问时核验授权' : '目录名称已记录 · 需重新选择以访问'; }
function renderProjectFolders() {
$('projectFolders').innerHTML = (projectDraft?.folders || []).map(f => `<div class="folder-row">${icon('folder')}<span class="folder-details"><strong>${esc(f.name)}</strong><small>${esc(folderStatus(f))}</small></span><button class="icon-button" type="button" data-remove-folder="${esc(f.id)}" aria-label="移除目录${esc(f.name)}">${icon('close')}</button></div>`).join('');
}
async function pickDirectory(target) {
folderTarget = target;
if (!('showDirectoryPicker' in window)) { $('directoryPicker').click(); return; }
try {
const handle = await window.showDirectoryPicker({ mode: 'read', id: 'zkcoding-source' });
const f = { id: uid(), name: handle.name, type: 'directory', mode: 'handle' };
if (target === 'project' && !projectDraft) return;
if (target === 'project' && projectDraft) {
// Two roots can have the same basename. Deduplicate by identity, never by name.
for (const existing of projectDraft.folders) {
const old = projectDraft.newHandles.get(existing.id) || await getHandle(existing.id, user().id).catch(() => null);
if (old && await old.isSameEntry(handle)) { toast('这个目录已经添加。'); return; }
}
projectDraft.folders.push(f); projectDraft.newHandles.set(f.id, handle);
if (!$('projectName').value.trim()) $('projectName').value = handle.name;
renderProjectFolders();
} else { attachments.push({ ...f, handle }); renderContext(); }
log('选择本地目录', '仅取得浏览器本地只读授权,未上传文件内容');
} catch (error) {
if (error.name === 'AbortError') return;
if (error.name === 'SecurityError' || error.name === 'NotAllowedError') { toast('浏览器限制了目录授权,请使用兼容目录选择。'); $('directoryPicker').click(); }
else toast(`目录选择失败:${error.message}`);
}
}
function fallbackDirectory(files) {
if (!files.length) return;
const groups = new Map();
for (const f of files) { const name = f.webkitRelativePath?.split('/')[0] || '所选目录'; groups.set(name, (groups.get(name) || 0) + 1); }
for (const [name, count] of groups) {
const f = { id: uid(), name, count, type: 'directory', mode: 'metadata' };
if (folderTarget === 'project' && projectDraft) { projectDraft.folders.push(f); if (!$('projectName').value.trim()) $('projectName').value = name; }
else attachments.push(f);
}
renderProjectFolders(); renderContext();
toast('已记录所选目录;兼容模式下刷新后需重新选择。');
log('选择目录(兼容模式)', '仅保存目录元数据,不上传文件');
}
async function saveProject(event) {
event.preventDefault();
if (!projectDraft || projectDraft.owner !== user().id) return;
const name = $('projectName').value.trim();
if (!name) { $('projectError').textContent = '请填写项目名称。'; return; }
const existing = projects().find(p => p.name === name && p.id !== projectDraft.id);
if (existing) { $('projectError').textContent = '已有同名项目,请使用另一个名称。'; return; }
$('saveProject').disabled = true;
try {
const draft = projectDraft;
for (const f of draft.folders) {
const handle = draft.newHandles.get(f.id);
if (handle) try { await putHandle(f.id, user().id, handle); } catch { f.mode = 'metadata'; toast('浏览器未保存目录授权,目录名称已保留,访问时需重新选择。'); }
}
let p = project(draft.id);
if (p) {
const removed = p.folders.filter(f => !draft.folders.some(n => n.id === f.id));
p.name = name; p.folders = draft.folders;
await Promise.all(removed.map(f => deleteHandle(f.id).catch(() => {})));
} else {
p = { id: uid(), owner: user().id, name, folders: draft.folders, created: Date.now(), expanded: true };
state.projects.push(p); state.projectsExpanded = true;
}
const editing = !!draft.id;
persist(); $('projectDialog').close(); projectDraft = null;
if (!editing) resetDraft(p.id); else { render(); if (drawer === 'folders') renderFolders(); }
log(editing ? '更新项目' : '创建项目', `${name} · ${p.folders.length} 个本地目录`);
toast(editing ? '项目已保存。' : '项目已创建,可以开始对话。');
} finally { $('saveProject').disabled = false; }
}
function confirmProjectDelete(id) {
const p = project(id); if (!p) return;
deleteTarget = { type: 'project', id };
$('deleteTitle').textContent = '删除项目';
$('deleteDescription').textContent = `删除「${p.name}」及其目录引用?本地文件不会被删除,已有对话保留为独立对话。`;
$('deleteDialog').showModal();
}
function confirmChatDelete(id) {
const c = chats().find(x => x.id === id); if (!c) return;
deleteTarget = { type: 'chat', id };
$('deleteTitle').textContent = '删除对话';
$('deleteDescription').textContent = `删除「${c.title}」的本地对话记录?项目和本地文件会保留。`;
$('deleteDialog').showModal();
}
async function deleteConfirmed() {
if (!deleteTarget) return;
const target = deleteTarget; deleteTarget = null; $('deleteDialog').close();
if (target.type === 'project') {
const p = project(target.id); if (!p) return;
state.projects = state.projects.filter(x => x.id !== p.id);
chats().filter(c => c.projectId === p.id).forEach(c => { c.projectId = null; });
if (draftProjectId === p.id) draftProjectId = null;
await Promise.all(p.folders.map(f => deleteHandle(f.id).catch(() => {})));
log('删除项目', '移除本地项目与目录引用,保留文件和对话');
} else {
const c = chats().find(x => x.id === target.id); if (!c) return;
if (pending?.chatId === c.id) stopReply();
state.chats = state.chats.filter(x => x.id !== c.id);
if (currentChatId === c.id) resetDraft(c.projectId);
log('删除对话', '仅删除本地记录');
}
persist(); render(); if (drawer === 'folders') renderFolders();
}
function showDrawer(mode) { closeMenu(); drawer = mode; $('drawer').hidden = false; closeMobile(); renderDrawer(); }
function renderDrawer() {
if (drawer === 'logs') return renderLogs();
if (drawer === 'folders') return renderFolders();
const config = {
skills: ['Skill', `<div class="drawer-note">Skill 为可选项。不选时使用普通大模型对话;选用后按对应 Skill 编程。</div><div class="resource-card"><h3>Java ERP</h3><p>用批准的框架与规约约束 Java、HTML 和 JavaScript 工程。</p><div class="resource-tags"><span>Java</span><span>HTML / JS</span><span>ERP</span></div><button class="drawer-button" data-toggle-skill>${prefs.skill ? '已选用 · 点击取消' : '在当前对话选用'}</button></div><div class="drawer-note">本页为样式原型;Skill 执行、版本发布与框架检查暂未接入。</div>`],
knowledge: ['知识库', `<div class="drawer-note">选择知识库后,业务问题与结果直接进入当前对话。三个业务演示使用可查询、可登记并回读的本地数据。</div>${BASES.map(b => `<div class="resource-card"><h3>${esc(b.name)}</h3><p>${esc(b.description)}</p><button class="drawer-button" data-toggle-base="${b.id}">${prefs.bases.includes(b.id) ? '在当前对话使用' : '选择知识库'}</button></div>`).join('')}`],
schedule: ['定时任务', `<div class="drawer-empty">${icon('clock')}<h3>暂未创建定时任务</h3><p>当前先预览工作台样式。<br>自动调度与执行将在后续接入。</p></div>`],
connections: ['连接', `<div class="drawer-empty">${icon('link')}<h3>连接能力暂未启用</h3><p>配置库、制品库和企业系统<br>将在后续通过统一工具入口接入。</p></div>`]
}[drawer];
if (config) { $('drawerTitle').textContent = config[0]; $('drawerBody').innerHTML = config[1]; }
}
function renderLogs() {
const items = state.logs.filter(l => l.owner === user().id).slice(0, 45);
$('drawerTitle').textContent = '运行日志';
$('drawerBody').innerHTML = `<div class="log-summary"><div><strong>${items.length}</strong><small>本地交互事件</small></div><div><strong>0</strong><small>模型 / API 请求</small></div></div><div class="drawer-heading-row"><strong>最近记录</strong><button class="drawer-button" data-clear-logs>清空</button></div><p class="drawer-note">仅记录此浏览器的界面操作,不代表后端或模型调用。</p>${items.map(l => `<div class="log-entry"><span class="log-entry-dot"></span><div><strong>${esc(l.action)}</strong><p>${esc(l.detail)}</p><time>${esc(new Date(l.at).toLocaleString('zh-CN', { hour12: false }))}</time></div></div>`).join('') || '<div class="menu-empty">暂无记录</div>'}`;
}
async function renderFolders() {
const epoch = ++folderEpoch, p = selectedProject();
$('drawerTitle').textContent = '项目目录';
if (!p) { $('drawerBody').innerHTML = `<div class="drawer-empty">${icon('folder')}<h3>还没有选择项目</h3><p>在输入框上方选择项目,<br>或新建项目并添加本地文件夹。</p><button class="drawer-button" data-create-project>新建项目</button></div>`; return; }
const folderStates = await Promise.all(p.folders.map(async f => {
let permission = 'prompt';
if (f.mode === 'handle') try { const handle = await getHandle(f.id, user().id); if (handle) permission = await handle.queryPermission({ mode: 'read' }); } catch { /* Explicit reselect remains available. */ }
return { f, permission };
}));
if (epoch !== folderEpoch || drawer !== 'folders') return;
$('drawerBody').innerHTML = `<div class="drawer-heading-row"><strong>${esc(p.name)}</strong><button class="drawer-button" data-edit-project="${esc(p.id)}">管理目录</button></div><div class="drawer-note">目录只在此计算机的浏览器中授权。打开对话可恢复目录引用;访问前核验权限。</div>${folderStates.map(({ f, permission }) => `<div class="folder-row">${icon('folder')}<span class="folder-details"><strong title="${esc(f.name)}">${esc(f.name)}</strong><small>${f.mode !== 'handle' ? '兼容引用 · 需重新选择' : permission === 'granted' ? '已授权 · 可浏览目录' : permission === 'denied' ? '访问未获授权 · 可重新选择' : '需要再次授权'}</small></span><button class="drawer-button" data-browse-folder="${esc(f.id)}">${permission === 'granted' ? '浏览' : '授权'}</button></div><div class="file-tree" id="tree-${esc(f.id)}" hidden></div>`).join('') || '<div class="menu-empty">尚未绑定目录,请在管理目录中添加。</div>'}`;
}
async function browseFolder(id, button) {
const p = selectedProject(), f = p?.folders.find(x => x.id === id); if (!f) return;
let handle = await getHandle(id, user().id).catch(() => null);
try {
if (!handle) { openProjectDialog(p.id); toast('请重新添加这个目录以恢复访问。'); return; }
let permission = await handle.queryPermission({ mode: 'read' });
if (permission !== 'granted') permission = await handle.requestPermission({ mode: 'read' });
if (permission !== 'granted') { toast('目录未获授权,未读取任何文件。'); return; }
const tree = $(`tree-${id}`); if (!tree || drawer !== 'folders') return;
const entries = []; let more = false;
for await (const [name, entry] of handle.entries()) { if (entries.length >= 80) { more = true; break; } entries.push({ name, kind: entry.kind }); }
entries.sort((a, b) => (a.kind === b.kind ? a.name.localeCompare(b.name) : a.kind === 'directory' ? -1 : 1));
tree.innerHTML = entries.map(e => `<div>${icon(e.kind === 'directory' ? 'folder' : 'file')}<span>${esc(e.name)}${e.kind === 'directory' ? '/' : ''}</span></div>`).join('') || '<div>这个目录是空的。</div>';
if (more) tree.insertAdjacentHTML('beforeend', '<div>仅展示前 80 项。</div>');
tree.hidden = false; button.textContent = '浏览';
log('浏览项目目录', '仅列出本地文件名,未读取或上传文件内容');
} catch (error) { toast(error.name === 'NotFoundError' ? '目录已移动或不可用,请在管理目录中重新选择。' : `目录暂不可用:${error.message}`); }
}
async function stopReply() {
if (!pending) return;
const active = pending;
if(active.kind==='business-action'){toast('登记请求已发送,正在确认写入与回读结果,请勿重复提交。');return;}
try {
if (active.runId) await runtime.api(`/api/jobs/${active.runId}/cancel`, {});
active.stopped = true;
const c = state.chats.find(x => x.id === active.chatId && x.owner === user().id);
if (c) c.messages.push({role:'assistant',content:active.runId ? '已提交中止请求;后台最终停止状态以任务卡为准。已保存的需求、代码、文档与诊断保留,可从任务卡下载;未返回的模型结果不冒充已保存,未知调用预留不释放、不自动重放。' : '已停止等待模型回复。请求可能已计费,服务端结果按请求键保留,不自动重放。'});
if(pending === active) pending = null;
persist(); render();
} catch(error) { toast(error.message); }
}
function saveRequestResult(c,active) {
c.updated=Date.now();
saveState(state);
if(user().id===active.owner&&!switchingUser) {
renderSidebar();
if(chat()?.id===c.id){const scroll=$('chatScroll'),follow=scroll.scrollHeight-scroll.scrollTop-scroll.clientHeight<100,top=scroll.scrollTop;renderContext();renderMessages();if(follow)bottom();else scroll.scrollTop=top;}
}
}
async function monitorJavaJob(c,response,job,active) {
active.kind='java';active.runId=job.id;c.runId=job.id;
while(!active.stopped&&pending===active) {
response.jobObservedAt=Date.now();job.observed_at=response.jobObservedAt;
response.job=job;response.jobError='';response.content=runtime.jobText(job);saveRequestResult(c,active);
if(!['queued','working'].includes(job.status)){
if(job.status==='failed'&&job.auto_recovery&&!job.auto_recovery.attempt&&!job.auto_recovery.error&&!job.auto_recovery.next_run_id){
await new Promise(resolve=>setTimeout(resolve,2000));
job=await runtime.api(`/api/jobs/${encodeURIComponent(job.id)}`);response.job=job;
}
if(job.auto_recovery?.next_run_id&&!active.stopped&&pending===active){
job=await runtime.api(`/api/jobs/${encodeURIComponent(job.auto_recovery.next_run_id)}`);
response=c.messages.find(m=>m.job?.id===job.id)||{role:'assistant',content:'正在自动恢复,保留原任务和诊断。',job};
if(!c.messages.includes(response))c.messages.push(response);
active.runId=job.id;c.runId=job.id;continue;
}
if(job.status==='verified'&&!job.project){try{job.project=await runtime.api(`/api/jobs/${encodeURIComponent(job.id)}/project`,{});saveRequestResult(c,active);}catch(error){response.jobError='工程保存未完成:'+error.message;saveRequestResult(c,active);}}
break;
}
await new Promise(resolve=>setTimeout(resolve,2000));
if(pending!==active||active.stopped||user().id!==active.owner)break;
let refreshed=false;
while(!refreshed&&!active.stopped&&pending===active&&user().id===active.owner){
try{job=await runtime.api(`/api/jobs/${encodeURIComponent(job.id)}`);refreshed=true;}
catch(error){if([401,403,404].includes(error.status))throw error;response.jobError='连接暂时中断,正在重新读取同一任务,不会重复提交:'+error.message;saveRequestResult(c,active);await new Promise(resolve=>setTimeout(resolve,5000));}
}
}
}
async function refreshJavaMessage(index) {
const c=chat(),response=c?.messages[index];
if(!response?.job||switchingUser)return;
if(pending){if(pending.runId!==response.job.id)toast('当前请求正在运行,请稍后读取。');return;}
const active={chatId:c.id,owner:c.owner,key:uid(),runId:response.job.id,kind:'java',stopped:false};pending=active;
let finishRead;active.completion=new Promise(resolve=>{finishRead=resolve;});
renderContext();
try {await monitorJavaJob(c,response,await runtime.api(`/api/jobs/${encodeURIComponent(response.job.id)}`),active);}
catch(error){response.jobError=error.message;}
finally{if(pending===active)pending=null;saveRequestResult(c,active);finishRead();}
}
async function decideJobBudget(index,accept,expectedDigest){
const response=chat()?.messages[index],job=response?.job;
if(switchingUser||budgetInFlight.has(job?.id)||!hasBudgetDecision(job)||!(job.budget_request||job.limit_request))return;
if(expectedDigest!==(job.budget_request||job.limit_request).digest){response.jobError='预算申请已更新,请重新查看并确认。';renderMessages();return;}
budgetInFlight.add(job.id);renderMessages();
try{
response.job=await runtime.api(`/api/jobs/${encodeURIComponent(job.id)}/budget`,{digest:(job.budget_request||job.limit_request).digest,revision:(job.budget_request||job.limit_request).task_revision,accept});
response.jobError='';
if(!accept){state.budgetDismissed||={};state.budgetDismissed[budgetDismissKey(response.job)]=(response.job.budget_request||response.job.limit_request)?.digest;$('budgetDialog').close();}
persist();render();
if(accept)await refreshJavaMessage(index);
}catch(error){
response.jobError=error.message;
if(error.code==='BUDGET_REQUEST_CHANGED'){
try{response.job=await runtime.api(`/api/jobs/${encodeURIComponent(job.id)}`);persist();}catch{}
}
}finally{budgetInFlight.delete(job.id);render();}
}
function resumeVisibleJob() {
if(pending||switchingUser||!runtime.session?.authenticated)return;
const messages=chat()?.messages||[];
for(let i=messages.length-1;i>=0;i--)if(['queued','working','waiting_budget','waiting_limit','unknown','failed'].includes(messages[i].job?.status)){refreshJavaMessage(i);break;}
}
let syncingTaskStates=false;
async function syncTaskStates(){
if(syncingTaskStates||switchingUser||!runtime.session?.authenticated)return;
const owner=user().id,actor=runtime.session.actor?.user_id;
const saved=chats().flatMap(c=>c.messages||[]).filter(m=>m.job&&['queued','working','waiting_budget','waiting_limit','unknown'].includes(m.job.status));
if(!saved.length)return;
syncingTaskStates=true;
try{
const jobs=await runtime.api('/api/jobs');
if(user().id!==owner||switchingUser||runtime.session.actor?.user_id!==actor)return;
const byId=new Map(jobs.map(j=>[j.id,j]));
for(const m of saved){const updated=byId.get(m.job.id);if(updated)m.job={...m.job,...updated,observed_at:Date.now()};}
saveState(state);renderSidebar();
if(!pending)renderMessages();
}catch{if(user().id===owner&&!switchingUser)renderSidebar();}
finally{syncingTaskStates=false;}
}
setInterval(syncTaskStates,5000);
async function openJobFollowup(index,runId) {
const c=chat(),original=c?.messages[index];
if(switchingUser||!original?.job?.followups?.some(row=>row.id===runId))return;
if(pending?.runId===original.job.id&&pending.completion)await pending.completion;
if(chat()?.id!==c.id||user().id!==c.owner||switchingUser)return;
if(pending){toast('当前请求尚未完成,请稍候。');return;}
try {
const job=await runtime.api(`/api/jobs/${encodeURIComponent(runId)}`);
let target=c.messages.findIndex(m=>m.job?.id===runId);
if(target<0){target=c.messages.length;c.messages.push({role:'assistant',content:runtime.jobText(job),job});persist();render();}
await refreshJavaMessage(target);
} catch(error){toast(error.message);}
}
document.addEventListener('open-recorded-job',async event=>{
if(pending||switchingUser){toast('当前请求尚未结束,请稍候。');return;}
const owner=user().id;
try{
const job=await runtime.api(`/api/jobs/${encodeURIComponent(event.detail)}`);
if(user().id!==owner||switchingUser)return;
let c=chats().find(c=>c.messages?.some(m=>m.job?.id===job.id));
if(!c){
const serverId=runtime.scenarios.find(s=>s.id===job.scenario)?.project_id;
c={id:uid(),owner,title:job.requirement.slice(0,25),projectId:projects().find(p=>p.serverId===serverId)?.id||null,
created:Date.now(),updated:Date.now(),model:job.model||'auto',skill:job.scenario,bases:[],
messages:[{role:'user',content:job.requirement},{role:'assistant',content:'读取已保存的任务记录,不会重新生成。',job}]};
state.chats.push(c);
}
$('closeDrawer').click();openChat(c.id);
}catch(error){toast(error.message);}
});
async function repairJavaMessage(index,confirmed=false) {
const c=chat(),original=c?.messages[index];
if(switchingUser||!['failed','unknown'].includes(original?.job?.status))return;
if(!original.repairRunId&&!confirmed){original.repairConfirmation=true;renderMessages();return;}
original.repairConfirmation=false;
if(pending?.runId===original.job.id&&pending.completion)await pending.completion;
if(chat()?.id!==c.id||user().id!==c.owner||switchingUser)return;
if(pending){toast('当前请求尚未完成,请稍候。');return;}
if(original.repairRunId){await refreshJavaMessage(c.messages.findIndex(m=>m.job?.id===original.repairRunId));return;}
original.repairKey ||= uid();persist();
const response={role:'assistant',content:'正在依据原需求、失败源码及诊断创建修复任务…'};
c.messages.push(response);
const active={chatId:c.id,owner:c.owner,key:original.repairKey,kind:'java',stopped:false};pending=active;render();
try {
const job=await runtime.api('/api/jobs',{scenario:original.job.scenario,requirement:original.job.requirement,
request_key:original.repairKey,recovery_of:original.job.id,acknowledge_new_cost:true,model:prefs.model||'auto'});
original.repairRunId=job.id;active.runId=job.id;response.job=job;
await monitorJavaJob(c,response,job,active);
} catch(error){response.content=error.message;response.jobError=error.message;}
finally{if(pending===active)pending=null;saveRequestResult(c,active);}
}
async function confirmBusinessAction(index,resetScenario=null) {
const c=chat(),message=c?.messages[index],result=message?.business;
if(!result||switchingUser)return;
if(pending){toast('当前请求尚未完成,请稍候。');return;}
const action=result.action;
if(!resetScenario&&(!action||message.actionState?.status==='completed'))return;
const scenario=result.scenario||'erp';
const slot=resetScenario?'resetState':'actionState';
const saved=message[slot] ||= {key:uid(),status:'ready'};
if(saved.status==='completed')return;
const active={chatId:c.id,owner:c.owner,key:saved.key,kind:'business-action',stopped:false};pending=active;
saved.status='submitting';saved.error='';persist();render();
try {
const response=resetScenario
? await runtime.api('/api/business/reset',{scenario,request_key:saved.key})
: await runtime.api('/api/business/actions',{scenario,action:action.kind,entity_id:action.entity_id,parameters:action.parameters||{},expected_version:action.expected_version,request_key:saved.key});
saved.status='completed';
c.messages.push({role:'assistant',content:runtime.businessText(response),business:{...response,scenario}});
} catch(error) {
const uncertain=!error.status||error.status>=500;
saved.status=uncertain?'unknown':'failed';
saved.error=uncertain?'上次请求结果尚待核对。连接中断或服务暂时未返回;再次点击会使用同一请求号核对,不重复执行。':error.message;
}
finally { if(pending===active)pending=null;saveRequestResult(c,active); }
}
async function scopeAction(index,action){
const c=chat(),m=c?.messages[index];if(!m||m.scopeBusy||pending)return;
if(action==='focus'){$(`scope-supplement-${index}`)?.focus();return;}
m.scopeBusy=true;m.scopeError='';
const supplement=$(`scope-supplement-${index}`)?.value.trim();
const active={chatId:c.id,owner:user().id,key:m.scopeRequest?.request_key||uid(),stopped:false};
try{
if(action==='iterate'){
const scope=await runtime.api('/api/business-scope',{requirement:m.job.requirement,base_run:m.job.id,request_key:'scope:'+uid()});
c.messages.push({role:'assistant',content:'新一轮范围确认',scope,scopeRequest:{scenario:'business-app',request_key:uid(),model:m.job.model}});
}else if(action==='update'){
if(!supplement){m.scopeError='请先填写要补充或调整的内容。';return;}
m.scope=await runtime.api('/api/business-scope',{requirement:m.scope.original_requirement,parent_id:m.scope.id,supplement,request_key:'scope:'+uid()});
}else{
if(supplement){m.scopeError='补充内容尚未确认,请先更新范围卡。';return;}
const scope=await runtime.api(`/api/business-scope/${encodeURIComponent(m.scope.id)}/confirm`,{digest:m.scope.digest});
pending=active;
const job=await runtime.api('/api/jobs',{...m.scopeRequest,requirement:scope.requirement,scope_id:scope.id});
m.scopeHistory=scope;m.scope=null;m.job=job;
await monitorJavaJob(c,m,job,active);
}
}catch(error){if(error.code==='SCOPE_BUDGET_CHANGED'&&error.details?.scope)m.scope=error.details.scope;m.scopeError=error.message;}
finally{m.scopeBusy=false;if(pending===active)pending=null;persist();render();bottom();}
}
async function send(event) {
event.preventDefault();
if (pending?.chatId === currentChatId) { await stopReply(); return; }
const content = $('prompt').value.trim(); if (!content) return;
if (pending) { toast('当前还有请求在等待,请先处理。'); return; }
if (switchingUser||!runtime.session?.authenticated) { toast('登录尚未完成,请使用左下角三用户入口。'); return; }
if (attachments.length) { toast('当前附件仅保存本地引用,尚未上传内容。请将需要使用的需求文本写入对话。'); return; }
const option = runtime.skillOptions().find(s => s.id === prefs.skill);
if(prefs.skill && !option){toast('此技能不可见,请重新选择。');return;}
const business=option?.kind==='business'?option:!option&&prefs.bases.length===1?runtime.businessPresets.find(p=>p.base===prefs.bases[0]):null;
const programming=option&&!business;
const bound = selectedProject()?.serverId;
if(programming && selectedProject() && !bound){toast('此项目只有浏览器目录引用。Java 编程请先选择已接入后端的 ERP、WMS 或设备项目。');return;}
if(programming && bound && bound !== runtime.scenarios.find(s => s.id === option.scenario)?.project_id){toast('所选 Java 技能与项目不一致,请选择对应项目。');return;}
if(!option && !business && prefs.bases.length){toast('请选择对应业务助手,或选择 Java Skill 使用编码资料。');return;}
let c = chat();
if (!c) {
c = { id:uid(),owner:user().id,title:content.slice(0,25),projectId:selectedProjectId(),created:Date.now(),updated:Date.now(),model:prefs.model,skill:prefs.skill,bases:[...prefs.bases],messages:[] };
state.chats.push(c); currentChatId=c.id;
}
c.messages.push({role:'user',content}); c.updated=Date.now();
const response = {role:'assistant',content:'正在提交真实请求…'};c.messages.push(response);
const active = {chatId:c.id,owner:user().id,key:uid(),stopped:false}; pending=active;
$('prompt').value='';$('prompt').style.height='';persist();render();bottom();
try {
if(business) {
const result=await runtime.api('/api/business/ask',{scenario:business.scenario,question:content});
response.content=runtime.businessText(result);response.business={...result,scenario:business.scenario};
} else if(programming) {
const jobRequest={scenario:option.scenario,requirement:content,request_key:active.key,...(prefs.model==='auto'?{}:{model:prefs.model}),...(runtime.session?.capabilities?.automatic_recovery?{auto_recover:true}:{}),...(option.id.startsWith('java-')?{skill_id:option.id}:{})};
const job=await runtime.api('/api/jobs',jobRequest);
await monitorJavaJob(c,response,job,active);
} else {
let result=await runtime.api('/api/chat',{conversation:c.id,prompt:content,request_key:active.key,project:bound||null,...(prefs.model==='auto'?{}:{model:prefs.model})});
while(result.state==='running'&&!active.stopped&&pending===active){await new Promise(resolve=>setTimeout(resolve,1500));if(pending!==active)break;result=await runtime.api(`/api/chat/${result.id}`);}
if(!active.stopped&&pending===active)response.content=result.answer||`${runtime.statusText(result.state)}:${result.error||'请求处理中'};请勿自动重复提交。`;
}
} catch(error) { if(response.job)response.jobError=error.message;else response.content='请求未完成:'+error.message; }
finally { if(pending===active)pending=null;saveRequestResult(c,active); }
}
mountIcons();
$('newChat').onclick = e => newChatMenu(e.currentTarget);
$('projectPicker').onclick = e => projectMenu(e.currentTarget);
$('skillsNav').onclick = () => openRuntime('examples');
$('scheduleNav').onclick = () => showDrawer('schedule');
$('projectsNav').onclick = e => { if (state.collapsed && innerWidth > 800) projectMenu(e.currentTarget); else { state.projectsExpanded = !state.projectsExpanded; persist(); renderSidebar(); } };
$('addProject').onclick = () => openProjectDialog();
$('moreNav').onclick = e => menu(e.currentTarget, [{ label: '连接', icon: 'link', action: () => showDrawer('connections') }, { label: '知识库', icon: 'book', action: () => showDrawer('knowledge') }]);
$('profileSwitch').onclick = e => menu(e.currentTarget, USERS.map(u => ({ label: u.name, description: u.role, icon: 'user', selected: user().id === u.id, action: () => switchUser(u.id) })), '当前人员');
$('logsNav').onclick = () => openRuntime('jobs');
$('computerContext').onclick = () => showDrawer('folders');
$('chooseSkills').onclick = e => skillMenu(e.currentTarget);
$('chooseBases').onclick = e => knowledgeMenu(e.currentTarget);
$('modelPicker').onclick = e => modelMenu(e.currentTarget);
$('attach').onclick = e => menu(e.currentTarget, [{ label: '添加文件', description: '可一次选择多个文件', icon: 'file', action: () => $('filePicker').click() }, { label: '添加目录', description: '可重复添加多个目录', icon: 'folder', action: () => pickDirectory('message') }]);
$('conversationMore').onclick = e => menu(e.currentTarget, [{ label: '新建独立对话', icon: 'new', action: () => resetDraft() }, ...(chat() ? [{ label: '删除当前对话', icon: 'trash', danger: true, action: () => confirmChatDelete(currentChatId) }] : [])]);
$('collapseSidebar').onclick = () => { if (innerWidth <= 800) { closeMobile(); return; } state.collapsed = !state.collapsed; persist(); closeMenu(); renderSidebar(); };
$('menuToggle').onclick = () => { const open = !$('shell').classList.contains('sidebar-open'); $('shell').classList.toggle('sidebar-open', open); $('mobileScrim').hidden = !open; };
$('mobileScrim').onclick = closeMobile;
$('closeDrawer').onclick = closeDrawer;
$('addProjectFolder').onclick = () => pickDirectory('project');
$('projectForm').onsubmit = saveProject;
$('projectDialog').addEventListener('close', () => { projectDraft = null; });
$('confirmDelete').onclick = deleteConfirmed;
$('composer').onsubmit = send;
$('prompt').addEventListener('input', () => { $('prompt').style.height = ''; $('prompt').style.height = `${Math.min(180, Math.max(innerHeight < 720 ? 54 : 66, $('prompt').scrollHeight))}px`; updateSend(); });
$('prompt').addEventListener('keydown', e => { if (e.key === 'Enter' && !e.shiftKey && !e.isComposing) { e.preventDefault(); if (!$('send').disabled) $('composer').requestSubmit(); } });
$('filePicker').onchange = e => { const files = [...e.target.files]; attachments.push(...files.map(f => ({ id: uid(), type: 'file', name: f.name, size: f.size }))); e.target.value = ''; renderContext(); if (files.length) log('选择附件', `${files.length} 个文件,仅保留本地文件名与大小`); };
$('directoryPicker').onchange = e => { fallbackDirectory([...e.target.files]); e.target.value = ''; };
$('popover').addEventListener('click', async e => { e.stopPropagation(); const b = e.target.closest('[data-menu-index]'); if (!b) return; const item = menuActions[Number(b.dataset.menuIndex)]; closeMenu(); try { await item?.action(); } catch (error) { toast(error.message || '操作未完成。'); } });
document.addEventListener('click', async e => {
for(const [attribute,action] of [['scopeStart','start'],['scopeFocus','focus'],['scopeUpdate','update'],['scopeIterate','iterate']]){
const control=e.target.closest(`[data-${attribute.replace(/[A-Z]/g,c=>'-'+c.toLowerCase())}]`);if(control){await scopeAction(Number(control.dataset[attribute]),action);return;}
}
if(e.target.closest('[data-budget-close]')){closeBudgetDialog();return;}
const reopenBudget=e.target.closest('[data-budget-open]');if(reopenBudget){syncBudgetDialog(Number(reopenBudget.dataset.budgetOpen));return;}
const close = e.target.closest('[data-close]'); if (close) { $(close.dataset.close).close(); return; }
const p = e.target.closest('[data-project]'); if (p) { const item = project(p.dataset.project); if (!item) return; item.expanded = !item.expanded; if (selectedProjectId() !== item.id || chat()) resetDraft(item.id); else renderSidebar(); persist(); return; }
const pc = e.target.closest('[data-project-chat]'); if (pc) { resetDraft(pc.dataset.projectChat); return; }
const pm = e.target.closest('[data-project-menu]'); if (pm) { projectOptions(pm.dataset.projectMenu, pm); return; }
const c = e.target.closest('[data-chat]'); if (c) { openChat(c.dataset.chat); return; }
const cm = e.target.closest('[data-chat-menu]'); if (cm) { menu(cm, [{ label: '删除对话', icon: 'trash', danger: true, action: () => confirmChatDelete(cm.dataset.chatMenu) }]); return; }
const ra = e.target.closest('[data-remove-attachment]'); if (ra) { attachments.splice(Number(ra.dataset.removeAttachment), 1); renderContext(); return; }
const rf = e.target.closest('[data-remove-folder]'); if (rf && projectDraft) { projectDraft.folders = projectDraft.folders.filter(f => f.id !== rf.dataset.removeFolder); projectDraft.newHandles.delete(rf.dataset.removeFolder); renderProjectFolders(); return; }
if (e.target.closest('[data-toggle-skill]')) { prefs.skill = prefs.skill ? false : 'erp'; updatePrefs(); renderDrawer(); return; }
const kb = e.target.closest('[data-toggle-base]'); if (kb) { selectKnowledge(kb.dataset.toggleBase); return; }
const confirm=e.target.closest('[data-business-confirm]');if(confirm){await confirmBusinessAction(Number(confirm.dataset.businessConfirm));return;}
const reset=e.target.closest('[data-business-reset]');if(reset){await confirmBusinessAction(Number(reset.dataset.businessReset),reset.dataset.businessScenario);return;}
const followup=e.target.closest('[data-business-prompt]');if(followup){injectBusiness(followup.dataset.businessScenario,followup.dataset.businessPrompt);return;}
const develop=e.target.closest('[data-develop-scenario]');if(develop){injectDevelopment(develop.dataset.developScenario);return;}
const refresh=e.target.closest('[data-job-refresh]');if(refresh){await refreshJavaMessage(Number(refresh.dataset.jobRefresh));return;}
const budget=e.target.closest('[data-job-budget]');if(budget){await decideJobBudget(Number(budget.dataset.jobBudget),budget.dataset.accept==='true',budget.dataset.budgetDigest);return;}
const jobFollowup=e.target.closest('[data-job-followup]');if(jobFollowup){await openJobFollowup(Number(jobFollowup.dataset.jobFollowup),jobFollowup.dataset.runId);return;}
const approveNew=e.target.closest('[data-job-repair-confirm]');if(approveNew){await repairJavaMessage(Number(approveNew.dataset.jobRepairConfirm),true);return;}
const dismissNew=e.target.closest('[data-job-repair-dismiss]');if(dismissNew){const m=chat()?.messages[Number(dismissNew.dataset.jobRepairDismiss)];if(m)m.repairConfirmation=false;renderMessages();return;}
const jobRepair=e.target.closest('[data-job-repair]');if(jobRepair){await repairJavaMessage(Number(jobRepair.dataset.jobRepair));return;}
if (e.target.closest('[data-create-project]')) { openProjectDialog(); return; }
const edit = e.target.closest('[data-edit-project]'); if (edit) { openProjectDialog(edit.dataset.editProject); return; }
const browse = e.target.closest('[data-browse-folder]'); if (browse) { await browseFolder(browse.dataset.browseFolder, browse); return; }
if (e.target.closest('[data-clear-logs]')) { state.logs = state.logs.filter(l => l.owner !== user().id); persist(); renderLogs(); return; }
const copy = e.target.closest('[data-copy-message]'); if (copy) { try { await navigator.clipboard.writeText(chat()?.messages[Number(copy.dataset.copyMessage)]?.content || ''); toast('回复已复制。'); } catch { toast('浏览器不允许复制,请手动选择回复文字。'); } return; }
if (!$('popover').hidden && !e.target.closest('#popover') && !menuAnchor?.contains(e.target)) closeMenu();
});
document.addEventListener('keydown', e => {
if (e.key === 'Escape') { closeMenu(true); if (!$('projectDialog').open && !$('deleteDialog').open) { closeDrawer(); closeMobile(); } }
if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'n' && !e.shiftKey) { e.preventDefault(); newChatMenu($('newChat')); }
if (!$('popover').hidden && ['ArrowDown', 'ArrowUp'].includes(e.key)) {
e.preventDefault(); const items = [...$('popover').querySelectorAll('button')], at = items.indexOf(document.activeElement);
items[(at + (e.key === 'ArrowDown' ? 1 : -1) + items.length) % items.length]?.focus();
}
});
window.addEventListener('resize', () => closeMenu());
window.addEventListener('pagehide', persist);
$('runtimeNav').onclick = e => menu(e.currentTarget, [
...runtime.developmentPresets.map(p=>({label:p.name,description:'完整背景、需求、界面与验收条目',icon:'skill',action:()=>injectDevelopment(p.id)})),
{separator:true},
...[['ERP 订单向导','erp'],['WMS 库存向导','wms'],['设备工单向导','equipment'],['Skill 工具','examples'],['任务与证据','jobs'],['运行沙箱','preview'],['管理状态','admin'],['本地演示登录','account']].map(([label,view])=>({label,icon:'file',action:()=>openRuntime(view)}))
], '开发场景与运行');
restoreView();switchingUser=true;render();
setInterval(()=>runtime.tickJobClocks(),1000);
runtime.initialize(state.currentUser, selectSkill, () => {drawer='runtime';$('drawer').hidden=false;closeMobile();}).then(() => {
switchingUser=false;syncServerProjects(); render(); log('打开工作台','真实本地会话;按所选 Skill 进入业务操作或 Java 编程流程');resumeVisibleJob();
}).catch(error => { switchingUser=false;renderContext();renderMessages();toast(error.message); });
|