2 lines
11 KiB
JavaScript
2 lines
11 KiB
JavaScript
import{l as x,m as u}from"./main.js";import"./runtime-dom.esm-bundler.js";import"./_plugin-vue_export-helper.js";import"./useMarkdownRenderer.js";const g=(...e)=>{},S=(...e)=>{console.log(...e)},p=(...e)=>{console.log("[JSONDEBUG]",...e)},C="[CONN_DIAG]",v=2e3,c=(e,n={})=>{const l={ts:new Date().toISOString(),event:e,...n};try{if(typeof window<"u"){const a=window;Array.isArray(a.__CONN_DIAG_LOGS__)||(a.__CONN_DIAG_LOGS__=[]),a.__CONN_DIAG_LOGS__.push(l),a.__CONN_DIAG_LOGS__.length>v&&a.__CONN_DIAG_LOGS__.splice(0,a.__CONN_DIAG_LOGS__.length-v)}}catch{}console.log(C,e,l)},D=x("task",{state:()=>({currentTaskId:null,lastEventIndex:0,pollingInterval:null,taskStatus:"idle",isPolling:!1,pollingError:null,pollingErrorCount:0,pollingInFlight:!1,pollingSeq:0,pollingWarned:!1,pollingRequestTimeoutMs:12e3,pollingFailThreshold:8,pollingIntervalMs:250,taskCreatedAt:null,taskUpdatedAt:null,runtimeQueueSnapshotKey:""}),getters:{hasActiveTask:e=>e.currentTaskId!==null&&e.taskStatus==="running",isTaskCompleted:e=>["succeeded","failed","canceled"].includes(e.taskStatus)},actions:{async createTask(e,n=[],d=[],l=null,a={}){try{u("[Task] 创建任务:",{message:e,conversationId:l});const i=await fetch("/api/tasks",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({message:e,images:n,videos:d,conversation_id:l,model_key:a.model_key??void 0,run_mode:a.run_mode??void 0,thinking_mode:typeof a.thinking_mode=="boolean"?a.thinking_mode:void 0,message_source:a.message_source??void 0})});if(!i.ok){const h=await i.json();throw new Error(h.error||"创建任务失败")}const r=await i.json();if(!r.success)throw new Error(r.error||"创建任务失败");return this.currentTaskId=r.data.task_id,this.taskStatus=r.data.status,this.lastEventIndex=0,this.taskCreatedAt=r.data.created_at,this.runtimeQueueSnapshotKey="",this.pollingError=null,this.pollingErrorCount=0,this.pollingWarned=!1,u("[Task] 任务创建成功:",r.data.task_id),c("task-created",{taskId:r.data.task_id,conversationId:l}),this.startPolling(a.eventHandler),r.data}catch(i){throw c("task-create-failed",{error:(i==null?void 0:i.message)||String(i),conversationId:l}),i}},async pollTaskEvents(e){var i;if(!this.currentTaskId){this.stopPolling("no-active-task");return}if(this.pollingInFlight)return;this.pollingInFlight=!0;const n=this.currentTaskId,d=this.lastEventIndex,l=`${Date.now()}-${++this.pollingSeq}`,a=Date.now();try{const r=await fetch(`/api/tasks/${n}?from=${d}`,{signal:AbortSignal.timeout(this.pollingRequestTimeoutMs),headers:{"X-Task-Poll":l}});if(!r.ok)throw new Error(`HTTP ${r.status}`);const h=await r.json();if(!h.success)throw new Error(h.error||"轮询任务失败");const t=h.data,_=Array.isArray(t==null?void 0:t.events)?t.events.length:0;p("taskStore.poll:response",{taskId:n,from:d,status:t==null?void 0:t.status,nextOffset:t==null?void 0:t.next_offset,eventsCount:_}),(_>0||this.pollingErrorCount>0||(t==null?void 0:t.status)!=="running"||d===0)&&c("task-poll-ok",{requestId:l,taskId:n,from:d,nextOffset:t==null?void 0:t.next_offset,status:t==null?void 0:t.status,eventsCount:_,elapsedMs:Date.now()-a}),this.taskStatus=t.status,this.taskUpdatedAt=t.updated_at;const f=Array.isArray(t==null?void 0:t.runtime_queued_messages)?t.runtime_queued_messages:[],T=JSON.stringify(f.map(o=>[String((o==null?void 0:o.id)||""),String((o==null?void 0:o.text)||"")]));if(T!==this.runtimeQueueSnapshotKey){this.runtimeQueueSnapshotKey=T;try{e({type:"runtime_queue_sync",data:{task_id:(t==null?void 0:t.task_id)||this.currentTaskId,conversation_id:(t==null?void 0:t.conversation_id)||null,messages:f}})}catch(o){console.warn("[Task] 处理 runtime_queue_sync 失败:",o)}}let I=!1,m=!1;if(t.events&&t.events.length>0){u(`[Task] 收到 ${t.events.length} 个新事件`);for(const s of t.events){((s==null?void 0:s.type)==="task_complete"||(s==null?void 0:s.type)==="task_stopped"||(s==null?void 0:s.type)==="error")&&p("taskStore.poll:event",{idx:s==null?void 0:s.idx,type:s==null?void 0:s.type,data:s==null?void 0:s.data}),(s==null?void 0:s.type)==="task_complete"&&(I=!0),(s==null?void 0:s.type)==="task_stopped"&&(m=!0);try{e(s)}catch(k){console.error("[Task] 处理事件失败:",k,s)}}const o=t.events.filter(s=>["user_message","sub_agent_waiting","task_complete","task_stopped","error"].includes(s==null?void 0:s.type));o.length>0&&S("[DEBUG_NOTIFY_KEY][task] events",{taskId:this.currentTaskId,from:this.lastEventIndex,nextOffset:t.next_offset,count:o.length,items:o.map(s=>{var k,E,y,w;return{idx:s==null?void 0:s.idx,type:s==null?void 0:s.type,sub_agent_notice:!!((k=s==null?void 0:s.data)!=null&&k.sub_agent_notice),has_running_sub_agents:(E=s==null?void 0:s.data)==null?void 0:E.has_running_sub_agents,has_running_background_commands:(y=s==null?void 0:s.data)==null?void 0:y.has_running_background_commands,task_id:(w=s==null?void 0:s.data)==null?void 0:w.task_id}})}),this.lastEventIndex=t.next_offset}if(t.status==="canceled"&&!m){u("[Task] 状态已取消但未收到 task_stopped,补发本地事件"),p("taskStore.poll:emit-synthetic-task-stopped",{taskId:t.task_id||this.currentTaskId,conversation_id:t.conversation_id||null});try{e({type:"task_stopped",data:{task_id:t.task_id||this.currentTaskId,conversation_id:t.conversation_id||null,synthetic:!0}})}catch(o){console.error("[Task] 处理补发 task_stopped 失败:",o)}}if(t.status==="succeeded"&&!I){u("[Task] 状态已成功但未收到 task_complete,补发本地事件"),p("taskStore.poll:emit-synthetic-task-complete",{taskId:t.task_id||this.currentTaskId,conversation_id:t.conversation_id||null});try{e({type:"task_complete",data:{task_id:t.task_id||this.currentTaskId,conversation_id:t.conversation_id||null,synthetic:!0,has_running_sub_agents:!1,has_running_background_commands:!1}})}catch(o){console.error("[Task] 处理补发 task_complete 失败:",o)}}this.isTaskCompleted&&(u("[Task] 任务已完成,停止轮询:",this.taskStatus),this.stopPolling(`task-${this.taskStatus}`)),this.pollingError=null,this.pollingErrorCount=0,this.pollingWarned=!1}catch(r){this.pollingErrorCount++,this.pollingError=r.message;const h=(r==null?void 0:r.message)||String(r),t=/timeout|timed out|abort|aborted/i.test(h);if(console.error("[Task] 轮询失败:",r),c("task-poll-failed",{requestId:l,taskId:n,from:d,elapsedMs:Date.now()-a,error:h,isTimeoutLike:t,pollingErrorCount:this.pollingErrorCount}),g("[DEBUG_NOTIFY][task] pollTaskEvents:error",{taskId:this.currentTaskId,from:this.lastEventIndex,error:(r==null?void 0:r.message)||String(r),pollingErrorCount:this.pollingErrorCount}),/HTTP 404|HTTP 410/.test(h)){this.stopPolling("task-not-found");return}this.pollingErrorCount>=this.pollingFailThreshold&&!this.pollingWarned&&(this.pollingWarned=!0,(i=window.__vueApp)!=null&&i.uiPushToast&&window.__vueApp.uiPushToast({title:"轮询波动",message:"消息更新暂时不稳定,正在自动重试",type:"warning",duration:5e3}))}finally{this.pollingInFlight=!1}},startPolling(e){if(this.isPolling){g("[DEBUG_NOTIFY][task] startPolling:already-running",{taskId:this.currentTaskId,lastEventIndex:this.lastEventIndex});return}if(!this.currentTaskId)return;u("[Task] 启动轮询:",this.currentTaskId),g("[DEBUG_NOTIFY][task] startPolling",{taskId:this.currentTaskId,lastEventIndex:this.lastEventIndex}),this.isPolling=!0,this.pollingError=null,this.pollingErrorCount=0,this.pollingWarned=!1;const n=e||window.__taskEventHandler;if(!n){console.error("[Task] 没有事件处理器,无法启动轮询"),c("task-poll-start-failed-no-handler",{taskId:this.currentTaskId}),this.isPolling=!1;return}c("task-poll-start",{taskId:this.currentTaskId,from:this.lastEventIndex,intervalMs:this.pollingIntervalMs,timeoutMs:this.pollingRequestTimeoutMs}),this.pollTaskEvents(n),this.pollingInterval=window.setInterval(()=>{this.pollTaskEvents(n)},this.pollingIntervalMs)},resumeTask(e,n={}){e&&(g("[DEBUG_NOTIFY][task] resumeTask",{incomingTaskId:e,currentTaskId:this.currentTaskId,options:n}),S("[DEBUG_NOTIFY_KEY][task] resumeTask",{incomingTaskId:e,currentTaskId:this.currentTaskId,resetOffset:(n==null?void 0:n.resetOffset)!==!1}),this.currentTaskId&&this.currentTaskId!==e&&this.stopPolling(),this.currentTaskId=e,this.taskStatus=n.status||"running",n.resetOffset!==!1&&(this.lastEventIndex=0),this.pollingError=null,this.runtimeQueueSnapshotKey="",this.startPolling(n.eventHandler))},stopPolling(e="manual"){c("task-poll-stop",{reason:e,taskId:this.currentTaskId,status:this.taskStatus,from:this.lastEventIndex,pollingErrorCount:this.pollingErrorCount}),this.pollingInterval&&(clearInterval(this.pollingInterval),this.pollingInterval=null),this.isPolling=!1,this.pollingInFlight=!1,this.pollingWarned=!1,this.runtimeQueueSnapshotKey="",this.currentTaskId=null},async cancelTask(){if(this.currentTaskId)try{u("[Task] 取消任务:",this.currentTaskId);const e=await fetch(`/api/tasks/${this.currentTaskId}/cancel`,{method:"POST"});if(!e.ok)throw new Error("取消任务失败");const n=await e.json();if(!n.success)throw new Error(n.error||"取消任务失败");u("[Task] 已发送取消请求,等待后端停止确认")}catch(e){throw console.error("[Task] 取消任务失败:",e),e}},async loadRunningTask(e=null){try{u("[Task] 查找运行中的任务");const n=await fetch("/api/tasks");if(!n.ok)throw new Error("获取任务列表失败");const d=await n.json();if(!d.success)throw new Error(d.error||"获取任务列表失败");const l=new Set(["pending","running","cancel_requested"]),a=d.data.find(i=>l.has(String(i.status||""))&&(!e||i.conversation_id===e));if(a){u("[Task] 发现运行中的任务:",a.task_id),this.currentTaskId=a.task_id,this.taskStatus=a.status,this.taskCreatedAt=a.created_at,this.taskUpdatedAt=a.updated_at,this.pollingError=null,this.pollingErrorCount=0,this.pollingWarned=!1,this.runtimeQueueSnapshotKey="";try{const i=await fetch(`/api/tasks/${a.task_id}`);if(i.ok){const r=await i.json();r.success&&r.data.events?(this.lastEventIndex=r.data.next_offset||r.data.events.length,u("[Task] 设置起始偏移量:",this.lastEventIndex)):this.lastEventIndex=0}else this.lastEventIndex=0}catch(i){console.warn("[Task] 获取任务详情失败,从头开始:",i),this.lastEventIndex=0}return a}return u("[Task] 没有运行中的任务"),null}catch(n){return console.error("[Task] 加载运行中任务失败:",n),null}},clearTask(){this.stopPolling(),this.currentTaskId=null,this.lastEventIndex=0,this.taskStatus="idle",this.pollingError=null,this.pollingErrorCount=0,this.pollingWarned=!1,this.taskCreatedAt=null,this.taskUpdatedAt=null,this.runtimeQueueSnapshotKey=""},resetForNewConversation(){this.stopPolling(),this.currentTaskId=null,this.lastEventIndex=0,this.taskStatus="idle",this.pollingError=null,this.pollingErrorCount=0,this.pollingWarned=!1,this.runtimeQueueSnapshotKey=""}}});export{D as useTaskStore};
|