/* 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='

文档预览

100%
';document.body.append(dialog);let zoom=1,original=null; function openPreview(title,content,format='markdown',note='',attachment=null){zoom=1;original=attachment;$('documentPreviewTitle').textContent=title;$('documentPreviewNote').textContent=note;$('documentPreviewZoom').textContent='100%';$('documentPreviewBody').style.fontSize='14px';dialog.querySelector('[data-cp-original]').hidden=!original;if(format==='markdown')$('documentPreviewBody').innerHTML=markdown(content);else{$('documentPreviewBody').replaceChildren();const pre=document.createElement('pre');pre.textContent=content;$('documentPreviewBody').append(pre)}if(!dialog.open)dialog.showModal()} const beforeArtifact=renderArtifact;renderArtifact=function(){beforeArtifact();const a=S.artifact;if(shownArtifact!==a?.artifact_id){shownArtifact=a?.artifact_id;editing=false}toolbar.hidden=!a;readable.hidden=!a||editing;$('artifactContent').classList.toggle('hidden',!!a&&!editing);if(a)readable.innerHTML=markdown($('artifactContent').value);toolbar.querySelector('[data-cp-view]').setAttribute('aria-pressed',String(!editing));toolbar.querySelector('[data-cp-edit]').setAttribute('aria-pressed',String(editing));$('saveArtifact').disabled=!a||$('artifactContent').value===a.content}; $('artifactContent').addEventListener('input',()=>{$('saveArtifact').disabled=!S.artifact||$('artifactContent').value===S.artifact.content}); const beforeAttachments=renderAttachments;renderAttachments=function(){beforeAttachments();[...$('attachmentChips').children].forEach((el,i)=>{const a=S.attachments[i];if(!a||a.parse_status!=='ready')return;const button=document.createElement('button');button.type='button';button.dataset.cpAttachment=a.attachment_id;button.textContent='预览';button.setAttribute('aria-label','预览 '+a.filename);el.append(button)})}; function returnToChat(){if(!$('employee').value)return;$('employee').value='';S.selectedSkills.clear();S.selectedBases.clear();S.form={};selections();$('prompt').placeholder='继续提问,或告诉我需要怎样修改这份纪要…'} const beforeBusy=setBusy;setBusy=function(value){beforeBusy(value);if(!value)window.workosWorkflowInputs?.setRunning(!!S.run&&S.run.employee_id===currentEmployee()?.employee_id&&['queued','running'].includes(S.run.status));if(!value&&pendingFinish){pendingFinish=null;returnToChat()}if(!value&&pendingFailure){const failure=pendingFailure;pendingFailure=null;if(failure.wid===S.wid&&failure.epoch===S.epoch){$('replyState').className='cp-failed';$('replyState').innerHTML=failure.html}}}; const beforeRun=renderRun;renderRun=function(){beforeRun();if(S.run?.artifact_id&&['awaiting_confirmation','succeeded'].includes(S.run.status)&&!finishedRuns.has(S.run.run_id)){finishedRuns.add(S.run.run_id);if(currentEmployee()?.employee_id===S.run.employee_id)returnToChat()}}; const beforeRestore=restoreSelections;restoreSelections=function(){beforeRestore();if(currentEmployee()?.input_schema?.length&&(S.artifact||S.run?.artifact_id))returnToChat()}; const beforeApi=api; function stopWatch(){if(watch){clearTimeout(watch.timer);clearInterval(watch.clock)}watch=null} function stepHTML(steps=[]){return steps.length?'
    '+steps.map(step=>'
  1. '+({completed:'✓',running:'◉',failed:'!',unknown:'?'}[step.status]||'·')+'
    '+esc(step.label||step.name)+''+esc(step.detail||'')+'
  2. ').join('')+'
':''} function processElapsed(seconds){seconds=Math.max(0,Math.floor(Number(seconds)||0));return seconds>=60?Math.floor(seconds/60)+'分'+seconds%60+'秒':seconds+'秒'} function processOverview(data={},turn=null){const m=data.metrics||{},parts=[];if(m.file_count)parts.push('已读取 '+m.file_count+' 份材料');if(m.characters)parts.push(m.characters.toLocaleString()+' 字');if(m.citation_count)parts.push(m.citation_count+' 条参考依据');if(turn?.meeting?.actions?.length)parts.push('整理 '+turn.meeting.actions.length+' 项行动');if(!parts.length&&turn?.assistant_message?.content)parts.push('已生成 '+turn.assistant_message.content.length+' 字答复');return parts.join(' · ')||data.detail||'正在确认本轮输入与处理方式。'} function processCard(data={},turn=null,live=false){const steps=data.steps||[],completed=steps.filter(s=>s.status==='completed').length,done=data.status==='completed',failed=['failed','unknown'].includes(data.status),paused=data.status==='awaiting_confirmation';const state=done?'已完成':failed?'已停止':paused?'等待核对':'处理中';return '
Work OS
'+esc(done?'本轮处理已完成':data.label||'正在处理本轮任务')+'

'+esc(processOverview(data,turn))+'

过程消息'+ (steps.length?(completed?'已完成 '+completed+' 个步骤':'正在开始处理'):'查看处理信息')+'

'+esc(data.detail||'依据实际处理回执记录。')+'

'+stepHTML(steps)+(turn?.model_id?'
'+esc(turn.model_id)+(turn.usage?' · 输入 '+(turn.usage.input_tokens||0)+' / 输出 '+(turn.usage.output_tokens||0)+' tokens':'')+'
':'')+'
'} function statusHTML(label,elapsed,detail='',steps=[],receipt={}){return processCard({...receipt,status:receipt.status||'running',label,detail,steps,elapsed_seconds:elapsed},null,true)} function failureHTML(error,last,elapsed){const code=error.code||last?.error?.code||'NETWORK_ERROR',unknown=code.includes('UNKNOWN')||last?.error?.outcome_unknown;const message=last?.error?.message||error.message||'连接已中断,当前无法确认处理结果。';let next='本轮输入已恢复到输入框,可按原因调整后再发送。';if(unknown)next='模型结果尚未确认,请先刷新当前对话查询结果,避免重复提交。';else if(code==='NETWORK_ERROR')next='请检查网络,再刷新当前对话确认是否已生成结果。';else if(code==='LLM_AUTH_FAILED')next='请管理员检查服务端模型凭据和地域配置。';else if(code==='LLM_RATE_LIMITED'||code.includes('ADMISSION'))next='模型服务繁忙,请稍候再尝试。';else if(code.startsWith('MEETING_')||code==='WORKFLOW_INPUT_REQUIRED')next='请检查当前会议文件或补充原文;会议日期可以留空。';else if(code.startsWith('INVALID_MEETING'))next='这是模型输出格式问题,会议日期可以留空;原始材料已保留。';return '
本次处理'+(unknown?'结果待确认':'未完成')+' · '+Math.floor(elapsed)+' 秒

停止阶段:'+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(); })();