${esc(b.text)}
${review?`'+review.issues.map(esc).join('
'):''}${review.unavailable?'
'+esc(review.unavailable):''}
(() => { 'use strict'; const $=id=>document.getElementById(id),esc=v=>String(v??'').replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c])); const s={token:'',session:null,projects:[],current:null,frame:null,run:null,stream:null,epoch:0,opening:0,loading:false,sending:false};let timer; function toast(message){$('toast').textContent=message;$('toast').hidden=false;clearTimeout(timer);timer=setTimeout(()=>$('toast').hidden=true,7000);} async function api(path,body){const r=await fetch(path,{method:body===undefined?'GET':'POST',headers:body===undefined?{}:{'Content-Type':'application/json','x-vivid-token':s.token},body:body===undefined?undefined:JSON.stringify(body)});const d=await r.json();if(!r.ok)throw Error(d.error?.message||'请求失败');return d;} const safely=fn=>async(...a)=>{try{await fn(...a);}catch(e){toast(e.message);}}; const settings=window.VividModelSettings.bind({api,toast}); document.querySelectorAll('[data-close]').forEach(b=>b.onclick=()=>$(b.dataset.close).close()); function bridge(){return s.frame?.contentWindow?.VividArchitectureBridge;} async function flush(){if(s.frame&&!bridge())throw Error('编辑器尚未载入,请稍候。');if(bridge()){await bridge().flush();const snap=bridge().snapshot();s.current={...s.current,revision:snap.revision};}} function active(){return s.run&&['queued','running','waiting'].includes(s.run.status);} function controls(){const locked=s.loading||s.sending;$('send').disabled=locked||!!active()||!s.session;$('new-session').disabled=locked;$('sessions').disabled=locked;$('task-target').querySelector('[value="current"]').disabled=!s.current;$('task-target').disabled=locked;} function context(){const snap=bridge()?.snapshot(),sel=snap?.selected||[];const current=$('task-target').value==='current';$('context-chip').textContent=current?(sel.length?'⌖ '+sel.join(' / '):'▧ '+(s.current?.name||'当前图')):'+ 新建架构图';$('clear-selection').hidden=!current||!sel.length;$('preferred-asset').disabled=current;} function projects(){const list=$('charts');list.replaceChildren();for(const p of s.projects){const b=document.createElement('button');b.className='rail-item'+(s.current?.id===p.id?' active':'');b.textContent='▧ '+p.name;const small=document.createElement('small');small.textContent='版本 '+p.revision;b.append(small);b.onclick=safely(()=>openProject(p.id));list.append(b);}if(!s.projects.length)list.textContent='从需求描述或架构图库开始';$('chart-heading').textContent=s.current?.name||'开始一张新架构图';$('revision-badge').textContent=s.current?'v'+s.current.revision:'';controls();context();} async function listSessions(){const d=await api('/api/agent/sessions?domain=architecture');$('sessions').replaceChildren();for(const p of d.items){const o=document.createElement('option');o.value=p.id;o.textContent=p.name;$('sessions').append(o);}if(s.session)$('sessions').value=s.session.id;return d.items;} function messages(){const html=s.session.messages.map(m=>{const b=m.body,r=b.result,review=b.review;return ``;}).join('');$('messages').innerHTML=html||'
';$('messages').querySelectorAll('[data-project]').forEach(b=>b.onclick=safely(()=>openProject(b.dataset.project)));$('messages').querySelectorAll('[data-candidate]').forEach(b=>b.onclick=safely(async()=>{const epoch=s.epoch;const r=await api('/api/agent/runs/'+b.dataset.candidate+'/candidate',{});if(epoch!==s.epoch)return;await refresh();await openProject(r.architecture_id);}));$('messages').scrollTop=$('messages').scrollHeight;} async function refresh(){if(!s.session)return;const epoch=s.epoch,id=s.session.id;const [session,figures]=await Promise.all([api('/api/agent/sessions/'+id),api('/api/architecture/sessions/'+id+'/projects')]);if(epoch!==s.epoch)return;s.session=session;s.projects=figures.items;messages();projects();} async function openProject(id){const n=++s.opening,epoch=s.epoch;await flush();const p=await api('/api/architecture/projects/'+id);if(n!==s.opening||epoch!==s.epoch)return;if(!s.projects.some(x=>x.id===id))throw Error('图件不属于当前工作区。');s.current=p;s.frame=document.createElement('iframe');s.frame.title='架构图模块编辑器';s.frame.src='architecture-editor.html?embed=1&project='+encodeURIComponent(id);$('editor-host').replaceChildren(s.frame);$('editor-host').hidden=false;$('empty-state').hidden=true;$('preview-host').hidden=true;$('standalone').hidden=false;$('standalone').href='architecture-editor.html?project='+id;$('task-target').value='current';projects();} async function openSession(id,project=null){if(s.loading)return;s.loading=true;controls();try{await flush();const next=await api('/api/agent/sessions/'+id);if(next.domain!=='architecture')throw Error('请选择架构工作区。');const epoch=++s.epoch;s.opening++;s.stream?.close();s.stream=null;s.run=null;s.session=next;s.current=null;s.frame=null;$('editor-host').replaceChildren();$('editor-host').hidden=true;$('preview-host').hidden=true;$('empty-state').hidden=false;$('standalone').hidden=true;$('activity').hidden=true;$('run-notice').hidden=true;localStorage.setItem('vivid-architecture-agent-session',id);history.replaceState(null,'','architecture-agent.html?session='+id);$('sessions').value=id;$('task-target').value='new';if(project)await api('/api/architecture/sessions/'+id+'/projects',{project});await refresh();if(epoch!==s.epoch)return;const chosen=project||s.projects.at(-1)?.id;if(chosen)await openProject(chosen);const run=next.runs.find(r=>['queued','running','waiting','interrupted','error'].includes(r.status));if(run){s.run=run;paintRun();if(['queued','running'].includes(run.status))connect(run.id);}else paintRun();}finally{s.loading=false;controls();}} function toolLine(text,error=false){const d=document.createElement('div');d.className='tool-line';d.textContent=text;if(error)d.style.color='#a43940';$('tool-feed').append(d);while($('tool-feed').children.length>25)$('tool-feed').firstChild.remove();$('tool-feed').scrollTop=$('tool-feed').scrollHeight;} function paintRun(){const r=s.run;$('activity').hidden=!r;$('agent-status').textContent=!r||r.status==='done'?'就绪':({queued:'排队中',running:'生成中',waiting:'待补充',interrupted:'可续接',error:'需处理',cancelled:'已停止'}[r.status]||r.status);$('stop-run').hidden=!r||!['queued','running','waiting'].includes(r.status);$('run-notice').replaceChildren();$('run-notice').hidden=true;if(r&&['waiting','interrupted','error'].includes(r.status)){const n=$('run-notice');n.hidden=false;const text=document.createElement('p');text.textContent=r.body.question||r.body.message||'上次任务中断,可继续。';n.append(text);let input;if(r.status==='waiting'){input=document.createElement('textarea');input.placeholder='补充必要信息';input.id='clarification';n.append(input);}const b=document.createElement('button');b.textContent='补充 / 继续任务';b.onclick=safely(async()=>{b.disabled=true;try{await api('/api/agent/runs/'+r.id+'/resume',{response:input?.value});s.run=await api('/api/agent/runs/'+r.id);paintRun();connect(r.id);}finally{b.disabled=false;}});n.append(b);}controls();} function connect(rid){s.stream?.close();const epoch=s.epoch,stream=new EventSource('/api/agent/runs/'+rid+'/events');s.stream=stream;const valid=()=>epoch===s.epoch&&s.stream===stream;stream.onmessage=e=>{if(!valid())return;const ev=JSON.parse(e.data);if(ev.type==='CUSTOM'){const v=ev.value;if(ev.name==='progress'){$('activity-title').textContent=v.message;toolLine(v.message);}else if(ev.name==='plan')toolLine(v.message);else if(ev.name==='tool_result')toolLine((v.ok?'✓ ':'! ')+v.tool+' · '+v.summary,!v.ok);else if(ev.name==='preview'&&v.url&&!s.current){$('preview').src=v.url+'?t='+Date.now();$('preview-host').hidden=false;$('empty-state').hidden=true;}}else if(ev.type==='RUN_ERROR')toolLine(ev.message,true);};stream.addEventListener('settled',safely(async()=>{if(!valid())return;stream.close();s.stream=null;const r=await api('/api/agent/runs/'+rid);if(epoch!==s.epoch)return;s.run=r;paintRun();await refresh();if(epoch!==s.epoch)return;if(r.status==='done'&&r.body.result?.architecture_id){try{await openProject(r.body.result.architecture_id);}catch(e){toast('结果已保存;当前画布修改仍保留。'+e.message);}}}));stream.onerror=()=>{if(valid())$('activity-title').textContent='连接暂断,正在重连…';};} $('composer').onsubmit=safely(async e=>{e.preventDefault();if(s.sending||s.loading||active())return;const prompt=$('prompt').value.trim();if(!prompt)return;s.sending=true;controls();const epoch=s.epoch;try{await flush();if(epoch!==s.epoch)return;const snap=bridge()?.snapshot();const r=await api('/api/agent/sessions/'+s.session.id+'/runs',{domain:'architecture',prompt,target:$('task-target').value,architecture_id:s.current?.id,preferred_asset:$('preferred-asset').value.trim()||null,selected_object:snap?.selected?.length?{mode:snap.mode,ids:snap.selected}:null});if(epoch!==s.epoch)return;$('prompt').value='';$('tool-feed').replaceChildren();s.run=r;paintRun();await refresh();connect(r.id);}finally{s.sending=false;controls();}}); $('prompt').onkeydown=e=>{if(e.key==='Enter'&&!e.shiftKey&&!e.isComposing){e.preventDefault();$('composer').requestSubmit();}}; $('stop-run').onclick=safely(async()=>{if(!s.run)return;await api('/api/agent/runs/'+s.run.id+'/stop',{});s.run=await api('/api/agent/runs/'+s.run.id);paintRun();if(s.run.status==='cancelled'){s.stream?.close();s.stream=null;await refresh();}}); $('sessions').onchange=safely(()=>openSession($('sessions').value)); $('new-session').onclick=safely(async()=>{await flush();const p=await api('/api/agent/sessions',{name:'新的架构图项目',domain:'architecture'});await listSessions();await openSession(p.id);}); $('task-target').onchange=context;$('clear-selection').onclick=()=>{bridge()?.clearSelection();context();}; $('example').onclick=()=>{$('prompt').value='画一张英文的论文方法架构图,表达城市应急资源调度:需求与路网输入 → 需求预测 → 多目标优化 → 派车执行,执行结果反馈到下一轮预测。强调输入、优化核心与反馈关系,沿用合适资产的细节,去掉不相关的演示内容。';$('prompt').focus();}; $('toggle-sidebar').onclick=()=>document.body.classList.toggle('hide-sidebar');$('toggle-agent').onclick=()=>document.body.classList.toggle('hide-agent'); window.addEventListener('message',e=>{if(e.origin!==location.origin||e.source!==s.frame?.contentWindow||!e.data?.vividArchitecture)return;context();if(e.data.type==='saved'&&s.current){s.current.revision=e.data.revision;$('revision-badge').textContent='v'+e.data.revision;}}); setInterval(()=>{if(s.run&&['running','queued'].includes(s.run.status))$('run-elapsed').textContent=Math.max(0,Math.floor(Date.now()/1000-s.run.created))+'s';},1000); safely(async()=>{const health=await api('/api/health');if(!health.architecture_agent)throw Error('请重启完整本地工作台以载入架构 Agent。');const b=await api('/api/bootstrap');s.token=b.token;settings.paint(b.model);const q=new URLSearchParams(location.search);$('preferred-asset').value=q.get('asset')||'';const all=await listSessions();let id=q.get('session')||localStorage.getItem('vivid-architecture-agent-session');if(!all.some(p=>p.id===id))id=all[0]?.id;if(!id){id=(await api('/api/agent/sessions',{name:'架构图工作区',domain:'architecture'})).id;await listSessions();}await openSession(id,q.get('project'));if(q.get('asset'))$('task-target').value='new';context();})(); })();