/* Readable artifacts, owned full-screen previews, live execution status and one-shot employee cards. */ (()=>{'use strict'; let editing=false,shownArtifact=null,pendingFinish=null,watch=null,pendingFailure=null;const finishedRuns=new Set(); const toolbar=document.createElement('div');toolbar.className='cp-result-tools';toolbar.innerHTML=''; $('artifactContent').before(toolbar);const readable=document.createElement('article');readable.id='artifactPreview';readable.className='cp-document markdown';readable.setAttribute('aria-label','排版后的成果');$('artifactContent').before(readable); const dialog=document.createElement('dialog');dialog.id='documentPreviewDialog';dialog.innerHTML='
'+esc(processOverview(data,turn))+'
'+esc(data.detail||'依据实际处理回执记录。')+'
'+stepHTML(steps)+(turn?.model_id?'':'')+'停止阶段:'+esc(last?.label||'提交或连接服务')+'
原因:'+esc(message)+'
'+stepHTML(last?.steps)+''+esc(next)+'
错误编号:'+esc(code)+(error.trace_id?' · 请求追踪:'+esc(error.trace_id):'')+''} function startWatch(path,key){stopWatch();const wid=S.wid,epoch=S.epoch,started=Date.now();watch={key,wid,epoch,timer:null,clock:null,label:'正在准备材料并核对本轮要求',detail:'',changed:0,pending:null,steps:[],last:null,pollFailures:0,started};const mine=watch; function paint(){if(watch!==mine||S.epoch!==epoch)return;const elapsed=Math.floor((Date.now()-started)/1000);if(mine.pending&&Date.now()-mine.changed>1600){Object.assign(mine,mine.pending);mine.pending=null;mine.changed=Date.now()}let detail=mine.detail;if(mine.pollFailures>=3)detail+=' · 进度连接暂时不可用,主请求仍在进行。';else if(elapsed>=45&&mine.last?.status==='running')detail+=' · 本阶段仍未返回;目前尚无失败回执。';$('replyState').className='cp-processing';const signature=JSON.stringify([mine.label,detail,mine.steps,mine.last?.metrics]);if(signature!==mine.signature||!$('replyState').querySelector('.cp-live-card')){const expanded=$('replyState').querySelector('.cp-process-details')?.open;const focused=document.activeElement===$('replyState').querySelector('.cp-process-details>summary');$('replyState').innerHTML=statusHTML(mine.label,elapsed,detail,mine.steps,mine.last||{});$('replyState').querySelector('.cp-process-details').open=!!expanded;if(focused)$('replyState').querySelector('.cp-process-details>summary').focus();mine.signature=signature}else{const clock=$('replyState').querySelector('time');if(clock)clock.textContent=(['failed','unknown'].includes(mine.last?.status)?'已停止':'处理中')+' · '+processElapsed(elapsed)}} async function poll(){if(watch!==mine)return;try{const result=await beforeApi('/workspaces/'+wid+'/chat-progress?request_key='+encodeURIComponent(key));if(watch===mine){mine.last=result;mine.pollFailures=0;mine.pending={label:result.label,detail:result.detail||(result.source_chunks>1?'全文按 '+result.source_chunks+' 段处理 · 已完成 '+result.completed_stages+' 个模型阶段':'模型正在处理,本阶段尚未返回结果。'),steps:result.steps||[]};if(['failed','unknown'].includes(result.status)){mine.label='处理已停止,正在接收错误信息';mine.detail=result.error?.message||result.detail;mine.steps=result.steps||[];mine.pending=null}}}catch{mine.pollFailures++}finally{if(watch===mine)mine.timer=setTimeout(poll,1500)}} paint();bottom();mine.clock=setInterval(paint,1000);mine.timer=setTimeout(poll,800) } api=async function(path,method='GET',body,key){const chat=method==='POST'&&/^\/workspaces\/[^/]+\/chat$/.test(path);if(!chat){const launch=method==='POST'&&/^\/workspaces\/[^/]+\/runs$/.test(path);if(launch)window.workosWorkflowInputs?.setRunning(true);try{return await beforeApi(path,method,body,key)}catch(error){if(launch)window.workosWorkflowInputs?.setRunning(false);throw error}}const employee=currentEmployee();if(!employee&&S.artifact){await saveArtifact();body={...body,artifact_id:S.artifact.artifact_id,artifact_version:S.artifact.version}}pendingFailure=null;window.workosWorkflowInputs?.setRunning(true);startWatch(path,key);try{const result=await beforeApi(path,method,body,key);if(!result.process&&watch){const elapsed_seconds=(Date.now()-watch.started)/1000;result.process={...(watch.last||{}),status:'completed',label:result.artifact?'成果已生成并保存':'本轮答复已完成',elapsed_seconds,steps:(watch.last?.steps||[]).map(step=>({...step,status:step.status==='running'?'completed':step.status}))}}if(result.artifact&&employee?.input_schema?.length)pendingFinish={employee:employee.employee_id};$('replyState').className='cp-completed';$('replyState').textContent=result.artifact_revised?'修订稿已生成,请核对。可以继续提出修改意见。':result.artifact?'纪要已生成。可以直接继续提问或提出修改意见。':'';return result}catch(error){const mine=watch;let last=mine?.last;try{const status=await beforeApi('/workspaces/'+S.wid+'/chat-progress?request_key='+encodeURIComponent(key));if(status?.error)last=status}catch{}pendingFailure={wid:mine?.wid||S.wid,epoch:mine?.epoch??S.epoch,html:failureHTML(error,last,mine?(Date.now()-mine.started)/1000:0)};throw error}finally{stopWatch()}}; document.addEventListener('click',async e=>{const target=e.target.closest('button');if(!target)return;try{ if(target.hasAttribute('data-cp-refresh-chat'))await selectSpace(S.wid); if(target.hasAttribute('data-cp-edit')){editing=true;renderArtifact();$('artifactContent').focus()} if(target.hasAttribute('data-cp-view')){editing=false;renderArtifact()} if(target.hasAttribute('data-cp-preview')){if(S.artifact)openPreview('成果预览',$('artifactContent').value,'markdown','草稿 v'+S.artifact.version+' · 请核对事实、责任人和期限')} if(target.dataset.cpAttachment){target.disabled=true;const value=await beforeApi('/workspaces/'+S.wid+'/attachments/'+target.dataset.cpAttachment+'/preview');openPreview(value.filename,value.text,value.format,(value.format==='text'?'原文正文预览(提取文字)':'Markdown 排版预览')+(value.truncated?' · 仅显示前20万字符':''),{id:target.dataset.cpAttachment,name:value.filename})} if(target.hasAttribute('data-cp-close'))dialog.close(); if(target.hasAttribute('data-cp-full')){dialog.classList.toggle('cp-fullscreen');target.textContent=dialog.classList.contains('cp-fullscreen')?'退出全屏':'全屏';target.setAttribute('aria-pressed',String(dialog.classList.contains('cp-fullscreen')))} if(target.dataset.cpZoom){zoom=Math.max(.75,Math.min(1.75,zoom+(target.dataset.cpZoom==='+'?.1:-.1)));$('documentPreviewBody').style.fontSize=(14*zoom)+'px';$('documentPreviewZoom').textContent=Math.round(zoom*100)+'%'} if(target.hasAttribute('data-cp-original')&&original)await download('/attachments/'+original.id+'/content',original.name) }catch(error){toast(error.message)}finally{if(target.isConnected)target.disabled=false}}); $('employee').addEventListener('change',()=>{if($('employee').value){$('replyState').className='';$('replyState').textContent='';$('prompt').placeholder='给 Work OS 一项任务…'}}); const beforeProcessMessages=renderMessages; renderMessages=function(){beforeProcessMessages();document.querySelectorAll('#messages .message.assistant').forEach(el=>{const index=[...$('messages').children].indexOf(el),message=S.messages[index],turn=S.turns.find(t=>t.assistant_message?.message_id===message?.message_id);if(!turn?.process)return;const body=el.querySelector('.message-body');body?.insertAdjacentHTML('beforebegin',processCard(turn.process,turn,false))})}; const beforeProcessRun=renderRun; renderRun=function(){const expanded=$('runProgress').querySelector('.cp-process-details')?.open;beforeProcessRun();const run=S.run;window.workosWorkflowInputs?.setRunning(!!run&&run.employee_id===currentEmployee()?.employee_id&&['queued','running'].includes(run.status));if(!run)return;const terminal=['succeeded','failed','cancelled','awaiting_confirmation'].includes(run.status),start=Date.parse(run.created_at),end=terminal?Date.parse(run.updated_at):Date.now();const data={status:run.status==='succeeded'?'completed':run.status,label:run.status==='awaiting_confirmation'?'初稿已完成,核对后继续后续节点':run.status==='succeeded'?'数字员工流程已完成':run.error?.message||run.steps.find(s=>s.status==='running')?.label||states[run.status],elapsed_seconds:Number.isFinite(start)&&Number.isFinite(end)?Math.max(0,(end-start)/1000):undefined,detail:run.status==='awaiting_confirmation'?'可以在右侧核对并修改成果,确认后执行后续节点。':run.error?.message||'以下显示已发布工作流各节点的实际状态。',metrics:{file_count:run.files?.length||0,citation_count:run.citations?.length||0},steps:run.steps.map(step=>({name:step.step_id,label:step.label,status:step.status==='succeeded'?'completed':step.status==='failed'?'failed':step.status==='running'?'running':'pending',detail:step.status==='pending'?'等待前序节点完成':step.status==='awaiting_confirmation'?'等待人工核对':''}))};const el=$('runProgress');el.querySelector('.steps')?.remove();el.firstElementChild?.insertAdjacentHTML('afterend',processCard(data,{model_id:run.generation?.model_id},true));const detail=el.querySelector('.cp-process-details');if(detail)detail.open=!!expanded}; renderArtifact();renderAttachments(); })();