@qt4798/pi-web 0.17.8 → 0.17.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/.next/BUILD_ID +1 -1
  2. package/.next/app-path-routes-manifest.json +21 -21
  3. package/.next/build-manifest.json +2 -2
  4. package/.next/prerender-manifest.json +3 -3
  5. package/.next/required-server-files.js +1 -1
  6. package/.next/required-server-files.json +1 -1
  7. package/.next/server/app/_global-error/page_client-reference-manifest.js +1 -1
  8. package/.next/server/app/_global-error.html +1 -1
  9. package/.next/server/app/_global-error.rsc +1 -1
  10. package/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
  11. package/.next/server/app/_global-error.segments/_global-error/__PAGE__.segment.rsc +1 -1
  12. package/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  13. package/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
  14. package/.next/server/app/_not-found.html +1 -1
  15. package/.next/server/app/_not-found.rsc +1 -1
  16. package/.next/server/app/_not-found.segments/_full.segment.rsc +1 -1
  17. package/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +1 -1
  18. package/.next/server/app/_not-found.segments/_tree.segment.rsc +1 -1
  19. package/.next/server/app/api/app-update/route.js +1 -1
  20. package/.next/server/app/api/pair/route.js +1 -1
  21. package/.next/server/app/index.html +1 -1
  22. package/.next/server/app/index.rsc +3 -3
  23. package/.next/server/app/index.segments/__PAGE__.segment.rsc +3 -3
  24. package/.next/server/app/index.segments/_full.segment.rsc +3 -3
  25. package/.next/server/app/index.segments/_tree.segment.rsc +1 -1
  26. package/.next/server/app/page.js +1 -1
  27. package/.next/server/app/page_client-reference-manifest.js +1 -1
  28. package/.next/server/app-paths-manifest.json +21 -21
  29. package/.next/server/chunks/4154.js +1 -0
  30. package/.next/server/chunks/7915.js +1 -1
  31. package/.next/server/instrumentation.js +1 -1
  32. package/.next/server/instrumentation.js.nft.json +1 -1
  33. package/.next/server/middleware-build-manifest.js +1 -1
  34. package/.next/server/pages/404.html +1 -1
  35. package/.next/server/pages/500.html +1 -1
  36. package/.next/server/server-reference-manifest.json +1 -1
  37. package/.next/static/chunks/app/{page-de2ca995a25e94cb.js → page-4dc15b51da9c8fc9.js} +1 -1
  38. package/.next/trace +7 -8
  39. package/.next/trace-build +1 -1
  40. package/package.json +1 -1
  41. package/.next/server/chunks/1742.js +0 -1
  42. /package/.next/static/{VwDgjr_v4HvbtX-jQo6TZ → vOqofO6dUkQhxJHaAA5d2}/_buildManifest.js +0 -0
  43. /package/.next/static/{VwDgjr_v4HvbtX-jQo6TZ → vOqofO6dUkQhxJHaAA5d2}/_ssgManifest.js +0 -0
@@ -191,7 +191,7 @@ ${e}`;(0,n.useEffect)(()=>{t||l(!0)},[t]),(0,n.useEffect)(()=>{if(!a||t)return;l
191
191
 
192
192
  Goal: ${r}`:e9)}return t.join("\n\n")}({collaborationMode:eS.current,tokenMode:eC.current,goalText:"goal"===eS.current?ez.current??void 0:void 0}),c=[eS.current,eC.current,d?String(d.length):""].join("|"),p=t?.id??"new";d&&(eI.current.sessionKey!==p||eI.current.signature!==c)?(eI.current={sessionKey:p,signature:c},s=`${d}
193
193
 
194
- ${r}`):s=r;let h=s,g=n?.map(e=>({type:"image",source:{type:"base64",media_type:e.mimeType,data:e.data}})),m={role:"user",content:g?.length?[...r.trim()?[{type:"text",text:r}]:[],...g]:r,timestamp:Date.now()};T(e=>[...e,m]),ro.current=ci(m),rr.current=l;let f="goal"===eS.current&&!a&&i.length>0&&"idle"===eF.current.status;f&&(ez.current=i,eN(e=>({...e,status:"running",goalText:i,turnsUsed:0,noProgressTurns:0,tokensUsed:0})),eD.current=!0),tV.current=!0,U(!0),ta(a?{kind:"running_command"}:{kind:"waiting_model"}),W({type:"start"}),t6.current=!0,td(!0),t4.current=!0;let x=n?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),v=null,k=!1;try{if(u&&o){let e=tq.current??await re.current,t=e??await rw();if(t){v=t,rb(1,r),ei&&(eX(ei),e&&await tP(t,{type:"set_model",provider:ei.provider,modelId:ei.modelId}));let o=await Promise.race([rR(t).then(()=>!0).catch(()=>!1),cr(4e3).then(()=>!1)]);k=!0,await tP(t,{type:"prompt",message:h,...x?.length?{images:x}:{}}),o||rH(t,l),f&&tP(t,{type:"goal_start",goalText:i}).catch(()=>{})}else throw Error("Unable to create a session for this message")}else if(t){v=t.id;let e=await Promise.race([rR(t.id).then(()=>!0).catch(()=>!1),cr(4e3).then(()=>!1)]);k=!0,await tP(t.id,{type:"prompt",message:h,...x?.length?{images:x}:{}}),e||rH(t.id,l),f&&tP(t.id,{type:"goal_start",goalText:i}).catch(()=>{})}a&&v&&rH(v,l)}catch(t){if(console.error("Failed to send message:",t),k&&v)return void rH(v,l);if(tG.current=!1,rC(),t instanceof ct){let e=ro.current;e&&T(t=>{let r=t[t.length-1];return r?.role==="user"&&ci(r)===e?t.slice(0,-1):t}),rM({type:"error",message:t.message})}else{let r=ro.current;r&&T(e=>{let t=e[e.length-1];return t?.role==="user"&&ci(t)===r?e.slice(0,-1):e}),e.chatInputRef?.current?.replaceMessage?.(m),rM({type:"error",message:`Failed to send message: ${t instanceof Error?t.message:String(t)}`})}ro.current=null,tV.current=!1,U(!1),ta(null),W({type:"end"})}},[u,o,ei,t,rw,rR,rb,rH,rM,rS,rC,rp]),rV=(0,n.useCallback)(async(r,o)=>{if(tV.current||tZ.current)return;let n=`${o?"!!":"!"}${r}`;tZ.current=!0,K({command:r,excludeFromContext:o}),q(!0);try{let e=tq.current??t?.id??await rw();if(!e)throw Error("Unable to create a session for the shell command");rb(1,n),await tP(e,{type:"bash",command:r,excludeFromContext:o}),await rk(e)}catch(t){console.error("Failed to execute shell command:",t),rM({type:"error",message:t instanceof Error?t.message:String(t)}),e.chatInputRef?.current?.insertIfEmpty(n)}finally{tZ.current=!1,K(null),q(!1)}},[rM,rw,rk,e.chatInputRef,rb,t]),rK=(0,n.useCallback)(async()=>{let e=tq.current;if(e)try{await tP(e,{type:tZ.current?"abort_bash":"abort"})}catch(e){console.error("Failed to abort:",e)}},[]),rG=(0,n.useCallback)(async e=>{let t=tq.current;if(t){eK(e);try{let{cancelled:r,newSessionId:o}=await tP(t,{type:"fork",entryId:e})??{};!r&&o&&a?.(o)}catch(e){console.error("Fork failed:",e)}finally{eK(null)}}},[a]),rJ=(0,n.useCallback)(async e=>{let t=tq.current;t&&(tP(t,{type:"navigate_tree",targetId:e}).catch(()=>{}),S(e),await rE(t,e))},[rE]),rY=(0,n.useCallback)(async e=>{S(e);let t=tq.current;t&&(await rE(t,e),e&&tP(t,{type:"navigate_tree",targetId:e}).catch(()=>{}))},[rE]),rX=(0,n.useCallback)(async(e,t)=>{if(u){let r={provider:e,modelId:t};rl.current=r,ea(r),eX(r);let o=tq.current??await re.current;if(!o)return;try{await tP(o,{type:"set_model",provider:e,modelId:t})}catch(e){console.error("Failed to set model:",e)}return}let r=tq.current;if(!r)return;let o=++rn.current,n=eG??g?.context.model??null;eJ({provider:e,modelId:t});try{await tP(r,{type:"set_model",provider:e,modelId:t})}catch(r){console.error("Failed to set model:",r),rn.current===o&&(eJ(n&&(n.provider!==e||n.modelId!==t)?n:null),rM({type:"error",message:r instanceof Error?r.message:String(r)}))}},[rM,eG,g?.context.model,u,ea]),rZ=(0,n.useCallback)(async()=>{let e=tq.current;if(e&&!eZ){tt(!0),to(null),ts(null);try{let t=await tP(e,{type:"compact"});ts(ca(t,"manual")),await rk(e,!0)}catch(e){to(e instanceof Error?e.message:String(e)),ts(null)}finally{tt(!1)}}},[eZ,rk]),rQ=(0,n.useCallback)(async e=>{let r=++rs.current,n=o??t?.cwd??"",s=n?`/api/models?cwd=${encodeURIComponent(n)}`:"/api/models",i=ri.current;i?.abort();let a=new AbortController;ri.current=a;let l=()=>a.abort();e?.aborted?a.abort():e?.addEventListener("abort",l,{once:!0});try{let e=await fetch(s,{signal:a.signal});if(!e.ok){let t=`HTTP ${e.status}`;try{let r=await e.json();r?.error&&(t=r.error)}catch{}throw Error(t)}let t=await e.json();if(r!==rs.current||h!==ra.current)return;es(null),J(t.models),Q(t.thinkingLevels??{}),et(t.thinkingLevelMaps??{}),eo(t.modelScopeWarnings??[]);let o=t.modelList??[];if(X(o),u&&!tq.current){let e=(t.defaultModel?o.find(e=>e.id===t.defaultModel?.modelId&&e.provider===t.defaultModel?.provider):void 0)??o[0];ed(e?{provider:e.provider,modelId:e.id}:null);let r=e?t.thinkingLevelPins?.[`${e.provider}/${e.id}`]:void 0;null===rd.current&&e$(r??"auto")}}catch(e){if(a.signal.aborted||r!==rs.current||h!==ra.current)return;es(e instanceof Error?e.message:String(e))}finally{e?.removeEventListener("abort",l),ri.current===a&&(ri.current=null)}},[u,h,o,t?.cwd]),r0=(0,n.useCallback)(async e=>{if(!e.startsWith("/"))return{handled:!1};let t=e.match(/^\/([^\s]+)(?:\s+([\s\S]*))?$/);if(!t)return{handled:!1};let[,r,o=""]=t,n=o.trim(),s=tq.current??await rw(),i=e=>(e.handled&&(e.error?rM({type:"error",message:e.error}):"openSessionStats"!==e.action&&rM({type:"success",message:e.message??"Command completed"})),e);try{switch(r){case"compact":{if(!s||eZ)return i({handled:!0,error:"No active session to compact"});tt(!0),to(null),ts(null);let e=await tP(s,{type:"compact",...n?{customInstructions:n}:{}});return ts(ca(e,"manual")),await rk(s,!0)&&rb(),i({handled:!0,message:"Compacted context"})}case"reload":if(!s)return i({handled:!0,error:"No active session to reload"});return await tP(s,{type:"reload"}),await Promise.all([rk(s,!1,!0),ry(s),rj(),rQ()]),i({handled:!0,message:"Reloaded session resources"});case"name":if(!s)return i({handled:!0,error:"No active session to name"});if(!n)return i({handled:!0,error:"Usage: /name <name>"});return await tP(s,{type:"set_session_name",name:te(n)}),await rk(s)&&rb(),i({handled:!0,message:`Session renamed to ${n}`});case"session":{if(!s)return i({handled:!0,error:"No active session"});let e=await tP(s,{type:"get_session_stats"});return e&&tx(e),p?.(),i({handled:!0,action:"openSessionStats"})}case"copy":{if(!s)return i({handled:!0,error:"No active session"});let e=await tP(s,{type:"get_last_assistant_text"}),t=e?.text??"";if(!t)return i({handled:!0,error:"No assistant message to copy"});return await navigator.clipboard.writeText(t),i({handled:!0,message:"Copied last assistant message"})}default:return{handled:!1}}}catch(e){return i({handled:!0,error:e instanceof Error?e.message:String(e)})}finally{"compact"===r&&tt(!1)}},[rM,rw,eZ,rQ,rk,rj,ry,rb,p]),r1=(0,n.useCallback)(async e=>{let t=!1;try{let r=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(r.ok){let e=await r.json(),o=e.state;if(e.running&&o&&(o.isStreaming||o.isPromptRunning||o.isBashRunning||o.isCompacting))return;t=!0}}catch{}t?rF():rH(e)},[rH,rF]),r2=(0,n.useCallback)(async(e,t)=>{let r=tq.current;if(!r)return;let o=t?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType}));tV.current=!0,U(!0),ta(e=>e??{kind:"waiting_model"});try{await tP(r,{type:"steer",message:e,...o?.length?{images:o}:{}})}catch(e){console.error("Failed to steer:",e),r1(r)}},[r1]),r6=(0,n.useCallback)(async(e,t,r)=>{let o=tq.current;if(!o)return;let n=r?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType}));tV.current=!0,U(!0),ta(e=>e??{kind:"waiting_model"});try{await tP(o,{type:"prompt",message:e,streamingBehavior:t,...n?.length?{images:n}:{}})}catch(e){console.error("Failed to queue prompt:",e),r1(o)}},[r1]),r4=(0,n.useCallback)(async(e,t)=>{let r=tq.current;if(!r)return;let o=t?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType}));tV.current=!0,U(!0),ta(e=>e??{kind:"waiting_model"});try{await tP(r,{type:"follow_up",message:e,...o?.length?{images:o}:{}})}catch(e){console.error("Failed to follow up:",e),r1(r)}},[r1]),r5=(0,n.useCallback)(async()=>{let e=tq.current;if(e)try{await tP(e,{type:"abort_compaction"})}catch(e){console.error("Failed to abort compaction:",e)}},[]),r8=(0,n.useCallback)(async()=>{let t=tq.current;if(t)try{let r=await tP(t,{type:"clear_queue"});tz({steering:[],followUp:[]});let o=[...r?.steering??[],...r?.followUp??[]];o.length>0&&e.chatInputRef?.current?.prependText(o.join("\n\n"))}catch(e){console.error("Failed to recall queued messages:",e),rM({type:"error",message:"Failed to recall queued messages"})}},[e.chatInputRef,rM,tz]);(0,n.useEffect)(()=>{0===tI.length&&tW(!1)},[tI.length]);let r3=(0,n.useCallback)(async(e,t,r=!1)=>{let o=tq.current;if(!o)return tI;try{let n=await tP(o,{type:"resolve_recovery",keep:e,discard:t,continueRun:r}),s=n?.remaining??[];return tE(s),r&&e.length>0&&(async()=>{try{let e=await fetch(`/api/agent/${encodeURIComponent(o)}`);if(!e.ok)return;let t=await e.json(),r=t.state;if(!t.running||!r||!r.isStreaming&&!r.isPromptRunning)return;tK.current=!!r.isStreaming,tG.current=!!r.isPromptRunning,tV.current=!0,U(!0),ta(d8(r)),W({type:"start"}),rT(o),!r.isStreaming&&r.isPromptRunning&&rH(o)}catch{}})(),s}catch(e){return console.error("Failed to resolve queued message recovery:",e),rM({type:"error",message:"Failed to resolve queued message recovery"}),tI}},[tI,rM,rT,rH,tE]),r7=(0,n.useCallback)(async()=>{let e=tq.current;if(!e)return null;try{return await tP(e,{type:"export_queue"})}catch(e){return console.error("Failed to export queue:",e),rM({type:"error",message:"Failed to export queue"}),null}},[rM]),r9=(0,n.useCallback)(async e=>{let t=tq.current;if(!t)return null;try{let r=await tP(t,{type:"import_queue",entries:e});return r&&tz(d7(r)),r?.imported??0}catch(e){return console.error("Failed to import queue:",e),rM({type:"error",message:"Failed to import queue"}),null}},[rM,tz]),oe=(0,n.useCallback)(async e=>{let t=tq.current;if(!t)return null;try{let r=await tP(t,{type:"stage_recovery",entries:e});return r?.pendingRecovery&&tE(r.pendingRecovery),(r?.staged??0)>0&&tW(!0),r?.staged??0}catch(e){return console.error("Failed to stage imported queue:",e),rM({type:"error",message:"Failed to stage imported queue"}),null}},[rM,tE]),ot=(0,n.useCallback)(async(e,t,r)=>{let o=tq.current;if(!o)return!1;try{let n=await tP(o,{type:"move_queue",kind:e,fromIndex:t,toIndex:r});return n&&tz(d7(n)),!0}catch(e){return console.error("Failed to move queued message:",e),rM({type:"error",message:e instanceof Error?e.message:"Failed to move queued message"}),!1}},[rM,tz]),or=(0,n.useCallback)(async(e,t)=>{let r=tq.current;if(!r)return null;try{let o=await tP(r,{type:"recall_queue_item",kind:e,index:t});return o&&(void 0!==o.steering||void 0!==o.followUp)&&tz(d7(o)),o?.entry?{text:o.entry.text,images:o.entry.images?.map(({data:e,mimeType:t})=>({data:e,mimeType:t}))}:null}catch(e){return console.error("Failed to recall queued message:",e),rM({type:"error",message:e instanceof Error?e.message:"Failed to recall queued message"}),null}},[rM,tz]),oo=(0,n.useCallback)(async(e,t,r,o)=>{let n=tq.current;if(!n)return!1;try{let s=await tP(n,{type:"requeue_at",kind:e,index:t,text:r,images:o?.map(({data:e,mimeType:t})=>({type:"image",data:e,mimeType:t}))});return s&&tz(d7(s)),!0}catch(e){return console.error("Failed to requeue message:",e),rM({type:"error",message:e instanceof Error?e.message:"Failed to requeue message"}),!1}},[rM,tz]),on=(0,n.useCallback)(async(e,t)=>{let r=tq.current;if(!r)return!1;try{let o=await tP(r,{type:"remove_queue_item",kind:e,index:t});return o&&tz(d7(o)),!0}catch(e){return console.error("Failed to remove queued message:",e),rM({type:"error",message:e instanceof Error?e.message:"Failed to remove queued message"}),!1}},[rM,tz]),os=(0,n.useCallback)(async e=>{if(rd.current="auto"===e?null:e,e$(e),"auto"===e)return;let t=tq.current??await re.current;if(t)try{await tP(t,{type:"set_thinking_level",level:e})}catch(e){console.error("Failed to set thinking level:",e)}},[]),oi=(0,n.useCallback)(async e=>{let t=(0,d2.xG)(e);rh(e);let r=tq.current??await re.current;if(r)try{await tP(r,{type:"set_tools",toolNames:t})}catch(e){console.error("Failed to set tools:",e)}},[rh]),oa=(0,n.useRef)(0),ol=(0,n.useCallback)(async e=>{let t=tq.current??await re.current,r=++oa.current;if("plan"===e){if(eu.current="plan"===ec?"default":ec,t)try{await tP(t,{type:"prompt",message:"/plan"})}catch(e){if(oa.current!==r)return;console.error("Failed to enter plan mode:",e)}return}if(t){try{if(await tP(t,{type:"prompt",message:"/plan exit"}),oa.current!==r)return}catch(e){if(oa.current!==r)return;console.error("Failed to exit plan mode:",e)}if(oa.current!==r)return;try{await tP(t,{type:"set_tools",toolNames:(0,d2.xG)(eu.current)})}catch(e){console.error("Failed to restore tools after plan exit:",e)}}},[ec]),od=(0,n.useCallback)(e=>{em(e);let t=tq.current;if(!t){ef.current=e;return}ef.current=null,fetch(`/api/modes?session=${encodeURIComponent(t)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}).catch(e=>{console.error("Failed to persist mode settings:",e)})},[]),oc=(0,n.useCallback)(e=>{let t=e2(e),r="plan"===eS.current;if(od({...eM.current,collaborationMode:t}),eS.current=t,eI.current={sessionKey:"",signature:""},"goal"!==t){ez.current=null,eD.current=!1,eN(e=>"idle"===e.status?e:{...e,status:"idle",goalText:null});let e=tq.current;e&&tP(e,{type:"goal_stop"}).catch(()=>{})}return"plan"!==t||r?"plan"!==t&&r?ol("normal"):Promise.resolve():ol("plan")},[od,ol]),op=(0,n.useCallback)(async e=>{od({...eM.current,tokenMode:e6(e)});let t=tq.current??await re.current;if(t)try{if("economy"!==e||eh.current){if("economy"!==e){let e=eh.current?d2.SC:(0,d2.xG)("plan"===ec?"default":ec);await tP(t,{type:"set_tools",toolNames:e})}}else await tP(t,{type:"set_tools",toolNames:[...e5]})}catch(e){console.error("Failed to apply token mode tools:",e)}},[od,ec]),ou=(0,n.useCallback)(async e=>{od({...eM.current,toolApprovalMode:e4(e)});let t=tq.current??await re.current;if(t)try{await tP(t,{type:"set_approval_mode",mode:e4(e)})}catch(e){console.error("Failed to apply approval mode:",e)}},[od]),oh=(0,n.useCallback)(async e=>{od({...eM.current,permissionRules:e});let t=tq.current??await re.current;if(t)try{await tP(t,{type:"set_approval_policy",policy:e})}catch(e){console.error("Failed to apply permission rules:",e)}},[od]),og=(0,n.useCallback)(async(e,t,r)=>{let o=tq.current;if(o)try{await tP(o,{type:"resolve_approval",id:e,approve:t,reason:r})}catch(e){console.error("Failed to resolve approval:",e)}finally{eE(t=>t.filter(t=>t.id!==e))}},[]),om=(0,n.useCallback)(e=>{ez.current=e},[]),of=(0,n.useCallback)(e=>{let t=e.trim();if(!t)return;ez.current=t,eN(e=>({...e,status:"running",goalText:t,turnsUsed:0,noProgressTurns:0,tokensUsed:0,startedAt:Date.now()}));let r=tq.current;r&&tP(r,{type:"goal_start",goalText:t}).catch(()=>{})},[]),ox=(0,n.useCallback)(()=>{if("running"!==eF.current.status)return;eN(e=>({...e,status:"paused"}));let e=tq.current;e&&tP(e,{type:"goal_pause"}).catch(()=>{})},[]),ov=(0,n.useCallback)(()=>{let e=eF.current;if("paused"!==e.status&&"blocked"!==e.status)return;eN(e=>({...e,status:"running"}));let t=tq.current;t&&tP(t,{type:"goal_resume"}).catch(()=>{})},[]),ok=(0,n.useCallback)(()=>{eD.current=!1,ez.current=null,eN(e=>({...e,status:"idle",goalText:null,turnsUsed:0,noProgressTurns:0}));let e=tq.current;e&&tP(e,{type:"goal_stop"}).catch(()=>{})},[]),oy=(0,n.useCallback)(e=>{let t=e.trim();if(!t)return;eN(e=>({...e,goalText:t}));let r=tq.current;r&&tP(r,{type:"goal_edit",goalText:t}).catch(()=>{})},[]),ob=(0,n.useCallback)(()=>{let e=t9.current,t=t2.current;if(!e||!t)return;let r=t.getBoundingClientRect().top-e.getBoundingClientRect().top+e.scrollTop,o=Math.max(0,e.scrollHeight-e.clientHeight),n=Math.min(Math.max(0,r-16),o);t5.current=n>=o-150,t3.current=Date.now()+700,e.scrollTo({top:n,behavior:"smooth"})},[]),ow=(0,n.useCallback)(e=>{if(e instanceof KeyboardEvent){if(!ce.has(e.key)||e.target instanceof Element&&e.target.closest("input, textarea, [contenteditable='true']"))return}else if(e instanceof PointerEvent){let t=t9.current;if(t&&e.target instanceof Element&&!t.contains(e.target))return}t8.current=Date.now()+1200},[]),oj=(0,n.useCallback)(()=>{let e=t9.current;if(e){let{scrollTop:t,clientHeight:r,scrollHeight:o}=e;t5.current=t+r>=o-150}if(Date.now()<t8.current){t4.current=!1;return}Date.now()<t3.current||(t4.current=!1)},[]);(0,n.useEffect)(()=>{if(tY.current=!0,t){tq.current=t.id;let e=eT.current,r=eR.current;("auto"!==e||r.allow.length||r.ask.length||r.deny.length)&&(tP(t.id,{type:"set_approval_mode",mode:e}).catch(()=>{}),tP(t.id,{type:"set_approval_policy",policy:r}).catch(()=>{}));let o=e=>{!tQ.current&&(tQ.current=!0,e.isBashRunning&&(tZ.current=!0,q(!0)),ry(t.id),(e.isStreaming||e.isPromptRunning)&&(tK.current=!!e.isStreaming,tG.current=!!e.isPromptRunning,tV.current=!0,U(!0),ta(d8(e)),W({type:"start"}),rT(t.id),!e.isStreaming&&e.isPromptRunning&&rH(t.id)))};(async()=>{try{let e,r=new AbortController,n=setTimeout(()=>r.abort(),2e4);try{e=await fetch(`/api/sessions/${encodeURIComponent(t.id)}/state`,{signal:r.signal})}finally{clearTimeout(n)}if(!e.ok)throw Error(`HTTP ${e.status}`);let s=await e.json();if(!tY.current||tq.current!==t.id)return;s.running&&s.state&&o(s.state)}catch{}})(),rk(t.id,!0,!0).then(e=>{e?.running&&e.state&&o(e.state),e?.state&&(void 0!==e.state.isCompacting&&tt(e.state.isCompacting),void 0!==e.state.contextUsage&&eU(e.state.contextUsage??null),void 0!==e.state.systemPrompt&&eq(e.state.systemPrompt??null),void 0!==e.state.thinkingLevel&&e$(e.state.thinkingLevel??"auto"),void 0!==e.state.extensionStatuses&&tj(e.state.extensionStatuses??[]),void 0!==e.state.extensionWidgets&&tC(e.state.extensionWidgets??[]),void 0!==e.state.queuedMessages&&tz(d7(e.state.queuedMessages)),void 0!==e.state.pendingRecovery&&tE(e.state.pendingRecovery??[])),e?.running||(async()=>{for(let e=0;e<5;e++){if(e>0&&await new Promise(e=>setTimeout(e,2e3)),!tY.current||tq.current!==t.id||tV.current)return;try{let e=await fetch(`/api/agent/${encodeURIComponent(t.id)}`);if(!e.ok)continue;let r=await e.json();if(!tY.current||tq.current!==t.id)return;if(r?.running&&r.state)return void o(r.state)}catch{}}})()})}return()=>{tY.current=!1,f.current?.abort(),v.current?.abort(),rp(),tD(),rS(),rC()}},[rp]),(0,n.useEffect)(()=>{c?.(e_)},[e_,c]),(0,n.useEffect)(()=>{d&&d(g?.tree??[],j,rY)},[g?.tree,j,rY,d]),(0,n.useEffect)(()=>(window.addEventListener("keydown",ow),window.addEventListener("pointerdown",ow,{passive:!0}),()=>{window.removeEventListener("keydown",ow),window.removeEventListener("pointerdown",ow)}),[ow]),(0,n.useEffect)(()=>{let e=t9.current;if(e)return e.addEventListener("wheel",ow,{passive:!0}),e.addEventListener("touchstart",ow,{passive:!0}),e.addEventListener("scroll",oj,{passive:!0}),()=>{e.removeEventListener("wheel",ow),e.removeEventListener("touchstart",ow),e.removeEventListener("scroll",oj)}},[C.length,k,oj,ow]),(0,n.useEffect)(()=>{C.length>0&&(t6.current?(t1.current=!0,t2.current&&(t6.current=!1,ob())):k||!t1.current?(k||(t1.current=!0),rU("instant")):!tV.current&&(t4.current||t5.current)&&(rU("smooth"),oT(e=>e+1)))},[C.length,k,B,rU,ob]);let oS=(0,n.useRef)(null),[oC,oT]=(0,n.useState)(0),oR=`${t?.id??null}#${oC}`;(0,n.useEffect)(()=>{let e;if(k){oS.current=null;return}if(0===C.length||oS.current===oR)return;oS.current=oR;let t=!1,r=!1,o=-1,n=0,s=Date.now(),i=()=>{if(t||r)return;let a=t9.current;if(a){if(Date.now()<t8.current){let{scrollTop:e,clientHeight:t,scrollHeight:o}=a;if(e+t<o-150){r=!0;return}}if(rU("instant"),a.scrollHeight===o){if((n+=1)>=4||Date.now()-s>=3e4)return}else if(o=a.scrollHeight,n=0,Date.now()-s>=3e4)return;e=window.setTimeout(i,n>0?500:250)}};return e=window.setTimeout(i,250),()=>{t=!0,void 0!==e&&window.clearTimeout(e)}},[k,rU,oR]),(0,n.useEffect)(()=>{let e=new AbortController;return rQ(e.signal).catch(e=>{if(e instanceof DOMException&&"AbortError"===e.name)return}),()=>e.abort()},[rQ,l]),(0,n.useEffect)(()=>{if(!en)return;let e=()=>{"visible"===document.visibilityState&&rQ()};return document.addEventListener("visibilitychange",e),window.addEventListener("online",e),()=>{document.removeEventListener("visibilitychange",e),window.removeEventListener("online",e)}},[en,rQ]),(0,n.useEffect)(()=>{if(!tr)return;let e=setTimeout(()=>to(null),3e3);return()=>clearTimeout(e)},[tr]),(0,n.useEffect)(()=>{if(!tn)return;let e=setTimeout(()=>ts(null),6e3);return()=>clearTimeout(e)},[tn]),(0,n.useEffect)(()=>{if(0===tg.visible.length)return;let e=tg.visible.find(e=>e.exiting);if(e){let t=setTimeout(()=>{tm({type:"remove",id:e.id})},180);return()=>clearTimeout(t)}if(!tg.visible[0])return;let t=setTimeout(()=>{tm({type:"mark_oldest_exiting"})},5e3);return()=>clearTimeout(t)},[tg.visible]),(0,n.useEffect)(()=>{tx(null)},[C.length,eB?.tokens,eB?.percent,eB?.contextWindow]);let oz=g?.tree??[];return{data:g,loading:k,error:b,activeLeafId:j,messages:C,entryIds:R,historyCursor:I,hasEarlierMessages:P,streamState:A,agentRunning:B,bashRunning:_,pendingBash:V,modelNames:G,modelList:Y,modelThinkingLevels:Z,modelThinkingLevelMaps:ee,modelScopeWarnings:er,modelsError:en,newSessionModel:ei,toolPreset:ec,thinkingLevel:eL,retryInfo:eH,contextUsage:eB,systemPrompt:e_,forkingEntryId:eV,isCompacting:eZ,compactError:tr,compactResult:tn,currentModel:rf,displayModel:rx,sessionStats:rv,tokenRate:F,planMode:ej,collaborationMode:ek,tokenMode:ey,toolApprovalMode:eb,permissionRules:ew,modeSettings:eg,approvalRequests:eP,handleCollaborationModeChange:oc,handleTokenModeChange:op,handleToolApprovalModeChange:ou,handlePermissionRulesChange:oh,resolveApproval:og,setActiveGoalText:om,goalState:eW,handleGoalStart:of,handleGoalPause:ox,handleGoalResume:ov,handleGoalStop:ok,handleGoalEdit:oy,slashCommands:tc,slashCommandsLoading:tu,queuedMessages:tT,pendingRecovery:tI,recoveryIsImport:tA,notices:tg.visible,extensionDialog:tv,extensionCustomUi:ty,extensionStatuses:tw,extensionWidgets:tS,respondToExtensionUi:rz,sendExtensionCustomInput:rI,agentPhase:ti,isNew:u,promptAnchorActive:tl,branchTree:oz,sessionIdRef:tq,eventSourceRef:tL,messagesEndRef:t7,scrollContainerRef:t9,lastUserMsgRef:t2,pendingScrollToUserRef:t6,initialScrollDoneRef:t1,scrollUserMsgToTop:ob,handleSend:rq,executeBash:rV,handleAbort:rK,handleFork:rG,handleNavigate:rJ,handleModelChange:rX,handleCompact:rZ,handleSteer:r2,handleFollowUp:r4,handlePromptWithStreamingBehavior:r6,handleAbortCompaction:r5,handleRecallQueue:r8,resolveRecovery:r3,exportQueueData:r7,importQueueData:r9,stageQueueImport:oe,moveQueuedMessage:ot,recallQueuedMessage:or,requeueAt:oo,removeQueuedMessage:on,handleBuiltinSlashCommand:r0,handleToolPresetChange:oi,handleThinkingLevelChange:os,loadTools:ry,loadSlashCommands:rj,reloadModels:rQ,setActiveLeafId:S,setData:m,setMessages:T,loadContext:rE,dispatch:W,setAgentRunning:U,setForkingEntryId:eK,handleLeafChange:rY,handleAgentEventRef:t0}}({session:e,newSessionCwd:t,onAgentEnd:N,onSessionCreated:i,onSessionForked:l,modelsRefreshKey:d,chatInputRef:c,onBranchDataChange:p,onSystemPromptChange:u,onSessionStatsPanelOpen:g}),[tj,tS]=(0,n.useState)(!1);(0,n.useEffect)(()=>{0===em.length&&tS(!1)},[em.length]);let{balance:tC,refresh:tT,refreshSoon:tR}=function(){let[e,t]=(0,n.useState)(null),[r,o]=(0,n.useState)(!1),s=(0,n.useRef)(null),i=(0,n.useRef)(null),a=(0,n.useRef)(!0);(0,n.useEffect)(()=>(a.current=!0,()=>{a.current=!1,i.current&&clearTimeout(i.current),s.current?.abort()}),[]);let l=(0,n.useRef)(null),d=(0,n.useCallback)(async()=>{s.current?.abort();let e=new AbortController;s.current=e;try{let r=await fetch("/api/deepseek/balance",{signal:e.signal,cache:"no-store"}),n=await r.json();if(!a.current)return;if(n?.available&&null!=n.totalBalance){let e=l.current;(null===e||e.available!==n.available||e.reason!==n.reason||e.currency!==n.currency||e.totalBalance!==n.totalBalance||e.grantedBalance!==n.grantedBalance||e.toppedUpBalance!==n.toppedUpBalance)&&(l.current=n,t(n)),o(!1)}else null===l.current&&o(!0)}catch{if(!a.current)return;null===l.current&&o(!0)}},[]),c=(0,n.useCallback)(()=>{i.current&&clearTimeout(i.current),i.current=setTimeout(()=>{i.current=null,d()},2e3)},[d]);return{balance:e,failed:r,refresh:d,refreshSoon:c}}(),tz=ed?.provider==="deepseek",tI=(0,n.useRef)(null);(0,n.useEffect)(()=>{tz&&tT()},[tz,tT]),(0,n.useEffect)(()=>{if(tz)for(let e=O.length-1;e>=0;e--){let t=O[e];if("assistant"!==t.role||!t.usage)continue;let r=`${e}:${B[e]??""}`;r!==tI.current&&(tI.current=r,tR());break}},[O,B,tz,tR]);let tM=(0,n.useMemo)(()=>{let e=O.findLast(e=>"assistant"===e.role&&!!e.usage);if(!e?.usage)return null;let t=e.usage;return{model:e.model??"",input:t.input??0,output:t.output??0,cacheRead:t.cacheRead??0,costCNY:aI(e.model)?aM(e.model,t):0,costUSD:aI(e.model)?0:t.cost?.total??0}},[O]),[tE,tA]=(0,n.useState)(!1),[tW,tN]=(0,n.useState)(null),tF=(0,n.useRef)(!1);(0,n.useEffect)(()=>{if(!ta){tF.current=!1;return}if(_){tF.current=!0;return}tF.current&&(tF.current=!1,tN(function(e){for(let t=e.length-1;t>=0;t--){let r=e[t];if("assistant"!==r.role)continue;let o=r.content;if("string"==typeof o&&o.trim())return o;if(Array.isArray(o)){let e=o.filter(e=>"text"===e.type).map(e=>e.text??"").join("\n").trim();if(e)return e}}for(let t=e.length-1;t>=0;t--){let r=e[t];if("toolResult"!==r.role)continue;let o=r.content,n="string"==typeof o?o:Array.isArray(o)?o.map(e=>e.text??"").join("\n"):"";if(!n)continue;let s=n.match(/\*\*Proposed Plan\*\*\s*\n+([\s\S]+)/i);if(s?.[1]?.trim())return s[1].trim()}return null}(O)??null),tA(!0))},[_,ta,O]);let tD=(0,n.useCallback)(()=>{tA(!1);let e=tL.current;e&&tc("plan"===tl?"normal":tl).catch(e=>{console.error("Failed to leave plan mode before executing:",e)}).then(()=>{eF(P("tasks.planReviewExecutePrompt",{plan:e}))})},[tc,eF,P,tl]),tL=(0,n.useRef)(null);(0,n.useEffect)(()=>{tL.current=tW},[tW]);let t$=(0,n.useCallback)(e=>{tA(!1),eF(e)},[eF]),tH=(0,n.useCallback)(()=>{tA(!1),tc("plan"===tl?"normal":tl)},[tc,tl]);(0,n.useEffect)(()=>{ev&&W.current!==ev.id&&(W.current=ev.id,A.current&&E.current())},[ev]),(0,n.useEffect)(()=>(a=_||q?eL:null,()=>void(a=null)),[_,q,eL]);let[tO,tB]=(0,n.useState)(!1),[tU,t_]=(0,n.useState)(!1),[tq,tV]=(0,n.useState)(!1),tK=(0,n.useCallback)(()=>{let e=eP.current;if(!e)return;let t=e.scrollHeight-e.scrollTop-e.clientHeight;tB(e.scrollTop>1),t_(t>1),tV(t>240)},[eP]),tG=(0,n.useCallback)(()=>{window.requestAnimationFrame(()=>{let e=eP.current,t=eM.current;if(!e||!t)return;let r=Math.max(88,c?.current?.measureHeight?.()??0),o=()=>{if(!e||!t)return;let o=Math.max(0,t.getBoundingClientRect().top-e.getBoundingClientRect().top+e.scrollTop-96-e.clientHeight+r);e.scrollTo({top:o,behavior:"auto"})};o(),tK(),window.setTimeout(o,200)})},[eM,eP,tK,c]);(0,n.useEffect)(()=>{let e=eP.current;if(!e)return;let t=new ResizeObserver(tK);return t.observe(e),e.firstElementChild&&t.observe(e.firstElementChild),e.addEventListener("scroll",tK,{passive:!0}),tK(),()=>{e.removeEventListener("scroll",tK),t.disconnect()}},[O.length,eP,tK]);let tJ=(0,n.useRef)(!1);(0,n.useEffect)(()=>{let t=eP.current;if(!t)return;let r=()=>{if(tJ.current||!tb||!ty||t.scrollTop>8)return;let r=e?.id;if(!r)return;tJ.current=!0;let o=t.scrollHeight-t.scrollTop;tw(r,eR,ty).finally(()=>{tJ.current=!1,requestAnimationFrame(()=>{let e=t.scrollHeight-o;Math.abs(t.scrollTop-e)>1&&t.scrollTo({top:e,behavior:"auto"})})})};return t.addEventListener("scroll",r,{passive:!0}),()=>t.removeEventListener("scroll",r)},[eP,ty,tb,tw,e?.id,eR]);let tY=(0,n.useRef)(!1);(0,n.useEffect)(()=>{if(!tb||!ty)return;let t=eP.current,r=e?.id;if(!t||!r||tJ.current||tY.current||$||t.scrollTop>8||t.scrollHeight>t.clientHeight+50)return;tY.current=!0;let o=t.scrollHeight-t.scrollTop;tw(r,eR,ty).finally(()=>{tY.current=!1,requestAnimationFrame(()=>{let e=t.scrollHeight-o;Math.abs(t.scrollTop-e)>1&&t.scrollTo({top:e,behavior:"auto"})})})},[eP,ty,tb,tw,e?.id,eR,$,O.length]);let tX=(0,n.useRef)(null),tZ=(0,n.useRef)([]),tQ=(0,n.useRef)(new Map),t0=(0,n.useRef)(null),[t1,t2]=(0,n.useState)(0);(0,n.useEffect)(()=>{let e=t0.current;if(!e)return void t2(e=>0===e?e:0);let t=()=>{let t=Math.round(e.getBoundingClientRect().height);t2(e=>e===t?e:t)};t();let r=new ResizeObserver(t);return r.observe(e),()=>r.disconnect()},[]);let t6=(0,n.useMemo)(()=>({getOffsetForIndex:e=>tX.current?.getOffsetForIndex(e)?.[0]??0,sizeFor:e=>{let t=tX.current;if(!t)return 0;let r=t.measurementsCache[e];return r?.size??t.options.estimateSize?.(e)??0},totalHeight:()=>tX.current?.getTotalSize()??0,refToItemIndex:e=>tZ.current[e],itemCount:tZ.current.length}),[]),t4=ec?[ec.sessionId,ec.sessionFile??"",ec.sessionName??"",ec.userMessages,ec.assistantMessages,ec.toolCalls,ec.toolResults,ec.totalMessages,ec.tokens.input,ec.tokens.output,ec.tokens.cacheRead,ec.tokens.cacheWrite,ec.tokens.total,ec.cost??0,ec.totalActiveMs??0].join("|"):null,t5=(0,n.useRef)(ec);t5.current=ec,(0,n.useEffect)(()=>{h?.(t5.current)},[t4,h]),(0,n.useEffect)(()=>()=>{h?.(null)},[h]);let t8=en?`${en.percent??"null"}|${en.contextWindow}|${en.tokens??"null"}`:null,t3=(0,n.useRef)(en);t3.current=en,(0,n.useEffect)(()=>{m?.(t3.current)},[t8,m]),(0,n.useEffect)(()=>()=>{m?.(null)},[m]);let{isDragOver:t7,handleDragEnter:t9,handleDragOver:re,handleDragLeave:rt,handleDrop:rr}=function(e){let[t,r]=(0,n.useState)(!1),o=(0,n.useRef)(0),s=(0,n.useCallback)(e=>{e.dataTransfer.files.length&&(e.preventDefault(),o.current+=1,r(!0))},[]),i=(0,n.useCallback)(e=>{e.dataTransfer.files.length&&e.preventDefault()},[]);return{isDragOver:t,handleDragEnter:s,handleDragOver:i,handleDragLeave:(0,n.useCallback)(()=>{o.current-=1,o.current<=0&&(o.current=0,r(!1))},[]),handleDrop:(0,n.useCallback)(t=>{t.preventDefault(),o.current=0,r(!1),e(Array.from(t.dataTransfer.files),t.dataTransfer)},[e])}}((0,n.useCallback)((e,t)=>{if(_){let t=e.filter(e=>e.type.startsWith("image/"));t.length&&c?.current?.addImages(t);return}c?.current?.addFiles(e,t)},[_,c])),ro=O.filter(e=>"user"===e.role||"assistant"===e.role),rn=(0,n.useMemo)(()=>{let e=new Set,t=[];for(let o=O.length-1;o>=0&&t.length<50;o-=1){var r;let n="user"!==(r=O[o]).role?null:("string"==typeof r.content?r.content:r.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n")).trim()||null;!n||e.has(n)||(e.add(n),t.push(n))}return t},[O]),rs=(S=ro.length,(C=(0,n.useRef)([])).current.length!==S&&(C.current=Array.from({length:S},(e,t)=>C.current[t]??null)),C),ri=eC&&0===O.length&&!U.isStreaming&&!_,ra=e?.cwd??t??void 0,rl=(0,n.useMemo)(()=>(function(e,t,r){let o=new Map;for(let t of e)"toolResult"===t.role&&o.set(t.toolCallId,t);let n=-1;for(let t=e.length-1;t>=0;t--)if("user"===e[t].role){n=t;break}let s=new Map,i=0;e.forEach((e,t)=>{("user"===e.role||"assistant"===e.role)&&s.set(t,i++)});let a=[];for(let n=0;n<e.length;){let s,i=e[n],l="custom"===i.role&&"compaction"===i.customType;if(0===n&&"user"!==i.role&&!l){let r=1;for(;r<e.length&&"user"!==e[r].role;)r+=1;let s=Array.from({length:r},(e,t)=>t).filter(t=>ie(e[t])),i=s5(e,t,s,o);if(i.length>0){a.push({kind:"turn",userIdx:-1,endIdx:r,startsCompactionTurn:!1,finalAssistantIdx:-1,visibleProcessIndices:s,processBlocks:i,processSegments:s0(i),finalAnswerMessage:null,writtenFiles:void 0}),n=r;continue}}if("user"!==i.role&&!l){a.push({kind:"single",idx:n}),n+=1;continue}let d=n,c=d+1;for(;c<e.length&&"user"!==e[c].role;)c+=1;let p=function(e,t,r){for(let n=r-1;n>t;n--){var o;if("assistant"===(o=e[n]).role&&sX(o).answerBlocks.some(e=>"image"===e.type||"text"===e.type&&e.text.trim().length>0))return n}for(let o=r-1;o>t;o--)if(e[o]?.role==="assistant")return o;return -1}(e,d,c);if(-1===p){let r=Array.from({length:c-d-1},(e,t)=>d+1+t).filter(t=>ie(e[t])),s=s5(e,t,r,o);a.push({kind:"turn",userIdx:d,endIdx:c,startsCompactionTurn:l,finalAssistantIdx:p,visibleProcessIndices:r,processBlocks:s,processSegments:s0(s),finalAnswerMessage:null,writtenFiles:void 0}),n=c;continue}let u=[];for(let e=d+1;e<p;e++)u.push(e);let h=u.filter(t=>ie(e[t])),g=e[p],m=sX(g),f=m.processBlocks.length>0?it(g,m.processBlocks,{omitUsage:!0}):null,x=m.answerBlocks.length>0?it(g,m.answerBlocks):null,v=s5(e,t,h,o);if(f&&(v=v.concat(s4(g,{messageIndex:p,entryId:t[p],toolResults:o}).processBlocks)),x){let t=[];for(let r=d+1;r<=p;r++){let o=e[r];if(o?.role==="assistant")for(let e of o.content??[])t.push(e)}s=function(e,t,r){let o=new Set,n=[];for(let s of e){if("toolCall"!==s.type||!function(e){let t,r;return"write"===(t=e.toLowerCase())||t.startsWith("write_")||t.endsWith(".write")||t.endsWith("_write")||"edit"===(r=e.toLowerCase())||r.startsWith("edit_")||r.endsWith(".edit")||r.endsWith("_edit")||r.includes("str_replace")||r.includes("replace_editor")}(s.toolName))continue;let e=t?.get(s.toolCallId);if(!e||e.isError)continue;let i=function(e){if(!e)return null;let t=e.file_path??e.path;return"string"==typeof t&&t.length>0?t:null}(s.input);if(!i)continue;let a=function(e,t){let r;if(!e)return null;let o=/^[a-zA-Z]:[\\/]/.test(e)||e.startsWith("\\\\")||void 0!==t&&(/^[a-zA-Z]:[\\/]/.test(t)||t.startsWith("\\\\")),n=e=>o?e.replace(/\\/g,"/"):e,s=n(e),i=t?n(t).replace(/\/+$/,""):void 0,a=/^[a-zA-Z]:\//.test(s),l=s.startsWith("//");if(a||l)r=s;else if(s.startsWith("/")){let e=i?.match(/^([a-zA-Z]:)(?:\/|$)/)?.[1]??i?.match(/^(\/\/[^/]+\/[^/]+)(?:\/|$)/)?.[1];r=e?`${e}${s}`:s}else{if(!i)return null;r=`${i}/${s}`}return s7(r)}(i,r);a&&(o.has(a)||(o.add(a),n.push({filePath:a})))}return n}(t,o,r)}a.push({kind:"turn",userIdx:d,endIdx:c,startsCompactionTurn:l,finalAssistantIdx:p,visibleProcessIndices:h,processBlocks:v,processSegments:s0(v),finalAnswerMessage:x,writtenFiles:s}),n=c}return{toolResultsMap:o,lastUserIdx:n,visibleRefIndexByMessage:s,items:a}})(O,B,ra),[O,B,ra]),rd=ed?Y[`${ed.provider}:${ed.modelId}`]??null:null,rc=ed?X[`${ed.provider}:${ed.modelId}`]??null:null,rp=(0,n.useCallback)(()=>{ee()},[ee]),ru=(0,n.useCallback)(e=>{tc(e)},[tc]),rh=e?.relation?.kind==="subagent"?(0,o.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",gap:8,padding:"14px 16px",borderTop:"1px solid var(--border)",color:"var(--text-dim)",fontSize:12},children:[(0,o.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,o.jsx)("rect",{x:"3",y:"11",width:"18",height:"10",rx:"2"}),(0,o.jsx)("circle",{cx:"12",cy:"5",r:"2"}),(0,o.jsx)("path",{d:"M12 7v4"})]}),P("subagent.readOnlyNotice")]}):(0,o.jsx)(dA,{ref:c,onSend:eF,onBash:eD,tasksBoardEnabled:y,onAbort:eL,onSteer:_?eU:void 0,onFollowUp:_?e_:void 0,onPromptWithStreamingBehavior:_?eq:void 0,isStreaming:_,model:ed,modelNames:K,modelList:G,modelScopeWarnings:Z,modelsError:Q,onRetryModels:rp,onModelChange:eO,compactResult:el,toolPreset:et,onToolPresetChange:e||eC?tn:void 0,collaborationMode:tl,toolApprovalMode:td,onCollaborationModeChange:ru,goalState:tg,onGoalStart:tm,onGoalPause:tf,onGoalResume:tx,onGoalStop:tv,thinkingLevel:er,onThinkingLevelChange:e||eC?ts:void 0,availableThinkingLevels:rd,thinkingLevelMap:rc,retryInfo:eo,queuedMessages:eg,inputHistory:rn,onRecallQueue:eK,onMoveQueue:eX,onRecallOne:eZ,onRequeueAt:tt,onRemoveQueueItem:tr,slashCommands:eu,slashCommandsLoading:eh,onLoadSlashCommands:ti,onBuiltinCommand:to,onAudioUnlock:I,draftKey:e?.id??(t?`new:${t}`:void 0),cwd:e?.cwd??t}),rg=eb.filter(e=>"belowEditor"!==e.placement),rm=eb.filter(e=>"belowEditor"===e.placement),rf=ei?P("desktop.compacting"):function(e,t){if(e?.kind==="running_tools"){let r=e.tools.map(e=>e.name);return 0===r.length?t("desktop.runningTool"):t("desktop.runningTools",{tools:r.length<=3?r.join(", "):`${r.slice(0,2).join(", ")} (+${r.length-2})`})}return e?.kind==="waiting_model"?t("desktop.waitingForModel"):e?.kind==="running_command"?t("desktop.runningCommand"):null}(eS,P);return $?(0,o.jsx)("div",{className:"flex h-full items-center justify-center text-text-muted",children:P("desktop.loadingSession")}):H?(0,o.jsx)("div",{className:"flex h-full items-center justify-center text-red-400",children:H}):(0,o.jsxs)("div",{className:"relative flex h-full min-w-0 flex-col overflow-hidden",onDragEnter:t9,onDragOver:re,onDragLeave:rt,onDrop:rr,children:[t7&&(0,o.jsxs)("div",{className:"pointer-events-none absolute inset-0 z-50 flex animate-[drop-zone-in_0.15s_ease_both] items-center justify-center bg-[rgba(37,99,235,0.06)] backdrop-blur-[1px]",children:[(0,o.jsx)("div",{className:"pointer-events-none absolute inset-0 flex items-center justify-center",children:[0,.8,1.6].map(e=>(0,o.jsx)("div",{className:"absolute h-[720px] w-[720px] rounded-full border-[1.5px] border-solid border-[rgba(37,99,235,0.5)] animate-[drop-ripple_2.4s_ease-out_infinite_backwards]",style:{transformOrigin:"center",animationDelay:`${e}s`}},e))}),(0,o.jsxs)("svg",{width:"280",height:"280",viewBox:"0 0 140 140",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:"drop-shadow-[0_6px_18px_rgba(37,99,235,0.18)]",children:[(0,o.jsx)("rect",{x:"28",y:"44",width:"84",height:"60",rx:"8",fill:"rgba(37,99,235,0.08)",stroke:"rgba(37,99,235,0.50)",strokeWidth:"1.8"}),(0,o.jsx)("path",{d:"M36 100 L54 72 L68 88 L80 74 L104 100Z",fill:"rgba(37,99,235,0.16)",stroke:"rgba(37,99,235,0.40)",strokeWidth:"1.4",strokeLinejoin:"round"}),(0,o.jsx)("circle",{cx:"96",cy:"58",r:"8",fill:"rgba(37,99,235,0.22)",stroke:"rgba(37,99,235,0.55)",strokeWidth:"1.6"}),(0,o.jsxs)("g",{stroke:"rgba(37,99,235,0.45)",strokeWidth:"1.4",strokeLinecap:"round",children:[(0,o.jsx)("line",{x1:"96",y1:"46",x2:"96",y2:"43"}),(0,o.jsx)("line",{x1:"96",y1:"70",x2:"96",y2:"73"}),(0,o.jsx)("line",{x1:"84",y1:"58",x2:"81",y2:"58"}),(0,o.jsx)("line",{x1:"108",y1:"58",x2:"111",y2:"58"}),(0,o.jsx)("line",{x1:"87.5",y1:"49.5",x2:"85.4",y2:"47.4"}),(0,o.jsx)("line",{x1:"104.5",y1:"66.5",x2:"106.6",y2:"68.6"}),(0,o.jsx)("line",{x1:"104.5",y1:"49.5",x2:"106.6",y2:"47.4"}),(0,o.jsx)("line",{x1:"87.5",y1:"66.5",x2:"85.4",y2:"68.6"})]})]})]}),ev&&(0,o.jsx)(cg,{request:ev,onRespond:ew}),ek&&(0,o.jsx)(cm,{request:ek,onInput:ej}),!eC&&em.length>0&&!tj&&(0,o.jsx)(dF,{items:em,sessionId:e?.id,onResolve:eG,onExport:eJ,onStageImport:eY,onDismiss:()=>tS(!0),mode:ef?"import":"recovery"}),tp.length>0&&(0,o.jsx)(le,{request:tp[0]??null,queuedCount:Math.max(0,tp.length-1),busy:!1,onResolve:(e,t)=>{let r=tp[0];r&&th(r.id,e,t)}}),ri?(0,o.jsx)("div",{className:"flex flex-1 flex-col items-center justify-center overflow-y-auto",children:(0,o.jsxs)("div",{className:"w-full max-w-[820px]",children:[(0,o.jsx)("div",{style:{display:"flex",justifyContent:"center",marginBottom:28},children:(0,o.jsxs)("svg",{fill:"currentColor",fillRule:"evenodd",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",style:{width:64,height:64,color:"var(--accent)",opacity:.85},"aria-label":"Pi",children:[(0,o.jsx)("title",{children:"Pi"}),(0,o.jsx)("path",{clipRule:"evenodd",d:"M1 1h16.5v11H12v5.5H6.5V23H1V1zm5.5 5.5V12H12V6.5H6.5z"}),(0,o.jsx)("path",{d:"M17.5 12H23v11h-5.5V12z"})]})}),M&&(0,o.jsxs)("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",gap:10,marginBottom:18,marginTop:-14},children:[(0,o.jsxs)("span",{style:{fontSize:11,color:"var(--text-muted)",fontFamily:"var(--font-mono)"},children:["web ",(0,o.jsxs)("span",{style:{color:"var(--text)"},children:["v","0.17.8"]})]}),(0,o.jsxs)("span",{style:{fontSize:11,color:"var(--text-muted)",fontFamily:"var(--font-mono)"},children:["pi ",(0,o.jsxs)("span",{style:{color:"var(--text)"},children:["v","0.85.1"]})]})]}),(0,o.jsx)("div",{style:{padding:"0 34px 6px 7px",paddingRight:M?16:34},children:(0,o.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12},children:[(0,o.jsx)("div",{ref:x,style:{display:"flex",alignItems:"center",minWidth:0,flex:1,minHeight:48}}),(0,o.jsxs)("div",{style:{display:M?"none":"flex",flexDirection:"column",alignItems:"flex-end",gap:2,flexShrink:0},children:[(0,o.jsxs)("span",{style:{fontSize:11,color:"var(--text-muted)",fontFamily:"var(--font-mono)"},children:["web ",(0,o.jsxs)("span",{style:{color:"var(--text)"},children:["v","0.17.8"]})]}),(0,o.jsxs)("span",{style:{fontSize:11,color:"var(--text-muted)",fontFamily:"var(--font-mono)"},children:["pi ",(0,o.jsxs)("span",{style:{color:"var(--text)"},children:["v","0.85.1"]})]})]})]})}),(0,o.jsx)("div",{style:{padding:"0 16px",paddingRight:M?16:34},children:(0,o.jsx)(ch,{notices:ex,align:"right"})}),"goal"===tl&&(0,o.jsx)(a7,{goalState:tg,onPause:tf,onResume:tx,onStop:tv,onEdit:tk}),rh,(0,o.jsx)("div",{style:{padding:"0 16px 6px",paddingRight:M?16:34,marginTop:-15},children:(0,o.jsx)(dG,{onViewFullHistory:v,cwd:ra,systemPrompt:k,sessionStats:ec,contextUsage:en,hasSession:!!e,showChat:!0,showSoundLabel:!0,soundEnabled:T,onSoundToggle:R,onCompact:e?eB:void 0,onAbortCompaction:eV,isCompacting:ei,compactError:ea,isDeepSeekOfficial:tz,deepseekBalance:tC,lastTurnUsage:tM})})]})}):(0,o.jsxs)(o.Fragment,{children:[(0,o.jsxs)("div",{className:"relative flex flex-1 overflow-hidden z-0",children:[(0,o.jsx)("div",{style:{position:"absolute",top:12,left:0,right:18*!M,zIndex:40,padding:"0 16px",pointerEvents:"none"},children:(0,o.jsx)("div",{style:{maxWidth:820,margin:"0 auto"},children:(0,o.jsx)(ch,{notices:ex,floating:!0,align:"right"})})}),(0,o.jsxs)("div",{className:"relative flex-1 min-h-0 min-w-0",children:[(0,o.jsx)("div",{ref:eP,className:"h-full min-w-0 overflow-x-hidden overflow-y-auto pt-4 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden",children:(0,o.jsx)("div",{style:{minWidth:0,padding:"0 16px"},children:(0,o.jsxs)("div",{style:{width:"100%",minWidth:0,maxWidth:820,margin:"0 auto"},children:[(0,o.jsxs)("div",{ref:t0,children:[(0,o.jsx)(cp,{statuses:ey}),(0,o.jsx)(cu,{widgets:rg})]}),(()=>{let{toolResultsMap:t,lastUserIdx:r,visibleRefIndexByMessage:n,items:s}=rl,i=tQ.current,a=(s,a={})=>{let l=a.messageOverride??O[s];if(!l||"toolResult"===l.role)return null;let d="user"===l.role&&s>0&&"assistant"===O[s-1].role?B[s-1]:void 0,c="user"===l.role||"assistant"===l.role,p=n.get(s),u=a.keyPrefix??"message",h=!1;if("assistant"===l.role){h=!0;for(let e=s+1;e<O.length;e++){let t=O[e].role;if("user"===t)break;if("assistant"===t){h=!1;break}}h&&U.isStreaming&&s===O.length-1&&(h=!1)}void 0!==a.showTimestamp&&(h=a.showTimestamp);let g=(0,o.jsx)(aF,{message:l,toolResults:t,modelNames:K,cwd:ra,onOpenFile:f,entryId:B[s],onFork:_||eC||0===s&&"user"===l.role?void 0:e$,forking:es===B[s],onNavigate:_?void 0:eH,prevAssistantEntryId:_?void 0:d,onEditContent:F,onQuoteReply:D,onOpenSession:b,onCreateTask:L,showTimestamp:h,prevTimestamp:s>0?O[s-1].timestamp:void 0,sessionId:e?.id??eI.current??void 0,writtenFiles:a.writtenFiles},`${u}-view-${s}`);return c&&!1!==a.attachRef&&void 0!==p?(0,o.jsx)("div",{ref:((e,t)=>{let o=i.get(t);if(!o){let e={isLastUser:!1};o={state:e,callback:r=>{rs.current[t]=r,e.isLastUser&&(eE.current=r,r&&eA.current&&(eA.current=!1,eW.current=!0,eN()))}},i.set(t,o)}return o.state.isLastUser=e===r,o.callback})(s,p),children:g},`${u}-${s}`):g},l=[],d=[],c=[],p=(e,t,r)=>{null!==e&&(l.push(e),d.push(t),c.push(r))},u=(e,t)=>B[e]||`${t}-${e}`,h=e=>`live-answer-u${e}`,g=e=>`answer-${u(e,"user")}`,m=e=>`subagent-${e}`,x=e=>sQ(e.result?.details)?e.result.details.sessionId:"",v=(e,t)=>`live-process-u${e}-seg${t}`,k=(e,t,r)=>`process-${u(e,"user")}-${r||`seg${t}`}`;for(let i of s){if("single"===i.kind){if(O[i.idx]?.role==="toolResult")continue;p(a(i.idx),n.get(i.idx),u(i.idx,"single"));continue}let{userIdx:s,endIdx:l,startsCompactionTurn:d,finalAssistantIdx:c}=i;if((_||U.isStreaming)&&l===O.length&&(s===r||d)){s>=0&&p(a(s),n.get(s),u(s,"user"));let r=U.streamingMessage?.role==="assistant",i=[],d=!r&&c>=0?c:l;for(let e=s+1;e<d;e++)ie(O[e])&&i.push(e);let g=s5(O,B,i,t),k=null;if(!r&&c>=0){let e=O[c],r=sX(e,{isStreaming:!0}),o=s4(e,{messageIndex:c,entryId:B[c],toolResults:t,isStreaming:!0});g=g.concat(o.processBlocks),r.answerBlocks.length>0&&(k=it(e,r.answerBlocks,{omitUsage:!0}))}if(r){let e=U.streamingMessage,r=sX(e,{isStreaming:!0}),o=s4(e,{messageIndex:O.length,toolResults:t,isStreaming:!0});g=g.concat(o.processBlocks),r.answerBlocks.length>0&&(k=it(e,r.answerBlocks,{omitUsage:!0}))}if(g.length>0){let t=i.map(e=>n.get(e)).find(e=>"number"==typeof e);s0(g).forEach((r,n)=>{"subagent"===r.kind&&r.subagent?p((0,o.jsx)(lY,{run:r.subagent,onOpenSubagent:w,sessionRun:j?.get(x(r.subagent))},m(r.subagent.toolCallId)),t,m(r.subagent.toolCallId)):p((0,o.jsx)("div",{ref:void 0===t?void 0:e=>{rs.current[t]=e},children:(0,o.jsx)(lK,{blocks:r.blocks,isStreaming:_||U.isStreaming,cwd:ra,onOpenFile:f,sessionId:e?.id??eI.current??void 0,tokenRate:ep})},v(s,n)),t,v(s,n))})}k&&p((0,o.jsx)(aF,{message:k,isStreaming:!0,modelNames:K,cwd:ra,onOpenFile:f,onQuoteReply:D,onOpenSession:b},`live-answer-${s}`),c>=0?n.get(c):void 0,h(s));continue}if(-1===c&&0===i.processBlocks.length){if(s>=0)for(let e=s;e<l;e++)p(a(e),n.get(e),u(e,"raw"));continue}s>=0&&p(a(s),n.get(s),u(s,"user"));let{finalAnswerMessage:y,writtenFiles:S,visibleProcessIndices:C}=i;if(i.processBlocks.length>0){let t=C.map(e=>n.get(e)).find(e=>"number"==typeof e)??(y?void 0:n.get(c));i.processSegments.forEach((r,n)=>{"subagent"===r.kind&&r.subagent?p((0,o.jsx)(lY,{run:r.subagent,onOpenSubagent:w,sessionRun:j?.get(x(r.subagent))},m(r.subagent.toolCallId)),t,m(r.subagent.toolCallId)):p((0,o.jsx)("div",{ref:void 0===t?void 0:e=>{rs.current[t]=e},children:(0,o.jsx)(lK,{blocks:r.blocks,isStreaming:!1,defaultExpanded:!1,onAutoExpanded:void 0,cwd:ra,onOpenFile:f,sessionId:e?.id??eI.current??void 0})},`process-group-${s}-${n}`),t,k(s,n,r.blocks[0]?.id??""))})}if(y&&p(a(c,{messageOverride:y,writtenFiles:S}),n.get(c),g(s)),c>=0)for(let e=c+1;e<l;e++)p(a(e),n.get(e),u(e,"tail"))}let y=[],S=d.map((e,t)=>({startRef:e,itemIdx:t})).filter(e=>void 0!==e.startRef);return S.forEach((e,t)=>{let r=S[t+1]?.startRef??ro.length;for(let t=e.startRef;t<r;t++)y[t]=e.itemIdx}),tZ.current=y,(0,o.jsx)(dY,{scrollElementRef:eP,items:l,itemKeys:c,virtualizerRef:tX,headerHeight:t1})})(),rf&&(ei||_&&!U.streamingMessage)&&(0,o.jsx)("div",{className:"py-2 text-[13px] text-text-muted",children:(0,o.jsxs)("span",{className:"animate-[pulse_1.5s_infinite]",children:[rf,eS?.kind==="waiting_model"&&(0,o.jsx)("span",{style:{display:"inline-block",width:12,height:12,marginLeft:6,verticalAlign:"-2px",border:"1.5px solid var(--text-muted)",borderTopColor:"transparent",borderRadius:"50%",animation:"spin 0.6s linear infinite"}})]})}),V&&(0,o.jsx)(aF,{message:{role:"bashExecution",command:V.command,output:"",excludeFromContext:V.excludeFromContext},sessionId:e?.id??eI.current??void 0}),q&&!V&&(0,o.jsx)("div",{className:"py-2 text-[13px] text-text-muted",children:(0,o.jsx)("span",{className:"animate-[pulse_1.5s_infinite]",children:P("desktop.runningShellCommand")})}),(0,o.jsx)("div",{style:{height:96}}),(0,o.jsx)("div",{ref:eM}),(0,o.jsx)(a2,{open:tE,planText:tW,busy:_,onExecute:tD,onFeedback:t$,onExit:tH,onClose:()=>tA(!1)})]})})}),tO&&(0,o.jsx)("div",{"aria-hidden":"true",className:"pointer-events-none absolute inset-x-0 top-0 z-10 h-8 bg-gradient-to-b from-[var(--bg)] to-transparent"}),tU&&(0,o.jsx)("div",{"aria-hidden":"true",className:"pointer-events-none absolute inset-x-0 bottom-0 z-10 h-8 bg-gradient-to-t from-[var(--bg)] to-transparent"}),tq&&(0,o.jsxs)("button",{type:"button",onClick:()=>tG(),title:P("desktop.scrollToBottom"),"aria-label":P("desktop.scrollToBottom"),style:{position:"absolute",bottom:14,right:18,zIndex:20,display:"flex",alignItems:"center",gap:6,padding:"5px 10px",border:"1px solid var(--border)",borderRadius:999,background:"color-mix(in srgb, var(--bg-panel) 92%, transparent)",color:"var(--text-muted)",fontSize:11,fontWeight:600,cursor:"pointer",boxShadow:"0 4px 14px rgba(0,0,0,0.14)",backdropFilter:"blur(4px)",transition:"color 0.12s, border-color 0.12s, background 0.12s"},onMouseEnter:e=>{e.currentTarget.style.color="var(--accent)",e.currentTarget.style.borderColor="var(--accent)"},onMouseLeave:e=>{e.currentTarget.style.color="var(--text-muted)",e.currentTarget.style.borderColor="var(--border)"},children:[(0,o.jsx)(aw.Z,{size:12,weight:"bold","aria-hidden":"true"}),P("desktop.scrollToBottom")]})]}),M?null:(0,o.jsx)(dQ,{messages:O,streamingMessage:U.streamingMessage,scrollContainer:eP,messageRefs:rs,virtualizer:t6})]}),(0,o.jsxs)("div",{className:"relative z-10",children:[(0,o.jsx)("div",{style:{padding:"0 16px",paddingRight:M?16:34},children:(0,o.jsx)("div",{style:{maxWidth:820,margin:"0 auto"},children:(0,o.jsx)(cu,{widgets:rm})})}),rh,(0,o.jsx)("div",{className:`session-info-bar-wrap${M?" is-mobile":""}`,children:(0,o.jsx)("div",{className:"session-info-bar-inner",children:(0,o.jsx)(dG,{onViewFullHistory:v,cwd:ra,systemPrompt:k,sessionStats:ec,contextUsage:en,hasSession:!!e,showChat:!0,soundEnabled:T,onSoundToggle:R,onCompact:e?eB:void 0,onAbortCompaction:eV,isCompacting:ei,compactError:ea,branchTree:eT,branchActiveLeafId:eR,onBranchLeafChange:ez,isDeepSeekOfficial:tz,deepseekBalance:tC,lastTurnUsage:tM})})})]})]})]})}function cp({statuses:e}){return 0===e.length?null:(0,o.jsx)("div",{style:{display:"flex",flexWrap:"wrap",gap:6,marginBottom:10},children:e.map(e=>(0,o.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6,maxWidth:"100%",padding:"4px 8px",border:"1px solid color-mix(in srgb, var(--accent) 24%, var(--border))",borderRadius:6,background:"color-mix(in srgb, var(--accent) 7%, var(--bg))",color:"var(--text-muted)",fontSize:12},children:[(0,o.jsx)("span",{style:{color:"var(--accent)",fontFamily:"var(--font-mono)",fontSize:11},children:e.key}),(0,o.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.text})]},e.key))})}function cu({widgets:e}){return 0===e.length?null:(0,o.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:8,marginBottom:10},children:e.map(e=>(0,o.jsxs)("div",{style:{border:"1px solid var(--border)",borderRadius:7,background:"var(--bg-panel)",overflow:"hidden"},children:[(0,o.jsx)("div",{style:{padding:"5px 9px",borderBottom:"1px solid var(--border)",color:"var(--text-dim)",fontSize:11,fontFamily:"var(--font-mono)"},children:e.key}),(0,o.jsx)("pre",{style:{margin:0,padding:"8px 9px",color:"var(--text-muted)",fontSize:12,lineHeight:1.5,whiteSpace:"pre-wrap",wordBreak:"break-word",fontFamily:"var(--font-mono)"},children:e.lines.join("\n")})]},e.key))})}function ch({notices:e,floating:t=!1,align:r="left"}){return 0===e.length?null:(0,o.jsx)("div",{style:{display:"flex",flexDirection:"column",alignItems:"right"===r?"flex-end":"stretch",marginBottom:10*!t},children:e.map((r,n)=>{let s="error"===r.type?"var(--status-error)":"warning"===r.type?"var(--status-warning)":"success"===r.type?"#10b981":"var(--accent)";return(0,o.jsxs)("div",{className:"notice-shelf-item",style:{display:"flex",alignItems:"center",gap:10,minHeight:44,maxHeight:180,marginBottom:6*(n!==e.length-1),overflowY:"auto",overflowX:"hidden",borderRadius:14,border:"1px solid color-mix(in srgb, var(--border) 70%, transparent)",background:"var(--bg)",color:"var(--text-muted)",width:"fit-content",maxWidth:"min(100%, 620px)",boxShadow:t?"0 1px 2px rgba(15,23,42,0.05), 0 10px 28px -14px rgba(15,23,42,0.24)":"0 1px 2px rgba(15,23,42,0.04), 0 8px 24px -12px rgba(15,23,42,0.10)",fontSize:13,lineHeight:1.45,transformOrigin:"top center",animation:r.exiting?"notice-shelf-out 0.18s ease-in forwards":"notice-shelf-in 0.18s ease-out both",padding:"0 12px"},children:[(0,o.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:s,flexShrink:0}}),(0,o.jsx)("span",{style:{padding:"10px 0",minWidth:0,maxWidth:"100%",overflowWrap:"anywhere",whiteSpace:"pre-wrap"},children:r.message})]},r.id)})})}function cg({request:e,onRespond:t}){let{t:r}=(0,J.s)(),[s,i]=(0,n.useState)("editor"===e.method?e.prefill??"":"");(0,n.useEffect)(()=>{i("editor"===e.method?e.prefill??"":"")},[e]);let a=()=>{"confirm"===e.method?t(e,{confirmed:!0}):t(e,{value:s})};return(0,o.jsx)("div",{style:{position:"absolute",inset:0,zIndex:90,display:"flex",alignItems:"center",justifyContent:"center",padding:20,background:"rgba(0,0,0,0.18)"},children:(0,o.jsxs)("div",{role:"dialog","aria-modal":"true",style:{width:"min(560px, 100%)",border:"1px solid var(--border)",borderRadius:8,background:"var(--bg)",boxShadow:"0 20px 60px rgba(0,0,0,0.28)",overflow:"hidden"},children:[(0,o.jsxs)("div",{style:{padding:"12px 14px",borderBottom:"1px solid var(--border)"},children:[(0,o.jsx)("div",{style:{color:"var(--text)",fontSize:14,fontWeight:650},children:e.title}),(0,o.jsx)("div",{style:{marginTop:3,color:"var(--text-dim)",fontSize:11,fontFamily:"var(--font-mono)"},children:r("desktop.extensionRequest")})]}),(0,o.jsxs)("div",{style:{padding:14},children:["confirm"===e.method&&(0,o.jsx)("div",{style:{color:"var(--text-muted)",fontSize:13,lineHeight:1.6,whiteSpace:"pre-wrap"},children:e.message}),"select"===e.method&&(0,o.jsx)("div",{style:{display:"grid",gap:8},children:e.options.map(r=>(0,o.jsx)("button",{onClick:()=>t(e,{value:r}),style:{width:"100%",padding:"9px 10px",borderRadius:7,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text)",cursor:"pointer",textAlign:"left",fontSize:13},children:r},r))}),"input"===e.method&&(0,o.jsx)("input",{autoFocus:!0,value:s,placeholder:e.placeholder,onChange:e=>i(e.target.value),onKeyDown:r=>{"Enter"===r.key&&a(),"Escape"===r.key&&t(e,{cancelled:!0})},style:{width:"100%",padding:"9px 10px",borderRadius:7,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text)",outline:"none",fontSize:13}}),"editor"===e.method&&(0,o.jsx)("textarea",{autoFocus:!0,value:s,onChange:e=>i(e.target.value),onKeyDown:r=>{"Escape"===r.key&&t(e,{cancelled:!0}),(r.metaKey||r.ctrlKey)&&"Enter"===r.key&&a()},style:{width:"100%",minHeight:220,padding:10,borderRadius:7,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text)",outline:"none",resize:"vertical",fontSize:13,lineHeight:1.55,fontFamily:"var(--font-mono)"}})]}),(0,o.jsxs)("div",{style:{display:"flex",justifyContent:"flex-end",gap:8,padding:"10px 14px",borderTop:"1px solid var(--border)",background:"var(--bg-panel)"},children:[(0,o.jsx)("button",{onClick:()=>t(e,{cancelled:!0}),style:{padding:"6px 10px",borderRadius:6,border:"1px solid var(--border)",background:"var(--bg)",color:"var(--text-muted)",cursor:"pointer"},children:r("desktop.cancel")}),"confirm"===e.method?(0,o.jsx)("button",{onClick:a,style:{padding:"6px 10px",borderRadius:6,border:"1px solid var(--accent)",background:"var(--accent)",color:"#fff",cursor:"pointer"},children:r("desktop.confirm")}):"select"!==e.method?(0,o.jsx)("button",{onClick:a,style:{padding:"6px 10px",borderRadius:6,border:"1px solid var(--accent)",background:"var(--accent)",color:"#fff",cursor:"pointer"},children:r("desktop.submit")}):null]})]})})}function cm({request:e,onInput:t}){let{t:r}=(0,J.s)(),s=(0,n.useRef)(null),i=function(e){let t=/^[┌├└╭╰][─┬┴┼]+[┐┤┘╮╯]$/,r=[];for(let o of e){let e=sq(o).trimEnd();if(t.test(e))continue;let n=o,s=sG(n);("│"===s||"┃"===s)&&" "===sG(n=sK(n,0))&&(n=sK(n,0));let i=function(e){let t=sV(e);for(let e=t.length-1;e>=0;e--)if(""!==t[e].char.trim())return e;return -1}(n),a=i>=0?sV(n)[i]?.char:void 0;("│"===a||"┃"===a)&&(n=sK(n,i)),r.push(function(e){let t=e;for(;;){let e=sV(t),r=e[e.length-1];if(!r||""!==r.char.trim())return t;t=t.slice(0,r.start)+t.slice(r.end)}}(n))}for(;r.length>0&&""===sq(r[0]).trim();)r.shift();for(;r.length>0&&""===sq(r[r.length-1]).trim();)r.pop();return r.length?r:e}(e.lines);return(0,n.useEffect)(()=>{s.current?.focus()},[e.id]),(0,o.jsx)("div",{style:{position:"absolute",inset:0,zIndex:95,display:"flex",alignItems:"center",justifyContent:"center",padding:20,background:"rgba(0,0,0,0.18)"},children:(0,o.jsxs)("div",{ref:s,tabIndex:0,role:"dialog","aria-modal":"true",onKeyDown:r=>{let o=function(e){if(e.ctrlKey&&!e.metaKey&&!e.altKey&&1===e.key.length){let t=e.key.toLowerCase();if(t>="a"&&t<="z")return String.fromCharCode(t.charCodeAt(0)-96)}switch(e.key){case"ArrowUp":return"\x1b[A";case"ArrowDown":return"\x1b[B";case"ArrowRight":return"\x1b[C";case"ArrowLeft":return"\x1b[D";case"Enter":return"\r";case"Escape":return"\x1b";case"Backspace":return"";case"Tab":return" ";case" ":return" ";default:if(!e.ctrlKey&&!e.metaKey&&!e.altKey&&1===e.key.length)return e.key;return null}}(r);o&&(r.preventDefault(),r.stopPropagation(),t(e,o))},style:{width:"min(920px, 100%)",maxHeight:"min(760px, calc(100vh - 40px))",border:"1px solid var(--border)",borderRadius:8,background:"var(--bg)",boxShadow:"0 20px 60px rgba(0,0,0,0.28)",overflow:"hidden",outline:"none"},children:[(0,o.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,padding:"10px 12px",borderBottom:"1px solid var(--border)"},children:[(0,o.jsx)("div",{style:{color:"var(--text)",fontSize:13,fontWeight:650},children:r("desktop.extensionPanel")}),(0,o.jsx)("button",{onClick:()=>t(e,"\x03"),style:{padding:"5px 9px",borderRadius:6,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",cursor:"pointer",fontSize:12},children:r("desktop.close")})]}),(0,o.jsx)("pre",{style:{margin:0,padding:14,maxHeight:"calc(min(760px, 100vh - 40px) - 48px)",overflow:"auto",background:"var(--bg-panel)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:13,lineHeight:1.45,whiteSpace:"pre"},children:(i.length?i:[""]).map((e,t,r)=>{var s;return(0,o.jsxs)(n.Fragment,{children:[(s=`line-${t}`,(function(e){let t,r=[],o={},n=0;for(sB.lastIndex=0;null!==(t=sB.exec(e));)t.index>n&&r.push({text:e.slice(n,t.index),style:o}),o=function(e,t){let r={...e};for(let e=0;e<t.length;e++){let o=t[e];if(0===o)for(let e of Object.keys(r))delete r[e];else if(1===o)r.fontWeight=700;else if(2===o)r.opacity=.65;else if(3===o)r.fontStyle="italic";else if(4===o)r.textDecoration="underline";else if(22===o)delete r.fontWeight,delete r.opacity;else if(23===o)delete r.fontStyle;else if(24===o)delete r.textDecoration;else if(39===o)delete r.color;else if(49===o)delete r.backgroundColor;else if(o>=30&&o<=37)r.color=sU[o-30];else if(o>=90&&o<=97)r.color=s_[o-90];else if(o>=40&&o<=47)r.backgroundColor=sU[o-40];else if(o>=100&&o<=107)r.backgroundColor=s_[o-100];else if((38===o||48===o)&&2===t[e+1]){let[n,s,i]=[t[e+2],t[e+3],t[e+4]];[n,s,i].every(e=>"number"==typeof e&&Number.isFinite(e))&&(38===o?r.color=`rgb(${n}, ${s}, ${i})`:r.backgroundColor=`rgb(${n}, ${s}, ${i})`),e+=4}else if((38===o||48===o)&&5===t[e+1]){let n=function(e){if(e>=0&&e<8)return sU[e];if(e>=8&&e<16)return s_[e-8];if(e>=16&&e<=231){let t=e-16,r=Math.floor(t/36),o=Math.floor(t%36/6),n=e=>0===e?0:55+40*e;return`rgb(${n(r)}, ${n(o)}, ${n(t%6)})`}if(e>=232&&e<=255){let t=8+(e-232)*10;return`rgb(${t}, ${t}, ${t})`}}(t[e+2]);n&&(38===o?r.color=n:r.backgroundColor=n),e+=2}}return r}(o,t[1]?t[1].split(";").map(e=>Number(e||"0")):[0]),n=t.index+t[0].length;return n<e.length&&r.push({text:e.slice(n),style:o}),r})(e).map((e,t)=>Object.keys(e.style).length>0?(0,o.jsx)("span",{style:e.style,children:e.text},`${s}-${t}`):e.text)),t<r.length-1?"\n":null]},t)})})]})})}var cf=r(93549);let cx={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",bmp:"image/bmp",ico:"image/x-icon",avif:"image/avif"},cv={mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",oga:"audio/ogg",opus:"audio/ogg",m4a:"audio/mp4",aac:"audio/aac",flac:"audio/flac",weba:"audio/webm"};function ck(e){return(e.replace(/\\/g,"/").split("/").pop()??"").toLowerCase().split(".").pop()??""}function cy(e){let t=e.nodeType===Node.ELEMENT_NODE?e:e.parentElement;return t?.closest(".file-source-line[data-line-number]")??null}function cb(e,t){if(!t||t.isCollapsed||0===t.rangeCount)return null;let r=t.getRangeAt(0);if(!e.contains(r.startContainer)||!e.contains(r.endContainer))return null;let o=Number(cy(r.startContainer)?.dataset.lineNumber),n=Number(cy(r.endContainer)?.dataset.lineNumber);return Number.isInteger(o)&&Number.isInteger(n)?o<=n?{startLine:o,endLine:n}:{startLine:n,endLine:o}:null}function cw(e,t,r,o={}){let n=nf(e),s=new URLSearchParams({type:t});for(let[e,t]of(r&&s.set("sessionId",r),Object.entries(o)))void 0!==t&&s.set(e,String(t));return`/api/files/${n}?${s.toString()}`}function cj({filePath:e,sourceSessionId:t}){let{t:r}=(0,J.s)();return(0,o.jsx)("a",{href:cw(e,"download",t),download:nx(e),title:r("desktop.downloadFile"),style:{display:"flex",alignItems:"center",justifyContent:"center",height:20,padding:"0 5px",background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:4,color:"var(--text-muted)",cursor:"pointer",flexShrink:0,textDecoration:"none"},children:(0,o.jsx)(I.z,{size:11,"aria-hidden":"true"})})}let cS={fontFamily:"var(--font-mono)",fontSize:13,lineHeight:1.6,tabSize:2},cC={fontFamily:"var(--font-mono)",fontSize:13,lineHeight:1.6,padding:"12px 0 12px 16px",color:"var(--text-dim)",textAlign:"right",userSelect:"none"};async function cT(e,t){let r=await fetch(`/api/files/${nf(e)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:t})});if(!r.ok)throw Error((await r.json().catch(()=>({}))).error??`HTTP ${r.status}`);let o=await r.json();return"number"==typeof o.size?o.size:0}let cR={delete:"3px solid var(--git-status-deleted)",add:"3px solid var(--git-status-added)",edit:"3px solid var(--git-status-modified)"},cz="var(--git-status-deleted-bg)",cI="var(--git-status-added-bg)",cM="var(--git-status-added)";function cP(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KB`:`${(e/1048576).toFixed(1)} MB`}function cE({oldContent:e,newContent:t}){let{t:r}=(0,J.s)(),n=function(e,t){let r=e.length,o=t.length,n=r+o,s=Array(2*n+1).fill(0),i=[];for(let a=0;a<=n;a++){i.push([...s]);for(let l=-a;l<=a;l+=2){let d,c=(d=l===-a||l!==a&&s[l-1+n]<s[l+1+n]?s[l+1+n]:s[l-1+n]+1)-l;for(;d<r&&c<o&&e[d]===t[c];)d++,c++;if(s[l+n]=d,d>=r&&c>=o){let s=[],l=r,d=o;for(let r=a;r>0;r--){let o,a=i[r-1],c=l-d;o=c===-r||c!==r&&a[c-1+n]<a[c+1+n]?c+1:c-1;let p=a[o+n],u=p-o;for(;l>p&&d>u;)l--,d--,s.unshift({type:"unchanged",text:e[l]});r>0&&(l>p?(l--,s.unshift({type:"removed",text:e[l]})):(d--,s.unshift({type:"added",text:t[d]})))}for(;l>0&&d>0;)l--,d--,s.unshift({type:"unchanged",text:e[l]});return s}}}return[...e.map(e=>({type:"removed",text:e})),...t.map(e=>({type:"added",text:e}))]}(e.split("\n"),t.split("\n"));if(!n.some(e=>"unchanged"!==e.type))return(0,o.jsx)("div",{style:{padding:"12px 16px",fontSize:12,color:"var(--text-dim)",fontFamily:"var(--font-mono)"},children:r("desktop.noChanges")});let s=new Set(n.flatMap((e,t)=>"unchanged"!==e.type?[t]:[])),i=new Set;for(let e of s)for(let t=Math.max(0,e-3);t<=Math.min(n.length-1,e+3);t++)i.add(t);let a=[],l=0;for(;l<n.length;)if(i.has(l)){let e=[];for(;l<n.length&&i.has(l);)e.push(n[l]),l++;a.push({hidden:!1,lines:e})}else{let e=0;for(;l<n.length&&!i.has(l);)e++,l++;a.push({hidden:!0,count:e})}let d=[],c=1;for(let e of n)"removed"===e.type?d.push(0):d.push(c++);let p=0;return(0,o.jsx)("div",{style:{fontFamily:"var(--font-mono)",fontSize:13,lineHeight:1.6,minWidth:"max-content"},children:a.map((e,t)=>{if(e.hidden){let n=(0,o.jsx)("div",{style:{padding:"2px 16px",color:"var(--text-dim)",background:"var(--bg-panel)",fontSize:11,borderTop:"1px solid var(--border)",borderBottom:"1px solid var(--border)"},children:r("desktop.unchangedLines",{count:e.count})},t);return p+=e.count,n}let n=[],s=[],i=[],a=()=>{if(s.length||i.length){let e=s.length&&i.length?"edit":s.length?"delete":"add";for(let t of s)n.push({key:t.key,kind:"removed",text:t.text,lineNo:null,block:e});for(let t of i)n.push({key:t.key,kind:"added",text:t.text,lineNo:t.lineNo,block:e});s=[],i=[]}};e.lines.forEach((e,r)=>{"unchanged"===e.type?(a(),n.push({key:`${t}:${r}`,kind:"context",text:e.text,lineNo:d[p+r],block:null})):"removed"===e.type?s.push({key:`${t}:${r}`,text:e.text}):i.push({key:`${t}:${r}`,text:e.text,lineNo:d[p+r]})}),a();let l=n.map(e=>{let t="removed"===e.kind?cz:"added"===e.kind?cI:"transparent",r=e.block?cR[e.block]:"3px solid transparent",n="added"===e.kind?cM:"var(--text-dim)";return(0,o.jsxs)("div",{style:{display:"flex",background:t,borderLeft:r},children:[(0,o.jsx)("span",{style:{minWidth:44,padding:"0 8px 0 16px",textAlign:"right",color:n,userSelect:"none",fontSize:11,lineHeight:1.6,flexShrink:0},children:e.lineNo??""}),(0,o.jsx)("span",{style:{flex:1,minWidth:0,padding:"0 8px 0 0",whiteSpace:"pre",color:"var(--text)"},children:e.text||"\xa0"})]},e.key)});return p+=e.lines.length,(0,o.jsx)("div",{children:l},t)})})}function cA({patch:e}){let t=af(e);if(!t)return null;let r=[],n=[],s=[],i=()=>{if(n.length||s.length){let e=n.length&&s.length?"edit":n.length?"delete":"add";for(let t of n)r.push({key:t.key,kind:"removed",text:t.text,lineNo:null,block:e});for(let t of s)r.push({key:t.key,kind:"added",text:t.text,lineNo:t.lineNo,block:e});n=[],s=[]}};return t.forEach((e,t)=>{e.rows.forEach((e,o)=>{if("hunk"===e.type){i(),r.push({key:`${t}:${o}:h`,kind:"hunk",text:e.text,lineNo:null,block:null});return}let{left:a,right:l}=e;if("context"===a.type&&"context"===l.type){i(),r.push({key:`${t}:${o}:c`,kind:"context",text:a.text,lineNo:l.lineNo,block:null});return}"removed"===a.type&&n.push({key:`${t}:${o}:l`,text:a.text}),"added"===l.type&&s.push({key:`${t}:${o}:r`,text:l.text,lineNo:l.lineNo})})}),i(),(0,o.jsx)("div",{style:{fontFamily:"var(--font-mono)",fontSize:12,lineHeight:1.55,minWidth:"max-content"},children:r.map(e=>{if("hunk"===e.kind)return(0,o.jsxs)("div",{children:[(0,o.jsx)("div",{style:{height:"1.55em"}}),(0,o.jsx)("div",{style:{padding:"3px 12px",color:"var(--accent-blue)",background:"var(--bg-secondary)"},children:e.text}),(0,o.jsx)("div",{style:{height:"1.55em"}})]},e.key);let t="removed"===e.kind?cz:"added"===e.kind?cI:"transparent",r=e.block?cR[e.block]:"3px solid transparent",n="added"===e.kind?cM:"var(--text-dim)";return(0,o.jsxs)("div",{style:{display:"flex",background:t,borderLeft:r},children:[(0,o.jsx)("span",{style:{width:44,flexShrink:0,padding:"0 8px 0 16px",textAlign:"right",color:n,userSelect:"none",fontSize:11},children:e.lineNo??""}),(0,o.jsx)("span",{style:{flex:1,minWidth:0,padding:"0 8px 0 0",whiteSpace:"pre",color:"var(--text)"},children:e.text||"\xa0"})]},e.key)})})}function cW({filePath:e,cwd:t,sourceSessionId:r}){let{t:s}=(0,J.s)(),[i,a]=(0,n.useState)(0),[l,d]=(0,n.useState)(null),[c,p]=(0,n.useState)(null),[u,h]=(0,n.useState)(null),g=(0,n.useRef)(null),m=nx(e).toLowerCase().split(".").pop()??"";(0,n.useEffect)(()=>{a(0),d(null),p(null),h(null),g.current&&(g.current.close(),g.current=null);let t=new EventSource(cw(e,"watch",r));return g.current=t,t.addEventListener("change",e=>{try{let t=JSON.parse(e.data);"number"==typeof t.size&&d(t.size)}catch{}a(e=>e+1)}),()=>{t.close(),g.current=null}},[e,r]);let f=cw(e,"read",r,i?{v:i}:void 0),x=null!=l?cP(l):null;return(0,o.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,o.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:12,padding:"4px 16px",borderBottom:"1px solid var(--border)",fontSize:11,color:"var(--text-dim)",background:"var(--bg)",flexShrink:0},children:[(0,o.jsx)("span",{style:{fontFamily:"var(--font-mono)"},title:e,children:nv(e,t)}),(0,o.jsx)("span",{style:{marginLeft:"auto"},children:m||s("desktop.image")}),c&&(0,o.jsxs)("span",{children:[c.w," \xd7 ",c.h]}),x&&(0,o.jsx)("span",{children:x}),(0,o.jsx)(cj,{filePath:e,sourceSessionId:r})]}),(0,o.jsx)("div",{style:{flex:1,overflow:"auto",background:"var(--bg-panel)",display:"flex",alignItems:"center",justifyContent:"center",padding:16,backgroundImage:"linear-gradient(45deg, var(--bg) 25%, transparent 25%), linear-gradient(-45deg, var(--bg) 25%, transparent 25%), linear-gradient(45deg, transparent 75%, var(--bg) 75%), linear-gradient(-45deg, transparent 75%, var(--bg) 75%)",backgroundSize:"16px 16px",backgroundPosition:"0 0, 0 8px, 8px -8px, -8px 0px"},children:u?(0,o.jsx)("div",{style:{color:"var(--status-error)",fontSize:13},children:u}):(0,o.jsx)("img",{src:f,alt:e,onLoad:e=>{let t=e.currentTarget;p({w:t.naturalWidth,h:t.naturalHeight})},onError:()=>h(s("desktop.failedToLoadImage")),style:{maxWidth:"100%",maxHeight:"100%",objectFit:"contain",boxShadow:"0 2px 8px rgba(0,0,0,0.15)"}})})]})}function cN({filePath:e,cwd:t,sourceSessionId:r}){let{t:s}=(0,J.s)(),[i,a]=(0,n.useState)(0),[l,d]=(0,n.useState)(null),[c,p]=(0,n.useState)(null),[u,h]=(0,n.useState)(null),g=(0,n.useRef)(null),m=nx(e).toLowerCase().split(".").pop()??"";(0,n.useEffect)(()=>{a(0),d(null),p(null),h(null),g.current&&(g.current.close(),g.current=null);let t=new EventSource(cw(e,"watch",r));return g.current=t,t.addEventListener("change",e=>{try{let t=JSON.parse(e.data);"number"==typeof t.size&&d(t.size)}catch{}p(null),h(null),a(e=>e+1)}),()=>{t.close(),g.current=null}},[e,r]);let f=cw(e,"read",r,i?{v:i}:void 0);return(0,o.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,o.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:12,padding:"4px 16px",borderBottom:"1px solid var(--border)",fontSize:11,color:"var(--text-dim)",background:"var(--bg)",flexShrink:0},children:[(0,o.jsx)("span",{style:{fontFamily:"var(--font-mono)"},title:e,children:nv(e,t)}),(0,o.jsx)("span",{style:{marginLeft:"auto"},children:m||s("desktop.audio")}),null!=c&&(0,o.jsx)("span",{children:function(e){if(!Number.isFinite(e))return"";let t=Math.round(e),r=Math.floor(t/60);return`${r}:${String(t%60).padStart(2,"0")}`}(c)}),null!=l&&(0,o.jsx)("span",{children:cP(l)}),(0,o.jsx)(cj,{filePath:e,sourceSessionId:r})]}),(0,o.jsx)("div",{style:{flex:1,display:"flex",alignItems:"center",justifyContent:"center",padding:24,background:"var(--bg-panel)"},children:(0,o.jsxs)("div",{style:{width:"min(680px, 100%)"},children:[u&&(0,o.jsx)("div",{style:{color:"var(--status-error)",fontSize:13,marginBottom:12,textAlign:"center"},children:u}),(0,o.jsx)("audio",{controls:!0,preload:"metadata",src:f,onLoadedMetadata:e=>p(e.currentTarget.duration),onError:()=>h(s("desktop.failedToLoadAudio")),style:{width:"100%"}},f)]})})]})}function cF({filePath:e,cwd:t,sourceSessionId:r}){let{t:s}=(0,J.s)(),[i,a]=(0,n.useState)(0),[l,d]=(0,n.useState)(null),[c,p]=(0,n.useState)(null),u=(0,n.useRef)(null),h=ck(e),g="pdf"===h,m=g?cw(e,"read",r,i?{v:i}:void 0):cw(e,"preview",r,i?{v:i}:void 0);return(0,n.useEffect)(()=>{a(0),d(null),p(null),u.current&&(u.current.close(),u.current=null),fetch(cw(e,"meta",r)).then(e=>e.json()).then(e=>{e.error&&p(e.error),"number"==typeof e.size&&(d(e.size),!g&&e.size>0xa00000&&p(s("desktop.docxTooLargeForPreview")))}).catch(e=>p(String(e)));let t=new EventSource(cw(e,"watch",r));return u.current=t,t.addEventListener("change",e=>{try{let t=JSON.parse(e.data);if("number"==typeof t.size&&(d(t.size),!g&&t.size>0xa00000))return void p(s("desktop.docxTooLargeForPreview"))}catch{}p(null),a(e=>e+1)}),()=>{t.close(),u.current=null}},[e,g,r,s]),(0,o.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,o.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:12,padding:"4px 16px",borderBottom:"1px solid var(--border)",fontSize:11,color:"var(--text-dim)",background:"var(--bg)",flexShrink:0},children:[(0,o.jsx)("span",{style:{fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:e,children:nv(e,t)}),(0,o.jsx)("span",{style:{marginLeft:"auto"},children:"docx"===h?s("desktop.docxPreview"):"pdf"}),null!=l&&(0,o.jsx)("span",{children:cP(l)}),(0,o.jsx)(cj,{filePath:e,sourceSessionId:r})]}),(0,o.jsx)("div",{style:{flex:1,minHeight:0,background:"var(--bg-panel)"},children:c?(0,o.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",padding:24,color:"var(--status-error)",fontSize:13,textAlign:"center"},children:c}):(0,o.jsx)("iframe",{src:m,sandbox:g?void 0:"allow-same-origin",title:s("desktop.previewFile",{file:nx(e)}),style:{width:"100%",height:"100%",border:"none",background:g?"var(--bg)":"#eef1f5"}},m)})]})}function cD({filePath:e,cwd:t,sourceSessionId:r,onOpenFile:n,onAtMention:s,onMentionLines:i,initialDisplayMode:a,onFileSaved:l}){let d;return null!==(cx[ck(e)]??null)?(0,o.jsx)(cW,{filePath:e,cwd:t,sourceSessionId:r}):null!==(cv[ck(e)]??null)?(0,o.jsx)(cN,{filePath:e,cwd:t,sourceSessionId:r}):null!==("pdf"===(d=ck(e))||"docx"===d?d:null)?(0,o.jsx)(cF,{filePath:e,cwd:t,sourceSessionId:r}):(0,o.jsx)(cL,{filePath:e,cwd:t,sourceSessionId:r,onOpenFile:n,onAtMention:s,onMentionLines:i,initialDisplayMode:a,onFileSaved:l})}function cL({filePath:e,cwd:t,sourceSessionId:r,onOpenFile:s,onAtMention:i,onMentionLines:a,initialDisplayMode:l,onFileSaved:d}){let c,p,{t:u}=(0,J.s)(),[g,m]=(0,n.useState)(null),[x,v]=(0,n.useState)(null),[k,y]=(0,n.useState)(null),[b,w]=(0,n.useState)(!0),[j,S]=(0,n.useState)(null),[C,T]=(0,n.useState)(!1),[R,z]=(0,n.useState)("source"),[I,M]=(0,n.useState)(!1),[P,E]=(0,n.useState)(0),[A,W]=(0,n.useState)(null),N=(0,n.useRef)(null),F=(0,n.useRef)(null),[D,L]=(0,n.useState)(!1),[$,H]=(0,n.useState)(""),[O,B]=(0,n.useState)(""),[U,_]=(0,n.useState)(!1),[q,V]=(0,n.useState)(null),[K,G]=(0,n.useState)(!1),Y=(0,n.useRef)(null),X=(0,n.useRef)(null),Z=(0,n.useRef)(0),Q=(0,n.useRef)(!1);(0,n.useEffect)(()=>{Q.current=D},[D]);let ee=D&&$!==O,et=!!(g?.content&&g.content.includes("\0")),er=(0,n.useCallback)(async e=>{if(!t)return void y(null);try{let r=new URLSearchParams({cwd:t,path:e}),o=await fetch(`/api/git/diff?${r.toString()}`),n=await o.json();y(o.ok&&n.supported&&"string"==typeof n.patch?n:null)}catch{y(null)}},[t]),eo=(0,n.useCallback)((e,t=!1)=>fetch(cw(e,"read",r)).then(e=>e.json()).then(e=>e.error?(S(e.error),null):(t?(m(t=>(t&&v(t.content),e)),E(e=>e+1)):m(e),e)).catch(e=>(S(String(e)),null)),[r]);(0,n.useEffect)(()=>{w(!0),S(null),m(null),v(null),y(null),T(!1),z("source"),M(!1),E(0),L(!1),H(""),B(""),V(null),G(!1),_(!1),N.current&&(N.current.close(),N.current=null),eo(e).then(e=>{(e?.language==="markdown"||e?.language==="html")&&"diff"!==l&&T(!0)}).finally(()=>w(!1)),er(e);let t=new EventSource(cw(e,"watch",r));return N.current=t,t.addEventListener("change",()=>{Q.current?G(!0):(eo(e,!0),er(e))}),()=>{t.close(),N.current=null}},[e,eo,er,l,r]);let en=(0,n.useCallback)(()=>{g&&!et&&(H(g.content),B(g.content),V(null),G(!1),L(!0))},[g,et]),es=(0,n.useCallback)(()=>{L(!1),H(""),B(""),V(null),G(!1)},[]),ei=(0,n.useCallback)(()=>{(!ee||window.confirm(u("files.unsavedChanges")))&&es()},[ee,es,u]),ea=(0,n.useCallback)(async()=>{if(!g||U)return;let t=++Z.current;_(!0),V(null);try{let r=await cT(e,$);if(t!==Z.current)return;m(e=>e?{...e,content:$,size:r}:e),B($),_(!1),es(),er(e),d?.()}catch(e){if(t!==Z.current)return;V(e instanceof Error?e.message:String(e)),_(!1)}},[g,U,$,e,es,er,d]);(0,n.useEffect)(()=>{if(!D)return;let e=e=>{if((e.metaKey||e.ctrlKey)&&"s"===e.key.toLowerCase()){e.preventDefault(),ea();return}"Escape"===e.key&&(e.preventDefault(),ei())};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[D,ea,ei]),(0,n.useEffect)(()=>{if(!ee)return;let e=e=>{e.preventDefault(),e.returnValue=""};return window.addEventListener("beforeunload",e),()=>window.removeEventListener("beforeunload",e)},[ee]);let el=(0,n.useCallback)(()=>{let e=Y.current,t=X.current;e&&t&&(t.scrollTop=e.scrollTop)},[]),ed=(0,n.useCallback)(e=>{if("Tab"!==e.key||e.metaKey||e.ctrlKey||e.altKey)return;e.preventDefault();let t=e.currentTarget,{selectionStart:r,selectionEnd:o}=t;H(t.value.slice(0,r)+" "+t.value.slice(o)),requestAnimationFrame(()=>{let e=Y.current;if(!e)return;let t=r+2;e.selectionStart=t,e.selectionEnd=t})},[]),ec=(0,n.useMemo)(()=>iJ(g?.content??""),[g?.content]),ep=k?.supported===!0&&"string"==typeof k.patch;(0,n.useEffect)(()=>{"diff"===l&&ep&&z("diff")},[ep,l]);let eu=ep&&k?.status==="deleted",eh=(0,n.useCallback)(r=>{a&&r&&a(nv(e,t),r.startLine,r.endLine)},[t,e,a]);if((0,n.useEffect)(()=>{let e=()=>{let e=F.current,t="source"===R&&!C;W(a&&t&&e?cb(e,window.getSelection()):null)};if(e(),a&&"source"===R&&!C)return document.addEventListener("selectionchange",e),()=>document.removeEventListener("selectionchange",e)},[g?.content,a,C,R]),(0,n.useEffect)(()=>{if(!a||"source"!==R||C)return;let e=e=>{if(e.repeat||"i"!==e.key.toLowerCase()||!e.metaKey&&!e.ctrlKey||e.altKey||e.shiftKey)return;let t=e.target;if(t instanceof Element&&t.closest("input, textarea, [contenteditable='true']"))return;let r=F.current,o=r?cb(r,window.getSelection()):null;o&&(e.preventDefault(),eh(o))};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[eh,a,C,R]),b)return(0,o.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-muted)",fontSize:13},children:u("desktop.loadingFile")});if(eu&&!g)return(0,o.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,o.jsx)("div",{style:{padding:"5px 16px",borderBottom:"1px solid var(--border)",color:"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:11},title:e,children:nv(e,t)}),(0,o.jsx)("div",{style:{flex:1,overflow:"auto",background:"var(--bg)"},children:(0,o.jsx)(cA,{patch:k.patch})})]});if(j)return(0,o.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--status-error)",fontSize:13},children:j});if(!g)return null;let eg="html"===g.language,em="markdown"===g.language,ef=(p=(c=nm(e).replace(/\/+$/,"")).lastIndexOf("/"))<0?"":0===p?"/":2===p&&/^[a-zA-Z]:\//.test(c)?c.slice(0,3):c.slice(0,p),ex=g.content.split("\n"),ev=null!==x&&x!==g.content||ep,ek=!eu&&!et&&nb();return(0,o.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,o.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:12,padding:"4px 16px",borderBottom:"1px solid var(--border)",fontSize:11,color:"var(--text-dim)",background:"var(--bg)",flexShrink:0},children:[(0,o.jsx)("span",{style:{fontFamily:"var(--font-mono)"},title:e,children:nv(e,t)}),(0,o.jsx)("span",{style:{marginLeft:"auto"},children:g.language}),"source"===R&&!D&&(0,o.jsx)("span",{children:u("desktop.lines",{count:ex.length})}),(0,o.jsx)("span",{children:cP(g.size)}),ev&&!D&&(0,o.jsxs)("div",{style:{display:"flex",borderRadius:5,overflow:"hidden",border:"1px solid var(--border)"},children:[(0,o.jsx)("button",{onClick:()=>z("source"),style:{padding:"2px 8px",fontSize:11,border:"none",cursor:"pointer",background:"source"===R?"var(--bg-selected)":"var(--bg-hover)",color:"source"===R?"var(--text)":"var(--text-muted)",fontWeight:"source"===R?600:400},children:u("desktop.source")}),(0,o.jsxs)("button",{onClick:()=>z("diff"),style:{padding:"2px 8px",fontSize:11,border:"none",borderLeft:"1px solid var(--border)",cursor:"pointer",background:"diff"===R?"var(--bg-selected)":"var(--bg-hover)",color:"diff"===R?"var(--text)":"var(--text-muted)",fontWeight:"diff"===R?600:400},children:[u("desktop.diff")," ",P>0&&(0,o.jsxs)("span",{style:{color:"var(--git-status-added)",marginLeft:2},children:["+",P]})]})]}),"source"===R&&!C&&!D&&(0,o.jsx)("button",{onClick:()=>M(e=>!e),title:I?u("desktop.disableWordWrap"):u("desktop.enableWordWrap"),style:{padding:"2px 8px",fontSize:11,cursor:"pointer",background:I?"var(--bg-selected)":"var(--bg-hover)",color:I?"var(--text)":"var(--text-muted)",border:"1px solid var(--border)",borderRadius:5,fontWeight:I?600:400},children:u("desktop.wrap")}),eg&&"source"===R&&!D&&(0,o.jsxs)("div",{style:{display:"flex",borderRadius:5,overflow:"hidden",border:"1px solid var(--border)"},children:[(0,o.jsx)("button",{onClick:()=>T(!1),style:{padding:"2px 8px",fontSize:11,border:"none",cursor:"pointer",background:C?"var(--bg-hover)":"var(--bg-selected)",color:C?"var(--text-muted)":"var(--text)",fontWeight:C?400:600},children:u("desktop.code")}),(0,o.jsx)("button",{onClick:()=>T(!0),style:{padding:"2px 8px",fontSize:11,border:"none",borderLeft:"1px solid var(--border)",cursor:"pointer",background:C?"var(--bg-selected)":"var(--bg-hover)",color:C?"var(--text)":"var(--text-muted)",fontWeight:C?600:400},children:u("desktop.preview")})]}),em&&"source"===R&&!D&&(0,o.jsxs)("div",{style:{display:"flex",borderRadius:5,overflow:"hidden",border:"1px solid var(--border)"},children:[(0,o.jsx)("button",{onClick:()=>T(!0),style:{padding:"2px 8px",fontSize:11,border:"none",cursor:"pointer",background:C?"var(--bg-selected)":"var(--bg-hover)",color:C?"var(--text)":"var(--text-muted)",fontWeight:C?600:400},children:u("desktop.preview")}),(0,o.jsx)("button",{onClick:()=>T(!1),style:{padding:"2px 8px",fontSize:11,border:"none",borderLeft:"1px solid var(--border)",cursor:"pointer",background:C?"var(--bg-hover)":"var(--bg-selected)",color:C?"var(--text-muted)":"var(--text)",fontWeight:C?400:600},children:u("desktop.raw")})]}),D?(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)("button",{type:"button",onClick:()=>void ea(),disabled:U,title:u("files.saveHint"),"aria-label":u("files.save"),style:{height:20,minWidth:20,padding:"0 5px",display:"inline-flex",alignItems:"center",justifyContent:"center",border:"1px solid var(--border)",borderRadius:4,background:"var(--bg-selected)",color:"var(--text)",cursor:"pointer"},children:(0,o.jsx)(cf.g,{size:13,"aria-hidden":"true"})}),(0,o.jsx)("button",{type:"button",onClick:ei,disabled:U,title:u("files.cancelEdit"),"aria-label":u("files.cancelEdit"),style:{height:20,minWidth:20,padding:"0 5px",display:"inline-flex",alignItems:"center",justifyContent:"center",border:"1px solid var(--border)",borderRadius:4,background:"var(--bg-panel)",color:"var(--text-muted)",cursor:"pointer"},children:(0,o.jsx)(h.X,{size:13,"aria-hidden":"true"})})]}):"source"===R&&ek?(0,o.jsx)("button",{type:"button",onClick:en,title:u("files.edit"),"aria-label":u("files.edit"),style:{height:20,minWidth:20,padding:"0 5px",display:"inline-flex",alignItems:"center",justifyContent:"center",border:"1px solid var(--border)",borderRadius:4,background:"var(--bg-panel)",color:"var(--text-muted)",cursor:"pointer"},children:(0,o.jsx)(f.I,{size:13,"aria-hidden":"true"})}):null,(i||a)&&!D&&(0,o.jsx)("button",{type:"button",onPointerDown:e=>e.preventDefault(),onClick:()=>{A&&a?eh(A):i?.(nv(e,t),!1)},title:A?u("desktop.mentionSelectedLines",{start:A.startLine,end:A.endLine}):u("desktop.mentionFile"),"aria-label":A?u("desktop.mentionSelectedLines",{start:A.startLine,end:A.endLine}):u("desktop.mentionFile"),style:{height:20,minWidth:20,padding:"0 5px",border:"1px solid var(--border)",borderRadius:4,background:"var(--bg-panel)",color:"var(--text-muted)",cursor:"pointer"},children:"@"}),!D&&(0,o.jsx)(cj,{filePath:e,sourceSessionId:r})]}),(0,o.jsx)("div",{ref:F,style:{flex:1,overflow:"auto",background:"var(--bg)"},children:D?(0,o.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[K&&(0,o.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"5px 12px",borderBottom:"1px solid var(--border)",background:"rgba(214,168,75,0.14)",color:"#d6a84b",fontSize:11,flexShrink:0},children:[(0,o.jsx)("span",{style:{flex:1},children:u("files.externalModified")}),(0,o.jsx)("button",{type:"button",onClick:()=>{(!ee||window.confirm(u("files.reloadOverwriteConfirm")))&&eo(e).then(e=>{e&&(H(e.content),B(e.content),G(!1))})},disabled:U,style:{padding:"2px 8px",fontSize:11,border:"1px solid #d6a84b",borderRadius:4,background:"transparent",color:"#d6a84b",cursor:"pointer"},children:u("files.reload")})]}),q&&(0,o.jsx)("div",{style:{padding:"5px 12px",borderBottom:"1px solid var(--border)",background:"rgba(248,113,113,0.14)",color:"var(--status-error)",fontSize:11,flexShrink:0},children:u("files.saveFailed",{error:q})}),(0,o.jsxs)("div",{style:{flex:1,display:"flex",overflow:"hidden"},children:[(0,o.jsx)("div",{ref:X,"aria-hidden":"true",style:{...cC,height:"100%",overflow:"hidden",whiteSpace:"pre",pointerEvents:"none"},children:$.split("\n").map((e,t)=>`${t+1}
194
+ ${r}`):s=r;let h=s,g=n?.map(e=>({type:"image",source:{type:"base64",media_type:e.mimeType,data:e.data}})),m={role:"user",content:g?.length?[...r.trim()?[{type:"text",text:r}]:[],...g]:r,timestamp:Date.now()};T(e=>[...e,m]),ro.current=ci(m),rr.current=l;let f="goal"===eS.current&&!a&&i.length>0&&"idle"===eF.current.status;f&&(ez.current=i,eN(e=>({...e,status:"running",goalText:i,turnsUsed:0,noProgressTurns:0,tokensUsed:0})),eD.current=!0),tV.current=!0,U(!0),ta(a?{kind:"running_command"}:{kind:"waiting_model"}),W({type:"start"}),t6.current=!0,td(!0),t4.current=!0;let x=n?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),v=null,k=!1;try{if(u&&o){let e=tq.current??await re.current,t=e??await rw();if(t){v=t,rb(1,r),ei&&(eX(ei),e&&await tP(t,{type:"set_model",provider:ei.provider,modelId:ei.modelId}));let o=await Promise.race([rR(t).then(()=>!0).catch(()=>!1),cr(4e3).then(()=>!1)]);k=!0,await tP(t,{type:"prompt",message:h,...x?.length?{images:x}:{}}),o||rH(t,l),f&&tP(t,{type:"goal_start",goalText:i}).catch(()=>{})}else throw Error("Unable to create a session for this message")}else if(t){v=t.id;let e=await Promise.race([rR(t.id).then(()=>!0).catch(()=>!1),cr(4e3).then(()=>!1)]);k=!0,await tP(t.id,{type:"prompt",message:h,...x?.length?{images:x}:{}}),e||rH(t.id,l),f&&tP(t.id,{type:"goal_start",goalText:i}).catch(()=>{})}a&&v&&rH(v,l)}catch(t){if(console.error("Failed to send message:",t),k&&v)return void rH(v,l);if(tG.current=!1,rC(),t instanceof ct){let e=ro.current;e&&T(t=>{let r=t[t.length-1];return r?.role==="user"&&ci(r)===e?t.slice(0,-1):t}),rM({type:"error",message:t.message})}else{let r=ro.current;r&&T(e=>{let t=e[e.length-1];return t?.role==="user"&&ci(t)===r?e.slice(0,-1):e}),e.chatInputRef?.current?.replaceMessage?.(m),rM({type:"error",message:`Failed to send message: ${t instanceof Error?t.message:String(t)}`})}ro.current=null,tV.current=!1,U(!1),ta(null),W({type:"end"})}},[u,o,ei,t,rw,rR,rb,rH,rM,rS,rC,rp]),rV=(0,n.useCallback)(async(r,o)=>{if(tV.current||tZ.current)return;let n=`${o?"!!":"!"}${r}`;tZ.current=!0,K({command:r,excludeFromContext:o}),q(!0);try{let e=tq.current??t?.id??await rw();if(!e)throw Error("Unable to create a session for the shell command");rb(1,n),await tP(e,{type:"bash",command:r,excludeFromContext:o}),await rk(e)}catch(t){console.error("Failed to execute shell command:",t),rM({type:"error",message:t instanceof Error?t.message:String(t)}),e.chatInputRef?.current?.insertIfEmpty(n)}finally{tZ.current=!1,K(null),q(!1)}},[rM,rw,rk,e.chatInputRef,rb,t]),rK=(0,n.useCallback)(async()=>{let e=tq.current;if(e)try{await tP(e,{type:tZ.current?"abort_bash":"abort"})}catch(e){console.error("Failed to abort:",e)}},[]),rG=(0,n.useCallback)(async e=>{let t=tq.current;if(t){eK(e);try{let{cancelled:r,newSessionId:o}=await tP(t,{type:"fork",entryId:e})??{};!r&&o&&a?.(o)}catch(e){console.error("Fork failed:",e)}finally{eK(null)}}},[a]),rJ=(0,n.useCallback)(async e=>{let t=tq.current;t&&(tP(t,{type:"navigate_tree",targetId:e}).catch(()=>{}),S(e),await rE(t,e))},[rE]),rY=(0,n.useCallback)(async e=>{S(e);let t=tq.current;t&&(await rE(t,e),e&&tP(t,{type:"navigate_tree",targetId:e}).catch(()=>{}))},[rE]),rX=(0,n.useCallback)(async(e,t)=>{if(u){let r={provider:e,modelId:t};rl.current=r,ea(r),eX(r);let o=tq.current??await re.current;if(!o)return;try{await tP(o,{type:"set_model",provider:e,modelId:t})}catch(e){console.error("Failed to set model:",e)}return}let r=tq.current;if(!r)return;let o=++rn.current,n=eG??g?.context.model??null;eJ({provider:e,modelId:t});try{await tP(r,{type:"set_model",provider:e,modelId:t})}catch(r){console.error("Failed to set model:",r),rn.current===o&&(eJ(n&&(n.provider!==e||n.modelId!==t)?n:null),rM({type:"error",message:r instanceof Error?r.message:String(r)}))}},[rM,eG,g?.context.model,u,ea]),rZ=(0,n.useCallback)(async()=>{let e=tq.current;if(e&&!eZ){tt(!0),to(null),ts(null);try{let t=await tP(e,{type:"compact"});ts(ca(t,"manual")),await rk(e,!0)}catch(e){to(e instanceof Error?e.message:String(e)),ts(null)}finally{tt(!1)}}},[eZ,rk]),rQ=(0,n.useCallback)(async e=>{let r=++rs.current,n=o??t?.cwd??"",s=n?`/api/models?cwd=${encodeURIComponent(n)}`:"/api/models",i=ri.current;i?.abort();let a=new AbortController;ri.current=a;let l=()=>a.abort();e?.aborted?a.abort():e?.addEventListener("abort",l,{once:!0});try{let e=await fetch(s,{signal:a.signal});if(!e.ok){let t=`HTTP ${e.status}`;try{let r=await e.json();r?.error&&(t=r.error)}catch{}throw Error(t)}let t=await e.json();if(r!==rs.current||h!==ra.current)return;es(null),J(t.models),Q(t.thinkingLevels??{}),et(t.thinkingLevelMaps??{}),eo(t.modelScopeWarnings??[]);let o=t.modelList??[];if(X(o),u&&!tq.current){let e=(t.defaultModel?o.find(e=>e.id===t.defaultModel?.modelId&&e.provider===t.defaultModel?.provider):void 0)??o[0];ed(e?{provider:e.provider,modelId:e.id}:null);let r=e?t.thinkingLevelPins?.[`${e.provider}/${e.id}`]:void 0;null===rd.current&&e$(r??"auto")}}catch(e){if(a.signal.aborted||r!==rs.current||h!==ra.current)return;es(e instanceof Error?e.message:String(e))}finally{e?.removeEventListener("abort",l),ri.current===a&&(ri.current=null)}},[u,h,o,t?.cwd]),r0=(0,n.useCallback)(async e=>{if(!e.startsWith("/"))return{handled:!1};let t=e.match(/^\/([^\s]+)(?:\s+([\s\S]*))?$/);if(!t)return{handled:!1};let[,r,o=""]=t,n=o.trim(),s=tq.current??await rw(),i=e=>(e.handled&&(e.error?rM({type:"error",message:e.error}):"openSessionStats"!==e.action&&rM({type:"success",message:e.message??"Command completed"})),e);try{switch(r){case"compact":{if(!s||eZ)return i({handled:!0,error:"No active session to compact"});tt(!0),to(null),ts(null);let e=await tP(s,{type:"compact",...n?{customInstructions:n}:{}});return ts(ca(e,"manual")),await rk(s,!0)&&rb(),i({handled:!0,message:"Compacted context"})}case"reload":if(!s)return i({handled:!0,error:"No active session to reload"});return await tP(s,{type:"reload"}),await Promise.all([rk(s,!1,!0),ry(s),rj(),rQ()]),i({handled:!0,message:"Reloaded session resources"});case"name":if(!s)return i({handled:!0,error:"No active session to name"});if(!n)return i({handled:!0,error:"Usage: /name <name>"});return await tP(s,{type:"set_session_name",name:te(n)}),await rk(s)&&rb(),i({handled:!0,message:`Session renamed to ${n}`});case"session":{if(!s)return i({handled:!0,error:"No active session"});let e=await tP(s,{type:"get_session_stats"});return e&&tx(e),p?.(),i({handled:!0,action:"openSessionStats"})}case"copy":{if(!s)return i({handled:!0,error:"No active session"});let e=await tP(s,{type:"get_last_assistant_text"}),t=e?.text??"";if(!t)return i({handled:!0,error:"No assistant message to copy"});return await navigator.clipboard.writeText(t),i({handled:!0,message:"Copied last assistant message"})}default:return{handled:!1}}}catch(e){return i({handled:!0,error:e instanceof Error?e.message:String(e)})}finally{"compact"===r&&tt(!1)}},[rM,rw,eZ,rQ,rk,rj,ry,rb,p]),r1=(0,n.useCallback)(async e=>{let t=!1;try{let r=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(r.ok){let e=await r.json(),o=e.state;if(e.running&&o&&(o.isStreaming||o.isPromptRunning||o.isBashRunning||o.isCompacting))return;t=!0}}catch{}t?rF():rH(e)},[rH,rF]),r2=(0,n.useCallback)(async(e,t)=>{let r=tq.current;if(!r)return;let o=t?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType}));tV.current=!0,U(!0),ta(e=>e??{kind:"waiting_model"});try{await tP(r,{type:"steer",message:e,...o?.length?{images:o}:{}})}catch(e){console.error("Failed to steer:",e),r1(r)}},[r1]),r6=(0,n.useCallback)(async(e,t,r)=>{let o=tq.current;if(!o)return;let n=r?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType}));tV.current=!0,U(!0),ta(e=>e??{kind:"waiting_model"});try{await tP(o,{type:"prompt",message:e,streamingBehavior:t,...n?.length?{images:n}:{}})}catch(e){console.error("Failed to queue prompt:",e),r1(o)}},[r1]),r4=(0,n.useCallback)(async(e,t)=>{let r=tq.current;if(!r)return;let o=t?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType}));tV.current=!0,U(!0),ta(e=>e??{kind:"waiting_model"});try{await tP(r,{type:"follow_up",message:e,...o?.length?{images:o}:{}})}catch(e){console.error("Failed to follow up:",e),r1(r)}},[r1]),r5=(0,n.useCallback)(async()=>{let e=tq.current;if(e)try{await tP(e,{type:"abort_compaction"})}catch(e){console.error("Failed to abort compaction:",e)}},[]),r8=(0,n.useCallback)(async()=>{let t=tq.current;if(t)try{let r=await tP(t,{type:"clear_queue"});tz({steering:[],followUp:[]});let o=[...r?.steering??[],...r?.followUp??[]];o.length>0&&e.chatInputRef?.current?.prependText(o.join("\n\n"))}catch(e){console.error("Failed to recall queued messages:",e),rM({type:"error",message:"Failed to recall queued messages"})}},[e.chatInputRef,rM,tz]);(0,n.useEffect)(()=>{0===tI.length&&tW(!1)},[tI.length]);let r3=(0,n.useCallback)(async(e,t,r=!1)=>{let o=tq.current;if(!o)return tI;try{let n=await tP(o,{type:"resolve_recovery",keep:e,discard:t,continueRun:r}),s=n?.remaining??[];return tE(s),r&&e.length>0&&(async()=>{try{let e=await fetch(`/api/agent/${encodeURIComponent(o)}`);if(!e.ok)return;let t=await e.json(),r=t.state;if(!t.running||!r||!r.isStreaming&&!r.isPromptRunning)return;tK.current=!!r.isStreaming,tG.current=!!r.isPromptRunning,tV.current=!0,U(!0),ta(d8(r)),W({type:"start"}),rT(o),!r.isStreaming&&r.isPromptRunning&&rH(o)}catch{}})(),s}catch(e){return console.error("Failed to resolve queued message recovery:",e),rM({type:"error",message:"Failed to resolve queued message recovery"}),tI}},[tI,rM,rT,rH,tE]),r7=(0,n.useCallback)(async()=>{let e=tq.current;if(!e)return null;try{return await tP(e,{type:"export_queue"})}catch(e){return console.error("Failed to export queue:",e),rM({type:"error",message:"Failed to export queue"}),null}},[rM]),r9=(0,n.useCallback)(async e=>{let t=tq.current;if(!t)return null;try{let r=await tP(t,{type:"import_queue",entries:e});return r&&tz(d7(r)),r?.imported??0}catch(e){return console.error("Failed to import queue:",e),rM({type:"error",message:"Failed to import queue"}),null}},[rM,tz]),oe=(0,n.useCallback)(async e=>{let t=tq.current;if(!t)return null;try{let r=await tP(t,{type:"stage_recovery",entries:e});return r?.pendingRecovery&&tE(r.pendingRecovery),(r?.staged??0)>0&&tW(!0),r?.staged??0}catch(e){return console.error("Failed to stage imported queue:",e),rM({type:"error",message:"Failed to stage imported queue"}),null}},[rM,tE]),ot=(0,n.useCallback)(async(e,t,r)=>{let o=tq.current;if(!o)return!1;try{let n=await tP(o,{type:"move_queue",kind:e,fromIndex:t,toIndex:r});return n&&tz(d7(n)),!0}catch(e){return console.error("Failed to move queued message:",e),rM({type:"error",message:e instanceof Error?e.message:"Failed to move queued message"}),!1}},[rM,tz]),or=(0,n.useCallback)(async(e,t)=>{let r=tq.current;if(!r)return null;try{let o=await tP(r,{type:"recall_queue_item",kind:e,index:t});return o&&(void 0!==o.steering||void 0!==o.followUp)&&tz(d7(o)),o?.entry?{text:o.entry.text,images:o.entry.images?.map(({data:e,mimeType:t})=>({data:e,mimeType:t}))}:null}catch(e){return console.error("Failed to recall queued message:",e),rM({type:"error",message:e instanceof Error?e.message:"Failed to recall queued message"}),null}},[rM,tz]),oo=(0,n.useCallback)(async(e,t,r,o)=>{let n=tq.current;if(!n)return!1;try{let s=await tP(n,{type:"requeue_at",kind:e,index:t,text:r,images:o?.map(({data:e,mimeType:t})=>({type:"image",data:e,mimeType:t}))});return s&&tz(d7(s)),!0}catch(e){return console.error("Failed to requeue message:",e),rM({type:"error",message:e instanceof Error?e.message:"Failed to requeue message"}),!1}},[rM,tz]),on=(0,n.useCallback)(async(e,t)=>{let r=tq.current;if(!r)return!1;try{let o=await tP(r,{type:"remove_queue_item",kind:e,index:t});return o&&tz(d7(o)),!0}catch(e){return console.error("Failed to remove queued message:",e),rM({type:"error",message:e instanceof Error?e.message:"Failed to remove queued message"}),!1}},[rM,tz]),os=(0,n.useCallback)(async e=>{if(rd.current="auto"===e?null:e,e$(e),"auto"===e)return;let t=tq.current??await re.current;if(t)try{await tP(t,{type:"set_thinking_level",level:e})}catch(e){console.error("Failed to set thinking level:",e)}},[]),oi=(0,n.useCallback)(async e=>{let t=(0,d2.xG)(e);rh(e);let r=tq.current??await re.current;if(r)try{await tP(r,{type:"set_tools",toolNames:t})}catch(e){console.error("Failed to set tools:",e)}},[rh]),oa=(0,n.useRef)(0),ol=(0,n.useCallback)(async e=>{let t=tq.current??await re.current,r=++oa.current;if("plan"===e){if(eu.current="plan"===ec?"default":ec,t)try{await tP(t,{type:"prompt",message:"/plan"})}catch(e){if(oa.current!==r)return;console.error("Failed to enter plan mode:",e)}return}if(t){try{if(await tP(t,{type:"prompt",message:"/plan exit"}),oa.current!==r)return}catch(e){if(oa.current!==r)return;console.error("Failed to exit plan mode:",e)}if(oa.current!==r)return;try{await tP(t,{type:"set_tools",toolNames:(0,d2.xG)(eu.current)})}catch(e){console.error("Failed to restore tools after plan exit:",e)}}},[ec]),od=(0,n.useCallback)(e=>{em(e);let t=tq.current;if(!t){ef.current=e;return}ef.current=null,fetch(`/api/modes?session=${encodeURIComponent(t)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}).catch(e=>{console.error("Failed to persist mode settings:",e)})},[]),oc=(0,n.useCallback)(e=>{let t=e2(e),r="plan"===eS.current;if(od({...eM.current,collaborationMode:t}),eS.current=t,eI.current={sessionKey:"",signature:""},"goal"!==t){ez.current=null,eD.current=!1,eN(e=>"idle"===e.status?e:{...e,status:"idle",goalText:null});let e=tq.current;e&&tP(e,{type:"goal_stop"}).catch(()=>{})}return"plan"!==t||r?"plan"!==t&&r?ol("normal"):Promise.resolve():ol("plan")},[od,ol]),op=(0,n.useCallback)(async e=>{od({...eM.current,tokenMode:e6(e)});let t=tq.current??await re.current;if(t)try{if("economy"!==e||eh.current){if("economy"!==e){let e=eh.current?d2.SC:(0,d2.xG)("plan"===ec?"default":ec);await tP(t,{type:"set_tools",toolNames:e})}}else await tP(t,{type:"set_tools",toolNames:[...e5]})}catch(e){console.error("Failed to apply token mode tools:",e)}},[od,ec]),ou=(0,n.useCallback)(async e=>{od({...eM.current,toolApprovalMode:e4(e)});let t=tq.current??await re.current;if(t)try{await tP(t,{type:"set_approval_mode",mode:e4(e)})}catch(e){console.error("Failed to apply approval mode:",e)}},[od]),oh=(0,n.useCallback)(async e=>{od({...eM.current,permissionRules:e});let t=tq.current??await re.current;if(t)try{await tP(t,{type:"set_approval_policy",policy:e})}catch(e){console.error("Failed to apply permission rules:",e)}},[od]),og=(0,n.useCallback)(async(e,t,r)=>{let o=tq.current;if(o)try{await tP(o,{type:"resolve_approval",id:e,approve:t,reason:r})}catch(e){console.error("Failed to resolve approval:",e)}finally{eE(t=>t.filter(t=>t.id!==e))}},[]),om=(0,n.useCallback)(e=>{ez.current=e},[]),of=(0,n.useCallback)(e=>{let t=e.trim();if(!t)return;ez.current=t,eN(e=>({...e,status:"running",goalText:t,turnsUsed:0,noProgressTurns:0,tokensUsed:0,startedAt:Date.now()}));let r=tq.current;r&&tP(r,{type:"goal_start",goalText:t}).catch(()=>{})},[]),ox=(0,n.useCallback)(()=>{if("running"!==eF.current.status)return;eN(e=>({...e,status:"paused"}));let e=tq.current;e&&tP(e,{type:"goal_pause"}).catch(()=>{})},[]),ov=(0,n.useCallback)(()=>{let e=eF.current;if("paused"!==e.status&&"blocked"!==e.status)return;eN(e=>({...e,status:"running"}));let t=tq.current;t&&tP(t,{type:"goal_resume"}).catch(()=>{})},[]),ok=(0,n.useCallback)(()=>{eD.current=!1,ez.current=null,eN(e=>({...e,status:"idle",goalText:null,turnsUsed:0,noProgressTurns:0}));let e=tq.current;e&&tP(e,{type:"goal_stop"}).catch(()=>{})},[]),oy=(0,n.useCallback)(e=>{let t=e.trim();if(!t)return;eN(e=>({...e,goalText:t}));let r=tq.current;r&&tP(r,{type:"goal_edit",goalText:t}).catch(()=>{})},[]),ob=(0,n.useCallback)(()=>{let e=t9.current,t=t2.current;if(!e||!t)return;let r=t.getBoundingClientRect().top-e.getBoundingClientRect().top+e.scrollTop,o=Math.max(0,e.scrollHeight-e.clientHeight),n=Math.min(Math.max(0,r-16),o);t5.current=n>=o-150,t3.current=Date.now()+700,e.scrollTo({top:n,behavior:"smooth"})},[]),ow=(0,n.useCallback)(e=>{if(e instanceof KeyboardEvent){if(!ce.has(e.key)||e.target instanceof Element&&e.target.closest("input, textarea, [contenteditable='true']"))return}else if(e instanceof PointerEvent){let t=t9.current;if(t&&e.target instanceof Element&&!t.contains(e.target))return}t8.current=Date.now()+1200},[]),oj=(0,n.useCallback)(()=>{let e=t9.current;if(e){let{scrollTop:t,clientHeight:r,scrollHeight:o}=e;t5.current=t+r>=o-150}if(Date.now()<t8.current){t4.current=!1;return}Date.now()<t3.current||(t4.current=!1)},[]);(0,n.useEffect)(()=>{if(tY.current=!0,t){tq.current=t.id;let e=eT.current,r=eR.current;("auto"!==e||r.allow.length||r.ask.length||r.deny.length)&&(tP(t.id,{type:"set_approval_mode",mode:e}).catch(()=>{}),tP(t.id,{type:"set_approval_policy",policy:r}).catch(()=>{}));let o=e=>{!tQ.current&&(tQ.current=!0,e.isBashRunning&&(tZ.current=!0,q(!0)),ry(t.id),(e.isStreaming||e.isPromptRunning)&&(tK.current=!!e.isStreaming,tG.current=!!e.isPromptRunning,tV.current=!0,U(!0),ta(d8(e)),W({type:"start"}),rT(t.id),!e.isStreaming&&e.isPromptRunning&&rH(t.id)))};(async()=>{try{let e,r=new AbortController,n=setTimeout(()=>r.abort(),2e4);try{e=await fetch(`/api/sessions/${encodeURIComponent(t.id)}/state`,{signal:r.signal})}finally{clearTimeout(n)}if(!e.ok)throw Error(`HTTP ${e.status}`);let s=await e.json();if(!tY.current||tq.current!==t.id)return;s.running&&s.state&&o(s.state)}catch{}})(),rk(t.id,!0,!0).then(e=>{e?.running&&e.state&&o(e.state),e?.state&&(void 0!==e.state.isCompacting&&tt(e.state.isCompacting),void 0!==e.state.contextUsage&&eU(e.state.contextUsage??null),void 0!==e.state.systemPrompt&&eq(e.state.systemPrompt??null),void 0!==e.state.thinkingLevel&&e$(e.state.thinkingLevel??"auto"),void 0!==e.state.extensionStatuses&&tj(e.state.extensionStatuses??[]),void 0!==e.state.extensionWidgets&&tC(e.state.extensionWidgets??[]),void 0!==e.state.queuedMessages&&tz(d7(e.state.queuedMessages)),void 0!==e.state.pendingRecovery&&tE(e.state.pendingRecovery??[])),e?.running||(async()=>{for(let e=0;e<5;e++){if(e>0&&await new Promise(e=>setTimeout(e,2e3)),!tY.current||tq.current!==t.id||tV.current)return;try{let e=await fetch(`/api/agent/${encodeURIComponent(t.id)}`);if(!e.ok)continue;let r=await e.json();if(!tY.current||tq.current!==t.id)return;if(r?.running&&r.state)return void o(r.state)}catch{}}})()})}return()=>{tY.current=!1,f.current?.abort(),v.current?.abort(),rp(),tD(),rS(),rC()}},[rp]),(0,n.useEffect)(()=>{c?.(e_)},[e_,c]),(0,n.useEffect)(()=>{d&&d(g?.tree??[],j,rY)},[g?.tree,j,rY,d]),(0,n.useEffect)(()=>(window.addEventListener("keydown",ow),window.addEventListener("pointerdown",ow,{passive:!0}),()=>{window.removeEventListener("keydown",ow),window.removeEventListener("pointerdown",ow)}),[ow]),(0,n.useEffect)(()=>{let e=t9.current;if(e)return e.addEventListener("wheel",ow,{passive:!0}),e.addEventListener("touchstart",ow,{passive:!0}),e.addEventListener("scroll",oj,{passive:!0}),()=>{e.removeEventListener("wheel",ow),e.removeEventListener("touchstart",ow),e.removeEventListener("scroll",oj)}},[C.length,k,oj,ow]),(0,n.useEffect)(()=>{C.length>0&&(t6.current?(t1.current=!0,t2.current&&(t6.current=!1,ob())):k||!t1.current?(k||(t1.current=!0),rU("instant")):!tV.current&&(t4.current||t5.current)&&(rU("smooth"),oT(e=>e+1)))},[C.length,k,B,rU,ob]);let oS=(0,n.useRef)(null),[oC,oT]=(0,n.useState)(0),oR=`${t?.id??null}#${oC}`;(0,n.useEffect)(()=>{let e;if(k){oS.current=null;return}if(0===C.length||oS.current===oR)return;oS.current=oR;let t=!1,r=!1,o=-1,n=0,s=Date.now(),i=()=>{if(t||r)return;let a=t9.current;if(a){if(Date.now()<t8.current){let{scrollTop:e,clientHeight:t,scrollHeight:o}=a;if(e+t<o-150){r=!0;return}}if(rU("instant"),a.scrollHeight===o){if((n+=1)>=4||Date.now()-s>=3e4)return}else if(o=a.scrollHeight,n=0,Date.now()-s>=3e4)return;e=window.setTimeout(i,n>0?500:250)}};return e=window.setTimeout(i,250),()=>{t=!0,void 0!==e&&window.clearTimeout(e)}},[k,rU,oR]),(0,n.useEffect)(()=>{let e=new AbortController;return rQ(e.signal).catch(e=>{if(e instanceof DOMException&&"AbortError"===e.name)return}),()=>e.abort()},[rQ,l]),(0,n.useEffect)(()=>{if(!en)return;let e=()=>{"visible"===document.visibilityState&&rQ()};return document.addEventListener("visibilitychange",e),window.addEventListener("online",e),()=>{document.removeEventListener("visibilitychange",e),window.removeEventListener("online",e)}},[en,rQ]),(0,n.useEffect)(()=>{if(!tr)return;let e=setTimeout(()=>to(null),3e3);return()=>clearTimeout(e)},[tr]),(0,n.useEffect)(()=>{if(!tn)return;let e=setTimeout(()=>ts(null),6e3);return()=>clearTimeout(e)},[tn]),(0,n.useEffect)(()=>{if(0===tg.visible.length)return;let e=tg.visible.find(e=>e.exiting);if(e){let t=setTimeout(()=>{tm({type:"remove",id:e.id})},180);return()=>clearTimeout(t)}if(!tg.visible[0])return;let t=setTimeout(()=>{tm({type:"mark_oldest_exiting"})},5e3);return()=>clearTimeout(t)},[tg.visible]),(0,n.useEffect)(()=>{tx(null)},[C.length,eB?.tokens,eB?.percent,eB?.contextWindow]);let oz=g?.tree??[];return{data:g,loading:k,error:b,activeLeafId:j,messages:C,entryIds:R,historyCursor:I,hasEarlierMessages:P,streamState:A,agentRunning:B,bashRunning:_,pendingBash:V,modelNames:G,modelList:Y,modelThinkingLevels:Z,modelThinkingLevelMaps:ee,modelScopeWarnings:er,modelsError:en,newSessionModel:ei,toolPreset:ec,thinkingLevel:eL,retryInfo:eH,contextUsage:eB,systemPrompt:e_,forkingEntryId:eV,isCompacting:eZ,compactError:tr,compactResult:tn,currentModel:rf,displayModel:rx,sessionStats:rv,tokenRate:F,planMode:ej,collaborationMode:ek,tokenMode:ey,toolApprovalMode:eb,permissionRules:ew,modeSettings:eg,approvalRequests:eP,handleCollaborationModeChange:oc,handleTokenModeChange:op,handleToolApprovalModeChange:ou,handlePermissionRulesChange:oh,resolveApproval:og,setActiveGoalText:om,goalState:eW,handleGoalStart:of,handleGoalPause:ox,handleGoalResume:ov,handleGoalStop:ok,handleGoalEdit:oy,slashCommands:tc,slashCommandsLoading:tu,queuedMessages:tT,pendingRecovery:tI,recoveryIsImport:tA,notices:tg.visible,extensionDialog:tv,extensionCustomUi:ty,extensionStatuses:tw,extensionWidgets:tS,respondToExtensionUi:rz,sendExtensionCustomInput:rI,agentPhase:ti,isNew:u,promptAnchorActive:tl,branchTree:oz,sessionIdRef:tq,eventSourceRef:tL,messagesEndRef:t7,scrollContainerRef:t9,lastUserMsgRef:t2,pendingScrollToUserRef:t6,initialScrollDoneRef:t1,scrollUserMsgToTop:ob,handleSend:rq,executeBash:rV,handleAbort:rK,handleFork:rG,handleNavigate:rJ,handleModelChange:rX,handleCompact:rZ,handleSteer:r2,handleFollowUp:r4,handlePromptWithStreamingBehavior:r6,handleAbortCompaction:r5,handleRecallQueue:r8,resolveRecovery:r3,exportQueueData:r7,importQueueData:r9,stageQueueImport:oe,moveQueuedMessage:ot,recallQueuedMessage:or,requeueAt:oo,removeQueuedMessage:on,handleBuiltinSlashCommand:r0,handleToolPresetChange:oi,handleThinkingLevelChange:os,loadTools:ry,loadSlashCommands:rj,reloadModels:rQ,setActiveLeafId:S,setData:m,setMessages:T,loadContext:rE,dispatch:W,setAgentRunning:U,setForkingEntryId:eK,handleLeafChange:rY,handleAgentEventRef:t0}}({session:e,newSessionCwd:t,onAgentEnd:N,onSessionCreated:i,onSessionForked:l,modelsRefreshKey:d,chatInputRef:c,onBranchDataChange:p,onSystemPromptChange:u,onSessionStatsPanelOpen:g}),[tj,tS]=(0,n.useState)(!1);(0,n.useEffect)(()=>{0===em.length&&tS(!1)},[em.length]);let{balance:tC,refresh:tT,refreshSoon:tR}=function(){let[e,t]=(0,n.useState)(null),[r,o]=(0,n.useState)(!1),s=(0,n.useRef)(null),i=(0,n.useRef)(null),a=(0,n.useRef)(!0);(0,n.useEffect)(()=>(a.current=!0,()=>{a.current=!1,i.current&&clearTimeout(i.current),s.current?.abort()}),[]);let l=(0,n.useRef)(null),d=(0,n.useCallback)(async()=>{s.current?.abort();let e=new AbortController;s.current=e;try{let r=await fetch("/api/deepseek/balance",{signal:e.signal,cache:"no-store"}),n=await r.json();if(!a.current)return;if(n?.available&&null!=n.totalBalance){let e=l.current;(null===e||e.available!==n.available||e.reason!==n.reason||e.currency!==n.currency||e.totalBalance!==n.totalBalance||e.grantedBalance!==n.grantedBalance||e.toppedUpBalance!==n.toppedUpBalance)&&(l.current=n,t(n)),o(!1)}else null===l.current&&o(!0)}catch{if(!a.current)return;null===l.current&&o(!0)}},[]),c=(0,n.useCallback)(()=>{i.current&&clearTimeout(i.current),i.current=setTimeout(()=>{i.current=null,d()},2e3)},[d]);return{balance:e,failed:r,refresh:d,refreshSoon:c}}(),tz=ed?.provider==="deepseek",tI=(0,n.useRef)(null);(0,n.useEffect)(()=>{tz&&tT()},[tz,tT]),(0,n.useEffect)(()=>{if(tz)for(let e=O.length-1;e>=0;e--){let t=O[e];if("assistant"!==t.role||!t.usage)continue;let r=`${e}:${B[e]??""}`;r!==tI.current&&(tI.current=r,tR());break}},[O,B,tz,tR]);let tM=(0,n.useMemo)(()=>{let e=O.findLast(e=>"assistant"===e.role&&!!e.usage);if(!e?.usage)return null;let t=e.usage;return{model:e.model??"",input:t.input??0,output:t.output??0,cacheRead:t.cacheRead??0,costCNY:aI(e.model)?aM(e.model,t):0,costUSD:aI(e.model)?0:t.cost?.total??0}},[O]),[tE,tA]=(0,n.useState)(!1),[tW,tN]=(0,n.useState)(null),tF=(0,n.useRef)(!1);(0,n.useEffect)(()=>{if(!ta){tF.current=!1;return}if(_){tF.current=!0;return}tF.current&&(tF.current=!1,tN(function(e){for(let t=e.length-1;t>=0;t--){let r=e[t];if("assistant"!==r.role)continue;let o=r.content;if("string"==typeof o&&o.trim())return o;if(Array.isArray(o)){let e=o.filter(e=>"text"===e.type).map(e=>e.text??"").join("\n").trim();if(e)return e}}for(let t=e.length-1;t>=0;t--){let r=e[t];if("toolResult"!==r.role)continue;let o=r.content,n="string"==typeof o?o:Array.isArray(o)?o.map(e=>e.text??"").join("\n"):"";if(!n)continue;let s=n.match(/\*\*Proposed Plan\*\*\s*\n+([\s\S]+)/i);if(s?.[1]?.trim())return s[1].trim()}return null}(O)??null),tA(!0))},[_,ta,O]);let tD=(0,n.useCallback)(()=>{tA(!1);let e=tL.current;e&&tc("plan"===tl?"normal":tl).catch(e=>{console.error("Failed to leave plan mode before executing:",e)}).then(()=>{eF(P("tasks.planReviewExecutePrompt",{plan:e}))})},[tc,eF,P,tl]),tL=(0,n.useRef)(null);(0,n.useEffect)(()=>{tL.current=tW},[tW]);let t$=(0,n.useCallback)(e=>{tA(!1),eF(e)},[eF]),tH=(0,n.useCallback)(()=>{tA(!1),tc("plan"===tl?"normal":tl)},[tc,tl]);(0,n.useEffect)(()=>{ev&&W.current!==ev.id&&(W.current=ev.id,A.current&&E.current())},[ev]),(0,n.useEffect)(()=>(a=_||q?eL:null,()=>void(a=null)),[_,q,eL]);let[tO,tB]=(0,n.useState)(!1),[tU,t_]=(0,n.useState)(!1),[tq,tV]=(0,n.useState)(!1),tK=(0,n.useCallback)(()=>{let e=eP.current;if(!e)return;let t=e.scrollHeight-e.scrollTop-e.clientHeight;tB(e.scrollTop>1),t_(t>1),tV(t>240)},[eP]),tG=(0,n.useCallback)(()=>{window.requestAnimationFrame(()=>{let e=eP.current,t=eM.current;if(!e||!t)return;let r=Math.max(88,c?.current?.measureHeight?.()??0),o=()=>{if(!e||!t)return;let o=Math.max(0,t.getBoundingClientRect().top-e.getBoundingClientRect().top+e.scrollTop-96-e.clientHeight+r);e.scrollTo({top:o,behavior:"auto"})};o(),tK(),window.setTimeout(o,200)})},[eM,eP,tK,c]);(0,n.useEffect)(()=>{let e=eP.current;if(!e)return;let t=new ResizeObserver(tK);return t.observe(e),e.firstElementChild&&t.observe(e.firstElementChild),e.addEventListener("scroll",tK,{passive:!0}),tK(),()=>{e.removeEventListener("scroll",tK),t.disconnect()}},[O.length,eP,tK]);let tJ=(0,n.useRef)(!1);(0,n.useEffect)(()=>{let t=eP.current;if(!t)return;let r=()=>{if(tJ.current||!tb||!ty||t.scrollTop>8)return;let r=e?.id;if(!r)return;tJ.current=!0;let o=t.scrollHeight-t.scrollTop;tw(r,eR,ty).finally(()=>{tJ.current=!1,requestAnimationFrame(()=>{let e=t.scrollHeight-o;Math.abs(t.scrollTop-e)>1&&t.scrollTo({top:e,behavior:"auto"})})})};return t.addEventListener("scroll",r,{passive:!0}),()=>t.removeEventListener("scroll",r)},[eP,ty,tb,tw,e?.id,eR]);let tY=(0,n.useRef)(!1);(0,n.useEffect)(()=>{if(!tb||!ty)return;let t=eP.current,r=e?.id;if(!t||!r||tJ.current||tY.current||$||t.scrollTop>8||t.scrollHeight>t.clientHeight+50)return;tY.current=!0;let o=t.scrollHeight-t.scrollTop;tw(r,eR,ty).finally(()=>{tY.current=!1,requestAnimationFrame(()=>{let e=t.scrollHeight-o;Math.abs(t.scrollTop-e)>1&&t.scrollTo({top:e,behavior:"auto"})})})},[eP,ty,tb,tw,e?.id,eR,$,O.length]);let tX=(0,n.useRef)(null),tZ=(0,n.useRef)([]),tQ=(0,n.useRef)(new Map),t0=(0,n.useRef)(null),[t1,t2]=(0,n.useState)(0);(0,n.useEffect)(()=>{let e=t0.current;if(!e)return void t2(e=>0===e?e:0);let t=()=>{let t=Math.round(e.getBoundingClientRect().height);t2(e=>e===t?e:t)};t();let r=new ResizeObserver(t);return r.observe(e),()=>r.disconnect()},[]);let t6=(0,n.useMemo)(()=>({getOffsetForIndex:e=>tX.current?.getOffsetForIndex(e)?.[0]??0,sizeFor:e=>{let t=tX.current;if(!t)return 0;let r=t.measurementsCache[e];return r?.size??t.options.estimateSize?.(e)??0},totalHeight:()=>tX.current?.getTotalSize()??0,refToItemIndex:e=>tZ.current[e],itemCount:tZ.current.length}),[]),t4=ec?[ec.sessionId,ec.sessionFile??"",ec.sessionName??"",ec.userMessages,ec.assistantMessages,ec.toolCalls,ec.toolResults,ec.totalMessages,ec.tokens.input,ec.tokens.output,ec.tokens.cacheRead,ec.tokens.cacheWrite,ec.tokens.total,ec.cost??0,ec.totalActiveMs??0].join("|"):null,t5=(0,n.useRef)(ec);t5.current=ec,(0,n.useEffect)(()=>{h?.(t5.current)},[t4,h]),(0,n.useEffect)(()=>()=>{h?.(null)},[h]);let t8=en?`${en.percent??"null"}|${en.contextWindow}|${en.tokens??"null"}`:null,t3=(0,n.useRef)(en);t3.current=en,(0,n.useEffect)(()=>{m?.(t3.current)},[t8,m]),(0,n.useEffect)(()=>()=>{m?.(null)},[m]);let{isDragOver:t7,handleDragEnter:t9,handleDragOver:re,handleDragLeave:rt,handleDrop:rr}=function(e){let[t,r]=(0,n.useState)(!1),o=(0,n.useRef)(0),s=(0,n.useCallback)(e=>{e.dataTransfer.files.length&&(e.preventDefault(),o.current+=1,r(!0))},[]),i=(0,n.useCallback)(e=>{e.dataTransfer.files.length&&e.preventDefault()},[]);return{isDragOver:t,handleDragEnter:s,handleDragOver:i,handleDragLeave:(0,n.useCallback)(()=>{o.current-=1,o.current<=0&&(o.current=0,r(!1))},[]),handleDrop:(0,n.useCallback)(t=>{t.preventDefault(),o.current=0,r(!1),e(Array.from(t.dataTransfer.files),t.dataTransfer)},[e])}}((0,n.useCallback)((e,t)=>{if(_){let t=e.filter(e=>e.type.startsWith("image/"));t.length&&c?.current?.addImages(t);return}c?.current?.addFiles(e,t)},[_,c])),ro=O.filter(e=>"user"===e.role||"assistant"===e.role),rn=(0,n.useMemo)(()=>{let e=new Set,t=[];for(let o=O.length-1;o>=0&&t.length<50;o-=1){var r;let n="user"!==(r=O[o]).role?null:("string"==typeof r.content?r.content:r.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n")).trim()||null;!n||e.has(n)||(e.add(n),t.push(n))}return t},[O]),rs=(S=ro.length,(C=(0,n.useRef)([])).current.length!==S&&(C.current=Array.from({length:S},(e,t)=>C.current[t]??null)),C),ri=eC&&0===O.length&&!U.isStreaming&&!_,ra=e?.cwd??t??void 0,rl=(0,n.useMemo)(()=>(function(e,t,r){let o=new Map;for(let t of e)"toolResult"===t.role&&o.set(t.toolCallId,t);let n=-1;for(let t=e.length-1;t>=0;t--)if("user"===e[t].role){n=t;break}let s=new Map,i=0;e.forEach((e,t)=>{("user"===e.role||"assistant"===e.role)&&s.set(t,i++)});let a=[];for(let n=0;n<e.length;){let s,i=e[n],l="custom"===i.role&&"compaction"===i.customType;if(0===n&&"user"!==i.role&&!l){let r=1;for(;r<e.length&&"user"!==e[r].role;)r+=1;let s=Array.from({length:r},(e,t)=>t).filter(t=>ie(e[t])),i=s5(e,t,s,o);if(i.length>0){a.push({kind:"turn",userIdx:-1,endIdx:r,startsCompactionTurn:!1,finalAssistantIdx:-1,visibleProcessIndices:s,processBlocks:i,processSegments:s0(i),finalAnswerMessage:null,writtenFiles:void 0}),n=r;continue}}if("user"!==i.role&&!l){a.push({kind:"single",idx:n}),n+=1;continue}let d=n,c=d+1;for(;c<e.length&&"user"!==e[c].role;)c+=1;let p=function(e,t,r){for(let n=r-1;n>t;n--){var o;if("assistant"===(o=e[n]).role&&sX(o).answerBlocks.some(e=>"image"===e.type||"text"===e.type&&e.text.trim().length>0))return n}for(let o=r-1;o>t;o--)if(e[o]?.role==="assistant")return o;return -1}(e,d,c);if(-1===p){let r=Array.from({length:c-d-1},(e,t)=>d+1+t).filter(t=>ie(e[t])),s=s5(e,t,r,o);a.push({kind:"turn",userIdx:d,endIdx:c,startsCompactionTurn:l,finalAssistantIdx:p,visibleProcessIndices:r,processBlocks:s,processSegments:s0(s),finalAnswerMessage:null,writtenFiles:void 0}),n=c;continue}let u=[];for(let e=d+1;e<p;e++)u.push(e);let h=u.filter(t=>ie(e[t])),g=e[p],m=sX(g),f=m.processBlocks.length>0?it(g,m.processBlocks,{omitUsage:!0}):null,x=m.answerBlocks.length>0?it(g,m.answerBlocks):null,v=s5(e,t,h,o);if(f&&(v=v.concat(s4(g,{messageIndex:p,entryId:t[p],toolResults:o}).processBlocks)),x){let t=[];for(let r=d+1;r<=p;r++){let o=e[r];if(o?.role==="assistant")for(let e of o.content??[])t.push(e)}s=function(e,t,r){let o=new Set,n=[];for(let s of e){if("toolCall"!==s.type||!function(e){let t,r;return"write"===(t=e.toLowerCase())||t.startsWith("write_")||t.endsWith(".write")||t.endsWith("_write")||"edit"===(r=e.toLowerCase())||r.startsWith("edit_")||r.endsWith(".edit")||r.endsWith("_edit")||r.includes("str_replace")||r.includes("replace_editor")}(s.toolName))continue;let e=t?.get(s.toolCallId);if(!e||e.isError)continue;let i=function(e){if(!e)return null;let t=e.file_path??e.path;return"string"==typeof t&&t.length>0?t:null}(s.input);if(!i)continue;let a=function(e,t){let r;if(!e)return null;let o=/^[a-zA-Z]:[\\/]/.test(e)||e.startsWith("\\\\")||void 0!==t&&(/^[a-zA-Z]:[\\/]/.test(t)||t.startsWith("\\\\")),n=e=>o?e.replace(/\\/g,"/"):e,s=n(e),i=t?n(t).replace(/\/+$/,""):void 0,a=/^[a-zA-Z]:\//.test(s),l=s.startsWith("//");if(a||l)r=s;else if(s.startsWith("/")){let e=i?.match(/^([a-zA-Z]:)(?:\/|$)/)?.[1]??i?.match(/^(\/\/[^/]+\/[^/]+)(?:\/|$)/)?.[1];r=e?`${e}${s}`:s}else{if(!i)return null;r=`${i}/${s}`}return s7(r)}(i,r);a&&(o.has(a)||(o.add(a),n.push({filePath:a})))}return n}(t,o,r)}a.push({kind:"turn",userIdx:d,endIdx:c,startsCompactionTurn:l,finalAssistantIdx:p,visibleProcessIndices:h,processBlocks:v,processSegments:s0(v),finalAnswerMessage:x,writtenFiles:s}),n=c}return{toolResultsMap:o,lastUserIdx:n,visibleRefIndexByMessage:s,items:a}})(O,B,ra),[O,B,ra]),rd=ed?Y[`${ed.provider}:${ed.modelId}`]??null:null,rc=ed?X[`${ed.provider}:${ed.modelId}`]??null:null,rp=(0,n.useCallback)(()=>{ee()},[ee]),ru=(0,n.useCallback)(e=>{tc(e)},[tc]),rh=e?.relation?.kind==="subagent"?(0,o.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",gap:8,padding:"14px 16px",borderTop:"1px solid var(--border)",color:"var(--text-dim)",fontSize:12},children:[(0,o.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,o.jsx)("rect",{x:"3",y:"11",width:"18",height:"10",rx:"2"}),(0,o.jsx)("circle",{cx:"12",cy:"5",r:"2"}),(0,o.jsx)("path",{d:"M12 7v4"})]}),P("subagent.readOnlyNotice")]}):(0,o.jsx)(dA,{ref:c,onSend:eF,onBash:eD,tasksBoardEnabled:y,onAbort:eL,onSteer:_?eU:void 0,onFollowUp:_?e_:void 0,onPromptWithStreamingBehavior:_?eq:void 0,isStreaming:_,model:ed,modelNames:K,modelList:G,modelScopeWarnings:Z,modelsError:Q,onRetryModels:rp,onModelChange:eO,compactResult:el,toolPreset:et,onToolPresetChange:e||eC?tn:void 0,collaborationMode:tl,toolApprovalMode:td,onCollaborationModeChange:ru,goalState:tg,onGoalStart:tm,onGoalPause:tf,onGoalResume:tx,onGoalStop:tv,thinkingLevel:er,onThinkingLevelChange:e||eC?ts:void 0,availableThinkingLevels:rd,thinkingLevelMap:rc,retryInfo:eo,queuedMessages:eg,inputHistory:rn,onRecallQueue:eK,onMoveQueue:eX,onRecallOne:eZ,onRequeueAt:tt,onRemoveQueueItem:tr,slashCommands:eu,slashCommandsLoading:eh,onLoadSlashCommands:ti,onBuiltinCommand:to,onAudioUnlock:I,draftKey:e?.id??(t?`new:${t}`:void 0),cwd:e?.cwd??t}),rg=eb.filter(e=>"belowEditor"!==e.placement),rm=eb.filter(e=>"belowEditor"===e.placement),rf=ei?P("desktop.compacting"):function(e,t){if(e?.kind==="running_tools"){let r=e.tools.map(e=>e.name);return 0===r.length?t("desktop.runningTool"):t("desktop.runningTools",{tools:r.length<=3?r.join(", "):`${r.slice(0,2).join(", ")} (+${r.length-2})`})}return e?.kind==="waiting_model"?t("desktop.waitingForModel"):e?.kind==="running_command"?t("desktop.runningCommand"):null}(eS,P);return $?(0,o.jsx)("div",{className:"flex h-full items-center justify-center text-text-muted",children:P("desktop.loadingSession")}):H?(0,o.jsx)("div",{className:"flex h-full items-center justify-center text-red-400",children:H}):(0,o.jsxs)("div",{className:"relative flex h-full min-w-0 flex-col overflow-hidden",onDragEnter:t9,onDragOver:re,onDragLeave:rt,onDrop:rr,children:[t7&&(0,o.jsxs)("div",{className:"pointer-events-none absolute inset-0 z-50 flex animate-[drop-zone-in_0.15s_ease_both] items-center justify-center bg-[rgba(37,99,235,0.06)] backdrop-blur-[1px]",children:[(0,o.jsx)("div",{className:"pointer-events-none absolute inset-0 flex items-center justify-center",children:[0,.8,1.6].map(e=>(0,o.jsx)("div",{className:"absolute h-[720px] w-[720px] rounded-full border-[1.5px] border-solid border-[rgba(37,99,235,0.5)] animate-[drop-ripple_2.4s_ease-out_infinite_backwards]",style:{transformOrigin:"center",animationDelay:`${e}s`}},e))}),(0,o.jsxs)("svg",{width:"280",height:"280",viewBox:"0 0 140 140",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:"drop-shadow-[0_6px_18px_rgba(37,99,235,0.18)]",children:[(0,o.jsx)("rect",{x:"28",y:"44",width:"84",height:"60",rx:"8",fill:"rgba(37,99,235,0.08)",stroke:"rgba(37,99,235,0.50)",strokeWidth:"1.8"}),(0,o.jsx)("path",{d:"M36 100 L54 72 L68 88 L80 74 L104 100Z",fill:"rgba(37,99,235,0.16)",stroke:"rgba(37,99,235,0.40)",strokeWidth:"1.4",strokeLinejoin:"round"}),(0,o.jsx)("circle",{cx:"96",cy:"58",r:"8",fill:"rgba(37,99,235,0.22)",stroke:"rgba(37,99,235,0.55)",strokeWidth:"1.6"}),(0,o.jsxs)("g",{stroke:"rgba(37,99,235,0.45)",strokeWidth:"1.4",strokeLinecap:"round",children:[(0,o.jsx)("line",{x1:"96",y1:"46",x2:"96",y2:"43"}),(0,o.jsx)("line",{x1:"96",y1:"70",x2:"96",y2:"73"}),(0,o.jsx)("line",{x1:"84",y1:"58",x2:"81",y2:"58"}),(0,o.jsx)("line",{x1:"108",y1:"58",x2:"111",y2:"58"}),(0,o.jsx)("line",{x1:"87.5",y1:"49.5",x2:"85.4",y2:"47.4"}),(0,o.jsx)("line",{x1:"104.5",y1:"66.5",x2:"106.6",y2:"68.6"}),(0,o.jsx)("line",{x1:"104.5",y1:"49.5",x2:"106.6",y2:"47.4"}),(0,o.jsx)("line",{x1:"87.5",y1:"66.5",x2:"85.4",y2:"68.6"})]})]})]}),ev&&(0,o.jsx)(cg,{request:ev,onRespond:ew}),ek&&(0,o.jsx)(cm,{request:ek,onInput:ej}),!eC&&em.length>0&&!tj&&(0,o.jsx)(dF,{items:em,sessionId:e?.id,onResolve:eG,onExport:eJ,onStageImport:eY,onDismiss:()=>tS(!0),mode:ef?"import":"recovery"}),tp.length>0&&(0,o.jsx)(le,{request:tp[0]??null,queuedCount:Math.max(0,tp.length-1),busy:!1,onResolve:(e,t)=>{let r=tp[0];r&&th(r.id,e,t)}}),ri?(0,o.jsx)("div",{className:"flex flex-1 flex-col items-center justify-center overflow-y-auto",children:(0,o.jsxs)("div",{className:"w-full max-w-[820px]",children:[(0,o.jsx)("div",{style:{display:"flex",justifyContent:"center",marginBottom:28},children:(0,o.jsxs)("svg",{fill:"currentColor",fillRule:"evenodd",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",style:{width:64,height:64,color:"var(--accent)",opacity:.85},"aria-label":"Pi",children:[(0,o.jsx)("title",{children:"Pi"}),(0,o.jsx)("path",{clipRule:"evenodd",d:"M1 1h16.5v11H12v5.5H6.5V23H1V1zm5.5 5.5V12H12V6.5H6.5z"}),(0,o.jsx)("path",{d:"M17.5 12H23v11h-5.5V12z"})]})}),M&&(0,o.jsxs)("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",gap:10,marginBottom:18,marginTop:-14},children:[(0,o.jsxs)("span",{style:{fontSize:11,color:"var(--text-muted)",fontFamily:"var(--font-mono)"},children:["web ",(0,o.jsxs)("span",{style:{color:"var(--text)"},children:["v","0.17.9"]})]}),(0,o.jsxs)("span",{style:{fontSize:11,color:"var(--text-muted)",fontFamily:"var(--font-mono)"},children:["pi ",(0,o.jsxs)("span",{style:{color:"var(--text)"},children:["v","0.85.1"]})]})]}),(0,o.jsx)("div",{style:{padding:"0 34px 6px 7px",paddingRight:M?16:34},children:(0,o.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12},children:[(0,o.jsx)("div",{ref:x,style:{display:"flex",alignItems:"center",minWidth:0,flex:1,minHeight:48}}),(0,o.jsxs)("div",{style:{display:M?"none":"flex",flexDirection:"column",alignItems:"flex-end",gap:2,flexShrink:0},children:[(0,o.jsxs)("span",{style:{fontSize:11,color:"var(--text-muted)",fontFamily:"var(--font-mono)"},children:["web ",(0,o.jsxs)("span",{style:{color:"var(--text)"},children:["v","0.17.9"]})]}),(0,o.jsxs)("span",{style:{fontSize:11,color:"var(--text-muted)",fontFamily:"var(--font-mono)"},children:["pi ",(0,o.jsxs)("span",{style:{color:"var(--text)"},children:["v","0.85.1"]})]})]})]})}),(0,o.jsx)("div",{style:{padding:"0 16px",paddingRight:M?16:34},children:(0,o.jsx)(ch,{notices:ex,align:"right"})}),"goal"===tl&&(0,o.jsx)(a7,{goalState:tg,onPause:tf,onResume:tx,onStop:tv,onEdit:tk}),rh,(0,o.jsx)("div",{style:{padding:"0 16px 6px",paddingRight:M?16:34,marginTop:-15},children:(0,o.jsx)(dG,{onViewFullHistory:v,cwd:ra,systemPrompt:k,sessionStats:ec,contextUsage:en,hasSession:!!e,showChat:!0,showSoundLabel:!0,soundEnabled:T,onSoundToggle:R,onCompact:e?eB:void 0,onAbortCompaction:eV,isCompacting:ei,compactError:ea,isDeepSeekOfficial:tz,deepseekBalance:tC,lastTurnUsage:tM})})]})}):(0,o.jsxs)(o.Fragment,{children:[(0,o.jsxs)("div",{className:"relative flex flex-1 overflow-hidden z-0",children:[(0,o.jsx)("div",{style:{position:"absolute",top:12,left:0,right:18*!M,zIndex:40,padding:"0 16px",pointerEvents:"none"},children:(0,o.jsx)("div",{style:{maxWidth:820,margin:"0 auto"},children:(0,o.jsx)(ch,{notices:ex,floating:!0,align:"right"})})}),(0,o.jsxs)("div",{className:"relative flex-1 min-h-0 min-w-0",children:[(0,o.jsx)("div",{ref:eP,className:"h-full min-w-0 overflow-x-hidden overflow-y-auto pt-4 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden",children:(0,o.jsx)("div",{style:{minWidth:0,padding:"0 16px"},children:(0,o.jsxs)("div",{style:{width:"100%",minWidth:0,maxWidth:820,margin:"0 auto"},children:[(0,o.jsxs)("div",{ref:t0,children:[(0,o.jsx)(cp,{statuses:ey}),(0,o.jsx)(cu,{widgets:rg})]}),(()=>{let{toolResultsMap:t,lastUserIdx:r,visibleRefIndexByMessage:n,items:s}=rl,i=tQ.current,a=(s,a={})=>{let l=a.messageOverride??O[s];if(!l||"toolResult"===l.role)return null;let d="user"===l.role&&s>0&&"assistant"===O[s-1].role?B[s-1]:void 0,c="user"===l.role||"assistant"===l.role,p=n.get(s),u=a.keyPrefix??"message",h=!1;if("assistant"===l.role){h=!0;for(let e=s+1;e<O.length;e++){let t=O[e].role;if("user"===t)break;if("assistant"===t){h=!1;break}}h&&U.isStreaming&&s===O.length-1&&(h=!1)}void 0!==a.showTimestamp&&(h=a.showTimestamp);let g=(0,o.jsx)(aF,{message:l,toolResults:t,modelNames:K,cwd:ra,onOpenFile:f,entryId:B[s],onFork:_||eC||0===s&&"user"===l.role?void 0:e$,forking:es===B[s],onNavigate:_?void 0:eH,prevAssistantEntryId:_?void 0:d,onEditContent:F,onQuoteReply:D,onOpenSession:b,onCreateTask:L,showTimestamp:h,prevTimestamp:s>0?O[s-1].timestamp:void 0,sessionId:e?.id??eI.current??void 0,writtenFiles:a.writtenFiles},`${u}-view-${s}`);return c&&!1!==a.attachRef&&void 0!==p?(0,o.jsx)("div",{ref:((e,t)=>{let o=i.get(t);if(!o){let e={isLastUser:!1};o={state:e,callback:r=>{rs.current[t]=r,e.isLastUser&&(eE.current=r,r&&eA.current&&(eA.current=!1,eW.current=!0,eN()))}},i.set(t,o)}return o.state.isLastUser=e===r,o.callback})(s,p),children:g},`${u}-${s}`):g},l=[],d=[],c=[],p=(e,t,r)=>{null!==e&&(l.push(e),d.push(t),c.push(r))},u=(e,t)=>B[e]||`${t}-${e}`,h=e=>`live-answer-u${e}`,g=e=>`answer-${u(e,"user")}`,m=e=>`subagent-${e}`,x=e=>sQ(e.result?.details)?e.result.details.sessionId:"",v=(e,t)=>`live-process-u${e}-seg${t}`,k=(e,t,r)=>`process-${u(e,"user")}-${r||`seg${t}`}`;for(let i of s){if("single"===i.kind){if(O[i.idx]?.role==="toolResult")continue;p(a(i.idx),n.get(i.idx),u(i.idx,"single"));continue}let{userIdx:s,endIdx:l,startsCompactionTurn:d,finalAssistantIdx:c}=i;if((_||U.isStreaming)&&l===O.length&&(s===r||d)){s>=0&&p(a(s),n.get(s),u(s,"user"));let r=U.streamingMessage?.role==="assistant",i=[],d=!r&&c>=0?c:l;for(let e=s+1;e<d;e++)ie(O[e])&&i.push(e);let g=s5(O,B,i,t),k=null;if(!r&&c>=0){let e=O[c],r=sX(e,{isStreaming:!0}),o=s4(e,{messageIndex:c,entryId:B[c],toolResults:t,isStreaming:!0});g=g.concat(o.processBlocks),r.answerBlocks.length>0&&(k=it(e,r.answerBlocks,{omitUsage:!0}))}if(r){let e=U.streamingMessage,r=sX(e,{isStreaming:!0}),o=s4(e,{messageIndex:O.length,toolResults:t,isStreaming:!0});g=g.concat(o.processBlocks),r.answerBlocks.length>0&&(k=it(e,r.answerBlocks,{omitUsage:!0}))}if(g.length>0){let t=i.map(e=>n.get(e)).find(e=>"number"==typeof e);s0(g).forEach((r,n)=>{"subagent"===r.kind&&r.subagent?p((0,o.jsx)(lY,{run:r.subagent,onOpenSubagent:w,sessionRun:j?.get(x(r.subagent))},m(r.subagent.toolCallId)),t,m(r.subagent.toolCallId)):p((0,o.jsx)("div",{ref:void 0===t?void 0:e=>{rs.current[t]=e},children:(0,o.jsx)(lK,{blocks:r.blocks,isStreaming:_||U.isStreaming,cwd:ra,onOpenFile:f,sessionId:e?.id??eI.current??void 0,tokenRate:ep})},v(s,n)),t,v(s,n))})}k&&p((0,o.jsx)(aF,{message:k,isStreaming:!0,modelNames:K,cwd:ra,onOpenFile:f,onQuoteReply:D,onOpenSession:b},`live-answer-${s}`),c>=0?n.get(c):void 0,h(s));continue}if(-1===c&&0===i.processBlocks.length){if(s>=0)for(let e=s;e<l;e++)p(a(e),n.get(e),u(e,"raw"));continue}s>=0&&p(a(s),n.get(s),u(s,"user"));let{finalAnswerMessage:y,writtenFiles:S,visibleProcessIndices:C}=i;if(i.processBlocks.length>0){let t=C.map(e=>n.get(e)).find(e=>"number"==typeof e)??(y?void 0:n.get(c));i.processSegments.forEach((r,n)=>{"subagent"===r.kind&&r.subagent?p((0,o.jsx)(lY,{run:r.subagent,onOpenSubagent:w,sessionRun:j?.get(x(r.subagent))},m(r.subagent.toolCallId)),t,m(r.subagent.toolCallId)):p((0,o.jsx)("div",{ref:void 0===t?void 0:e=>{rs.current[t]=e},children:(0,o.jsx)(lK,{blocks:r.blocks,isStreaming:!1,defaultExpanded:!1,onAutoExpanded:void 0,cwd:ra,onOpenFile:f,sessionId:e?.id??eI.current??void 0})},`process-group-${s}-${n}`),t,k(s,n,r.blocks[0]?.id??""))})}if(y&&p(a(c,{messageOverride:y,writtenFiles:S}),n.get(c),g(s)),c>=0)for(let e=c+1;e<l;e++)p(a(e),n.get(e),u(e,"tail"))}let y=[],S=d.map((e,t)=>({startRef:e,itemIdx:t})).filter(e=>void 0!==e.startRef);return S.forEach((e,t)=>{let r=S[t+1]?.startRef??ro.length;for(let t=e.startRef;t<r;t++)y[t]=e.itemIdx}),tZ.current=y,(0,o.jsx)(dY,{scrollElementRef:eP,items:l,itemKeys:c,virtualizerRef:tX,headerHeight:t1})})(),rf&&(ei||_&&!U.streamingMessage)&&(0,o.jsx)("div",{className:"py-2 text-[13px] text-text-muted",children:(0,o.jsxs)("span",{className:"animate-[pulse_1.5s_infinite]",children:[rf,eS?.kind==="waiting_model"&&(0,o.jsx)("span",{style:{display:"inline-block",width:12,height:12,marginLeft:6,verticalAlign:"-2px",border:"1.5px solid var(--text-muted)",borderTopColor:"transparent",borderRadius:"50%",animation:"spin 0.6s linear infinite"}})]})}),V&&(0,o.jsx)(aF,{message:{role:"bashExecution",command:V.command,output:"",excludeFromContext:V.excludeFromContext},sessionId:e?.id??eI.current??void 0}),q&&!V&&(0,o.jsx)("div",{className:"py-2 text-[13px] text-text-muted",children:(0,o.jsx)("span",{className:"animate-[pulse_1.5s_infinite]",children:P("desktop.runningShellCommand")})}),(0,o.jsx)("div",{style:{height:96}}),(0,o.jsx)("div",{ref:eM}),(0,o.jsx)(a2,{open:tE,planText:tW,busy:_,onExecute:tD,onFeedback:t$,onExit:tH,onClose:()=>tA(!1)})]})})}),tO&&(0,o.jsx)("div",{"aria-hidden":"true",className:"pointer-events-none absolute inset-x-0 top-0 z-10 h-8 bg-gradient-to-b from-[var(--bg)] to-transparent"}),tU&&(0,o.jsx)("div",{"aria-hidden":"true",className:"pointer-events-none absolute inset-x-0 bottom-0 z-10 h-8 bg-gradient-to-t from-[var(--bg)] to-transparent"}),tq&&(0,o.jsxs)("button",{type:"button",onClick:()=>tG(),title:P("desktop.scrollToBottom"),"aria-label":P("desktop.scrollToBottom"),style:{position:"absolute",bottom:14,right:18,zIndex:20,display:"flex",alignItems:"center",gap:6,padding:"5px 10px",border:"1px solid var(--border)",borderRadius:999,background:"color-mix(in srgb, var(--bg-panel) 92%, transparent)",color:"var(--text-muted)",fontSize:11,fontWeight:600,cursor:"pointer",boxShadow:"0 4px 14px rgba(0,0,0,0.14)",backdropFilter:"blur(4px)",transition:"color 0.12s, border-color 0.12s, background 0.12s"},onMouseEnter:e=>{e.currentTarget.style.color="var(--accent)",e.currentTarget.style.borderColor="var(--accent)"},onMouseLeave:e=>{e.currentTarget.style.color="var(--text-muted)",e.currentTarget.style.borderColor="var(--border)"},children:[(0,o.jsx)(aw.Z,{size:12,weight:"bold","aria-hidden":"true"}),P("desktop.scrollToBottom")]})]}),M?null:(0,o.jsx)(dQ,{messages:O,streamingMessage:U.streamingMessage,scrollContainer:eP,messageRefs:rs,virtualizer:t6})]}),(0,o.jsxs)("div",{className:"relative z-10",children:[(0,o.jsx)("div",{style:{padding:"0 16px",paddingRight:M?16:34},children:(0,o.jsx)("div",{style:{maxWidth:820,margin:"0 auto"},children:(0,o.jsx)(cu,{widgets:rm})})}),rh,(0,o.jsx)("div",{className:`session-info-bar-wrap${M?" is-mobile":""}`,children:(0,o.jsx)("div",{className:"session-info-bar-inner",children:(0,o.jsx)(dG,{onViewFullHistory:v,cwd:ra,systemPrompt:k,sessionStats:ec,contextUsage:en,hasSession:!!e,showChat:!0,soundEnabled:T,onSoundToggle:R,onCompact:e?eB:void 0,onAbortCompaction:eV,isCompacting:ei,compactError:ea,branchTree:eT,branchActiveLeafId:eR,onBranchLeafChange:ez,isDeepSeekOfficial:tz,deepseekBalance:tC,lastTurnUsage:tM})})})]})]})]})}function cp({statuses:e}){return 0===e.length?null:(0,o.jsx)("div",{style:{display:"flex",flexWrap:"wrap",gap:6,marginBottom:10},children:e.map(e=>(0,o.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6,maxWidth:"100%",padding:"4px 8px",border:"1px solid color-mix(in srgb, var(--accent) 24%, var(--border))",borderRadius:6,background:"color-mix(in srgb, var(--accent) 7%, var(--bg))",color:"var(--text-muted)",fontSize:12},children:[(0,o.jsx)("span",{style:{color:"var(--accent)",fontFamily:"var(--font-mono)",fontSize:11},children:e.key}),(0,o.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.text})]},e.key))})}function cu({widgets:e}){return 0===e.length?null:(0,o.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:8,marginBottom:10},children:e.map(e=>(0,o.jsxs)("div",{style:{border:"1px solid var(--border)",borderRadius:7,background:"var(--bg-panel)",overflow:"hidden"},children:[(0,o.jsx)("div",{style:{padding:"5px 9px",borderBottom:"1px solid var(--border)",color:"var(--text-dim)",fontSize:11,fontFamily:"var(--font-mono)"},children:e.key}),(0,o.jsx)("pre",{style:{margin:0,padding:"8px 9px",color:"var(--text-muted)",fontSize:12,lineHeight:1.5,whiteSpace:"pre-wrap",wordBreak:"break-word",fontFamily:"var(--font-mono)"},children:e.lines.join("\n")})]},e.key))})}function ch({notices:e,floating:t=!1,align:r="left"}){return 0===e.length?null:(0,o.jsx)("div",{style:{display:"flex",flexDirection:"column",alignItems:"right"===r?"flex-end":"stretch",marginBottom:10*!t},children:e.map((r,n)=>{let s="error"===r.type?"var(--status-error)":"warning"===r.type?"var(--status-warning)":"success"===r.type?"#10b981":"var(--accent)";return(0,o.jsxs)("div",{className:"notice-shelf-item",style:{display:"flex",alignItems:"center",gap:10,minHeight:44,maxHeight:180,marginBottom:6*(n!==e.length-1),overflowY:"auto",overflowX:"hidden",borderRadius:14,border:"1px solid color-mix(in srgb, var(--border) 70%, transparent)",background:"var(--bg)",color:"var(--text-muted)",width:"fit-content",maxWidth:"min(100%, 620px)",boxShadow:t?"0 1px 2px rgba(15,23,42,0.05), 0 10px 28px -14px rgba(15,23,42,0.24)":"0 1px 2px rgba(15,23,42,0.04), 0 8px 24px -12px rgba(15,23,42,0.10)",fontSize:13,lineHeight:1.45,transformOrigin:"top center",animation:r.exiting?"notice-shelf-out 0.18s ease-in forwards":"notice-shelf-in 0.18s ease-out both",padding:"0 12px"},children:[(0,o.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:s,flexShrink:0}}),(0,o.jsx)("span",{style:{padding:"10px 0",minWidth:0,maxWidth:"100%",overflowWrap:"anywhere",whiteSpace:"pre-wrap"},children:r.message})]},r.id)})})}function cg({request:e,onRespond:t}){let{t:r}=(0,J.s)(),[s,i]=(0,n.useState)("editor"===e.method?e.prefill??"":"");(0,n.useEffect)(()=>{i("editor"===e.method?e.prefill??"":"")},[e]);let a=()=>{"confirm"===e.method?t(e,{confirmed:!0}):t(e,{value:s})};return(0,o.jsx)("div",{style:{position:"absolute",inset:0,zIndex:90,display:"flex",alignItems:"center",justifyContent:"center",padding:20,background:"rgba(0,0,0,0.18)"},children:(0,o.jsxs)("div",{role:"dialog","aria-modal":"true",style:{width:"min(560px, 100%)",border:"1px solid var(--border)",borderRadius:8,background:"var(--bg)",boxShadow:"0 20px 60px rgba(0,0,0,0.28)",overflow:"hidden"},children:[(0,o.jsxs)("div",{style:{padding:"12px 14px",borderBottom:"1px solid var(--border)"},children:[(0,o.jsx)("div",{style:{color:"var(--text)",fontSize:14,fontWeight:650},children:e.title}),(0,o.jsx)("div",{style:{marginTop:3,color:"var(--text-dim)",fontSize:11,fontFamily:"var(--font-mono)"},children:r("desktop.extensionRequest")})]}),(0,o.jsxs)("div",{style:{padding:14},children:["confirm"===e.method&&(0,o.jsx)("div",{style:{color:"var(--text-muted)",fontSize:13,lineHeight:1.6,whiteSpace:"pre-wrap"},children:e.message}),"select"===e.method&&(0,o.jsx)("div",{style:{display:"grid",gap:8},children:e.options.map(r=>(0,o.jsx)("button",{onClick:()=>t(e,{value:r}),style:{width:"100%",padding:"9px 10px",borderRadius:7,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text)",cursor:"pointer",textAlign:"left",fontSize:13},children:r},r))}),"input"===e.method&&(0,o.jsx)("input",{autoFocus:!0,value:s,placeholder:e.placeholder,onChange:e=>i(e.target.value),onKeyDown:r=>{"Enter"===r.key&&a(),"Escape"===r.key&&t(e,{cancelled:!0})},style:{width:"100%",padding:"9px 10px",borderRadius:7,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text)",outline:"none",fontSize:13}}),"editor"===e.method&&(0,o.jsx)("textarea",{autoFocus:!0,value:s,onChange:e=>i(e.target.value),onKeyDown:r=>{"Escape"===r.key&&t(e,{cancelled:!0}),(r.metaKey||r.ctrlKey)&&"Enter"===r.key&&a()},style:{width:"100%",minHeight:220,padding:10,borderRadius:7,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text)",outline:"none",resize:"vertical",fontSize:13,lineHeight:1.55,fontFamily:"var(--font-mono)"}})]}),(0,o.jsxs)("div",{style:{display:"flex",justifyContent:"flex-end",gap:8,padding:"10px 14px",borderTop:"1px solid var(--border)",background:"var(--bg-panel)"},children:[(0,o.jsx)("button",{onClick:()=>t(e,{cancelled:!0}),style:{padding:"6px 10px",borderRadius:6,border:"1px solid var(--border)",background:"var(--bg)",color:"var(--text-muted)",cursor:"pointer"},children:r("desktop.cancel")}),"confirm"===e.method?(0,o.jsx)("button",{onClick:a,style:{padding:"6px 10px",borderRadius:6,border:"1px solid var(--accent)",background:"var(--accent)",color:"#fff",cursor:"pointer"},children:r("desktop.confirm")}):"select"!==e.method?(0,o.jsx)("button",{onClick:a,style:{padding:"6px 10px",borderRadius:6,border:"1px solid var(--accent)",background:"var(--accent)",color:"#fff",cursor:"pointer"},children:r("desktop.submit")}):null]})]})})}function cm({request:e,onInput:t}){let{t:r}=(0,J.s)(),s=(0,n.useRef)(null),i=function(e){let t=/^[┌├└╭╰][─┬┴┼]+[┐┤┘╮╯]$/,r=[];for(let o of e){let e=sq(o).trimEnd();if(t.test(e))continue;let n=o,s=sG(n);("│"===s||"┃"===s)&&" "===sG(n=sK(n,0))&&(n=sK(n,0));let i=function(e){let t=sV(e);for(let e=t.length-1;e>=0;e--)if(""!==t[e].char.trim())return e;return -1}(n),a=i>=0?sV(n)[i]?.char:void 0;("│"===a||"┃"===a)&&(n=sK(n,i)),r.push(function(e){let t=e;for(;;){let e=sV(t),r=e[e.length-1];if(!r||""!==r.char.trim())return t;t=t.slice(0,r.start)+t.slice(r.end)}}(n))}for(;r.length>0&&""===sq(r[0]).trim();)r.shift();for(;r.length>0&&""===sq(r[r.length-1]).trim();)r.pop();return r.length?r:e}(e.lines);return(0,n.useEffect)(()=>{s.current?.focus()},[e.id]),(0,o.jsx)("div",{style:{position:"absolute",inset:0,zIndex:95,display:"flex",alignItems:"center",justifyContent:"center",padding:20,background:"rgba(0,0,0,0.18)"},children:(0,o.jsxs)("div",{ref:s,tabIndex:0,role:"dialog","aria-modal":"true",onKeyDown:r=>{let o=function(e){if(e.ctrlKey&&!e.metaKey&&!e.altKey&&1===e.key.length){let t=e.key.toLowerCase();if(t>="a"&&t<="z")return String.fromCharCode(t.charCodeAt(0)-96)}switch(e.key){case"ArrowUp":return"\x1b[A";case"ArrowDown":return"\x1b[B";case"ArrowRight":return"\x1b[C";case"ArrowLeft":return"\x1b[D";case"Enter":return"\r";case"Escape":return"\x1b";case"Backspace":return"";case"Tab":return" ";case" ":return" ";default:if(!e.ctrlKey&&!e.metaKey&&!e.altKey&&1===e.key.length)return e.key;return null}}(r);o&&(r.preventDefault(),r.stopPropagation(),t(e,o))},style:{width:"min(920px, 100%)",maxHeight:"min(760px, calc(100vh - 40px))",border:"1px solid var(--border)",borderRadius:8,background:"var(--bg)",boxShadow:"0 20px 60px rgba(0,0,0,0.28)",overflow:"hidden",outline:"none"},children:[(0,o.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,padding:"10px 12px",borderBottom:"1px solid var(--border)"},children:[(0,o.jsx)("div",{style:{color:"var(--text)",fontSize:13,fontWeight:650},children:r("desktop.extensionPanel")}),(0,o.jsx)("button",{onClick:()=>t(e,"\x03"),style:{padding:"5px 9px",borderRadius:6,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",cursor:"pointer",fontSize:12},children:r("desktop.close")})]}),(0,o.jsx)("pre",{style:{margin:0,padding:14,maxHeight:"calc(min(760px, 100vh - 40px) - 48px)",overflow:"auto",background:"var(--bg-panel)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:13,lineHeight:1.45,whiteSpace:"pre"},children:(i.length?i:[""]).map((e,t,r)=>{var s;return(0,o.jsxs)(n.Fragment,{children:[(s=`line-${t}`,(function(e){let t,r=[],o={},n=0;for(sB.lastIndex=0;null!==(t=sB.exec(e));)t.index>n&&r.push({text:e.slice(n,t.index),style:o}),o=function(e,t){let r={...e};for(let e=0;e<t.length;e++){let o=t[e];if(0===o)for(let e of Object.keys(r))delete r[e];else if(1===o)r.fontWeight=700;else if(2===o)r.opacity=.65;else if(3===o)r.fontStyle="italic";else if(4===o)r.textDecoration="underline";else if(22===o)delete r.fontWeight,delete r.opacity;else if(23===o)delete r.fontStyle;else if(24===o)delete r.textDecoration;else if(39===o)delete r.color;else if(49===o)delete r.backgroundColor;else if(o>=30&&o<=37)r.color=sU[o-30];else if(o>=90&&o<=97)r.color=s_[o-90];else if(o>=40&&o<=47)r.backgroundColor=sU[o-40];else if(o>=100&&o<=107)r.backgroundColor=s_[o-100];else if((38===o||48===o)&&2===t[e+1]){let[n,s,i]=[t[e+2],t[e+3],t[e+4]];[n,s,i].every(e=>"number"==typeof e&&Number.isFinite(e))&&(38===o?r.color=`rgb(${n}, ${s}, ${i})`:r.backgroundColor=`rgb(${n}, ${s}, ${i})`),e+=4}else if((38===o||48===o)&&5===t[e+1]){let n=function(e){if(e>=0&&e<8)return sU[e];if(e>=8&&e<16)return s_[e-8];if(e>=16&&e<=231){let t=e-16,r=Math.floor(t/36),o=Math.floor(t%36/6),n=e=>0===e?0:55+40*e;return`rgb(${n(r)}, ${n(o)}, ${n(t%6)})`}if(e>=232&&e<=255){let t=8+(e-232)*10;return`rgb(${t}, ${t}, ${t})`}}(t[e+2]);n&&(38===o?r.color=n:r.backgroundColor=n),e+=2}}return r}(o,t[1]?t[1].split(";").map(e=>Number(e||"0")):[0]),n=t.index+t[0].length;return n<e.length&&r.push({text:e.slice(n),style:o}),r})(e).map((e,t)=>Object.keys(e.style).length>0?(0,o.jsx)("span",{style:e.style,children:e.text},`${s}-${t}`):e.text)),t<r.length-1?"\n":null]},t)})})]})})}var cf=r(93549);let cx={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",bmp:"image/bmp",ico:"image/x-icon",avif:"image/avif"},cv={mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",oga:"audio/ogg",opus:"audio/ogg",m4a:"audio/mp4",aac:"audio/aac",flac:"audio/flac",weba:"audio/webm"};function ck(e){return(e.replace(/\\/g,"/").split("/").pop()??"").toLowerCase().split(".").pop()??""}function cy(e){let t=e.nodeType===Node.ELEMENT_NODE?e:e.parentElement;return t?.closest(".file-source-line[data-line-number]")??null}function cb(e,t){if(!t||t.isCollapsed||0===t.rangeCount)return null;let r=t.getRangeAt(0);if(!e.contains(r.startContainer)||!e.contains(r.endContainer))return null;let o=Number(cy(r.startContainer)?.dataset.lineNumber),n=Number(cy(r.endContainer)?.dataset.lineNumber);return Number.isInteger(o)&&Number.isInteger(n)?o<=n?{startLine:o,endLine:n}:{startLine:n,endLine:o}:null}function cw(e,t,r,o={}){let n=nf(e),s=new URLSearchParams({type:t});for(let[e,t]of(r&&s.set("sessionId",r),Object.entries(o)))void 0!==t&&s.set(e,String(t));return`/api/files/${n}?${s.toString()}`}function cj({filePath:e,sourceSessionId:t}){let{t:r}=(0,J.s)();return(0,o.jsx)("a",{href:cw(e,"download",t),download:nx(e),title:r("desktop.downloadFile"),style:{display:"flex",alignItems:"center",justifyContent:"center",height:20,padding:"0 5px",background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:4,color:"var(--text-muted)",cursor:"pointer",flexShrink:0,textDecoration:"none"},children:(0,o.jsx)(I.z,{size:11,"aria-hidden":"true"})})}let cS={fontFamily:"var(--font-mono)",fontSize:13,lineHeight:1.6,tabSize:2},cC={fontFamily:"var(--font-mono)",fontSize:13,lineHeight:1.6,padding:"12px 0 12px 16px",color:"var(--text-dim)",textAlign:"right",userSelect:"none"};async function cT(e,t){let r=await fetch(`/api/files/${nf(e)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:t})});if(!r.ok)throw Error((await r.json().catch(()=>({}))).error??`HTTP ${r.status}`);let o=await r.json();return"number"==typeof o.size?o.size:0}let cR={delete:"3px solid var(--git-status-deleted)",add:"3px solid var(--git-status-added)",edit:"3px solid var(--git-status-modified)"},cz="var(--git-status-deleted-bg)",cI="var(--git-status-added-bg)",cM="var(--git-status-added)";function cP(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KB`:`${(e/1048576).toFixed(1)} MB`}function cE({oldContent:e,newContent:t}){let{t:r}=(0,J.s)(),n=function(e,t){let r=e.length,o=t.length,n=r+o,s=Array(2*n+1).fill(0),i=[];for(let a=0;a<=n;a++){i.push([...s]);for(let l=-a;l<=a;l+=2){let d,c=(d=l===-a||l!==a&&s[l-1+n]<s[l+1+n]?s[l+1+n]:s[l-1+n]+1)-l;for(;d<r&&c<o&&e[d]===t[c];)d++,c++;if(s[l+n]=d,d>=r&&c>=o){let s=[],l=r,d=o;for(let r=a;r>0;r--){let o,a=i[r-1],c=l-d;o=c===-r||c!==r&&a[c-1+n]<a[c+1+n]?c+1:c-1;let p=a[o+n],u=p-o;for(;l>p&&d>u;)l--,d--,s.unshift({type:"unchanged",text:e[l]});r>0&&(l>p?(l--,s.unshift({type:"removed",text:e[l]})):(d--,s.unshift({type:"added",text:t[d]})))}for(;l>0&&d>0;)l--,d--,s.unshift({type:"unchanged",text:e[l]});return s}}}return[...e.map(e=>({type:"removed",text:e})),...t.map(e=>({type:"added",text:e}))]}(e.split("\n"),t.split("\n"));if(!n.some(e=>"unchanged"!==e.type))return(0,o.jsx)("div",{style:{padding:"12px 16px",fontSize:12,color:"var(--text-dim)",fontFamily:"var(--font-mono)"},children:r("desktop.noChanges")});let s=new Set(n.flatMap((e,t)=>"unchanged"!==e.type?[t]:[])),i=new Set;for(let e of s)for(let t=Math.max(0,e-3);t<=Math.min(n.length-1,e+3);t++)i.add(t);let a=[],l=0;for(;l<n.length;)if(i.has(l)){let e=[];for(;l<n.length&&i.has(l);)e.push(n[l]),l++;a.push({hidden:!1,lines:e})}else{let e=0;for(;l<n.length&&!i.has(l);)e++,l++;a.push({hidden:!0,count:e})}let d=[],c=1;for(let e of n)"removed"===e.type?d.push(0):d.push(c++);let p=0;return(0,o.jsx)("div",{style:{fontFamily:"var(--font-mono)",fontSize:13,lineHeight:1.6,minWidth:"max-content"},children:a.map((e,t)=>{if(e.hidden){let n=(0,o.jsx)("div",{style:{padding:"2px 16px",color:"var(--text-dim)",background:"var(--bg-panel)",fontSize:11,borderTop:"1px solid var(--border)",borderBottom:"1px solid var(--border)"},children:r("desktop.unchangedLines",{count:e.count})},t);return p+=e.count,n}let n=[],s=[],i=[],a=()=>{if(s.length||i.length){let e=s.length&&i.length?"edit":s.length?"delete":"add";for(let t of s)n.push({key:t.key,kind:"removed",text:t.text,lineNo:null,block:e});for(let t of i)n.push({key:t.key,kind:"added",text:t.text,lineNo:t.lineNo,block:e});s=[],i=[]}};e.lines.forEach((e,r)=>{"unchanged"===e.type?(a(),n.push({key:`${t}:${r}`,kind:"context",text:e.text,lineNo:d[p+r],block:null})):"removed"===e.type?s.push({key:`${t}:${r}`,text:e.text}):i.push({key:`${t}:${r}`,text:e.text,lineNo:d[p+r]})}),a();let l=n.map(e=>{let t="removed"===e.kind?cz:"added"===e.kind?cI:"transparent",r=e.block?cR[e.block]:"3px solid transparent",n="added"===e.kind?cM:"var(--text-dim)";return(0,o.jsxs)("div",{style:{display:"flex",background:t,borderLeft:r},children:[(0,o.jsx)("span",{style:{minWidth:44,padding:"0 8px 0 16px",textAlign:"right",color:n,userSelect:"none",fontSize:11,lineHeight:1.6,flexShrink:0},children:e.lineNo??""}),(0,o.jsx)("span",{style:{flex:1,minWidth:0,padding:"0 8px 0 0",whiteSpace:"pre",color:"var(--text)"},children:e.text||"\xa0"})]},e.key)});return p+=e.lines.length,(0,o.jsx)("div",{children:l},t)})})}function cA({patch:e}){let t=af(e);if(!t)return null;let r=[],n=[],s=[],i=()=>{if(n.length||s.length){let e=n.length&&s.length?"edit":n.length?"delete":"add";for(let t of n)r.push({key:t.key,kind:"removed",text:t.text,lineNo:null,block:e});for(let t of s)r.push({key:t.key,kind:"added",text:t.text,lineNo:t.lineNo,block:e});n=[],s=[]}};return t.forEach((e,t)=>{e.rows.forEach((e,o)=>{if("hunk"===e.type){i(),r.push({key:`${t}:${o}:h`,kind:"hunk",text:e.text,lineNo:null,block:null});return}let{left:a,right:l}=e;if("context"===a.type&&"context"===l.type){i(),r.push({key:`${t}:${o}:c`,kind:"context",text:a.text,lineNo:l.lineNo,block:null});return}"removed"===a.type&&n.push({key:`${t}:${o}:l`,text:a.text}),"added"===l.type&&s.push({key:`${t}:${o}:r`,text:l.text,lineNo:l.lineNo})})}),i(),(0,o.jsx)("div",{style:{fontFamily:"var(--font-mono)",fontSize:12,lineHeight:1.55,minWidth:"max-content"},children:r.map(e=>{if("hunk"===e.kind)return(0,o.jsxs)("div",{children:[(0,o.jsx)("div",{style:{height:"1.55em"}}),(0,o.jsx)("div",{style:{padding:"3px 12px",color:"var(--accent-blue)",background:"var(--bg-secondary)"},children:e.text}),(0,o.jsx)("div",{style:{height:"1.55em"}})]},e.key);let t="removed"===e.kind?cz:"added"===e.kind?cI:"transparent",r=e.block?cR[e.block]:"3px solid transparent",n="added"===e.kind?cM:"var(--text-dim)";return(0,o.jsxs)("div",{style:{display:"flex",background:t,borderLeft:r},children:[(0,o.jsx)("span",{style:{width:44,flexShrink:0,padding:"0 8px 0 16px",textAlign:"right",color:n,userSelect:"none",fontSize:11},children:e.lineNo??""}),(0,o.jsx)("span",{style:{flex:1,minWidth:0,padding:"0 8px 0 0",whiteSpace:"pre",color:"var(--text)"},children:e.text||"\xa0"})]},e.key)})})}function cW({filePath:e,cwd:t,sourceSessionId:r}){let{t:s}=(0,J.s)(),[i,a]=(0,n.useState)(0),[l,d]=(0,n.useState)(null),[c,p]=(0,n.useState)(null),[u,h]=(0,n.useState)(null),g=(0,n.useRef)(null),m=nx(e).toLowerCase().split(".").pop()??"";(0,n.useEffect)(()=>{a(0),d(null),p(null),h(null),g.current&&(g.current.close(),g.current=null);let t=new EventSource(cw(e,"watch",r));return g.current=t,t.addEventListener("change",e=>{try{let t=JSON.parse(e.data);"number"==typeof t.size&&d(t.size)}catch{}a(e=>e+1)}),()=>{t.close(),g.current=null}},[e,r]);let f=cw(e,"read",r,i?{v:i}:void 0),x=null!=l?cP(l):null;return(0,o.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,o.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:12,padding:"4px 16px",borderBottom:"1px solid var(--border)",fontSize:11,color:"var(--text-dim)",background:"var(--bg)",flexShrink:0},children:[(0,o.jsx)("span",{style:{fontFamily:"var(--font-mono)"},title:e,children:nv(e,t)}),(0,o.jsx)("span",{style:{marginLeft:"auto"},children:m||s("desktop.image")}),c&&(0,o.jsxs)("span",{children:[c.w," \xd7 ",c.h]}),x&&(0,o.jsx)("span",{children:x}),(0,o.jsx)(cj,{filePath:e,sourceSessionId:r})]}),(0,o.jsx)("div",{style:{flex:1,overflow:"auto",background:"var(--bg-panel)",display:"flex",alignItems:"center",justifyContent:"center",padding:16,backgroundImage:"linear-gradient(45deg, var(--bg) 25%, transparent 25%), linear-gradient(-45deg, var(--bg) 25%, transparent 25%), linear-gradient(45deg, transparent 75%, var(--bg) 75%), linear-gradient(-45deg, transparent 75%, var(--bg) 75%)",backgroundSize:"16px 16px",backgroundPosition:"0 0, 0 8px, 8px -8px, -8px 0px"},children:u?(0,o.jsx)("div",{style:{color:"var(--status-error)",fontSize:13},children:u}):(0,o.jsx)("img",{src:f,alt:e,onLoad:e=>{let t=e.currentTarget;p({w:t.naturalWidth,h:t.naturalHeight})},onError:()=>h(s("desktop.failedToLoadImage")),style:{maxWidth:"100%",maxHeight:"100%",objectFit:"contain",boxShadow:"0 2px 8px rgba(0,0,0,0.15)"}})})]})}function cN({filePath:e,cwd:t,sourceSessionId:r}){let{t:s}=(0,J.s)(),[i,a]=(0,n.useState)(0),[l,d]=(0,n.useState)(null),[c,p]=(0,n.useState)(null),[u,h]=(0,n.useState)(null),g=(0,n.useRef)(null),m=nx(e).toLowerCase().split(".").pop()??"";(0,n.useEffect)(()=>{a(0),d(null),p(null),h(null),g.current&&(g.current.close(),g.current=null);let t=new EventSource(cw(e,"watch",r));return g.current=t,t.addEventListener("change",e=>{try{let t=JSON.parse(e.data);"number"==typeof t.size&&d(t.size)}catch{}p(null),h(null),a(e=>e+1)}),()=>{t.close(),g.current=null}},[e,r]);let f=cw(e,"read",r,i?{v:i}:void 0);return(0,o.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,o.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:12,padding:"4px 16px",borderBottom:"1px solid var(--border)",fontSize:11,color:"var(--text-dim)",background:"var(--bg)",flexShrink:0},children:[(0,o.jsx)("span",{style:{fontFamily:"var(--font-mono)"},title:e,children:nv(e,t)}),(0,o.jsx)("span",{style:{marginLeft:"auto"},children:m||s("desktop.audio")}),null!=c&&(0,o.jsx)("span",{children:function(e){if(!Number.isFinite(e))return"";let t=Math.round(e),r=Math.floor(t/60);return`${r}:${String(t%60).padStart(2,"0")}`}(c)}),null!=l&&(0,o.jsx)("span",{children:cP(l)}),(0,o.jsx)(cj,{filePath:e,sourceSessionId:r})]}),(0,o.jsx)("div",{style:{flex:1,display:"flex",alignItems:"center",justifyContent:"center",padding:24,background:"var(--bg-panel)"},children:(0,o.jsxs)("div",{style:{width:"min(680px, 100%)"},children:[u&&(0,o.jsx)("div",{style:{color:"var(--status-error)",fontSize:13,marginBottom:12,textAlign:"center"},children:u}),(0,o.jsx)("audio",{controls:!0,preload:"metadata",src:f,onLoadedMetadata:e=>p(e.currentTarget.duration),onError:()=>h(s("desktop.failedToLoadAudio")),style:{width:"100%"}},f)]})})]})}function cF({filePath:e,cwd:t,sourceSessionId:r}){let{t:s}=(0,J.s)(),[i,a]=(0,n.useState)(0),[l,d]=(0,n.useState)(null),[c,p]=(0,n.useState)(null),u=(0,n.useRef)(null),h=ck(e),g="pdf"===h,m=g?cw(e,"read",r,i?{v:i}:void 0):cw(e,"preview",r,i?{v:i}:void 0);return(0,n.useEffect)(()=>{a(0),d(null),p(null),u.current&&(u.current.close(),u.current=null),fetch(cw(e,"meta",r)).then(e=>e.json()).then(e=>{e.error&&p(e.error),"number"==typeof e.size&&(d(e.size),!g&&e.size>0xa00000&&p(s("desktop.docxTooLargeForPreview")))}).catch(e=>p(String(e)));let t=new EventSource(cw(e,"watch",r));return u.current=t,t.addEventListener("change",e=>{try{let t=JSON.parse(e.data);if("number"==typeof t.size&&(d(t.size),!g&&t.size>0xa00000))return void p(s("desktop.docxTooLargeForPreview"))}catch{}p(null),a(e=>e+1)}),()=>{t.close(),u.current=null}},[e,g,r,s]),(0,o.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,o.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:12,padding:"4px 16px",borderBottom:"1px solid var(--border)",fontSize:11,color:"var(--text-dim)",background:"var(--bg)",flexShrink:0},children:[(0,o.jsx)("span",{style:{fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:e,children:nv(e,t)}),(0,o.jsx)("span",{style:{marginLeft:"auto"},children:"docx"===h?s("desktop.docxPreview"):"pdf"}),null!=l&&(0,o.jsx)("span",{children:cP(l)}),(0,o.jsx)(cj,{filePath:e,sourceSessionId:r})]}),(0,o.jsx)("div",{style:{flex:1,minHeight:0,background:"var(--bg-panel)"},children:c?(0,o.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",padding:24,color:"var(--status-error)",fontSize:13,textAlign:"center"},children:c}):(0,o.jsx)("iframe",{src:m,sandbox:g?void 0:"allow-same-origin",title:s("desktop.previewFile",{file:nx(e)}),style:{width:"100%",height:"100%",border:"none",background:g?"var(--bg)":"#eef1f5"}},m)})]})}function cD({filePath:e,cwd:t,sourceSessionId:r,onOpenFile:n,onAtMention:s,onMentionLines:i,initialDisplayMode:a,onFileSaved:l}){let d;return null!==(cx[ck(e)]??null)?(0,o.jsx)(cW,{filePath:e,cwd:t,sourceSessionId:r}):null!==(cv[ck(e)]??null)?(0,o.jsx)(cN,{filePath:e,cwd:t,sourceSessionId:r}):null!==("pdf"===(d=ck(e))||"docx"===d?d:null)?(0,o.jsx)(cF,{filePath:e,cwd:t,sourceSessionId:r}):(0,o.jsx)(cL,{filePath:e,cwd:t,sourceSessionId:r,onOpenFile:n,onAtMention:s,onMentionLines:i,initialDisplayMode:a,onFileSaved:l})}function cL({filePath:e,cwd:t,sourceSessionId:r,onOpenFile:s,onAtMention:i,onMentionLines:a,initialDisplayMode:l,onFileSaved:d}){let c,p,{t:u}=(0,J.s)(),[g,m]=(0,n.useState)(null),[x,v]=(0,n.useState)(null),[k,y]=(0,n.useState)(null),[b,w]=(0,n.useState)(!0),[j,S]=(0,n.useState)(null),[C,T]=(0,n.useState)(!1),[R,z]=(0,n.useState)("source"),[I,M]=(0,n.useState)(!1),[P,E]=(0,n.useState)(0),[A,W]=(0,n.useState)(null),N=(0,n.useRef)(null),F=(0,n.useRef)(null),[D,L]=(0,n.useState)(!1),[$,H]=(0,n.useState)(""),[O,B]=(0,n.useState)(""),[U,_]=(0,n.useState)(!1),[q,V]=(0,n.useState)(null),[K,G]=(0,n.useState)(!1),Y=(0,n.useRef)(null),X=(0,n.useRef)(null),Z=(0,n.useRef)(0),Q=(0,n.useRef)(!1);(0,n.useEffect)(()=>{Q.current=D},[D]);let ee=D&&$!==O,et=!!(g?.content&&g.content.includes("\0")),er=(0,n.useCallback)(async e=>{if(!t)return void y(null);try{let r=new URLSearchParams({cwd:t,path:e}),o=await fetch(`/api/git/diff?${r.toString()}`),n=await o.json();y(o.ok&&n.supported&&"string"==typeof n.patch?n:null)}catch{y(null)}},[t]),eo=(0,n.useCallback)((e,t=!1)=>fetch(cw(e,"read",r)).then(e=>e.json()).then(e=>e.error?(S(e.error),null):(t?(m(t=>(t&&v(t.content),e)),E(e=>e+1)):m(e),e)).catch(e=>(S(String(e)),null)),[r]);(0,n.useEffect)(()=>{w(!0),S(null),m(null),v(null),y(null),T(!1),z("source"),M(!1),E(0),L(!1),H(""),B(""),V(null),G(!1),_(!1),N.current&&(N.current.close(),N.current=null),eo(e).then(e=>{(e?.language==="markdown"||e?.language==="html")&&"diff"!==l&&T(!0)}).finally(()=>w(!1)),er(e);let t=new EventSource(cw(e,"watch",r));return N.current=t,t.addEventListener("change",()=>{Q.current?G(!0):(eo(e,!0),er(e))}),()=>{t.close(),N.current=null}},[e,eo,er,l,r]);let en=(0,n.useCallback)(()=>{g&&!et&&(H(g.content),B(g.content),V(null),G(!1),L(!0))},[g,et]),es=(0,n.useCallback)(()=>{L(!1),H(""),B(""),V(null),G(!1)},[]),ei=(0,n.useCallback)(()=>{(!ee||window.confirm(u("files.unsavedChanges")))&&es()},[ee,es,u]),ea=(0,n.useCallback)(async()=>{if(!g||U)return;let t=++Z.current;_(!0),V(null);try{let r=await cT(e,$);if(t!==Z.current)return;m(e=>e?{...e,content:$,size:r}:e),B($),_(!1),es(),er(e),d?.()}catch(e){if(t!==Z.current)return;V(e instanceof Error?e.message:String(e)),_(!1)}},[g,U,$,e,es,er,d]);(0,n.useEffect)(()=>{if(!D)return;let e=e=>{if((e.metaKey||e.ctrlKey)&&"s"===e.key.toLowerCase()){e.preventDefault(),ea();return}"Escape"===e.key&&(e.preventDefault(),ei())};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[D,ea,ei]),(0,n.useEffect)(()=>{if(!ee)return;let e=e=>{e.preventDefault(),e.returnValue=""};return window.addEventListener("beforeunload",e),()=>window.removeEventListener("beforeunload",e)},[ee]);let el=(0,n.useCallback)(()=>{let e=Y.current,t=X.current;e&&t&&(t.scrollTop=e.scrollTop)},[]),ed=(0,n.useCallback)(e=>{if("Tab"!==e.key||e.metaKey||e.ctrlKey||e.altKey)return;e.preventDefault();let t=e.currentTarget,{selectionStart:r,selectionEnd:o}=t;H(t.value.slice(0,r)+" "+t.value.slice(o)),requestAnimationFrame(()=>{let e=Y.current;if(!e)return;let t=r+2;e.selectionStart=t,e.selectionEnd=t})},[]),ec=(0,n.useMemo)(()=>iJ(g?.content??""),[g?.content]),ep=k?.supported===!0&&"string"==typeof k.patch;(0,n.useEffect)(()=>{"diff"===l&&ep&&z("diff")},[ep,l]);let eu=ep&&k?.status==="deleted",eh=(0,n.useCallback)(r=>{a&&r&&a(nv(e,t),r.startLine,r.endLine)},[t,e,a]);if((0,n.useEffect)(()=>{let e=()=>{let e=F.current,t="source"===R&&!C;W(a&&t&&e?cb(e,window.getSelection()):null)};if(e(),a&&"source"===R&&!C)return document.addEventListener("selectionchange",e),()=>document.removeEventListener("selectionchange",e)},[g?.content,a,C,R]),(0,n.useEffect)(()=>{if(!a||"source"!==R||C)return;let e=e=>{if(e.repeat||"i"!==e.key.toLowerCase()||!e.metaKey&&!e.ctrlKey||e.altKey||e.shiftKey)return;let t=e.target;if(t instanceof Element&&t.closest("input, textarea, [contenteditable='true']"))return;let r=F.current,o=r?cb(r,window.getSelection()):null;o&&(e.preventDefault(),eh(o))};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[eh,a,C,R]),b)return(0,o.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-muted)",fontSize:13},children:u("desktop.loadingFile")});if(eu&&!g)return(0,o.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,o.jsx)("div",{style:{padding:"5px 16px",borderBottom:"1px solid var(--border)",color:"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:11},title:e,children:nv(e,t)}),(0,o.jsx)("div",{style:{flex:1,overflow:"auto",background:"var(--bg)"},children:(0,o.jsx)(cA,{patch:k.patch})})]});if(j)return(0,o.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--status-error)",fontSize:13},children:j});if(!g)return null;let eg="html"===g.language,em="markdown"===g.language,ef=(p=(c=nm(e).replace(/\/+$/,"")).lastIndexOf("/"))<0?"":0===p?"/":2===p&&/^[a-zA-Z]:\//.test(c)?c.slice(0,3):c.slice(0,p),ex=g.content.split("\n"),ev=null!==x&&x!==g.content||ep,ek=!eu&&!et&&nb();return(0,o.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,o.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:12,padding:"4px 16px",borderBottom:"1px solid var(--border)",fontSize:11,color:"var(--text-dim)",background:"var(--bg)",flexShrink:0},children:[(0,o.jsx)("span",{style:{fontFamily:"var(--font-mono)"},title:e,children:nv(e,t)}),(0,o.jsx)("span",{style:{marginLeft:"auto"},children:g.language}),"source"===R&&!D&&(0,o.jsx)("span",{children:u("desktop.lines",{count:ex.length})}),(0,o.jsx)("span",{children:cP(g.size)}),ev&&!D&&(0,o.jsxs)("div",{style:{display:"flex",borderRadius:5,overflow:"hidden",border:"1px solid var(--border)"},children:[(0,o.jsx)("button",{onClick:()=>z("source"),style:{padding:"2px 8px",fontSize:11,border:"none",cursor:"pointer",background:"source"===R?"var(--bg-selected)":"var(--bg-hover)",color:"source"===R?"var(--text)":"var(--text-muted)",fontWeight:"source"===R?600:400},children:u("desktop.source")}),(0,o.jsxs)("button",{onClick:()=>z("diff"),style:{padding:"2px 8px",fontSize:11,border:"none",borderLeft:"1px solid var(--border)",cursor:"pointer",background:"diff"===R?"var(--bg-selected)":"var(--bg-hover)",color:"diff"===R?"var(--text)":"var(--text-muted)",fontWeight:"diff"===R?600:400},children:[u("desktop.diff")," ",P>0&&(0,o.jsxs)("span",{style:{color:"var(--git-status-added)",marginLeft:2},children:["+",P]})]})]}),"source"===R&&!C&&!D&&(0,o.jsx)("button",{onClick:()=>M(e=>!e),title:I?u("desktop.disableWordWrap"):u("desktop.enableWordWrap"),style:{padding:"2px 8px",fontSize:11,cursor:"pointer",background:I?"var(--bg-selected)":"var(--bg-hover)",color:I?"var(--text)":"var(--text-muted)",border:"1px solid var(--border)",borderRadius:5,fontWeight:I?600:400},children:u("desktop.wrap")}),eg&&"source"===R&&!D&&(0,o.jsxs)("div",{style:{display:"flex",borderRadius:5,overflow:"hidden",border:"1px solid var(--border)"},children:[(0,o.jsx)("button",{onClick:()=>T(!1),style:{padding:"2px 8px",fontSize:11,border:"none",cursor:"pointer",background:C?"var(--bg-hover)":"var(--bg-selected)",color:C?"var(--text-muted)":"var(--text)",fontWeight:C?400:600},children:u("desktop.code")}),(0,o.jsx)("button",{onClick:()=>T(!0),style:{padding:"2px 8px",fontSize:11,border:"none",borderLeft:"1px solid var(--border)",cursor:"pointer",background:C?"var(--bg-selected)":"var(--bg-hover)",color:C?"var(--text)":"var(--text-muted)",fontWeight:C?600:400},children:u("desktop.preview")})]}),em&&"source"===R&&!D&&(0,o.jsxs)("div",{style:{display:"flex",borderRadius:5,overflow:"hidden",border:"1px solid var(--border)"},children:[(0,o.jsx)("button",{onClick:()=>T(!0),style:{padding:"2px 8px",fontSize:11,border:"none",cursor:"pointer",background:C?"var(--bg-selected)":"var(--bg-hover)",color:C?"var(--text)":"var(--text-muted)",fontWeight:C?600:400},children:u("desktop.preview")}),(0,o.jsx)("button",{onClick:()=>T(!1),style:{padding:"2px 8px",fontSize:11,border:"none",borderLeft:"1px solid var(--border)",cursor:"pointer",background:C?"var(--bg-hover)":"var(--bg-selected)",color:C?"var(--text-muted)":"var(--text)",fontWeight:C?400:600},children:u("desktop.raw")})]}),D?(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)("button",{type:"button",onClick:()=>void ea(),disabled:U,title:u("files.saveHint"),"aria-label":u("files.save"),style:{height:20,minWidth:20,padding:"0 5px",display:"inline-flex",alignItems:"center",justifyContent:"center",border:"1px solid var(--border)",borderRadius:4,background:"var(--bg-selected)",color:"var(--text)",cursor:"pointer"},children:(0,o.jsx)(cf.g,{size:13,"aria-hidden":"true"})}),(0,o.jsx)("button",{type:"button",onClick:ei,disabled:U,title:u("files.cancelEdit"),"aria-label":u("files.cancelEdit"),style:{height:20,minWidth:20,padding:"0 5px",display:"inline-flex",alignItems:"center",justifyContent:"center",border:"1px solid var(--border)",borderRadius:4,background:"var(--bg-panel)",color:"var(--text-muted)",cursor:"pointer"},children:(0,o.jsx)(h.X,{size:13,"aria-hidden":"true"})})]}):"source"===R&&ek?(0,o.jsx)("button",{type:"button",onClick:en,title:u("files.edit"),"aria-label":u("files.edit"),style:{height:20,minWidth:20,padding:"0 5px",display:"inline-flex",alignItems:"center",justifyContent:"center",border:"1px solid var(--border)",borderRadius:4,background:"var(--bg-panel)",color:"var(--text-muted)",cursor:"pointer"},children:(0,o.jsx)(f.I,{size:13,"aria-hidden":"true"})}):null,(i||a)&&!D&&(0,o.jsx)("button",{type:"button",onPointerDown:e=>e.preventDefault(),onClick:()=>{A&&a?eh(A):i?.(nv(e,t),!1)},title:A?u("desktop.mentionSelectedLines",{start:A.startLine,end:A.endLine}):u("desktop.mentionFile"),"aria-label":A?u("desktop.mentionSelectedLines",{start:A.startLine,end:A.endLine}):u("desktop.mentionFile"),style:{height:20,minWidth:20,padding:"0 5px",border:"1px solid var(--border)",borderRadius:4,background:"var(--bg-panel)",color:"var(--text-muted)",cursor:"pointer"},children:"@"}),!D&&(0,o.jsx)(cj,{filePath:e,sourceSessionId:r})]}),(0,o.jsx)("div",{ref:F,style:{flex:1,overflow:"auto",background:"var(--bg)"},children:D?(0,o.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[K&&(0,o.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"5px 12px",borderBottom:"1px solid var(--border)",background:"rgba(214,168,75,0.14)",color:"#d6a84b",fontSize:11,flexShrink:0},children:[(0,o.jsx)("span",{style:{flex:1},children:u("files.externalModified")}),(0,o.jsx)("button",{type:"button",onClick:()=>{(!ee||window.confirm(u("files.reloadOverwriteConfirm")))&&eo(e).then(e=>{e&&(H(e.content),B(e.content),G(!1))})},disabled:U,style:{padding:"2px 8px",fontSize:11,border:"1px solid #d6a84b",borderRadius:4,background:"transparent",color:"#d6a84b",cursor:"pointer"},children:u("files.reload")})]}),q&&(0,o.jsx)("div",{style:{padding:"5px 12px",borderBottom:"1px solid var(--border)",background:"rgba(248,113,113,0.14)",color:"var(--status-error)",fontSize:11,flexShrink:0},children:u("files.saveFailed",{error:q})}),(0,o.jsxs)("div",{style:{flex:1,display:"flex",overflow:"hidden"},children:[(0,o.jsx)("div",{ref:X,"aria-hidden":"true",style:{...cC,height:"100%",overflow:"hidden",whiteSpace:"pre",pointerEvents:"none"},children:$.split("\n").map((e,t)=>`${t+1}
195
195
  `).join("")}),(0,o.jsx)("textarea",{ref:Y,value:$,onChange:e=>H(e.target.value),onScroll:el,onKeyDown:ed,spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",wrap:"off",style:{flex:1,height:"100%",resize:"none",border:"none",outline:"none",background:"var(--bg)",color:"var(--text)",...cS,whiteSpace:"pre",overflow:"auto",padding:0,tabSize:2}})]})]}):"diff"===R&&ev?ep?(0,o.jsx)(cA,{patch:k.patch}):(0,o.jsx)(cE,{oldContent:x,newContent:g.content}):eg&&C?(0,o.jsx)("iframe",{srcDoc:g.content,sandbox:"allow-scripts",style:{width:"100%",height:"100%",border:"none",background:"var(--bg)"},title:u("desktop.htmlPreview")}):em&&C?(0,o.jsx)("div",{className:"markdown-body markdown-file-preview",style:{padding:"24px 32px"},children:(0,o.jsx)(ir.oz,{remarkPlugins:iZ,rehypePlugins:iQ,components:{h1:({children:e})=>(0,o.jsx)("h1",{id:iG(e),children:e}),h2:({children:e})=>(0,o.jsx)("h2",{id:iG(e),children:e}),h3:({children:e})=>(0,o.jsx)("h3",{id:iG(e),children:e}),code({className:e,children:t,...r}){let n=e?.replace("language-","").toLowerCase()??"",s=String(t);return e?.includes("language-")||s.includes("\n")?"mermaid"===n?(0,o.jsx)(as,{code:s.replace(/\n$/,"")}):(0,o.jsx)(al,{code:s.replace(/\n$/,""),lang:n}):(0,o.jsx)("code",{className:"inline max-w-full whitespace-normal break-words [overflow-wrap:anywhere] align-baseline bg-(--bg-secondary) border border-(--border) px-1.5 py-0.5 text-xs font-mono text-(--accent-blue)",...r,children:t})},pre:({children:e})=>(0,o.jsx)(o.Fragment,{children:e}),a({href:e,children:r,...n}){delete n.node;let i="text-(--accent-blue) underline underline-offset-2 hover:text-(--accent-blue)/80",a=s?s9(e,ef,t??ef):null;return a&&s?(0,o.jsx)("a",{href:e,...n,className:i,onClick:e=>{if(e.defaultPrevented||0!==e.button||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey)return;let t=e.currentTarget.getAttribute("target");t&&"_self"!==t||(e.preventDefault(),s(a))},children:r}):(0,o.jsx)("a",{href:e,...n,className:i,target:"_blank",rel:"noopener noreferrer",children:r})},table:({children:e})=>(0,o.jsx)("div",{className:"my-3 rounded-lg overflow-hidden border border-(--border)",children:(0,o.jsx)("div",{className:"overflow-x-auto",children:(0,o.jsx)("table",{className:"w-full text-sm border-collapse [&_tr:last-child>td]:border-b-0",children:e})})})},children:ec})}):(0,o.jsx)(io.A,{language:"text"===g.language?"plaintext":g.language,style:i0,showLineNumbers:!0,lineNumberStyle:{color:"var(--text-dim)",fontStyle:"normal",minWidth:"3em",paddingRight:"1em"},customStyle:{margin:0,padding:"12px 0",background:"var(--bg)",fontSize:13,lineHeight:1.6,fontFamily:"var(--font-mono)",minHeight:"100%"},codeTagProps:{style:{fontFamily:"var(--font-mono)"}},lineProps:e=>({className:"file-source-line","data-line-number":String(e)}),wrapLongLines:I,children:g.content})})]})}function c$({sessionId:e,label:t,running:r=!1,onOpenFile:s}){let{t:i}=(0,J.s)(),[a,l]=(0,n.useState)([]),[d,c]=(0,n.useState)([]),[p,u]=(0,n.useState)(!0),[h,g]=(0,n.useState)(null);(0,n.useEffect)(()=>{let t=!1;return(async r=>{r&&u(!0);try{let r=await fetch(`/api/sessions/${encodeURIComponent(e)}?tail=500`,{cache:"no-store"}),o=await r.json();if(t)return;if(!r.ok)throw Error(o.error??`HTTP ${r.status}`);l(o.context?.messages??[]),c([]),g(null)}catch(e){if(t)return;g(e instanceof Error?e.message:String(e))}finally{t||u(!1)}})(!0),()=>{t=!0}},[e]),(0,n.useEffect)(()=>{if(!r)return;let t=!1,o=window.setInterval(async()=>{if("visible"===document.visibilityState)try{let r=await fetch(`/api/sessions/${encodeURIComponent(e)}?tail=500`,{cache:"no-store"});if(!r.ok)return;let o=await r.json();if(t)return;l(o.context?.messages??[])}catch{}},2500);return()=>{t=!0,window.clearInterval(o)}},[r,e]);let m=(0,n.useMemo)(()=>{let e=new Map;for(let t of a)"toolResult"===t.role&&e.set(t.toolCallId,t);return e},[a]),f=(0,n.useMemo)(()=>a.filter(e=>"user"===e.role||"assistant"===e.role),[a]);return(0,o.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",minHeight:0,background:"var(--bg)"},children:[(0,o.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,flexShrink:0,padding:"8px 12px",borderBottom:"1px solid var(--border)",background:"var(--bg-panel)"},children:[(0,o.jsx)("span",{style:{fontSize:12,fontWeight:600,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:t||i("subagent.transcriptTitle")}),r&&(0,o.jsx)("span",{style:{marginLeft:"auto",fontSize:11,color:"var(--accent)",whiteSpace:"nowrap"},children:i("agentSwitcher.status.running")})]}),(0,o.jsxs)("div",{className:"scroll-overlay",style:{flex:1,minHeight:0,overflowY:"auto",padding:"10px 12px"},children:[p&&0===a.length&&(0,o.jsx)("div",{style:{color:"var(--text-dim)",fontSize:12},children:i("subagent.transcriptLoading")}),h&&0===a.length&&(0,o.jsx)("div",{style:{color:"var(--status-error)",fontSize:12},children:i("subagent.transcriptFailed",{error:h})}),!p&&!h&&0===f.length&&(0,o.jsx)("div",{style:{color:"var(--text-dim)",fontSize:12},children:i("subagent.transcriptEmpty")}),f.map((t,r)=>(0,o.jsx)(aF,{message:t,toolResults:m,entryId:d[r],sessionId:e,onOpenFile:s},`subagent-msg-${r}`))]})]})}function cH({tabs:e,activeTabId:t,onSelectTab:r,onCloseTab:s}){let{t:i}=(0,J.s)(),a=(0,n.useRef)(null),[l,d]=(0,n.useState)(!1);(0,n.useEffect)(()=>{if(!t)return;let e=a.current;if(!e)return;let r=e.querySelector(`[data-tab-id="${CSS.escape(t)}"]`);r?.scrollIntoView({block:"nearest",inline:"nearest"})},[t,e.length]),(0,n.useEffect)(()=>{let e=a.current;if(!e)return;let t=()=>d(e.scrollWidth>e.clientWidth+1);t();let r=new ResizeObserver(t);return r.observe(e),()=>r.disconnect()},[e.length]);let c=(0,n.useCallback)((t,o)=>{if(t.target!==t.currentTarget)return;if("Enter"===t.key||" "===t.key){t.preventDefault(),r(o.id);return}if(!["ArrowLeft","ArrowRight","Home","End"].includes(t.key))return;t.preventDefault();let n=e.findIndex(e=>e.id===o.id),s="Home"===t.key?0:"End"===t.key?e.length-1:(n+("ArrowRight"===t.key?1:-1)+e.length)%e.length;r(e[s].id);let i=a.current;i?.querySelector(`[data-tab-id="${CSS.escape(e[s].id)}"]`)?.focus()},[r,e]);return(0,o.jsx)("div",{ref:a,role:"tablist",className:`file-tab-bar${l?"":" no-overflow"}`,children:e.map(n=>{let a=n.id===t;return(0,o.jsxs)("div",{role:"tab","data-tab-id":n.id,"aria-label":"terminal"===n.kind?i("terminal.tabLabel",{name:n.label}):"subagent"===n.kind?i("subagent.transcriptTitle")+": "+n.label:n.label,"aria-selected":a,tabIndex:a||!t&&e[0].id===n.id?0:-1,className:"file-tab",onKeyDown:e=>c(e,n),onClick:()=>r(n.id),onMouseDown:e=>{1===e.button&&e.preventDefault()},onAuxClick:e=>{1===e.button&&(e.preventDefault(),e.stopPropagation(),n.closing||s(n.id))},children:[(0,o.jsx)("span",{className:"file-tab-icon",children:"subagent"===n.kind?(0,o.jsx)(_.d,{size:13,"aria-hidden":"true"}):"terminal"===n.kind?(0,o.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,o.jsx)("polyline",{points:"4 17 10 11 4 5"}),(0,o.jsx)("line",{x1:"12",y1:"19",x2:"20",y2:"19"})]}):ng(n.label,13)}),(0,o.jsx)("span",{className:"file-tab-label",title:n.filePath,children:n.label}),(0,o.jsx)("button",{type:"button",className:"file-tab-close",disabled:n.closing,onClick:e=>{e.stopPropagation(),s(n.id)},title:i("desktop.closeTab"),"aria-label":i("desktop.closeTabWithLabel",{label:n.label}),children:(0,o.jsx)(h.X,{size:11,"aria-hidden":"true"})})]},n.id)})})}let cO="pi-web:file-tabs";function cB(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}let cU=new Set(["awaiting_input","review","failed"]),c_=(0,n.createContext)(null);function cq(){let e=(0,n.useContext)(c_);if(!e)throw Error("useTasksView must be used within TasksViewProvider");return e}function cV({children:e}){let{t}=(0,J.s)(),r=(0,n.useRef)(t);(0,n.useEffect)(()=>{r.current=t},[t]);let[s,i]=(0,n.useState)([]),[a,l]=(0,n.useState)([]),d=(0,n.useRef)(0),c=(0,n.useCallback)(async()=>{let e=++d.current;try{let t=await (0,l7.Wt)(),r=(await Promise.all(t.map(e=>(0,l7.Vk)(e).catch(()=>[])))).flat().sort((e,t)=>t.id-e.id);if(e!==d.current)return;l(e=>cK(e,t)?e:t),i(e=>cK(e,r)?e:r)}catch{}},[]);(0,n.useEffect)(()=>{c();let e=null,t=!1,r=()=>{t||((e=new EventSource("/api/tasks/events")).onmessage=()=>{c()},e.onerror=()=>{e?.close(),e=null,c(),setTimeout(r,2e3)})};r();let o=()=>{"visible"===document.visibilityState&&c()},n=()=>void c();document.addEventListener("visibilitychange",o),window.addEventListener("online",n);let s=setInterval(()=>void c(),6e4);return()=>{t=!0,e?.close(),document.removeEventListener("visibilitychange",o),window.removeEventListener("online",n),clearInterval(s)}},[c]);let p=(0,n.useMemo)(()=>s.filter(e=>cU.has(e.status)&&null==e.archivedAt).length,[s]),u=(0,n.useRef)(null);(0,n.useEffect)(()=>{let e=u.current;if((u.current=new Map(s.map(e=>[e.id,e.status])),e&&0!==s.length)&&"Notification"in window){for(let r of s)if(e.get(r.id)!==r.status&&("review"===r.status||"failed"===r.status)&&null==r.archivedAt&&"visible"!==document.visibilityState)try{let e="review"===r.status?t("tasks.notifyReview",{title:r.title}):t("tasks.notifyFailed",{title:r.title});!function(e,t){new Promise(r=>{if(!("Notification"in window))return void r();let o=()=>{try{new Notification(e,{body:t,tag:"pi-tasks"})}catch{}r()};"granted"===Notification.permission?o():"denied"!==Notification.permission?Notification.requestPermission().then(e=>{"granted"===e?o():r()}):r()})}("Pi Web Tasks",e)}catch{}}},[s,t]);let h=(0,n.useMemo)(()=>({tasks:s,projects:a,attentionCount:p,refetch:c}),[s,a,p,c]);return(0,o.jsx)(c_.Provider,{value:h,children:e})}function cK(e,t){return JSON.stringify(e)===JSON.stringify(t)}var cG=r(4539),cJ=r(12449),cY=r(2571);let cX=["todo","inProgress","attention","done"];function cZ(e){return"review"===e.status&&0===e.filesChanged}function cQ(){return{defaultAgentType:null,modeId:null,configValues:{},autoProcess:!0,maxConcurrent:1,mergeStrategy:"merge",deleteWorktreeDefault:!0,preflightCommand:null,initCommand:null,stagePrompts:null}}let c0=["todo","inProgress","attention","done"],c1={todo:{id:"todo",marker:"var(--text-dim)"},inProgress:{id:"inProgress",marker:"var(--accent)"},attention:{id:"attention",marker:"var(--status-warning)"},done:{id:"done",marker:"var(--status-success)"}};var c2=r(54775),c6=r(98998),c4=r(36668);function c5({task:e}){let{t}=(0,J.s)(),r=t("failed"===e.status&&"interrupted"===e.failureReason?"tasks.statusInterrupted":function(e){switch(e){case"todo":return"tasks.statusTodo";case"queued":return"tasks.statusQueued";case"preparing":return"tasks.statusPreparing";case"running":return"tasks.statusRunning";case"awaiting_input":return"tasks.statusAwaitingInput";case"review":return"tasks.statusReview";case"merging":return"tasks.statusMerging";case"done":return"tasks.statusDone";case"failed":return"tasks.statusFailed";case"canceled":return"tasks.statusCanceled"}}(e.status)),n={display:"inline-flex",alignItems:"center",gap:4,borderRadius:999,padding:"2px 8px",fontSize:10,fontWeight:600,lineHeight:1.4,flexShrink:0,whiteSpace:"nowrap"};switch(e.status){case"queued":case"preparing":case"running":case"merging":return(0,o.jsxs)("span",{style:{...n,color:"var(--accent)"},children:[(0,o.jsx)(c2.N,{size:11,className:"pi-spin",style:{animation:"pi-spin 1s linear infinite"},"aria-hidden":"true"}),r]});case"awaiting_input":case"review":return(0,o.jsx)("span",{style:{...n,border:"1px solid rgba(245,158,11,0.45)",background:"rgba(245,158,11,0.08)",color:"var(--status-warning)"},children:r});case"done":return(0,o.jsxs)("span",{style:{...n,background:"rgba(16,185,129,0.12)",color:"#059669"},children:[(0,o.jsx)(m.J,{size:10,weight:"bold","aria-hidden":"true"}),r]});case"failed":return(0,o.jsx)("span",{style:{...n,background:"rgba(239,68,68,0.12)",color:"var(--status-error)"},children:r});default:return(0,o.jsx)("span",{style:{...n,background:"var(--bg-hover)",color:"var(--text-muted)"},children:r})}}function c8({task:e}){let t=e.preflight;if(!t||"review"!==e.status)return null;let r="passed"===t.status?{background:"rgba(16,185,129,0.12)",color:"#059669"}:"failed"===t.status?{background:"rgba(239,68,68,0.12)",color:"var(--status-error)"}:{background:"var(--bg-hover)",color:"var(--text-muted)"};return(0,o.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:4,borderRadius:999,padding:"1px 6px",fontSize:10,fontWeight:500,lineHeight:1.5,maxWidth:"100%",...r},title:t.command,children:["running"===t.status?(0,o.jsx)(c2.N,{size:10,style:{animation:"pi-spin 1s linear infinite"},"aria-hidden":"true"}):"passed"===t.status?(0,o.jsx)(es.r,{size:10,"aria-hidden":"true"}):(0,o.jsx)(r0.J,{size:10,"aria-hidden":"true"}),(0,o.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:t.command})]})}function c3({task:e,folderName:t,now:r,onOpen:n,onStart:s,onCancel:i,onRetry:a,onRequeue:l,onViewSession:d,onMerge:c,onArchive:p,onEdit:u}){let{t:h}=(0,J.s)(),g=null!=e.archivedAt,f="running"===e.status||"awaiting_input"===e.status||"merging"===e.status,x=null!=e.filesChanged&&e.filesChanged>0?(0,o.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:3,fontFamily:"var(--font-mono)",fontSize:10},children:[(0,o.jsxs)("span",{style:{color:"#059669"},children:["+",e.additions??0]}),(0,o.jsxs)("span",{style:{color:"var(--status-error)"},children:["-",e.deletions??0]})]}):null,v=function(e,t){if(!e)return"";let r=new Date(e).getTime();if(Number.isNaN(r))return"";let o=Math.floor(Math.max(0,t-r)/6e4);if(o<1)return"now";if(o<60)return`${o}m`;let n=Math.floor(o/60);if(n<24)return`${n}h`;let s=Math.floor(n/24);return`${s}d`}(e.finishedAt??e.settledAt??e.startedAt??e.createdAt,r),{primary:k,more:y}=(()=>{let t=[],r=null;if(g)return{primary:r={icon:z.T,label:h("tasks.actionUnarchive"),onClick:p},more:t};switch(e.status){case"todo":r={icon:cY.j,label:h("tasks.actionStart"),onClick:s},t.push({icon:lA.S,label:h("tasks.actionEdit"),onClick:u});break;case"queued":case"preparing":case"running":case"awaiting_input":r={icon:c6.k,label:h("tasks.actionCancel"),onClick:i};break;case"review":r=cZ(e)?{icon:m.J,label:h("tasks.actionComplete"),onClick:c}:{icon:c4.r,label:h("tasks.actionMerge"),onClick:c};break;case"merging":break;case"failed":r={icon:C.S,label:h("tasks.actionRetry"),onClick:a},t.push({icon:lA.S,label:h("tasks.actionEdit"),onClick:u}),t.push({icon:z.T,label:h("tasks.actionArchive"),onClick:p});break;case"done":r={icon:z.T,label:h("tasks.actionArchive"),onClick:p};break;case"canceled":r={icon:a1.f,label:h("tasks.actionRequeue"),onClick:l},t.push({icon:z.T,label:h("tasks.actionArchive"),onClick:p})}return{primary:r,more:t}})(),b=[...y];return null!=e.conversationId&&b.push({icon:a0.y,label:h("tasks.actionViewSession"),onClick:d}),(0,o.jsxs)("div",{role:"button",tabIndex:0,onClick:n,onKeyDown:e=>{("Enter"===e.key||" "===e.key)&&(e.preventDefault(),n())},style:{display:"flex",flexDirection:"column",cursor:"pointer",borderRadius:12,border:"1px solid color-mix(in srgb, var(--border) 85%, transparent)",background:"var(--bg-panel)",padding:12,textAlign:"left",transition:"border-color 0.12s",opacity:g?.6:1,boxShadow:"0 1px 2px rgba(0,0,0,0.04)"},className:"task-card-hover",onMouseEnter:e=>{e.currentTarget.style.borderColor="var(--accent)"},onMouseLeave:e=>{e.currentTarget.style.borderColor="color-mix(in srgb, var(--border) 85%, transparent)"},children:[(0,o.jsxs)("div",{style:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:8},children:[(0,o.jsx)("span",{style:{minWidth:0,overflowWrap:"break-word",fontSize:13,fontWeight:500,lineHeight:1.4},children:e.title}),(0,o.jsx)(c5,{task:e})]}),(0,o.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:"2px 6px",marginTop:6,fontSize:11,color:"var(--text-muted)"},children:[t?(0,o.jsx)("span",{style:{maxWidth:160,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:t}):null,t&&e.workBranch?(0,o.jsx)("span",{style:{opacity:.5},children:"/"}):null,e.workBranch?(0,o.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:10,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",maxWidth:180},children:e.workBranch}):null,(t||e.workBranch)&&(x||v)?(0,o.jsx)("span",{style:{opacity:.5},children:"\xb7"}):null,x,x&&v?(0,o.jsx)("span",{style:{opacity:.5},children:"\xb7"}):null,v?(0,o.jsx)("span",{style:{flexShrink:0},children:v}):null,(0,o.jsx)(c8,{task:e})]}),e.lastError&&("failed"===e.status||"review"===e.status)?(0,o.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6,marginTop:8,borderRadius:8,background:"rgba(239,68,68,0.08)",padding:"6px 8px",fontSize:11,color:"var(--status-error)"},children:[(0,o.jsx)(aT.t,{size:13,style:{flexShrink:0},"aria-hidden":"true"}),(0,o.jsx)("span",{style:{minWidth:0,flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.lastError}),(0,o.jsx)("button",{type:"button",style:{flexShrink:0,fontWeight:600,background:"none",border:"none",cursor:"pointer",color:"inherit",fontSize:11,textDecoration:"underline"},onClick:e=>{e.stopPropagation(),n()},children:h("tasks.errorView")})]}):null,"review"===e.status&&e.resultSummary?(0,o.jsx)("p",{style:{margin:"6px 0 0",display:"-webkit-box",WebkitLineClamp:2,WebkitBoxOrient:"vertical",overflow:"hidden",fontSize:11,lineHeight:1.5,color:"var(--text-muted)"},children:e.resultSummary}):null,f&&e.latestProgress?(0,o.jsx)("p",{style:{margin:"6px 0 0",display:"-webkit-box",WebkitLineClamp:2,WebkitBoxOrient:"vertical",overflow:"hidden",fontSize:11,lineHeight:1.5,color:"var(--text-muted)",fontStyle:"italic"},children:e.latestProgress}):null,k||b.length>0?(0,o.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6,marginTop:12,paddingTop:12,borderTop:"1px solid var(--border)"},children:[k?(0,o.jsxs)("button",{type:"button",onClick:e=>{e.stopPropagation(),k.onClick()},style:{display:"inline-flex",alignItems:"center",gap:5,padding:"4px 10px",borderRadius:7,background:"var(--accent)",color:"var(--accent-fg)",border:"none",cursor:"pointer",fontSize:11,fontWeight:600},children:[(0,o.jsx)(k.icon,{size:12,weight:"bold","aria-hidden":"true"}),k.label]}):null,(0,o.jsx)("div",{style:{flex:1}}),b.map(e=>(0,o.jsx)("button",{type:"button",title:e.label,"aria-label":e.label,onClick:t=>{t.stopPropagation(),e.onClick()},style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,padding:0,borderRadius:999,background:"none",border:"1px solid var(--border)",color:"var(--text-muted)",cursor:"pointer",opacity:0,transition:"opacity 0.12s, background 0.12s, color 0.12s"},className:"task-card-secondary",onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background="none",e.currentTarget.style.color="var(--text-muted)"},children:(0,o.jsx)(e.icon,{size:13,"aria-hidden":"true"})},e.label))]}):null]})}function c7({open:e,onOpenChange:t,task:r}){let{t:s}=(0,J.s)(),{refetch:i}=cq(),[a,l]=(0,n.useState)(""),[d,c]=(0,n.useState)(!1);if(A(!d,()=>t(!1)),(0,n.useEffect)(()=>{e&&(l(""),c(!1))},[e,r]),!e||!r)return null;let p=async()=>{if(!d){c(!0);try{await (0,l7.oQ)(r.id,r.projectRoot,"cancel",{reason:a.trim()||null}),t(!1),i()}catch(e){console.error("cancel failed",e)}finally{c(!1)}}};return(0,o.jsx)("div",{style:{position:"fixed",inset:0,zIndex:950,display:"flex",alignItems:"center",justifyContent:"center",background:"rgba(0,0,0,0.45)"},children:(0,o.jsxs)("div",{style:{width:"min(440px, calc(100vw - 48px))",background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:14,boxShadow:"0 16px 48px rgba(0,0,0,0.3)"},children:[(0,o.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"14px 16px 0"},children:[(0,o.jsx)("h3",{style:{fontSize:15,fontWeight:600,margin:0},children:s("tasks.cancelTitle")}),(0,o.jsx)("button",{type:"button",onClick:()=>t(!1),"aria-label":s("i18n.close"),style:{background:"none",border:"none",cursor:"pointer",color:"var(--text-muted)",padding:4,display:"flex"},children:(0,o.jsx)(h.X,{size:16,"aria-hidden":"true"})})]}),(0,o.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:12,padding:"14px 16px 16px"},children:[(0,o.jsx)("p",{style:{margin:0,fontSize:12,lineHeight:1.5,color:"var(--text-muted)"},children:s("tasks.cancelDescription")}),(0,o.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:5},children:[(0,o.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)"},children:s("tasks.cancelReasonLabel")}),(0,o.jsx)("textarea",{value:a,onChange:e=>l(e.target.value),placeholder:s("tasks.cancelReasonPlaceholder"),rows:3,autoFocus:!0,style:{width:"100%",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:8,padding:"8px 10px",color:"var(--text)",fontSize:13,outline:"none",fontFamily:"inherit",resize:"vertical"}})]}),(0,o.jsxs)("div",{style:{display:"flex",justifyContent:"flex-end",gap:8,marginTop:4},children:[(0,o.jsx)("button",{type:"button",onClick:()=>t(!1),disabled:d,style:{padding:"8px 14px",borderRadius:8,background:"none",border:"1px solid var(--border)",color:"var(--text)",fontSize:12,cursor:"pointer"},children:s("tasks.cancelKeep")}),(0,o.jsx)("button",{type:"button",onClick:()=>void p(),disabled:d,style:{padding:"8px 16px",borderRadius:8,background:"var(--accent)",color:"var(--accent-fg)",border:"none",fontSize:12,fontWeight:600,cursor:"pointer"},children:s("tasks.cancelSubmit")})]})]})]})})}function c9({open:e,onOpenChange:t,task:r}){let{t:s}=(0,J.s)(),{refetch:i}=cq(),[a,l]=(0,n.useState)(!0),[d,c]=(0,n.useState)(!1);A(!d,()=>t(!1));let p=r?.worktreePath!=null;if((0,n.useEffect)(()=>{if(!e||!r)return;c(!1);let t=!1;return(0,l7.CG)(r.projectRoot).then(e=>{t||l(e.deleteWorktreeDefault)}).catch(()=>{t||l(!0)}),()=>{t=!0}},[e,r]),!e||!r)return null;let u=async()=>{if(!d){c(!0);try{await (0,l7.ZX)(r.id,r.projectRoot,p&&a),t(!1),i()}catch(e){console.error("complete failed",e)}finally{c(!1)}}};return(0,o.jsx)("div",{style:{position:"fixed",inset:0,zIndex:950,display:"flex",alignItems:"center",justifyContent:"center",background:"rgba(0,0,0,0.45)"},children:(0,o.jsxs)("div",{style:{width:"min(440px, calc(100vw - 48px))",background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:14,boxShadow:"0 16px 48px rgba(0,0,0,0.3)"},children:[(0,o.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"14px 16px 0"},children:[(0,o.jsx)("h3",{style:{fontSize:15,fontWeight:600,margin:0},children:s("tasks.completeTitle")}),(0,o.jsx)("button",{type:"button",onClick:()=>t(!1),"aria-label":s("i18n.close"),style:{background:"none",border:"none",cursor:"pointer",color:"var(--text-muted)",padding:4,display:"flex"},children:(0,o.jsx)(h.X,{size:16,"aria-hidden":"true"})})]}),(0,o.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:12,padding:"14px 16px 16px"},children:[(0,o.jsx)("p",{style:{margin:0,fontSize:12,lineHeight:1.5,color:"var(--text-muted)"},children:s("tasks.completeDescription")}),p?(0,o.jsxs)("label",{style:{display:"flex",alignItems:"center",gap:8,fontSize:13,cursor:"pointer"},children:[(0,o.jsx)("input",{type:"checkbox",checked:a,onChange:e=>l(e.target.checked),style:{accentColor:"var(--accent)"}}),s("tasks.completeDeleteWorktree")]}):null,(0,o.jsxs)("div",{style:{display:"flex",justifyContent:"flex-end",gap:8,marginTop:4},children:[(0,o.jsx)("button",{type:"button",onClick:()=>t(!1),disabled:d,style:{padding:"8px 14px",borderRadius:8,background:"none",border:"1px solid var(--border)",color:"var(--text)",fontSize:12,cursor:"pointer"},children:s("i18n.cancel")}),(0,o.jsx)("button",{type:"button",onClick:()=>void u(),disabled:d,style:{padding:"8px 16px",borderRadius:8,background:"var(--accent)",color:"var(--accent-fg)",border:"none",fontSize:12,fontWeight:600,cursor:"pointer"},children:s("tasks.completeSubmit")})]})]})]})})}var pe=r(51285),pt=r(16894);function pr({open:e,onOpenChange:t,task:r,onViewSession:s,onMerge:i,onEdit:a,onCancel:l,onRetry:d,onRequeue:c,onComplete:p}){let{t:u}=(0,J.s)(),{refetch:g}=cq(),[f,x]=(0,n.useState)([]),[v,k]=(0,n.useState)([]),[b,w]=(0,n.useState)(null),[j,S]=(0,n.useState)(null),[R,I]=(0,n.useState)(!1),[M,P]=(0,n.useState)(!1),[E,W]=(0,n.useState)(""),[N,F]=(0,n.useState)(!1),[D,L]=(0,n.useState)(!1),[$,H]=(0,n.useState)(!1);A(!0,()=>t(!1));let O=r?.id??null,B=r?.projectRoot??null,U=(0,n.useCallback)(async()=>{if(null==O||null==B)return;let[e,t]=await Promise.all([(0,l7.HB)(B,O).catch(()=>[]),r?.worktreePath?(0,l7.JH)(B,O).then(e=>e.files).catch(()=>[]):Promise.resolve([])]);x(e),k(t)},[O,B,r?.worktreePath]);(0,n.useEffect)(()=>{if(!e||null==O)return;x([]),k([]),P(!1),W(""),U();let t=window.setInterval(()=>void U(),5e3);return()=>window.clearInterval(t)},[e,O,U]);let _=(0,n.useCallback)(async e=>{H(!0);try{await e()}catch(e){console.error("detail action failed",e)}finally{H(!1),g()}},[g]),q=(0,n.useCallback)(async e=>{if(null!=B&&null!=O){I(!0);try{let t=await (0,l7.h)(B,O,e);S(t.supported&&t.patch?t.patch:null)}catch{S(null)}finally{I(!1)}}},[B,O]),V=async()=>{null!=r&&null!=B&&(await _(()=>(0,l7.bH)(r.id,B,D)),t(!1))},K=async()=>{null!=r&&null!=B&&E.trim()&&(await _(()=>(0,l7.in)(r.id,B,E.trim())),P(!1),W(""))};if(!e||null==r||null==B)return null;let G=[];if(null==r.archivedAt)switch(r.status){case"todo":G.push({label:u("tasks.actionStart"),icon:cY.j,onClick:()=>void _(()=>(0,l7.oQ)(r.id,B,"start")),filled:!0}),G.push({label:u("tasks.actionEdit"),icon:lA.S,onClick:()=>a(r)});break;case"queued":case"preparing":case"running":case"awaiting_input":G.push({label:u("tasks.actionCancel"),icon:c6.k,onClick:()=>l(r),danger:!0});break;case"review":G.push({label:cZ(r)?u("tasks.actionComplete"):u("tasks.actionMerge"),icon:cZ(r)?m.J:pe.Y,onClick:()=>cZ(r)?p(r):i(r),filled:!0}),G.push({label:u("tasks.actionReturn"),icon:a1.f,onClick:()=>P(!0)});break;case"failed":G.push({label:u("tasks.actionRetry"),icon:C.S,onClick:()=>d(r),filled:!0}),G.push({label:u("tasks.actionEdit"),icon:lA.S,onClick:()=>a(r)});break;case"done":G.push({label:u("tasks.actionArchive"),icon:z.T,onClick:()=>void _(()=>(0,l7.et)(r.id,B,!0))});break;case"canceled":G.push({label:u("tasks.actionRequeue"),icon:a1.f,onClick:()=>c(r),filled:!0})}else G.push({label:u("tasks.actionUnarchive"),icon:z.T,onClick:()=>void _(()=>(0,l7.et)(r.id,B,!1))});return null!=r.conversationId&&G.push({label:u("tasks.actionViewSession"),icon:a0.y,onClick:()=>s(r)}),(0,o.jsx)("div",{style:{position:"fixed",inset:0,zIndex:800,background:"rgba(0,0,0,0.35)"},children:(0,o.jsxs)("div",{style:{position:"absolute",top:0,right:0,bottom:0,width:"min(480px, 90vw)",background:"var(--bg-panel)",borderLeft:"1px solid var(--border)",display:"flex",flexDirection:"column",boxShadow:"-8px 0 32px rgba(0,0,0,0.2)"},children:[(0,o.jsxs)("div",{style:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:12,padding:"16px 16px 0"},children:[(0,o.jsxs)("div",{style:{minWidth:0},children:[(0,o.jsx)("h3",{style:{margin:0,fontSize:15,fontWeight:600,lineHeight:1.4,overflowWrap:"break-word"},children:r.title}),(0,o.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,marginTop:6},children:[(0,o.jsx)(c5,{task:r}),r.workBranch?(0,o.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:4,fontFamily:"var(--font-mono)",fontSize:11,color:"var(--text-muted)"},children:[(0,o.jsx)(y.Z,{size:12,"aria-hidden":"true"}),r.workBranch]}):null]})]}),(0,o.jsx)("button",{type:"button",onClick:()=>t(!1),"aria-label":u("i18n.close"),style:{background:"none",border:"none",cursor:"pointer",color:"var(--text-muted)",padding:4,display:"flex",flexShrink:0},children:(0,o.jsx)(h.X,{size:16,"aria-hidden":"true"})})]}),(0,o.jsx)("div",{style:{display:"flex",flexWrap:"wrap",gap:8,padding:"14px 16px 0"},children:G.map(e=>{let t,r;return(0,o.jsxs)("button",{type:"button",onClick:e.onClick,disabled:$,style:(t=e.filled,r=e.danger,{display:"inline-flex",alignItems:"center",gap:5,padding:"7px 12px",borderRadius:8,fontSize:12,fontWeight:600,cursor:"pointer",background:t?"var(--accent)":r?"rgba(239,68,68,0.1)":"var(--bg-hover)",color:t?"#fff":r?"var(--status-error)":"var(--text)",border:t||r?"none":"1px solid var(--border)"}),children:[(0,o.jsx)(e.icon,{size:13,weight:"bold","aria-hidden":"true"}),e.label]},e.label)})}),M&&(0,o.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:8,padding:"12px 16px 0"},children:[(0,o.jsx)("textarea",{value:E,onChange:e=>W(e.target.value),placeholder:u("tasks.returnPlaceholder"),rows:3,style:{width:"100%",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:8,padding:"8px 10px",color:"var(--text)",fontSize:12,resize:"vertical",fontFamily:"inherit"}}),(0,o.jsxs)("div",{style:{display:"flex",justifyContent:"flex-end",gap:8},children:[(0,o.jsx)("button",{type:"button",onClick:()=>P(!1),style:{padding:"6px 12px",borderRadius:8,background:"none",border:"1px solid var(--border)",color:"var(--text)",fontSize:12,cursor:"pointer"},children:u("i18n.cancel")}),(0,o.jsx)("button",{type:"button",onClick:()=>void K(),disabled:!E.trim(),style:{padding:"6px 14px",borderRadius:8,background:"var(--accent)",color:"var(--accent-fg)",border:"none",fontSize:12,fontWeight:600,cursor:"pointer"},children:u("tasks.returnSubmit")})]})]}),(0,o.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:6,padding:"14px 16px 0",fontSize:12,color:"var(--text-muted)"},children:[(0,o.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,o.jsx)("span",{style:{flexShrink:0,color:"var(--text-dim)",width:64},children:u("tasks.metaProject")}),(0,o.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontFamily:"var(--font-mono)",fontSize:11},children:r.projectRoot})]}),r.createdAt?(0,o.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,o.jsx)("span",{style:{flexShrink:0,color:"var(--text-dim)",width:64},children:u("tasks.metaCreated")}),(0,o.jsx)("span",{children:new Date(r.createdAt).toLocaleString()})]}):null,r.mergeCommit?(0,o.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,o.jsx)("span",{style:{flexShrink:0,color:"var(--text-dim)",width:64},children:u("tasks.metaCommit")}),(0,o.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:11},children:r.mergeCommit})]}):null]}),v.length>0&&(0,o.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4,padding:"14px 16px 0"},children:[(0,o.jsx)("span",{style:{fontSize:11,fontWeight:600,color:"var(--text-muted)",textTransform:"uppercase",letterSpacing:"0.05em"},children:u("tasks.changedFiles")}),(0,o.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:2,maxHeight:140,overflowY:"auto"},children:v.map(e=>(0,o.jsxs)("button",{type:"button",onClick:()=>{var t;w(t=e.file),S(null),q(t)},style:{display:"flex",alignItems:"center",gap:8,textAlign:"left",padding:"4px 6px",borderRadius:6,background:"none",border:"none",color:"var(--text)",fontSize:12,cursor:"pointer"},children:[(0,o.jsx)(pt.o,{size:13,style:{flexShrink:0,color:"var(--text-muted)"},"aria-hidden":"true"}),(0,o.jsx)("span",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontFamily:"var(--font-mono)",fontSize:11},children:e.file}),(0,o.jsxs)("span",{style:{fontFamily:"var(--font-mono)",fontSize:10,color:"#059669",flexShrink:0},children:["+",e.additions]}),(0,o.jsxs)("span",{style:{fontFamily:"var(--font-mono)",fontSize:10,color:"var(--status-error)",flexShrink:0},children:["-",e.deletions]})]},e.file))})]}),null!=b&&(0,o.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:6,padding:"12px 16px 0",minHeight:0,flexShrink:0},children:[(0,o.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[(0,o.jsx)("span",{style:{fontSize:11,fontWeight:600,color:"var(--text-muted)"},children:u("tasks.diff")}),(0,o.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:10,color:"var(--text-muted)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1},children:b}),(0,o.jsx)("button",{type:"button",onClick:()=>w(null),style:{background:"none",border:"none",cursor:"pointer",color:"var(--text-muted)",padding:2,display:"flex"},children:(0,o.jsx)(h.X,{size:12,"aria-hidden":"true"})})]}),R?(0,o.jsx)("div",{style:{fontSize:11,color:"var(--text-muted)",padding:8},children:u("tasks.loading")}):j?(0,o.jsx)("pre",{style:{margin:0,maxHeight:200,overflow:"auto",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:8,padding:10,fontSize:11,lineHeight:1.5,fontFamily:"var(--font-mono)",color:"var(--text-muted)",whiteSpace:"pre"},children:j.split("\n").map((e,t)=>{let r;return e.startsWith("+")&&!e.startsWith("+++")?r="#059669":e.startsWith("-")&&!e.startsWith("---")?r="var(--status-error)":e.startsWith("@@")&&(r="var(--accent)"),(0,o.jsx)("div",{style:{color:r},children:e||" "},t)})}):(0,o.jsx)("div",{style:{fontSize:11,color:"var(--text-muted)",padding:8},children:u("tasks.noDiff")})]}),(0,o.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4,padding:"14px 16px 0",flex:1,minHeight:0},children:[(0,o.jsx)("span",{style:{fontSize:11,fontWeight:600,color:"var(--text-muted)",textTransform:"uppercase",letterSpacing:"0.05em"},children:u("tasks.timeline")}),(0,o.jsx)("div",{style:{flex:1,minHeight:0,overflowY:"auto",paddingBottom:8},children:0===f.length?(0,o.jsx)("div",{style:{fontSize:11,color:"var(--text-dim)",padding:8},children:u("tasks.noEvents")}):(0,o.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:2},children:[...f].reverse().map(e=>{var t;let r,n;return(0,o.jsxs)("div",{style:{display:"flex",gap:8,padding:"4px 6px",borderRadius:6,fontSize:11},children:[(0,o.jsx)("span",{style:{color:"var(--text-dim)",flexShrink:0,fontFamily:"var(--font-mono)",fontSize:10,paddingTop:1},children:new Date(e.createdAt).toLocaleTimeString()}),(0,o.jsx)("span",{style:{color:"var(--text)",flexShrink:0,fontWeight:500},children:(t=e.kind,(n=u(r=`tasks.event_${t}`))===r?t:n)}),e.payload?.feedback?(0,o.jsx)("span",{style:{color:"var(--text-muted)",fontStyle:"italic",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:String(e.payload.feedback)}):null]},e.id)})})})]}),(0,o.jsx)("div",{style:{display:"flex",alignItems:"center",justifyContent:"flex-end",gap:8,padding:"10px 16px",borderTop:"1px solid var(--border)",flexShrink:0},children:N?(0,o.jsxs)(o.Fragment,{children:[(0,o.jsxs)("label",{style:{display:"flex",alignItems:"center",gap:6,fontSize:12,cursor:"pointer"},children:[(0,o.jsx)("input",{type:"checkbox",checked:D,onChange:e=>L(e.target.checked),style:{accentColor:"var(--accent)"}}),u("tasks.deleteWorktree")]}),(0,o.jsx)("button",{type:"button",onClick:()=>F(!1),style:{padding:"6px 12px",borderRadius:8,background:"none",border:"1px solid var(--border)",color:"var(--text)",fontSize:12,cursor:"pointer"},children:u("i18n.cancel")}),(0,o.jsx)("button",{type:"button",onClick:()=>void V(),disabled:$,style:{padding:"6px 14px",borderRadius:8,background:"var(--status-error)",color:"#fff",border:"none",fontSize:12,fontWeight:600,cursor:"pointer"},children:u("tasks.deleteConfirm")})]}):(0,o.jsxs)("button",{type:"button",onClick:()=>F(!0),style:{display:"inline-flex",alignItems:"center",gap:5,padding:"6px 12px",borderRadius:8,background:"none",border:"1px solid var(--border)",color:"var(--status-error)",fontSize:12,cursor:"pointer"},children:[(0,o.jsx)(T.l,{size:13,"aria-hidden":"true"}),u("tasks.delete")]})})]})})}var po=r(17757);function pn({open:e,onOpenChange:t,task:r,defaultProject:s,projects:i,prefillTitle:a,prefillPrompt:l,onSubmit:d}){let{t:c}=(0,J.s)(),[p,u]=(0,n.useState)(""),[g,m]=(0,n.useState)(""),[f,x]=(0,n.useState)(""),[v,k]=(0,n.useState)([]),[y,b]=(0,n.useState)(""),[w,j]=(0,n.useState)(!1);A(!w,()=>t(!1));let S=(0,n.useRef)(!1);if((0,n.useEffect)(()=>{if(!e){S.current=!1;return}S.current||(S.current=!0,u(r?.projectRoot??s??i[0]??""),m(r?.title??a??""),x(r?.config?.prompt??l??""),(0,l7.VB)().then(k).catch(()=>void 0))},[e,r,s,i,a,l]),!e)return null;let C=async()=>{if(p&&g.trim()&&!w){j(!0);try{await d(p,g.trim(),{prompt:f.trim(),agentType:r?.config?.agentType??null,modelId:r?.config?.modelId??null,thinkingLevel:r?.config?.thinkingLevel??null}),t(!1)}catch(e){console.error("submit task failed",e)}finally{j(!1)}}},R=async()=>{if(y.trim()&&g.trim())try{await (0,l7.nY)({name:y.trim(),title:g.trim(),config:{prompt:f.trim()}}),b(""),(0,l7.VB)().then(k).catch(()=>void 0)}catch(e){console.error("save template failed",e)}},z=async e=>{try{await (0,l7.B_)(e),(0,l7.VB)().then(k).catch(()=>void 0)}catch(e){console.error("delete template failed",e)}},I={width:"100%",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:8,padding:"8px 10px",color:"var(--text)",fontSize:13,outline:"none"};return(0,o.jsx)("div",{style:{position:"fixed",inset:0,zIndex:900,display:"flex",alignItems:"center",justifyContent:"center",background:"rgba(0,0,0,0.45)"},children:(0,o.jsxs)("div",{style:{width:"min(520px, calc(100vw - 48px))",maxHeight:"80vh",overflowY:"auto",background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:14,boxShadow:"0 16px 48px rgba(0,0,0,0.3)"},children:[(0,o.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"14px 16px 0"},children:[(0,o.jsx)("h3",{style:{fontSize:15,fontWeight:600,margin:0},children:r?c("tasks.editTitle"):c("tasks.newTitle")}),(0,o.jsx)("button",{type:"button",onClick:()=>t(!1),"aria-label":c("i18n.close"),style:{background:"none",border:"none",cursor:"pointer",color:"var(--text-muted)",padding:4,display:"flex"},children:(0,o.jsx)(h.X,{size:16,"aria-hidden":"true"})})]}),(0,o.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:12,padding:"14px 16px 16px"},children:[v.length>0&&(0,o.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,o.jsx)("span",{style:{fontSize:11,fontWeight:600,color:"var(--text-muted)",textTransform:"uppercase",letterSpacing:"0.05em"},children:c("tasks.templates")}),(0,o.jsx)("div",{style:{display:"flex",flexWrap:"wrap",gap:6},children:v.map(e=>(0,o.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:4,borderRadius:999,background:"var(--bg-hover)",padding:"3px 8px",fontSize:11},children:[(0,o.jsx)("button",{type:"button",onClick:()=>{m(e.title),x(e.config?.prompt??"")},style:{background:"none",border:"none",cursor:"pointer",color:"var(--text)",fontSize:11,padding:0},children:e.name}),(0,o.jsx)("button",{type:"button",onClick:()=>void z(e.id),"aria-label":c("tasks.deleteTemplate"),style:{background:"none",border:"none",cursor:"pointer",color:"var(--text-dim)",padding:0,display:"flex"},children:(0,o.jsx)(T.l,{size:10,"aria-hidden":"true"})})]},e.id))})]}),(0,o.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,o.jsx)("span",{style:{fontSize:12,fontWeight:500,color:"var(--text)"},children:c("tasks.fieldProject")}),(0,o.jsx)("select",{value:p,onChange:e=>u(e.target.value),style:I,children:i.map(e=>(0,o.jsx)("option",{value:e,children:e.split("/").filter(Boolean).pop()??e},e))})]}),(0,o.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,o.jsx)("span",{style:{fontSize:12,fontWeight:500,color:"var(--text)"},children:c("tasks.fieldTitle")}),(0,o.jsx)("input",{value:g,onChange:e=>m(e.target.value),placeholder:c("tasks.fieldTitlePlaceholder"),style:I,autoFocus:!0})]}),(0,o.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,o.jsx)("span",{style:{fontSize:12,fontWeight:500,color:"var(--text)"},children:c("tasks.fieldPrompt")}),(0,o.jsx)("textarea",{value:f,onChange:e=>x(e.target.value),placeholder:c("tasks.fieldPromptPlaceholder"),rows:6,style:{...I,resize:"vertical",fontFamily:"inherit",lineHeight:1.5}})]}),(0,o.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6},children:[(0,o.jsx)("input",{value:y,onChange:e=>b(e.target.value),placeholder:c("tasks.templateNamePlaceholder"),style:{...I,flex:1}}),(0,o.jsxs)("button",{type:"button",onClick:()=>void R(),disabled:!y.trim()||!g.trim(),style:{display:"inline-flex",alignItems:"center",gap:5,padding:"8px 12px",borderRadius:8,background:"var(--bg-hover)",border:"1px solid var(--border)",color:"var(--text)",fontSize:12,cursor:"pointer"},children:[(0,o.jsx)(po.D,{size:13,"aria-hidden":"true"}),c("tasks.saveAsTemplate")]})]}),(0,o.jsxs)("div",{style:{display:"flex",justifyContent:"flex-end",gap:8,marginTop:4},children:[(0,o.jsx)("button",{type:"button",onClick:()=>t(!1),style:{padding:"8px 14px",borderRadius:8,background:"none",border:"1px solid var(--border)",color:"var(--text)",fontSize:12,cursor:"pointer"},children:c("i18n.cancel")}),(0,o.jsx)("button",{type:"button",onClick:()=>void C(),disabled:!p||!g.trim()||w,style:{padding:"8px 16px",borderRadius:8,background:"var(--accent)",color:"var(--accent-fg)",border:"none",fontSize:12,fontWeight:600,cursor:"pointer"},children:c("tasks.save")})]})]})]})})}function ps({open:e,onOpenChange:t,task:r}){let{t:s}=(0,J.s)(),{refetch:i}=cq(),[a,l]=(0,n.useState)(!0),[d,c]=(0,n.useState)(""),[p,u]=(0,n.useState)(!0),[g,m]=(0,n.useState)(!1);if(A(!g,()=>t(!1)),(0,n.useEffect)(()=>{e&&r&&(l(!0),c(r.title),m(!1),(0,l7.CG)(r.projectRoot).then(e=>u(e.deleteWorktreeDefault)).catch(()=>u(!0)))},[e,r]),!e||!r)return null;let f=async()=>{if((a||d.trim())&&!g){m(!0);try{await (0,l7.oB)(r.id,r.projectRoot,a?null:d.trim(),p),t(!1),i()}catch(e){console.error("merge failed",e)}finally{m(!1)}}};return(0,o.jsx)("div",{style:{position:"fixed",inset:0,zIndex:950,display:"flex",alignItems:"center",justifyContent:"center",background:"rgba(0,0,0,0.45)"},children:(0,o.jsxs)("div",{style:{width:"min(440px, calc(100vw - 48px))",background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:14,boxShadow:"0 16px 48px rgba(0,0,0,0.3)"},children:[(0,o.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"14px 16px 0"},children:[(0,o.jsx)("h3",{style:{fontSize:15,fontWeight:600,margin:0},children:s("tasks.mergeTitle")}),(0,o.jsx)("button",{type:"button",onClick:()=>t(!1),"aria-label":s("i18n.close"),style:{background:"none",border:"none",cursor:"pointer",color:"var(--text-muted)",padding:4,display:"flex"},children:(0,o.jsx)(h.X,{size:16,"aria-hidden":"true"})})]}),(0,o.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:12,padding:"14px 16px 16px"},children:[(0,o.jsxs)("label",{style:{display:"flex",alignItems:"center",gap:8,fontSize:13,cursor:"pointer"},children:[(0,o.jsx)("input",{type:"radio",checked:a,onChange:()=>l(!0),style:{accentColor:"var(--accent)"}}),s("tasks.mergeAutoMessage")]}),(0,o.jsxs)("label",{style:{display:"flex",alignItems:"center",gap:8,fontSize:13,cursor:"pointer"},children:[(0,o.jsx)("input",{type:"radio",checked:!a,onChange:()=>l(!1),style:{accentColor:"var(--accent)"}}),s("tasks.mergeManualMessage")]}),!a&&(0,o.jsx)("input",{value:d,onChange:e=>c(e.target.value),placeholder:s("tasks.mergeMessagePlaceholder"),style:{width:"100%",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:8,padding:"8px 10px",color:"var(--text)",fontSize:13,outline:"none",fontFamily:"inherit"}}),(0,o.jsxs)("label",{style:{display:"flex",alignItems:"center",gap:8,fontSize:13,cursor:"pointer"},children:[(0,o.jsx)("input",{type:"checkbox",checked:p,onChange:e=>u(e.target.checked),style:{accentColor:"var(--accent)"}}),s("tasks.mergeDeleteWorktree")]}),(0,o.jsxs)("div",{style:{display:"flex",justifyContent:"flex-end",gap:8,marginTop:4},children:[(0,o.jsx)("button",{type:"button",onClick:()=>t(!1),style:{padding:"8px 14px",borderRadius:8,background:"none",border:"1px solid var(--border)",color:"var(--text)",fontSize:12,cursor:"pointer"},children:s("i18n.cancel")}),(0,o.jsx)("button",{type:"button",onClick:()=>void f(),disabled:!a&&!d.trim()||g,style:{padding:"8px 16px",borderRadius:8,background:"var(--accent)",color:"var(--accent-fg)",border:"none",fontSize:12,fontWeight:600,cursor:"pointer"},children:s("tasks.mergeConfirm")})]})]})]})})}function pi({open:e,onOpenChange:t,task:r,kind:s}){let{t:i}=(0,J.s)(),{refetch:a}=cq(),[l,d]=(0,n.useState)(""),[c,p]=(0,n.useState)(!1);if(A(!c,()=>t(!1)),(0,n.useEffect)(()=>{e&&(d(""),p(!1))},[e,r]),!e||!r)return null;let u="retry"===s,g=async()=>{if(!c){p(!0);try{await (0,l7.oQ)(r.id,r.projectRoot,s,{note:l.trim()||null}),t(!1),a()}catch(e){console.error("restart failed",e)}finally{p(!1)}}};return(0,o.jsx)("div",{style:{position:"fixed",inset:0,zIndex:950,display:"flex",alignItems:"center",justifyContent:"center",background:"rgba(0,0,0,0.45)"},children:(0,o.jsxs)("div",{style:{width:"min(480px, calc(100vw - 48px))",background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:14,boxShadow:"0 16px 48px rgba(0,0,0,0.3)"},children:[(0,o.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"14px 16px 0"},children:[(0,o.jsx)("h3",{style:{fontSize:15,fontWeight:600,margin:0},children:i(u?"tasks.restartTitleRetry":"tasks.restartTitleRequeue")}),(0,o.jsx)("button",{type:"button",onClick:()=>t(!1),"aria-label":i("i18n.close"),style:{background:"none",border:"none",cursor:"pointer",color:"var(--text-muted)",padding:4,display:"flex"},children:(0,o.jsx)(h.X,{size:16,"aria-hidden":"true"})})]}),(0,o.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:12,padding:"14px 16px 16px"},children:[(0,o.jsx)("p",{style:{margin:0,fontSize:12,lineHeight:1.5,color:"var(--text-muted)"},children:i("tasks.restartDescription")}),(0,o.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:5},children:[(0,o.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)"},children:i("tasks.actionAddNote")}),(0,o.jsx)("textarea",{value:l,onChange:e=>d(e.target.value),placeholder:i(u?"tasks.followUpPlaceholderRetry":"tasks.followUpPlaceholderRequeue"),rows:3,autoFocus:!0,style:{width:"100%",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:8,padding:"8px 10px",color:"var(--text)",fontSize:13,outline:"none",fontFamily:"inherit",resize:"vertical"}})]}),(0,o.jsxs)("div",{style:{display:"flex",justifyContent:"flex-end",gap:8,marginTop:4},children:[(0,o.jsx)("button",{type:"button",onClick:()=>t(!1),disabled:c,style:{padding:"8px 14px",borderRadius:8,background:"none",border:"1px solid var(--border)",color:"var(--text)",fontSize:12,cursor:"pointer"},children:i("i18n.cancel")}),(0,o.jsx)("button",{type:"button",onClick:()=>void g(),disabled:c,style:{padding:"8px 16px",borderRadius:8,background:"var(--accent)",color:"var(--accent-fg)",border:"none",fontSize:12,fontWeight:600,cursor:"pointer"},children:i(u?"tasks.actionRetry":"tasks.actionRequeue")})]})]})]})})}let pa=["work","retry","return","merge"];function pl({open:e,onOpenChange:t,projectRoot:r}){let{t:s}=(0,J.s)(),{projects:i}=cq(),[a,l]=(0,n.useState)(""),[d,c]=(0,n.useState)(()=>cQ()),[p,u]=(0,n.useState)(!1),[g,m]=(0,n.useState)(!1);if(A(!g,()=>t(!1)),(0,n.useEffect)(()=>{if(!e)return;let t=r??i[0]??"";l(t),t&&(0,l7.Pf)(t).then(e=>{u(null!=e),c(e??cQ())}).catch(()=>{u(!1),c(cQ())})},[e,r,i]),!e)return null;let f=(e,t)=>{c(r=>({...r,[e]:t}))},x=async()=>{if(a&&!g){m(!0);try{await (0,l7.eA)(a,d),u(!0),t(!1)}catch(e){console.error("save settings failed",e)}finally{m(!1)}}},v=async()=>{if(a)try{await (0,l7.E)(a),u(!1),c(cQ())}catch(e){console.error("reset settings failed",e)}},k={width:"100%",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:8,padding:"7px 10px",color:"var(--text)",fontSize:12,outline:"none",fontFamily:"inherit"},y={display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,padding:"10px 0",borderBottom:"1px solid var(--border)"};return(0,o.jsx)("div",{style:{position:"fixed",inset:0,zIndex:960,display:"flex",alignItems:"center",justifyContent:"center",background:"rgba(0,0,0,0.45)"},children:(0,o.jsxs)("div",{style:{width:"min(560px, calc(100vw - 48px))",maxHeight:"82vh",overflowY:"auto",background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:14,boxShadow:"0 16px 48px rgba(0,0,0,0.3)"},children:[(0,o.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"14px 16px 0"},children:[(0,o.jsx)("h3",{style:{fontSize:15,fontWeight:600,margin:0},children:s("tasks.settingsTitle")}),(0,o.jsx)("button",{type:"button",onClick:()=>t(!1),"aria-label":s("i18n.close"),style:{background:"none",border:"none",cursor:"pointer",color:"var(--text-muted)",padding:4,display:"flex"},children:(0,o.jsx)(h.X,{size:16,"aria-hidden":"true"})})]}),(0,o.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:10,padding:"14px 16px 16px"},children:[(0,o.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,o.jsx)("span",{style:{fontSize:12,fontWeight:500},children:s("tasks.settingsProject")}),(0,o.jsx)("select",{value:a,onChange:e=>l(e.target.value),style:k,children:i.map(e=>(0,o.jsx)("option",{value:e,children:e.split("/").filter(Boolean).pop()??e},e))})]}),a?(0,o.jsxs)(o.Fragment,{children:[(0,o.jsxs)("div",{style:y,children:[(0,o.jsx)("span",{style:{fontSize:12},children:s("tasks.settingsAutoProcess")}),(0,o.jsx)("input",{type:"checkbox",checked:d.autoProcess,onChange:e=>f("autoProcess",e.target.checked),style:{accentColor:"var(--accent)"}})]}),(0,o.jsxs)("div",{style:y,children:[(0,o.jsx)("span",{style:{fontSize:12},children:s("tasks.settingsMaxConcurrent")}),(0,o.jsx)("input",{type:"number",min:0,value:d.maxConcurrent,onChange:e=>f("maxConcurrent",Math.max(0,Number(e.target.value)||0)),style:{...k,width:90}})]}),(0,o.jsxs)("div",{style:y,children:[(0,o.jsx)("span",{style:{fontSize:12},children:s("tasks.settingsMergeStrategy")}),(0,o.jsxs)("select",{value:d.mergeStrategy,onChange:e=>f("mergeStrategy",e.target.value),style:{...k,width:140},children:[(0,o.jsx)("option",{value:"merge",children:s("tasks.mergeStrategyMerge")}),(0,o.jsx)("option",{value:"squash",children:s("tasks.mergeStrategySquash")})]})]}),(0,o.jsxs)("div",{style:y,children:[(0,o.jsx)("span",{style:{fontSize:12},children:s("tasks.settingsDeleteWorktree")}),(0,o.jsx)("input",{type:"checkbox",checked:d.deleteWorktreeDefault,onChange:e=>f("deleteWorktreeDefault",e.target.checked),style:{accentColor:"var(--accent)"}})]}),(0,o.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,o.jsx)("span",{style:{fontSize:12},children:s("tasks.settingsPreflightCommand")}),(0,o.jsx)("input",{value:d.preflightCommand??"",onChange:e=>f("preflightCommand",e.target.value||null),placeholder:s("tasks.settingsPreflightPlaceholder"),style:{...k,fontFamily:"var(--font-mono)",fontSize:11}})]}),(0,o.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,o.jsx)("span",{style:{fontSize:12},children:s("tasks.settingsInitCommand")}),(0,o.jsx)("input",{value:d.initCommand??"",onChange:e=>f("initCommand",e.target.value||null),placeholder:s("tasks.settingsInitPlaceholder"),style:{...k,fontFamily:"var(--font-mono)",fontSize:11}})]}),(0,o.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:6,paddingTop:4},children:[(0,o.jsx)("span",{style:{fontSize:12,fontWeight:500},children:s("tasks.settingsStagePrompts")}),pa.map(e=>(0,o.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,o.jsx)("span",{style:{fontSize:11,color:"var(--text-muted)"},children:s(`tasks.stage.${e}`)}),(0,o.jsx)("input",{value:d.stagePrompts?.[e]??"",onChange:t=>f("stagePrompts",{...d.stagePrompts??{},[e]:t.target.value}),style:{...k,fontSize:11}})]},e))]}),p&&(0,o.jsx)("button",{type:"button",onClick:()=>void v(),style:{alignSelf:"flex-start",padding:"6px 12px",borderRadius:8,background:"none",border:"1px solid var(--border)",color:"var(--text-muted)",fontSize:12,cursor:"pointer"},children:s("tasks.settingsReset")})]}):(0,o.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)",padding:8},children:s("tasks.settingsNoProject")}),(0,o.jsxs)("div",{style:{display:"flex",justifyContent:"flex-end",gap:8,marginTop:4},children:[(0,o.jsx)("button",{type:"button",onClick:()=>t(!1),style:{padding:"8px 14px",borderRadius:8,background:"none",border:"1px solid var(--border)",color:"var(--text)",fontSize:12,cursor:"pointer"},children:s("i18n.cancel")}),(0,o.jsx)("button",{type:"button",onClick:()=>void x(),disabled:!a||g,style:{padding:"8px 16px",borderRadius:8,background:"var(--accent)",color:"var(--accent-fg)",border:"none",fontSize:12,fontWeight:600,cursor:"pointer"},children:s("tasks.save")})]})]})]})})}function pd({open:e,onOpenChange:t,task:r}){let{t:s}=(0,J.s)();return(A(e&&!!r,()=>t(!1)),(0,n.useEffect)(()=>{if(!e)return},[e,r]),e&&r)?(0,o.jsx)("div",{style:{position:"fixed",inset:0,zIndex:970,display:"flex",alignItems:"center",justifyContent:"center",background:"rgba(0,0,0,0.45)"},children:(0,o.jsxs)("div",{style:{width:"min(520px, calc(100vw - 48px))",background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:14,boxShadow:"0 16px 48px rgba(0,0,0,0.3)"},children:[(0,o.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"14px 16px 0"},children:[(0,o.jsx)("h3",{style:{fontSize:15,fontWeight:600,margin:0},children:s("tasks.sessionTitle")}),(0,o.jsx)("button",{type:"button",onClick:()=>t(!1),"aria-label":s("i18n.close"),style:{background:"none",border:"none",cursor:"pointer",color:"var(--text-muted)",padding:4,display:"flex"},children:(0,o.jsx)(h.X,{size:16,"aria-hidden":"true"})})]}),(0,o.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:10,padding:"14px 16px 16px",fontSize:12},children:[(0,o.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:8,padding:10},children:[(0,o.jsx)("span",{style:{color:"var(--text-muted)"},children:s("tasks.sessionId")}),(0,o.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:11,overflowWrap:"anywhere"},children:r.conversationId??"—"})]}),r.sessionFile?(0,o.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:8,padding:10},children:[(0,o.jsx)("span",{style:{color:"var(--text-muted)"},children:s("tasks.sessionFile")}),(0,o.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:11,overflowWrap:"anywhere"},children:r.sessionFile})]}):null,(0,o.jsx)("div",{style:{fontSize:11,color:"var(--text-muted)",lineHeight:1.6},children:s("tasks.sessionHint")}),(0,o.jsx)("div",{style:{display:"flex",justifyContent:"flex-end",marginTop:4},children:(0,o.jsx)("button",{type:"button",onClick:()=>t(!1),style:{padding:"8px 16px",borderRadius:8,background:"var(--accent)",color:"var(--accent-fg)",border:"none",fontSize:12,fontWeight:600,cursor:"pointer"},children:s("i18n.close")})})]})]})}):null}let pc="__all__",pp="pi-tasks-board-filter",pu={showCanceled:!1,showArchived:!1},ph="pi:open-task-settings";function pg(){let{t:e}=(0,J.s)(),{attentionCount:t}=cq();return(0,o.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,height:36,flexShrink:0,padding:"0 16px",borderBottom:"1px solid var(--border)",background:"var(--bg-panel)"},children:[(0,o.jsxs)("h1",{style:{margin:0,display:"flex",alignItems:"center",gap:6,fontSize:13,fontWeight:600},children:[(0,o.jsx)(eG.x,{size:15,color:"var(--text-muted)","aria-hidden":"true"}),e("tasks.title"),(0,o.jsx)("span",{style:{borderRadius:999,background:"rgba(37,99,235,0.12)",color:"var(--accent)",padding:"1px 8px",fontSize:9,fontWeight:700,textTransform:"uppercase",letterSpacing:"0.04em"},children:"Beta"})]}),t>0?(0,o.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:4,borderRadius:999,background:"rgba(239,68,68,0.12)",color:"var(--status-error)",padding:"1px 8px",fontSize:10,fontWeight:700},children:[t," ",e("tasks.attentionBadge")]}):null,(0,o.jsx)("div",{style:{flex:1}}),(0,o.jsxs)("button",{type:"button",onClick:()=>window.dispatchEvent(new Event(ph)),style:{display:"inline-flex",alignItems:"center",gap:5,height:26,padding:"0 10px",borderRadius:7,background:"none",border:"none",color:"var(--text-muted)",fontSize:12,cursor:"pointer"},title:e("tasks.settingsTitle"),children:[(0,o.jsx)(cG.O,{size:13,"aria-hidden":"true"}),e("tasks.settingsTitle")]})]})}function pm({activeProject:e}){let{t}=(0,J.s)(),{tasks:s,projects:i,refetch:a}=cq(),[l,d]=(0,n.useState)(null),[c,u]=(0,n.useState)(()=>(function(){try{let e=window.localStorage.getItem(pp);if(e){let t=JSON.parse(e);return{showCanceled:t.showCanceled??!1,showArchived:t.showArchived??!1}}}catch{}return pu})()),[h,g]=(0,n.useState)(!1);(0,n.useEffect)(()=>{try{window.localStorage.setItem(pp,JSON.stringify(c))}catch{}},[c]);let[m,f]=(0,n.useState)(null),[x,v]=(0,n.useState)(!1),y=(0,n.useRef)(null),b=(0,n.useRef)({x:0,y:0}),w=(0,n.useRef)(null),j=(0,n.useRef)(null),[S,C]=(0,n.useState)(null),T=(0,n.useRef)(null);T.current=S;let R=(0,n.useRef)(!1),z=(0,n.useRef)(!1),[I,M]=(0,n.useState)(()=>Date.now());(0,n.useEffect)(()=>{let e=window.setInterval(()=>M(Date.now()),6e4);return()=>window.clearInterval(e)},[]);let[P,E]=(0,n.useState)(!1),[A,W]=(0,n.useState)(null),[N,F]=(0,n.useState)(null);(0,n.useEffect)(()=>{let e=()=>{let e,t=(e=lr,lr=null,e);t&&(W(null),F(t),E(!0))};return e(),window.addEventListener(lt,e),()=>window.removeEventListener(lt,e)},[]);let[D,L]=(0,n.useState)(null),[$,H]=(0,n.useState)(null),[O,B]=(0,n.useState)(!1),[U,_]=(0,n.useState)(null),[q,V]=(0,n.useState)(!1),[K,G]=(0,n.useState)(null),[Y,X]=(0,n.useState)("retry"),[Z,Q]=(0,n.useState)(!1),[ee,et]=(0,n.useState)(null),[er,eo]=(0,n.useState)(!1),[en,es]=(0,n.useState)(!1),[ei,ea]=(0,n.useState)(null),[el,ed]=(0,n.useState)(!1);(0,n.useEffect)(()=>{let e=()=>es(!0);return window.addEventListener(ph,e),()=>window.removeEventListener(ph,e)},[]);let ec=(0,n.useMemo)(()=>null==l?s:s.filter(e=>e.projectRoot===l),[s,l]),ep=(0,n.useMemo)(()=>(function(e,t,r=!1){let o={todo:[],inProgress:[],attention:[],done:[]};for(let n of e)("canceled"!==n.status||t)&&(null==n.archivedAt||r)&&o[function(e){switch(e){case"todo":case"queued":return"todo";case"preparing":case"running":return"inProgress";case"awaiting_input":case"review":case"merging":case"failed":return"attention";case"done":case"canceled":return"done"}}(n.status)].push(n);for(let e of cX)o[e].sort((e,t)=>(t.updatedAt??"").localeCompare(e.updatedAt??""));return o})(ec,c.showCanceled,c.showArchived),[ec,c]),eu=(0,n.useMemo)(()=>{let e=ep.todo;if(null==S)return e;let t=new Map(e.map(e=>[e.id,e])),r=S.flatMap(e=>t.get(e)??[]);for(let t of e)S.includes(t.id)||r.push(t);return r},[ep.todo,S]),eh=(0,n.useMemo)(()=>s.find(e=>e.id===D)??null,[s,D]),eg=(0,n.useMemo)(()=>s.find(e=>e.id===ei)??null,[s,ei]),em=(0,n.useCallback)(async e=>{try{await e()}catch(e){console.error("task action failed",e)}finally{a()}},[a]),ef=(0,n.useCallback)(e=>{null!=e.conversationId&&(ea(e.id),ed(!0))},[ea,ed]),ex=(0,n.useCallback)(e=>{H(e),B(!0)},[H,B]),ev=(0,n.useCallback)(()=>{W(null),E(!0)},[W,E]),ek=(0,n.useCallback)((e,t)=>{let r=w.current,o=y.current;r&&o&&(r.style.transform=`translate3d(${e-o.dx}px, ${t-o.dy}px, 0)`)},[]),ey=e=>{let t=e.currentTarget.getBoundingClientRect();y.current={dx:e.clientX-t.left,dy:e.clientY-t.top,width:t.width}},eb=(0,n.useCallback)(e=>{if(f(null),v(!1),e){R.current=!1;return}requestAnimationFrame(()=>{R.current=!1})},[f,v]),ew=(0,n.useCallback)(()=>{z.current=!0,C(null),eb(!0)},[eb,C]);(0,n.useEffect)(()=>{if(!m)return;let e=()=>{document.hidden&&ew()};return window.addEventListener("blur",ew),document.addEventListener("visibilitychange",e),()=>{window.removeEventListener("blur",ew),document.removeEventListener("visibilitychange",e)}},[m,ew]),(0,n.useEffect)(()=>{m&&!eu.some(e=>e.id===m.task.id)&&ew()},[m,eu,ew]);let ej=(0,n.useCallback)((e,t,r)=>{if(z.current){eb(!0),C(null);return}let o=j.current?.getBoundingClientRect(),n=null!=o&&t>=o.left&&t<=o.right&&r>=o.top&&r<=o.bottom;if(eb(!1),n){C(null);let t=s.find(t=>t.id===e.id);t?.status==="todo"&&null!=l&&em(()=>(0,l7.oQ)(e.id,e.projectRoot,"start"));return}let i=T.current;null!=l&&null!=i&&(async()=>{try{await (0,l7.Lu)(l,i)}catch(e){console.error("reorder failed",e)}await a(),C(null)})()},[em,eb,l,a,s]),eS=(0,n.useCallback)(()=>{em(async()=>{let e=await (0,l7.a5)(l);e>0&&console.log(`started ${e} tasks`)})},[em,l]),eC=(0,n.useCallback)(()=>{let e=ep.done.filter(e=>null==e.archivedAt);0!==e.length&&em(()=>Promise.all(e.map(e=>(0,l7.et)(e.id,e.projectRoot,!0))))},[em,ep.done]),eT=+(c.showCanceled!==pu.showCanceled)+ +(c.showArchived!==pu.showArchived),eR=s.length>0,ez=(0,n.useMemo)(()=>{let t=new Set(i);return e&&t.add(e),[...t].sort()},[i,e]),eI=(0,n.useMemo)(()=>{let e=new Map;for(let t of ez)e.set(t,t.split("/").filter(Boolean).pop()??t);return e},[ez]);return(0,o.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",minHeight:0},children:[eR&&(0,o.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:8,padding:"14px 16px 8px"},children:[(0,o.jsxs)("select",{value:l??pc,onChange:e=>d(e.target.value===pc?null:e.target.value),style:{height:30,borderRadius:999,padding:"0 10px",background:"var(--bg-panel)",border:"1px solid var(--border)",color:"var(--text)",fontSize:12,fontWeight:500,cursor:"pointer",maxWidth:"14rem"},"aria-label":t("tasks.allFolders"),children:[(0,o.jsx)("option",{value:pc,children:t("tasks.allFolders")}),ez.map(e=>(0,o.jsx)("option",{value:e,children:eI.get(e)??e},e))]}),(0,o.jsxs)("div",{style:{position:"relative"},children:[(0,o.jsxs)("button",{type:"button",onClick:()=>g(e=>!e),style:{display:"inline-flex",alignItems:"center",gap:6,height:30,borderRadius:999,padding:"0 12px",background:"var(--bg-panel)",border:"1px solid var(--border)",color:"var(--text)",fontSize:12,fontWeight:500,cursor:"pointer"},children:[(0,o.jsx)(cJ.n,{size:13,"aria-hidden":"true"}),t("tasks.filter"),eT>0?(0,o.jsx)("span",{style:{borderRadius:999,background:"rgba(37,99,235,0.12)",color:"var(--accent)",padding:"1px 6px",fontSize:10,fontWeight:700},children:eT}):null]}),h&&(0,o.jsx)("div",{style:{position:"absolute",top:34,left:0,zIndex:50,width:200,borderRadius:12,padding:6,background:"var(--bg-panel)",border:"1px solid var(--border)",boxShadow:"0 8px 24px rgba(0,0,0,0.16)"},children:[["showCanceled",t("tasks.showCanceled")],["showArchived",t("tasks.showArchived")]].map(([e,t])=>(0,o.jsxs)("label",{style:{display:"flex",alignItems:"center",gap:8,padding:"6px 8px",borderRadius:8,cursor:"pointer",fontSize:12},children:[(0,o.jsx)("input",{type:"checkbox",checked:c[e],onChange:t=>u(r=>({...r,[e]:t.target.checked})),style:{accentColor:"var(--accent)"}}),t]},e))})]}),(0,o.jsx)("div",{style:{flex:1}}),(0,o.jsxs)("button",{type:"button",onClick:eS,style:{display:"inline-flex",alignItems:"center",gap:6,height:30,borderRadius:999,padding:"0 12px",background:"none",border:"none",color:"var(--text)",fontSize:12,cursor:"pointer"},title:t("tasks.startAll"),children:[(0,o.jsx)(cY.j,{size:13,"aria-hidden":"true"}),t("tasks.startAll")]}),(0,o.jsxs)("button",{type:"button",onClick:ev,style:{display:"inline-flex",alignItems:"center",gap:6,height:30,borderRadius:999,padding:"0 14px",background:"var(--accent)",color:"var(--accent-fg)",border:"none",fontSize:12,fontWeight:600,cursor:"pointer"},children:[(0,o.jsx)(k.F,{size:13,weight:"bold","aria-hidden":"true"}),t("tasks.new")]})]}),eR?(0,o.jsx)("div",{style:{flex:1,minHeight:0,overflowX:"auto"},children:(0,o.jsx)("div",{style:{display:"grid",gridTemplateColumns:"repeat(4, minmax(0, 1fr))",gap:16,minWidth:"56rem",height:"100%",padding:"4px 16px 16px"},children:c0.map(e=>{let r="todo"===e?eu:ep[e],n=c1[e],s=e=>(0,o.jsx)(c3,{task:e,folderName:e.projectRoot?eI.get(e.projectRoot)??null:null,now:I,onOpen:()=>{R.current||L(e.id)},onStart:()=>void em(()=>(0,l7.oQ)(e.id,e.projectRoot,"start")),onCancel:()=>{_(e),V(!0)},onRetry:()=>{G(e),X("retry"),Q(!0)},onRequeue:()=>{G(e),X("requeue"),Q(!0)},onViewSession:()=>ef(e),onMerge:()=>{cZ(e)?(et(e),eo(!0)):ex(e)},onArchive:()=>void em(()=>(0,l7.et)(e.id,e.projectRoot,null==e.archivedAt)),onEdit:()=>{W(e),E(!0)}},e.id);return(0,o.jsxs)("div",{ref:"inProgress"===e?j:void 0,style:{display:"flex",flexDirection:"column",minHeight:0,gap:8},children:[(0,o.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,height:24,flexShrink:0,padding:"0 2px"},children:[(0,o.jsx)("span",{style:{width:3,height:14,borderRadius:999,background:n.marker,flexShrink:0},"aria-hidden":"true"}),(0,o.jsx)("h2",{style:{fontSize:12,fontWeight:600,color:"var(--text)"},children:t(`tasks.col${e[0].toUpperCase()}${e.slice(1)}`)}),(0,o.jsx)("span",{style:{borderRadius:999,background:"var(--bg-hover)",padding:"1px 8px",fontSize:10,fontWeight:600,color:"var(--text-muted)"},children:r.length}),(0,o.jsx)("div",{style:{flex:1}}),"done"===e&&ep.done.some(e=>null==e.archivedAt)?(0,o.jsx)("button",{type:"button",onClick:eC,style:{background:"none",border:"none",cursor:"pointer",fontSize:11,color:"var(--text-muted)",padding:"2px 6px",borderRadius:6},children:t("tasks.archiveAllDone")}):null]}),0===r.length?(0,o.jsx)("div",{style:{flex:1,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:4,borderRadius:12,border:"1px dashed var(--border)",padding:16,textAlign:"center",..."inProgress"===e&&m?x?{borderColor:"var(--accent)",background:"rgba(37,99,235,0.08)"}:{borderColor:"var(--accent)"}:{}},children:(0,o.jsx)("p",{style:{fontSize:12,color:"var(--text-muted)"},children:t(`tasks.emptyCol${e[0].toUpperCase()}${e.slice(1)}`)})}):(0,o.jsx)("div",{style:{flex:1,minHeight:0,overflowY:"auto",borderRadius:12,transition:"background 0.15s, box-shadow 0.15s",..."inProgress"===e&&m?x?{background:"rgba(37,99,235,0.06)",boxShadow:"inset 0 0 0 2px var(--accent)"}:{boxShadow:"inset 0 0 0 1px rgba(37,99,235,0.25)"}:{}},children:(0,o.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:16,paddingBottom:4},children:r.map(t=>"todo"===e?(0,o.jsx)("div",{draggable:!0,onDragStart:e=>{var r,o;e.dataTransfer.effectAllowed="move",r=e.clientX,o=e.clientY,R.current=!0,z.current=!1,b.current={x:r,y:o},f({task:t,width:y.current?.width??280})},onDrag:e=>{var t,r;let o,n;return b.current={x:t=e.clientX,y:r=e.clientY},ek(t,r),void((n=null!=(o=j.current?.getBoundingClientRect())&&t>=o.left&&t<=o.right&&r>=o.top&&r<=o.bottom)!==x&&v(n))},onDragEnd:e=>ej(t,e.clientX,e.clientY),onPointerDown:ey,style:{cursor:"grab",opacity:m?.task.id===t.id?.4:1},children:s(t)},t.id):(0,o.jsx)("div",{children:s(t)},t.id))})})]},e)})})}):(0,o.jsxs)("div",{style:{flex:1,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:12,padding:32,textAlign:"center"},children:[(0,o.jsx)(eG.x,{size:40,color:"var(--text-dim)",opacity:.4,"aria-hidden":"true"}),(0,o.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,o.jsx)("p",{style:{fontSize:14,fontWeight:500,color:"var(--text)"},children:t("tasks.empty")}),(0,o.jsx)("p",{style:{maxWidth:320,fontSize:12,color:"var(--text-muted)",lineHeight:1.6},children:t("tasks.emptyHint")})]}),(0,o.jsxs)("button",{type:"button",onClick:ev,style:{display:"inline-flex",alignItems:"center",gap:6,padding:"7px 14px",borderRadius:8,background:"var(--accent)",color:"var(--accent-fg)",border:"none",fontSize:12,fontWeight:600,cursor:"pointer"},children:[(0,o.jsx)(k.F,{size:13,weight:"bold","aria-hidden":"true"}),t("tasks.new")]})]}),(0,o.jsx)(pn,{open:P,onOpenChange:E,task:A,defaultProject:N?.projectRoot??l??e??null,projects:ez,prefillTitle:N?N.text.slice(0,80):void 0,prefillPrompt:N?N.text:void 0,onSubmit:async(e,t,o)=>{await em(async()=>{let{createTaskApi:n}=await Promise.resolve().then(r.bind(r,23084)),{updateTaskApi:s}=await Promise.resolve().then(r.bind(r,23084));A?await s(A.id,e,{title:t,config:o}):await n({projectRoot:e,title:t,config:o})}),E(!1),F(null)}}),(0,o.jsx)(pr,{open:null!=D,onOpenChange:e=>{e||L(null)},task:eh,onViewSession:ef,onMerge:ex,onEdit:e=>{W(e),E(!0)},onCancel:e=>{_(e),V(!0)},onRetry:e=>{G(e),X("retry"),Q(!0)},onRequeue:e=>{G(e),X("requeue"),Q(!0)},onComplete:e=>{et(e),eo(!0)}}),(0,o.jsx)(ps,{open:O,onOpenChange:B,task:$}),(0,o.jsx)(c7,{open:q,onOpenChange:V,task:U}),(0,o.jsx)(pi,{open:Z,onOpenChange:Q,task:K,kind:Y}),(0,o.jsx)(c9,{open:er,onOpenChange:eo,task:ee}),(0,o.jsx)(pd,{open:el&&null!=eg,onOpenChange:ed,task:eg}),(0,o.jsx)(pl,{open:en,onOpenChange:es,projectRoot:l}),m?(0,p.createPortal)((0,o.jsx)("div",{ref:w,style:{position:"fixed",left:0,top:0,zIndex:999,pointerEvents:"none",width:m.width,willChange:"transform"},"aria-hidden":"true",children:(0,o.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:8,borderRadius:12,border:x?"1px solid var(--accent)":"1px solid var(--border)",background:"var(--bg-panel)",padding:12,boxShadow:"0 8px 24px rgba(0,0,0,0.2)",transform:"rotate(-1deg)"},children:[(0,o.jsxs)("div",{style:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:8},children:[(0,o.jsx)("span",{style:{minWidth:0,overflowWrap:"break-word",fontSize:13,fontWeight:500},children:m.task.title}),(0,o.jsx)(c5,{task:m.task})]}),x?(0,o.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:4,fontSize:11,fontWeight:600,color:"var(--accent)"},children:[(0,o.jsx)(cY.j,{size:11,weight:"bold","aria-hidden":"true"}),t("tasks.dropToStart")]}):null]})}),document.body):null]})}var pf=r(62235),px=r(1022);function pv(){return!!window.__TAURI_INTERNALS__}let pk=null;function py(){return pk||(pk=r.e(8518).then(r.bind(r,38518)).then(e=>e.getCurrentWindow())),pk}async function pb(e){let t=await py();await e(t)}async function pw(){await pb(e=>e.minimize())}async function pj(){await pb(e=>e.toggleMaximize())}async function pS(){await pb(e=>e.startDragging())}async function pC(){await pb(e=>e.close())}async function pT(){return(await py()).isMaximized()}function pR(){let[e,t]=(0,n.useState)(null);return(0,n.useEffect)(()=>{pv()&&t(function(){if("u"<typeof navigator)return null;let e=navigator.platform||"";return/mac/i.test(e)?"macos":/win/i.test(e)?"windows":/linux/i.test(e)?"linux":null}())},[]),{platform:e,isDesktop:null!==e,isMacOS:"macos"===e,dragRegionProps:e?{"data-tauri-drag-region":!0}:{}}}let pz="pi-web-island-pos";function pI(e,t,r,o,n,s){return{x:Math.min(Math.max(0,e),Math.max(0,r-n)),y:Math.min(Math.max(0,t),Math.max(0,o-s))}}let pM={display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,padding:0,flexShrink:0,background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",borderRadius:7,transition:"background 0.12s, color 0.12s"};function pP({onRefreshSession:e}={}){let{t:t}=(0,J.s)(),{isDark:r}=eF(),{isDesktop:s,isMacOS:i}=pR(),a=s&&!i,[l,d]=(0,n.useState)(!1),[c,p]=(0,n.useState)(null),[u,h]=(0,n.useState)(null),g=(0,n.useRef)(null),m=(0,n.useRef)(null);(0,n.useEffect)(()=>{a&&py().then(()=>void 0,e=>{throw pk=null,e}).catch(e=>{console.error("[DynamicIsland] window API preload failed:",e)})},[a]);let f=(0,n.useCallback)(e=>{e().catch(e=>{console.error("[DynamicIsland] window command failed:",e),p(String(e)),window.setTimeout(()=>p(null),4e3)})},[]),x=(0,n.useCallback)(()=>{window.location.reload()},[]);(0,n.useEffect)(()=>{if(!pv()||!a)return;let e=()=>{pT().then(d)};return e(),window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[a]),(0,n.useEffect)(()=>{if(a)try{let e=localStorage.getItem(pz);if(e){let t=JSON.parse(e);"number"==typeof t.x&&"number"==typeof t.y&&h(pI(t.x,t.y,window.innerWidth,window.innerHeight,168,34))}}catch{}},[a]),(0,n.useEffect)(()=>{if(a&&u)try{localStorage.setItem(pz,JSON.stringify(u))}catch{}},[u,a]);let[v,k]=(0,n.useState)(0);(0,n.useEffect)(()=>{if(!a)return;let e=()=>{k(window.innerWidth),h(e=>e?pI(e.x,e.y,window.innerWidth,window.innerHeight,168,34):e)};return e(),window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[a]);let y=(0,n.useCallback)(e=>{if(0!==e.button||e.target.closest?.("[data-island-btn]"))return;let t=g.current;if(!t)return;let r=t.getBoundingClientRect();m.current={startX:e.clientX,startY:e.clientY,origX:r.left,origY:r.top},e.currentTarget.setPointerCapture(e.pointerId)},[]),b=(0,n.useCallback)(e=>{let t=m.current;if(!t)return;let r=e.clientX-t.startX,o=e.clientY-t.startY;h(pI(t.origX+r,t.origY+o,window.innerWidth,window.innerHeight,168,34))},[]),w=(0,n.useCallback)(e=>{m.current=null;try{e.currentTarget.releasePointerCapture(e.pointerId)}catch{}},[]),j=(0,n.useCallback)(()=>pj().then(()=>{d(e=>!e)}),[]),S=(0,n.useCallback)(e=>{if(!m.current&&!e.target.closest?.("[data-island-btn]")){h(null);try{localStorage.removeItem(pz)}catch{}}},[]);if(!a)return null;let T=v||window.innerWidth,R=null!==u?u.x:Math.max(0,T-168-14);return(0,o.jsxs)(o.Fragment,{children:[(0,o.jsxs)("div",{ref:g,role:"toolbar","aria-label":t("desktop.islandLabel"),title:t("desktop.islandResetHint"),onPointerDown:y,onPointerMove:b,onPointerUp:w,onPointerCancel:w,onDoubleClick:S,onMouseDown:e=>e.stopPropagation(),onDoubleClickCapture:e=>e.stopPropagation(),style:{position:"fixed",top:null!==u?u.y:100,left:R,zIndex:700,display:"flex",alignItems:"center",gap:1,padding:"3px 5px",borderRadius:999,background:"color-mix(in srgb, var(--bg-panel) 88%, transparent)",border:"1px solid var(--border)",boxShadow:r?"0 6px 24px rgba(0,0,0,0.45)":"0 6px 20px rgba(0,0,0,0.12)",cursor:"grab",userSelect:"none",touchAction:"none"},children:[(0,o.jsx)("span",{"data-island-grip":!0,"aria-hidden":"true",title:t("desktop.islandDrag"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:12,height:26,flexShrink:0,marginRight:2,color:"var(--text-dim)",cursor:"grab"},children:(0,o.jsxs)("svg",{width:"6",height:"14",viewBox:"0 0 6 14",fill:"currentColor","aria-hidden":"true",children:[(0,o.jsx)("circle",{cx:"1.5",cy:"2",r:"1.2"}),(0,o.jsx)("circle",{cx:"4.5",cy:"2",r:"1.2"}),(0,o.jsx)("circle",{cx:"1.5",cy:"7",r:"1.2"}),(0,o.jsx)("circle",{cx:"4.5",cy:"7",r:"1.2"}),(0,o.jsx)("circle",{cx:"1.5",cy:"12",r:"1.2"}),(0,o.jsx)("circle",{cx:"4.5",cy:"12",r:"1.2"})]})}),e&&(0,o.jsx)("button",{type:"button","data-island-btn":!0,"aria-label":t("desktop.refreshSession"),title:t("desktop.refreshSession"),onClick:()=>{try{e()}catch(e){console.error("[DynamicIsland] refresh session failed:",e)}},style:pM,onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background="none",e.currentTarget.style.color="var(--text-muted)"},children:(0,o.jsx)(px.P,{size:13,"aria-hidden":"true"})}),(0,o.jsx)("button",{type:"button","data-island-btn":!0,"aria-label":t("desktop.reloadPage"),title:t("desktop.reloadPage"),onClick:x,style:pM,onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background="none",e.currentTarget.style.color="var(--text-muted)"},children:(0,o.jsx)(C.S,{size:13,"aria-hidden":"true"})}),(0,o.jsx)("span",{"aria-hidden":"true",style:{width:1,height:18,flexShrink:0,background:"var(--border)",margin:"0 3px"}}),(0,o.jsx)("button",{type:"button","data-island-btn":!0,"aria-label":t("desktop.minimize"),title:t("desktop.minimize"),onClick:()=>f(pw),style:pM,onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background="none",e.currentTarget.style.color="var(--text-muted)"},children:(0,o.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1",children:(0,o.jsx)("line",{x1:"1",y1:"5",x2:"9",y2:"5"})})}),(0,o.jsx)("button",{type:"button","data-island-btn":!0,"aria-label":t(l?"desktop.restore":"desktop.maximize"),title:t(l?"desktop.restore":"desktop.maximize"),onClick:()=>f(j),style:pM,onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background="none",e.currentTarget.style.color="var(--text-muted)"},children:l?(0,o.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1",children:[(0,o.jsx)("rect",{x:"2",y:"0.5",width:"7.5",height:"7.5"}),(0,o.jsx)("path",{d:"M0.5 2.5 V9.5 H7.5"})]}):(0,o.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1",children:(0,o.jsx)("rect",{x:"0.5",y:"0.5",width:"9",height:"9"})})}),(0,o.jsx)("button",{type:"button","data-island-btn":!0,"aria-label":t("desktop.close"),title:t("desktop.close"),onClick:()=>f(pC),style:pM,onMouseEnter:e=>{e.currentTarget.style.background="#e81123",e.currentTarget.style.color="#fff"},onMouseLeave:e=>{e.currentTarget.style.background="none",e.currentTarget.style.color="var(--text-muted)"},children:(0,o.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1",children:[(0,o.jsx)("line",{x1:"0",y1:"0",x2:"10",y2:"10"}),(0,o.jsx)("line",{x1:"10",y1:"0",x2:"0",y2:"10"})]})})]}),c&&(0,o.jsx)("div",{role:"alert",style:{position:"fixed",top:(null!==u?u.y:100)+34+6,left:R,zIndex:700,maxWidth:280,padding:"5px 10px",borderRadius:8,background:"var(--bg-panel)",border:"1px solid var(--status-error, #f85149)",color:"var(--status-error, #f85149)",fontSize:11,lineHeight:1.5,wordBreak:"break-all",boxShadow:r?"0 6px 24px rgba(0,0,0,0.45)":"0 6px 20px rgba(0,0,0,0.12)",pointerEvents:"none"},children:c})]})}function pE(){try{return window.localStorage}catch{return null}}let pA="pi-web:desktop-server-hint-seen";function pW(e=pE()){if(e)try{e.setItem(pA,"1")}catch{}}function pN(){let{t:e}=(0,J.s)(),[t,r]=(0,n.useState)(!1);(0,n.useEffect)(()=>{let e=!1;try{e=new URLSearchParams(window.location.search).has("piweb_connected")}catch{e=!1}e&&function(e=pE()){if(!e)return!1;try{return"1"!==e.getItem(pA)}catch{return!1}}()&&r(!0)},[]);let s=(0,n.useCallback)(()=>{pW(),r(!1)},[]),i=(0,n.useCallback)(()=>{pW(),r(!1),window.location.href="piweb-switch://manage"},[]);return t?(0,o.jsxs)("div",{role:"status",style:{position:"fixed",top:56,right:16,zIndex:700,width:288,padding:"14px 16px 14px",borderRadius:12,background:"var(--bg-panel)",border:"1px solid var(--border)",boxShadow:"0 12px 36px rgba(0,0,0,0.32)",color:"var(--text)"},children:[(0,o.jsx)("span",{"aria-hidden":"true",style:{position:"absolute",top:-6,right:28,width:10,height:10,background:"var(--bg-panel)",borderTop:"1px solid var(--border)",borderLeft:"1px solid var(--border)",transform:"rotate(45deg)"}}),(0,o.jsxs)("div",{style:{display:"flex",alignItems:"flex-start",gap:10},children:[(0,o.jsx)(W.X,{size:18,color:"var(--accent)",style:{flexShrink:0,marginTop:1}}),(0,o.jsxs)("div",{style:{minWidth:0,flex:1},children:[(0,o.jsx)("div",{style:{fontSize:13.5,fontWeight:600,lineHeight:1.45},children:e("desktop.serverHintTitle")}),(0,o.jsx)("p",{style:{margin:"6px 0 0",fontSize:12.5,lineHeight:1.65,color:"var(--text-muted)"},children:e("desktop.serverHintBody")})]}),(0,o.jsx)("button",{type:"button",onClick:s,"aria-label":e("desktop.serverHintDismiss"),title:e("desktop.serverHintDismiss"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:22,height:22,padding:0,flexShrink:0,background:"none",border:"none",cursor:"pointer",color:"var(--text-dim)"},children:(0,o.jsx)(h.X,{size:14,"aria-hidden":"true"})})]}),(0,o.jsx)("button",{type:"button",onClick:i,style:{marginTop:12,width:"100%",display:"flex",alignItems:"center",justifyContent:"center",gap:6,padding:"8px 12px",borderRadius:9,background:"var(--accent)",border:"none",color:"#fff",fontSize:13,fontWeight:600,cursor:"pointer"},children:e("desktop.serverHintAction")})]}):null}function pF({isDark:e,toggleTheme:t,translate:r}){let[s,i]=(0,n.useState)(!1);(0,n.useEffect)(()=>{i(!0)},[]);let a=r(s?e?"desktop.switchToLight":"desktop.switchToDark":"desktop.switchToLight");return(0,o.jsx)("button",{className:"app-no-drag",suppressHydrationWarning:!0,onClick:e=>{let r=e.currentTarget.getBoundingClientRect();t({x:r.left+r.width/2,y:r.top+r.height/2})},title:a,"aria-label":a,"aria-pressed":!s||e,style:{display:"flex",alignItems:"center",justifyContent:"center",width:36,height:36,padding:0,background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",flexShrink:0,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background="none",e.currentTarget.style.color="var(--text-muted)"},children:s?e?(0,o.jsx)(ec.b,{size:16,"aria-hidden":"true"}):(0,o.jsx)(ed.A,{size:16,"aria-hidden":"true"}):(0,o.jsx)(ec.b,{size:16,"aria-hidden":"true"})})}function pD({topBarRef:e,sidebarOpen:t,onSidebarToggle:r,isDark:s,toggleTheme:i,isMobile:a,showTasks:l,tasksBoardEnabled:d,onToggleTasks:c,systemPrompt:p,activeTopPanel:u,topPanelPos:h,sessionStats:g,selectedSession:f,contextUsage:x,copiedSessionField:v,onCopySessionField:k,rightPanelOpen:y,onToggleFilePanel:b,onRefreshSession:j,onOpenSettings:S,sessionTitle:T,onWorkspaceControlsHostChange:R,onTitleRightHostChange:z,desktopChrome:I,windowDrag:M}){let P,E,N,F,D,L,$,H,O,B,U,{t:_}=(0,J.s)(),[q,V]=(0,n.useState)(!1);A(q,()=>V(!1));let[K,G]=(0,n.useState)(!1);return(0,n.useEffect)(()=>{try{G(new URLSearchParams(window.location.search).has("piweb_connected"))}catch{G(!1)}},[]),(0,o.jsxs)(o.Fragment,{children:[K&&(0,o.jsx)(pN,{}),(0,o.jsxs)("div",{ref:e,className:"app-title-bar",...I?.dragRegionProps,...M,style:{display:"flex",alignItems:"center",flexShrink:0,borderBottom:"1px solid var(--border)",height:48,background:"var(--bg-panel)",position:"relative",zIndex:600,paddingLeft:76*!!I?.isMacOS},children:[(0,o.jsxs)("div",{style:{display:"flex",alignItems:"center",minWidth:0,height:"100%",flex:"0 1 auto",position:"relative",zIndex:1},children:[(0,o.jsx)("button",{className:"app-no-drag",onClick:r,title:t?_("desktop.hideSidebar"):_("desktop.showSidebar"),"aria-label":t?_("desktop.hideSidebar"):_("desktop.showSidebar"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:36,height:36,padding:0,flexShrink:0,background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",transition:"color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.color="var(--text)"},onMouseLeave:e=>{e.currentTarget.style.color="var(--text-muted)"},children:t?(0,o.jsx)(pf.V,{size:16,"aria-hidden":"true"}):(0,o.jsx)(w.B,{size:16,"aria-hidden":"true"})}),(0,o.jsx)("div",{className:"app-no-drag",ref:R,style:{flex:"0 1 auto",minWidth:0,maxWidth:"min(60vw, 820px)",height:"100%",display:"flex",alignItems:"center",padding:"0 8px 0 0",overflow:"visible"}})]}),(0,o.jsxs)("div",{className:"app-title-drag",style:{position:"absolute",left:"var(--pi-titlebar-sidebar-offset, 0px)",right:0,top:0,bottom:0,minWidth:0,display:"flex",alignItems:"center",justifyContent:"center",padding:"0 12px",overflow:"hidden",userSelect:"none"},children:[T&&(0,o.jsx)("button",{type:"button",onClick:()=>{a&&V(!0)},title:a?T:void 0,style:{display:"block",flex:"0 1 auto",minWidth:0,maxWidth:"calc(100% - 320px)",fontSize:12,fontWeight:500,color:"var(--text-muted)",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",background:"none",border:"none",cursor:"pointer",padding:"2px 6px",borderRadius:5},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.background="none"},children:T}),(0,o.jsx)("div",{className:"app-no-drag",ref:z,style:{flexShrink:0,display:"flex",alignItems:"center",marginLeft:4}})]}),(0,o.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"flex-end",gap:3,minWidth:0,height:"100%",flexShrink:1,overflow:"hidden",marginLeft:"auto",position:"relative",zIndex:1},children:[!a&&d&&(0,o.jsx)("button",{className:"app-no-drag",onClick:c,title:l?_("desktop.hideTaskBoard"):_("desktop.showTaskBoard"),"aria-label":l?_("desktop.hideTaskBoard"):_("desktop.showTaskBoard"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:36,height:36,padding:0,background:l?"var(--bg-selected)":"none",border:"none",color:l?"var(--text)":"var(--text-muted)",cursor:"pointer",flexShrink:0,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background=l?"var(--bg-selected)":"none",e.currentTarget.style.color=l?"var(--text)":"var(--text-muted)"},children:(0,o.jsx)(eG.x,{size:16,"aria-hidden":"true"})}),(0,o.jsx)("button",{className:"app-no-drag",onClick:b,title:y?_("desktop.hideFilePanel"):_("desktop.showFilePanel"),"aria-label":y?_("desktop.hideFilePanel"):_("desktop.showFilePanel"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:36,height:36,padding:0,background:y?"var(--bg-selected)":"none",border:"none",color:y?"var(--text)":"var(--text-muted)",cursor:"pointer",flexShrink:0,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background=y?"var(--bg-selected)":"none",e.currentTarget.style.color=y?"var(--text)":"var(--text-muted)"},children:(0,o.jsx)(pf.V,{size:16,"aria-hidden":"true",style:{transform:"scaleX(-1)"}})}),(0,o.jsx)(pF,{isDark:s,toggleTheme:i,translate:_}),K&&(0,o.jsx)("button",{className:"app-no-drag",type:"button",onClick:()=>{window.location.href="piweb-switch://manage"},title:_("desktop.serverSwitch"),"aria-label":_("desktop.serverSwitch"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:36,height:36,padding:0,background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",flexShrink:0,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background="none",e.currentTarget.style.color="var(--text-muted)"},children:(0,o.jsx)(W.X,{size:16,"aria-hidden":"true"})}),!K&&(0,o.jsx)("button",{className:"app-no-drag",type:"button",onClick:j,title:_("desktop.refreshSession"),"aria-label":_("desktop.refreshSession"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:36,height:36,padding:0,background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",flexShrink:0,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background="none",e.currentTarget.style.color="var(--text-muted)"},children:(0,o.jsx)(C.S,{size:16,"aria-hidden":"true"})}),(0,o.jsx)("button",{className:"app-no-drag",type:"button",onClick:S,title:_("desktop.settings"),"aria-label":_("desktop.settings"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:36,height:36,padding:0,background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",flexShrink:0,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background="none",e.currentTarget.style.color="var(--text-muted)"},children:(0,o.jsx)(cG.O,{size:16,"aria-hidden":"true"})})]})]}),(0,o.jsx)(pP,{onRefreshSession:j}),u&&h&&(0,o.jsxs)("div",{style:{position:"fixed",top:h.top,left:h.left,width:h.width,maxHeight:`calc(100dvh - ${h.top}px)`,overflowY:"auto",zIndex:500},children:["system"===u&&(0,o.jsx)("div",{style:{background:"var(--bg-panel)",borderBottom:"1px solid var(--border)"},children:p?(0,o.jsx)("div",{style:{maxHeight:"min(600px, 75vh)",overflowY:"auto",padding:"12px 16px",color:"var(--text-muted)",fontSize:12,lineHeight:1.6,whiteSpace:"pre-wrap",fontFamily:"var(--font-mono)"},children:p}):""===p?(0,o.jsx)("div",{style:{padding:"10px 16px",fontSize:12,color:"var(--text-muted)",fontStyle:"italic"},children:"System prompt is empty (tools are disabled)"}):(0,o.jsx)("div",{style:{padding:"10px 16px",fontSize:12,color:"var(--text-muted)",fontStyle:"italic"},children:"Send a message to load the system prompt"})}),"session"===u&&(0,o.jsx)("div",{style:{background:"var(--bg-panel)",borderBottom:"1px solid var(--border)",boxShadow:"0 10px 28px rgba(0,0,0,0.10)",padding:"12px 16px"},children:g?(P=[...g.sessionName?[{label:_("desktop.name"),value:g.sessionName,copyField:null}]:[],{label:_("desktop.sessionInfoFile"),value:g.sessionFile??_("desktop.sessionInfoInMemory"),copyField:"file"},{label:_("desktop.sessionInfoId"),value:g.sessionId,copyField:"id"}],E=[[_("desktop.sessionInfoUser"),g.userMessages.toLocaleString()],[_("desktop.sessionInfoAssistant"),g.assistantMessages.toLocaleString()],[_("desktop.sessionInfoToolCalls"),g.toolCalls.toLocaleString()],[_("desktop.sessionInfoToolResults"),g.toolResults.toLocaleString()],[_("desktop.sessionInfoTotal"),g.totalMessages.toLocaleString()]],N=[[_("desktop.sessionInfoInput"),g.tokens.input.toLocaleString()],[_("desktop.sessionInfoOutput"),g.tokens.output.toLocaleString()],...g.tokens.cacheRead>0?[[_("desktop.sessionInfoCacheRead"),g.tokens.cacheRead.toLocaleString()]]:[],...g.tokens.cacheWrite>0?[[_("desktop.sessionInfoCacheWrite"),g.tokens.cacheWrite.toLocaleString()]]:[],[_("desktop.sessionInfoTotal"),g.tokens.total.toLocaleString()]],F=x??g.contextUsage,L=[...g.cost>0?[[_("desktop.sessionInfoCost"),`$${g.cost.toFixed(4)}`]]:[],...F?.contextWindow?[[_("desktop.sessionInfoContext"),`${null!==F.percent?`${F.percent.toFixed(1)}%`:"?"} / ${(D=F.contextWindow)>=1e6?`${(D/1e6).toFixed(1)}M`:D>=1e3?`${(D/1e3).toFixed(0)}k`:String(D)}`]]:[]],$=(e,t,r="left",n=!1)=>(0,o.jsxs)("div",{style:{minWidth:0},children:[(0,o.jsx)("div",{style:{fontSize:11,fontWeight:700,color:"var(--text)",marginBottom:6},children:e}),(0,o.jsx)("div",{style:{display:"grid",gridTemplateColumns:n?"max-content max-content":"auto minmax(0, 1fr)",columnGap:n?14:12,rowGap:4,justifyContent:n?"start":void 0},children:t.map(([t,s])=>(0,o.jsxs)("div",{style:{display:"contents"},children:[(0,o.jsx)("div",{style:{color:"var(--text-dim)",whiteSpace:"nowrap"},children:t}),(0,o.jsx)("div",{style:{color:"var(--text-muted)",minWidth:0,overflowWrap:n?"normal":"anywhere",textAlign:r,whiteSpace:"right"===r?"nowrap":"normal"},children:s})]},`${e}:${t}`))})]}),H=(e,t)=>{let r=v===e;return(0,o.jsx)("button",{type:"button",title:r?_("desktop.copied"):_({file:"desktop.copyFilePath",id:"desktop.copySessionId",projectDir:"desktop.copyProjectDir",gitBranch:"desktop.copyGitBranch",gitWorktree:"desktop.copyGitWorktree"}[e]),onClick:()=>k(e,t),style:{alignSelf:"start",display:"inline-flex",alignItems:"center",justifyContent:"center",width:22,height:22,marginTop:-2,color:r?"var(--accent)":"var(--text-dim)",background:"transparent",border:"1px solid var(--border)",borderRadius:4,cursor:"pointer",flex:"0 0 auto",transition:"color 0.12s, border-color 0.12s, background 0.12s"},onMouseEnter:e=>{e.currentTarget.style.color="var(--accent)",e.currentTarget.style.borderColor="var(--accent)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.color=r?"var(--accent)":"var(--text-dim)",e.currentTarget.style.borderColor="var(--border)",e.currentTarget.style.background="transparent"},children:r?(0,o.jsx)(m.J,{size:12,"aria-hidden":"true"}):(0,o.jsx)(o2.Q,{size:12,"aria-hidden":"true"})})},O=(0,o.jsxs)("div",{style:{minWidth:0},children:[(0,o.jsx)("div",{style:{fontSize:11,fontWeight:700,color:"var(--text)",marginBottom:6},children:_("desktop.sessionInfoTitle")}),(0,o.jsx)("div",{style:{display:"grid",gridTemplateColumns:"auto minmax(0, 1fr) auto",columnGap:12,rowGap:8,alignItems:"start"},children:P.map(e=>(0,o.jsxs)("div",{style:{display:"contents"},children:[(0,o.jsx)("div",{style:{color:"var(--text-dim)",whiteSpace:"nowrap"},children:e.label}),(0,o.jsx)("div",{style:{color:"var(--text-muted)",minWidth:0,overflowWrap:"anywhere",wordBreak:"break-word",whiteSpace:"normal"},children:e.value}),(0,o.jsx)("div",{children:e.copyField?H(e.copyField,e.value):null})]},`session-info:${e.label}`))})]}),U=(B=[...f?[{label:_("desktop.projectDir"),value:f.projectRoot??f.cwd,copyField:"projectDir"}]:[],...f?.branch?[{label:_("desktop.gitBranch"),value:f.branch,copyField:"gitBranch"}]:[],...f?.isWorktree?[{label:_("desktop.gitWorktree"),value:f.cwd,copyField:"gitWorktree"}]:[]]).length>0?(0,o.jsxs)("div",{style:{minWidth:0},children:[(0,o.jsx)("div",{style:{fontSize:11,fontWeight:700,color:"var(--text)",marginBottom:6},children:_("desktop.projectSection")}),(0,o.jsx)("div",{style:{display:"grid",gridTemplateColumns:"auto minmax(0, 1fr) auto",columnGap:12,rowGap:8,alignItems:"start"},children:B.map(e=>(0,o.jsxs)("div",{style:{display:"contents"},children:[(0,o.jsx)("div",{style:{color:"var(--text-dim)",whiteSpace:"nowrap"},children:e.label}),(0,o.jsx)("div",{style:{color:"var(--text-muted)",minWidth:0,overflowWrap:"anywhere",wordBreak:"break-word",whiteSpace:"normal"},children:e.value}),(0,o.jsx)("div",{children:e.copyField?H(e.copyField,e.value):null})]},`project-info:${e.label}`))})]}):null,(0,o.jsxs)("div",{style:{display:"grid",gridTemplateColumns:a?"1fr":"minmax(360px, 1.7fr) minmax(140px, 0.55fr) minmax(190px, 0.75fr)",gap:a?16:24,fontSize:12,lineHeight:1.5,fontFamily:"var(--font-mono)"},children:[(0,o.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:a?16:20,minWidth:0},children:[O,U]}),$(_("desktop.sessionInfoMessages"),E),$(_("desktop.sessionInfoTokens"),[...N,...L],"right",!0)]})):(0,o.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)",fontStyle:"italic"},children:_("desktop.sendMessageForSessionInfo")})})]}),q&&T&&(0,o.jsx)("div",{style:{position:"fixed",inset:0,zIndex:3e3,display:"flex",alignItems:"flex-start",justifyContent:"center",paddingTop:48,background:"rgba(0,0,0,0.35)"},children:(0,o.jsx)("div",{role:"dialog","aria-label":T,style:{maxWidth:"min(560px, calc(100vw - 32px))",maxHeight:"min(60vh, 400px)",overflow:"auto",background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:12,boxShadow:"0 16px 40px rgba(0,0,0,0.3)",padding:"14px 18px",fontSize:13,lineHeight:1.6,color:"var(--text)",wordBreak:"break-word",whiteSpace:"pre-wrap"},children:T})})]})}function pL({cwd:e,busy:t,error:r,onCancelAction:n,onConfirmAction:s}){let{t:i}=(0,J.s)();return A(!t,n),(0,o.jsx)("div",{role:"presentation",style:{position:"fixed",inset:0,zIndex:1100,display:"flex",alignItems:"center",justifyContent:"center",padding:16,background:"rgba(0, 0, 0, 0.4)"},children:(0,o.jsxs)("section",{role:"dialog","aria-modal":"true","aria-labelledby":"project-trust-title",style:{width:440,maxWidth:"100%",border:"1px solid var(--border)",borderRadius:8,background:"var(--bg-panel)",boxShadow:"0 12px 36px rgba(0, 0, 0, 0.24)",overflow:"hidden"},children:[(0,o.jsxs)("div",{style:{display:"flex",gap:12,padding:"18px 18px 14px"},children:[(0,o.jsx)(a9.o,{size:21,weight:"duotone",color:"var(--accent-orange)",style:{flexShrink:0,marginTop:1},"aria-hidden":"true"}),(0,o.jsxs)("div",{style:{minWidth:0},children:[(0,o.jsx)("h2",{id:"project-trust-title",style:{margin:0,fontSize:15,fontWeight:700,color:"var(--text)"},children:i("desktop.trustProjectTitle")}),(0,o.jsx)("p",{style:{margin:"7px 0 0",fontSize:12,lineHeight:1.6,color:"var(--text-muted)"},children:i("desktop.trustProjectBody")}),(0,o.jsx)("code",{style:{display:"block",marginTop:10,padding:"8px 10px",border:"1px solid var(--border)",borderRadius:5,background:"var(--bg)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:11,overflowWrap:"anywhere"},children:e}),r&&(0,o.jsx)("div",{role:"alert",style:{marginTop:10,color:"var(--accent-red)",fontSize:12,lineHeight:1.5},children:r})]})]}),(0,o.jsxs)("footer",{style:{display:"flex",justifyContent:"flex-end",gap:8,padding:"10px 18px",borderTop:"1px solid var(--border)"},children:[(0,o.jsx)("button",{type:"button",onClick:n,disabled:t,style:{height:32,padding:"0 12px",border:"1px solid var(--border)",borderRadius:5,background:"transparent",color:"var(--text-muted)",cursor:t?"not-allowed":"pointer",fontSize:12},children:i("desktop.cancel")}),(0,o.jsx)("button",{type:"button",onClick:s,disabled:t,style:{height:32,padding:"0 12px",border:"1px solid var(--accent)",borderRadius:5,background:"var(--accent)",color:"white",cursor:t?"wait":"pointer",opacity:t?.7:1,fontSize:12,fontWeight:600},children:i(t?"desktop.trustingProject":"desktop.trustProject")})]})]})})}function p$(e,t,r){let o=Number.isFinite(e)?e:t,n=Math.max(t,r);return Math.round(Math.max(t,Math.min(n,o)))}function pH(e){return p$(.42*e,360,640)}function pO(e,t){try{window.localStorage.setItem(e,String(t))}catch{}}function pB(e){let{ariaLabel:t,cssVariable:r,defaultWidth:o,getDefaultWidth:s,getMaxWidth:i,growthDirection:a,maxWidth:l,minWidth:d,storageKey:c,widthRef:p}=e,u=(0,n.useRef)(null),h=(0,n.useRef)(null),g=(0,n.useRef)(!1),[m,f]=(0,n.useState)(o),[x,v]=(0,n.useState)(!1),[k,y]=(0,n.useState)(!1);(0,n.useEffect)(()=>{y(!0)},[]);let b=(0,n.useCallback)(()=>Math.min(l,Math.max(d,i())),[i,l,d]),w=(0,n.useCallback)(e=>p$(e,d,b()),[b,d]),j=(0,n.useCallback)(e=>{p.current=e;let t=`${e}px`;u.current?.style.setProperty(r,t),u.current?.parentElement?.style.setProperty(r,t)},[r,p]),S=(0,n.useCallback)((e,t={})=>{let{forcePersist:r=!1,persist:o=!0}=t,n=w(e),s=n!==p.current;return j(n),f(n),o&&(s||r)&&pO(c,n),n},[j,w,c,p]),C=(0,n.useCallback)(e=>{document.body.style.cursor=e.previousCursor,document.body.style.userSelect=e.previousUserSelect},[]),T=(0,n.useCallback)(e=>{let t=h.current;if(t&&t.pointerId===e){h.current=null,C(t),v(!1),S(p.current,{forcePersist:!0});try{t.target.hasPointerCapture(e)&&t.target.releasePointerCapture(e)}catch{}}},[S,C,p]),R=(0,n.useCallback)(e=>{if("mouse"===e.pointerType&&0!==e.button)return;e.preventDefault(),e.stopPropagation();let t=h.current;t&&T(t.pointerId);let r=e.currentTarget;r.focus({preventScroll:!0}),r.setPointerCapture(e.pointerId),h.current={pointerId:e.pointerId,startX:e.clientX,startWidth:p.current,target:r,previousCursor:document.body.style.cursor,previousUserSelect:document.body.style.userSelect},document.body.style.cursor="col-resize",document.body.style.userSelect="none",v(!0)},[T,p]),z=(0,n.useCallback)(e=>{let t=h.current;if(!t||t.pointerId!==e.pointerId)return;if("mouse"===e.pointerType&&0===e.buttons)return void T(e.pointerId);e.preventDefault();let r="right"===a?1:-1,o=w(t.startWidth+(e.clientX-t.startX)*r);j(o),e.currentTarget.setAttribute("aria-valuenow",String(o)),e.currentTarget.setAttribute("aria-valuetext",`${o} px`)},[j,w,T,a]),I=(0,n.useCallback)(e=>{T(e.pointerId)},[T]),M=(0,n.useCallback)(e=>{T(e.pointerId)},[T]),P=(0,n.useCallback)(e=>{T(e.pointerId)},[T]),E=(0,n.useCallback)(()=>{S(s?.()??o,{forcePersist:!0})},[S,o,s]),A=(0,n.useCallback)(()=>{S(p.current)},[S,p]),W=(0,n.useCallback)(e=>{let t=e.shiftKey?32:12,r="right"===a?"ArrowRight":"ArrowLeft",o="right"===a?"ArrowLeft":"ArrowRight";e.key===r?(e.preventDefault(),S(p.current+t,{forcePersist:!0})):e.key===o?(e.preventDefault(),S(p.current-t,{forcePersist:!0})):"Home"===e.key?(e.preventDefault(),S(d,{forcePersist:!0})):"End"===e.key?(e.preventDefault(),S(b(),{forcePersist:!0})):"Enter"===e.key&&(e.preventDefault(),E())},[S,b,a,d,E,p]);return(0,n.useEffect)(()=>{if(g.current)return;g.current=!0;let e=function(e){try{let t=window.localStorage.getItem(e);if(null===t)return null;let r=Number.parseInt(t,10);return Number.isFinite(r)?r:null}catch{return null}}(c),t=S(e??s?.()??o,{persist:!1});null!==e&&e!==t&&pO(c,t)},[S,o,s,c]),(0,n.useEffect)(()=>{if(!g.current)return;S(p.current);let e=()=>{S(p.current)};return window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[S,p]),(0,n.useEffect)(()=>{if(!x)return;let e=()=>{let e=h.current;e&&T(e.pointerId)},t=()=>{"visible"!==document.visibilityState&&e()};return window.addEventListener("blur",e),document.addEventListener("visibilitychange",t),()=>{window.removeEventListener("blur",e),document.removeEventListener("visibilitychange",t)}},[T,x]),(0,n.useEffect)(()=>()=>{let e=h.current;e&&(h.current=null,C(e))},[C]),{isResizing:x,panelRef:u,reclampWidth:A,separatorProps:{"aria-label":t,"aria-orientation":"vertical","aria-valuemax":k?b():l,"aria-valuemin":d,"aria-valuenow":m,"aria-valuetext":`${m} px`,onDoubleClick:E,onKeyDown:W,onLostPointerCapture:P,onPointerCancel:M,onPointerDown:R,onPointerMove:z,onPointerUp:I,role:"separator",tabIndex:0},width:m}}function pU(e){return e.name||e.firstMessage||e.id.slice(0,12)}function p_({status:e}){return"running"===e||"starting"===e?(0,o.jsxs)("svg",{className:"animate-spin",width:"13",height:"13",viewBox:"0 0 24 24",fill:"none","aria-hidden":"true",children:[(0,o.jsx)("circle",{cx:"12",cy:"12",r:"9",stroke:"currentColor",strokeWidth:"2",opacity:"0.25"}),(0,o.jsx)("path",{d:"M21 12a9 9 0 0 0-9-9",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})]}):"failed"===e?(0,o.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:[(0,o.jsx)("circle",{cx:"12",cy:"12",r:"9"}),(0,o.jsx)("path",{d:"m9 9 6 6M15 9l-6 6"})]}):"aborted"===e||"interrupted"===e?(0,o.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:[(0,o.jsx)("circle",{cx:"12",cy:"12",r:"9"}),(0,o.jsx)("path",{d:"M9 9h6v6H9z"})]}):(0,o.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,o.jsx)("circle",{cx:"12",cy:"12",r:"9"}),(0,o.jsx)("path",{d:"m8 12 3 3 5-6"})]})}function pq({session:e,main:t,selected:r,running:n,onSelect:s}){let{locale:i,t:a}=(0,J.s)(),l=e.relation?.kind==="subagent"?e.relation:null,d=n?"running":l?.status??"completed",c=t?a("agentSwitcher.main"):l?.description||pU(e),p=t?pU(e):`${l?.profile??a("agentSwitcher.subagent")} \xb7 ${function(e,t){let r=new Date(e).getTime();if(!Number.isFinite(r))return"";let o=Math.round((r-Date.now())/1e3),n=new Intl.RelativeTimeFormat(t,{numeric:"auto"});if(60>Math.abs(o))return n.format(o,"second");let s=Math.round(o/60);if(60>Math.abs(s))return n.format(s,"minute");let i=Math.round(s/60);return 24>Math.abs(i)?n.format(i,"hour"):n.format(Math.round(i/24),"day")}(e.modified,i)}`;return(0,o.jsxs)("button",{type:"button",role:"option","aria-selected":r,onClick:s,style:{width:"100%",minHeight:56,display:"grid",gridTemplateColumns:"28px minmax(0, 1fr) auto",alignItems:"center",gap:9,padding:"7px 12px",border:"none",borderBottom:"1px solid var(--border)",borderLeft:r?"2px solid var(--accent)":"2px solid transparent",background:r?"var(--bg-selected)":"transparent",color:"var(--text)",cursor:"pointer",textAlign:"left"},onMouseEnter:e=>{r||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{r||(e.currentTarget.style.background="transparent")},children:[(0,o.jsx)("span",{style:{width:28,height:28,display:"grid",placeItems:"center",color:t?"var(--text-muted)":"var(--accent)"},children:t?(0,o.jsxs)("svg",{width:"17",height:"17",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,o.jsx)("circle",{cx:"12",cy:"8",r:"4"}),(0,o.jsx)("path",{d:"M4 21a8 8 0 0 1 16 0"})]}):(0,o.jsxs)("svg",{width:"17",height:"17",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,o.jsx)("rect",{x:"5",y:"7",width:"14",height:"11",rx:"2"}),(0,o.jsx)("path",{d:"M9 11h.01M15 11h.01M9 15h6M12 7V4M10 4h4"})]})}),(0,o.jsxs)("span",{style:{minWidth:0},children:[(0,o.jsx)("span",{style:{display:"block",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:12,fontWeight:r?600:500},title:c,children:c}),(0,o.jsx)("span",{style:{display:"block",marginTop:2,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontSize:11},title:p,children:p})]}),(0,o.jsx)("span",{style:{display:"flex",alignItems:"center",gap:6,color:t&&!n?"var(--text-dim)":"running"===d||"starting"===d?"var(--accent)":"completed"===d?"var(--status-success)":"failed"===d?"var(--status-error)":"aborted"===d?"var(--status-warning)":"var(--text-dim)",fontSize:11,whiteSpace:"nowrap"},children:t&&!n?r?a("agentSwitcher.current"):null:(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)(p_,{status:d}),(0,o.jsx)("span",{children:a(`agentSwitcher.status.${d}`)})]})})]})}function pV({rootSession:e,subagents:t,selectedSessionId:r,runningSessionIds:s,onSelectSession:i}){let{t:a}=(0,J.s)(),[l,d]=(0,n.useState)(""),c=(0,n.useMemo)(()=>[...t].sort((e,t)=>{let r=s.has(e.id);return r!==s.has(t.id)?r?-1:1:t.modified.localeCompare(e.modified)}),[s,t]),p=l.trim().toLowerCase(),u=p?c.filter(e=>{let t=e.relation?.kind==="subagent"?e.relation:null;return[t?.description,t?.profile,e.name,e.firstMessage].some(e=>e?.toLowerCase().includes(p))}):c,h=t.filter(e=>s.has(e.id)).length;return(0,o.jsx)("div",{role:"listbox","aria-label":a("agentSwitcher.title"),style:{background:"var(--bg-panel)",borderLeft:"1px solid var(--border)",borderRight:"1px solid var(--border)",borderBottom:"1px solid var(--border)",borderRadius:"0 0 6px 6px",boxShadow:"0 10px 28px rgba(0,0,0,0.10)",overflow:"hidden"},children:(0,o.jsxs)("div",{children:[(0,o.jsxs)("div",{style:{minHeight:44,display:"flex",alignItems:"center",gap:8,padding:"7px 12px",borderBottom:"1px solid var(--border)"},children:[(0,o.jsx)("strong",{style:{fontSize:12,fontWeight:600},children:a("agentSwitcher.title")}),(0,o.jsx)("span",{style:{color:"var(--text-dim)",fontSize:11},children:a("agentSwitcher.count",{count:t.length})}),h>0&&(0,o.jsx)("span",{style:{marginLeft:"auto",color:"var(--accent)",fontSize:11},children:a("agentSwitcher.runningCount",{count:h})})]}),t.length>8&&(0,o.jsx)("div",{style:{padding:8,borderBottom:"1px solid var(--border)"},children:(0,o.jsx)("input",{type:"search",value:l,onChange:e=>d(e.target.value),placeholder:a("agentSwitcher.search"),"aria-label":a("agentSwitcher.search"),style:{width:"100%",height:32,padding:"0 10px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg)",color:"var(--text)",fontSize:12,outline:"none"}})}),(0,o.jsxs)("div",{style:{maxHeight:"min(58dvh, 480px)",overflowY:"auto"},children:[(0,o.jsx)(pq,{session:e,main:!0,selected:e.id===r,running:s.has(e.id),onSelect:()=>i(e)}),u.map(e=>(0,o.jsx)(pq,{session:e,selected:e.id===r,running:s.has(e.id),onSelect:()=>i(e)},e.id)),0===u.length&&(0,o.jsx)("div",{style:{padding:"22px 12px",color:"var(--text-dim)",fontSize:12,textAlign:"center"},children:a("agentSwitcher.noMatches")})]})]})})}function pK(){var e;let t,r,l=(0,i.useRouter)(),d=(0,i.useSearchParams)(),c=(0,n.useMemo)(()=>{let e;return{requestedCwd:e=d.get("cwd")?.trim()||null,sessionId:e?null:d.get("session")}},[d]),{isDark:p,toggleTheme:u}=eF(),{t:h}=(0,J.s)(),g=tu(),[m,f]=(0,n.useState)(null),[x,v]=(0,n.useState)(null),[k,y]=(0,n.useState)(0),[b,w]=(0,n.useState)(0),[j,S]=(0,n.useState)(0),[C,T]=(0,n.useState)(!1),[R,z]=(0,n.useState)("models"),[I,M]=(0,n.useState)(0),[P,E]=(0,n.useState)(null),[A,W]=(0,n.useState)(!1),[N,F]=(0,n.useState)(!1),[D,L]=(0,n.useState)(null),[$,H]=(0,n.useState)(!0),[O,B]=(0,n.useState)(!1);(0,n.useEffect)(()=>{g&&H(!1)},[g]),(0,n.useEffect)(()=>{B(!0)},[]);let U=(0,n.useRef)(null),_=(0,n.useRef)(null),[q,V]=(0,n.useState)(null),[K,G]=(0,n.useState)(null),[Y,X]=(0,n.useState)(null),Z=pR(),Q=function(){let{isDesktop:e,isMacOS:t}=pR(),r=(0,n.useCallback)(e=>{var t;0===e.button&&(t=e.target).closest("[data-tauri-drag-region]")&&!t.closest('button, a, input, textarea, select, [role="button"], [contenteditable="true"], [data-no-drag]')&&(e.preventDefault(),e.stopPropagation(),2===e.detail?pj():pS())},[]);return e&&!t?{onMouseDown:r}:{}}(),[ee,et]=(0,n.useState)(null),er=(0,n.useCallback)(e=>{et(e)},[]),[eo,en]=(0,n.useState)(null),es=(0,n.useCallback)(e=>{en(e)},[]),[ei,ea]=(0,n.useState)(null),el=(0,n.useRef)(null),ed=(0,n.useCallback)((e,t)=>{ot(t).then(()=>{el.current&&clearTimeout(el.current),ea(e),el.current=setTimeout(()=>ea(null),1400)})},[]);(0,n.useEffect)(()=>()=>{el.current&&clearTimeout(el.current)},[]);let[ec,ep]=(0,n.useState)(null),eu=(0,n.useCallback)(e=>{ep(e)},[]),[eh,eg]=(0,n.useState)(null),[em,ef]=(0,n.useState)(null),ex=(0,n.useCallback)(()=>{g&&H(!1),eg("session")},[g]),ev=(0,n.useCallback)(()=>{g&&eg(null),H(e=>!e)},[g]);(0,n.useEffect)(()=>{if(!eh||!_.current)return;let e=()=>{let e=_.current.getBoundingClientRect();ef({top:e.bottom,left:e.left,width:e.width})};e();let t=new ResizeObserver(e);return t.observe(_.current),()=>t.disconnect()},[eh]);let[ek,ey]=(0,n.useState)([]),[eb,ew]=(0,n.useState)(null),[ej,eS]=(0,n.useState)(!1),eC=(0,n.useRef)(!1);(0,n.useEffect)(()=>{let e;if(!eC.current){eC.current=!0;try{e=function(e){try{let t=JSON.parse(e??"null");if(!cB(t))return{tabs:[],activeId:null,open:!1};let r=[],o=new Set;for(let e of Array.isArray(t.tabs)?t.tabs:[]){if(!cB(e))continue;let t="string"==typeof e.id?e.id:"",n="string"==typeof e.filePath?e.filePath:"",s="string"==typeof e.label?e.label:"",i="subagent"===e.kind,a="string"==typeof e.sessionId?e.sessionId:"";!(!t||!s||o.has(t))&&(i?a:n)&&(o.add(t),r.push({id:t,label:s,filePath:n,..."terminal"===e.kind?{kind:"terminal"}:{},...i?{kind:"subagent",sessionId:a}:{},..."string"==typeof e.sourceSessionId?{sourceSessionId:e.sourceSessionId}:{},..."diff"===e.initialDisplayMode?{initialDisplayMode:"diff"}:{}}))}let n="string"==typeof t.activeId&&r.some(e=>e.id===t.activeId)?t.activeId:r[r.length-1]?.id??null;return{tabs:r,activeId:n,open:!0===t.open&&r.length>0}}catch{return{tabs:[],activeId:null,open:!1}}}(localStorage.getItem(cO))}catch{return}0!==e.tabs.length&&(ey(e.tabs),ew(e.activeId),eS(e.open))}},[]),(0,n.useEffect)(()=>{if(eC.current)try{localStorage.setItem(cO,JSON.stringify({tabs:ek.filter(e=>!e.closing).map(e=>({id:e.id,label:e.label,filePath:e.filePath,...e.kind?{kind:e.kind}:{},...e.sessionId?{sessionId:e.sessionId}:{},...e.sourceSessionId?{sourceSessionId:e.sourceSessionId}:{},...e.initialDisplayMode?{initialDisplayMode:e.initialDisplayMode}:{}})),activeId:eb,open:ej}))}catch{}},[ek,eb,ej]);let[eT,eR]=(0,n.useState)(!1),[ez,eI]=(0,n.useState)([]),[eM,eP]=(0,n.useState)(()=>new Set);(0,n.useEffect)(()=>{if(!eT)return void eI(e=>0===e.length?e:[]);let e=!1,t=()=>{fetch("/api/sessions",{cache:"no-store"}).then(e=>e.json()).then(t=>{e||(eI(t.sessions??[]),eP(new Set(t.runningSessionIds??[])))}).catch(()=>{})};t();let r=setInterval(t,3e3);return()=>{e=!0,clearInterval(r)}},[eT,m?.id,k]);let eE=(0,n.useCallback)(async e=>{try{let t=await fetch(`/api/sessions/${encodeURIComponent(e)}`,{cache:"no-store"}),r=await t.json();if(!t.ok||!r.info)throw Error(r.error??`HTTP ${t.status}`);e9.current(r.info)}catch(e){console.error("[pi-web] failed to open session:",e instanceof Error?e.message:e)}},[]),eA=(0,n.useRef)(260),eW=(0,n.useRef)(pH(1366)),eN=(0,n.useCallback)(()=>pH(window.innerWidth),[]),eD=(0,n.useCallback)(()=>(function(e){let{viewportWidth:t,rightPanelOpen:r,rightPanelWidth:o}=e;if(t<=640)return 480;let n=t<960;return Math.min(480,t-(n?320:420)-(!n&&r?o:0))})({viewportWidth:window.innerWidth,rightPanelOpen:ej,rightPanelWidth:eW.current}),[ej]),eL=(0,n.useCallback)(()=>(function(e){let{viewportWidth:t,sidebarOpen:r,sidebarWidth:o}=e;return t<960?1200:Math.min(1200,t-420-(r?o:0))})({viewportWidth:window.innerWidth,sidebarOpen:$,sidebarWidth:eA.current}),[$]),e$=pB({ariaLabel:h("desktop.resizeSidebar"),cssVariable:"--sidebar-width",defaultWidth:260,getMaxWidth:eD,growthDirection:"right",maxWidth:480,minWidth:180,storageKey:"pi-sidebar-width",widthRef:eA}),eH=pB({ariaLabel:h("desktop.resizeFilePanel"),cssVariable:"--right-panel-width",defaultWidth:pH(1366),getDefaultWidth:eN,getMaxWidth:eL,growthDirection:"left",maxWidth:1200,minWidth:300,storageKey:"pi-right-panel-width",widthRef:eW}),eO=e$.reclampWidth,eB=eH.reclampWidth;(0,n.useEffect)(()=>{ej&&(eO(),eB())},[eB,eO,ej]);let eU=(0,n.useCallback)((e,t)=>{U.current?.insertText(l3(e,t))},[]),e_=(0,n.useCallback)(e=>{let t=e.map(e=>l3(e,!1)).join("");t&&U.current?.insertText(t)},[]),eq=(0,n.useCallback)((e,t,r)=>{let o,n,s,i;U.current?.insertText((o=Math.max(1,Math.min(t,r)),n=Math.max(1,Math.max(t,r)),s=e.includes(" ")?`@"${e}"`:`@${e}`,i=o===n?`:${o}`:`:${o}-${n}`,`${s}${i} `))},[]),[eV,eK]=(0,n.useState)(()=>c.sessionId),[eG,eJ]=(0,n.useState)(null),[eY,eX]=(0,n.useState)(()=>c.requestedCwd?"validating":"idle"),[eZ,eQ]=(0,n.useState)(null),[e0,e1]=(0,n.useState)(()=>!eV),e2=(0,n.useRef)(!1),e6=(0,n.useRef)(new Map),[e4,e5]=(0,n.useState)(null),e8=(0,n.useRef)("");(0,n.useEffect)(()=>{let e=`${c.requestedCwd??""}|${c.sessionId??""}`;e8.current!==e&&(e8.current=e,eK(c.sessionId),e1(!c.sessionId),c.requestedCwd||eX("idle"),eQ(null))},[c]),(0,n.useEffect)(()=>{let e=c.requestedCwd;if(!e)return;let t=new AbortController;return eX("validating"),eQ(null),fetch("/api/cwd/validate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e}),signal:t.signal}).then(async e=>{let t=await e.json().catch(()=>({}));if(!e.ok||!t.cwd)throw Error(t.error??`HTTP ${e.status}`);e2.current=!0,v(t.cwd),eX("ready")}).catch(e=>{t.signal.aborted||(eQ(e instanceof Error?e.message:String(e)),eX("error"))}),()=>t.abort()},[c]);let e3=(0,n.useCallback)((e,t)=>{if(!e)return;if(eJ(e),e2.current&&m&&sC(m.projectRoot??m.cwd,t??e)){if(e2.current=!1,m){let e=m.projectRoot??m.cwd;e&&e6.current.set(e,m.id)}return}e2.current=!1;let r=t??e;if(m&&sC(m.projectRoot??m.cwd,r)){(m.projectRoot??m.cwd)&&e6.current.set(r,m.id);return}if(m){let e=m.projectRoot??m.cwd;e&&e6.current.set(e,m.id)}f(null),v(t=>t&&t!==e?null:t),w(e=>e+1),et(null),eg(null),window.history.replaceState(null,"","/");let o=e6.current.get(r);e5(o?{projectRoot:r,sessionId:o}:null)},[m]);(0,n.useEffect)(()=>{let e=eG?nx(eG)||eG:null;document.title=e?`${e} — Pi Agent Web`:"Pi Agent Web"},[eG]);let e7=(0,n.useCallback)((e,t=!1)=>{if(t||e5(null),!t&&m){let t=sC(m.projectRoot??m.cwd,e.projectRoot??e.cwd);if(m.id===e.id&&t){g&&H(!1);return}}let r=e.projectRoot??e.cwd;r&&e6.current.set(r,e.id),v(null),f(e),w(e=>e+1),et(null),e1(!0),g&&!t&&H(!1),t&&(e2.current=!0),t||window.history.replaceState(null,"",`?session=${encodeURIComponent(e.id)}`)},[g,m]),e9=(0,n.useRef)(()=>{});(0,n.useEffect)(()=>{e9.current=e7},[e7]);let tt=(0,n.useCallback)(e=>{fetch("/api/sessions").then(e=>e.ok?e.json():null).then(t=>{let r=t?.sessions.find(t=>t.id===e);r&&f(t=>!t||t.id!==e||t.projectRoot&&t.name?t:r)}).catch(()=>{})},[]);(0,n.useEffect)(()=>{if(!e4)return;let{projectRoot:e,sessionId:t}=e4;e9.current({path:"",id:t,cwd:e,created:"",modified:"",messageCount:0,firstMessage:"",projectRoot:e},!0),tt(t),window.history.replaceState(null,"",`?session=${encodeURIComponent(t)}`),e5(null)},[e4,tt]);let tr=(0,n.useCallback)((e,t)=>{e5(null),f(null),v(t),w(e=>e+1),et(null),eg(null),g&&H(!1),window.history.replaceState(null,"","/")},[l,g]);!function(e){let{onNewSession:t,activeCwd:r}=e;(0,n.useEffect)(()=>{let e=e=>{if("Escape"===e.key){if(!a)return;let t=e.target?.tagName;if("TEXTAREA"===t||"INPUT"===t)return;e.preventDefault(),a();return}if("n"===e.key&&e.ctrlKey&&e.altKey){if(!r||!t)return;e.preventDefault(),t(r)}};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[r,t])}({onNewSession:e=>tr(`kb-${Date.now()}`,e),activeCwd:eG});let to=(0,n.useCallback)(e=>{v(null),e5(null);let t=e.projectRoot??e.cwd;t&&e6.current.set(t,e.id),f(e),e.cwd&&eJ(e.cwd),y(e=>e+1),tt(e.id),window.history.replaceState(null,"",`?session=${encodeURIComponent(e.id)}`),window.setTimeout(()=>y(e=>e+1),1200),window.setTimeout(()=>y(e=>e+1),4e3)},[l,tt]),tn=(0,n.useCallback)(()=>{y(e=>e+1),S(e=>e+1)},[]),ts=(0,n.useCallback)(e=>{y(e=>e+1),w(e=>e+1),v(null),e5(null),f(t=>{let r={...t??{path:"",cwd:"",created:"",modified:"",messageCount:0,firstMessage:""},id:e},o=r.projectRoot??r.cwd;return o&&e6.current.set(o,e),r}),tt(e),window.history.replaceState(null,"",`?session=${encodeURIComponent(e)}`)},[l,tt]),ti=(0,n.useCallback)(()=>{e1(!0)},[]),ta=(0,n.useCallback)(e=>{if(y(e=>e+1),m?.id===e){let e=m.cwd;f(null),v(e??null),w(e=>e+1),et(null),eg(null),window.history.replaceState(null,"","/")}},[l,m]),tl=(0,n.useCallback)((e,t,r,o)=>{let n="string"==typeof r||null===r?r:void 0,s="object"==typeof r&&null!==r?r:o,i=`file:${e}`;ey(r=>{let o=r.find(e=>e.id===i);return o?n&&o.sourceSessionId!==n||s?.initialDisplayMode&&o.initialDisplayMode!==s.initialDisplayMode?r.map(e=>e.id===i?{...e,sourceSessionId:n??e.sourceSessionId,initialDisplayMode:s?.initialDisplayMode??e.initialDisplayMode}:e):r:[...r,{id:i,label:t,filePath:e,sourceSessionId:n,initialDisplayMode:s?.initialDisplayMode}]}),ew(i),eS(!0),g&&H(!1)},[g]),td=(0,n.useCallback)(e=>{tl(e,nx(e),m?.id??null)},[tl,m?.id]),tc=(0,n.useMemo)(()=>{let e=new Map;for(let t of ez){if(t.relation?.kind!=="subagent")continue;let r=t.relation;e.set(t.id,{status:eM.has(t.id)?"running":r.status,...r.createdAt?{createdAt:r.createdAt}:{},...r.completedAt?{completedAt:r.completedAt}:{}})}return e},[ez,eM]),tp=(0,n.useCallback)((e,t)=>{let r=`subagent:${e}`;ey(o=>o.some(e=>e.id===r)?o:[...o,{id:r,label:t,filePath:"",kind:"subagent",sessionId:e}]),ew(r),eS(!0),g&&H(!1)},[g]),th=(0,n.useCallback)(e=>{ey(t=>{let r=t.filter(t=>t.id!==e);return 0===r.length&&eS(!1),r}),ew(t=>{if(t!==e)return t;let r=ek.filter(t=>t.id!==e);return r.length>0?r[r.length-1].id:null})},[ek]),tg=(0,n.useCallback)(e=>{S(e=>e+1),tl(e,nx(e))},[tl]),tm=(0,n.useCallback)((e,t)=>{S(e=>e+1);let r=e.endsWith("/")?e:e+"/",o=o=>o===e||t&&o.startsWith(r);ey(e=>{let t=e.filter(e=>!o(e.filePath));return 0===t.length&&eS(!1),t}),ew(e=>{if(!e)return e;let t=ek.find(t=>t.id===e);if(!t||!o(t.filePath))return e;let r=ek.filter(e=>!o(e.filePath));return r.length>0?r[r.length-1].id:null})},[ek]),tf=m?te(m.name||eo?.sessionName)||m.firstMessage.slice(0,50)||m.id.slice(0,12):(t=eG??x)?t.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||t:null,tx=(0,n.useCallback)(()=>{m&&window.open(`/api/sessions/${encodeURIComponent(m.id)}/export?inline=1`,"_blank","noopener,noreferrer")},[m]),tv=x??(null===m&&eG?eG:null),tk="validating"!==eY&&"error"!==eY&&(null!==m||null!==tv),ty=m?.cwd??tv,[tb,tw]=(0,n.useState)(!1),tj=(0,n.useCallback)(()=>{g||tw(e=>!e)},[g]),[tS,tC]=(0,n.useState)(!0);(0,n.useEffect)(()=>{let e=!1,t=()=>fetch("/api/features").then(e=>e.ok?e.json():null).then(t=>{!e&&t&&"boolean"==typeof t.tasksBoard&&(tC(t.tasksBoard),t.tasksBoard||tw(!1))}).catch(()=>{});t();let r=()=>t();return window.addEventListener("pi:features-changed",r),()=>{e=!0,window.removeEventListener("pi:features-changed",r)}},[]);let tT=e0&&!tk;(0,n.useEffect)(()=>{let e=()=>{g||tw(!0)};return window.addEventListener(cd,e),()=>window.removeEventListener(cd,e)},[g]),(0,n.useEffect)(()=>{if(E(null),W(!1),L(null),!ty)return;let e=new AbortController;return fetch(`/api/project-trust?cwd=${encodeURIComponent(ty)}`,{signal:e.signal}).then(async e=>{let t=await e.json();if(!e.ok||t.error)throw Error(t.error??`HTTP ${e.status}`);E(t)}).catch(e=>{e instanceof DOMException&&"AbortError"===e.name||console.error("Failed to load project trust:",e)}),()=>e.abort()},[ty]);let tR=(0,n.useCallback)(async()=>{if(ty&&!N){F(!0),L(null);try{let e=await fetch("/api/project-trust",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:ty})}),t=await e.json();if(!e.ok||t.error)throw Error(t.error??`HTTP ${e.status}`);E(t),W(!1),M(e=>e+1),w(e=>e+1)}catch(e){L(e instanceof Error?e.message:String(e))}finally{F(!1)}}},[N,ty]),tz=ek.find(e=>e.id===eb)??null,tI=eG??m?.cwd??x,tM=(0,n.useCallback)(e=>{z(e),T(!0)},[]),tP=(0,o.jsx)(o.Fragment,{children:(0,o.jsx)(sN,{selectedSessionId:m?.id??null,onSelectSession:e7,onNewSession:tr,initialSessionId:eV,onInitialRestoreDone:ti,refreshKey:k,onSessionDeleted:ta,selectedCwd:m?.cwd??x??null,onCwdChange:e3,onOpenFile:tl,selectedSessionStats:eo,onOpenSettings:e=>{tM(e??"models")},explorerRefreshKey:j,onAtMention:eU,onAtMentions:e_,onFileCreated:tg,onFileDeleted:tm,workspaceControlsHosts:{title:q,welcome:Y,titleRight:K},showWorkspaceControls:!0})});return(0,o.jsxs)(cV,{children:[(0,o.jsx)("style",{children:`
196
196
  @media (max-width: 640px) {
197
197
  .sidebar-overlay-backdrop.sidebar-mobile-pending {