@qt4798/pi-web 0.14.4 → 0.14.6
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.
- package/.next/BUILD_ID +1 -1
- package/.next/app-path-routes-manifest.json +22 -22
- package/.next/build-manifest.json +2 -2
- package/.next/required-server-files.js +1 -1
- package/.next/required-server-files.json +1 -1
- package/.next/server/app/_global-error/page_client-reference-manifest.js +1 -1
- package/.next/server/app/_global-error.html +1 -1
- package/.next/server/app/_global-error.rsc +1 -1
- package/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
- package/.next/server/app/_global-error.segments/_global-error/__PAGE__.segment.rsc +1 -1
- package/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
- package/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
- package/.next/server/app/_not-found.html +1 -1
- package/.next/server/app/_not-found.rsc +1 -1
- package/.next/server/app/_not-found.segments/_full.segment.rsc +1 -1
- package/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +1 -1
- package/.next/server/app/_not-found.segments/_tree.segment.rsc +1 -1
- package/.next/server/app/api/app-update/route.js +1 -1
- package/.next/server/app/index.html +1 -1
- package/.next/server/app/index.rsc +3 -3
- package/.next/server/app/index.segments/__PAGE__.segment.rsc +3 -3
- package/.next/server/app/index.segments/_full.segment.rsc +3 -3
- package/.next/server/app/index.segments/_tree.segment.rsc +1 -1
- package/.next/server/app/page.js +1 -1
- package/.next/server/app/page_client-reference-manifest.js +1 -1
- package/.next/server/app-paths-manifest.json +22 -22
- package/.next/server/chunks/7915.js +1 -1
- package/.next/server/middleware-build-manifest.js +1 -1
- package/.next/server/pages/404.html +1 -1
- package/.next/server/pages/500.html +1 -1
- package/.next/static/chunks/app/{page-bcc0e2ed5b5f6035.js → page-54c57e029a68ffd4.js} +1 -1
- package/.next/trace +7 -8
- package/.next/trace-build +1 -1
- package/bin/memory-watchdog.js +135 -0
- package/bin/pi-web.js +8 -2
- package/bin/watchdog-preload.js +20 -0
- package/package.json +1 -1
- /package/.next/static/{h9xeO9wlQinP87V3yuXj6 → 7xdY7qoeKsF7B1usdcD8R}/_buildManifest.js +0 -0
- /package/.next/static/{h9xeO9wlQinP87V3yuXj6 → 7xdY7qoeKsF7B1usdcD8R}/_ssgManifest.js +0 -0
|
@@ -33,7 +33,7 @@ ${e}`;(0,r.useEffect)(()=>{if(!a||t)return;let n=!1;return g(null),(async()=>{le
|
|
|
33
33
|
|
|
34
34
|
Goal: ${o}`:e_)}return t.join("\n\n")}({collaborationMode:ew.current,tokenMode:ej.current,goalText:"goal"===ew.current?eT.current??void 0:void 0}),c=d||!eu.current||a?"":iE,p=d||c,u=[ew.current,ej.current,eu.current?"legacy-plan":"",p?String(p.length):""].join("|"),g=t?.id??"new";p&&(eR.current.sessionKey!==g||eR.current.signature!==u)?(eR.current={sessionKey:g,signature:u},s=`${p}
|
|
35
35
|
|
|
36
|
-
${o}`):s=o;let m=s,f=r?.map(e=>({type:"image",source:{type:"base64",media_type:e.mimeType,data:e.data}})),x={role:"user",content:f?.length?[...o.trim()?[{type:"text",text:o}]:[],...f]:o,timestamp:Date.now()};S(e=>[...e,x]),ol.current=iO(x),oa.current=l,"goal"!==ew.current||a||(eT.current=i,eF(e=>({...e,status:"running",goalText:i,turnsUsed:0,noProgressTurns:0,tokensUsed:0})),eK.current=!0),tX.current=!0,O(!0),ts(a?{kind:"running_command"}:{kind:"waiting_model"}),E({type:"start"}),t7.current=!0,ta(!0),t9.current=!0;let k=r?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),v=null,y=!1;try{if(h&&n){let e=tY.current??await os.current,t=e??await oz();if(t){v=t,oR(1,o),en&&(e3(en),e&&await iS(t,{type:"set_model",provider:en.provider,modelId:en.modelId}));let n=await Promise.race([oF(t).then(()=>!0).catch(()=>!1),iA(4e3).then(()=>!1)]);y=!0,await iS(t,{type:"prompt",message:m,...k?.length?{images:k}:{}}),n||o_(t,l),"goal"!==ew.current||a||iS(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([oF(t.id).then(()=>!0).catch(()=>!1),iA(4e3).then(()=>!1)]);y=!0,await iS(t.id,{type:"prompt",message:m,...k?.length?{images:k}:{}}),e||o_(t.id,l),"goal"!==ew.current||a||iS(t.id,{type:"goal_start",goalText:i}).catch(()=>{})}a&&v&&o_(v,l)}catch(t){if(console.error("Failed to send message:",t),y&&v)return void o_(v,l);if(tQ.current=!1,oP(),t instanceof iW){let e=ol.current;e&&S(t=>{let o=t[t.length-1];return o?.role==="user"&&iO(o)===e?t.slice(0,-1):t}),oA({type:"error",message:t.message})}else{let o=ol.current;o&&S(e=>{let t=e[e.length-1];return t?.role==="user"&&iO(t)===o?e.slice(0,-1):e}),e.chatInputRef?.current?.replaceMessage?.(x),oA({type:"error",message:`Failed to send message: ${t instanceof Error?t.message:String(t)}`})}ol.current=null,tX.current=!1,O(!1),ts(null),E({type:"end"})}},[h,n,en,t,oz,oF,oR,o_,oA,oM,oP,of]),oJ=(0,r.useCallback)(async(o,n)=>{if(tX.current||t4.current)return;let r=`${n?"!!":"!"}${o}`;t4.current=!0,_({command:o,excludeFromContext:n}),B(!0);try{let e=tY.current??t?.id??await oz();if(!e)throw Error("Unable to create a session for the shell command");oR(1,r),await iS(e,{type:"bash",command:o,excludeFromContext:n}),await oS(e)}catch(t){console.error("Failed to execute shell command:",t),oA({type:"error",message:t instanceof Error?t.message:String(t)}),e.chatInputRef?.current?.insertIfEmpty(r)}finally{t4.current=!1,_(null),B(!1)}},[oA,oz,oS,e.chatInputRef,oR,t]),oY=(0,r.useCallback)(async()=>{let e=tY.current;if(e)try{await iS(e,{type:t4.current?"abort_bash":"abort"})}catch(e){console.error("Failed to abort:",e)}},[]),oX=(0,r.useCallback)(async e=>{let t=tY.current;if(t){e4(e);try{let{cancelled:o,newSessionId:n}=await iS(t,{type:"fork",entryId:e})??{};!o&&n&&a?.(n)}catch(e){console.error("Fork failed:",e)}finally{e4(null)}}},[a]),oZ=(0,r.useCallback)(async e=>{let t=tY.current;t&&(iS(t,{type:"navigate_tree",targetId:e}).catch(()=>{}),w(e),await oC(t,e))},[oC]),oQ=(0,r.useCallback)(async e=>{w(e);let t=tY.current;t&&(await oC(t,e),e&&iS(t,{type:"navigate_tree",targetId:e}).catch(()=>{}))},[oC]),o0=(0,r.useCallback)(async(e,t)=>{if(h){let o={provider:e,modelId:t};oh.current=o,er(o),e3(o);let n=tY.current??await os.current;if(!n)return;try{await iS(n,{type:"set_model",provider:e,modelId:t})}catch(e){console.error("Failed to set model:",e)}return}let o=tY.current;if(!o)return;let n=++od.current,r=e6??m?.context.model??null;e8({provider:e,modelId:t});try{await iS(o,{type:"set_model",provider:e,modelId:t})}catch(o){console.error("Failed to set model:",o),od.current===n&&(e8(r&&(r.provider!==e||r.modelId!==t)?r:null),oA({type:"error",message:o instanceof Error?o.message:String(o)}))}},[oA,e6,m?.context.model,h,er]),o1=(0,r.useCallback)(async()=>{let e=tY.current;if(e&&!e7){e9(!0),tt(null),tn(null);try{let t=await iS(e,{type:"compact"});tn(iH(t,"manual")),await oS(e,!0)}catch(e){tt(e instanceof Error?e.message:String(e)),tn(null)}finally{e9(!1)}}},[e7,oS]),o2=(0,r.useCallback)(async e=>{let o=++oc.current,r=n??t?.cwd??"",s=r?`/api/models?cwd=${encodeURIComponent(r)}`:"/api/models",i=op.current;i?.abort();let a=new AbortController;op.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 o=await e.json();o?.error&&(t=o.error)}catch{}throw Error(t)}let t=await e.json();if(o!==oc.current||g!==ou.current)return;eo(null),V(t.models),Y(t.thinkingLevels??{}),Z(t.thinkingLevelMaps??{}),ee(t.modelScopeWarnings??[]);let n=t.modelList??[];if(G(n),h&&!tY.current){let e=(t.defaultModel?n.find(e=>e.id===t.defaultModel?.modelId&&e.provider===t.defaultModel?.provider):void 0)??n[0];ei(e?{provider:e.provider,modelId:e.id}:null);let o=e?t.thinkingLevelPins?.[`${e.provider}/${e.id}`]:void 0;null===og.current&&eJ(o??"auto")}}catch(e){if(a.signal.aborted||o!==oc.current||g!==ou.current)return;eo(e instanceof Error?e.message:String(e))}finally{e?.removeEventListener("abort",l),op.current===a&&(op.current=null)}},[h,g,n,t?.cwd]),o4=(0,r.useCallback)(async e=>{if(!e.startsWith("/"))return{handled:!1};let t=e.match(/^\/([^\s]+)(?:\s+([\s\S]*))?$/);if(!t)return{handled:!1};let[,o,n=""]=t,r=n.trim(),s=tY.current??await oz(),i=e=>(e.handled&&(e.error?oA({type:"error",message:e.error}):"openSessionStats"!==e.action&&oA({type:"success",message:e.message??"Command completed"})),e);try{switch(o){case"compact":{if(!s||e7)return i({handled:!0,error:"No active session to compact"});e9(!0),tt(null),tn(null);let e=await iS(s,{type:"compact",...r?{customInstructions:r}:{}});return tn(iH(e,"manual")),await oS(s,!0)&&oR(),i({handled:!0,message:"Compacted context"})}case"reload":if(!s)return i({handled:!0,error:"No active session to reload"});return await iS(s,{type:"reload"}),await Promise.all([oS(s,!1,!0),oT(s),oI(),o2()]),i({handled:!0,message:"Reloaded session resources"});case"name":if(!s)return i({handled:!0,error:"No active session to name"});if(!r)return i({handled:!0,error:"Usage: /name <name>"});return await iS(s,{type:"set_session_name",name:eq(r)}),await oS(s)&&oR(),i({handled:!0,message:`Session renamed to ${r}`});case"session":{if(!s)return i({handled:!0,error:"No active session"});let e=await iS(s,{type:"get_session_stats"});return e&&tm(e),p?.(),i({handled:!0,action:"openSessionStats"})}case"copy":{if(!s)return i({handled:!0,error:"No active session"});let e=await iS(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"===o&&e9(!1)}},[oA,oz,e7,o2,oS,oI,oT,oR,p]),o6=(0,r.useCallback)(async e=>{let t=!1;try{let o=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(o.ok){let e=await o.json(),n=e.state;if(e.running&&n&&(n.isStreaming||n.isPromptRunning||n.isBashRunning||n.isCompacting))return;t=!0}}catch{}if(t){tX.current=!1,O(!1),ts(null);return}o_(e)},[o_]),o8=(0,r.useCallback)(async(e,t)=>{let o=tY.current;if(!o)return;let n=t?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType}));tX.current=!0,O(!0),ts(e=>e??{kind:"waiting_model"});try{await iS(o,{type:"steer",message:e,...n?.length?{images:n}:{}})}catch(e){console.error("Failed to steer:",e),o6(o)}},[o6]),o5=(0,r.useCallback)(async(e,t,o)=>{let n=tY.current;if(!n)return;let r=o?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType}));tX.current=!0,O(!0),ts(e=>e??{kind:"waiting_model"});try{await iS(n,{type:"prompt",message:e,streamingBehavior:t,...r?.length?{images:r}:{}})}catch(e){console.error("Failed to queue prompt:",e),o6(n)}},[o6]),o3=(0,r.useCallback)(async(e,t)=>{let o=tY.current;if(!o)return;let n=t?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType}));tX.current=!0,O(!0),ts(e=>e??{kind:"waiting_model"});try{await iS(o,{type:"follow_up",message:e,...n?.length?{images:n}:{}})}catch(e){console.error("Failed to follow up:",e),o6(o)}},[o6]),o7=(0,r.useCallback)(async()=>{let e=tY.current;if(e)try{await iS(e,{type:"abort_compaction"})}catch(e){console.error("Failed to abort compaction:",e)}},[]),o9=(0,r.useCallback)(async()=>{let t=tY.current;if(t)try{let o=await iS(t,{type:"clear_queue"});tT({steering:[],followUp:[]});let n=[...o?.steering??[],...o?.followUp??[]];n.length>0&&e.chatInputRef?.current?.prependText(n.join("\n\n"))}catch(e){console.error("Failed to recall queued messages:",e),oA({type:"error",message:"Failed to recall queued messages"})}},[e.chatInputRef,oA,tT]);(0,r.useEffect)(()=>{0===tR.length&&tP(!1)},[tR.length]);let ne=(0,r.useCallback)(async(e,t,o=!1)=>{let n=tY.current;if(!n)return tR;try{let r=await iS(n,{type:"resolve_recovery",keep:e,discard:t,continueRun:o}),s=r?.remaining??[];return tI(s),o&&e.length>0&&(async()=>{try{let e=await fetch(`/api/agent/${encodeURIComponent(n)}`);if(!e.ok)return;let t=await e.json(),o=t.state;if(!t.running||!o||!o.isStreaming&&!o.isPromptRunning)return;tZ.current=!!o.isStreaming,tQ.current=!!o.isPromptRunning,tX.current=!0,O(!0),ts(iI(o)),E({type:"start"}),oE(n),!o.isStreaming&&o.isPromptRunning&&o_(n)}catch{}})(),s}catch(e){return console.error("Failed to resolve queued message recovery:",e),oA({type:"error",message:"Failed to resolve queued message recovery"}),tR}},[tR,oA,oE,o_,tI]),nt=(0,r.useCallback)(async()=>{let e=tY.current;if(!e)return null;try{return await iS(e,{type:"export_queue"})}catch(e){return console.error("Failed to export queue:",e),oA({type:"error",message:"Failed to export queue"}),null}},[oA]),no=(0,r.useCallback)(async e=>{let t=tY.current;if(!t)return null;try{let o=await iS(t,{type:"import_queue",entries:e});return o&&tT(iP(o)),o?.imported??0}catch(e){return console.error("Failed to import queue:",e),oA({type:"error",message:"Failed to import queue"}),null}},[oA,tT]),nn=(0,r.useCallback)(async e=>{let t=tY.current;if(!t)return null;try{let o=await iS(t,{type:"stage_recovery",entries:e});return o?.pendingRecovery&&tI(o.pendingRecovery),(o?.staged??0)>0&&tP(!0),o?.staged??0}catch(e){return console.error("Failed to stage imported queue:",e),oA({type:"error",message:"Failed to stage imported queue"}),null}},[oA,tI]),nr=(0,r.useCallback)(async(e,t,o)=>{let n=tY.current;if(!n)return!1;try{let r=await iS(n,{type:"move_queue",kind:e,fromIndex:t,toIndex:o});return r&&tT(iP(r)),!0}catch(e){return console.error("Failed to move queued message:",e),oA({type:"error",message:e instanceof Error?e.message:"Failed to move queued message"}),!1}},[oA,tT]),ns=(0,r.useCallback)(async(e,t)=>{let o=tY.current;if(!o)return null;try{let n=await iS(o,{type:"recall_queue_item",kind:e,index:t});return n&&(void 0!==n.steering||void 0!==n.followUp)&&tT(iP(n)),n?.entry?{text:n.entry.text,images:n.entry.images?.map(({data:e,mimeType:t})=>({data:e,mimeType:t}))}:null}catch(e){return console.error("Failed to recall queued message:",e),oA({type:"error",message:e instanceof Error?e.message:"Failed to recall queued message"}),null}},[oA,tT]),ni=(0,r.useCallback)(async(e,t,o,n)=>{let r=tY.current;if(!r)return!1;try{let s=await iS(r,{type:"requeue_at",kind:e,index:t,text:o,images:n?.map(({data:e,mimeType:t})=>({type:"image",data:e,mimeType:t}))});return s&&tT(iP(s)),!0}catch(e){return console.error("Failed to requeue message:",e),oA({type:"error",message:e instanceof Error?e.message:"Failed to requeue message"}),!1}},[oA,tT]),na=(0,r.useCallback)(async(e,t)=>{let o=tY.current;if(!o)return!1;try{let n=await iS(o,{type:"remove_queue_item",kind:e,index:t});return n&&tT(iP(n)),!0}catch(e){return console.error("Failed to remove queued message:",e),oA({type:"error",message:e instanceof Error?e.message:"Failed to remove queued message"}),!1}},[oA,tT]),nl=(0,r.useCallback)(async e=>{if(og.current="auto"===e?null:e,eJ(e),"auto"===e)return;let t=tY.current??await os.current;if(t)try{await iS(t,{type:"set_thinking_level",level:e})}catch(e){console.error("Failed to set thinking level:",e)}},[]),nd=(0,r.useCallback)(async e=>{let t=(0,iC.xG)(e);ok(e);let o=tY.current??await os.current;if(o)try{await iS(o,{type:"set_tools",toolNames:t})}catch(e){console.error("Failed to set tools:",e)}},[ok]),nc=(0,r.useRef)(0),np=(0,r.useCallback)(async e=>{let t=tY.current??await os.current,o=++nc.current;if(e){if(ep.current="plan"===ea?"default":ea,ec(!0),eu.current=!0,eR.current={sessionKey:"",signature:""},t)try{if(await iS(t,{type:"prompt",message:"/plan"}),nc.current!==o)return}catch(e){if(nc.current!==o)return;console.error("Failed to enter plan mode:",e)}}else if(ec(!1),eu.current=!1,eR.current={sessionKey:"",signature:""},t){try{if(await iS(t,{type:"prompt",message:"/plan exit"}),nc.current!==o)return}catch(e){if(nc.current!==o)return;console.error("Failed to exit plan mode:",e)}if(nc.current!==o)return;try{let e=ep.current;await iS(t,{type:"set_tools",toolNames:(0,iC.xG)(e)})}catch(e){console.error("Failed to restore tools after plan exit:",e)}}},[ea]),nu=(0,r.useCallback)(e=>{eg(e);let t=tY.current;if(!t){em.current=e;return}em.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)})},[]),nm=(0,r.useCallback)(e=>{if(nu({...ez.current,collaborationMode:eN(e)}),ew.current=eN(e),eR.current={sessionKey:"",signature:""},"goal"!==e){eT.current=null,eK.current=!1,eF(e=>"idle"===e.status?e:{...e,status:"idle",goalText:null});let e=tY.current;e&&iS(e,{type:"goal_stop"}).catch(()=>{})}},[nu]),nf=(0,r.useCallback)(async e=>{nu({...ez.current,tokenMode:e$(e)});let t=tY.current??await os.current;if(t)try{if("economy"!==e||eu.current){if("economy"!==e){let e=eu.current?iC.SC:(0,iC.xG)("plan"===ea?"default":ea);await iS(t,{type:"set_tools",toolNames:e})}}else await iS(t,{type:"set_tools",toolNames:[...eO]})}catch(e){console.error("Failed to apply token mode tools:",e)}},[nu,ea]),nx=(0,r.useCallback)(async e=>{nu({...ez.current,toolApprovalMode:eL(e)});let t=tY.current??await os.current;if(t)try{await iS(t,{type:"set_approval_mode",mode:eL(e)})}catch(e){console.error("Failed to apply approval mode:",e)}},[nu]),nk=(0,r.useCallback)(async e=>{nu({...ez.current,permissionRules:e});let t=tY.current??await os.current;if(t)try{await iS(t,{type:"set_approval_policy",policy:e})}catch(e){console.error("Failed to apply permission rules:",e)}},[nu]),nv=(0,r.useCallback)(async(e,t,o)=>{let n=tY.current;if(n)try{await iS(n,{type:"resolve_approval",id:e,approve:t,reason:o})}catch(e){console.error("Failed to resolve approval:",e)}finally{eM(t=>t.filter(t=>t.id!==e))}},[]),ny=(0,r.useCallback)(e=>{eT.current=e},[]),nb=(0,r.useCallback)(e=>{let t=e.trim();if(!t)return;eT.current=t,eF(e=>({...e,status:"running",goalText:t,turnsUsed:0,noProgressTurns:0,tokensUsed:0,startedAt:Date.now()}));let o=tY.current;o&&iS(o,{type:"goal_start",goalText:t}).catch(()=>{})},[]),nw=(0,r.useCallback)(()=>{if("running"!==eV.current.status)return;eF(e=>({...e,status:"paused"}));let e=tY.current;e&&iS(e,{type:"goal_pause"}).catch(()=>{})},[]),nj=(0,r.useCallback)(()=>{let e=eV.current;if("paused"!==e.status&&"blocked"!==e.status)return;eF(e=>({...e,status:"running"}));let t=tY.current;t&&iS(t,{type:"goal_resume"}).catch(()=>{})},[]),nS=(0,r.useCallback)(()=>{eK.current=!1,eT.current=null,eF(e=>({...e,status:"idle",goalText:null,turnsUsed:0,noProgressTurns:0}));let e=tY.current;e&&iS(e,{type:"goal_stop"}).catch(()=>{})},[]),nC=(0,r.useCallback)(e=>{let t=e.trim();if(!t)return;eF(e=>({...e,goalText:t}));let o=tY.current;o&&iS(o,{type:"goal_edit",goalText:t}).catch(()=>{})},[]),nT=tE.map(e=>`${e.id}:${e.status}:${e.completedAt??""}`).join("|"),nR=(0,r.useRef)(tE);nR.current=tE,(0,r.useEffect)(()=>{u?.(nR.current)},[nT,u]),(0,r.useEffect)(()=>()=>{u?.([])},[u]),(0,r.useEffect)(()=>{tA(()=>[])},[t?.id,n??t?.cwd]);let nz=(0,r.useCallback)(()=>{let e=or.current,t=t3.current;if(!e||!t)return;let o=t.getBoundingClientRect().top-e.getBoundingClientRect().top+e.scrollTop,n=Math.max(0,e.scrollHeight-e.clientHeight),r=Math.min(Math.max(0,o-16),n);oe.current=r>=n-150,oo.current=Date.now()+700,e.scrollTo({top:r,behavior:"smooth"})},[]),nI=(0,r.useCallback)(e=>{if(e instanceof KeyboardEvent){if(!iD.has(e.key)||e.target instanceof Element&&e.target.closest("input, textarea, [contenteditable='true']"))return}else if(e instanceof PointerEvent){let t=or.current;if(t&&e.target instanceof Element&&!t.contains(e.target))return}ot.current=Date.now()+1200},[]),nM=(0,r.useCallback)(()=>{let e=or.current;if(e){let{scrollTop:t,clientHeight:o,scrollHeight:n}=e;oe.current=t+o>=n-150}if(Date.now()<ot.current){t9.current=!1;return}Date.now()<oo.current||(t9.current=!1)},[]);(0,r.useEffect)(()=>{if(t1.current=!0,t){tY.current=t.id;let e=eS.current,o=eC.current;("auto"!==e||o.allow.length||o.ask.length||o.deny.length)&&(iS(t.id,{type:"set_approval_mode",mode:e}).catch(()=>{}),iS(t.id,{type:"set_approval_policy",policy:o}).catch(()=>{}));let n=e=>{!t6.current&&(t6.current=!0,e.isBashRunning&&(t4.current=!0,B(!0)),oT(t.id),(e.isStreaming||e.isPromptRunning)&&(tZ.current=!!e.isStreaming,tQ.current=!!e.isPromptRunning,tX.current=!0,O(!0),ts(iI(e)),E({type:"start"}),oE(t.id),!e.isStreaming&&e.isPromptRunning&&o_(t.id)))};(async()=>{try{let e,o=new AbortController,r=setTimeout(()=>o.abort(),2e4);try{e=await fetch(`/api/sessions/${encodeURIComponent(t.id)}/state`,{signal:o.signal})}finally{clearTimeout(r)}if(!e.ok)throw Error(`HTTP ${e.status}`);let s=await e.json();if(!t1.current||tY.current!==t.id)return;s.running&&s.state&&n(s.state)}catch{}})(),oS(t.id,!0,!0).then(e=>{e?.running&&e.state&&n(e.state),e?.state&&(void 0!==e.state.isCompacting&&e9(e.state.isCompacting),void 0!==e.state.contextUsage&&eQ(e.state.contextUsage??null),void 0!==e.state.systemPrompt&&e1(e.state.systemPrompt??null),void 0!==e.state.thinkingLevel&&eJ(e.state.thinkingLevel??"auto"),void 0!==e.state.extensionStatuses&&tb(e.state.extensionStatuses??[]),void 0!==e.state.extensionWidgets&&tj(e.state.extensionWidgets??[]),void 0!==e.state.queuedMessages&&tT(iP(e.state.queuedMessages)),void 0!==e.state.pendingRecovery&&tI(e.state.pendingRecovery??[])),e?.running||(async()=>{for(let e=0;e<5;e++){if(e>0&&await new Promise(e=>setTimeout(e,2e3)),!t1.current||tY.current!==t.id||tX.current)return;try{let e=await fetch(`/api/agent/${encodeURIComponent(t.id)}`);if(!e.ok)continue;let o=await e.json();if(!t1.current||tY.current!==t.id)return;if(o?.running&&o.state)return void n(o.state)}catch{}}})()})}return()=>{t1.current=!1,of(),tU(),oM(),oP()}},[of]),(0,r.useEffect)(()=>{c?.(e0)},[e0,c]),(0,r.useEffect)(()=>{d&&d(m?.tree??[],b,oQ)},[m?.tree,b,oQ,d]),(0,r.useEffect)(()=>(window.addEventListener("keydown",nI),window.addEventListener("pointerdown",nI,{passive:!0}),()=>{window.removeEventListener("keydown",nI),window.removeEventListener("pointerdown",nI)}),[nI]),(0,r.useEffect)(()=>{let e=or.current;if(e)return e.addEventListener("wheel",nI,{passive:!0}),e.addEventListener("touchstart",nI,{passive:!0}),e.addEventListener("scroll",nM,{passive:!0}),()=>{e.removeEventListener("wheel",nI),e.removeEventListener("touchstart",nI),e.removeEventListener("scroll",nM)}},[j.length,x,nM,nI]),(0,r.useEffect)(()=>{j.length>0&&(t7.current?(t5.current=!0,t3.current&&(t7.current=!1,nz())):x||!t5.current?(x||(t5.current=!0),oV("instant")):!tX.current&&(t9.current||oe.current)&&oV("smooth"))},[j.length,x,L,oV,nz]);let nP=(0,r.useRef)(null),nE=t?.id??null;(0,r.useEffect)(()=>{let e;if(x){nP.current=null;return}if(0===j.length||nP.current===nE)return;nP.current=nE;let t=!1,o=!1,n=-1,r=0,s=Date.now(),i=()=>{if(t||o)return;let a=or.current;if(a){if(Date.now()<ot.current){let{scrollTop:e,clientHeight:t,scrollHeight:n}=a;if(e+t<n-150){o=!0;return}}if(oV("instant"),a.scrollHeight===n){if((r+=1)>=4||Date.now()-s>=3e4)return}else if(n=a.scrollHeight,r=0,Date.now()-s>=3e4)return;e=window.setTimeout(i,r>0?500:250)}};return e=window.setTimeout(i,250),()=>{t=!0,void 0!==e&&window.clearTimeout(e)}},[x,oV,nE]),(0,r.useEffect)(()=>{let e=new AbortController;return o2(e.signal).catch(e=>{if(e instanceof DOMException&&"AbortError"===e.name)return}),()=>e.abort()},[o2,l]),(0,r.useEffect)(()=>{if(!et)return;let e=()=>{"visible"===document.visibilityState&&o2()};return document.addEventListener("visibilitychange",e),window.addEventListener("online",e),()=>{document.removeEventListener("visibilitychange",e),window.removeEventListener("online",e)}},[et,o2]),(0,r.useEffect)(()=>{if(!te)return;let e=setTimeout(()=>tt(null),3e3);return()=>clearTimeout(e)},[te]),(0,r.useEffect)(()=>{if(!to)return;let e=setTimeout(()=>tn(null),6e3);return()=>clearTimeout(e)},[to]),(0,r.useEffect)(()=>{if(0===tu.visible.length)return;let e=tu.visible.find(e=>e.exiting);if(e){let t=setTimeout(()=>{th({type:"remove",id:e.id})},180);return()=>clearTimeout(t)}if(!tu.visible[0])return;let t=setTimeout(()=>{th({type:"mark_oldest_exiting"})},5e3);return()=>clearTimeout(t)},[tu.visible]),(0,r.useEffect)(()=>{tm(null)},[j.length,eZ?.tokens,eZ?.percent,eZ?.contextWindow]);let nF=m?.tree??[];return{data:m,loading:x,error:v,activeLeafId:b,messages:j,entryIds:C,historyCursor:R,hasEarlierMessages:I,streamState:P,agentRunning:L,bashRunning:H,pendingBash:U,modelNames:q,modelList:K,modelThinkingLevels:J,modelThinkingLevelMaps:X,modelScopeWarnings:Q,modelsError:et,newSessionModel:en,toolPreset:ea,thinkingLevel:eG,retryInfo:eY,contextUsage:eZ,systemPrompt:e0,forkingEntryId:e2,isCompacting:e7,compactError:te,compactResult:to,currentModel:ob,displayModel:ow,sessionStats:oj,tokenRate:F,planMode:ed,subagents:tE,collaborationMode:ek,tokenMode:ev,toolApprovalMode:ey,permissionRules:eb,modeSettings:eh,approvalRequests:eI,handleCollaborationModeChange:nm,handleTokenModeChange:nf,handleToolApprovalModeChange:nx,handlePermissionRulesChange:nk,resolveApproval:nv,setActiveGoalText:ny,goalState:eE,handleGoalStart:nb,handleGoalPause:nw,handleGoalResume:nj,handleGoalStop:nS,handleGoalEdit:nC,slashCommands:tl,slashCommandsLoading:tc,queuedMessages:tS,pendingRecovery:tR,recoveryIsImport:tM,notices:tu.visible,extensionDialog:tf,extensionCustomUi:tk,extensionStatuses:ty,extensionWidgets:tw,respondToExtensionUi:oD,sendExtensionCustomInput:oW,agentPhase:tr,isNew:h,promptAnchorActive:ti,branchTree:nF,sessionIdRef:tY,eventSourceRef:t_,messagesEndRef:on,scrollContainerRef:or,lastUserMsgRef:t3,pendingScrollToUserRef:t7,initialScrollDoneRef:t5,scrollUserMsgToTop:nz,handleSend:oG,executeBash:oJ,handleAbort:oY,handleFork:oX,handleNavigate:oZ,handleModelChange:o0,handleCompact:o1,handleSteer:o8,handleFollowUp:o3,handlePromptWithStreamingBehavior:o5,handleAbortCompaction:o7,handleRecallQueue:o9,resolveRecovery:ne,exportQueueData:nt,importQueueData:no,stageQueueImport:nn,moveQueuedMessage:nr,recallQueuedMessage:ns,requeueAt:ni,removeQueuedMessage:na,handleBuiltinSlashCommand:o4,handleToolPresetChange:nd,handleThinkingLevelChange:nl,handlePlanModeChange:np,loadTools:oT,loadSlashCommands:oI,reloadModels:o2,setActiveLeafId:w,setData:f,setMessages:S,loadContext:oC,dispatch:E,setAgentRunning:O,setForkingEntryId:e4,handleLeafChange:oQ,handleAgentEventRef:t8}}({session:e,newSessionCwd:t,onAgentEnd:A,onSessionCreated:i,onSessionForked:a,modelsRefreshKey:d,chatInputRef:c,onBranchDataChange:p,onSystemPromptChange:u,onSessionStatsPanelOpen:m,onSubagentsChange:g}),[tF,tD]=(0,r.useState)(!1);(0,r.useEffect)(()=>{0===ef.length&&tD(!1)},[ef.length]);let{balance:tW,refresh:tA,refreshSoon:tN}=function(){let[e,t]=(0,r.useState)(null),[o,n]=(0,r.useState)(!1),s=(0,r.useRef)(null),i=(0,r.useRef)(null),a=(0,r.useRef)(!0);(0,r.useEffect)(()=>(a.current=!0,()=>{a.current=!1,i.current&&clearTimeout(i.current),s.current?.abort()}),[]);let l=(0,r.useRef)(null),d=(0,r.useCallback)(async()=>{s.current?.abort();let e=new AbortController;s.current=e;try{let o=await fetch("/api/deepseek/balance",{signal:e.signal,cache:"no-store"}),r=await o.json();if(!a.current)return;if(r?.available&&null!=r.totalBalance){let e=l.current;(null===e||e.available!==r.available||e.reason!==r.reason||e.currency!==r.currency||e.totalBalance!==r.totalBalance||e.grantedBalance!==r.grantedBalance||e.toppedUpBalance!==r.toppedUpBalance)&&(l.current=r,t(r)),n(!1)}else null===l.current&&n(!0)}catch{if(!a.current)return;null===l.current&&n(!0)}},[]),c=(0,r.useCallback)(()=>{i.current&&clearTimeout(i.current),i.current=setTimeout(()=>{i.current=null,d()},2e3)},[d]);return{balance:e,failed:o,refresh:d,refreshSoon:c}}(),t$=ec?.provider==="deepseek",tL=(0,r.useRef)(null);(0,r.useEffect)(()=>{t$&&tA()},[t$,tA]),(0,r.useEffect)(()=>{if(t$)for(let e=U.length-1;e>=0;e--){let t=U[e];if("assistant"!==t.role||!t.usage)continue;let o=`${e}:${_[e]??""}`;o!==tL.current&&(tL.current=o,tN());break}},[U,_,t$,tN]);let tO=(0,r.useMemo)(()=>{let e=U.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:nh(e.model)?ng(e.model,t):0,costUSD:nh(e.model)?0:t.cost?.total??0}},[U]),[tH,tB]=(0,r.useState)(!1),[tU,t_]=(0,r.useState)(null),tq=(0,r.useRef)(!1);(0,r.useEffect)(()=>{if(!tl){tq.current=!1;return}if(V){tq.current=!0;return}tq.current&&(tq.current=!1,t_(function(e){for(let t=e.length-1;t>=0;t--){let o=e[t];if("assistant"!==o.role)continue;let n=o.content;if("string"==typeof n&&n.trim())return n;if(Array.isArray(n)){let e=n.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 o=e[t];if("toolResult"!==o.role)continue;let n=o.content,r="string"==typeof n?n:Array.isArray(n)?n.map(e=>e.text??"").join("\n"):"";if(!r)continue;let s=r.match(/\*\*Proposed Plan\*\*\s*\n+([\s\S]+)/i);if(s?.[1]?.trim())return s[1].trim()}return null}(U)??null),tB(!0))},[V,tl,U]);let tV=(0,r.useCallback)(()=>{tB(!1);let e=tK.current;"plan"===tc&&tg("normal"),td(!1).then(()=>{e&&eJ(P("tasks.planReviewExecutePrompt",{plan:e}))})},[td,eJ,P,tc,tg]),tK=(0,r.useRef)(null);(0,r.useEffect)(()=>{tK.current=tU},[tU]);let tG=(0,r.useCallback)(e=>{tB(!1),e2(e)},[e2]),tJ=(0,r.useCallback)(()=>{tB(!1),"plan"===tc&&tg("normal"),td(!1)},[td,tc,tg]);(0,r.useEffect)(()=>{ev&&W.current!==ev.id&&(W.current=ev.id,D.current&&E.current())},[ev]),(0,r.useEffect)(()=>(l=V||K?eX:null,()=>void(l=null)),[V,K,eX]);let[tY,tX]=(0,r.useState)(!1),[tZ,tQ]=(0,r.useState)(!1),[t0,t1]=(0,r.useState)(!1),t2=(0,r.useCallback)(()=>{let e=eE.current;if(!e)return;let t=e.scrollHeight-e.scrollTop-e.clientHeight;tX(e.scrollTop>1),tQ(t>1),t1(t>240)},[eE]),t4=(0,r.useCallback)(()=>{window.requestAnimationFrame(()=>{let e=eE.current,t=eP.current;if(!e||!t)return;let o=Math.max(88,c?.current?.measureHeight?.()??0),n=()=>{if(!e||!t)return;let n=Math.max(0,t.getBoundingClientRect().top-e.getBoundingClientRect().top+e.scrollTop-96-e.clientHeight+o);e.scrollTo({top:n,behavior:"auto"})};n(),t2(),window.setTimeout(n,200)})},[eP,eE,t2,c]);(0,r.useEffect)(()=>{let e=eE.current;if(!e)return;let t=new ResizeObserver(t2);return t.observe(e),e.firstElementChild&&t.observe(e.firstElementChild),e.addEventListener("scroll",t2,{passive:!0}),t2(),()=>{e.removeEventListener("scroll",t2),t.disconnect()}},[U.length,eE,t2]);let t6=(0,r.useRef)(!1);(0,r.useEffect)(()=>{let t=eE.current;if(!t)return;let o=()=>{if(t6.current||!tP||!tM||t.scrollTop>8)return;let o=e?.id;if(!o)return;t6.current=!0;let n=t.scrollHeight-t.scrollTop;tE(o,ez,tM).finally(()=>{t6.current=!1,requestAnimationFrame(()=>{let e=t.scrollHeight-n;Math.abs(t.scrollTop-e)>1&&t.scrollTo({top:e,behavior:"auto"})})})};return t.addEventListener("scroll",o,{passive:!0}),()=>t.removeEventListener("scroll",o)},[eE,tM,tP,tE,e?.id,ez]);let t8=(0,r.useRef)(null),t5=(0,r.useRef)([]),t3=(0,r.useMemo)(()=>({getOffsetForIndex:e=>t8.current?.getOffsetForIndex(e)?.[0]??0,sizeFor:e=>{let t=t8.current;if(!t)return 0;let o=t.measurementsCache[e];return o?.size??t.options.estimateSize?.(e)??0},totalHeight:()=>t8.current?.getTotalSize()??0,refToItemIndex:e=>t5.current[e],itemCount:t5.current.length}),[]),t7=ep?[ep.sessionId,ep.sessionFile??"",ep.sessionName??"",ep.userMessages,ep.assistantMessages,ep.toolCalls,ep.toolResults,ep.totalMessages,ep.tokens.input,ep.tokens.output,ep.tokens.cacheRead,ep.tokens.cacheWrite,ep.tokens.total,ep.cost??0,ep.totalActiveMs??0].join("|"):null,t9=(0,r.useRef)(ep);t9.current=ep,(0,r.useEffect)(()=>{h?.(t9.current)},[t7,h]),(0,r.useEffect)(()=>()=>{h?.(null)},[h]);let oe=es?`${es.percent??"null"}|${es.contextWindow}|${es.tokens??"null"}`:null,ot=(0,r.useRef)(es);ot.current=es,(0,r.useEffect)(()=>{f?.(ot.current)},[oe,f]),(0,r.useEffect)(()=>()=>{f?.(null)},[f]);let{isDragOver:oo,handleDragEnter:on,handleDragOver:or,handleDragLeave:os,handleDrop:oi}=function(e){let[t,o]=(0,r.useState)(!1),n=(0,r.useRef)(0),s=(0,r.useCallback)(e=>{e.dataTransfer.files.length&&(e.preventDefault(),n.current+=1,o(!0))},[]),i=(0,r.useCallback)(e=>{e.dataTransfer.files.length&&e.preventDefault()},[]);return{isDragOver:t,handleDragEnter:s,handleDragOver:i,handleDragLeave:(0,r.useCallback)(()=>{n.current-=1,n.current<=0&&(n.current=0,o(!1))},[]),handleDrop:(0,r.useCallback)(t=>{t.preventDefault(),n.current=0,o(!1),e(Array.from(t.dataTransfer.files),t.dataTransfer)},[e])}}((0,r.useCallback)((e,t)=>{if(V){let t=e.filter(e=>e.type.startsWith("image/"));t.length&&c?.current?.addImages(t);return}c?.current?.addFiles(e,t)},[V,c])),oa=U.filter(e=>"user"===e.role||"assistant"===e.role),ol=(0,r.useMemo)(()=>{let e=new Set,t=[];for(let n=U.length-1;n>=0&&t.length<50;n-=1){var o;let r="user"!==(o=U[n]).role?null:("string"==typeof o.content?o.content:o.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n")).trim()||null;!r||e.has(r)||(e.add(r),t.push(r))}return t},[U]),od=(S=oa.length,(C=(0,r.useRef)([])).current=Array(S).fill(null).map((e,t)=>C.current[t]??null),C),oc=eT&&0===U.length&&!q.isStreaming&&!V,op=e?.cwd??t??void 0,ou=(0,r.useMemo)(()=>(function(e,t,o){let n=new Map;for(let t of e)"toolResult"===t.role&&n.set(t.toolCallId,t);let r=-1;for(let t=e.length-1;t>=0;t--)if("user"===e[t].role){r=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 r=0;r<e.length;){let s,i=e[r],l="custom"===i.role&&"compaction"===i.customType;if("user"!==i.role&&!l){a.push({kind:"single",idx:r}),r+=1;continue}let d=r,c=d+1;for(;c<e.length&&"user"!==e[c].role;)c+=1;let p=function(e,t,o){for(let r=o-1;r>t;r--){var n;if("assistant"===(n=e[r]).role&&tp(n).answerBlocks.some(e=>"image"===e.type||"text"===e.type&&e.text.trim().length>0))return r}for(let n=o-1;n>t;n--)if(e[n]?.role==="assistant")return n;return -1}(e,d,c);if(-1===p){a.push({kind:"turn",userIdx:d,endIdx:c,startsCompactionTurn:l,finalAssistantIdx:p,visibleProcessIndices:[],processBlocks:[],finalAnswerMessage:null,writtenFiles:void 0}),r=c;continue}let u=[];for(let e=d+1;e<p;e++)u.push(e);let h=u.filter(t=>tb(e[t])),g=e[p],m=tp(g),f=m.processBlocks.length>0?tw(g,m.processBlocks,{omitUsage:!0}):null,x=m.answerBlocks.length>0?tw(g,m.answerBlocks):null,k=tf(e,t,h,n);if(f&&(k=k.concat(tm(g,{messageIndex:p,entryId:t[p],toolResults:n}).processBlocks)),x){let t=[];for(let o=d+1;o<=p;o++){let n=e[o];if(n?.role==="assistant")for(let e of n.content??[])t.push(e)}s=function(e,t,o){let n=new Set,r=[];for(let s of e){if("toolCall"!==s.type||!function(e){let t,o;return"write"===(t=e.toLowerCase())||t.startsWith("write_")||t.endsWith(".write")||t.endsWith("_write")||"edit"===(o=e.toLowerCase())||o.startsWith("edit_")||o.endsWith(".edit")||o.endsWith("_edit")||o.includes("str_replace")||o.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 o;if(!e)return null;let n=/^[a-zA-Z]:[\\/]/.test(e)||e.startsWith("\\\\")||void 0!==t&&(/^[a-zA-Z]:[\\/]/.test(t)||t.startsWith("\\\\")),r=e=>n?e.replace(/\\/g,"/"):e,s=r(e),i=t?r(t).replace(/\/+$/,""):void 0,a=/^[a-zA-Z]:\//.test(s),l=s.startsWith("//");if(a||l)o=s;else if(s.startsWith("/")){let e=i?.match(/^([a-zA-Z]:)(?:\/|$)/)?.[1]??i?.match(/^(\/\/[^/]+\/[^/]+)(?:\/|$)/)?.[1];o=e?`${e}${s}`:s}else{if(!i)return null;o=`${i}/${s}`}return tv(o)}(i,o);a&&(n.has(a)||(n.add(a),r.push({filePath:a})))}return r}(t,n,o)}a.push({kind:"turn",userIdx:d,endIdx:c,startsCompactionTurn:l,finalAssistantIdx:p,visibleProcessIndices:h,processBlocks:k,finalAnswerMessage:x,writtenFiles:s}),r=c}return{toolResultsMap:n,lastUserIdx:r,visibleRefIndexByMessage:s,items:a}})(U,_,op),[U,_,op]),oh=ec?X[`${ec.provider}:${ec.modelId}`]??null:null,og=ec?Z[`${ec.provider}:${ec.modelId}`]??null:null,om=(0,r.useCallback)(()=>{et()},[et]),of=(0,r.useCallback)(e=>{td(e),e&&"plan"!==tc?tg("plan"):e||"plan"!==tc||tg("normal")},[td,tg,tc]),ox=(0,r.useCallback)(e=>{tg(e),"plan"!==e||tl?"plan"!==e&&tl&&td(!1):td(!0)},[tg,td,tl]),ok=(0,n.jsx)(s4,{ref:c,onSend:eJ,onBash:eY,tasksBoardEnabled:b,onAbort:eX,onSteer:V?e2:void 0,onFollowUp:V?e4:void 0,onPromptWithStreamingBehavior:V?e6:void 0,isStreaming:V,model:ec,modelNames:J,modelList:Y,modelScopeWarnings:Q,modelsError:ee,onRetryModels:om,onModelChange:e0,compactResult:ed,toolPreset:eo,onToolPresetChange:e||eT?ts:void 0,planMode:tl,onPlanModeChange:of,collaborationMode:tc,tokenMode:tu,toolApprovalMode:th,onCollaborationModeChange:ox,onTokenModeChange:tx,onToolApprovalModeChange:tk,goalState:tS,onGoalStart:tC,onGoalPause:tT,onGoalResume:tR,onGoalStop:tz,thinkingLevel:en,onThinkingLevelChange:e||eT?ti:void 0,availableThinkingLevels:oh,thinkingLevelMap:og,retryInfo:er,queuedMessages:em,inputHistory:ol,onRecallQueue:e5,onMoveQueue:te,onRecallOne:tt,onRequeueAt:to,onRemoveQueueItem:tn,slashCommands:eh,slashCommandsLoading:eg,onLoadSlashCommands:ta,onBuiltinCommand:tr,onAudioUnlock:I,draftKey:e?.id??(t?`new:${t}`:void 0),cwd:e?.cwd??t}),ov=ew.filter(e=>"belowEditor"!==e.placement),oy=ew.filter(e=>"belowEditor"===e.placement),ob=ea?P("desktop.compacting"):function(e,t){if(e?.kind==="running_tools"){let o=e.tools.map(e=>e.name);return 0===o.length?t("desktop.runningTool"):t("desktop.runningTools",{tools:o.length<=3?o.join(", "):`${o.slice(0,2).join(", ")} (+${o.length-2})`})}return e?.kind==="waiting_model"?t("desktop.waitingForModel"):e?.kind==="running_command"?t("desktop.runningCommand"):null}(eC,P);return H?(0,n.jsx)("div",{className:"flex h-full items-center justify-center text-text-muted",children:P("desktop.loadingSession")}):B?(0,n.jsx)("div",{className:"flex h-full items-center justify-center text-red-400",children:B}):(0,n.jsxs)("div",{className:"relative flex h-full min-w-0 flex-col overflow-hidden",onDragEnter:on,onDragOver:or,onDragLeave:os,onDrop:oi,children:[oo&&(0,n.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,n.jsx)("div",{className:"pointer-events-none absolute inset-0 flex items-center justify-center",children:[0,.8,1.6].map(e=>(0,n.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,n.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,n.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,n.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,n.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,n.jsxs)("g",{stroke:"rgba(37,99,235,0.45)",strokeWidth:"1.4",strokeLinecap:"round",children:[(0,n.jsx)("line",{x1:"96",y1:"46",x2:"96",y2:"43"}),(0,n.jsx)("line",{x1:"96",y1:"70",x2:"96",y2:"73"}),(0,n.jsx)("line",{x1:"84",y1:"58",x2:"81",y2:"58"}),(0,n.jsx)("line",{x1:"108",y1:"58",x2:"111",y2:"58"}),(0,n.jsx)("line",{x1:"87.5",y1:"49.5",x2:"85.4",y2:"47.4"}),(0,n.jsx)("line",{x1:"104.5",y1:"66.5",x2:"106.6",y2:"68.6"}),(0,n.jsx)("line",{x1:"104.5",y1:"49.5",x2:"106.6",y2:"47.4"}),(0,n.jsx)("line",{x1:"87.5",y1:"66.5",x2:"85.4",y2:"68.6"})]})]})]}),ev&&(0,n.jsx)(iG,{request:ev,onRespond:ej}),ey&&(0,n.jsx)(iJ,{request:ey,onInput:eS}),!eT&&ef.length>0&&!tF&&(0,n.jsx)(s5,{items:ef,sessionId:e?.id,onResolve:e3,onExport:e7,onStageImport:e9,onDismiss:()=>tD(!0),mode:ex?"import":"recovery"}),ty.length>0&&(0,n.jsx)(nY,{request:ty[0]??null,queuedCount:Math.max(0,ty.length-1),busy:!1,onResolve:(e,t)=>{let o=ty[0];o&&tj(o.id,e,t)}}),oc?(0,n.jsx)("div",{className:"flex flex-1 flex-col items-center justify-center overflow-y-auto",children:(0,n.jsxs)("div",{className:"w-full max-w-[820px]",children:[(0,n.jsx)("div",{style:{display:"flex",justifyContent:"center",marginBottom:28},children:(0,n.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,n.jsx)("title",{children:"Pi"}),(0,n.jsx)("path",{clipRule:"evenodd",d:"M1 1h16.5v11H12v5.5H6.5V23H1V1zm5.5 5.5V12H12V6.5H6.5z"}),(0,n.jsx)("path",{d:"M17.5 12H23v11h-5.5V12z"})]})}),M&&(0,n.jsxs)("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",gap:10,marginBottom:18,marginTop:-14},children:[(0,n.jsxs)("span",{style:{fontSize:11,color:"var(--text-muted)",fontFamily:"var(--font-mono)"},children:["web ",(0,n.jsxs)("span",{style:{color:"var(--text)"},children:["v","0.14.4"]})]}),(0,n.jsxs)("span",{style:{fontSize:11,color:"var(--text-muted)",fontFamily:"var(--font-mono)"},children:["pi ",(0,n.jsxs)("span",{style:{color:"var(--text)"},children:["v","0.84.3"]})]})]}),(0,n.jsx)("div",{style:{padding:"0 34px 6px 7px",paddingRight:M?16:34},children:(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12},children:[(0,n.jsx)("div",{ref:k,style:{display:"flex",alignItems:"center",minWidth:0,flex:1,minHeight:48}}),(0,n.jsxs)("div",{style:{display:M?"none":"flex",flexDirection:"column",alignItems:"flex-end",gap:2,flexShrink:0},children:[(0,n.jsxs)("span",{style:{fontSize:11,color:"var(--text-muted)",fontFamily:"var(--font-mono)"},children:["web ",(0,n.jsxs)("span",{style:{color:"var(--text)"},children:["v","0.14.4"]})]}),(0,n.jsxs)("span",{style:{fontSize:11,color:"var(--text-muted)",fontFamily:"var(--font-mono)"},children:["pi ",(0,n.jsxs)("span",{style:{color:"var(--text)"},children:["v","0.84.3"]})]})]})]})}),(0,n.jsx)("div",{style:{padding:"0 16px",paddingRight:M?16:34},children:(0,n.jsx)(iK,{notices:ek,align:"right"})}),"goal"===tc&&(0,n.jsx)(nG,{goalState:tS,onPause:tT,onResume:tR,onStop:tz,onEdit:tI}),ok,(0,n.jsx)("div",{style:{padding:"0 16px 6px",paddingRight:M?16:34,marginTop:-15},children:(0,n.jsx)(iu,{onViewFullHistory:v,cwd:op,systemPrompt:y,sessionStats:ep,contextUsage:es,hasSession:!!e,showChat:!0,showSoundLabel:!0,soundEnabled:T,onSoundToggle:R,onCompact:e?e1:void 0,onAbortCompaction:e8,isCompacting:ea,compactError:el,isDeepSeekOfficial:t$,deepseekBalance:tW,lastTurnUsage:tO})})]})}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("div",{className:"relative flex flex-1 overflow-hidden z-0",children:[(0,n.jsx)("div",{style:{position:"absolute",top:12,left:0,right:18*!M,zIndex:40,padding:"0 16px",pointerEvents:"none"},children:(0,n.jsx)("div",{style:{maxWidth:820,margin:"0 auto"},children:(0,n.jsx)(iK,{notices:ek,floating:!0,align:"right"})})}),(0,n.jsxs)("div",{className:"relative flex-1 min-h-0 min-w-0",children:[(0,n.jsx)("div",{ref:eE,className:"h-full min-w-0 overflow-x-hidden overflow-y-auto pt-4 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden",children:(0,n.jsx)("div",{style:{minWidth:0,padding:"0 16px"},children:(0,n.jsxs)("div",{style:{width:"100%",minWidth:0,maxWidth:820,margin:"0 auto"},children:[(0,n.jsx)(iq,{statuses:eb}),(0,n.jsx)(iV,{widgets:ov}),(()=>{let{toolResultsMap:t,lastUserIdx:o,visibleRefIndexByMessage:r,items:s}=ou,i=(s,i={})=>{let a=i.messageOverride??U[s],l="user"===a.role&&s>0&&"assistant"===U[s-1].role?_[s-1]:void 0,d="user"===a.role||"assistant"===a.role,c=r.get(s),p=i.keyPrefix??"message",u=!1;if("assistant"===a.role){u=!0;for(let e=s+1;e<U.length;e++){let t=U[e].role;if("user"===t)break;if("assistant"===t){u=!1;break}}u&&q.isStreaming&&s===U.length-1&&(u=!1)}void 0!==i.showTimestamp&&(u=i.showTimestamp);let h=(0,n.jsx)(ny,{message:a,toolResults:t,modelNames:J,cwd:op,onOpenFile:x,entryId:_[s],onFork:V||eT||0===s&&"user"===a.role?void 0:eZ,forking:ei===_[s],onNavigate:V?void 0:eQ,prevAssistantEntryId:V?void 0:l,onEditContent:N,onQuoteReply:L,onCreateTask:O,showTimestamp:u,prevTimestamp:s>0?U[s-1].timestamp:void 0,sessionId:e?.id??eM.current??void 0,writtenFiles:i.writtenFiles,subagents:w,onOpenSubagent:j},`${p}-view-${s}`);return d&&!1!==i.attachRef&&void 0!==c?(0,n.jsx)("div",{ref:e=>{od.current[c]=e,s===o&&(eF.current=e,e&&eV.current&&(eV.current=!1,eK.current=!0,eG()))},children:h},`${p}-${s}`):h},a=[],l=[],d=(e,t)=>{a.push(e),l.push(t)};for(let a of s){if("single"===a.kind){d(i(a.idx),r.get(a.idx));continue}let{userIdx:s,endIdx:l,startsCompactionTurn:c,finalAssistantIdx:p}=a;if((V||q.isStreaming)&&l===U.length&&(s===o||c)){d(i(s),r.get(s));let o=q.streamingMessage?.role==="assistant",a=[],c=!o&&p>=0?p:l;for(let e=s+1;e<c;e++)tb(U[e])&&a.push(e);let u=tf(U,_,a,t),h=null;if(!o&&p>=0){let e=U[p],o=tp(e,{isStreaming:!0}),n=tm(e,{messageIndex:p,entryId:_[p],toolResults:t,isStreaming:!0});u=u.concat(n.processBlocks),o.answerBlocks.length>0&&(h=tw(e,o.answerBlocks,{omitUsage:!0}))}if(o){let e=q.streamingMessage,o=tp(e,{isStreaming:!0}),n=tm(e,{messageIndex:U.length,toolResults:t,isStreaming:!0});u=u.concat(n.processBlocks),o.answerBlocks.length>0&&(h=tw(e,o.answerBlocks,{omitUsage:!0}))}if(u.length>0){let t=a.map(e=>r.get(e)).find(e=>"number"==typeof e);d((0,n.jsx)("div",{ref:void 0===t?void 0:e=>{od.current[t]=e},children:(0,n.jsx)(rF,{blocks:u,isStreaming:V||q.isStreaming,cwd:op,onOpenFile:x,sessionId:e?.id??eM.current??void 0,tokenRate:eu})},`live-process-group-${s}`),t)}h&&d((0,n.jsx)(ny,{message:h,isStreaming:!0,modelNames:J,cwd:op,onOpenFile:x,onQuoteReply:L},`live-answer-${s}`),p>=0?r.get(p):void 0);continue}if(-1===p){for(let e=s;e<l;e++)d(i(e),r.get(e));continue}d(i(s),r.get(s));let{processBlocks:u,finalAnswerMessage:h,writtenFiles:g,visibleProcessIndices:m}=a;if(u.length>0){let t=m.map(e=>r.get(e)).find(e=>"number"==typeof e)??(h?void 0:r.get(p));d((0,n.jsx)("div",{ref:void 0===t?void 0:e=>{od.current[t]=e},children:(0,n.jsx)(rF,{blocks:u,isStreaming:!1,defaultExpanded:!h,onAutoExpanded:void 0,cwd:op,onOpenFile:x,sessionId:e?.id??eM.current??void 0})},`process-group-${s}-${p}`),t)}h&&d(i(p,{messageOverride:h,writtenFiles:g}),r.get(p));for(let e=p+1;e<l;e++)d(i(e),r.get(e))}let c=[];return l.forEach((e,t)=>{void 0!==e&&(c[e]=t)}),t5.current=c,(0,n.jsx)(ig,{scrollElementRef:eE,items:a,virtualizerRef:t8})})(),ob&&(ea||V&&!q.streamingMessage)&&(0,n.jsx)("div",{className:"py-2 text-[13px] text-text-muted",children:(0,n.jsxs)("span",{className:"animate-[pulse_1.5s_infinite]",children:[ob,eC?.kind==="waiting_model"&&(0,n.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"}})]})}),G&&(0,n.jsx)(ny,{message:{role:"bashExecution",command:G.command,output:"",excludeFromContext:G.excludeFromContext},sessionId:e?.id??eM.current??void 0}),K&&!G&&(0,n.jsx)("div",{className:"py-2 text-[13px] text-text-muted",children:(0,n.jsx)("span",{className:"animate-[pulse_1.5s_infinite]",children:P("desktop.runningShellCommand")})}),(0,n.jsx)("div",{style:{height:96}}),(0,n.jsx)("div",{ref:eP}),(0,n.jsx)(nB,{open:tH,planText:tU,busy:V,onExecute:tV,onFeedback:tG,onExit:tJ,onClose:()=>tB(!1)})]})})}),tY&&(0,n.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"}),tZ&&(0,n.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"}),t0&&(0,n.jsxs)("button",{type:"button",onClick:()=>t4(),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,n.jsx)(ns.Z,{size:12,weight:"bold","aria-hidden":"true"}),P("desktop.scrollToBottom")]})]}),M?null:(0,n.jsx)(ik,{messages:U,streamingMessage:q.streamingMessage,scrollContainer:eE,messageRefs:od,virtualizer:t3})]}),(0,n.jsxs)("div",{className:"relative z-10",children:[(0,n.jsx)("div",{style:{padding:"0 16px",paddingRight:M?16:34},children:(0,n.jsx)("div",{style:{maxWidth:820,margin:"0 auto"},children:(0,n.jsx)(iV,{widgets:oy})})}),ok,(0,n.jsx)("div",{className:`session-info-bar-wrap${M?" is-mobile":""}`,children:(0,n.jsx)("div",{className:"session-info-bar-inner",children:(0,n.jsx)(iu,{onViewFullHistory:v,cwd:op,systemPrompt:y,sessionStats:ep,contextUsage:es,hasSession:!!e,showChat:!0,soundEnabled:T,onSoundToggle:R,onCompact:e?e1:void 0,onAbortCompaction:e8,isCompacting:ea,compactError:el,branchTree:eR,branchActiveLeafId:ez,onBranchLeafChange:eI,isDeepSeekOfficial:t$,deepseekBalance:tW,lastTurnUsage:tO})})})]})]})]})}function iq({statuses:e}){return 0===e.length?null:(0,n.jsx)("div",{style:{display:"flex",flexWrap:"wrap",gap:6,marginBottom:10},children:e.map(e=>(0,n.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,n.jsx)("span",{style:{color:"var(--accent)",fontFamily:"var(--font-mono)",fontSize:11},children:e.key}),(0,n.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.text})]},e.key))})}function iV({widgets:e}){return 0===e.length?null:(0,n.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:8,marginBottom:10},children:e.map(e=>(0,n.jsxs)("div",{style:{border:"1px solid var(--border)",borderRadius:7,background:"var(--bg-panel)",overflow:"hidden"},children:[(0,n.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,n.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 iK({notices:e,floating:t=!1,align:o="left"}){return 0===e.length?null:(0,n.jsx)("div",{style:{display:"flex",flexDirection:"column",alignItems:"right"===o?"flex-end":"stretch",marginBottom:10*!t},children:e.map((o,r)=>{let s="error"===o.type?"#ef4444":"warning"===o.type?"#d97706":"success"===o.type?"#10b981":"var(--accent)";return(0,n.jsxs)("div",{className:"notice-shelf-item",style:{display:"flex",alignItems:"center",gap:10,minHeight:44,maxHeight:180,marginBottom:6*(r!==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:o.exiting?"notice-shelf-out 0.18s ease-in forwards":"notice-shelf-in 0.18s ease-out both",padding:"0 12px"},children:[(0,n.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:s,flexShrink:0}}),(0,n.jsx)("span",{style:{padding:"10px 0",minWidth:0,maxWidth:"100%",overflowWrap:"anywhere",whiteSpace:"pre-wrap"},children:o.message})]},o.id)})})}function iG({request:e,onRespond:t}){let{t:o}=(0,F.s)(),[s,i]=(0,r.useState)("editor"===e.method?e.prefill??"":"");(0,r.useEffect)(()=>{i("editor"===e.method?e.prefill??"":"")},[e]);let a=()=>{"confirm"===e.method?t(e,{confirmed:!0}):t(e,{value:s})};return(0,n.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,n.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,n.jsxs)("div",{style:{padding:"12px 14px",borderBottom:"1px solid var(--border)"},children:[(0,n.jsx)("div",{style:{color:"var(--text)",fontSize:14,fontWeight:650},children:e.title}),(0,n.jsx)("div",{style:{marginTop:3,color:"var(--text-dim)",fontSize:11,fontFamily:"var(--font-mono)"},children:o("desktop.extensionRequest")})]}),(0,n.jsxs)("div",{style:{padding:14},children:["confirm"===e.method&&(0,n.jsx)("div",{style:{color:"var(--text-muted)",fontSize:13,lineHeight:1.6,whiteSpace:"pre-wrap"},children:e.message}),"select"===e.method&&(0,n.jsx)("div",{style:{display:"grid",gap:8},children:e.options.map(o=>(0,n.jsx)("button",{onClick:()=>t(e,{value:o}),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:o},o))}),"input"===e.method&&(0,n.jsx)("input",{autoFocus:!0,value:s,placeholder:e.placeholder,onChange:e=>i(e.target.value),onKeyDown:o=>{"Enter"===o.key&&a(),"Escape"===o.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,n.jsx)("textarea",{autoFocus:!0,value:s,onChange:e=>i(e.target.value),onKeyDown:o=>{"Escape"===o.key&&t(e,{cancelled:!0}),(o.metaKey||o.ctrlKey)&&"Enter"===o.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,n.jsxs)("div",{style:{display:"flex",justifyContent:"flex-end",gap:8,padding:"10px 14px",borderTop:"1px solid var(--border)",background:"var(--bg-panel)"},children:[(0,n.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:o("desktop.cancel")}),"confirm"===e.method?(0,n.jsx)("button",{onClick:a,style:{padding:"6px 10px",borderRadius:6,border:"1px solid var(--accent)",background:"var(--accent)",color:"#fff",cursor:"pointer"},children:o("desktop.confirm")}):"select"!==e.method?(0,n.jsx)("button",{onClick:a,style:{padding:"6px 10px",borderRadius:6,border:"1px solid var(--accent)",background:"var(--accent)",color:"#fff",cursor:"pointer"},children:o("desktop.submit")}):null]})]})})}function iJ({request:e,onInput:t}){let{t:o}=(0,F.s)(),s=(0,r.useRef)(null),i=function(e){let t=/^[┌├└╭╰][─┬┴┼]+[┐┤┘╮╯]$/,o=[];for(let n of e){let e=ts(n).trimEnd();if(t.test(e))continue;let r=n,s=tl(r);("│"===s||"┃"===s)&&" "===tl(r=ta(r,0))&&(r=ta(r,0));let i=function(e){let t=ti(e);for(let e=t.length-1;e>=0;e--)if(""!==t[e].char.trim())return e;return -1}(r),a=i>=0?ti(r)[i]?.char:void 0;("│"===a||"┃"===a)&&(r=ta(r,i)),o.push(function(e){let t=e;for(;;){let e=ti(t),o=e[e.length-1];if(!o||""!==o.char.trim())return t;t=t.slice(0,o.start)+t.slice(o.end)}}(r))}for(;o.length>0&&""===ts(o[0]).trim();)o.shift();for(;o.length>0&&""===ts(o[o.length-1]).trim();)o.pop();return o.length?o:e}(e.lines);return(0,r.useEffect)(()=>{s.current?.focus()},[e.id]),(0,n.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,n.jsxs)("div",{ref:s,tabIndex:0,role:"dialog","aria-modal":"true",onKeyDown:o=>{let n=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}}(o);n&&(o.preventDefault(),o.stopPropagation(),t(e,n))},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,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,padding:"10px 12px",borderBottom:"1px solid var(--border)"},children:[(0,n.jsx)("div",{style:{color:"var(--text)",fontSize:13,fontWeight:650},children:o("desktop.extensionPanel")}),(0,n.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:o("desktop.close")})]}),(0,n.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,o)=>{var s;return(0,n.jsxs)(r.Fragment,{children:[(s=`line-${t}`,(function(e){let t,o=[],n={},r=0;for(to.lastIndex=0;null!==(t=to.exec(e));)t.index>r&&o.push({text:e.slice(r,t.index),style:n}),n=function(e,t){let o={...e};for(let e=0;e<t.length;e++){let n=t[e];if(0===n)for(let e of Object.keys(o))delete o[e];else if(1===n)o.fontWeight=700;else if(2===n)o.opacity=.65;else if(3===n)o.fontStyle="italic";else if(4===n)o.textDecoration="underline";else if(22===n)delete o.fontWeight,delete o.opacity;else if(23===n)delete o.fontStyle;else if(24===n)delete o.textDecoration;else if(39===n)delete o.color;else if(49===n)delete o.backgroundColor;else if(n>=30&&n<=37)o.color=tn[n-30];else if(n>=90&&n<=97)o.color=tr[n-90];else if(n>=40&&n<=47)o.backgroundColor=tn[n-40];else if(n>=100&&n<=107)o.backgroundColor=tr[n-100];else if((38===n||48===n)&&2===t[e+1]){let[r,s,i]=[t[e+2],t[e+3],t[e+4]];[r,s,i].every(e=>"number"==typeof e&&Number.isFinite(e))&&(38===n?o.color=`rgb(${r}, ${s}, ${i})`:o.backgroundColor=`rgb(${r}, ${s}, ${i})`),e+=4}else if((38===n||48===n)&&5===t[e+1]){let r=function(e){if(e>=0&&e<8)return tn[e];if(e>=8&&e<16)return tr[e-8];if(e>=16&&e<=231){let t=e-16,o=Math.floor(t/36),n=Math.floor(t%36/6),r=e=>0===e?0:55+40*e;return`rgb(${r(o)}, ${r(n)}, ${r(t%6)})`}if(e>=232&&e<=255){let t=8+(e-232)*10;return`rgb(${t}, ${t}, ${t})`}}(t[e+2]);r&&(38===n?o.color=r:o.backgroundColor=r),e+=2}}return o}(n,t[1]?t[1].split(";").map(e=>Number(e||"0")):[0]),r=t.index+t[0].length;return r<e.length&&o.push({text:e.slice(r),style:n}),o})(e).map((e,t)=>Object.keys(e.style).length>0?(0,n.jsx)("span",{style:e.style,children:e.text},`${s}-${t}`):e.text)),t<o.length-1?"\n":null]},t)})})]})})}var iY=o(93549);let iX={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"},iZ={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",webm:"audio/webm"};function iQ(e){return(e.replace(/\\/g,"/").split("/").pop()??"").toLowerCase().split(".").pop()??""}function i0(e){let t=e.nodeType===Node.ELEMENT_NODE?e:e.parentElement;return t?.closest(".file-source-line[data-line-number]")??null}function i1(e,t){if(!t||t.isCollapsed||0===t.rangeCount)return null;let o=t.getRangeAt(0);if(!e.contains(o.startContainer)||!e.contains(o.endContainer))return null;let n=Number(i0(o.startContainer)?.dataset.lineNumber),r=Number(i0(o.endContainer)?.dataset.lineNumber);return Number.isInteger(n)&&Number.isInteger(r)?n<=r?{startLine:n,endLine:r}:{startLine:r,endLine:n}:null}function i2(e,t,o,n={}){let r=ei(e),s=new URLSearchParams({type:t});for(let[e,t]of(o&&s.set("sessionId",o),Object.entries(n)))void 0!==t&&s.set(e,String(t));return`/api/files/${r}?${s.toString()}`}function i4({filePath:e,sourceSessionId:t}){let{t:o}=(0,F.s)();return(0,n.jsx)("a",{href:i2(e,"download",t),download:ea(e),title:o("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,n.jsx)(I.z,{size:11,"aria-hidden":"true"})})}let i6={fontFamily:"var(--font-mono)",fontSize:13,lineHeight:1.6,tabSize:2},i8={fontFamily:"var(--font-mono)",fontSize:13,lineHeight:1.6,padding:"12px 0 12px 16px",color:"var(--text-dim)",textAlign:"right",userSelect:"none"};async function i5(e,t){let o=await fetch(`/api/files/${ei(e)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:t})});if(!o.ok)throw Error((await o.json().catch(()=>({}))).error??`HTTP ${o.status}`);let n=await o.json();return"number"==typeof n.size?n.size:0}let i3={delete:"3px solid var(--git-status-deleted)",add:"3px solid var(--git-status-added)",edit:"3px solid var(--git-status-modified)"},i7="var(--git-status-deleted-bg)",i9="var(--git-status-added-bg)",ae="var(--git-status-added)";function at(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KB`:`${(e/1048576).toFixed(1)} MB`}function ao({oldContent:e,newContent:t}){let{t:o}=(0,F.s)(),r=function(e,t){let o=e.length,n=t.length,r=o+n,s=Array(2*r+1).fill(0),i=[];for(let a=0;a<=r;a++){i.push([...s]);for(let l=-a;l<=a;l+=2){let d,c=(d=l===-a||l!==a&&s[l-1+r]<s[l+1+r]?s[l+1+r]:s[l-1+r]+1)-l;for(;d<o&&c<n&&e[d]===t[c];)d++,c++;if(s[l+r]=d,d>=o&&c>=n){let s=[],l=o,d=n;for(let o=a;o>0;o--){let n,a=i[o-1],c=l-d;n=c===-o||c!==o&&a[c-1+r]<a[c+1+r]?c+1:c-1;let p=a[n+r],u=p-n;for(;l>p&&d>u;)l--,d--,s.unshift({type:"unchanged",text:e[l]});o>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(!r.some(e=>"unchanged"!==e.type))return(0,n.jsx)("div",{style:{padding:"12px 16px",fontSize:12,color:"var(--text-dim)",fontFamily:"var(--font-mono)"},children:o("desktop.noChanges")});let s=new Set(r.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(r.length-1,e+3);t++)i.add(t);let a=[],l=0;for(;l<r.length;)if(i.has(l)){let e=[];for(;l<r.length&&i.has(l);)e.push(r[l]),l++;a.push({hidden:!1,lines:e})}else{let e=0;for(;l<r.length&&!i.has(l);)e++,l++;a.push({hidden:!0,count:e})}let d=[],c=1;for(let e of r)"removed"===e.type?d.push(0):d.push(c++);let p=0;return(0,n.jsx)("div",{style:{fontFamily:"var(--font-mono)",fontSize:13,lineHeight:1.6,minWidth:"max-content"},children:a.map((e,t)=>{if(e.hidden){let r=(0,n.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:o("desktop.unchangedLines",{count:e.count})},t);return p+=e.count,r}let r=[],s=[],i=[],a=()=>{if(s.length||i.length){let e=s.length&&i.length?"edit":s.length?"delete":"add";for(let t of s)r.push({key:t.key,kind:"removed",text:t.text,lineNo:null,block:e});for(let t of i)r.push({key:t.key,kind:"added",text:t.text,lineNo:t.lineNo,block:e});s=[],i=[]}};e.lines.forEach((e,o)=>{"unchanged"===e.type?(a(),r.push({key:`${t}:${o}`,kind:"context",text:e.text,lineNo:d[p+o],block:null})):"removed"===e.type?s.push({key:`${t}:${o}`,text:e.text}):i.push({key:`${t}:${o}`,text:e.text,lineNo:d[p+o]})}),a();let l=r.map(e=>{let t="removed"===e.kind?i7:"added"===e.kind?i9:"transparent",o=e.block?i3[e.block]:"3px solid transparent",r="added"===e.kind?ae:"var(--text-dim)";return(0,n.jsxs)("div",{style:{display:"flex",background:t,borderLeft:o},children:[(0,n.jsx)("span",{style:{minWidth:44,padding:"0 8px 0 16px",textAlign:"right",color:r,userSelect:"none",fontSize:11,lineHeight:1.6,flexShrink:0},children:e.lineNo??""}),(0,n.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,n.jsx)("div",{children:l},t)})})}function an({patch:e}){let t=o7(e);if(!t)return null;let o=[],r=[],s=[],i=()=>{if(r.length||s.length){let e=r.length&&s.length?"edit":r.length?"delete":"add";for(let t of r)o.push({key:t.key,kind:"removed",text:t.text,lineNo:null,block:e});for(let t of s)o.push({key:t.key,kind:"added",text:t.text,lineNo:t.lineNo,block:e});r=[],s=[]}};return t.forEach((e,t)=>{e.rows.forEach((e,n)=>{if("hunk"===e.type){i(),o.push({key:`${t}:${n}: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(),o.push({key:`${t}:${n}:c`,kind:"context",text:a.text,lineNo:l.lineNo,block:null});return}"removed"===a.type&&r.push({key:`${t}:${n}:l`,text:a.text}),"added"===l.type&&s.push({key:`${t}:${n}:r`,text:l.text,lineNo:l.lineNo})})}),i(),(0,n.jsx)("div",{style:{fontFamily:"var(--font-mono)",fontSize:12,lineHeight:1.55,minWidth:"max-content"},children:o.map(e=>{if("hunk"===e.kind)return(0,n.jsxs)("div",{children:[(0,n.jsx)("div",{style:{height:"1.55em"}}),(0,n.jsx)("div",{style:{padding:"3px 12px",color:"var(--accent-blue)",background:"var(--bg-secondary)"},children:e.text}),(0,n.jsx)("div",{style:{height:"1.55em"}})]},e.key);let t="removed"===e.kind?i7:"added"===e.kind?i9:"transparent",o=e.block?i3[e.block]:"3px solid transparent",r="added"===e.kind?ae:"var(--text-dim)";return(0,n.jsxs)("div",{style:{display:"flex",background:t,borderLeft:o},children:[(0,n.jsx)("span",{style:{width:44,flexShrink:0,padding:"0 8px 0 16px",textAlign:"right",color:r,userSelect:"none",fontSize:11},children:e.lineNo??""}),(0,n.jsx)("span",{style:{flex:1,minWidth:0,padding:"0 8px 0 0",whiteSpace:"pre",color:"var(--text)"},children:e.text||"\xa0"})]},e.key)})})}function ar({filePath:e,cwd:t,sourceSessionId:o}){let{t:s}=(0,F.s)(),[i,a]=(0,r.useState)(0),[l,d]=(0,r.useState)(null),[c,p]=(0,r.useState)(null),[u,h]=(0,r.useState)(null),g=(0,r.useRef)(null),m=ea(e).toLowerCase().split(".").pop()??"";(0,r.useEffect)(()=>{a(0),d(null),p(null),h(null),g.current&&(g.current.close(),g.current=null);let t=new EventSource(i2(e,"watch",o));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,o]);let f=i2(e,"read",o,i?{v:i}:void 0),x=null!=l?at(l):null;return(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,n.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,n.jsx)("span",{style:{fontFamily:"var(--font-mono)"},title:e,children:el(e,t)}),(0,n.jsx)("span",{style:{marginLeft:"auto"},children:m||s("desktop.image")}),c&&(0,n.jsxs)("span",{children:[c.w," \xd7 ",c.h]}),x&&(0,n.jsx)("span",{children:x}),(0,n.jsx)(i4,{filePath:e,sourceSessionId:o})]}),(0,n.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,n.jsx)("div",{style:{color:"#f87171",fontSize:13},children:u}):(0,n.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 as({filePath:e,cwd:t,sourceSessionId:o}){let{t:s}=(0,F.s)(),[i,a]=(0,r.useState)(0),[l,d]=(0,r.useState)(null),[c,p]=(0,r.useState)(null),[u,h]=(0,r.useState)(null),g=(0,r.useRef)(null),m=ea(e).toLowerCase().split(".").pop()??"";(0,r.useEffect)(()=>{a(0),d(null),p(null),h(null),g.current&&(g.current.close(),g.current=null);let t=new EventSource(i2(e,"watch",o));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,o]);let f=i2(e,"read",o,i?{v:i}:void 0);return(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,n.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,n.jsx)("span",{style:{fontFamily:"var(--font-mono)"},title:e,children:el(e,t)}),(0,n.jsx)("span",{style:{marginLeft:"auto"},children:m||s("desktop.audio")}),null!=c&&(0,n.jsx)("span",{children:function(e){if(!Number.isFinite(e))return"";let t=Math.round(e),o=Math.floor(t/60);return`${o}:${String(t%60).padStart(2,"0")}`}(c)}),null!=l&&(0,n.jsx)("span",{children:at(l)}),(0,n.jsx)(i4,{filePath:e,sourceSessionId:o})]}),(0,n.jsx)("div",{style:{flex:1,display:"flex",alignItems:"center",justifyContent:"center",padding:24,background:"var(--bg-panel)"},children:(0,n.jsxs)("div",{style:{width:"min(680px, 100%)"},children:[u&&(0,n.jsx)("div",{style:{color:"#f87171",fontSize:13,marginBottom:12,textAlign:"center"},children:u}),(0,n.jsx)("audio",{controls:!0,preload:"metadata",src:f,onLoadedMetadata:e=>p(e.currentTarget.duration),onError:()=>h(s("desktop.failedToLoadAudio")),style:{width:"100%"}},f)]})})]})}function ai({filePath:e,cwd:t,sourceSessionId:o}){let{t:s}=(0,F.s)(),[i,a]=(0,r.useState)(0),[l,d]=(0,r.useState)(null),[c,p]=(0,r.useState)(null),u=(0,r.useRef)(null),h=iQ(e),g="pdf"===h,m=g?i2(e,"read",o,i?{v:i}:void 0):i2(e,"preview",o,i?{v:i}:void 0);return(0,r.useEffect)(()=>{a(0),d(null),p(null),u.current&&(u.current.close(),u.current=null),fetch(i2(e,"meta",o)).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(i2(e,"watch",o));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,o,s]),(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,n.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,n.jsx)("span",{style:{fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:e,children:el(e,t)}),(0,n.jsx)("span",{style:{marginLeft:"auto"},children:"docx"===h?s("desktop.docxPreview"):"pdf"}),null!=l&&(0,n.jsx)("span",{children:at(l)}),(0,n.jsx)(i4,{filePath:e,sourceSessionId:o})]}),(0,n.jsx)("div",{style:{flex:1,minHeight:0,background:"var(--bg-panel)"},children:c?(0,n.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",padding:24,color:"#f87171",fontSize:13,textAlign:"center"},children:c}):(0,n.jsx)("iframe",{src:m,sandbox:g?void 0:"allow-same-origin",title:s("desktop.previewFile",{file:ea(e)}),style:{width:"100%",height:"100%",border:"none",background:g?"var(--bg)":"#eef1f5"}},m)})]})}function aa({filePath:e,cwd:t,sourceSessionId:o,onOpenFile:r,onAtMention:s,onMentionLines:i,initialDisplayMode:a,onFileSaved:l}){let d;return null!==(iX[iQ(e)]??null)?(0,n.jsx)(ar,{filePath:e,cwd:t,sourceSessionId:o}):null!==(iZ[iQ(e)]??null)?(0,n.jsx)(as,{filePath:e,cwd:t,sourceSessionId:o}):null!==("pdf"===(d=iQ(e))||"docx"===d?d:null)?(0,n.jsx)(ai,{filePath:e,cwd:t,sourceSessionId:o}):(0,n.jsx)(al,{filePath:e,cwd:t,sourceSessionId:o,onOpenFile:r,onAtMention:s,onMentionLines:i,initialDisplayMode:a,onFileSaved:l})}function al({filePath:e,cwd:t,sourceSessionId:o,onOpenFile:s,onAtMention:i,onMentionLines:a,initialDisplayMode:l,onFileSaved:d}){let c,u,{t:h}=(0,F.s)(),[m,f]=(0,r.useState)(null),[x,k]=(0,r.useState)(null),[v,y]=(0,r.useState)(null),[b,w]=(0,r.useState)(!0),[j,S]=(0,r.useState)(null),[C,T]=(0,r.useState)(!1),[R,z]=(0,r.useState)("source"),[I,M]=(0,r.useState)(!1),[P,E]=(0,r.useState)(0),[D,W]=(0,r.useState)(null),A=(0,r.useRef)(null),N=(0,r.useRef)(null),[$,L]=(0,r.useState)(!1),[O,H]=(0,r.useState)(""),[B,U]=(0,r.useState)(""),[_,q]=(0,r.useState)(!1),[V,K]=(0,r.useState)(null),[G,J]=(0,r.useState)(!1),Y=(0,r.useRef)(null),X=(0,r.useRef)(null),Z=(0,r.useRef)(0),Q=(0,r.useRef)(!1);(0,r.useEffect)(()=>{Q.current=$},[$]);let ee=$&&O!==B,et=!!(m?.content&&m.content.includes("\0")),eo=(0,r.useCallback)(async e=>{if(!t)return void y(null);try{let o=new URLSearchParams({cwd:t,path:e}),n=await fetch(`/api/git/diff?${o.toString()}`),r=await n.json();y(n.ok&&r.supported&&"string"==typeof r.patch?r:null)}catch{y(null)}},[t]),en=(0,r.useCallback)((e,t=!1)=>fetch(i2(e,"read",o)).then(e=>e.json()).then(e=>e.error?(S(e.error),null):(t?(f(t=>(t&&k(t.content),e)),E(e=>e+1)):f(e),e)).catch(e=>(S(String(e)),null)),[o]);(0,r.useEffect)(()=>{w(!0),S(null),f(null),k(null),y(null),T(!1),z("source"),M(!1),E(0),L(!1),H(""),U(""),K(null),J(!1),q(!1),A.current&&(A.current.close(),A.current=null),en(e).then(e=>{(e?.language==="markdown"||e?.language==="html")&&"diff"!==l&&T(!0)}).finally(()=>w(!1)),eo(e);let t=new EventSource(i2(e,"watch",o));return A.current=t,t.addEventListener("change",()=>{Q.current?J(!0):(en(e,!0),eo(e))}),()=>{t.close(),A.current=null}},[e,en,eo,l,o]);let er=(0,r.useCallback)(()=>{m&&!et&&(H(m.content),U(m.content),K(null),J(!1),L(!0))},[m,et]),ei=(0,r.useCallback)(()=>{L(!1),H(""),U(""),K(null),J(!1)},[]),ea=(0,r.useCallback)(()=>{(!ee||window.confirm(h("files.unsavedChanges")))&&ei()},[ee,ei,h]),ed=(0,r.useCallback)(async()=>{if(!m||_)return;let t=++Z.current;q(!0),K(null);try{let o=await i5(e,O);if(t!==Z.current)return;f(e=>e?{...e,content:O,size:o}:e),U(O),q(!1),ei(),eo(e),d?.()}catch(e){if(t!==Z.current)return;K(e instanceof Error?e.message:String(e)),q(!1)}},[m,_,O,e,ei,eo,d]);(0,r.useEffect)(()=>{if(!$)return;let e=e=>{if((e.metaKey||e.ctrlKey)&&"s"===e.key.toLowerCase()){e.preventDefault(),ed();return}"Escape"===e.key&&(e.preventDefault(),ea())};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[$,ed,ea]),(0,r.useEffect)(()=>{if(!ee)return;let e=e=>{e.preventDefault(),e.returnValue=""};return window.addEventListener("beforeunload",e),()=>window.removeEventListener("beforeunload",e)},[ee]);let ec=(0,r.useCallback)(()=>{let e=Y.current,t=X.current;e&&t&&(t.scrollTop=e.scrollTop)},[]),eu=(0,r.useCallback)(e=>{if("Tab"!==e.key||e.metaKey||e.ctrlKey||e.altKey)return;e.preventDefault();let t=e.currentTarget,{selectionStart:o,selectionEnd:n}=t;H(t.value.slice(0,o)+" "+t.value.slice(n)),requestAnimationFrame(()=>{let e=Y.current;if(!e)return;let t=o+2;e.selectionStart=t,e.selectionEnd=t})},[]),eh=(0,r.useMemo)(()=>oP(m?.content??""),[m?.content]),eg=v?.supported===!0&&"string"==typeof v.patch;(0,r.useEffect)(()=>{"diff"===l&&eg&&z("diff")},[eg,l]);let em=eg&&v?.status==="deleted",ef=(0,r.useCallback)(o=>{a&&o&&a(el(e,t),o.startLine,o.endLine)},[t,e,a]);if((0,r.useEffect)(()=>{let e=()=>{let e=N.current,t="source"===R&&!C;W(a&&t&&e?i1(e,window.getSelection()):null)};if(e(),a&&"source"===R&&!C)return document.addEventListener("selectionchange",e),()=>document.removeEventListener("selectionchange",e)},[m?.content,a,C,R]),(0,r.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 o=N.current,n=o?i1(o,window.getSelection()):null;n&&(e.preventDefault(),ef(n))};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[ef,a,C,R]),b)return(0,n.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-muted)",fontSize:13},children:h("desktop.loadingFile")});if(em&&!m)return(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,n.jsx)("div",{style:{padding:"5px 16px",borderBottom:"1px solid var(--border)",color:"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:11},title:e,children:el(e,t)}),(0,n.jsx)("div",{style:{flex:1,overflow:"auto",background:"var(--bg)"},children:(0,n.jsx)(an,{patch:v.patch})})]});if(j)return(0,n.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"#f87171",fontSize:13},children:j});if(!m)return null;let ex="html"===m.language,ek="markdown"===m.language,ev=(u=(c=es(e).replace(/\/+$/,"")).lastIndexOf("/"))<0?"":0===u?"/":2===u&&/^[a-zA-Z]:\//.test(c)?c.slice(0,3):c.slice(0,u),ey=m.content.split("\n"),eb=null!==x&&x!==m.content||eg,ew=!em&&!et&&ep();return(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,n.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,n.jsx)("span",{style:{fontFamily:"var(--font-mono)"},title:e,children:el(e,t)}),(0,n.jsx)("span",{style:{marginLeft:"auto"},children:m.language}),"source"===R&&!$&&(0,n.jsx)("span",{children:h("desktop.lines",{count:ey.length})}),(0,n.jsx)("span",{children:at(m.size)}),eb&&!$&&(0,n.jsxs)("div",{style:{display:"flex",borderRadius:5,overflow:"hidden",border:"1px solid var(--border)"},children:[(0,n.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:h("desktop.source")}),(0,n.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:[h("desktop.diff")," ",P>0&&(0,n.jsxs)("span",{style:{color:"var(--git-status-added)",marginLeft:2},children:["+",P]})]})]}),"source"===R&&!C&&!$&&(0,n.jsx)("button",{onClick:()=>M(e=>!e),title:I?h("desktop.disableWordWrap"):h("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:h("desktop.wrap")}),ex&&"source"===R&&!$&&(0,n.jsxs)("div",{style:{display:"flex",borderRadius:5,overflow:"hidden",border:"1px solid var(--border)"},children:[(0,n.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:h("desktop.code")}),(0,n.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:h("desktop.preview")})]}),ek&&"source"===R&&!$&&(0,n.jsxs)("div",{style:{display:"flex",borderRadius:5,overflow:"hidden",border:"1px solid var(--border)"},children:[(0,n.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:h("desktop.preview")}),(0,n.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:h("desktop.raw")})]}),$?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("button",{type:"button",onClick:()=>void ed(),disabled:_,title:h("files.saveHint"),"aria-label":h("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,n.jsx)(iY.g,{size:13,"aria-hidden":"true"})}),(0,n.jsx)("button",{type:"button",onClick:ea,disabled:_,title:h("files.cancelEdit"),"aria-label":h("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,n.jsx)(p.X,{size:13,"aria-hidden":"true"})})]}):"source"===R&&ew?(0,n.jsx)("button",{type:"button",onClick:er,title:h("files.edit"),"aria-label":h("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,n.jsx)(g.I,{size:13,"aria-hidden":"true"})}):null,(i||a)&&!$&&(0,n.jsx)("button",{type:"button",onPointerDown:e=>e.preventDefault(),onClick:()=>{D&&a?ef(D):i?.(el(e,t),!1)},title:D?h("desktop.mentionSelectedLines",{start:D.startLine,end:D.endLine}):h("desktop.mentionFile"),"aria-label":D?h("desktop.mentionSelectedLines",{start:D.startLine,end:D.endLine}):h("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:"@"}),!$&&(0,n.jsx)(i4,{filePath:e,sourceSessionId:o})]}),(0,n.jsx)("div",{ref:N,style:{flex:1,overflow:"auto",background:"var(--bg)"},children:$?(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[G&&(0,n.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,n.jsx)("span",{style:{flex:1},children:h("files.externalModified")}),(0,n.jsx)("button",{type:"button",onClick:()=>{(!ee||window.confirm(h("files.reloadOverwriteConfirm")))&&en(e).then(e=>{e&&(H(e.content),U(e.content),J(!1))})},disabled:_,style:{padding:"2px 8px",fontSize:11,border:"1px solid #d6a84b",borderRadius:4,background:"transparent",color:"#d6a84b",cursor:"pointer"},children:h("files.reload")})]}),V&&(0,n.jsx)("div",{style:{padding:"5px 12px",borderBottom:"1px solid var(--border)",background:"rgba(248,113,113,0.14)",color:"#f87171",fontSize:11,flexShrink:0},children:h("files.saveFailed",{error:V})}),(0,n.jsxs)("div",{style:{flex:1,display:"flex",overflow:"hidden"},children:[(0,n.jsx)("div",{ref:X,"aria-hidden":"true",style:{...i8,height:"100%",overflow:"hidden",whiteSpace:"pre",pointerEvents:"none"},children:O.split("\n").map((e,t)=>`${t+1}
|
|
36
|
+
${o}`):s=o;let m=s,f=r?.map(e=>({type:"image",source:{type:"base64",media_type:e.mimeType,data:e.data}})),x={role:"user",content:f?.length?[...o.trim()?[{type:"text",text:o}]:[],...f]:o,timestamp:Date.now()};S(e=>[...e,x]),ol.current=iO(x),oa.current=l,"goal"!==ew.current||a||(eT.current=i,eF(e=>({...e,status:"running",goalText:i,turnsUsed:0,noProgressTurns:0,tokensUsed:0})),eK.current=!0),tX.current=!0,O(!0),ts(a?{kind:"running_command"}:{kind:"waiting_model"}),E({type:"start"}),t7.current=!0,ta(!0),t9.current=!0;let k=r?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),v=null,y=!1;try{if(h&&n){let e=tY.current??await os.current,t=e??await oz();if(t){v=t,oR(1,o),en&&(e3(en),e&&await iS(t,{type:"set_model",provider:en.provider,modelId:en.modelId}));let n=await Promise.race([oF(t).then(()=>!0).catch(()=>!1),iA(4e3).then(()=>!1)]);y=!0,await iS(t,{type:"prompt",message:m,...k?.length?{images:k}:{}}),n||o_(t,l),"goal"!==ew.current||a||iS(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([oF(t.id).then(()=>!0).catch(()=>!1),iA(4e3).then(()=>!1)]);y=!0,await iS(t.id,{type:"prompt",message:m,...k?.length?{images:k}:{}}),e||o_(t.id,l),"goal"!==ew.current||a||iS(t.id,{type:"goal_start",goalText:i}).catch(()=>{})}a&&v&&o_(v,l)}catch(t){if(console.error("Failed to send message:",t),y&&v)return void o_(v,l);if(tQ.current=!1,oP(),t instanceof iW){let e=ol.current;e&&S(t=>{let o=t[t.length-1];return o?.role==="user"&&iO(o)===e?t.slice(0,-1):t}),oA({type:"error",message:t.message})}else{let o=ol.current;o&&S(e=>{let t=e[e.length-1];return t?.role==="user"&&iO(t)===o?e.slice(0,-1):e}),e.chatInputRef?.current?.replaceMessage?.(x),oA({type:"error",message:`Failed to send message: ${t instanceof Error?t.message:String(t)}`})}ol.current=null,tX.current=!1,O(!1),ts(null),E({type:"end"})}},[h,n,en,t,oz,oF,oR,o_,oA,oM,oP,of]),oJ=(0,r.useCallback)(async(o,n)=>{if(tX.current||t4.current)return;let r=`${n?"!!":"!"}${o}`;t4.current=!0,_({command:o,excludeFromContext:n}),B(!0);try{let e=tY.current??t?.id??await oz();if(!e)throw Error("Unable to create a session for the shell command");oR(1,r),await iS(e,{type:"bash",command:o,excludeFromContext:n}),await oS(e)}catch(t){console.error("Failed to execute shell command:",t),oA({type:"error",message:t instanceof Error?t.message:String(t)}),e.chatInputRef?.current?.insertIfEmpty(r)}finally{t4.current=!1,_(null),B(!1)}},[oA,oz,oS,e.chatInputRef,oR,t]),oY=(0,r.useCallback)(async()=>{let e=tY.current;if(e)try{await iS(e,{type:t4.current?"abort_bash":"abort"})}catch(e){console.error("Failed to abort:",e)}},[]),oX=(0,r.useCallback)(async e=>{let t=tY.current;if(t){e4(e);try{let{cancelled:o,newSessionId:n}=await iS(t,{type:"fork",entryId:e})??{};!o&&n&&a?.(n)}catch(e){console.error("Fork failed:",e)}finally{e4(null)}}},[a]),oZ=(0,r.useCallback)(async e=>{let t=tY.current;t&&(iS(t,{type:"navigate_tree",targetId:e}).catch(()=>{}),w(e),await oC(t,e))},[oC]),oQ=(0,r.useCallback)(async e=>{w(e);let t=tY.current;t&&(await oC(t,e),e&&iS(t,{type:"navigate_tree",targetId:e}).catch(()=>{}))},[oC]),o0=(0,r.useCallback)(async(e,t)=>{if(h){let o={provider:e,modelId:t};oh.current=o,er(o),e3(o);let n=tY.current??await os.current;if(!n)return;try{await iS(n,{type:"set_model",provider:e,modelId:t})}catch(e){console.error("Failed to set model:",e)}return}let o=tY.current;if(!o)return;let n=++od.current,r=e6??m?.context.model??null;e8({provider:e,modelId:t});try{await iS(o,{type:"set_model",provider:e,modelId:t})}catch(o){console.error("Failed to set model:",o),od.current===n&&(e8(r&&(r.provider!==e||r.modelId!==t)?r:null),oA({type:"error",message:o instanceof Error?o.message:String(o)}))}},[oA,e6,m?.context.model,h,er]),o1=(0,r.useCallback)(async()=>{let e=tY.current;if(e&&!e7){e9(!0),tt(null),tn(null);try{let t=await iS(e,{type:"compact"});tn(iH(t,"manual")),await oS(e,!0)}catch(e){tt(e instanceof Error?e.message:String(e)),tn(null)}finally{e9(!1)}}},[e7,oS]),o2=(0,r.useCallback)(async e=>{let o=++oc.current,r=n??t?.cwd??"",s=r?`/api/models?cwd=${encodeURIComponent(r)}`:"/api/models",i=op.current;i?.abort();let a=new AbortController;op.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 o=await e.json();o?.error&&(t=o.error)}catch{}throw Error(t)}let t=await e.json();if(o!==oc.current||g!==ou.current)return;eo(null),V(t.models),Y(t.thinkingLevels??{}),Z(t.thinkingLevelMaps??{}),ee(t.modelScopeWarnings??[]);let n=t.modelList??[];if(G(n),h&&!tY.current){let e=(t.defaultModel?n.find(e=>e.id===t.defaultModel?.modelId&&e.provider===t.defaultModel?.provider):void 0)??n[0];ei(e?{provider:e.provider,modelId:e.id}:null);let o=e?t.thinkingLevelPins?.[`${e.provider}/${e.id}`]:void 0;null===og.current&&eJ(o??"auto")}}catch(e){if(a.signal.aborted||o!==oc.current||g!==ou.current)return;eo(e instanceof Error?e.message:String(e))}finally{e?.removeEventListener("abort",l),op.current===a&&(op.current=null)}},[h,g,n,t?.cwd]),o4=(0,r.useCallback)(async e=>{if(!e.startsWith("/"))return{handled:!1};let t=e.match(/^\/([^\s]+)(?:\s+([\s\S]*))?$/);if(!t)return{handled:!1};let[,o,n=""]=t,r=n.trim(),s=tY.current??await oz(),i=e=>(e.handled&&(e.error?oA({type:"error",message:e.error}):"openSessionStats"!==e.action&&oA({type:"success",message:e.message??"Command completed"})),e);try{switch(o){case"compact":{if(!s||e7)return i({handled:!0,error:"No active session to compact"});e9(!0),tt(null),tn(null);let e=await iS(s,{type:"compact",...r?{customInstructions:r}:{}});return tn(iH(e,"manual")),await oS(s,!0)&&oR(),i({handled:!0,message:"Compacted context"})}case"reload":if(!s)return i({handled:!0,error:"No active session to reload"});return await iS(s,{type:"reload"}),await Promise.all([oS(s,!1,!0),oT(s),oI(),o2()]),i({handled:!0,message:"Reloaded session resources"});case"name":if(!s)return i({handled:!0,error:"No active session to name"});if(!r)return i({handled:!0,error:"Usage: /name <name>"});return await iS(s,{type:"set_session_name",name:eq(r)}),await oS(s)&&oR(),i({handled:!0,message:`Session renamed to ${r}`});case"session":{if(!s)return i({handled:!0,error:"No active session"});let e=await iS(s,{type:"get_session_stats"});return e&&tm(e),p?.(),i({handled:!0,action:"openSessionStats"})}case"copy":{if(!s)return i({handled:!0,error:"No active session"});let e=await iS(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"===o&&e9(!1)}},[oA,oz,e7,o2,oS,oI,oT,oR,p]),o6=(0,r.useCallback)(async e=>{let t=!1;try{let o=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(o.ok){let e=await o.json(),n=e.state;if(e.running&&n&&(n.isStreaming||n.isPromptRunning||n.isBashRunning||n.isCompacting))return;t=!0}}catch{}if(t){tX.current=!1,O(!1),ts(null);return}o_(e)},[o_]),o8=(0,r.useCallback)(async(e,t)=>{let o=tY.current;if(!o)return;let n=t?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType}));tX.current=!0,O(!0),ts(e=>e??{kind:"waiting_model"});try{await iS(o,{type:"steer",message:e,...n?.length?{images:n}:{}})}catch(e){console.error("Failed to steer:",e),o6(o)}},[o6]),o5=(0,r.useCallback)(async(e,t,o)=>{let n=tY.current;if(!n)return;let r=o?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType}));tX.current=!0,O(!0),ts(e=>e??{kind:"waiting_model"});try{await iS(n,{type:"prompt",message:e,streamingBehavior:t,...r?.length?{images:r}:{}})}catch(e){console.error("Failed to queue prompt:",e),o6(n)}},[o6]),o3=(0,r.useCallback)(async(e,t)=>{let o=tY.current;if(!o)return;let n=t?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType}));tX.current=!0,O(!0),ts(e=>e??{kind:"waiting_model"});try{await iS(o,{type:"follow_up",message:e,...n?.length?{images:n}:{}})}catch(e){console.error("Failed to follow up:",e),o6(o)}},[o6]),o7=(0,r.useCallback)(async()=>{let e=tY.current;if(e)try{await iS(e,{type:"abort_compaction"})}catch(e){console.error("Failed to abort compaction:",e)}},[]),o9=(0,r.useCallback)(async()=>{let t=tY.current;if(t)try{let o=await iS(t,{type:"clear_queue"});tT({steering:[],followUp:[]});let n=[...o?.steering??[],...o?.followUp??[]];n.length>0&&e.chatInputRef?.current?.prependText(n.join("\n\n"))}catch(e){console.error("Failed to recall queued messages:",e),oA({type:"error",message:"Failed to recall queued messages"})}},[e.chatInputRef,oA,tT]);(0,r.useEffect)(()=>{0===tR.length&&tP(!1)},[tR.length]);let ne=(0,r.useCallback)(async(e,t,o=!1)=>{let n=tY.current;if(!n)return tR;try{let r=await iS(n,{type:"resolve_recovery",keep:e,discard:t,continueRun:o}),s=r?.remaining??[];return tI(s),o&&e.length>0&&(async()=>{try{let e=await fetch(`/api/agent/${encodeURIComponent(n)}`);if(!e.ok)return;let t=await e.json(),o=t.state;if(!t.running||!o||!o.isStreaming&&!o.isPromptRunning)return;tZ.current=!!o.isStreaming,tQ.current=!!o.isPromptRunning,tX.current=!0,O(!0),ts(iI(o)),E({type:"start"}),oE(n),!o.isStreaming&&o.isPromptRunning&&o_(n)}catch{}})(),s}catch(e){return console.error("Failed to resolve queued message recovery:",e),oA({type:"error",message:"Failed to resolve queued message recovery"}),tR}},[tR,oA,oE,o_,tI]),nt=(0,r.useCallback)(async()=>{let e=tY.current;if(!e)return null;try{return await iS(e,{type:"export_queue"})}catch(e){return console.error("Failed to export queue:",e),oA({type:"error",message:"Failed to export queue"}),null}},[oA]),no=(0,r.useCallback)(async e=>{let t=tY.current;if(!t)return null;try{let o=await iS(t,{type:"import_queue",entries:e});return o&&tT(iP(o)),o?.imported??0}catch(e){return console.error("Failed to import queue:",e),oA({type:"error",message:"Failed to import queue"}),null}},[oA,tT]),nn=(0,r.useCallback)(async e=>{let t=tY.current;if(!t)return null;try{let o=await iS(t,{type:"stage_recovery",entries:e});return o?.pendingRecovery&&tI(o.pendingRecovery),(o?.staged??0)>0&&tP(!0),o?.staged??0}catch(e){return console.error("Failed to stage imported queue:",e),oA({type:"error",message:"Failed to stage imported queue"}),null}},[oA,tI]),nr=(0,r.useCallback)(async(e,t,o)=>{let n=tY.current;if(!n)return!1;try{let r=await iS(n,{type:"move_queue",kind:e,fromIndex:t,toIndex:o});return r&&tT(iP(r)),!0}catch(e){return console.error("Failed to move queued message:",e),oA({type:"error",message:e instanceof Error?e.message:"Failed to move queued message"}),!1}},[oA,tT]),ns=(0,r.useCallback)(async(e,t)=>{let o=tY.current;if(!o)return null;try{let n=await iS(o,{type:"recall_queue_item",kind:e,index:t});return n&&(void 0!==n.steering||void 0!==n.followUp)&&tT(iP(n)),n?.entry?{text:n.entry.text,images:n.entry.images?.map(({data:e,mimeType:t})=>({data:e,mimeType:t}))}:null}catch(e){return console.error("Failed to recall queued message:",e),oA({type:"error",message:e instanceof Error?e.message:"Failed to recall queued message"}),null}},[oA,tT]),ni=(0,r.useCallback)(async(e,t,o,n)=>{let r=tY.current;if(!r)return!1;try{let s=await iS(r,{type:"requeue_at",kind:e,index:t,text:o,images:n?.map(({data:e,mimeType:t})=>({type:"image",data:e,mimeType:t}))});return s&&tT(iP(s)),!0}catch(e){return console.error("Failed to requeue message:",e),oA({type:"error",message:e instanceof Error?e.message:"Failed to requeue message"}),!1}},[oA,tT]),na=(0,r.useCallback)(async(e,t)=>{let o=tY.current;if(!o)return!1;try{let n=await iS(o,{type:"remove_queue_item",kind:e,index:t});return n&&tT(iP(n)),!0}catch(e){return console.error("Failed to remove queued message:",e),oA({type:"error",message:e instanceof Error?e.message:"Failed to remove queued message"}),!1}},[oA,tT]),nl=(0,r.useCallback)(async e=>{if(og.current="auto"===e?null:e,eJ(e),"auto"===e)return;let t=tY.current??await os.current;if(t)try{await iS(t,{type:"set_thinking_level",level:e})}catch(e){console.error("Failed to set thinking level:",e)}},[]),nd=(0,r.useCallback)(async e=>{let t=(0,iC.xG)(e);ok(e);let o=tY.current??await os.current;if(o)try{await iS(o,{type:"set_tools",toolNames:t})}catch(e){console.error("Failed to set tools:",e)}},[ok]),nc=(0,r.useRef)(0),np=(0,r.useCallback)(async e=>{let t=tY.current??await os.current,o=++nc.current;if(e){if(ep.current="plan"===ea?"default":ea,ec(!0),eu.current=!0,eR.current={sessionKey:"",signature:""},t)try{if(await iS(t,{type:"prompt",message:"/plan"}),nc.current!==o)return}catch(e){if(nc.current!==o)return;console.error("Failed to enter plan mode:",e)}}else if(ec(!1),eu.current=!1,eR.current={sessionKey:"",signature:""},t){try{if(await iS(t,{type:"prompt",message:"/plan exit"}),nc.current!==o)return}catch(e){if(nc.current!==o)return;console.error("Failed to exit plan mode:",e)}if(nc.current!==o)return;try{let e=ep.current;await iS(t,{type:"set_tools",toolNames:(0,iC.xG)(e)})}catch(e){console.error("Failed to restore tools after plan exit:",e)}}},[ea]),nu=(0,r.useCallback)(e=>{eg(e);let t=tY.current;if(!t){em.current=e;return}em.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)})},[]),nm=(0,r.useCallback)(e=>{if(nu({...ez.current,collaborationMode:eN(e)}),ew.current=eN(e),eR.current={sessionKey:"",signature:""},"goal"!==e){eT.current=null,eK.current=!1,eF(e=>"idle"===e.status?e:{...e,status:"idle",goalText:null});let e=tY.current;e&&iS(e,{type:"goal_stop"}).catch(()=>{})}},[nu]),nf=(0,r.useCallback)(async e=>{nu({...ez.current,tokenMode:e$(e)});let t=tY.current??await os.current;if(t)try{if("economy"!==e||eu.current){if("economy"!==e){let e=eu.current?iC.SC:(0,iC.xG)("plan"===ea?"default":ea);await iS(t,{type:"set_tools",toolNames:e})}}else await iS(t,{type:"set_tools",toolNames:[...eO]})}catch(e){console.error("Failed to apply token mode tools:",e)}},[nu,ea]),nx=(0,r.useCallback)(async e=>{nu({...ez.current,toolApprovalMode:eL(e)});let t=tY.current??await os.current;if(t)try{await iS(t,{type:"set_approval_mode",mode:eL(e)})}catch(e){console.error("Failed to apply approval mode:",e)}},[nu]),nk=(0,r.useCallback)(async e=>{nu({...ez.current,permissionRules:e});let t=tY.current??await os.current;if(t)try{await iS(t,{type:"set_approval_policy",policy:e})}catch(e){console.error("Failed to apply permission rules:",e)}},[nu]),nv=(0,r.useCallback)(async(e,t,o)=>{let n=tY.current;if(n)try{await iS(n,{type:"resolve_approval",id:e,approve:t,reason:o})}catch(e){console.error("Failed to resolve approval:",e)}finally{eM(t=>t.filter(t=>t.id!==e))}},[]),ny=(0,r.useCallback)(e=>{eT.current=e},[]),nb=(0,r.useCallback)(e=>{let t=e.trim();if(!t)return;eT.current=t,eF(e=>({...e,status:"running",goalText:t,turnsUsed:0,noProgressTurns:0,tokensUsed:0,startedAt:Date.now()}));let o=tY.current;o&&iS(o,{type:"goal_start",goalText:t}).catch(()=>{})},[]),nw=(0,r.useCallback)(()=>{if("running"!==eV.current.status)return;eF(e=>({...e,status:"paused"}));let e=tY.current;e&&iS(e,{type:"goal_pause"}).catch(()=>{})},[]),nj=(0,r.useCallback)(()=>{let e=eV.current;if("paused"!==e.status&&"blocked"!==e.status)return;eF(e=>({...e,status:"running"}));let t=tY.current;t&&iS(t,{type:"goal_resume"}).catch(()=>{})},[]),nS=(0,r.useCallback)(()=>{eK.current=!1,eT.current=null,eF(e=>({...e,status:"idle",goalText:null,turnsUsed:0,noProgressTurns:0}));let e=tY.current;e&&iS(e,{type:"goal_stop"}).catch(()=>{})},[]),nC=(0,r.useCallback)(e=>{let t=e.trim();if(!t)return;eF(e=>({...e,goalText:t}));let o=tY.current;o&&iS(o,{type:"goal_edit",goalText:t}).catch(()=>{})},[]),nT=tE.map(e=>`${e.id}:${e.status}:${e.completedAt??""}`).join("|"),nR=(0,r.useRef)(tE);nR.current=tE,(0,r.useEffect)(()=>{u?.(nR.current)},[nT,u]),(0,r.useEffect)(()=>()=>{u?.([])},[u]),(0,r.useEffect)(()=>{tA(()=>[])},[t?.id,n??t?.cwd]);let nz=(0,r.useCallback)(()=>{let e=or.current,t=t3.current;if(!e||!t)return;let o=t.getBoundingClientRect().top-e.getBoundingClientRect().top+e.scrollTop,n=Math.max(0,e.scrollHeight-e.clientHeight),r=Math.min(Math.max(0,o-16),n);oe.current=r>=n-150,oo.current=Date.now()+700,e.scrollTo({top:r,behavior:"smooth"})},[]),nI=(0,r.useCallback)(e=>{if(e instanceof KeyboardEvent){if(!iD.has(e.key)||e.target instanceof Element&&e.target.closest("input, textarea, [contenteditable='true']"))return}else if(e instanceof PointerEvent){let t=or.current;if(t&&e.target instanceof Element&&!t.contains(e.target))return}ot.current=Date.now()+1200},[]),nM=(0,r.useCallback)(()=>{let e=or.current;if(e){let{scrollTop:t,clientHeight:o,scrollHeight:n}=e;oe.current=t+o>=n-150}if(Date.now()<ot.current){t9.current=!1;return}Date.now()<oo.current||(t9.current=!1)},[]);(0,r.useEffect)(()=>{if(t1.current=!0,t){tY.current=t.id;let e=eS.current,o=eC.current;("auto"!==e||o.allow.length||o.ask.length||o.deny.length)&&(iS(t.id,{type:"set_approval_mode",mode:e}).catch(()=>{}),iS(t.id,{type:"set_approval_policy",policy:o}).catch(()=>{}));let n=e=>{!t6.current&&(t6.current=!0,e.isBashRunning&&(t4.current=!0,B(!0)),oT(t.id),(e.isStreaming||e.isPromptRunning)&&(tZ.current=!!e.isStreaming,tQ.current=!!e.isPromptRunning,tX.current=!0,O(!0),ts(iI(e)),E({type:"start"}),oE(t.id),!e.isStreaming&&e.isPromptRunning&&o_(t.id)))};(async()=>{try{let e,o=new AbortController,r=setTimeout(()=>o.abort(),2e4);try{e=await fetch(`/api/sessions/${encodeURIComponent(t.id)}/state`,{signal:o.signal})}finally{clearTimeout(r)}if(!e.ok)throw Error(`HTTP ${e.status}`);let s=await e.json();if(!t1.current||tY.current!==t.id)return;s.running&&s.state&&n(s.state)}catch{}})(),oS(t.id,!0,!0).then(e=>{e?.running&&e.state&&n(e.state),e?.state&&(void 0!==e.state.isCompacting&&e9(e.state.isCompacting),void 0!==e.state.contextUsage&&eQ(e.state.contextUsage??null),void 0!==e.state.systemPrompt&&e1(e.state.systemPrompt??null),void 0!==e.state.thinkingLevel&&eJ(e.state.thinkingLevel??"auto"),void 0!==e.state.extensionStatuses&&tb(e.state.extensionStatuses??[]),void 0!==e.state.extensionWidgets&&tj(e.state.extensionWidgets??[]),void 0!==e.state.queuedMessages&&tT(iP(e.state.queuedMessages)),void 0!==e.state.pendingRecovery&&tI(e.state.pendingRecovery??[])),e?.running||(async()=>{for(let e=0;e<5;e++){if(e>0&&await new Promise(e=>setTimeout(e,2e3)),!t1.current||tY.current!==t.id||tX.current)return;try{let e=await fetch(`/api/agent/${encodeURIComponent(t.id)}`);if(!e.ok)continue;let o=await e.json();if(!t1.current||tY.current!==t.id)return;if(o?.running&&o.state)return void n(o.state)}catch{}}})()})}return()=>{t1.current=!1,of(),tU(),oM(),oP()}},[of]),(0,r.useEffect)(()=>{c?.(e0)},[e0,c]),(0,r.useEffect)(()=>{d&&d(m?.tree??[],b,oQ)},[m?.tree,b,oQ,d]),(0,r.useEffect)(()=>(window.addEventListener("keydown",nI),window.addEventListener("pointerdown",nI,{passive:!0}),()=>{window.removeEventListener("keydown",nI),window.removeEventListener("pointerdown",nI)}),[nI]),(0,r.useEffect)(()=>{let e=or.current;if(e)return e.addEventListener("wheel",nI,{passive:!0}),e.addEventListener("touchstart",nI,{passive:!0}),e.addEventListener("scroll",nM,{passive:!0}),()=>{e.removeEventListener("wheel",nI),e.removeEventListener("touchstart",nI),e.removeEventListener("scroll",nM)}},[j.length,x,nM,nI]),(0,r.useEffect)(()=>{j.length>0&&(t7.current?(t5.current=!0,t3.current&&(t7.current=!1,nz())):x||!t5.current?(x||(t5.current=!0),oV("instant")):!tX.current&&(t9.current||oe.current)&&oV("smooth"))},[j.length,x,L,oV,nz]);let nP=(0,r.useRef)(null),nE=t?.id??null;(0,r.useEffect)(()=>{let e;if(x){nP.current=null;return}if(0===j.length||nP.current===nE)return;nP.current=nE;let t=!1,o=!1,n=-1,r=0,s=Date.now(),i=()=>{if(t||o)return;let a=or.current;if(a){if(Date.now()<ot.current){let{scrollTop:e,clientHeight:t,scrollHeight:n}=a;if(e+t<n-150){o=!0;return}}if(oV("instant"),a.scrollHeight===n){if((r+=1)>=4||Date.now()-s>=3e4)return}else if(n=a.scrollHeight,r=0,Date.now()-s>=3e4)return;e=window.setTimeout(i,r>0?500:250)}};return e=window.setTimeout(i,250),()=>{t=!0,void 0!==e&&window.clearTimeout(e)}},[x,oV,nE]),(0,r.useEffect)(()=>{let e=new AbortController;return o2(e.signal).catch(e=>{if(e instanceof DOMException&&"AbortError"===e.name)return}),()=>e.abort()},[o2,l]),(0,r.useEffect)(()=>{if(!et)return;let e=()=>{"visible"===document.visibilityState&&o2()};return document.addEventListener("visibilitychange",e),window.addEventListener("online",e),()=>{document.removeEventListener("visibilitychange",e),window.removeEventListener("online",e)}},[et,o2]),(0,r.useEffect)(()=>{if(!te)return;let e=setTimeout(()=>tt(null),3e3);return()=>clearTimeout(e)},[te]),(0,r.useEffect)(()=>{if(!to)return;let e=setTimeout(()=>tn(null),6e3);return()=>clearTimeout(e)},[to]),(0,r.useEffect)(()=>{if(0===tu.visible.length)return;let e=tu.visible.find(e=>e.exiting);if(e){let t=setTimeout(()=>{th({type:"remove",id:e.id})},180);return()=>clearTimeout(t)}if(!tu.visible[0])return;let t=setTimeout(()=>{th({type:"mark_oldest_exiting"})},5e3);return()=>clearTimeout(t)},[tu.visible]),(0,r.useEffect)(()=>{tm(null)},[j.length,eZ?.tokens,eZ?.percent,eZ?.contextWindow]);let nF=m?.tree??[];return{data:m,loading:x,error:v,activeLeafId:b,messages:j,entryIds:C,historyCursor:R,hasEarlierMessages:I,streamState:P,agentRunning:L,bashRunning:H,pendingBash:U,modelNames:q,modelList:K,modelThinkingLevels:J,modelThinkingLevelMaps:X,modelScopeWarnings:Q,modelsError:et,newSessionModel:en,toolPreset:ea,thinkingLevel:eG,retryInfo:eY,contextUsage:eZ,systemPrompt:e0,forkingEntryId:e2,isCompacting:e7,compactError:te,compactResult:to,currentModel:ob,displayModel:ow,sessionStats:oj,tokenRate:F,planMode:ed,subagents:tE,collaborationMode:ek,tokenMode:ev,toolApprovalMode:ey,permissionRules:eb,modeSettings:eh,approvalRequests:eI,handleCollaborationModeChange:nm,handleTokenModeChange:nf,handleToolApprovalModeChange:nx,handlePermissionRulesChange:nk,resolveApproval:nv,setActiveGoalText:ny,goalState:eE,handleGoalStart:nb,handleGoalPause:nw,handleGoalResume:nj,handleGoalStop:nS,handleGoalEdit:nC,slashCommands:tl,slashCommandsLoading:tc,queuedMessages:tS,pendingRecovery:tR,recoveryIsImport:tM,notices:tu.visible,extensionDialog:tf,extensionCustomUi:tk,extensionStatuses:ty,extensionWidgets:tw,respondToExtensionUi:oD,sendExtensionCustomInput:oW,agentPhase:tr,isNew:h,promptAnchorActive:ti,branchTree:nF,sessionIdRef:tY,eventSourceRef:t_,messagesEndRef:on,scrollContainerRef:or,lastUserMsgRef:t3,pendingScrollToUserRef:t7,initialScrollDoneRef:t5,scrollUserMsgToTop:nz,handleSend:oG,executeBash:oJ,handleAbort:oY,handleFork:oX,handleNavigate:oZ,handleModelChange:o0,handleCompact:o1,handleSteer:o8,handleFollowUp:o3,handlePromptWithStreamingBehavior:o5,handleAbortCompaction:o7,handleRecallQueue:o9,resolveRecovery:ne,exportQueueData:nt,importQueueData:no,stageQueueImport:nn,moveQueuedMessage:nr,recallQueuedMessage:ns,requeueAt:ni,removeQueuedMessage:na,handleBuiltinSlashCommand:o4,handleToolPresetChange:nd,handleThinkingLevelChange:nl,handlePlanModeChange:np,loadTools:oT,loadSlashCommands:oI,reloadModels:o2,setActiveLeafId:w,setData:f,setMessages:S,loadContext:oC,dispatch:E,setAgentRunning:O,setForkingEntryId:e4,handleLeafChange:oQ,handleAgentEventRef:t8}}({session:e,newSessionCwd:t,onAgentEnd:A,onSessionCreated:i,onSessionForked:a,modelsRefreshKey:d,chatInputRef:c,onBranchDataChange:p,onSystemPromptChange:u,onSessionStatsPanelOpen:m,onSubagentsChange:g}),[tF,tD]=(0,r.useState)(!1);(0,r.useEffect)(()=>{0===ef.length&&tD(!1)},[ef.length]);let{balance:tW,refresh:tA,refreshSoon:tN}=function(){let[e,t]=(0,r.useState)(null),[o,n]=(0,r.useState)(!1),s=(0,r.useRef)(null),i=(0,r.useRef)(null),a=(0,r.useRef)(!0);(0,r.useEffect)(()=>(a.current=!0,()=>{a.current=!1,i.current&&clearTimeout(i.current),s.current?.abort()}),[]);let l=(0,r.useRef)(null),d=(0,r.useCallback)(async()=>{s.current?.abort();let e=new AbortController;s.current=e;try{let o=await fetch("/api/deepseek/balance",{signal:e.signal,cache:"no-store"}),r=await o.json();if(!a.current)return;if(r?.available&&null!=r.totalBalance){let e=l.current;(null===e||e.available!==r.available||e.reason!==r.reason||e.currency!==r.currency||e.totalBalance!==r.totalBalance||e.grantedBalance!==r.grantedBalance||e.toppedUpBalance!==r.toppedUpBalance)&&(l.current=r,t(r)),n(!1)}else null===l.current&&n(!0)}catch{if(!a.current)return;null===l.current&&n(!0)}},[]),c=(0,r.useCallback)(()=>{i.current&&clearTimeout(i.current),i.current=setTimeout(()=>{i.current=null,d()},2e3)},[d]);return{balance:e,failed:o,refresh:d,refreshSoon:c}}(),t$=ec?.provider==="deepseek",tL=(0,r.useRef)(null);(0,r.useEffect)(()=>{t$&&tA()},[t$,tA]),(0,r.useEffect)(()=>{if(t$)for(let e=U.length-1;e>=0;e--){let t=U[e];if("assistant"!==t.role||!t.usage)continue;let o=`${e}:${_[e]??""}`;o!==tL.current&&(tL.current=o,tN());break}},[U,_,t$,tN]);let tO=(0,r.useMemo)(()=>{let e=U.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:nh(e.model)?ng(e.model,t):0,costUSD:nh(e.model)?0:t.cost?.total??0}},[U]),[tH,tB]=(0,r.useState)(!1),[tU,t_]=(0,r.useState)(null),tq=(0,r.useRef)(!1);(0,r.useEffect)(()=>{if(!tl){tq.current=!1;return}if(V){tq.current=!0;return}tq.current&&(tq.current=!1,t_(function(e){for(let t=e.length-1;t>=0;t--){let o=e[t];if("assistant"!==o.role)continue;let n=o.content;if("string"==typeof n&&n.trim())return n;if(Array.isArray(n)){let e=n.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 o=e[t];if("toolResult"!==o.role)continue;let n=o.content,r="string"==typeof n?n:Array.isArray(n)?n.map(e=>e.text??"").join("\n"):"";if(!r)continue;let s=r.match(/\*\*Proposed Plan\*\*\s*\n+([\s\S]+)/i);if(s?.[1]?.trim())return s[1].trim()}return null}(U)??null),tB(!0))},[V,tl,U]);let tV=(0,r.useCallback)(()=>{tB(!1);let e=tK.current;"plan"===tc&&tg("normal"),td(!1).then(()=>{e&&eJ(P("tasks.planReviewExecutePrompt",{plan:e}))})},[td,eJ,P,tc,tg]),tK=(0,r.useRef)(null);(0,r.useEffect)(()=>{tK.current=tU},[tU]);let tG=(0,r.useCallback)(e=>{tB(!1),e2(e)},[e2]),tJ=(0,r.useCallback)(()=>{tB(!1),"plan"===tc&&tg("normal"),td(!1)},[td,tc,tg]);(0,r.useEffect)(()=>{ev&&W.current!==ev.id&&(W.current=ev.id,D.current&&E.current())},[ev]),(0,r.useEffect)(()=>(l=V||K?eX:null,()=>void(l=null)),[V,K,eX]);let[tY,tX]=(0,r.useState)(!1),[tZ,tQ]=(0,r.useState)(!1),[t0,t1]=(0,r.useState)(!1),t2=(0,r.useCallback)(()=>{let e=eE.current;if(!e)return;let t=e.scrollHeight-e.scrollTop-e.clientHeight;tX(e.scrollTop>1),tQ(t>1),t1(t>240)},[eE]),t4=(0,r.useCallback)(()=>{window.requestAnimationFrame(()=>{let e=eE.current,t=eP.current;if(!e||!t)return;let o=Math.max(88,c?.current?.measureHeight?.()??0),n=()=>{if(!e||!t)return;let n=Math.max(0,t.getBoundingClientRect().top-e.getBoundingClientRect().top+e.scrollTop-96-e.clientHeight+o);e.scrollTo({top:n,behavior:"auto"})};n(),t2(),window.setTimeout(n,200)})},[eP,eE,t2,c]);(0,r.useEffect)(()=>{let e=eE.current;if(!e)return;let t=new ResizeObserver(t2);return t.observe(e),e.firstElementChild&&t.observe(e.firstElementChild),e.addEventListener("scroll",t2,{passive:!0}),t2(),()=>{e.removeEventListener("scroll",t2),t.disconnect()}},[U.length,eE,t2]);let t6=(0,r.useRef)(!1);(0,r.useEffect)(()=>{let t=eE.current;if(!t)return;let o=()=>{if(t6.current||!tP||!tM||t.scrollTop>8)return;let o=e?.id;if(!o)return;t6.current=!0;let n=t.scrollHeight-t.scrollTop;tE(o,ez,tM).finally(()=>{t6.current=!1,requestAnimationFrame(()=>{let e=t.scrollHeight-n;Math.abs(t.scrollTop-e)>1&&t.scrollTo({top:e,behavior:"auto"})})})};return t.addEventListener("scroll",o,{passive:!0}),()=>t.removeEventListener("scroll",o)},[eE,tM,tP,tE,e?.id,ez]);let t8=(0,r.useRef)(null),t5=(0,r.useRef)([]),t3=(0,r.useMemo)(()=>({getOffsetForIndex:e=>t8.current?.getOffsetForIndex(e)?.[0]??0,sizeFor:e=>{let t=t8.current;if(!t)return 0;let o=t.measurementsCache[e];return o?.size??t.options.estimateSize?.(e)??0},totalHeight:()=>t8.current?.getTotalSize()??0,refToItemIndex:e=>t5.current[e],itemCount:t5.current.length}),[]),t7=ep?[ep.sessionId,ep.sessionFile??"",ep.sessionName??"",ep.userMessages,ep.assistantMessages,ep.toolCalls,ep.toolResults,ep.totalMessages,ep.tokens.input,ep.tokens.output,ep.tokens.cacheRead,ep.tokens.cacheWrite,ep.tokens.total,ep.cost??0,ep.totalActiveMs??0].join("|"):null,t9=(0,r.useRef)(ep);t9.current=ep,(0,r.useEffect)(()=>{h?.(t9.current)},[t7,h]),(0,r.useEffect)(()=>()=>{h?.(null)},[h]);let oe=es?`${es.percent??"null"}|${es.contextWindow}|${es.tokens??"null"}`:null,ot=(0,r.useRef)(es);ot.current=es,(0,r.useEffect)(()=>{f?.(ot.current)},[oe,f]),(0,r.useEffect)(()=>()=>{f?.(null)},[f]);let{isDragOver:oo,handleDragEnter:on,handleDragOver:or,handleDragLeave:os,handleDrop:oi}=function(e){let[t,o]=(0,r.useState)(!1),n=(0,r.useRef)(0),s=(0,r.useCallback)(e=>{e.dataTransfer.files.length&&(e.preventDefault(),n.current+=1,o(!0))},[]),i=(0,r.useCallback)(e=>{e.dataTransfer.files.length&&e.preventDefault()},[]);return{isDragOver:t,handleDragEnter:s,handleDragOver:i,handleDragLeave:(0,r.useCallback)(()=>{n.current-=1,n.current<=0&&(n.current=0,o(!1))},[]),handleDrop:(0,r.useCallback)(t=>{t.preventDefault(),n.current=0,o(!1),e(Array.from(t.dataTransfer.files),t.dataTransfer)},[e])}}((0,r.useCallback)((e,t)=>{if(V){let t=e.filter(e=>e.type.startsWith("image/"));t.length&&c?.current?.addImages(t);return}c?.current?.addFiles(e,t)},[V,c])),oa=U.filter(e=>"user"===e.role||"assistant"===e.role),ol=(0,r.useMemo)(()=>{let e=new Set,t=[];for(let n=U.length-1;n>=0&&t.length<50;n-=1){var o;let r="user"!==(o=U[n]).role?null:("string"==typeof o.content?o.content:o.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n")).trim()||null;!r||e.has(r)||(e.add(r),t.push(r))}return t},[U]),od=(S=oa.length,(C=(0,r.useRef)([])).current=Array(S).fill(null).map((e,t)=>C.current[t]??null),C),oc=eT&&0===U.length&&!q.isStreaming&&!V,op=e?.cwd??t??void 0,ou=(0,r.useMemo)(()=>(function(e,t,o){let n=new Map;for(let t of e)"toolResult"===t.role&&n.set(t.toolCallId,t);let r=-1;for(let t=e.length-1;t>=0;t--)if("user"===e[t].role){r=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 r=0;r<e.length;){let s,i=e[r],l="custom"===i.role&&"compaction"===i.customType;if("user"!==i.role&&!l){a.push({kind:"single",idx:r}),r+=1;continue}let d=r,c=d+1;for(;c<e.length&&"user"!==e[c].role;)c+=1;let p=function(e,t,o){for(let r=o-1;r>t;r--){var n;if("assistant"===(n=e[r]).role&&tp(n).answerBlocks.some(e=>"image"===e.type||"text"===e.type&&e.text.trim().length>0))return r}for(let n=o-1;n>t;n--)if(e[n]?.role==="assistant")return n;return -1}(e,d,c);if(-1===p){a.push({kind:"turn",userIdx:d,endIdx:c,startsCompactionTurn:l,finalAssistantIdx:p,visibleProcessIndices:[],processBlocks:[],finalAnswerMessage:null,writtenFiles:void 0}),r=c;continue}let u=[];for(let e=d+1;e<p;e++)u.push(e);let h=u.filter(t=>tb(e[t])),g=e[p],m=tp(g),f=m.processBlocks.length>0?tw(g,m.processBlocks,{omitUsage:!0}):null,x=m.answerBlocks.length>0?tw(g,m.answerBlocks):null,k=tf(e,t,h,n);if(f&&(k=k.concat(tm(g,{messageIndex:p,entryId:t[p],toolResults:n}).processBlocks)),x){let t=[];for(let o=d+1;o<=p;o++){let n=e[o];if(n?.role==="assistant")for(let e of n.content??[])t.push(e)}s=function(e,t,o){let n=new Set,r=[];for(let s of e){if("toolCall"!==s.type||!function(e){let t,o;return"write"===(t=e.toLowerCase())||t.startsWith("write_")||t.endsWith(".write")||t.endsWith("_write")||"edit"===(o=e.toLowerCase())||o.startsWith("edit_")||o.endsWith(".edit")||o.endsWith("_edit")||o.includes("str_replace")||o.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 o;if(!e)return null;let n=/^[a-zA-Z]:[\\/]/.test(e)||e.startsWith("\\\\")||void 0!==t&&(/^[a-zA-Z]:[\\/]/.test(t)||t.startsWith("\\\\")),r=e=>n?e.replace(/\\/g,"/"):e,s=r(e),i=t?r(t).replace(/\/+$/,""):void 0,a=/^[a-zA-Z]:\//.test(s),l=s.startsWith("//");if(a||l)o=s;else if(s.startsWith("/")){let e=i?.match(/^([a-zA-Z]:)(?:\/|$)/)?.[1]??i?.match(/^(\/\/[^/]+\/[^/]+)(?:\/|$)/)?.[1];o=e?`${e}${s}`:s}else{if(!i)return null;o=`${i}/${s}`}return tv(o)}(i,o);a&&(n.has(a)||(n.add(a),r.push({filePath:a})))}return r}(t,n,o)}a.push({kind:"turn",userIdx:d,endIdx:c,startsCompactionTurn:l,finalAssistantIdx:p,visibleProcessIndices:h,processBlocks:k,finalAnswerMessage:x,writtenFiles:s}),r=c}return{toolResultsMap:n,lastUserIdx:r,visibleRefIndexByMessage:s,items:a}})(U,_,op),[U,_,op]),oh=ec?X[`${ec.provider}:${ec.modelId}`]??null:null,og=ec?Z[`${ec.provider}:${ec.modelId}`]??null:null,om=(0,r.useCallback)(()=>{et()},[et]),of=(0,r.useCallback)(e=>{td(e),e&&"plan"!==tc?tg("plan"):e||"plan"!==tc||tg("normal")},[td,tg,tc]),ox=(0,r.useCallback)(e=>{tg(e),"plan"!==e||tl?"plan"!==e&&tl&&td(!1):td(!0)},[tg,td,tl]),ok=(0,n.jsx)(s4,{ref:c,onSend:eJ,onBash:eY,tasksBoardEnabled:b,onAbort:eX,onSteer:V?e2:void 0,onFollowUp:V?e4:void 0,onPromptWithStreamingBehavior:V?e6:void 0,isStreaming:V,model:ec,modelNames:J,modelList:Y,modelScopeWarnings:Q,modelsError:ee,onRetryModels:om,onModelChange:e0,compactResult:ed,toolPreset:eo,onToolPresetChange:e||eT?ts:void 0,planMode:tl,onPlanModeChange:of,collaborationMode:tc,tokenMode:tu,toolApprovalMode:th,onCollaborationModeChange:ox,onTokenModeChange:tx,onToolApprovalModeChange:tk,goalState:tS,onGoalStart:tC,onGoalPause:tT,onGoalResume:tR,onGoalStop:tz,thinkingLevel:en,onThinkingLevelChange:e||eT?ti:void 0,availableThinkingLevels:oh,thinkingLevelMap:og,retryInfo:er,queuedMessages:em,inputHistory:ol,onRecallQueue:e5,onMoveQueue:te,onRecallOne:tt,onRequeueAt:to,onRemoveQueueItem:tn,slashCommands:eh,slashCommandsLoading:eg,onLoadSlashCommands:ta,onBuiltinCommand:tr,onAudioUnlock:I,draftKey:e?.id??(t?`new:${t}`:void 0),cwd:e?.cwd??t}),ov=ew.filter(e=>"belowEditor"!==e.placement),oy=ew.filter(e=>"belowEditor"===e.placement),ob=ea?P("desktop.compacting"):function(e,t){if(e?.kind==="running_tools"){let o=e.tools.map(e=>e.name);return 0===o.length?t("desktop.runningTool"):t("desktop.runningTools",{tools:o.length<=3?o.join(", "):`${o.slice(0,2).join(", ")} (+${o.length-2})`})}return e?.kind==="waiting_model"?t("desktop.waitingForModel"):e?.kind==="running_command"?t("desktop.runningCommand"):null}(eC,P);return H?(0,n.jsx)("div",{className:"flex h-full items-center justify-center text-text-muted",children:P("desktop.loadingSession")}):B?(0,n.jsx)("div",{className:"flex h-full items-center justify-center text-red-400",children:B}):(0,n.jsxs)("div",{className:"relative flex h-full min-w-0 flex-col overflow-hidden",onDragEnter:on,onDragOver:or,onDragLeave:os,onDrop:oi,children:[oo&&(0,n.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,n.jsx)("div",{className:"pointer-events-none absolute inset-0 flex items-center justify-center",children:[0,.8,1.6].map(e=>(0,n.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,n.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,n.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,n.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,n.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,n.jsxs)("g",{stroke:"rgba(37,99,235,0.45)",strokeWidth:"1.4",strokeLinecap:"round",children:[(0,n.jsx)("line",{x1:"96",y1:"46",x2:"96",y2:"43"}),(0,n.jsx)("line",{x1:"96",y1:"70",x2:"96",y2:"73"}),(0,n.jsx)("line",{x1:"84",y1:"58",x2:"81",y2:"58"}),(0,n.jsx)("line",{x1:"108",y1:"58",x2:"111",y2:"58"}),(0,n.jsx)("line",{x1:"87.5",y1:"49.5",x2:"85.4",y2:"47.4"}),(0,n.jsx)("line",{x1:"104.5",y1:"66.5",x2:"106.6",y2:"68.6"}),(0,n.jsx)("line",{x1:"104.5",y1:"49.5",x2:"106.6",y2:"47.4"}),(0,n.jsx)("line",{x1:"87.5",y1:"66.5",x2:"85.4",y2:"68.6"})]})]})]}),ev&&(0,n.jsx)(iG,{request:ev,onRespond:ej}),ey&&(0,n.jsx)(iJ,{request:ey,onInput:eS}),!eT&&ef.length>0&&!tF&&(0,n.jsx)(s5,{items:ef,sessionId:e?.id,onResolve:e3,onExport:e7,onStageImport:e9,onDismiss:()=>tD(!0),mode:ex?"import":"recovery"}),ty.length>0&&(0,n.jsx)(nY,{request:ty[0]??null,queuedCount:Math.max(0,ty.length-1),busy:!1,onResolve:(e,t)=>{let o=ty[0];o&&tj(o.id,e,t)}}),oc?(0,n.jsx)("div",{className:"flex flex-1 flex-col items-center justify-center overflow-y-auto",children:(0,n.jsxs)("div",{className:"w-full max-w-[820px]",children:[(0,n.jsx)("div",{style:{display:"flex",justifyContent:"center",marginBottom:28},children:(0,n.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,n.jsx)("title",{children:"Pi"}),(0,n.jsx)("path",{clipRule:"evenodd",d:"M1 1h16.5v11H12v5.5H6.5V23H1V1zm5.5 5.5V12H12V6.5H6.5z"}),(0,n.jsx)("path",{d:"M17.5 12H23v11h-5.5V12z"})]})}),M&&(0,n.jsxs)("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",gap:10,marginBottom:18,marginTop:-14},children:[(0,n.jsxs)("span",{style:{fontSize:11,color:"var(--text-muted)",fontFamily:"var(--font-mono)"},children:["web ",(0,n.jsxs)("span",{style:{color:"var(--text)"},children:["v","0.14.6"]})]}),(0,n.jsxs)("span",{style:{fontSize:11,color:"var(--text-muted)",fontFamily:"var(--font-mono)"},children:["pi ",(0,n.jsxs)("span",{style:{color:"var(--text)"},children:["v","0.84.3"]})]})]}),(0,n.jsx)("div",{style:{padding:"0 34px 6px 7px",paddingRight:M?16:34},children:(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12},children:[(0,n.jsx)("div",{ref:k,style:{display:"flex",alignItems:"center",minWidth:0,flex:1,minHeight:48}}),(0,n.jsxs)("div",{style:{display:M?"none":"flex",flexDirection:"column",alignItems:"flex-end",gap:2,flexShrink:0},children:[(0,n.jsxs)("span",{style:{fontSize:11,color:"var(--text-muted)",fontFamily:"var(--font-mono)"},children:["web ",(0,n.jsxs)("span",{style:{color:"var(--text)"},children:["v","0.14.6"]})]}),(0,n.jsxs)("span",{style:{fontSize:11,color:"var(--text-muted)",fontFamily:"var(--font-mono)"},children:["pi ",(0,n.jsxs)("span",{style:{color:"var(--text)"},children:["v","0.84.3"]})]})]})]})}),(0,n.jsx)("div",{style:{padding:"0 16px",paddingRight:M?16:34},children:(0,n.jsx)(iK,{notices:ek,align:"right"})}),"goal"===tc&&(0,n.jsx)(nG,{goalState:tS,onPause:tT,onResume:tR,onStop:tz,onEdit:tI}),ok,(0,n.jsx)("div",{style:{padding:"0 16px 6px",paddingRight:M?16:34,marginTop:-15},children:(0,n.jsx)(iu,{onViewFullHistory:v,cwd:op,systemPrompt:y,sessionStats:ep,contextUsage:es,hasSession:!!e,showChat:!0,showSoundLabel:!0,soundEnabled:T,onSoundToggle:R,onCompact:e?e1:void 0,onAbortCompaction:e8,isCompacting:ea,compactError:el,isDeepSeekOfficial:t$,deepseekBalance:tW,lastTurnUsage:tO})})]})}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("div",{className:"relative flex flex-1 overflow-hidden z-0",children:[(0,n.jsx)("div",{style:{position:"absolute",top:12,left:0,right:18*!M,zIndex:40,padding:"0 16px",pointerEvents:"none"},children:(0,n.jsx)("div",{style:{maxWidth:820,margin:"0 auto"},children:(0,n.jsx)(iK,{notices:ek,floating:!0,align:"right"})})}),(0,n.jsxs)("div",{className:"relative flex-1 min-h-0 min-w-0",children:[(0,n.jsx)("div",{ref:eE,className:"h-full min-w-0 overflow-x-hidden overflow-y-auto pt-4 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden",children:(0,n.jsx)("div",{style:{minWidth:0,padding:"0 16px"},children:(0,n.jsxs)("div",{style:{width:"100%",minWidth:0,maxWidth:820,margin:"0 auto"},children:[(0,n.jsx)(iq,{statuses:eb}),(0,n.jsx)(iV,{widgets:ov}),(()=>{let{toolResultsMap:t,lastUserIdx:o,visibleRefIndexByMessage:r,items:s}=ou,i=(s,i={})=>{let a=i.messageOverride??U[s],l="user"===a.role&&s>0&&"assistant"===U[s-1].role?_[s-1]:void 0,d="user"===a.role||"assistant"===a.role,c=r.get(s),p=i.keyPrefix??"message",u=!1;if("assistant"===a.role){u=!0;for(let e=s+1;e<U.length;e++){let t=U[e].role;if("user"===t)break;if("assistant"===t){u=!1;break}}u&&q.isStreaming&&s===U.length-1&&(u=!1)}void 0!==i.showTimestamp&&(u=i.showTimestamp);let h=(0,n.jsx)(ny,{message:a,toolResults:t,modelNames:J,cwd:op,onOpenFile:x,entryId:_[s],onFork:V||eT||0===s&&"user"===a.role?void 0:eZ,forking:ei===_[s],onNavigate:V?void 0:eQ,prevAssistantEntryId:V?void 0:l,onEditContent:N,onQuoteReply:L,onCreateTask:O,showTimestamp:u,prevTimestamp:s>0?U[s-1].timestamp:void 0,sessionId:e?.id??eM.current??void 0,writtenFiles:i.writtenFiles,subagents:w,onOpenSubagent:j},`${p}-view-${s}`);return d&&!1!==i.attachRef&&void 0!==c?(0,n.jsx)("div",{ref:e=>{od.current[c]=e,s===o&&(eF.current=e,e&&eV.current&&(eV.current=!1,eK.current=!0,eG()))},children:h},`${p}-${s}`):h},a=[],l=[],d=(e,t)=>{a.push(e),l.push(t)};for(let a of s){if("single"===a.kind){d(i(a.idx),r.get(a.idx));continue}let{userIdx:s,endIdx:l,startsCompactionTurn:c,finalAssistantIdx:p}=a;if((V||q.isStreaming)&&l===U.length&&(s===o||c)){d(i(s),r.get(s));let o=q.streamingMessage?.role==="assistant",a=[],c=!o&&p>=0?p:l;for(let e=s+1;e<c;e++)tb(U[e])&&a.push(e);let u=tf(U,_,a,t),h=null;if(!o&&p>=0){let e=U[p],o=tp(e,{isStreaming:!0}),n=tm(e,{messageIndex:p,entryId:_[p],toolResults:t,isStreaming:!0});u=u.concat(n.processBlocks),o.answerBlocks.length>0&&(h=tw(e,o.answerBlocks,{omitUsage:!0}))}if(o){let e=q.streamingMessage,o=tp(e,{isStreaming:!0}),n=tm(e,{messageIndex:U.length,toolResults:t,isStreaming:!0});u=u.concat(n.processBlocks),o.answerBlocks.length>0&&(h=tw(e,o.answerBlocks,{omitUsage:!0}))}if(u.length>0){let t=a.map(e=>r.get(e)).find(e=>"number"==typeof e);d((0,n.jsx)("div",{ref:void 0===t?void 0:e=>{od.current[t]=e},children:(0,n.jsx)(rF,{blocks:u,isStreaming:V||q.isStreaming,cwd:op,onOpenFile:x,sessionId:e?.id??eM.current??void 0,tokenRate:eu})},`live-process-group-${s}`),t)}h&&d((0,n.jsx)(ny,{message:h,isStreaming:!0,modelNames:J,cwd:op,onOpenFile:x,onQuoteReply:L},`live-answer-${s}`),p>=0?r.get(p):void 0);continue}if(-1===p){for(let e=s;e<l;e++)d(i(e),r.get(e));continue}d(i(s),r.get(s));let{processBlocks:u,finalAnswerMessage:h,writtenFiles:g,visibleProcessIndices:m}=a;if(u.length>0){let t=m.map(e=>r.get(e)).find(e=>"number"==typeof e)??(h?void 0:r.get(p));d((0,n.jsx)("div",{ref:void 0===t?void 0:e=>{od.current[t]=e},children:(0,n.jsx)(rF,{blocks:u,isStreaming:!1,defaultExpanded:!h,onAutoExpanded:void 0,cwd:op,onOpenFile:x,sessionId:e?.id??eM.current??void 0})},`process-group-${s}-${p}`),t)}h&&d(i(p,{messageOverride:h,writtenFiles:g}),r.get(p));for(let e=p+1;e<l;e++)d(i(e),r.get(e))}let c=[];return l.forEach((e,t)=>{void 0!==e&&(c[e]=t)}),t5.current=c,(0,n.jsx)(ig,{scrollElementRef:eE,items:a,virtualizerRef:t8})})(),ob&&(ea||V&&!q.streamingMessage)&&(0,n.jsx)("div",{className:"py-2 text-[13px] text-text-muted",children:(0,n.jsxs)("span",{className:"animate-[pulse_1.5s_infinite]",children:[ob,eC?.kind==="waiting_model"&&(0,n.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"}})]})}),G&&(0,n.jsx)(ny,{message:{role:"bashExecution",command:G.command,output:"",excludeFromContext:G.excludeFromContext},sessionId:e?.id??eM.current??void 0}),K&&!G&&(0,n.jsx)("div",{className:"py-2 text-[13px] text-text-muted",children:(0,n.jsx)("span",{className:"animate-[pulse_1.5s_infinite]",children:P("desktop.runningShellCommand")})}),(0,n.jsx)("div",{style:{height:96}}),(0,n.jsx)("div",{ref:eP}),(0,n.jsx)(nB,{open:tH,planText:tU,busy:V,onExecute:tV,onFeedback:tG,onExit:tJ,onClose:()=>tB(!1)})]})})}),tY&&(0,n.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"}),tZ&&(0,n.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"}),t0&&(0,n.jsxs)("button",{type:"button",onClick:()=>t4(),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,n.jsx)(ns.Z,{size:12,weight:"bold","aria-hidden":"true"}),P("desktop.scrollToBottom")]})]}),M?null:(0,n.jsx)(ik,{messages:U,streamingMessage:q.streamingMessage,scrollContainer:eE,messageRefs:od,virtualizer:t3})]}),(0,n.jsxs)("div",{className:"relative z-10",children:[(0,n.jsx)("div",{style:{padding:"0 16px",paddingRight:M?16:34},children:(0,n.jsx)("div",{style:{maxWidth:820,margin:"0 auto"},children:(0,n.jsx)(iV,{widgets:oy})})}),ok,(0,n.jsx)("div",{className:`session-info-bar-wrap${M?" is-mobile":""}`,children:(0,n.jsx)("div",{className:"session-info-bar-inner",children:(0,n.jsx)(iu,{onViewFullHistory:v,cwd:op,systemPrompt:y,sessionStats:ep,contextUsage:es,hasSession:!!e,showChat:!0,soundEnabled:T,onSoundToggle:R,onCompact:e?e1:void 0,onAbortCompaction:e8,isCompacting:ea,compactError:el,branchTree:eR,branchActiveLeafId:ez,onBranchLeafChange:eI,isDeepSeekOfficial:t$,deepseekBalance:tW,lastTurnUsage:tO})})})]})]})]})}function iq({statuses:e}){return 0===e.length?null:(0,n.jsx)("div",{style:{display:"flex",flexWrap:"wrap",gap:6,marginBottom:10},children:e.map(e=>(0,n.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,n.jsx)("span",{style:{color:"var(--accent)",fontFamily:"var(--font-mono)",fontSize:11},children:e.key}),(0,n.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.text})]},e.key))})}function iV({widgets:e}){return 0===e.length?null:(0,n.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:8,marginBottom:10},children:e.map(e=>(0,n.jsxs)("div",{style:{border:"1px solid var(--border)",borderRadius:7,background:"var(--bg-panel)",overflow:"hidden"},children:[(0,n.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,n.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 iK({notices:e,floating:t=!1,align:o="left"}){return 0===e.length?null:(0,n.jsx)("div",{style:{display:"flex",flexDirection:"column",alignItems:"right"===o?"flex-end":"stretch",marginBottom:10*!t},children:e.map((o,r)=>{let s="error"===o.type?"#ef4444":"warning"===o.type?"#d97706":"success"===o.type?"#10b981":"var(--accent)";return(0,n.jsxs)("div",{className:"notice-shelf-item",style:{display:"flex",alignItems:"center",gap:10,minHeight:44,maxHeight:180,marginBottom:6*(r!==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:o.exiting?"notice-shelf-out 0.18s ease-in forwards":"notice-shelf-in 0.18s ease-out both",padding:"0 12px"},children:[(0,n.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:s,flexShrink:0}}),(0,n.jsx)("span",{style:{padding:"10px 0",minWidth:0,maxWidth:"100%",overflowWrap:"anywhere",whiteSpace:"pre-wrap"},children:o.message})]},o.id)})})}function iG({request:e,onRespond:t}){let{t:o}=(0,F.s)(),[s,i]=(0,r.useState)("editor"===e.method?e.prefill??"":"");(0,r.useEffect)(()=>{i("editor"===e.method?e.prefill??"":"")},[e]);let a=()=>{"confirm"===e.method?t(e,{confirmed:!0}):t(e,{value:s})};return(0,n.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,n.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,n.jsxs)("div",{style:{padding:"12px 14px",borderBottom:"1px solid var(--border)"},children:[(0,n.jsx)("div",{style:{color:"var(--text)",fontSize:14,fontWeight:650},children:e.title}),(0,n.jsx)("div",{style:{marginTop:3,color:"var(--text-dim)",fontSize:11,fontFamily:"var(--font-mono)"},children:o("desktop.extensionRequest")})]}),(0,n.jsxs)("div",{style:{padding:14},children:["confirm"===e.method&&(0,n.jsx)("div",{style:{color:"var(--text-muted)",fontSize:13,lineHeight:1.6,whiteSpace:"pre-wrap"},children:e.message}),"select"===e.method&&(0,n.jsx)("div",{style:{display:"grid",gap:8},children:e.options.map(o=>(0,n.jsx)("button",{onClick:()=>t(e,{value:o}),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:o},o))}),"input"===e.method&&(0,n.jsx)("input",{autoFocus:!0,value:s,placeholder:e.placeholder,onChange:e=>i(e.target.value),onKeyDown:o=>{"Enter"===o.key&&a(),"Escape"===o.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,n.jsx)("textarea",{autoFocus:!0,value:s,onChange:e=>i(e.target.value),onKeyDown:o=>{"Escape"===o.key&&t(e,{cancelled:!0}),(o.metaKey||o.ctrlKey)&&"Enter"===o.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,n.jsxs)("div",{style:{display:"flex",justifyContent:"flex-end",gap:8,padding:"10px 14px",borderTop:"1px solid var(--border)",background:"var(--bg-panel)"},children:[(0,n.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:o("desktop.cancel")}),"confirm"===e.method?(0,n.jsx)("button",{onClick:a,style:{padding:"6px 10px",borderRadius:6,border:"1px solid var(--accent)",background:"var(--accent)",color:"#fff",cursor:"pointer"},children:o("desktop.confirm")}):"select"!==e.method?(0,n.jsx)("button",{onClick:a,style:{padding:"6px 10px",borderRadius:6,border:"1px solid var(--accent)",background:"var(--accent)",color:"#fff",cursor:"pointer"},children:o("desktop.submit")}):null]})]})})}function iJ({request:e,onInput:t}){let{t:o}=(0,F.s)(),s=(0,r.useRef)(null),i=function(e){let t=/^[┌├└╭╰][─┬┴┼]+[┐┤┘╮╯]$/,o=[];for(let n of e){let e=ts(n).trimEnd();if(t.test(e))continue;let r=n,s=tl(r);("│"===s||"┃"===s)&&" "===tl(r=ta(r,0))&&(r=ta(r,0));let i=function(e){let t=ti(e);for(let e=t.length-1;e>=0;e--)if(""!==t[e].char.trim())return e;return -1}(r),a=i>=0?ti(r)[i]?.char:void 0;("│"===a||"┃"===a)&&(r=ta(r,i)),o.push(function(e){let t=e;for(;;){let e=ti(t),o=e[e.length-1];if(!o||""!==o.char.trim())return t;t=t.slice(0,o.start)+t.slice(o.end)}}(r))}for(;o.length>0&&""===ts(o[0]).trim();)o.shift();for(;o.length>0&&""===ts(o[o.length-1]).trim();)o.pop();return o.length?o:e}(e.lines);return(0,r.useEffect)(()=>{s.current?.focus()},[e.id]),(0,n.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,n.jsxs)("div",{ref:s,tabIndex:0,role:"dialog","aria-modal":"true",onKeyDown:o=>{let n=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}}(o);n&&(o.preventDefault(),o.stopPropagation(),t(e,n))},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,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,padding:"10px 12px",borderBottom:"1px solid var(--border)"},children:[(0,n.jsx)("div",{style:{color:"var(--text)",fontSize:13,fontWeight:650},children:o("desktop.extensionPanel")}),(0,n.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:o("desktop.close")})]}),(0,n.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,o)=>{var s;return(0,n.jsxs)(r.Fragment,{children:[(s=`line-${t}`,(function(e){let t,o=[],n={},r=0;for(to.lastIndex=0;null!==(t=to.exec(e));)t.index>r&&o.push({text:e.slice(r,t.index),style:n}),n=function(e,t){let o={...e};for(let e=0;e<t.length;e++){let n=t[e];if(0===n)for(let e of Object.keys(o))delete o[e];else if(1===n)o.fontWeight=700;else if(2===n)o.opacity=.65;else if(3===n)o.fontStyle="italic";else if(4===n)o.textDecoration="underline";else if(22===n)delete o.fontWeight,delete o.opacity;else if(23===n)delete o.fontStyle;else if(24===n)delete o.textDecoration;else if(39===n)delete o.color;else if(49===n)delete o.backgroundColor;else if(n>=30&&n<=37)o.color=tn[n-30];else if(n>=90&&n<=97)o.color=tr[n-90];else if(n>=40&&n<=47)o.backgroundColor=tn[n-40];else if(n>=100&&n<=107)o.backgroundColor=tr[n-100];else if((38===n||48===n)&&2===t[e+1]){let[r,s,i]=[t[e+2],t[e+3],t[e+4]];[r,s,i].every(e=>"number"==typeof e&&Number.isFinite(e))&&(38===n?o.color=`rgb(${r}, ${s}, ${i})`:o.backgroundColor=`rgb(${r}, ${s}, ${i})`),e+=4}else if((38===n||48===n)&&5===t[e+1]){let r=function(e){if(e>=0&&e<8)return tn[e];if(e>=8&&e<16)return tr[e-8];if(e>=16&&e<=231){let t=e-16,o=Math.floor(t/36),n=Math.floor(t%36/6),r=e=>0===e?0:55+40*e;return`rgb(${r(o)}, ${r(n)}, ${r(t%6)})`}if(e>=232&&e<=255){let t=8+(e-232)*10;return`rgb(${t}, ${t}, ${t})`}}(t[e+2]);r&&(38===n?o.color=r:o.backgroundColor=r),e+=2}}return o}(n,t[1]?t[1].split(";").map(e=>Number(e||"0")):[0]),r=t.index+t[0].length;return r<e.length&&o.push({text:e.slice(r),style:n}),o})(e).map((e,t)=>Object.keys(e.style).length>0?(0,n.jsx)("span",{style:e.style,children:e.text},`${s}-${t}`):e.text)),t<o.length-1?"\n":null]},t)})})]})})}var iY=o(93549);let iX={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"},iZ={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",webm:"audio/webm"};function iQ(e){return(e.replace(/\\/g,"/").split("/").pop()??"").toLowerCase().split(".").pop()??""}function i0(e){let t=e.nodeType===Node.ELEMENT_NODE?e:e.parentElement;return t?.closest(".file-source-line[data-line-number]")??null}function i1(e,t){if(!t||t.isCollapsed||0===t.rangeCount)return null;let o=t.getRangeAt(0);if(!e.contains(o.startContainer)||!e.contains(o.endContainer))return null;let n=Number(i0(o.startContainer)?.dataset.lineNumber),r=Number(i0(o.endContainer)?.dataset.lineNumber);return Number.isInteger(n)&&Number.isInteger(r)?n<=r?{startLine:n,endLine:r}:{startLine:r,endLine:n}:null}function i2(e,t,o,n={}){let r=ei(e),s=new URLSearchParams({type:t});for(let[e,t]of(o&&s.set("sessionId",o),Object.entries(n)))void 0!==t&&s.set(e,String(t));return`/api/files/${r}?${s.toString()}`}function i4({filePath:e,sourceSessionId:t}){let{t:o}=(0,F.s)();return(0,n.jsx)("a",{href:i2(e,"download",t),download:ea(e),title:o("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,n.jsx)(I.z,{size:11,"aria-hidden":"true"})})}let i6={fontFamily:"var(--font-mono)",fontSize:13,lineHeight:1.6,tabSize:2},i8={fontFamily:"var(--font-mono)",fontSize:13,lineHeight:1.6,padding:"12px 0 12px 16px",color:"var(--text-dim)",textAlign:"right",userSelect:"none"};async function i5(e,t){let o=await fetch(`/api/files/${ei(e)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:t})});if(!o.ok)throw Error((await o.json().catch(()=>({}))).error??`HTTP ${o.status}`);let n=await o.json();return"number"==typeof n.size?n.size:0}let i3={delete:"3px solid var(--git-status-deleted)",add:"3px solid var(--git-status-added)",edit:"3px solid var(--git-status-modified)"},i7="var(--git-status-deleted-bg)",i9="var(--git-status-added-bg)",ae="var(--git-status-added)";function at(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KB`:`${(e/1048576).toFixed(1)} MB`}function ao({oldContent:e,newContent:t}){let{t:o}=(0,F.s)(),r=function(e,t){let o=e.length,n=t.length,r=o+n,s=Array(2*r+1).fill(0),i=[];for(let a=0;a<=r;a++){i.push([...s]);for(let l=-a;l<=a;l+=2){let d,c=(d=l===-a||l!==a&&s[l-1+r]<s[l+1+r]?s[l+1+r]:s[l-1+r]+1)-l;for(;d<o&&c<n&&e[d]===t[c];)d++,c++;if(s[l+r]=d,d>=o&&c>=n){let s=[],l=o,d=n;for(let o=a;o>0;o--){let n,a=i[o-1],c=l-d;n=c===-o||c!==o&&a[c-1+r]<a[c+1+r]?c+1:c-1;let p=a[n+r],u=p-n;for(;l>p&&d>u;)l--,d--,s.unshift({type:"unchanged",text:e[l]});o>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(!r.some(e=>"unchanged"!==e.type))return(0,n.jsx)("div",{style:{padding:"12px 16px",fontSize:12,color:"var(--text-dim)",fontFamily:"var(--font-mono)"},children:o("desktop.noChanges")});let s=new Set(r.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(r.length-1,e+3);t++)i.add(t);let a=[],l=0;for(;l<r.length;)if(i.has(l)){let e=[];for(;l<r.length&&i.has(l);)e.push(r[l]),l++;a.push({hidden:!1,lines:e})}else{let e=0;for(;l<r.length&&!i.has(l);)e++,l++;a.push({hidden:!0,count:e})}let d=[],c=1;for(let e of r)"removed"===e.type?d.push(0):d.push(c++);let p=0;return(0,n.jsx)("div",{style:{fontFamily:"var(--font-mono)",fontSize:13,lineHeight:1.6,minWidth:"max-content"},children:a.map((e,t)=>{if(e.hidden){let r=(0,n.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:o("desktop.unchangedLines",{count:e.count})},t);return p+=e.count,r}let r=[],s=[],i=[],a=()=>{if(s.length||i.length){let e=s.length&&i.length?"edit":s.length?"delete":"add";for(let t of s)r.push({key:t.key,kind:"removed",text:t.text,lineNo:null,block:e});for(let t of i)r.push({key:t.key,kind:"added",text:t.text,lineNo:t.lineNo,block:e});s=[],i=[]}};e.lines.forEach((e,o)=>{"unchanged"===e.type?(a(),r.push({key:`${t}:${o}`,kind:"context",text:e.text,lineNo:d[p+o],block:null})):"removed"===e.type?s.push({key:`${t}:${o}`,text:e.text}):i.push({key:`${t}:${o}`,text:e.text,lineNo:d[p+o]})}),a();let l=r.map(e=>{let t="removed"===e.kind?i7:"added"===e.kind?i9:"transparent",o=e.block?i3[e.block]:"3px solid transparent",r="added"===e.kind?ae:"var(--text-dim)";return(0,n.jsxs)("div",{style:{display:"flex",background:t,borderLeft:o},children:[(0,n.jsx)("span",{style:{minWidth:44,padding:"0 8px 0 16px",textAlign:"right",color:r,userSelect:"none",fontSize:11,lineHeight:1.6,flexShrink:0},children:e.lineNo??""}),(0,n.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,n.jsx)("div",{children:l},t)})})}function an({patch:e}){let t=o7(e);if(!t)return null;let o=[],r=[],s=[],i=()=>{if(r.length||s.length){let e=r.length&&s.length?"edit":r.length?"delete":"add";for(let t of r)o.push({key:t.key,kind:"removed",text:t.text,lineNo:null,block:e});for(let t of s)o.push({key:t.key,kind:"added",text:t.text,lineNo:t.lineNo,block:e});r=[],s=[]}};return t.forEach((e,t)=>{e.rows.forEach((e,n)=>{if("hunk"===e.type){i(),o.push({key:`${t}:${n}: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(),o.push({key:`${t}:${n}:c`,kind:"context",text:a.text,lineNo:l.lineNo,block:null});return}"removed"===a.type&&r.push({key:`${t}:${n}:l`,text:a.text}),"added"===l.type&&s.push({key:`${t}:${n}:r`,text:l.text,lineNo:l.lineNo})})}),i(),(0,n.jsx)("div",{style:{fontFamily:"var(--font-mono)",fontSize:12,lineHeight:1.55,minWidth:"max-content"},children:o.map(e=>{if("hunk"===e.kind)return(0,n.jsxs)("div",{children:[(0,n.jsx)("div",{style:{height:"1.55em"}}),(0,n.jsx)("div",{style:{padding:"3px 12px",color:"var(--accent-blue)",background:"var(--bg-secondary)"},children:e.text}),(0,n.jsx)("div",{style:{height:"1.55em"}})]},e.key);let t="removed"===e.kind?i7:"added"===e.kind?i9:"transparent",o=e.block?i3[e.block]:"3px solid transparent",r="added"===e.kind?ae:"var(--text-dim)";return(0,n.jsxs)("div",{style:{display:"flex",background:t,borderLeft:o},children:[(0,n.jsx)("span",{style:{width:44,flexShrink:0,padding:"0 8px 0 16px",textAlign:"right",color:r,userSelect:"none",fontSize:11},children:e.lineNo??""}),(0,n.jsx)("span",{style:{flex:1,minWidth:0,padding:"0 8px 0 0",whiteSpace:"pre",color:"var(--text)"},children:e.text||"\xa0"})]},e.key)})})}function ar({filePath:e,cwd:t,sourceSessionId:o}){let{t:s}=(0,F.s)(),[i,a]=(0,r.useState)(0),[l,d]=(0,r.useState)(null),[c,p]=(0,r.useState)(null),[u,h]=(0,r.useState)(null),g=(0,r.useRef)(null),m=ea(e).toLowerCase().split(".").pop()??"";(0,r.useEffect)(()=>{a(0),d(null),p(null),h(null),g.current&&(g.current.close(),g.current=null);let t=new EventSource(i2(e,"watch",o));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,o]);let f=i2(e,"read",o,i?{v:i}:void 0),x=null!=l?at(l):null;return(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,n.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,n.jsx)("span",{style:{fontFamily:"var(--font-mono)"},title:e,children:el(e,t)}),(0,n.jsx)("span",{style:{marginLeft:"auto"},children:m||s("desktop.image")}),c&&(0,n.jsxs)("span",{children:[c.w," \xd7 ",c.h]}),x&&(0,n.jsx)("span",{children:x}),(0,n.jsx)(i4,{filePath:e,sourceSessionId:o})]}),(0,n.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,n.jsx)("div",{style:{color:"#f87171",fontSize:13},children:u}):(0,n.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 as({filePath:e,cwd:t,sourceSessionId:o}){let{t:s}=(0,F.s)(),[i,a]=(0,r.useState)(0),[l,d]=(0,r.useState)(null),[c,p]=(0,r.useState)(null),[u,h]=(0,r.useState)(null),g=(0,r.useRef)(null),m=ea(e).toLowerCase().split(".").pop()??"";(0,r.useEffect)(()=>{a(0),d(null),p(null),h(null),g.current&&(g.current.close(),g.current=null);let t=new EventSource(i2(e,"watch",o));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,o]);let f=i2(e,"read",o,i?{v:i}:void 0);return(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,n.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,n.jsx)("span",{style:{fontFamily:"var(--font-mono)"},title:e,children:el(e,t)}),(0,n.jsx)("span",{style:{marginLeft:"auto"},children:m||s("desktop.audio")}),null!=c&&(0,n.jsx)("span",{children:function(e){if(!Number.isFinite(e))return"";let t=Math.round(e),o=Math.floor(t/60);return`${o}:${String(t%60).padStart(2,"0")}`}(c)}),null!=l&&(0,n.jsx)("span",{children:at(l)}),(0,n.jsx)(i4,{filePath:e,sourceSessionId:o})]}),(0,n.jsx)("div",{style:{flex:1,display:"flex",alignItems:"center",justifyContent:"center",padding:24,background:"var(--bg-panel)"},children:(0,n.jsxs)("div",{style:{width:"min(680px, 100%)"},children:[u&&(0,n.jsx)("div",{style:{color:"#f87171",fontSize:13,marginBottom:12,textAlign:"center"},children:u}),(0,n.jsx)("audio",{controls:!0,preload:"metadata",src:f,onLoadedMetadata:e=>p(e.currentTarget.duration),onError:()=>h(s("desktop.failedToLoadAudio")),style:{width:"100%"}},f)]})})]})}function ai({filePath:e,cwd:t,sourceSessionId:o}){let{t:s}=(0,F.s)(),[i,a]=(0,r.useState)(0),[l,d]=(0,r.useState)(null),[c,p]=(0,r.useState)(null),u=(0,r.useRef)(null),h=iQ(e),g="pdf"===h,m=g?i2(e,"read",o,i?{v:i}:void 0):i2(e,"preview",o,i?{v:i}:void 0);return(0,r.useEffect)(()=>{a(0),d(null),p(null),u.current&&(u.current.close(),u.current=null),fetch(i2(e,"meta",o)).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(i2(e,"watch",o));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,o,s]),(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,n.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,n.jsx)("span",{style:{fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:e,children:el(e,t)}),(0,n.jsx)("span",{style:{marginLeft:"auto"},children:"docx"===h?s("desktop.docxPreview"):"pdf"}),null!=l&&(0,n.jsx)("span",{children:at(l)}),(0,n.jsx)(i4,{filePath:e,sourceSessionId:o})]}),(0,n.jsx)("div",{style:{flex:1,minHeight:0,background:"var(--bg-panel)"},children:c?(0,n.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",padding:24,color:"#f87171",fontSize:13,textAlign:"center"},children:c}):(0,n.jsx)("iframe",{src:m,sandbox:g?void 0:"allow-same-origin",title:s("desktop.previewFile",{file:ea(e)}),style:{width:"100%",height:"100%",border:"none",background:g?"var(--bg)":"#eef1f5"}},m)})]})}function aa({filePath:e,cwd:t,sourceSessionId:o,onOpenFile:r,onAtMention:s,onMentionLines:i,initialDisplayMode:a,onFileSaved:l}){let d;return null!==(iX[iQ(e)]??null)?(0,n.jsx)(ar,{filePath:e,cwd:t,sourceSessionId:o}):null!==(iZ[iQ(e)]??null)?(0,n.jsx)(as,{filePath:e,cwd:t,sourceSessionId:o}):null!==("pdf"===(d=iQ(e))||"docx"===d?d:null)?(0,n.jsx)(ai,{filePath:e,cwd:t,sourceSessionId:o}):(0,n.jsx)(al,{filePath:e,cwd:t,sourceSessionId:o,onOpenFile:r,onAtMention:s,onMentionLines:i,initialDisplayMode:a,onFileSaved:l})}function al({filePath:e,cwd:t,sourceSessionId:o,onOpenFile:s,onAtMention:i,onMentionLines:a,initialDisplayMode:l,onFileSaved:d}){let c,u,{t:h}=(0,F.s)(),[m,f]=(0,r.useState)(null),[x,k]=(0,r.useState)(null),[v,y]=(0,r.useState)(null),[b,w]=(0,r.useState)(!0),[j,S]=(0,r.useState)(null),[C,T]=(0,r.useState)(!1),[R,z]=(0,r.useState)("source"),[I,M]=(0,r.useState)(!1),[P,E]=(0,r.useState)(0),[D,W]=(0,r.useState)(null),A=(0,r.useRef)(null),N=(0,r.useRef)(null),[$,L]=(0,r.useState)(!1),[O,H]=(0,r.useState)(""),[B,U]=(0,r.useState)(""),[_,q]=(0,r.useState)(!1),[V,K]=(0,r.useState)(null),[G,J]=(0,r.useState)(!1),Y=(0,r.useRef)(null),X=(0,r.useRef)(null),Z=(0,r.useRef)(0),Q=(0,r.useRef)(!1);(0,r.useEffect)(()=>{Q.current=$},[$]);let ee=$&&O!==B,et=!!(m?.content&&m.content.includes("\0")),eo=(0,r.useCallback)(async e=>{if(!t)return void y(null);try{let o=new URLSearchParams({cwd:t,path:e}),n=await fetch(`/api/git/diff?${o.toString()}`),r=await n.json();y(n.ok&&r.supported&&"string"==typeof r.patch?r:null)}catch{y(null)}},[t]),en=(0,r.useCallback)((e,t=!1)=>fetch(i2(e,"read",o)).then(e=>e.json()).then(e=>e.error?(S(e.error),null):(t?(f(t=>(t&&k(t.content),e)),E(e=>e+1)):f(e),e)).catch(e=>(S(String(e)),null)),[o]);(0,r.useEffect)(()=>{w(!0),S(null),f(null),k(null),y(null),T(!1),z("source"),M(!1),E(0),L(!1),H(""),U(""),K(null),J(!1),q(!1),A.current&&(A.current.close(),A.current=null),en(e).then(e=>{(e?.language==="markdown"||e?.language==="html")&&"diff"!==l&&T(!0)}).finally(()=>w(!1)),eo(e);let t=new EventSource(i2(e,"watch",o));return A.current=t,t.addEventListener("change",()=>{Q.current?J(!0):(en(e,!0),eo(e))}),()=>{t.close(),A.current=null}},[e,en,eo,l,o]);let er=(0,r.useCallback)(()=>{m&&!et&&(H(m.content),U(m.content),K(null),J(!1),L(!0))},[m,et]),ei=(0,r.useCallback)(()=>{L(!1),H(""),U(""),K(null),J(!1)},[]),ea=(0,r.useCallback)(()=>{(!ee||window.confirm(h("files.unsavedChanges")))&&ei()},[ee,ei,h]),ed=(0,r.useCallback)(async()=>{if(!m||_)return;let t=++Z.current;q(!0),K(null);try{let o=await i5(e,O);if(t!==Z.current)return;f(e=>e?{...e,content:O,size:o}:e),U(O),q(!1),ei(),eo(e),d?.()}catch(e){if(t!==Z.current)return;K(e instanceof Error?e.message:String(e)),q(!1)}},[m,_,O,e,ei,eo,d]);(0,r.useEffect)(()=>{if(!$)return;let e=e=>{if((e.metaKey||e.ctrlKey)&&"s"===e.key.toLowerCase()){e.preventDefault(),ed();return}"Escape"===e.key&&(e.preventDefault(),ea())};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[$,ed,ea]),(0,r.useEffect)(()=>{if(!ee)return;let e=e=>{e.preventDefault(),e.returnValue=""};return window.addEventListener("beforeunload",e),()=>window.removeEventListener("beforeunload",e)},[ee]);let ec=(0,r.useCallback)(()=>{let e=Y.current,t=X.current;e&&t&&(t.scrollTop=e.scrollTop)},[]),eu=(0,r.useCallback)(e=>{if("Tab"!==e.key||e.metaKey||e.ctrlKey||e.altKey)return;e.preventDefault();let t=e.currentTarget,{selectionStart:o,selectionEnd:n}=t;H(t.value.slice(0,o)+" "+t.value.slice(n)),requestAnimationFrame(()=>{let e=Y.current;if(!e)return;let t=o+2;e.selectionStart=t,e.selectionEnd=t})},[]),eh=(0,r.useMemo)(()=>oP(m?.content??""),[m?.content]),eg=v?.supported===!0&&"string"==typeof v.patch;(0,r.useEffect)(()=>{"diff"===l&&eg&&z("diff")},[eg,l]);let em=eg&&v?.status==="deleted",ef=(0,r.useCallback)(o=>{a&&o&&a(el(e,t),o.startLine,o.endLine)},[t,e,a]);if((0,r.useEffect)(()=>{let e=()=>{let e=N.current,t="source"===R&&!C;W(a&&t&&e?i1(e,window.getSelection()):null)};if(e(),a&&"source"===R&&!C)return document.addEventListener("selectionchange",e),()=>document.removeEventListener("selectionchange",e)},[m?.content,a,C,R]),(0,r.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 o=N.current,n=o?i1(o,window.getSelection()):null;n&&(e.preventDefault(),ef(n))};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[ef,a,C,R]),b)return(0,n.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-muted)",fontSize:13},children:h("desktop.loadingFile")});if(em&&!m)return(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,n.jsx)("div",{style:{padding:"5px 16px",borderBottom:"1px solid var(--border)",color:"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:11},title:e,children:el(e,t)}),(0,n.jsx)("div",{style:{flex:1,overflow:"auto",background:"var(--bg)"},children:(0,n.jsx)(an,{patch:v.patch})})]});if(j)return(0,n.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"#f87171",fontSize:13},children:j});if(!m)return null;let ex="html"===m.language,ek="markdown"===m.language,ev=(u=(c=es(e).replace(/\/+$/,"")).lastIndexOf("/"))<0?"":0===u?"/":2===u&&/^[a-zA-Z]:\//.test(c)?c.slice(0,3):c.slice(0,u),ey=m.content.split("\n"),eb=null!==x&&x!==m.content||eg,ew=!em&&!et&&ep();return(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,n.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,n.jsx)("span",{style:{fontFamily:"var(--font-mono)"},title:e,children:el(e,t)}),(0,n.jsx)("span",{style:{marginLeft:"auto"},children:m.language}),"source"===R&&!$&&(0,n.jsx)("span",{children:h("desktop.lines",{count:ey.length})}),(0,n.jsx)("span",{children:at(m.size)}),eb&&!$&&(0,n.jsxs)("div",{style:{display:"flex",borderRadius:5,overflow:"hidden",border:"1px solid var(--border)"},children:[(0,n.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:h("desktop.source")}),(0,n.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:[h("desktop.diff")," ",P>0&&(0,n.jsxs)("span",{style:{color:"var(--git-status-added)",marginLeft:2},children:["+",P]})]})]}),"source"===R&&!C&&!$&&(0,n.jsx)("button",{onClick:()=>M(e=>!e),title:I?h("desktop.disableWordWrap"):h("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:h("desktop.wrap")}),ex&&"source"===R&&!$&&(0,n.jsxs)("div",{style:{display:"flex",borderRadius:5,overflow:"hidden",border:"1px solid var(--border)"},children:[(0,n.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:h("desktop.code")}),(0,n.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:h("desktop.preview")})]}),ek&&"source"===R&&!$&&(0,n.jsxs)("div",{style:{display:"flex",borderRadius:5,overflow:"hidden",border:"1px solid var(--border)"},children:[(0,n.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:h("desktop.preview")}),(0,n.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:h("desktop.raw")})]}),$?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("button",{type:"button",onClick:()=>void ed(),disabled:_,title:h("files.saveHint"),"aria-label":h("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,n.jsx)(iY.g,{size:13,"aria-hidden":"true"})}),(0,n.jsx)("button",{type:"button",onClick:ea,disabled:_,title:h("files.cancelEdit"),"aria-label":h("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,n.jsx)(p.X,{size:13,"aria-hidden":"true"})})]}):"source"===R&&ew?(0,n.jsx)("button",{type:"button",onClick:er,title:h("files.edit"),"aria-label":h("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,n.jsx)(g.I,{size:13,"aria-hidden":"true"})}):null,(i||a)&&!$&&(0,n.jsx)("button",{type:"button",onPointerDown:e=>e.preventDefault(),onClick:()=>{D&&a?ef(D):i?.(el(e,t),!1)},title:D?h("desktop.mentionSelectedLines",{start:D.startLine,end:D.endLine}):h("desktop.mentionFile"),"aria-label":D?h("desktop.mentionSelectedLines",{start:D.startLine,end:D.endLine}):h("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:"@"}),!$&&(0,n.jsx)(i4,{filePath:e,sourceSessionId:o})]}),(0,n.jsx)("div",{ref:N,style:{flex:1,overflow:"auto",background:"var(--bg)"},children:$?(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[G&&(0,n.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,n.jsx)("span",{style:{flex:1},children:h("files.externalModified")}),(0,n.jsx)("button",{type:"button",onClick:()=>{(!ee||window.confirm(h("files.reloadOverwriteConfirm")))&&en(e).then(e=>{e&&(H(e.content),U(e.content),J(!1))})},disabled:_,style:{padding:"2px 8px",fontSize:11,border:"1px solid #d6a84b",borderRadius:4,background:"transparent",color:"#d6a84b",cursor:"pointer"},children:h("files.reload")})]}),V&&(0,n.jsx)("div",{style:{padding:"5px 12px",borderBottom:"1px solid var(--border)",background:"rgba(248,113,113,0.14)",color:"#f87171",fontSize:11,flexShrink:0},children:h("files.saveFailed",{error:V})}),(0,n.jsxs)("div",{style:{flex:1,display:"flex",overflow:"hidden"},children:[(0,n.jsx)("div",{ref:X,"aria-hidden":"true",style:{...i8,height:"100%",overflow:"hidden",whiteSpace:"pre",pointerEvents:"none"},children:O.split("\n").map((e,t)=>`${t+1}
|
|
37
37
|
`).join("")}),(0,n.jsx)("textarea",{ref:Y,value:O,onChange:e=>H(e.target.value),onScroll:ec,onKeyDown:eu,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)",...i6,whiteSpace:"pre",overflow:"auto",padding:0,tabSize:2}})]})]}):"diff"===R&&eb?eg?(0,n.jsx)(an,{patch:v.patch}):(0,n.jsx)(ao,{oldContent:x,newContent:m.content}):ex&&C?(0,n.jsx)("iframe",{srcDoc:m.content,sandbox:"allow-scripts",style:{width:"100%",height:"100%",border:"none",background:"var(--bg)"},title:h("desktop.htmlPreview")}):ek&&C?(0,n.jsx)("div",{className:"markdown-body markdown-file-preview",style:{padding:"24px 32px"},children:(0,n.jsx)(tS.oz,{remarkPlugins:oD,rehypePlugins:oW,components:{h1:({children:e})=>(0,n.jsx)("h1",{id:oM(e),children:e}),h2:({children:e})=>(0,n.jsx)("h2",{id:oM(e),children:e}),h3:({children:e})=>(0,n.jsx)("h3",{id:oM(e),children:e}),code({className:e,children:t,...o}){let r=e?.replace("language-","").toLowerCase()??"",s=String(t);return e?.includes("language-")||s.includes("\n")?"mermaid"===r?(0,n.jsx)(oX,{code:s.replace(/\n$/,"")}):(0,n.jsx)(o0,{code:s.replace(/\n$/,""),lang:r}):(0,n.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)",...o,children:t})},pre:({children:e})=>(0,n.jsx)(n.Fragment,{children:e}),a({href:e,children:o,...r}){delete r.node;let i="text-(--accent-blue) underline underline-offset-2 hover:text-(--accent-blue)/80",a=s?ty(e,ev,t??ev):null;return a&&s?(0,n.jsx)("a",{href:e,...r,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:o}):(0,n.jsx)("a",{href:e,...r,className:i,target:"_blank",rel:"noopener noreferrer",children:o})},table:({children:e})=>(0,n.jsx)("div",{className:"my-3 rounded-lg overflow-hidden border border-(--border)",children:(0,n.jsx)("div",{className:"overflow-x-auto",children:(0,n.jsx)("table",{className:"w-full text-sm border-collapse [&_tr:last-child>td]:border-b-0",children:e})})})},children:eh})}):(0,n.jsx)(tC.A,{language:"text"===m.language?"plaintext":m.language,style:oA,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:m.content})})]})}let ad={running:"var(--accent)",completed:"#22c55e",failed:"#ef4444",stopped:"#d97706"},ac={running:"desktop.subagentsStatusRunning",completed:"desktop.subagentsStatusCompleted",failed:"desktop.subagentsStatusFailed",stopped:"desktop.subagentsStatusStopped"};function ap({agent:e,selected:t,onSelect:o}){let[s,i]=(0,r.useState)(!1),{t:a}=(0,F.s)(),[l,d]=(0,r.useState)(()=>Date.now());(0,r.useEffect)(()=>{if("running"!==e.status)return;let t=setInterval(()=>d(Date.now()),1e3);return()=>clearInterval(t)},[e.status]);let c=e.completedAt?e.completedAt-e.startedAt:l-e.startedAt,p=e.tokens?.total??e.tokens?.input??e.tokens?.output,u=ad[e.status];return(0,n.jsxs)("button",{type:"button",onClick:()=>o?.(e),onMouseEnter:()=>i(!0),onMouseLeave:()=>i(!1),title:e.error||`${e.agentType} \xb7 ${e.description}`,style:{width:"100%",display:"flex",alignItems:"center",gap:7,padding:"5px 10px",border:"none",borderRadius:5,background:t?"var(--bg-selected)":s?"var(--bg-hover)":"transparent",color:"var(--text)",cursor:"pointer",textAlign:"left",minWidth:0},children:[(0,n.jsx)("span",{"aria-hidden":"true",style:{width:7,height:7,flexShrink:0,borderRadius:"50%",background:u,boxShadow:"running"===e.status?`0 0 0 0 ${u}`:"none",animation:"running"===e.status?"subagent-pulse 1.4s ease-out infinite":"none"}}),(0,n.jsx)("span",{style:{flexShrink:0,fontSize:10,fontFamily:"var(--font-mono)",fontWeight:600,color:"var(--text-dim)"},children:e.agentType}),(0,n.jsx)("span",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:11.5,color:"var(--text-muted)"},children:e.description||a("desktop.subagentsNoDesc")}),void 0!==p&&p>0&&(0,n.jsxs)("span",{style:{flexShrink:0,fontSize:10,fontFamily:"var(--font-mono)",color:"var(--text-dim)"},children:[void 0===p?"":p>=1e6?`${(p/1e6).toFixed(1)}M`:p>=1e3?`${(p/1e3).toFixed(1)}k`:`${p}`,"t"]}),(0,n.jsx)("span",{style:{flexShrink:0,fontSize:10,fontFamily:"var(--font-mono)",color:"var(--text-dim)"},children:function(e){if(void 0===e)return"…";if(e<1e3)return`${e}ms`;let t=Math.floor(e/1e3);if(t<60)return`${t}s`;let o=Math.floor(t/60),n=t%60;return n>0?`${o}m ${n}s`:`${o}m`}(c)}),(0,n.jsx)("span",{style:{flexShrink:0,fontSize:10,color:u},children:a(ac[e.status])})]})}function au({subagents:e,onSelect:t,selectedId:o}){let{t:s}=(0,F.s)(),[i,a]=(0,r.useState)(!0),l=e.filter(e=>"running"===e.status).length;return 0===e.length?(0,n.jsx)("div",{style:{padding:"18px 14px",fontSize:12,color:"var(--text-dim)",textAlign:"center"},children:s("desktop.subagentsEmpty")}):(0,n.jsxs)("section",{style:{flex:1,minHeight:0,display:"flex",flexDirection:"column",overflow:"hidden"},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",flexShrink:0,padding:"6px 10px",borderBottom:"1px solid var(--border)"},children:[(0,n.jsxs)("button",{type:"button",onClick:()=>a(e=>!e),"aria-expanded":i,style:{display:"flex",alignItems:"center",gap:6,flex:1,minWidth:0,background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",fontSize:11,fontWeight:600,letterSpacing:"0.05em",textTransform:"uppercase",textAlign:"left"},children:[(0,n.jsx)(v.K,{size:9,weight:"regular",style:{transform:i?"rotate(90deg)":"none",transition:"transform 0.15s",flexShrink:0},"aria-hidden":"true"}),(0,n.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:s("desktop.subagentsPanelTitle")})]}),l>0&&(0,n.jsxs)("span",{style:{marginRight:4,fontSize:10,fontFamily:"var(--font-mono)",color:"var(--accent)"},children:["● ",l," ",s("desktop.subagentsStatusRunning")]})]}),i&&(0,n.jsx)("div",{style:{flex:1,minHeight:0,overflowY:"auto",overflowX:"hidden",padding:"4px 0 8px"},children:e.map(e=>(0,n.jsx)(ap,{agent:e,selected:e.id===o,onSelect:t},e.id))})]})}let ah={user:{color:"var(--accent)"},assistant:{color:"var(--text)"},toolResult:{color:"var(--text-dim)"},bashExecution:{color:"var(--text-muted)"}};function ag({line:e,roleLabel:t}){let o=ah[e.role]??ah.toolResult;return(0,n.jsxs)("div",{style:{marginBottom:6},children:[(0,n.jsxs)("div",{style:{fontSize:10.5,fontWeight:600,color:o.color,marginBottom:2,fontFamily:"var(--font-mono)"},children:["[",t(e.role),"]"]}),(0,n.jsx)("pre",{style:{margin:0,fontSize:11.5,lineHeight:1.55,color:"var(--text-muted)",whiteSpace:"pre-wrap",wordBreak:"break-word",fontFamily:"var(--font-mono)",maxHeight:240,overflowY:"auto",background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:6,padding:"6px 8px"},children:e.text})]})}function am({agent:e,cwd:t,onBack:o}){let{t:s}=(0,F.s)(),a=e=>s("user"===e?"desktop.transcriptRoleUser":"assistant"===e?"desktop.transcriptRoleAssistant":"toolResult"===e?"desktop.transcriptRoleResult":"desktop.transcriptRoleBash"),[l,d]=(0,r.useState)([]),[c,p]=(0,r.useState)(!0),[u,h]=(0,r.useState)(null),g=(0,r.useRef)(null),m=(0,r.useRef)(!0),f=(0,r.useCallback)(async(o=!1)=>{if(e.id&&t){o||p(!0);try{let n=new URLSearchParams({id:e.id,cwd:t}),r=await fetch(`/api/subagents/transcript?${n}`),s=await r.json();if(!r.ok||s.error){o||h(s.error??`HTTP ${r.status}`);return}d(s.lines??[]),h(null)}catch(e){o||h(e instanceof Error?e.message:String(e))}finally{p(!1)}}},[e.id,t]);(0,r.useEffect)(()=>{f()},[f]);let x=(0,r.useRef)(e.status);(0,r.useEffect)(()=>{let t="running"===x.current;x.current=e.status,t&&"running"!==e.status&&f(!0)},[e.status]),(0,r.useEffect)(()=>{if("running"!==e.status)return;let t=setInterval(()=>void f(!0),2e3);return()=>clearInterval(t)},[e.status,f]),(0,r.useEffect)(()=>{let e=g.current;e&&m.current&&(e.scrollTop=e.scrollHeight)},[l]);let k=e.completedAt?e.completedAt-e.startedAt:void 0,v=e.tokens?.total??e.tokens?.input??e.tokens?.output,y="completed"===e.status?"#22c55e":"failed"===e.status?"#ef4444":"stopped"===e.status?"#d97706":"var(--accent)";return(0,n.jsxs)("div",{style:{flex:1,minHeight:0,display:"flex",flexDirection:"column"},children:[(0,n.jsxs)("div",{style:{flexShrink:0,borderBottom:"1px solid var(--border)",background:"var(--bg-panel)",padding:"6px 8px"},children:[(0,n.jsx)("div",{style:{display:"flex",alignItems:"center",gap:8},children:(0,n.jsxs)("button",{type:"button",onClick:o,title:s("desktop.subagentsBack"),style:{display:"inline-flex",alignItems:"center",gap:2,padding:"3px 6px",border:"none",borderRadius:5,background:"transparent",color:"var(--text-muted)",cursor:"pointer",fontSize:11},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background="transparent",e.currentTarget.style.color="var(--text-muted)"},children:[(0,n.jsx)(i.Z,{size:12,"aria-hidden":"true"}),s("desktop.subagentsBack")]})}),(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6,marginTop:4,minWidth:0},children:[(0,n.jsx)("span",{"aria-hidden":"true",style:{width:8,height:8,flexShrink:0,borderRadius:"50%",background:y,boxShadow:"running"===e.status?`0 0 0 0 ${y}`:"none",animation:"running"===e.status?"subagent-pulse 1.4s ease-out infinite":"none"}}),(0,n.jsx)("span",{style:{fontSize:12,fontWeight:700,color:"var(--text)",fontFamily:"var(--font-mono)",flexShrink:0},children:e.agentType}),(0,n.jsx)("span",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:11.5,color:"var(--text-muted)"},children:e.description})]}),(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10,marginTop:3,fontSize:10.5,fontFamily:"var(--font-mono)",color:"var(--text-dim)"},children:[void 0!==e.toolUses&&e.toolUses>0&&(0,n.jsxs)("span",{children:[e.toolUses," tool",1===e.toolUses?"":"s"]}),void 0!==v&&v>0&&(0,n.jsxs)("span",{children:[void 0===v?"":v>=1e6?`${(v/1e6).toFixed(1)}M`:v>=1e3?`${(v/1e3).toFixed(1)}k`:`${v}`," tokens"]}),void 0!==k&&(0,n.jsx)("span",{children:function(e){if(void 0===e)return"";if(e<1e3)return`${e}ms`;let t=Math.floor(e/1e3);if(t<60)return`${t}s`;let o=Math.floor(t/60),n=t%60;return n>0?`${o}m ${n}s`:`${o}m`}(k)}),(0,n.jsx)("span",{style:{color:y},children:s(`desktop.subagentsStatus${"running"===e.status?"Running":"completed"===e.status?"Completed":"failed"===e.status?"Failed":"Stopped"}`)})]})]}),(0,n.jsx)("div",{ref:g,onScroll:e=>{let t=e.currentTarget;m.current=t.scrollHeight-t.scrollTop-t.clientHeight<40},style:{flex:1,minHeight:0,overflowY:"auto",overflowX:"hidden",padding:"8px 10px",background:"var(--bg)"},children:c?(0,n.jsxs)("div",{style:{fontSize:12,color:"var(--text-dim)",padding:"12px 4px"},children:[s("desktop.loading"),"…"]}):u?(0,n.jsx)("div",{style:{fontSize:12,color:"#ef4444",padding:"12px 4px"},children:u}):0===l.length?(0,n.jsx)("div",{style:{fontSize:12,color:"var(--text-dim)",padding:"12px 4px"},children:"running"===e.status?s("desktop.subagentsWaitingFirstMessage"):s("desktop.subagentsNoTranscript")}):(0,n.jsx)("div",{style:{paddingBottom:8},children:l.map((e,t)=>(0,n.jsx)(ag,{line:e,roleLabel:a},t))})})]})}function af({tabs:e,activeTabId:t,onSelectTab:o,onCloseTab:s}){let{t:i}=(0,F.s)(),[a,l]=(0,r.useState)(null);return(0,n.jsx)("div",{style:{display:"flex",alignItems:"flex-end",background:"var(--bg-panel)",overflowX:"auto",flexShrink:0,height:36},children:e.map(e=>{let r=e.id===t;return(0,n.jsxs)("div",{onClick:()=>o(e.id),onMouseDown:e=>{1===e.button&&e.preventDefault()},onAuxClick:t=>{1===t.button&&(t.preventDefault(),t.stopPropagation(),s(e.id))},style:{display:"flex",alignItems:"center",gap:6,height:36,paddingLeft:12,paddingRight:6,borderRight:"1px solid var(--border)",background:r?"var(--bg)":"var(--bg-panel)",cursor:"pointer",fontSize:12,color:r?"var(--text)":"var(--text-muted)",whiteSpace:"nowrap",maxWidth:180,minWidth:80,flexShrink:0,userSelect:"none",transition:"background 0.1s, color 0.1s"},children:[(0,n.jsx)("span",{style:{flexShrink:0,opacity:r?1:.7,display:"flex",alignItems:"center"},children:er(e.label,13)}),(0,n.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",flex:1,fontWeight:r?500:400},title:e.filePath,children:e.label}),(0,n.jsx)("button",{onClick:t=>{t.stopPropagation(),s(e.id)},onMouseEnter:()=>l(e.id),onMouseLeave:()=>l(null),style:{display:"flex",alignItems:"center",justifyContent:"center",width:24,height:24,background:a===e.id?"var(--bg-hover)":"transparent",border:"none",borderRadius:4,color:a===e.id?"var(--text)":"var(--text-dim)",cursor:"pointer",padding:0,flexShrink:0,transition:"background 0.1s, color 0.1s"},title:i("desktop.closeTab"),"aria-label":i("desktop.closeTabWithLabel",{label:e.label}),children:(0,n.jsx)(p.X,{size:11,"aria-hidden":"true"})})]},e.id)})})}var ax=o(27289),ak=o(93534),av=o(45781),ay=o(68731),ab=o(93912),aw=o(23675),aj=o(48716),aS=o(47013),aC=o(51265);let aT={"restore-script":"restore","generate-cmd":"cmd",keep:"keep","keep-with-warning":"warning",manual:"manual"};function aR({cwd:e}){let{t}=(0,F.s)(),o=(0,r.useRef)(null),[s,i]=(0,r.useState)(!0),[a,l]=(0,r.useState)(!1),[d,c]=(0,r.useState)(!1),[p,u]=(0,r.useState)(null),[h,g]=(0,r.useState)(null),[m,f]=(0,r.useState)(new Set),[x,k]=(0,r.useState)(new Set),[v,y]=(0,r.useState)(!1),[b,w]=(0,r.useState)(null),[j,S]=(0,r.useState)(!1),[C,T]=(0,r.useState)(null),[R,z]=(0,r.useState)([]),[I,M]=(0,r.useState)(""),[P,E]=(0,r.useState)(null),[D,W]=(0,r.useState)(null);(0,r.useEffect)(()=>{fetch("/api/models").then(e=>e.json()).then(e=>{let t=e.models??[];z(t),t.length>0&&M(`${t[0].provider}/${t[0].id}`)}).catch(()=>{})},[]);let A=(0,r.useCallback)(async()=>{c(!0),u(null);try{let e=await fetch("/api/backup/export",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({includeSecrets:s,includeSessions:a})});if(!e.ok){let t=await e.json();u(t.error??`HTTP ${e.status}`);return}let t=await e.blob(),o=(e.headers.get("Content-Disposition")??"").match(/filename="?([^";]+)"?/),n=URL.createObjectURL(t),r=document.createElement("a");r.href=n,r.download=o?.[1]??"pi-backup.zip",document.body.appendChild(r),r.click(),r.remove(),URL.revokeObjectURL(n)}catch{u(String(t("desktop.backupExportFailed")))}finally{c(!1)}},[s,a,t]),N=(0,r.useCallback)(async e=>{if(e){w(null),T(null),g(null);try{let o=new FormData;o.append("phase","parse"),o.append("file",e);let n=await fetch("/api/backup/import",{method:"POST",body:o}),r=await n.json();if(!n.ok||r.error)return void w(r.error??`HTTP ${n.status}`);if("preview"!==r.phase||!r.preview)return void w(String(t("desktop.backupImportFailed")));g(r),f(new Set(r.preview.categories)),k(new Set),y(!1)}catch{w(String(t("desktop.backupImportFailed")))}}},[t]),$=(0,r.useCallback)(async()=>{if(h){S(!0),w(null);try{let e=new FormData;e.append("phase","restore"),e.append("token",h.token),e.append("selections",JSON.stringify({categories:[...m],skippedMcpServers:[...x],reinstallNpm:v}));let n=await fetch("/api/backup/import",{method:"POST",body:e}),r=await n.json();if(!n.ok||r.error)return void w(r.error??`HTTP ${n.status}`);if("report"!==r.phase||!r.report)return void w(String(t("desktop.backupRestoreFailed")));T(r.report),g(null),o.current&&(o.current.value="")}catch{w(String(t("desktop.backupRestoreFailed")))}finally{S(!1)}}},[h,m,x,v,t]),L=(0,r.useCallback)(async o=>{if(o.installPrompt&&e){E(o.name),W(null);try{let t=I.indexOf("/"),n=t>0?I.slice(0,t):void 0,r=t>0?I.slice(t+1):void 0,s=await fetch("/api/agent/new",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e,message:o.installPrompt,provider:n,modelId:r})}),i=await s.json();if(!s.ok||i.error)return void w(i.error??`HTTP ${s.status}`);W({server:o.name,sessionId:i.sessionId})}catch{w(String(t("desktop.backupInstallSessionFailed")))}finally{E(null)}}},[e,I,t]),O=e=>"win32"===e?"Windows":"darwin"===e?"macOS":"Linux";return(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",flex:1,minWidth:0,minHeight:0,overflowY:"auto"},children:[(0,n.jsx)("header",{style:{padding:"18px 22px 14px",borderBottom:"1px solid var(--border)"},children:(0,n.jsx)("h1",{style:{margin:0,fontSize:16,fontWeight:700,color:"var(--text)"},children:t("desktop.backup")})}),(0,n.jsxs)("section",{style:{padding:"18px 22px",borderBottom:"1px solid var(--border)"},children:[(0,n.jsx)("h2",{style:{margin:0,fontSize:13,fontWeight:600,color:"var(--text)"},children:t("desktop.backupExportTitle")}),(0,n.jsx)("p",{style:{margin:"6px 0 12px",fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:t("desktop.backupExportDescription")}),(0,n.jsxs)("label",{style:{display:"flex",gap:8,alignItems:"flex-start",cursor:"pointer",marginBottom:8},children:[(0,n.jsx)("input",{type:"checkbox",checked:s,onChange:e=>i(e.target.checked),style:{marginTop:2}}),(0,n.jsxs)("span",{style:{fontSize:12,color:"var(--text)"},children:[t("desktop.backupIncludeSecrets"),(0,n.jsx)("span",{style:{display:"block",fontSize:11,color:"#ef4444"},children:t("desktop.backupSecretsWarning")})]})]}),(0,n.jsxs)("label",{style:{display:"flex",gap:8,alignItems:"flex-start",cursor:"pointer",marginBottom:14},children:[(0,n.jsx)("input",{type:"checkbox",checked:a,onChange:e=>l(e.target.checked),style:{marginTop:2}}),(0,n.jsxs)("span",{style:{fontSize:12,color:"var(--text)"},children:[t("desktop.backupIncludeSessions"),(0,n.jsx)("span",{style:{display:"block",fontSize:11,color:"var(--text-dim)"},children:t("desktop.backupSessionsHint")})]})]}),(0,n.jsxs)("button",{type:"button",onClick:A,disabled:d,style:{display:"inline-flex",alignItems:"center",gap:7,padding:"8px 14px",background:"var(--accent)",border:"none",borderRadius:6,color:"#fff",fontSize:12,fontWeight:600,cursor:d?"wait":"pointer"},children:[(0,n.jsx)(aS.f,{size:15,"aria-hidden":"true"}),d?t("desktop.backupExporting"):t("desktop.backupExportButton")]}),p&&(0,n.jsx)("p",{style:{margin:"8px 0 0",fontSize:11,color:"#ef4444"},children:p})]}),(0,n.jsxs)("section",{style:{padding:"18px 22px"},children:[(0,n.jsx)("h2",{style:{margin:0,fontSize:13,fontWeight:600,color:"var(--text)"},children:t("desktop.backupImportTitle")}),(0,n.jsx)("p",{style:{margin:"6px 0 12px",fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:t("desktop.backupImportDescription")}),(0,n.jsx)("input",{ref:o,type:"file",accept:".zip,application/zip",onChange:e=>N(e.target.files?.[0]),style:{display:"none"}}),(0,n.jsxs)("button",{type:"button",onClick:()=>o.current?.click(),style:{display:"inline-flex",alignItems:"center",gap:7,padding:"8px 14px",background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:6,color:"var(--text)",fontSize:12,fontWeight:600,cursor:"pointer"},children:[(0,n.jsx)(aC._,{size:15,"aria-hidden":"true"}),t("desktop.backupImportButton")]}),b&&(0,n.jsx)("p",{style:{margin:"0 0 10px",fontSize:11,color:"#ef4444",lineHeight:1.5},children:b}),h&&(0,n.jsxs)("div",{style:{border:"1px solid var(--border)",borderRadius:8,padding:14,background:"var(--bg-panel)",display:"flex",flexDirection:"column",gap:12},children:[(0,n.jsxs)("div",{style:{fontSize:12,color:"var(--text-muted)",lineHeight:1.6},children:[(0,n.jsxs)("span",{style:{color:"var(--text)",fontWeight:600},children:[t("desktop.backupManifest"),":"]})," ",new Date(h.preview.manifest.createdAt).toLocaleString()," \xb7 ",O(h.preview.manifest.sourcePlatform)," →",O(navigator.platform.includes("Win")?"win32":navigator.platform.includes("Linux")?"linux":"darwin")," \xb7 pi-web ",h.preview.manifest.piWebVersion,h.preview.manifest.includeSecrets?"":` \xb7 ${t("desktop.backupNoSecrets")}`]}),(0,n.jsxs)("div",{children:[(0,n.jsx)("div",{style:{fontSize:11,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:6},children:t("desktop.backupCategories")}),(0,n.jsx)("div",{style:{display:"flex",gap:14,flexWrap:"wrap"},children:h.preview.categories.map(e=>(0,n.jsxs)("label",{style:{display:"flex",gap:6,alignItems:"center",cursor:"pointer",fontSize:12,color:"var(--text)"},children:[(0,n.jsx)("input",{type:"checkbox",checked:m.has(e),onChange:t=>{let o=new Set(m);t.target.checked?o.add(e):o.delete(e),f(o)}}),t(`desktop.backupCategory${e}`)]},e))})]}),h.preview.servers.length>0&&(0,n.jsxs)("div",{children:[(0,n.jsx)("div",{style:{fontSize:11,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:6},children:t("desktop.backupMcpServers")}),(0,n.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:h.preview.servers.map(o=>(0,n.jsxs)("div",{style:{display:"flex",alignItems:"flex-start",gap:8,fontSize:12},children:[(0,n.jsx)("input",{type:"checkbox",checked:!x.has(o.name),onChange:e=>{let t=new Set(x);e.target.checked?t.delete(o.name):t.add(o.name),k(t)},style:{marginTop:2}}),(0,n.jsxs)("div",{style:{flex:1,minWidth:0,display:"flex",flexDirection:"column",gap:2},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[(0,n.jsx)("code",{style:{fontSize:11,fontFamily:"var(--font-mono)",color:"var(--text)"},children:o.name}),(0,n.jsx)("span",{style:{fontSize:10,padding:"1px 6px",borderRadius:8,background:"manual"===o.action||"keep-with-warning"===o.action?"rgba(239,68,68,0.15)":"var(--bg-selected)",color:"manual"===o.action||"keep-with-warning"===o.action?"#ef4444":"var(--text-muted)"},children:aT[o.action]})]}),(0,n.jsxs)("div",{style:{fontSize:11,color:"var(--text-dim)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[(0,n.jsx)("code",{style:{fontFamily:"var(--font-mono)"},children:o.original.command}),o.adapted&&o.adapted.command!==o.original.command&&(0,n.jsxs)(n.Fragment,{children:[" → ",(0,n.jsx)("code",{style:{fontFamily:"var(--font-mono)",color:"var(--text)"},children:o.adapted.command})]})]}),o.reason&&(0,n.jsx)("div",{style:{fontSize:11,color:"#ef4444"},children:o.reason}),"manual"===o.action&&o.installPrompt&&e&&(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,marginTop:2,flexWrap:"wrap"},children:[(0,n.jsx)("select",{value:I,onChange:e=>M(e.target.value),style:{fontSize:11,padding:"4px 6px",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:4,color:"var(--text)",maxWidth:220},title:t("desktop.backupInstallModel"),children:R.map(e=>(0,n.jsxs)("option",{value:`${e.provider}/${e.id}`,children:[e.provider,"/",e.name||e.id]},`${e.provider}/${e.id}`))}),(0,n.jsx)("button",{type:"button",disabled:P===o.name,onClick:()=>L(o),style:{padding:"4px 10px",fontSize:11,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:4,color:"var(--text)",cursor:P===o.name?"wait":"pointer"},children:P===o.name?"…":t("desktop.backupInstallSession")}),D?.server===o.name&&(0,n.jsx)("a",{href:`?session=${encodeURIComponent(D.sessionId)}`,style:{fontSize:11,color:"var(--accent)"},children:t("desktop.backupOpenSession")})]})]})]},o.name))})]}),h.preview.npmPackages.length>0&&(0,n.jsxs)("div",{children:[(0,n.jsx)("div",{style:{fontSize:11,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:6},children:t("desktop.backupNpmPackages")}),(0,n.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:4,marginBottom:6},children:h.preview.npmPackages.map(e=>(0,n.jsx)("code",{style:{fontSize:11,fontFamily:"var(--font-mono)",color:"var(--text)"},children:e},e))}),(0,n.jsxs)("label",{style:{display:"flex",gap:6,alignItems:"flex-start",cursor:"pointer",fontSize:12,color:"var(--text)",lineHeight:1.4},children:[(0,n.jsx)("input",{type:"checkbox",checked:v,onChange:e=>y(e.target.checked),style:{marginTop:2}}),(0,n.jsxs)("span",{children:[t("desktop.backupReinstallNpm"),(0,n.jsx)("span",{style:{display:"block",fontSize:11,color:"var(--text-dim)"},children:t("desktop.backupReinstallNpmHint")})]})]})]}),h.preview.warnings.length>0&&(0,n.jsx)("div",{style:{fontSize:11,color:"#ef4444",lineHeight:1.5},children:h.preview.warnings.map((e,t)=>(0,n.jsxs)("div",{children:["⚠ ",e]},t))}),(0,n.jsxs)("div",{style:{display:"flex",gap:8},children:[(0,n.jsxs)("button",{type:"button",onClick:$,disabled:j||0===m.size,style:{display:"inline-flex",alignItems:"center",gap:7,padding:"8px 14px",background:"var(--accent)",border:"none",borderRadius:6,color:"#fff",fontSize:12,fontWeight:600,cursor:j?"wait":"pointer",opacity:0===m.size?.5:1},children:[(0,n.jsx)(aC._,{size:15,"aria-hidden":"true"}),j?t("desktop.backupRestoring"):t("desktop.backupRestoreButton")]}),(0,n.jsx)("button",{type:"button",onClick:()=>{g(null),o.current&&(o.current.value="")},disabled:j,style:{padding:"8px 14px",background:"none",border:"1px solid var(--border)",borderRadius:6,color:"var(--text-muted)",fontSize:12,cursor:"pointer"},children:t("desktop.cancel")})]})]}),C&&(0,n.jsxs)("div",{style:{border:"1px solid var(--border)",borderRadius:8,padding:14,background:"var(--bg-panel)",display:"flex",flexDirection:"column",gap:10},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,fontSize:13,fontWeight:600,color:"var(--text)"},children:[(0,n.jsx)(nd.W,{size:16,"aria-hidden":"true"}),t("desktop.backupRestoreReport")]}),C.restored.length>0&&(0,n.jsxs)("div",{children:[(0,n.jsxs)("div",{style:{fontSize:11,fontWeight:600,color:"#4ade80",marginBottom:4},children:["✓ ",t("desktop.backupReportRestored")]}),(0,n.jsx)("div",{style:{fontSize:11,color:"var(--text-muted)",lineHeight:1.6,fontFamily:"var(--font-mono)",wordBreak:"break-all"},children:C.restored.join("\n")})]}),C.needsRestart.length>0&&(0,n.jsxs)("div",{children:[(0,n.jsxs)("div",{style:{fontSize:11,fontWeight:600,color:"#fbbf24",marginBottom:4},children:["\uD83D\uDD04 ",t("desktop.backupReportRestart")]}),(0,n.jsx)("div",{style:{fontSize:11,color:"var(--text-muted)",lineHeight:1.6,fontFamily:"var(--font-mono)"},children:C.needsRestart.join("\n")})]}),C.manual.length>0&&(0,n.jsxs)("div",{children:[(0,n.jsxs)("div",{style:{fontSize:11,fontWeight:600,color:"#ef4444",marginBottom:4},children:[(0,n.jsx)(G.N,{size:12,style:{verticalAlign:-2},"aria-hidden":"true"})," ",t("desktop.backupReportManual")]}),C.manual.map((e,t)=>(0,n.jsxs)("div",{style:{fontSize:11,color:"var(--text-muted)",lineHeight:1.6},children:[(0,n.jsx)("strong",{style:{color:"var(--text)"},children:e.server}),": ",e.message]},t))]}),C.warnings.length>0&&(0,n.jsx)("div",{style:{fontSize:11,color:"#ef4444",lineHeight:1.6},children:C.warnings.map((e,t)=>(0,n.jsxs)("div",{children:["⚠ ",e]},t))}),C.needsRestart.length>0&&(0,n.jsx)("p",{style:{margin:0,fontSize:11,color:"#fbbf24",lineHeight:1.5},children:t("desktop.backupRestartHint")})]})]})]})}let az={position:"relative",width:40,height:22,borderRadius:11,border:"none",cursor:"pointer",padding:0,flexShrink:0,transition:"background 0.18s ease",outline:"none"},aI={position:"absolute",top:3,width:16,height:16,borderRadius:"50%",background:"#fff",transition:"left 0.18s ease, transform 0.18s ease",boxShadow:"0 1px 3px rgba(0,0,0,0.18)"};function aM({checked:e,onChange:t,label:o,description:r}){return(0,n.jsxs)("label",{style:{display:"flex",alignItems:r?"flex-start":"center",justifyContent:"space-between",gap:12,padding:"12px 14px",borderRadius:7,cursor:"pointer",userSelect:"none",transition:"background 0.12s",margin:"0 -14px"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.background="transparent"},children:[(0,n.jsxs)("span",{style:{flex:1,minWidth:0},children:[(0,n.jsx)("span",{style:{display:"block",fontSize:13,fontWeight:550,color:"var(--text)",lineHeight:1.4},children:o}),r&&(0,n.jsx)("span",{style:{display:"block",fontSize:11,lineHeight:1.5,color:"var(--text-muted)",marginTop:2},children:r})]}),(0,n.jsx)("button",{type:"button",role:"switch","aria-checked":e,onClick:o=>{o.preventDefault(),t(!e)},style:{...az,background:e?"var(--accent)":"color-mix(in srgb, var(--border) 70%, var(--bg))"},children:(0,n.jsx)("span",{style:{...aI,left:e?21:3}})})]})}function aP({title:e,description:t,children:o}){return(0,n.jsxs)("section",{style:{padding:"20px 22px",borderBottom:"1px solid var(--border)"},children:[(0,n.jsx)("h2",{style:{margin:0,fontSize:14,fontWeight:650,color:"var(--text)"},children:e}),(0,n.jsx)("p",{style:{margin:"5px 0 14px",fontSize:12,lineHeight:1.5,color:"var(--text-muted)"},children:t}),(0,n.jsx)("div",{children:o})]})}let aE="pi-input-shortcut";function aF(){try{let e=localStorage.getItem(aE);return"ctrl-enter"===e?"ctrl-enter":"enter"}catch{return"enter"}}function aD(){let{t:e}=(0,F.s)(),[t,o]=(0,r.useState)(aF);(0,r.useEffect)(()=>{let e=()=>o(aF());return window.addEventListener("storage",e),()=>window.removeEventListener("storage",e)},[]);let s=(0,r.useCallback)(e=>{o(e);try{localStorage.setItem(aE,e),window.dispatchEvent(new StorageEvent("storage",{key:aE,newValue:e}))}catch{}},[]);return(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",flex:1,minWidth:0,minHeight:0,overflowY:"auto"},children:[(0,n.jsx)("header",{style:{padding:"18px 22px 14px",borderBottom:"1px solid var(--border)"},children:(0,n.jsx)("h1",{style:{margin:0,fontSize:16,fontWeight:700,color:"var(--text)"},children:e("desktop.chat")})}),(0,n.jsx)(aP,{title:e("desktop.inputShortcut"),description:e("desktop.inputShortcutDescription"),children:(0,n.jsx)(aM,{checked:"ctrl-enter"===t,onChange:e=>s(e?"ctrl-enter":"enter"),label:e("desktop.useCtrlEnter"),description:e("desktop.useCtrlEnterDescription")})})]})}var aW=o(95650),aA=o(55803),aN=o(23602),a$=o(18613),aL=o(12779);let aO={display:"flex",gap:6,flexWrap:"wrap"};function aH(e,t,o){return{display:"inline-flex",alignItems:"center",gap:7,padding:"7px 14px",border:`1px solid ${e?"var(--accent)":t?"var(--border-hover)":"var(--border)"}`,borderRadius:8,background:e?"color-mix(in srgb, var(--accent) 12%, var(--bg))":t?"var(--bg-hover)":"var(--bg-card)",color:e?"var(--accent)":t?"var(--text)":"var(--text-muted)",fontSize:13,fontWeight:e?600:400,cursor:o?"not-allowed":"pointer",opacity:o?.5:1,transition:"border-color 0.15s, background 0.15s, color 0.15s",outline:"none",whiteSpace:"nowrap"}}function aB({icon:e,label:t,actions:o}){return(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:10,width:"100%"},children:[(0,n.jsx)("span",{style:{color:"var(--text-dim)",display:"inline-flex",flexShrink:0},children:e}),(0,n.jsx)("span",{style:{fontSize:11,fontWeight:700,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.06em"},children:t}),o&&(0,n.jsx)("span",{style:{display:"inline-flex",alignItems:"center",gap:12,marginLeft:"auto"},children:o})]})}let aU={display:"inline-flex",alignItems:"center",gap:6,padding:0,border:0,background:"transparent",color:"var(--accent)",fontSize:11,cursor:"pointer",whiteSpace:"nowrap"},a_={onMouseEnter:e=>{e.currentTarget.style.textDecoration="underline"},onMouseLeave:e=>{e.currentTarget.style.textDecoration="none"}};function aq({title:e,description:t,children:o}){return(0,n.jsxs)("section",{style:{padding:"20px 22px",borderBottom:"1px solid var(--border)"},children:[(0,n.jsx)("h2",{style:{margin:0,fontSize:14,fontWeight:650,color:"var(--text)"},children:e}),(0,n.jsx)("p",{style:{margin:"5px 0 16px",fontSize:12,lineHeight:1.5,color:"var(--text-muted)"},children:t}),o]})}function aV({depth:e}){let t=e/100;return(0,n.jsxs)("svg",{width:14,height:14,viewBox:"0 0 14 14",style:{flexShrink:0},children:[(0,n.jsx)("rect",{x:1.5,y:1.5,width:11,height:11,rx:2.5,style:{fill:"none",stroke:"var(--text-dim)",strokeWidth:1+2*t,opacity:.2+.8*t}}),(0,n.jsx)("rect",{x:4,y:4,width:6,height:6,rx:1,style:{fill:"var(--text-dim)",opacity:.05+.35*t}})]})}function aK({hasDark:e,hasLight:t,darkColor:o,lightColor:r,t:s}){return(0,n.jsxs)("span",{style:{display:"inline-flex",gap:3,alignItems:"center",flexShrink:0},children:[e&&(0,n.jsx)("span",{title:s("desktop.darkVariant"),style:{display:"inline-block",width:7,height:7,borderRadius:"50%",background:o??"#7c6f64"}}),t&&(0,n.jsx)("span",{title:s("desktop.lightVariant"),style:{display:"inline-block",width:7,height:7,borderRadius:"50%",background:r??"#d5c4a1",border:"1px solid rgba(0,0,0,0.1)"}})]})}function aG(){let{mode:e,resolvedMode:t,themeName:o,setMode:s,setTheme:i,previewTheme:a,clearPreview:l,isThemeCached:d,borderDepth:c,setBorderDepth:p}=ov(),{locale:u,setLocale:h,t:g}=(0,F.s)(),[m,f]=(0,r.useState)([]),[x,k]=(0,r.useState)(!0),[v,y]=(0,r.useState)(null),[b,w]=(0,r.useState)(null);(0,r.useEffect)(()=>{let e=!1;return fetch("/api/themes").then(e=>e.ok?e.json():null).then(t=>{!e&&t&&f(t.themeSets)}).catch(()=>{}).finally(()=>{e||k(!1)}),()=>{e=!0}},[]);let j=(0,r.useCallback)(e=>{y(e),i(e).finally(()=>y(null))},[i]),S=(0,r.useRef)(null),C=(0,r.useCallback)(e=>{w(e),null!==S.current&&window.clearTimeout(S.current),S.current=window.setTimeout(()=>{S.current=null,null!==e?d(e)&&a(e):l()},160)},[a,l,d]),T=(0,r.useCallback)(e=>{s(e)},[s]),R=(0,r.useCallback)(()=>{window.piDesktop?.openThemeFolder()},[]),z=(0,r.useCallback)(()=>{window.piDesktop?window.piDesktop.openThemeDocs():window.open("https://pi.dev/docs/latest/themes","_blank","noopener,noreferrer")},[]);return(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",flex:1,minWidth:0,minHeight:0,overflowY:"auto"},children:[(0,n.jsx)("header",{style:{padding:"18px 22px 14px",borderBottom:"1px solid var(--border)"},children:(0,n.jsx)("h1",{style:{margin:0,fontSize:16,fontWeight:700,color:"var(--text)"},children:g("desktop.display")})}),(0,n.jsxs)(aq,{title:g("desktop.theme"),description:g("desktop.themeDescription"),children:[(0,n.jsx)(aB,{icon:(0,n.jsx)(aW.p,{size:14,weight:"fill"}),label:g("desktop.colorScheme"),actions:(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("button",{type:"button",onClick:R,style:aU,...a_,children:[(0,n.jsx)(aA.N,{size:12,weight:"regular","aria-hidden":"true"}),g("desktop.openThemeFolder")]}),(0,n.jsxs)("button",{type:"button",onClick:z,style:aU,...a_,children:[(0,n.jsx)(aN.B,{size:12,weight:"regular","aria-hidden":"true"}),g("desktop.learnPiThemes")]})]})}),x?(0,n.jsx)("span",{style:{fontSize:12,color:"var(--text-dim)"},children:g("desktop.loadingThemes")}):(0,n.jsxs)("div",{style:aO,children:[(0,n.jsx)("button",{type:"button",onClick:()=>j(""),disabled:null!==v,style:aH(""===o,"__default__"===b,null!==v),onMouseEnter:()=>C(""),onMouseLeave:()=>C(null),children:g("desktop.defaultTheme")}),m.map(e=>(0,n.jsxs)("button",{type:"button",onClick:()=>j(e.name),disabled:null!==v,style:aH(o===e.name,b===e.name,v===e.name),onMouseEnter:()=>C(e.name),onMouseLeave:()=>C(null),children:[e.displayName,(0,n.jsx)(aK,{hasDark:e.hasDark,hasLight:e.hasLight,darkColor:e.accent,lightColor:e.accentLight,t:g})]},e.name))]}),(0,n.jsxs)("div",{style:{marginTop:20},children:[(0,n.jsx)(aB,{icon:(0,n.jsx)(aV,{depth:c}),label:`${g("desktop.borderVisibility")} (${c})`}),(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10},children:[(0,n.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",flexShrink:0},children:g("desktop.borderSubtle")}),(0,n.jsx)("input",{type:"range",min:0,max:100,step:1,value:c,onChange:e=>p(Number(e.target.value)),style:{flex:1,accentColor:"var(--accent)",height:6,cursor:"pointer"}}),(0,n.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",flexShrink:0},children:g("desktop.borderBold")})]}),(0,n.jsx)("div",{style:{marginTop:10,display:"flex",gap:10},children:[0,25,50,75,100].map(e=>{let t=c===e,o=e<=50?`color-mix(in srgb, var(--border-orig) ${2*e}%, var(--bg) ${100-2*e}%)`:`color-mix(in srgb, var(--border-orig) ${100-(e-50)*2}%, var(--text) ${(e-50)*2}%)`;return(0,n.jsx)("div",{onClick:()=>p(e),style:{width:28,height:20,border:`2px solid ${t?"var(--accent)":o}`,borderRadius:5,background:"var(--bg-card)",cursor:"pointer",transition:"border-color 0.1s"}},e)})})]}),(0,n.jsxs)("div",{style:{marginTop:20},children:[(0,n.jsx)(aB,{icon:"dark"===t?(0,n.jsx)(a$.A,{size:14,weight:"fill"}):(0,n.jsx)(aL.b,{size:14,weight:"fill"}),label:g("desktop.appearanceMode")}),(0,n.jsx)("div",{style:aO,children:[{value:"light",icon:(0,n.jsx)(aL.b,{size:15,weight:"light"===e?"fill":"regular"})},{value:"dark",icon:(0,n.jsx)(a$.A,{size:15,weight:"dark"===e?"fill":"regular"})},{value:"system",icon:(0,n.jsx)(ak.V,{size:15,weight:"system"===e?"fill":"regular"})}].map(t=>{let o=e===t.value;return(0,n.jsxs)("button",{type:"button",onClick:()=>T(t.value),style:aH(o,b===`mode:${t.value}`),onMouseEnter:()=>w(`mode:${t.value}`),onMouseLeave:()=>w(null),children:[t.icon,g(`desktop.${t.value}`)]},t.value)})})]}),!x&&0===m.length&&(0,n.jsxs)("p",{style:{margin:"14px 0 0",fontSize:11,color:"var(--text-dim)",lineHeight:1.5},children:[g("desktop.noCustomThemes")," ",g("desktop.noCustomThemesHint")," ",(0,n.jsx)("code",{style:{fontSize:10,background:"var(--bg-secondary)",padding:"1px 5px",borderRadius:3,fontFamily:"var(--font-mono)"},children:"~/.pi/agent/themes/*.json"})," ",g("desktop.noCustomThemesHint2")]})]}),(0,n.jsx)(aq,{title:g("desktop.language"),description:g("desktop.languageDescription"),children:(0,n.jsx)("div",{style:aO,children:["en","zh-CN"].map(e=>(0,n.jsx)("button",{type:"button",onClick:()=>h("zh-CN"===e?"zh-CN":"en"),style:aH("zh-CN"===e?"zh-CN"===u:"zh-CN"!==u,b===`lang:${e}`),onMouseEnter:()=>w(`lang:${e}`),onMouseLeave:()=>w(null),children:"en"===e?g("desktop.english"):g("desktop.chinese")},e))})})]})}var aJ=o(94638);function aY({children:e}){return(0,n.jsx)("div",{style:{borderRadius:12,border:"1px solid var(--border)",background:"color-mix(in srgb, var(--bg-panel) 55%, transparent)",overflow:"hidden"},children:e})}function aX({children:e}){return(0,n.jsx)("div",{style:{padding:"0 14px"},children:(0,n.jsx)("div",{style:{borderBottom:"1px solid var(--border)"},children:e})})}function aZ({children:e}){return(0,n.jsx)("div",{style:{padding:"0 14px"},children:e})}function aQ({children:e}){return(0,n.jsx)("div",{style:{display:"flex",gap:8,borderRadius:10,border:"1px solid var(--border)",background:"color-mix(in srgb, var(--bg-panel) 55%, transparent)",padding:"10px 12px",fontSize:12,lineHeight:1.5,color:"var(--text-muted)"},children:e})}let a0=[{value:"normal",labelKey:"modes.collabNormal"},{value:"plan",labelKey:"modes.collabPlan"},{value:"goal",labelKey:"modes.collabGoal"}],a1=[{value:"economy",labelKey:"modes.tokenEconomy"},{value:"full",labelKey:"modes.tokenFull"},{value:"delivery",labelKey:"modes.tokenDelivery"}],a2=[{value:"ask",labelKey:"modes.approvalAsk"},{value:"auto",labelKey:"modes.approvalAuto"},{value:"yolo",labelKey:"modes.approvalYolo"}];function a4({options:e,value:t,onChange:o,disabled:r,accentFor:s}){let{t:i}=(0,F.s)();return(0,n.jsx)("div",{role:"radiogroup",style:{display:"flex",border:"1px solid var(--border)",borderRadius:8,overflow:"hidden",height:28,flexShrink:0},children:e.map(e=>{let a=e.value===t,l=s?.(e.value);return(0,n.jsx)("button",{type:"button",role:"radio","aria-checked":a,disabled:r,onClick:()=>{e.value!==t&&o(e.value)},style:{display:"flex",alignItems:"center",justifyContent:"center",height:"100%",padding:"0 12px",background:a?"var(--bg-selected)":"none",border:"none",color:a?l??"var(--accent)":"var(--text-muted)",cursor:r?"not-allowed":"pointer",fontSize:11.5,fontWeight:a?650:500,opacity:r?.5:1,whiteSpace:"nowrap",transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{a||r||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{a||(e.currentTarget.style.background="none")},children:i(e.labelKey)},e.value)})})}function a6(){let{t:e}=(0,F.s)(),[t,o]=(0,r.useState)({tasksBoard:!0}),[s,i]=(0,r.useState)(null),[a,l]=(0,r.useState)(!1),[d,c]=(0,r.useState)(!1);(0,r.useEffect)(()=>{let e=!1;return(async()=>{try{let[t,n]=await Promise.all([fetch("/api/features"),fetch("/api/modes")]);if(!e&&t.ok){let e=await t.json();o(t=>({...t,...e}))}if(!e&&n.ok){let e=await n.json();i({collaborationMode:eN(e.collaborationMode),tokenMode:e$(e.tokenMode),toolApprovalMode:eL(e.toolApprovalMode),permissionRules:e.permissionRules??{allow:[],ask:[],deny:[]}})}e||l(!0)}catch{}})(),()=>{e=!0}},[]);let p=(0,r.useCallback)(async e=>{c(!0);try{let t=await fetch("/api/features",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({tasksBoard:e})});if(t.ok){let e=await t.json();o(t=>({...t,...e.features})),window.dispatchEvent(new CustomEvent("pi:features-changed"))}}catch{}finally{c(!1)}},[]),u=(0,r.useCallback)(async e=>{c(!0);try{let t=await fetch("/api/modes",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(t.ok){let e=await t.json();i(t=>t?{...t,collaborationMode:eN(e.modes?.collaborationMode??t.collaborationMode),tokenMode:e$(e.modes?.tokenMode??t.tokenMode),toolApprovalMode:eL(e.modes?.toolApprovalMode??t.toolApprovalMode),permissionRules:e.modes?.permissionRules??t.permissionRules}:t),window.dispatchEvent(new CustomEvent("pi:modes-changed"))}}catch{}finally{c(!1)}},[]);return(0,n.jsx)("div",{style:{flex:1,overflow:"auto",minWidth:0,padding:"20px 22px",display:"flex",flexDirection:"column",gap:16},children:(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[a?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(aY,{children:(0,n.jsx)(aZ,{children:(0,n.jsx)(aM,{checked:t.tasksBoard,onChange:e=>void p(e),label:(0,n.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:6},children:[(0,n.jsx)(aJ.x,{size:14,"aria-hidden":"true"}),e("desktop.featuresTasksBoard"),(0,n.jsx)("span",{style:{borderRadius:999,background:"rgba(37,99,235,0.12)",color:"var(--accent)",padding:"1px 7px",fontSize:9,fontWeight:700,textTransform:"uppercase",letterSpacing:"0.04em"},children:"Beta"})]}),description:e("desktop.featuresTasksBoardDesc")})})}),s&&(0,n.jsxs)(aY,{children:[(0,n.jsx)(aX,{children:(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:16,padding:"12px 0"},children:[(0,n.jsxs)("div",{style:{minWidth:0},children:[(0,n.jsx)("div",{style:{fontSize:13,fontWeight:600,color:"var(--text)"},children:e("desktop.featuresCollabDefault")}),(0,n.jsx)("div",{style:{fontSize:11,color:"var(--text-muted)",marginTop:2},children:e("desktop.featuresCollabDefaultDesc")})]}),(0,n.jsx)(a4,{options:a0,value:s.collaborationMode,onChange:e=>void u({collaborationMode:e}),disabled:d})]})}),(0,n.jsx)(aX,{children:(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:16,padding:"12px 0"},children:[(0,n.jsxs)("div",{style:{minWidth:0},children:[(0,n.jsx)("div",{style:{fontSize:13,fontWeight:600,color:"var(--text)"},children:e("desktop.featuresTokenDefault")}),(0,n.jsx)("div",{style:{fontSize:11,color:"var(--text-muted)",marginTop:2},children:e("desktop.featuresTokenDefaultDesc")})]}),(0,n.jsx)(a4,{options:a1,value:s.tokenMode,onChange:e=>void u({tokenMode:e}),disabled:d})]})}),(0,n.jsx)(aZ,{children:(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:16,padding:"12px 0"},children:[(0,n.jsxs)("div",{style:{minWidth:0},children:[(0,n.jsx)("div",{style:{fontSize:13,fontWeight:600,color:"var(--text)"},children:e("desktop.featuresApprovalDefault")}),(0,n.jsx)("div",{style:{fontSize:11,color:"var(--text-muted)",marginTop:2},children:e("desktop.featuresApprovalDefaultDesc")})]}),(0,n.jsx)(a4,{options:a2,value:s.toolApprovalMode,onChange:e=>void u({toolApprovalMode:e}),disabled:d,accentFor:e=>"yolo"===e?"var(--accent-red, #ef4444)":void 0})]})})]})]}):(0,n.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)"},children:e("desktop.featuresLoading")}),(0,n.jsx)(aQ,{children:e("desktop.featuresDesc")}),d&&(0,n.jsx)("div",{style:{padding:"0 2px",fontSize:11,color:"var(--text-muted)"},children:e("desktop.featuresSaving")})]})})}var a8=o(76553);function a5({open:e,onClose:t,children:o}){let[s,i]=(0,r.useState)(!1),[a,l]=(0,r.useState)(!1);return((0,r.useEffect)(()=>{if(e)l(!0),requestAnimationFrame(()=>requestAnimationFrame(()=>i(!0)));else{i(!1);let e=setTimeout(()=>l(!1),250);return()=>clearTimeout(e)}},[e]),a)?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("div",{onClick:t,style:{position:"fixed",inset:0,zIndex:1001,background:s?"rgba(0,0,0,0.35)":"rgba(0,0,0,0)",transition:"background 0.25s ease"}}),(0,n.jsxs)("div",{style:{position:"fixed",bottom:0,left:0,right:0,zIndex:1002,maxHeight:"85dvh",borderRadius:"16px 16px 0 0",background:"var(--bg)",boxShadow:"0 -4px 24px rgba(0,0,0,0.15)",transform:s?"translateY(0)":"translateY(100%)",transition:"transform 0.25s cubic-bezier(0.32, 0.72, 0, 1)",display:"flex",flexDirection:"column",overflow:"hidden"},children:[(0,n.jsx)("div",{style:{display:"flex",justifyContent:"center",padding:"10px 0 4px",flexShrink:0},children:(0,n.jsx)("div",{style:{width:36,height:4,borderRadius:2,background:"var(--border)"}})}),(0,n.jsx)("div",{style:{flex:1,overflow:"auto",minHeight:0},children:o})]})]}):null}function a3({onSessionsChanged:e}){let{t}=(0,F.s)(),o=$(),[s,i]=(0,r.useState)(null),[a,l]=(0,r.useState)([]),[d,c]=(0,r.useState)([]),[u,h]=(0,r.useState)(new Set),[g,m]=(0,r.useState)(null),[f,x]=(0,r.useState)({imported:0,skipped:0,errors:0,total:0,done:!1}),[k,v]=(0,r.useState)([]),[y,b]=(0,r.useState)(!1),[w,j]=(0,r.useState)({done:0,total:0}),[S,C]=(0,r.useState)(!1),[T,R]=(0,r.useState)(null),[z,M]=(0,r.useState)(!1),P=(0,r.useCallback)(async()=>{C(!0),R(null);try{let e=await fetch("/api/import/discover"),t=await e.json();if(!e.ok||t.error)throw Error(t.error??`HTTP ${e.status}`);l(t.sources),t.reasonix?.available&&(c(t.reasonix.projects),i("reasonix"))}catch(e){R(e instanceof Error?e.message:String(e))}finally{C(!1)}},[]),[E,D]=(0,r.useState)(!1);(0,r.useEffect)(()=>{E||(D(!0),P())},[E,P]);let W=(0,r.useCallback)(async()=>{if(0!==u.size&&s){C(!0),R(null);try{let e=await fetch("/api/import/execute",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({source:s,projects:[...u]})}),t=await e.json();if(!e.ok||t.error)throw Error(t.error??`HTTP ${e.status}`);m(t.jobId)}catch(e){R(e instanceof Error?e.message:String(e))}finally{C(!1)}}},[s,u]);(0,r.useEffect)(()=>{let t;if(!g)return;let o=!0,n=async()=>{if(o)try{let r=await fetch(`/api/import/status?jobId=${encodeURIComponent(g)}`),s=await r.json();if(!o)return;x({imported:s.imported??0,skipped:s.skipped??0,errors:s.errors??0,total:s.total??0,done:s.done??!1}),s.done&&s.sessionIds&&(v(s.sessionIds),e?.()),s.done||(t=setTimeout(n,800))}catch{o&&(t=setTimeout(n,2e3))}};return n(),()=>{o=!1,clearTimeout(t)}},[g,e]);let A=(0,r.useCallback)(async()=>{if(0===k.length)return;b(!0),j({done:0,total:k.length});let t=0,o=async()=>{for(;t<k.length;){let e=t++,o=k[e];if(o){try{await fetch(`/api/sessions/${encodeURIComponent(o)}/auto-name`,{method:"POST"})}catch{}j({done:e+1,total:k.length})}}},n=Array.from({length:Math.min(4,k.length)},o);await Promise.all(n),b(!1),e?.()},[k,e]);if(f.done&&k.length>0)return(0,n.jsxs)("div",{style:{padding:"18px 22px",display:"flex",flexDirection:"column",gap:14},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10},children:[(0,n.jsx)(nO.r,{size:20,weight:"fill",style:{color:"#4ade80"}}),(0,n.jsx)("span",{style:{fontSize:14,fontWeight:600,color:"var(--text)"},children:t("desktop.importDone")??"导入完成"})]}),(0,n.jsxs)("div",{style:{fontSize:12,color:"var(--text-muted)",lineHeight:1.6},children:[t("desktop.importedSummary",{imported:f.imported})??`成功导入 ${f.imported} 个会话`,f.skipped>0&&(0,n.jsx)("span",{style:{marginLeft:8},children:t("desktop.importSkippedCount",{skipped:f.skipped})??`,${f.skipped} 个跳过`}),f.errors>0&&(0,n.jsx)("span",{style:{marginLeft:8,color:"#ef4444"},children:t("desktop.importErrorsCount",{errors:f.errors})??`,${f.errors} 个失败`})]}),y?(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,fontSize:12,color:"var(--text-muted)"},children:[(0,n.jsx)(_.y,{size:14,style:{animation:"spin 1s linear infinite"}}),t("desktop.importGeneratingTitles")??"正在生成标题…"," ","(",w.done,"/",w.total,")"]}):(0,n.jsxs)("button",{type:"button",onClick:A,style:{display:"inline-flex",alignItems:"center",gap:7,padding:"8px 14px",background:"var(--accent)",border:"none",borderRadius:6,color:"#fff",fontSize:12,fontWeight:600,cursor:"pointer",alignSelf:"flex-start"},children:[(0,n.jsx)(a8.o,{size:15}),t("desktop.importGenerateTitles")??"为导入的会话生成标题"]}),(0,n.jsx)("button",{type:"button",onClick:()=>{m(null),x({imported:0,skipped:0,errors:0,total:0,done:!1}),v([]),b(!1),j({done:0,total:0})},style:{display:"inline-flex",alignItems:"center",gap:7,padding:"8px 14px",background:"none",border:"1px solid var(--border)",borderRadius:6,color:"var(--text-muted)",fontSize:12,cursor:"pointer",alignSelf:"flex-start"},children:t("desktop.importAgain")??"再次导入"})]});let N=(0,n.jsxs)("div",{style:{padding:o?"12px 18px":"18px 22px",display:"flex",flexDirection:"column",gap:14},children:[T&&(0,n.jsxs)("div",{style:{display:"flex",alignItems:"flex-start",gap:8,fontSize:12,color:"#ef4444",lineHeight:1.5},children:[(0,n.jsx)(G.N,{size:14,style:{flexShrink:0,marginTop:1}}),(0,n.jsx)("span",{children:T})]}),!g&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)",lineHeight:1.6},children:t("desktop.importSessionsDesc")??"从其他 AI 编码工具导入历史对话记录到 pi-web。目前支持 Reasonix,更多工具陆续支持中。"}),(0,n.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:a.map(e=>(0,n.jsxs)("label",{style:{display:"flex",alignItems:"center",gap:10,padding:"10px 14px",border:"1px solid var(--border)",borderRadius:8,cursor:"available"===e.status?"pointer":"default",background:s===e.key?"var(--bg-selected)":"var(--bg-panel)",opacity:"unavailable"===e.status?.5:"coming-soon"===e.status?.7:1,transition:"background 0.12s"},children:[(0,n.jsx)("input",{type:"radio",name:"import-source",value:e.key,checked:s===e.key,disabled:"available"!==e.status,onChange:()=>i(e.key)}),(0,n.jsxs)("div",{style:{flex:1},children:[(0,n.jsx)("div",{style:{fontSize:13,fontWeight:600,color:"var(--text)"},children:e.label}),"coming-soon"===e.status&&(0,n.jsx)("div",{style:{fontSize:11,color:"var(--text-dim)",marginTop:1},children:t("desktop.comingSoon")??"即将支持"})]}),"reasonix"===e.key&&d.length>0&&(0,n.jsxs)("span",{style:{fontSize:11,color:"var(--text-muted)"},children:[d.length," ",t("desktop.projects")??"个项目"," \xb7 ",d.reduce((e,t)=>e+t.sessions,0)," ",t("desktop.sessions")??"会话"]})]},e.key))}),"reasonix"===s&&d.length>0&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[(0,n.jsx)("span",{style:{fontSize:12,fontWeight:600,color:"var(--text)"},children:t("desktop.importSelectProjects")??"选择要导入的项目"}),(0,n.jsx)("button",{type:"button",onClick:()=>h(new Set(d.map(e=>e.name))),style:a7,children:t("desktop.importSelectAll")??"全选"}),(0,n.jsx)("button",{type:"button",onClick:()=>h(new Set),style:a7,children:t("desktop.importDeselectAll")??"取消全选"})]}),(0,n.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:4},children:d.map(e=>(0,n.jsxs)("label",{style:{display:"flex",alignItems:"center",gap:10,padding:"8px 12px",border:"1px solid var(--border)",borderRadius:6,cursor:"pointer",background:u.has(e.name)?"var(--bg-selected)":"transparent",transition:"background 0.12s"},children:[(0,n.jsx)("input",{type:"checkbox",checked:u.has(e.name),onChange:()=>{var t;return t=e.name,void h(e=>{let o=new Set(e);return o.has(t)?o.delete(t):o.add(t),o})}}),(0,n.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,n.jsx)("div",{style:{fontSize:12,fontWeight:500,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name}),(0,n.jsxs)("div",{style:{fontSize:11,color:"var(--text-dim)",marginTop:2},children:[e.sessions," ",t("desktop.sessions")??"会话",e.matched&&(0,n.jsxs)("span",{style:{marginLeft:8,color:"var(--accent)"},children:["→ ",t("desktop.importMerged")??"合并到现有项目",e.existingCount>0&&` (${t("desktop.importExistingCount",{count:e.existingCount})??`${e.existingCount} 个已有`})`]}),!e.matched&&(0,n.jsxs)("span",{style:{marginLeft:8,color:"var(--text-muted)"},children:["→ ",t("desktop.importNewProject")??"新建项目"]})]})]})]},e.name))}),(0,n.jsx)("button",{type:"button",onClick:W,disabled:S||0===u.size,style:{display:"inline-flex",alignItems:"center",gap:7,padding:"8px 14px",background:"var(--accent)",border:"none",borderRadius:6,color:"#fff",fontSize:12,fontWeight:600,cursor:0===u.size?"not-allowed":"pointer",alignSelf:"flex-start",opacity:0===u.size?.5:1},children:S?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(_.y,{size:14,style:{animation:"spin 1s linear infinite"}})," ",t("desktop.importing")??"导入中…"]}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(I.z,{size:15})," ",t("desktop.importStart")??"开始导入"]})})]}),"reasonix"===s&&0===d.length&&!S&&(0,n.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)",padding:"12px 0"},children:t("desktop.importNoData")??"未找到 Reasonix 数据。请确认 ~/.reasonix/projects/ 目录存在且包含会话文件。"})]}),g&&!f.done&&(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,fontSize:12,color:"var(--text)"},children:[(0,n.jsx)(_.y,{size:14,style:{animation:"spin 1s linear infinite"}}),t("desktop.importing")??"导入中…"]}),(0,n.jsx)("div",{style:{height:6,borderRadius:3,background:"var(--bg-panel)",overflow:"hidden"},children:(0,n.jsx)("div",{style:{height:"100%",borderRadius:3,background:"var(--accent)",width:`${f.total>0?(f.imported+f.skipped+f.errors)/f.total*100:0}%`,transition:"width 0.3s ease"}})}),(0,n.jsxs)("div",{style:{fontSize:11,color:"var(--text-dim)"},children:[f.imported+f.skipped+f.errors," / ",f.total,f.skipped>0&&` \xb7 ${t("desktop.importSkippedCount",{skipped:f.skipped})??`${f.skipped} 跳过`}`]})]})]});return o?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("button",{type:"button",onClick:()=>M(!0),style:{display:"flex",alignItems:"center",gap:8,padding:"10px 14px",width:"100%",background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:8,color:"var(--text)",fontSize:12,cursor:"pointer"},children:[(0,n.jsx)(I.z,{size:16}),(0,n.jsx)("span",{style:{fontWeight:500},children:t("desktop.importSessions")??"导入会话"})]}),(0,n.jsxs)(a5,{open:z,onClose:()=>M(!1),children:[(0,n.jsxs)("div",{style:{padding:"4px 18px 14px",borderBottom:"1px solid var(--border)",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[(0,n.jsx)("span",{style:{fontSize:15,fontWeight:700,color:"var(--text)"},children:t("desktop.importSessions")??"导入会话"}),(0,n.jsx)("button",{onClick:()=>M(!1),style:a9,children:(0,n.jsx)(p.X,{size:18})})]}),N]})]}):N}let a7={background:"none",border:"none",color:"var(--accent)",fontSize:11,cursor:"pointer",padding:"2px 4px"},a9={background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",padding:4,display:"flex"},le="deepseek-vision",lt={padding:"7px 9px",background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:6,color:"var(--text)",fontSize:12,fontFamily:"var(--font-mono)",width:"100%",boxSizing:"border-box"};function lo(){return{fontSize:12,color:"var(--text-muted)"}}let ln={padding:"7px 12px",border:"none",borderRadius:6,background:"var(--accent)",color:"#fff",cursor:"pointer",fontSize:12};function lr({sessionId:e}){let{t}=(0,F.s)(),[o,s]=(0,r.useState)(!1),[i,a]=(0,r.useState)(null),[l,d]=(0,r.useState)(!1),[c,p]=(0,r.useState)(null),[u,h]=(0,r.useState)(!1),[g,m]=(0,r.useState)({}),[f,x]=(0,r.useState)(""),[k,v]=(0,r.useState)(""),[y,b]=(0,r.useState)("eager"),[w,j]=(0,r.useState)(!1),[S,C]=(0,r.useState)(null),[T,R]=(0,r.useState)(!1),[z,I]=(0,r.useState)(!1),[M,P]=(0,r.useState)({provider:"custom",baseUrl:"",apiKey:"",model:"",maxTokens:4096,hasApiKey:!1}),[E,D]=(0,r.useState)(""),[W,A]=(0,r.useState)(""),[N,$]=(0,r.useState)(!1),[L,O]=(0,r.useState)(null),[H,B]=(0,r.useState)(!1);(0,r.useEffect)(()=>{let e=!1;return(async()=>{a(null);try{let[t,o]=await Promise.all([fetch("/api/mcp"),fetch("/api/vision-config")]),n=await t.json();if(!t.ok||n.error)throw Error(n.error??`HTTP ${t.status}`);let r=await o.json();if(!o.ok||r.error)throw Error(r.error??`HTTP ${o.status}`);if(e)return;m(n.mcpServers??{}),x(n.filePath);let i=(n.mcpServers??{})[le];v(i?.command??""),b(i?.lifecycle==="lazy"?"lazy":"eager"),P({provider:r.provider,baseUrl:r.baseUrl,apiKey:"",model:r.model,maxTokens:r.maxTokens,hasApiKey:r.hasApiKey}),r.path&&A(r.path),s(!0)}catch(t){e||a(t instanceof Error?t.message:String(t))}})(),()=>{e=!0}},[]);let U=(0,r.useCallback)(async()=>{if(!k.trim())return void C(t("desktop.mcpVisionCommandRequired"));j(!0),C(null),R(!1),I(!1);try{let e=g[le],t={...g,[le]:{...e??{},command:k.trim(),args:Array.isArray(e?.args)?e.args:[],transport:"stdio",lifecycle:y}},o=await fetch("/api/mcp",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({mcpServers:t})}),n=await o.json();if(!o.ok||n.error)throw Error(n.error??`HTTP ${o.status}`);m(t),R(!0)}catch(e){C(e instanceof Error?e.message:String(e))}finally{j(!1)}},[g,k,y,t]),_=(0,r.useCallback)(async()=>{j(!0),C(null),R(!1),I(!1);try{let e={...g};delete e[le];let t=await fetch("/api/mcp",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({mcpServers:e})}),o=await t.json();if(!t.ok||o.error)throw Error(o.error??`HTTP ${t.status}`);m(e),v(""),b("eager"),I(!0)}catch(e){C(e instanceof Error?e.message:String(e))}finally{j(!1)}},[g]),q=(0,r.useCallback)(async()=>{$(!0),O(null),B(!1);try{let e=await fetch("/api/vision-config",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({...M,...E?{apiKey:E}:{}})}),t=await e.json();if(!e.ok||t.error)throw Error(t.error??`HTTP ${e.status}`);P({...t,apiKey:"",hasApiKey:t.hasApiKey}),D(""),B(!0)}catch(e){O(e instanceof Error?e.message:String(e))}finally{$(!1)}},[M,E]),V=(0,r.useCallback)(async()=>{if(e){d(!0),p(null),h(!1);try{let t=await fetch("/api/mcp/restart",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:e,name:le})}),o=await t.json();if(!t.ok||o.error)throw Error(o.error??`HTTP ${t.status}`);h(!0)}catch(e){p(e instanceof Error?e.message:String(e))}finally{d(!1)}}},[e]),K=!!g[le];return(0,n.jsxs)(aY,{children:[(0,n.jsx)(aX,{children:(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:7,padding:"12px 0"},children:[(0,n.jsx)(rG.k,{size:15,"aria-hidden":"true"}),(0,n.jsxs)("div",{style:{minWidth:0},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[(0,n.jsx)("span",{style:{fontSize:13,fontWeight:600,color:"var(--text)"},children:t("desktop.mcpVisionTitle")}),(0,n.jsx)("span",{style:{fontSize:10,padding:"1px 6px",borderRadius:3,background:K?"rgba(37,99,235,0.12)":"rgba(245,158,11,0.12)",color:K?"var(--accent)":"#d97706",textTransform:"capitalize"},children:K?t("desktop.mcpVisionRegistered"):t("desktop.mcpVisionNotRegistered")})]}),(0,n.jsx)("div",{style:{fontSize:11,color:"var(--text-muted)",marginTop:2},children:t("desktop.mcpVisionDesc")})]})]})}),o?i?(0,n.jsx)(aZ,{children:(0,n.jsx)("div",{style:{padding:"8px 0",fontSize:12,color:"#ef4444"},children:i})}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(aX,{children:(0,n.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)",padding:"10px 0 2px"},children:t("desktop.mcpVisionRegistration")})}),(0,n.jsx)(aX,{children:(0,n.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"minmax(120px, 180px) 1fr",gap:8,alignItems:"center",padding:"6px 0"},children:[(0,n.jsxs)("span",{style:lo(),children:[t("desktop.mcpVisionCommand")," *"]}),(0,n.jsx)("input",{value:k,onChange:e=>v(e.target.value),placeholder:"/path/to/deepseek-vision-mcp",style:lt}),(0,n.jsx)("span",{style:lo(),children:t("desktop.mcpVisionLifecycle")}),(0,n.jsxs)("select",{value:y,onChange:e=>b(e.target.value),style:{...lt,fontFamily:"var(--font-mono)"},children:[(0,n.jsx)("option",{value:"eager",children:"eager"}),(0,n.jsx)("option",{value:"lazy",children:"lazy"})]}),(0,n.jsx)("span",{style:lo(),children:t("desktop.mcpVisionTransport")}),(0,n.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)",fontFamily:"var(--font-mono)",padding:"7px 0"},children:t("desktop.mcpVisionTransportFixed")})]})}),(0,n.jsx)(aX,{children:(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"6px 0",flexWrap:"wrap"},children:[(0,n.jsx)("button",{type:"button",onClick:()=>void U(),disabled:w,style:{...ln,cursor:w?"wait":"pointer"},children:w?t("desktop.saving"):t("desktop.mcpVisionSaveReg")}),K&&(0,n.jsx)("button",{type:"button",onClick:()=>void _(),disabled:w,title:t("desktop.mcpVisionRemove"),style:{padding:"7px 12px",background:"none",border:"1px solid var(--border)",borderRadius:6,color:"#ef4444",cursor:w?"not-allowed":"pointer",fontSize:12},children:t("desktop.mcpVisionRemove")}),T&&(0,n.jsx)("span",{style:{color:"#22c55e",fontSize:12},children:t("desktop.mcpVisionSavedReg")}),z&&(0,n.jsx)("span",{style:{color:"#22c55e",fontSize:12},children:t("desktop.mcpVisionRemoved")}),S&&(0,n.jsx)("span",{style:{color:"#ef4444",fontSize:12},children:S})]})}),(0,n.jsx)(aX,{children:(0,n.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)",padding:"10px 0 2px"},children:t("desktop.mcpVisionModelConfig")})}),(0,n.jsx)(aX,{children:(0,n.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"minmax(120px, 180px) 1fr",gap:8,alignItems:"center",padding:"6px 0"},children:[(0,n.jsx)("span",{style:lo(),children:t("desktop.mcpVisionProvider")}),(0,n.jsx)("input",{value:M.provider,onChange:e=>P(t=>({...t,provider:e.target.value})),style:lt}),(0,n.jsx)("span",{style:lo(),children:t("desktop.mcpVisionBaseUrl")}),(0,n.jsx)("input",{value:M.baseUrl,onChange:e=>P(t=>({...t,baseUrl:e.target.value})),style:lt}),(0,n.jsx)("span",{style:lo(),children:t("desktop.mcpVisionApiKey")}),(0,n.jsx)("input",{type:"password",value:E,onChange:e=>D(e.target.value),placeholder:M.hasApiKey?"••••••••":"API key",style:lt}),(0,n.jsx)("span",{style:lo(),children:t("desktop.mcpVisionModel")}),(0,n.jsx)("input",{value:M.model,onChange:e=>P(t=>({...t,model:e.target.value})),style:lt}),(0,n.jsx)("span",{style:lo(),children:t("desktop.mcpVisionMaxTokens")}),(0,n.jsx)("input",{type:"number",min:1,value:M.maxTokens,onChange:e=>P(t=>({...t,maxTokens:Number(e.target.value)||1})),style:lt})]})}),(0,n.jsx)(aZ,{children:(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:8,padding:"6px 0"},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:[(0,n.jsx)("button",{type:"button",onClick:()=>void q(),disabled:N,style:{...ln,cursor:N?"wait":"pointer"},children:N?t("desktop.saving"):t("desktop.mcpVisionSaveModel")}),(0,n.jsx)("button",{type:"button",onClick:()=>void V(),disabled:l||!e||!K,title:e?t("desktop.mcpVisionRestartTitle"):t("desktop.mcpVisionRestartNoSession"),style:{padding:"7px 12px",background:"none",border:"1px solid var(--border)",borderRadius:6,color:"var(--text-muted)",cursor:!l&&e&&K?"pointer":"not-allowed",fontSize:12,opacity:!l&&e&&K?1:.5},children:l?t("desktop.mcpVisionRestarting"):t("desktop.mcpVisionRestart")}),H&&(0,n.jsx)("span",{style:{color:"#22c55e",fontSize:12},children:t("desktop.mcpVisionSavedModel")}),u&&(0,n.jsx)("span",{style:{color:"#22c55e",fontSize:12},children:t("desktop.mcpVisionRestarted")}),L&&(0,n.jsx)("span",{style:{color:"#ef4444",fontSize:12},children:L}),c&&(0,n.jsx)("span",{style:{color:"#ef4444",fontSize:12},children:c})]}),(0,n.jsxs)(aQ,{children:[t("desktop.mcpVisionModelNote"),W&&(0,n.jsx)("div",{style:{marginTop:4,fontFamily:"var(--font-mono)",fontSize:10},children:W}),f&&(0,n.jsx)("div",{style:{fontFamily:"var(--font-mono)",fontSize:10},children:f})]})]})})]}):(0,n.jsx)(aZ,{children:(0,n.jsx)("div",{style:{padding:"8px 0",fontSize:12,color:"var(--text-muted)"},children:t("desktop.loading")})})]})}function ls({sessionId:e,onApplied:t,onBeforeApply:o}){let{t:s}=(0,F.s)(),[i,a]=(0,r.useState)(!1),[l,d]=(0,r.useState)(!1),[c,p]=(0,r.useState)(null),u=(0,r.useCallback)(async()=>{if(e){a(!0),p(null),d(!1);try{await o?.(),await iS(e,{type:"reload"}),d(!0),await t?.()}catch(e){p(e instanceof Error?e.message:String(e))}finally{a(!1)}}},[e,t,o]),h=i||!e;return(0,n.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[(0,n.jsx)("button",{type:"button",onClick:()=>void u(),disabled:h,title:s(e?"desktop.applyNowTitle":"desktop.applyNowNoSession"),style:{padding:"7px 12px",background:"none",border:"1px solid var(--border)",borderRadius:6,color:"var(--text-muted)",cursor:h?"not-allowed":"pointer",fontSize:12,opacity:h?.5:1,whiteSpace:"nowrap"},children:s(i?"desktop.applyNowApplying":"desktop.applyNow")}),l&&(0,n.jsx)("span",{style:{color:"#22c55e",fontSize:12},children:s("desktop.applyNowDone")}),c&&(0,n.jsx)("span",{style:{color:"#ef4444",fontSize:12},children:c})]})}let li=["stdio","sse","http"],la=["eager","lazy"],ll={name:"",command:"",args:"",transport:"stdio",lifecycle:"eager",requestTimeoutMs:"",env:""},ld={padding:"7px 9px",background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:6,color:"var(--text)",fontSize:12,fontFamily:"var(--font-mono)",width:"100%",boxSizing:"border-box"};function lc(){return{fontSize:12,color:"var(--text-muted)"}}function lp(e,t){return{fontSize:10,padding:"1px 6px",borderRadius:3,background:t,color:e,flexShrink:0,textTransform:"capitalize"}}function lu({sessionId:e}){let{t}=(0,F.s)(),[o,s]=(0,r.useState)({}),[i,a]=(0,r.useState)(""),[l,d]=(0,r.useState)(!1),[c,p]=(0,r.useState)(null),[u,h]=(0,r.useState)(null),[m,f]=(0,r.useState)(ll),[k,v]=(0,r.useState)(!1),[y,b]=(0,r.useState)(null),[w,j]=(0,r.useState)(!1),C=(0,r.useCallback)(async()=>{p(null);try{let e=await fetch("/api/mcp"),t=await e.json();if(!e.ok||t.error)throw Error(t.error??`HTTP ${e.status}`);s(t.mcpServers??{}),a(t.filePath)}catch(e){p(e instanceof Error?e.message:String(e))}finally{d(!0)}},[]);(0,r.useEffect)(()=>{C()},[C]);let T=(0,r.useCallback)(()=>{f(ll),h({name:"",isNew:!0}),b(null),j(!1)},[]),R=(0,r.useCallback)((e,t)=>{f({name:e,command:t.command??"",args:Array.isArray(t.args)?t.args.join("\n"):"",transport:"string"==typeof t.transport?t.transport:"stdio",lifecycle:"string"==typeof t.lifecycle?t.lifecycle:"eager",requestTimeoutMs:"number"==typeof t.requestTimeoutMs?String(t.requestTimeoutMs):"",env:void 0!==t.env?JSON.stringify(t.env,null,2):""}),h({name:e,isNew:!1}),b(null),j(!1)},[]),z=(0,r.useCallback)(async()=>{if(u){v(!0),b(null),j(!1);try{let e=m.name.trim();if(u.isNew&&!e)return void b("Server name is required");if(u.isNew&&!/^[a-zA-Z0-9_-]+$/.test(e))return void b("Allowed characters: a-z, A-Z, 0-9, _ and -");if(u.isNew&&e===le)return void b(t("desktop.mcpVisionNameReserved"));let n=function(e){if(!e.command.trim())return{error:"Command is required"};let t=e.args.split("\n").map(e=>e.trim()).filter(Boolean),o={command:e.command.trim(),args:t,transport:li.includes(e.transport)?e.transport:"stdio",lifecycle:la.includes(e.lifecycle)?e.lifecycle:"eager"};if(""!==e.requestTimeoutMs.trim()){let t=Number(e.requestTimeoutMs);if(!Number.isFinite(t)||t<=0)return{error:"Request timeout must be a positive number"};o.requestTimeoutMs=t}if(""!==e.env.trim())try{o.env=JSON.parse(e.env)}catch{return{error:"Environment must be valid JSON"}}return{server:o}}(m);if(n.error||!n.server)return void b(n.error??"Invalid server");let r={...o};u.isNew?r[e]=n.server:(delete r[u.name],r[m.name.trim()||u.name]=n.server);let i=await fetch("/api/mcp",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({mcpServers:r})}),a=await i.json();if(!i.ok||a.error)throw Error(a.error??`HTTP ${i.status}`);s(r),h(null),j(!0)}catch(e){b(e instanceof Error?e.message:String(e))}finally{v(!1)}}},[u,m,o,t]),I=(0,r.useCallback)(async e=>{v(!0),b(null);try{let t={...o};delete t[e];let n=await fetch("/api/mcp",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({mcpServers:t})}),r=await n.json();if(!n.ok||r.error)throw Error(r.error??`HTTP ${n.status}`);s(t),j(!0)}catch(e){b(e instanceof Error?e.message:String(e))}finally{v(!1)}},[o]),M=(0,r.useCallback)((e,t)=>{f(o=>({...o,[e]:t}))},[]),P=Object.entries(o).filter(([e])=>e!==le);return(0,n.jsx)("div",{style:{flex:1,overflow:"auto",minWidth:0,padding:"20px 22px",display:"flex",flexDirection:"column",gap:16},children:(0,n.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:l?c?(0,n.jsx)("div",{style:{fontSize:12,color:"#ef4444"},children:c}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12},children:[(0,n.jsxs)("div",{style:{minWidth:0},children:[(0,n.jsx)("div",{style:{fontSize:14,fontWeight:700,color:"var(--text)"},children:t("desktop.mcpServers")}),(0,n.jsx)("div",{style:{fontSize:11,color:"var(--text-dim)",fontFamily:"var(--font-mono)",marginTop:2,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:i})]}),(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10,flexShrink:0},children:[(0,n.jsx)(ls,{sessionId:e,onApplied:C}),(0,n.jsxs)("button",{type:"button",onClick:T,style:{display:"flex",alignItems:"center",gap:6,padding:"7px 12px",border:"none",borderRadius:6,background:"var(--accent)",color:"#fff",cursor:"pointer",fontSize:12,flexShrink:0},children:[(0,n.jsx)(x.c,{size:13,"aria-hidden":"true"}),t("desktop.mcpAddServer")]})]})]}),(0,n.jsx)(aQ,{children:t("desktop.mcpRestartNote")}),(0,n.jsx)(lr,{sessionId:e}),0!==P.length||u?P.map(([e,o])=>(0,n.jsx)(aY,{children:(0,n.jsx)(aZ,{children:(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"12px 0",minWidth:0},children:[(0,n.jsxs)("div",{style:{minWidth:0,flex:1},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[(0,n.jsx)("span",{style:{fontSize:13,fontWeight:600,color:"var(--text)",fontFamily:"var(--font-mono)"},children:e}),(0,n.jsx)("span",{style:lp("var(--accent)","rgba(37,99,235,0.12)"),children:o.transport??"stdio"}),(0,n.jsx)("span",{style:lp("#d97706","rgba(245,158,11,0.12)"),children:o.lifecycle??"lazy"})]}),(0,n.jsxs)("div",{style:{fontSize:11,color:"var(--text-muted)",fontFamily:"var(--font-mono)",marginTop:4,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[o.command,Array.isArray(o.args)&&o.args.length>0?` ${o.args.map(e=>e.includes(" ")?`"${e}"`:e).join(" ")}`:""]})]}),(0,n.jsxs)("div",{style:{display:"flex",gap:6,flexShrink:0},children:[(0,n.jsxs)("button",{type:"button",onClick:()=>R(e,o),disabled:k,style:{display:"flex",alignItems:"center",gap:5,padding:"6px 10px",background:"none",border:"1px solid var(--border)",borderRadius:6,color:"var(--text-muted)",cursor:k?"not-allowed":"pointer",fontSize:12,opacity:k?.5:1},children:[(0,n.jsx)(g.I,{size:12,"aria-hidden":"true"}),t("desktop.mcpEdit")]}),(0,n.jsx)("button",{type:"button",onClick:()=>void I(e),disabled:k,title:t("desktop.mcpDelete"),"aria-label":t("desktop.mcpDelete"),style:{display:"flex",alignItems:"center",padding:"6px 9px",background:"rgba(239,68,68,0.08)",border:"1px solid var(--border)",borderRadius:6,color:"#ef4444",cursor:k?"not-allowed":"pointer",fontSize:12,opacity:k?.5:1},children:(0,n.jsx)(S.l,{size:12,"aria-hidden":"true"})})]})]})})},e)):(0,n.jsx)(aY,{children:(0,n.jsx)(aZ,{children:(0,n.jsx)("div",{style:{padding:"14px 0",fontSize:12,color:"var(--text-dim)"},children:o[le]?t("desktop.mcpEmptyOther"):t("desktop.mcpEmpty")})})}),u&&(0,n.jsxs)(aY,{children:[(0,n.jsx)(aX,{children:(0,n.jsx)("div",{style:{fontSize:13,fontWeight:600,color:"var(--text)",padding:"12px 0 4px"},children:u.isNew?t("desktop.mcpNewServer"):t("desktop.mcpEditServer",{name:u.name})})}),(0,n.jsx)(aX,{children:(0,n.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"minmax(150px, 220px) 1fr",gap:"8px 12px",alignItems:"center",padding:"8px 0"},children:[(0,n.jsx)("span",{style:lc(),children:t("desktop.mcpServerName")}),(0,n.jsx)("input",{value:m.name,onChange:e=>M("name",e.target.value),disabled:!u.isNew,placeholder:"my-server",style:{...ld,opacity:u.isNew?1:.5}}),(0,n.jsxs)("span",{style:lc(),children:[t("desktop.mcpCommand")," *"]}),(0,n.jsx)("input",{value:m.command,onChange:e=>M("command",e.target.value),placeholder:"npx @modelcontextprotocol/server-foo",style:ld}),(0,n.jsx)("span",{style:lc(),children:t("desktop.mcpArgs")}),(0,n.jsx)("textarea",{value:m.args,onChange:e=>M("args",e.target.value),placeholder:"--port 3000\n--verbose",rows:3,style:{...ld,resize:"vertical",lineHeight:1.5}}),(0,n.jsx)("span",{style:lc(),children:t("desktop.mcpTransport")}),(0,n.jsx)("select",{value:m.transport,onChange:e=>M("transport",e.target.value),style:{...ld,fontFamily:"var(--font-mono)"},children:li.map(e=>(0,n.jsx)("option",{value:e,children:e},e))}),(0,n.jsx)("span",{style:lc(),children:t("desktop.mcpLifecycle")}),(0,n.jsx)("select",{value:m.lifecycle,onChange:e=>M("lifecycle",e.target.value),style:{...ld,fontFamily:"var(--font-mono)"},children:la.map(e=>(0,n.jsx)("option",{value:e,children:e},e))}),(0,n.jsx)("span",{style:lc(),children:t("desktop.mcpRequestTimeoutMs")}),(0,n.jsx)("input",{type:"number",min:1,value:m.requestTimeoutMs,onChange:e=>M("requestTimeoutMs",e.target.value),placeholder:"300000",style:ld}),(0,n.jsx)("span",{style:lc(),children:t("desktop.mcpEnv")}),(0,n.jsx)("textarea",{value:m.env,onChange:e=>M("env",e.target.value),placeholder:'{\n "API_KEY": "..."\n}',rows:3,style:{...ld,resize:"vertical",lineHeight:1.5}})]})}),(0,n.jsx)(aZ,{children:(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"10px 0"},children:[(0,n.jsx)("button",{type:"button",onClick:()=>void z(),disabled:k,style:{padding:"7px 12px",border:"none",borderRadius:6,background:"var(--accent)",color:"#fff",cursor:k?"wait":"pointer",fontSize:12},children:k?t("desktop.saving"):t("desktop.mcpSave")}),(0,n.jsx)("button",{type:"button",onClick:()=>h(null),disabled:k,style:{padding:"7px 12px",background:"none",border:"1px solid var(--border)",borderRadius:6,color:"var(--text-muted)",cursor:k?"not-allowed":"pointer",fontSize:12},children:t("desktop.mcpCancel")}),y&&(0,n.jsx)("span",{style:{color:"#ef4444",fontSize:12},children:y})]})})]}),w&&!u&&(0,n.jsx)("div",{style:{fontSize:12,color:"#22c55e"},children:t("desktop.mcpSavedRestart")})]}):(0,n.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)"},children:t("desktop.loading")})})})}var lh=o(9210);function lg(){let{t:e}=(0,F.s)(),[t,o]=(0,r.useState)(null),[s,i]=(0,r.useState)([]),[a,l]=(0,r.useState)(!0),[d,c]=(0,r.useState)(!1),[p,u]=(0,r.useState)(!1),[h,g]=(0,r.useState)(null);(0,r.useEffect)(()=>{fetch("/api/settings/title-model").then(e=>e.json()).then(e=>{o(e.value),i(e.models??[])}).catch(()=>{}).finally(()=>l(!1))},[]);let m=null!==t&&!s.some(e=>e.label===t),f=(0,r.useCallback)(async t=>{c(!0),g(null),u(!1);try{let e=await fetch("/api/settings/title-model",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({value:""===t?null:t})}),n=await e.json();if(!e.ok||n.error)return void g(n.error??`HTTP ${e.status}`);o(n.value??null),u(!0),setTimeout(()=>u(!1),2e3)}catch{g(String(e("desktop.titleModelSaveError")))}finally{c(!1)}},[e]),x=[...new Set(s.map(e=>e.provider))];return(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:6,padding:"12px 18px",borderBottom:"1px solid var(--border)",background:"var(--bg-panel)",flexShrink:0},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:[(0,n.jsx)("span",{style:{fontSize:12,fontWeight:600,color:"var(--text)",whiteSpace:"nowrap"},children:e("desktop.titleModel")}),(0,n.jsxs)("select",{value:t??"",disabled:a||d,onChange:e=>f(e.target.value),style:{flex:1,minWidth:200,maxWidth:420,padding:"6px 9px",fontSize:12,color:"var(--text)",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:5},children:[(0,n.jsx)("option",{value:"",children:e("desktop.titleModelFollowSession")}),m&&null!==t&&(0,n.jsxs)("option",{value:t,style:{color:"#ef4444"},children:[t,"(",e("desktop.titleModelInvalid"),")"]}),x.map(e=>(0,n.jsx)("optgroup",{label:e,children:s.filter(t=>t.provider===e).map(e=>(0,n.jsxs)("option",{value:e.label,children:[e.name||e.id,e.reasoning?"(reasoning)":""]},e.label))},e))]}),d&&(0,n.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)"},children:"…"}),!d&&p&&(0,n.jsx)("span",{style:{fontSize:11,color:"#4ade80"},children:e("desktop.titleModelSaved")})]}),(0,n.jsx)("p",{style:{margin:0,fontSize:11,color:"var(--text-muted)",lineHeight:1.5},children:e("desktop.titleModelDescription")}),h&&(0,n.jsx)("p",{style:{margin:0,fontSize:11,color:"#ef4444",lineHeight:1.5},children:h}),m&&null!==t&&(0,n.jsxs)("p",{style:{margin:0,fontSize:11,color:"#ef4444",lineHeight:1.5},children:[t,"(",e("desktop.titleModelInvalid"),")"]})]})}let lm=["name","reasoning","contextWindow","maxTokens","thinkingLevelMap","hidden"];function lf(e){if(""===e.trim())return;let t=Number(e);return Number.isFinite(t)&&t>0?t:void 0}function lx(e){let t=lf(e.contextWindow??""),o=lf(e.maxTokens??""),n=e.thinkingLevelMap&&Object.keys(e.thinkingLevelMap).length>0?{...e.thinkingLevelMap}:void 0;return{...e.name?.trim()?{name:e.name.trim()}:{},..."boolean"==typeof e.reasoning?{reasoning:e.reasoning}:{},...void 0!==t?{contextWindow:t}:{},...void 0!==o?{maxTokens:o}:{},...n?{thinkingLevelMap:n}:{},..."boolean"==typeof e.hidden?{hidden:e.hidden}:{}}}function lk({providerId:e,onRegisterFlush:t,onConfigChange:o}){let{t:s}=(0,F.s)(),i=$(),[a,l]=(0,r.useState)([]),[d,c]=(0,r.useState)({}),[p,u]=(0,r.useState)({}),[h,g]=(0,r.useState)(new Set),[m,f]=(0,r.useState)(!0),[x,k]=(0,r.useState)(!1),[v,y]=(0,r.useState)(null),[b,w]=(0,r.useState)(!1),[j,S]=(0,r.useState)(null),C=(0,r.useRef)(d),T=(0,r.useRef)(p),R=(0,r.useRef)(a),z=(0,r.useRef)(h),I=(0,r.useRef)(0),M=(0,r.useRef)(null);C.current=d,T.current=p,R.current=a,z.current=h,(0,r.useEffect)(()=>{let t=!1;return f(!0),y(null),(async()=>{try{let o=await fetch(`/api/models-config/builtin?provider=${encodeURIComponent(e)}`),n=await o.json();if(!o.ok||n.error)throw Error(n.error??`HTTP ${o.status}`);if(t)return;let r={};for(let e of n.models){let t=n.overrides[e.id]??{};r[e.id]={name:"string"==typeof t.name&&t.name.length>0?t.name:e.name,reasoning:"boolean"==typeof t.reasoning?t.reasoning:e.reasoning,contextWindow:"number"==typeof t.contextWindow?String(t.contextWindow):null!=e.contextWindow?String(e.contextWindow):"",maxTokens:"number"==typeof t.maxTokens?String(t.maxTokens):null!=e.maxTokens?String(e.maxTokens):"",hidden:"boolean"==typeof t.hidden&&t.hidden,thinkingLevelMap:t.thinkingLevelMap??e.thinkingLevelMap}}l(n.models),c(r),u(r),g(new Set)}catch(e){t||y(e instanceof Error?e.message:String(e))}finally{t||f(!1)}})(),()=>{t=!0}},[e]);let P=(0,r.useCallback)((e,t)=>{I.current+=1,c(o=>({...o,[e]:{...o[e]??{},...t}})),g(t=>new Set(t).add(e))},[]),E=(0,r.useCallback)(async()=>{let t=M.current;if(t)return t;let n=(async()=>{let t=new Set(z.current);if(0===t.size)return;let n=I.current,r={...C.current},s={},i={};for(let e of R.current){let t=r[e.id],o=T.current[e.id];t&&(s[e.id]=lx(t)),o&&(i[e.id]=lx(o))}let a=function(e,t,o){let n={};for(let r of e){let e=t[r];if(!e)continue;let s=o[r]??{},i={};for(let t of lm){let o=e[t],n=s[t];JSON.stringify(o)!==JSON.stringify(n)&&(i[t]=void 0===o?null:o)}Object.keys(i).length>0&&(n[r]=i)}return n}(t,s,i);if(0===Object.keys(a).length)return void g(new Set);k(!0),y(null),w(!1);try{let s=await fetch("/api/models-config/builtin",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:e,patches:a})}),i=await s.json();if(!s.ok||i.error)throw Error(i.error??`HTTP ${s.status}`);o?.(i.provider??null);let l={...T.current};for(let e of t){let t=r[e];t&&(l[e]={...t})}T.current=l,u(l),I.current===n&&g(e=>new Set([...e].filter(e=>!t.has(e)))),w(!0),setTimeout(()=>w(!1),2e3)}catch(e){throw y(e instanceof Error?e.message:String(e)),e}finally{k(!1)}})();M.current=n;try{await n}finally{M.current===n&&(M.current=null)}},[o,e]);(0,r.useEffect)(()=>{if(t)return t(e,E)??void 0},[t,e,E]);let[D,W]=(0,r.useState)({phase:"idle"}),[A,N]=(0,r.useState)([]),L=(0,r.useCallback)(async()=>{W({phase:"loading"});try{let t=await fetch("/api/models-config/discover",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({providerName:e,provider:{}})}),o=await t.json();if(!t.ok||o.error||!o.models)return void W({phase:"error",message:o.error??`HTTP ${t.status}`});let n=new Set(R.current.map(e=>e.id)),r=new Set(o.models.filter(e=>!n.has(e.id)).map(e=>e.id));W({phase:"success",models:o.models,newIds:r}),N(o.models.filter(e=>r.has(e.id)).map(e=>e.id))}catch(e){W({phase:"error",message:e instanceof Error?e.message:String(e)})}},[e]),O=(0,r.useCallback)(async()=>{if(D.models?.length){k(!0),y(null);try{let t=D.models.map(e=>({id:e.id,...e.name?{name:e.name}:{}})),n=await fetch("/api/models-config/builtin",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:e,models:t})}),r=await n.json();if(!n.ok||r.error)throw Error(r.error??`HTTP ${n.status}`);o?.(r.provider??null),W({phase:"idle"}),N([]);let s=await fetch(`/api/models-config/builtin?provider=${encodeURIComponent(e)}`);if(s.ok){let e=await s.json();if(e.models){l(e.models),R.current=e.models;let t={};for(let o of e.models){let n=e.overrides?.[o.id]??{};t[o.id]={name:"string"==typeof n.name&&n.name.length>0?n.name:o.name,reasoning:"boolean"==typeof n.reasoning?n.reasoning:o.reasoning,contextWindow:"number"==typeof n.contextWindow?String(n.contextWindow):null!=o.contextWindow?String(o.contextWindow):"",maxTokens:"number"==typeof n.maxTokens?String(n.maxTokens):null!=o.maxTokens?String(o.maxTokens):"",hidden:"boolean"==typeof n.hidden&&n.hidden,thinkingLevelMap:n.thinkingLevelMap??o.thinkingLevelMap}}c(t),u(t),g(new Set)}}}catch(e){y(e instanceof Error?e.message:String(e))}finally{k(!1)}}},[D.models,o,e]);return m?(0,n.jsx)("div",{style:{borderTop:"1px solid var(--border)",marginTop:14,paddingTop:12},children:(0,n.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-dim)"},children:s("desktop.modelsLoading")})}):(0,n.jsxs)("div",{style:{borderTop:"1px solid var(--border)",marginTop:14,paddingTop:12,display:"flex",flexDirection:"column",gap:10},children:[(0,n.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)"},children:s("desktop.builtinModelsTitle")}),(0,n.jsxs)("div",{style:{borderTop:"1px solid var(--border)",paddingTop:10,display:"flex",flexDirection:"column",gap:8},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[(0,n.jsx)("button",{type:"button",onClick:()=>{L()},disabled:"loading"===D.phase,style:{padding:"5px 12px",background:(D.phase,"var(--bg-panel)"),border:"1px solid var(--border)",borderRadius:5,color:"loading"===D.phase?"var(--text-dim)":"var(--text-muted)",cursor:"loading"===D.phase?"not-allowed":"pointer",fontSize:12},children:"loading"===D.phase?s("desktop.modelsDiscoveryFetching"):s("desktop.builtinModelsFetchNew")}),"success"===D.phase&&D.models&&(0,n.jsx)("button",{type:"button",onClick:()=>{O()},disabled:x||0===A.length,style:{padding:"5px 12px",background:A.length>0&&!x?"var(--accent)":"var(--bg-panel)",border:"none",borderRadius:5,color:A.length>0&&!x?"#fff":"var(--text-dim)",cursor:A.length>0&&!x?"pointer":"not-allowed",fontSize:12,fontWeight:600},children:x?s("desktop.modelsSaving"):`${s("desktop.modelsAddModelManual")} (${A.length})`})]}),"error"===D.phase&&(0,n.jsx)("p",{style:{margin:0,fontSize:11,color:"#f87171"},children:D.message}),"success"===D.phase&&D.models&&(0,n.jsx)("div",{style:{maxHeight:200,overflowY:"auto",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-panel)"},children:D.models.map(e=>{let t=D.newIds?.has(e.id)??!1,o=A.includes(e.id);return(0,n.jsxs)("label",{style:{display:"flex",alignItems:"center",gap:8,minHeight:32,padding:"5px 9px",borderBottom:"1px solid var(--border)",cursor:t?"pointer":"default",opacity:t?1:.55},children:[(0,n.jsx)("input",{type:"checkbox",checked:o,disabled:!t,onChange:t=>{N(o=>t.target.checked?[...o,e.id]:o.filter(t=>t!==e.id))},style:{width:13,height:13,accentColor:"var(--accent)",flexShrink:0}}),(0,n.jsx)("span",{style:{fontSize:12,color:"var(--text)",fontWeight:t?600:400},children:e.name||e.id}),(0,n.jsx)("code",{style:{fontSize:10,color:"var(--text-dim)",fontFamily:"var(--font-mono)"},children:e.id}),t&&(0,n.jsx)("span",{style:{fontSize:10,padding:"1px 6px",borderRadius:8,background:"var(--accent)",color:"#fff",marginLeft:"auto"},children:"新"})]},e.id)})})]}),v&&(0,n.jsx)("p",{style:{margin:0,fontSize:11,color:"#f87171"},children:v}),0===a.length&&!v&&(0,n.jsx)("p",{style:{margin:0,fontSize:11,color:"var(--text-dim)"},children:s("desktop.builtinModelsEmpty")}),(0,n.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:8},children:a.map(e=>{let t=d[e.id]??{},o=j===e.id,r=h.has(e.id);return(0,n.jsxs)("div",{style:{border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-panel)",padding:"8px 10px"},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[(0,n.jsxs)("button",{type:"button",onClick:()=>S(o?null:e.id),style:{background:"none",border:"none",cursor:"pointer",color:"var(--text)",fontSize:12,fontWeight:600,padding:0,textAlign:"left"},children:[t.name||e.name||e.id,r&&(0,n.jsx)("span",{style:{color:"var(--accent)",marginLeft:6},children:"•"})]}),(0,n.jsx)("code",{style:{fontSize:10,color:"var(--text-dim)",fontFamily:"var(--font-mono)"},children:e.id}),(t.reasoning??e.reasoning)&&(0,n.jsx)("span",{style:{fontSize:10,padding:"1px 6px",borderRadius:8,background:"var(--bg-selected)",color:"var(--text-muted)"},children:"reasoning"}),(0,n.jsxs)("span",{style:{fontSize:11,color:"var(--text-muted)"},children:[s("desktop.builtinModelsContext"),": ",(0,n.jsx)("b",{children:t.contextWindow?Number(t.contextWindow).toLocaleString():"—"})," \xb7 ",s("desktop.builtinModelsMaxTokens"),": ",(0,n.jsx)("b",{children:t.maxTokens?Number(t.maxTokens).toLocaleString():"—"})]})]}),o&&(0,n.jsxs)("div",{style:{marginTop:10,display:"flex",flexDirection:"column",gap:10},children:[(0,n.jsxs)("label",{style:{display:"flex",gap:6,alignItems:"center",fontSize:12,color:"var(--text)",width:"100%"},children:[s("desktop.modelsName"),(0,n.jsx)("input",{type:"text",value:t.name??"",placeholder:e.name||e.id,onChange:t=>P(e.id,{name:t.target.value.trim()||void 0}),style:{flex:1,minWidth:0,padding:"4px 7px",fontSize:11,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:4,color:"var(--text)",fontFamily:"var(--font-mono)"}}),(0,n.jsxs)("label",{style:{display:"flex",gap:4,alignItems:"center",fontSize:11,color:t.hidden?"#f87171":"var(--text-muted)",cursor:"pointer",whiteSpace:"nowrap",marginLeft:8},children:[(0,n.jsx)("input",{type:"checkbox",checked:!0===t.hidden,onChange:t=>P(e.id,{hidden:t.target.checked})}),s("desktop.builtinModelsHide")]})]}),(0,n.jsxs)("div",{style:{display:"flex",gap:16,flexWrap:"wrap",flexDirection:i?"column":"row",alignItems:i?"flex-start":"center"},children:[(0,n.jsxs)("label",{style:{display:"flex",gap:6,alignItems:"center",fontSize:12,color:"var(--text)",cursor:"pointer"},children:[(0,n.jsx)("input",{type:"checkbox",checked:!0===t.reasoning,onChange:t=>P(e.id,{reasoning:t.target.checked})}),s("desktop.builtinModelsReasoning")]}),(0,n.jsxs)("label",{style:{display:"flex",gap:6,alignItems:"center",fontSize:12,color:"var(--text)",flex:i?1:void 0,width:i?"100%":void 0},children:[s("desktop.modelsContextWindow"),(0,n.jsx)("input",{type:"number",min:1,value:t.contextWindow??"",placeholder:null!=e.contextWindow?String(e.contextWindow):"",onChange:t=>P(e.id,{contextWindow:t.target.value}),style:{flex:1,minWidth:0,padding:"4px 7px",fontSize:11,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:4,color:"var(--text)",fontFamily:"var(--font-mono)"}})]}),(0,n.jsxs)("label",{style:{display:"flex",gap:6,alignItems:"center",fontSize:12,color:"var(--text)",flex:i?1:void 0,width:i?"100%":void 0},children:[s("desktop.modelsMaxOutputTokens"),(0,n.jsx)("input",{type:"number",min:1,value:t.maxTokens??"",placeholder:null!=e.maxTokens?String(e.maxTokens):"",onChange:t=>P(e.id,{maxTokens:t.target.value}),style:{flex:1,minWidth:0,padding:"4px 7px",fontSize:11,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:4,color:"var(--text)",fontFamily:"var(--font-mono)"}})]})]}),(0,n.jsx)("div",{style:{fontSize:11,fontWeight:600,color:"var(--text-dim)"},children:s("desktop.builtinModelsThinking")}),(0,n.jsx)(lF,{value:t.thinkingLevelMap,onChange:t=>P(e.id,{thinkingLevelMap:t})})]})]},e.id)})}),(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[(0,n.jsx)("button",{type:"button",onClick:()=>{E().catch(()=>{})},disabled:x||0===h.size,style:{alignSelf:"flex-start",padding:"5px 14px",background:h.size>0&&!x?"var(--accent)":"var(--bg-panel)",border:"none",borderRadius:5,color:h.size>0&&!x?"#fff":"var(--text-dim)",cursor:h.size>0&&!x?"pointer":"not-allowed",fontSize:12,fontWeight:600},children:x?s("desktop.modelsSaving"):b?s("desktop.modelsSaved"):s("desktop.modelsSave")}),h.size>0&&(0,n.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)"},children:s("desktop.builtinModelsDirty",{count:h.size})})]})]})}let lv=["openai-completions","openai-responses","anthropic-messages","google-generative-ai","mistral-conversations"],ly="__custom__";function lb(){let{t:e}=(0,F.s)();return(0,r.useCallback)((t,o)=>e(t,o),[e])}function lw({label:e,children:t}){return(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,n.jsx)("label",{style:{fontSize:11,color:"var(--text-muted)",fontWeight:500},children:e}),t]})}let lj={padding:"6px 9px",background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:5,color:"var(--text)",fontSize:12,outline:"none",width:"100%",boxSizing:"border-box"};function lS({value:e,onChange:t,placeholder:o,mono:r,inputRef:s}){return(0,n.jsx)("input",{ref:s,value:e,onChange:e=>t(e.target.value),placeholder:o,style:{...lj,fontFamily:r?"var(--font-mono)":"inherit"}})}function lC({value:e,onChange:t,placeholder:o,mono:s,onKeyDown:i,autoComplete:a="off",spellCheck:l=!1,style:d}){let c=lb(),[p,u]=(0,r.useState)(!1);return(0,r.useEffect)(()=>{e||u(!1)},[e]),(0,n.jsxs)("div",{style:{position:"relative",width:"100%",...d},children:[(0,n.jsx)("input",{type:p?"text":"password",value:e,onChange:e=>t(e.target.value),onKeyDown:i,placeholder:o,style:{...lj,paddingRight:34,fontFamily:s?"var(--font-mono)":"inherit"},autoComplete:a,spellCheck:l}),(0,n.jsx)("button",{type:"button",onClick:()=>u(e=>!e),"aria-label":c(p?"desktop.modelsHideApiKey":"desktop.modelsShowApiKey"),title:c(p?"desktop.modelsHideApiKey":"desktop.modelsShowApiKey"),style:{position:"absolute",right:5,top:"50%",transform:"translateY(-50%)",width:24,height:24,padding:0,border:"none",background:"transparent",color:"var(--text-dim)",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center"},children:p?(0,n.jsx)(lh.G,{size:15}):(0,n.jsx)(rG.b,{size:15})})]})}function lT({value:e,onChange:t,placeholder:o}){return(0,n.jsx)("input",{type:"number",value:e,onChange:e=>t(e.target.value),placeholder:o,style:lj})}function lR({value:e,onChange:t,options:o,required:r}){let s=lb();return(0,n.jsxs)("select",{value:e,onChange:e=>t(e.target.value),style:{...lj,color:e?"var(--text)":"var(--text-dim)"},children:[!r&&(0,n.jsx)("option",{value:"",children:s("desktop.modelsInheritNone")}),o.map(e=>(0,n.jsx)("option",{value:e,children:e},e))]})}function lz({label:e,checked:t,onChange:o}){return(0,n.jsxs)("label",{style:{display:"flex",alignItems:"center",gap:6,cursor:"pointer",fontSize:12,color:"var(--text-muted)"},children:[(0,n.jsx)("input",{type:"checkbox",checked:t,onChange:e=>o(e.target.checked),style:{width:13,height:13,accentColor:"var(--accent)",cursor:"pointer"}}),e]})}function lI({children:e}){return(0,n.jsx)("div",{style:{fontSize:11,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:2},children:e})}function lM({name:e,provider:t,onChange:o,onRename:s,onDelete:i,onAddModels:a,onAddModel:l}){let d=lb(),[c,p]=(0,r.useState)(e),[u,h]=(0,r.useState)({phase:"idle"}),[g,m]=(0,r.useState)(""),[f,x]=(0,r.useState)([]),k=(0,r.useRef)(0),v=(0,r.useRef)(null);(0,r.useEffect)(()=>p(e),[e]);let y=(e,n)=>o({...t,[e]:n});(0,r.useEffect)(()=>{t.api||o({...t,api:"openai-completions"})},[t.api]),(0,r.useEffect)(()=>{k.current+=1,h({phase:"idle"}),m(""),x([])},[e,t.baseUrl,t.api,t.apiKey]);let b=(0,r.useCallback)(async()=>{if("loading"===u.phase)return;let o=++k.current;h({phase:"loading"}),x([]);try{let n=await fetch("/api/models-config/discover",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({providerName:e,provider:{...t,models:void 0}})}),r=await n.json();if(o!==k.current)return;if(!n.ok||r.error||!r.models)return void h({phase:"error",message:r.error??`HTTP ${n.status}`});h({phase:"success",models:r.models,endpoint:r.endpoint??t.baseUrl??""})}catch(e){if(o!==k.current)return;h({phase:"error",message:e instanceof Error?e.message:String(e)})}},[u.phase,e,t]),w=new Set((t.models??[]).map(e=>e.id)),j="success"===u.phase?u.models:[],S=g.trim().toLocaleLowerCase(),C=j.filter(e=>!S||e.id.toLocaleLowerCase().includes(S)||e.name?.toLocaleLowerCase().includes(S)),T=C.slice(0,300),R=T.filter(e=>!w.has(e.id)).map(e=>e.id),z=f.filter(e=>!w.has(e)).length,I=R.length>0&&R.every(e=>f.includes(e)),M=!I&&R.some(e=>f.includes(e));return(0,r.useEffect)(()=>{v.current&&(v.current.indeterminate=M)},[M]),(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[(0,n.jsx)(lI,{children:d("desktop.modelsProvider")}),(0,n.jsx)("button",{onClick:i,style:{padding:"3px 8px",background:"none",border:"1px solid rgba(239,68,68,0.3)",borderRadius:4,color:"#ef4444",cursor:"pointer",fontSize:11},children:d("desktop.delete")})]}),(0,n.jsxs)(lw,{label:d("desktop.modelsProviderName"),children:[(0,n.jsx)(lS,{value:c,onChange:p,placeholder:"provider-name",mono:!0}),c!==e&&c.trim()&&(0,n.jsx)("button",{onClick:()=>s(c.trim()),style:{marginTop:4,padding:"3px 10px",background:"var(--accent)",border:"none",borderRadius:4,color:"#fff",cursor:"pointer",fontSize:11,alignSelf:"flex-start"},children:d("desktop.rename")})]}),(0,n.jsx)(lw,{label:d("desktop.modelsBaseUrl"),children:(0,n.jsx)(lS,{value:t.baseUrl??"",onChange:e=>y("baseUrl",e||void 0),placeholder:"http(s)://host:port/v1",mono:!0})}),(0,n.jsxs)(lw,{label:d("desktop.modelsApiKey"),children:[(0,n.jsx)(lC,{value:t.apiKey??"",onChange:e=>y("apiKey",e||void 0),placeholder:d("desktop.modelsApiKeyPlaceholder"),mono:!0}),(0,n.jsx)("span",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:d("desktop.modelsApiKeyHelp")})]}),(0,n.jsx)(lw,{label:d("desktop.modelsApi"),children:(0,n.jsx)(lR,{value:t.api??"openai-completions",onChange:e=>y("api",e),options:lv,required:!0})}),(0,n.jsxs)("div",{style:{borderTop:"1px solid var(--border)",paddingTop:14,display:"flex",flexDirection:"column",gap:10},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:["success"!==u.phase&&(0,n.jsx)("button",{onClick:b,disabled:"loading"===u.phase,style:{height:30,padding:"0 12px",border:"1px solid var(--border)",borderRadius:5,background:"var(--bg-panel)",color:t.baseUrl?.trim()&&"loading"!==u.phase?"var(--text-muted)":"var(--text-dim)",cursor:t.baseUrl?.trim()&&"loading"!==u.phase?"pointer":"not-allowed",fontSize:11},children:"loading"===u.phase?d("desktop.modelsDiscoveryFetching"):d("desktop.modelsDiscoveryFetch")}),(0,n.jsx)("button",{onClick:l,title:d("desktop.modelsAddModelManual"),style:{height:30,padding:"0 12px",border:"none",borderRadius:5,background:"var(--accent)",color:"#fff",cursor:"pointer",fontSize:11,fontWeight:600},children:d("desktop.modelsAddModelManual")})]}),"error"===u.phase&&(0,n.jsx)("div",{style:{padding:"7px 9px",border:"1px solid rgba(239,68,68,0.3)",borderRadius:5,color:"#ef4444",fontSize:11,lineHeight:1.4},children:u.message}),"success"===u.phase&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("input",{value:g,onChange:e=>m(e.target.value),placeholder:d("desktop.modelsDiscoveryFilterPlaceholder",{count:u.models.length}),"aria-label":d("desktop.modelsDiscoveryFilter"),style:{...lj,width:"100%",minWidth:0}}),(0,n.jsxs)("div",{style:{maxHeight:220,overflowY:"auto",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-panel)"},children:[(0,n.jsxs)("label",{style:{minHeight:32,padding:"5px 9px",display:"flex",alignItems:"center",gap:8,position:"sticky",top:0,zIndex:1,borderBottom:"1px solid var(--border)",background:"var(--bg)",cursor:R.length?"pointer":"default",color:"var(--text-muted)",fontSize:10,fontWeight:600},children:[(0,n.jsx)("input",{ref:v,type:"checkbox",checked:I,disabled:0===R.length,onChange:()=>{let e=new Set(R);x(t=>I?t.filter(t=>!e.has(t)):Array.from(new Set([...t,...R])))},style:{width:13,height:13,accentColor:"var(--accent)",flexShrink:0}}),d("desktop.modelsDiscoverySelectShown")]}),0===T.length?(0,n.jsx)("div",{style:{padding:12,color:"var(--text-dim)",fontSize:11},children:d("desktop.modelsDiscoveryNoMatches")}):T.map((e,t)=>{let o=w.has(e.id),r=f.includes(e.id);return(0,n.jsxs)("label",{style:{minHeight:36,padding:"6px 9px",display:"flex",alignItems:"center",gap:8,borderTop:0===t?"none":"1px solid var(--border)",cursor:o?"default":"pointer",opacity:o?.65:1},children:[(0,n.jsx)("input",{type:"checkbox",checked:r||o,disabled:o,onChange:()=>{var t;return t=e.id,void x(e=>e.includes(t)?e.filter(e=>e!==t):[...e,t])},style:{width:13,height:13,accentColor:"var(--accent)",flexShrink:0}}),(0,n.jsxs)("span",{style:{minWidth:0,flex:1},children:[(0,n.jsx)("span",{style:{display:"block",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text)",fontSize:11},children:e.name??e.id}),e.name&&(0,n.jsx)("code",{style:{display:"block",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontSize:10,fontFamily:"var(--font-mono)"},children:e.id})]}),o&&(0,n.jsx)("span",{style:{color:"var(--text-dim)",fontSize:10},children:d("desktop.modelsDiscoveryAdded")})]},e.id)})]}),(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:10},children:[(0,n.jsx)("span",{title:u.endpoint,style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontSize:10},children:C.length>T.length?d("desktop.modelsDiscoveryShowing",{shown:T.length,total:C.length}):d("desktop.modelsDiscoveryFetched",{count:u.models.length})}),(0,n.jsx)("button",{onClick:()=>{if("success"!==u.phase)return;let e=new Set(f),t=u.models.filter(t=>e.has(t.id)&&!w.has(t.id));0!==t.length&&(a(t),x([]))},disabled:0===z,style:{height:28,padding:"0 11px",border:"none",borderRadius:5,background:z?"var(--accent)":"var(--bg-panel)",color:z?"#fff":"var(--text-dim)",cursor:z?"pointer":"not-allowed",fontSize:11,fontWeight:600,whiteSpace:"nowrap"},children:z?d("desktop.modelsDiscoveryAddSelectedCount",{count:z}):d("desktop.modelsDiscoveryAddSelected")})]})]})]})]})}let lP=["off","minimal","low","medium","high","xhigh","max"],lE={off:"var(--text-dim)",minimal:"var(--text-muted)",low:"#60a5fa",medium:"#a78bfa",high:"#f472b6",xhigh:"#fb923c",max:"#ef4444"};function lF({value:e,onChange:t}){let o=lb(),r=e??{},s=(e,o)=>{let n={...r};"omit"===o?delete n[e]:n[e]=o,t(Object.keys(n).length?n:void 0)};return(0,n.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:2},children:lP.map(e=>{let t=r[e],i=e in r?null===t?"null":"string":"omit",a="string"==typeof t?t:"",l=lE[e],d={padding:"4px 10px",fontSize:10,border:"none",cursor:"pointer",fontWeight:400,transition:"background 0.1s, color 0.1s",whiteSpace:"nowrap",background:"var(--bg-panel)",color:"var(--text-dim)"},c={background:"var(--accent)",color:"#fff",fontWeight:600};return(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"5px 4px",borderRadius:6,background:"transparent",border:"1px solid transparent"},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:5,width:68,flexShrink:0},children:[(0,n.jsx)("span",{style:{width:6,height:6,borderRadius:"50%",background:l,flexShrink:0,opacity:"null"===i?.3:1}}),(0,n.jsx)("span",{style:{fontSize:11,fontFamily:"var(--font-mono)",color:"null"===i?"var(--text-dim)":"var(--text-muted)",textDecoration:"null"===i?"line-through":"none"},children:e})]}),(0,n.jsxs)("div",{style:{display:"flex",borderRadius:5,border:"1px solid var(--border)",overflow:"hidden",flexShrink:0},children:[(0,n.jsx)("button",{onClick:()=>s(e,"omit"),style:{...d,..."omit"===i?c:{}},children:o("desktop.modelsDefault")}),(0,n.jsx)("button",{onClick:()=>s(e,null),style:{...d,borderLeft:"1px solid var(--border)",..."null"===i?{background:"#ef4444",color:"#fff",fontWeight:600}:{}},children:o("desktop.modelsDisabled")})]}),(0,n.jsxs)("div",{style:{display:"flex",borderRadius:5,border:`1px solid ${"string"===i?"var(--accent)":"var(--border)"}`,overflow:"hidden",transition:"border-color 0.1s"},children:[(0,n.jsx)("button",{onClick:()=>s(e,a||e),style:{...d,..."string"===i?c:{},borderRight:"1px solid var(--border)",flexShrink:0},children:o("desktop.modelsCustom")}),(0,n.jsx)("input",{value:a,onChange:t=>s(e,t.target.value),onFocus:()=>{"string"!==i&&s(e,a||e)},placeholder:e,maxLength:10,style:{width:"12ch",background:"string"===i?"var(--bg)":"var(--bg-panel)",border:"none",outline:"none",color:"string"===i?"var(--text)":"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:11,padding:"4px 7px",transition:"background 0.1s, color 0.1s"}})]})]},e)})})}let lD={thinkingFormat:"deepseek",requiresReasoningContentOnAssistantMessages:!0};function lW({providerName:e,provider:t,model:o,onChange:s,onDelete:i}){let a=lb(),[l,d]=(0,r.useState)({phase:"idle"}),[c,p]=(0,r.useState)({phase:"idle"}),u=(0,r.useRef)(0),g=(0,r.useRef)(null),m=(e,t)=>s({...o,[e]:t}),f=(()=>{if("idle"===l.phase)return null;if("testing"===l.phase)return a("desktop.modelsTestingConnection");let e=[void 0!==l.latencyMs?`${l.latencyMs}ms`:null,void 0!==l.status?`HTTP ${l.status}`:null].filter(Boolean);return"success"===l.phase?[a("desktop.modelsConnected"),...e,l.responseText||null].filter(Boolean).join(" \xb7 "):[a("desktop.modelsFailed"),...e,l.message].filter(Boolean).join(" \xb7 ")})();(0,r.useEffect)(()=>{d({phase:"idle"})},[e,t.baseUrl,t.api,t.apiKey,o.id,o.api]);let x=(0,r.useCallback)(async()=>{if(o.id.trim()&&"testing"!==l.phase){d({phase:"testing"});try{let n=await fetch("/api/models-config/test",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({providerName:e,provider:t,model:o})}),r=await n.json();if(!n.ok||!r.ok)return void d({phase:"error",message:r.error??`HTTP ${n.status}`,latencyMs:r.latencyMs,status:r.status});d({phase:"success",latencyMs:r.latencyMs,status:r.status,responseText:r.responseText})}catch(e){d({phase:"error",message:e instanceof Error?e.message:String(e)})}}},[o,t,e,l.phase]);(0,r.useEffect)(()=>{u.current+=1,p({phase:"idle"}),g.current=null},[e,t.baseUrl,o.id]);let k=(0,r.useCallback)(async()=>{let n=o.id.trim();if(!n||"loading"===c.phase)return;let r=++u.current;p({phase:"loading"});try{let i=new URLSearchParams({q:n,provider:e,limit:"50"});t.baseUrl?.trim()&&i.set("baseUrl",t.baseUrl.trim());let a=await fetch(`/api/models-config/catalog?${i}`),l=await a.json();if(r!==u.current)return;if(!a.ok||l.error||!l.recommendation)return void p({phase:"error",message:l.error??`HTTP ${a.status}`});let d=function(e,t){let o={...e},n=0;if(!e.name?.trim()&&t.name&&(o.name=t.name,n+=1),void 0===e.reasoning&&!0===t.reasoning&&(o.reasoning=!0,n+=1),!e.input?.length&&t.input?.length&&(o.input=[...t.input],n+=1),void 0===e.contextWindow&&void 0!==t.contextWindow&&(o.contextWindow=t.contextWindow,n+=1),void 0===e.maxTokens&&void 0!==t.maxTokens&&(o.maxTokens=t.maxTokens,n+=1),t.cost){let r={...e.cost??{}},s=!1;for(let e of["input","output","cacheRead","cacheWrite"])void 0===r[e]&&void 0!==t.cost[e]&&(r[e]=t.cost[e],s=!0,n+=1);s&&(o.cost=r)}return{model:o,appliedCount:n}}(o,l.recommendation.preset);d.appliedCount>0&&(g.current=o,s(d.model)),p({phase:"success",recommendation:l.recommendation,appliedCount:d.appliedCount})}catch(e){if(r!==u.current)return;p({phase:"error",message:e instanceof Error?e.message:String(e)})}},[c.phase,o,s,t.baseUrl,e]),v=(()=>{if("success"!==c.phase)return null;let{recommendation:t,appliedCount:o}=c,n=o>0?a("desktop.modelsCatalogFilled",{count:o}):a("desktop.modelsCatalogNoEmptyFields");if("unreliable"===t.price.status){let e="no-exact-match"===t.price.reason?a("desktop.modelsCatalogNoExactMatch"):a("desktop.modelsCatalogPriceUnreliable");return`${n} \xb7 ${e}`}let r="provider"===t.price.method?a("desktop.modelsCatalogPriceProvider",{provider:t.price.providerName??t.price.providerId??e}):"base-url"===t.price.method?a("desktop.modelsCatalogPriceBaseUrl",{provider:t.price.providerName??t.price.providerId??e}):a("desktop.modelsCatalogPriceConsensus",{support:t.price.support,total:t.price.total});return`${n} \xb7 ${r}`})(),y="error"===c.phase?c.message:v,b="error"===c.phase?"#ef4444":"success"===c.phase&&"unreliable"===c.recommendation.price.status?"#d97706":"var(--text-dim)";return(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[(0,n.jsx)(lI,{children:a("desktop.modelsModelSection")}),(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[f&&(0,n.jsx)("span",{title:f,style:{maxWidth:260,height:24,padding:"0 8px",border:`1px solid ${"error"===l.phase?"#fecaca":"success"===l.phase?"#bbf7d0":"var(--border)"}`,borderRadius:4,background:"error"===l.phase?"#fee2e2":"success"===l.phase?"#dcfce7":"#e5e7eb",color:"#111827",fontSize:11,display:"inline-flex",alignItems:"center",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",boxSizing:"border-box"},children:f}),(0,n.jsxs)("button",{onClick:x,disabled:!o.id.trim()||"testing"===l.phase,title:a("desktop.modelsTestConnection"),style:{height:24,padding:"0 8px",background:"success"===l.phase?"#16a34a":"none",border:`1px solid ${"success"===l.phase?"#16a34a":"var(--border)"}`,borderRadius:4,color:"success"===l.phase?"#fff":o.id.trim()&&"testing"!==l.phase?"var(--text-muted)":"var(--text-dim)",cursor:o.id.trim()&&"testing"!==l.phase?"pointer":"not-allowed",fontSize:11,display:"inline-flex",alignItems:"center",justifyContent:"center",boxSizing:"border-box",gap:5},children:["success"===l.phase&&(0,n.jsx)(h.S,{size:11}),"testing"===l.phase?a("desktop.modelsTesting"):"success"===l.phase?a("desktop.modelsOk"):a("desktop.modelsTest")]}),(0,n.jsx)("button",{onClick:i,style:{height:24,padding:"0 8px",background:"none",border:"1px solid rgba(239,68,68,0.3)",borderRadius:4,color:"#ef4444",cursor:"pointer",fontSize:11,boxSizing:"border-box"},children:a("desktop.modelsRemove")})]})]}),(0,n.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10},children:[(0,n.jsx)(lw,{label:a("desktop.modelsIdRequired"),children:(0,n.jsx)(lS,{value:o.id,onChange:e=>m("id",e),placeholder:"model-id",mono:!0})}),(0,n.jsx)(lw,{label:a("desktop.modelsName"),children:(0,n.jsx)(lS,{value:o.name??"",onChange:e=>m("name",e||void 0),placeholder:a("desktop.modelsDisplayName")})})]}),(0,n.jsxs)("div",{style:{padding:"10px 0",borderTop:"1px solid var(--border)",borderBottom:"1px solid var(--border)"},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[(0,n.jsx)("button",{onClick:()=>void k(),disabled:!o.id.trim()||"loading"===c.phase,style:{height:28,padding:"0 10px",border:"1px solid var(--border)",borderRadius:5,background:"var(--bg-panel)",color:o.id.trim()&&"loading"!==c.phase?"var(--text-muted)":"var(--text-dim)",cursor:o.id.trim()&&"loading"!==c.phase?"pointer":"not-allowed",fontSize:11},children:"loading"===c.phase?a("desktop.modelsCatalogFilling"):a("desktop.modelsCatalogFill")}),(0,n.jsx)("a",{href:"https://github.com/anomalyco/models.dev",target:"_blank",rel:"noreferrer",style:{marginLeft:"auto",color:"var(--text-dim)",fontSize:10,textDecoration:"none"},children:a("desktop.modelsCatalogSource")})]}),(0,n.jsxs)("div",{"aria-live":"polite",style:{marginTop:6,height:20,display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,color:b,fontSize:10},children:[(0,n.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:y}),"success"===c.phase&&g.current&&(0,n.jsx)("button",{onClick:()=>{let e=g.current;e&&(g.current=null,s(e),p({phase:"idle"}))},style:{background:"none",border:"none",color:"var(--accent)",cursor:"pointer",fontSize:10,flexShrink:0},children:a("desktop.modelsCatalogUndo")})]})]}),(0,n.jsx)(lw,{label:a("desktop.modelsApiOverride"),children:(0,n.jsx)(lR,{value:o.api??"",onChange:e=>m("api",e||void 0),options:lv})}),(0,n.jsxs)("div",{style:{display:"flex",gap:20,flexWrap:"wrap"},children:[(0,n.jsx)(lz,{label:a("desktop.modelsReasoningThinking"),checked:o.reasoning??!1,onChange:e=>m("reasoning",e||void 0)}),(0,n.jsx)(lz,{label:a("desktop.modelsImageInput"),checked:o.input?.includes("image")??!1,onChange:e=>m("input",e?["text","image"]:void 0)})]}),o.reasoning&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(lz,{label:a("desktop.modelsDeepSeekCompat"),checked:o.compat?.thinkingFormat==="deepseek",onChange:e=>s(function(e,t){if(t)return{...e,compat:{...e.compat??{},...lD}};if(!e.compat)return e;let o={...e.compat};return delete o.thinkingFormat,delete o.requiresReasoningContentOnAssistantMessages,{...e,compat:Object.keys(o).length?o:void 0}}(o,e))}),(0,n.jsxs)("div",{children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:8},children:[(0,n.jsx)(lI,{children:a("desktop.modelsThinkingLevelMap")}),o.thinkingLevelMap&&(0,n.jsx)("button",{onClick:()=>m("thinkingLevelMap",void 0),style:{fontSize:10,padding:"2px 7px",background:"none",border:"1px solid var(--border)",borderRadius:4,color:"var(--text-dim)",cursor:"pointer"},children:a("desktop.modelsClearAll")})]}),(0,n.jsx)(lF,{value:o.thinkingLevelMap,onChange:e=>m("thinkingLevelMap",e)})]})]}),(0,n.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10},children:[(0,n.jsx)(lw,{label:a("desktop.modelsContextWindow"),children:(0,n.jsx)(lT,{value:void 0!==o.contextWindow?String(o.contextWindow):"",onChange:e=>m("contextWindow",e?parseInt(e):void 0),placeholder:"128000"})}),(0,n.jsx)(lw,{label:a("desktop.modelsMaxOutputTokens"),children:(0,n.jsx)(lT,{value:void 0!==o.maxTokens?String(o.maxTokens):"",onChange:e=>m("maxTokens",e?parseInt(e):void 0),placeholder:"16384"})})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)(lI,{children:a("desktop.modelsCostPerMillionTokens")}),(0,n.jsx)("div",{style:{marginTop:8,display:"grid",gridTemplateColumns:"1fr 1fr 1fr 1fr",gap:8},children:["input","output","cacheRead","cacheWrite"].map(e=>(0,n.jsx)(lw,{label:e,children:(0,n.jsx)(lT,{value:o.cost?.[e]!==void 0?String(o.cost[e]):"",onChange:t=>{let n;return n=parseFloat(t),void s({...o,cost:{...o.cost??{},[e]:isNaN(n)?void 0:n}})},placeholder:"0"})},e))})]})]})}function lA({provider:e,onRefresh:t,onRegisterBuiltinFlush:o,onBuiltinProviderChange:s}){let i=lb(),[a,l]=(0,r.useState)({phase:"idle"}),[d,c]=(0,r.useState)(""),p=(0,r.useRef)(null),u=(0,r.useRef)(null);(0,r.useEffect)(()=>{("auth"===a.phase||"prompt"===a.phase)&&setTimeout(()=>u.current?.focus(),50)},[a.phase]),(0,r.useEffect)(()=>{l({phase:"idle"}),c(""),p.current?.close(),p.current=null},[e.id]),(0,r.useEffect)(()=>()=>{p.current?.close()},[]);let h=(0,r.useCallback)(()=>{p.current?.close(),l({phase:"connecting"}),c("");let o=new EventSource(`/api/auth/login/${encodeURIComponent(e.id)}`);p.current=o,o.onmessage=e=>{let n=JSON.parse(e.data);"auth"===n.type?(l({phase:"auth",url:n.url,instructions:n.instructions??null,token:n.token}),window.open(n.url,"_blank","noopener,noreferrer")):"device_code"===n.type?(l({phase:"device_code",userCode:n.userCode,verificationUri:n.verificationUri,intervalSeconds:n.intervalSeconds??null,expiresInSeconds:n.expiresInSeconds??null}),window.open(n.verificationUri,"_blank","noopener,noreferrer")):"prompt_request"===n.type?l({phase:"prompt",message:n.message,placeholder:n.placeholder??null,token:n.token}):"select_request"===n.type?l({phase:"select",message:n.message,options:n.options??[],token:n.token}):"progress"===n.type?l({phase:"progress",message:n.message}):"success"===n.type?(o.close(),l({phase:"success"}),t()):"error"===n.type?(o.close(),l({phase:"error",message:n.message})):"cancelled"===n.type&&(o.close(),l({phase:"idle"}))},o.onerror=()=>{o.close(),l(e=>"success"===e.phase?e:{phase:"error",message:i("desktop.modelsConnectionLost")})}},[e.id,t,i]),g=(0,r.useCallback)(async()=>{try{let t=await fetch(`/api/auth/logout/${encodeURIComponent(e.id)}`,{method:"POST"});if(t.ok)l({phase:"idle"});else{let e=await t.json().catch(()=>null);l({phase:"error",message:409===t.status?i("desktop.modelsAuthenticationStateChanged"):e?.error??`HTTP ${t.status}`})}}catch(e){l({phase:"error",message:e instanceof Error?e.message:String(e)})}finally{t()}},[e.id,t,i]),m=(0,r.useCallback)(async(t,o)=>{if(o.trim()){l({phase:"progress",message:i("desktop.modelsVerifying")});try{let n=await fetch(`/api/auth/login/${encodeURIComponent(e.id)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t,code:o.trim()})});if(!n.ok){let e=await n.json().catch(()=>({}));l({phase:"error",message:e.error??i("desktop.modelsServerError",{status:n.status})});return}c("")}catch(e){l({phase:"error",message:e instanceof Error?e.message:i("desktop.modelsNetworkError")})}}},[e.id,i]),f=(0,r.useCallback)(async(t,o)=>{l({phase:"progress",message:i("desktop.modelsContinuing")});try{let n=await fetch(`/api/auth/login/${encodeURIComponent(e.id)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t,code:o})});if(!n.ok){let e=await n.json().catch(()=>({}));l({phase:"error",message:e.error??i("desktop.modelsServerError",{status:n.status})})}}catch(e){l({phase:"error",message:e instanceof Error?e.message:i("desktop.modelsNetworkError")})}},[e.id,i]),x="connecting"===a.phase||"progress"===a.phase||"auth"===a.phase||"device_code"===a.phase||"prompt"===a.phase||"select"===a.phase;return(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[(0,n.jsx)(lI,{children:i("desktop.modelsSubscription")}),(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6},children:[(0,n.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:e.loggedIn?"#4ade80":"var(--border)",display:"inline-block"}}),(0,n.jsx)("span",{style:{fontSize:11,color:e.loggedIn?"#4ade80":"var(--text-dim)"},children:e.loggedIn?i("desktop.modelsConnected"):i("desktop.modelsNotConnected")})]})]}),(0,n.jsxs)("div",{style:{minHeight:48},children:["idle"===a.phase&&(0,n.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:e.loggedIn?i("desktop.modelsAlreadyConnected"):i("desktop.modelsConnectAccount",{provider:e.name})}),"connecting"===a.phase&&(0,n.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)"},children:i("desktop.modelsOpeningBrowser")}),"select"===a.phase&&(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[(0,n.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:a.message}),(0,n.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:a.options.map(e=>(0,n.jsx)("button",{onClick:()=>f(a.token,e.id),style:{padding:"6px 9px",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:5,color:"var(--text)",cursor:"pointer",fontSize:12,textAlign:"left"},children:e.label},e.id))})]}),("auth"===a.phase||"prompt"===a.phase)&&(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[(0,n.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:"auth"===a.phase?i("desktop.modelsCompleteSignIn"):a.message}),"auth"===a.phase&&(0,n.jsxs)("p",{style:{margin:0,fontSize:11,color:"var(--text-dim)",lineHeight:1.5},children:[i("desktop.modelsBrowserDidNotOpen")," ",(0,n.jsx)("a",{href:a.url,target:"_blank",rel:"noopener noreferrer",style:{color:"var(--accent)",wordBreak:"break-all"},children:i("desktop.modelsOpenLoginPage")}),"."]}),(0,n.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,n.jsx)("input",{ref:u,value:d,onChange:e=>c(e.target.value),onKeyDown:e=>{"Enter"===e.key&&m(a.token,d)},placeholder:"auth"===a.phase?"http://localhost:1455/auth/callback?code=…":a.placeholder??i("desktop.modelsEnterValue"),style:{flex:1,padding:"6px 9px",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:5,color:"var(--text)",fontSize:12,outline:"none",fontFamily:"var(--font-mono)",boxSizing:"border-box"}}),(0,n.jsx)("button",{onClick:()=>m(a.token,d),disabled:!d.trim(),style:{padding:"6px 12px",background:d.trim()?"var(--accent)":"var(--bg-panel)",border:"none",borderRadius:5,color:d.trim()?"#fff":"var(--text-dim)",cursor:d.trim()?"pointer":"not-allowed",fontSize:12,fontWeight:600,flexShrink:0},children:i("desktop.submit")})]})]}),"device_code"===a.phase&&(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[(0,n.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:i("desktop.modelsOpenVerificationPage")}),(0,n.jsx)("div",{style:{padding:"8px 10px",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:5,color:"var(--text)",fontSize:16,fontWeight:700,fontFamily:"var(--font-mono)",letterSpacing:0},children:a.userCode}),(0,n.jsxs)("p",{style:{margin:0,fontSize:11,color:"var(--text-dim)",lineHeight:1.5},children:[(0,n.jsx)("a",{href:a.verificationUri,target:"_blank",rel:"noopener noreferrer",style:{color:"var(--accent)",wordBreak:"break-all"},children:a.verificationUri}),a.expiresInSeconds?` ${i("desktop.modelsExpiresInMinutes",{count:Math.ceil(a.expiresInSeconds/60)})}`:""]})]}),"progress"===a.phase&&(0,n.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)"},children:a.message}),"success"===a.phase&&(0,n.jsx)("p",{style:{margin:0,fontSize:12,color:"#4ade80"},children:i("desktop.modelsConnectedSuccessfully")}),"error"===a.phase&&(0,n.jsx)("p",{style:{margin:0,fontSize:12,color:"#f87171"},children:a.message})]}),(0,n.jsx)("div",{style:{display:"flex",gap:8},children:x?(0,n.jsx)("button",{onClick:()=>{p.current?.close(),l({phase:"idle"})},style:{padding:"5px 12px",background:"none",border:"1px solid var(--border)",borderRadius:5,color:"var(--text-muted)",cursor:"pointer",fontSize:12},children:i("desktop.cancel")}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("button",{onClick:h,style:{padding:"5px 14px",background:"var(--accent)",border:"none",borderRadius:5,color:"#fff",cursor:"pointer",fontSize:12,fontWeight:600},children:e.loggedIn?i("desktop.modelsReLogin"):i("desktop.modelsLogin")}),e.loggedIn&&(0,n.jsx)("button",{onClick:g,style:{padding:"5px 12px",background:"none",border:"1px solid rgba(239,68,68,0.3)",borderRadius:5,color:"#ef4444",cursor:"pointer",fontSize:12},children:i("desktop.modelsDisconnect")})]})}),(0,n.jsx)(lk,{providerId:e.id,onRegisterFlush:o,onConfigChange:s})]})}function lN({provider:e,onRefresh:t,onRegisterBuiltinFlush:o,onBuiltinProviderChange:s}){let i=lb(),[a,l]=(0,r.useState)(""),[d,c]=(0,r.useState)(!1),[p,u]=(0,r.useState)(!1),[g,m]=(0,r.useState)(null),[f,x]=(0,r.useState)(!1);(0,r.useEffect)(()=>{l(""),m(null),x(!1)},[e.id]);let k=(0,r.useCallback)(async()=>{if(a.trim()){c(!0),m(null),x(!1);try{let o=await fetch(`/api/auth/api-key/${encodeURIComponent(e.id)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:a.trim()})}),n=await o.json();!o.ok||n.error?m(n.error??`HTTP ${o.status}`):(l(""),x(!0),setTimeout(()=>x(!1),2e3),t())}catch(e){m(String(e))}finally{c(!1)}}},[a,e.id,t]),v=(0,r.useCallback)(async()=>{u(!0),m(null);try{let t=await fetch(`/api/auth/api-key/${encodeURIComponent(e.id)}`,{method:"DELETE"}),o=await t.json();(!t.ok||o.error)&&m(409===t.status?i("desktop.modelsAuthenticationStateChanged"):o.error??`HTTP ${t.status}`)}catch(e){m(String(e))}finally{t(),u(!1)}},[e.id,t,i]);return(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[(0,n.jsx)(lI,{children:i("desktop.modelsApiKey")}),(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6},children:[(0,n.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:e.configured?"#4ade80":"var(--border)",display:"inline-block"}}),(0,n.jsx)("span",{style:{fontSize:11,color:e.configured?"#4ade80":"var(--text-dim)"},children:e.configured?i("desktop.modelsConfigured"):i("desktop.modelsNotConfigured")})]})]}),(0,n.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:e.configured?i("desktop.modelsApiKeyStored"):i("desktop.modelsEnableModels",{provider:e.displayName,count:e.modelCount,models:1===e.modelCount?i("desktop.modelsSingular"):i("desktop.modelsPlural")})}),(0,n.jsx)(lw,{label:i("desktop.modelsApiKey"),children:(0,n.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,n.jsx)(lC,{value:a,onChange:l,onKeyDown:e=>{"Enter"===e.key&&a.trim()&&k()},placeholder:e.configured?i("desktop.modelsEnterNewKey"):"sk-…",style:{flex:1},autoComplete:"off",spellCheck:!1,mono:!0}),(0,n.jsxs)("button",{onClick:k,disabled:d||!a.trim()||f,style:{padding:"6px 12px",background:f?"#16a34a":a.trim()?"var(--accent)":"var(--bg-panel)",border:"none",borderRadius:5,color:a.trim()||f?"#fff":"var(--text-dim)",cursor:d||!a.trim()||f?"not-allowed":"pointer",fontSize:12,fontWeight:600,flexShrink:0,display:"flex",alignItems:"center",gap:5},children:[f&&(0,n.jsx)(h.S,{size:12}),f?i("desktop.modelsSaved"):d?i("desktop.modelsSaving"):i("desktop.modelsSave")]})]})}),g&&(0,n.jsx)("p",{style:{margin:0,fontSize:12,color:"#f87171"},children:g}),e.configured&&(0,n.jsx)("button",{onClick:v,disabled:p,style:{alignSelf:"flex-start",padding:"5px 12px",background:"none",border:"1px solid rgba(239,68,68,0.3)",borderRadius:5,color:"#ef4444",cursor:p?"not-allowed":"pointer",fontSize:12},children:p?i("desktop.modelsRemoving"):i("desktop.modelsDisconnect")}),(0,n.jsx)(lk,{providerId:e.id,onRegisterFlush:o,onConfigChange:s})]})}function l$({oauthProviders:e,apiKeyProviders:t,onSelectOAuth:o,onSelectApiKey:s,onAddCustom:i,onClose:a}){let l=lb(),[d,p]=(0,r.useState)(""),u=(0,r.useRef)(null);(0,r.useEffect)(()=>{setTimeout(()=>u.current?.focus(),30)},[]);let h=d.trim().toLowerCase(),g=e.filter(e=>!e.loggedIn&&(!h||e.name.toLowerCase().includes(h))),m=t.filter(e=>!e.configured&&(!h||e.displayName.toLowerCase().includes(h)||e.id.toLowerCase().includes(h))),f=!h||"custom".includes(h)||"openai-compatible".includes(h)||"anthropic-compatible".includes(h),k=g.length+m.length+ +!!f,v={display:"flex",flexDirection:"row",alignItems:"center",gap:8,padding:"10px 12px",background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:7,boxSizing:"border-box",cursor:"pointer",minWidth:0,textAlign:"left",transition:"border-color 0.12s, background 0.12s",width:"100%"};return(0,n.jsx)("div",{style:{position:"fixed",inset:0,zIndex:1100,background:"rgba(0,0,0,0.4)",display:"flex",alignItems:"center",justifyContent:"center"},onClick:e=>{e.target===e.currentTarget&&a()},children:(0,n.jsxs)("div",{style:{width:820,maxWidth:"calc(100vw - 32px)",maxHeight:"min(72vh, calc(100vh - 32px))",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:10,display:"flex",flexDirection:"column",boxShadow:"0 8px 32px rgba(0,0,0,0.22)",overflow:"hidden"},children:[(0,n.jsxs)("div",{style:{padding:"10px 14px",borderBottom:"1px solid var(--border)",flexShrink:0,display:"flex",alignItems:"center",gap:8},children:[(0,n.jsx)(c.$,{size:13,style:{color:"var(--text-dim)",flexShrink:0}}),(0,n.jsx)("input",{ref:u,value:d,onChange:e=>p(e.target.value),onKeyDown:e=>{"Escape"===e.key&&a()},placeholder:l("desktop.modelsSearchProviders"),style:{flex:1,background:"none",border:"none",outline:"none",color:"var(--text)",fontSize:13,boxSizing:"border-box"}})]}),(0,n.jsx)("div",{style:{flex:1,overflowY:"auto",padding:14},children:0===k?(0,n.jsx)("div",{style:{padding:"20px 0",fontSize:12,color:"var(--text-dim)",textAlign:"center"},children:l("desktop.modelsNoProvidersMatch")}):(0,n.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(min(240px, 100%), 1fr))",gap:8},children:[f&&(0,n.jsx)("div",{style:{gridColumn:"1 / -1",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:l("desktop.modelsCustom")}),f&&(0,n.jsxs)("button",{onClick:()=>{i(),a()},style:v,onMouseEnter:e=>{e.currentTarget.style.borderColor="var(--accent)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.borderColor="var(--border)",e.currentTarget.style.background="var(--bg-panel)"},children:[(0,n.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,n.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)",lineHeight:1.3,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:l("desktop.modelsCompatibleProvider")}),(0,n.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:l("desktop.modelsCustomEndpointFormat")})]}),(0,n.jsx)("span",{style:{width:26,height:26,borderRadius:5,background:"var(--bg-hover)",border:"1px dashed var(--border)",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:(0,n.jsx)(x.c,{size:13,style:{color:"var(--text-dim)"}})})]}),g.length>0&&(0,n.jsx)("div",{style:{gridColumn:"1 / -1",paddingTop:6*!!f,fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:l("desktop.modelsSubscriptions")}),g.map(e=>(0,n.jsxs)("button",{onClick:()=>{o(e.id),a()},style:v,onMouseEnter:e=>{e.currentTarget.style.borderColor="var(--accent)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.borderColor="var(--border)",e.currentTarget.style.background="var(--bg-panel)"},children:[(0,n.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,n.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)",lineHeight:1.3,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name}),(0,n.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:"OAuth"})]}),(0,n.jsx)(sC,{id:e.id,size:28})]},e.id)),m.length>0&&(0,n.jsx)("div",{style:{gridColumn:"1 / -1",paddingTop:6*(g.length>0),fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:l("desktop.modelsApiKey")}),m.map(e=>(0,n.jsxs)("button",{onClick:()=>{s(e.id),a()},style:v,onMouseEnter:e=>{e.currentTarget.style.borderColor="var(--accent)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.borderColor="var(--border)",e.currentTarget.style.background="var(--bg-panel)"},children:[(0,n.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,n.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)",lineHeight:1.3,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.displayName}),(0,n.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:l("desktop.modelsCount",{count:e.modelCount})})]}),(0,n.jsx)(sC,{id:e.id,size:28})]},e.id))]})})]})})}function lL({existingProviders:e,onCancel:t,onSubmit:o}){let s=lb(),[i,a]=(0,r.useState)(""),[l,d]=(0,r.useState)(lv[0]),[c,p]=(0,r.useState)(lv[0]),[u,h]=(0,r.useState)(""),[g,m]=(0,r.useState)(""),[f,k]=(0,r.useState)(void 0),[v,y]=(0,r.useState)(!1),[b,w]=(0,r.useState)(""),[j,S]=(0,r.useState)(""),[C,T]=(0,r.useState)(""),[R,z]=(0,r.useState)(""),I=(0,r.useRef)(null);(0,r.useEffect)(()=>{setTimeout(()=>I.current?.focus(),30)},[]);let M=!u.trim()||/^https?:\/\//i.test(u.trim());return(0,n.jsx)("div",{style:{position:"fixed",inset:0,zIndex:1100,background:"rgba(0,0,0,0.4)",display:"flex",alignItems:"center",justifyContent:"center"},onClick:e=>{e.target===e.currentTarget&&t()},children:(0,n.jsxs)("div",{style:{width:480,maxWidth:"calc(100vw - 32px)",maxHeight:"min(82vh, calc(100vh - 32px))",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:10,display:"flex",flexDirection:"column",boxShadow:"0 8px 32px rgba(0,0,0,0.22)",overflow:"hidden"},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 16px",borderBottom:"1px solid var(--border)",flexShrink:0},children:[(0,n.jsx)("span",{style:{fontSize:14,fontWeight:700,color:"var(--text)"},children:s("desktop.modelsAddCustomTitle")}),(0,n.jsx)("button",{onClick:t,"aria-label":s("desktop.modelsClose"),title:s("desktop.modelsClose"),style:{background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",fontSize:20,lineHeight:1,padding:"2px 6px"},children:"\xd7"})]}),(0,n.jsxs)("div",{style:{padding:16,overflowY:"auto",display:"flex",flexDirection:"column",gap:14},children:[(0,n.jsx)(lw,{label:s("desktop.modelsProviderNameOptional"),children:(0,n.jsx)(lS,{value:i,onChange:a,placeholder:"new-provider",mono:!0,inputRef:I})}),(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,n.jsx)(lI,{children:s("desktop.modelsCallFormat")}),(0,n.jsxs)("select",{value:c,onChange:e=>{let t=e.target.value;(p(t),t===ly)?y(!0):d(t)},style:lj,children:[lv.map(e=>(0,n.jsx)("option",{value:e,children:e},e)),(0,n.jsx)("option",{value:ly,children:s("desktop.modelsCustomCallFormat")})]}),(0,n.jsx)("span",{style:{fontSize:10,color:"var(--text-dim)"},children:s("desktop.modelsCallFormatHelp")}),c===ly&&(0,n.jsx)("span",{style:{fontSize:10,color:"#d97706",lineHeight:1.4},children:s("desktop.modelsCustomCallFormatHelp")})]}),(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,n.jsx)(lI,{children:s("desktop.modelsImportProvider")}),(0,n.jsxs)("select",{value:R,onChange:t=>{var o;let n;return z(o=t.target.value),void((n=e.find(e=>e.name===o))&&(n.provider.api&&(d(n.provider.api),p(n.provider.api)),h(n.provider.baseUrl??""),m(n.provider.apiKey??""),k(n.provider.headers?{...n.provider.headers}:void 0)))},style:{...lj,color:R?"var(--text)":"var(--text-dim)"},children:[(0,n.jsx)("option",{value:"",children:s("desktop.modelsImportProviderPlaceholder")}),e.map(e=>(0,n.jsxs)("option",{value:e.name,children:[e.name,e.provider.api?` \xb7 ${e.provider.api}`:""]},e.name))]}),R&&(0,n.jsxs)("span",{style:{fontSize:10,color:"#4ade80"},children:[s("desktop.modelsImported"),": ",R]})]}),(0,n.jsxs)("div",{style:{borderTop:"1px solid var(--border)",paddingTop:12,display:"flex",flexDirection:"column",gap:4},children:[(0,n.jsx)(lI,{children:s("desktop.modelsFullUrl")}),v?(0,n.jsxs)("div",{style:{display:"flex",gap:6,alignItems:"center"},children:[(0,n.jsx)(lS,{value:u,onChange:h,placeholder:s("desktop.modelsUrlPlaceholder"),mono:!0}),(0,n.jsx)("button",{onClick:()=>{y(!1),h("")},title:s("desktop.modelsRemove"),style:{flexShrink:0,width:28,height:28,background:"none",border:"1px solid var(--border)",borderRadius:5,color:"var(--text-dim)",cursor:"pointer",fontSize:14,lineHeight:1,display:"flex",alignItems:"center",justifyContent:"center"},children:"\xd7"})]}):(0,n.jsxs)("button",{onClick:()=>y(!0),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:"7px 0",background:"none",border:"1px dashed var(--border)",borderRadius:5,color:"var(--text-muted)",cursor:"pointer",fontSize:12},onMouseEnter:e=>{e.currentTarget.style.borderColor="var(--accent)",e.currentTarget.style.color="var(--accent)"},onMouseLeave:e=>{e.currentTarget.style.borderColor="var(--border)",e.currentTarget.style.color="var(--text-muted)"},children:[(0,n.jsx)(x.c,{size:12}),s("desktop.modelsAddUrl")]}),u.trim()&&!M&&(0,n.jsx)("span",{style:{fontSize:10,color:"#ef4444"},children:s("desktop.modelsUrlInvalid")}),(0,n.jsxs)(lw,{label:s("desktop.modelsApiKey"),children:[(0,n.jsx)(lC,{value:g,onChange:m,placeholder:s("desktop.modelsApiKeyPlaceholder"),mono:!0}),(0,n.jsx)("span",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:s("desktop.modelsApiKeyHelp")})]})]}),(0,n.jsxs)("div",{style:{borderTop:"1px solid var(--border)",paddingTop:12,display:"flex",flexDirection:"column",gap:10},children:[(0,n.jsx)(lI,{children:s("desktop.modelsCustomRequest")}),(0,n.jsxs)(lw,{label:s("desktop.modelsRequestModelId"),children:[(0,n.jsx)(lS,{value:b,onChange:w,placeholder:"model-id",mono:!0}),(0,n.jsx)("span",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:s("desktop.modelsRequestModelIdHelp")})]}),(0,n.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10},children:[(0,n.jsx)(lw,{label:s("desktop.modelsRequestContextLength"),children:(0,n.jsx)(lT,{value:j,onChange:S,placeholder:"128000"})}),(0,n.jsx)(lw,{label:s("desktop.modelsRequestOutputLength"),children:(0,n.jsx)(lT,{value:C,onChange:T,placeholder:"16384"})})]})]})]}),(0,n.jsxs)("div",{style:{display:"flex",justifyContent:"flex-end",gap:8,padding:"10px 16px",borderTop:"1px solid var(--border)",flexShrink:0},children:[(0,n.jsx)("button",{onClick:t,style:{padding:"6px 14px",background:"none",border:"1px solid var(--border)",borderRadius:6,color:"var(--text-muted)",cursor:"pointer",fontSize:13},children:s("desktop.cancel")}),(0,n.jsx)("button",{onClick:()=>{let e=b.trim()?{id:b.trim(),...parseInt(j,10)>0?{contextWindow:parseInt(j,10)}:{},...parseInt(C,10)>0?{maxTokens:parseInt(C,10)}:{}}:void 0;o({name:i.trim(),api:l,...u.trim()?{baseUrl:u.trim()}:{},...g.trim()?{apiKey:g.trim()}:{},...f?{headers:f}:{},model:e})},disabled:!M,style:{padding:"6px 16px",background:M?"var(--accent)":"var(--bg-panel)",border:"none",borderRadius:6,color:M?"#fff":"var(--text-dim)",cursor:M?"pointer":"not-allowed",fontSize:13,fontWeight:600},children:s("desktop.modelsAdd")})]})]})})}function lO({embedded:e=!1,sessionId:t,onCloseAction:o,onSavedAction:s,onRegisterFlush:i}){let a=lb(),l=$(),[d,c]=(0,r.useState)({providers:{}}),[p,u]=(0,r.useState)(!0),[g,m]=(0,r.useState)(!1),[f,x]=(0,r.useState)(null),[k,v]=(0,r.useState)(!1),[y,b]=(0,r.useState)(null),[w,j]=(0,r.useState)([]),[S,C]=(0,r.useState)([]),[R,z]=(0,r.useState)(!1),[I,M]=(0,r.useState)(!1),[P,E]=(0,r.useState)({oauth:!1,apiKey:!1}),F=(0,r.useRef)({providers:{}}),D=(0,r.useRef)(new Map),W=(0,r.useRef)(0),A=(0,r.useRef)(!1);F.current=d;let N=(0,r.useCallback)(e=>{let t=e(F.current);return F.current=t,W.current+=1,c(t),t},[]),L=(0,r.useCallback)(()=>{fetch("/api/auth/combined").then(e=>e.json()).then(e=>{j(e.oauth??[]),C(e.apiKey??[])}).catch(()=>{}).finally(()=>E({oauth:!0,apiKey:!0}))},[]),O=(0,r.useCallback)((e,t)=>(D.current.set(e,t),()=>{D.current.get(e)===t&&D.current.delete(e)}),[]),H=(0,r.useCallback)(async()=>{for(let e of[...D.current.values()])await e()},[]);(0,r.useEffect)(()=>{if(i)return i(H)??void 0},[H,i]);let B=(0,r.useCallback)((e,t)=>{N(o=>{let n={...o.providers??{}};return t?n[e]=t:delete n[e],{...o,providers:n}}),s?.()},[s,N]),U=(0,r.useCallback)(async e=>{if(!A.current){A.current=!0,x(null);try{await H(),b(e)}catch(e){x(e instanceof Error?e.message:String(e))}finally{A.current=!1}}},[H]);(0,r.useEffect)(()=>{fetch("/api/models-config").then(e=>e.json()).then(e=>{let t=e.providers?e:{...e,providers:{}};F.current=t,W.current+=1,c(t)}).catch(()=>{let e={providers:{}};F.current=e,W.current+=1,c(e)}).finally(()=>u(!1)),L()},[L]);let _=(0,r.useCallback)(async e=>{if(!A.current){A.current=!0,x(null);try{await H();let t=e.name.trim()||"new-provider",o=t,n=1;for(;F.current.providers?.[o];)o=`${t}-${n++}`;let r={api:e.api||"openai-completions",...e.baseUrl?{baseUrl:e.baseUrl}:{},...e.apiKey?{apiKey:e.apiKey}:{},...e.headers?{headers:e.headers}:{},...e.model?{models:[e.model]}:{}};N(e=>({...e,providers:{...e.providers??{},[o]:r}})),b({type:"provider",name:o}),M(!1)}catch(e){x(e instanceof Error?e.message:String(e))}finally{A.current=!1}}},[H,N]),q=(0,r.useCallback)((e,t)=>{N(o=>({...o,providers:{...o.providers??{},[e]:t}}))},[N]),V=(0,r.useCallback)((e,t)=>{N(o=>{let n=Object.entries(o.providers??{}),r=n.findIndex(([t])=>t===e);return -1===r?o:(n[r]=[t,n[r][1]],{...o,providers:Object.fromEntries(n)})}),b(o=>o?"provider"===o.type&&o.name===e?{type:"provider",name:t}:"model"===o.type&&o.providerName===e?{...o,providerName:t}:o:o)},[N]),K=(0,r.useCallback)(e=>{let t=Object.keys(N(t=>{let o={...t.providers??{}};return delete o[e],{...t,providers:o}}).providers??{});b(t.length>0?{type:"provider",name:t[0]}:null)},[N]),G=(0,r.useCallback)(async e=>{if(!A.current){A.current=!0,x(null);try{await H();let t=N(t=>{let o=t.providers?.[e]??{},n=[...o.models??[],{id:""}];return{...t,providers:{...t.providers??{},[e]:{...o,models:n}}}}),o=(t.providers?.[e]?.models?.length??1)-1;b({type:"model",providerName:e,index:o})}catch(e){x(e instanceof Error?e.message:String(e))}finally{A.current=!1}}},[H,N]),J=(0,r.useCallback)((e,t)=>{N(o=>{let n=o.providers?.[e]??{},r=[...n.models??[]],s=new Set(r.map(e=>e.id));for(let e of t)s.has(e.id)||(s.add(e.id),r.push({id:e.id,name:e.name}));return{...o,providers:{...o.providers??{},[e]:{...n,models:r}}}})},[N]),Y=(0,r.useCallback)((e,t,o)=>{N(n=>{let r=n.providers?.[e]??{},s=[...r.models??[]];return s[t]=o,{...n,providers:{...n.providers??{},[e]:{...r,models:s}}}})},[N]),X=(0,r.useCallback)(async(e,t)=>{if(!A.current){A.current=!0,x(null);try{await H(),N(o=>{let n=o.providers?.[e]??{},r=[...n.models??[]];return r.splice(t,1),{...o,providers:{...o.providers??{},[e]:{...n,models:r.length?r:void 0}}}}),b({type:"provider",name:e})}catch(e){x(e instanceof Error?e.message:String(e))}finally{A.current=!1}}},[H,N]),Z=(0,r.useCallback)(async()=>{if(!g){m(!0),x(null),v(!1);try{await H();let e=F.current,t=await fetch("/api/models-config",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),o=await t.json();if(!t.ok||o.error)throw Error(o.error??`HTTP ${t.status}`);o.config&&(F.current=o.config,W.current+=1,c(o.config)),v(!0),s?.(),setTimeout(()=>v(!1),2e3)}catch(e){x(e instanceof Error?e.message:String(e))}finally{m(!1)}}},[H,s,g]),Q=(0,r.useCallback)(async()=>{try{await H(),o?.()}catch(e){x(e instanceof Error?e.message:String(e))}},[H,o]),ee=Object.entries(d.providers??{}),et=new Set([...w.map(e=>e.id),...S.map(e=>e.id)]),eo=ee.filter(([e])=>!et.has(e)),en=w.filter(e=>e.loggedIn),er=S.filter(e=>e.configured);(0,r.useEffect)(()=>{if(y||p||!P.oauth||!P.apiKey)return;let e=en[0]?{type:"oauth",providerId:en[0].id}:er[0]?{type:"apikey",providerId:er[0].id}:eo[0]?.[0]?{type:"provider",name:eo[0][0]}:null;e&&b(e)},[er,en,eo,p,P.apiKey,P.oauth,y]);let es=(()=>{if(!y)return null;if("oauth"===y.type){let e=w.find(e=>e.id===y.providerId);return e?(0,n.jsx)(lA,{provider:e,onRefresh:L,onRegisterBuiltinFlush:O,onBuiltinProviderChange:t=>B(e.id,t)},e.id):null}if("apikey"===y.type){let e=S.find(e=>e.id===y.providerId);return e?(0,n.jsx)(lN,{provider:e,onRefresh:L,onRegisterBuiltinFlush:O,onBuiltinProviderChange:t=>B(e.id,t)},e.id):null}if("provider"===y.type){let e=d.providers?.[y.name];return e?(0,n.jsx)(lM,{name:y.name,provider:e,onChange:e=>q(y.name,e),onRename:e=>V(y.name,e),onDelete:()=>K(y.name),onAddModels:e=>J(y.name,e),onAddModel:()=>{G(y.name)}},y.name):null}let e=d.providers?.[y.providerName],t=e?.models?.[y.index];return t?(0,n.jsx)(lW,{providerName:y.providerName,provider:e,model:t,onChange:e=>Y(y.providerName,y.index,e),onDelete:()=>{X(y.providerName,y.index)}},`${y.providerName}-${y.index}`):null})();return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("div",{style:e?{display:"flex",flex:1,minWidth:0,minHeight:0,overflow:"hidden"}:{position:"fixed",inset:0,zIndex:1e3,background:"rgba(0,0,0,0.35)",display:"flex",alignItems:"center",justifyContent:"center"},onClick:t=>{e||t.target!==t.currentTarget||Q()},children:(0,n.jsxs)("div",{style:e?{flex:1,minWidth:0,minHeight:0,display:"flex",flexDirection:"column",overflow:"hidden"}:{width:l?"calc(100vw - 16px)":860,maxWidth:"calc(100vw - 16px)",height:l?"calc(100dvh - 16px)":"78vh",maxHeight:"calc(100dvh - 16px)",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:10,display:"flex",flexDirection:"column",boxShadow:"0 8px 32px rgba(0,0,0,0.18)",overflow:"hidden"},children:[!e&&(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 18px",borderBottom:"1px solid var(--border)",flexShrink:0},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"baseline",gap:10},children:[(0,n.jsx)("span",{style:{fontSize:15,fontWeight:700,color:"var(--text)"},children:a("desktop.models")}),(0,n.jsx)("code",{style:{fontSize:11,color:"var(--text-muted)",fontFamily:"var(--font-mono)"},children:"~/.pi/agent/models.json"})]}),(0,n.jsx)("button",{onClick:()=>{Q()},"aria-label":a("desktop.modelsClose"),title:a("desktop.modelsClose"),style:{background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",fontSize:20,lineHeight:1,padding:"2px 6px"},children:"\xd7"})]}),(0,n.jsx)(lg,{}),(0,n.jsxs)("div",{style:{flex:1,display:"flex",flexDirection:l?"column":"row",overflow:"hidden"},children:[(0,n.jsxs)("div",{style:{width:l?"100%":210,maxHeight:l?"40vh":void 0,borderRight:l?"none":"1px solid var(--border)",borderBottom:l?"1px solid var(--border)":"none",display:"flex",flexDirection:"column",flexShrink:0,background:"var(--bg-panel)"},children:[(0,n.jsxs)("div",{style:{flex:1,overflowY:"auto",padding:"8px 6px"},children:[en.map(e=>{let t=y?.type==="oauth"&&y.providerId===e.id;return(0,n.jsxs)("div",{onClick:()=>{U({type:"oauth",providerId:e.id})},style:{display:"flex",alignItems:"center",gap:7,padding:"5px 8px",borderRadius:5,cursor:"pointer",background:t?"var(--bg-selected)":"none"},onMouseEnter:e=>{t||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{t||(e.currentTarget.style.background="none")},children:[(0,n.jsx)(sC,{id:e.id,size:16}),(0,n.jsx)("span",{style:{fontSize:12,color:"var(--text)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name})]},e.id)}),er.map(e=>{let t=y?.type==="apikey"&&y.providerId===e.id;return(0,n.jsxs)("div",{onClick:()=>{U({type:"apikey",providerId:e.id})},style:{display:"flex",alignItems:"center",gap:7,padding:"5px 8px",borderRadius:5,cursor:"pointer",background:t?"var(--bg-selected)":"none"},onMouseEnter:e=>{t||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{t||(e.currentTarget.style.background="none")},children:[(0,n.jsx)(sC,{id:e.id,size:16}),(0,n.jsx)("span",{style:{fontSize:12,color:"var(--text)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.displayName})]},e.id)}),(en.length>0||er.length>0)&&eo.length>0&&(0,n.jsx)("div",{style:{margin:"4px 8px",borderTop:"1px solid var(--border)"}}),p?(0,n.jsx)("div",{style:{padding:"10px 8px",fontSize:12,color:"var(--text-muted)"},children:a("desktop.modelsLoading")}):eo.map(([e,t])=>{let o=y?.type==="provider"&&y.name===e,r=t.models??[];return(0,n.jsxs)("div",{style:{marginBottom:2},children:[(0,n.jsxs)("div",{onClick:()=>{U({type:"provider",name:e})},style:{display:"flex",alignItems:"center",gap:6,padding:"7px 8px",borderRadius:5,cursor:"pointer",background:o?"var(--bg-selected)":"none"},onMouseEnter:e=>{o||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{o||(e.currentTarget.style.background="none")},children:[(0,n.jsx)(T.G,{size:11,style:{color:"var(--text-dim)",flexShrink:0}}),(0,n.jsx)("span",{style:{fontSize:12,fontWeight:o?600:400,color:"var(--text)",fontFamily:"var(--font-mono)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e})]}),r.map((t,o)=>{let r=y?.type==="model"&&y.providerName===e&&y.index===o;return(0,n.jsxs)("div",{onClick:()=>{U({type:"model",providerName:e,index:o})},style:{display:"flex",alignItems:"center",gap:6,padding:"5px 8px 5px 26px",borderRadius:5,cursor:"pointer",background:r?"var(--bg-selected)":"none"},onMouseEnter:e=>{r||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{r||(e.currentTarget.style.background="none")},children:[(0,n.jsx)("span",{style:{fontSize:11,fontFamily:"var(--font-mono)",color:t.id?"var(--text-muted)":"var(--text-dim)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:t.id||a("desktop.modelsNewModel")}),t.reasoning&&(0,n.jsx)("span",{style:{fontSize:9,padding:"1px 4px",background:"rgba(99,102,241,0.12)",color:"rgba(99,102,241,0.8)",borderRadius:3,flexShrink:0},children:"T"})]},o)}),(0,n.jsx)("div",{onClick:t=>{t.stopPropagation(),G(e)},style:{display:"flex",alignItems:"center",gap:4,padding:"4px 8px 4px 26px",borderRadius:5,cursor:"pointer",color:"var(--text-dim)"},onMouseEnter:e=>{e.currentTarget.style.color="var(--accent)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.color="var(--text-dim)",e.currentTarget.style.background="none"},children:(0,n.jsx)("span",{style:{fontSize:11},children:a("desktop.modelsAddModel")})})]},e)})]}),(0,n.jsx)("div",{style:{borderTop:"1px solid var(--border)",padding:"8px 6px"},children:(0,n.jsx)("button",{onClick:()=>z(!0),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,width:"100%",padding:"6px 0",background:"none",border:"1px dashed var(--border)",borderRadius:5,color:"var(--text-muted)",cursor:"pointer",fontSize:12},onMouseEnter:e=>{e.currentTarget.style.borderColor="var(--accent)",e.currentTarget.style.color="var(--accent)"},onMouseLeave:e=>{e.currentTarget.style.borderColor="var(--border)",e.currentTarget.style.color="var(--text-muted)"},children:a("desktop.modelsAddProvider")})})]}),(0,n.jsx)("div",{style:{flex:1,overflowY:"auto",padding:20},children:p?null:es??(0,n.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-dim)",fontSize:13},children:a("desktop.modelsSelectProviderOrModel")})})]}),(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"flex-end",gap:10,padding:"10px 18px",borderTop:"1px solid var(--border)",flexShrink:0},children:[f&&(0,n.jsx)("span",{style:{fontSize:12,color:"#f87171",flex:1},children:f}),!e&&(0,n.jsx)("button",{onClick:()=>{Q()},style:{padding:"6px 14px",background:"none",border:"1px solid var(--border)",borderRadius:6,color:"var(--text-muted)",cursor:"pointer",fontSize:13},children:a("desktop.cancel")}),(0,n.jsx)(ls,{sessionId:t,onBeforeApply:Z}),(0,n.jsxs)("button",{onClick:Z,disabled:g||k,style:{position:"relative",padding:"6px 16px",minWidth:92,background:k?"#16a34a":g?"var(--bg-panel)":"var(--accent)",border:"none",borderRadius:6,color:k?"#fff":g?"var(--text-muted)":"#fff",cursor:g||k?"default":"pointer",fontSize:13,fontWeight:600,display:"inline-flex",alignItems:"center",justifyContent:"center",gap:6,transition:"background-color 0.2s ease, color 0.2s ease",animation:k?"saved-pop 0.45s ease":void 0},children:[k&&(0,n.jsx)(h.S,{size:14,style:{strokeDasharray:18,animation:"saved-check-draw 0.35s ease forwards",flexShrink:0}}),(0,n.jsx)("span",{children:k?a("desktop.modelsSaved"):g?a("desktop.modelsSaving"):a("desktop.modelsSave")})]})]})]})}),R&&(0,n.jsx)(l$,{oauthProviders:w,apiKeyProviders:S,onSelectOAuth:e=>{U({type:"oauth",providerId:e})},onSelectApiKey:e=>{U({type:"apikey",providerId:e})},onAddCustom:()=>{z(!1),M(!0)},onClose:()=>z(!1)}),I&&(0,n.jsx)(lL,{existingProviders:eo.map(([e,t])=>({name:e,provider:t})),onCancel:()=>M(!1),onSubmit:e=>{_(e)}})]})}function lH(e){return e.replace(/^\/(?:Users|home)\/[^/]+/,"~")}function lB(e){let t=e.trim().match(/^\$?\s*pi\s+install\s+(\S+)\s*$/);return t?.[1]??e}function lU(e){return`${e.scope}\0${e.source}`}function l_(e,t){if(e.disabled)return t("desktop.disabled");let o=[e.counts.extensions?t("desktop.extensionsCount",{count:e.counts.extensions}):"",e.counts.skills?t("desktop.skillsCount",{count:e.counts.skills}):"",e.counts.prompts?t("desktop.promptsCount",{count:e.counts.prompts}):"",e.counts.themes?t("desktop.themesCount",{count:e.counts.themes}):""].filter(Boolean);return o.length?o.join(" \xb7 "):t("desktop.noResources")}function lq(e,t){let o=[];return e.version&&o.push(t("desktop.installedVersion",{version:e.version})),e.configuredVersion&&o.push(t("desktop.configuredVersion",{version:e.configuredVersion})),o.length?o.join(" \xb7 "):t("desktop.unknown")}function lV(e){return"loaded"===e?"var(--accent)":"installed"===e?"#f59e0b":"disabled"===e?"var(--text-dim)":"#ef4444"}function lK({pkg:e}){let{t}=(0,F.s)(),o=[["extension",t("desktop.extensions")],["skill",t("desktop.skills")],["prompt",t("desktop.prompts")],["theme",t("desktop.themes")]].map(([t,o])=>({kind:t,label:o,resources:e.resources.filter(e=>e.kind===t)})).filter(e=>e.resources.length>0);return 0===o.length?(0,n.jsx)("div",{style:{fontSize:12,color:"var(--text-dim)"},children:t(e.disabled?"desktop.packageDisabled":"desktop.noResolvedResources")}):(0,n.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:12},children:o.map((e,t)=>(0,n.jsxs)("div",{style:{borderTop:0===t?"none":"1px solid var(--border)",paddingTop:12*(0!==t)},children:[(0,n.jsx)("div",{style:{fontSize:10,fontWeight:700,color:"var(--text-dim)",textTransform:"uppercase",marginBottom:6},children:e.label}),(0,n.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:e.resources.map(e=>(0,n.jsxs)("div",{style:{minWidth:0},children:[(0,n.jsx)("div",{style:{fontSize:12,color:"var(--text)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:e.path,children:e.name}),(0,n.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",marginTop:1},title:e.path,children:e.relativePath})]},`${e.kind}:${e.path}`))})]},e.kind))})}function lG({scope:e}){let{t}=(0,F.s)();return(0,n.jsx)("span",{style:{fontSize:10,padding:"1px 5px",borderRadius:3,flexShrink:0,background:"project"===e?"rgba(99,102,241,0.12)":"rgba(120,120,120,0.12)",color:"project"===e?"rgba(99,102,241,0.85)":"var(--text-dim)"},children:t(`desktop.${e}`)})}function lJ(e,t){return{padding:"6px 12px",background:t?"rgba(239,68,68,0.08)":"none",border:"1px solid var(--border)",borderRadius:6,color:t?"#ef4444":"var(--text-muted)",cursor:e?"not-allowed":"pointer",fontSize:12,opacity:e?.5:1}}function lY({enabled:e,loading:t,onToggle:o,label:r}){return(0,n.jsx)("button",{type:"button",onClick:o,disabled:t,title:r,"aria-label":r,"aria-pressed":e,style:{flexShrink:0,width:40,height:22,borderRadius:11,border:"none",padding:0,cursor:t?"wait":"pointer",background:e?"var(--accent)":"var(--border)",position:"relative",transition:"background 0.18s",outline:"none",opacity:t?.65:1},children:(0,n.jsx)("span",{style:{position:"absolute",top:3,left:e?21:3,width:16,height:16,borderRadius:"50%",background:"var(--bg)",boxShadow:"0 1px 4px rgba(0,0,0,0.22)",transition:"left 0.18s cubic-bezier(.4,0,.2,1)"}})})}function lX({value:e,onChange:t}){let{t:o}=(0,F.s)();return(0,n.jsx)("div",{style:{display:"inline-flex",border:"1px solid var(--border)",borderRadius:7,overflow:"hidden",height:30},children:["global","project"].map(r=>{let s=e===r;return(0,n.jsx)("button",{onClick:()=>t(r),style:{width:76,border:"none",borderRight:"global"===r?"1px solid var(--border)":"none",background:s?"var(--bg-selected)":"none",color:s?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12},children:o(`desktop.${r}`)},r)})})}function lZ({cwd:e,source:t,scope:o,busy:s,actionError:i,onSourceChange:a,onScopeChange:l,onInstall:d}){let{t:c}=(0,F.s)(),p=(0,r.useRef)(null);return(0,r.useEffect)(()=>{p.current?.focus()},[]),(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:18,maxWidth:660,minHeight:"100%"},children:[(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:5},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,flexWrap:"wrap"},children:[(0,n.jsx)("div",{style:{fontSize:14,fontWeight:700,color:"var(--text)"},children:c("desktop.addPluginTitle")}),(0,n.jsx)("a",{href:"https://pi.dev/packages",target:"_blank",rel:"noopener noreferrer",style:{color:"var(--accent)",fontSize:12,textDecoration:"none",whiteSpace:"nowrap"},children:"pi.dev/packages ↗"})]}),(0,n.jsx)("div",{style:{fontSize:12,color:"var(--text-dim)",fontFamily:"var(--font-mono)"},children:"project"===o?`${lH(e)}/.pi/agent/{npm,git}`:"~/.pi/agent/{npm,git}"})]}),(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:7},children:[(0,n.jsx)("label",{htmlFor:"plugin-source",style:{fontSize:12,fontWeight:600,color:"var(--text-muted)"},children:c("desktop.pluginSource")}),(0,n.jsx)("input",{id:"plugin-source",ref:p,value:t,onChange:e=>a(e.target.value),onPaste:e=>{let t=e.clipboardData.getData("text"),o=lB(t);o!==t&&(e.preventDefault(),a(o))},onBlur:e=>a(lB(e.currentTarget.value)),placeholder:"npm:@scope/package",style:{width:"100%",height:36,padding:"0 11px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-panel)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:13,outline:"none"},onKeyDown:e=>{"Enter"===e.key&&t.trim()&&!s&&d()}})]}),(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:[(0,n.jsx)(lX,{value:o,onChange:l}),(0,n.jsx)("button",{type:"button",onClick:d,disabled:s||!t.trim(),style:{...lJ(s||!t.trim()),background:"var(--accent)",color:"white",borderColor:"var(--accent)"},children:c(s?"desktop.installing":"desktop.install")})]}),(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:7},children:[(0,n.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text-muted)"},children:c("desktop.examples")}),(0,n.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:["npm:@scope/pi-plugin","git:https://github.com/user/repo","/absolute/path/to/plugin"].map(e=>(0,n.jsx)("button",{type:"button",onClick:()=>a(e),style:{width:"100%",minHeight:30,textAlign:"left",padding:"6px 9px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-panel)",color:"var(--text-dim)",cursor:"pointer",fontFamily:"var(--font-mono)",fontSize:11},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text-muted)"},onMouseLeave:e=>{e.currentTarget.style.background="var(--bg-panel)",e.currentTarget.style.color="var(--text-dim)"},children:e},e))})]}),i&&(0,n.jsx)("div",{style:{fontSize:12,color:"#ef4444",whiteSpace:"pre-wrap"},children:i})]})}function lQ({pkg:e,cwd:t,busyKey:o,actionError:r,actionMessage:s,sessionId:i,onAction:a,onReloadSession:l}){let{t:d}=(0,F.s)(),c=lU(e),p=o?.endsWith(c)??!1,u="reload"===o,h=!e.disabled;return(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:20,maxWidth:680},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:12,minWidth:0,flexWrap:"wrap"},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:180,flex:1},children:[(0,n.jsx)(lY,{enabled:h,loading:p||u,onToggle:()=>a(e.disabled?"enable":"disable",e),label:d(e.disabled?"desktop.enablePackage":"desktop.disablePackage")}),(0,n.jsx)(lG,{scope:e.scope}),e.disabled?(0,n.jsx)("span",{style:{fontSize:10,padding:"1px 5px",borderRadius:3,background:"rgba(120,120,120,0.12)",color:"var(--text-dim)"},children:d("desktop.disabled")}):e.filtered&&(0,n.jsx)("span",{style:{fontSize:10,padding:"1px 5px",borderRadius:3,background:"rgba(245,158,11,0.12)",color:"#d97706"},children:d("desktop.filtered")}),(0,n.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:12,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.source})]}),(0,n.jsxs)("div",{style:{display:"flex",gap:8,flexWrap:"wrap"},children:[(0,n.jsx)("button",{onClick:()=>a("update",e),disabled:p||u,style:lJ(p||u),children:d(o===`update:${c}`?"desktop.updating":"desktop.update")}),(0,n.jsx)("button",{onClick:l,disabled:!i||u||p,style:lJ(!i||u||p),title:d(i?"desktop.reloadCurrentSession":"desktop.openSessionToReload"),children:d(u?"desktop.reloading":"desktop.reloadSession")}),(0,n.jsx)("button",{onClick:()=>a("remove",e),disabled:p||u,style:lJ(p||u,!0),children:d(o===`remove:${c}`?"desktop.removing":"desktop.remove")})]})]}),(0,n.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"minmax(96px, 130px) minmax(0, 1fr)",gap:"9px 14px",fontSize:12,lineHeight:1.45},children:[(0,n.jsx)("div",{style:{color:"var(--text-dim)"},children:d("desktop.status")}),(0,n.jsx)("div",{style:{color:lV(e.status),textTransform:"capitalize"},children:e.status}),(0,n.jsx)("div",{style:{color:"var(--text-dim)"},children:d("desktop.version")}),(0,n.jsx)("div",{style:{color:"var(--text-muted)",fontFamily:"var(--font-mono)"},children:lq(e,d)}),(0,n.jsx)("div",{style:{color:"var(--text-dim)"},children:d("desktop.package")}),(0,n.jsx)("div",{style:{color:"var(--text-muted)",fontFamily:"var(--font-mono)",overflowWrap:"anywhere"},children:e.packageName??d("desktop.unknown")}),(0,n.jsx)("div",{style:{color:"var(--text-dim)"},children:d("desktop.resources")}),(0,n.jsx)("div",{style:{color:"var(--text-muted)"},children:l_(e,d)}),(0,n.jsx)("div",{style:{color:"var(--text-dim)"},children:d("desktop.installedPath")}),(0,n.jsx)("div",{style:{color:e.installedPath?"var(--text-muted)":"#ef4444",fontFamily:"var(--font-mono)",overflowWrap:"anywhere"},children:e.installedPath?lH(e.installedPath):d("desktop.notFound")}),(0,n.jsx)("div",{style:{color:"var(--text-dim)"},children:d("desktop.cwd")}),(0,n.jsx)("div",{style:{color:"var(--text-dim)",fontFamily:"var(--font-mono)",overflowWrap:"anywhere"},children:lH(t)})]}),(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[(0,n.jsx)("div",{style:{fontSize:12,fontWeight:700,color:"var(--text)"},children:d("desktop.resolvedResources")}),(0,n.jsx)(lK,{pkg:e})]}),s&&(0,n.jsx)("div",{style:{fontSize:12,color:"#16a34a"},children:s}),r&&(0,n.jsx)("div",{style:{fontSize:12,color:"#ef4444",whiteSpace:"pre-wrap"},children:r})]})}function l0({cwd:e,sessionId:t,embedded:o=!1,onCloseAction:s,onReloadedAction:i}){let a=$(),{t:l}=(0,F.s)(),[d,c]=(0,r.useState)(null),[p,u]=(0,r.useState)(!0),[h,g]=(0,r.useState)(null),[m,f]=(0,r.useState)(null),[k,v]=(0,r.useState)(!1),[y,b]=(0,r.useState)(""),[w,j]=(0,r.useState)("global"),[S,C]=(0,r.useState)(null),[T,R]=(0,r.useState)(null),[z,I]=(0,r.useState)(null),M=(0,r.useMemo)(()=>d?.packages??[],[d?.packages]),P=M.find(e=>lU(e)===m)??null,E=(0,r.useMemo)(()=>["project","global"].map(e=>({scope:e,packages:M.filter(t=>t.scope===e)})).filter(e=>e.packages.length>0),[M]),D=(0,r.useCallback)(async()=>{u(!0),g(null);try{let t=await fetch(`/api/plugins?cwd=${encodeURIComponent(e)}`),o=await t.json();if(!t.ok||o.error)throw Error(o.error??`HTTP ${t.status}`);c(o),v(e=>0===o.packages.length||e),f(e=>e&&o.packages.some(t=>lU(t)===e)?e:o.packages[0]?lU(o.packages[0]):null)}catch(e){g(e instanceof Error?e.message:String(e))}finally{u(!1)}},[e]);(0,r.useEffect)(()=>{D()},[D]);let W=(0,r.useCallback)(async(t,o)=>{let n=lU(o);C(`${t}:${n}`),R(null),I(null);try{let n=await fetch("/api/plugins",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:t,source:o.source,scope:o.scope,cwd:e})}),r=await n.json();if(!n.ok||r.error)throw Error(r.error??`HTTP ${n.status}`);if(c(r),"remove"===t)f(r.packages[0]?lU(r.packages[0]):null),0===r.packages.length&&v(!0),I(l("desktop.packageRemoved"));else{let e={install:l("desktop.packageInstalled"),update:l("desktop.packageUpdated"),disable:l("desktop.packageDisabledMessage"),enable:l("desktop.packageEnabled")};I(e[t])}}catch(e){R(e instanceof Error?e.message:String(e))}finally{C(null)}},[e,l]),A=(0,r.useCallback)(async()=>{let t=lB(y).trim();if(!t)return;let o=`${w}\0${t}`;C(`install:${o}`),R(null),I(null);try{var n;let r,s,i=await fetch("/api/plugins",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"install",source:t,scope:w,cwd:e})}),a=await i.json();if(!i.ok||a.error)throw Error(a.error??`HTTP ${i.status}`);c(a);let d=(n=a.packages,s=(r=t.trim()).startsWith("npm:")?r.slice(4):r,n.find(e=>e.scope===w&&e.source===r)??n.find(e=>e.scope===w&&e.source===`npm:${s}`)??n.find(e=>e.scope===w&&e.source.endsWith(r)));f(d?lU(d):o),v(!1),b(""),I(l("desktop.packageInstalled"))}catch(e){R(e instanceof Error?e.message:String(e))}finally{C(null)}},[e,w,y,l]),N=(0,r.useCallback)(async()=>{if(t){C("reload"),R(null),I(null);try{await iS(t,{type:"reload"}),i?.(),await D(),I(l("desktop.sessionReloaded"))}catch(e){R(e instanceof Error?e.message:String(e))}finally{C(null)}}},[D,i,t,l]),L=S?.startsWith("install:")??!1;return(0,n.jsx)("div",{style:o?{display:"flex",flex:1,minWidth:0,minHeight:0,overflow:"hidden"}:{position:"fixed",inset:0,zIndex:1e3,background:"rgba(0,0,0,0.35)",display:"flex",alignItems:"center",justifyContent:"center"},onClick:e=>{o||e.target!==e.currentTarget||s?.()},children:(0,n.jsxs)("div",{style:o?{display:"flex",flex:1,minWidth:0,minHeight:0,flexDirection:"column",overflow:"hidden"}:{width:a?"calc(100vw - 16px)":860,maxWidth:"calc(100vw - 16px)",height:a?"calc(100dvh - 16px)":"76vh",maxHeight:"calc(100dvh - 16px)",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:8,display:"flex",flexDirection:"column",boxShadow:"0 8px 32px rgba(0,0,0,0.18)",overflow:"hidden"},children:[!o&&(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 18px",borderBottom:"1px solid var(--border)",flexShrink:0},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"baseline",gap:10,minWidth:0},children:[(0,n.jsx)("span",{style:{fontSize:15,fontWeight:700,color:"var(--text)"},children:l("desktop.plugins")}),(0,n.jsx)("code",{style:{fontSize:11,color:"var(--text-muted)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:lH(e)})]}),(0,n.jsx)("button",{onClick:s,title:l("desktop.close"),"aria-label":l("desktop.close"),style:{background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",fontSize:20,lineHeight:1,padding:"2px 6px"},children:"\xd7"})]}),(0,n.jsxs)("div",{style:{flex:1,display:"flex",flexDirection:a?"column":"row",overflow:"hidden"},children:[(0,n.jsxs)("div",{style:{width:a?"100%":245,maxHeight:a?"40vh":void 0,borderRight:a?"none":"1px solid var(--border)",borderBottom:a?"1px solid var(--border)":"none",display:"flex",flexDirection:"column",flexShrink:0,background:"var(--bg-panel)"},children:[(0,n.jsx)("div",{style:{flex:1,overflowY:"auto",padding:"8px 6px"},children:p?(0,n.jsx)("div",{style:{padding:"10px 8px",fontSize:12,color:"var(--text-muted)"},children:l("desktop.loading")}):h?(0,n.jsx)("div",{style:{padding:"10px 8px",fontSize:11,color:"#ef4444"},children:h}):0===M.length?(0,n.jsx)("div",{style:{padding:"10px 8px",fontSize:11,color:"var(--text-dim)"},children:l("desktop.noPluginsConfigured")}):E.map(e=>(0,n.jsxs)("div",{style:{marginBottom:6},children:[(0,n.jsx)("div",{style:{padding:"4px 8px 3px",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase"},children:l(`desktop.${e.scope}`)}),e.packages.map(e=>{let t=lU(e),o=!k&&m===t;return(0,n.jsxs)("div",{onClick:()=>{f(t),v(!1),R(null),I(null)},style:{display:"flex",alignItems:"center",gap:7,padding:"8px 8px",borderRadius:5,cursor:"pointer",background:o?"var(--bg-selected)":"none"},onMouseEnter:e=>{o||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{o||(e.currentTarget.style.background="none")},children:[(0,n.jsx)("span",{style:{flexShrink:0,width:7,height:7,borderRadius:"50%",background:lV(e.status)}}),(0,n.jsxs)("div",{style:{minWidth:0,flex:1},children:[(0,n.jsx)("div",{style:{fontSize:12,fontWeight:o?600:400,color:"var(--text)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.source}),(0,n.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",marginTop:2},children:l_(e,l)}),(e.version||e.configuredVersion)&&(0,n.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",marginTop:2},children:lq(e,l)})]})]},t)})]},e.scope))}),(0,n.jsx)("div",{style:{padding:"8px 6px",borderTop:"1px solid var(--border)",flexShrink:0},children:(0,n.jsxs)("button",{type:"button",onClick:()=>{v(!0),R(null),I(null)},style:{display:"flex",alignItems:"center",gap:6,padding:"7px 8px",borderRadius:5,border:"none",width:"100%",cursor:"pointer",background:k?"var(--bg-selected)":"none",color:k?"var(--accent)":"var(--text-dim)",fontSize:12},onMouseEnter:e=>{k||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{k||(e.currentTarget.style.background="none")},children:[(0,n.jsx)(x.c,{size:13}),l("desktop.addPlugin")]})})]}),(0,n.jsx)("div",{style:{flex:1,overflowY:"auto",padding:20},children:k?(0,n.jsx)(lZ,{cwd:e,source:y,scope:w,busy:L,actionError:T,onSourceChange:b,onScopeChange:j,onInstall:A}):p?null:P?(0,n.jsx)(lQ,{pkg:P,cwd:e,busyKey:S,actionError:T,actionMessage:z,sessionId:t,onAction:W,onReloadSession:N},lU(P)):(0,n.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-dim)",fontSize:13},children:l("desktop.selectPackage")})})]}),(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,padding:"10px 18px",borderTop:"1px solid var(--border)",flexShrink:0},children:[(0,n.jsx)("div",{style:{minWidth:0,flex:1,fontSize:11,color:"var(--text-dim)",overflow:"hidden"},children:d?.diagnostics.length?(0,n.jsx)("span",{title:d.diagnostics.map(e=>`${e.type}: ${e.source?`${e.source}: `:""}${e.message}`).join("\n"),style:{color:d.diagnostics.some(e=>"error"===e.type)?"#ef4444":"#d97706"},children:l("desktop.diagnosticsCount",{count:d.diagnostics.length,suffix:1===d.diagnostics.length?"":"s"})}):(0,n.jsx)("span",{children:d?l("desktop.pluginResourceTotals",{extensions:d.totals.extensions,skills:d.totals.skills,prompts:d.totals.prompts,themes:d.totals.themes}):""})}),(0,n.jsx)("button",{onClick:()=>void D(),disabled:p||null!==S,style:lJ(p||null!==S),children:l("desktop.refresh")}),!o&&(0,n.jsx)("button",{onClick:s,style:lJ(!1),children:l("desktop.close")})]})]})})}var l1=o(36282);function l2(){let{t:e}=(0,F.s)(),[t,o]=(0,r.useState)({enabled:!1,protocol:"http",host:"127.0.0.1",port:7890,username:"",password:"",noProxy:"localhost,127.0.0.1,.local",hasPassword:!1}),[s,i]=(0,r.useState)(!1),[a,l]=(0,r.useState)(!1),[d,c]=(0,r.useState)(null),[p,u]=(0,r.useState)(null),[h,g]=(0,r.useState)(null),[m,f]=(0,r.useState)(!1),[x,k]=(0,r.useState)(!1);(0,r.useEffect)(()=>{(async()=>{try{let e=await fetch("/api/proxy");if(e.ok){let t=await e.json();o(e=>({...e,...t,password:""}))}}catch{}})()},[]);let v=(0,r.useCallback)((e,t)=>{o(o=>({...o,[e]:t})),"password"===e&&k(!0),f(!0),u(null),g(null)},[]),y=(0,r.useCallback)(async()=>{i(!0),u(null),g(null);try{let n={...t};delete n.hasPassword,x||delete n.password;let r=await fetch("/api/proxy",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)}),s=await r.json();if(r.ok){u(!0),f(!1),k(!1);let e=await fetch("/api/proxy");if(e.ok){let t=await e.json();o(e=>({...e,...t,password:""}))}}else u(!1),g(s.error||e("desktop.proxySaveFailed"))}catch(t){u(!1),g(t instanceof Error?t.message:e("desktop.proxySaveFailed"))}finally{i(!1)}},[t,x,e]),b=(0,r.useCallback)(async()=>{l(!0),c(null),m&&await y();try{let t=await fetch("/api/proxy/test",{method:"POST"}),o=await t.json();o.success?c({ok:!0,message:`${e("desktop.proxyTestSuccess")} \xb7 ${o.latencyMs}ms`,latencyMs:o.latencyMs}):c({ok:!1,message:o.error||e("desktop.proxyTestFailed")})}catch(t){c({ok:!1,message:t instanceof Error?t.message:e("desktop.proxyTestFailed")})}finally{l(!1)}},[m,y,e]),w=(0,r.useCallback)(()=>{if(!t.enabled||!t.host||!t.port)return null;let e="";return t.username&&t.password?e=`${t.username}:${"•".repeat(Math.min(t.password.length,8))}@`:t.username&&(e=`${t.username}@`),`${t.protocol}://${e}${t.host}:${t.port}`},[t.enabled,t.host,t.port,t.protocol,t.username,t.password])();return(0,n.jsxs)("div",{style:{flex:1,display:"flex",flexDirection:"column",padding:"16px 20px",overflow:"auto",gap:16},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:12,marginBottom:4},children:[(0,n.jsxs)("label",{style:{display:"flex",alignItems:"center",gap:8,fontSize:14,fontWeight:500,color:"var(--text)",cursor:"pointer"},children:[(0,n.jsx)("input",{type:"checkbox",checked:t.enabled,onChange:e=>v("enabled",e.target.checked),style:{width:16,height:16,accentColor:"var(--accent)"}}),e("desktop.proxyEnable")]}),t.enabled&&w&&(0,n.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",fontFamily:"var(--font-mono)",backgroundColor:"var(--bg-hover)",padding:"2px 10px",borderRadius:4,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",maxWidth:"60%"},title:w,children:w})]}),(0,n.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:"12px 16px",opacity:t.enabled?1:.5,pointerEvents:t.enabled?"auto":"none"},children:[(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,n.jsx)("label",{style:{fontSize:12,color:"var(--text-muted)"},children:e("desktop.proxyProtocol")}),(0,n.jsxs)("select",{value:t.protocol,onChange:e=>v("protocol",e.target.value),style:{padding:"6px 10px",borderRadius:6,border:"1px solid var(--border)",background:"var(--bg)",color:"var(--text)",fontSize:13,fontFamily:"var(--font-mono)",outline:"none"},children:[(0,n.jsx)("option",{value:"http",children:"HTTP"}),(0,n.jsx)("option",{value:"https",children:"HTTPS"}),(0,n.jsx)("option",{value:"socks5",children:"SOCKS5"})]})]}),(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,n.jsx)("label",{style:{fontSize:12,color:"var(--text-muted)"},children:e("desktop.proxyHost")}),(0,n.jsx)("input",{type:"text",value:t.host,onChange:e=>v("host",e.target.value),placeholder:"127.0.0.1",style:{padding:"6px 10px",borderRadius:6,border:"1px solid var(--border)",background:"var(--bg)",color:"var(--text)",fontSize:13,fontFamily:"var(--font-mono)",outline:"none"}})]}),(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,n.jsx)("label",{style:{fontSize:12,color:"var(--text-muted)"},children:e("desktop.proxyPort")}),(0,n.jsx)("input",{type:"number",value:t.port,onChange:e=>v("port",parseInt(e.target.value,10)||0),placeholder:"7890",min:1,max:65535,style:{padding:"6px 10px",borderRadius:6,border:"1px solid var(--border)",background:"var(--bg)",color:"var(--text)",fontSize:13,fontFamily:"var(--font-mono)",outline:"none"}})]}),(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,n.jsx)("label",{style:{fontSize:12,color:"var(--text-muted)"},children:e("desktop.proxyUsername")}),(0,n.jsx)("input",{type:"text",value:t.username,onChange:e=>v("username",e.target.value),placeholder:t.username?"":e("desktop.proxyUsername"),style:{padding:"6px 10px",borderRadius:6,border:"1px solid var(--border)",background:"var(--bg)",color:"var(--text)",fontSize:13,fontFamily:"var(--font-mono)",outline:"none"}})]}),(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,n.jsx)("label",{style:{fontSize:12,color:"var(--text-muted)"},children:e("desktop.proxyPassword")}),(0,n.jsx)("input",{type:"password",value:t.password,onChange:e=>v("password",e.target.value),placeholder:t.hasPassword?"••••••••":e("desktop.proxyPassword"),style:{padding:"6px 10px",borderRadius:6,border:"1px solid var(--border)",background:"var(--bg)",color:"var(--text)",fontSize:13,fontFamily:"var(--font-mono)",outline:"none"}})]}),(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4,gridColumn:"1 / -1"},children:[(0,n.jsx)("label",{style:{fontSize:12,color:"var(--text-muted)"},children:e("desktop.proxyNoProxy")}),(0,n.jsx)("input",{type:"text",value:t.noProxy,onChange:e=>v("noProxy",e.target.value),placeholder:"localhost,127.0.0.1,.local",style:{padding:"6px 10px",borderRadius:6,border:"1px solid var(--border)",background:"var(--bg)",color:"var(--text)",fontSize:13,fontFamily:"var(--font-mono)",outline:"none"}})]})]}),(0,n.jsxs)("div",{style:{display:"flex",gap:10,marginTop:4},children:[(0,n.jsx)("button",{type:"button",onClick:y,disabled:s,style:{padding:"6px 18px",borderRadius:6,border:"none",background:"var(--accent)",color:"#fff",fontSize:13,fontWeight:500,cursor:s?"not-allowed":"pointer",opacity:s?.5:1,transition:"background 0.15s"},onMouseEnter:e=>{s||(e.currentTarget.style.background="var(--accent-hover)")},onMouseLeave:e=>{s||(e.currentTarget.style.background="var(--accent)")},children:s?e("desktop.proxySaving"):e("desktop.proxySave")}),(0,n.jsx)("button",{type:"button",onClick:b,disabled:a||!t.enabled,style:{padding:"6px 18px",borderRadius:6,border:"1px solid var(--border)",background:"var(--bg)",color:t.enabled?"var(--text)":"var(--text-muted)",fontSize:13,fontWeight:500,cursor:t.enabled?"pointer":"not-allowed",opacity:t.enabled?1:.5,transition:"background 0.15s"},onMouseEnter:e=>{t.enabled&&(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{t.enabled&&(e.currentTarget.style.background="var(--bg)")},children:a?e("desktop.proxyTesting"):e("desktop.proxyTest")})]}),!0===p&&(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"6px 12px",borderRadius:6,backgroundColor:"rgba(34, 197, 94, 0.12)",color:"#22c55e",fontSize:13},children:[(0,n.jsx)(nO.r,{size:16,weight:"fill"}),e("desktop.proxySaved")]}),!1===p&&h&&(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"6px 12px",borderRadius:6,backgroundColor:"rgba(239, 68, 68, 0.10)",color:"#ef4444",fontSize:13},children:[(0,n.jsx)(ia.J,{size:16,weight:"fill"}),h]}),d&&(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"6px 12px",borderRadius:6,backgroundColor:d.ok?"rgba(34, 197, 94, 0.10)":"rgba(239, 68, 68, 0.10)",color:d.ok?"#22c55e":"#ef4444",fontSize:13},children:[d.ok?(0,n.jsx)(nO.r,{size:16,weight:"fill"}):(0,n.jsx)(ia.J,{size:16,weight:"fill"}),d.message,void 0!==d.latencyMs&&(0,n.jsxs)("span",{style:{color:"var(--text-muted)",fontSize:12,marginLeft:4},children:["(",d.latencyMs,"ms)"]})]}),m&&!p&&!h&&(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"4px 12px",borderRadius:6,backgroundColor:"var(--bg-hover)",color:"var(--text-muted)",fontSize:12},children:[(0,n.jsx)(l1.j,{size:12,weight:"fill"}),e("desktop.proxyUnsaved")]})]})}function l4(e){return e.replace(/^\/(?:Users|home)\/[^/]+/,"~")}function l6(e){let t=e.sourceInfo?.source,o=e.sourceInfo?.scope;return"user"===o||"user"===t?"global":"project"===o||"project"===t?"project":"path"}function l8(e){let t=l6(e);return"path"===t?t:e.install?.skillsShUrl?`${t} / skills.sh`:t}function l5(e){return e.install?`${e.install.scope}\0${e.install.package}`:null}function l3(e,t){return e?e.slice(0,8):t}function l7({enabled:e,loading:t,onToggle:o}){let{t:r}=(0,F.s)();return(0,n.jsx)("button",{onClick:o,disabled:t,title:r(e?"desktop.visibleInModelPrompt":"desktop.hiddenFromModelPrompt"),style:{flexShrink:0,width:40,height:22,borderRadius:11,border:"none",padding:0,cursor:t?"wait":"pointer",background:e?"var(--accent)":"var(--border)",position:"relative",transition:"background 0.18s",outline:"none"},children:(0,n.jsx)("span",{style:{position:"absolute",top:3,left:e?21:3,width:16,height:16,borderRadius:"50%",background:"var(--bg)",boxShadow:"0 1px 4px rgba(0,0,0,0.22)",transition:"left 0.18s cubic-bezier(.4,0,.2,1)"}})})}function l9({skill:e,cwd:t,onToggle:o,toggling:r,saveError:s,updateStatus:i,checkingUpdate:a,updating:l,updateError:d,onCheckUpdate:c,onUpdate:p}){let{t:u}=(0,F.s)(),h=l6(e),g=!e.disableModelInvocation;return(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:20},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:7},children:[(0,n.jsx)("span",{style:{fontSize:10,padding:"1px 5px",borderRadius:3,flexShrink:0,background:"project"===h?"rgba(99,102,241,0.12)":"rgba(120,120,120,0.12)",color:"project"===h?"rgba(99,102,241,0.8)":"var(--text-dim)"},children:u(`desktop.${h}`)}),(0,n.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:11,color:"var(--text-dim)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:function(e){if("project"===h&&e.startsWith(t)){let o=e.slice(t.length).replace(/^[/\\]/,"");return`./${o}`}return l4(e)}(e.filePath)}),(0,n.jsx)(l7,{enabled:g,loading:r,onToggle:()=>o(e)}),s&&(0,n.jsx)("span",{style:{fontSize:12,color:"#f87171",flexShrink:0},children:s})]}),!g&&(0,n.jsx)("div",{style:{marginTop:-12,color:"var(--text-dim)",fontSize:12},children:u("desktop.hiddenButInvocable")}),e.install?.skillsShUrl&&(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:5},children:[(0,n.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",fontWeight:500},children:u("desktop.pluginSource")}),(0,n.jsx)("a",{href:e.install.skillsShUrl,target:"_blank",rel:"noreferrer",title:e.install.skillsShUrl,style:{display:"flex",alignItems:"center",gap:8,width:"fit-content",maxWidth:"100%",color:"var(--accent)",textDecoration:"none"},children:(0,n.jsxs)("span",{style:{fontFamily:"var(--font-mono)",fontSize:12,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[e.install.skillsShUrl.replace(/^https?:\/\//,"")," ↗"]})})]}),e.install&&(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:7},children:[(0,n.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",fontWeight:500},children:u("desktop.version")}),(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:[(0,n.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:12,color:"var(--text-muted)"},children:l3(i?.currentVersion??e.install.versionHash,u("desktop.unknown"))}),e.install.canCheckForUpdates&&(0,n.jsx)("button",{onClick:c,disabled:a||l,style:{padding:"4px 9px",border:"1px solid var(--border)",borderRadius:5,background:"none",color:"var(--text-muted)",cursor:a||l?"not-allowed":"pointer",opacity:a||l?.5:1,fontSize:11},children:u("desktop.check")}),i?.state==="update-available"&&(0,n.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:12,color:"#d97706"},children:l3(i.latestVersion,u("desktop.unknown"))}),(a||i&&"update-available"!==i.state)&&(0,n.jsx)("span",{style:{fontSize:12,color:a?"var(--accent)":i?.state==="up-to-date"?"#16a34a":i?.state==="error"?"#ef4444":"var(--text-dim)"},children:a?u("desktop.checking"):i?.state==="up-to-date"?u("desktop.upToDate"):i?.state==="unsupported"?u("desktop.automaticChecksUnavailable"):i?.message||u("desktop.checkFailed")}),i?.state==="update-available"&&(0,n.jsx)("button",{onClick:p,disabled:l||a,style:{padding:"4px 10px",border:"none",borderRadius:5,background:"var(--accent)",color:"#fff",cursor:l||a?"not-allowed":"pointer",opacity:l||a?.5:1,fontSize:11,fontWeight:600},children:u(l?"desktop.updating":"desktop.update")})]}),d&&(0,n.jsx)("span",{style:{fontSize:12,color:"#ef4444"},children:d})]}),(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:5},children:[(0,n.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",fontWeight:500},children:u("desktop.name")}),(0,n.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:14,color:"var(--text)"},children:e.name})]}),(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:5},children:[(0,n.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",fontWeight:500},children:u("desktop.description")}),(0,n.jsx)("span",{style:{fontSize:14,color:"var(--text-muted)",lineHeight:1.6},children:e.description})]})]})}function de({cwd:e,installedPackages:t,projectResourcesLoaded:o,onInstalled:s}){let{t:i}=(0,F.s)(),[a,l]=(0,r.useState)(""),[d,c]=(0,r.useState)([]),[p,u]=(0,r.useState)(!1),[h,g]=(0,r.useState)(null),[m,f]=(0,r.useState)(null),[x,k]=(0,r.useState)(null),[v,y]=(0,r.useState)(new Set),[b,w]=(0,r.useState)("global"),j=(0,r.useRef)(null);(0,r.useEffect)(()=>{j.current?.focus()},[]),(0,r.useEffect)(()=>{o||w("global")},[o]);let S=(0,r.useCallback)(async e=>{if(e.trim()){u(!0),g(null),c([]);try{let t=await fetch("/api/skills/search",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({query:e.trim()})}),o=await t.json();if(o.error)return void g(o.error);c(o.results??[]),0===(o.results??[]).length&&g(i("desktop.noSkillsFound"))}catch(e){g(String(e))}finally{u(!1)}}},[i]),C=(0,r.useCallback)(async t=>{f(t),k(null);try{let o=await fetch("/api/skills/install",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({package:t,scope:b,cwd:e})}),n=await o.json();if(!o.ok||n.error)return void k(n.error??`HTTP ${o.status}`);y(e=>new Set(e).add(`${b}:${t}`)),s()}catch(e){k(String(e))}finally{f(null)}},[s,b,e]),T="global"===b?"~/.pi/agent/skills/":`${l4(e)}/.pi/skills/`;return(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%"},children:[(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:12,marginBottom:20},children:[(0,n.jsx)("div",{style:{fontSize:14,fontWeight:600,color:"var(--text)"},children:i("desktop.addSkillTitle")}),(0,n.jsxs)("div",{style:{display:"flex",gap:8},children:[(0,n.jsx)("input",{ref:j,value:a,onChange:e=>l(e.target.value),onKeyDown:e=>{"Enter"===e.key&&S(a)},placeholder:i("desktop.skillSearchPlaceholder"),style:{flex:1,padding:"7px 10px",fontSize:13,background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:6,color:"var(--text)",outline:"none"}}),(0,n.jsx)("button",{onClick:()=>S(a),disabled:p||!a.trim(),style:{padding:"7px 16px",fontSize:13,borderRadius:6,border:"none",background:"var(--accent)",color:"#fff",cursor:p||!a.trim()?"not-allowed":"pointer",opacity:p||!a.trim()?.5:1,flexShrink:0},children:p?i("desktop.searching"):i("desktop.search")})]}),(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10},children:[(0,n.jsx)("div",{style:{display:"flex",borderRadius:5,border:"1px solid var(--border)",overflow:"hidden",fontSize:12,flexShrink:0},children:["global","project"].map(e=>(0,n.jsx)("button",{onClick:()=>w(e),disabled:"project"===e&&!o,title:"project"!==e||o?void 0:i("desktop.projectSkillInstallUnavailable"),style:{padding:"3px 10px",border:"none",cursor:"project"!==e||o?"pointer":"not-allowed",opacity:"project"!==e||o?1:.5,background:b===e?"var(--bg-selected)":"none",color:b===e?"var(--text)":"var(--text-dim)",fontWeight:b===e?600:400,borderRight:"global"===e?"1px solid var(--border)":"none"},children:i(`desktop.${e}`)},e))}),(0,n.jsxs)("span",{style:{fontSize:12,color:"var(--text-dim)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:["→ ",T]})]}),h&&(0,n.jsx)("div",{style:{fontSize:12,color:"#f87171"},children:h}),x&&(0,n.jsx)("div",{style:{fontSize:12,color:"#f87171",wordBreak:"break-word"},children:x})]}),d.length>0?(0,n.jsx)("div",{style:{flex:1,overflowY:"auto"},children:d.map(e=>{let o=t[b].has(e.package)||v.has(`${b}:${e.package}`),r=m===e.package,s=e.package.indexOf("@"),a=s>-1?e.package.slice(0,s):e.package,l=s>-1?e.package.slice(s+1):null;return(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:14,padding:"12px 0",borderBottom:"1px solid var(--border)"},children:[(0,n.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,n.jsx)("div",{style:{fontSize:13,fontWeight:600,color:"var(--text)",marginBottom:3},children:l??a}),(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:[(0,n.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:11,color:"var(--text-dim)"},children:a}),(0,n.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",fontWeight:500},children:e.installs}),e.url&&(0,n.jsx)("a",{href:e.url,target:"_blank",rel:"noreferrer",style:{fontSize:12,color:"var(--accent)",textDecoration:"none"},children:"skills.sh ↗"})]})]}),(0,n.jsx)("button",{onClick:()=>!o&&!r&&C(e.package),disabled:o||r||null!==m,style:{flexShrink:0,padding:"5px 14px",fontSize:12,fontWeight:500,borderRadius:5,border:"1px solid var(--border)",cursor:o||r||null!==m?"not-allowed":"pointer",background:o?"rgba(34,197,94,0.1)":"none",color:o?"#16a34a":r?"var(--accent)":"var(--text-muted)",transition:"color 0.12s"},children:o?`✓ ${i("desktop.installed")}`:r?i("desktop.installing"):i("desktop.install")})]},e.package)})}):!h&&!p&&(0,n.jsxs)("div",{style:{fontSize:13,color:"var(--text-dim)",lineHeight:1.8},children:[i("desktop.skillSearchHint").split("skills.sh")[0],(0,n.jsx)("a",{href:"https://skills.sh",target:"_blank",rel:"noreferrer",style:{color:"var(--accent)",textDecoration:"none"},children:"skills.sh"}),i("desktop.skillSearchHint").split("skills.sh")[1]]})]})}function dt({cwd:e,embedded:t=!1,sessionId:o,onCloseAction:s}){let i=$(),{t:a}=(0,F.s)(),[l,d]=(0,r.useState)([]),[c,p]=(0,r.useState)(!0),[u,h]=(0,r.useState)(null),[g,m]=(0,r.useState)(null),[f,k]=(0,r.useState)(new Set),[v,y]=(0,r.useState)(null),[b,w]=(0,r.useState)(!1),[j,S]=(0,r.useState)({}),[C,T]=(0,r.useState)(new Set),[R,z]=(0,r.useState)(!1),[I,M]=(0,r.useState)(null),[P,E]=(0,r.useState)(null),[D,W]=(0,r.useState)(!0),[A,N]=(0,r.useState)({}),L=(0,r.useCallback)(async()=>{p(!0),h(null);try{let t=await fetch(`/api/skills?cwd=${encodeURIComponent(e)}`),o=await t.json();if(!t.ok||o.error)throw Error(o.error??`HTTP ${t.status}`);let n=o.skills??[];if(d(n),W(o.projectResourcesLoaded??!0),n.length>0&&!g){let e=n.find(e=>!e.disableModelInvocation)??n[0];m(e.filePath),e.disableModelInvocation&&N(t=>({...t,[l8(e)]:!0}))}return n}catch(e){return h(String(e)),[]}finally{p(!1)}},[e,g]);(0,r.useEffect)(()=>{S({}),E(null),L()},[e]);let O=(0,r.useCallback)(async t=>{let o=(t?[t]:l.filter(e=>!!e.install)).map(l5).filter(e=>!!e);if(0!==o.length){E(null),T(e=>new Set([...e,...o])),t||z(!0);try{let o=await fetch("/api/skills/check",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e,package:t?.install?.package,scope:t?.install?.scope})}),n=await o.json();if(!o.ok||n.error)throw Error(n.error??`HTTP ${o.status}`);S(e=>{let t={...e};for(let e of n.updates??[])t[`${e.scope}\0${e.package}`]=e;return t})}catch(e){E(e instanceof Error?e.message:String(e))}finally{T(e=>{let t=new Set(e);for(let e of o)t.delete(e);return t}),t||z(!1)}}},[e,l]),H=(0,r.useCallback)(async t=>{if(!t.install)return;let o=l5(t);M(o),E(null);try{let n=await fetch("/api/skills/update",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e,package:t.install.package,scope:t.install.scope})}),r=await n.json();if(!n.ok||r.error||!r.success)throw Error(r.error??`HTTP ${n.status}`);await L();let s=r.skill?.install?.versionHash;S(e=>({...e,[o]:{package:t.install.package,scope:t.install.scope,state:"up-to-date",currentVersion:s,latestVersion:s}}))}catch(e){E(e instanceof Error?e.message:String(e))}finally{M(null)}},[e,L]),B=(0,r.useCallback)(async t=>{let o=!t.disableModelInvocation;k(e=>new Set(e).add(t.filePath)),y(null);try{let n=await fetch("/api/skills",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e,filePath:t.filePath,disableModelInvocation:o})}),r=await n.json();if(!n.ok||r.error)return void y(r.error??`HTTP ${n.status}`);d(e=>e.map(e=>e.filePath===t.filePath?{...e,disableModelInvocation:o}:e)),o&&N(e=>({...e,[l8(t)]:!0}))}catch(e){y(String(e))}finally{k(e=>{let o=new Set(e);return o.delete(t.filePath),o})}},[e]),U=l.find(e=>e.filePath===g)??null;return(0,n.jsx)("div",{style:t?{display:"flex",flex:1,minWidth:0,minHeight:0,overflow:"hidden"}:{position:"fixed",inset:0,zIndex:1e3,background:"rgba(0,0,0,0.35)",display:"flex",alignItems:"center",justifyContent:"center"},onClick:e=>{t||e.target!==e.currentTarget||s?.()},children:(0,n.jsxs)("div",{style:t?{display:"flex",flex:1,minWidth:0,minHeight:0,flexDirection:"column",overflow:"hidden"}:{width:i?"calc(100vw - 16px)":860,maxWidth:"calc(100vw - 16px)",height:i?"calc(100dvh - 16px)":"78vh",maxHeight:"calc(100dvh - 16px)",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:10,display:"flex",flexDirection:"column",boxShadow:"0 8px 32px rgba(0,0,0,0.18)",overflow:"hidden"},children:[!t&&(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 18px",borderBottom:"1px solid var(--border)",flexShrink:0},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"baseline",gap:10},children:[(0,n.jsx)("span",{style:{fontSize:15,fontWeight:700,color:"var(--text)"},children:a("desktop.skills")}),(0,n.jsx)("code",{style:{fontSize:11,color:"var(--text-muted)",fontFamily:"var(--font-mono)",maxWidth:320,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:l4(e)})]}),(0,n.jsx)("button",{onClick:s,title:a("desktop.close"),"aria-label":a("desktop.close"),style:{background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",fontSize:20,lineHeight:1,padding:"2px 6px"},children:"\xd7"})]}),!D&&(0,n.jsx)("div",{role:"status",style:{padding:"8px 18px",borderBottom:"1px solid var(--border)",background:"var(--bg-subtle)",color:"var(--text-muted)",fontSize:12},children:a("desktop.projectSkillsRestricted")}),(0,n.jsxs)("div",{style:{flex:1,display:"flex",flexDirection:i?"column":"row",overflow:"hidden"},children:[(0,n.jsxs)("div",{style:{width:i?"100%":210,maxHeight:i?"40vh":void 0,borderRight:i?"none":"1px solid var(--border)",borderBottom:i?"1px solid var(--border)":"none",display:"flex",flexDirection:"column",flexShrink:0,background:"var(--bg-panel)"},children:[(0,n.jsx)("div",{style:{padding:"8px 8px 0",display:"flex",justifyContent:"flex-end"},children:(0,n.jsx)(ls,{sessionId:o,onApplied:L})}),(0,n.jsx)("div",{style:{flex:1,overflowY:"auto",padding:"8px 6px"},children:c?(0,n.jsx)("div",{style:{padding:"10px 8px",fontSize:12,color:"var(--text-muted)"},children:a("desktop.loading")}):u?(0,n.jsx)("div",{style:{padding:"10px 8px",fontSize:11,color:"#f87171"},children:u}):0===l.length?(0,n.jsx)("div",{style:{padding:"10px 8px",fontSize:11,color:"var(--text-dim)"},children:a("desktop.noSkillsFound")}):(()=>{let e=[];for(let{key:t,label:o,matches:n}of[{key:"project / skills.sh",label:`${a("desktop.project")} / skills.sh`,matches:e=>"project"===l6(e)&&!!e.install?.skillsShUrl},{key:"project",label:a("desktop.project"),matches:e=>"project"===l6(e)&&!e.install?.skillsShUrl},{key:"global / skills.sh",label:`${a("desktop.global")} / skills.sh`,matches:e=>"global"===l6(e)&&!!e.install?.skillsShUrl},{key:"global",label:a("desktop.global"),matches:e=>"global"===l6(e)&&!e.install?.skillsShUrl},{key:"path",label:a("desktop.path"),matches:e=>"path"===l6(e)}]){let r=l.filter(n);r.length>0&&e.push({key:t,label:o,skills:r})}return e.map(({key:e,label:t,skills:o})=>{let r=o.filter(e=>!e.disableModelInvocation),s=o.filter(e=>e.disableModelInvocation),i=A[e]??!1,l=i?[...r,...s]:r;return(0,n.jsxs)("div",{style:{marginBottom:6},children:[(0,n.jsx)("div",{style:{padding:"4px 8px 3px",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.06em"},children:t}),s.length>0&&(0,n.jsxs)("button",{type:"button",onClick:()=>N(t=>({...t,[e]:!i})),style:{display:"flex",alignItems:"center",gap:5,width:"100%",padding:"4px 8px 3px",border:"none",background:"transparent",color:"var(--text-dim)",cursor:"pointer",fontSize:10,fontWeight:600,letterSpacing:"0.06em",textAlign:"left",textTransform:"uppercase"},children:[(0,n.jsx)("span",{style:{fontSize:8},children:i?"▾":"▸"}),a("desktop.dormant")," (",s.length,")"]}),l.map(e=>{let t,o,r=!b&&g===e.filePath,s=e.disableModelInvocation;return(0,n.jsxs)("div",{onClick:()=>{m(e.filePath),w(!1)},style:{display:"flex",alignItems:"center",gap:7,padding:"8px 8px",borderRadius:5,cursor:"pointer",background:r?"var(--bg-selected)":"none"},onMouseEnter:e=>{r||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{r||(e.currentTarget.style.background="none")},children:[(0,n.jsx)("span",{style:{flexShrink:0,width:7,height:7,borderRadius:"50%",background:s?"var(--border)":"var(--accent)",boxShadow:s?"none":"0 0 4px var(--accent)",transition:"background 0.15s, box-shadow 0.15s"}}),(0,n.jsx)("span",{style:{fontSize:12,fontWeight:r?600:400,color:s?"var(--text-dim)":"var(--text)",fontFamily:"var(--font-mono)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name}),(o=(t=l5(e))?j[t]:void 0,o?.state!=="update-available"?null:(0,n.jsx)("span",{title:a("desktop.updateAvailable"),style:{color:"#d97706",fontSize:13,lineHeight:1,flexShrink:0},children:"↑"}))]},e.filePath)})]},e)})})()}),(0,n.jsx)("div",{style:{padding:"8px 6px",borderTop:"1px solid var(--border)",flexShrink:0},children:(0,n.jsxs)("div",{onClick:()=>w(!0),style:{display:"flex",alignItems:"center",gap:6,padding:"7px 8px",borderRadius:5,cursor:"pointer",background:b?"var(--bg-selected)":"none",color:b?"var(--accent)":"var(--text-dim)",fontSize:12},onMouseEnter:e=>{b||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{b||(e.currentTarget.style.background="none")},children:[(0,n.jsx)(x.c,{size:13}),a("desktop.addSkill")]})})]}),(0,n.jsx)("div",{style:{flex:1,overflowY:"auto",padding:20},children:b?(0,n.jsx)(de,{cwd:e,installedPackages:{global:new Set(l.filter(e=>e.install?.scope==="global").map(e=>e.install.package)),project:new Set(l.filter(e=>e.install?.scope==="project").map(e=>e.install.package))},projectResourcesLoaded:D,onInstalled:()=>{L()}}):c?null:U?(0,n.jsx)(l9,{skill:U,cwd:e,onToggle:B,toggling:f.has(U.filePath),saveError:v,updateStatus:l5(U)?j[l5(U)]:void 0,checkingUpdate:!!l5(U)&&C.has(l5(U)),updating:I===l5(U),updateError:P,onCheckUpdate:()=>void O(U),onUpdate:()=>void H(U)},U.filePath):(0,n.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-dim)",fontSize:13},children:a("desktop.selectSkill")})})]}),(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 18px",borderTop:"1px solid var(--border)",flexShrink:0},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10},children:[l.some(e=>!!e.install)&&(0,n.jsx)("button",{onClick:()=>void O(),disabled:R||null!==I,style:{padding:"6px 12px",background:"none",border:"1px solid var(--border)",borderRadius:6,color:"var(--text-muted)",cursor:R||null!==I?"not-allowed":"pointer",opacity:R||null!==I?.5:1,fontSize:12},children:R?a("desktop.checking"):a("desktop.checkUpdates")}),Object.values(j).filter(e=>"update-available"===e.state).length>0&&(0,n.jsx)("span",{style:{fontSize:12,color:"#d97706"},children:a("desktop.updatesCount").replace("{count}",String(Object.values(j).filter(e=>"update-available"===e.state).length)).replace("{suffix}",1===Object.values(j).filter(e=>"update-available"===e.state).length?"":"s")})]}),!t&&(0,n.jsx)("button",{onClick:s,style:{padding:"6px 14px",background:"none",border:"1px solid var(--border)",borderRadius:6,color:"var(--text-muted)",cursor:"pointer",fontSize:13},children:a("desktop.close")})]})]})})}function dn(){let{t:e}=(0,F.s)(),[t,o]=(0,r.useState)([]),[s,i]=(0,r.useState)(""),[a,l]=(0,r.useState)(""),[d,c]=(0,r.useState)(""),[p,u]=(0,r.useState)(""),[h,g]=(0,r.useState)(!0),[m,f]=(0,r.useState)(null),x=(0,r.useCallback)(async()=>{g(!0),f(null);try{let e=await fetch("/api/logs?limit=500"),t=await e.json();if(!e.ok)throw Error(t.error??`HTTP ${e.status}`);o(t.entries??[])}catch(e){f(e instanceof Error?e.message:String(e))}finally{g(!1)}},[]);(0,r.useEffect)(()=>{x()},[x]);let k=(0,r.useMemo)(()=>[...new Set(t.map(e=>e.source).filter(Boolean))].sort(),[t]),v=(0,r.useMemo)(()=>[...new Set(t.map(e=>e.statusCode).filter(e=>void 0!==e))].sort((e,t)=>e-t),[t]),y=(0,r.useMemo)(()=>{let e=p.trim().toLocaleLowerCase();return t.filter(e=>!s||e.level===s).filter(e=>!a||e.statusCode===Number(a)).filter(e=>!d||e.source===d).filter(t=>!e||[t.message,t.details,t.provider,t.model,t.source].filter(Boolean).some(t=>t.toLocaleLowerCase().includes(e))).slice(0,200)},[t,s,a,d,p]),b=async()=>{try{let e=await fetch("/api/logs",{method:"DELETE"});if(!e.ok)throw Error(`HTTP ${e.status}`);o([])}catch(e){f(e instanceof Error?e.message:String(e))}},w=async e=>{let t=[`[${e.timestamp}] ${e.level.toUpperCase()} ${e.statusCode??"—"}`,`${e.source}${e.provider?` \xb7 ${e.provider}`:""}${e.model?` \xb7 ${e.model}`:""}`,e.message,e.details].filter(Boolean).join("\n");try{await oy(t),f(null)}catch(e){f(e instanceof Error?e.message:String(e))}};return(0,n.jsxs)("div",{style:{flex:1,minWidth:0,minHeight:0,overflow:"auto",padding:"18px 20px",display:"flex",flexDirection:"column",gap:12},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[(0,n.jsxs)("select",{value:s,onChange:e=>i(e.target.value),style:{padding:"7px 9px",background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:6,color:"var(--text)",fontSize:12},children:[(0,n.jsx)("option",{value:"",children:e("desktop.logsAllLevels")}),["error","warning","info"].map(e=>(0,n.jsx)("option",{value:e,children:e},e))]}),(0,n.jsxs)("select",{value:a,onChange:e=>l(e.target.value),style:{padding:"7px 9px",background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:6,color:"var(--text)",fontSize:12},children:[(0,n.jsx)("option",{value:"",children:e("desktop.logsAllCodes")}),v.map(e=>(0,n.jsx)("option",{value:e,children:e},e))]}),(0,n.jsxs)("select",{value:d,onChange:e=>c(e.target.value),style:{padding:"7px 9px",background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:6,color:"var(--text)",fontSize:12},children:[(0,n.jsx)("option",{value:"",children:e("desktop.logsAllSources")}),k.map(e=>(0,n.jsx)("option",{value:e,children:e},e))]}),(0,n.jsx)("input",{value:p,onChange:e=>u(e.target.value),placeholder:e("desktop.logsSearch"),style:{flex:1,minWidth:180,padding:"7px 9px",background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:6,color:"var(--text)",fontSize:12}}),(0,n.jsx)("button",{type:"button",onClick:()=>void x(),title:e("desktop.refresh"),"aria-label":e("desktop.refresh"),style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:30,height:30,border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-panel)",color:"var(--text-muted)",cursor:"pointer"},children:(0,n.jsx)(j.S,{size:14})}),(0,n.jsx)("button",{type:"button",onClick:()=>void b(),title:e("desktop.logsClear"),"aria-label":e("desktop.logsClear"),style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:30,height:30,border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-panel)",color:"#ef4444",cursor:"pointer"},children:(0,n.jsx)(S.l,{size:14})})]}),h&&(0,n.jsx)("div",{style:{color:"var(--text-muted)",fontSize:12},children:e("desktop.loading")}),m&&(0,n.jsx)("div",{style:{color:"#ef4444",fontSize:12},children:m}),!h&&!m&&0===y.length&&(0,n.jsx)("div",{style:{color:"var(--text-muted)",fontSize:12},children:e("desktop.logsEmpty")}),(0,n.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:8},children:y.map(t=>(0,n.jsxs)("details",{style:{border:"1px solid var(--border)",borderRadius:7,background:"var(--bg-panel)",padding:"8px 10px"},children:[(0,n.jsxs)("summary",{style:{cursor:"pointer",color:"error"===t.level?"#ef4444":"warning"===t.level?"#f59e0b":"var(--text)",fontSize:12},children:[(0,n.jsx)("span",{style:{fontFamily:"var(--font-mono)",marginRight:8},children:t.statusCode??"—"}),(0,n.jsx)("span",{style:{marginRight:8},children:new Date(t.timestamp).toLocaleString()}),(0,n.jsx)("span",{style:{overflowWrap:"anywhere"},children:t.message.length>180?`${t.message.slice(0,180)}…`:t.message})]}),(0,n.jsxs)("div",{style:{padding:"8px 0 0 18px",color:"var(--text-muted)",fontSize:11,lineHeight:1.5,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:[(0,n.jsxs)("div",{children:[t.source,t.provider?` \xb7 ${t.provider}`:"",t.model?` \xb7 ${t.model}`:""]}),(0,n.jsx)("div",{style:{marginTop:5,maxHeight:260,overflow:"auto"},children:t.message}),t.details&&(0,n.jsx)("div",{style:{marginTop:5,maxHeight:260,overflow:"auto"},children:t.details}),(0,n.jsx)("button",{type:"button",onClick:()=>void w(t),style:{marginTop:8,padding:"4px 7px",border:"1px solid var(--border)",borderRadius:5,background:"var(--bg)",color:"var(--text-muted)",cursor:"pointer",fontSize:11},children:e("desktop.logsCopy")})]})]},t.id))})]})}let dr={padding:"7px 9px",background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:6,color:"var(--text)",fontSize:12,width:"100%"},ds={padding:"6px 12px",border:"none",borderRadius:6,background:"var(--accent)",color:"#fff",cursor:"pointer",fontSize:12};function di(){let{t:e}=(0,F.s)(),[t,o]=(0,r.useState)([]),[s,i]=(0,r.useState)(!0),[a,l]=(0,r.useState)(null),[d,c]=(0,r.useState)(""),[u,h]=(0,r.useState)(""),[m,f]=(0,r.useState)(!1),[k,v]=(0,r.useState)(null),y=(0,r.useCallback)(async()=>{try{let e=await fetch("/api/snippets");if(!e.ok)return;let t=await e.json();o(t.snippets??[]),i(!1)}catch{i(!1)}},[]);(0,r.useEffect)(()=>{y()},[y]);let b=(0,r.useCallback)(()=>{window.dispatchEvent(new Event("pi:snippets-changed"))},[]),w=()=>{l(null),c(""),h(""),v(null)},j=(0,r.useCallback)(async()=>{let t=d.trim();if(!t)return void v(e("desktop.snippetNameRequired"));f(!0),v(null);try{if(a){let e=await fetch(`/api/snippets/${encodeURIComponent(a.id)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:t,content:u})});if(!e.ok)throw Error(`HTTP ${e.status}`)}else{let e=await fetch("/api/snippets",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:t,content:u})});if(!e.ok)throw Error(`HTTP ${e.status}`)}await y(),b(),w()}catch(e){v(e instanceof Error?e.message:String(e))}finally{f(!1)}},[a,d,u,y,b,e]),C=(0,r.useCallback)(async e=>{try{let t=await fetch(`/api/snippets/${encodeURIComponent(e)}`,{method:"DELETE"});if(!t.ok)throw Error(`HTTP ${t.status}`);a?.id===e&&w(),await y(),b()}catch(e){v(e instanceof Error?e.message:String(e))}},[a,y,b]);return(0,n.jsxs)(aY,{children:[(0,n.jsx)(aX,{children:(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:7,padding:"12px 0"},children:[(0,n.jsx)(rv.c,{size:15,"aria-hidden":"true"}),(0,n.jsxs)("div",{children:[(0,n.jsx)("div",{style:{fontSize:13,fontWeight:600,color:"var(--text)"},children:e("desktop.snippets")}),(0,n.jsx)("div",{style:{fontSize:11,color:"var(--text-muted)",marginTop:2},children:e("desktop.snippetsDesc")})]})]})}),(0,n.jsx)(aX,{children:(0,n.jsxs)("div",{style:{width:"100%"},children:[(0,n.jsxs)("div",{style:{display:"flex",gap:6,flexWrap:"wrap",marginBottom:8},children:[(0,n.jsx)("button",{type:"button",onClick:w,style:ds,children:(0,n.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:5},children:[(0,n.jsx)(x.F,{size:13})," ",e("desktop.snippetNew")]})}),a&&(0,n.jsx)("button",{type:"button",onClick:w,style:{...ds,background:"var(--bg-hover)",color:"var(--text-muted)"},children:(0,n.jsx)(p.X,{size:13})})]}),(0,n.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"minmax(120px, 200px) 1fr",gap:8,alignItems:"start",marginBottom:8},children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",display:"block",marginBottom:4},children:e("desktop.snippetName")}),(0,n.jsx)("input",{value:d,onChange:e=>c(e.target.value),placeholder:"#name",style:dr})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",display:"block",marginBottom:4},children:e("desktop.snippetContent")}),(0,n.jsx)("textarea",{value:u,onChange:e=>h(e.target.value),rows:3,style:{...dr,resize:"vertical",fontFamily:"var(--font-mono)",fontSize:11}})]})]}),(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10,marginBottom:10},children:[(0,n.jsx)("button",{type:"button",onClick:()=>void j(),disabled:m,style:{...ds,cursor:m?"wait":"pointer"},children:e("desktop.snippetSave")}),k&&(0,n.jsx)("span",{style:{color:"var(--status-error, #ef4444)",fontSize:12},children:k})]}),s?(0,n.jsx)("span",{style:{fontSize:12,color:"var(--text-dim)"},children:e("desktop.loadingThemes")}):0===t.length?(0,n.jsx)(aQ,{children:e("desktop.snippetEmpty")}):(0,n.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:4},children:t.map(t=>(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"6px 10px",background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:6},children:[(0,n.jsx)("span",{style:{color:"var(--accent)",fontFamily:"var(--font-mono)",fontSize:11},children:"#"}),(0,n.jsx)("span",{style:{fontWeight:600,fontSize:12,flexShrink:0},children:t.name}),(0,n.jsx)("span",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-muted)",fontSize:11,fontFamily:"var(--font-mono)"},children:t.content.split("\n")[0]}),(0,n.jsx)("button",{type:"button",onClick:()=>{l(t),c(t.name),h(t.content),v(null)},title:e("desktop.snippetEdit"),style:{background:"none",border:"none",color:"var(--text-dim)",cursor:"pointer",padding:2},children:(0,n.jsx)(g.I,{size:13})}),(0,n.jsx)("button",{type:"button",onClick:()=>void C(t.id),title:e("desktop.snippetDelete"),style:{background:"none",border:"none",color:"var(--text-dim)",cursor:"pointer",padding:2},children:(0,n.jsx)(S.l,{size:13})})]},t.id))})]})}),(0,n.jsx)(aZ,{children:(0,n.jsx)(aQ,{children:e("desktop.snippetHint")})})]})}let da=["async","group","smart"],dl=["full","compact","custom"],dd=["all","background","off"],dc={padding:"7px 9px",background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:6,color:"var(--text)",fontSize:12,width:"min(200px, 100%)",fontFamily:"var(--font-mono)"};function dp(){return{fontSize:12,color:"var(--text-muted)"}}function du({cwd:e,sessionId:t}){let{t:o}=(0,F.s)(),[s,i]=(0,r.useState)({}),[a,l]=(0,r.useState)([]),[d,c]=(0,r.useState)(""),[p,u]=(0,r.useState)(!1),[h,g]=(0,r.useState)(null),[m,f]=(0,r.useState)(!1),[x,k]=(0,r.useState)(null),[v,y]=(0,r.useState)(!1),[b,w]=(0,r.useState)([]),[j,S]=(0,r.useState)({}),C=(0,r.useCallback)(async()=>{g(null);try{let e=await fetch("/api/subagents"),t=await e.json();if(!e.ok||t.error)throw Error(t.error??`HTTP ${e.status}`);i(t.config??{}),l(t.agents??[]),c(t.filePath)}catch(e){g(e instanceof Error?e.message:String(e))}finally{u(!0)}},[]);(0,r.useEffect)(()=>{let t=e?`?cwd=${encodeURIComponent(e)}`:"";fetch(`/api/models${t}`).then(e=>e.ok?e.json():null).then(e=>{e?.modelList&&w(e.modelList)}).catch(()=>{})},[e]),(0,r.useEffect)(()=>{C()},[C]);let T=(0,r.useCallback)((e,t)=>{i(o=>({...o,[e]:t})),y(!1),k(null)},[]),R=(0,r.useCallback)(async()=>{f(!0),k(null),y(!1);try{let e=await fetch("/api/subagents",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)}),t=await e.json();if(!e.ok||t.error)throw Error(t.error??`HTTP ${e.status}`);i(t.config??{}),y(!0)}catch(e){k(e instanceof Error?e.message:String(e))}finally{f(!1)}},[s]),z=(0,r.useRef)({}),I=(0,r.useCallback)(async(e,t)=>{let o=(z.current[e]??0)+1;z.current[e]=o,S(t=>({...t,[e]:"saving"}));try{let n=await fetch(`/api/subagents/agents/${encodeURIComponent(e)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:t})});if(z.current[e]!==o)return;let r=await n.json();if(!n.ok||r.error)throw Error(r.error??`HTTP ${n.status}`);S(t=>({...t,[e]:"saved"})),l(o=>o.map(o=>o.name===e?{...o,model:t??void 0}:o)),setTimeout(()=>{S(t=>{if("saved"===t[e]){let o={...t};return delete o[e],o}return t})},2e3)}catch(t){if(z.current[e]!==o)return;S(o=>({...o,[e]:`error:${t instanceof Error?t.message:String(t)}`}))}},[]),M=(e,t)=>(0,n.jsx)(aX,{children:(0,n.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"minmax(150px, 240px) 1fr",gap:"8px 12px",alignItems:"center",padding:"8px 0"},children:[(0,n.jsx)("span",{style:dp(),children:o(t)}),(0,n.jsx)("input",{type:"number",min:0,value:s[e]??"",onChange:t=>T(e,""===t.target.value?void 0:Number(t.target.value)),placeholder:"defaultMaxTurns"===e?"0 = 不限":"",style:dc})]})},e),P=(e,t,r)=>(0,n.jsx)(aX,{children:(0,n.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"minmax(150px, 240px) 1fr",gap:"8px 12px",alignItems:"center",padding:"8px 0"},children:[(0,n.jsx)("span",{style:dp(),children:o(t)}),(0,n.jsx)("select",{value:s[e]??r[0],onChange:t=>T(e,t.target.value),style:{...dc,fontFamily:"var(--font-mono)"},children:r.map(e=>(0,n.jsx)("option",{value:e,children:e},e))})]})},e),E=(e,t,r)=>(0,n.jsx)(aX,{children:(0,n.jsx)(aM,{checked:s[e]??!1,onChange:t=>T(e,t),label:o(t),description:r?o(r):void 0})},e);return(0,n.jsx)("div",{style:{flex:1,overflow:"auto",minWidth:0,padding:"20px 22px",display:"flex",flexDirection:"column",gap:16},children:(0,n.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:p?h?(0,n.jsx)("div",{style:{fontSize:12,color:"#ef4444"},children:h}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("div",{style:{minWidth:0},children:[(0,n.jsx)("div",{style:{fontSize:14,fontWeight:700,color:"var(--text)"},children:o("desktop.subagents")}),(0,n.jsx)("div",{style:{fontSize:11,color:"var(--text-dim)",fontFamily:"var(--font-mono)",marginTop:2,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:d||"~/.pi/agent/subagents.json"})]}),(0,n.jsx)(aQ,{children:o("desktop.subagentsDesc")}),(0,n.jsxs)(aY,{children:[M("maxConcurrent","desktop.subagentsMaxConcurrent"),M("defaultMaxTurns","desktop.subagentsDefaultMaxTurns"),M("graceTurns","desktop.subagentsGraceTurns"),P("defaultJoinMode","desktop.subagentsJoinMode",da),P("widgetMode","desktop.subagentsWidgetMode",dd),P("toolDescriptionMode","desktop.subagentsToolDescMode",dl),E("schedulingEnabled","desktop.subagentsScheduling","desktop.subagentsSchedulingDesc"),E("scopeModels","desktop.subagentsScopeModels","desktop.subagentsScopeModelsDesc"),E("disableDefaultAgents","desktop.subagentsDisableDefault","desktop.subagentsDisableDefaultDesc"),E("fleetView","desktop.subagentsFleetView","desktop.subagentsFleetViewDesc"),(0,n.jsx)(aZ,{children:E("outputTranscript","desktop.subagentsOutputTranscript","desktop.subagentsOutputTranscriptDesc")})]}),(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10},children:[(0,n.jsx)("button",{type:"button",onClick:()=>void R(),disabled:m,style:{padding:"7px 12px",border:"none",borderRadius:6,background:"var(--accent)",color:"#fff",cursor:m?"wait":"pointer",fontSize:12},children:m?o("desktop.saving"):o("desktop.mcpSave")}),v&&(0,n.jsx)("span",{style:{color:"#22c55e",fontSize:12},children:o("desktop.subagentsSaved")}),x&&(0,n.jsx)("span",{style:{color:"#ef4444",fontSize:12},children:x}),(0,n.jsx)(ls,{sessionId:t})]}),a.length>0&&(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:7,fontSize:13,fontWeight:600,color:"var(--text)"},children:[(0,n.jsx)(aj.d,{size:15,"aria-hidden":"true"}),o("desktop.subagentsDiscovered")]}),(0,n.jsx)(aY,{children:a.map((e,t)=>(0,n.jsx)(aZ,{children:(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:3,padding:t===a.length-1?"12px 0":"12px 0 0"},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[(0,n.jsx)("span",{style:{fontSize:12.5,fontWeight:600,color:"var(--text)",fontFamily:"var(--font-mono)"},children:e.name}),e.displayName&&(0,n.jsx)("span",{style:{fontSize:11,color:"var(--text-muted)"},children:e.displayName}),e.model&&(0,n.jsx)("span",{style:{fontSize:10,padding:"1px 6px",borderRadius:3,background:"rgba(37,99,235,0.12)",color:"var(--accent)",fontFamily:"var(--font-mono)"},children:e.model})]}),(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6,flexWrap:"wrap"},children:[(0,n.jsx)("span",{style:{fontSize:11,color:"var(--text-muted)"},children:o("desktop.subagentsModel")}),(0,n.jsxs)("select",{value:e.model??"",onChange:t=>void I(e.name,t.target.value||null),style:{...dc,width:"min(260px, 100%)",maxWidth:260},children:[(0,n.jsx)("option",{value:"",children:o("desktop.subagentsModelDefault")}),e.model&&!b.some(t=>`${t.provider}/${t.id}`===e.model)&&(0,n.jsx)("option",{value:e.model,children:e.model}),b.map(e=>(0,n.jsxs)("option",{value:`${e.provider}/${e.id}`,children:[e.name,"(",e.provider,"/",e.id,")"]},`${e.provider}/${e.id}`))]}),"saving"===j[e.name]&&(0,n.jsxs)("span",{style:{fontSize:10,color:"var(--text-dim)"},children:[o("desktop.saving"),"…"]}),"saved"===j[e.name]&&(0,n.jsx)("span",{style:{fontSize:10,color:"#22c55e"},children:o("desktop.subagentsSaved")}),j[e.name]?.startsWith("error:")&&(0,n.jsx)("span",{style:{fontSize:10,color:"#ef4444"},children:j[e.name].slice(6)})]}),e.description&&(0,n.jsx)("div",{style:{fontSize:11,color:"var(--text-muted)",lineHeight:1.5},children:e.description})]})},e.name))})]})]}):(0,n.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)"},children:o("desktop.loading")})})})}function dh({sessionId:e,onSessionReloaded:t}){let{t:o}=(0,F.s)(),[s,i]=(0,r.useState)(null),[a,l]=(0,r.useState)(null);(0,r.useEffect)(()=>{let e=!1;return fetch("/api/tools/settings").then(async t=>{let o=await t.json();if(!t.ok||o.error)throw Error(o.error??`HTTP ${t.status}`);e||i(o)}).catch(t=>{e||l(t instanceof Error?t.message:String(t))}),()=>{e=!0}},[]);let d=(0,r.useCallback)(async o=>{l(null);try{let n=await fetch("/api/tools/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({enabled:o})}),r=await n.json();if(!n.ok||r.error)throw Error(r.error??`HTTP ${n.status}`);i(r),e&&(await iS(e,{type:"reload"}),t())}catch(e){l(e instanceof Error?e.message:String(e))}},[t,e]);return(0,n.jsx)("div",{style:{padding:16,overflowY:"auto",minHeight:0,flex:1},children:(0,n.jsxs)(aY,{children:[(0,n.jsx)(aX,{children:(0,n.jsx)(aM,{label:o("desktop.usePowerShell"),description:o("desktop.shellToolDescription"),checked:s?.powerShellEnabled??!1,onChange:e=>void d(e)})}),(0,n.jsx)(aZ,{children:(0,n.jsx)("div",{style:{padding:"10px 0",fontSize:12,lineHeight:1.5,color:"var(--text-dim)"},children:s?.isWindows?o("desktop.shellToolWindowsOnly"):a??o("desktop.shellToolMacOnly")})})]})})}function dg(e){return null==e?"—":io(e)}function dm({sessionId:e,cwd:t}){let{t:o}=(0,F.s)(),[s,i]=(0,r.useState)(null),[a,l]=(0,r.useState)(null),[d,c]=(0,r.useState)(!1);(0,r.useEffect)(()=>{let t=!1;return e?(fetch(`/api/agent/${encodeURIComponent(e)}`).then(e=>e.ok?e.json():null).then(e=>{t||i(e?.state?.contextUsage??null)}).catch(()=>{}),()=>{t=!0}):void i(null)},[e]);let p=(0,r.useCallback)(async()=>{c(!0);try{let e=await fetch("/api/usage");e.ok&&l(await e.json())}catch{}finally{c(!1)}},[]);(0,r.useEffect)(()=>{p()},[p]);let u=(0,r.useMemo)(()=>a?.daily.slice(-14)??[],[a]),h=(0,r.useMemo)(()=>u.reduce((e,t)=>Math.max(e,t.tokens),0),[u]);return(0,n.jsxs)("div",{style:{flex:1,overflow:"auto",minWidth:0,padding:"16px 20px",display:"flex",flexDirection:"column",gap:16},children:[(0,n.jsx)("h3",{style:{margin:0,fontSize:15,fontWeight:600,color:"var(--text)"},children:o("desktop.usage")}),(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[(0,n.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text-muted)"},children:o("desktop.usageSession")}),(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:12},children:[e?(0,n.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:12,borderRadius:12,border:"1px solid var(--border)",padding:16},children:s?(0,n.jsx)(n.Fragment,{children:(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:16},children:[(0,n.jsxs)("svg",{width:72,height:72,viewBox:"0 0 72 72",style:{flexShrink:0},children:[(0,n.jsx)("circle",{cx:36,cy:36,r:30,fill:"none",stroke:"var(--border)",strokeWidth:7}),(0,n.jsx)("circle",{cx:36,cy:36,r:30,fill:"none",stroke:"var(--accent)",strokeWidth:7,strokeLinecap:"round",strokeDasharray:2*Math.PI*30,strokeDashoffset:2*Math.PI*30*(1-Math.min(1,(s.percent??0)/100)),transform:"rotate(-90 36 36)",style:{transition:"stroke-dashoffset 0.4s ease"}}),(0,n.jsx)("text",{x:36,y:41,textAnchor:"middle",fontSize:15,fontWeight:700,fill:"var(--text)",children:null!=s.percent?`${s.percent.toFixed(0)}%`:"?"})]}),(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:3},children:[(0,n.jsx)("span",{style:{fontSize:13,color:"var(--text)"},children:o("desktop.usageContext",{used:dg(s.tokens),window:dg(s.contextWindow)})}),(0,n.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)"},children:o("desktop.usageContextHint")})]})]})}):(0,n.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)"},children:o("desktop.usageNoSessionData")})}):(0,n.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)"},children:o("desktop.usageNoSession")}),t&&(0,n.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:t})]})]}),(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[(0,n.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text-muted)"},children:o("desktop.usageGlobal")}),(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,n.jsx)("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(140px, 1fr))",gap:10},children:[{label:o("desktop.usageTotal"),value:dg(a?.totalTokens),sub:a?`${a.totalSessions} ${o("desktop.usageSessions")}`:"…"},{label:o("desktop.usageMessages"),value:a?String(a.messageCount):"…",sub:o("desktop.usageMessagesHint")}].map(e=>(0,n.jsxs)("div",{style:{borderRadius:12,border:"1px solid var(--border)",padding:"12px 14px",background:"var(--bg-panel)"},children:[(0,n.jsx)("div",{style:{fontSize:11,color:"var(--text-muted)",marginBottom:4},children:e.label}),(0,n.jsx)("div",{style:{fontSize:18,fontWeight:700,color:"var(--text)"},children:e.value}),(0,n.jsx)("div",{style:{fontSize:10.5,color:"var(--text-dim)",marginTop:2},children:e.sub})]},e.label))}),(0,n.jsxs)("div",{style:{borderRadius:12,border:"1px solid var(--border)",padding:"14px 16px"},children:[(0,n.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)",marginBottom:10},children:o("desktop.usageDaily")}),0===u.length?(0,n.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)"},children:o(d?"desktop.featuresLoading":"desktop.usageNoData")}):(0,n.jsx)("div",{style:{display:"flex",alignItems:"flex-end",gap:6,height:96,overflowX:"auto"},children:u.map(e=>{let t=h>0?Math.max(4,Math.round(e.tokens/h*72)):4;return(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",gap:4,flexShrink:0},children:[(0,n.jsx)("div",{style:{fontSize:9,color:"var(--text-dim)"},children:e.tokens>0?dg(e.tokens):""}),(0,n.jsx)("div",{style:{width:8,height:t,borderRadius:4,background:e.tokens>0?"var(--accent)":"var(--bg-hover)",opacity:e.tokens>0?.85:1},title:`${e.day}: ${dg(e.tokens)}`}),(0,n.jsx)("div",{style:{fontSize:9,color:"var(--text-dim)"},children:e.day.slice(5)})]},e.day)})})]}),(0,n.jsxs)("div",{style:{borderRadius:12,border:"1px solid var(--border)",overflow:"hidden"},children:[(0,n.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)",padding:"10px 14px",borderBottom:"1px solid var(--border)"},children:o("desktop.usageTopSessions")}),a&&0===a.sessions.length?(0,n.jsx)("div",{style:{padding:"14px",fontSize:12,color:"var(--text-muted)"},children:o("desktop.usageNoData")}):(a?.sessions??[]).slice(0,12).map(e=>(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"8px 14px",borderBottom:"1px solid var(--border)"},children:[(0,n.jsx)("span",{style:{flex:1,minWidth:0,fontSize:12,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name??e.firstMessage??e.id}),(0,n.jsx)("span",{style:{flexShrink:0,fontSize:11,color:"var(--text-muted)",fontFamily:"var(--font-mono)"},children:dg(e.tokens)})]},e.path))]})]})]})]})}function df(){let{t:e}=(0,F.s)(),[t,o]=(0,r.useState)(!1),[s,i]=(0,r.useState)("");(0,r.useEffect)(()=>{o(new URLSearchParams(window.location.search).has("piweb_connected")),i(window.location.host)},[]);let a=(0,r.useCallback)(()=>{window.location.href="piweb-switch://manage"},[]);return t?(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",flex:1,minWidth:0,minHeight:0,overflowY:"auto"},children:[(0,n.jsx)("header",{style:{padding:"18px 22px 14px",borderBottom:"1px solid var(--border)"},children:(0,n.jsx)("h1",{style:{margin:0,fontSize:16,fontWeight:700,color:"var(--text)"},children:e("desktop.server")})}),(0,n.jsxs)("div",{style:{padding:"18px 22px",display:"flex",flexDirection:"column",gap:14},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"12px 14px",borderRadius:10,background:"var(--bg-hover)",border:"1px solid var(--border)"},children:[(0,n.jsx)(ax.X,{size:18,color:"var(--accent)"}),(0,n.jsxs)("div",{style:{minWidth:0},children:[(0,n.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)"},children:e("desktop.serverCurrent")}),(0,n.jsx)("div",{style:{fontSize:14,fontWeight:600,color:"var(--text)",fontFamily:"var(--font-mono)",wordBreak:"break-all"},children:s})]})]}),(0,n.jsxs)("button",{type:"button",onClick:a,style:{display:"flex",alignItems:"center",justifyContent:"center",gap:8,padding:"10px 16px",borderRadius:10,background:"linear-gradient(135deg, var(--accent), var(--accent-hover, var(--accent)))",color:"#fff",fontSize:14,fontWeight:600,cursor:"pointer",border:"none"},children:[(0,n.jsx)(a8.o,{size:16}),e("desktop.serverSwitch")]}),(0,n.jsx)("p",{style:{margin:0,fontSize:12.5,lineHeight:1.7,color:"var(--text-muted)"},children:e("desktop.serverSwitchHint")})]})]}):null}let dx=[{id:"server",labelKey:"desktop.server",Icon:ax.X},{id:"display",labelKey:"desktop.display",Icon:ak.V},{id:"chat",labelKey:"desktop.chat",Icon:av.W},{id:"models",labelKey:"desktop.models",Icon:T.f},{id:"skills",labelKey:"desktop.skills",Icon:R.B},{id:"plugins",labelKey:"desktop.plugins",Icon:z.F},{id:"proxy",labelKey:"desktop.proxy",Icon:ay.l},{id:"features",labelKey:"desktop.features",Icon:u.l},{id:"logs",labelKey:"desktop.logs",Icon:y.B},{id:"snippets",labelKey:"desktop.snippets",Icon:rv.c},{id:"usage",labelKey:"desktop.usage",Icon:ab._},{id:"mcp",labelKey:"desktop.mcp",Icon:aw.b},{id:"subagents",labelKey:"desktop.subagents",Icon:aj.d},{id:"tools",labelKey:"desktop.tools",Icon:aw.b},{id:"backup",labelKey:"desktop.backup",Icon:nd.W},{id:"import",labelKey:"desktop.importSessions",Icon:I.z}];function dk({initialTab:e="models",cwd:t,sessionId:o,onCloseAction:s,onModelsSavedAction:i,onSessionReloadedAction:a,onSessionsChanged:l}){let d=$(),{t:c}=(0,F.s)(),[u,h]=(0,r.useState)("skills"===e||"plugins"===e?t?e:"display":e),[g,m]=(0,r.useState)(!1);(0,r.useEffect)(()=>{m(new URLSearchParams(window.location.search).has("piweb_connected"))},[]);let f=g?dx:dx.filter(({id:e})=>"server"!==e),[x,k]=(0,r.useState)(!1),[v,y]=(0,r.useState)(null),b=(0,r.useRef)(new Set),w=(0,r.useCallback)(e=>(b.current.add(e),()=>{b.current.delete(e)}),[]),j=(0,r.useCallback)(async()=>{if(!x){k(!0),y(null);try{let e=(await Promise.allSettled([...b.current].map(e=>e()))).find(e=>"rejected"===e.status);if(e)throw e.reason;s()}catch(e){y(e instanceof Error?e.message:String(e))}finally{k(!1)}}},[x,s]);return(0,n.jsx)("div",{style:{position:"fixed",inset:0,zIndex:1e3,background:"rgba(0,0,0,0.35)",display:"flex",alignItems:"center",justifyContent:"center"},onClick:e=>{e.target===e.currentTarget&&j()},children:(0,n.jsxs)("section",{role:"dialog","aria-modal":"true","aria-label":c("desktop.settings"),className:"settings-modal",style:{width:d?"calc(100vw - 16px)":1e3,maxWidth:"calc(100vw - 16px)",height:d?"calc(100dvh - 16px)":"80vh",maxHeight:"calc(100dvh - 16px)",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:10,display:"flex",flexDirection:"column",boxShadow:"0 8px 32px rgba(0,0,0,0.18)",overflow:"hidden"},children:[(0,n.jsxs)("header",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 18px",borderBottom:"1px solid var(--border)",flexShrink:0},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"baseline",gap:10,minWidth:0},children:[(0,n.jsx)("span",{style:{fontSize:15,fontWeight:700,color:"var(--text)"},children:c("desktop.settings")}),"models"===u?(0,n.jsx)("code",{style:{fontSize:11,color:"var(--text-muted)",fontFamily:"var(--font-mono)"},children:"~/.pi/agent/models.json"}):t&&(0,n.jsx)("code",{style:{fontSize:11,color:"var(--text-muted)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:t})]}),(0,n.jsx)("button",{type:"button",onClick:()=>{j()},disabled:x,title:c("desktop.closeSettings"),"aria-label":c("desktop.closeSettings"),style:{background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",padding:4,display:"flex"},children:(0,n.jsx)(p.X,{size:18,"aria-hidden":"true"})})]}),(0,n.jsxs)("div",{style:{flex:1,display:"flex",flexDirection:d?"column":"row",minHeight:0,overflow:"hidden",pointerEvents:x?"none":void 0},children:[(0,n.jsx)("nav",{"aria-label":c("desktop.settingsSections"),style:{display:"flex",flexDirection:d?"row":"column",gap:4,width:d?"100%":150,padding:8,flexShrink:0,minWidth:0,background:"var(--bg-panel)",borderRight:d?"none":"1px solid var(--border)",borderBottom:d?"1px solid var(--border)":"none",overflowX:d?"auto":void 0,overflowY:d?"hidden":void 0,WebkitOverflowScrolling:d?"touch":void 0},children:f.filter(({id:e})=>!(d&&"import"===e)).map(({id:e,labelKey:o,Icon:r})=>{let s=("skills"===e||"plugins"===e)&&!t,i=u===e;return(0,n.jsxs)("button",{type:"button",disabled:s,onClick:()=>h(e),"aria-current":i?"page":void 0,style:{display:"flex",alignItems:"center",gap:8,flex:d?"0 0 auto":void 0,whiteSpace:"nowrap",width:d?void 0:"100%",padding:"8px 10px",border:"none",borderRadius:6,background:i?"var(--bg-selected)":"none",color:i?"var(--text)":"var(--text-muted)",cursor:s?"not-allowed":"pointer",opacity:s?.4:1,fontSize:12,fontWeight:i?600:400,textAlign:"left",transition:"background 0.12s, color 0.12s"},title:c(o),"aria-label":c(o),onMouseEnter:e=>{i||s||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{i||(e.currentTarget.style.background="none",e.currentTarget.style.color="var(--text-muted)")},children:[(0,n.jsx)(r,{size:16,"aria-hidden":"true"}),!d&&(0,n.jsx)("span",{children:c(o)})]},e)})}),(0,n.jsx)("div",{style:{display:"server"===u?"flex":"none",flex:1,minWidth:0,minHeight:0},children:(0,n.jsx)(df,{})}),(0,n.jsx)("div",{style:{display:"display"===u?"flex":"none",flex:1,minWidth:0,minHeight:0},children:(0,n.jsx)(aG,{})}),(0,n.jsx)("div",{style:{display:"chat"===u?"flex":"none",flex:1,minWidth:0,minHeight:0},children:(0,n.jsx)(aD,{})}),(0,n.jsx)("div",{style:{display:"models"===u?"flex":"none",flex:1,minWidth:0,minHeight:0},children:(0,n.jsx)(lO,{embedded:!0,sessionId:o,onSavedAction:i,onRegisterFlush:w})}),t&&(0,n.jsx)("div",{style:{display:"skills"===u?"flex":"none",flex:1,minWidth:0,minHeight:0},children:(0,n.jsx)(dt,{cwd:t,embedded:!0,sessionId:o})}),t&&(0,n.jsx)("div",{style:{display:"plugins"===u?"flex":"none",flex:1,minWidth:0,minHeight:0},children:(0,n.jsx)(l0,{cwd:t,sessionId:o,embedded:!0,onReloadedAction:a})}),(0,n.jsx)("div",{style:{display:"proxy"===u?"flex":"none",flex:1,minWidth:0,minHeight:0},children:(0,n.jsx)(l2,{})}),(0,n.jsx)("div",{style:{display:"features"===u?"flex":"none",flex:1,minWidth:0,minHeight:0},children:(0,n.jsx)(a6,{})}),(0,n.jsx)("div",{style:{display:"logs"===u?"flex":"none",flex:1,minWidth:0,minHeight:0},children:(0,n.jsx)(dn,{})}),(0,n.jsx)("div",{style:{display:"snippets"===u?"flex":"none",flex:1,minWidth:0,minHeight:0},children:(0,n.jsx)(di,{})}),(0,n.jsx)("div",{style:{display:"usage"===u?"flex":"none",flex:1,minWidth:0,minHeight:0},children:(0,n.jsx)(dm,{sessionId:o,cwd:t})}),(0,n.jsx)("div",{style:{display:"mcp"===u?"flex":"none",flex:1,minWidth:0,minHeight:0},children:(0,n.jsx)(lu,{sessionId:o})}),(0,n.jsx)("div",{style:{display:"subagents"===u?"flex":"none",flex:1,minWidth:0,minHeight:0},children:(0,n.jsx)(du,{cwd:t,sessionId:o})}),(0,n.jsx)("div",{style:{display:"tools"===u?"flex":"none",flex:1,minWidth:0,minHeight:0},children:(0,n.jsx)(dh,{sessionId:o,onSessionReloaded:a})}),(0,n.jsx)("div",{style:{display:"backup"===u?"flex":"none",flex:1,minWidth:0,minHeight:0},children:(0,n.jsx)(aR,{cwd:t})}),(0,n.jsx)("div",{style:{display:"import"===u?"flex":"none",flex:1,minWidth:0,minHeight:0,overflowY:"auto"},children:(0,n.jsx)(a3,{onSessionsChanged:l})})]}),v&&(0,n.jsx)("div",{style:{padding:"6px 18px",borderTop:"1px solid var(--border)",color:"#f87171",fontSize:11},children:v})]})})}let dv=new Set(["awaiting_input","review","failed"]),dy=(0,r.createContext)(null);function db(){let e=(0,r.useContext)(dy);if(!e)throw Error("useTasksView must be used within TasksViewProvider");return e}function dw({children:e}){let{t}=(0,F.s)(),o=(0,r.useRef)(t);(0,r.useEffect)(()=>{o.current=t},[t]);let[s,i]=(0,r.useState)([]),[a,l]=(0,r.useState)([]),d=(0,r.useRef)(0),c=(0,r.useCallback)(async()=>{let e=++d.current;try{let t=await (0,rq.Wt)(),o=(await Promise.all(t.map(e=>(0,rq.Vk)(e).catch(()=>[])))).flat().sort((e,t)=>t.id-e.id);if(e!==d.current)return;l(e=>dj(e,t)?e:t),i(e=>dj(e,o)?e:o)}catch{}},[]);(0,r.useEffect)(()=>{c();let e=null,t=!1,o=()=>{t||((e=new EventSource("/api/tasks/events")).onmessage=()=>{c()},e.onerror=()=>{e?.close(),e=null,c(),setTimeout(o,2e3)})};o();let n=()=>{"visible"===document.visibilityState&&c()},r=()=>void c();document.addEventListener("visibilitychange",n),window.addEventListener("online",r);let s=setInterval(()=>void c(),6e4);return()=>{t=!0,e?.close(),document.removeEventListener("visibilitychange",n),window.removeEventListener("online",r),clearInterval(s)}},[c]);let p=(0,r.useMemo)(()=>s.filter(e=>dv.has(e.status)&&null==e.archivedAt).length,[s]),u=(0,r.useRef)(null);(0,r.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 o of s)if(e.get(o.id)!==o.status&&("review"===o.status||"failed"===o.status)&&null==o.archivedAt&&"visible"!==document.visibilityState)try{let e="review"===o.status?t("tasks.notifyReview",{title:o.title}):t("tasks.notifyFailed",{title:o.title});!function(e,t){new Promise(o=>{if(!("Notification"in window))return void o();let n=()=>{try{new Notification(e,{body:t,tag:"pi-tasks"})}catch{}o()};"granted"===Notification.permission?n():"denied"!==Notification.permission?Notification.requestPermission().then(e=>{"granted"===e?n():o()}):o()})}("Pi Web Tasks",e)}catch{}}},[s,t]);let h=(0,r.useMemo)(()=>({tasks:s,projects:a,attentionCount:p,refetch:c}),[s,a,p,c]);return(0,n.jsx)(dy.Provider,{value:h,children:e})}function dj(e,t){return JSON.stringify(e)===JSON.stringify(t)}var dS=o(4539),dC=o(12449),dT=o(2571);let dR=["todo","inProgress","attention","done"];function dz(e){return"review"===e.status&&0===e.filesChanged}function dI(){return{defaultAgentType:null,modeId:null,configValues:{},autoProcess:!0,maxConcurrent:1,mergeStrategy:"merge",deleteWorktreeDefault:!0,preflightCommand:null,initCommand:null,stagePrompts:null}}let dM=["todo","inProgress","attention","done"],dP={todo:{id:"todo",marker:"var(--text-dim)"},inProgress:{id:"inProgress",marker:"var(--accent)"},attention:{id:"attention",marker:"#f59e0b"},done:{id:"done",marker:"#10b981"}};var dE=o(54775),dF=o(98998),dD=o(36668);function dW({task:e}){let{t}=(0,F.s)(),o=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)),r={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,n.jsxs)("span",{style:{...r,color:"var(--accent)"},children:[(0,n.jsx)(dE.N,{size:11,className:"pi-spin",style:{animation:"pi-spin 1s linear infinite"},"aria-hidden":"true"}),o]});case"awaiting_input":case"review":return(0,n.jsx)("span",{style:{...r,border:"1px solid rgba(245,158,11,0.45)",background:"rgba(245,158,11,0.08)",color:"#d97706"},children:o});case"done":return(0,n.jsxs)("span",{style:{...r,background:"rgba(16,185,129,0.12)",color:"#059669"},children:[(0,n.jsx)(h.J,{size:10,weight:"bold","aria-hidden":"true"}),o]});case"failed":return(0,n.jsx)("span",{style:{...r,background:"rgba(239,68,68,0.12)",color:"#dc2626"},children:o});default:return(0,n.jsx)("span",{style:{...r,background:"var(--bg-hover)",color:"var(--text-muted)"},children:o})}}function dA({task:e}){let t=e.preflight;if(!t||"review"!==e.status)return null;let o="passed"===t.status?{background:"rgba(16,185,129,0.12)",color:"#059669"}:"failed"===t.status?{background:"rgba(239,68,68,0.12)",color:"#dc2626"}:{background:"var(--bg-hover)",color:"var(--text-muted)"};return(0,n.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:4,borderRadius:999,padding:"1px 6px",fontSize:10,fontWeight:500,lineHeight:1.5,maxWidth:"100%",...o},title:t.command,children:["running"===t.status?(0,n.jsx)(dE.N,{size:10,style:{animation:"pi-spin 1s linear infinite"},"aria-hidden":"true"}):"passed"===t.status?(0,n.jsx)(nO.r,{size:10,"aria-hidden":"true"}):(0,n.jsx)(ia.J,{size:10,"aria-hidden":"true"}),(0,n.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:t.command})]})}function dN({task:e,folderName:t,now:o,onOpen:r,onStart:s,onCancel:i,onRetry:a,onRequeue:l,onViewSession:d,onMerge:c,onArchive:p,onEdit:u}){let{t:g}=(0,F.s)(),m=null!=e.archivedAt,f="running"===e.status||"awaiting_input"===e.status||"merging"===e.status,x=null!=e.filesChanged&&e.filesChanged>0?(0,n.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:3,fontFamily:"var(--font-mono)",fontSize:10},children:[(0,n.jsxs)("span",{style:{color:"#059669"},children:["+",e.additions??0]}),(0,n.jsxs)("span",{style:{color:"#dc2626"},children:["-",e.deletions??0]})]}):null,k=function(e,t){if(!e)return"";let o=new Date(e).getTime();if(Number.isNaN(o))return"";let n=Math.floor(Math.max(0,t-o)/6e4);if(n<1)return"now";if(n<60)return`${n}m`;let r=Math.floor(n/60);if(r<24)return`${r}h`;let s=Math.floor(r/24);return`${s}d`}(e.finishedAt??e.settledAt??e.startedAt??e.createdAt,o),{primary:v,more:y}=(()=>{let t=[],o=null;if(m)return{primary:o={icon:id.T,label:g("tasks.actionUnarchive"),onClick:p},more:t};switch(e.status){case"todo":o={icon:dT.j,label:g("tasks.actionStart"),onClick:s},t.push({icon:ry.S,label:g("tasks.actionEdit"),onClick:u});break;case"queued":case"preparing":case"running":case"awaiting_input":o={icon:dF.k,label:g("tasks.actionCancel"),onClick:i};break;case"review":o=dz(e)?{icon:h.J,label:g("tasks.actionComplete"),onClick:c}:{icon:dD.r,label:g("tasks.actionMerge"),onClick:c};break;case"merging":break;case"failed":o={icon:j.S,label:g("tasks.actionRetry"),onClick:a},t.push({icon:ry.S,label:g("tasks.actionEdit"),onClick:u}),t.push({icon:id.T,label:g("tasks.actionArchive"),onClick:p});break;case"done":o={icon:id.T,label:g("tasks.actionArchive"),onClick:p};break;case"canceled":o={icon:nH.f,label:g("tasks.actionRequeue"),onClick:l},t.push({icon:id.T,label:g("tasks.actionArchive"),onClick:p})}return{primary:o,more:t}})(),b=[...y];return null!=e.conversationId&&b.push({icon:nL.y,label:g("tasks.actionViewSession"),onClick:d}),(0,n.jsxs)("div",{role:"button",tabIndex:0,onClick:r,onKeyDown:e=>{("Enter"===e.key||" "===e.key)&&(e.preventDefault(),r())},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:m?.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,n.jsxs)("div",{style:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:8},children:[(0,n.jsx)("span",{style:{minWidth:0,overflowWrap:"break-word",fontSize:13,fontWeight:500,lineHeight:1.4},children:e.title}),(0,n.jsx)(dW,{task:e})]}),(0,n.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:"2px 6px",marginTop:6,fontSize:11,color:"var(--text-muted)"},children:[t?(0,n.jsx)("span",{style:{maxWidth:160,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:t}):null,t&&e.workBranch?(0,n.jsx)("span",{style:{opacity:.5},children:"/"}):null,e.workBranch?(0,n.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||k)?(0,n.jsx)("span",{style:{opacity:.5},children:"\xb7"}):null,x,x&&k?(0,n.jsx)("span",{style:{opacity:.5},children:"\xb7"}):null,k?(0,n.jsx)("span",{style:{flexShrink:0},children:k}):null,(0,n.jsx)(dA,{task:e})]}),e.lastError&&("failed"===e.status||"review"===e.status)?(0,n.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:"#dc2626"},children:[(0,n.jsx)(nc.t,{size:13,style:{flexShrink:0},"aria-hidden":"true"}),(0,n.jsx)("span",{style:{minWidth:0,flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.lastError}),(0,n.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(),r()},children:g("tasks.errorView")})]}):null,"review"===e.status&&e.resultSummary?(0,n.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,n.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,v||b.length>0?(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6,marginTop:12,paddingTop:12,borderTop:"1px solid var(--border)"},children:[v?(0,n.jsxs)("button",{type:"button",onClick:e=>{e.stopPropagation(),v.onClick()},style:{display:"inline-flex",alignItems:"center",gap:5,padding:"4px 10px",borderRadius:7,background:"var(--accent)",color:"#fff",border:"none",cursor:"pointer",fontSize:11,fontWeight:600},children:[(0,n.jsx)(v.icon,{size:12,weight:"bold","aria-hidden":"true"}),v.label]}):null,(0,n.jsx)("div",{style:{flex:1}}),b.map(e=>(0,n.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,n.jsx)(e.icon,{size:13,"aria-hidden":"true"})},e.label))]}):null]})}function d$({open:e,onOpenChange:t,task:o}){let{t:s}=(0,F.s)(),{refetch:i}=db(),[a,l]=(0,r.useState)(""),[d,c]=(0,r.useState)(!1);if((0,r.useEffect)(()=>{e&&(l(""),c(!1))},[e,o]),!e||!o)return null;let u=async()=>{if(!d){c(!0);try{await (0,rq.oQ)(o.id,o.projectRoot,"cancel",{reason:a.trim()||null}),t(!1),i()}catch(e){console.error("cancel failed",e)}finally{c(!1)}}};return(0,n.jsx)("div",{style:{position:"fixed",inset:0,zIndex:950,display:"flex",alignItems:"center",justifyContent:"center",background:"rgba(0,0,0,0.45)"},onMouseDown:e=>{e.target===e.currentTarget&&t(!1)},children:(0,n.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,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"14px 16px 0"},children:[(0,n.jsx)("h3",{style:{fontSize:15,fontWeight:600,margin:0},children:s("tasks.cancelTitle")}),(0,n.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,n.jsx)(p.X,{size:16,"aria-hidden":"true"})})]}),(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:12,padding:"14px 16px 16px"},children:[(0,n.jsx)("p",{style:{margin:0,fontSize:12,lineHeight:1.5,color:"var(--text-muted)"},children:s("tasks.cancelDescription")}),(0,n.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:5},children:[(0,n.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)"},children:s("tasks.cancelReasonLabel")}),(0,n.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,n.jsxs)("div",{style:{display:"flex",justifyContent:"flex-end",gap:8,marginTop:4},children:[(0,n.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,n.jsx)("button",{type:"button",onClick:()=>void u(),disabled:d,style:{padding:"8px 16px",borderRadius:8,background:"var(--accent)",color:"#fff",border:"none",fontSize:12,fontWeight:600,cursor:"pointer"},children:s("tasks.cancelSubmit")})]})]})]})})}function dL({open:e,onOpenChange:t,task:o}){let{t:s}=(0,F.s)(),{refetch:i}=db(),[a,l]=(0,r.useState)(!0),[d,c]=(0,r.useState)(!1),u=o?.worktreePath!=null;if((0,r.useEffect)(()=>{if(!e||!o)return;c(!1);let t=!1;return(0,rq.CG)(o.projectRoot).then(e=>{t||l(e.deleteWorktreeDefault)}).catch(()=>{t||l(!0)}),()=>{t=!0}},[e,o]),!e||!o)return null;let h=async()=>{if(!d){c(!0);try{await (0,rq.ZX)(o.id,o.projectRoot,u&&a),t(!1),i()}catch(e){console.error("complete failed",e)}finally{c(!1)}}};return(0,n.jsx)("div",{style:{position:"fixed",inset:0,zIndex:950,display:"flex",alignItems:"center",justifyContent:"center",background:"rgba(0,0,0,0.45)"},onMouseDown:e=>{e.target===e.currentTarget&&t(!1)},children:(0,n.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,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"14px 16px 0"},children:[(0,n.jsx)("h3",{style:{fontSize:15,fontWeight:600,margin:0},children:s("tasks.completeTitle")}),(0,n.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,n.jsx)(p.X,{size:16,"aria-hidden":"true"})})]}),(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:12,padding:"14px 16px 16px"},children:[(0,n.jsx)("p",{style:{margin:0,fontSize:12,lineHeight:1.5,color:"var(--text-muted)"},children:s("tasks.completeDescription")}),u?(0,n.jsxs)("label",{style:{display:"flex",alignItems:"center",gap:8,fontSize:13,cursor:"pointer"},children:[(0,n.jsx)("input",{type:"checkbox",checked:a,onChange:e=>l(e.target.checked),style:{accentColor:"var(--accent)"}}),s("tasks.completeDeleteWorktree")]}):null,(0,n.jsxs)("div",{style:{display:"flex",justifyContent:"flex-end",gap:8,marginTop:4},children:[(0,n.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,n.jsx)("button",{type:"button",onClick:()=>void h(),disabled:d,style:{padding:"8px 16px",borderRadius:8,background:"var(--accent)",color:"#fff",border:"none",fontSize:12,fontWeight:600,cursor:"pointer"},children:s("tasks.completeSubmit")})]})]})]})})}var dO=o(51285),dH=o(16894);function dB({open:e,onOpenChange:t,task:o,onViewSession:s,onMerge:i,onEdit:a,onCancel:l,onRetry:d,onRequeue:c,onComplete:u}){let{t:g}=(0,F.s)(),{refetch:m}=db(),[f,x]=(0,r.useState)([]),[v,y]=(0,r.useState)([]),[b,w]=(0,r.useState)(null),[C,T]=(0,r.useState)(null),[R,z]=(0,r.useState)(!1),[I,M]=(0,r.useState)(!1),[P,E]=(0,r.useState)(""),[D,W]=(0,r.useState)(!1),[A,N]=(0,r.useState)(!1),[$,L]=(0,r.useState)(!1),O=o?.id??null,H=o?.projectRoot??null,B=(0,r.useCallback)(async()=>{if(null==O||null==H)return;let[e,t]=await Promise.all([(0,rq.HB)(H,O).catch(()=>[]),o?.worktreePath?(0,rq.JH)(H,O).then(e=>e.files).catch(()=>[]):Promise.resolve([])]);x(e),y(t)},[O,H,o?.worktreePath]);(0,r.useEffect)(()=>{if(!e||null==O)return;x([]),y([]),M(!1),E(""),B();let t=window.setInterval(()=>void B(),5e3);return()=>window.clearInterval(t)},[e,O,B]);let U=(0,r.useCallback)(async e=>{L(!0);try{await e()}catch(e){console.error("detail action failed",e)}finally{L(!1),m()}},[m]),_=(0,r.useCallback)(async e=>{if(null!=H&&null!=O){z(!0);try{let t=await (0,rq.h)(H,O,e);T(t.supported&&t.patch?t.patch:null)}catch{T(null)}finally{z(!1)}}},[H,O]),q=async()=>{null!=o&&null!=H&&(await U(()=>(0,rq.bH)(o.id,H,A)),t(!1))},V=async()=>{null!=o&&null!=H&&P.trim()&&(await U(()=>(0,rq.in)(o.id,H,P.trim())),M(!1),E(""))};if(!e||null==o||null==H)return null;let K=[];if(null==o.archivedAt)switch(o.status){case"todo":K.push({label:g("tasks.actionStart"),icon:dT.j,onClick:()=>void U(()=>(0,rq.oQ)(o.id,H,"start")),filled:!0}),K.push({label:g("tasks.actionEdit"),icon:ry.S,onClick:()=>a(o)});break;case"queued":case"preparing":case"running":case"awaiting_input":K.push({label:g("tasks.actionCancel"),icon:dF.k,onClick:()=>l(o),danger:!0});break;case"review":K.push({label:dz(o)?g("tasks.actionComplete"):g("tasks.actionMerge"),icon:dz(o)?h.J:dO.Y,onClick:()=>dz(o)?u(o):i(o),filled:!0}),K.push({label:g("tasks.actionReturn"),icon:nH.f,onClick:()=>M(!0)});break;case"failed":K.push({label:g("tasks.actionRetry"),icon:j.S,onClick:()=>d(o),filled:!0}),K.push({label:g("tasks.actionEdit"),icon:ry.S,onClick:()=>a(o)});break;case"done":K.push({label:g("tasks.actionArchive"),icon:id.T,onClick:()=>void U(()=>(0,rq.et)(o.id,H,!0))});break;case"canceled":K.push({label:g("tasks.actionRequeue"),icon:nH.f,onClick:()=>c(o),filled:!0})}else K.push({label:g("tasks.actionUnarchive"),icon:id.T,onClick:()=>void U(()=>(0,rq.et)(o.id,H,!1))});return null!=o.conversationId&&K.push({label:g("tasks.actionViewSession"),icon:nL.y,onClick:()=>s(o)}),(0,n.jsx)("div",{style:{position:"fixed",inset:0,zIndex:800,background:"rgba(0,0,0,0.35)"},onMouseDown:e=>{e.target===e.currentTarget&&t(!1)},children:(0,n.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,n.jsxs)("div",{style:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:12,padding:"16px 16px 0"},children:[(0,n.jsxs)("div",{style:{minWidth:0},children:[(0,n.jsx)("h3",{style:{margin:0,fontSize:15,fontWeight:600,lineHeight:1.4,overflowWrap:"break-word"},children:o.title}),(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,marginTop:6},children:[(0,n.jsx)(dW,{task:o}),o.workBranch?(0,n.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:4,fontFamily:"var(--font-mono)",fontSize:11,color:"var(--text-muted)"},children:[(0,n.jsx)(k.Z,{size:12,"aria-hidden":"true"}),o.workBranch]}):null]})]}),(0,n.jsx)("button",{type:"button",onClick:()=>t(!1),"aria-label":g("i18n.close"),style:{background:"none",border:"none",cursor:"pointer",color:"var(--text-muted)",padding:4,display:"flex",flexShrink:0},children:(0,n.jsx)(p.X,{size:16,"aria-hidden":"true"})})]}),(0,n.jsx)("div",{style:{display:"flex",flexWrap:"wrap",gap:8,padding:"14px 16px 0"},children:K.map(e=>{let t,o;return(0,n.jsxs)("button",{type:"button",onClick:e.onClick,disabled:$,style:(t=e.filled,o=e.danger,{display:"inline-flex",alignItems:"center",gap:5,padding:"7px 12px",borderRadius:8,fontSize:12,fontWeight:600,cursor:"pointer",background:t?"var(--accent)":o?"rgba(239,68,68,0.1)":"var(--bg-hover)",color:t?"#fff":o?"#dc2626":"var(--text)",border:t||o?"none":"1px solid var(--border)"}),children:[(0,n.jsx)(e.icon,{size:13,weight:"bold","aria-hidden":"true"}),e.label]},e.label)})}),I&&(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:8,padding:"12px 16px 0"},children:[(0,n.jsx)("textarea",{value:P,onChange:e=>E(e.target.value),placeholder:g("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,n.jsxs)("div",{style:{display:"flex",justifyContent:"flex-end",gap:8},children:[(0,n.jsx)("button",{type:"button",onClick:()=>M(!1),style:{padding:"6px 12px",borderRadius:8,background:"none",border:"1px solid var(--border)",color:"var(--text)",fontSize:12,cursor:"pointer"},children:g("i18n.cancel")}),(0,n.jsx)("button",{type:"button",onClick:()=>void V(),disabled:!P.trim(),style:{padding:"6px 14px",borderRadius:8,background:"var(--accent)",color:"#fff",border:"none",fontSize:12,fontWeight:600,cursor:"pointer"},children:g("tasks.returnSubmit")})]})]}),(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:6,padding:"14px 16px 0",fontSize:12,color:"var(--text-muted)"},children:[(0,n.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,n.jsx)("span",{style:{flexShrink:0,color:"var(--text-dim)",width:64},children:g("tasks.metaProject")}),(0,n.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontFamily:"var(--font-mono)",fontSize:11},children:o.projectRoot})]}),o.createdAt?(0,n.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,n.jsx)("span",{style:{flexShrink:0,color:"var(--text-dim)",width:64},children:g("tasks.metaCreated")}),(0,n.jsx)("span",{children:new Date(o.createdAt).toLocaleString()})]}):null,o.mergeCommit?(0,n.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,n.jsx)("span",{style:{flexShrink:0,color:"var(--text-dim)",width:64},children:g("tasks.metaCommit")}),(0,n.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:11},children:o.mergeCommit})]}):null]}),v.length>0&&(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4,padding:"14px 16px 0"},children:[(0,n.jsx)("span",{style:{fontSize:11,fontWeight:600,color:"var(--text-muted)",textTransform:"uppercase",letterSpacing:"0.05em"},children:g("tasks.changedFiles")}),(0,n.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:2,maxHeight:140,overflowY:"auto"},children:v.map(e=>(0,n.jsxs)("button",{type:"button",onClick:()=>{var t;w(t=e.file),T(null),_(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,n.jsx)(dH.o,{size:13,style:{flexShrink:0,color:"var(--text-muted)"},"aria-hidden":"true"}),(0,n.jsx)("span",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontFamily:"var(--font-mono)",fontSize:11},children:e.file}),(0,n.jsxs)("span",{style:{fontFamily:"var(--font-mono)",fontSize:10,color:"#059669",flexShrink:0},children:["+",e.additions]}),(0,n.jsxs)("span",{style:{fontFamily:"var(--font-mono)",fontSize:10,color:"#dc2626",flexShrink:0},children:["-",e.deletions]})]},e.file))})]}),null!=b&&(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:6,padding:"12px 16px 0",minHeight:0,flexShrink:0},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[(0,n.jsx)("span",{style:{fontSize:11,fontWeight:600,color:"var(--text-muted)"},children:g("tasks.diff")}),(0,n.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:10,color:"var(--text-muted)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1},children:b}),(0,n.jsx)("button",{type:"button",onClick:()=>w(null),style:{background:"none",border:"none",cursor:"pointer",color:"var(--text-muted)",padding:2,display:"flex"},children:(0,n.jsx)(p.X,{size:12,"aria-hidden":"true"})})]}),R?(0,n.jsx)("div",{style:{fontSize:11,color:"var(--text-muted)",padding:8},children:g("tasks.loading")}):C?(0,n.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:C.split("\n").map((e,t)=>{let o;return e.startsWith("+")&&!e.startsWith("+++")?o="#059669":e.startsWith("-")&&!e.startsWith("---")?o="#dc2626":e.startsWith("@@")&&(o="var(--accent)"),(0,n.jsx)("div",{style:{color:o},children:e||" "},t)})}):(0,n.jsx)("div",{style:{fontSize:11,color:"var(--text-muted)",padding:8},children:g("tasks.noDiff")})]}),(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4,padding:"14px 16px 0",flex:1,minHeight:0},children:[(0,n.jsx)("span",{style:{fontSize:11,fontWeight:600,color:"var(--text-muted)",textTransform:"uppercase",letterSpacing:"0.05em"},children:g("tasks.timeline")}),(0,n.jsx)("div",{style:{flex:1,minHeight:0,overflowY:"auto",paddingBottom:8},children:0===f.length?(0,n.jsx)("div",{style:{fontSize:11,color:"var(--text-dim)",padding:8},children:g("tasks.noEvents")}):(0,n.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:2},children:[...f].reverse().map(e=>{var t;let o,r;return(0,n.jsxs)("div",{style:{display:"flex",gap:8,padding:"4px 6px",borderRadius:6,fontSize:11},children:[(0,n.jsx)("span",{style:{color:"var(--text-dim)",flexShrink:0,fontFamily:"var(--font-mono)",fontSize:10,paddingTop:1},children:new Date(e.createdAt).toLocaleTimeString()}),(0,n.jsx)("span",{style:{color:"var(--text)",flexShrink:0,fontWeight:500},children:(t=e.kind,(r=g(o=`tasks.event_${t}`))===o?t:r)}),e.payload?.feedback?(0,n.jsx)("span",{style:{color:"var(--text-muted)",fontStyle:"italic",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:String(e.payload.feedback)}):null]},e.id)})})})]}),(0,n.jsx)("div",{style:{display:"flex",alignItems:"center",justifyContent:"flex-end",gap:8,padding:"10px 16px",borderTop:"1px solid var(--border)",flexShrink:0},children:D?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("label",{style:{display:"flex",alignItems:"center",gap:6,fontSize:12,cursor:"pointer"},children:[(0,n.jsx)("input",{type:"checkbox",checked:A,onChange:e=>N(e.target.checked),style:{accentColor:"var(--accent)"}}),g("tasks.deleteWorktree")]}),(0,n.jsx)("button",{type:"button",onClick:()=>W(!1),style:{padding:"6px 12px",borderRadius:8,background:"none",border:"1px solid var(--border)",color:"var(--text)",fontSize:12,cursor:"pointer"},children:g("i18n.cancel")}),(0,n.jsx)("button",{type:"button",onClick:()=>void q(),disabled:$,style:{padding:"6px 14px",borderRadius:8,background:"#dc2626",color:"#fff",border:"none",fontSize:12,fontWeight:600,cursor:"pointer"},children:g("tasks.deleteConfirm")})]}):(0,n.jsxs)("button",{type:"button",onClick:()=>W(!0),style:{display:"inline-flex",alignItems:"center",gap:5,padding:"6px 12px",borderRadius:8,background:"none",border:"1px solid var(--border)",color:"#dc2626",fontSize:12,cursor:"pointer"},children:[(0,n.jsx)(S.l,{size:13,"aria-hidden":"true"}),g("tasks.delete")]})})]})})}var dU=o(17757);function d_({open:e,onOpenChange:t,task:o,defaultProject:s,projects:i,prefillTitle:a,prefillPrompt:l,onSubmit:d}){let{t:c}=(0,F.s)(),[u,h]=(0,r.useState)(""),[g,m]=(0,r.useState)(""),[f,x]=(0,r.useState)(""),[k,v]=(0,r.useState)([]),[y,b]=(0,r.useState)(""),[w,j]=(0,r.useState)(!1),C=(0,r.useRef)(!1);if((0,r.useEffect)(()=>{if(!e){C.current=!1;return}C.current||(C.current=!0,h(o?.projectRoot??s??i[0]??""),m(o?.title??a??""),x(o?.config?.prompt??l??""),(0,rq.VB)().then(v).catch(()=>void 0))},[e,o,s,i,a,l]),!e)return null;let T=async()=>{if(u&&g.trim()&&!w){j(!0);try{await d(u,g.trim(),{prompt:f.trim(),agentType:o?.config?.agentType??null,modelId:o?.config?.modelId??null,thinkingLevel:o?.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,rq.nY)({name:y.trim(),title:g.trim(),config:{prompt:f.trim()}}),b(""),(0,rq.VB)().then(v).catch(()=>void 0)}catch(e){console.error("save template failed",e)}},z=async e=>{try{await (0,rq.B_)(e),(0,rq.VB)().then(v).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,n.jsx)("div",{style:{position:"fixed",inset:0,zIndex:900,display:"flex",alignItems:"center",justifyContent:"center",background:"rgba(0,0,0,0.45)"},onMouseDown:e=>{e.target===e.currentTarget&&t(!1)},children:(0,n.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,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"14px 16px 0"},children:[(0,n.jsx)("h3",{style:{fontSize:15,fontWeight:600,margin:0},children:o?c("tasks.editTitle"):c("tasks.newTitle")}),(0,n.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,n.jsx)(p.X,{size:16,"aria-hidden":"true"})})]}),(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:12,padding:"14px 16px 16px"},children:[k.length>0&&(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,n.jsx)("span",{style:{fontSize:11,fontWeight:600,color:"var(--text-muted)",textTransform:"uppercase",letterSpacing:"0.05em"},children:c("tasks.templates")}),(0,n.jsx)("div",{style:{display:"flex",flexWrap:"wrap",gap:6},children:k.map(e=>(0,n.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:4,borderRadius:999,background:"var(--bg-hover)",padding:"3px 8px",fontSize:11},children:[(0,n.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,n.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,n.jsx)(S.l,{size:10,"aria-hidden":"true"})})]},e.id))})]}),(0,n.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,n.jsx)("span",{style:{fontSize:12,fontWeight:500,color:"var(--text)"},children:c("tasks.fieldProject")}),(0,n.jsx)("select",{value:u,onChange:e=>h(e.target.value),style:I,children:i.map(e=>(0,n.jsx)("option",{value:e,children:e.split("/").filter(Boolean).pop()??e},e))})]}),(0,n.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,n.jsx)("span",{style:{fontSize:12,fontWeight:500,color:"var(--text)"},children:c("tasks.fieldTitle")}),(0,n.jsx)("input",{value:g,onChange:e=>m(e.target.value),placeholder:c("tasks.fieldTitlePlaceholder"),style:I,autoFocus:!0})]}),(0,n.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,n.jsx)("span",{style:{fontSize:12,fontWeight:500,color:"var(--text)"},children:c("tasks.fieldPrompt")}),(0,n.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,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6},children:[(0,n.jsx)("input",{value:y,onChange:e=>b(e.target.value),placeholder:c("tasks.templateNamePlaceholder"),style:{...I,flex:1}}),(0,n.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,n.jsx)(dU.D,{size:13,"aria-hidden":"true"}),c("tasks.saveAsTemplate")]})]}),(0,n.jsxs)("div",{style:{display:"flex",justifyContent:"flex-end",gap:8,marginTop:4},children:[(0,n.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,n.jsx)("button",{type:"button",onClick:()=>void T(),disabled:!u||!g.trim()||w,style:{padding:"8px 16px",borderRadius:8,background:"var(--accent)",color:"#fff",border:"none",fontSize:12,fontWeight:600,cursor:"pointer"},children:c("tasks.save")})]})]})]})})}function dq({open:e,onOpenChange:t,task:o}){let{t:s}=(0,F.s)(),{refetch:i}=db(),[a,l]=(0,r.useState)(!0),[d,c]=(0,r.useState)(""),[u,h]=(0,r.useState)(!0),[g,m]=(0,r.useState)(!1);if((0,r.useEffect)(()=>{e&&o&&(l(!0),c(o.title),m(!1),(0,rq.CG)(o.projectRoot).then(e=>h(e.deleteWorktreeDefault)).catch(()=>h(!0)))},[e,o]),!e||!o)return null;let f=async()=>{if((a||d.trim())&&!g){m(!0);try{await (0,rq.oB)(o.id,o.projectRoot,a?null:d.trim(),u),t(!1),i()}catch(e){console.error("merge failed",e)}finally{m(!1)}}};return(0,n.jsx)("div",{style:{position:"fixed",inset:0,zIndex:950,display:"flex",alignItems:"center",justifyContent:"center",background:"rgba(0,0,0,0.45)"},onMouseDown:e=>{e.target===e.currentTarget&&t(!1)},children:(0,n.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,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"14px 16px 0"},children:[(0,n.jsx)("h3",{style:{fontSize:15,fontWeight:600,margin:0},children:s("tasks.mergeTitle")}),(0,n.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,n.jsx)(p.X,{size:16,"aria-hidden":"true"})})]}),(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:12,padding:"14px 16px 16px"},children:[(0,n.jsxs)("label",{style:{display:"flex",alignItems:"center",gap:8,fontSize:13,cursor:"pointer"},children:[(0,n.jsx)("input",{type:"radio",checked:a,onChange:()=>l(!0),style:{accentColor:"var(--accent)"}}),s("tasks.mergeAutoMessage")]}),(0,n.jsxs)("label",{style:{display:"flex",alignItems:"center",gap:8,fontSize:13,cursor:"pointer"},children:[(0,n.jsx)("input",{type:"radio",checked:!a,onChange:()=>l(!1),style:{accentColor:"var(--accent)"}}),s("tasks.mergeManualMessage")]}),!a&&(0,n.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,n.jsxs)("label",{style:{display:"flex",alignItems:"center",gap:8,fontSize:13,cursor:"pointer"},children:[(0,n.jsx)("input",{type:"checkbox",checked:u,onChange:e=>h(e.target.checked),style:{accentColor:"var(--accent)"}}),s("tasks.mergeDeleteWorktree")]}),(0,n.jsxs)("div",{style:{display:"flex",justifyContent:"flex-end",gap:8,marginTop:4},children:[(0,n.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,n.jsx)("button",{type:"button",onClick:()=>void f(),disabled:!a&&!d.trim()||g,style:{padding:"8px 16px",borderRadius:8,background:"var(--accent)",color:"#fff",border:"none",fontSize:12,fontWeight:600,cursor:"pointer"},children:s("tasks.mergeConfirm")})]})]})]})})}function dV({open:e,onOpenChange:t,task:o,kind:s}){let{t:i}=(0,F.s)(),{refetch:a}=db(),[l,d]=(0,r.useState)(""),[c,u]=(0,r.useState)(!1);if((0,r.useEffect)(()=>{e&&(d(""),u(!1))},[e,o]),!e||!o)return null;let h="retry"===s,g=async()=>{if(!c){u(!0);try{await (0,rq.oQ)(o.id,o.projectRoot,s,{note:l.trim()||null}),t(!1),a()}catch(e){console.error("restart failed",e)}finally{u(!1)}}};return(0,n.jsx)("div",{style:{position:"fixed",inset:0,zIndex:950,display:"flex",alignItems:"center",justifyContent:"center",background:"rgba(0,0,0,0.45)"},onMouseDown:e=>{e.target===e.currentTarget&&t(!1)},children:(0,n.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,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"14px 16px 0"},children:[(0,n.jsx)("h3",{style:{fontSize:15,fontWeight:600,margin:0},children:i(h?"tasks.restartTitleRetry":"tasks.restartTitleRequeue")}),(0,n.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,n.jsx)(p.X,{size:16,"aria-hidden":"true"})})]}),(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:12,padding:"14px 16px 16px"},children:[(0,n.jsx)("p",{style:{margin:0,fontSize:12,lineHeight:1.5,color:"var(--text-muted)"},children:i("tasks.restartDescription")}),(0,n.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:5},children:[(0,n.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)"},children:i("tasks.actionAddNote")}),(0,n.jsx)("textarea",{value:l,onChange:e=>d(e.target.value),placeholder:i(h?"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,n.jsxs)("div",{style:{display:"flex",justifyContent:"flex-end",gap:8,marginTop:4},children:[(0,n.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,n.jsx)("button",{type:"button",onClick:()=>void g(),disabled:c,style:{padding:"8px 16px",borderRadius:8,background:"var(--accent)",color:"#fff",border:"none",fontSize:12,fontWeight:600,cursor:"pointer"},children:i(h?"tasks.actionRetry":"tasks.actionRequeue")})]})]})]})})}let dK=["work","retry","return","merge"];function dG({open:e,onOpenChange:t,projectRoot:o}){let{t:s}=(0,F.s)(),{projects:i}=db(),[a,l]=(0,r.useState)(""),[d,c]=(0,r.useState)(()=>dI()),[u,h]=(0,r.useState)(!1),[g,m]=(0,r.useState)(!1);if((0,r.useEffect)(()=>{if(!e)return;let t=o??i[0]??"";l(t),t&&(0,rq.Pf)(t).then(e=>{h(null!=e),c(e??dI())}).catch(()=>{h(!1),c(dI())})},[e,o,i]),!e)return null;let f=(e,t)=>{c(o=>({...o,[e]:t}))},x=async()=>{if(a&&!g){m(!0);try{await (0,rq.eA)(a,d),h(!0),t(!1)}catch(e){console.error("save settings failed",e)}finally{m(!1)}}},k=async()=>{if(a)try{await (0,rq.E)(a),h(!1),c(dI())}catch(e){console.error("reset settings failed",e)}},v={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,n.jsx)("div",{style:{position:"fixed",inset:0,zIndex:960,display:"flex",alignItems:"center",justifyContent:"center",background:"rgba(0,0,0,0.45)"},onMouseDown:e=>{e.target===e.currentTarget&&t(!1)},children:(0,n.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,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"14px 16px 0"},children:[(0,n.jsx)("h3",{style:{fontSize:15,fontWeight:600,margin:0},children:s("tasks.settingsTitle")}),(0,n.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,n.jsx)(p.X,{size:16,"aria-hidden":"true"})})]}),(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:10,padding:"14px 16px 16px"},children:[(0,n.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,n.jsx)("span",{style:{fontSize:12,fontWeight:500},children:s("tasks.settingsProject")}),(0,n.jsx)("select",{value:a,onChange:e=>l(e.target.value),style:v,children:i.map(e=>(0,n.jsx)("option",{value:e,children:e.split("/").filter(Boolean).pop()??e},e))})]}),a?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("div",{style:y,children:[(0,n.jsx)("span",{style:{fontSize:12},children:s("tasks.settingsAutoProcess")}),(0,n.jsx)("input",{type:"checkbox",checked:d.autoProcess,onChange:e=>f("autoProcess",e.target.checked),style:{accentColor:"var(--accent)"}})]}),(0,n.jsxs)("div",{style:y,children:[(0,n.jsx)("span",{style:{fontSize:12},children:s("tasks.settingsMaxConcurrent")}),(0,n.jsx)("input",{type:"number",min:0,value:d.maxConcurrent,onChange:e=>f("maxConcurrent",Math.max(0,Number(e.target.value)||0)),style:{...v,width:90}})]}),(0,n.jsxs)("div",{style:y,children:[(0,n.jsx)("span",{style:{fontSize:12},children:s("tasks.settingsMergeStrategy")}),(0,n.jsxs)("select",{value:d.mergeStrategy,onChange:e=>f("mergeStrategy",e.target.value),style:{...v,width:140},children:[(0,n.jsx)("option",{value:"merge",children:s("tasks.mergeStrategyMerge")}),(0,n.jsx)("option",{value:"squash",children:s("tasks.mergeStrategySquash")})]})]}),(0,n.jsxs)("div",{style:y,children:[(0,n.jsx)("span",{style:{fontSize:12},children:s("tasks.settingsDeleteWorktree")}),(0,n.jsx)("input",{type:"checkbox",checked:d.deleteWorktreeDefault,onChange:e=>f("deleteWorktreeDefault",e.target.checked),style:{accentColor:"var(--accent)"}})]}),(0,n.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,n.jsx)("span",{style:{fontSize:12},children:s("tasks.settingsPreflightCommand")}),(0,n.jsx)("input",{value:d.preflightCommand??"",onChange:e=>f("preflightCommand",e.target.value||null),placeholder:s("tasks.settingsPreflightPlaceholder"),style:{...v,fontFamily:"var(--font-mono)",fontSize:11}})]}),(0,n.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,n.jsx)("span",{style:{fontSize:12},children:s("tasks.settingsInitCommand")}),(0,n.jsx)("input",{value:d.initCommand??"",onChange:e=>f("initCommand",e.target.value||null),placeholder:s("tasks.settingsInitPlaceholder"),style:{...v,fontFamily:"var(--font-mono)",fontSize:11}})]}),(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:6,paddingTop:4},children:[(0,n.jsx)("span",{style:{fontSize:12,fontWeight:500},children:s("tasks.settingsStagePrompts")}),dK.map(e=>(0,n.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,n.jsx)("span",{style:{fontSize:11,color:"var(--text-muted)"},children:s(`tasks.stage.${e}`)}),(0,n.jsx)("input",{value:d.stagePrompts?.[e]??"",onChange:t=>f("stagePrompts",{...d.stagePrompts??{},[e]:t.target.value}),style:{...v,fontSize:11}})]},e))]}),u&&(0,n.jsx)("button",{type:"button",onClick:()=>void k(),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,n.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)",padding:8},children:s("tasks.settingsNoProject")}),(0,n.jsxs)("div",{style:{display:"flex",justifyContent:"flex-end",gap:8,marginTop:4},children:[(0,n.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,n.jsx)("button",{type:"button",onClick:()=>void x(),disabled:!a||g,style:{padding:"8px 16px",borderRadius:8,background:"var(--accent)",color:"#fff",border:"none",fontSize:12,fontWeight:600,cursor:"pointer"},children:s("tasks.save")})]})]})]})})}function dJ({open:e,onOpenChange:t,task:o}){let{t:s}=(0,F.s)();return((0,r.useEffect)(()=>{if(!e)return},[e,o]),e&&o)?(0,n.jsx)("div",{style:{position:"fixed",inset:0,zIndex:970,display:"flex",alignItems:"center",justifyContent:"center",background:"rgba(0,0,0,0.45)"},onMouseDown:e=>{e.target===e.currentTarget&&t(!1)},children:(0,n.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,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"14px 16px 0"},children:[(0,n.jsx)("h3",{style:{fontSize:15,fontWeight:600,margin:0},children:s("tasks.sessionTitle")}),(0,n.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,n.jsx)(p.X,{size:16,"aria-hidden":"true"})})]}),(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:10,padding:"14px 16px 16px",fontSize:12},children:[(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:8,padding:10},children:[(0,n.jsx)("span",{style:{color:"var(--text-muted)"},children:s("tasks.sessionId")}),(0,n.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:11,overflowWrap:"anywhere"},children:o.conversationId??"—"})]}),o.sessionFile?(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:8,padding:10},children:[(0,n.jsx)("span",{style:{color:"var(--text-muted)"},children:s("tasks.sessionFile")}),(0,n.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:11,overflowWrap:"anywhere"},children:o.sessionFile})]}):null,(0,n.jsx)("div",{style:{fontSize:11,color:"var(--text-muted)",lineHeight:1.6},children:s("tasks.sessionHint")}),(0,n.jsx)("div",{style:{display:"flex",justifyContent:"flex-end",marginTop:4},children:(0,n.jsx)("button",{type:"button",onClick:()=>t(!1),style:{padding:"8px 16px",borderRadius:8,background:"var(--accent)",color:"#fff",border:"none",fontSize:12,fontWeight:600,cursor:"pointer"},children:s("i18n.close")})})]})]})}):null}let dY="__all__",dX="pi-tasks-board-filter",dZ={showCanceled:!1,showArchived:!1},dQ="pi:open-task-settings";function d0(){let{t:e}=(0,F.s)(),{attentionCount:t}=db();return(0,n.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,n.jsxs)("h1",{style:{margin:0,display:"flex",alignItems:"center",gap:6,fontSize:13,fontWeight:600},children:[(0,n.jsx)(aJ.x,{size:15,color:"var(--text-muted)","aria-hidden":"true"}),e("tasks.title"),(0,n.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,n.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:4,borderRadius:999,background:"rgba(239,68,68,0.12)",color:"#dc2626",padding:"1px 8px",fontSize:10,fontWeight:700},children:[t," ",e("tasks.attentionBadge")]}):null,(0,n.jsx)("div",{style:{flex:1}}),(0,n.jsxs)("button",{type:"button",onClick:()=>window.dispatchEvent(new Event(dQ)),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,n.jsx)(dS.O,{size:13,"aria-hidden":"true"}),e("tasks.settingsTitle")]})]})}function d1({activeProject:e}){let{t}=(0,F.s)(),{tasks:s,projects:i,refetch:a}=db(),[l,c]=(0,r.useState)(null),[p,u]=(0,r.useState)(()=>(function(){try{let e=window.localStorage.getItem(dX);if(e){let t=JSON.parse(e);return{showCanceled:t.showCanceled??!1,showArchived:t.showArchived??!1}}}catch{}return dZ})()),[h,g]=(0,r.useState)(!1);(0,r.useEffect)(()=>{try{window.localStorage.setItem(dX,JSON.stringify(p))}catch{}},[p]);let[m,f]=(0,r.useState)(null),[k,v]=(0,r.useState)(!1),y=(0,r.useRef)(null),b=(0,r.useRef)({x:0,y:0}),w=(0,r.useRef)(null),j=(0,r.useRef)(null),[S,C]=(0,r.useState)(null),T=(0,r.useRef)(null);T.current=S;let R=(0,r.useRef)(!1),z=(0,r.useRef)(!1),[I,M]=(0,r.useState)(()=>Date.now());(0,r.useEffect)(()=>{let e=window.setInterval(()=>M(Date.now()),6e4);return()=>window.clearInterval(e)},[]);let[P,E]=(0,r.useState)(!1),[D,W]=(0,r.useState)(null),[A,N]=(0,r.useState)(null);(0,r.useEffect)(()=>{let e=()=>{let e,t=(e=nZ,nZ=null,e);t&&(W(null),N(t),E(!0))};return e(),window.addEventListener(nX,e),()=>window.removeEventListener(nX,e)},[]);let[$,L]=(0,r.useState)(null),[O,H]=(0,r.useState)(null),[B,U]=(0,r.useState)(!1),[_,q]=(0,r.useState)(null),[V,K]=(0,r.useState)(!1),[G,J]=(0,r.useState)(null),[Y,X]=(0,r.useState)("retry"),[Z,Q]=(0,r.useState)(!1),[ee,et]=(0,r.useState)(null),[eo,en]=(0,r.useState)(!1),[er,es]=(0,r.useState)(!1),[ei,ea]=(0,r.useState)(null),[el,ed]=(0,r.useState)(!1);(0,r.useEffect)(()=>{let e=()=>es(!0);return window.addEventListener(dQ,e),()=>window.removeEventListener(dQ,e)},[]);let ec=(0,r.useMemo)(()=>null==l?s:s.filter(e=>e.projectRoot===l),[s,l]),ep=(0,r.useMemo)(()=>(function(e,t,o=!1){let n={todo:[],inProgress:[],attention:[],done:[]};for(let r of e)("canceled"!==r.status||t)&&(null==r.archivedAt||o)&&n[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"}}(r.status)].push(r);for(let e of dR)n[e].sort((e,t)=>(t.updatedAt??"").localeCompare(e.updatedAt??""));return n})(ec,p.showCanceled,p.showArchived),[ec,p]),eu=(0,r.useMemo)(()=>{let e=ep.todo;if(null==S)return e;let t=new Map(e.map(e=>[e.id,e])),o=S.flatMap(e=>t.get(e)??[]);for(let t of e)S.includes(t.id)||o.push(t);return o},[ep.todo,S]),eh=(0,r.useMemo)(()=>s.find(e=>e.id===$)??null,[s,$]),eg=(0,r.useMemo)(()=>s.find(e=>e.id===ei)??null,[s,ei]),em=(0,r.useCallback)(async e=>{try{await e()}catch(e){console.error("task action failed",e)}finally{a()}},[a]),ef=(0,r.useCallback)(e=>{null!=e.conversationId&&(ea(e.id),ed(!0))},[ea,ed]),ex=(0,r.useCallback)(e=>{H(e),U(!0)},[H,U]),ek=(0,r.useCallback)(()=>{W(null),E(!0)},[W,E]),ev=(0,r.useCallback)((e,t)=>{let o=w.current,n=y.current;o&&n&&(o.style.transform=`translate3d(${e-n.dx}px, ${t-n.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,r.useCallback)(e=>{if(f(null),v(!1),e){R.current=!1;return}requestAnimationFrame(()=>{R.current=!1})},[f,v]),ew=(0,r.useCallback)(()=>{z.current=!0,C(null),eb(!0)},[eb,C]);(0,r.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,r.useEffect)(()=>{m&&!eu.some(e=>e.id===m.task.id)&&ew()},[m,eu,ew]);let ej=(0,r.useCallback)((e,t,o)=>{if(z.current){eb(!0),C(null);return}let n=j.current?.getBoundingClientRect(),r=null!=n&&t>=n.left&&t<=n.right&&o>=n.top&&o<=n.bottom;if(eb(!1),r){C(null);let t=s.find(t=>t.id===e.id);t?.status==="todo"&&null!=l&&em(()=>(0,rq.oQ)(e.id,e.projectRoot,"start"));return}let i=T.current;null!=l&&null!=i&&(async()=>{try{await (0,rq.Lu)(l,i)}catch(e){console.error("reorder failed",e)}await a(),C(null)})()},[em,eb,l,a,s]),eS=(0,r.useCallback)(()=>{em(async()=>{let e=await (0,rq.a5)(l);e>0&&console.log(`started ${e} tasks`)})},[em,l]),eC=(0,r.useCallback)(()=>{let e=ep.done.filter(e=>null==e.archivedAt);0!==e.length&&em(()=>Promise.all(e.map(e=>(0,rq.et)(e.id,e.projectRoot,!0))))},[em,ep.done]),eT=+(p.showCanceled!==dZ.showCanceled)+ +(p.showArchived!==dZ.showArchived),eR=s.length>0,ez=(0,r.useMemo)(()=>{let t=new Set(i);return e&&t.add(e),[...t].sort()},[i,e]),eI=(0,r.useMemo)(()=>{let e=new Map;for(let t of ez)e.set(t,t.split("/").filter(Boolean).pop()??t);return e},[ez]);return(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",minHeight:0},children:[eR&&(0,n.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:8,padding:"14px 16px 8px"},children:[(0,n.jsxs)("select",{value:l??dY,onChange:e=>c(e.target.value===dY?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,n.jsx)("option",{value:dY,children:t("tasks.allFolders")}),ez.map(e=>(0,n.jsx)("option",{value:e,children:eI.get(e)??e},e))]}),(0,n.jsxs)("div",{style:{position:"relative"},children:[(0,n.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,n.jsx)(dC.n,{size:13,"aria-hidden":"true"}),t("tasks.filter"),eT>0?(0,n.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,n.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,n.jsxs)("label",{style:{display:"flex",alignItems:"center",gap:8,padding:"6px 8px",borderRadius:8,cursor:"pointer",fontSize:12},children:[(0,n.jsx)("input",{type:"checkbox",checked:p[e],onChange:t=>u(o=>({...o,[e]:t.target.checked})),style:{accentColor:"var(--accent)"}}),t]},e))})]}),(0,n.jsx)("div",{style:{flex:1}}),(0,n.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,n.jsx)(dT.j,{size:13,"aria-hidden":"true"}),t("tasks.startAll")]}),(0,n.jsxs)("button",{type:"button",onClick:ek,style:{display:"inline-flex",alignItems:"center",gap:6,height:30,borderRadius:999,padding:"0 14px",background:"var(--accent)",color:"#fff",border:"none",fontSize:12,fontWeight:600,cursor:"pointer"},children:[(0,n.jsx)(x.F,{size:13,weight:"bold","aria-hidden":"true"}),t("tasks.new")]})]}),eR?(0,n.jsx)("div",{style:{flex:1,minHeight:0,overflowX:"auto"},children:(0,n.jsx)("div",{style:{display:"grid",gridTemplateColumns:"repeat(4, minmax(0, 1fr))",gap:16,minWidth:"56rem",height:"100%",padding:"4px 16px 16px"},children:dM.map(e=>{let o="todo"===e?eu:ep[e],r=dP[e],s=e=>(0,n.jsx)(dN,{task:e,folderName:e.projectRoot?eI.get(e.projectRoot)??null:null,now:I,onOpen:()=>{R.current||L(e.id)},onStart:()=>void em(()=>(0,rq.oQ)(e.id,e.projectRoot,"start")),onCancel:()=>{q(e),K(!0)},onRetry:()=>{J(e),X("retry"),Q(!0)},onRequeue:()=>{J(e),X("requeue"),Q(!0)},onViewSession:()=>ef(e),onMerge:()=>{dz(e)?(et(e),en(!0)):ex(e)},onArchive:()=>void em(()=>(0,rq.et)(e.id,e.projectRoot,null==e.archivedAt)),onEdit:()=>{W(e),E(!0)}},e.id);return(0,n.jsxs)("div",{ref:"inProgress"===e?j:void 0,style:{display:"flex",flexDirection:"column",minHeight:0,gap:8},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,height:24,flexShrink:0,padding:"0 2px"},children:[(0,n.jsx)("span",{style:{width:3,height:14,borderRadius:999,background:r.marker,flexShrink:0},"aria-hidden":"true"}),(0,n.jsx)("h2",{style:{fontSize:12,fontWeight:600,color:"var(--text)"},children:t(`tasks.col${e[0].toUpperCase()}${e.slice(1)}`)}),(0,n.jsx)("span",{style:{borderRadius:999,background:"var(--bg-hover)",padding:"1px 8px",fontSize:10,fontWeight:600,color:"var(--text-muted)"},children:o.length}),(0,n.jsx)("div",{style:{flex:1}}),"done"===e&&ep.done.some(e=>null==e.archivedAt)?(0,n.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===o.length?(0,n.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?k?{borderColor:"var(--accent)",background:"rgba(37,99,235,0.08)"}:{borderColor:"var(--accent)"}:{}},children:(0,n.jsx)("p",{style:{fontSize:12,color:"var(--text-muted)"},children:t(`tasks.emptyCol${e[0].toUpperCase()}${e.slice(1)}`)})}):(0,n.jsx)("div",{style:{flex:1,minHeight:0,overflowY:"auto",borderRadius:12,transition:"background 0.15s, box-shadow 0.15s",..."inProgress"===e&&m?k?{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,n.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:16,paddingBottom:4},children:o.map(t=>"todo"===e?(0,n.jsx)("div",{draggable:!0,onDragStart:e=>{var o,n;e.dataTransfer.effectAllowed="move",o=e.clientX,n=e.clientY,R.current=!0,z.current=!1,b.current={x:o,y:n},f({task:t,width:y.current?.width??280})},onDrag:e=>{var t,o;let n,r;return b.current={x:t=e.clientX,y:o=e.clientY},ev(t,o),void((r=null!=(n=j.current?.getBoundingClientRect())&&t>=n.left&&t<=n.right&&o>=n.top&&o<=n.bottom)!==k&&v(r))},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,n.jsx)("div",{children:s(t)},t.id))})})]},e)})})}):(0,n.jsxs)("div",{style:{flex:1,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:12,padding:32,textAlign:"center"},children:[(0,n.jsx)(aJ.x,{size:40,color:"var(--text-dim)",opacity:.4,"aria-hidden":"true"}),(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,n.jsx)("p",{style:{fontSize:14,fontWeight:500,color:"var(--text)"},children:t("tasks.empty")}),(0,n.jsx)("p",{style:{maxWidth:320,fontSize:12,color:"var(--text-muted)",lineHeight:1.6},children:t("tasks.emptyHint")})]}),(0,n.jsxs)("button",{type:"button",onClick:ek,style:{display:"inline-flex",alignItems:"center",gap:6,padding:"7px 14px",borderRadius:8,background:"var(--accent)",color:"#fff",border:"none",fontSize:12,fontWeight:600,cursor:"pointer"},children:[(0,n.jsx)(x.F,{size:13,weight:"bold","aria-hidden":"true"}),t("tasks.new")]})]}),(0,n.jsx)(d_,{open:P,onOpenChange:E,task:D,defaultProject:A?.projectRoot??l??e??null,projects:ez,prefillTitle:A?A.text.slice(0,80):void 0,prefillPrompt:A?A.text:void 0,onSubmit:async(e,t,n)=>{await em(async()=>{let{createTaskApi:r}=await Promise.resolve().then(o.bind(o,23084)),{updateTaskApi:s}=await Promise.resolve().then(o.bind(o,23084));D?await s(D.id,e,{title:t,config:n}):await r({projectRoot:e,title:t,config:n})}),E(!1),N(null)}}),(0,n.jsx)(dB,{open:null!=$,onOpenChange:e=>{e||L(null)},task:eh,onViewSession:ef,onMerge:ex,onEdit:e=>{W(e),E(!0)},onCancel:e=>{q(e),K(!0)},onRetry:e=>{J(e),X("retry"),Q(!0)},onRequeue:e=>{J(e),X("requeue"),Q(!0)},onComplete:e=>{et(e),en(!0)}}),(0,n.jsx)(dq,{open:B,onOpenChange:U,task:O}),(0,n.jsx)(d$,{open:V,onOpenChange:K,task:_}),(0,n.jsx)(dV,{open:Z,onOpenChange:Q,task:G,kind:Y}),(0,n.jsx)(dL,{open:eo,onOpenChange:en,task:ee}),(0,n.jsx)(dJ,{open:el&&null!=eg,onOpenChange:ed,task:eg}),(0,n.jsx)(dG,{open:er,onOpenChange:es,projectRoot:l}),m?(0,d.createPortal)((0,n.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,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:8,borderRadius:12,border:k?"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,n.jsxs)("div",{style:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:8},children:[(0,n.jsx)("span",{style:{minWidth:0,overflowWrap:"break-word",fontSize:13,fontWeight:500},children:m.task.title}),(0,n.jsx)(dW,{task:m.task})]}),k?(0,n.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:4,fontSize:11,fontWeight:600,color:"var(--accent)"},children:[(0,n.jsx)(dT.j,{size:11,weight:"bold","aria-hidden":"true"}),t("tasks.dropToStart")]}):null]})}),document.body):null]})}var d2=o(62235);function d4(){return!!window.__TAURI_INTERNALS__}async function d6(){let{getCurrentWindow:e}=await o.e(8518).then(o.bind(o,38518));await e().minimize()}async function d8(){let{getCurrentWindow:e}=await o.e(8518).then(o.bind(o,38518));await e().toggleMaximize()}async function d5(){let{getCurrentWindow:e}=await o.e(8518).then(o.bind(o,38518));await e().startDragging()}async function d3(){let{getCurrentWindow:e}=await o.e(8518).then(o.bind(o,38518));await e().close()}async function d7(){let{getCurrentWindow:e}=await o.e(8518).then(o.bind(o,38518));return e().isMaximized()}function d9(){let[e,t]=(0,r.useState)(null);return(0,r.useEffect)(()=>{d4()&&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 ce="pi-web-island-pos";function ct(e,t,o,n,r,s){return{x:Math.min(Math.max(0,e),Math.max(0,o-r)),y:Math.min(Math.max(0,t),Math.max(0,n-s))}}let co={display:"flex",alignItems:"center",justifyContent:"center",width:32,height:32,padding:0,flexShrink:0,background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",borderRadius:8,transition:"background 0.12s, color 0.12s"};function cn(){let{t:e}=(0,F.s)(),{isDark:t}=ov(),{isDesktop:o,isMacOS:s}=d9(),i=o&&!s,[a,l]=(0,r.useState)(!1),[d,c]=(0,r.useState)(null),[p,u]=(0,r.useState)(null),h=(0,r.useRef)(null),g=(0,r.useRef)(null),m=(0,r.useCallback)(e=>{e().catch(e=>{console.error("[DynamicIsland] window command failed:",e),c(String(e)),window.setTimeout(()=>c(null),4e3)})},[]),f=(0,r.useCallback)(()=>{window.location.reload()},[]);(0,r.useEffect)(()=>{if(!d4()||!i)return;let e=()=>{d7().then(l)};return e(),window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[i]),(0,r.useEffect)(()=>{if(i)try{let e=localStorage.getItem(ce);if(e){let t=JSON.parse(e);"number"==typeof t.x&&"number"==typeof t.y&&u(ct(t.x,t.y,window.innerWidth,window.innerHeight,152,42))}}catch{}},[i]),(0,r.useEffect)(()=>{if(i&&p)try{localStorage.setItem(ce,JSON.stringify(p))}catch{}},[p,i]);let[x,k]=(0,r.useState)(0);(0,r.useEffect)(()=>{if(!i)return;let e=()=>{k(window.innerWidth),u(e=>e?ct(e.x,e.y,window.innerWidth,window.innerHeight,152,42):e)};return e(),window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[i]);let v=(0,r.useCallback)(e=>{if(0!==e.button||e.target.closest?.("[data-island-btn]"))return;let t=h.current;if(!t)return;let o=t.getBoundingClientRect();g.current={startX:e.clientX,startY:e.clientY,origX:o.left,origY:o.top},e.currentTarget.setPointerCapture(e.pointerId)},[]),y=(0,r.useCallback)(e=>{let t=g.current;if(!t)return;let o=e.clientX-t.startX,n=e.clientY-t.startY;u(ct(t.origX+o,t.origY+n,window.innerWidth,window.innerHeight,152,42))},[]),b=(0,r.useCallback)(e=>{g.current=null;try{e.currentTarget.releasePointerCapture(e.pointerId)}catch{}},[]),w=(0,r.useCallback)(()=>(l(e=>!e),d8()),[]),S=(0,r.useCallback)(e=>{if(!g.current&&!e.target.closest?.("[data-island-btn]")){u(null);try{localStorage.removeItem(ce)}catch{}}},[]);if(!i)return null;let C=x||window.innerWidth,T=null!==p?p.x:Math.max(0,C-152-14);return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("div",{ref:h,role:"toolbar","aria-label":e("desktop.islandLabel"),title:e("desktop.islandResetHint"),onPointerDown:v,onPointerMove:y,onPointerUp:b,onPointerCancel:b,onDoubleClick:S,onMouseDown:e=>e.stopPropagation(),onDoubleClickCapture:e=>e.stopPropagation(),style:{position:"fixed",top:null!==p?p.y:100,left:T,zIndex:700,display:"flex",alignItems:"center",gap:2,padding:"4px 6px",borderRadius:999,background:"color-mix(in srgb, var(--bg-panel) 88%, transparent)",border:"1px solid var(--border)",boxShadow:t?"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,n.jsx)("button",{type:"button","data-island-btn":!0,"aria-label":e("desktop.refreshSession"),title:e("desktop.refreshSession"),onClick:f,style:co,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,n.jsx)(j.S,{size:14,"aria-hidden":"true"})}),(0,n.jsx)("span",{"aria-hidden":"true",style:{width:1,height:18,flexShrink:0,background:"var(--border)",margin:"0 3px"}}),(0,n.jsx)("button",{type:"button","data-island-btn":!0,"aria-label":e("desktop.minimize"),title:e("desktop.minimize"),onClick:()=>m(d6),style:co,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,n.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1",children:(0,n.jsx)("line",{x1:"0",y1:"5",x2:"10",y2:"5"})})}),(0,n.jsx)("button",{type:"button","data-island-btn":!0,"aria-label":e(a?"desktop.restore":"desktop.maximize"),title:e(a?"desktop.restore":"desktop.maximize"),onClick:()=>m(w),style:co,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:a?(0,n.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1",children:[(0,n.jsx)("rect",{x:"2",y:"0.5",width:"7.5",height:"7.5"}),(0,n.jsx)("path",{d:"M0.5 2.5 V9.5 H7.5"})]}):(0,n.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1",children:(0,n.jsx)("rect",{x:"0.5",y:"0.5",width:"9",height:"9"})})}),(0,n.jsx)("button",{type:"button","data-island-btn":!0,"aria-label":e("desktop.close"),title:e("desktop.close"),onClick:()=>m(d3),style:co,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,n.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1",children:[(0,n.jsx)("line",{x1:"0",y1:"0",x2:"10",y2:"10"}),(0,n.jsx)("line",{x1:"10",y1:"0",x2:"0",y2:"10"})]})})]}),d&&(0,n.jsx)("div",{role:"alert",style:{position:"fixed",top:(null!==p?p.y:100)+42+6,left:T,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:t?"0 6px 24px rgba(0,0,0,0.45)":"0 6px 20px rgba(0,0,0,0.12)",pointerEvents:"none"},children:d})]})}function cr({isDark:e,toggleTheme:t,translate:o}){let[s,i]=(0,r.useState)(!1);(0,r.useEffect)(()=>{i(!0)},[]);let a=o(s?e?"desktop.switchToLight":"desktop.switchToDark":"desktop.switchToLight");return(0,n.jsx)("button",{className:"app-no-drag",suppressHydrationWarning:!0,onClick:e=>{let o=e.currentTarget.getBoundingClientRect();t({x:o.left+o.width/2,y:o.top+o.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,n.jsx)(aL.b,{size:16,"aria-hidden":"true"}):(0,n.jsx)(a$.A,{size:16,"aria-hidden":"true"}):(0,n.jsx)(aL.b,{size:16,"aria-hidden":"true"})})}function cs({topBarRef:e,sidebarOpen:t,onSidebarToggle:o,isDark:s,toggleTheme:i,isMobile:a,showTasks:l,tasksBoardEnabled:d,onToggleTasks:c,systemPrompt:p,activeTopPanel:u,topPanelPos:g,sessionStats:m,selectedSession:f,contextUsage:x,copiedSessionField:k,onCopySessionField:v,rightPanelOpen:b,onToggleFilePanel:w,onRefreshSession:S,onOpenSettings:C,sessionTitle:T,onWorkspaceControlsHostChange:R,onTitleRightHostChange:z,desktopChrome:I,windowDrag:M}){let P,E,D,W,A,N,$,L,O,H,B,{t:U}=(0,F.s)(),[_,q]=(0,r.useState)(!1),[V,K]=(0,r.useState)(!1);return(0,r.useEffect)(()=>{try{K(new URLSearchParams(window.location.search).has("piweb_connected"))}catch{K(!1)}},[]),(0,n.jsxs)(n.Fragment,{children:[(0,n.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,n.jsxs)("div",{style:{display:"flex",alignItems:"center",minWidth:0,height:"100%",flex:"0 1 auto"},children:[(0,n.jsx)("button",{className:"app-no-drag",onClick:o,title:t?U("desktop.hideSidebar"):U("desktop.showSidebar"),"aria-label":t?U("desktop.hideSidebar"):U("desktop.showSidebar"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:36,height:36,padding:0,flexShrink:0,background:t?"var(--bg-selected)":"none",border:"none",color:t?"var(--text)":"var(--text-muted)",cursor:"pointer",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=t?"var(--bg-selected)":"none",e.currentTarget.style.color=t?"var(--text)":"var(--text-muted)"},children:t?(0,n.jsx)(d2.V,{size:16,"aria-hidden":"true"}):(0,n.jsx)(y.B,{size:16,"aria-hidden":"true"})}),(0,n.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,n.jsxs)("div",{className:"app-title-drag",style:{flex:1,minWidth:0,display:"flex",alignItems:"center",justifyContent:"center",height:"100%",padding:"0 12px",overflow:"hidden",userSelect:"none"},children:[T&&(0,n.jsx)("button",{type:"button",onClick:()=>{a&&q(!0)},title:a?T:void 0,style:{display:"block",flex:"0 1 auto",minWidth:0,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,n.jsx)("div",{className:"app-no-drag",ref:z,style:{flexShrink:0,display:"flex",alignItems:"center",marginLeft:4}})]}),(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"flex-end",gap:3,minWidth:0,height:"100%",flexShrink:1,overflow:"hidden"},children:[!a&&d&&(0,n.jsx)("button",{className:"app-no-drag",onClick:c,title:l?U("desktop.hideTaskBoard"):U("desktop.showTaskBoard"),"aria-label":l?U("desktop.hideTaskBoard"):U("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,n.jsx)(aJ.x,{size:16,"aria-hidden":"true"})}),(0,n.jsx)("button",{className:"app-no-drag",onClick:w,title:b?U("desktop.hideFilePanel"):U("desktop.showFilePanel"),"aria-label":b?U("desktop.hideFilePanel"):U("desktop.showFilePanel"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:36,height:36,padding:0,background:b?"var(--bg-selected)":"none",border:"none",color:b?"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=b?"var(--bg-selected)":"none",e.currentTarget.style.color=b?"var(--text)":"var(--text-muted)"},children:(0,n.jsx)(d2.V,{size:16,"aria-hidden":"true",style:{transform:"scaleX(-1)"}})}),(0,n.jsx)(cr,{isDark:s,toggleTheme:i,translate:U}),V&&(0,n.jsx)("button",{className:"app-no-drag",type:"button",onClick:()=>{window.location.href="piweb-switch://manage"},title:U("desktop.serverSwitch"),"aria-label":U("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,n.jsx)(ax.X,{size:16,"aria-hidden":"true"})}),!V&&(0,n.jsx)("button",{className:"app-no-drag",type:"button",onClick:S,title:U("desktop.refreshSession"),"aria-label":U("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,n.jsx)(j.S,{size:16,"aria-hidden":"true"})}),(0,n.jsx)("button",{className:"app-no-drag",type:"button",onClick:C,title:U("desktop.settings"),"aria-label":U("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,n.jsx)(dS.O,{size:16,"aria-hidden":"true"})})]})]}),(0,n.jsx)(cn,{}),u&&g&&(0,n.jsxs)("div",{style:{position:"fixed",top:g.top,left:g.left,width:g.width,maxHeight:`calc(100dvh - ${g.top}px)`,overflowY:"auto",zIndex:500},children:["system"===u&&(0,n.jsx)("div",{style:{background:"var(--bg-panel)",borderBottom:"1px solid var(--border)"},children:p?(0,n.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,n.jsx)("div",{style:{padding:"10px 16px",fontSize:12,color:"var(--text-muted)",fontStyle:"italic"},children:"System prompt is empty (tools are disabled)"}):(0,n.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,n.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:m?(P=[...m.sessionName?[{label:U("desktop.name"),value:m.sessionName,copyField:null}]:[],{label:U("desktop.sessionInfoFile"),value:m.sessionFile??U("desktop.sessionInfoInMemory"),copyField:"file"},{label:U("desktop.sessionInfoId"),value:m.sessionId,copyField:"id"}],E=[[U("desktop.sessionInfoUser"),m.userMessages.toLocaleString()],[U("desktop.sessionInfoAssistant"),m.assistantMessages.toLocaleString()],[U("desktop.sessionInfoToolCalls"),m.toolCalls.toLocaleString()],[U("desktop.sessionInfoToolResults"),m.toolResults.toLocaleString()],[U("desktop.sessionInfoTotal"),m.totalMessages.toLocaleString()]],D=[[U("desktop.sessionInfoInput"),m.tokens.input.toLocaleString()],[U("desktop.sessionInfoOutput"),m.tokens.output.toLocaleString()],...m.tokens.cacheRead>0?[[U("desktop.sessionInfoCacheRead"),m.tokens.cacheRead.toLocaleString()]]:[],...m.tokens.cacheWrite>0?[[U("desktop.sessionInfoCacheWrite"),m.tokens.cacheWrite.toLocaleString()]]:[],[U("desktop.sessionInfoTotal"),m.tokens.total.toLocaleString()]],W=x??m.contextUsage,N=[...m.cost>0?[[U("desktop.sessionInfoCost"),`$${m.cost.toFixed(4)}`]]:[],...W?.contextWindow?[[U("desktop.sessionInfoContext"),`${null!==W.percent?`${W.percent.toFixed(1)}%`:"?"} / ${(A=W.contextWindow)>=1e6?`${(A/1e6).toFixed(1)}M`:A>=1e3?`${(A/1e3).toFixed(0)}k`:String(A)}`]]:[]],$=(e,t,o="left",r=!1)=>(0,n.jsxs)("div",{style:{minWidth:0},children:[(0,n.jsx)("div",{style:{fontSize:11,fontWeight:700,color:"var(--text)",marginBottom:6},children:e}),(0,n.jsx)("div",{style:{display:"grid",gridTemplateColumns:r?"max-content max-content":"auto minmax(0, 1fr)",columnGap:r?14:12,rowGap:4,justifyContent:r?"start":void 0},children:t.map(([t,s])=>(0,n.jsxs)("div",{style:{display:"contents"},children:[(0,n.jsx)("div",{style:{color:"var(--text-dim)",whiteSpace:"nowrap"},children:t}),(0,n.jsx)("div",{style:{color:"var(--text-muted)",minWidth:0,overflowWrap:r?"normal":"anywhere",textAlign:o,whiteSpace:"right"===o?"nowrap":"normal"},children:s})]},`${e}:${t}`))})]}),L=(e,t)=>{let o=k===e;return(0,n.jsx)("button",{type:"button",title:o?U("desktop.copied"):U({file:"desktop.copyFilePath",id:"desktop.copySessionId",projectDir:"desktop.copyProjectDir",gitBranch:"desktop.copyGitBranch",gitWorktree:"desktop.copyGitWorktree"}[e]),onClick:()=>v(e,t),style:{alignSelf:"start",display:"inline-flex",alignItems:"center",justifyContent:"center",width:22,height:22,marginTop:-2,color:o?"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=o?"var(--accent)":"var(--text-dim)",e.currentTarget.style.borderColor="var(--border)",e.currentTarget.style.background="transparent"},children:o?(0,n.jsx)(h.J,{size:12,"aria-hidden":"true"}):(0,n.jsx)(tj.Q,{size:12,"aria-hidden":"true"})})},O=(0,n.jsxs)("div",{style:{minWidth:0},children:[(0,n.jsx)("div",{style:{fontSize:11,fontWeight:700,color:"var(--text)",marginBottom:6},children:U("desktop.sessionInfoTitle")}),(0,n.jsx)("div",{style:{display:"grid",gridTemplateColumns:"auto minmax(0, 1fr) auto",columnGap:12,rowGap:8,alignItems:"start"},children:P.map(e=>(0,n.jsxs)("div",{style:{display:"contents"},children:[(0,n.jsx)("div",{style:{color:"var(--text-dim)",whiteSpace:"nowrap"},children:e.label}),(0,n.jsx)("div",{style:{color:"var(--text-muted)",minWidth:0,overflowWrap:"anywhere",wordBreak:"break-word",whiteSpace:"normal"},children:e.value}),(0,n.jsx)("div",{children:e.copyField?L(e.copyField,e.value):null})]},`session-info:${e.label}`))})]}),B=(H=[...f?[{label:U("desktop.projectDir"),value:f.projectRoot??f.cwd,copyField:"projectDir"}]:[],...f?.branch?[{label:U("desktop.gitBranch"),value:f.branch,copyField:"gitBranch"}]:[],...f?.isWorktree?[{label:U("desktop.gitWorktree"),value:f.cwd,copyField:"gitWorktree"}]:[]]).length>0?(0,n.jsxs)("div",{style:{minWidth:0},children:[(0,n.jsx)("div",{style:{fontSize:11,fontWeight:700,color:"var(--text)",marginBottom:6},children:U("desktop.projectSection")}),(0,n.jsx)("div",{style:{display:"grid",gridTemplateColumns:"auto minmax(0, 1fr) auto",columnGap:12,rowGap:8,alignItems:"start"},children:H.map(e=>(0,n.jsxs)("div",{style:{display:"contents"},children:[(0,n.jsx)("div",{style:{color:"var(--text-dim)",whiteSpace:"nowrap"},children:e.label}),(0,n.jsx)("div",{style:{color:"var(--text-muted)",minWidth:0,overflowWrap:"anywhere",wordBreak:"break-word",whiteSpace:"normal"},children:e.value}),(0,n.jsx)("div",{children:e.copyField?L(e.copyField,e.value):null})]},`project-info:${e.label}`))})]}):null,(0,n.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,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:a?16:20,minWidth:0},children:[O,B]}),$(U("desktop.sessionInfoMessages"),E),$(U("desktop.sessionInfoTokens"),[...D,...N],"right",!0)]})):(0,n.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)",fontStyle:"italic"},children:U("desktop.sendMessageForSessionInfo")})})]}),_&&T&&(0,n.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)"},onMouseDown:e=>{e.target===e.currentTarget&&q(!1)},children:(0,n.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 ci({cwd:e,busy:t,error:o,onCancelAction:r,onConfirmAction:s}){let{t:i}=(0,F.s)();return(0,n.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)"},onClick:e=>{t||e.target!==e.currentTarget||r()},children:(0,n.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,n.jsxs)("div",{style:{display:"flex",gap:12,padding:"18px 18px 14px"},children:[(0,n.jsx)(nJ.o,{size:21,weight:"duotone",color:"var(--accent-orange)",style:{flexShrink:0,marginTop:1},"aria-hidden":"true"}),(0,n.jsxs)("div",{style:{minWidth:0},children:[(0,n.jsx)("h2",{id:"project-trust-title",style:{margin:0,fontSize:15,fontWeight:700,color:"var(--text)"},children:i("desktop.trustProjectTitle")}),(0,n.jsx)("p",{style:{margin:"7px 0 0",fontSize:12,lineHeight:1.6,color:"var(--text-muted)"},children:i("desktop.trustProjectBody")}),(0,n.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}),o&&(0,n.jsx)("div",{role:"alert",style:{marginTop:10,color:"var(--accent-red)",fontSize:12,lineHeight:1.5},children:o})]})]}),(0,n.jsxs)("footer",{style:{display:"flex",justifyContent:"flex-end",gap:8,padding:"10px 18px",borderTop:"1px solid var(--border)"},children:[(0,n.jsx)("button",{type:"button",onClick:r,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,n.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 ca(e,t,o){let n=Number.isFinite(e)?e:t,r=Math.max(t,o);return Math.round(Math.max(t,Math.min(r,n)))}function cl(e){return ca(.42*e,360,640)}function cd(e,t){try{window.localStorage.setItem(e,String(t))}catch{}}function cc(e){let{ariaLabel:t,cssVariable:o,defaultWidth:n,getDefaultWidth:s,getMaxWidth:i,growthDirection:a,maxWidth:l,minWidth:d,storageKey:c,widthRef:p}=e,u=(0,r.useRef)(null),h=(0,r.useRef)(null),g=(0,r.useRef)(!1),[m,f]=(0,r.useState)(n),[x,k]=(0,r.useState)(!1),[v,y]=(0,r.useState)(!1);(0,r.useEffect)(()=>{y(!0)},[]);let b=(0,r.useCallback)(()=>Math.min(l,Math.max(d,i())),[i,l,d]),w=(0,r.useCallback)(e=>ca(e,d,b()),[b,d]),j=(0,r.useCallback)(e=>{p.current=e;let t=`${e}px`;u.current?.style.setProperty(o,t),u.current?.parentElement?.style.setProperty(o,t)},[o,p]),S=(0,r.useCallback)((e,t={})=>{let{forcePersist:o=!1,persist:n=!0}=t,r=w(e),s=r!==p.current;return j(r),f(r),n&&(s||o)&&cd(c,r),r},[j,w,c,p]),C=(0,r.useCallback)(e=>{document.body.style.cursor=e.previousCursor,document.body.style.userSelect=e.previousUserSelect},[]),T=(0,r.useCallback)(e=>{let t=h.current;if(t&&t.pointerId===e){h.current=null,C(t),k(!1),S(p.current,{forcePersist:!0});try{t.target.hasPointerCapture(e)&&t.target.releasePointerCapture(e)}catch{}}},[S,C,p]),R=(0,r.useCallback)(e=>{if("mouse"===e.pointerType&&0!==e.button)return;e.preventDefault(),e.stopPropagation();let t=h.current;t&&T(t.pointerId);let o=e.currentTarget;o.focus({preventScroll:!0}),o.setPointerCapture(e.pointerId),h.current={pointerId:e.pointerId,startX:e.clientX,startWidth:p.current,target:o,previousCursor:document.body.style.cursor,previousUserSelect:document.body.style.userSelect},document.body.style.cursor="col-resize",document.body.style.userSelect="none",k(!0)},[T,p]),z=(0,r.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 o="right"===a?1:-1,n=w(t.startWidth+(e.clientX-t.startX)*o);j(n),e.currentTarget.setAttribute("aria-valuenow",String(n)),e.currentTarget.setAttribute("aria-valuetext",`${n} px`)},[j,w,T,a]),I=(0,r.useCallback)(e=>{T(e.pointerId)},[T]),M=(0,r.useCallback)(e=>{T(e.pointerId)},[T]),P=(0,r.useCallback)(e=>{T(e.pointerId)},[T]),E=(0,r.useCallback)(()=>{S(s?.()??n,{forcePersist:!0})},[S,n,s]),F=(0,r.useCallback)(()=>{S(p.current)},[S,p]),D=(0,r.useCallback)(e=>{let t=e.shiftKey?32:12,o="right"===a?"ArrowRight":"ArrowLeft",n="right"===a?"ArrowLeft":"ArrowRight";e.key===o?(e.preventDefault(),S(p.current+t,{forcePersist:!0})):e.key===n?(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,r.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 o=Number.parseInt(t,10);return Number.isFinite(o)?o:null}catch{return null}}(c),t=S(e??s?.()??n,{persist:!1});null!==e&&e!==t&&cd(c,t)},[S,n,s,c]),(0,r.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,r.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,r.useEffect)(()=>()=>{let e=h.current;e&&(h.current=null,C(e))},[C]),{isResizing:x,panelRef:u,reclampWidth:F,separatorProps:{"aria-label":t,"aria-orientation":"vertical","aria-valuemax":v?b():l,"aria-valuemin":d,"aria-valuenow":m,"aria-valuetext":`${m} px`,onDoubleClick:E,onKeyDown:D,onLostPointerCapture:P,onPointerCancel:M,onPointerDown:R,onPointerMove:z,onPointerUp:I,role:"separator",tabIndex:0},width:m}}function cp(){let e,t,o,d=(0,a.useRouter)(),c=(0,a.useSearchParams)(),p=(0,r.useMemo)(()=>{let e;return{requestedCwd:e=c.get("cwd")?.trim()||null,sessionId:e?null:c.get("session")}},[c]),{isDark:u,toggleTheme:h}=ov(),{t:g}=(0,F.s)(),m=$(),[f,x]=(0,r.useState)(null),[k,v]=(0,r.useState)(null),[y,b]=(0,r.useState)(0),[w,j]=(0,r.useState)(0),[S,C]=(0,r.useState)(0),[T,R]=(0,r.useState)(!1),[z,I]=(0,r.useState)("models"),[M,P]=(0,r.useState)(0),[E,D]=(0,r.useState)(null),[W,A]=(0,r.useState)(!1),[N,L]=(0,r.useState)(!1),[O,H]=(0,r.useState)(null),[B,U]=(0,r.useState)(!0),[_,q]=(0,r.useState)(!1);(0,r.useEffect)(()=>{m&&U(!1)},[m]),(0,r.useEffect)(()=>{q(!0)},[]);let V=(0,r.useRef)(null),K=(0,r.useRef)(null),[G,J]=(0,r.useState)(null),[Y,X]=(0,r.useState)(null),[Z,Q]=(0,r.useState)(null),ee=d9(),et=function(){let{isDesktop:e,isMacOS:t}=d9(),o=(0,r.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?d8():d5())},[]);return e&&!t?{onMouseDown:o}:{}}(),[eo,en]=(0,r.useState)(null),er=(0,r.useCallback)(e=>{en(e)},[]),[es,ei]=(0,r.useState)(null),el=(0,r.useCallback)(e=>{ei(e)},[]),[ed,ec]=(0,r.useState)([]),ep=(0,r.useCallback)(e=>{ec(e)},[]),eu=ed.filter(e=>"running"===e.status).length,[eh,eg]=(0,r.useState)(null),em=(0,r.useRef)(null),ef=(0,r.useCallback)((e,t)=>{oy(t).then(()=>{em.current&&clearTimeout(em.current),eg(e),em.current=setTimeout(()=>eg(null),1400)})},[]);(0,r.useEffect)(()=>()=>{em.current&&clearTimeout(em.current)},[]);let[ex,ek]=(0,r.useState)(null),ev=(0,r.useCallback)(e=>{ek(e)},[]),[ey,eb]=(0,r.useState)(null),[ew,ej]=(0,r.useState)(null),eS=(0,r.useCallback)(()=>{m&&U(!1),eb("session")},[m]),eC=(0,r.useCallback)(()=>{m&&eb(null),U(e=>!e)},[m]);(0,r.useEffect)(()=>{if(!ey||!K.current)return;let e=()=>{let e=K.current.getBoundingClientRect();ej({top:e.bottom,left:e.left,width:e.width})};e();let t=new ResizeObserver(e);return t.observe(K.current),()=>t.disconnect()},[ey]);let[eT,eR]=(0,r.useState)([]),[ez,eI]=(0,r.useState)(null),[eM,eP]=(0,r.useState)(!1),[eE,eD]=(0,r.useState)(!1),[eW,eA]=(0,r.useState)(null),eN=(0,r.useCallback)(e=>{eA(e??null),eD(!0),eP(!0),m&&U(!1)},[m]),e$=(0,r.useCallback)(()=>{eD(!1),eA(null)},[]),[eL,eO]=(0,r.useState)(null),eH=(0,r.useCallback)(e=>eO(e),[]),eB=(0,r.useCallback)(()=>eO(null),[]);(0,r.useEffect)(()=>{if(!eL)return;let e=e=>{"Escape"===e.key&&(e.stopImmediatePropagation(),e.preventDefault(),eO(null))};return window.addEventListener("keydown",e,!0),()=>window.removeEventListener("keydown",e,!0)},[eL]);let eU=(0,r.useRef)(260),e_=(0,r.useRef)(cl(1366)),eV=(0,r.useCallback)(()=>cl(window.innerWidth),[]),eK=(0,r.useCallback)(()=>(function(e){let{viewportWidth:t,rightPanelOpen:o,rightPanelWidth:n}=e;if(t<=640)return 480;let r=t<960;return Math.min(480,t-(r?320:420)-(!r&&o?n:0))})({viewportWidth:window.innerWidth,rightPanelOpen:eM,rightPanelWidth:e_.current}),[eM]),eG=(0,r.useCallback)(()=>(function(e){let{viewportWidth:t,sidebarOpen:o,sidebarWidth:n}=e;return t<960?1200:Math.min(1200,t-420-(o?n:0))})({viewportWidth:window.innerWidth,sidebarOpen:B,sidebarWidth:eU.current}),[B]),eJ=cc({ariaLabel:g("desktop.resizeSidebar"),cssVariable:"--sidebar-width",defaultWidth:260,getMaxWidth:eK,growthDirection:"right",maxWidth:480,minWidth:180,storageKey:"pi-sidebar-width",widthRef:eU}),eY=cc({ariaLabel:g("desktop.resizeFilePanel"),cssVariable:"--right-panel-width",defaultWidth:cl(1366),getDefaultWidth:eV,getMaxWidth:eG,growthDirection:"left",maxWidth:1200,minWidth:300,storageKey:"pi-right-panel-width",widthRef:e_}),eX=eJ.reclampWidth,eZ=eY.reclampWidth;(0,r.useEffect)(()=>{eM&&(eX(),eZ())},[eZ,eX,eM]);let eQ=(0,r.useCallback)((e,t)=>{V.current?.insertText(r_(e,t))},[]),e0=(0,r.useCallback)(e=>{let t=e.map(e=>r_(e,!1)).join("");t&&V.current?.insertText(t)},[]),e1=(0,r.useCallback)((e,t,o)=>{let n,r,s,i;V.current?.insertText((n=Math.max(1,Math.min(t,o)),r=Math.max(1,Math.max(t,o)),s=e.includes(" ")?`@"${e}"`:`@${e}`,i=n===r?`:${n}`:`:${n}-${r}`,`${s}${i} `))},[]),[e2,e6]=(0,r.useState)(()=>p.sessionId),[e8,e5]=(0,r.useState)(null),[e3,e7]=(0,r.useState)(()=>p.requestedCwd?"validating":"idle"),[e9,te]=(0,r.useState)(null),[tt,to]=(0,r.useState)(()=>!e2),tn=(0,r.useRef)(!1),tr=(0,r.useRef)(new Map),[ts,ti]=(0,r.useState)(null),ta=(0,r.useRef)("");(0,r.useEffect)(()=>{let e=`${p.requestedCwd??""}|${p.sessionId??""}`;ta.current!==e&&(ta.current=e,e6(p.sessionId),to(!p.sessionId),p.requestedCwd||e7("idle"),te(null))},[p]),(0,r.useEffect)(()=>{let e=p.requestedCwd;if(!e)return;let t=new AbortController;return e7("validating"),te(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}`);tn.current=!0,v(t.cwd),e7("ready")}).catch(e=>{t.signal.aborted||(te(e instanceof Error?e.message:String(e)),e7("error"))}),()=>t.abort()},[p]);let tl=(0,r.useCallback)((e,t)=>{if(!e)return;if(e5(e),tn.current&&f&&eF(f.projectRoot??f.cwd,t??e)){if(tn.current=!1,f){let e=f.projectRoot??f.cwd;e&&tr.current.set(e,f.id)}return}tn.current=!1;let o=t??e;if(f&&eF(f.projectRoot??f.cwd,o)){(f.projectRoot??f.cwd)&&tr.current.set(o,f.id);return}if(f){let e=f.projectRoot??f.cwd;e&&tr.current.set(e,f.id)}x(null),v(t=>t&&t!==e?null:t),j(e=>e+1),en(null),eb(null),window.history.replaceState(null,"","/");let n=tr.current.get(o);ti(n?{projectRoot:o,sessionId:n}:null)},[f]);(0,r.useEffect)(()=>{let e=e8?ea(e8)||e8:null;document.title=e?`${e} — Pi Agent Web`:"Pi Agent Web"},[e8]);let td=(0,r.useCallback)((e,t=!1)=>{if(t||ti(null),!t&&f){let t=eF(f.projectRoot??f.cwd,e.projectRoot??e.cwd);if(f.id===e.id&&t){m&&U(!1);return}}let o=e.projectRoot??e.cwd;o&&tr.current.set(o,e.id),v(null),x(e),j(e=>e+1),en(null),to(!0),m&&!t&&U(!1),t&&(tn.current=!0),t||window.history.replaceState(null,"",`?session=${encodeURIComponent(e.id)}`)},[m,f]),tc=(0,r.useRef)(()=>{});(0,r.useEffect)(()=>{tc.current=td},[td]);let tp=(0,r.useCallback)(e=>{fetch("/api/sessions").then(e=>e.ok?e.json():null).then(t=>{let o=t?.sessions.find(t=>t.id===e);o&&x(t=>!t||t.id!==e||t.projectRoot&&t.name?t:o)}).catch(()=>{})},[]);(0,r.useEffect)(()=>{if(!ts)return;let{projectRoot:e,sessionId:t}=ts;tc.current({path:"",id:t,cwd:e,created:"",modified:"",messageCount:0,firstMessage:"",projectRoot:e},!0),tp(t),window.history.replaceState(null,"",`?session=${encodeURIComponent(t)}`),ti(null)},[ts,tp]);let tu=(0,r.useCallback)((e,t)=>{ti(null),x(null),v(t),j(e=>e+1),en(null),eb(null),m&&U(!1),window.history.replaceState(null,"","/")},[d,m]);!function(e){let{onNewSession:t,activeCwd:o}=e;(0,r.useEffect)(()=>{let e=e=>{if("Escape"===e.key){if(!l)return;let t=e.target?.tagName;if("TEXTAREA"===t||"INPUT"===t)return;e.preventDefault(),l();return}if("n"===e.key&&e.ctrlKey&&e.altKey){if(!o||!t)return;e.preventDefault(),t(o)}};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[o,t])}({onNewSession:e=>tu(`kb-${Date.now()}`,e),activeCwd:e8});let th=(0,r.useCallback)(e=>{v(null),ti(null);let t=e.projectRoot??e.cwd;t&&tr.current.set(t,e.id),x(e),e.cwd&&e5(e.cwd),b(e=>e+1),tp(e.id),window.history.replaceState(null,"",`?session=${encodeURIComponent(e.id)}`),window.setTimeout(()=>b(e=>e+1),1200),window.setTimeout(()=>b(e=>e+1),4e3)},[d,tp]),tg=(0,r.useCallback)(()=>{b(e=>e+1),C(e=>e+1)},[]),tm=(0,r.useCallback)(e=>{b(e=>e+1),j(e=>e+1),v(null),ti(null),x(t=>{let o={...t??{path:"",cwd:"",created:"",modified:"",messageCount:0,firstMessage:""},id:e},n=o.projectRoot??o.cwd;return n&&tr.current.set(n,e),o}),tp(e),window.history.replaceState(null,"",`?session=${encodeURIComponent(e)}`)},[d,tp]),tf=(0,r.useCallback)(()=>{to(!0)},[]),tx=(0,r.useCallback)(e=>{if(b(e=>e+1),f?.id===e){let e=f.cwd;x(null),v(e??null),j(e=>e+1),en(null),eb(null),window.history.replaceState(null,"","/")}},[d,f]),tk=(0,r.useCallback)((e,t,o,n)=>{let r="string"==typeof o||null===o?o:void 0,s="object"==typeof o&&null!==o?o:n,i=`file:${e}`;eR(o=>{let n=o.find(e=>e.id===i);return n?r&&n.sourceSessionId!==r||s?.initialDisplayMode&&n.initialDisplayMode!==s.initialDisplayMode?o.map(e=>e.id===i?{...e,sourceSessionId:r??e.sourceSessionId,initialDisplayMode:s?.initialDisplayMode??e.initialDisplayMode}:e):o:[...o,{id:i,label:t,filePath:e,sourceSessionId:r,initialDisplayMode:s?.initialDisplayMode}]}),eI(i),eP(!0),m&&U(!1)},[m]),tv=(0,r.useCallback)(e=>{tk(e,ea(e),f?.id??null)},[tk,f?.id]),ty=(0,r.useCallback)(e=>{eR(t=>{let o=t.filter(t=>t.id!==e);return 0===o.length&&eP(!1),o}),eI(t=>{if(t!==e)return t;let o=eT.filter(t=>t.id!==e);return o.length>0?o[o.length-1].id:null})},[eT]),tb=(0,r.useCallback)(e=>{C(e=>e+1),tk(e,ea(e))},[tk]),tw=(0,r.useCallback)((e,t)=>{C(e=>e+1);let o=e.endsWith("/")?e:e+"/",n=n=>n===e||t&&n.startsWith(o);eR(e=>{let t=e.filter(e=>!n(e.filePath));return 0===t.length&&eP(!1),t}),eI(e=>{if(!e)return e;let t=eT.find(t=>t.id===e);if(!t||!n(t.filePath))return e;let o=eT.filter(e=>!n(e.filePath));return o.length>0?o[o.length-1].id:null})},[eT]),tj=f?eq(f.name||es?.sessionName)||f.firstMessage.slice(0,50)||f.id.slice(0,12):(e=e8??k)?e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e:null,tS=(0,r.useCallback)(()=>{f&&window.open(`/api/sessions/${encodeURIComponent(f.id)}/export?inline=1`,"_blank","noopener,noreferrer")},[f]),tC=k??(null===f&&e8?e8:null),tT="validating"!==e3&&"error"!==e3&&(null!==f||null!==tC),tR=f?.id;(0,r.useEffect)(()=>{eL&&eO(null)},[tR,tT]);let tz=f?.cwd??tC,[tI,tM]=(0,r.useState)(!1),tP=(0,r.useCallback)(()=>{m||tM(e=>!e)},[m]),[tE,tF]=(0,r.useState)(!0);(0,r.useEffect)(()=>{let e=!1,t=()=>fetch("/api/features").then(e=>e.ok?e.json():null).then(t=>{!e&&t&&"boolean"==typeof t.tasksBoard&&(tF(t.tasksBoard),t.tasksBoard||tM(!1))}).catch(()=>{});t();let o=()=>t();return window.addEventListener("pi:features-changed",o),()=>{e=!0,window.removeEventListener("pi:features-changed",o)}},[]);let tD=tt&&!tT;(0,r.useEffect)(()=>{let e=()=>{m||tM(!0)};return window.addEventListener(iU,e),()=>window.removeEventListener(iU,e)},[m]),(0,r.useEffect)(()=>{if(D(null),A(!1),H(null),!tz)return;let e=new AbortController;return fetch(`/api/project-trust?cwd=${encodeURIComponent(tz)}`,{signal:e.signal}).then(async e=>{let t=await e.json();if(!e.ok||t.error)throw Error(t.error??`HTTP ${e.status}`);D(t)}).catch(e=>{e instanceof DOMException&&"AbortError"===e.name||console.error("Failed to load project trust:",e)}),()=>e.abort()},[tz]);let tW=(0,r.useCallback)(async()=>{if(tz&&!N){L(!0),H(null);try{let e=await fetch("/api/project-trust",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:tz})}),t=await e.json();if(!e.ok||t.error)throw Error(t.error??`HTTP ${e.status}`);D(t),A(!1),P(e=>e+1),j(e=>e+1)}catch(e){H(e instanceof Error?e.message:String(e))}finally{L(!1)}}},[N,tz]),tA=eT.find(e=>e.id===ez)??null,tN=e8??f?.cwd??k,t$=(0,r.useCallback)(e=>{I(e),R(!0)},[]),tL=(0,n.jsx)(n.Fragment,{children:(0,n.jsx)(e4,{selectedSessionId:f?.id??null,onSelectSession:td,onNewSession:tu,initialSessionId:e2,onInitialRestoreDone:tf,refreshKey:y,onSessionDeleted:tx,selectedCwd:f?.cwd??k??null,onCwdChange:tl,onOpenFile:tk,selectedSessionStats:es,onOpenSettings:e=>{t$(["models","skills","plugins","chat","features","logs"].includes(e)?e:"models")},explorerRefreshKey:S,onAtMention:eQ,onAtMentions:e0,onFileCreated:tb,onFileDeleted:tw,workspaceControlsHosts:{title:G,welcome:Z,titleRight:Y},showWorkspaceControls:!0})});return(0,n.jsxs)(dw,{children:[(0,n.jsx)("style",{children:`
|
|
38
38
|
@media (max-width: 640px) {
|
|
39
39
|
.sidebar-overlay-backdrop.sidebar-mobile-pending {
|