@qt4798/pi-web 0.9.31 → 0.9.32
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 +19 -19
- package/.next/build-manifest.json +2 -2
- package/.next/prerender-manifest.json +3 -3
- 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/_global-error.segment.rsc +1 -1
- package/.next/server/app/_global-error.segments/_head.segment.rsc +1 -1
- package/.next/server/app/_global-error.segments/_index.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/_head.segment.rsc +1 -1
- package/.next/server/app/_not-found.segments/_index.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/_not-found.segment.rsc +1 -1
- package/.next/server/app/_not-found.segments/_tree.segment.rsc +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/_head.segment.rsc +1 -1
- package/.next/server/app/index.segments/_index.segment.rsc +1 -1
- 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 +19 -19
- 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/server/server-reference-manifest.json +1 -1
- package/.next/static/chunks/app/{page-5325a93105a99f2f.js → page-333fbc81cd67ec98.js} +1 -1
- package/.next/trace +185 -185
- package/.next/trace-build +1 -1
- package/README.md +8 -7
- package/package.json +1 -1
- /package/.next/static/{lHe9-XXtit9Zjl2EH2nbu → rR0F4yolURm-e-v5Xr8l7}/_buildManifest.js +0 -0
- /package/.next/static/{lHe9-XXtit9Zjl2EH2nbu → rR0F4yolURm-e-v5Xr8l7}/_ssgManifest.js +0 -0
|
@@ -33,7 +33,7 @@ ${e}`;(0,n.useEffect)(()=>{if(!a||t)return;let r=!1;return h(null),(async()=>{le
|
|
|
33
33
|
|
|
34
34
|
Goal: ${o}`:eW)}return t.join("\n\n")}({collaborationMode:ex.current,tokenMode:em.current,goalText:"goal"===ex.current?ey.current??void 0:void 0}),d=l||!ei.current||i?"":sP,c=l||d,p=[ex.current,em.current,ei.current?"legacy-plan":"",c?String(c.length):""].join("|"),u=t?.id??"new";c&&(eb.current.sessionKey!==u||eb.current.signature!==p)?(eb.current={sessionKey:u,signature:p},n=`${c}
|
|
35
35
|
|
|
36
|
-
${e}`):n=e;let h=n,f=o?.map(e=>({type:"image",source:{type:"base64",media_type:e.mimeType,data:e.data}})),x={role:"user",content:f?.length?[...e.trim()?[{type:"text",text:e}]:[],...f]:e,timestamp:Date.now()};S(e=>[...e,x]),t3.current=sO(x),t5.current=a,"goal"!==ex.current||i||(ey.current=s,eA(e=>({...e,status:"running",goalText:s,turnsUsed:0,noProgressTurns:0,tokensUsed:0})),eH.current=!0),tB.current=!0,$(!0),e9(i?{kind:"running_command"}:{kind:"waiting_model"}),z({type:"start"}),tY.current=!0,tt(!0),tX.current=!0;let m=o?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),k=null,v=!1;try{if(g&&r){let t=tH.current??await t4.current,o=t??await ox();if(o){k=o,X&&(e1(X),t&&await sT(o,{type:"set_model",provider:X.provider,modelId:X.modelId}));let r=await Promise.race([ob(o).then(()=>!0).catch(()=>!1),s$(4e3).then(()=>!1)]);v=!0,await sT(o,{type:"prompt",message:h,...m?.length?{images:m}:{}}),of(1,e),r||oF(o,a),"goal"!==ex.current||i||sT(o,{type:"goal_start",goalText:s}).catch(()=>{})}}else if(t){k=t.id;let e=await Promise.race([ob(t.id).then(()=>!0).catch(()=>!1),s$(4e3).then(()=>!1)]);v=!0,await sT(t.id,{type:"prompt",message:h,...m?.length?{images:m}:{}}),e||oF(t.id,a),"goal"!==ex.current||i||sT(t.id,{type:"goal_start",goalText:s}).catch(()=>{})}i&&k&&oF(k,a)}catch(e){if(console.error("Failed to send message:",e),v&&k)return void oF(k,a);if(t_.current=!1,ov(),e instanceof sW){let t=t3.current;t&&S(e=>{let o=e[e.length-1];return o?.role==="user"&&sO(o)===t?e.slice(0,-1):e}),oS({type:"error",message:e.message})}else oS({type:"error",message:`Failed to send message: ${e instanceof Error?e.message:String(e)}`});t3.current=null,tB.current=!1,$(!1),e9(null),z({type:"end"})}},[g,r,X,t,ox,ob,of,oF,oS,ok,ov,on]),oA=(0,n.useCallback)(async(o,r)=>{if(tB.current||tV.current)return;let n=`${r?"!!":"!"}${o}`;tV.current=!0,O({command:o,excludeFromContext:r}),L(!0);try{let e=tH.current??t?.id??await ox();if(!e)throw Error("Unable to create a session for the shell command");await sT(e,{type:"bash",command:o,excludeFromContext:r}),await ou(e),of(1,n)}catch(t){console.error("Failed to execute shell command:",t),oS({type:"error",message:t instanceof Error?t.message:String(t)}),e.chatInputRef?.current?.insertIfEmpty(n)}finally{tV.current=!1,O(null),L(!1)}},[oS,ox,ou,e.chatInputRef,of,t]),oO=(0,n.useCallback)(async()=>{let e=tH.current;if(e)try{await sT(e,{type:tV.current?"abort_bash":"abort"})}catch(e){console.error("Failed to abort:",e)}},[]),oH=(0,n.useCallback)(async e=>{let t=tH.current;if(t){eX(e);try{let{cancelled:o,newSessionId:r}=await sT(t,{type:"fork",entryId:e})??{};!o&&r&&a?.(r)}catch(e){console.error("Fork failed:",e)}finally{eX(null)}}},[a]),oB=(0,n.useCallback)(async e=>{let t=tH.current;t&&(sT(t,{type:"navigate_tree",targetId:e}).catch(()=>{}),w(e),await og(t,e))},[og]),oU=(0,n.useCallback)(async e=>{w(e);let t=tH.current;t&&(await og(t,e),e&&sT(t,{type:"navigate_tree",targetId:e}).catch(()=>{}))},[og]),o_=(0,n.useCallback)(async(e,t)=>{if(g){let o={provider:e,modelId:t};ot.current=o,Z(o),e1(o);let r=tH.current??await t4.current;if(!r)return;try{await sT(r,{type:"set_model",provider:e,modelId:t})}catch(e){console.error("Failed to set model:",e)}return}let o=tH.current;if(!o)return;let r=++t8.current,n=eZ??f?.context.model??null;eQ({provider:e,modelId:t});try{await sT(o,{type:"set_model",provider:e,modelId:t})}catch(o){console.error("Failed to set model:",o),t8.current===r&&(eQ(n&&(n.provider!==e||n.modelId!==t)?n:null),oS({type:"error",message:o instanceof Error?o.message:String(o)}))}},[oS,eZ,f?.context.model,g,Z]),oq=(0,n.useCallback)(async()=>{let e=tH.current;if(e&&!e2){e4(!0),e5(null),e8(null);try{let t=await sT(e,{type:"compact"});e8(sH(t,"manual")),await ou(e,!0)}catch(e){e5(e instanceof Error?e.message:String(e)),e8(null)}finally{e4(!1)}}},[e2,ou]),oV=(0,n.useCallback)(async e=>{let o=++t7.current,n=r??t?.cwd??"",s=n?`/api/models?cwd=${encodeURIComponent(n)}`:"/api/models",i=t9.current;i?.abort();let a=new AbortController;t9.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)throw Error(`HTTP ${e.status}`);let t=await e.json();if(o!==t7.current||h!==oe.current)return;B(t.models),V(t.thinkingLevels??{}),J(t.thinkingLevelMaps??{}),Y(t.modelScopeWarnings??[]);let r=t.modelList??[];if(_(r),g&&!tH.current){let e=(t.defaultModel?r.find(e=>e.id===t.defaultModel?.modelId&&e.provider===t.defaultModel?.provider):void 0)??r[0];ee(e?{provider:e.provider,modelId:e.id}:null);let o=e?t.thinkingLevelPins?.[`${e.provider}/${e.id}`]:void 0;null===oo.current&&eU(o??"auto")}}finally{e?.removeEventListener("abort",l),t9.current===a&&(t9.current=null)}},[g,h,r,t?.cwd]),oK=(0,n.useCallback)(async e=>{if(!e.startsWith("/"))return{handled:!1};let t=e.match(/^\/([^\s]+)(?:\s+([\s\S]*))?$/);if(!t)return{handled:!1};let[,o,r=""]=t,n=r.trim(),s=tH.current??await ox(),i=e=>(e.handled&&(e.error?oS({type:"error",message:e.error}):"openSessionStats"!==e.action&&oS({type:"success",message:e.message??"Command completed"})),e);try{switch(o){case"compact":{if(!s||e2)return i({handled:!0,error:"No active session to compact"});e4(!0),e5(null),e8(null);let e=await sT(s,{type:"compact",...n?{customInstructions:n}:{}});return e8(sH(e,"manual")),await ou(s,!0)&&of(),i({handled:!0,message:"Compacted context"})}case"reload":if(!s)return i({handled:!0,error:"No active session to reload"});return await sT(s,{type:"reload"}),await Promise.all([ou(s,!1,!0),oh(s),om(),oV()]),i({handled:!0,message:"Reloaded session resources"});case"name":if(!s)return i({handled:!0,error:"No active session to name"});if(!n)return i({handled:!0,error:"Usage: /name <name>"});return await sT(s,{type:"set_session_name",name:e$(n)}),await ou(s)&&of(),i({handled:!0,message:`Session renamed to ${n}`});case"session":{if(!s)return i({handled:!0,error:"No active session"});let e=await sT(s,{type:"get_session_stats"});return e&&td(e),p?.(),i({handled:!0,action:"openSessionStats"})}case"copy":{if(!s)return i({handled:!0,error:"No active session"});let e=await sT(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&&e4(!1)}},[oS,ox,e2,oV,ou,om,oh,of,p]),oJ=(0,n.useCallback)(async(e,t)=>{let o=tH.current;if(!o)return;let r=t?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType}));try{await sT(o,{type:"steer",message:e,...r?.length?{images:r}:{}})}catch(e){console.error("Failed to steer:",e)}},[]),oG=(0,n.useCallback)(async(e,t,o)=>{let r=tH.current;if(!r)return;let n=o?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType}));try{await sT(r,{type:"prompt",message:e,streamingBehavior:t,...n?.length?{images:n}:{}})}catch(e){console.error("Failed to queue prompt:",e)}},[]),oY=(0,n.useCallback)(async(e,t)=>{let o=tH.current;if(!o)return;let r=t?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType}));try{await sT(o,{type:"follow_up",message:e,...r?.length?{images:r}:{}})}catch(e){console.error("Failed to follow up:",e)}},[]),oX=(0,n.useCallback)(async()=>{let e=tH.current;if(e)try{await sT(e,{type:"abort_compaction"})}catch(e){console.error("Failed to abort compaction:",e)}},[]),oZ=(0,n.useCallback)(async()=>{let t=tH.current;if(t)try{let o=await sT(t,{type:"clear_queue"});tv({steering:[],followUp:[]});let r=[...o?.steering??[],...o?.followUp??[]];r.length>0&&e.chatInputRef?.current?.prependText(r.join("\n\n"))}catch(e){console.error("Failed to recall queued messages:",e),oS({type:"error",message:"Failed to recall queued messages"})}},[e.chatInputRef,oS]);(0,n.useEffect)(()=>{0===ty.length&&tj(!1)},[ty.length]);let oQ=(0,n.useCallback)(async(e,t,o=!1)=>{let r=tH.current;if(!r)return ty;try{let n=await sT(r,{type:"resolve_recovery",keep:e,discard:t,continueRun:o}),s=n?.remaining??[];return tb(s),o&&e.length>0&&(async()=>{try{let e=await fetch(`/api/agent/${encodeURIComponent(r)}`);if(!e.ok)return;let t=await e.json(),o=t.state;if(!t.running||!o||!o.isStreaming&&!o.isPromptRunning)return;tU.current=!!o.isStreaming,t_.current=!!o.isPromptRunning,tB.current=!0,$(!0),e9(sM(o)),z({type:"start"}),oy(r),!o.isStreaming&&o.isPromptRunning&&oF(r)}catch{}})(),s}catch(e){return console.error("Failed to resolve queued message recovery:",e),oS({type:"error",message:"Failed to resolve queued message recovery"}),ty}},[ty,oS,oy,oF]),o0=(0,n.useCallback)(async()=>{let e=tH.current;if(!e)return null;try{return await sT(e,{type:"export_queue"})}catch(e){return console.error("Failed to export queue:",e),oS({type:"error",message:"Failed to export queue"}),null}},[oS]),o1=(0,n.useCallback)(async e=>{let t=tH.current;if(!t)return null;try{let o=await sT(t,{type:"import_queue",entries:e});return o&&tv(sE(o)),o?.imported??0}catch(e){return console.error("Failed to import queue:",e),oS({type:"error",message:"Failed to import queue"}),null}},[oS]),o2=(0,n.useCallback)(async e=>{let t=tH.current;if(!t)return null;try{let o=await sT(t,{type:"stage_recovery",entries:e});return o?.pendingRecovery&&tb(o.pendingRecovery),(o?.staged??0)>0&&tj(!0),o?.staged??0}catch(e){return console.error("Failed to stage imported queue:",e),oS({type:"error",message:"Failed to stage imported queue"}),null}},[oS]),o4=(0,n.useCallback)(async(e,t,o)=>{let r=tH.current;if(!r)return!1;try{let n=await sT(r,{type:"move_queue",kind:e,fromIndex:t,toIndex:o});return n&&tv(sE(n)),!0}catch(e){return console.error("Failed to move queued message:",e),oS({type:"error",message:e instanceof Error?e.message:"Failed to move queued message"}),!1}},[oS]),o6=(0,n.useCallback)(async(e,t)=>{let o=tH.current;if(!o)return null;try{let r=await sT(o,{type:"recall_queue_item",kind:e,index:t});return r&&(void 0!==r.steering||void 0!==r.followUp)&&tv(sE(r)),r?.entry?{text:r.entry.text,images:r.entry.images?.map(({data:e,mimeType:t})=>({data:e,mimeType:t}))}:null}catch(e){return console.error("Failed to recall queued message:",e),oS({type:"error",message:e instanceof Error?e.message:"Failed to recall queued message"}),null}},[oS]),o5=(0,n.useCallback)(async(e,t,o,r)=>{let n=tH.current;if(!n)return!1;try{let s=await sT(n,{type:"requeue_at",kind:e,index:t,text:o,images:r?.map(({data:e,mimeType:t})=>({type:"image",data:e,mimeType:t}))});return s&&tv(sE(s)),!0}catch(e){return console.error("Failed to requeue message:",e),oS({type:"error",message:e instanceof Error?e.message:"Failed to requeue message"}),!1}},[oS]),o3=(0,n.useCallback)(async(e,t)=>{let o=tH.current;if(!o)return!1;try{let r=await sT(o,{type:"remove_queue_item",kind:e,index:t});return r&&tv(sE(r)),!0}catch(e){return console.error("Failed to remove queued message:",e),oS({type:"error",message:e instanceof Error?e.message:"Failed to remove queued message"}),!1}},[oS]),o8=(0,n.useCallback)(async e=>{if(oo.current="auto"===e?null:e,eU(e),"auto"===e)return;let t=tH.current??await t4.current;if(t)try{await sT(t,{type:"set_thinking_level",level:e})}catch(e){console.error("Failed to set thinking level:",e)}},[]),o7=(0,n.useCallback)(async e=>{let t=(0,sR.xG)(e);oi(e);let o=tH.current??await t4.current;if(o)try{await sT(o,{type:"set_tools",toolNames:t})}catch(e){console.error("Failed to set tools:",e)}},[oi]),o9=(0,n.useRef)(0),re=(0,n.useCallback)(async e=>{let t=tH.current??await t4.current,o=++o9.current;if(e){if(es.current="plan"===et?"default":et,en(!0),ei.current=!0,eb.current={sessionKey:"",signature:""},t)try{if(await sT(t,{type:"prompt",message:"/plan"}),o9.current!==o)return}catch(e){if(o9.current!==o)return;console.error("Failed to enter plan mode:",e)}}else if(en(!1),ei.current=!1,eb.current={sessionKey:"",signature:""},t){try{if(await sT(t,{type:"prompt",message:"/plan exit"}),o9.current!==o)return}catch(e){if(o9.current!==o)return;console.error("Failed to exit plan mode:",e)}if(o9.current!==o)return;try{let e=es.current;await sT(t,{type:"set_tools",toolNames:(0,sR.xG)(e)})}catch(e){console.error("Failed to restore tools after plan exit:",e)}}},[et]),rt=(0,n.useCallback)(e=>{el(e);let t=tH.current;if(!t){ed.current=e;return}ed.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)})},[]),ro=(0,n.useCallback)(e=>{if(rt({...ew.current,collaborationMode:ez(e)}),ex.current=ez(e),eb.current={sessionKey:"",signature:""},"goal"!==e){ey.current=null,eH.current=!1,eA(e=>"idle"===e.status?e:{...e,status:"idle",goalText:null});let e=tH.current;e&&sT(e,{type:"goal_stop"}).catch(()=>{})}},[rt]),rr=(0,n.useCallback)(async e=>{rt({...ew.current,tokenMode:eI(e)});let t=tH.current??await t4.current;if(t)try{if("economy"!==e||ei.current){if("economy"!==e){let e=ei.current?sR.SC:(0,sR.xG)("plan"===et?"default":et);await sT(t,{type:"set_tools",toolNames:e})}}else await sT(t,{type:"set_tools",toolNames:[...eE]})}catch(e){console.error("Failed to apply token mode tools:",e)}},[rt,et]),rn=(0,n.useCallback)(async e=>{rt({...ew.current,toolApprovalMode:eM(e)});let t=tH.current??await t4.current;if(t)try{await sT(t,{type:"set_approval_mode",mode:eM(e)})}catch(e){console.error("Failed to apply approval mode:",e)}},[rt]),rs=(0,n.useCallback)(async e=>{rt({...ew.current,permissionRules:e});let t=tH.current??await t4.current;if(t)try{await sT(t,{type:"set_approval_policy",policy:e})}catch(e){console.error("Failed to apply permission rules:",e)}},[rt]),ri=(0,n.useCallback)(async(e,t,o)=>{let r=tH.current;if(r)try{await sT(r,{type:"resolve_approval",id:e,approve:t,reason:o})}catch(e){console.error("Failed to resolve approval:",e)}finally{eS(t=>t.filter(t=>t.id!==e))}},[]),ra=(0,n.useCallback)(e=>{ey.current=e},[]),rl=(0,n.useCallback)(e=>{let t=e.trim();if(!t)return;ey.current=t,eA(e=>({...e,status:"running",goalText:t,turnsUsed:0,noProgressTurns:0,tokensUsed:0,startedAt:Date.now()}));let o=tH.current;o&&sT(o,{type:"goal_start",goalText:t}).catch(()=>{})},[]),rd=(0,n.useCallback)(()=>{if("running"!==eO.current.status)return;eA(e=>({...e,status:"paused"}));let e=tH.current;e&&sT(e,{type:"goal_pause"}).catch(()=>{})},[]),rc=(0,n.useCallback)(()=>{let e=eO.current;if("paused"!==e.status&&"blocked"!==e.status)return;eA(e=>({...e,status:"running"}));let t=tH.current;t&&sT(t,{type:"goal_resume"}).catch(()=>{})},[]),rp=(0,n.useCallback)(()=>{eH.current=!1,ey.current=null,eA(e=>({...e,status:"idle",goalText:null,turnsUsed:0,noProgressTurns:0}));let e=tH.current;e&&sT(e,{type:"goal_stop"}).catch(()=>{})},[]),ru=(0,n.useCallback)(e=>{let t=e.trim();if(!t)return;eA(e=>({...e,goalText:t}));let o=tH.current;o&&sT(o,{type:"goal_edit",goalText:t}).catch(()=>{})},[]),rg=tS.map(e=>`${e.id}:${e.status}:${e.completedAt??""}`).join("|"),rh=(0,n.useRef)(tS);rh.current=tS,(0,n.useEffect)(()=>{u?.(rh.current)},[rg,u]),(0,n.useEffect)(()=>()=>{u?.([])},[u]),(0,n.useEffect)(()=>{tz(()=>[])},[t?.id,r??t?.cwd]);let rf=(0,n.useCallback)(()=>{let e=t2.current,t=tG.current;if(!e||!t)return;let o=t.getBoundingClientRect().top-e.getBoundingClientRect().top+e.scrollTop,r=Math.max(0,e.scrollHeight-e.clientHeight),n=Math.min(Math.max(0,o-16),r);tZ.current=n>=r-150,t0.current=Date.now()+700,e.scrollTo({top:n,behavior:"smooth"})},[]),rx=(0,n.useCallback)(e=>{e instanceof KeyboardEvent&&(!sF.has(e.key)||e.target instanceof Element&&e.target.closest("input, textarea, [contenteditable='true']"))||(tQ.current=Date.now()+1200)},[]),rm=(0,n.useCallback)(()=>{let e=t2.current;if(e){let{scrollTop:t,clientHeight:o,scrollHeight:r}=e;tZ.current=t+o>=r-150}if(Date.now()<tQ.current){tX.current=!1;return}Date.now()<t0.current||(tX.current=!1)},[]);(0,n.useEffect)(()=>{if(t){tH.current=t.id;let e=ek.current,o=ev.current;("auto"!==e||o.allow.length||o.ask.length||o.deny.length)&&(sT(t.id,{type:"set_approval_mode",mode:e}).catch(()=>{}),sT(t.id,{type:"set_approval_policy",policy:o}).catch(()=>{})),ou(t.id,!0,!0).then(e=>{e?.running&&(e.state?.isBashRunning&&(tV.current=!0,L(!0)),oh(t.id),(e.state?.isStreaming||e.state?.isPromptRunning)&&(tU.current=!!e.state.isStreaming,t_.current=!!e.state.isPromptRunning,tB.current=!0,$(!0),e9(sM(e.state)),z({type:"start"}),oy(t.id),!e.state.isStreaming&&e.state.isPromptRunning&&oF(t.id))),e?.state&&(void 0!==e.state.isCompacting&&e4(e.state.isCompacting),void 0!==e.state.contextUsage&&eK(e.state.contextUsage??null),void 0!==e.state.systemPrompt&&eG(e.state.systemPrompt??null),void 0!==e.state.thinkingLevel&&eU(e.state.thinkingLevel??"auto"),void 0!==e.state.extensionStatuses&&tf(e.state.extensionStatuses??[]),void 0!==e.state.extensionWidgets&&tm(e.state.extensionWidgets??[]),void 0!==e.state.queuedMessages&&tv(sE(e.state.queuedMessages)),void 0!==e.state.pendingRecovery&&tb(e.state.pendingRecovery??[])),e?.running||fetch(`/api/agent/${encodeURIComponent(t.id)}`).then(e=>e.ok?e.json():null).then(e=>{e&&e.running&&oh(t.id)}).catch(()=>{})})}return()=>{on(),tF(),ok(),ov()}},[on]),(0,n.useEffect)(()=>{c?.(eJ)},[eJ,c]),(0,n.useEffect)(()=>{d&&d(f?.tree??[],b,oU)},[f?.tree,b,oU,d]),(0,n.useEffect)(()=>(window.addEventListener("keydown",rx),window.addEventListener("pointerdown",rx,{passive:!0}),()=>{window.removeEventListener("keydown",rx),window.removeEventListener("pointerdown",rx)}),[rx]),(0,n.useEffect)(()=>{let e=t2.current;if(e)return e.addEventListener("wheel",rx,{passive:!0}),e.addEventListener("touchstart",rx,{passive:!0}),e.addEventListener("scroll",rm,{passive:!0}),()=>{e.removeEventListener("wheel",rx),e.removeEventListener("touchstart",rx),e.removeEventListener("scroll",rm)}},[j.length,m,rm,rx]),(0,n.useEffect)(()=>{j.length>0&&(tY.current?(tJ.current=!0,tG.current&&(tY.current=!1,rf())):m||!tJ.current?(m||(tJ.current=!0),o$("instant")):!tB.current&&(tX.current||tZ.current)&&o$("smooth"))},[j.length,m,W,o$,rf]);let rk=(0,n.useRef)(!1);(0,n.useEffect)(()=>{let e;if(m){rk.current=!1;return}if(rk.current||0===j.length)return;rk.current=!0;let t=!1,o=-1,r=0,n=()=>{if(t||tB.current||!(tX.current||tZ.current))return;o$("instant");let s=t2.current;if(s){if(s.scrollHeight===o){if((r+=1)>=2)return}else o=s.scrollHeight,r=0;e=window.setTimeout(n,250)}};return e=window.setTimeout(n,250),()=>{t=!0,void 0!==e&&window.clearTimeout(e)}},[m,j.length,o$]),(0,n.useEffect)(()=>{let e=new AbortController;return oV(e.signal).catch(e=>{if(e instanceof DOMException&&"AbortError"===e.name)return}),()=>e.abort()},[oV,l]),(0,n.useEffect)(()=>{if(!e6)return;let e=setTimeout(()=>e5(null),3e3);return()=>clearTimeout(e)},[e6]),(0,n.useEffect)(()=>{if(!e3)return;let e=setTimeout(()=>e8(null),6e3);return()=>clearTimeout(e)},[e3]),(0,n.useEffect)(()=>{if(0===ti.visible.length)return;let e=ti.visible.find(e=>e.exiting);if(e){let t=setTimeout(()=>{ta({type:"remove",id:e.id})},180);return()=>clearTimeout(t)}if(!ti.visible[0])return;let t=setTimeout(()=>{ta({type:"mark_oldest_exiting"})},5e3);return()=>clearTimeout(t)},[ti.visible]),(0,n.useEffect)(()=>{td(null)},[j.length,eV?.tokens,eV?.percent,eV?.contextWindow]);let rv=f?.tree??[];return{data:f,loading:m,error:v,activeLeafId:b,messages:j,entryIds:C,streamState:R,agentRunning:W,bashRunning:N,pendingBash:A,modelNames:H,modelList:U,modelThinkingLevels:q,modelThinkingLevelMaps:K,modelScopeWarnings:G,newSessionModel:X,toolPreset:et,thinkingLevel:eB,retryInfo:e_,contextUsage:eV,systemPrompt:eJ,forkingEntryId:eY,isCompacting:e2,compactError:e6,compactResult:e3,currentModel:od,displayModel:oc,sessionStats:op,tokenRate:I,planMode:er,subagents:tS,collaborationMode:eu,tokenMode:eg,toolApprovalMode:eh,permissionRules:ef,modeSettings:ea,approvalRequests:ej,handleCollaborationModeChange:ro,handleTokenModeChange:rr,handleToolApprovalModeChange:rn,handlePermissionRulesChange:rs,resolveApproval:ri,setActiveGoalText:ra,goalState:eL,handleGoalStart:rl,handleGoalPause:rd,handleGoalResume:rc,handleGoalStop:rp,handleGoalEdit:ru,slashCommands:to,slashCommandsLoading:tn,queuedMessages:tk,pendingRecovery:ty,recoveryIsImport:tw,notices:ti.visible,extensionDialog:tc,extensionCustomUi:tu,extensionStatuses:th,extensionWidgets:tx,respondToExtensionUi:ow,sendExtensionCustomInput:oj,agentPhase:e7,isNew:g,promptAnchorActive:te,branchTree:rv,sessionIdRef:tH,eventSourceRef:tW,messagesEndRef:t1,scrollContainerRef:t2,lastUserMsgRef:tG,pendingScrollToUserRef:tY,initialScrollDoneRef:tJ,scrollUserMsgToTop:rf,handleSend:oL,executeBash:oA,handleAbort:oO,handleFork:oH,handleNavigate:oB,handleModelChange:o_,handleCompact:oq,handleSteer:oJ,handleFollowUp:oY,handlePromptWithStreamingBehavior:oG,handleAbortCompaction:oX,handleRecallQueue:oZ,resolveRecovery:oQ,exportQueueData:o0,importQueueData:o1,stageQueueImport:o2,moveQueuedMessage:o4,recallQueuedMessage:o6,requeueAt:o5,removeQueuedMessage:o3,handleBuiltinSlashCommand:oK,handleToolPresetChange:o7,handleThinkingLevelChange:o8,handlePlanModeChange:re,loadTools:oh,loadSlashCommands:om,setActiveLeafId:w,setData:x,setMessages:S,dispatch:z,setAgentRunning:$,setForkingEntryId:eX,handleLeafChange:oU,handleAgentEventRef:tK}}({session:e,newSessionCwd:t,onAgentEnd:F,onSessionCreated:i,onSessionForked:l,modelsRefreshKey:d,chatInputRef:c,onBranchDataChange:p,onSystemPromptChange:u,onSessionStatsPanelOpen:f,onSubagentsChange:h}),[tS,tC]=(0,n.useState)(!1);(0,n.useEffect)(()=>{0===eu.length&&tC(!1)},[eu.length]);let{balance:tT,refresh:tR,refreshSoon:tz}=function(){let[e,t]=(0,n.useState)(null),[o,r]=(0,n.useState)(!1),s=(0,n.useRef)(null),i=(0,n.useRef)(null),a=(0,n.useRef)(!0);(0,n.useEffect)(()=>(a.current=!0,()=>{a.current=!1,i.current&&clearTimeout(i.current),s.current?.abort()}),[]);let l=(0,n.useCallback)(async()=>{s.current?.abort();let o=new AbortController;s.current=o;try{let n=await fetch("/api/deepseek/balance",{signal:o.signal,cache:"no-store"}),s=await n.json();if(!a.current)return;s?.available&&null!=s.totalBalance?(t(s),r(!1)):null===e&&r(!0)}catch{if(!a.current)return;null===e&&r(!0)}},[e]),d=(0,n.useCallback)(()=>{i.current&&clearTimeout(i.current),i.current=setTimeout(()=>{i.current=null,l()},2e3)},[l]);return{balance:e,failed:o,refresh:l,refreshSoon:d}}(),tI=ei?.provider==="deepseek",tM=(0,n.useRef)(null);(0,n.useEffect)(()=>{tI&&tR()},[tI,tR]),(0,n.useEffect)(()=>{if(tI)for(let e=H.length-1;e>=0;e--){let t=H[e];if("assistant"!==t.role||!t.usage)continue;let o=`${e}:${B[e]??""}`;o!==tM.current&&(tM.current=o,tz());break}},[H,B,tI,tz]);let tE=(0,n.useMemo)(()=>{let e=H.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:oR(e.model)?oz(e.model,t):0,costUSD:oR(e.model)?0:t.cost?.total??0}},[H]),[tP,tD]=(0,n.useState)(!1),[tF,tW]=(0,n.useState)(null),t$=(0,n.useRef)(!1);(0,n.useEffect)(()=>{if(!ti){t$.current=!1;return}if(_){t$.current=!0;return}t$.current&&(t$.current=!1,tW(function(e){for(let t=e.length-1;t>=0;t--){let o=e[t];if("assistant"!==o.role)continue;let r=o.content;if("string"==typeof r&&r.trim())return r;if(Array.isArray(r)){let e=r.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 r=o.content,n="string"==typeof r?r:Array.isArray(r)?r.map(e=>e.text??"").join("\n"):"";if(!n)continue;let s=n.match(/\*\*Proposed Plan\*\*\s*\n+([\s\S]+)/i);if(s?.[1]?.trim())return s[1].trim()}return null}(H)??null),tD(!0))},[_,ti,H]);let tN=(0,n.useCallback)(()=>{tD(!1);let e=tL.current;"plan"===tl&&tg("normal"),ta(!1).then(()=>{e&&eq(I("tasks.planReviewExecutePrompt",{plan:e}))})},[ta,eq,I,tl,tg]),tL=(0,n.useRef)(null);(0,n.useEffect)(()=>{tL.current=tF},[tF]);let tA=(0,n.useCallback)(e=>{tD(!1),eZ(e)},[eZ]),tO=(0,n.useCallback)(()=>{tD(!1),"plan"===tl&&tg("normal"),ta(!1)},[ta,tl,tg]);(0,n.useEffect)(()=>{ef&&D.current!==ef.id&&(D.current=ef.id,P.current&&M.current())},[ef]),(0,n.useEffect)(()=>{a=_||q?eK:null},[_,q,eK]);let[tH,tB]=(0,n.useState)(!1),[tU,t_]=(0,n.useState)(!1),[tq,tV]=(0,n.useState)(!1),tK=(0,n.useCallback)(()=>{let e=eO.current;if(!e)return;let t=e.scrollHeight-e.scrollTop-e.clientHeight;tB(e.scrollTop>1),t_(t>1),tV(t>240)},[eO]),tJ=(0,n.useCallback)(()=>{window.requestAnimationFrame(()=>{let e=eO.current,t=eA.current;if(!e||!t)return;let o=Math.max(88,c?.current?.measureHeight?.()??0),r=()=>{if(!e||!t)return;let r=Math.max(0,t.getBoundingClientRect().top-e.getBoundingClientRect().top+e.scrollTop-96-e.clientHeight+o);e.scrollTo({top:r,behavior:"auto"})};r(),tK(),window.setTimeout(r,200)})},[eA,eO,tK,c]);(0,n.useEffect)(()=>{let e=eO.current;if(!e)return;let t=new ResizeObserver(tK);return t.observe(e),e.firstElementChild&&t.observe(e.firstElementChild),e.addEventListener("scroll",tK,{passive:!0}),tK(),()=>{e.removeEventListener("scroll",tK),t.disconnect()}},[H.length,eO,tK]);let tG=(0,n.useRef)(null),tY=(0,n.useRef)([]),tX=(0,n.useMemo)(()=>({getOffsetForIndex:e=>tG.current?.getOffsetForIndex(e)?.[0]??0,sizeFor:e=>{let t=tG.current;if(!t)return 0;let o=t.measurementsCache[e];return o?.size??t.options.estimateSize?.(e)??0},totalHeight:()=>tG.current?.getTotalSize()??0,refToItemIndex:e=>tY.current[e],itemCount:tY.current.length}),[]),tZ=ea?[ea.sessionId,ea.sessionFile??"",ea.sessionName??"",ea.userMessages,ea.assistantMessages,ea.toolCalls,ea.toolResults,ea.totalMessages,ea.tokens.input,ea.tokens.output,ea.tokens.cacheRead,ea.tokens.cacheWrite,ea.tokens.total,ea.cost??0,ea.totalActiveMs??0].join("|"):null,tQ=(0,n.useRef)(ea);tQ.current=ea,(0,n.useEffect)(()=>{g?.(tQ.current)},[tZ,g]),(0,n.useEffect)(()=>()=>{g?.(null)},[g]);let t0=et?`${et.percent??"null"}|${et.contextWindow}|${et.tokens??"null"}`:null,t1=(0,n.useRef)(et);t1.current=et,(0,n.useEffect)(()=>{x?.(t1.current)},[t0,x]),(0,n.useEffect)(()=>()=>{x?.(null)},[x]);let{isDragOver:t2,handleDragEnter:t4,handleDragOver:t6,handleDragLeave:t5,handleDrop:t3}=function(e){let[t,o]=(0,n.useState)(!1),r=(0,n.useRef)(0),s=(0,n.useCallback)(e=>{e.dataTransfer.files.length&&(e.preventDefault(),r.current+=1,o(!0))},[]),i=(0,n.useCallback)(e=>{e.dataTransfer.files.length&&e.preventDefault()},[]);return{isDragOver:t,handleDragEnter:s,handleDragOver:i,handleDragLeave:(0,n.useCallback)(()=>{r.current-=1,r.current<=0&&(r.current=0,o(!1))},[]),handleDrop:(0,n.useCallback)(t=>{t.preventDefault(),r.current=0,o(!1),e(Array.from(t.dataTransfer.files),t.dataTransfer)},[e])}}((0,n.useCallback)((e,t)=>{if(_){let t=e.filter(e=>e.type.startsWith("image/"));t.length&&c?.current?.addImages(t);return}c?.current?.addFiles(e,t)},[_,c])),t8=H.filter(e=>"user"===e.role||"assistant"===e.role),t7=(0,n.useMemo)(()=>{let e=new Set,t=[];for(let r=H.length-1;r>=0&&t.length<50;r-=1){var o;let n="user"!==(o=H[r]).role?null:("string"==typeof o.content?o.content:o.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n")).trim()||null;!n||e.has(n)||(e.add(n),t.push(n))}return t},[H]),t9=(w=t8.length,(j=(0,n.useRef)([])).current=Array(w).fill(null).map((e,t)=>j.current[t]??null),j),oe=ew&&0===H.length&&!U.isStreaming&&!_,ot=e?.cwd??t??void 0,oo=ei?G[`${ei.provider}:${ei.modelId}`]??null:null,or=ei?Y[`${ei.provider}:${ei.modelId}`]??null:null,on=(0,r.jsx)(st,{ref:c,onSend:eq,onBash:eV,tasksBoardEnabled:b,onAbort:eK,onSteer:_?eZ:void 0,onFollowUp:_?eQ:void 0,onPromptWithStreamingBehavior:_?e0:void 0,isStreaming:_,model:ei,modelNames:K,modelList:J,modelScopeWarnings:X,onModelChange:eY,compactResult:es,toolPreset:Z,onToolPresetChange:e||ew?to:void 0,planMode:ti,onPlanModeChange:e=>{ta(e),e&&"plan"!==tl?tg("plan"):e||"plan"!==tl||tg("normal")},collaborationMode:tl,tokenMode:tp,toolApprovalMode:tu,onCollaborationModeChange:e=>{tg(e),"plan"!==e||ti?"plan"!==e&&ti&&ta(!1):ta(!0)},onTokenModeChange:th,onToolApprovalModeChange:tf,goalState:tk,onGoalStart:tv,onGoalPause:ty,onGoalResume:tb,onGoalStop:tw,thinkingLevel:Q,onThinkingLevelChange:e||ew?tr:void 0,availableThinkingLevels:oo,thinkingLevelMap:or,retryInfo:ee,queuedMessages:ep,inputHistory:t7,onRecallQueue:e2,onMoveQueue:e3,onRecallOne:e8,onRequeueAt:e7,onRemoveQueueItem:e9,slashCommands:ed,slashCommandsLoading:ec,onLoadSlashCommands:ts,onBuiltinCommand:te,onAudioUnlock:R,draftKey:e?.id??(t?`new:${t}`:void 0),cwd:e?.cwd??t}),os=ek.filter(e=>"belowEditor"!==e.placement),oi=ek.filter(e=>"belowEditor"===e.placement),oa=er?I("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}(eb,I);return A?(0,r.jsx)("div",{className:"flex h-full items-center justify-center text-text-muted",children:I("desktop.loadingSession")}):O?(0,r.jsx)("div",{className:"flex h-full items-center justify-center text-red-400",children:O}):(0,r.jsxs)("div",{className:"relative flex h-full min-w-0 flex-col overflow-hidden",onDragEnter:t4,onDragOver:t6,onDragLeave:t5,onDrop:t3,children:[t2&&(0,r.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,r.jsx)("div",{className:"pointer-events-none absolute inset-0 flex items-center justify-center",children:[0,.8,1.6].map(e=>(0,r.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,r.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,r.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,r.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,r.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,r.jsxs)("g",{stroke:"rgba(37,99,235,0.45)",strokeWidth:"1.4",strokeLinecap:"round",children:[(0,r.jsx)("line",{x1:"96",y1:"46",x2:"96",y2:"43"}),(0,r.jsx)("line",{x1:"96",y1:"70",x2:"96",y2:"73"}),(0,r.jsx)("line",{x1:"84",y1:"58",x2:"81",y2:"58"}),(0,r.jsx)("line",{x1:"108",y1:"58",x2:"111",y2:"58"}),(0,r.jsx)("line",{x1:"87.5",y1:"49.5",x2:"85.4",y2:"47.4"}),(0,r.jsx)("line",{x1:"104.5",y1:"66.5",x2:"106.6",y2:"68.6"}),(0,r.jsx)("line",{x1:"104.5",y1:"49.5",x2:"106.6",y2:"47.4"}),(0,r.jsx)("line",{x1:"87.5",y1:"66.5",x2:"85.4",y2:"68.6"})]})]})]}),ef&&(0,r.jsx)(sY,{request:ef,onRespond:ev}),ex&&(0,r.jsx)(sX,{request:ex,onInput:ey}),!ew&&eu.length>0&&!tS&&(0,r.jsx)(sn,{items:eu,sessionId:e?.id,onResolve:e4,onExport:e6,onStageImport:e5,onDismiss:()=>tC(!0),mode:eg?"import":"recovery"}),tx.length>0&&(0,r.jsx)(o7,{request:tx[0]??null,queuedCount:Math.max(0,tx.length-1),busy:!1,onResolve:(e,t)=>{let o=tx[0];o&&tm(o.id,e,t)}}),oe?(0,r.jsx)("div",{className:"flex flex-1 flex-col items-center justify-center overflow-y-auto",children:(0,r.jsxs)("div",{className:"w-full max-w-[820px]",children:[(0,r.jsx)("div",{style:{display:"flex",justifyContent:"center",marginBottom:28},children:(0,r.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,r.jsx)("title",{children:"Pi"}),(0,r.jsx)("path",{clipRule:"evenodd",d:"M1 1h16.5v11H12v5.5H6.5V23H1V1zm5.5 5.5V12H12V6.5H6.5z"}),(0,r.jsx)("path",{d:"M17.5 12H23v11h-5.5V12z"})]})}),(0,r.jsx)("div",{style:{padding:"0 34px 6px 7px",paddingRight:z?16:34},children:(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12},children:[(0,r.jsx)("div",{ref:k,style:{display:"flex",alignItems:"center",minWidth:0,flex:1,minHeight:48}}),(0,r.jsxs)("div",{style:{display:z?"none":"flex",flexDirection:"column",alignItems:"flex-end",gap:2,flexShrink:0},children:[(0,r.jsxs)("span",{style:{fontSize:11,color:"var(--text-muted)",fontFamily:"var(--font-mono)"},children:["web ",(0,r.jsxs)("span",{style:{color:"var(--text)"},children:["v","0.9.31"]})]}),(0,r.jsxs)("span",{style:{fontSize:11,color:"var(--text-muted)",fontFamily:"var(--font-mono)"},children:["pi ",(0,r.jsxs)("span",{style:{color:"var(--text)"},children:["v","0.84.0"]})]})]})]})}),(0,r.jsx)("div",{style:{padding:"0 16px",paddingRight:z?16:34},children:(0,r.jsx)(sG,{notices:eh,align:"right"})}),"goal"===tl&&(0,r.jsx)(o3,{goalState:tk,onPause:ty,onResume:tb,onStop:tw,onEdit:tj}),on,(0,r.jsx)("div",{style:{padding:"0 16px 6px",paddingRight:z?16:34,marginTop:-15},children:(0,r.jsx)(sv,{onViewFullHistory:v,cwd:ot,systemPrompt:y,sessionStats:ea,contextUsage:et,hasSession:!!e,showChat:!0,showSoundLabel:!0,soundEnabled:S,onSoundToggle:C,onCompact:e?eX:void 0,onAbortCompaction:e1,isCompacting:er,compactError:en,isDeepSeekOfficial:tI,deepseekBalance:tT,lastTurnUsage:tE})})]})}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("div",{className:"relative flex flex-1 overflow-hidden z-0",children:[(0,r.jsx)("div",{style:{position:"absolute",top:12,left:0,right:18*!z,zIndex:40,padding:"0 16px",pointerEvents:"none"},children:(0,r.jsx)("div",{style:{maxWidth:820,margin:"0 auto"},children:(0,r.jsx)(sG,{notices:eh,floating:!0,align:"right"})})}),(0,r.jsxs)("div",{className:"relative flex-1 min-h-0 min-w-0",children:[(0,r.jsx)("div",{ref:eO,className:"h-full min-w-0 overflow-x-hidden overflow-y-auto pt-4 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden",children:(0,r.jsx)("div",{style:{minWidth:0,padding:"0 16px"},children:(0,r.jsxs)("div",{style:{width:"100%",minWidth:0,maxWidth:820,margin:"0 auto"},children:[(0,r.jsx)(sK,{statuses:em}),(0,r.jsx)(sJ,{widgets:os}),(()=>{let t=new Map;for(let e of H)"toolResult"===e.role&&t.set(e.toolCallId,e);let o=-1;for(let e=H.length-1;e>=0;e--)if("user"===H[e].role){o=e;break}let n=new Map,s=0;H.forEach((e,t)=>{("user"===e.role||"assistant"===e.role)&&n.set(t,s++)});let i=(s,i={})=>{let a=i.messageOverride??H[s],l="user"===a.role&&s>0&&"assistant"===H[s-1].role?B[s-1]:void 0,d="user"===a.role||"assistant"===a.role,c=n.get(s),p=i.keyPrefix??"message",u=!1;if("assistant"===a.role){u=!0;for(let e=s+1;e<H.length;e++){let t=H[e].role;if("user"===t)break;if("assistant"===t){u=!1;break}}u&&U.isStreaming&&s===H.length-1&&(u=!1)}void 0!==i.showTimestamp&&(u=i.showTimestamp);let g=(0,r.jsx)(oF,{message:a,toolResults:t,modelNames:K,cwd:ot,onOpenFile:m,entryId:B[s],onFork:_||ew||0===s&&"user"===a.role?void 0:eJ,forking:eo===B[s],onNavigate:_?void 0:eG,prevAssistantEntryId:_?void 0:l,onEditContent:W,onQuoteReply:N,onCreateTask:L,showTimestamp:u,prevTimestamp:s>0?H[s-1].timestamp:void 0,sessionId:e?.id??eL.current??void 0,writtenFiles:i.writtenFiles},`${p}-view-${s}`);return d&&!1!==i.attachRef&&void 0!==c?(0,r.jsx)("div",{ref:e=>{t9.current[c]=e,s===o&&(eH.current=e,e&&eB.current&&(eB.current=!1,eU.current=!0,e_()))},children:g},`${p}-${s}`):g},a=[],l=[],d=(e,t)=>{a.push(e),l.push(t)};for(let s=0;s<H.length;){let a=H[s],l="custom"===a.role&&"compaction"===a.customType;if("user"!==a.role&&!l){d(i(s),n.get(s)),s+=1;continue}let c=s,p=c+1;for(;p<H.length&&"user"!==H[p].role;)p+=1;let u=function(e,t,o){for(let n=o-1;n>t;n--){var r;if("assistant"===(r=e[n]).role&&tt(r).answerBlocks.some(e=>"image"===e.type||"text"===e.type&&e.text.trim().length>0))return n}for(let r=o-1;r>t;r--)if(e[r]?.role==="assistant")return r;return -1}(H,c,p);if((_||U.isStreaming)&&p===H.length&&(c===o||l)){d(i(c),n.get(c));let o=U.streamingMessage?.role==="assistant",a=[],l=!o&&u>=0?u:p;for(let e=c+1;e<l;e++)s_(H[e])&&a.push(e);let g=tc(H,B,a,t),h=null;if(!o&&u>=0){let e=H[u],o=tt(e,{isStreaming:!0}),r=td(e,{messageIndex:u,entryId:B[u],toolResults:t,isStreaming:!0});g=g.concat(r.processBlocks),o.answerBlocks.length>0&&(h=sq(e,o.answerBlocks,{omitUsage:!0}))}if(o){let e=U.streamingMessage,o=tt(e,{isStreaming:!0}),r=td(e,{messageIndex:H.length,toolResults:t,isStreaming:!0});g=g.concat(r.processBlocks),o.answerBlocks.length>0&&(h=sq(e,o.answerBlocks,{omitUsage:!0}))}if(g.length>0){let t=a.map(e=>n.get(e)).find(e=>"number"==typeof e);d((0,r.jsx)("div",{ref:void 0===t?void 0:e=>{t9.current[t]=e},children:(0,r.jsx)(rV,{blocks:g,isStreaming:_||U.isStreaming,cwd:ot,onOpenFile:m,sessionId:e?.id??eL.current??void 0,tokenRate:el})},`live-process-group-${c}`),t)}h&&d((0,r.jsx)(oF,{message:h,isStreaming:!0,modelNames:K,cwd:ot,onOpenFile:m,onQuoteReply:N},`live-answer-${c}`),u>=0?n.get(u):void 0),s=p;continue}if(-1===u){for(let e=c;e<p;e++)d(i(e),n.get(e));s=p;continue}d(i(c),n.get(c));let g=[];for(let e=c+1;e<u;e++)g.push(e);let h=g.filter(e=>s_(H[e])),f=H[u],x=tt(f),k=x.processBlocks.length>0?sq(f,x.processBlocks,{omitUsage:!0}):null,v=x.answerBlocks.length>0?sq(f,x.answerBlocks):null,y=tc(H,B,h,t);if(k&&(y=y.concat(td(f,{messageIndex:u,entryId:B[u],toolResults:t}).processBlocks)),y.length>0){let t=h.map(e=>n.get(e)).find(e=>"number"==typeof e)??(v?void 0:n.get(u));d((0,r.jsx)("div",{ref:void 0===t?void 0:e=>{t9.current[t]=e},children:(0,r.jsx)(rV,{blocks:y,isStreaming:!1,defaultExpanded:!v,onAutoExpanded:void 0,cwd:ot,onOpenFile:m,sessionId:e?.id??eL.current??void 0})},`process-group-${c}-${u}`),t)}if(v){let e=[];for(let t=c+1;t<=u;t++){let o=H[t];if(o?.role==="assistant")for(let t of o.content??[])e.push(t)}d(i(u,{messageOverride:v,writtenFiles:function(e,t,o){let r=new Set,n=[];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 r=/^[a-zA-Z]:[\\/]/.test(e)||e.startsWith("\\\\")||void 0!==t&&(/^[a-zA-Z]:[\\/]/.test(t)||t.startsWith("\\\\")),n=e=>r?e.replace(/\\/g,"/"):e,s=n(e),i=t?n(t).replace(/\/+$/,""):void 0,a=/^[a-zA-Z]:\//.test(s),l=s.startsWith("//");if(a||l)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 tn(o)}(i,o);a&&(r.has(a)||(r.add(a),n.push({filePath:a})))}return n}(e,t,ot)}),n.get(u))}for(let e=u+1;e<p;e++)d(i(e),n.get(e));s=p}let c=[];return l.forEach((e,t)=>{void 0!==e&&(c[e]=t)}),tY.current=c,(0,r.jsx)(sb,{scrollElementRef:eO,items:a,virtualizerRef:tG})})(),oa&&(er||_&&!U.streamingMessage)&&(0,r.jsx)("div",{className:"py-2 text-[13px] text-text-muted",children:(0,r.jsxs)("span",{className:"animate-[pulse_1.5s_infinite]",children:[oa,eb?.kind==="waiting_model"&&(0,r.jsx)("span",{style:{display:"inline-block",width:12,height:12,marginLeft:6,verticalAlign:"-2px",border:"1.5px solid var(--text-muted)",borderTopColor:"transparent",borderRadius:"50%",animation:"spin 0.6s linear infinite"}})]})}),V&&(0,r.jsx)(oF,{message:{role:"bashExecution",command:V.command,output:"",excludeFromContext:V.excludeFromContext},sessionId:e?.id??eL.current??void 0}),q&&!V&&(0,r.jsx)("div",{className:"py-2 text-[13px] text-text-muted",children:(0,r.jsx)("span",{className:"animate-[pulse_1.5s_infinite]",children:I("desktop.runningShellCommand")})}),(0,r.jsx)("div",{style:{height:96}}),(0,r.jsx)("div",{ref:eA}),(0,r.jsx)(o0,{open:tP,planText:tF,busy:_,onExecute:tN,onFeedback:tA,onExit:tO,onClose:()=>tD(!1)})]})})}),tH&&(0,r.jsx)("div",{"aria-hidden":"true",className:"pointer-events-none absolute inset-x-0 top-0 z-10 h-8 bg-gradient-to-b from-[var(--bg)] to-transparent"}),tU&&(0,r.jsx)("div",{"aria-hidden":"true",className:"pointer-events-none absolute inset-x-0 bottom-0 z-10 h-8 bg-gradient-to-t from-[var(--bg)] to-transparent"}),tq&&(0,r.jsxs)("button",{type:"button",onClick:()=>tJ(),title:I("desktop.scrollToBottom"),"aria-label":I("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,r.jsx)(ov.Z,{size:12,weight:"bold","aria-hidden":"true"}),I("desktop.scrollToBottom")]})]}),z?null:(0,r.jsx)(sS,{messages:H,streamingMessage:U.streamingMessage,scrollContainer:eO,messageRefs:t9,virtualizer:tX})]}),(0,r.jsxs)("div",{className:"relative z-10",children:[(0,r.jsx)("div",{style:{padding:"0 16px",paddingRight:z?16:34},children:(0,r.jsx)("div",{style:{maxWidth:820,margin:"0 auto"},children:(0,r.jsx)(sJ,{widgets:oi})})}),on,(0,r.jsx)("div",{className:`session-info-bar-wrap${z?" is-mobile":""}`,children:(0,r.jsx)("div",{className:"session-info-bar-inner",children:(0,r.jsx)(sv,{onViewFullHistory:v,cwd:ot,systemPrompt:y,sessionStats:ea,contextUsage:et,hasSession:!!e,showChat:!0,soundEnabled:S,onSoundToggle:C,onCompact:e?eX:void 0,onAbortCompaction:e1,isCompacting:er,compactError:en,branchTree:ej,branchActiveLeafId:eS,onBranchLeafChange:eN,isDeepSeekOfficial:tI,deepseekBalance:tT,lastTurnUsage:tE})})})]})]})]})}function sK({statuses:e}){return 0===e.length?null:(0,r.jsx)("div",{style:{display:"flex",flexWrap:"wrap",gap:6,marginBottom:10},children:e.map(e=>(0,r.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,r.jsx)("span",{style:{color:"var(--accent)",fontFamily:"var(--font-mono)",fontSize:11},children:e.key}),(0,r.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.text})]},e.key))})}function sJ({widgets:e}){return 0===e.length?null:(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:8,marginBottom:10},children:e.map(e=>(0,r.jsxs)("div",{style:{border:"1px solid var(--border)",borderRadius:7,background:"var(--bg-panel)",overflow:"hidden"},children:[(0,r.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,r.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 sG({notices:e,floating:t=!1,align:o="left"}){return 0===e.length?null:(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",alignItems:"right"===o?"flex-end":"stretch",marginBottom:10*!t},children:e.map((o,n)=>{let s="error"===o.type?"#ef4444":"warning"===o.type?"#d97706":"success"===o.type?"#10b981":"var(--accent)";return(0,r.jsxs)("div",{className:"notice-shelf-item",style:{display:"flex",alignItems:"center",gap:10,minHeight:44,maxHeight:180,marginBottom:6*(n!==e.length-1),overflowY:"auto",overflowX:"hidden",borderRadius:14,border:"1px solid color-mix(in srgb, var(--border) 70%, transparent)",background:"var(--bg)",color:"var(--text-muted)",width:"fit-content",maxWidth:"min(100%, 620px)",boxShadow:t?"0 1px 2px rgba(15,23,42,0.05), 0 10px 28px -14px rgba(15,23,42,0.24)":"0 1px 2px rgba(15,23,42,0.04), 0 8px 24px -12px rgba(15,23,42,0.10)",fontSize:13,lineHeight:1.45,transformOrigin:"top center",animation:o.exiting?"notice-shelf-out 0.18s ease-in forwards":"notice-shelf-in 0.18s ease-out both",padding:"0 12px"},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:s,flexShrink:0}}),(0,r.jsx)("span",{style:{padding:"10px 0",minWidth:0,maxWidth:"100%",overflowWrap:"anywhere",whiteSpace:"pre-wrap"},children:o.message})]},o.id)})})}function sY({request:e,onRespond:t}){let{t:o}=(0,E.s)(),[s,i]=(0,n.useState)("editor"===e.method?e.prefill??"":"");(0,n.useEffect)(()=>{i("editor"===e.method?e.prefill??"":"")},[e]);let a=()=>{"confirm"===e.method?t(e,{confirmed:!0}):t(e,{value:s})};return(0,r.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,r.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,r.jsxs)("div",{style:{padding:"12px 14px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("div",{style:{color:"var(--text)",fontSize:14,fontWeight:650},children:e.title}),(0,r.jsx)("div",{style:{marginTop:3,color:"var(--text-dim)",fontSize:11,fontFamily:"var(--font-mono)"},children:o("desktop.extensionRequest")})]}),(0,r.jsxs)("div",{style:{padding:14},children:["confirm"===e.method&&(0,r.jsx)("div",{style:{color:"var(--text-muted)",fontSize:13,lineHeight:1.6,whiteSpace:"pre-wrap"},children:e.message}),"select"===e.method&&(0,r.jsx)("div",{style:{display:"grid",gap:8},children:e.options.map(o=>(0,r.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,r.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,r.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,r.jsxs)("div",{style:{display:"flex",justifyContent:"flex-end",gap:8,padding:"10px 14px",borderTop:"1px solid var(--border)",background:"var(--bg-panel)"},children:[(0,r.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,r.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,r.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 sX({request:e,onInput:t}){let{t:o}=(0,E.s)(),s=(0,n.useRef)(null),i=function(e){let t=/^[┌├└╭╰][─┬┴┼]+[┐┤┘╮╯]$/,o=[];for(let r of e){let e=e5(r).trimEnd();if(t.test(e))continue;let n=r,s=e7(n);("│"===s||"┃"===s)&&" "===e7(n=e8(n,0))&&(n=e8(n,0));let i=function(e){let t=e3(e);for(let e=t.length-1;e>=0;e--)if(""!==t[e].char.trim())return e;return -1}(n),a=i>=0?e3(n)[i]?.char:void 0;("│"===a||"┃"===a)&&(n=e8(n,i)),o.push(function(e){let t=e;for(;;){let e=e3(t),o=e[e.length-1];if(!o||""!==o.char.trim())return t;t=t.slice(0,o.start)+t.slice(o.end)}}(n))}for(;o.length>0&&""===e5(o[0]).trim();)o.shift();for(;o.length>0&&""===e5(o[o.length-1]).trim();)o.pop();return o.length?o:e}(e.lines);return(0,n.useEffect)(()=>{s.current?.focus()},[e.id]),(0,r.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,r.jsxs)("div",{ref:s,tabIndex:0,role:"dialog","aria-modal":"true",onKeyDown:o=>{let r=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);r&&(o.preventDefault(),o.stopPropagation(),t(e,r))},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,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,padding:"10px 12px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("div",{style:{color:"var(--text)",fontSize:13,fontWeight:650},children:o("desktop.extensionPanel")}),(0,r.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,r.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,r.jsxs)(n.Fragment,{children:[(s=`line-${t}`,(function(e){let t,o=[],r={},n=0;for(e2.lastIndex=0;null!==(t=e2.exec(e));)t.index>n&&o.push({text:e.slice(n,t.index),style:r}),r=function(e,t){let o={...e};for(let e=0;e<t.length;e++){let r=t[e];if(0===r)for(let e of Object.keys(o))delete o[e];else if(1===r)o.fontWeight=700;else if(2===r)o.opacity=.65;else if(3===r)o.fontStyle="italic";else if(4===r)o.textDecoration="underline";else if(22===r)delete o.fontWeight,delete o.opacity;else if(23===r)delete o.fontStyle;else if(24===r)delete o.textDecoration;else if(39===r)delete o.color;else if(49===r)delete o.backgroundColor;else if(r>=30&&r<=37)o.color=e4[r-30];else if(r>=90&&r<=97)o.color=e6[r-90];else if(r>=40&&r<=47)o.backgroundColor=e4[r-40];else if(r>=100&&r<=107)o.backgroundColor=e6[r-100];else if((38===r||48===r)&&2===t[e+1]){let[n,s,i]=[t[e+2],t[e+3],t[e+4]];[n,s,i].every(e=>"number"==typeof e&&Number.isFinite(e))&&(38===r?o.color=`rgb(${n}, ${s}, ${i})`:o.backgroundColor=`rgb(${n}, ${s}, ${i})`),e+=4}else if((38===r||48===r)&&5===t[e+1]){let n=function(e){if(e>=0&&e<8)return e4[e];if(e>=8&&e<16)return e6[e-8];if(e>=16&&e<=231){let t=e-16,o=Math.floor(t/36),r=Math.floor(t%36/6),n=e=>0===e?0:55+40*e;return`rgb(${n(o)}, ${n(r)}, ${n(t%6)})`}if(e>=232&&e<=255){let t=8+(e-232)*10;return`rgb(${t}, ${t}, ${t})`}}(t[e+2]);n&&(38===r?o.color=n:o.backgroundColor=n),e+=2}}return o}(r,t[1]?t[1].split(";").map(e=>Number(e||"0")):[0]),n=t.index+t[0].length;return n<e.length&&o.push({text:e.slice(n),style:r}),o})(e).map((e,t)=>Object.keys(e.style).length>0?(0,r.jsx)("span",{style:e.style,children:e.text},`${s}-${t}`):e.text)),t<o.length-1?"\n":null]},t)})})]})})}let sZ={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"},sQ={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 s0(e){return(e.replace(/\\/g,"/").split("/").pop()??"").toLowerCase().split(".").pop()??""}function s1(e){let t=e.nodeType===Node.ELEMENT_NODE?e:e.parentElement;return t?.closest(".file-source-line[data-line-number]")??null}function s2(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 r=Number(s1(o.startContainer)?.dataset.lineNumber),n=Number(s1(o.endContainer)?.dataset.lineNumber);return Number.isInteger(r)&&Number.isInteger(n)?r<=n?{startLine:r,endLine:n}:{startLine:n,endLine:r}:null}function s4(e,t,o,r={}){let n=eo(e),s=new URLSearchParams({type:t});for(let[e,t]of(o&&s.set("sessionId",o),Object.entries(r)))void 0!==t&&s.set(e,String(t));return`/api/files/${n}?${s.toString()}`}function s6({filePath:e,sourceSessionId:t}){let{t:o}=(0,E.s)();return(0,r.jsx)("a",{href:s4(e,"download",t),download:er(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,r.jsx)(z.z,{size:11,"aria-hidden":"true"})})}let s5={delete:"3px solid var(--git-status-deleted)",add:"3px solid var(--git-status-added)",edit:"3px solid var(--git-status-modified)"},s3="var(--git-status-deleted-bg)",s8="var(--git-status-added-bg)",s7="var(--git-status-added)";function s9(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KB`:`${(e/1048576).toFixed(1)} MB`}function ie({oldContent:e,newContent:t}){let{t:o}=(0,E.s)(),n=function(e,t){let o=e.length,r=t.length,n=o+r,s=Array(2*n+1).fill(0),i=[];for(let a=0;a<=n;a++){i.push([...s]);for(let l=-a;l<=a;l+=2){let d,c=(d=l===-a||l!==a&&s[l-1+n]<s[l+1+n]?s[l+1+n]:s[l-1+n]+1)-l;for(;d<o&&c<r&&e[d]===t[c];)d++,c++;if(s[l+n]=d,d>=o&&c>=r){let s=[],l=o,d=r;for(let o=a;o>0;o--){let r,a=i[o-1],c=l-d;r=c===-o||c!==o&&a[c-1+n]<a[c+1+n]?c+1:c-1;let p=a[r+n],u=p-r;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(!n.some(e=>"unchanged"!==e.type))return(0,r.jsx)("div",{style:{padding:"12px 16px",fontSize:12,color:"var(--text-dim)",fontFamily:"var(--font-mono)"},children:o("desktop.noChanges")});let s=new Set(n.flatMap((e,t)=>"unchanged"!==e.type?[t]:[])),i=new Set;for(let e of s)for(let t=Math.max(0,e-3);t<=Math.min(n.length-1,e+3);t++)i.add(t);let a=[],l=0;for(;l<n.length;)if(i.has(l)){let e=[];for(;l<n.length&&i.has(l);)e.push(n[l]),l++;a.push({hidden:!1,lines:e})}else{let e=0;for(;l<n.length&&!i.has(l);)e++,l++;a.push({hidden:!0,count:e})}let d=[],c=1;for(let e of n)"removed"===e.type?d.push(0):d.push(c++);let p=0;return(0,r.jsx)("div",{style:{fontFamily:"var(--font-mono)",fontSize:13,lineHeight:1.6,minWidth:"max-content"},children:a.map((e,t)=>{if(e.hidden){let n=(0,r.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,n}let n=[],s=[],i=[],a=()=>{if(s.length||i.length){let e=s.length&&i.length?"edit":s.length?"delete":"add";for(let t of s)n.push({key:t.key,kind:"removed",text:t.text,lineNo:null,block:e});for(let t of i)n.push({key:t.key,kind:"added",text:t.text,lineNo:t.lineNo,block:e});s=[],i=[]}};e.lines.forEach((e,o)=>{"unchanged"===e.type?(a(),n.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=n.map(e=>{let t="removed"===e.kind?s3:"added"===e.kind?s8:"transparent",o=e.block?s5[e.block]:"3px solid transparent",n="added"===e.kind?s7:"var(--text-dim)";return(0,r.jsxs)("div",{style:{display:"flex",background:t,borderLeft:o},children:[(0,r.jsx)("span",{style:{minWidth:44,padding:"0 8px 0 16px",textAlign:"right",color:n,userSelect:"none",fontSize:11,lineHeight:1.6,flexShrink:0},children:e.lineNo??""}),(0,r.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,r.jsx)("div",{children:l},t)})})}function it({patch:e}){let t=of(e);if(!t)return null;let o=[],n=[],s=[],i=()=>{if(n.length||s.length){let e=n.length&&s.length?"edit":n.length?"delete":"add";for(let t of n)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});n=[],s=[]}};return t.forEach((e,t)=>{e.rows.forEach((e,r)=>{if("hunk"===e.type){i(),o.push({key:`${t}:${r}: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}:${r}:c`,kind:"context",text:a.text,lineNo:l.lineNo,block:null});return}"removed"===a.type&&n.push({key:`${t}:${r}:l`,text:a.text}),"added"===l.type&&s.push({key:`${t}:${r}:r`,text:l.text,lineNo:l.lineNo})})}),i(),(0,r.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,r.jsxs)("div",{children:[(0,r.jsx)("div",{style:{height:"1.55em"}}),(0,r.jsx)("div",{style:{padding:"3px 12px",color:"var(--accent-blue)",background:"var(--bg-secondary)"},children:e.text}),(0,r.jsx)("div",{style:{height:"1.55em"}})]},e.key);let t="removed"===e.kind?s3:"added"===e.kind?s8:"transparent",o=e.block?s5[e.block]:"3px solid transparent",n="added"===e.kind?s7:"var(--text-dim)";return(0,r.jsxs)("div",{style:{display:"flex",background:t,borderLeft:o},children:[(0,r.jsx)("span",{style:{width:44,flexShrink:0,padding:"0 8px 0 16px",textAlign:"right",color:n,userSelect:"none",fontSize:11},children:e.lineNo??""}),(0,r.jsx)("span",{style:{flex:1,minWidth:0,padding:"0 8px 0 0",whiteSpace:"pre",color:"var(--text)"},children:e.text||"\xa0"})]},e.key)})})}function io({filePath:e,cwd:t,sourceSessionId:o}){let{t:s}=(0,E.s)(),[i,a]=(0,n.useState)(0),[l,d]=(0,n.useState)(null),[c,p]=(0,n.useState)(null),[u,g]=(0,n.useState)(null),h=(0,n.useRef)(null),f=er(e).toLowerCase().split(".").pop()??"";(0,n.useEffect)(()=>{a(0),d(null),p(null),g(null),h.current&&(h.current.close(),h.current=null);let t=new EventSource(s4(e,"watch",o));return h.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(),h.current=null}},[e,o]);let x=s4(e,"read",o,i?{v:i}:void 0),m=null!=l?s9(l):null;return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,r.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,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},title:e,children:en(e,t)}),(0,r.jsx)("span",{style:{marginLeft:"auto"},children:f||s("desktop.image")}),c&&(0,r.jsxs)("span",{children:[c.w," \xd7 ",c.h]}),m&&(0,r.jsx)("span",{children:m}),(0,r.jsx)(s6,{filePath:e,sourceSessionId:o})]}),(0,r.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,r.jsx)("div",{style:{color:"#f87171",fontSize:13},children:u}):(0,r.jsx)("img",{src:x,alt:e,onLoad:e=>{let t=e.currentTarget;p({w:t.naturalWidth,h:t.naturalHeight})},onError:()=>g(s("desktop.failedToLoadImage")),style:{maxWidth:"100%",maxHeight:"100%",objectFit:"contain",boxShadow:"0 2px 8px rgba(0,0,0,0.15)"}})})]})}function ir({filePath:e,cwd:t,sourceSessionId:o}){let{t:s}=(0,E.s)(),[i,a]=(0,n.useState)(0),[l,d]=(0,n.useState)(null),[c,p]=(0,n.useState)(null),[u,g]=(0,n.useState)(null),h=(0,n.useRef)(null),f=er(e).toLowerCase().split(".").pop()??"";(0,n.useEffect)(()=>{a(0),d(null),p(null),g(null),h.current&&(h.current.close(),h.current=null);let t=new EventSource(s4(e,"watch",o));return h.current=t,t.addEventListener("change",e=>{try{let t=JSON.parse(e.data);"number"==typeof t.size&&d(t.size)}catch{}p(null),g(null),a(e=>e+1)}),()=>{t.close(),h.current=null}},[e,o]);let x=s4(e,"read",o,i?{v:i}:void 0);return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,r.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,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},title:e,children:en(e,t)}),(0,r.jsx)("span",{style:{marginLeft:"auto"},children:f||s("desktop.audio")}),null!=c&&(0,r.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,r.jsx)("span",{children:s9(l)}),(0,r.jsx)(s6,{filePath:e,sourceSessionId:o})]}),(0,r.jsx)("div",{style:{flex:1,display:"flex",alignItems:"center",justifyContent:"center",padding:24,background:"var(--bg-panel)"},children:(0,r.jsxs)("div",{style:{width:"min(680px, 100%)"},children:[u&&(0,r.jsx)("div",{style:{color:"#f87171",fontSize:13,marginBottom:12,textAlign:"center"},children:u}),(0,r.jsx)("audio",{controls:!0,preload:"metadata",src:x,onLoadedMetadata:e=>p(e.currentTarget.duration),onError:()=>g(s("desktop.failedToLoadAudio")),style:{width:"100%"}},x)]})})]})}function is({filePath:e,cwd:t,sourceSessionId:o}){let{t:s}=(0,E.s)(),[i,a]=(0,n.useState)(0),[l,d]=(0,n.useState)(null),[c,p]=(0,n.useState)(null),u=(0,n.useRef)(null),g=s0(e),h="pdf"===g,f=h?s4(e,"read",o,i?{v:i}:void 0):s4(e,"preview",o,i?{v:i}:void 0);return(0,n.useEffect)(()=>{a(0),d(null),p(null),u.current&&(u.current.close(),u.current=null),fetch(s4(e,"meta",o)).then(e=>e.json()).then(e=>{e.error&&p(e.error),"number"==typeof e.size&&(d(e.size),!h&&e.size>0xa00000&&p(s("desktop.docxTooLargeForPreview")))}).catch(e=>p(String(e)));let t=new EventSource(s4(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),!h&&t.size>0xa00000))return void p(s("desktop.docxTooLargeForPreview"))}catch{}p(null),a(e=>e+1)}),()=>{t.close(),u.current=null}},[e,h,o,s]),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,r.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,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:e,children:en(e,t)}),(0,r.jsx)("span",{style:{marginLeft:"auto"},children:"docx"===g?s("desktop.docxPreview"):"pdf"}),null!=l&&(0,r.jsx)("span",{children:s9(l)}),(0,r.jsx)(s6,{filePath:e,sourceSessionId:o})]}),(0,r.jsx)("div",{style:{flex:1,minHeight:0,background:"var(--bg-panel)"},children:c?(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",padding:24,color:"#f87171",fontSize:13,textAlign:"center"},children:c}):(0,r.jsx)("iframe",{src:f,sandbox:h?void 0:"allow-same-origin",title:s("desktop.previewFile",{file:er(e)}),style:{width:"100%",height:"100%",border:"none",background:h?"var(--bg)":"#eef1f5"}},f)})]})}function ii({filePath:e,cwd:t,sourceSessionId:o,onOpenFile:n,onAtMention:s,onMentionLines:i,initialDisplayMode:a}){let l;return null!==(sZ[s0(e)]??null)?(0,r.jsx)(io,{filePath:e,cwd:t,sourceSessionId:o}):null!==(sQ[s0(e)]??null)?(0,r.jsx)(ir,{filePath:e,cwd:t,sourceSessionId:o}):null!==("pdf"===(l=s0(e))||"docx"===l?l:null)?(0,r.jsx)(is,{filePath:e,cwd:t,sourceSessionId:o}):(0,r.jsx)(ia,{filePath:e,cwd:t,sourceSessionId:o,onOpenFile:n,onAtMention:s,onMentionLines:i,initialDisplayMode:a})}function ia({filePath:e,cwd:t,sourceSessionId:o,onOpenFile:s,onAtMention:i,onMentionLines:a,initialDisplayMode:l}){let d,c,{t:p}=(0,E.s)(),[u,g]=(0,n.useState)(null),[h,f]=(0,n.useState)(null),[x,m]=(0,n.useState)(null),[k,v]=(0,n.useState)(!0),[y,b]=(0,n.useState)(null),[w,j]=(0,n.useState)(!1),[S,C]=(0,n.useState)("source"),[T,R]=(0,n.useState)(!1),[z,I]=(0,n.useState)(0),[M,P]=(0,n.useState)(null),D=(0,n.useRef)(null),F=(0,n.useRef)(null),W=(0,n.useCallback)(async e=>{if(!t)return void m(null);try{let o=new URLSearchParams({cwd:t,path:e}),r=await fetch(`/api/git/diff?${o.toString()}`),n=await r.json();m(r.ok&&n.supported&&"string"==typeof n.patch?n:null)}catch{m(null)}},[t]),$=(0,n.useCallback)((e,t=!1)=>fetch(s4(e,"read",o)).then(e=>e.json()).then(e=>e.error?(b(e.error),null):(t?(g(t=>(t&&f(t.content),e)),I(e=>e+1)):g(e),e)).catch(e=>(b(String(e)),null)),[o]);(0,n.useEffect)(()=>{v(!0),b(null),g(null),f(null),m(null),j(!1),C("source"),R(!1),I(0),D.current&&(D.current.close(),D.current=null),$(e).then(e=>{(e?.language==="markdown"||e?.language==="html")&&"diff"!==l&&j(!0)}).finally(()=>v(!1)),W(e);let t=new EventSource(s4(e,"watch",o));return D.current=t,t.addEventListener("change",()=>{$(e,!0),W(e)}),()=>{t.close(),D.current=null}},[e,$,W,l,o]);let N=(0,n.useMemo)(()=>tG(u?.content??""),[u?.content]),L=x?.supported===!0&&"string"==typeof x.patch;(0,n.useEffect)(()=>{"diff"===l&&L&&C("diff")},[L,l]);let A=L&&x?.status==="deleted",O=(0,n.useCallback)(o=>{a&&o&&a(en(e,t),o.startLine,o.endLine)},[t,e,a]);if((0,n.useEffect)(()=>{let e=()=>{let e=F.current,t="source"===S&&!w;P(a&&t&&e?s2(e,window.getSelection()):null)};if(e(),a&&"source"===S&&!w)return document.addEventListener("selectionchange",e),()=>document.removeEventListener("selectionchange",e)},[u?.content,a,w,S]),(0,n.useEffect)(()=>{if(!a||"source"!==S||w)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=F.current,r=o?s2(o,window.getSelection()):null;r&&(e.preventDefault(),O(r))};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[O,a,w,S]),k)return(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-muted)",fontSize:13},children:p("desktop.loadingFile")});if(A&&!u)return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,r.jsx)("div",{style:{padding:"5px 16px",borderBottom:"1px solid var(--border)",color:"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:11},title:e,children:en(e,t)}),(0,r.jsx)("div",{style:{flex:1,overflow:"auto",background:"var(--bg)"},children:(0,r.jsx)(it,{patch:x.patch})})]});if(y)return(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"#f87171",fontSize:13},children:y});if(!u)return null;let H="html"===u.language,B="markdown"===u.language,U=(c=(d=et(e).replace(/\/+$/,"")).lastIndexOf("/"))<0?"":0===c?"/":2===c&&/^[a-zA-Z]:\//.test(d)?d.slice(0,3):d.slice(0,c),_=u.content.split("\n"),q=null!==h&&h!==u.content||L;return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,r.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,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},title:e,children:en(e,t)}),(0,r.jsx)("span",{style:{marginLeft:"auto"},children:u.language}),"source"===S&&(0,r.jsx)("span",{children:p("desktop.lines",{count:_.length})}),(0,r.jsx)("span",{children:s9(u.size)}),q&&(0,r.jsxs)("div",{style:{display:"flex",borderRadius:5,overflow:"hidden",border:"1px solid var(--border)"},children:[(0,r.jsx)("button",{onClick:()=>C("source"),style:{padding:"2px 8px",fontSize:11,border:"none",cursor:"pointer",background:"source"===S?"var(--bg-selected)":"var(--bg-hover)",color:"source"===S?"var(--text)":"var(--text-muted)",fontWeight:"source"===S?600:400},children:p("desktop.source")}),(0,r.jsxs)("button",{onClick:()=>C("diff"),style:{padding:"2px 8px",fontSize:11,border:"none",borderLeft:"1px solid var(--border)",cursor:"pointer",background:"diff"===S?"var(--bg-selected)":"var(--bg-hover)",color:"diff"===S?"var(--text)":"var(--text-muted)",fontWeight:"diff"===S?600:400},children:[p("desktop.diff")," ",z>0&&(0,r.jsxs)("span",{style:{color:"var(--git-status-added)",marginLeft:2},children:["+",z]})]})]}),"source"===S&&!w&&(0,r.jsx)("button",{onClick:()=>R(e=>!e),title:p(T?"desktop.disableWordWrap":"desktop.enableWordWrap"),style:{padding:"2px 8px",fontSize:11,cursor:"pointer",background:T?"var(--bg-selected)":"var(--bg-hover)",color:T?"var(--text)":"var(--text-muted)",border:"1px solid var(--border)",borderRadius:5,fontWeight:T?600:400},children:p("desktop.wrap")}),H&&"source"===S&&(0,r.jsxs)("div",{style:{display:"flex",borderRadius:5,overflow:"hidden",border:"1px solid var(--border)"},children:[(0,r.jsx)("button",{onClick:()=>j(!1),style:{padding:"2px 8px",fontSize:11,border:"none",cursor:"pointer",background:w?"var(--bg-hover)":"var(--bg-selected)",color:w?"var(--text-muted)":"var(--text)",fontWeight:w?400:600},children:p("desktop.code")}),(0,r.jsx)("button",{onClick:()=>j(!0),style:{padding:"2px 8px",fontSize:11,border:"none",borderLeft:"1px solid var(--border)",cursor:"pointer",background:w?"var(--bg-selected)":"var(--bg-hover)",color:w?"var(--text)":"var(--text-muted)",fontWeight:w?600:400},children:p("desktop.preview")})]}),B&&"source"===S&&(0,r.jsxs)("div",{style:{display:"flex",borderRadius:5,overflow:"hidden",border:"1px solid var(--border)"},children:[(0,r.jsx)("button",{onClick:()=>j(!0),style:{padding:"2px 8px",fontSize:11,border:"none",cursor:"pointer",background:w?"var(--bg-selected)":"var(--bg-hover)",color:w?"var(--text)":"var(--text-muted)",fontWeight:w?600:400},children:p("desktop.preview")}),(0,r.jsx)("button",{onClick:()=>j(!1),style:{padding:"2px 8px",fontSize:11,border:"none",borderLeft:"1px solid var(--border)",cursor:"pointer",background:w?"var(--bg-hover)":"var(--bg-selected)",color:w?"var(--text-muted)":"var(--text)",fontWeight:w?400:600},children:p("desktop.raw")})]}),(i||a)&&(0,r.jsx)("button",{type:"button",onPointerDown:e=>e.preventDefault(),onClick:()=>{M&&a?O(M):i?.(en(e,t),!1)},title:M?p("desktop.mentionSelectedLines",{start:M.startLine,end:M.endLine}):p("desktop.mentionFile"),"aria-label":M?p("desktop.mentionSelectedLines",{start:M.startLine,end:M.endLine}):p("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,r.jsx)(s6,{filePath:e,sourceSessionId:o})]}),(0,r.jsx)("div",{ref:F,style:{flex:1,overflow:"auto",background:"var(--bg)"},children:"diff"===S&&q?L?(0,r.jsx)(it,{patch:x.patch}):(0,r.jsx)(ie,{oldContent:h,newContent:u.content}):H&&w?(0,r.jsx)("iframe",{srcDoc:u.content,sandbox:"allow-scripts",style:{width:"100%",height:"100%",border:"none",background:"var(--bg)"},title:p("desktop.htmlPreview")}):B&&w?(0,r.jsx)("div",{className:"markdown-body markdown-file-preview",style:{padding:"24px 32px"},children:(0,r.jsx)(tu.oz,{remarkPlugins:tZ,rehypePlugins:tQ,components:{h1:({children:e})=>(0,r.jsx)("h1",{id:tJ(e),children:e}),h2:({children:e})=>(0,r.jsx)("h2",{id:tJ(e),children:e}),h3:({children:e})=>(0,r.jsx)("h3",{id:tJ(e),children:e}),code({className:e,children:t,...o}){let n=e?.replace("language-","").toLowerCase()??"",s=String(t);return e?.includes("language-")||s.includes("\n")?"mermaid"===n?(0,r.jsx)(os,{code:s.replace(/\n$/,"")}):(0,r.jsx)(ol,{code:s.replace(/\n$/,""),lang:n}):(0,r.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,r.jsx)(r.Fragment,{children:e}),a({href:e,children:o,...n}){delete n.node;let i="text-(--accent-blue) underline underline-offset-2 hover:text-(--accent-blue)/80",a=s?ts(e,U,t??U):null;return a&&s?(0,r.jsx)("a",{href:e,...n,className:i,onClick:e=>{if(e.defaultPrevented||0!==e.button||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey)return;let t=e.currentTarget.getAttribute("target");t&&"_self"!==t||(e.preventDefault(),s(a))},children:o}):(0,r.jsx)("a",{href:e,...n,className:i,target:"_blank",rel:"noopener noreferrer",children:o})},table:({children:e})=>(0,r.jsx)("div",{className:"my-3 rounded-lg overflow-hidden border border-(--border)",children:(0,r.jsx)("div",{className:"overflow-x-auto",children:(0,r.jsx)("table",{className:"w-full text-sm border-collapse [&_tr:last-child>td]:border-b-0",children:e})})})},children:N})}):(0,r.jsx)(tg.A,{language:"text"===u.language?"plaintext":u.language,style:t0,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:T,children:u.content})})]})}let il={running:"var(--accent)",completed:"#22c55e",failed:"#ef4444",stopped:"#d97706"},id={running:"desktop.subagentsStatusRunning",completed:"desktop.subagentsStatusCompleted",failed:"desktop.subagentsStatusFailed",stopped:"desktop.subagentsStatusStopped"};function ic({agent:e,selected:t,onSelect:o}){let[s,i]=(0,n.useState)(!1),{t:a}=(0,E.s)(),[l,d]=(0,n.useState)(()=>Date.now());(0,n.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=il[e.status];return(0,r.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,r.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,r.jsx)("span",{style:{flexShrink:0,fontSize:10,fontFamily:"var(--font-mono)",fontWeight:600,color:"var(--text-dim)"},children:e.agentType}),(0,r.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,r.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,r.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),r=t%60;return r>0?`${o}m ${r}s`:`${o}m`}(c)}),(0,r.jsx)("span",{style:{flexShrink:0,fontSize:10,color:u},children:a(id[e.status])})]})}function ip({subagents:e,onSelect:t,selectedId:o}){let{t:s}=(0,E.s)(),[i,a]=(0,n.useState)(!0),l=e.filter(e=>"running"===e.status).length;return 0===e.length?(0,r.jsx)("div",{style:{padding:"18px 14px",fontSize:12,color:"var(--text-dim)",textAlign:"center"},children:s("desktop.subagentsEmpty")}):(0,r.jsxs)("section",{style:{flex:1,minHeight:0,display:"flex",flexDirection:"column",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",flexShrink:0,padding:"6px 10px",borderBottom:"1px solid var(--border)"},children:[(0,r.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,r.jsx)(k.K,{size:9,weight:"regular",style:{transform:i?"rotate(90deg)":"none",transition:"transform 0.15s",flexShrink:0},"aria-hidden":"true"}),(0,r.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:s("desktop.subagentsPanelTitle")})]}),l>0&&(0,r.jsxs)("span",{style:{marginRight:4,fontSize:10,fontFamily:"var(--font-mono)",color:"var(--accent)"},children:["● ",l," ",s("desktop.subagentsStatusRunning")]})]}),i&&(0,r.jsx)("div",{style:{flex:1,minHeight:0,overflowY:"auto",overflowX:"hidden",padding:"4px 0 8px"},children:e.map(e=>(0,r.jsx)(ic,{agent:e,selected:e.id===o,onSelect:t},e.id))})]})}var iu=o(31597);let ig={user:{label:"User",color:"var(--accent)"},assistant:{label:"Assistant",color:"var(--text)"},toolResult:{label:"Result",color:"var(--text-dim)"},bashExecution:{label:"Bash",color:"var(--text-muted)"}};function ih({line:e}){let t=ig[e.role]??ig.toolResult;return(0,r.jsxs)("div",{style:{marginBottom:6},children:[(0,r.jsxs)("div",{style:{fontSize:10.5,fontWeight:600,color:t.color,marginBottom:2,fontFamily:"var(--font-mono)"},children:["[",t.label,"]"]}),(0,r.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 ix({agent:e,cwd:t,onBack:o}){let{t:s}=(0,E.s)(),[i,a]=(0,n.useState)([]),[l,d]=(0,n.useState)(!0),[c,p]=(0,n.useState)(null),u=(0,n.useRef)(null),g=(0,n.useRef)(!0),h=(0,n.useCallback)(async(o=!1)=>{if(e.id&&t){o||d(!0);try{let r=new URLSearchParams({id:e.id,cwd:t}),n=await fetch(`/api/subagents/transcript?${r}`),s=await n.json();if(!n.ok||s.error){o||p(s.error??`HTTP ${n.status}`);return}a(s.lines??[]),p(null)}catch(e){o||p(e instanceof Error?e.message:String(e))}finally{d(!1)}}},[e.id,t]);(0,n.useEffect)(()=>{h()},[h]),(0,n.useEffect)(()=>{if("running"!==e.status)return;let t=setInterval(()=>void h(!0),2e3);return()=>clearInterval(t)},[e.status,h]),(0,n.useEffect)(()=>{let e=u.current;e&&g.current&&(e.scrollTop=e.scrollHeight)},[i]);let f=e.completedAt?e.completedAt-e.startedAt:void 0,x=e.tokens?.total??e.tokens?.input??e.tokens?.output,m="completed"===e.status?"#22c55e":"failed"===e.status?"#ef4444":"stopped"===e.status?"#d97706":"var(--accent)";return(0,r.jsxs)("div",{style:{flex:1,minHeight:0,display:"flex",flexDirection:"column"},children:[(0,r.jsxs)("div",{style:{flexShrink:0,borderBottom:"1px solid var(--border)",background:"var(--bg-panel)",padding:"6px 8px"},children:[(0,r.jsx)("div",{style:{display:"flex",alignItems:"center",gap:8},children:(0,r.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,r.jsx)(iu.Z,{size:12,"aria-hidden":"true"}),s("desktop.subagentsBack")]})}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6,marginTop:4,minWidth:0},children:[(0,r.jsx)("span",{"aria-hidden":"true",style:{width:8,height:8,flexShrink:0,borderRadius:"50%",background:m,boxShadow:"running"===e.status?`0 0 0 0 ${m}`:"none",animation:"running"===e.status?"subagent-pulse 1.4s ease-out infinite":"none"}}),(0,r.jsx)("span",{style:{fontSize:12,fontWeight:700,color:"var(--text)",fontFamily:"var(--font-mono)",flexShrink:0},children:e.agentType}),(0,r.jsx)("span",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:11.5,color:"var(--text-muted)"},children:e.description})]}),(0,r.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,r.jsxs)("span",{children:[e.toolUses," tool",1===e.toolUses?"":"s"]}),void 0!==x&&x>0&&(0,r.jsxs)("span",{children:[void 0===x?"":x>=1e6?`${(x/1e6).toFixed(1)}M`:x>=1e3?`${(x/1e3).toFixed(1)}k`:`${x}`," tokens"]}),void 0!==f&&(0,r.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),r=t%60;return r>0?`${o}m ${r}s`:`${o}m`}(f)}),(0,r.jsx)("span",{style:{color:m},children:s(`desktop.subagentsStatus${"running"===e.status?"Running":"completed"===e.status?"Completed":"failed"===e.status?"Failed":"Stopped"}`)})]})]}),(0,r.jsx)("div",{ref:u,onScroll:e=>{let t=e.currentTarget;g.current=t.scrollHeight-t.scrollTop-t.clientHeight<40},style:{flex:1,minHeight:0,overflowY:"auto",overflowX:"hidden",padding:"8px 10px",background:"var(--bg)"},children:l?(0,r.jsxs)("div",{style:{fontSize:12,color:"var(--text-dim)",padding:"12px 4px"},children:[s("desktop.loading"),"…"]}):c?(0,r.jsx)("div",{style:{fontSize:12,color:"#ef4444",padding:"12px 4px"},children:c}):0===i.length?(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-dim)",padding:"12px 4px"},children:s("running"===e.status?"desktop.subagentsWaitingFirstMessage":"desktop.subagentsNoTranscript")}):(0,r.jsx)("div",{style:{paddingBottom:8},children:i.map((e,t)=>(0,r.jsx)(ih,{line:e},t))})})]})}function im({tabs:e,activeTabId:t,onSelectTab:o,onCloseTab:s}){let{t:i}=(0,E.s)(),[a,l]=(0,n.useState)(null);return(0,r.jsx)("div",{style:{display:"flex",alignItems:"flex-end",background:"var(--bg-panel)",overflowX:"auto",flexShrink:0,height:36},children:e.map(e=>{let n=e.id===t;return(0,r.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:n?"var(--bg)":"var(--bg-panel)",cursor:"pointer",fontSize:12,color:n?"var(--text)":"var(--text-muted)",whiteSpace:"nowrap",maxWidth:180,minWidth:80,flexShrink:0,userSelect:"none",transition:"background 0.1s, color 0.1s"},children:[(0,r.jsx)("span",{style:{flexShrink:0,opacity:n?1:.7,display:"flex",alignItems:"center"},children:ee(e.label,13)}),(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",flex:1,fontWeight:n?500:400},title:e.filePath,children:e.label}),(0,r.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,r.jsx)(c.X,{size:11,"aria-hidden":"true"})})]},e.id)})})}var ik=o(27289),iv=o(93534),iy=o(45781),ib=o(68731),iw=o(93912),ij=o(23675),iS=o(48716),iC=o(47013),iT=o(51265);let iR={"restore-script":"restore","generate-cmd":"cmd",keep:"keep","keep-with-warning":"warning",manual:"manual"};function iz({cwd:e}){let{t}=(0,E.s)(),o=(0,n.useRef)(null),[s,i]=(0,n.useState)(!0),[a,l]=(0,n.useState)(!1),[d,c]=(0,n.useState)(!1),[p,u]=(0,n.useState)(null),[g,h]=(0,n.useState)(null),[f,x]=(0,n.useState)(new Set),[m,k]=(0,n.useState)(new Set),[v,y]=(0,n.useState)(!1),[b,w]=(0,n.useState)(null),[j,S]=(0,n.useState)(!1),[C,T]=(0,n.useState)(null),[R,z]=(0,n.useState)([]),[I,M]=(0,n.useState)(""),[P,D]=(0,n.useState)(null),[F,W]=(0,n.useState)(null);(0,n.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 $=(0,n.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="?([^";]+)"?/),r=URL.createObjectURL(t),n=document.createElement("a");n.href=r,n.download=o?.[1]??"pi-backup.zip",document.body.appendChild(n),n.click(),n.remove(),URL.revokeObjectURL(r)}catch{u(String(t("desktop.backupExportFailed")))}finally{c(!1)}},[s,a,t]),N=(0,n.useCallback)(async e=>{if(e){w(null),T(null),h(null);try{let o=new FormData;o.append("phase","parse"),o.append("file",e);let r=await fetch("/api/backup/import",{method:"POST",body:o}),n=await r.json();if(!r.ok||n.error)return void w(n.error??`HTTP ${r.status}`);if("preview"!==n.phase||!n.preview)return void w(String(t("desktop.backupImportFailed")));h(n),x(new Set(n.preview.categories)),k(new Set),y(!1)}catch{w(String(t("desktop.backupImportFailed")))}}},[t]),L=(0,n.useCallback)(async()=>{if(g){S(!0),w(null);try{let e=new FormData;e.append("phase","restore"),e.append("token",g.token),e.append("selections",JSON.stringify({categories:[...f],skippedMcpServers:[...m],reinstallNpm:v}));let r=await fetch("/api/backup/import",{method:"POST",body:e}),n=await r.json();if(!r.ok||n.error)return void w(n.error??`HTTP ${r.status}`);if("report"!==n.phase||!n.report)return void w(String(t("desktop.backupRestoreFailed")));T(n.report),h(null),o.current&&(o.current.value="")}catch{w(String(t("desktop.backupRestoreFailed")))}finally{S(!1)}}},[g,f,m,v,t]),A=(0,n.useCallback)(async o=>{if(o.installPrompt&&e){D(o.name),W(null);try{let t=I.indexOf("/"),r=t>0?I.slice(0,t):void 0,n=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:r,modelId:n})}),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{D(null)}}},[e,I,t]),O=e=>"win32"===e?"Windows":"darwin"===e?"macOS":"Linux";return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",flex:1,minWidth:0,minHeight:0,overflowY:"auto"},children:[(0,r.jsx)("header",{style:{padding:"18px 22px 14px",borderBottom:"1px solid var(--border)"},children:(0,r.jsx)("h1",{style:{margin:0,fontSize:16,fontWeight:700,color:"var(--text)"},children:t("desktop.backup")})}),(0,r.jsxs)("section",{style:{padding:"18px 22px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("h2",{style:{margin:0,fontSize:13,fontWeight:600,color:"var(--text)"},children:t("desktop.backupExportTitle")}),(0,r.jsx)("p",{style:{margin:"6px 0 12px",fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:t("desktop.backupExportDescription")}),(0,r.jsxs)("label",{style:{display:"flex",gap:8,alignItems:"flex-start",cursor:"pointer",marginBottom:8},children:[(0,r.jsx)("input",{type:"checkbox",checked:s,onChange:e=>i(e.target.checked),style:{marginTop:2}}),(0,r.jsxs)("span",{style:{fontSize:12,color:"var(--text)"},children:[t("desktop.backupIncludeSecrets"),(0,r.jsx)("span",{style:{display:"block",fontSize:11,color:"#ef4444"},children:t("desktop.backupSecretsWarning")})]})]}),(0,r.jsxs)("label",{style:{display:"flex",gap:8,alignItems:"flex-start",cursor:"pointer",marginBottom:14},children:[(0,r.jsx)("input",{type:"checkbox",checked:a,onChange:e=>l(e.target.checked),style:{marginTop:2}}),(0,r.jsxs)("span",{style:{fontSize:12,color:"var(--text)"},children:[t("desktop.backupIncludeSessions"),(0,r.jsx)("span",{style:{display:"block",fontSize:11,color:"var(--text-dim)"},children:t("desktop.backupSessionsHint")})]})]}),(0,r.jsxs)("button",{type:"button",onClick:$,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,r.jsx)(iC.f,{size:15,"aria-hidden":"true"}),d?t("desktop.backupExporting"):t("desktop.backupExportButton")]}),p&&(0,r.jsx)("p",{style:{margin:"8px 0 0",fontSize:11,color:"#ef4444"},children:p})]}),(0,r.jsxs)("section",{style:{padding:"18px 22px"},children:[(0,r.jsx)("h2",{style:{margin:0,fontSize:13,fontWeight:600,color:"var(--text)"},children:t("desktop.backupImportTitle")}),(0,r.jsx)("p",{style:{margin:"6px 0 12px",fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:t("desktop.backupImportDescription")}),(0,r.jsx)("input",{ref:o,type:"file",accept:".zip,application/zip",onChange:e=>N(e.target.files?.[0]),style:{display:"none"}}),(0,r.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,r.jsx)(iT._,{size:15,"aria-hidden":"true"}),t("desktop.backupImportButton")]}),b&&(0,r.jsx)("p",{style:{margin:"0 0 10px",fontSize:11,color:"#ef4444",lineHeight:1.5},children:b}),g&&(0,r.jsxs)("div",{style:{border:"1px solid var(--border)",borderRadius:8,padding:14,background:"var(--bg-panel)",display:"flex",flexDirection:"column",gap:12},children:[(0,r.jsxs)("div",{style:{fontSize:12,color:"var(--text-muted)",lineHeight:1.6},children:[(0,r.jsxs)("span",{style:{color:"var(--text)",fontWeight:600},children:[t("desktop.backupManifest"),":"]})," ",new Date(g.preview.manifest.createdAt).toLocaleString()," \xb7 ",O(g.preview.manifest.sourcePlatform)," →",O(navigator.platform.includes("Win")?"win32":navigator.platform.includes("Linux")?"linux":"darwin")," \xb7 pi-web ",g.preview.manifest.piWebVersion,g.preview.manifest.includeSecrets?"":` \xb7 ${t("desktop.backupNoSecrets")}`]}),(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{style:{fontSize:11,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:6},children:t("desktop.backupCategories")}),(0,r.jsx)("div",{style:{display:"flex",gap:14,flexWrap:"wrap"},children:g.preview.categories.map(e=>(0,r.jsxs)("label",{style:{display:"flex",gap:6,alignItems:"center",cursor:"pointer",fontSize:12,color:"var(--text)"},children:[(0,r.jsx)("input",{type:"checkbox",checked:f.has(e),onChange:t=>{let o=new Set(f);t.target.checked?o.add(e):o.delete(e),x(o)}}),t(`desktop.backupCategory${e}`)]},e))})]}),g.preview.servers.length>0&&(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{style:{fontSize:11,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:6},children:t("desktop.backupMcpServers")}),(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:g.preview.servers.map(o=>(0,r.jsxs)("div",{style:{display:"flex",alignItems:"flex-start",gap:8,fontSize:12},children:[(0,r.jsx)("input",{type:"checkbox",checked:!m.has(o.name),onChange:e=>{let t=new Set(m);e.target.checked?t.delete(o.name):t.add(o.name),k(t)},style:{marginTop:2}}),(0,r.jsxs)("div",{style:{flex:1,minWidth:0,display:"flex",flexDirection:"column",gap:2},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[(0,r.jsx)("code",{style:{fontSize:11,fontFamily:"var(--font-mono)",color:"var(--text)"},children:o.name}),(0,r.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:iR[o.action]})]}),(0,r.jsxs)("div",{style:{fontSize:11,color:"var(--text-dim)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[(0,r.jsx)("code",{style:{fontFamily:"var(--font-mono)"},children:o.original.command}),o.adapted&&o.adapted.command!==o.original.command&&(0,r.jsxs)(r.Fragment,{children:[" → ",(0,r.jsx)("code",{style:{fontFamily:"var(--font-mono)",color:"var(--text)"},children:o.adapted.command})]})]}),o.reason&&(0,r.jsx)("div",{style:{fontSize:11,color:"#ef4444"},children:o.reason}),"manual"===o.action&&o.installPrompt&&e&&(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,marginTop:2,flexWrap:"wrap"},children:[(0,r.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,r.jsxs)("option",{value:`${e.provider}/${e.id}`,children:[e.provider,"/",e.name||e.id]},`${e.provider}/${e.id}`))}),(0,r.jsx)("button",{type:"button",disabled:P===o.name,onClick:()=>A(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")}),F?.server===o.name&&(0,r.jsx)("a",{href:`?session=${encodeURIComponent(F.sessionId)}`,style:{fontSize:11,color:"var(--accent)"},children:t("desktop.backupOpenSession")})]})]})]},o.name))})]}),g.preview.npmPackages.length>0&&(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{style:{fontSize:11,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:6},children:t("desktop.backupNpmPackages")}),(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:4,marginBottom:6},children:g.preview.npmPackages.map(e=>(0,r.jsx)("code",{style:{fontSize:11,fontFamily:"var(--font-mono)",color:"var(--text)"},children:e},e))}),(0,r.jsxs)("label",{style:{display:"flex",gap:6,alignItems:"flex-start",cursor:"pointer",fontSize:12,color:"var(--text)",lineHeight:1.4},children:[(0,r.jsx)("input",{type:"checkbox",checked:v,onChange:e=>y(e.target.checked),style:{marginTop:2}}),(0,r.jsxs)("span",{children:[t("desktop.backupReinstallNpm"),(0,r.jsx)("span",{style:{display:"block",fontSize:11,color:"var(--text-dim)"},children:t("desktop.backupReinstallNpmHint")})]})]})]}),g.preview.warnings.length>0&&(0,r.jsx)("div",{style:{fontSize:11,color:"#ef4444",lineHeight:1.5},children:g.preview.warnings.map((e,t)=>(0,r.jsxs)("div",{children:["⚠ ",e]},t))}),(0,r.jsxs)("div",{style:{display:"flex",gap:8},children:[(0,r.jsxs)("button",{type:"button",onClick:L,disabled:j||0===f.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===f.size?.5:1},children:[(0,r.jsx)(iT._,{size:15,"aria-hidden":"true"}),j?t("desktop.backupRestoring"):t("desktop.backupRestoreButton")]}),(0,r.jsx)("button",{type:"button",onClick:()=>{h(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,r.jsxs)("div",{style:{border:"1px solid var(--border)",borderRadius:8,padding:14,background:"var(--bg-panel)",display:"flex",flexDirection:"column",gap:10},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,fontSize:13,fontWeight:600,color:"var(--text)"},children:[(0,r.jsx)(oj.W,{size:16,"aria-hidden":"true"}),t("desktop.backupRestoreReport")]}),C.restored.length>0&&(0,r.jsxs)("div",{children:[(0,r.jsxs)("div",{style:{fontSize:11,fontWeight:600,color:"#4ade80",marginBottom:4},children:["✓ ",t("desktop.backupReportRestored")]}),(0,r.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,r.jsxs)("div",{children:[(0,r.jsxs)("div",{style:{fontSize:11,fontWeight:600,color:"#fbbf24",marginBottom:4},children:["\uD83D\uDD04 ",t("desktop.backupReportRestart")]}),(0,r.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,r.jsxs)("div",{children:[(0,r.jsxs)("div",{style:{fontSize:11,fontWeight:600,color:"#ef4444",marginBottom:4},children:[(0,r.jsx)(_.N,{size:12,style:{verticalAlign:-2},"aria-hidden":"true"})," ",t("desktop.backupReportManual")]}),C.manual.map((e,t)=>(0,r.jsxs)("div",{style:{fontSize:11,color:"var(--text-muted)",lineHeight:1.6},children:[(0,r.jsx)("strong",{style:{color:"var(--text)"},children:e.server}),": ",e.message]},t))]}),C.warnings.length>0&&(0,r.jsx)("div",{style:{fontSize:11,color:"#ef4444",lineHeight:1.6},children:C.warnings.map((e,t)=>(0,r.jsxs)("div",{children:["⚠ ",e]},t))}),C.needsRestart.length>0&&(0,r.jsx)("p",{style:{margin:0,fontSize:11,color:"#fbbf24",lineHeight:1.5},children:t("desktop.backupRestartHint")})]})]})]})}let iI={position:"relative",width:40,height:22,borderRadius:11,border:"none",cursor:"pointer",padding:0,flexShrink:0,transition:"background 0.18s ease",outline:"none"},iM={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 iE({checked:e,onChange:t,label:o,description:n}){return(0,r.jsxs)("label",{style:{display:"flex",alignItems:n?"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,r.jsxs)("span",{style:{flex:1,minWidth:0},children:[(0,r.jsx)("span",{style:{display:"block",fontSize:13,fontWeight:550,color:"var(--text)",lineHeight:1.4},children:o}),n&&(0,r.jsx)("span",{style:{display:"block",fontSize:11,lineHeight:1.5,color:"var(--text-muted)",marginTop:2},children:n})]}),(0,r.jsx)("button",{type:"button",role:"switch","aria-checked":e,onClick:o=>{o.preventDefault(),t(!e)},style:{...iI,background:e?"var(--accent)":"color-mix(in srgb, var(--border) 70%, var(--bg))"},children:(0,r.jsx)("span",{style:{...iM,left:e?21:3}})})]})}function iP({title:e,description:t,children:o}){return(0,r.jsxs)("section",{style:{padding:"20px 22px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("h2",{style:{margin:0,fontSize:14,fontWeight:650,color:"var(--text)"},children:e}),(0,r.jsx)("p",{style:{margin:"5px 0 14px",fontSize:12,lineHeight:1.5,color:"var(--text-muted)"},children:t}),(0,r.jsx)("div",{children:o})]})}let iD="pi-input-shortcut";function iF(){try{let e=localStorage.getItem(iD);return"ctrl-enter"===e?"ctrl-enter":"enter"}catch{return"enter"}}function iW(){let{t:e}=(0,E.s)(),[t,o]=(0,n.useState)(iF);(0,n.useEffect)(()=>{let e=()=>o(iF());return window.addEventListener("storage",e),()=>window.removeEventListener("storage",e)},[]);let s=(0,n.useCallback)(e=>{o(e);try{localStorage.setItem(iD,e),window.dispatchEvent(new StorageEvent("storage",{key:iD,newValue:e}))}catch{}},[]);return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",flex:1,minWidth:0,minHeight:0,overflowY:"auto"},children:[(0,r.jsx)("header",{style:{padding:"18px 22px 14px",borderBottom:"1px solid var(--border)"},children:(0,r.jsx)("h1",{style:{margin:0,fontSize:16,fontWeight:700,color:"var(--text)"},children:e("desktop.chat")})}),(0,r.jsx)(iP,{title:e("desktop.inputShortcut"),description:e("desktop.inputShortcutDescription"),children:(0,r.jsx)(iE,{checked:"ctrl-enter"===t,onChange:e=>s(e?"ctrl-enter":"enter"),label:e("desktop.useCtrlEnter"),description:e("desktop.useCtrlEnterDescription")})})]})}var i$=o(95650),iN=o(55803),iL=o(23602),iA=o(18613),iO=o(12779);let iH={display:"flex",gap:6,flexWrap:"wrap"};function iB(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 iU({icon:e,label:t,actions:o}){return(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:10,width:"100%"},children:[(0,r.jsx)("span",{style:{color:"var(--text-dim)",display:"inline-flex",flexShrink:0},children:e}),(0,r.jsx)("span",{style:{fontSize:11,fontWeight:700,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.06em"},children:t}),o&&(0,r.jsx)("span",{style:{display:"inline-flex",alignItems:"center",gap:12,marginLeft:"auto"},children:o})]})}let i_={display:"inline-flex",alignItems:"center",gap:6,padding:0,border:0,background:"transparent",color:"var(--accent)",fontSize:11,cursor:"pointer",whiteSpace:"nowrap"},iq={onMouseEnter:e=>{e.currentTarget.style.textDecoration="underline"},onMouseLeave:e=>{e.currentTarget.style.textDecoration="none"}};function iV({title:e,description:t,children:o}){return(0,r.jsxs)("section",{style:{padding:"20px 22px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("h2",{style:{margin:0,fontSize:14,fontWeight:650,color:"var(--text)"},children:e}),(0,r.jsx)("p",{style:{margin:"5px 0 16px",fontSize:12,lineHeight:1.5,color:"var(--text-muted)"},children:t}),o]})}function iK({depth:e}){let t=e/100;return(0,r.jsxs)("svg",{width:14,height:14,viewBox:"0 0 14 14",style:{flexShrink:0},children:[(0,r.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,r.jsx)("rect",{x:4,y:4,width:6,height:6,rx:1,style:{fill:"var(--text-dim)",opacity:.05+.35*t}})]})}function iJ({hasDark:e,hasLight:t,darkColor:o,lightColor:n,t:s}){return(0,r.jsxs)("span",{style:{display:"inline-flex",gap:3,alignItems:"center",flexShrink:0},children:[e&&(0,r.jsx)("span",{title:s("desktop.darkVariant"),style:{display:"inline-block",width:7,height:7,borderRadius:"50%",background:o??"#7c6f64"}}),t&&(0,r.jsx)("span",{title:s("desktop.lightVariant"),style:{display:"inline-block",width:7,height:7,borderRadius:"50%",background:n??"#d5c4a1",border:"1px solid rgba(0,0,0,0.1)"}})]})}function iG(){let{mode:e,resolvedMode:t,themeName:o,setMode:s,setTheme:i,previewTheme:a,clearPreview:l,isThemeCached:d,borderDepth:c,setBorderDepth:p}=tL(),{locale:u,setLocale:g,t:h}=(0,E.s)(),[f,x]=(0,n.useState)([]),[m,k]=(0,n.useState)(!0),[v,y]=(0,n.useState)(null),[b,w]=(0,n.useState)(null);(0,n.useEffect)(()=>{let e=!1;return fetch("/api/themes").then(e=>e.ok?e.json():null).then(t=>{!e&&t&&x(t.themeSets)}).catch(()=>{}).finally(()=>{e||k(!1)}),()=>{e=!0}},[]);let j=(0,n.useCallback)(e=>{y(e),i(e).finally(()=>y(null))},[i]),S=(0,n.useRef)(null),C=(0,n.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,n.useCallback)(e=>{s(e)},[s]),R=(0,n.useCallback)(()=>{window.piDesktop?.openThemeFolder()},[]),z=(0,n.useCallback)(()=>{window.piDesktop?window.piDesktop.openThemeDocs():window.open("https://pi.dev/docs/latest/themes","_blank","noopener,noreferrer")},[]);return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",flex:1,minWidth:0,minHeight:0,overflowY:"auto"},children:[(0,r.jsx)("header",{style:{padding:"18px 22px 14px",borderBottom:"1px solid var(--border)"},children:(0,r.jsx)("h1",{style:{margin:0,fontSize:16,fontWeight:700,color:"var(--text)"},children:h("desktop.display")})}),(0,r.jsxs)(iV,{title:h("desktop.theme"),description:h("desktop.themeDescription"),children:[(0,r.jsx)(iU,{icon:(0,r.jsx)(i$.p,{size:14,weight:"fill"}),label:h("desktop.colorScheme"),actions:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("button",{type:"button",onClick:R,style:i_,...iq,children:[(0,r.jsx)(iN.N,{size:12,weight:"regular","aria-hidden":"true"}),h("desktop.openThemeFolder")]}),(0,r.jsxs)("button",{type:"button",onClick:z,style:i_,...iq,children:[(0,r.jsx)(iL.B,{size:12,weight:"regular","aria-hidden":"true"}),h("desktop.learnPiThemes")]})]})}),m?(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-dim)"},children:h("desktop.loadingThemes")}):(0,r.jsxs)("div",{style:iH,children:[(0,r.jsx)("button",{type:"button",onClick:()=>j(""),disabled:null!==v,style:iB(""===o,"__default__"===b,null!==v),onMouseEnter:()=>C(""),onMouseLeave:()=>C(null),children:h("desktop.defaultTheme")}),f.map(e=>(0,r.jsxs)("button",{type:"button",onClick:()=>j(e.name),disabled:null!==v,style:iB(o===e.name,b===e.name,v===e.name),onMouseEnter:()=>C(e.name),onMouseLeave:()=>C(null),children:[e.displayName,(0,r.jsx)(iJ,{hasDark:e.hasDark,hasLight:e.hasLight,darkColor:e.accent,lightColor:e.accentLight,t:h})]},e.name))]}),(0,r.jsxs)("div",{style:{marginTop:20},children:[(0,r.jsx)(iU,{icon:(0,r.jsx)(iK,{depth:c}),label:`${h("desktop.borderVisibility")} (${c})`}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10},children:[(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",flexShrink:0},children:h("desktop.borderSubtle")}),(0,r.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,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",flexShrink:0},children:h("desktop.borderBold")})]}),(0,r.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,r.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,r.jsxs)("div",{style:{marginTop:20},children:[(0,r.jsx)(iU,{icon:"dark"===t?(0,r.jsx)(iA.A,{size:14,weight:"fill"}):(0,r.jsx)(iO.b,{size:14,weight:"fill"}),label:h("desktop.appearanceMode")}),(0,r.jsx)("div",{style:iH,children:[{value:"light",icon:(0,r.jsx)(iO.b,{size:15,weight:"light"===e?"fill":"regular"})},{value:"dark",icon:(0,r.jsx)(iA.A,{size:15,weight:"dark"===e?"fill":"regular"})},{value:"system",icon:(0,r.jsx)(iv.V,{size:15,weight:"system"===e?"fill":"regular"})}].map(t=>{let o=e===t.value;return(0,r.jsxs)("button",{type:"button",onClick:()=>T(t.value),style:iB(o,b===`mode:${t.value}`),onMouseEnter:()=>w(`mode:${t.value}`),onMouseLeave:()=>w(null),children:[t.icon,h(`desktop.${t.value}`)]},t.value)})})]}),!m&&0===f.length&&(0,r.jsxs)("p",{style:{margin:"14px 0 0",fontSize:11,color:"var(--text-dim)",lineHeight:1.5},children:[h("desktop.noCustomThemes")," ",h("desktop.noCustomThemesHint")," ",(0,r.jsx)("code",{style:{fontSize:10,background:"var(--bg-secondary)",padding:"1px 5px",borderRadius:3,fontFamily:"var(--font-mono)"},children:"~/.pi/agent/themes/*.json"})," ",h("desktop.noCustomThemesHint2")]})]}),(0,r.jsx)(iV,{title:h("desktop.language"),description:h("desktop.languageDescription"),children:(0,r.jsx)("div",{style:iH,children:["en","zh-CN"].map(e=>(0,r.jsx)("button",{type:"button",onClick:()=>g("zh-CN"===e?"zh-CN":"en"),style:iB("zh-CN"===e?"zh-CN"===u:"zh-CN"!==u,b===`lang:${e}`),onMouseEnter:()=>w(`lang:${e}`),onMouseLeave:()=>w(null),children:"en"===e?h("desktop.english"):h("desktop.chinese")},e))})})]})}var iY=o(94638);function iX({children:e}){return(0,r.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 iZ({children:e}){return(0,r.jsx)("div",{style:{padding:"0 14px"},children:(0,r.jsx)("div",{style:{borderBottom:"1px solid var(--border)"},children:e})})}function iQ({children:e}){return(0,r.jsx)("div",{style:{padding:"0 14px"},children:e})}function i0({children:e}){return(0,r.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 i1=[{value:"normal",labelKey:"modes.collabNormal"},{value:"plan",labelKey:"modes.collabPlan"},{value:"goal",labelKey:"modes.collabGoal"}],i2=[{value:"economy",labelKey:"modes.tokenEconomy"},{value:"full",labelKey:"modes.tokenFull"},{value:"delivery",labelKey:"modes.tokenDelivery"}],i4=[{value:"ask",labelKey:"modes.approvalAsk"},{value:"auto",labelKey:"modes.approvalAuto"},{value:"yolo",labelKey:"modes.approvalYolo"}];function i6({options:e,value:t,onChange:o,disabled:n,accentFor:s}){let{t:i}=(0,E.s)();return(0,r.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,r.jsx)("button",{type:"button",role:"radio","aria-checked":a,disabled:n,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:n?"not-allowed":"pointer",fontSize:11.5,fontWeight:a?650:500,opacity:n?.5:1,whiteSpace:"nowrap",transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{a||n||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{a||(e.currentTarget.style.background="none")},children:i(e.labelKey)},e.value)})})}function i5(){let{t:e}=(0,E.s)(),[t,o]=(0,n.useState)({tasksBoard:!0}),[s,i]=(0,n.useState)(null),[a,l]=(0,n.useState)(!1),[d,c]=(0,n.useState)(!1);(0,n.useEffect)(()=>{let e=!1;return(async()=>{try{let[t,r]=await Promise.all([fetch("/api/features"),fetch("/api/modes")]);if(!e&&t.ok){let e=await t.json();o(t=>({...t,...e}))}if(!e&&r.ok){let e=await r.json();i({collaborationMode:ez(e.collaborationMode),tokenMode:eI(e.tokenMode),toolApprovalMode:eM(e.toolApprovalMode),permissionRules:e.permissionRules??{allow:[],ask:[],deny:[]}})}e||l(!0)}catch{}})(),()=>{e=!0}},[]);let p=(0,n.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,n.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:ez(e.modes?.collaborationMode??t.collaborationMode),tokenMode:eI(e.modes?.tokenMode??t.tokenMode),toolApprovalMode:eM(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,r.jsx)("div",{style:{flex:1,overflow:"auto",minWidth:0,padding:"20px 22px",display:"flex",flexDirection:"column",gap:16},children:(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[a?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(iX,{children:(0,r.jsx)(iQ,{children:(0,r.jsx)(iE,{checked:t.tasksBoard,onChange:e=>void p(e),label:(0,r.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:6},children:[(0,r.jsx)(iY.x,{size:14,"aria-hidden":"true"}),e("desktop.featuresTasksBoard"),(0,r.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,r.jsxs)(iX,{children:[(0,r.jsx)(iZ,{children:(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:16,padding:"12px 0"},children:[(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:13,fontWeight:600,color:"var(--text)"},children:e("desktop.featuresCollabDefault")}),(0,r.jsx)("div",{style:{fontSize:11,color:"var(--text-muted)",marginTop:2},children:e("desktop.featuresCollabDefaultDesc")})]}),(0,r.jsx)(i6,{options:i1,value:s.collaborationMode,onChange:e=>void u({collaborationMode:e}),disabled:d})]})}),(0,r.jsx)(iZ,{children:(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:16,padding:"12px 0"},children:[(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:13,fontWeight:600,color:"var(--text)"},children:e("desktop.featuresTokenDefault")}),(0,r.jsx)("div",{style:{fontSize:11,color:"var(--text-muted)",marginTop:2},children:e("desktop.featuresTokenDefaultDesc")})]}),(0,r.jsx)(i6,{options:i2,value:s.tokenMode,onChange:e=>void u({tokenMode:e}),disabled:d})]})}),(0,r.jsx)(iQ,{children:(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:16,padding:"12px 0"},children:[(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:13,fontWeight:600,color:"var(--text)"},children:e("desktop.featuresApprovalDefault")}),(0,r.jsx)("div",{style:{fontSize:11,color:"var(--text-muted)",marginTop:2},children:e("desktop.featuresApprovalDefaultDesc")})]}),(0,r.jsx)(i6,{options:i4,value:s.toolApprovalMode,onChange:e=>void u({toolApprovalMode:e}),disabled:d,accentFor:e=>"yolo"===e?"var(--accent-red, #ef4444)":void 0})]})})]})]}):(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)"},children:e("desktop.featuresLoading")}),(0,r.jsx)(i0,{children:e("desktop.featuresDesc")}),d&&(0,r.jsx)("div",{style:{padding:"0 2px",fontSize:11,color:"var(--text-muted)"},children:e("desktop.featuresSaving")})]})})}var i3=o(76553);function i8({open:e,onClose:t,children:o}){let[s,i]=(0,n.useState)(!1),[a,l]=(0,n.useState)(!1);return((0,n.useEffect)(()=>{if(e)l(!0),requestAnimationFrame(()=>requestAnimationFrame(()=>i(!0)));else{i(!1);let e=setTimeout(()=>l(!1),250);return()=>clearTimeout(e)}},[e]),a)?(0,r.jsxs)(r.Fragment,{children:[(0,r.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,r.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,r.jsx)("div",{style:{display:"flex",justifyContent:"center",padding:"10px 0 4px",flexShrink:0},children:(0,r.jsx)("div",{style:{width:36,height:4,borderRadius:2,background:"var(--border)"}})}),(0,r.jsx)("div",{style:{flex:1,overflow:"auto",minHeight:0},children:o})]})]}):null}function i7({onSessionsChanged:e}){let{t}=(0,E.s)(),o=$(),[s,i]=(0,n.useState)(null),[a,l]=(0,n.useState)([]),[d,p]=(0,n.useState)([]),[u,g]=(0,n.useState)(new Set),[h,f]=(0,n.useState)(null),[x,m]=(0,n.useState)({imported:0,skipped:0,errors:0,total:0,done:!1}),[k,v]=(0,n.useState)([]),[y,b]=(0,n.useState)(!1),[w,j]=(0,n.useState)({done:0,total:0}),[S,C]=(0,n.useState)(!1),[T,R]=(0,n.useState)(null),[I,M]=(0,n.useState)(!1),P=(0,n.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&&(p(t.reasonix.projects),i("reasonix"))}catch(e){R(e instanceof Error?e.message:String(e))}finally{C(!1)}},[]),[D,F]=(0,n.useState)(!1);(0,n.useEffect)(()=>{D||(F(!0),P())},[D,P]);let W=(0,n.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}`);f(t.jobId)}catch(e){R(e instanceof Error?e.message:String(e))}finally{C(!1)}}},[s,u]);(0,n.useEffect)(()=>{let t;if(!h)return;let o=!0,r=async()=>{if(o)try{let n=await fetch(`/api/import/status?jobId=${encodeURIComponent(h)}`),s=await n.json();if(!o)return;m({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(r,800))}catch{o&&(t=setTimeout(r,2e3))}};return r(),()=>{o=!1,clearTimeout(t)}},[h,e]);let N=(0,n.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})}}},r=Array.from({length:Math.min(4,k.length)},o);await Promise.all(r),b(!1),e?.()},[k,e]);if(x.done&&k.length>0)return(0,r.jsxs)("div",{style:{padding:"18px 22px",display:"flex",flexDirection:"column",gap:14},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10},children:[(0,r.jsx)(oZ.r,{size:20,weight:"fill",style:{color:"#4ade80"}}),(0,r.jsx)("span",{style:{fontSize:14,fontWeight:600,color:"var(--text)"},children:t("desktop.importDone")??"导入完成"})]}),(0,r.jsxs)("div",{style:{fontSize:12,color:"var(--text-muted)",lineHeight:1.6},children:[t("desktop.importedSummary",{imported:x.imported})??`成功导入 ${x.imported} 个会话`,x.skipped>0&&(0,r.jsx)("span",{style:{marginLeft:8},children:t("desktop.importSkippedCount",{skipped:x.skipped})??`,${x.skipped} 个跳过`}),x.errors>0&&(0,r.jsx)("span",{style:{marginLeft:8,color:"#ef4444"},children:t("desktop.importErrorsCount",{errors:x.errors})??`,${x.errors} 个失败`})]}),y?(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,fontSize:12,color:"var(--text-muted)"},children:[(0,r.jsx)(B.y,{size:14,style:{animation:"spin 1s linear infinite"}}),t("desktop.importGeneratingTitles")??"正在生成标题…"," ","(",w.done,"/",w.total,")"]}):(0,r.jsxs)("button",{type:"button",onClick:N,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,r.jsx)(i3.o,{size:15}),t("desktop.importGenerateTitles")??"为导入的会话生成标题"]}),(0,r.jsx)("button",{type:"button",onClick:()=>{f(null),m({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 L=(0,r.jsxs)("div",{style:{padding:o?"12px 18px":"18px 22px",display:"flex",flexDirection:"column",gap:14},children:[T&&(0,r.jsxs)("div",{style:{display:"flex",alignItems:"flex-start",gap:8,fontSize:12,color:"#ef4444",lineHeight:1.5},children:[(0,r.jsx)(_.N,{size:14,style:{flexShrink:0,marginTop:1}}),(0,r.jsx)("span",{children:T})]}),!h&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)",lineHeight:1.6},children:t("desktop.importSessionsDesc")??"从其他 AI 编码工具导入历史对话记录到 pi-web。目前支持 Reasonix,更多工具陆续支持中。"}),(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:a.map(e=>(0,r.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,r.jsx)("input",{type:"radio",name:"import-source",value:e.key,checked:s===e.key,disabled:"available"!==e.status,onChange:()=>i(e.key)}),(0,r.jsxs)("div",{style:{flex:1},children:[(0,r.jsx)("div",{style:{fontSize:13,fontWeight:600,color:"var(--text)"},children:e.label}),"coming-soon"===e.status&&(0,r.jsx)("div",{style:{fontSize:11,color:"var(--text-dim)",marginTop:1},children:t("desktop.comingSoon")??"即将支持"})]}),"reasonix"===e.key&&d.length>0&&(0,r.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,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[(0,r.jsx)("span",{style:{fontSize:12,fontWeight:600,color:"var(--text)"},children:t("desktop.importSelectProjects")??"选择要导入的项目"}),(0,r.jsx)("button",{type:"button",onClick:()=>g(new Set(d.map(e=>e.name))),style:i9,children:t("desktop.importSelectAll")??"全选"}),(0,r.jsx)("button",{type:"button",onClick:()=>g(new Set),style:i9,children:t("desktop.importDeselectAll")??"取消全选"})]}),(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:4},children:d.map(e=>(0,r.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,r.jsx)("input",{type:"checkbox",checked:u.has(e.name),onChange:()=>{var t;return t=e.name,void g(e=>{let o=new Set(e);return o.has(t)?o.delete(t):o.add(t),o})}}),(0,r.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:500,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name}),(0,r.jsxs)("div",{style:{fontSize:11,color:"var(--text-dim)",marginTop:2},children:[e.sessions," ",t("desktop.sessions")??"会话",e.matched&&(0,r.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,r.jsxs)("span",{style:{marginLeft:8,color:"var(--text-muted)"},children:["→ ",t("desktop.importNewProject")??"新建项目"]})]})]})]},e.name))}),(0,r.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,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(B.y,{size:14,style:{animation:"spin 1s linear infinite"}})," ",t("desktop.importing")??"导入中…"]}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(z.z,{size:15})," ",t("desktop.importStart")??"开始导入"]})})]}),"reasonix"===s&&0===d.length&&!S&&(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)",padding:"12px 0"},children:t("desktop.importNoData")??"未找到 Reasonix 数据。请确认 ~/.reasonix/projects/ 目录存在且包含会话文件。"})]}),h&&!x.done&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,fontSize:12,color:"var(--text)"},children:[(0,r.jsx)(B.y,{size:14,style:{animation:"spin 1s linear infinite"}}),t("desktop.importing")??"导入中…"]}),(0,r.jsx)("div",{style:{height:6,borderRadius:3,background:"var(--bg-panel)",overflow:"hidden"},children:(0,r.jsx)("div",{style:{height:"100%",borderRadius:3,background:"var(--accent)",width:`${x.total>0?(x.imported+x.skipped+x.errors)/x.total*100:0}%`,transition:"width 0.3s ease"}})}),(0,r.jsxs)("div",{style:{fontSize:11,color:"var(--text-dim)"},children:[x.imported+x.skipped+x.errors," / ",x.total,x.skipped>0&&` \xb7 ${t("desktop.importSkippedCount",{skipped:x.skipped})??`${x.skipped} 跳过`}`]})]})]});return o?(0,r.jsxs)(r.Fragment,{children:[(0,r.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,r.jsx)(z.z,{size:16}),(0,r.jsx)("span",{style:{fontWeight:500},children:t("desktop.importSessions")??"导入会话"})]}),(0,r.jsxs)(i8,{open:I,onClose:()=>M(!1),children:[(0,r.jsxs)("div",{style:{padding:"4px 18px 14px",borderBottom:"1px solid var(--border)",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[(0,r.jsx)("span",{style:{fontSize:15,fontWeight:700,color:"var(--text)"},children:t("desktop.importSessions")??"导入会话"}),(0,r.jsx)("button",{onClick:()=>M(!1),style:ae,children:(0,r.jsx)(c.X,{size:18})})]}),L]})]}):L}let i9={background:"none",border:"none",color:"var(--accent)",fontSize:11,cursor:"pointer",padding:"2px 4px"},ae={background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",padding:4,display:"flex"},at="deepseek-vision",ao={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 ar(){return{fontSize:12,color:"var(--text-muted)"}}let an={padding:"7px 12px",border:"none",borderRadius:6,background:"var(--accent)",color:"#fff",cursor:"pointer",fontSize:12};function as({sessionId:e}){let{t}=(0,E.s)(),[o,s]=(0,n.useState)(!1),[i,a]=(0,n.useState)(null),[l,d]=(0,n.useState)(!1),[c,p]=(0,n.useState)(null),[u,g]=(0,n.useState)(!1),[h,f]=(0,n.useState)({}),[x,m]=(0,n.useState)(""),[k,v]=(0,n.useState)(""),[y,b]=(0,n.useState)("eager"),[w,j]=(0,n.useState)(!1),[S,C]=(0,n.useState)(null),[T,R]=(0,n.useState)(!1),[z,I]=(0,n.useState)(!1),[M,P]=(0,n.useState)({provider:"custom",baseUrl:"",apiKey:"",model:"",maxTokens:4096,hasApiKey:!1}),[D,F]=(0,n.useState)(""),[W,$]=(0,n.useState)(""),[N,L]=(0,n.useState)(!1),[A,O]=(0,n.useState)(null),[H,B]=(0,n.useState)(!1);(0,n.useEffect)(()=>{let e=!1;return(async()=>{a(null);try{let[t,o]=await Promise.all([fetch("/api/mcp"),fetch("/api/vision-config")]),r=await t.json();if(!t.ok||r.error)throw Error(r.error??`HTTP ${t.status}`);let n=await o.json();if(!o.ok||n.error)throw Error(n.error??`HTTP ${o.status}`);if(e)return;f(r.mcpServers??{}),m(r.filePath);let i=(r.mcpServers??{})[at];v(i?.command??""),b(i?.lifecycle==="lazy"?"lazy":"eager"),P({provider:n.provider,baseUrl:n.baseUrl,apiKey:"",model:n.model,maxTokens:n.maxTokens,hasApiKey:n.hasApiKey}),n.path&&$(n.path),s(!0)}catch(t){e||a(t instanceof Error?t.message:String(t))}})(),()=>{e=!0}},[]);let U=(0,n.useCallback)(async()=>{if(!k.trim())return void C(t("desktop.mcpVisionCommandRequired"));j(!0),C(null),R(!1),I(!1);try{let e=h[at],t={...h,[at]:{...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})}),r=await o.json();if(!o.ok||r.error)throw Error(r.error??`HTTP ${o.status}`);f(t),R(!0)}catch(e){C(e instanceof Error?e.message:String(e))}finally{j(!1)}},[h,k,y,t]),_=(0,n.useCallback)(async()=>{j(!0),C(null),R(!1),I(!1);try{let e={...h};delete e[at];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}`);f(e),v(""),b("eager"),I(!0)}catch(e){C(e instanceof Error?e.message:String(e))}finally{j(!1)}},[h]),q=(0,n.useCallback)(async()=>{L(!0),O(null),B(!1);try{let e=await fetch("/api/vision-config",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({...M,...D?{apiKey:D}:{}})}),t=await e.json();if(!e.ok||t.error)throw Error(t.error??`HTTP ${e.status}`);P({...t,apiKey:"",hasApiKey:t.hasApiKey}),F(""),B(!0)}catch(e){O(e instanceof Error?e.message:String(e))}finally{L(!1)}},[M,D]),V=(0,n.useCallback)(async()=>{if(e){d(!0),p(null),g(!1);try{let t=await fetch("/api/mcp/restart",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:e,name:at})}),o=await t.json();if(!t.ok||o.error)throw Error(o.error??`HTTP ${t.status}`);g(!0)}catch(e){p(e instanceof Error?e.message:String(e))}finally{d(!1)}}},[e]),K=!!h[at];return(0,r.jsxs)(iX,{children:[(0,r.jsx)(iZ,{children:(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:7,padding:"12px 0"},children:[(0,r.jsx)(r5.k,{size:15,"aria-hidden":"true"}),(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[(0,r.jsx)("span",{style:{fontSize:13,fontWeight:600,color:"var(--text)"},children:t("desktop.mcpVisionTitle")}),(0,r.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,r.jsx)("div",{style:{fontSize:11,color:"var(--text-muted)",marginTop:2},children:t("desktop.mcpVisionDesc")})]})]})}),o?i?(0,r.jsx)(iQ,{children:(0,r.jsx)("div",{style:{padding:"8px 0",fontSize:12,color:"#ef4444"},children:i})}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(iZ,{children:(0,r.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)",padding:"10px 0 2px"},children:t("desktop.mcpVisionRegistration")})}),(0,r.jsx)(iZ,{children:(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"minmax(120px, 180px) 1fr",gap:8,alignItems:"center",padding:"6px 0"},children:[(0,r.jsxs)("span",{style:ar(),children:[t("desktop.mcpVisionCommand")," *"]}),(0,r.jsx)("input",{value:k,onChange:e=>v(e.target.value),placeholder:"/path/to/deepseek-vision-mcp",style:ao}),(0,r.jsx)("span",{style:ar(),children:t("desktop.mcpVisionLifecycle")}),(0,r.jsxs)("select",{value:y,onChange:e=>b(e.target.value),style:{...ao,fontFamily:"var(--font-mono)"},children:[(0,r.jsx)("option",{value:"eager",children:"eager"}),(0,r.jsx)("option",{value:"lazy",children:"lazy"})]}),(0,r.jsx)("span",{style:ar(),children:t("desktop.mcpVisionTransport")}),(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)",fontFamily:"var(--font-mono)",padding:"7px 0"},children:t("desktop.mcpVisionTransportFixed")})]})}),(0,r.jsx)(iZ,{children:(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"6px 0",flexWrap:"wrap"},children:[(0,r.jsx)("button",{type:"button",onClick:()=>void U(),disabled:w,style:{...an,cursor:w?"wait":"pointer"},children:w?t("desktop.saving"):t("desktop.mcpVisionSaveReg")}),K&&(0,r.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,r.jsx)("span",{style:{color:"#22c55e",fontSize:12},children:t("desktop.mcpVisionSavedReg")}),z&&(0,r.jsx)("span",{style:{color:"#22c55e",fontSize:12},children:t("desktop.mcpVisionRemoved")}),S&&(0,r.jsx)("span",{style:{color:"#ef4444",fontSize:12},children:S})]})}),(0,r.jsx)(iZ,{children:(0,r.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)",padding:"10px 0 2px"},children:t("desktop.mcpVisionModelConfig")})}),(0,r.jsx)(iZ,{children:(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"minmax(120px, 180px) 1fr",gap:8,alignItems:"center",padding:"6px 0"},children:[(0,r.jsx)("span",{style:ar(),children:t("desktop.mcpVisionProvider")}),(0,r.jsx)("input",{value:M.provider,onChange:e=>P(t=>({...t,provider:e.target.value})),style:ao}),(0,r.jsx)("span",{style:ar(),children:t("desktop.mcpVisionBaseUrl")}),(0,r.jsx)("input",{value:M.baseUrl,onChange:e=>P(t=>({...t,baseUrl:e.target.value})),style:ao}),(0,r.jsx)("span",{style:ar(),children:t("desktop.mcpVisionApiKey")}),(0,r.jsx)("input",{type:"password",value:D,onChange:e=>F(e.target.value),placeholder:M.hasApiKey?"••••••••":"API key",style:ao}),(0,r.jsx)("span",{style:ar(),children:t("desktop.mcpVisionModel")}),(0,r.jsx)("input",{value:M.model,onChange:e=>P(t=>({...t,model:e.target.value})),style:ao}),(0,r.jsx)("span",{style:ar(),children:t("desktop.mcpVisionMaxTokens")}),(0,r.jsx)("input",{type:"number",min:1,value:M.maxTokens,onChange:e=>P(t=>({...t,maxTokens:Number(e.target.value)||1})),style:ao})]})}),(0,r.jsx)(iQ,{children:(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:8,padding:"6px 0"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:[(0,r.jsx)("button",{type:"button",onClick:()=>void q(),disabled:N,style:{...an,cursor:N?"wait":"pointer"},children:N?t("desktop.saving"):t("desktop.mcpVisionSaveModel")}),(0,r.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,r.jsx)("span",{style:{color:"#22c55e",fontSize:12},children:t("desktop.mcpVisionSavedModel")}),u&&(0,r.jsx)("span",{style:{color:"#22c55e",fontSize:12},children:t("desktop.mcpVisionRestarted")}),A&&(0,r.jsx)("span",{style:{color:"#ef4444",fontSize:12},children:A}),c&&(0,r.jsx)("span",{style:{color:"#ef4444",fontSize:12},children:c})]}),(0,r.jsxs)(i0,{children:[t("desktop.mcpVisionModelNote"),W&&(0,r.jsx)("div",{style:{marginTop:4,fontFamily:"var(--font-mono)",fontSize:10},children:W}),x&&(0,r.jsx)("div",{style:{fontFamily:"var(--font-mono)",fontSize:10},children:x})]})]})})]}):(0,r.jsx)(iQ,{children:(0,r.jsx)("div",{style:{padding:"8px 0",fontSize:12,color:"var(--text-muted)"},children:t("desktop.loading")})})]})}function ai({sessionId:e,onApplied:t}){let{t:o}=(0,E.s)(),[s,i]=(0,n.useState)(!1),[a,l]=(0,n.useState)(!1),[d,c]=(0,n.useState)(null),p=(0,n.useCallback)(async()=>{if(e){i(!0),c(null),l(!1);try{await sT(e,{type:"reload"}),l(!0),await t?.()}catch(e){c(e instanceof Error?e.message:String(e))}finally{i(!1)}}},[e,t]),u=s||!e;return(0,r.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[(0,r.jsx)("button",{type:"button",onClick:()=>void p(),disabled:u,title:o(e?"desktop.applyNowTitle":"desktop.applyNowNoSession"),style:{padding:"7px 12px",background:"none",border:"1px solid var(--border)",borderRadius:6,color:"var(--text-muted)",cursor:u?"not-allowed":"pointer",fontSize:12,opacity:u?.5:1,whiteSpace:"nowrap"},children:o(s?"desktop.applyNowApplying":"desktop.applyNow")}),a&&(0,r.jsx)("span",{style:{color:"#22c55e",fontSize:12},children:o("desktop.applyNowDone")}),d&&(0,r.jsx)("span",{style:{color:"#ef4444",fontSize:12},children:d})]})}let aa=["stdio","sse","http"],al=["eager","lazy"],ad={name:"",command:"",args:"",transport:"stdio",lifecycle:"eager",requestTimeoutMs:"",env:""},ac={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 ap(){return{fontSize:12,color:"var(--text-muted)"}}function au(e,t){return{fontSize:10,padding:"1px 6px",borderRadius:3,background:t,color:e,flexShrink:0,textTransform:"capitalize"}}function ag({sessionId:e}){let{t}=(0,E.s)(),[o,s]=(0,n.useState)({}),[i,a]=(0,n.useState)(""),[l,d]=(0,n.useState)(!1),[c,p]=(0,n.useState)(null),[u,h]=(0,n.useState)(null),[f,m]=(0,n.useState)(ad),[k,v]=(0,n.useState)(!1),[y,b]=(0,n.useState)(null),[w,S]=(0,n.useState)(!1),C=(0,n.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,n.useEffect)(()=>{C()},[C]);let T=(0,n.useCallback)(()=>{m(ad),h({name:"",isNew:!0}),b(null),S(!1)},[]),R=(0,n.useCallback)((e,t)=>{m({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),S(!1)},[]),z=(0,n.useCallback)(async()=>{if(u){v(!0),b(null),S(!1);try{let e=f.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===at)return void b(t("desktop.mcpVisionNameReserved"));let r=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:aa.includes(e.transport)?e.transport:"stdio",lifecycle:al.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}}(f);if(r.error||!r.server)return void b(r.error??"Invalid server");let n={...o};u.isNew?n[e]=r.server:(delete n[u.name],n[f.name.trim()||u.name]=r.server);let i=await fetch("/api/mcp",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({mcpServers:n})}),a=await i.json();if(!i.ok||a.error)throw Error(a.error??`HTTP ${i.status}`);s(n),h(null),S(!0)}catch(e){b(e instanceof Error?e.message:String(e))}finally{v(!1)}}},[u,f,o,t]),I=(0,n.useCallback)(async e=>{v(!0),b(null);try{let t={...o};delete t[e];let r=await fetch("/api/mcp",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({mcpServers:t})}),n=await r.json();if(!r.ok||n.error)throw Error(n.error??`HTTP ${r.status}`);s(t),S(!0)}catch(e){b(e instanceof Error?e.message:String(e))}finally{v(!1)}},[o]),M=(0,n.useCallback)((e,t)=>{m(o=>({...o,[e]:t}))},[]),P=Object.entries(o).filter(([e])=>e!==at);return(0,r.jsx)("div",{style:{flex:1,overflow:"auto",minWidth:0,padding:"20px 22px",display:"flex",flexDirection:"column",gap:16},children:(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:l?c?(0,r.jsx)("div",{style:{fontSize:12,color:"#ef4444"},children:c}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12},children:[(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:14,fontWeight:700,color:"var(--text)"},children:t("desktop.mcpServers")}),(0,r.jsx)("div",{style:{fontSize:11,color:"var(--text-dim)",fontFamily:"var(--font-mono)",marginTop:2,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:i})]}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10,flexShrink:0},children:[(0,r.jsx)(ai,{sessionId:e,onApplied:C}),(0,r.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,r.jsx)(x.c,{size:13,"aria-hidden":"true"}),t("desktop.mcpAddServer")]})]})]}),(0,r.jsx)(i0,{children:t("desktop.mcpRestartNote")}),(0,r.jsx)(as,{sessionId:e}),0!==P.length||u?P.map(([e,o])=>(0,r.jsx)(iX,{children:(0,r.jsx)(iQ,{children:(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"12px 0",minWidth:0},children:[(0,r.jsxs)("div",{style:{minWidth:0,flex:1},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[(0,r.jsx)("span",{style:{fontSize:13,fontWeight:600,color:"var(--text)",fontFamily:"var(--font-mono)"},children:e}),(0,r.jsx)("span",{style:au("var(--accent)","rgba(37,99,235,0.12)"),children:o.transport??"stdio"}),(0,r.jsx)("span",{style:au("#d97706","rgba(245,158,11,0.12)"),children:o.lifecycle??"lazy"})]}),(0,r.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,r.jsxs)("div",{style:{display:"flex",gap:6,flexShrink:0},children:[(0,r.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,r.jsx)(g.I,{size:12,"aria-hidden":"true"}),t("desktop.mcpEdit")]}),(0,r.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,r.jsx)(j.l,{size:12,"aria-hidden":"true"})})]})]})})},e)):(0,r.jsx)(iX,{children:(0,r.jsx)(iQ,{children:(0,r.jsx)("div",{style:{padding:"14px 0",fontSize:12,color:"var(--text-dim)"},children:o[at]?t("desktop.mcpEmptyOther"):t("desktop.mcpEmpty")})})}),u&&(0,r.jsxs)(iX,{children:[(0,r.jsx)(iZ,{children:(0,r.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,r.jsx)(iZ,{children:(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"minmax(150px, 220px) 1fr",gap:"8px 12px",alignItems:"center",padding:"8px 0"},children:[(0,r.jsx)("span",{style:ap(),children:t("desktop.mcpServerName")}),(0,r.jsx)("input",{value:f.name,onChange:e=>M("name",e.target.value),disabled:!u.isNew,placeholder:"my-server",style:{...ac,opacity:u.isNew?1:.5}}),(0,r.jsxs)("span",{style:ap(),children:[t("desktop.mcpCommand")," *"]}),(0,r.jsx)("input",{value:f.command,onChange:e=>M("command",e.target.value),placeholder:"npx @modelcontextprotocol/server-foo",style:ac}),(0,r.jsx)("span",{style:ap(),children:t("desktop.mcpArgs")}),(0,r.jsx)("textarea",{value:f.args,onChange:e=>M("args",e.target.value),placeholder:"--port 3000\n--verbose",rows:3,style:{...ac,resize:"vertical",lineHeight:1.5}}),(0,r.jsx)("span",{style:ap(),children:t("desktop.mcpTransport")}),(0,r.jsx)("select",{value:f.transport,onChange:e=>M("transport",e.target.value),style:{...ac,fontFamily:"var(--font-mono)"},children:aa.map(e=>(0,r.jsx)("option",{value:e,children:e},e))}),(0,r.jsx)("span",{style:ap(),children:t("desktop.mcpLifecycle")}),(0,r.jsx)("select",{value:f.lifecycle,onChange:e=>M("lifecycle",e.target.value),style:{...ac,fontFamily:"var(--font-mono)"},children:al.map(e=>(0,r.jsx)("option",{value:e,children:e},e))}),(0,r.jsx)("span",{style:ap(),children:t("desktop.mcpRequestTimeoutMs")}),(0,r.jsx)("input",{type:"number",min:1,value:f.requestTimeoutMs,onChange:e=>M("requestTimeoutMs",e.target.value),placeholder:"300000",style:ac}),(0,r.jsx)("span",{style:ap(),children:t("desktop.mcpEnv")}),(0,r.jsx)("textarea",{value:f.env,onChange:e=>M("env",e.target.value),placeholder:'{\n "API_KEY": "..."\n}',rows:3,style:{...ac,resize:"vertical",lineHeight:1.5}})]})}),(0,r.jsx)(iQ,{children:(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"10px 0"},children:[(0,r.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,r.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,r.jsx)("span",{style:{color:"#ef4444",fontSize:12},children:y})]})})]}),w&&!u&&(0,r.jsx)("div",{style:{fontSize:12,color:"#22c55e"},children:t("desktop.mcpSavedRestart")})]}):(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)"},children:t("desktop.loading")})})})}var ah=o(9210);function af(){let{t:e}=(0,E.s)(),[t,o]=(0,n.useState)(null),[s,i]=(0,n.useState)([]),[a,l]=(0,n.useState)(!0),[d,c]=(0,n.useState)(!1),[p,u]=(0,n.useState)(!1),[g,h]=(0,n.useState)(null);(0,n.useEffect)(()=>{fetch("/api/settings/title-model").then(e=>e.json()).then(e=>{o(e.value),i(e.models??[])}).catch(()=>{}).finally(()=>l(!1))},[]);let f=null!==t&&!s.some(e=>e.label===t),x=(0,n.useCallback)(async t=>{c(!0),h(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})}),r=await e.json();if(!e.ok||r.error)return void h(r.error??`HTTP ${e.status}`);o(r.value??null),u(!0),setTimeout(()=>u(!1),2e3)}catch{h(String(e("desktop.titleModelSaveError")))}finally{c(!1)}},[e]),m=[...new Set(s.map(e=>e.provider))];return(0,r.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,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:[(0,r.jsx)("span",{style:{fontSize:12,fontWeight:600,color:"var(--text)",whiteSpace:"nowrap"},children:e("desktop.titleModel")}),(0,r.jsxs)("select",{value:t??"",disabled:a||d,onChange:e=>x(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,r.jsx)("option",{value:"",children:e("desktop.titleModelFollowSession")}),f&&null!==t&&(0,r.jsxs)("option",{value:t,style:{color:"#ef4444"},children:[t,"(",e("desktop.titleModelInvalid"),")"]}),m.map(e=>(0,r.jsx)("optgroup",{label:e,children:s.filter(t=>t.provider===e).map(e=>(0,r.jsxs)("option",{value:e.label,children:[e.name||e.id,e.reasoning?"(reasoning)":""]},e.label))},e))]}),d&&(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)"},children:"…"}),!d&&p&&(0,r.jsx)("span",{style:{fontSize:11,color:"#4ade80"},children:e("desktop.titleModelSaved")})]}),(0,r.jsx)("p",{style:{margin:0,fontSize:11,color:"var(--text-muted)",lineHeight:1.5},children:e("desktop.titleModelDescription")}),g&&(0,r.jsx)("p",{style:{margin:0,fontSize:11,color:"#ef4444",lineHeight:1.5},children:g}),f&&null!==t&&(0,r.jsxs)("p",{style:{margin:0,fontSize:11,color:"#ef4444",lineHeight:1.5},children:[t,"(",e("desktop.titleModelInvalid"),")"]})]})}let ax=["name","reasoning","contextWindow","maxTokens","thinkingLevelMap","hidden"];function am(e){if(""===e.trim())return;let t=Number(e);return Number.isFinite(t)&&t>0?t:void 0}function ak(e){let t=am(e.contextWindow??""),o=am(e.maxTokens??""),r=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}:{},...r?{thinkingLevelMap:r}:{},..."boolean"==typeof e.hidden?{hidden:e.hidden}:{}}}function av({providerId:e,onRegisterFlush:t,onConfigChange:o}){let{t:s}=(0,E.s)(),i=$(),[a,l]=(0,n.useState)([]),[d,c]=(0,n.useState)({}),[p,u]=(0,n.useState)({}),[g,h]=(0,n.useState)(new Set),[f,x]=(0,n.useState)(!0),[m,k]=(0,n.useState)(!1),[v,y]=(0,n.useState)(null),[b,w]=(0,n.useState)(!1),[j,S]=(0,n.useState)(null),C=(0,n.useRef)(d),T=(0,n.useRef)(p),R=(0,n.useRef)(a),z=(0,n.useRef)(g),I=(0,n.useRef)(0),M=(0,n.useRef)(null);C.current=d,T.current=p,R.current=a,z.current=g,(0,n.useEffect)(()=>{let t=!1;return x(!0),y(null),(async()=>{try{let o=await fetch(`/api/models-config/builtin?provider=${encodeURIComponent(e)}`),r=await o.json();if(!o.ok||r.error)throw Error(r.error??`HTTP ${o.status}`);if(t)return;let n={};for(let e of r.models){let t=r.overrides[e.id]??{};n[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(r.models),c(n),u(n),h(new Set)}catch(e){t||y(e instanceof Error?e.message:String(e))}finally{t||x(!1)}})(),()=>{t=!0}},[e]);let P=(0,n.useCallback)((e,t)=>{I.current+=1,c(o=>({...o,[e]:{...o[e]??{},...t}})),h(t=>new Set(t).add(e))},[]),D=(0,n.useCallback)(async()=>{let t=M.current;if(t)return t;let r=(async()=>{let t=new Set(z.current);if(0===t.size)return;let r=I.current,n={...C.current},s={},i={};for(let e of R.current){let t=n[e.id],o=T.current[e.id];t&&(s[e.id]=ak(t)),o&&(i[e.id]=ak(o))}let a=function(e,t,o){let r={};for(let n of e){let e=t[n],s=o[n];if(!e||!s)continue;let i={};for(let t of ax){let o=e[t],r=s[t];JSON.stringify(o)!==JSON.stringify(r)&&(i[t]=void 0===o?null:o)}Object.keys(i).length>0&&(r[n]=i)}return r}(t,s,i);if(0===Object.keys(a).length)return void h(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=n[e];t&&(l[e]={...t})}T.current=l,u(l),I.current===r&&h(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=r;try{await r}finally{M.current===r&&(M.current=null)}},[o,e]);return((0,n.useEffect)(()=>{if(t)return t(e,D)??void 0},[t,e,D]),f)?(0,r.jsx)("div",{style:{borderTop:"1px solid var(--border)",marginTop:14,paddingTop:12},children:(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-dim)"},children:s("desktop.modelsLoading")})}):(0,r.jsxs)("div",{style:{borderTop:"1px solid var(--border)",marginTop:14,paddingTop:12,display:"flex",flexDirection:"column",gap:10},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)"},children:s("desktop.builtinModelsTitle")}),v&&(0,r.jsx)("p",{style:{margin:0,fontSize:11,color:"#f87171"},children:v}),0===a.length&&!v&&(0,r.jsx)("p",{style:{margin:0,fontSize:11,color:"var(--text-dim)"},children:s("desktop.builtinModelsEmpty")}),(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:8},children:a.map(e=>{let t=d[e.id]??{},o=j===e.id,n=g.has(e.id);return(0,r.jsxs)("div",{style:{border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-panel)",padding:"8px 10px"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[(0,r.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,n&&(0,r.jsx)("span",{style:{color:"var(--accent)",marginLeft:6},children:"•"})]}),(0,r.jsx)("code",{style:{fontSize:10,color:"var(--text-dim)",fontFamily:"var(--font-mono)"},children:e.id}),(t.reasoning??e.reasoning)&&(0,r.jsx)("span",{style:{fontSize:10,padding:"1px 6px",borderRadius:8,background:"var(--bg-selected)",color:"var(--text-muted)"},children:"reasoning"}),(0,r.jsxs)("span",{style:{fontSize:11,color:"var(--text-muted)"},children:[s("desktop.builtinModelsContext"),": ",(0,r.jsx)("b",{children:t.contextWindow?Number(t.contextWindow).toLocaleString():"—"})," \xb7 ",s("desktop.builtinModelsMaxTokens"),": ",(0,r.jsx)("b",{children:t.maxTokens?Number(t.maxTokens).toLocaleString():"—"})]})]}),o&&(0,r.jsxs)("div",{style:{marginTop:10,display:"flex",flexDirection:"column",gap:10},children:[(0,r.jsxs)("label",{style:{display:"flex",gap:6,alignItems:"center",fontSize:12,color:"var(--text)",width:"100%"},children:[s("desktop.modelsName"),(0,r.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,r.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,r.jsx)("input",{type:"checkbox",checked:!0===t.hidden,onChange:t=>P(e.id,{hidden:t.target.checked})}),s("desktop.builtinModelsHide")]})]}),(0,r.jsxs)("div",{style:{display:"flex",gap:16,flexWrap:"wrap",flexDirection:i?"column":"row",alignItems:i?"flex-start":"center"},children:[(0,r.jsxs)("label",{style:{display:"flex",gap:6,alignItems:"center",fontSize:12,color:"var(--text)",cursor:"pointer"},children:[(0,r.jsx)("input",{type:"checkbox",checked:!0===t.reasoning,onChange:t=>P(e.id,{reasoning:t.target.checked})}),s("desktop.builtinModelsReasoning")]}),(0,r.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,r.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,r.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,r.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,r.jsx)("div",{style:{fontSize:11,fontWeight:600,color:"var(--text-dim)"},children:s("desktop.builtinModelsThinking")}),(0,r.jsx)(aD,{value:t.thinkingLevelMap,onChange:t=>P(e.id,{thinkingLevelMap:t})})]})]},e.id)})}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[(0,r.jsx)("button",{type:"button",onClick:()=>{D().catch(()=>{})},disabled:m||0===g.size,style:{alignSelf:"flex-start",padding:"5px 14px",background:g.size>0&&!m?"var(--accent)":"var(--bg-panel)",border:"none",borderRadius:5,color:g.size>0&&!m?"#fff":"var(--text-dim)",cursor:g.size>0&&!m?"pointer":"not-allowed",fontSize:12,fontWeight:600},children:m?s("desktop.modelsSaving"):b?s("desktop.modelsSaved"):s("desktop.modelsSave")}),g.size>0&&(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)"},children:s("desktop.builtinModelsDirty",{count:g.size})})]})]})}let ay=["openai-completions","openai-responses","anthropic-messages","google-generative-ai"];function ab(){let{t:e}=(0,E.s)();return(0,n.useCallback)((t,o)=>e(t,o),[e])}function aw({label:e,children:t}){return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,r.jsx)("label",{style:{fontSize:11,color:"var(--text-muted)",fontWeight:500},children:e}),t]})}let aj={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 aS({value:e,onChange:t,placeholder:o,mono:n}){return(0,r.jsx)("input",{value:e,onChange:e=>t(e.target.value),placeholder:o,style:{...aj,fontFamily:n?"var(--font-mono)":"inherit"}})}function aC({value:e,onChange:t,placeholder:o,mono:s,onKeyDown:i,autoComplete:a="off",spellCheck:l=!1,style:d}){let c=ab(),[p,u]=(0,n.useState)(!1);return(0,n.useEffect)(()=>{e||u(!1)},[e]),(0,r.jsxs)("div",{style:{position:"relative",width:"100%",...d},children:[(0,r.jsx)("input",{type:p?"text":"password",value:e,onChange:e=>t(e.target.value),onKeyDown:i,placeholder:o,style:{...aj,paddingRight:34,fontFamily:s?"var(--font-mono)":"inherit"},autoComplete:a,spellCheck:l}),(0,r.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,r.jsx)(ah.G,{size:15}):(0,r.jsx)(r5.b,{size:15})})]})}function aT({value:e,onChange:t,placeholder:o}){return(0,r.jsx)("input",{type:"number",value:e,onChange:e=>t(e.target.value),placeholder:o,style:aj})}function aR({value:e,onChange:t,options:o,required:n}){let s=ab();return(0,r.jsxs)("select",{value:e,onChange:e=>t(e.target.value),style:{...aj,color:e?"var(--text)":"var(--text-dim)"},children:[!n&&(0,r.jsx)("option",{value:"",children:s("desktop.modelsInheritNone")}),o.map(e=>(0,r.jsx)("option",{value:e,children:e},e))]})}function az({label:e,checked:t,onChange:o}){return(0,r.jsxs)("label",{style:{display:"flex",alignItems:"center",gap:6,cursor:"pointer",fontSize:12,color:"var(--text-muted)"},children:[(0,r.jsx)("input",{type:"checkbox",checked:t,onChange:e=>o(e.target.checked),style:{width:13,height:13,accentColor:"var(--accent)",cursor:"pointer"}}),e]})}function aI({children:e}){return(0,r.jsx)("div",{style:{fontSize:11,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:2},children:e})}function aM({name:e,provider:t,onChange:o,onRename:s,onDelete:i,onAddModels:a}){let l=ab(),[d,c]=(0,n.useState)(e),[p,u]=(0,n.useState)({phase:"idle"}),[g,h]=(0,n.useState)(""),[f,x]=(0,n.useState)([]),m=(0,n.useRef)(0),k=(0,n.useRef)(null);(0,n.useEffect)(()=>c(e),[e]);let v=(e,r)=>o({...t,[e]:r});(0,n.useEffect)(()=>{t.api||o({...t,api:"openai-completions"})},[t.api]),(0,n.useEffect)(()=>{m.current+=1,u({phase:"idle"}),h(""),x([])},[e,t.baseUrl,t.api,t.apiKey]);let y=(0,n.useCallback)(async()=>{if(!t.baseUrl?.trim()||"loading"===p.phase)return;let o=++m.current;u({phase:"loading"}),x([]);try{let r=await fetch("/api/models-config/discover",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({providerName:e,provider:{...t,models:void 0}})}),n=await r.json();if(o!==m.current)return;if(!r.ok||n.error||!n.models)return void u({phase:"error",message:n.error??`HTTP ${r.status}`});u({phase:"success",models:n.models,endpoint:n.endpoint??t.baseUrl})}catch(e){if(o!==m.current)return;u({phase:"error",message:e instanceof Error?e.message:String(e)})}},[p.phase,e,t]),b=new Set((t.models??[]).map(e=>e.id)),w="success"===p.phase?p.models:[],j=g.trim().toLocaleLowerCase(),S=w.filter(e=>!j||e.id.toLocaleLowerCase().includes(j)||e.name?.toLocaleLowerCase().includes(j)),C=S.slice(0,300),T=C.filter(e=>!b.has(e.id)).map(e=>e.id),R=f.filter(e=>!b.has(e)).length,z=T.length>0&&T.every(e=>f.includes(e)),I=!z&&T.some(e=>f.includes(e));return(0,n.useEffect)(()=>{k.current&&(k.current.indeterminate=I)},[I]),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[(0,r.jsx)(aI,{children:l("desktop.modelsProvider")}),(0,r.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:l("desktop.delete")})]}),(0,r.jsxs)(aw,{label:l("desktop.modelsProviderName"),children:[(0,r.jsx)(aS,{value:d,onChange:c,placeholder:"provider-name",mono:!0}),d!==e&&d.trim()&&(0,r.jsx)("button",{onClick:()=>s(d.trim()),style:{marginTop:4,padding:"3px 10px",background:"var(--accent)",border:"none",borderRadius:4,color:"#fff",cursor:"pointer",fontSize:11,alignSelf:"flex-start"},children:l("desktop.rename")})]}),(0,r.jsx)(aw,{label:l("desktop.modelsBaseUrl"),children:(0,r.jsx)(aS,{value:t.baseUrl??"",onChange:e=>v("baseUrl",e||void 0),placeholder:"http(s)://host:port/v1",mono:!0})}),(0,r.jsxs)(aw,{label:l("desktop.modelsApiKey"),children:[(0,r.jsx)(aC,{value:t.apiKey??"",onChange:e=>v("apiKey",e||void 0),placeholder:l("desktop.modelsApiKeyPlaceholder"),mono:!0}),(0,r.jsx)("span",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:l("desktop.modelsApiKeyHelp")})]}),(0,r.jsx)(aw,{label:l("desktop.modelsApi"),children:(0,r.jsx)(aR,{value:t.api??"openai-completions",onChange:e=>v("api",e),options:ay,required:!0})}),(0,r.jsxs)("div",{style:{borderTop:"1px solid var(--border)",paddingTop:14,display:"flex",flexDirection:"column",gap:10},children:["success"!==p.phase&&(0,r.jsx)("button",{onClick:y,disabled:!t.baseUrl?.trim()||"loading"===p.phase,style:{alignSelf:"flex-start",height:30,padding:"0 12px",border:"1px solid var(--border)",borderRadius:5,background:"var(--bg-panel)",color:t.baseUrl?.trim()&&"loading"!==p.phase?"var(--text-muted)":"var(--text-dim)",cursor:t.baseUrl?.trim()&&"loading"!==p.phase?"pointer":"not-allowed",fontSize:11},children:"loading"===p.phase?l("desktop.modelsDiscoveryFetching"):l("desktop.modelsDiscoveryFetch")}),"error"===p.phase&&(0,r.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:p.message}),"success"===p.phase&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("input",{value:g,onChange:e=>h(e.target.value),placeholder:l("desktop.modelsDiscoveryFilterPlaceholder",{count:p.models.length}),"aria-label":l("desktop.modelsDiscoveryFilter"),style:{...aj,width:"100%",minWidth:0}}),(0,r.jsxs)("div",{style:{maxHeight:220,overflowY:"auto",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-panel)"},children:[(0,r.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:T.length?"pointer":"default",color:"var(--text-muted)",fontSize:10,fontWeight:600},children:[(0,r.jsx)("input",{ref:k,type:"checkbox",checked:z,disabled:0===T.length,onChange:()=>{let e=new Set(T);x(t=>z?t.filter(t=>!e.has(t)):Array.from(new Set([...t,...T])))},style:{width:13,height:13,accentColor:"var(--accent)",flexShrink:0}}),l("desktop.modelsDiscoverySelectShown")]}),0===C.length?(0,r.jsx)("div",{style:{padding:12,color:"var(--text-dim)",fontSize:11},children:l("desktop.modelsDiscoveryNoMatches")}):C.map((e,t)=>{let o=b.has(e.id),n=f.includes(e.id);return(0,r.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,r.jsx)("input",{type:"checkbox",checked:n||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,r.jsxs)("span",{style:{minWidth:0,flex:1},children:[(0,r.jsx)("span",{style:{display:"block",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text)",fontSize:11},children:e.name??e.id}),e.name&&(0,r.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,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:10},children:l("desktop.modelsDiscoveryAdded")})]},e.id)})]}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:10},children:[(0,r.jsx)("span",{title:p.endpoint,style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontSize:10},children:S.length>C.length?l("desktop.modelsDiscoveryShowing",{shown:C.length,total:S.length}):l("desktop.modelsDiscoveryFetched",{count:p.models.length})}),(0,r.jsx)("button",{onClick:()=>{if("success"!==p.phase)return;let e=new Set(f),t=p.models.filter(t=>e.has(t.id)&&!b.has(t.id));0!==t.length&&(a(t),x([]))},disabled:0===R,style:{height:28,padding:"0 11px",border:"none",borderRadius:5,background:R?"var(--accent)":"var(--bg-panel)",color:R?"#fff":"var(--text-dim)",cursor:R?"pointer":"not-allowed",fontSize:11,fontWeight:600,whiteSpace:"nowrap"},children:R?l("desktop.modelsDiscoveryAddSelectedCount",{count:R}):l("desktop.modelsDiscoveryAddSelected")})]})]})]})]})}let aE=["off","minimal","low","medium","high","xhigh","max"],aP={off:"var(--text-dim)",minimal:"var(--text-muted)",low:"#60a5fa",medium:"#a78bfa",high:"#f472b6",xhigh:"#fb923c",max:"#ef4444"};function aD({value:e,onChange:t}){let o=ab(),n=e??{},s=(e,o)=>{let r={...n};"omit"===o?delete r[e]:r[e]=o,t(Object.keys(r).length?r:void 0)};return(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:2},children:aE.map(e=>{let t=n[e],i=e in n?null===t?"null":"string":"omit",a="string"==typeof t?t:"",l=aP[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,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"5px 4px",borderRadius:6,background:"transparent",border:"1px solid transparent"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:5,width:68,flexShrink:0},children:[(0,r.jsx)("span",{style:{width:6,height:6,borderRadius:"50%",background:l,flexShrink:0,opacity:"null"===i?.3:1}}),(0,r.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,r.jsxs)("div",{style:{display:"flex",borderRadius:5,border:"1px solid var(--border)",overflow:"hidden",flexShrink:0},children:[(0,r.jsx)("button",{onClick:()=>s(e,"omit"),style:{...d,..."omit"===i?c:{}},children:o("desktop.modelsDefault")}),(0,r.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,r.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,r.jsx)("button",{onClick:()=>s(e,a||e),style:{...d,..."string"===i?c:{},borderRight:"1px solid var(--border)",flexShrink:0},children:o("desktop.modelsCustom")}),(0,r.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 aF={thinkingFormat:"deepseek",requiresReasoningContentOnAssistantMessages:!0};function aW({providerName:e,provider:t,model:o,onChange:s,onDelete:i}){let a=ab(),[l,d]=(0,n.useState)({phase:"idle"}),[c,p]=(0,n.useState)({phase:"idle"}),g=(0,n.useRef)(0),h=(0,n.useRef)(null),f=(e,t)=>s({...o,[e]:t}),x=(()=>{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,n.useEffect)(()=>{d({phase:"idle"})},[e,t.baseUrl,t.api,t.apiKey,o.id,o.api]);let m=(0,n.useCallback)(async()=>{if(o.id.trim()&&"testing"!==l.phase){d({phase:"testing"});try{let r=await fetch("/api/models-config/test",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({providerName:e,provider:t,model:o})}),n=await r.json();if(!r.ok||!n.ok)return void d({phase:"error",message:n.error??`HTTP ${r.status}`,latencyMs:n.latencyMs,status:n.status});d({phase:"success",latencyMs:n.latencyMs,status:n.status,responseText:n.responseText})}catch(e){d({phase:"error",message:e instanceof Error?e.message:String(e)})}}},[o,t,e,l.phase]);(0,n.useEffect)(()=>{g.current+=1,p({phase:"idle"}),h.current=null},[e,t.baseUrl,o.id]);let k=(0,n.useCallback)(async()=>{let r=o.id.trim();if(!r||"loading"===c.phase)return;let n=++g.current;p({phase:"loading"});try{let i=new URLSearchParams({q:r,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(n!==g.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},r=0;if(!e.name?.trim()&&t.name&&(o.name=t.name,r+=1),void 0===e.reasoning&&!0===t.reasoning&&(o.reasoning=!0,r+=1),!e.input?.length&&t.input?.length&&(o.input=[...t.input],r+=1),void 0===e.contextWindow&&void 0!==t.contextWindow&&(o.contextWindow=t.contextWindow,r+=1),void 0===e.maxTokens&&void 0!==t.maxTokens&&(o.maxTokens=t.maxTokens,r+=1),t.cost){let n={...e.cost??{}},s=!1;for(let e of["input","output","cacheRead","cacheWrite"])void 0===n[e]&&void 0!==t.cost[e]&&(n[e]=t.cost[e],s=!0,r+=1);s&&(o.cost=n)}return{model:o,appliedCount:r}}(o,l.recommendation.preset);d.appliedCount>0&&(h.current=o,s(d.model)),p({phase:"success",recommendation:l.recommendation,appliedCount:d.appliedCount})}catch(e){if(n!==g.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,r=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`${r} \xb7 ${e}`}let n="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`${r} \xb7 ${n}`})(),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,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[(0,r.jsx)(aI,{children:a("desktop.modelsModelSection")}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[x&&(0,r.jsx)("span",{title:x,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:x}),(0,r.jsxs)("button",{onClick:m,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,r.jsx)(u.S,{size:11}),"testing"===l.phase?a("desktop.modelsTesting"):"success"===l.phase?a("desktop.modelsOk"):a("desktop.modelsTest")]}),(0,r.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,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10},children:[(0,r.jsx)(aw,{label:a("desktop.modelsIdRequired"),children:(0,r.jsx)(aS,{value:o.id,onChange:e=>f("id",e),placeholder:"model-id",mono:!0})}),(0,r.jsx)(aw,{label:a("desktop.modelsName"),children:(0,r.jsx)(aS,{value:o.name??"",onChange:e=>f("name",e||void 0),placeholder:a("desktop.modelsDisplayName")})})]}),(0,r.jsxs)("div",{style:{padding:"10px 0",borderTop:"1px solid var(--border)",borderBottom:"1px solid var(--border)"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[(0,r.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,r.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,r.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,r.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:y}),"success"===c.phase&&h.current&&(0,r.jsx)("button",{onClick:()=>{let e=h.current;e&&(h.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,r.jsx)(aw,{label:a("desktop.modelsApiOverride"),children:(0,r.jsx)(aR,{value:o.api??"",onChange:e=>f("api",e||void 0),options:ay})}),(0,r.jsxs)("div",{style:{display:"flex",gap:20,flexWrap:"wrap"},children:[(0,r.jsx)(az,{label:a("desktop.modelsReasoningThinking"),checked:o.reasoning??!1,onChange:e=>f("reasoning",e||void 0)}),(0,r.jsx)(az,{label:a("desktop.modelsImageInput"),checked:o.input?.includes("image")??!1,onChange:e=>f("input",e?["text","image"]:void 0)})]}),o.reasoning&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(az,{label:a("desktop.modelsDeepSeekCompat"),checked:o.compat?.thinkingFormat==="deepseek",onChange:e=>s(function(e,t){if(t)return{...e,compat:{...e.compat??{},...aF}};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,r.jsxs)("div",{children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:8},children:[(0,r.jsx)(aI,{children:a("desktop.modelsThinkingLevelMap")}),o.thinkingLevelMap&&(0,r.jsx)("button",{onClick:()=>f("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,r.jsx)(aD,{value:o.thinkingLevelMap,onChange:e=>f("thinkingLevelMap",e)})]})]}),(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10},children:[(0,r.jsx)(aw,{label:a("desktop.modelsContextWindow"),children:(0,r.jsx)(aT,{value:void 0!==o.contextWindow?String(o.contextWindow):"",onChange:e=>f("contextWindow",e?parseInt(e):void 0),placeholder:"128000"})}),(0,r.jsx)(aw,{label:a("desktop.modelsMaxOutputTokens"),children:(0,r.jsx)(aT,{value:void 0!==o.maxTokens?String(o.maxTokens):"",onChange:e=>f("maxTokens",e?parseInt(e):void 0),placeholder:"16384"})})]}),(0,r.jsxs)("div",{children:[(0,r.jsx)(aI,{children:a("desktop.modelsCostPerMillionTokens")}),(0,r.jsx)("div",{style:{marginTop:8,display:"grid",gridTemplateColumns:"1fr 1fr 1fr 1fr",gap:8},children:["input","output","cacheRead","cacheWrite"].map(e=>(0,r.jsx)(aw,{label:e,children:(0,r.jsx)(aT,{value:o.cost?.[e]!==void 0?String(o.cost[e]):"",onChange:t=>{let r;return r=parseFloat(t),void s({...o,cost:{...o.cost??{},[e]:isNaN(r)?void 0:r}})},placeholder:"0"})},e))})]})]})}function a$({provider:e,onRefresh:t,onRegisterBuiltinFlush:o,onBuiltinProviderChange:s}){let i=ab(),[a,l]=(0,n.useState)({phase:"idle"}),[d,c]=(0,n.useState)(""),p=(0,n.useRef)(null),u=(0,n.useRef)(null);(0,n.useEffect)(()=>{("auth"===a.phase||"prompt"===a.phase)&&setTimeout(()=>u.current?.focus(),50)},[a.phase]),(0,n.useEffect)(()=>{l({phase:"idle"}),c(""),p.current?.close(),p.current=null},[e.id]),(0,n.useEffect)(()=>()=>{p.current?.close()},[]);let g=(0,n.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 r=JSON.parse(e.data);"auth"===r.type?(l({phase:"auth",url:r.url,instructions:r.instructions??null,token:r.token}),window.open(r.url,"_blank","noopener,noreferrer")):"device_code"===r.type?(l({phase:"device_code",userCode:r.userCode,verificationUri:r.verificationUri,intervalSeconds:r.intervalSeconds??null,expiresInSeconds:r.expiresInSeconds??null}),window.open(r.verificationUri,"_blank","noopener,noreferrer")):"prompt_request"===r.type?l({phase:"prompt",message:r.message,placeholder:r.placeholder??null,token:r.token}):"select_request"===r.type?l({phase:"select",message:r.message,options:r.options??[],token:r.token}):"progress"===r.type?l({phase:"progress",message:r.message}):"success"===r.type?(o.close(),l({phase:"success"}),t()):"error"===r.type?(o.close(),l({phase:"error",message:r.message})):"cancelled"===r.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]),h=(0,n.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]),f=(0,n.useCallback)(async(t,o)=>{if(o.trim()){l({phase:"progress",message:i("desktop.modelsVerifying")});try{let r=await fetch(`/api/auth/login/${encodeURIComponent(e.id)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t,code:o.trim()})});if(!r.ok){let e=await r.json().catch(()=>({}));l({phase:"error",message:e.error??i("desktop.modelsServerError",{status:r.status})});return}c("")}catch(e){l({phase:"error",message:e instanceof Error?e.message:i("desktop.modelsNetworkError")})}}},[e.id,i]),x=(0,n.useCallback)(async(t,o)=>{l({phase:"progress",message:i("desktop.modelsContinuing")});try{let r=await fetch(`/api/auth/login/${encodeURIComponent(e.id)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t,code:o})});if(!r.ok){let e=await r.json().catch(()=>({}));l({phase:"error",message:e.error??i("desktop.modelsServerError",{status:r.status})})}}catch(e){l({phase:"error",message:e instanceof Error?e.message:i("desktop.modelsNetworkError")})}},[e.id,i]),m="connecting"===a.phase||"progress"===a.phase||"auth"===a.phase||"device_code"===a.phase||"prompt"===a.phase||"select"===a.phase;return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[(0,r.jsx)(aI,{children:i("desktop.modelsSubscription")}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:e.loggedIn?"#4ade80":"var(--border)",display:"inline-block"}}),(0,r.jsx)("span",{style:{fontSize:11,color:e.loggedIn?"#4ade80":"var(--text-dim)"},children:e.loggedIn?i("desktop.modelsConnected"):i("desktop.modelsNotConnected")})]})]}),(0,r.jsxs)("div",{style:{minHeight:48},children:["idle"===a.phase&&(0,r.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,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)"},children:i("desktop.modelsOpeningBrowser")}),"select"===a.phase&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:a.message}),(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:a.options.map(e=>(0,r.jsx)("button",{onClick:()=>x(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,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[(0,r.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,r.jsxs)("p",{style:{margin:0,fontSize:11,color:"var(--text-dim)",lineHeight:1.5},children:[i("desktop.modelsBrowserDidNotOpen")," ",(0,r.jsx)("a",{href:a.url,target:"_blank",rel:"noopener noreferrer",style:{color:"var(--accent)",wordBreak:"break-all"},children:i("desktop.modelsOpenLoginPage")}),"."]}),(0,r.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,r.jsx)("input",{ref:u,value:d,onChange:e=>c(e.target.value),onKeyDown:e=>{"Enter"===e.key&&f(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,r.jsx)("button",{onClick:()=>f(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,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:i("desktop.modelsOpenVerificationPage")}),(0,r.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,r.jsxs)("p",{style:{margin:0,fontSize:11,color:"var(--text-dim)",lineHeight:1.5},children:[(0,r.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,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)"},children:a.message}),"success"===a.phase&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"#4ade80"},children:i("desktop.modelsConnectedSuccessfully")}),"error"===a.phase&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"#f87171"},children:a.message})]}),(0,r.jsx)("div",{style:{display:"flex",gap:8},children:m?(0,r.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,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("button",{onClick:g,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,r.jsx)("button",{onClick:h,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,r.jsx)(av,{providerId:e.id,onRegisterFlush:o,onConfigChange:s})]})}function aN({provider:e,onRefresh:t,onRegisterBuiltinFlush:o,onBuiltinProviderChange:s}){let i=ab(),[a,l]=(0,n.useState)(""),[d,c]=(0,n.useState)(!1),[p,g]=(0,n.useState)(!1),[h,f]=(0,n.useState)(null),[x,m]=(0,n.useState)(!1);(0,n.useEffect)(()=>{l(""),f(null),m(!1)},[e.id]);let k=(0,n.useCallback)(async()=>{if(a.trim()){c(!0),f(null),m(!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()})}),r=await o.json();!o.ok||r.error?f(r.error??`HTTP ${o.status}`):(l(""),m(!0),setTimeout(()=>m(!1),2e3),t())}catch(e){f(String(e))}finally{c(!1)}}},[a,e.id,t]),v=(0,n.useCallback)(async()=>{g(!0),f(null);try{let t=await fetch(`/api/auth/api-key/${encodeURIComponent(e.id)}`,{method:"DELETE"}),o=await t.json();(!t.ok||o.error)&&f(409===t.status?i("desktop.modelsAuthenticationStateChanged"):o.error??`HTTP ${t.status}`)}catch(e){f(String(e))}finally{t(),g(!1)}},[e.id,t,i]);return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[(0,r.jsx)(aI,{children:i("desktop.modelsApiKey")}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:e.configured?"#4ade80":"var(--border)",display:"inline-block"}}),(0,r.jsx)("span",{style:{fontSize:11,color:e.configured?"#4ade80":"var(--text-dim)"},children:e.configured?i("desktop.modelsConfigured"):i("desktop.modelsNotConfigured")})]})]}),(0,r.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,r.jsx)(aw,{label:i("desktop.modelsApiKey"),children:(0,r.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,r.jsx)(aC,{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,r.jsxs)("button",{onClick:k,disabled:d||!a.trim()||x,style:{padding:"6px 12px",background:x?"#16a34a":a.trim()?"var(--accent)":"var(--bg-panel)",border:"none",borderRadius:5,color:a.trim()||x?"#fff":"var(--text-dim)",cursor:d||!a.trim()||x?"not-allowed":"pointer",fontSize:12,fontWeight:600,flexShrink:0,display:"flex",alignItems:"center",gap:5},children:[x&&(0,r.jsx)(u.S,{size:12}),x?i("desktop.modelsSaved"):d?i("desktop.modelsSaving"):i("desktop.modelsSave")]})]})}),h&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"#f87171"},children:h}),e.configured&&(0,r.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,r.jsx)(av,{providerId:e.id,onRegisterFlush:o,onConfigChange:s})]})}function aL({oauthProviders:e,apiKeyProviders:t,onSelectOAuth:o,onSelectApiKey:s,onAddCustom:i,onClose:a}){let l=ab(),[c,p]=(0,n.useState)(""),u=(0,n.useRef)(null);(0,n.useEffect)(()=>{setTimeout(()=>u.current?.focus(),30)},[]);let g=c.trim().toLowerCase(),h=e.filter(e=>!e.loggedIn&&(!g||e.name.toLowerCase().includes(g))),f=t.filter(e=>!e.configured&&(!g||e.displayName.toLowerCase().includes(g)||e.id.toLowerCase().includes(g))),m=!g||"custom".includes(g)||"openai-compatible".includes(g)||"anthropic-compatible".includes(g),k=h.length+f.length+ +!!m,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,r.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,r.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,r.jsxs)("div",{style:{padding:"10px 14px",borderBottom:"1px solid var(--border)",flexShrink:0,display:"flex",alignItems:"center",gap:8},children:[(0,r.jsx)(d.$,{size:13,style:{color:"var(--text-dim)",flexShrink:0}}),(0,r.jsx)("input",{ref:u,value:c,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,r.jsx)("div",{style:{flex:1,overflowY:"auto",padding:14},children:0===k?(0,r.jsx)("div",{style:{padding:"20px 0",fontSize:12,color:"var(--text-dim)",textAlign:"center"},children:l("desktop.modelsNoProvidersMatch")}):(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(min(240px, 100%), 1fr))",gap:8},children:[m&&(0,r.jsx)("div",{style:{gridColumn:"1 / -1",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:l("desktop.modelsCustom")}),m&&(0,r.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,r.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)",lineHeight:1.3,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:l("desktop.modelsCompatibleProvider")}),(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:l("desktop.modelsCustomEndpointFormat")})]}),(0,r.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,r.jsx)(x.c,{size:13,style:{color:"var(--text-dim)"}})})]}),h.length>0&&(0,r.jsx)("div",{style:{gridColumn:"1 / -1",paddingTop:6*!!m,fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:l("desktop.modelsSubscriptions")}),h.map(e=>(0,r.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,r.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)",lineHeight:1.3,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name}),(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:"OAuth"})]}),(0,r.jsx)(n$,{id:e.id,size:28})]},e.id)),f.length>0&&(0,r.jsx)("div",{style:{gridColumn:"1 / -1",paddingTop:6*(h.length>0),fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:l("desktop.modelsApiKey")}),f.map(e=>(0,r.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,r.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)",lineHeight:1.3,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.displayName}),(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:l("desktop.modelsCount",{count:e.modelCount})})]}),(0,r.jsx)(n$,{id:e.id,size:28})]},e.id))]})})]})})}function aA({embedded:e=!1,sessionId:t,onCloseAction:o,onSavedAction:s,onRegisterFlush:i}){let a=ab(),l=$(),[d,c]=(0,n.useState)({providers:{}}),[p,g]=(0,n.useState)(!0),[h,f]=(0,n.useState)(!1),[x,m]=(0,n.useState)(null),[k,v]=(0,n.useState)(!1),[y,b]=(0,n.useState)(null),[w,j]=(0,n.useState)([]),[S,T]=(0,n.useState)([]),[R,z]=(0,n.useState)(!1),[I,M]=(0,n.useState)({oauth:!1,apiKey:!1}),E=(0,n.useRef)({providers:{}}),P=(0,n.useRef)(new Map),D=(0,n.useRef)(0),F=(0,n.useRef)(!1);E.current=d;let W=(0,n.useCallback)(e=>{let t=e(E.current);return E.current=t,D.current+=1,c(t),t},[]),N=(0,n.useCallback)(()=>{fetch("/api/auth/combined").then(e=>e.json()).then(e=>{j(e.oauth??[]),T(e.apiKey??[])}).catch(()=>{}).finally(()=>M({oauth:!0,apiKey:!0}))},[]),L=(0,n.useCallback)((e,t)=>(P.current.set(e,t),()=>{P.current.get(e)===t&&P.current.delete(e)}),[]),A=(0,n.useCallback)(async()=>{for(let e of[...P.current.values()])await e()},[]);(0,n.useEffect)(()=>{if(i)return i(A)??void 0},[A,i]);let O=(0,n.useCallback)((e,t)=>{W(o=>{let r={...o.providers??{}};return t?r[e]=t:delete r[e],{...o,providers:r}}),s?.()},[s,W]),H=(0,n.useCallback)(async e=>{if(!F.current){F.current=!0,m(null);try{await A(),b(e)}catch(e){m(e instanceof Error?e.message:String(e))}finally{F.current=!1}}},[A]);(0,n.useEffect)(()=>{fetch("/api/models-config").then(e=>e.json()).then(e=>{let t=e.providers?e:{...e,providers:{}};E.current=t,D.current+=1,c(t)}).catch(()=>{let e={providers:{}};E.current=e,D.current+=1,c(e)}).finally(()=>g(!1)),N()},[N]);let B=(0,n.useCallback)(async()=>{if(!F.current){F.current=!0,m(null);try{await A();let e="new-provider",t=1;for(;E.current.providers?.[e];)e=`new-provider-${t++}`;W(t=>({...t,providers:{...t.providers??{},[e]:{api:"openai-completions"}}})),b({type:"provider",name:e})}catch(e){m(e instanceof Error?e.message:String(e))}finally{F.current=!1}}},[A,W]),U=(0,n.useCallback)((e,t)=>{W(o=>({...o,providers:{...o.providers??{},[e]:t}}))},[W]),_=(0,n.useCallback)((e,t)=>{W(o=>{let r=Object.entries(o.providers??{}),n=r.findIndex(([t])=>t===e);return -1===n?o:(r[n]=[t,r[n][1]],{...o,providers:Object.fromEntries(r)})}),b(o=>o?"provider"===o.type&&o.name===e?{type:"provider",name:t}:"model"===o.type&&o.providerName===e?{...o,providerName:t}:o:o)},[W]),q=(0,n.useCallback)(e=>{let t=Object.keys(W(t=>{let o={...t.providers??{}};return delete o[e],{...t,providers:o}}).providers??{});b(t.length>0?{type:"provider",name:t[0]}:null)},[W]),V=(0,n.useCallback)(async e=>{if(!F.current){F.current=!0,m(null);try{await A();let t=W(t=>{let o=t.providers?.[e]??{},r=[...o.models??[],{id:""}];return{...t,providers:{...t.providers??{},[e]:{...o,models:r}}}}),o=(t.providers?.[e]?.models?.length??1)-1;b({type:"model",providerName:e,index:o})}catch(e){m(e instanceof Error?e.message:String(e))}finally{F.current=!1}}},[A,W]),K=(0,n.useCallback)((e,t)=>{W(o=>{let r=o.providers?.[e]??{},n=[...r.models??[]],s=new Set(n.map(e=>e.id));for(let e of t)s.has(e.id)||(s.add(e.id),n.push({id:e.id,name:e.name}));return{...o,providers:{...o.providers??{},[e]:{...r,models:n}}}})},[W]),J=(0,n.useCallback)((e,t,o)=>{W(r=>{let n=r.providers?.[e]??{},s=[...n.models??[]];return s[t]=o,{...r,providers:{...r.providers??{},[e]:{...n,models:s}}}})},[W]),G=(0,n.useCallback)(async(e,t)=>{if(!F.current){F.current=!0,m(null);try{await A(),W(o=>{let r=o.providers?.[e]??{},n=[...r.models??[]];return n.splice(t,1),{...o,providers:{...o.providers??{},[e]:{...r,models:n.length?n:void 0}}}}),b({type:"provider",name:e})}catch(e){m(e instanceof Error?e.message:String(e))}finally{F.current=!1}}},[A,W]),Y=(0,n.useCallback)(async()=>{if(!h){f(!0),m(null),v(!1);try{await A();let e=E.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&&(E.current=o.config,D.current+=1,c(o.config)),v(!0),s?.(),setTimeout(()=>v(!1),2e3)}catch(e){m(e instanceof Error?e.message:String(e))}finally{f(!1)}}},[A,s,h]),X=(0,n.useCallback)(async()=>{try{await A(),o?.()}catch(e){m(e instanceof Error?e.message:String(e))}},[A,o]),Z=Object.entries(d.providers??{}),Q=new Set([...w.map(e=>e.id),...S.map(e=>e.id)]),ee=Z.filter(([e])=>!Q.has(e)),et=w.filter(e=>e.loggedIn),eo=S.filter(e=>e.configured);(0,n.useEffect)(()=>{if(y||p||!I.oauth||!I.apiKey)return;let e=et[0]?{type:"oauth",providerId:et[0].id}:eo[0]?{type:"apikey",providerId:eo[0].id}:ee[0]?.[0]?{type:"provider",name:ee[0][0]}:null;e&&b(e)},[eo,et,ee,p,I.apiKey,I.oauth,y]);let er=(()=>{if(!y)return null;if("oauth"===y.type){let e=w.find(e=>e.id===y.providerId);return e?(0,r.jsx)(a$,{provider:e,onRefresh:N,onRegisterBuiltinFlush:L,onBuiltinProviderChange:t=>O(e.id,t)},e.id):null}if("apikey"===y.type){let e=S.find(e=>e.id===y.providerId);return e?(0,r.jsx)(aN,{provider:e,onRefresh:N,onRegisterBuiltinFlush:L,onBuiltinProviderChange:t=>O(e.id,t)},e.id):null}if("provider"===y.type){let e=d.providers?.[y.name];return e?(0,r.jsx)(aM,{name:y.name,provider:e,onChange:e=>U(y.name,e),onRename:e=>_(y.name,e),onDelete:()=>q(y.name),onAddModels:e=>K(y.name,e)},y.name):null}let e=d.providers?.[y.providerName],t=e?.models?.[y.index];return t?(0,r.jsx)(aW,{providerName:y.providerName,provider:e,model:t,onChange:e=>J(y.providerName,y.index,e),onDelete:()=>{G(y.providerName,y.index)}},`${y.providerName}-${y.index}`):null})();return(0,r.jsxs)(r.Fragment,{children:[(0,r.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||X()},children:(0,r.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,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 18px",borderBottom:"1px solid var(--border)",flexShrink:0},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"baseline",gap:10},children:[(0,r.jsx)("span",{style:{fontSize:15,fontWeight:700,color:"var(--text)"},children:a("desktop.models")}),(0,r.jsx)("code",{style:{fontSize:11,color:"var(--text-muted)",fontFamily:"var(--font-mono)"},children:"~/.pi/agent/models.json"})]}),(0,r.jsx)("button",{onClick:()=>{X()},"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,r.jsx)(af,{}),(0,r.jsxs)("div",{style:{flex:1,display:"flex",flexDirection:l?"column":"row",overflow:"hidden"},children:[(0,r.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,r.jsxs)("div",{style:{flex:1,overflowY:"auto",padding:"8px 6px"},children:[et.map(e=>{let t=y?.type==="oauth"&&y.providerId===e.id;return(0,r.jsxs)("div",{onClick:()=>{H({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,r.jsx)(n$,{id:e.id,size:16}),(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name})]},e.id)}),eo.map(e=>{let t=y?.type==="apikey"&&y.providerId===e.id;return(0,r.jsxs)("div",{onClick:()=>{H({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,r.jsx)(n$,{id:e.id,size:16}),(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.displayName})]},e.id)}),(et.length>0||eo.length>0)&&ee.length>0&&(0,r.jsx)("div",{style:{margin:"4px 8px",borderTop:"1px solid var(--border)"}}),p?(0,r.jsx)("div",{style:{padding:"10px 8px",fontSize:12,color:"var(--text-muted)"},children:a("desktop.modelsLoading")}):ee.map(([e,t])=>{let o=y?.type==="provider"&&y.name===e,n=t.models??[];return(0,r.jsxs)("div",{style:{marginBottom:2},children:[(0,r.jsxs)("div",{onClick:()=>{H({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,r.jsx)(C.G,{size:11,style:{color:"var(--text-dim)",flexShrink:0}}),(0,r.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})]}),n.map((t,o)=>{let n=y?.type==="model"&&y.providerName===e&&y.index===o;return(0,r.jsxs)("div",{onClick:()=>{H({type:"model",providerName:e,index:o})},style:{display:"flex",alignItems:"center",gap:6,padding:"5px 8px 5px 26px",borderRadius:5,cursor:"pointer",background:n?"var(--bg-selected)":"none"},onMouseEnter:e=>{n||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{n||(e.currentTarget.style.background="none")},children:[(0,r.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,r.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,r.jsx)("div",{onClick:t=>{t.stopPropagation(),V(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,r.jsx)("span",{style:{fontSize:11},children:a("desktop.modelsAddModel")})})]},e)})]}),(0,r.jsx)("div",{style:{borderTop:"1px solid var(--border)",padding:"8px 6px"},children:(0,r.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,r.jsx)("div",{style:{flex:1,overflowY:"auto",padding:20},children:p?null:er??(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-dim)",fontSize:13},children:a("desktop.modelsSelectProviderOrModel")})})]}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"flex-end",gap:10,padding:"10px 18px",borderTop:"1px solid var(--border)",flexShrink:0},children:[x&&(0,r.jsx)("span",{style:{fontSize:12,color:"#f87171",flex:1},children:x}),!e&&(0,r.jsx)("button",{onClick:()=>{X()},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,r.jsx)(ai,{sessionId:t}),(0,r.jsxs)("button",{onClick:Y,disabled:h||k,style:{position:"relative",padding:"6px 16px",minWidth:92,background:k?"#16a34a":h?"var(--bg-panel)":"var(--accent)",border:"none",borderRadius:6,color:k?"#fff":h?"var(--text-muted)":"#fff",cursor:h||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,r.jsx)(u.S,{size:14,style:{strokeDasharray:18,animation:"saved-check-draw 0.35s ease forwards",flexShrink:0}}),(0,r.jsx)("span",{children:k?a("desktop.modelsSaved"):h?a("desktop.modelsSaving"):a("desktop.modelsSave")})]})]})]})}),R&&(0,r.jsx)(aL,{oauthProviders:w,apiKeyProviders:S,onSelectOAuth:e=>{H({type:"oauth",providerId:e})},onSelectApiKey:e=>{H({type:"apikey",providerId:e})},onAddCustom:B,onClose:()=>z(!1)})]})}function aO(e){return e.replace(/^\/(?:Users|home)\/[^/]+/,"~")}function aH(e){let t=e.trim().match(/^\$?\s*pi\s+install\s+(\S+)\s*$/);return t?.[1]??e}function aB(e){return`${e.scope}\0${e.source}`}function aU(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 a_(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 aq(e){return"loaded"===e?"var(--accent)":"installed"===e?"#f59e0b":"disabled"===e?"var(--text-dim)":"#ef4444"}function aV({pkg:e}){let{t}=(0,E.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,r.jsx)("div",{style:{fontSize:12,color:"var(--text-dim)"},children:t(e.disabled?"desktop.packageDisabled":"desktop.noResolvedResources")}):(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:12},children:o.map((e,t)=>(0,r.jsxs)("div",{style:{borderTop:0===t?"none":"1px solid var(--border)",paddingTop:12*(0!==t)},children:[(0,r.jsx)("div",{style:{fontSize:10,fontWeight:700,color:"var(--text-dim)",textTransform:"uppercase",marginBottom:6},children:e.label}),(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:e.resources.map(e=>(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.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,r.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 aK({scope:e}){let{t}=(0,E.s)();return(0,r.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 aJ(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 aG({enabled:e,loading:t,onToggle:o,label:n}){return(0,r.jsx)("button",{type:"button",onClick:o,disabled:t,title:n,"aria-label":n,"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,r.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 aY({value:e,onChange:t}){let{t:o}=(0,E.s)();return(0,r.jsx)("div",{style:{display:"inline-flex",border:"1px solid var(--border)",borderRadius:7,overflow:"hidden",height:30},children:["global","project"].map(n=>{let s=e===n;return(0,r.jsx)("button",{onClick:()=>t(n),style:{width:76,border:"none",borderRight:"global"===n?"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.${n}`)},n)})})}function aX({cwd:e,source:t,scope:o,busy:s,actionError:i,onSourceChange:a,onScopeChange:l,onInstall:d}){let{t:c}=(0,E.s)(),p=(0,n.useRef)(null);return(0,n.useEffect)(()=>{p.current?.focus()},[]),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:18,maxWidth:660,minHeight:"100%"},children:[(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:5},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,flexWrap:"wrap"},children:[(0,r.jsx)("div",{style:{fontSize:14,fontWeight:700,color:"var(--text)"},children:c("desktop.addPluginTitle")}),(0,r.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,r.jsx)("div",{style:{fontSize:12,color:"var(--text-dim)",fontFamily:"var(--font-mono)"},children:"project"===o?`${aO(e)}/.pi/agent/{npm,git}`:"~/.pi/agent/{npm,git}"})]}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:7},children:[(0,r.jsx)("label",{htmlFor:"plugin-source",style:{fontSize:12,fontWeight:600,color:"var(--text-muted)"},children:c("desktop.pluginSource")}),(0,r.jsx)("input",{id:"plugin-source",ref:p,value:t,onChange:e=>a(e.target.value),onPaste:e=>{let t=e.clipboardData.getData("text"),o=aH(t);o!==t&&(e.preventDefault(),a(o))},onBlur:e=>a(aH(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,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:[(0,r.jsx)(aY,{value:o,onChange:l}),(0,r.jsx)("button",{type:"button",onClick:d,disabled:s||!t.trim(),style:{...aJ(s||!t.trim()),background:"var(--accent)",color:"white",borderColor:"var(--accent)"},children:c(s?"desktop.installing":"desktop.install")})]}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:7},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text-muted)"},children:c("desktop.examples")}),(0,r.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,r.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,r.jsx)("div",{style:{fontSize:12,color:"#ef4444",whiteSpace:"pre-wrap"},children:i})]})}function aZ({pkg:e,cwd:t,busyKey:o,actionError:n,actionMessage:s,sessionId:i,onAction:a,onReloadSession:l}){let{t:d}=(0,E.s)(),c=aB(e),p=o?.endsWith(c)??!1,u="reload"===o,g=!e.disabled;return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:20,maxWidth:680},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:12,minWidth:0,flexWrap:"wrap"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:180,flex:1},children:[(0,r.jsx)(aG,{enabled:g,loading:p||u,onToggle:()=>a(e.disabled?"enable":"disable",e),label:d(e.disabled?"desktop.enablePackage":"desktop.disablePackage")}),(0,r.jsx)(aK,{scope:e.scope}),e.disabled?(0,r.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,r.jsx)("span",{style:{fontSize:10,padding:"1px 5px",borderRadius:3,background:"rgba(245,158,11,0.12)",color:"#d97706"},children:d("desktop.filtered")}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:12,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.source})]}),(0,r.jsxs)("div",{style:{display:"flex",gap:8,flexWrap:"wrap"},children:[(0,r.jsx)("button",{onClick:()=>a("update",e),disabled:p||u,style:aJ(p||u),children:d(o===`update:${c}`?"desktop.updating":"desktop.update")}),(0,r.jsx)("button",{onClick:l,disabled:!i||u||p,style:aJ(!i||u||p),title:d(i?"desktop.reloadCurrentSession":"desktop.openSessionToReload"),children:d(u?"desktop.reloading":"desktop.reloadSession")}),(0,r.jsx)("button",{onClick:()=>a("remove",e),disabled:p||u,style:aJ(p||u,!0),children:d(o===`remove:${c}`?"desktop.removing":"desktop.remove")})]})]}),(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"minmax(96px, 130px) minmax(0, 1fr)",gap:"9px 14px",fontSize:12,lineHeight:1.45},children:[(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:d("desktop.status")}),(0,r.jsx)("div",{style:{color:aq(e.status),textTransform:"capitalize"},children:e.status}),(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:d("desktop.version")}),(0,r.jsx)("div",{style:{color:"var(--text-muted)",fontFamily:"var(--font-mono)"},children:a_(e,d)}),(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:d("desktop.package")}),(0,r.jsx)("div",{style:{color:"var(--text-muted)",fontFamily:"var(--font-mono)",overflowWrap:"anywhere"},children:e.packageName??d("desktop.unknown")}),(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:d("desktop.resources")}),(0,r.jsx)("div",{style:{color:"var(--text-muted)"},children:aU(e,d)}),(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:d("desktop.installedPath")}),(0,r.jsx)("div",{style:{color:e.installedPath?"var(--text-muted)":"#ef4444",fontFamily:"var(--font-mono)",overflowWrap:"anywhere"},children:e.installedPath?aO(e.installedPath):d("desktop.notFound")}),(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:d("desktop.cwd")}),(0,r.jsx)("div",{style:{color:"var(--text-dim)",fontFamily:"var(--font-mono)",overflowWrap:"anywhere"},children:aO(t)})]}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:700,color:"var(--text)"},children:d("desktop.resolvedResources")}),(0,r.jsx)(aV,{pkg:e})]}),s&&(0,r.jsx)("div",{style:{fontSize:12,color:"#16a34a"},children:s}),n&&(0,r.jsx)("div",{style:{fontSize:12,color:"#ef4444",whiteSpace:"pre-wrap"},children:n})]})}function aQ({cwd:e,sessionId:t,embedded:o=!1,onCloseAction:s,onReloadedAction:i}){let a=$(),{t:l}=(0,E.s)(),[d,c]=(0,n.useState)(null),[p,u]=(0,n.useState)(!0),[g,h]=(0,n.useState)(null),[f,m]=(0,n.useState)(null),[k,v]=(0,n.useState)(!1),[y,b]=(0,n.useState)(""),[w,j]=(0,n.useState)("global"),[S,C]=(0,n.useState)(null),[T,R]=(0,n.useState)(null),[z,I]=(0,n.useState)(null),M=(0,n.useMemo)(()=>d?.packages??[],[d?.packages]),P=M.find(e=>aB(e)===f)??null,D=(0,n.useMemo)(()=>["project","global"].map(e=>({scope:e,packages:M.filter(t=>t.scope===e)})).filter(e=>e.packages.length>0),[M]),F=(0,n.useCallback)(async()=>{u(!0),h(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),m(e=>e&&o.packages.some(t=>aB(t)===e)?e:o.packages[0]?aB(o.packages[0]):null)}catch(e){h(e instanceof Error?e.message:String(e))}finally{u(!1)}},[e]);(0,n.useEffect)(()=>{F()},[F]);let W=(0,n.useCallback)(async(t,o)=>{let r=aB(o);C(`${t}:${r}`),R(null),I(null);try{let r=await fetch("/api/plugins",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:t,source:o.source,scope:o.scope,cwd:e})}),n=await r.json();if(!r.ok||n.error)throw Error(n.error??`HTTP ${r.status}`);if(c(n),"remove"===t)m(n.packages[0]?aB(n.packages[0]):null),0===n.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]),N=(0,n.useCallback)(async()=>{let t=aH(y).trim();if(!t)return;let o=`${w}\0${t}`;C(`install:${o}`),R(null),I(null);try{var r;let n,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=(r=a.packages,s=(n=t.trim()).startsWith("npm:")?n.slice(4):n,r.find(e=>e.scope===w&&e.source===n)??r.find(e=>e.scope===w&&e.source===`npm:${s}`)??r.find(e=>e.scope===w&&e.source.endsWith(n)));m(d?aB(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]),L=(0,n.useCallback)(async()=>{if(t){C("reload"),R(null),I(null);try{await sT(t,{type:"reload"}),i?.(),await F(),I(l("desktop.sessionReloaded"))}catch(e){R(e instanceof Error?e.message:String(e))}finally{C(null)}}},[F,i,t,l]),A=S?.startsWith("install:")??!1;return(0,r.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,r.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,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 18px",borderBottom:"1px solid var(--border)",flexShrink:0},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"baseline",gap:10,minWidth:0},children:[(0,r.jsx)("span",{style:{fontSize:15,fontWeight:700,color:"var(--text)"},children:l("desktop.plugins")}),(0,r.jsx)("code",{style:{fontSize:11,color:"var(--text-muted)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:aO(e)})]}),(0,r.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,r.jsxs)("div",{style:{flex:1,display:"flex",flexDirection:a?"column":"row",overflow:"hidden"},children:[(0,r.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,r.jsx)("div",{style:{flex:1,overflowY:"auto",padding:"8px 6px"},children:p?(0,r.jsx)("div",{style:{padding:"10px 8px",fontSize:12,color:"var(--text-muted)"},children:l("desktop.loading")}):g?(0,r.jsx)("div",{style:{padding:"10px 8px",fontSize:11,color:"#ef4444"},children:g}):0===M.length?(0,r.jsx)("div",{style:{padding:"10px 8px",fontSize:11,color:"var(--text-dim)"},children:l("desktop.noPluginsConfigured")}):D.map(e=>(0,r.jsxs)("div",{style:{marginBottom:6},children:[(0,r.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=aB(e),o=!k&&f===t;return(0,r.jsxs)("div",{onClick:()=>{m(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,r.jsx)("span",{style:{flexShrink:0,width:7,height:7,borderRadius:"50%",background:aq(e.status)}}),(0,r.jsxs)("div",{style:{minWidth:0,flex:1},children:[(0,r.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,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",marginTop:2},children:aU(e,l)}),(e.version||e.configuredVersion)&&(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",marginTop:2},children:a_(e,l)})]})]},t)})]},e.scope))}),(0,r.jsx)("div",{style:{padding:"8px 6px",borderTop:"1px solid var(--border)",flexShrink:0},children:(0,r.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,r.jsx)(x.c,{size:13}),l("desktop.addPlugin")]})})]}),(0,r.jsx)("div",{style:{flex:1,overflowY:"auto",padding:20},children:k?(0,r.jsx)(aX,{cwd:e,source:y,scope:w,busy:A,actionError:T,onSourceChange:b,onScopeChange:j,onInstall:N}):p?null:P?(0,r.jsx)(aZ,{pkg:P,cwd:e,busyKey:S,actionError:T,actionMessage:z,sessionId:t,onAction:W,onReloadSession:L},aB(P)):(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-dim)",fontSize:13},children:l("desktop.selectPackage")})})]}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,padding:"10px 18px",borderTop:"1px solid var(--border)",flexShrink:0},children:[(0,r.jsx)("div",{style:{minWidth:0,flex:1,fontSize:11,color:"var(--text-dim)",overflow:"hidden"},children:d?.diagnostics.length?(0,r.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,r.jsx)("span",{children:d?l("desktop.pluginResourceTotals",{extensions:d.totals.extensions,skills:d.totals.skills,prompts:d.totals.prompts,themes:d.totals.themes}):""})}),(0,r.jsx)("button",{onClick:()=>void F(),disabled:p||null!==S,style:aJ(p||null!==S),children:l("desktop.refresh")}),!o&&(0,r.jsx)("button",{onClick:s,style:aJ(!1),children:l("desktop.close")})]})]})})}var a0=o(36282);function a1(){let{t:e}=(0,E.s)(),[t,o]=(0,n.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,n.useState)(!1),[a,l]=(0,n.useState)(!1),[d,c]=(0,n.useState)(null),[p,u]=(0,n.useState)(null),[g,h]=(0,n.useState)(null),[f,x]=(0,n.useState)(!1),[m,k]=(0,n.useState)(!1);(0,n.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,n.useCallback)((e,t)=>{o(o=>({...o,[e]:t})),"password"===e&&k(!0),x(!0),u(null),h(null)},[]),y=(0,n.useCallback)(async()=>{i(!0),u(null),h(null);try{let r={...t};delete r.hasPassword,m||delete r.password;let n=await fetch("/api/proxy",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)}),s=await n.json();if(n.ok){u(!0),x(!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),h(s.error||e("desktop.proxySaveFailed"))}catch(t){u(!1),h(t instanceof Error?t.message:e("desktop.proxySaveFailed"))}finally{i(!1)}},[t,m,e]),b=(0,n.useCallback)(async()=>{l(!0),c(null),f&&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)}},[f,y,e]),w=(0,n.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,r.jsxs)("div",{style:{flex:1,display:"flex",flexDirection:"column",padding:"16px 20px",overflow:"auto",gap:16},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:12,marginBottom:4},children:[(0,r.jsxs)("label",{style:{display:"flex",alignItems:"center",gap:8,fontSize:14,fontWeight:500,color:"var(--text)",cursor:"pointer"},children:[(0,r.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,r.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,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:"12px 16px",opacity:t.enabled?1:.5,pointerEvents:t.enabled?"auto":"none"},children:[(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,r.jsx)("label",{style:{fontSize:12,color:"var(--text-muted)"},children:e("desktop.proxyProtocol")}),(0,r.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,r.jsx)("option",{value:"http",children:"HTTP"}),(0,r.jsx)("option",{value:"https",children:"HTTPS"}),(0,r.jsx)("option",{value:"socks5",children:"SOCKS5"})]})]}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,r.jsx)("label",{style:{fontSize:12,color:"var(--text-muted)"},children:e("desktop.proxyHost")}),(0,r.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,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,r.jsx)("label",{style:{fontSize:12,color:"var(--text-muted)"},children:e("desktop.proxyPort")}),(0,r.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,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,r.jsx)("label",{style:{fontSize:12,color:"var(--text-muted)"},children:e("desktop.proxyUsername")}),(0,r.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,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,r.jsx)("label",{style:{fontSize:12,color:"var(--text-muted)"},children:e("desktop.proxyPassword")}),(0,r.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,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4,gridColumn:"1 / -1"},children:[(0,r.jsx)("label",{style:{fontSize:12,color:"var(--text-muted)"},children:e("desktop.proxyNoProxy")}),(0,r.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,r.jsxs)("div",{style:{display:"flex",gap:10,marginTop:4},children:[(0,r.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,r.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,r.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,r.jsx)(oZ.r,{size:16,weight:"fill"}),e("desktop.proxySaved")]}),!1===p&&g&&(0,r.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,r.jsx)(sh.J,{size:16,weight:"fill"}),g]}),d&&(0,r.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,r.jsx)(oZ.r,{size:16,weight:"fill"}):(0,r.jsx)(sh.J,{size:16,weight:"fill"}),d.message,void 0!==d.latencyMs&&(0,r.jsxs)("span",{style:{color:"var(--text-muted)",fontSize:12,marginLeft:4},children:["(",d.latencyMs,"ms)"]})]}),f&&!p&&!g&&(0,r.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,r.jsx)(a0.j,{size:12,weight:"fill"}),e("desktop.proxyUnsaved")]})]})}function a2(e){return e.replace(/^\/(?:Users|home)\/[^/]+/,"~")}function a4(e){let t=e.sourceInfo?.source,o=e.sourceInfo?.scope;return"user"===o||"user"===t?"global":"project"===o||"project"===t?"project":"path"}function a6(e){let t=a4(e);return"path"===t?t:e.install?.skillsShUrl?`${t} / skills.sh`:t}function a5(e){return e.install?`${e.install.scope}\0${e.install.package}`:null}function a3(e,t){return e?e.slice(0,8):t}function a8({enabled:e,loading:t,onToggle:o}){let{t:n}=(0,E.s)();return(0,r.jsx)("button",{onClick:o,disabled:t,title:n(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,r.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 a7({skill:e,cwd:t,onToggle:o,toggling:n,saveError:s,updateStatus:i,checkingUpdate:a,updating:l,updateError:d,onCheckUpdate:c,onUpdate:p}){let{t:u}=(0,E.s)(),g=a4(e),h=!e.disableModelInvocation;return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:20},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:7},children:[(0,r.jsx)("span",{style:{fontSize:10,padding:"1px 5px",borderRadius:3,flexShrink:0,background:"project"===g?"rgba(99,102,241,0.12)":"rgba(120,120,120,0.12)",color:"project"===g?"rgba(99,102,241,0.8)":"var(--text-dim)"},children:u(`desktop.${g}`)}),(0,r.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"===g&&e.startsWith(t)){let o=e.slice(t.length).replace(/^[/\\]/,"");return`./${o}`}return a2(e)}(e.filePath)}),(0,r.jsx)(a8,{enabled:h,loading:n,onToggle:()=>o(e)}),s&&(0,r.jsx)("span",{style:{fontSize:12,color:"#f87171",flexShrink:0},children:s})]}),!h&&(0,r.jsx)("div",{style:{marginTop:-12,color:"var(--text-dim)",fontSize:12},children:u("desktop.hiddenButInvocable")}),e.install?.skillsShUrl&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:5},children:[(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",fontWeight:500},children:u("desktop.pluginSource")}),(0,r.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,r.jsxs)("span",{style:{fontFamily:"var(--font-mono)",fontSize:12,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[e.install.skillsShUrl.replace(/^https?:\/\//,"")," ↗"]})})]}),e.install&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:7},children:[(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",fontWeight:500},children:u("desktop.version")}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:[(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:12,color:"var(--text-muted)"},children:a3(i?.currentVersion??e.install.versionHash,u("desktop.unknown"))}),e.install.canCheckForUpdates&&(0,r.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,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:12,color:"#d97706"},children:a3(i.latestVersion,u("desktop.unknown"))}),(a||i&&"update-available"!==i.state)&&(0,r.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,r.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,r.jsx)("span",{style:{fontSize:12,color:"#ef4444"},children:d})]}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:5},children:[(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",fontWeight:500},children:u("desktop.name")}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:14,color:"var(--text)"},children:e.name})]}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:5},children:[(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",fontWeight:500},children:u("desktop.description")}),(0,r.jsx)("span",{style:{fontSize:14,color:"var(--text-muted)",lineHeight:1.6},children:e.description})]})]})}function a9({cwd:e,installedPackages:t,projectResourcesLoaded:o,onInstalled:s}){let{t:i}=(0,E.s)(),[a,l]=(0,n.useState)(""),[d,c]=(0,n.useState)([]),[p,u]=(0,n.useState)(!1),[g,h]=(0,n.useState)(null),[f,x]=(0,n.useState)(null),[m,k]=(0,n.useState)(null),[v,y]=(0,n.useState)(new Set),[b,w]=(0,n.useState)("global"),j=(0,n.useRef)(null);(0,n.useEffect)(()=>{j.current?.focus()},[]),(0,n.useEffect)(()=>{o||w("global")},[o]);let S=(0,n.useCallback)(async e=>{if(e.trim()){u(!0),h(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 h(o.error);c(o.results??[]),0===(o.results??[]).length&&h(i("desktop.noSkillsFound"))}catch(e){h(String(e))}finally{u(!1)}}},[i]),C=(0,n.useCallback)(async t=>{x(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})}),r=await o.json();if(!o.ok||r.error)return void k(r.error??`HTTP ${o.status}`);y(e=>new Set(e).add(`${b}:${t}`)),s()}catch(e){k(String(e))}finally{x(null)}},[s,b,e]),T="global"===b?"~/.pi/agent/skills/":`${a2(e)}/.pi/skills/`;return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%"},children:[(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:12,marginBottom:20},children:[(0,r.jsx)("div",{style:{fontSize:14,fontWeight:600,color:"var(--text)"},children:i("desktop.addSkillTitle")}),(0,r.jsxs)("div",{style:{display:"flex",gap:8},children:[(0,r.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,r.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,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10},children:[(0,r.jsx)("div",{style:{display:"flex",borderRadius:5,border:"1px solid var(--border)",overflow:"hidden",fontSize:12,flexShrink:0},children:["global","project"].map(e=>(0,r.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,r.jsxs)("span",{style:{fontSize:12,color:"var(--text-dim)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:["→ ",T]})]}),g&&(0,r.jsx)("div",{style:{fontSize:12,color:"#f87171"},children:g}),m&&(0,r.jsx)("div",{style:{fontSize:12,color:"#f87171",wordBreak:"break-word"},children:m})]}),d.length>0?(0,r.jsx)("div",{style:{flex:1,overflowY:"auto"},children:d.map(e=>{let o=t[b].has(e.package)||v.has(`${b}:${e.package}`),n=f===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,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:14,padding:"12px 0",borderBottom:"1px solid var(--border)"},children:[(0,r.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:13,fontWeight:600,color:"var(--text)",marginBottom:3},children:l??a}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:[(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:11,color:"var(--text-dim)"},children:a}),(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",fontWeight:500},children:e.installs}),e.url&&(0,r.jsx)("a",{href:e.url,target:"_blank",rel:"noreferrer",style:{fontSize:12,color:"var(--accent)",textDecoration:"none"},children:"skills.sh ↗"})]})]}),(0,r.jsx)("button",{onClick:()=>!o&&!n&&C(e.package),disabled:o||n||null!==f,style:{flexShrink:0,padding:"5px 14px",fontSize:12,fontWeight:500,borderRadius:5,border:"1px solid var(--border)",cursor:o||n||null!==f?"not-allowed":"pointer",background:o?"rgba(34,197,94,0.1)":"none",color:o?"#16a34a":n?"var(--accent)":"var(--text-muted)",transition:"color 0.12s"},children:o?`✓ ${i("desktop.installed")}`:n?i("desktop.installing"):i("desktop.install")})]},e.package)})}):!g&&!p&&(0,r.jsxs)("div",{style:{fontSize:13,color:"var(--text-dim)",lineHeight:1.8},children:[i("desktop.skillSearchHint").split("skills.sh")[0],(0,r.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 le({cwd:e,embedded:t=!1,sessionId:o,onCloseAction:s}){let i=$(),{t:a}=(0,E.s)(),[l,d]=(0,n.useState)([]),[c,p]=(0,n.useState)(!0),[u,g]=(0,n.useState)(null),[h,f]=(0,n.useState)(null),[m,k]=(0,n.useState)(new Set),[v,y]=(0,n.useState)(null),[b,w]=(0,n.useState)(!1),[j,S]=(0,n.useState)({}),[C,T]=(0,n.useState)(new Set),[R,z]=(0,n.useState)(!1),[I,M]=(0,n.useState)(null),[P,D]=(0,n.useState)(null),[F,W]=(0,n.useState)(!0),[N,L]=(0,n.useState)({}),A=(0,n.useCallback)(async()=>{p(!0),g(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 r=o.skills??[];if(d(r),W(o.projectResourcesLoaded??!0),r.length>0&&!h){let e=r.find(e=>!e.disableModelInvocation)??r[0];f(e.filePath),e.disableModelInvocation&&L(t=>({...t,[a6(e)]:!0}))}return r}catch(e){return g(String(e)),[]}finally{p(!1)}},[e,h]);(0,n.useEffect)(()=>{S({}),D(null),A()},[e]);let O=(0,n.useCallback)(async t=>{let o=(t?[t]:l.filter(e=>!!e.install)).map(a5).filter(e=>!!e);if(0!==o.length){D(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})}),r=await o.json();if(!o.ok||r.error)throw Error(r.error??`HTTP ${o.status}`);S(e=>{let t={...e};for(let e of r.updates??[])t[`${e.scope}\0${e.package}`]=e;return t})}catch(e){D(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,n.useCallback)(async t=>{if(!t.install)return;let o=a5(t);M(o),D(null);try{let r=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})}),n=await r.json();if(!r.ok||n.error||!n.success)throw Error(n.error??`HTTP ${r.status}`);await A();let s=n.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){D(e instanceof Error?e.message:String(e))}finally{M(null)}},[e,A]),B=(0,n.useCallback)(async t=>{let o=!t.disableModelInvocation;k(e=>new Set(e).add(t.filePath)),y(null);try{let r=await fetch("/api/skills",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e,filePath:t.filePath,disableModelInvocation:o})}),n=await r.json();if(!r.ok||n.error)return void y(n.error??`HTTP ${r.status}`);d(e=>e.map(e=>e.filePath===t.filePath?{...e,disableModelInvocation:o}:e)),o&&L(e=>({...e,[a6(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===h)??null;return(0,r.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,r.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,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 18px",borderBottom:"1px solid var(--border)",flexShrink:0},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"baseline",gap:10},children:[(0,r.jsx)("span",{style:{fontSize:15,fontWeight:700,color:"var(--text)"},children:a("desktop.skills")}),(0,r.jsx)("code",{style:{fontSize:11,color:"var(--text-muted)",fontFamily:"var(--font-mono)",maxWidth:320,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:a2(e)})]}),(0,r.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"})]}),!F&&(0,r.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,r.jsxs)("div",{style:{flex:1,display:"flex",flexDirection:i?"column":"row",overflow:"hidden"},children:[(0,r.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,r.jsx)("div",{style:{padding:"8px 8px 0",display:"flex",justifyContent:"flex-end"},children:(0,r.jsx)(ai,{sessionId:o,onApplied:A})}),(0,r.jsx)("div",{style:{flex:1,overflowY:"auto",padding:"8px 6px"},children:c?(0,r.jsx)("div",{style:{padding:"10px 8px",fontSize:12,color:"var(--text-muted)"},children:a("desktop.loading")}):u?(0,r.jsx)("div",{style:{padding:"10px 8px",fontSize:11,color:"#f87171"},children:u}):0===l.length?(0,r.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:r}of[{key:"project / skills.sh",label:`${a("desktop.project")} / skills.sh`,matches:e=>"project"===a4(e)&&!!e.install?.skillsShUrl},{key:"project",label:a("desktop.project"),matches:e=>"project"===a4(e)&&!e.install?.skillsShUrl},{key:"global / skills.sh",label:`${a("desktop.global")} / skills.sh`,matches:e=>"global"===a4(e)&&!!e.install?.skillsShUrl},{key:"global",label:a("desktop.global"),matches:e=>"global"===a4(e)&&!e.install?.skillsShUrl},{key:"path",label:a("desktop.path"),matches:e=>"path"===a4(e)}]){let n=l.filter(r);n.length>0&&e.push({key:t,label:o,skills:n})}return e.map(({key:e,label:t,skills:o})=>{let n=o.filter(e=>!e.disableModelInvocation),s=o.filter(e=>e.disableModelInvocation),i=N[e]??!1,l=i?[...n,...s]:n;return(0,r.jsxs)("div",{style:{marginBottom:6},children:[(0,r.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,r.jsxs)("button",{type:"button",onClick:()=>L(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,r.jsx)("span",{style:{fontSize:8},children:i?"▾":"▸"}),a("desktop.dormant")," (",s.length,")"]}),l.map(e=>{let t,o,n=!b&&h===e.filePath,s=e.disableModelInvocation;return(0,r.jsxs)("div",{onClick:()=>{f(e.filePath),w(!1)},style:{display:"flex",alignItems:"center",gap:7,padding:"8px 8px",borderRadius:5,cursor:"pointer",background:n?"var(--bg-selected)":"none"},onMouseEnter:e=>{n||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{n||(e.currentTarget.style.background="none")},children:[(0,r.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,r.jsx)("span",{style:{fontSize:12,fontWeight:n?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=a5(e))?j[t]:void 0,o?.state!=="update-available"?null:(0,r.jsx)("span",{title:a("desktop.updateAvailable"),style:{color:"#d97706",fontSize:13,lineHeight:1,flexShrink:0},children:"↑"}))]},e.filePath)})]},e)})})()}),(0,r.jsx)("div",{style:{padding:"8px 6px",borderTop:"1px solid var(--border)",flexShrink:0},children:(0,r.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,r.jsx)(x.c,{size:13}),a("desktop.addSkill")]})})]}),(0,r.jsx)("div",{style:{flex:1,overflowY:"auto",padding:20},children:b?(0,r.jsx)(a9,{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:F,onInstalled:()=>{A()}}):c?null:U?(0,r.jsx)(a7,{skill:U,cwd:e,onToggle:B,toggling:m.has(U.filePath),saveError:v,updateStatus:a5(U)?j[a5(U)]:void 0,checkingUpdate:!!a5(U)&&C.has(a5(U)),updating:I===a5(U),updateError:P,onCheckUpdate:()=>void O(U),onUpdate:()=>void H(U)},U.filePath):(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-dim)",fontSize:13},children:a("desktop.selectSkill")})})]}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 18px",borderTop:"1px solid var(--border)",flexShrink:0},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10},children:[l.some(e=>!!e.install)&&(0,r.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,r.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,r.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 lt(){let{t:e}=(0,E.s)(),[t,o]=(0,n.useState)([]),[s,i]=(0,n.useState)(""),[a,l]=(0,n.useState)(""),[d,c]=(0,n.useState)(""),[p,u]=(0,n.useState)(""),[g,h]=(0,n.useState)(!0),[f,x]=(0,n.useState)(null),m=(0,n.useCallback)(async()=>{h(!0),x(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){x(e instanceof Error?e.message:String(e))}finally{h(!1)}},[]);(0,n.useEffect)(()=>{m()},[m]);let k=(0,n.useMemo)(()=>[...new Set(t.map(e=>e.source).filter(Boolean))].sort(),[t]),v=(0,n.useMemo)(()=>[...new Set(t.map(e=>e.statusCode).filter(e=>void 0!==e))].sort((e,t)=>e-t),[t]),y=(0,n.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){x(e instanceof Error?e.message:String(e))}},S=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 tA(t),x(null)}catch(e){x(e instanceof Error?e.message:String(e))}};return(0,r.jsxs)("div",{style:{flex:1,minWidth:0,minHeight:0,overflow:"auto",padding:"18px 20px",display:"flex",flexDirection:"column",gap:12},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[(0,r.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,r.jsx)("option",{value:"",children:e("desktop.logsAllLevels")}),["error","warning","info"].map(e=>(0,r.jsx)("option",{value:e,children:e},e))]}),(0,r.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,r.jsx)("option",{value:"",children:e("desktop.logsAllCodes")}),v.map(e=>(0,r.jsx)("option",{value:e,children:e},e))]}),(0,r.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,r.jsx)("option",{value:"",children:e("desktop.logsAllSources")}),k.map(e=>(0,r.jsx)("option",{value:e,children:e},e))]}),(0,r.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,r.jsx)("button",{type:"button",onClick:()=>void m(),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,r.jsx)(w.S,{size:14})}),(0,r.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,r.jsx)(j.l,{size:14})})]}),g&&(0,r.jsx)("div",{style:{color:"var(--text-muted)",fontSize:12},children:e("desktop.loading")}),f&&(0,r.jsx)("div",{style:{color:"#ef4444",fontSize:12},children:f}),!g&&!f&&0===y.length&&(0,r.jsx)("div",{style:{color:"var(--text-muted)",fontSize:12},children:e("desktop.logsEmpty")}),(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:8},children:y.map(t=>(0,r.jsxs)("details",{style:{border:"1px solid var(--border)",borderRadius:7,background:"var(--bg-panel)",padding:"8px 10px"},children:[(0,r.jsxs)("summary",{style:{cursor:"pointer",color:"error"===t.level?"#ef4444":"warning"===t.level?"#f59e0b":"var(--text)",fontSize:12},children:[(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",marginRight:8},children:t.statusCode??"—"}),(0,r.jsx)("span",{style:{marginRight:8},children:new Date(t.timestamp).toLocaleString()}),(0,r.jsx)("span",{style:{overflowWrap:"anywhere"},children:t.message.length>180?`${t.message.slice(0,180)}…`:t.message})]}),(0,r.jsxs)("div",{style:{padding:"8px 0 0 18px",color:"var(--text-muted)",fontSize:11,lineHeight:1.5,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:[(0,r.jsxs)("div",{children:[t.source,t.provider?` \xb7 ${t.provider}`:"",t.model?` \xb7 ${t.model}`:""]}),(0,r.jsx)("div",{style:{marginTop:5,maxHeight:260,overflow:"auto"},children:t.message}),t.details&&(0,r.jsx)("div",{style:{marginTop:5,maxHeight:260,overflow:"auto"},children:t.details}),(0,r.jsx)("button",{type:"button",onClick:()=>void S(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 lo={padding:"7px 9px",background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:6,color:"var(--text)",fontSize:12,width:"100%"},lr={padding:"6px 12px",border:"none",borderRadius:6,background:"var(--accent)",color:"#fff",cursor:"pointer",fontSize:12};function ln(){let{t:e}=(0,E.s)(),[t,o]=(0,n.useState)([]),[s,i]=(0,n.useState)(!0),[a,l]=(0,n.useState)(null),[d,p]=(0,n.useState)(""),[u,h]=(0,n.useState)(""),[f,m]=(0,n.useState)(!1),[k,v]=(0,n.useState)(null),y=(0,n.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,n.useEffect)(()=>{y()},[y]);let b=(0,n.useCallback)(()=>{window.dispatchEvent(new Event("pi:snippets-changed"))},[]),w=()=>{l(null),p(""),h(""),v(null)},S=(0,n.useCallback)(async()=>{let t=d.trim();if(!t)return void v(e("desktop.snippetNameRequired"));m(!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{m(!1)}},[a,d,u,y,b,e]),C=(0,n.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,r.jsxs)(iX,{children:[(0,r.jsx)(iZ,{children:(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:7,padding:"12px 0"},children:[(0,r.jsx)(rP.c,{size:15,"aria-hidden":"true"}),(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{style:{fontSize:13,fontWeight:600,color:"var(--text)"},children:e("desktop.snippets")}),(0,r.jsx)("div",{style:{fontSize:11,color:"var(--text-muted)",marginTop:2},children:e("desktop.snippetsDesc")})]})]})}),(0,r.jsx)(iZ,{children:(0,r.jsxs)("div",{style:{width:"100%"},children:[(0,r.jsxs)("div",{style:{display:"flex",gap:6,flexWrap:"wrap",marginBottom:8},children:[(0,r.jsx)("button",{type:"button",onClick:w,style:lr,children:(0,r.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:5},children:[(0,r.jsx)(x.F,{size:13})," ",e("desktop.snippetNew")]})}),a&&(0,r.jsx)("button",{type:"button",onClick:w,style:{...lr,background:"var(--bg-hover)",color:"var(--text-muted)"},children:(0,r.jsx)(c.X,{size:13})})]}),(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"minmax(120px, 200px) 1fr",gap:8,alignItems:"start",marginBottom:8},children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",display:"block",marginBottom:4},children:e("desktop.snippetName")}),(0,r.jsx)("input",{value:d,onChange:e=>p(e.target.value),placeholder:"#name",style:lo})]}),(0,r.jsxs)("div",{children:[(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",display:"block",marginBottom:4},children:e("desktop.snippetContent")}),(0,r.jsx)("textarea",{value:u,onChange:e=>h(e.target.value),rows:3,style:{...lo,resize:"vertical",fontFamily:"var(--font-mono)",fontSize:11}})]})]}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10,marginBottom:10},children:[(0,r.jsx)("button",{type:"button",onClick:()=>void S(),disabled:f,style:{...lr,cursor:f?"wait":"pointer"},children:e("desktop.snippetSave")}),k&&(0,r.jsx)("span",{style:{color:"var(--status-error, #ef4444)",fontSize:12},children:k})]}),s?(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-dim)"},children:e("desktop.loadingThemes")}):0===t.length?(0,r.jsx)(i0,{children:e("desktop.snippetEmpty")}):(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:4},children:t.map(t=>(0,r.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,r.jsx)("span",{style:{color:"var(--accent)",fontFamily:"var(--font-mono)",fontSize:11},children:"#"}),(0,r.jsx)("span",{style:{fontWeight:600,fontSize:12,flexShrink:0},children:t.name}),(0,r.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,r.jsx)("button",{type:"button",onClick:()=>{l(t),p(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,r.jsx)(g.I,{size:13})}),(0,r.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,r.jsx)(j.l,{size:13})})]},t.id))})]})}),(0,r.jsx)(iQ,{children:(0,r.jsx)(i0,{children:e("desktop.snippetHint")})})]})}let ls=["async","group","smart"],li=["full","compact","custom"],la=["all","background","off"],ll={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 ld(){return{fontSize:12,color:"var(--text-muted)"}}function lc({cwd:e,sessionId:t}){let{t:o}=(0,E.s)(),[s,i]=(0,n.useState)({}),[a,l]=(0,n.useState)([]),[d,c]=(0,n.useState)(""),[p,u]=(0,n.useState)(!1),[g,h]=(0,n.useState)(null),[f,x]=(0,n.useState)(!1),[m,k]=(0,n.useState)(null),[v,y]=(0,n.useState)(!1),[b,w]=(0,n.useState)([]),[j,S]=(0,n.useState)({}),C=(0,n.useCallback)(async()=>{h(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){h(e instanceof Error?e.message:String(e))}finally{u(!0)}},[]);(0,n.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,n.useEffect)(()=>{C()},[C]);let T=(0,n.useCallback)((e,t)=>{i(o=>({...o,[e]:t})),y(!1),k(null)},[]),R=(0,n.useCallback)(async()=>{x(!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{x(!1)}},[s]),z=(0,n.useRef)({}),I=(0,n.useCallback)(async(e,t)=>{let o=(z.current[e]??0)+1;z.current[e]=o,S(t=>({...t,[e]:"saving"}));try{let r=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 n=await r.json();if(!r.ok||n.error)throw Error(n.error??`HTTP ${r.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,r.jsx)(iZ,{children:(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"minmax(150px, 240px) 1fr",gap:"8px 12px",alignItems:"center",padding:"8px 0"},children:[(0,r.jsx)("span",{style:ld(),children:o(t)}),(0,r.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:ll})]})},e),P=(e,t,n)=>(0,r.jsx)(iZ,{children:(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"minmax(150px, 240px) 1fr",gap:"8px 12px",alignItems:"center",padding:"8px 0"},children:[(0,r.jsx)("span",{style:ld(),children:o(t)}),(0,r.jsx)("select",{value:s[e]??n[0],onChange:t=>T(e,t.target.value),style:{...ll,fontFamily:"var(--font-mono)"},children:n.map(e=>(0,r.jsx)("option",{value:e,children:e},e))})]})},e),D=(e,t,n)=>(0,r.jsx)(iZ,{children:(0,r.jsx)(iE,{checked:s[e]??!1,onChange:t=>T(e,t),label:o(t),description:n?o(n):void 0})},e);return(0,r.jsx)("div",{style:{flex:1,overflow:"auto",minWidth:0,padding:"20px 22px",display:"flex",flexDirection:"column",gap:16},children:(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:p?g?(0,r.jsx)("div",{style:{fontSize:12,color:"#ef4444"},children:g}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:14,fontWeight:700,color:"var(--text)"},children:o("desktop.subagents")}),(0,r.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,r.jsx)(i0,{children:o("desktop.subagentsDesc")}),(0,r.jsxs)(iX,{children:[M("maxConcurrent","desktop.subagentsMaxConcurrent"),M("defaultMaxTurns","desktop.subagentsDefaultMaxTurns"),M("graceTurns","desktop.subagentsGraceTurns"),P("defaultJoinMode","desktop.subagentsJoinMode",ls),P("widgetMode","desktop.subagentsWidgetMode",la),P("toolDescriptionMode","desktop.subagentsToolDescMode",li),D("schedulingEnabled","desktop.subagentsScheduling","desktop.subagentsSchedulingDesc"),D("scopeModels","desktop.subagentsScopeModels","desktop.subagentsScopeModelsDesc"),D("disableDefaultAgents","desktop.subagentsDisableDefault","desktop.subagentsDisableDefaultDesc"),D("fleetView","desktop.subagentsFleetView","desktop.subagentsFleetViewDesc"),(0,r.jsx)(iQ,{children:D("outputTranscript","desktop.subagentsOutputTranscript","desktop.subagentsOutputTranscriptDesc")})]}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10},children:[(0,r.jsx)("button",{type:"button",onClick:()=>void R(),disabled:f,style:{padding:"7px 12px",border:"none",borderRadius:6,background:"var(--accent)",color:"#fff",cursor:f?"wait":"pointer",fontSize:12},children:f?o("desktop.saving"):o("desktop.mcpSave")}),v&&(0,r.jsx)("span",{style:{color:"#22c55e",fontSize:12},children:o("desktop.subagentsSaved")}),m&&(0,r.jsx)("span",{style:{color:"#ef4444",fontSize:12},children:m}),(0,r.jsx)(ai,{sessionId:t})]}),a.length>0&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:7,fontSize:13,fontWeight:600,color:"var(--text)"},children:[(0,r.jsx)(iS.d,{size:15,"aria-hidden":"true"}),o("desktop.subagentsDiscovered")]}),(0,r.jsx)(iX,{children:a.map((e,t)=>(0,r.jsx)(iQ,{children:(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:3,padding:t===a.length-1?"12px 0":"12px 0 0"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[(0,r.jsx)("span",{style:{fontSize:12.5,fontWeight:600,color:"var(--text)",fontFamily:"var(--font-mono)"},children:e.name}),e.displayName&&(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-muted)"},children:e.displayName}),e.model&&(0,r.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,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6,flexWrap:"wrap"},children:[(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-muted)"},children:o("desktop.subagentsModel")}),(0,r.jsxs)("select",{value:e.model??"",onChange:t=>void I(e.name,t.target.value||null),style:{...ll,width:"min(260px, 100%)",maxWidth:260},children:[(0,r.jsx)("option",{value:"",children:o("desktop.subagentsModelDefault")}),e.model&&!b.some(t=>`${t.provider}/${t.id}`===e.model)&&(0,r.jsx)("option",{value:e.model,children:e.model}),b.map(e=>(0,r.jsxs)("option",{value:`${e.provider}/${e.id}`,children:[e.name,"(",e.provider,"/",e.id,")"]},`${e.provider}/${e.id}`))]}),"saving"===j[e.name]&&(0,r.jsxs)("span",{style:{fontSize:10,color:"var(--text-dim)"},children:[o("desktop.saving"),"…"]}),"saved"===j[e.name]&&(0,r.jsx)("span",{style:{fontSize:10,color:"#22c55e"},children:o("desktop.subagentsSaved")}),j[e.name]?.startsWith("error:")&&(0,r.jsx)("span",{style:{fontSize:10,color:"#ef4444"},children:j[e.name].slice(6)})]}),e.description&&(0,r.jsx)("div",{style:{fontSize:11,color:"var(--text-muted)",lineHeight:1.5},children:e.description})]})},e.name))})]})]}):(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)"},children:o("desktop.loading")})})})}function lp(e){return null==e?"—":sc(e)}function lu({sessionId:e,cwd:t}){let{t:o}=(0,E.s)(),[s,i]=(0,n.useState)(null),[a,l]=(0,n.useState)(null),[d,c]=(0,n.useState)(!1);(0,n.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,n.useCallback)(async()=>{c(!0);try{let e=await fetch("/api/usage");e.ok&&l(await e.json())}catch{}finally{c(!1)}},[]);(0,n.useEffect)(()=>{p()},[p]);let u=(0,n.useMemo)(()=>a?.daily.slice(-14)??[],[a]),g=(0,n.useMemo)(()=>u.reduce((e,t)=>Math.max(e,t.tokens),0),[u]);return(0,r.jsxs)("div",{style:{flex:1,overflow:"auto",minWidth:0,padding:"16px 20px",display:"flex",flexDirection:"column",gap:16},children:[(0,r.jsx)("h3",{style:{margin:0,fontSize:15,fontWeight:600,color:"var(--text)"},children:o("desktop.usage")}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text-muted)"},children:o("desktop.usageSession")}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:12},children:[e?(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:12,borderRadius:12,border:"1px solid var(--border)",padding:16},children:s?(0,r.jsx)(r.Fragment,{children:(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:16},children:[(0,r.jsxs)("svg",{width:72,height:72,viewBox:"0 0 72 72",style:{flexShrink:0},children:[(0,r.jsx)("circle",{cx:36,cy:36,r:30,fill:"none",stroke:"var(--border)",strokeWidth:7}),(0,r.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,r.jsx)("text",{x:36,y:41,textAnchor:"middle",fontSize:15,fontWeight:700,fill:"var(--text)",children:null!=s.percent?`${s.percent.toFixed(0)}%`:"?"})]}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:3},children:[(0,r.jsx)("span",{style:{fontSize:13,color:"var(--text)"},children:o("desktop.usageContext",{used:lp(s.tokens),window:lp(s.contextWindow)})}),(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)"},children:o("desktop.usageContextHint")})]})]})}):(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)"},children:o("desktop.usageNoSessionData")})}):(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)"},children:o("desktop.usageNoSession")}),t&&(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:t})]})]}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text-muted)"},children:o("desktop.usageGlobal")}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,r.jsx)("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(140px, 1fr))",gap:10},children:[{label:o("desktop.usageTotal"),value:lp(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,r.jsxs)("div",{style:{borderRadius:12,border:"1px solid var(--border)",padding:"12px 14px",background:"var(--bg-panel)"},children:[(0,r.jsx)("div",{style:{fontSize:11,color:"var(--text-muted)",marginBottom:4},children:e.label}),(0,r.jsx)("div",{style:{fontSize:18,fontWeight:700,color:"var(--text)"},children:e.value}),(0,r.jsx)("div",{style:{fontSize:10.5,color:"var(--text-dim)",marginTop:2},children:e.sub})]},e.label))}),(0,r.jsxs)("div",{style:{borderRadius:12,border:"1px solid var(--border)",padding:"14px 16px"},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)",marginBottom:10},children:o("desktop.usageDaily")}),0===u.length?(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)"},children:o(d?"desktop.featuresLoading":"desktop.usageNoData")}):(0,r.jsx)("div",{style:{display:"flex",alignItems:"flex-end",gap:6,height:96,overflowX:"auto"},children:u.map(e=>{let t=g>0?Math.max(4,Math.round(e.tokens/g*72)):4;return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",gap:4,flexShrink:0},children:[(0,r.jsx)("div",{style:{fontSize:9,color:"var(--text-dim)"},children:e.tokens>0?lp(e.tokens):""}),(0,r.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}: ${lp(e.tokens)}`}),(0,r.jsx)("div",{style:{fontSize:9,color:"var(--text-dim)"},children:e.day.slice(5)})]},e.day)})})]}),(0,r.jsxs)("div",{style:{borderRadius:12,border:"1px solid var(--border)",overflow:"hidden"},children:[(0,r.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,r.jsx)("div",{style:{padding:"14px",fontSize:12,color:"var(--text-muted)"},children:o("desktop.usageNoData")}):(a?.sessions??[]).slice(0,12).map(e=>(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"8px 14px",borderBottom:"1px solid var(--border)"},children:[(0,r.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,r.jsx)("span",{style:{flexShrink:0,fontSize:11,color:"var(--text-muted)",fontFamily:"var(--font-mono)"},children:lp(e.tokens)})]},e.path))]})]})]})]})}function lg(){let{t:e}=(0,E.s)(),[t,o]=(0,n.useState)(!1),[s,i]=(0,n.useState)("");(0,n.useEffect)(()=>{o(new URLSearchParams(window.location.search).has("piweb_connected")),i(window.location.host)},[]);let a=(0,n.useCallback)(()=>{window.location.href="piweb-switch://manage"},[]);return t?(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",flex:1,minWidth:0,minHeight:0,overflowY:"auto"},children:[(0,r.jsx)("header",{style:{padding:"18px 22px 14px",borderBottom:"1px solid var(--border)"},children:(0,r.jsx)("h1",{style:{margin:0,fontSize:16,fontWeight:700,color:"var(--text)"},children:e("desktop.server")})}),(0,r.jsxs)("div",{style:{padding:"18px 22px",display:"flex",flexDirection:"column",gap:14},children:[(0,r.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,r.jsx)(ik.X,{size:18,color:"var(--accent)"}),(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)"},children:e("desktop.serverCurrent")}),(0,r.jsx)("div",{style:{fontSize:14,fontWeight:600,color:"var(--text)",fontFamily:"var(--font-mono)",wordBreak:"break-all"},children:s})]})]}),(0,r.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,r.jsx)(i3.o,{size:16}),e("desktop.serverSwitch")]}),(0,r.jsx)("p",{style:{margin:0,fontSize:12.5,lineHeight:1.7,color:"var(--text-muted)"},children:e("desktop.serverSwitchHint")})]})]}):null}let lh=[{id:"server",labelKey:"desktop.server",Icon:ik.X},{id:"display",labelKey:"desktop.display",Icon:iv.V},{id:"chat",labelKey:"desktop.chat",Icon:iy.W},{id:"models",labelKey:"desktop.models",Icon:C.f},{id:"skills",labelKey:"desktop.skills",Icon:T.B},{id:"plugins",labelKey:"desktop.plugins",Icon:R.F},{id:"proxy",labelKey:"desktop.proxy",Icon:ib.l},{id:"features",labelKey:"desktop.features",Icon:p.l},{id:"logs",labelKey:"desktop.logs",Icon:v.B},{id:"snippets",labelKey:"desktop.snippets",Icon:rP.c},{id:"usage",labelKey:"desktop.usage",Icon:iw._},{id:"mcp",labelKey:"desktop.mcp",Icon:ij.b},{id:"subagents",labelKey:"desktop.subagents",Icon:iS.d},{id:"backup",labelKey:"desktop.backup",Icon:oj.W},{id:"import",labelKey:"desktop.importSessions",Icon:z.z}];function lf({initialTab:e="models",cwd:t,sessionId:o,onCloseAction:s,onModelsSavedAction:i,onSessionReloadedAction:a,onSessionsChanged:l}){let d=$(),{t:p}=(0,E.s)(),[u,g]=(0,n.useState)("skills"===e||"plugins"===e?t?e:"display":e),[h,f]=(0,n.useState)(!1);(0,n.useEffect)(()=>{f(new URLSearchParams(window.location.search).has("piweb_connected"))},[]);let x=h?lh:lh.filter(({id:e})=>"server"!==e),[m,k]=(0,n.useState)(!1),[v,y]=(0,n.useState)(null),b=(0,n.useRef)(new Set),w=(0,n.useCallback)(e=>(b.current.add(e),()=>{b.current.delete(e)}),[]),j=(0,n.useCallback)(async()=>{if(!m){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)}}},[m,s]);return(0,r.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,r.jsxs)("section",{role:"dialog","aria-modal":"true","aria-label":p("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,r.jsxs)("header",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 18px",borderBottom:"1px solid var(--border)",flexShrink:0},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"baseline",gap:10,minWidth:0},children:[(0,r.jsx)("span",{style:{fontSize:15,fontWeight:700,color:"var(--text)"},children:p("desktop.settings")}),"models"===u?(0,r.jsx)("code",{style:{fontSize:11,color:"var(--text-muted)",fontFamily:"var(--font-mono)"},children:"~/.pi/agent/models.json"}):t&&(0,r.jsx)("code",{style:{fontSize:11,color:"var(--text-muted)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:t})]}),(0,r.jsx)("button",{type:"button",onClick:()=>{j()},disabled:m,title:p("desktop.closeSettings"),"aria-label":p("desktop.closeSettings"),style:{background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",padding:4,display:"flex"},children:(0,r.jsx)(c.X,{size:18,"aria-hidden":"true"})})]}),(0,r.jsxs)("div",{style:{flex:1,display:"flex",flexDirection:d?"column":"row",minHeight:0,overflow:"hidden",pointerEvents:m?"none":void 0},children:[(0,r.jsx)("nav",{"aria-label":p("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:x.filter(({id:e})=>!(d&&"import"===e)).map(({id:e,labelKey:o,Icon:n})=>{let s=("skills"===e||"plugins"===e)&&!t,i=u===e;return(0,r.jsxs)("button",{type:"button",disabled:s,onClick:()=>g(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:p(o),"aria-label":p(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,r.jsx)(n,{size:16,"aria-hidden":"true"}),!d&&(0,r.jsx)("span",{children:p(o)})]},e)})}),(0,r.jsx)("div",{style:{display:"server"===u?"flex":"none",flex:1,minWidth:0,minHeight:0},children:(0,r.jsx)(lg,{})}),(0,r.jsx)("div",{style:{display:"display"===u?"flex":"none",flex:1,minWidth:0,minHeight:0},children:(0,r.jsx)(iG,{})}),(0,r.jsx)("div",{style:{display:"chat"===u?"flex":"none",flex:1,minWidth:0,minHeight:0},children:(0,r.jsx)(iW,{})}),(0,r.jsx)("div",{style:{display:"models"===u?"flex":"none",flex:1,minWidth:0,minHeight:0},children:(0,r.jsx)(aA,{embedded:!0,sessionId:o,onSavedAction:i,onRegisterFlush:w})}),t&&(0,r.jsx)("div",{style:{display:"skills"===u?"flex":"none",flex:1,minWidth:0,minHeight:0},children:(0,r.jsx)(le,{cwd:t,embedded:!0,sessionId:o})}),t&&(0,r.jsx)("div",{style:{display:"plugins"===u?"flex":"none",flex:1,minWidth:0,minHeight:0},children:(0,r.jsx)(aQ,{cwd:t,sessionId:o,embedded:!0,onReloadedAction:a})}),(0,r.jsx)("div",{style:{display:"proxy"===u?"flex":"none",flex:1,minWidth:0,minHeight:0},children:(0,r.jsx)(a1,{})}),(0,r.jsx)("div",{style:{display:"features"===u?"flex":"none",flex:1,minWidth:0,minHeight:0},children:(0,r.jsx)(i5,{})}),(0,r.jsx)("div",{style:{display:"logs"===u?"flex":"none",flex:1,minWidth:0,minHeight:0},children:(0,r.jsx)(lt,{})}),(0,r.jsx)("div",{style:{display:"snippets"===u?"flex":"none",flex:1,minWidth:0,minHeight:0},children:(0,r.jsx)(ln,{})}),(0,r.jsx)("div",{style:{display:"usage"===u?"flex":"none",flex:1,minWidth:0,minHeight:0},children:(0,r.jsx)(lu,{sessionId:o,cwd:t})}),(0,r.jsx)("div",{style:{display:"mcp"===u?"flex":"none",flex:1,minWidth:0,minHeight:0},children:(0,r.jsx)(ag,{sessionId:o})}),(0,r.jsx)("div",{style:{display:"subagents"===u?"flex":"none",flex:1,minWidth:0,minHeight:0},children:(0,r.jsx)(lc,{cwd:t,sessionId:o})}),(0,r.jsx)("div",{style:{display:"backup"===u?"flex":"none",flex:1,minWidth:0,minHeight:0},children:(0,r.jsx)(iz,{cwd:t})}),(0,r.jsx)("div",{style:{display:"import"===u?"flex":"none",flex:1,minWidth:0,minHeight:0,overflowY:"auto"},children:(0,r.jsx)(i7,{onSessionsChanged:l})})]}),v&&(0,r.jsx)("div",{style:{padding:"6px 18px",borderTop:"1px solid var(--border)",color:"#f87171",fontSize:11},children:v})]})})}let lx=new Set(["awaiting_input","review","failed"]),lm=(0,n.createContext)(null);function lk(){let e=(0,n.useContext)(lm);if(!e)throw Error("useTasksView must be used within TasksViewProvider");return e}function lv({children:e}){let{t}=(0,E.s)(),o=(0,n.useRef)(t);(0,n.useEffect)(()=>{o.current=t},[t]);let[s,i]=(0,n.useState)([]),[a,l]=(0,n.useState)([]),d=(0,n.useRef)(0),c=(0,n.useCallback)(async()=>{let e=++d.current;try{let t=await (0,r2.Wt)(),o=(await Promise.all(t.map(e=>(0,r2.Vk)(e).catch(()=>[])))).flat().sort((e,t)=>t.id-e.id);if(e!==d.current)return;l(e=>ly(e,t)?e:t),i(e=>ly(e,o)?e:o)}catch{}},[]);(0,n.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 r=()=>{"visible"===document.visibilityState&&c()},n=()=>void c();document.addEventListener("visibilitychange",r),window.addEventListener("online",n);let s=setInterval(()=>void c(),6e4);return()=>{t=!0,e?.close(),document.removeEventListener("visibilitychange",r),window.removeEventListener("online",n),clearInterval(s)}},[c]);let p=(0,n.useMemo)(()=>s.filter(e=>lx.has(e.status)&&null==e.archivedAt).length,[s]),u=(0,n.useRef)(null);(0,n.useEffect)(()=>{let e=u.current;if((u.current=new Map(s.map(e=>[e.id,e.status])),e&&0!==s.length)&&"Notification"in window){for(let 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 r=()=>{try{new Notification(e,{body:t,tag:"pi-tasks"})}catch{}o()};"granted"===Notification.permission?r():"denied"!==Notification.permission?Notification.requestPermission().then(e=>{"granted"===e?r():o()}):o()})}("Pi Web Tasks",e)}catch{}}},[s,t]);let g=(0,n.useMemo)(()=>({tasks:s,projects:a,attentionCount:p,refetch:c}),[s,a,p,c]);return(0,r.jsx)(lm.Provider,{value:g,children:e})}function ly(e,t){return JSON.stringify(e)===JSON.stringify(t)}var lb=o(4539),lw=o(12449),lj=o(2571);let lS=["todo","inProgress","attention","done"];function lC(e){return"review"===e.status&&0===e.filesChanged}function lT(){return{defaultAgentType:null,modeId:null,configValues:{},autoProcess:!0,maxConcurrent:1,mergeStrategy:"merge",deleteWorktreeDefault:!0,preflightCommand:null,initCommand:null,stagePrompts:null}}let lR=["todo","inProgress","attention","done"],lz={todo:{id:"todo",marker:"var(--text-dim)"},inProgress:{id:"inProgress",marker:"var(--accent)"},attention:{id:"attention",marker:"#f59e0b"},done:{id:"done",marker:"#10b981"}};var lI=o(54775),lM=o(98998),lE=o(36668);function lP({task:e}){let{t}=(0,E.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)),n={display:"inline-flex",alignItems:"center",gap:4,borderRadius:999,padding:"2px 8px",fontSize:10,fontWeight:600,lineHeight:1.4,flexShrink:0,whiteSpace:"nowrap"};switch(e.status){case"queued":case"preparing":case"running":case"merging":return(0,r.jsxs)("span",{style:{...n,color:"var(--accent)"},children:[(0,r.jsx)(lI.N,{size:11,className:"pi-spin",style:{animation:"pi-spin 1s linear infinite"},"aria-hidden":"true"}),o]});case"awaiting_input":case"review":return(0,r.jsx)("span",{style:{...n,border:"1px solid rgba(245,158,11,0.45)",background:"rgba(245,158,11,0.08)",color:"#d97706"},children:o});case"done":return(0,r.jsxs)("span",{style:{...n,background:"rgba(16,185,129,0.12)",color:"#059669"},children:[(0,r.jsx)(u.J,{size:10,weight:"bold","aria-hidden":"true"}),o]});case"failed":return(0,r.jsx)("span",{style:{...n,background:"rgba(239,68,68,0.12)",color:"#dc2626"},children:o});default:return(0,r.jsx)("span",{style:{...n,background:"var(--bg-hover)",color:"var(--text-muted)"},children:o})}}function lD({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,r.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,r.jsx)(lI.N,{size:10,style:{animation:"pi-spin 1s linear infinite"},"aria-hidden":"true"}):"passed"===t.status?(0,r.jsx)(oZ.r,{size:10,"aria-hidden":"true"}):(0,r.jsx)(sh.J,{size:10,"aria-hidden":"true"}),(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:t.command})]})}function lF({task:e,folderName:t,now:o,onOpen:n,onStart:s,onCancel:i,onRetry:a,onRequeue:l,onViewSession:d,onMerge:c,onArchive:p,onEdit:g}){let{t:h}=(0,E.s)(),f=null!=e.archivedAt,x="running"===e.status||"awaiting_input"===e.status||"merging"===e.status,m=null!=e.filesChanged&&e.filesChanged>0?(0,r.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:3,fontFamily:"var(--font-mono)",fontSize:10},children:[(0,r.jsxs)("span",{style:{color:"#059669"},children:["+",e.additions??0]}),(0,r.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 r=Math.floor(Math.max(0,t-o)/6e4);if(r<1)return"now";if(r<60)return`${r}m`;let n=Math.floor(r/60);if(n<24)return`${n}h`;let s=Math.floor(n/24);return`${s}d`}(e.finishedAt??e.settledAt??e.startedAt??e.createdAt,o),{primary:v,more:y}=(()=>{let t=[],o=null;if(f)return{primary:o={icon:sx.T,label:h("tasks.actionUnarchive"),onClick:p},more:t};switch(e.status){case"todo":o={icon:lj.j,label:h("tasks.actionStart"),onClick:s},t.push({icon:rD.S,label:h("tasks.actionEdit"),onClick:g});break;case"queued":case"preparing":case"running":case"awaiting_input":o={icon:lM.k,label:h("tasks.actionCancel"),onClick:i};break;case"review":o=lC(e)?{icon:u.J,label:h("tasks.actionComplete"),onClick:c}:{icon:lE.r,label:h("tasks.actionMerge"),onClick:c};break;case"merging":break;case"failed":o={icon:w.S,label:h("tasks.actionRetry"),onClick:a},t.push({icon:rD.S,label:h("tasks.actionEdit"),onClick:g}),t.push({icon:sx.T,label:h("tasks.actionArchive"),onClick:p});break;case"done":o={icon:sx.T,label:h("tasks.actionArchive"),onClick:p};break;case"canceled":o={icon:oQ.f,label:h("tasks.actionRequeue"),onClick:l},t.push({icon:sx.T,label:h("tasks.actionArchive"),onClick:p})}return{primary:o,more:t}})(),b=[...y];return null!=e.conversationId&&b.push({icon:oX.y,label:h("tasks.actionViewSession"),onClick:d}),(0,r.jsxs)("div",{role:"button",tabIndex:0,onClick:n,onKeyDown:e=>{("Enter"===e.key||" "===e.key)&&(e.preventDefault(),n())},style:{display:"flex",flexDirection:"column",cursor:"pointer",borderRadius:12,border:"1px solid color-mix(in srgb, var(--border) 85%, transparent)",background:"var(--bg-panel)",padding:12,textAlign:"left",transition:"border-color 0.12s",opacity:f?.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,r.jsxs)("div",{style:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:8},children:[(0,r.jsx)("span",{style:{minWidth:0,overflowWrap:"break-word",fontSize:13,fontWeight:500,lineHeight:1.4},children:e.title}),(0,r.jsx)(lP,{task:e})]}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:"2px 6px",marginTop:6,fontSize:11,color:"var(--text-muted)"},children:[t?(0,r.jsx)("span",{style:{maxWidth:160,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:t}):null,t&&e.workBranch?(0,r.jsx)("span",{style:{opacity:.5},children:"/"}):null,e.workBranch?(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:10,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",maxWidth:180},children:e.workBranch}):null,(t||e.workBranch)&&(m||k)?(0,r.jsx)("span",{style:{opacity:.5},children:"\xb7"}):null,m,m&&k?(0,r.jsx)("span",{style:{opacity:.5},children:"\xb7"}):null,k?(0,r.jsx)("span",{style:{flexShrink:0},children:k}):null,(0,r.jsx)(lD,{task:e})]}),e.lastError&&("failed"===e.status||"review"===e.status)?(0,r.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,r.jsx)(oS.t,{size:13,style:{flexShrink:0},"aria-hidden":"true"}),(0,r.jsx)("span",{style:{minWidth:0,flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.lastError}),(0,r.jsx)("button",{type:"button",style:{flexShrink:0,fontWeight:600,background:"none",border:"none",cursor:"pointer",color:"inherit",fontSize:11,textDecoration:"underline"},onClick:e=>{e.stopPropagation(),n()},children:h("tasks.errorView")})]}):null,"review"===e.status&&e.resultSummary?(0,r.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,x&&e.latestProgress?(0,r.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,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6,marginTop:12,paddingTop:12,borderTop:"1px solid var(--border)"},children:[v?(0,r.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,r.jsx)(v.icon,{size:12,weight:"bold","aria-hidden":"true"}),v.label]}):null,(0,r.jsx)("div",{style:{flex:1}}),b.map(e=>(0,r.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,r.jsx)(e.icon,{size:13,"aria-hidden":"true"})},e.label))]}):null]})}function lW({open:e,onOpenChange:t,task:o}){let{t:s}=(0,E.s)(),{refetch:i}=lk(),[a,l]=(0,n.useState)(""),[d,p]=(0,n.useState)(!1);if((0,n.useEffect)(()=>{e&&(l(""),p(!1))},[e,o]),!e||!o)return null;let u=async()=>{if(!d){p(!0);try{await (0,r2.oQ)(o.id,o.projectRoot,"cancel",{reason:a.trim()||null}),t(!1),i()}catch(e){console.error("cancel failed",e)}finally{p(!1)}}};return(0,r.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,r.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,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"14px 16px 0"},children:[(0,r.jsx)("h3",{style:{fontSize:15,fontWeight:600,margin:0},children:s("tasks.cancelTitle")}),(0,r.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,r.jsx)(c.X,{size:16,"aria-hidden":"true"})})]}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:12,padding:"14px 16px 16px"},children:[(0,r.jsx)("p",{style:{margin:0,fontSize:12,lineHeight:1.5,color:"var(--text-muted)"},children:s("tasks.cancelDescription")}),(0,r.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:5},children:[(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)"},children:s("tasks.cancelReasonLabel")}),(0,r.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,r.jsxs)("div",{style:{display:"flex",justifyContent:"flex-end",gap:8,marginTop:4},children:[(0,r.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,r.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 l$({open:e,onOpenChange:t,task:o}){let{t:s}=(0,E.s)(),{refetch:i}=lk(),[a,l]=(0,n.useState)(!0),[d,p]=(0,n.useState)(!1),u=o?.worktreePath!=null;if((0,n.useEffect)(()=>{if(!e||!o)return;p(!1);let t=!1;return(0,r2.CG)(o.projectRoot).then(e=>{t||l(e.deleteWorktreeDefault)}).catch(()=>{t||l(!0)}),()=>{t=!0}},[e,o]),!e||!o)return null;let g=async()=>{if(!d){p(!0);try{await (0,r2.ZX)(o.id,o.projectRoot,u&&a),t(!1),i()}catch(e){console.error("complete failed",e)}finally{p(!1)}}};return(0,r.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,r.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,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"14px 16px 0"},children:[(0,r.jsx)("h3",{style:{fontSize:15,fontWeight:600,margin:0},children:s("tasks.completeTitle")}),(0,r.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,r.jsx)(c.X,{size:16,"aria-hidden":"true"})})]}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:12,padding:"14px 16px 16px"},children:[(0,r.jsx)("p",{style:{margin:0,fontSize:12,lineHeight:1.5,color:"var(--text-muted)"},children:s("tasks.completeDescription")}),u?(0,r.jsxs)("label",{style:{display:"flex",alignItems:"center",gap:8,fontSize:13,cursor:"pointer"},children:[(0,r.jsx)("input",{type:"checkbox",checked:a,onChange:e=>l(e.target.checked),style:{accentColor:"var(--accent)"}}),s("tasks.completeDeleteWorktree")]}):null,(0,r.jsxs)("div",{style:{display:"flex",justifyContent:"flex-end",gap:8,marginTop:4},children:[(0,r.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,r.jsx)("button",{type:"button",onClick:()=>void g(),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 lN=o(51285),lL=o(16894);function lA({open:e,onOpenChange:t,task:o,onViewSession:s,onMerge:i,onEdit:a,onCancel:l,onRetry:d,onRequeue:p,onComplete:g}){let{t:h}=(0,E.s)(),{refetch:f}=lk(),[x,k]=(0,n.useState)([]),[v,y]=(0,n.useState)([]),[b,S]=(0,n.useState)(null),[C,T]=(0,n.useState)(null),[R,z]=(0,n.useState)(!1),[I,M]=(0,n.useState)(!1),[P,D]=(0,n.useState)(""),[F,W]=(0,n.useState)(!1),[$,N]=(0,n.useState)(!1),[L,A]=(0,n.useState)(!1),O=o?.id??null,H=o?.projectRoot??null,B=(0,n.useCallback)(async()=>{if(null==O||null==H)return;let[e,t]=await Promise.all([(0,r2.HB)(H,O).catch(()=>[]),o?.worktreePath?(0,r2.JH)(H,O).then(e=>e.files).catch(()=>[]):Promise.resolve([])]);k(e),y(t)},[O,H,o?.worktreePath]);(0,n.useEffect)(()=>{if(!e||null==O)return;k([]),y([]),M(!1),D(""),B();let t=window.setInterval(()=>void B(),5e3);return()=>window.clearInterval(t)},[e,O,B]);let U=(0,n.useCallback)(async e=>{A(!0);try{await e()}catch(e){console.error("detail action failed",e)}finally{A(!1),f()}},[f]),_=(0,n.useCallback)(async e=>{if(null!=H&&null!=O){z(!0);try{let t=await (0,r2.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,r2.bH)(o.id,H,$)),t(!1))},V=async()=>{null!=o&&null!=H&&P.trim()&&(await U(()=>(0,r2.in)(o.id,H,P.trim())),M(!1),D(""))};if(!e||null==o||null==H)return null;let K=[];if(null==o.archivedAt)switch(o.status){case"todo":K.push({label:h("tasks.actionStart"),icon:lj.j,onClick:()=>void U(()=>(0,r2.oQ)(o.id,H,"start")),filled:!0}),K.push({label:h("tasks.actionEdit"),icon:rD.S,onClick:()=>a(o)});break;case"queued":case"preparing":case"running":case"awaiting_input":K.push({label:h("tasks.actionCancel"),icon:lM.k,onClick:()=>l(o),danger:!0});break;case"review":K.push({label:lC(o)?h("tasks.actionComplete"):h("tasks.actionMerge"),icon:lC(o)?u.J:lN.Y,onClick:()=>lC(o)?g(o):i(o),filled:!0}),K.push({label:h("tasks.actionReturn"),icon:oQ.f,onClick:()=>M(!0)});break;case"failed":K.push({label:h("tasks.actionRetry"),icon:w.S,onClick:()=>d(o),filled:!0}),K.push({label:h("tasks.actionEdit"),icon:rD.S,onClick:()=>a(o)});break;case"done":K.push({label:h("tasks.actionArchive"),icon:sx.T,onClick:()=>void U(()=>(0,r2.et)(o.id,H,!0))});break;case"canceled":K.push({label:h("tasks.actionRequeue"),icon:oQ.f,onClick:()=>p(o),filled:!0})}else K.push({label:h("tasks.actionUnarchive"),icon:sx.T,onClick:()=>void U(()=>(0,r2.et)(o.id,H,!1))});return null!=o.conversationId&&K.push({label:h("tasks.actionViewSession"),icon:oX.y,onClick:()=>s(o)}),(0,r.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,r.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,r.jsxs)("div",{style:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:12,padding:"16px 16px 0"},children:[(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("h3",{style:{margin:0,fontSize:15,fontWeight:600,lineHeight:1.4,overflowWrap:"break-word"},children:o.title}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,marginTop:6},children:[(0,r.jsx)(lP,{task:o}),o.workBranch?(0,r.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:4,fontFamily:"var(--font-mono)",fontSize:11,color:"var(--text-muted)"},children:[(0,r.jsx)(m.Z,{size:12,"aria-hidden":"true"}),o.workBranch]}):null]})]}),(0,r.jsx)("button",{type:"button",onClick:()=>t(!1),"aria-label":h("i18n.close"),style:{background:"none",border:"none",cursor:"pointer",color:"var(--text-muted)",padding:4,display:"flex",flexShrink:0},children:(0,r.jsx)(c.X,{size:16,"aria-hidden":"true"})})]}),(0,r.jsx)("div",{style:{display:"flex",flexWrap:"wrap",gap:8,padding:"14px 16px 0"},children:K.map(e=>{let t,o;return(0,r.jsxs)("button",{type:"button",onClick:e.onClick,disabled:L,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,r.jsx)(e.icon,{size:13,weight:"bold","aria-hidden":"true"}),e.label]},e.label)})}),I&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:8,padding:"12px 16px 0"},children:[(0,r.jsx)("textarea",{value:P,onChange:e=>D(e.target.value),placeholder:h("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,r.jsxs)("div",{style:{display:"flex",justifyContent:"flex-end",gap:8},children:[(0,r.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:h("i18n.cancel")}),(0,r.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:h("tasks.returnSubmit")})]})]}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:6,padding:"14px 16px 0",fontSize:12,color:"var(--text-muted)"},children:[(0,r.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,r.jsx)("span",{style:{flexShrink:0,color:"var(--text-dim)",width:64},children:h("tasks.metaProject")}),(0,r.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontFamily:"var(--font-mono)",fontSize:11},children:o.projectRoot})]}),o.createdAt?(0,r.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,r.jsx)("span",{style:{flexShrink:0,color:"var(--text-dim)",width:64},children:h("tasks.metaCreated")}),(0,r.jsx)("span",{children:new Date(o.createdAt).toLocaleString()})]}):null,o.mergeCommit?(0,r.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,r.jsx)("span",{style:{flexShrink:0,color:"var(--text-dim)",width:64},children:h("tasks.metaCommit")}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:11},children:o.mergeCommit})]}):null]}),v.length>0&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4,padding:"14px 16px 0"},children:[(0,r.jsx)("span",{style:{fontSize:11,fontWeight:600,color:"var(--text-muted)",textTransform:"uppercase",letterSpacing:"0.05em"},children:h("tasks.changedFiles")}),(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:2,maxHeight:140,overflowY:"auto"},children:v.map(e=>(0,r.jsxs)("button",{type:"button",onClick:()=>{var t;S(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,r.jsx)(lL.o,{size:13,style:{flexShrink:0,color:"var(--text-muted)"},"aria-hidden":"true"}),(0,r.jsx)("span",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontFamily:"var(--font-mono)",fontSize:11},children:e.file}),(0,r.jsxs)("span",{style:{fontFamily:"var(--font-mono)",fontSize:10,color:"#059669",flexShrink:0},children:["+",e.additions]}),(0,r.jsxs)("span",{style:{fontFamily:"var(--font-mono)",fontSize:10,color:"#dc2626",flexShrink:0},children:["-",e.deletions]})]},e.file))})]}),null!=b&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:6,padding:"12px 16px 0",minHeight:0,flexShrink:0},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[(0,r.jsx)("span",{style:{fontSize:11,fontWeight:600,color:"var(--text-muted)"},children:h("tasks.diff")}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:10,color:"var(--text-muted)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1},children:b}),(0,r.jsx)("button",{type:"button",onClick:()=>S(null),style:{background:"none",border:"none",cursor:"pointer",color:"var(--text-muted)",padding:2,display:"flex"},children:(0,r.jsx)(c.X,{size:12,"aria-hidden":"true"})})]}),R?(0,r.jsx)("div",{style:{fontSize:11,color:"var(--text-muted)",padding:8},children:h("tasks.loading")}):C?(0,r.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,r.jsx)("div",{style:{color:o},children:e||" "},t)})}):(0,r.jsx)("div",{style:{fontSize:11,color:"var(--text-muted)",padding:8},children:h("tasks.noDiff")})]}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4,padding:"14px 16px 0",flex:1,minHeight:0},children:[(0,r.jsx)("span",{style:{fontSize:11,fontWeight:600,color:"var(--text-muted)",textTransform:"uppercase",letterSpacing:"0.05em"},children:h("tasks.timeline")}),(0,r.jsx)("div",{style:{flex:1,minHeight:0,overflowY:"auto",paddingBottom:8},children:0===x.length?(0,r.jsx)("div",{style:{fontSize:11,color:"var(--text-dim)",padding:8},children:h("tasks.noEvents")}):(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:2},children:[...x].reverse().map(e=>{var t;let o,n;return(0,r.jsxs)("div",{style:{display:"flex",gap:8,padding:"4px 6px",borderRadius:6,fontSize:11},children:[(0,r.jsx)("span",{style:{color:"var(--text-dim)",flexShrink:0,fontFamily:"var(--font-mono)",fontSize:10,paddingTop:1},children:new Date(e.createdAt).toLocaleTimeString()}),(0,r.jsx)("span",{style:{color:"var(--text)",flexShrink:0,fontWeight:500},children:(t=e.kind,(n=h(o=`tasks.event_${t}`))===o?t:n)}),e.payload?.feedback?(0,r.jsx)("span",{style:{color:"var(--text-muted)",fontStyle:"italic",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:String(e.payload.feedback)}):null]},e.id)})})})]}),(0,r.jsx)("div",{style:{display:"flex",alignItems:"center",justifyContent:"flex-end",gap:8,padding:"10px 16px",borderTop:"1px solid var(--border)",flexShrink:0},children:F?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("label",{style:{display:"flex",alignItems:"center",gap:6,fontSize:12,cursor:"pointer"},children:[(0,r.jsx)("input",{type:"checkbox",checked:$,onChange:e=>N(e.target.checked),style:{accentColor:"var(--accent)"}}),h("tasks.deleteWorktree")]}),(0,r.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:h("i18n.cancel")}),(0,r.jsx)("button",{type:"button",onClick:()=>void q(),disabled:L,style:{padding:"6px 14px",borderRadius:8,background:"#dc2626",color:"#fff",border:"none",fontSize:12,fontWeight:600,cursor:"pointer"},children:h("tasks.deleteConfirm")})]}):(0,r.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,r.jsx)(j.l,{size:13,"aria-hidden":"true"}),h("tasks.delete")]})})]})})}var lO=o(17757);function lH({open:e,onOpenChange:t,task:o,defaultProject:s,projects:i,prefillTitle:a,prefillPrompt:l,onSubmit:d}){let{t:p}=(0,E.s)(),[u,g]=(0,n.useState)(""),[h,f]=(0,n.useState)(""),[x,m]=(0,n.useState)(""),[k,v]=(0,n.useState)([]),[y,b]=(0,n.useState)(""),[w,S]=(0,n.useState)(!1),C=(0,n.useRef)(!1);if((0,n.useEffect)(()=>{if(!e){C.current=!1;return}C.current||(C.current=!0,g(o?.projectRoot??s??i[0]??""),f(o?.title??a??""),m(o?.config?.prompt??l??""),(0,r2.VB)().then(v).catch(()=>void 0))},[e,o,s,i,a,l]),!e)return null;let T=async()=>{if(u&&h.trim()&&!w){S(!0);try{await d(u,h.trim(),{prompt:x.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{S(!1)}}},R=async()=>{if(y.trim()&&h.trim())try{await (0,r2.nY)({name:y.trim(),title:h.trim(),config:{prompt:x.trim()}}),b(""),(0,r2.VB)().then(v).catch(()=>void 0)}catch(e){console.error("save template failed",e)}},z=async e=>{try{await (0,r2.B_)(e),(0,r2.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,r.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,r.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,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"14px 16px 0"},children:[(0,r.jsx)("h3",{style:{fontSize:15,fontWeight:600,margin:0},children:o?p("tasks.editTitle"):p("tasks.newTitle")}),(0,r.jsx)("button",{type:"button",onClick:()=>t(!1),"aria-label":p("i18n.close"),style:{background:"none",border:"none",cursor:"pointer",color:"var(--text-muted)",padding:4,display:"flex"},children:(0,r.jsx)(c.X,{size:16,"aria-hidden":"true"})})]}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:12,padding:"14px 16px 16px"},children:[k.length>0&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,r.jsx)("span",{style:{fontSize:11,fontWeight:600,color:"var(--text-muted)",textTransform:"uppercase",letterSpacing:"0.05em"},children:p("tasks.templates")}),(0,r.jsx)("div",{style:{display:"flex",flexWrap:"wrap",gap:6},children:k.map(e=>(0,r.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:4,borderRadius:999,background:"var(--bg-hover)",padding:"3px 8px",fontSize:11},children:[(0,r.jsx)("button",{type:"button",onClick:()=>{f(e.title),m(e.config?.prompt??"")},style:{background:"none",border:"none",cursor:"pointer",color:"var(--text)",fontSize:11,padding:0},children:e.name}),(0,r.jsx)("button",{type:"button",onClick:()=>void z(e.id),"aria-label":p("tasks.deleteTemplate"),style:{background:"none",border:"none",cursor:"pointer",color:"var(--text-dim)",padding:0,display:"flex"},children:(0,r.jsx)(j.l,{size:10,"aria-hidden":"true"})})]},e.id))})]}),(0,r.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,r.jsx)("span",{style:{fontSize:12,fontWeight:500,color:"var(--text)"},children:p("tasks.fieldProject")}),(0,r.jsx)("select",{value:u,onChange:e=>g(e.target.value),style:I,children:i.map(e=>(0,r.jsx)("option",{value:e,children:e.split("/").filter(Boolean).pop()??e},e))})]}),(0,r.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,r.jsx)("span",{style:{fontSize:12,fontWeight:500,color:"var(--text)"},children:p("tasks.fieldTitle")}),(0,r.jsx)("input",{value:h,onChange:e=>f(e.target.value),placeholder:p("tasks.fieldTitlePlaceholder"),style:I,autoFocus:!0})]}),(0,r.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,r.jsx)("span",{style:{fontSize:12,fontWeight:500,color:"var(--text)"},children:p("tasks.fieldPrompt")}),(0,r.jsx)("textarea",{value:x,onChange:e=>m(e.target.value),placeholder:p("tasks.fieldPromptPlaceholder"),rows:6,style:{...I,resize:"vertical",fontFamily:"inherit",lineHeight:1.5}})]}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6},children:[(0,r.jsx)("input",{value:y,onChange:e=>b(e.target.value),placeholder:p("tasks.templateNamePlaceholder"),style:{...I,flex:1}}),(0,r.jsxs)("button",{type:"button",onClick:()=>void R(),disabled:!y.trim()||!h.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,r.jsx)(lO.D,{size:13,"aria-hidden":"true"}),p("tasks.saveAsTemplate")]})]}),(0,r.jsxs)("div",{style:{display:"flex",justifyContent:"flex-end",gap:8,marginTop:4},children:[(0,r.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:p("i18n.cancel")}),(0,r.jsx)("button",{type:"button",onClick:()=>void T(),disabled:!u||!h.trim()||w,style:{padding:"8px 16px",borderRadius:8,background:"var(--accent)",color:"#fff",border:"none",fontSize:12,fontWeight:600,cursor:"pointer"},children:p("tasks.save")})]})]})]})})}function lB({open:e,onOpenChange:t,task:o}){let{t:s}=(0,E.s)(),{refetch:i}=lk(),[a,l]=(0,n.useState)(!0),[d,p]=(0,n.useState)(""),[u,g]=(0,n.useState)(!0),[h,f]=(0,n.useState)(!1);if((0,n.useEffect)(()=>{e&&o&&(l(!0),p(o.title),f(!1),(0,r2.CG)(o.projectRoot).then(e=>g(e.deleteWorktreeDefault)).catch(()=>g(!0)))},[e,o]),!e||!o)return null;let x=async()=>{if((a||d.trim())&&!h){f(!0);try{await (0,r2.oB)(o.id,o.projectRoot,a?null:d.trim(),u),t(!1),i()}catch(e){console.error("merge failed",e)}finally{f(!1)}}};return(0,r.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,r.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,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"14px 16px 0"},children:[(0,r.jsx)("h3",{style:{fontSize:15,fontWeight:600,margin:0},children:s("tasks.mergeTitle")}),(0,r.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,r.jsx)(c.X,{size:16,"aria-hidden":"true"})})]}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:12,padding:"14px 16px 16px"},children:[(0,r.jsxs)("label",{style:{display:"flex",alignItems:"center",gap:8,fontSize:13,cursor:"pointer"},children:[(0,r.jsx)("input",{type:"radio",checked:a,onChange:()=>l(!0),style:{accentColor:"var(--accent)"}}),s("tasks.mergeAutoMessage")]}),(0,r.jsxs)("label",{style:{display:"flex",alignItems:"center",gap:8,fontSize:13,cursor:"pointer"},children:[(0,r.jsx)("input",{type:"radio",checked:!a,onChange:()=>l(!1),style:{accentColor:"var(--accent)"}}),s("tasks.mergeManualMessage")]}),!a&&(0,r.jsx)("input",{value:d,onChange:e=>p(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,r.jsxs)("label",{style:{display:"flex",alignItems:"center",gap:8,fontSize:13,cursor:"pointer"},children:[(0,r.jsx)("input",{type:"checkbox",checked:u,onChange:e=>g(e.target.checked),style:{accentColor:"var(--accent)"}}),s("tasks.mergeDeleteWorktree")]}),(0,r.jsxs)("div",{style:{display:"flex",justifyContent:"flex-end",gap:8,marginTop:4},children:[(0,r.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,r.jsx)("button",{type:"button",onClick:()=>void x(),disabled:!a&&!d.trim()||h,style:{padding:"8px 16px",borderRadius:8,background:"var(--accent)",color:"#fff",border:"none",fontSize:12,fontWeight:600,cursor:"pointer"},children:s("tasks.mergeConfirm")})]})]})]})})}function lU({open:e,onOpenChange:t,task:o,kind:s}){let{t:i}=(0,E.s)(),{refetch:a}=lk(),[l,d]=(0,n.useState)(""),[p,u]=(0,n.useState)(!1);if((0,n.useEffect)(()=>{e&&(d(""),u(!1))},[e,o]),!e||!o)return null;let g="retry"===s,h=async()=>{if(!p){u(!0);try{await (0,r2.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,r.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,r.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,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"14px 16px 0"},children:[(0,r.jsx)("h3",{style:{fontSize:15,fontWeight:600,margin:0},children:i(g?"tasks.restartTitleRetry":"tasks.restartTitleRequeue")}),(0,r.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,r.jsx)(c.X,{size:16,"aria-hidden":"true"})})]}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:12,padding:"14px 16px 16px"},children:[(0,r.jsx)("p",{style:{margin:0,fontSize:12,lineHeight:1.5,color:"var(--text-muted)"},children:i("tasks.restartDescription")}),(0,r.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:5},children:[(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)"},children:i("tasks.actionAddNote")}),(0,r.jsx)("textarea",{value:l,onChange:e=>d(e.target.value),placeholder:i(g?"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,r.jsxs)("div",{style:{display:"flex",justifyContent:"flex-end",gap:8,marginTop:4},children:[(0,r.jsx)("button",{type:"button",onClick:()=>t(!1),disabled:p,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,r.jsx)("button",{type:"button",onClick:()=>void h(),disabled:p,style:{padding:"8px 16px",borderRadius:8,background:"var(--accent)",color:"#fff",border:"none",fontSize:12,fontWeight:600,cursor:"pointer"},children:i(g?"tasks.actionRetry":"tasks.actionRequeue")})]})]})]})})}let l_=["work","retry","return","merge"];function lq({open:e,onOpenChange:t,projectRoot:o}){let{t:s}=(0,E.s)(),{projects:i}=lk(),[a,l]=(0,n.useState)(""),[d,p]=(0,n.useState)(()=>lT()),[u,g]=(0,n.useState)(!1),[h,f]=(0,n.useState)(!1);if((0,n.useEffect)(()=>{if(!e)return;let t=o??i[0]??"";l(t),t&&(0,r2.Pf)(t).then(e=>{g(null!=e),p(e??lT())}).catch(()=>{g(!1),p(lT())})},[e,o,i]),!e)return null;let x=(e,t)=>{p(o=>({...o,[e]:t}))},m=async()=>{if(a&&!h){f(!0);try{await (0,r2.eA)(a,d),g(!0),t(!1)}catch(e){console.error("save settings failed",e)}finally{f(!1)}}},k=async()=>{if(a)try{await (0,r2.E)(a),g(!1),p(lT())}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,r.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,r.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,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"14px 16px 0"},children:[(0,r.jsx)("h3",{style:{fontSize:15,fontWeight:600,margin:0},children:s("tasks.settingsTitle")}),(0,r.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,r.jsx)(c.X,{size:16,"aria-hidden":"true"})})]}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:10,padding:"14px 16px 16px"},children:[(0,r.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,r.jsx)("span",{style:{fontSize:12,fontWeight:500},children:s("tasks.settingsProject")}),(0,r.jsx)("select",{value:a,onChange:e=>l(e.target.value),style:v,children:i.map(e=>(0,r.jsx)("option",{value:e,children:e.split("/").filter(Boolean).pop()??e},e))})]}),a?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("div",{style:y,children:[(0,r.jsx)("span",{style:{fontSize:12},children:s("tasks.settingsAutoProcess")}),(0,r.jsx)("input",{type:"checkbox",checked:d.autoProcess,onChange:e=>x("autoProcess",e.target.checked),style:{accentColor:"var(--accent)"}})]}),(0,r.jsxs)("div",{style:y,children:[(0,r.jsx)("span",{style:{fontSize:12},children:s("tasks.settingsMaxConcurrent")}),(0,r.jsx)("input",{type:"number",min:0,value:d.maxConcurrent,onChange:e=>x("maxConcurrent",Math.max(0,Number(e.target.value)||0)),style:{...v,width:90}})]}),(0,r.jsxs)("div",{style:y,children:[(0,r.jsx)("span",{style:{fontSize:12},children:s("tasks.settingsMergeStrategy")}),(0,r.jsxs)("select",{value:d.mergeStrategy,onChange:e=>x("mergeStrategy",e.target.value),style:{...v,width:140},children:[(0,r.jsx)("option",{value:"merge",children:s("tasks.mergeStrategyMerge")}),(0,r.jsx)("option",{value:"squash",children:s("tasks.mergeStrategySquash")})]})]}),(0,r.jsxs)("div",{style:y,children:[(0,r.jsx)("span",{style:{fontSize:12},children:s("tasks.settingsDeleteWorktree")}),(0,r.jsx)("input",{type:"checkbox",checked:d.deleteWorktreeDefault,onChange:e=>x("deleteWorktreeDefault",e.target.checked),style:{accentColor:"var(--accent)"}})]}),(0,r.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,r.jsx)("span",{style:{fontSize:12},children:s("tasks.settingsPreflightCommand")}),(0,r.jsx)("input",{value:d.preflightCommand??"",onChange:e=>x("preflightCommand",e.target.value||null),placeholder:s("tasks.settingsPreflightPlaceholder"),style:{...v,fontFamily:"var(--font-mono)",fontSize:11}})]}),(0,r.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,r.jsx)("span",{style:{fontSize:12},children:s("tasks.settingsInitCommand")}),(0,r.jsx)("input",{value:d.initCommand??"",onChange:e=>x("initCommand",e.target.value||null),placeholder:s("tasks.settingsInitPlaceholder"),style:{...v,fontFamily:"var(--font-mono)",fontSize:11}})]}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:6,paddingTop:4},children:[(0,r.jsx)("span",{style:{fontSize:12,fontWeight:500},children:s("tasks.settingsStagePrompts")}),l_.map(e=>(0,r.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-muted)"},children:s(`tasks.stage.${e}`)}),(0,r.jsx)("input",{value:d.stagePrompts?.[e]??"",onChange:t=>x("stagePrompts",{...d.stagePrompts??{},[e]:t.target.value}),style:{...v,fontSize:11}})]},e))]}),u&&(0,r.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,r.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)",padding:8},children:s("tasks.settingsNoProject")}),(0,r.jsxs)("div",{style:{display:"flex",justifyContent:"flex-end",gap:8,marginTop:4},children:[(0,r.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,r.jsx)("button",{type:"button",onClick:()=>void m(),disabled:!a||h,style:{padding:"8px 16px",borderRadius:8,background:"var(--accent)",color:"#fff",border:"none",fontSize:12,fontWeight:600,cursor:"pointer"},children:s("tasks.save")})]})]})]})})}function lV({open:e,onOpenChange:t,task:o}){let{t:s}=(0,E.s)();return((0,n.useEffect)(()=>{if(!e)return},[e,o]),e&&o)?(0,r.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,r.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,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"14px 16px 0"},children:[(0,r.jsx)("h3",{style:{fontSize:15,fontWeight:600,margin:0},children:s("tasks.sessionTitle")}),(0,r.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,r.jsx)(c.X,{size:16,"aria-hidden":"true"})})]}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:10,padding:"14px 16px 16px",fontSize:12},children:[(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:8,padding:10},children:[(0,r.jsx)("span",{style:{color:"var(--text-muted)"},children:s("tasks.sessionId")}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:11,overflowWrap:"anywhere"},children:o.conversationId??"—"})]}),o.sessionFile?(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:8,padding:10},children:[(0,r.jsx)("span",{style:{color:"var(--text-muted)"},children:s("tasks.sessionFile")}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:11,overflowWrap:"anywhere"},children:o.sessionFile})]}):null,(0,r.jsx)("div",{style:{fontSize:11,color:"var(--text-muted)",lineHeight:1.6},children:s("tasks.sessionHint")}),(0,r.jsx)("div",{style:{display:"flex",justifyContent:"flex-end",marginTop:4},children:(0,r.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 lK="__all__",lJ="pi-tasks-board-filter",lG={showCanceled:!1,showArchived:!1},lY="pi:open-task-settings";function lX(){let{t:e}=(0,E.s)(),{attentionCount:t}=lk();return(0,r.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,r.jsxs)("h1",{style:{margin:0,display:"flex",alignItems:"center",gap:6,fontSize:13,fontWeight:600},children:[(0,r.jsx)(iY.x,{size:15,color:"var(--text-muted)","aria-hidden":"true"}),e("tasks.title"),(0,r.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,r.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,r.jsx)("div",{style:{flex:1}}),(0,r.jsxs)("button",{type:"button",onClick:()=>window.dispatchEvent(new Event(lY)),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,r.jsx)(lb.O,{size:13,"aria-hidden":"true"}),e("tasks.settingsTitle")]})]})}function lZ({activeProject:e}){let{t}=(0,E.s)(),{tasks:s,projects:i,refetch:a}=lk(),[d,c]=(0,n.useState)(null),[p,u]=(0,n.useState)(()=>(function(){try{let e=window.localStorage.getItem(lJ);if(e){let t=JSON.parse(e);return{showCanceled:t.showCanceled??!1,showArchived:t.showArchived??!1}}}catch{}return lG})()),[g,h]=(0,n.useState)(!1);(0,n.useEffect)(()=>{try{window.localStorage.setItem(lJ,JSON.stringify(p))}catch{}},[p]);let[f,m]=(0,n.useState)(null),[k,v]=(0,n.useState)(!1),y=(0,n.useRef)(null),b=(0,n.useRef)({x:0,y:0}),w=(0,n.useRef)(null),j=(0,n.useRef)(null),[S,C]=(0,n.useState)(null),T=(0,n.useRef)(null);T.current=S;let R=(0,n.useRef)(!1),z=(0,n.useRef)(!1),[I,M]=(0,n.useState)(()=>Date.now());(0,n.useEffect)(()=>{let e=window.setInterval(()=>M(Date.now()),6e4);return()=>window.clearInterval(e)},[]);let[P,D]=(0,n.useState)(!1),[F,W]=(0,n.useState)(null),[$,N]=(0,n.useState)(null);(0,n.useEffect)(()=>{let e=()=>{let e,t=(e=re,re=null,e);t&&(W(null),N(t),D(!0))};return e(),window.addEventListener(o9,e),()=>window.removeEventListener(o9,e)},[]);let[L,A]=(0,n.useState)(null),[O,H]=(0,n.useState)(null),[B,U]=(0,n.useState)(!1),[_,q]=(0,n.useState)(null),[V,K]=(0,n.useState)(!1),[J,G]=(0,n.useState)(null),[Y,X]=(0,n.useState)("retry"),[Z,Q]=(0,n.useState)(!1),[ee,et]=(0,n.useState)(null),[eo,er]=(0,n.useState)(!1),[en,es]=(0,n.useState)(!1),[ei,ea]=(0,n.useState)(null),[el,ed]=(0,n.useState)(!1);(0,n.useEffect)(()=>{let e=()=>es(!0);return window.addEventListener(lY,e),()=>window.removeEventListener(lY,e)},[]);let ec=(0,n.useMemo)(()=>null==d?s:s.filter(e=>e.projectRoot===d),[s,d]),ep=(0,n.useMemo)(()=>(function(e,t,o=!1){let r={todo:[],inProgress:[],attention:[],done:[]};for(let n of e)("canceled"!==n.status||t)&&(null==n.archivedAt||o)&&r[function(e){switch(e){case"todo":case"queued":return"todo";case"preparing":case"running":return"inProgress";case"awaiting_input":case"review":case"merging":case"failed":return"attention";case"done":case"canceled":return"done"}}(n.status)].push(n);for(let e of lS)r[e].sort((e,t)=>(t.updatedAt??"").localeCompare(e.updatedAt??""));return r})(ec,p.showCanceled,p.showArchived),[ec,p]),eu=(0,n.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]),eg=(0,n.useMemo)(()=>s.find(e=>e.id===L)??null,[s,L]),eh=(0,n.useMemo)(()=>s.find(e=>e.id===ei)??null,[s,ei]),ef=(0,n.useCallback)(async e=>{try{await e()}catch(e){console.error("task action failed",e)}finally{a()}},[a]),ex=(0,n.useCallback)(e=>{null!=e.conversationId&&(ea(e.id),ed(!0))},[ea,ed]),em=(0,n.useCallback)(e=>{H(e),U(!0)},[H,U]),ek=(0,n.useCallback)(()=>{W(null),D(!0)},[W,D]),ev=(0,n.useCallback)((e,t)=>{let o=w.current,r=y.current;o&&r&&(o.style.transform=`translate3d(${e-r.dx}px, ${t-r.dy}px, 0)`)},[]),ey=e=>{let t=e.currentTarget.getBoundingClientRect();y.current={dx:e.clientX-t.left,dy:e.clientY-t.top,width:t.width}},eb=(0,n.useCallback)(e=>{if(m(null),v(!1),e){R.current=!1;return}requestAnimationFrame(()=>{R.current=!1})},[m,v]),ew=(0,n.useCallback)(()=>{z.current=!0,C(null),eb(!0)},[eb,C]);(0,n.useEffect)(()=>{if(!f)return;let e=()=>{document.hidden&&ew()};return window.addEventListener("blur",ew),document.addEventListener("visibilitychange",e),()=>{window.removeEventListener("blur",ew),document.removeEventListener("visibilitychange",e)}},[f,ew]),(0,n.useEffect)(()=>{f&&!eu.some(e=>e.id===f.task.id)&&ew()},[f,eu,ew]);let ej=(0,n.useCallback)((e,t,o)=>{if(z.current){eb(!0),C(null);return}let r=j.current?.getBoundingClientRect(),n=null!=r&&t>=r.left&&t<=r.right&&o>=r.top&&o<=r.bottom;if(eb(!1),n){C(null);let t=s.find(t=>t.id===e.id);t?.status==="todo"&&null!=d&&ef(()=>(0,r2.oQ)(e.id,e.projectRoot,"start"));return}let i=T.current;null!=d&&null!=i&&(async()=>{try{await (0,r2.Lu)(d,i)}catch(e){console.error("reorder failed",e)}await a(),C(null)})()},[ef,eb,d,a,s]),eS=(0,n.useCallback)(()=>{ef(async()=>{let e=await (0,r2.a5)(d);e>0&&console.log(`started ${e} tasks`)})},[ef,d]),eC=(0,n.useCallback)(()=>{let e=ep.done.filter(e=>null==e.archivedAt);0!==e.length&&ef(()=>Promise.all(e.map(e=>(0,r2.et)(e.id,e.projectRoot,!0))))},[ef,ep.done]),eT=+(p.showCanceled!==lG.showCanceled)+ +(p.showArchived!==lG.showArchived),eR=s.length>0,ez=(0,n.useMemo)(()=>{let t=new Set(i);return e&&t.add(e),[...t].sort()},[i,e]),eI=(0,n.useMemo)(()=>{let e=new Map;for(let t of ez)e.set(t,t.split("/").filter(Boolean).pop()??t);return e},[ez]);return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",minHeight:0},children:[eR&&(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:8,padding:"14px 16px 8px"},children:[(0,r.jsxs)("select",{value:d??lK,onChange:e=>c(e.target.value===lK?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,r.jsx)("option",{value:lK,children:t("tasks.allFolders")}),ez.map(e=>(0,r.jsx)("option",{value:e,children:eI.get(e)??e},e))]}),(0,r.jsxs)("div",{style:{position:"relative"},children:[(0,r.jsxs)("button",{type:"button",onClick:()=>h(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,r.jsx)(lw.n,{size:13,"aria-hidden":"true"}),t("tasks.filter"),eT>0?(0,r.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]}),g&&(0,r.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,r.jsxs)("label",{style:{display:"flex",alignItems:"center",gap:8,padding:"6px 8px",borderRadius:8,cursor:"pointer",fontSize:12},children:[(0,r.jsx)("input",{type:"checkbox",checked:p[e],onChange:t=>u(o=>({...o,[e]:t.target.checked})),style:{accentColor:"var(--accent)"}}),t]},e))})]}),(0,r.jsx)("div",{style:{flex:1}}),(0,r.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,r.jsx)(lj.j,{size:13,"aria-hidden":"true"}),t("tasks.startAll")]}),(0,r.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,r.jsx)(x.F,{size:13,weight:"bold","aria-hidden":"true"}),t("tasks.new")]})]}),eR?(0,r.jsx)("div",{style:{flex:1,minHeight:0,overflowX:"auto"},children:(0,r.jsx)("div",{style:{display:"grid",gridTemplateColumns:"repeat(4, minmax(0, 1fr))",gap:16,minWidth:"56rem",height:"100%",padding:"4px 16px 16px"},children:lR.map(e=>{let o="todo"===e?eu:ep[e],n=lz[e],s=e=>(0,r.jsx)(lF,{task:e,folderName:e.projectRoot?eI.get(e.projectRoot)??null:null,now:I,onOpen:()=>{R.current||A(e.id)},onStart:()=>void ef(()=>(0,r2.oQ)(e.id,e.projectRoot,"start")),onCancel:()=>{q(e),K(!0)},onRetry:()=>{G(e),X("retry"),Q(!0)},onRequeue:()=>{G(e),X("requeue"),Q(!0)},onViewSession:()=>ex(e),onMerge:()=>{lC(e)?(et(e),er(!0)):em(e)},onArchive:()=>void ef(()=>(0,r2.et)(e.id,e.projectRoot,null==e.archivedAt)),onEdit:()=>{W(e),D(!0)}},e.id);return(0,r.jsxs)("div",{ref:"inProgress"===e?j:void 0,style:{display:"flex",flexDirection:"column",minHeight:0,gap:8},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,height:24,flexShrink:0,padding:"0 2px"},children:[(0,r.jsx)("span",{style:{width:3,height:14,borderRadius:999,background:n.marker,flexShrink:0},"aria-hidden":"true"}),(0,r.jsx)("h2",{style:{fontSize:12,fontWeight:600,color:"var(--text)"},children:t(`tasks.col${e[0].toUpperCase()}${e.slice(1)}`)}),(0,r.jsx)("span",{style:{borderRadius:999,background:"var(--bg-hover)",padding:"1px 8px",fontSize:10,fontWeight:600,color:"var(--text-muted)"},children:o.length}),(0,r.jsx)("div",{style:{flex:1}}),"done"===e&&ep.done.some(e=>null==e.archivedAt)?(0,r.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,r.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&&f?k?{borderColor:"var(--accent)",background:"rgba(37,99,235,0.08)"}:{borderColor:"var(--accent)"}:{}},children:(0,r.jsx)("p",{style:{fontSize:12,color:"var(--text-muted)"},children:t(`tasks.emptyCol${e[0].toUpperCase()}${e.slice(1)}`)})}):(0,r.jsx)("div",{style:{flex:1,minHeight:0,overflowY:"auto",borderRadius:12,transition:"background 0.15s, box-shadow 0.15s",..."inProgress"===e&&f?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,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:16,paddingBottom:4},children:o.map(t=>"todo"===e?(0,r.jsx)("div",{draggable:!0,onDragStart:e=>{var o,r;e.dataTransfer.effectAllowed="move",o=e.clientX,r=e.clientY,R.current=!0,z.current=!1,b.current={x:o,y:r},m({task:t,width:y.current?.width??280})},onDrag:e=>{var t,o;let r,n;return b.current={x:t=e.clientX,y:o=e.clientY},ev(t,o),void((n=null!=(r=j.current?.getBoundingClientRect())&&t>=r.left&&t<=r.right&&o>=r.top&&o<=r.bottom)!==k&&v(n))},onDragEnd:e=>ej(t,e.clientX,e.clientY),onPointerDown:ey,style:{cursor:"grab",opacity:f?.task.id===t.id?.4:1},children:s(t)},t.id):(0,r.jsx)("div",{children:s(t)},t.id))})})]},e)})})}):(0,r.jsxs)("div",{style:{flex:1,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:12,padding:32,textAlign:"center"},children:[(0,r.jsx)(iY.x,{size:40,color:"var(--text-dim)",opacity:.4,"aria-hidden":"true"}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,r.jsx)("p",{style:{fontSize:14,fontWeight:500,color:"var(--text)"},children:t("tasks.empty")}),(0,r.jsx)("p",{style:{maxWidth:320,fontSize:12,color:"var(--text-muted)",lineHeight:1.6},children:t("tasks.emptyHint")})]}),(0,r.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,r.jsx)(x.F,{size:13,weight:"bold","aria-hidden":"true"}),t("tasks.new")]})]}),(0,r.jsx)(lH,{open:P,onOpenChange:D,task:F,defaultProject:$?.projectRoot??d??e??null,projects:ez,prefillTitle:$?$.text.slice(0,80):void 0,prefillPrompt:$?$.text:void 0,onSubmit:async(e,t,r)=>{await ef(async()=>{let{createTaskApi:n}=await Promise.resolve().then(o.bind(o,23084)),{updateTaskApi:s}=await Promise.resolve().then(o.bind(o,23084));F?await s(F.id,e,{title:t,config:r}):await n({projectRoot:e,title:t,config:r})}),D(!1),N(null)}}),(0,r.jsx)(lA,{open:null!=L,onOpenChange:e=>{e||A(null)},task:eg,onViewSession:ex,onMerge:em,onEdit:e=>{W(e),D(!0)},onCancel:e=>{q(e),K(!0)},onRetry:e=>{G(e),X("retry"),Q(!0)},onRequeue:e=>{G(e),X("requeue"),Q(!0)},onComplete:e=>{et(e),er(!0)}}),(0,r.jsx)(lB,{open:B,onOpenChange:U,task:O}),(0,r.jsx)(lW,{open:V,onOpenChange:K,task:_}),(0,r.jsx)(lU,{open:Z,onOpenChange:Q,task:J,kind:Y}),(0,r.jsx)(l$,{open:eo,onOpenChange:er,task:ee}),(0,r.jsx)(lV,{open:el&&null!=eh,onOpenChange:ed,task:eh}),(0,r.jsx)(lq,{open:en,onOpenChange:es,projectRoot:d}),f?(0,l.createPortal)((0,r.jsx)("div",{ref:w,style:{position:"fixed",left:0,top:0,zIndex:999,pointerEvents:"none",width:f.width,willChange:"transform"},"aria-hidden":"true",children:(0,r.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,r.jsxs)("div",{style:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:8},children:[(0,r.jsx)("span",{style:{minWidth:0,overflowWrap:"break-word",fontSize:13,fontWeight:500},children:f.task.title}),(0,r.jsx)(lP,{task:f.task})]}),k?(0,r.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:4,fontSize:11,fontWeight:600,color:"var(--accent)"},children:[(0,r.jsx)(lj.j,{size:11,weight:"bold","aria-hidden":"true"}),t("tasks.dropToStart")]}):null]})}),document.body):null]})}var lQ=o(62235);function l0({isDark:e,toggleTheme:t,translate:o}){let[s,i]=(0,n.useState)(!1);(0,n.useEffect)(()=>{i(!0)},[]);let a=o(s?e?"desktop.switchToLight":"desktop.switchToDark":"desktop.switchToLight");return(0,r.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,r.jsx)(iO.b,{size:16,"aria-hidden":"true"}):(0,r.jsx)(iA.A,{size:16,"aria-hidden":"true"}):(0,r.jsx)(iO.b,{size:16,"aria-hidden":"true"})})}function l1({topBarRef:e,sidebarOpen:t,onSidebarToggle:o,isDark:s,toggleTheme:i,isMobile:a,showTasks:l,tasksBoardEnabled:d,onToggleTasks:c,systemPrompt:p,activeTopPanel:g,topPanelPos:h,sessionStats:f,contextUsage:x,copiedSessionField:m,onCopySessionField:k,rightPanelOpen:y,onToggleFilePanel:b,onOpenSettings:w,sessionTitle:j,onWorkspaceControlsHostChange:S,onTitleRightHostChange:C}){let T,R,z,I,M,P,D,F,{t:W}=(0,E.s)(),[$,N]=(0,n.useState)(!1),[L,A]=(0,n.useState)(!1);return(0,n.useEffect)(()=>{try{A(new URLSearchParams(window.location.search).has("piweb_connected"))}catch{A(!1)}},[]),(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("div",{ref:e,className:"app-title-bar",style:{display:"flex",alignItems:"center",flexShrink:0,borderBottom:"1px solid var(--border)",height:36,background:"var(--bg-panel)",position:"relative",zIndex:600},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",minWidth:0,height:"100%",flex:"0 1 auto"},children:[(0,r.jsx)("button",{className:"app-no-drag",onClick:o,title:t?W("desktop.hideSidebar"):W("desktop.showSidebar"),"aria-label":t?W("desktop.hideSidebar"):W("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,r.jsx)(lQ.V,{size:16,"aria-hidden":"true"}):(0,r.jsx)(v.B,{size:16,"aria-hidden":"true"})}),(0,r.jsx)("div",{className:"app-no-drag",ref:S,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,r.jsxs)("div",{className:"app-title-drag",style:{flex:1,minWidth:0,display:"flex",alignItems:"center",justifyContent:"center",height:"100%",padding:"0 12px",userSelect:"none"},children:[j&&(0,r.jsx)("button",{type:"button",onClick:()=>{a&&N(!0)},title:a?j:void 0,style:{display:"block",maxWidth:"100%",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:j}),(0,r.jsx)("div",{className:"app-no-drag",ref:C,style:{flexShrink:0,display:"flex",alignItems:"center",marginLeft:4}})]}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"flex-end",minWidth:0,height:"100%",flexShrink:0},children:[!a&&d&&(0,r.jsx)("button",{className:"app-no-drag",onClick:c,title:l?W("desktop.hideTaskBoard"):W("desktop.showTaskBoard"),"aria-label":l?W("desktop.hideTaskBoard"):W("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,r.jsx)(iY.x,{size:16,"aria-hidden":"true"})}),(0,r.jsx)("button",{className:"app-no-drag",onClick:b,title:y?W("desktop.hideFilePanel"):W("desktop.showFilePanel"),"aria-label":y?W("desktop.hideFilePanel"):W("desktop.showFilePanel"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:36,height:36,padding:0,background:y?"var(--bg-selected)":"none",border:"none",color:y?"var(--text)":"var(--text-muted)",cursor:"pointer",flexShrink:0,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background=y?"var(--bg-selected)":"none",e.currentTarget.style.color=y?"var(--text)":"var(--text-muted)"},children:(0,r.jsx)(lQ.V,{size:16,"aria-hidden":"true",style:{transform:"scaleX(-1)"}})}),(0,r.jsx)(l0,{isDark:s,toggleTheme:i,translate:W}),L&&(0,r.jsx)("button",{className:"app-no-drag",type:"button",onClick:()=>{window.location.href="piweb-switch://manage"},title:W("desktop.serverSwitch"),"aria-label":W("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,r.jsx)(ik.X,{size:16,"aria-hidden":"true"})}),(0,r.jsx)("button",{className:"app-no-drag",type:"button",onClick:w,title:W("desktop.settings"),"aria-label":W("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,r.jsx)(lb.O,{size:16,"aria-hidden":"true"})})]})]}),g&&h&&(0,r.jsxs)("div",{style:{position:"fixed",top:h.top,left:h.left,width:h.width,maxHeight:`calc(100dvh - ${h.top}px)`,overflowY:"auto",zIndex:500},children:["system"===g&&(0,r.jsx)("div",{style:{background:"var(--bg-panel)",borderBottom:"1px solid var(--border)"},children:p?(0,r.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,r.jsx)("div",{style:{padding:"10px 16px",fontSize:12,color:"var(--text-muted)",fontStyle:"italic"},children:"System prompt is empty (tools are disabled)"}):(0,r.jsx)("div",{style:{padding:"10px 16px",fontSize:12,color:"var(--text-muted)",fontStyle:"italic"},children:"Send a message to load the system prompt"})}),"session"===g&&(0,r.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:f?(T=[...f.sessionName?[{label:W("desktop.name"),value:f.sessionName,copyField:null}]:[],{label:W("desktop.sessionInfoFile"),value:f.sessionFile??W("desktop.sessionInfoInMemory"),copyField:"file"},{label:W("desktop.sessionInfoId"),value:f.sessionId,copyField:"id"}],R=[[W("desktop.sessionInfoUser"),f.userMessages.toLocaleString()],[W("desktop.sessionInfoAssistant"),f.assistantMessages.toLocaleString()],[W("desktop.sessionInfoToolCalls"),f.toolCalls.toLocaleString()],[W("desktop.sessionInfoToolResults"),f.toolResults.toLocaleString()],[W("desktop.sessionInfoTotal"),f.totalMessages.toLocaleString()]],z=[[W("desktop.sessionInfoInput"),f.tokens.input.toLocaleString()],[W("desktop.sessionInfoOutput"),f.tokens.output.toLocaleString()],...f.tokens.cacheRead>0?[[W("desktop.sessionInfoCacheRead"),f.tokens.cacheRead.toLocaleString()]]:[],...f.tokens.cacheWrite>0?[[W("desktop.sessionInfoCacheWrite"),f.tokens.cacheWrite.toLocaleString()]]:[],[W("desktop.sessionInfoTotal"),f.tokens.total.toLocaleString()]],I=x??f.contextUsage,P=[...f.cost>0?[[W("desktop.sessionInfoCost"),`$${f.cost.toFixed(4)}`]]:[],...I?.contextWindow?[[W("desktop.sessionInfoContext"),`${null!==I.percent?`${I.percent.toFixed(1)}%`:"?"} / ${(M=I.contextWindow)>=1e6?`${(M/1e6).toFixed(1)}M`:M>=1e3?`${(M/1e3).toFixed(0)}k`:String(M)}`]]:[]],D=(e,t,o="left",n=!1)=>(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:11,fontWeight:700,color:"var(--text)",marginBottom:6},children:e}),(0,r.jsx)("div",{style:{display:"grid",gridTemplateColumns:n?"max-content max-content":"auto minmax(0, 1fr)",columnGap:n?14:12,rowGap:4,justifyContent:n?"start":void 0},children:t.map(([t,s])=>(0,r.jsxs)("div",{style:{display:"contents"},children:[(0,r.jsx)("div",{style:{color:"var(--text-dim)",whiteSpace:"nowrap"},children:t}),(0,r.jsx)("div",{style:{color:"var(--text-muted)",minWidth:0,overflowWrap:n?"normal":"anywhere",textAlign:o,whiteSpace:"right"===o?"nowrap":"normal"},children:s})]},`${e}:${t}`))})]}),F=(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:11,fontWeight:700,color:"var(--text)",marginBottom:6},children:W("desktop.sessionInfoTitle")}),(0,r.jsx)("div",{style:{display:"grid",gridTemplateColumns:"auto minmax(0, 1fr) auto",columnGap:12,rowGap:8,alignItems:"start"},children:T.map(e=>{var t,o;let n;return(0,r.jsxs)("div",{style:{display:"contents"},children:[(0,r.jsx)("div",{style:{color:"var(--text-dim)",whiteSpace:"nowrap"},children:e.label}),(0,r.jsx)("div",{style:{color:"var(--text-muted)",minWidth:0,overflowWrap:"anywhere",wordBreak:"break-word",whiteSpace:"normal"},children:e.value}),(0,r.jsx)("div",{children:e.copyField?(t=e.copyField,o=e.value,n=m===t,(0,r.jsx)("button",{type:"button",title:n?W("desktop.copied"):"file"===t?W("desktop.copyFilePath"):W("desktop.copySessionId"),onClick:()=>k(t,o),style:{alignSelf:"start",display:"inline-flex",alignItems:"center",justifyContent:"center",width:22,height:22,marginTop:-2,color:n?"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=n?"var(--accent)":"var(--text-dim)",e.currentTarget.style.borderColor="var(--border)",e.currentTarget.style.background="transparent"},children:n?(0,r.jsx)(u.J,{size:12,"aria-hidden":"true"}):(0,r.jsx)(tp.Q,{size:12,"aria-hidden":"true"})})):null})]},`session-info:${e.label}`)})})]}),(0,r.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:[F,D(W("desktop.sessionInfoMessages"),R),D(W("desktop.sessionInfoTokens"),[...z,...P],"right",!0)]})):(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)",fontStyle:"italic"},children:W("desktop.sendMessageForSessionInfo")})})]}),$&&j&&(0,r.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&&N(!1)},children:(0,r.jsx)("div",{role:"dialog","aria-label":j,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:j})})]})}function l2({cwd:e,busy:t,error:o,onCancelAction:n,onConfirmAction:s}){let{t:i}=(0,E.s)();return(0,r.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||n()},children:(0,r.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,r.jsxs)("div",{style:{display:"flex",gap:12,padding:"18px 18px 14px"},children:[(0,r.jsx)(o8.o,{size:21,weight:"duotone",color:"var(--accent-orange)",style:{flexShrink:0,marginTop:1},"aria-hidden":"true"}),(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("h2",{id:"project-trust-title",style:{margin:0,fontSize:15,fontWeight:700,color:"var(--text)"},children:i("desktop.trustProjectTitle")}),(0,r.jsx)("p",{style:{margin:"7px 0 0",fontSize:12,lineHeight:1.6,color:"var(--text-muted)"},children:i("desktop.trustProjectBody")}),(0,r.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,r.jsx)("div",{role:"alert",style:{marginTop:10,color:"var(--accent-red)",fontSize:12,lineHeight:1.5},children:o})]})]}),(0,r.jsxs)("footer",{style:{display:"flex",justifyContent:"flex-end",gap:8,padding:"10px 18px",borderTop:"1px solid var(--border)"},children:[(0,r.jsx)("button",{type:"button",onClick:n,disabled:t,style:{height:32,padding:"0 12px",border:"1px solid var(--border)",borderRadius:5,background:"transparent",color:"var(--text-muted)",cursor:t?"not-allowed":"pointer",fontSize:12},children:i("desktop.cancel")}),(0,r.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 l4(e,t,o){let r=Number.isFinite(e)?e:t,n=Math.max(t,o);return Math.round(Math.max(t,Math.min(n,r)))}function l6(e){return l4(.42*e,360,640)}function l5(e,t){try{window.localStorage.setItem(e,String(t))}catch{}}function l3(e){let{ariaLabel:t,cssVariable:o,defaultWidth:r,getDefaultWidth:s,getMaxWidth:i,growthDirection:a,maxWidth:l,minWidth:d,storageKey:c,widthRef:p}=e,u=(0,n.useRef)(null),g=(0,n.useRef)(null),h=(0,n.useRef)(!1),[f,x]=(0,n.useState)(r),[m,k]=(0,n.useState)(!1),v=(0,n.useCallback)(()=>Math.min(l,Math.max(d,i())),[i,l,d]),y=(0,n.useCallback)(e=>l4(e,d,v()),[v,d]),b=(0,n.useCallback)(e=>{p.current=e;let t=`${e}px`;u.current?.style.setProperty(o,t),u.current?.parentElement?.style.setProperty(o,t)},[o,p]),w=(0,n.useCallback)((e,t={})=>{let{forcePersist:o=!1,persist:r=!0}=t,n=y(e),s=n!==p.current;return b(n),x(n),r&&(s||o)&&l5(c,n),n},[b,y,c,p]),j=(0,n.useCallback)(e=>{document.body.style.cursor=e.previousCursor,document.body.style.userSelect=e.previousUserSelect},[]),S=(0,n.useCallback)(e=>{let t=g.current;if(t&&t.pointerId===e){g.current=null,j(t),k(!1),w(p.current,{forcePersist:!0});try{t.target.hasPointerCapture(e)&&t.target.releasePointerCapture(e)}catch{}}},[w,j,p]),C=(0,n.useCallback)(e=>{if("mouse"===e.pointerType&&0!==e.button)return;e.preventDefault(),e.stopPropagation();let t=g.current;t&&S(t.pointerId);let o=e.currentTarget;o.focus({preventScroll:!0}),o.setPointerCapture(e.pointerId),g.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)},[S,p]),T=(0,n.useCallback)(e=>{let t=g.current;if(!t||t.pointerId!==e.pointerId)return;if("mouse"===e.pointerType&&0===e.buttons)return void S(e.pointerId);e.preventDefault();let o="right"===a?1:-1,r=y(t.startWidth+(e.clientX-t.startX)*o);b(r),e.currentTarget.setAttribute("aria-valuenow",String(r)),e.currentTarget.setAttribute("aria-valuetext",`${r} px`)},[b,y,S,a]),R=(0,n.useCallback)(e=>{S(e.pointerId)},[S]),z=(0,n.useCallback)(e=>{S(e.pointerId)},[S]),I=(0,n.useCallback)(e=>{S(e.pointerId)},[S]),M=(0,n.useCallback)(()=>{w(s?.()??r,{forcePersist:!0})},[w,r,s]),E=(0,n.useCallback)(()=>{w(p.current)},[w,p]),P=(0,n.useCallback)(e=>{let t=e.shiftKey?32:12,o="right"===a?"ArrowRight":"ArrowLeft",r="right"===a?"ArrowLeft":"ArrowRight";e.key===o?(e.preventDefault(),w(p.current+t,{forcePersist:!0})):e.key===r?(e.preventDefault(),w(p.current-t,{forcePersist:!0})):"Home"===e.key?(e.preventDefault(),w(d,{forcePersist:!0})):"End"===e.key?(e.preventDefault(),w(v(),{forcePersist:!0})):"Enter"===e.key&&(e.preventDefault(),M())},[w,v,a,d,M,p]);return(0,n.useEffect)(()=>{if(h.current)return;h.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=w(e??s?.()??r,{persist:!1});null!==e&&e!==t&&l5(c,t)},[w,r,s,c]),(0,n.useEffect)(()=>{if(!h.current)return;w(p.current);let e=()=>{w(p.current)};return window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[w,p]),(0,n.useEffect)(()=>{if(!m)return;let e=()=>{let e=g.current;e&&S(e.pointerId)},t=()=>{"visible"!==document.visibilityState&&e()};return window.addEventListener("blur",e),document.addEventListener("visibilitychange",t),()=>{window.removeEventListener("blur",e),document.removeEventListener("visibilitychange",t)}},[S,m]),(0,n.useEffect)(()=>()=>{let e=g.current;e&&(g.current=null,j(e))},[j]),{isResizing:m,panelRef:u,reclampWidth:E,separatorProps:{"aria-label":t,"aria-orientation":"vertical","aria-valuemax":v(),"aria-valuemin":d,"aria-valuenow":f,"aria-valuetext":`${f} px`,onDoubleClick:M,onKeyDown:P,onLostPointerCapture:I,onPointerCancel:z,onPointerDown:C,onPointerMove:T,onPointerUp:R,role:"separator",tabIndex:0},width:f}}function l8(){let e,t,o=(0,i.useRouter)(),l=(0,i.useSearchParams)(),d=(0,n.useMemo)(()=>{let e;return{requestedCwd:e=l.get("cwd")?.trim()||null,sessionId:e?null:l.get("session")}},[l]),{isDark:c,toggleTheme:p}=tL(),{t:u}=(0,E.s)(),g=$(),[h,f]=(0,n.useState)(null),[x,m]=(0,n.useState)(null),[k,v]=(0,n.useState)(0),[y,b]=(0,n.useState)(0),[w,j]=(0,n.useState)(0),[S,C]=(0,n.useState)(!1),[T,R]=(0,n.useState)("models"),[z,I]=(0,n.useState)(0),[M,P]=(0,n.useState)(null),[D,F]=(0,n.useState)(!1),[W,N]=(0,n.useState)(!1),[L,A]=(0,n.useState)(null),[O,H]=(0,n.useState)(!0),[B,U]=(0,n.useState)(!1);(0,n.useEffect)(()=>{g&&H(!1)},[g]),(0,n.useEffect)(()=>{U(!0)},[]);let _=(0,n.useRef)(null),q=(0,n.useRef)(null),[V,K]=(0,n.useState)(null),[J,G]=(0,n.useState)(null),[Y,X]=(0,n.useState)(null),[Z,Q]=(0,n.useState)(null),ee=(0,n.useCallback)(e=>{Q(e)},[]),[et,eo]=(0,n.useState)(null),en=(0,n.useCallback)(e=>{eo(e)},[]),[es,ei]=(0,n.useState)([]),ea=(0,n.useCallback)(e=>{ei(e)},[]),el=es.filter(e=>"running"===e.status).length,[ed,ec]=(0,n.useState)(null),ep=(0,n.useRef)(null),eu=(0,n.useCallback)((e,t)=>{tA(t).then(()=>{ep.current&&clearTimeout(ep.current),ec(e),ep.current=setTimeout(()=>ec(null),1400)})},[]);(0,n.useEffect)(()=>()=>{ep.current&&clearTimeout(ep.current)},[]);let[eg,eh]=(0,n.useState)(null),ef=(0,n.useCallback)(e=>{eh(e)},[]),[ex,em]=(0,n.useState)(null),[ek,ev]=(0,n.useState)(null),ey=(0,n.useCallback)(()=>{g&&H(!1),em("session")},[g]),eb=(0,n.useCallback)(()=>{g&&em(null),H(e=>!e)},[g]);(0,n.useEffect)(()=>{if(!ex||!q.current)return;let e=()=>{let e=q.current.getBoundingClientRect();ev({top:e.bottom,left:e.left,width:e.width})};e();let t=new ResizeObserver(e);return t.observe(q.current),()=>t.disconnect()},[ex]);let[ew,ej]=(0,n.useState)([]),[eC,eT]=(0,n.useState)(null),[eR,ez]=(0,n.useState)(!1),[eI,eM]=(0,n.useState)(!1),[eE,eP]=(0,n.useState)(null),eD=(0,n.useCallback)(e=>{eP(e??null),eM(!0),ez(!0),g&&H(!1)},[g]),eF=(0,n.useCallback)(()=>{eM(!1),eP(null)},[]),eW=(0,n.useRef)(260),eN=(0,n.useRef)(l6(1366)),eL=(0,n.useCallback)(()=>l6(window.innerWidth),[]),eA=(0,n.useCallback)(()=>(function(e){let{viewportWidth:t,rightPanelOpen:o,rightPanelWidth:r}=e;if(t<=640)return 480;let n=t<960;return Math.min(480,t-(n?320:420)-(!n&&o?r:0))})({viewportWidth:window.innerWidth,rightPanelOpen:eR,rightPanelWidth:eN.current}),[eR]),eO=(0,n.useCallback)(()=>(function(e){let{viewportWidth:t,sidebarOpen:o,sidebarWidth:r}=e;return t<960?1200:Math.min(1200,t-420-(o?r:0))})({viewportWidth:window.innerWidth,sidebarOpen:O,sidebarWidth:eW.current}),[O]),eH=l3({ariaLabel:u("desktop.resizeSidebar"),cssVariable:"--sidebar-width",defaultWidth:260,getMaxWidth:eA,growthDirection:"right",maxWidth:480,minWidth:180,storageKey:"pi-sidebar-width",widthRef:eW}),eB=l3({ariaLabel:u("desktop.resizeFilePanel"),cssVariable:"--right-panel-width",defaultWidth:l6(1366),getDefaultWidth:eL,getMaxWidth:eO,growthDirection:"left",maxWidth:1200,minWidth:300,storageKey:"pi-right-panel-width",widthRef:eN}),eU=eH.reclampWidth,e_=eB.reclampWidth;(0,n.useEffect)(()=>{eR&&(eU(),e_())},[e_,eU,eR]);let eq=(0,n.useCallback)((e,t)=>{_.current?.insertText(r1(e,t))},[]),eV=(0,n.useCallback)(e=>{let t=e.map(e=>r1(e,!1)).join("");t&&_.current?.insertText(t)},[]),eJ=(0,n.useCallback)((e,t,o)=>{let r,n,s,i;_.current?.insertText((r=Math.max(1,Math.min(t,o)),n=Math.max(1,Math.max(t,o)),s=e.includes(" ")?`@"${e}"`:`@${e}`,i=r===n?`:${r}`:`:${r}-${n}`,`${s}${i} `))},[]),[eG,eY]=(0,n.useState)(()=>d.sessionId),[eX,eZ]=(0,n.useState)(null),[eQ,e0]=(0,n.useState)(()=>d.requestedCwd?"validating":"idle"),[e1,e2]=(0,n.useState)(null),[e4,e6]=(0,n.useState)(()=>!eG),e5=(0,n.useRef)(!1),e3=(0,n.useRef)(new Map),[e8,e7]=(0,n.useState)(null),e9=(0,n.useRef)("");(0,n.useEffect)(()=>{let e=`${d.requestedCwd??""}|${d.sessionId??""}`;e9.current!==e&&(e9.current=e,eY(d.sessionId),e6(!d.sessionId),d.requestedCwd||e0("idle"),e2(null))},[d]),(0,n.useEffect)(()=>{let e=d.requestedCwd;if(!e)return;let t=new AbortController;return e0("validating"),e2(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}`);e5.current=!0,m(t.cwd),e0("ready")}).catch(e=>{t.signal.aborted||(e2(e instanceof Error?e.message:String(e)),e0("error"))}),()=>t.abort()},[d]);let te=(0,n.useCallback)((e,t)=>{if(!e)return;if(eZ(e),e5.current&&h&&eS(h.projectRoot??h.cwd,t??e)){if(e5.current=!1,h){let e=h.projectRoot??h.cwd;e&&e3.current.set(e,h.id)}return}e5.current=!1;let o=t??e;if(h&&eS(h.projectRoot??h.cwd,o)){(h.projectRoot??h.cwd)&&e3.current.set(o,h.id);return}if(h){let e=h.projectRoot??h.cwd;e&&e3.current.set(e,h.id)}f(null),m(t=>t&&t!==e?null:t),b(e=>e+1),Q(null),em(null),window.history.replaceState(null,"","/");let r=e3.current.get(o);e7(r?{projectRoot:o,sessionId:r}:null)},[h]);(0,n.useEffect)(()=>{let e=eX?er(eX)||eX:null;document.title=e?`${e} — Pi Agent Web`:"Pi Agent Web"},[eX]);let tt=(0,n.useCallback)((e,t=!1)=>{if(t||e7(null),!t&&h){let t=eS(h.projectRoot??h.cwd,e.projectRoot??e.cwd);if(h.id===e.id&&t){g&&H(!1);return}}let o=e.projectRoot??e.cwd;o&&e3.current.set(o,e.id),m(null),f(e),b(e=>e+1),Q(null),e6(!0),g&&!t&&H(!1),t&&(e5.current=!0),t||window.history.replaceState(null,"",`?session=${encodeURIComponent(e.id)}`)},[g,h]),to=(0,n.useRef)(()=>{});(0,n.useEffect)(()=>{to.current=tt},[tt]);let tr=(0,n.useCallback)(e=>{fetch("/api/sessions").then(e=>e.ok?e.json():null).then(t=>{let o=t?.sessions.find(t=>t.id===e);o&&f(t=>!t||t.id!==e||t.projectRoot&&t.name?t:o)}).catch(()=>{})},[]);(0,n.useEffect)(()=>{if(!e8)return;let{projectRoot:e,sessionId:t}=e8;to.current({path:"",id:t,cwd:e,created:"",modified:"",messageCount:0,firstMessage:"",projectRoot:e},!0),tr(t),window.history.replaceState(null,"",`?session=${encodeURIComponent(t)}`),e7(null)},[e8,tr]);let tn=(0,n.useCallback)((e,t)=>{e7(null),f(null),m(t),b(e=>e+1),Q(null),em(null),g&&H(!1),window.history.replaceState(null,"","/")},[o,g]);!function(e){let{onNewSession:t,activeCwd:o}=e;(0,n.useEffect)(()=>{let e=e=>{if("Escape"===e.key){if(!a)return;let t=e.target?.tagName;if("TEXTAREA"===t||"INPUT"===t)return;e.preventDefault(),a();return}if("n"===e.key&&e.ctrlKey&&e.altKey){if(!o||!t)return;e.preventDefault(),t(o)}};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[o,t])}({onNewSession:e=>tn(`kb-${Date.now()}`,e),activeCwd:eX});let ts=(0,n.useCallback)(e=>{m(null),e7(null);let t=e.projectRoot??e.cwd;t&&e3.current.set(t,e.id),f(e),e.cwd&&eZ(e.cwd),v(e=>e+1),tr(e.id),window.history.replaceState(null,"",`?session=${encodeURIComponent(e.id)}`),window.setTimeout(()=>v(e=>e+1),1200)},[o,tr]),ti=(0,n.useCallback)(()=>{v(e=>e+1),j(e=>e+1)},[]),ta=(0,n.useCallback)(e=>{v(e=>e+1),b(e=>e+1),m(null),e7(null),f(t=>{let o={...t??{path:"",cwd:"",created:"",modified:"",messageCount:0,firstMessage:""},id:e},r=o.projectRoot??o.cwd;return r&&e3.current.set(r,e),o}),tr(e),window.history.replaceState(null,"",`?session=${encodeURIComponent(e)}`)},[o,tr]),tl=(0,n.useCallback)(()=>{e6(!0)},[]),td=(0,n.useCallback)(e=>{if(v(e=>e+1),h?.id===e){let e=h.cwd;f(null),m(e??null),b(e=>e+1),Q(null),em(null),window.history.replaceState(null,"","/")}},[o,h]),tc=(0,n.useCallback)((e,t,o,r)=>{let n="string"==typeof o||null===o?o:void 0,s="object"==typeof o&&null!==o?o:r,i=`file:${e}`;ej(o=>{let r=o.find(e=>e.id===i);return r?n&&r.sourceSessionId!==n||s?.initialDisplayMode&&r.initialDisplayMode!==s.initialDisplayMode?o.map(e=>e.id===i?{...e,sourceSessionId:n??e.sourceSessionId,initialDisplayMode:s?.initialDisplayMode??e.initialDisplayMode}:e):o:[...o,{id:i,label:t,filePath:e,sourceSessionId:n,initialDisplayMode:s?.initialDisplayMode}]}),eT(i),ez(!0),g&&H(!1)},[g]),tp=(0,n.useCallback)(e=>{tc(e,er(e),h?.id??null)},[tc,h?.id]),tu=(0,n.useCallback)(e=>{ej(t=>{let o=t.filter(t=>t.id!==e);return 0===o.length&&ez(!1),o}),eT(t=>{if(t!==e)return t;let o=ew.filter(t=>t.id!==e);return o.length>0?o[o.length-1].id:null})},[ew]),tg=h?e$(h.name||et?.sessionName)||h.firstMessage.slice(0,50)||h.id.slice(0,12):(e=eX??x)?e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e:null,th=(0,n.useCallback)(()=>{h&&window.open(`/api/sessions/${encodeURIComponent(h.id)}/export?inline=1`,"_blank","noopener,noreferrer")},[h]),tf=x??(null===h&&eX?eX:null),tx="validating"!==eQ&&"error"!==eQ&&(null!==h||null!==tf),tm=h?.cwd??tf,[tk,tv]=(0,n.useState)(!1),ty=(0,n.useCallback)(()=>{g||tv(e=>!e)},[g]),[tb,tw]=(0,n.useState)(!0);(0,n.useEffect)(()=>{let e=!1,t=()=>fetch("/api/features").then(e=>e.ok?e.json():null).then(t=>{!e&&t&&"boolean"==typeof t.tasksBoard&&(tw(t.tasksBoard),t.tasksBoard||tv(!1))}).catch(()=>{});t();let o=()=>t();return window.addEventListener("pi:features-changed",o),()=>{e=!0,window.removeEventListener("pi:features-changed",o)}},[]);let tj=e4&&!tx;(0,n.useEffect)(()=>{let e=()=>{g||tv(!0)};return window.addEventListener(sU,e),()=>window.removeEventListener(sU,e)},[g]),(0,n.useEffect)(()=>{if(P(null),F(!1),A(null),!tm)return;let e=new AbortController;return fetch(`/api/project-trust?cwd=${encodeURIComponent(tm)}`,{signal:e.signal}).then(async e=>{let t=await e.json();if(!e.ok||t.error)throw Error(t.error??`HTTP ${e.status}`);P(t)}).catch(e=>{e instanceof DOMException&&"AbortError"===e.name||console.error("Failed to load project trust:",e)}),()=>e.abort()},[tm]);let tS=(0,n.useCallback)(async()=>{if(tm&&!W){N(!0),A(null);try{let e=await fetch("/api/project-trust",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:tm})}),t=await e.json();if(!e.ok||t.error)throw Error(t.error??`HTTP ${e.status}`);P(t),F(!1),I(e=>e+1),b(e=>e+1)}catch(e){A(e instanceof Error?e.message:String(e))}finally{N(!1)}}},[W,tm]),tC=ew.find(e=>e.id===eC)??null,tT=eX??h?.cwd??x,tR=(0,n.useCallback)(e=>{R(e),C(!0)},[]),tz=(0,r.jsx)(r.Fragment,{children:(0,r.jsx)(eK,{selectedSessionId:h?.id??null,onSelectSession:tt,onNewSession:tn,initialSessionId:eG,onInitialRestoreDone:tl,refreshKey:k,onSessionDeleted:td,selectedCwd:h?.cwd??x??null,onCwdChange:te,onOpenFile:tc,selectedSessionStats:et,onOpenSettings:e=>{tR(["models","skills","plugins","chat","features","logs"].includes(e)?e:"models")},explorerRefreshKey:w,onAtMention:eq,onAtMentions:eV,workspaceControlsHosts:{title:V,welcome:Y,titleRight:J},showWorkspaceControls:!0})});return(0,r.jsxs)(lv,{children:[(0,r.jsx)("style",{children:`
|
|
36
|
+
${e}`):n=e;let h=n,f=o?.map(e=>({type:"image",source:{type:"base64",media_type:e.mimeType,data:e.data}})),x={role:"user",content:f?.length?[...e.trim()?[{type:"text",text:e}]:[],...f]:e,timestamp:Date.now()};S(e=>[...e,x]),t3.current=sO(x),t5.current=a,"goal"!==ex.current||i||(ey.current=s,eA(e=>({...e,status:"running",goalText:s,turnsUsed:0,noProgressTurns:0,tokensUsed:0})),eH.current=!0),tB.current=!0,$(!0),e9(i?{kind:"running_command"}:{kind:"waiting_model"}),z({type:"start"}),tY.current=!0,tt(!0),tX.current=!0;let m=o?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),k=null,v=!1;try{if(g&&r){let t=tH.current??await t4.current,o=t??await ox();if(o){k=o,X&&(e1(X),t&&await sT(o,{type:"set_model",provider:X.provider,modelId:X.modelId}));let r=await Promise.race([ob(o).then(()=>!0).catch(()=>!1),s$(4e3).then(()=>!1)]);v=!0,await sT(o,{type:"prompt",message:h,...m?.length?{images:m}:{}}),of(1,e),r||oF(o,a),"goal"!==ex.current||i||sT(o,{type:"goal_start",goalText:s}).catch(()=>{})}}else if(t){k=t.id;let e=await Promise.race([ob(t.id).then(()=>!0).catch(()=>!1),s$(4e3).then(()=>!1)]);v=!0,await sT(t.id,{type:"prompt",message:h,...m?.length?{images:m}:{}}),e||oF(t.id,a),"goal"!==ex.current||i||sT(t.id,{type:"goal_start",goalText:s}).catch(()=>{})}i&&k&&oF(k,a)}catch(e){if(console.error("Failed to send message:",e),v&&k)return void oF(k,a);if(t_.current=!1,ov(),e instanceof sW){let t=t3.current;t&&S(e=>{let o=e[e.length-1];return o?.role==="user"&&sO(o)===t?e.slice(0,-1):e}),oS({type:"error",message:e.message})}else oS({type:"error",message:`Failed to send message: ${e instanceof Error?e.message:String(e)}`});t3.current=null,tB.current=!1,$(!1),e9(null),z({type:"end"})}},[g,r,X,t,ox,ob,of,oF,oS,ok,ov,on]),oA=(0,n.useCallback)(async(o,r)=>{if(tB.current||tV.current)return;let n=`${r?"!!":"!"}${o}`;tV.current=!0,O({command:o,excludeFromContext:r}),L(!0);try{let e=tH.current??t?.id??await ox();if(!e)throw Error("Unable to create a session for the shell command");await sT(e,{type:"bash",command:o,excludeFromContext:r}),await ou(e),of(1,n)}catch(t){console.error("Failed to execute shell command:",t),oS({type:"error",message:t instanceof Error?t.message:String(t)}),e.chatInputRef?.current?.insertIfEmpty(n)}finally{tV.current=!1,O(null),L(!1)}},[oS,ox,ou,e.chatInputRef,of,t]),oO=(0,n.useCallback)(async()=>{let e=tH.current;if(e)try{await sT(e,{type:tV.current?"abort_bash":"abort"})}catch(e){console.error("Failed to abort:",e)}},[]),oH=(0,n.useCallback)(async e=>{let t=tH.current;if(t){eX(e);try{let{cancelled:o,newSessionId:r}=await sT(t,{type:"fork",entryId:e})??{};!o&&r&&a?.(r)}catch(e){console.error("Fork failed:",e)}finally{eX(null)}}},[a]),oB=(0,n.useCallback)(async e=>{let t=tH.current;t&&(sT(t,{type:"navigate_tree",targetId:e}).catch(()=>{}),w(e),await og(t,e))},[og]),oU=(0,n.useCallback)(async e=>{w(e);let t=tH.current;t&&(await og(t,e),e&&sT(t,{type:"navigate_tree",targetId:e}).catch(()=>{}))},[og]),o_=(0,n.useCallback)(async(e,t)=>{if(g){let o={provider:e,modelId:t};ot.current=o,Z(o),e1(o);let r=tH.current??await t4.current;if(!r)return;try{await sT(r,{type:"set_model",provider:e,modelId:t})}catch(e){console.error("Failed to set model:",e)}return}let o=tH.current;if(!o)return;let r=++t8.current,n=eZ??f?.context.model??null;eQ({provider:e,modelId:t});try{await sT(o,{type:"set_model",provider:e,modelId:t})}catch(o){console.error("Failed to set model:",o),t8.current===r&&(eQ(n&&(n.provider!==e||n.modelId!==t)?n:null),oS({type:"error",message:o instanceof Error?o.message:String(o)}))}},[oS,eZ,f?.context.model,g,Z]),oq=(0,n.useCallback)(async()=>{let e=tH.current;if(e&&!e2){e4(!0),e5(null),e8(null);try{let t=await sT(e,{type:"compact"});e8(sH(t,"manual")),await ou(e,!0)}catch(e){e5(e instanceof Error?e.message:String(e)),e8(null)}finally{e4(!1)}}},[e2,ou]),oV=(0,n.useCallback)(async e=>{let o=++t7.current,n=r??t?.cwd??"",s=n?`/api/models?cwd=${encodeURIComponent(n)}`:"/api/models",i=t9.current;i?.abort();let a=new AbortController;t9.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)throw Error(`HTTP ${e.status}`);let t=await e.json();if(o!==t7.current||h!==oe.current)return;B(t.models),V(t.thinkingLevels??{}),J(t.thinkingLevelMaps??{}),Y(t.modelScopeWarnings??[]);let r=t.modelList??[];if(_(r),g&&!tH.current){let e=(t.defaultModel?r.find(e=>e.id===t.defaultModel?.modelId&&e.provider===t.defaultModel?.provider):void 0)??r[0];ee(e?{provider:e.provider,modelId:e.id}:null);let o=e?t.thinkingLevelPins?.[`${e.provider}/${e.id}`]:void 0;null===oo.current&&eU(o??"auto")}}finally{e?.removeEventListener("abort",l),t9.current===a&&(t9.current=null)}},[g,h,r,t?.cwd]),oK=(0,n.useCallback)(async e=>{if(!e.startsWith("/"))return{handled:!1};let t=e.match(/^\/([^\s]+)(?:\s+([\s\S]*))?$/);if(!t)return{handled:!1};let[,o,r=""]=t,n=r.trim(),s=tH.current??await ox(),i=e=>(e.handled&&(e.error?oS({type:"error",message:e.error}):"openSessionStats"!==e.action&&oS({type:"success",message:e.message??"Command completed"})),e);try{switch(o){case"compact":{if(!s||e2)return i({handled:!0,error:"No active session to compact"});e4(!0),e5(null),e8(null);let e=await sT(s,{type:"compact",...n?{customInstructions:n}:{}});return e8(sH(e,"manual")),await ou(s,!0)&&of(),i({handled:!0,message:"Compacted context"})}case"reload":if(!s)return i({handled:!0,error:"No active session to reload"});return await sT(s,{type:"reload"}),await Promise.all([ou(s,!1,!0),oh(s),om(),oV()]),i({handled:!0,message:"Reloaded session resources"});case"name":if(!s)return i({handled:!0,error:"No active session to name"});if(!n)return i({handled:!0,error:"Usage: /name <name>"});return await sT(s,{type:"set_session_name",name:e$(n)}),await ou(s)&&of(),i({handled:!0,message:`Session renamed to ${n}`});case"session":{if(!s)return i({handled:!0,error:"No active session"});let e=await sT(s,{type:"get_session_stats"});return e&&td(e),p?.(),i({handled:!0,action:"openSessionStats"})}case"copy":{if(!s)return i({handled:!0,error:"No active session"});let e=await sT(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&&e4(!1)}},[oS,ox,e2,oV,ou,om,oh,of,p]),oJ=(0,n.useCallback)(async(e,t)=>{let o=tH.current;if(!o)return;let r=t?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType}));try{await sT(o,{type:"steer",message:e,...r?.length?{images:r}:{}})}catch(e){console.error("Failed to steer:",e)}},[]),oG=(0,n.useCallback)(async(e,t,o)=>{let r=tH.current;if(!r)return;let n=o?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType}));try{await sT(r,{type:"prompt",message:e,streamingBehavior:t,...n?.length?{images:n}:{}})}catch(e){console.error("Failed to queue prompt:",e)}},[]),oY=(0,n.useCallback)(async(e,t)=>{let o=tH.current;if(!o)return;let r=t?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType}));try{await sT(o,{type:"follow_up",message:e,...r?.length?{images:r}:{}})}catch(e){console.error("Failed to follow up:",e)}},[]),oX=(0,n.useCallback)(async()=>{let e=tH.current;if(e)try{await sT(e,{type:"abort_compaction"})}catch(e){console.error("Failed to abort compaction:",e)}},[]),oZ=(0,n.useCallback)(async()=>{let t=tH.current;if(t)try{let o=await sT(t,{type:"clear_queue"});tv({steering:[],followUp:[]});let r=[...o?.steering??[],...o?.followUp??[]];r.length>0&&e.chatInputRef?.current?.prependText(r.join("\n\n"))}catch(e){console.error("Failed to recall queued messages:",e),oS({type:"error",message:"Failed to recall queued messages"})}},[e.chatInputRef,oS]);(0,n.useEffect)(()=>{0===ty.length&&tj(!1)},[ty.length]);let oQ=(0,n.useCallback)(async(e,t,o=!1)=>{let r=tH.current;if(!r)return ty;try{let n=await sT(r,{type:"resolve_recovery",keep:e,discard:t,continueRun:o}),s=n?.remaining??[];return tb(s),o&&e.length>0&&(async()=>{try{let e=await fetch(`/api/agent/${encodeURIComponent(r)}`);if(!e.ok)return;let t=await e.json(),o=t.state;if(!t.running||!o||!o.isStreaming&&!o.isPromptRunning)return;tU.current=!!o.isStreaming,t_.current=!!o.isPromptRunning,tB.current=!0,$(!0),e9(sM(o)),z({type:"start"}),oy(r),!o.isStreaming&&o.isPromptRunning&&oF(r)}catch{}})(),s}catch(e){return console.error("Failed to resolve queued message recovery:",e),oS({type:"error",message:"Failed to resolve queued message recovery"}),ty}},[ty,oS,oy,oF]),o0=(0,n.useCallback)(async()=>{let e=tH.current;if(!e)return null;try{return await sT(e,{type:"export_queue"})}catch(e){return console.error("Failed to export queue:",e),oS({type:"error",message:"Failed to export queue"}),null}},[oS]),o1=(0,n.useCallback)(async e=>{let t=tH.current;if(!t)return null;try{let o=await sT(t,{type:"import_queue",entries:e});return o&&tv(sE(o)),o?.imported??0}catch(e){return console.error("Failed to import queue:",e),oS({type:"error",message:"Failed to import queue"}),null}},[oS]),o2=(0,n.useCallback)(async e=>{let t=tH.current;if(!t)return null;try{let o=await sT(t,{type:"stage_recovery",entries:e});return o?.pendingRecovery&&tb(o.pendingRecovery),(o?.staged??0)>0&&tj(!0),o?.staged??0}catch(e){return console.error("Failed to stage imported queue:",e),oS({type:"error",message:"Failed to stage imported queue"}),null}},[oS]),o4=(0,n.useCallback)(async(e,t,o)=>{let r=tH.current;if(!r)return!1;try{let n=await sT(r,{type:"move_queue",kind:e,fromIndex:t,toIndex:o});return n&&tv(sE(n)),!0}catch(e){return console.error("Failed to move queued message:",e),oS({type:"error",message:e instanceof Error?e.message:"Failed to move queued message"}),!1}},[oS]),o6=(0,n.useCallback)(async(e,t)=>{let o=tH.current;if(!o)return null;try{let r=await sT(o,{type:"recall_queue_item",kind:e,index:t});return r&&(void 0!==r.steering||void 0!==r.followUp)&&tv(sE(r)),r?.entry?{text:r.entry.text,images:r.entry.images?.map(({data:e,mimeType:t})=>({data:e,mimeType:t}))}:null}catch(e){return console.error("Failed to recall queued message:",e),oS({type:"error",message:e instanceof Error?e.message:"Failed to recall queued message"}),null}},[oS]),o5=(0,n.useCallback)(async(e,t,o,r)=>{let n=tH.current;if(!n)return!1;try{let s=await sT(n,{type:"requeue_at",kind:e,index:t,text:o,images:r?.map(({data:e,mimeType:t})=>({type:"image",data:e,mimeType:t}))});return s&&tv(sE(s)),!0}catch(e){return console.error("Failed to requeue message:",e),oS({type:"error",message:e instanceof Error?e.message:"Failed to requeue message"}),!1}},[oS]),o3=(0,n.useCallback)(async(e,t)=>{let o=tH.current;if(!o)return!1;try{let r=await sT(o,{type:"remove_queue_item",kind:e,index:t});return r&&tv(sE(r)),!0}catch(e){return console.error("Failed to remove queued message:",e),oS({type:"error",message:e instanceof Error?e.message:"Failed to remove queued message"}),!1}},[oS]),o8=(0,n.useCallback)(async e=>{if(oo.current="auto"===e?null:e,eU(e),"auto"===e)return;let t=tH.current??await t4.current;if(t)try{await sT(t,{type:"set_thinking_level",level:e})}catch(e){console.error("Failed to set thinking level:",e)}},[]),o7=(0,n.useCallback)(async e=>{let t=(0,sR.xG)(e);oi(e);let o=tH.current??await t4.current;if(o)try{await sT(o,{type:"set_tools",toolNames:t})}catch(e){console.error("Failed to set tools:",e)}},[oi]),o9=(0,n.useRef)(0),re=(0,n.useCallback)(async e=>{let t=tH.current??await t4.current,o=++o9.current;if(e){if(es.current="plan"===et?"default":et,en(!0),ei.current=!0,eb.current={sessionKey:"",signature:""},t)try{if(await sT(t,{type:"prompt",message:"/plan"}),o9.current!==o)return}catch(e){if(o9.current!==o)return;console.error("Failed to enter plan mode:",e)}}else if(en(!1),ei.current=!1,eb.current={sessionKey:"",signature:""},t){try{if(await sT(t,{type:"prompt",message:"/plan exit"}),o9.current!==o)return}catch(e){if(o9.current!==o)return;console.error("Failed to exit plan mode:",e)}if(o9.current!==o)return;try{let e=es.current;await sT(t,{type:"set_tools",toolNames:(0,sR.xG)(e)})}catch(e){console.error("Failed to restore tools after plan exit:",e)}}},[et]),rt=(0,n.useCallback)(e=>{el(e);let t=tH.current;if(!t){ed.current=e;return}ed.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)})},[]),ro=(0,n.useCallback)(e=>{if(rt({...ew.current,collaborationMode:ez(e)}),ex.current=ez(e),eb.current={sessionKey:"",signature:""},"goal"!==e){ey.current=null,eH.current=!1,eA(e=>"idle"===e.status?e:{...e,status:"idle",goalText:null});let e=tH.current;e&&sT(e,{type:"goal_stop"}).catch(()=>{})}},[rt]),rr=(0,n.useCallback)(async e=>{rt({...ew.current,tokenMode:eI(e)});let t=tH.current??await t4.current;if(t)try{if("economy"!==e||ei.current){if("economy"!==e){let e=ei.current?sR.SC:(0,sR.xG)("plan"===et?"default":et);await sT(t,{type:"set_tools",toolNames:e})}}else await sT(t,{type:"set_tools",toolNames:[...eE]})}catch(e){console.error("Failed to apply token mode tools:",e)}},[rt,et]),rn=(0,n.useCallback)(async e=>{rt({...ew.current,toolApprovalMode:eM(e)});let t=tH.current??await t4.current;if(t)try{await sT(t,{type:"set_approval_mode",mode:eM(e)})}catch(e){console.error("Failed to apply approval mode:",e)}},[rt]),rs=(0,n.useCallback)(async e=>{rt({...ew.current,permissionRules:e});let t=tH.current??await t4.current;if(t)try{await sT(t,{type:"set_approval_policy",policy:e})}catch(e){console.error("Failed to apply permission rules:",e)}},[rt]),ri=(0,n.useCallback)(async(e,t,o)=>{let r=tH.current;if(r)try{await sT(r,{type:"resolve_approval",id:e,approve:t,reason:o})}catch(e){console.error("Failed to resolve approval:",e)}finally{eS(t=>t.filter(t=>t.id!==e))}},[]),ra=(0,n.useCallback)(e=>{ey.current=e},[]),rl=(0,n.useCallback)(e=>{let t=e.trim();if(!t)return;ey.current=t,eA(e=>({...e,status:"running",goalText:t,turnsUsed:0,noProgressTurns:0,tokensUsed:0,startedAt:Date.now()}));let o=tH.current;o&&sT(o,{type:"goal_start",goalText:t}).catch(()=>{})},[]),rd=(0,n.useCallback)(()=>{if("running"!==eO.current.status)return;eA(e=>({...e,status:"paused"}));let e=tH.current;e&&sT(e,{type:"goal_pause"}).catch(()=>{})},[]),rc=(0,n.useCallback)(()=>{let e=eO.current;if("paused"!==e.status&&"blocked"!==e.status)return;eA(e=>({...e,status:"running"}));let t=tH.current;t&&sT(t,{type:"goal_resume"}).catch(()=>{})},[]),rp=(0,n.useCallback)(()=>{eH.current=!1,ey.current=null,eA(e=>({...e,status:"idle",goalText:null,turnsUsed:0,noProgressTurns:0}));let e=tH.current;e&&sT(e,{type:"goal_stop"}).catch(()=>{})},[]),ru=(0,n.useCallback)(e=>{let t=e.trim();if(!t)return;eA(e=>({...e,goalText:t}));let o=tH.current;o&&sT(o,{type:"goal_edit",goalText:t}).catch(()=>{})},[]),rg=tS.map(e=>`${e.id}:${e.status}:${e.completedAt??""}`).join("|"),rh=(0,n.useRef)(tS);rh.current=tS,(0,n.useEffect)(()=>{u?.(rh.current)},[rg,u]),(0,n.useEffect)(()=>()=>{u?.([])},[u]),(0,n.useEffect)(()=>{tz(()=>[])},[t?.id,r??t?.cwd]);let rf=(0,n.useCallback)(()=>{let e=t2.current,t=tG.current;if(!e||!t)return;let o=t.getBoundingClientRect().top-e.getBoundingClientRect().top+e.scrollTop,r=Math.max(0,e.scrollHeight-e.clientHeight),n=Math.min(Math.max(0,o-16),r);tZ.current=n>=r-150,t0.current=Date.now()+700,e.scrollTo({top:n,behavior:"smooth"})},[]),rx=(0,n.useCallback)(e=>{e instanceof KeyboardEvent&&(!sF.has(e.key)||e.target instanceof Element&&e.target.closest("input, textarea, [contenteditable='true']"))||(tQ.current=Date.now()+1200)},[]),rm=(0,n.useCallback)(()=>{let e=t2.current;if(e){let{scrollTop:t,clientHeight:o,scrollHeight:r}=e;tZ.current=t+o>=r-150}if(Date.now()<tQ.current){tX.current=!1;return}Date.now()<t0.current||(tX.current=!1)},[]);(0,n.useEffect)(()=>{if(t){tH.current=t.id;let e=ek.current,o=ev.current;("auto"!==e||o.allow.length||o.ask.length||o.deny.length)&&(sT(t.id,{type:"set_approval_mode",mode:e}).catch(()=>{}),sT(t.id,{type:"set_approval_policy",policy:o}).catch(()=>{})),ou(t.id,!0,!0).then(e=>{e?.running&&(e.state?.isBashRunning&&(tV.current=!0,L(!0)),oh(t.id),(e.state?.isStreaming||e.state?.isPromptRunning)&&(tU.current=!!e.state.isStreaming,t_.current=!!e.state.isPromptRunning,tB.current=!0,$(!0),e9(sM(e.state)),z({type:"start"}),oy(t.id),!e.state.isStreaming&&e.state.isPromptRunning&&oF(t.id))),e?.state&&(void 0!==e.state.isCompacting&&e4(e.state.isCompacting),void 0!==e.state.contextUsage&&eK(e.state.contextUsage??null),void 0!==e.state.systemPrompt&&eG(e.state.systemPrompt??null),void 0!==e.state.thinkingLevel&&eU(e.state.thinkingLevel??"auto"),void 0!==e.state.extensionStatuses&&tf(e.state.extensionStatuses??[]),void 0!==e.state.extensionWidgets&&tm(e.state.extensionWidgets??[]),void 0!==e.state.queuedMessages&&tv(sE(e.state.queuedMessages)),void 0!==e.state.pendingRecovery&&tb(e.state.pendingRecovery??[])),e?.running||fetch(`/api/agent/${encodeURIComponent(t.id)}`).then(e=>e.ok?e.json():null).then(e=>{e&&e.running&&oh(t.id)}).catch(()=>{})})}return()=>{on(),tF(),ok(),ov()}},[on]),(0,n.useEffect)(()=>{c?.(eJ)},[eJ,c]),(0,n.useEffect)(()=>{d&&d(f?.tree??[],b,oU)},[f?.tree,b,oU,d]),(0,n.useEffect)(()=>(window.addEventListener("keydown",rx),window.addEventListener("pointerdown",rx,{passive:!0}),()=>{window.removeEventListener("keydown",rx),window.removeEventListener("pointerdown",rx)}),[rx]),(0,n.useEffect)(()=>{let e=t2.current;if(e)return e.addEventListener("wheel",rx,{passive:!0}),e.addEventListener("touchstart",rx,{passive:!0}),e.addEventListener("scroll",rm,{passive:!0}),()=>{e.removeEventListener("wheel",rx),e.removeEventListener("touchstart",rx),e.removeEventListener("scroll",rm)}},[j.length,m,rm,rx]),(0,n.useEffect)(()=>{j.length>0&&(tY.current?(tJ.current=!0,tG.current&&(tY.current=!1,rf())):m||!tJ.current?(m||(tJ.current=!0),o$("instant")):!tB.current&&(tX.current||tZ.current)&&o$("smooth"))},[j.length,m,W,o$,rf]);let rk=(0,n.useRef)(!1);(0,n.useEffect)(()=>{let e;if(m){rk.current=!1;return}if(rk.current||0===j.length)return;rk.current=!0;let t=!1,o=-1,r=0,n=()=>{if(t||tB.current||!(tX.current||tZ.current))return;o$("instant");let s=t2.current;if(s){if(s.scrollHeight===o){if((r+=1)>=2)return}else o=s.scrollHeight,r=0;e=window.setTimeout(n,250)}};return e=window.setTimeout(n,250),()=>{t=!0,void 0!==e&&window.clearTimeout(e)}},[m,j.length,o$]),(0,n.useEffect)(()=>{let e=new AbortController;return oV(e.signal).catch(e=>{if(e instanceof DOMException&&"AbortError"===e.name)return}),()=>e.abort()},[oV,l]),(0,n.useEffect)(()=>{if(!e6)return;let e=setTimeout(()=>e5(null),3e3);return()=>clearTimeout(e)},[e6]),(0,n.useEffect)(()=>{if(!e3)return;let e=setTimeout(()=>e8(null),6e3);return()=>clearTimeout(e)},[e3]),(0,n.useEffect)(()=>{if(0===ti.visible.length)return;let e=ti.visible.find(e=>e.exiting);if(e){let t=setTimeout(()=>{ta({type:"remove",id:e.id})},180);return()=>clearTimeout(t)}if(!ti.visible[0])return;let t=setTimeout(()=>{ta({type:"mark_oldest_exiting"})},5e3);return()=>clearTimeout(t)},[ti.visible]),(0,n.useEffect)(()=>{td(null)},[j.length,eV?.tokens,eV?.percent,eV?.contextWindow]);let rv=f?.tree??[];return{data:f,loading:m,error:v,activeLeafId:b,messages:j,entryIds:C,streamState:R,agentRunning:W,bashRunning:N,pendingBash:A,modelNames:H,modelList:U,modelThinkingLevels:q,modelThinkingLevelMaps:K,modelScopeWarnings:G,newSessionModel:X,toolPreset:et,thinkingLevel:eB,retryInfo:e_,contextUsage:eV,systemPrompt:eJ,forkingEntryId:eY,isCompacting:e2,compactError:e6,compactResult:e3,currentModel:od,displayModel:oc,sessionStats:op,tokenRate:I,planMode:er,subagents:tS,collaborationMode:eu,tokenMode:eg,toolApprovalMode:eh,permissionRules:ef,modeSettings:ea,approvalRequests:ej,handleCollaborationModeChange:ro,handleTokenModeChange:rr,handleToolApprovalModeChange:rn,handlePermissionRulesChange:rs,resolveApproval:ri,setActiveGoalText:ra,goalState:eL,handleGoalStart:rl,handleGoalPause:rd,handleGoalResume:rc,handleGoalStop:rp,handleGoalEdit:ru,slashCommands:to,slashCommandsLoading:tn,queuedMessages:tk,pendingRecovery:ty,recoveryIsImport:tw,notices:ti.visible,extensionDialog:tc,extensionCustomUi:tu,extensionStatuses:th,extensionWidgets:tx,respondToExtensionUi:ow,sendExtensionCustomInput:oj,agentPhase:e7,isNew:g,promptAnchorActive:te,branchTree:rv,sessionIdRef:tH,eventSourceRef:tW,messagesEndRef:t1,scrollContainerRef:t2,lastUserMsgRef:tG,pendingScrollToUserRef:tY,initialScrollDoneRef:tJ,scrollUserMsgToTop:rf,handleSend:oL,executeBash:oA,handleAbort:oO,handleFork:oH,handleNavigate:oB,handleModelChange:o_,handleCompact:oq,handleSteer:oJ,handleFollowUp:oY,handlePromptWithStreamingBehavior:oG,handleAbortCompaction:oX,handleRecallQueue:oZ,resolveRecovery:oQ,exportQueueData:o0,importQueueData:o1,stageQueueImport:o2,moveQueuedMessage:o4,recallQueuedMessage:o6,requeueAt:o5,removeQueuedMessage:o3,handleBuiltinSlashCommand:oK,handleToolPresetChange:o7,handleThinkingLevelChange:o8,handlePlanModeChange:re,loadTools:oh,loadSlashCommands:om,setActiveLeafId:w,setData:x,setMessages:S,dispatch:z,setAgentRunning:$,setForkingEntryId:eX,handleLeafChange:oU,handleAgentEventRef:tK}}({session:e,newSessionCwd:t,onAgentEnd:F,onSessionCreated:i,onSessionForked:l,modelsRefreshKey:d,chatInputRef:c,onBranchDataChange:p,onSystemPromptChange:u,onSessionStatsPanelOpen:f,onSubagentsChange:h}),[tS,tC]=(0,n.useState)(!1);(0,n.useEffect)(()=>{0===eu.length&&tC(!1)},[eu.length]);let{balance:tT,refresh:tR,refreshSoon:tz}=function(){let[e,t]=(0,n.useState)(null),[o,r]=(0,n.useState)(!1),s=(0,n.useRef)(null),i=(0,n.useRef)(null),a=(0,n.useRef)(!0);(0,n.useEffect)(()=>(a.current=!0,()=>{a.current=!1,i.current&&clearTimeout(i.current),s.current?.abort()}),[]);let l=(0,n.useCallback)(async()=>{s.current?.abort();let o=new AbortController;s.current=o;try{let n=await fetch("/api/deepseek/balance",{signal:o.signal,cache:"no-store"}),s=await n.json();if(!a.current)return;s?.available&&null!=s.totalBalance?(t(s),r(!1)):null===e&&r(!0)}catch{if(!a.current)return;null===e&&r(!0)}},[e]),d=(0,n.useCallback)(()=>{i.current&&clearTimeout(i.current),i.current=setTimeout(()=>{i.current=null,l()},2e3)},[l]);return{balance:e,failed:o,refresh:l,refreshSoon:d}}(),tI=ei?.provider==="deepseek",tM=(0,n.useRef)(null);(0,n.useEffect)(()=>{tI&&tR()},[tI,tR]),(0,n.useEffect)(()=>{if(tI)for(let e=H.length-1;e>=0;e--){let t=H[e];if("assistant"!==t.role||!t.usage)continue;let o=`${e}:${B[e]??""}`;o!==tM.current&&(tM.current=o,tz());break}},[H,B,tI,tz]);let tE=(0,n.useMemo)(()=>{let e=H.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:oR(e.model)?oz(e.model,t):0,costUSD:oR(e.model)?0:t.cost?.total??0}},[H]),[tP,tD]=(0,n.useState)(!1),[tF,tW]=(0,n.useState)(null),t$=(0,n.useRef)(!1);(0,n.useEffect)(()=>{if(!ti){t$.current=!1;return}if(_){t$.current=!0;return}t$.current&&(t$.current=!1,tW(function(e){for(let t=e.length-1;t>=0;t--){let o=e[t];if("assistant"!==o.role)continue;let r=o.content;if("string"==typeof r&&r.trim())return r;if(Array.isArray(r)){let e=r.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 r=o.content,n="string"==typeof r?r:Array.isArray(r)?r.map(e=>e.text??"").join("\n"):"";if(!n)continue;let s=n.match(/\*\*Proposed Plan\*\*\s*\n+([\s\S]+)/i);if(s?.[1]?.trim())return s[1].trim()}return null}(H)??null),tD(!0))},[_,ti,H]);let tN=(0,n.useCallback)(()=>{tD(!1);let e=tL.current;"plan"===tl&&tg("normal"),ta(!1).then(()=>{e&&eq(I("tasks.planReviewExecutePrompt",{plan:e}))})},[ta,eq,I,tl,tg]),tL=(0,n.useRef)(null);(0,n.useEffect)(()=>{tL.current=tF},[tF]);let tA=(0,n.useCallback)(e=>{tD(!1),eZ(e)},[eZ]),tO=(0,n.useCallback)(()=>{tD(!1),"plan"===tl&&tg("normal"),ta(!1)},[ta,tl,tg]);(0,n.useEffect)(()=>{ef&&D.current!==ef.id&&(D.current=ef.id,P.current&&M.current())},[ef]),(0,n.useEffect)(()=>{a=_||q?eK:null},[_,q,eK]);let[tH,tB]=(0,n.useState)(!1),[tU,t_]=(0,n.useState)(!1),[tq,tV]=(0,n.useState)(!1),tK=(0,n.useCallback)(()=>{let e=eO.current;if(!e)return;let t=e.scrollHeight-e.scrollTop-e.clientHeight;tB(e.scrollTop>1),t_(t>1),tV(t>240)},[eO]),tJ=(0,n.useCallback)(()=>{window.requestAnimationFrame(()=>{let e=eO.current,t=eA.current;if(!e||!t)return;let o=Math.max(88,c?.current?.measureHeight?.()??0),r=()=>{if(!e||!t)return;let r=Math.max(0,t.getBoundingClientRect().top-e.getBoundingClientRect().top+e.scrollTop-96-e.clientHeight+o);e.scrollTo({top:r,behavior:"auto"})};r(),tK(),window.setTimeout(r,200)})},[eA,eO,tK,c]);(0,n.useEffect)(()=>{let e=eO.current;if(!e)return;let t=new ResizeObserver(tK);return t.observe(e),e.firstElementChild&&t.observe(e.firstElementChild),e.addEventListener("scroll",tK,{passive:!0}),tK(),()=>{e.removeEventListener("scroll",tK),t.disconnect()}},[H.length,eO,tK]);let tG=(0,n.useRef)(null),tY=(0,n.useRef)([]),tX=(0,n.useMemo)(()=>({getOffsetForIndex:e=>tG.current?.getOffsetForIndex(e)?.[0]??0,sizeFor:e=>{let t=tG.current;if(!t)return 0;let o=t.measurementsCache[e];return o?.size??t.options.estimateSize?.(e)??0},totalHeight:()=>tG.current?.getTotalSize()??0,refToItemIndex:e=>tY.current[e],itemCount:tY.current.length}),[]),tZ=ea?[ea.sessionId,ea.sessionFile??"",ea.sessionName??"",ea.userMessages,ea.assistantMessages,ea.toolCalls,ea.toolResults,ea.totalMessages,ea.tokens.input,ea.tokens.output,ea.tokens.cacheRead,ea.tokens.cacheWrite,ea.tokens.total,ea.cost??0,ea.totalActiveMs??0].join("|"):null,tQ=(0,n.useRef)(ea);tQ.current=ea,(0,n.useEffect)(()=>{g?.(tQ.current)},[tZ,g]),(0,n.useEffect)(()=>()=>{g?.(null)},[g]);let t0=et?`${et.percent??"null"}|${et.contextWindow}|${et.tokens??"null"}`:null,t1=(0,n.useRef)(et);t1.current=et,(0,n.useEffect)(()=>{x?.(t1.current)},[t0,x]),(0,n.useEffect)(()=>()=>{x?.(null)},[x]);let{isDragOver:t2,handleDragEnter:t4,handleDragOver:t6,handleDragLeave:t5,handleDrop:t3}=function(e){let[t,o]=(0,n.useState)(!1),r=(0,n.useRef)(0),s=(0,n.useCallback)(e=>{e.dataTransfer.files.length&&(e.preventDefault(),r.current+=1,o(!0))},[]),i=(0,n.useCallback)(e=>{e.dataTransfer.files.length&&e.preventDefault()},[]);return{isDragOver:t,handleDragEnter:s,handleDragOver:i,handleDragLeave:(0,n.useCallback)(()=>{r.current-=1,r.current<=0&&(r.current=0,o(!1))},[]),handleDrop:(0,n.useCallback)(t=>{t.preventDefault(),r.current=0,o(!1),e(Array.from(t.dataTransfer.files),t.dataTransfer)},[e])}}((0,n.useCallback)((e,t)=>{if(_){let t=e.filter(e=>e.type.startsWith("image/"));t.length&&c?.current?.addImages(t);return}c?.current?.addFiles(e,t)},[_,c])),t8=H.filter(e=>"user"===e.role||"assistant"===e.role),t7=(0,n.useMemo)(()=>{let e=new Set,t=[];for(let r=H.length-1;r>=0&&t.length<50;r-=1){var o;let n="user"!==(o=H[r]).role?null:("string"==typeof o.content?o.content:o.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n")).trim()||null;!n||e.has(n)||(e.add(n),t.push(n))}return t},[H]),t9=(w=t8.length,(j=(0,n.useRef)([])).current=Array(w).fill(null).map((e,t)=>j.current[t]??null),j),oe=ew&&0===H.length&&!U.isStreaming&&!_,ot=e?.cwd??t??void 0,oo=ei?G[`${ei.provider}:${ei.modelId}`]??null:null,or=ei?Y[`${ei.provider}:${ei.modelId}`]??null:null,on=(0,r.jsx)(st,{ref:c,onSend:eq,onBash:eV,tasksBoardEnabled:b,onAbort:eK,onSteer:_?eZ:void 0,onFollowUp:_?eQ:void 0,onPromptWithStreamingBehavior:_?e0:void 0,isStreaming:_,model:ei,modelNames:K,modelList:J,modelScopeWarnings:X,onModelChange:eY,compactResult:es,toolPreset:Z,onToolPresetChange:e||ew?to:void 0,planMode:ti,onPlanModeChange:e=>{ta(e),e&&"plan"!==tl?tg("plan"):e||"plan"!==tl||tg("normal")},collaborationMode:tl,tokenMode:tp,toolApprovalMode:tu,onCollaborationModeChange:e=>{tg(e),"plan"!==e||ti?"plan"!==e&&ti&&ta(!1):ta(!0)},onTokenModeChange:th,onToolApprovalModeChange:tf,goalState:tk,onGoalStart:tv,onGoalPause:ty,onGoalResume:tb,onGoalStop:tw,thinkingLevel:Q,onThinkingLevelChange:e||ew?tr:void 0,availableThinkingLevels:oo,thinkingLevelMap:or,retryInfo:ee,queuedMessages:ep,inputHistory:t7,onRecallQueue:e2,onMoveQueue:e3,onRecallOne:e8,onRequeueAt:e7,onRemoveQueueItem:e9,slashCommands:ed,slashCommandsLoading:ec,onLoadSlashCommands:ts,onBuiltinCommand:te,onAudioUnlock:R,draftKey:e?.id??(t?`new:${t}`:void 0),cwd:e?.cwd??t}),os=ek.filter(e=>"belowEditor"!==e.placement),oi=ek.filter(e=>"belowEditor"===e.placement),oa=er?I("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}(eb,I);return A?(0,r.jsx)("div",{className:"flex h-full items-center justify-center text-text-muted",children:I("desktop.loadingSession")}):O?(0,r.jsx)("div",{className:"flex h-full items-center justify-center text-red-400",children:O}):(0,r.jsxs)("div",{className:"relative flex h-full min-w-0 flex-col overflow-hidden",onDragEnter:t4,onDragOver:t6,onDragLeave:t5,onDrop:t3,children:[t2&&(0,r.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,r.jsx)("div",{className:"pointer-events-none absolute inset-0 flex items-center justify-center",children:[0,.8,1.6].map(e=>(0,r.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,r.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,r.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,r.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,r.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,r.jsxs)("g",{stroke:"rgba(37,99,235,0.45)",strokeWidth:"1.4",strokeLinecap:"round",children:[(0,r.jsx)("line",{x1:"96",y1:"46",x2:"96",y2:"43"}),(0,r.jsx)("line",{x1:"96",y1:"70",x2:"96",y2:"73"}),(0,r.jsx)("line",{x1:"84",y1:"58",x2:"81",y2:"58"}),(0,r.jsx)("line",{x1:"108",y1:"58",x2:"111",y2:"58"}),(0,r.jsx)("line",{x1:"87.5",y1:"49.5",x2:"85.4",y2:"47.4"}),(0,r.jsx)("line",{x1:"104.5",y1:"66.5",x2:"106.6",y2:"68.6"}),(0,r.jsx)("line",{x1:"104.5",y1:"49.5",x2:"106.6",y2:"47.4"}),(0,r.jsx)("line",{x1:"87.5",y1:"66.5",x2:"85.4",y2:"68.6"})]})]})]}),ef&&(0,r.jsx)(sY,{request:ef,onRespond:ev}),ex&&(0,r.jsx)(sX,{request:ex,onInput:ey}),!ew&&eu.length>0&&!tS&&(0,r.jsx)(sn,{items:eu,sessionId:e?.id,onResolve:e4,onExport:e6,onStageImport:e5,onDismiss:()=>tC(!0),mode:eg?"import":"recovery"}),tx.length>0&&(0,r.jsx)(o7,{request:tx[0]??null,queuedCount:Math.max(0,tx.length-1),busy:!1,onResolve:(e,t)=>{let o=tx[0];o&&tm(o.id,e,t)}}),oe?(0,r.jsx)("div",{className:"flex flex-1 flex-col items-center justify-center overflow-y-auto",children:(0,r.jsxs)("div",{className:"w-full max-w-[820px]",children:[(0,r.jsx)("div",{style:{display:"flex",justifyContent:"center",marginBottom:28},children:(0,r.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,r.jsx)("title",{children:"Pi"}),(0,r.jsx)("path",{clipRule:"evenodd",d:"M1 1h16.5v11H12v5.5H6.5V23H1V1zm5.5 5.5V12H12V6.5H6.5z"}),(0,r.jsx)("path",{d:"M17.5 12H23v11h-5.5V12z"})]})}),(0,r.jsx)("div",{style:{padding:"0 34px 6px 7px",paddingRight:z?16:34},children:(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12},children:[(0,r.jsx)("div",{ref:k,style:{display:"flex",alignItems:"center",minWidth:0,flex:1,minHeight:48}}),(0,r.jsxs)("div",{style:{display:z?"none":"flex",flexDirection:"column",alignItems:"flex-end",gap:2,flexShrink:0},children:[(0,r.jsxs)("span",{style:{fontSize:11,color:"var(--text-muted)",fontFamily:"var(--font-mono)"},children:["web ",(0,r.jsxs)("span",{style:{color:"var(--text)"},children:["v","0.9.32"]})]}),(0,r.jsxs)("span",{style:{fontSize:11,color:"var(--text-muted)",fontFamily:"var(--font-mono)"},children:["pi ",(0,r.jsxs)("span",{style:{color:"var(--text)"},children:["v","0.84.0"]})]})]})]})}),(0,r.jsx)("div",{style:{padding:"0 16px",paddingRight:z?16:34},children:(0,r.jsx)(sG,{notices:eh,align:"right"})}),"goal"===tl&&(0,r.jsx)(o3,{goalState:tk,onPause:ty,onResume:tb,onStop:tw,onEdit:tj}),on,(0,r.jsx)("div",{style:{padding:"0 16px 6px",paddingRight:z?16:34,marginTop:-15},children:(0,r.jsx)(sv,{onViewFullHistory:v,cwd:ot,systemPrompt:y,sessionStats:ea,contextUsage:et,hasSession:!!e,showChat:!0,showSoundLabel:!0,soundEnabled:S,onSoundToggle:C,onCompact:e?eX:void 0,onAbortCompaction:e1,isCompacting:er,compactError:en,isDeepSeekOfficial:tI,deepseekBalance:tT,lastTurnUsage:tE})})]})}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("div",{className:"relative flex flex-1 overflow-hidden z-0",children:[(0,r.jsx)("div",{style:{position:"absolute",top:12,left:0,right:18*!z,zIndex:40,padding:"0 16px",pointerEvents:"none"},children:(0,r.jsx)("div",{style:{maxWidth:820,margin:"0 auto"},children:(0,r.jsx)(sG,{notices:eh,floating:!0,align:"right"})})}),(0,r.jsxs)("div",{className:"relative flex-1 min-h-0 min-w-0",children:[(0,r.jsx)("div",{ref:eO,className:"h-full min-w-0 overflow-x-hidden overflow-y-auto pt-4 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden",children:(0,r.jsx)("div",{style:{minWidth:0,padding:"0 16px"},children:(0,r.jsxs)("div",{style:{width:"100%",minWidth:0,maxWidth:820,margin:"0 auto"},children:[(0,r.jsx)(sK,{statuses:em}),(0,r.jsx)(sJ,{widgets:os}),(()=>{let t=new Map;for(let e of H)"toolResult"===e.role&&t.set(e.toolCallId,e);let o=-1;for(let e=H.length-1;e>=0;e--)if("user"===H[e].role){o=e;break}let n=new Map,s=0;H.forEach((e,t)=>{("user"===e.role||"assistant"===e.role)&&n.set(t,s++)});let i=(s,i={})=>{let a=i.messageOverride??H[s],l="user"===a.role&&s>0&&"assistant"===H[s-1].role?B[s-1]:void 0,d="user"===a.role||"assistant"===a.role,c=n.get(s),p=i.keyPrefix??"message",u=!1;if("assistant"===a.role){u=!0;for(let e=s+1;e<H.length;e++){let t=H[e].role;if("user"===t)break;if("assistant"===t){u=!1;break}}u&&U.isStreaming&&s===H.length-1&&(u=!1)}void 0!==i.showTimestamp&&(u=i.showTimestamp);let g=(0,r.jsx)(oF,{message:a,toolResults:t,modelNames:K,cwd:ot,onOpenFile:m,entryId:B[s],onFork:_||ew||0===s&&"user"===a.role?void 0:eJ,forking:eo===B[s],onNavigate:_?void 0:eG,prevAssistantEntryId:_?void 0:l,onEditContent:W,onQuoteReply:N,onCreateTask:L,showTimestamp:u,prevTimestamp:s>0?H[s-1].timestamp:void 0,sessionId:e?.id??eL.current??void 0,writtenFiles:i.writtenFiles},`${p}-view-${s}`);return d&&!1!==i.attachRef&&void 0!==c?(0,r.jsx)("div",{ref:e=>{t9.current[c]=e,s===o&&(eH.current=e,e&&eB.current&&(eB.current=!1,eU.current=!0,e_()))},children:g},`${p}-${s}`):g},a=[],l=[],d=(e,t)=>{a.push(e),l.push(t)};for(let s=0;s<H.length;){let a=H[s],l="custom"===a.role&&"compaction"===a.customType;if("user"!==a.role&&!l){d(i(s),n.get(s)),s+=1;continue}let c=s,p=c+1;for(;p<H.length&&"user"!==H[p].role;)p+=1;let u=function(e,t,o){for(let n=o-1;n>t;n--){var r;if("assistant"===(r=e[n]).role&&tt(r).answerBlocks.some(e=>"image"===e.type||"text"===e.type&&e.text.trim().length>0))return n}for(let r=o-1;r>t;r--)if(e[r]?.role==="assistant")return r;return -1}(H,c,p);if((_||U.isStreaming)&&p===H.length&&(c===o||l)){d(i(c),n.get(c));let o=U.streamingMessage?.role==="assistant",a=[],l=!o&&u>=0?u:p;for(let e=c+1;e<l;e++)s_(H[e])&&a.push(e);let g=tc(H,B,a,t),h=null;if(!o&&u>=0){let e=H[u],o=tt(e,{isStreaming:!0}),r=td(e,{messageIndex:u,entryId:B[u],toolResults:t,isStreaming:!0});g=g.concat(r.processBlocks),o.answerBlocks.length>0&&(h=sq(e,o.answerBlocks,{omitUsage:!0}))}if(o){let e=U.streamingMessage,o=tt(e,{isStreaming:!0}),r=td(e,{messageIndex:H.length,toolResults:t,isStreaming:!0});g=g.concat(r.processBlocks),o.answerBlocks.length>0&&(h=sq(e,o.answerBlocks,{omitUsage:!0}))}if(g.length>0){let t=a.map(e=>n.get(e)).find(e=>"number"==typeof e);d((0,r.jsx)("div",{ref:void 0===t?void 0:e=>{t9.current[t]=e},children:(0,r.jsx)(rV,{blocks:g,isStreaming:_||U.isStreaming,cwd:ot,onOpenFile:m,sessionId:e?.id??eL.current??void 0,tokenRate:el})},`live-process-group-${c}`),t)}h&&d((0,r.jsx)(oF,{message:h,isStreaming:!0,modelNames:K,cwd:ot,onOpenFile:m,onQuoteReply:N},`live-answer-${c}`),u>=0?n.get(u):void 0),s=p;continue}if(-1===u){for(let e=c;e<p;e++)d(i(e),n.get(e));s=p;continue}d(i(c),n.get(c));let g=[];for(let e=c+1;e<u;e++)g.push(e);let h=g.filter(e=>s_(H[e])),f=H[u],x=tt(f),k=x.processBlocks.length>0?sq(f,x.processBlocks,{omitUsage:!0}):null,v=x.answerBlocks.length>0?sq(f,x.answerBlocks):null,y=tc(H,B,h,t);if(k&&(y=y.concat(td(f,{messageIndex:u,entryId:B[u],toolResults:t}).processBlocks)),y.length>0){let t=h.map(e=>n.get(e)).find(e=>"number"==typeof e)??(v?void 0:n.get(u));d((0,r.jsx)("div",{ref:void 0===t?void 0:e=>{t9.current[t]=e},children:(0,r.jsx)(rV,{blocks:y,isStreaming:!1,defaultExpanded:!v,onAutoExpanded:void 0,cwd:ot,onOpenFile:m,sessionId:e?.id??eL.current??void 0})},`process-group-${c}-${u}`),t)}if(v){let e=[];for(let t=c+1;t<=u;t++){let o=H[t];if(o?.role==="assistant")for(let t of o.content??[])e.push(t)}d(i(u,{messageOverride:v,writtenFiles:function(e,t,o){let r=new Set,n=[];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 r=/^[a-zA-Z]:[\\/]/.test(e)||e.startsWith("\\\\")||void 0!==t&&(/^[a-zA-Z]:[\\/]/.test(t)||t.startsWith("\\\\")),n=e=>r?e.replace(/\\/g,"/"):e,s=n(e),i=t?n(t).replace(/\/+$/,""):void 0,a=/^[a-zA-Z]:\//.test(s),l=s.startsWith("//");if(a||l)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 tn(o)}(i,o);a&&(r.has(a)||(r.add(a),n.push({filePath:a})))}return n}(e,t,ot)}),n.get(u))}for(let e=u+1;e<p;e++)d(i(e),n.get(e));s=p}let c=[];return l.forEach((e,t)=>{void 0!==e&&(c[e]=t)}),tY.current=c,(0,r.jsx)(sb,{scrollElementRef:eO,items:a,virtualizerRef:tG})})(),oa&&(er||_&&!U.streamingMessage)&&(0,r.jsx)("div",{className:"py-2 text-[13px] text-text-muted",children:(0,r.jsxs)("span",{className:"animate-[pulse_1.5s_infinite]",children:[oa,eb?.kind==="waiting_model"&&(0,r.jsx)("span",{style:{display:"inline-block",width:12,height:12,marginLeft:6,verticalAlign:"-2px",border:"1.5px solid var(--text-muted)",borderTopColor:"transparent",borderRadius:"50%",animation:"spin 0.6s linear infinite"}})]})}),V&&(0,r.jsx)(oF,{message:{role:"bashExecution",command:V.command,output:"",excludeFromContext:V.excludeFromContext},sessionId:e?.id??eL.current??void 0}),q&&!V&&(0,r.jsx)("div",{className:"py-2 text-[13px] text-text-muted",children:(0,r.jsx)("span",{className:"animate-[pulse_1.5s_infinite]",children:I("desktop.runningShellCommand")})}),(0,r.jsx)("div",{style:{height:96}}),(0,r.jsx)("div",{ref:eA}),(0,r.jsx)(o0,{open:tP,planText:tF,busy:_,onExecute:tN,onFeedback:tA,onExit:tO,onClose:()=>tD(!1)})]})})}),tH&&(0,r.jsx)("div",{"aria-hidden":"true",className:"pointer-events-none absolute inset-x-0 top-0 z-10 h-8 bg-gradient-to-b from-[var(--bg)] to-transparent"}),tU&&(0,r.jsx)("div",{"aria-hidden":"true",className:"pointer-events-none absolute inset-x-0 bottom-0 z-10 h-8 bg-gradient-to-t from-[var(--bg)] to-transparent"}),tq&&(0,r.jsxs)("button",{type:"button",onClick:()=>tJ(),title:I("desktop.scrollToBottom"),"aria-label":I("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,r.jsx)(ov.Z,{size:12,weight:"bold","aria-hidden":"true"}),I("desktop.scrollToBottom")]})]}),z?null:(0,r.jsx)(sS,{messages:H,streamingMessage:U.streamingMessage,scrollContainer:eO,messageRefs:t9,virtualizer:tX})]}),(0,r.jsxs)("div",{className:"relative z-10",children:[(0,r.jsx)("div",{style:{padding:"0 16px",paddingRight:z?16:34},children:(0,r.jsx)("div",{style:{maxWidth:820,margin:"0 auto"},children:(0,r.jsx)(sJ,{widgets:oi})})}),on,(0,r.jsx)("div",{className:`session-info-bar-wrap${z?" is-mobile":""}`,children:(0,r.jsx)("div",{className:"session-info-bar-inner",children:(0,r.jsx)(sv,{onViewFullHistory:v,cwd:ot,systemPrompt:y,sessionStats:ea,contextUsage:et,hasSession:!!e,showChat:!0,soundEnabled:S,onSoundToggle:C,onCompact:e?eX:void 0,onAbortCompaction:e1,isCompacting:er,compactError:en,branchTree:ej,branchActiveLeafId:eS,onBranchLeafChange:eN,isDeepSeekOfficial:tI,deepseekBalance:tT,lastTurnUsage:tE})})})]})]})]})}function sK({statuses:e}){return 0===e.length?null:(0,r.jsx)("div",{style:{display:"flex",flexWrap:"wrap",gap:6,marginBottom:10},children:e.map(e=>(0,r.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,r.jsx)("span",{style:{color:"var(--accent)",fontFamily:"var(--font-mono)",fontSize:11},children:e.key}),(0,r.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.text})]},e.key))})}function sJ({widgets:e}){return 0===e.length?null:(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:8,marginBottom:10},children:e.map(e=>(0,r.jsxs)("div",{style:{border:"1px solid var(--border)",borderRadius:7,background:"var(--bg-panel)",overflow:"hidden"},children:[(0,r.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,r.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 sG({notices:e,floating:t=!1,align:o="left"}){return 0===e.length?null:(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",alignItems:"right"===o?"flex-end":"stretch",marginBottom:10*!t},children:e.map((o,n)=>{let s="error"===o.type?"#ef4444":"warning"===o.type?"#d97706":"success"===o.type?"#10b981":"var(--accent)";return(0,r.jsxs)("div",{className:"notice-shelf-item",style:{display:"flex",alignItems:"center",gap:10,minHeight:44,maxHeight:180,marginBottom:6*(n!==e.length-1),overflowY:"auto",overflowX:"hidden",borderRadius:14,border:"1px solid color-mix(in srgb, var(--border) 70%, transparent)",background:"var(--bg)",color:"var(--text-muted)",width:"fit-content",maxWidth:"min(100%, 620px)",boxShadow:t?"0 1px 2px rgba(15,23,42,0.05), 0 10px 28px -14px rgba(15,23,42,0.24)":"0 1px 2px rgba(15,23,42,0.04), 0 8px 24px -12px rgba(15,23,42,0.10)",fontSize:13,lineHeight:1.45,transformOrigin:"top center",animation:o.exiting?"notice-shelf-out 0.18s ease-in forwards":"notice-shelf-in 0.18s ease-out both",padding:"0 12px"},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:s,flexShrink:0}}),(0,r.jsx)("span",{style:{padding:"10px 0",minWidth:0,maxWidth:"100%",overflowWrap:"anywhere",whiteSpace:"pre-wrap"},children:o.message})]},o.id)})})}function sY({request:e,onRespond:t}){let{t:o}=(0,E.s)(),[s,i]=(0,n.useState)("editor"===e.method?e.prefill??"":"");(0,n.useEffect)(()=>{i("editor"===e.method?e.prefill??"":"")},[e]);let a=()=>{"confirm"===e.method?t(e,{confirmed:!0}):t(e,{value:s})};return(0,r.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,r.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,r.jsxs)("div",{style:{padding:"12px 14px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("div",{style:{color:"var(--text)",fontSize:14,fontWeight:650},children:e.title}),(0,r.jsx)("div",{style:{marginTop:3,color:"var(--text-dim)",fontSize:11,fontFamily:"var(--font-mono)"},children:o("desktop.extensionRequest")})]}),(0,r.jsxs)("div",{style:{padding:14},children:["confirm"===e.method&&(0,r.jsx)("div",{style:{color:"var(--text-muted)",fontSize:13,lineHeight:1.6,whiteSpace:"pre-wrap"},children:e.message}),"select"===e.method&&(0,r.jsx)("div",{style:{display:"grid",gap:8},children:e.options.map(o=>(0,r.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,r.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,r.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,r.jsxs)("div",{style:{display:"flex",justifyContent:"flex-end",gap:8,padding:"10px 14px",borderTop:"1px solid var(--border)",background:"var(--bg-panel)"},children:[(0,r.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,r.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,r.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 sX({request:e,onInput:t}){let{t:o}=(0,E.s)(),s=(0,n.useRef)(null),i=function(e){let t=/^[┌├└╭╰][─┬┴┼]+[┐┤┘╮╯]$/,o=[];for(let r of e){let e=e5(r).trimEnd();if(t.test(e))continue;let n=r,s=e7(n);("│"===s||"┃"===s)&&" "===e7(n=e8(n,0))&&(n=e8(n,0));let i=function(e){let t=e3(e);for(let e=t.length-1;e>=0;e--)if(""!==t[e].char.trim())return e;return -1}(n),a=i>=0?e3(n)[i]?.char:void 0;("│"===a||"┃"===a)&&(n=e8(n,i)),o.push(function(e){let t=e;for(;;){let e=e3(t),o=e[e.length-1];if(!o||""!==o.char.trim())return t;t=t.slice(0,o.start)+t.slice(o.end)}}(n))}for(;o.length>0&&""===e5(o[0]).trim();)o.shift();for(;o.length>0&&""===e5(o[o.length-1]).trim();)o.pop();return o.length?o:e}(e.lines);return(0,n.useEffect)(()=>{s.current?.focus()},[e.id]),(0,r.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,r.jsxs)("div",{ref:s,tabIndex:0,role:"dialog","aria-modal":"true",onKeyDown:o=>{let r=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);r&&(o.preventDefault(),o.stopPropagation(),t(e,r))},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,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,padding:"10px 12px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("div",{style:{color:"var(--text)",fontSize:13,fontWeight:650},children:o("desktop.extensionPanel")}),(0,r.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,r.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,r.jsxs)(n.Fragment,{children:[(s=`line-${t}`,(function(e){let t,o=[],r={},n=0;for(e2.lastIndex=0;null!==(t=e2.exec(e));)t.index>n&&o.push({text:e.slice(n,t.index),style:r}),r=function(e,t){let o={...e};for(let e=0;e<t.length;e++){let r=t[e];if(0===r)for(let e of Object.keys(o))delete o[e];else if(1===r)o.fontWeight=700;else if(2===r)o.opacity=.65;else if(3===r)o.fontStyle="italic";else if(4===r)o.textDecoration="underline";else if(22===r)delete o.fontWeight,delete o.opacity;else if(23===r)delete o.fontStyle;else if(24===r)delete o.textDecoration;else if(39===r)delete o.color;else if(49===r)delete o.backgroundColor;else if(r>=30&&r<=37)o.color=e4[r-30];else if(r>=90&&r<=97)o.color=e6[r-90];else if(r>=40&&r<=47)o.backgroundColor=e4[r-40];else if(r>=100&&r<=107)o.backgroundColor=e6[r-100];else if((38===r||48===r)&&2===t[e+1]){let[n,s,i]=[t[e+2],t[e+3],t[e+4]];[n,s,i].every(e=>"number"==typeof e&&Number.isFinite(e))&&(38===r?o.color=`rgb(${n}, ${s}, ${i})`:o.backgroundColor=`rgb(${n}, ${s}, ${i})`),e+=4}else if((38===r||48===r)&&5===t[e+1]){let n=function(e){if(e>=0&&e<8)return e4[e];if(e>=8&&e<16)return e6[e-8];if(e>=16&&e<=231){let t=e-16,o=Math.floor(t/36),r=Math.floor(t%36/6),n=e=>0===e?0:55+40*e;return`rgb(${n(o)}, ${n(r)}, ${n(t%6)})`}if(e>=232&&e<=255){let t=8+(e-232)*10;return`rgb(${t}, ${t}, ${t})`}}(t[e+2]);n&&(38===r?o.color=n:o.backgroundColor=n),e+=2}}return o}(r,t[1]?t[1].split(";").map(e=>Number(e||"0")):[0]),n=t.index+t[0].length;return n<e.length&&o.push({text:e.slice(n),style:r}),o})(e).map((e,t)=>Object.keys(e.style).length>0?(0,r.jsx)("span",{style:e.style,children:e.text},`${s}-${t}`):e.text)),t<o.length-1?"\n":null]},t)})})]})})}let sZ={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"},sQ={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 s0(e){return(e.replace(/\\/g,"/").split("/").pop()??"").toLowerCase().split(".").pop()??""}function s1(e){let t=e.nodeType===Node.ELEMENT_NODE?e:e.parentElement;return t?.closest(".file-source-line[data-line-number]")??null}function s2(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 r=Number(s1(o.startContainer)?.dataset.lineNumber),n=Number(s1(o.endContainer)?.dataset.lineNumber);return Number.isInteger(r)&&Number.isInteger(n)?r<=n?{startLine:r,endLine:n}:{startLine:n,endLine:r}:null}function s4(e,t,o,r={}){let n=eo(e),s=new URLSearchParams({type:t});for(let[e,t]of(o&&s.set("sessionId",o),Object.entries(r)))void 0!==t&&s.set(e,String(t));return`/api/files/${n}?${s.toString()}`}function s6({filePath:e,sourceSessionId:t}){let{t:o}=(0,E.s)();return(0,r.jsx)("a",{href:s4(e,"download",t),download:er(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,r.jsx)(z.z,{size:11,"aria-hidden":"true"})})}let s5={delete:"3px solid var(--git-status-deleted)",add:"3px solid var(--git-status-added)",edit:"3px solid var(--git-status-modified)"},s3="var(--git-status-deleted-bg)",s8="var(--git-status-added-bg)",s7="var(--git-status-added)";function s9(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KB`:`${(e/1048576).toFixed(1)} MB`}function ie({oldContent:e,newContent:t}){let{t:o}=(0,E.s)(),n=function(e,t){let o=e.length,r=t.length,n=o+r,s=Array(2*n+1).fill(0),i=[];for(let a=0;a<=n;a++){i.push([...s]);for(let l=-a;l<=a;l+=2){let d,c=(d=l===-a||l!==a&&s[l-1+n]<s[l+1+n]?s[l+1+n]:s[l-1+n]+1)-l;for(;d<o&&c<r&&e[d]===t[c];)d++,c++;if(s[l+n]=d,d>=o&&c>=r){let s=[],l=o,d=r;for(let o=a;o>0;o--){let r,a=i[o-1],c=l-d;r=c===-o||c!==o&&a[c-1+n]<a[c+1+n]?c+1:c-1;let p=a[r+n],u=p-r;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(!n.some(e=>"unchanged"!==e.type))return(0,r.jsx)("div",{style:{padding:"12px 16px",fontSize:12,color:"var(--text-dim)",fontFamily:"var(--font-mono)"},children:o("desktop.noChanges")});let s=new Set(n.flatMap((e,t)=>"unchanged"!==e.type?[t]:[])),i=new Set;for(let e of s)for(let t=Math.max(0,e-3);t<=Math.min(n.length-1,e+3);t++)i.add(t);let a=[],l=0;for(;l<n.length;)if(i.has(l)){let e=[];for(;l<n.length&&i.has(l);)e.push(n[l]),l++;a.push({hidden:!1,lines:e})}else{let e=0;for(;l<n.length&&!i.has(l);)e++,l++;a.push({hidden:!0,count:e})}let d=[],c=1;for(let e of n)"removed"===e.type?d.push(0):d.push(c++);let p=0;return(0,r.jsx)("div",{style:{fontFamily:"var(--font-mono)",fontSize:13,lineHeight:1.6,minWidth:"max-content"},children:a.map((e,t)=>{if(e.hidden){let n=(0,r.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,n}let n=[],s=[],i=[],a=()=>{if(s.length||i.length){let e=s.length&&i.length?"edit":s.length?"delete":"add";for(let t of s)n.push({key:t.key,kind:"removed",text:t.text,lineNo:null,block:e});for(let t of i)n.push({key:t.key,kind:"added",text:t.text,lineNo:t.lineNo,block:e});s=[],i=[]}};e.lines.forEach((e,o)=>{"unchanged"===e.type?(a(),n.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=n.map(e=>{let t="removed"===e.kind?s3:"added"===e.kind?s8:"transparent",o=e.block?s5[e.block]:"3px solid transparent",n="added"===e.kind?s7:"var(--text-dim)";return(0,r.jsxs)("div",{style:{display:"flex",background:t,borderLeft:o},children:[(0,r.jsx)("span",{style:{minWidth:44,padding:"0 8px 0 16px",textAlign:"right",color:n,userSelect:"none",fontSize:11,lineHeight:1.6,flexShrink:0},children:e.lineNo??""}),(0,r.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,r.jsx)("div",{children:l},t)})})}function it({patch:e}){let t=of(e);if(!t)return null;let o=[],n=[],s=[],i=()=>{if(n.length||s.length){let e=n.length&&s.length?"edit":n.length?"delete":"add";for(let t of n)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});n=[],s=[]}};return t.forEach((e,t)=>{e.rows.forEach((e,r)=>{if("hunk"===e.type){i(),o.push({key:`${t}:${r}: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}:${r}:c`,kind:"context",text:a.text,lineNo:l.lineNo,block:null});return}"removed"===a.type&&n.push({key:`${t}:${r}:l`,text:a.text}),"added"===l.type&&s.push({key:`${t}:${r}:r`,text:l.text,lineNo:l.lineNo})})}),i(),(0,r.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,r.jsxs)("div",{children:[(0,r.jsx)("div",{style:{height:"1.55em"}}),(0,r.jsx)("div",{style:{padding:"3px 12px",color:"var(--accent-blue)",background:"var(--bg-secondary)"},children:e.text}),(0,r.jsx)("div",{style:{height:"1.55em"}})]},e.key);let t="removed"===e.kind?s3:"added"===e.kind?s8:"transparent",o=e.block?s5[e.block]:"3px solid transparent",n="added"===e.kind?s7:"var(--text-dim)";return(0,r.jsxs)("div",{style:{display:"flex",background:t,borderLeft:o},children:[(0,r.jsx)("span",{style:{width:44,flexShrink:0,padding:"0 8px 0 16px",textAlign:"right",color:n,userSelect:"none",fontSize:11},children:e.lineNo??""}),(0,r.jsx)("span",{style:{flex:1,minWidth:0,padding:"0 8px 0 0",whiteSpace:"pre",color:"var(--text)"},children:e.text||"\xa0"})]},e.key)})})}function io({filePath:e,cwd:t,sourceSessionId:o}){let{t:s}=(0,E.s)(),[i,a]=(0,n.useState)(0),[l,d]=(0,n.useState)(null),[c,p]=(0,n.useState)(null),[u,g]=(0,n.useState)(null),h=(0,n.useRef)(null),f=er(e).toLowerCase().split(".").pop()??"";(0,n.useEffect)(()=>{a(0),d(null),p(null),g(null),h.current&&(h.current.close(),h.current=null);let t=new EventSource(s4(e,"watch",o));return h.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(),h.current=null}},[e,o]);let x=s4(e,"read",o,i?{v:i}:void 0),m=null!=l?s9(l):null;return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,r.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,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},title:e,children:en(e,t)}),(0,r.jsx)("span",{style:{marginLeft:"auto"},children:f||s("desktop.image")}),c&&(0,r.jsxs)("span",{children:[c.w," \xd7 ",c.h]}),m&&(0,r.jsx)("span",{children:m}),(0,r.jsx)(s6,{filePath:e,sourceSessionId:o})]}),(0,r.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,r.jsx)("div",{style:{color:"#f87171",fontSize:13},children:u}):(0,r.jsx)("img",{src:x,alt:e,onLoad:e=>{let t=e.currentTarget;p({w:t.naturalWidth,h:t.naturalHeight})},onError:()=>g(s("desktop.failedToLoadImage")),style:{maxWidth:"100%",maxHeight:"100%",objectFit:"contain",boxShadow:"0 2px 8px rgba(0,0,0,0.15)"}})})]})}function ir({filePath:e,cwd:t,sourceSessionId:o}){let{t:s}=(0,E.s)(),[i,a]=(0,n.useState)(0),[l,d]=(0,n.useState)(null),[c,p]=(0,n.useState)(null),[u,g]=(0,n.useState)(null),h=(0,n.useRef)(null),f=er(e).toLowerCase().split(".").pop()??"";(0,n.useEffect)(()=>{a(0),d(null),p(null),g(null),h.current&&(h.current.close(),h.current=null);let t=new EventSource(s4(e,"watch",o));return h.current=t,t.addEventListener("change",e=>{try{let t=JSON.parse(e.data);"number"==typeof t.size&&d(t.size)}catch{}p(null),g(null),a(e=>e+1)}),()=>{t.close(),h.current=null}},[e,o]);let x=s4(e,"read",o,i?{v:i}:void 0);return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,r.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,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},title:e,children:en(e,t)}),(0,r.jsx)("span",{style:{marginLeft:"auto"},children:f||s("desktop.audio")}),null!=c&&(0,r.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,r.jsx)("span",{children:s9(l)}),(0,r.jsx)(s6,{filePath:e,sourceSessionId:o})]}),(0,r.jsx)("div",{style:{flex:1,display:"flex",alignItems:"center",justifyContent:"center",padding:24,background:"var(--bg-panel)"},children:(0,r.jsxs)("div",{style:{width:"min(680px, 100%)"},children:[u&&(0,r.jsx)("div",{style:{color:"#f87171",fontSize:13,marginBottom:12,textAlign:"center"},children:u}),(0,r.jsx)("audio",{controls:!0,preload:"metadata",src:x,onLoadedMetadata:e=>p(e.currentTarget.duration),onError:()=>g(s("desktop.failedToLoadAudio")),style:{width:"100%"}},x)]})})]})}function is({filePath:e,cwd:t,sourceSessionId:o}){let{t:s}=(0,E.s)(),[i,a]=(0,n.useState)(0),[l,d]=(0,n.useState)(null),[c,p]=(0,n.useState)(null),u=(0,n.useRef)(null),g=s0(e),h="pdf"===g,f=h?s4(e,"read",o,i?{v:i}:void 0):s4(e,"preview",o,i?{v:i}:void 0);return(0,n.useEffect)(()=>{a(0),d(null),p(null),u.current&&(u.current.close(),u.current=null),fetch(s4(e,"meta",o)).then(e=>e.json()).then(e=>{e.error&&p(e.error),"number"==typeof e.size&&(d(e.size),!h&&e.size>0xa00000&&p(s("desktop.docxTooLargeForPreview")))}).catch(e=>p(String(e)));let t=new EventSource(s4(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),!h&&t.size>0xa00000))return void p(s("desktop.docxTooLargeForPreview"))}catch{}p(null),a(e=>e+1)}),()=>{t.close(),u.current=null}},[e,h,o,s]),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,r.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,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:e,children:en(e,t)}),(0,r.jsx)("span",{style:{marginLeft:"auto"},children:"docx"===g?s("desktop.docxPreview"):"pdf"}),null!=l&&(0,r.jsx)("span",{children:s9(l)}),(0,r.jsx)(s6,{filePath:e,sourceSessionId:o})]}),(0,r.jsx)("div",{style:{flex:1,minHeight:0,background:"var(--bg-panel)"},children:c?(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",padding:24,color:"#f87171",fontSize:13,textAlign:"center"},children:c}):(0,r.jsx)("iframe",{src:f,sandbox:h?void 0:"allow-same-origin",title:s("desktop.previewFile",{file:er(e)}),style:{width:"100%",height:"100%",border:"none",background:h?"var(--bg)":"#eef1f5"}},f)})]})}function ii({filePath:e,cwd:t,sourceSessionId:o,onOpenFile:n,onAtMention:s,onMentionLines:i,initialDisplayMode:a}){let l;return null!==(sZ[s0(e)]??null)?(0,r.jsx)(io,{filePath:e,cwd:t,sourceSessionId:o}):null!==(sQ[s0(e)]??null)?(0,r.jsx)(ir,{filePath:e,cwd:t,sourceSessionId:o}):null!==("pdf"===(l=s0(e))||"docx"===l?l:null)?(0,r.jsx)(is,{filePath:e,cwd:t,sourceSessionId:o}):(0,r.jsx)(ia,{filePath:e,cwd:t,sourceSessionId:o,onOpenFile:n,onAtMention:s,onMentionLines:i,initialDisplayMode:a})}function ia({filePath:e,cwd:t,sourceSessionId:o,onOpenFile:s,onAtMention:i,onMentionLines:a,initialDisplayMode:l}){let d,c,{t:p}=(0,E.s)(),[u,g]=(0,n.useState)(null),[h,f]=(0,n.useState)(null),[x,m]=(0,n.useState)(null),[k,v]=(0,n.useState)(!0),[y,b]=(0,n.useState)(null),[w,j]=(0,n.useState)(!1),[S,C]=(0,n.useState)("source"),[T,R]=(0,n.useState)(!1),[z,I]=(0,n.useState)(0),[M,P]=(0,n.useState)(null),D=(0,n.useRef)(null),F=(0,n.useRef)(null),W=(0,n.useCallback)(async e=>{if(!t)return void m(null);try{let o=new URLSearchParams({cwd:t,path:e}),r=await fetch(`/api/git/diff?${o.toString()}`),n=await r.json();m(r.ok&&n.supported&&"string"==typeof n.patch?n:null)}catch{m(null)}},[t]),$=(0,n.useCallback)((e,t=!1)=>fetch(s4(e,"read",o)).then(e=>e.json()).then(e=>e.error?(b(e.error),null):(t?(g(t=>(t&&f(t.content),e)),I(e=>e+1)):g(e),e)).catch(e=>(b(String(e)),null)),[o]);(0,n.useEffect)(()=>{v(!0),b(null),g(null),f(null),m(null),j(!1),C("source"),R(!1),I(0),D.current&&(D.current.close(),D.current=null),$(e).then(e=>{(e?.language==="markdown"||e?.language==="html")&&"diff"!==l&&j(!0)}).finally(()=>v(!1)),W(e);let t=new EventSource(s4(e,"watch",o));return D.current=t,t.addEventListener("change",()=>{$(e,!0),W(e)}),()=>{t.close(),D.current=null}},[e,$,W,l,o]);let N=(0,n.useMemo)(()=>tG(u?.content??""),[u?.content]),L=x?.supported===!0&&"string"==typeof x.patch;(0,n.useEffect)(()=>{"diff"===l&&L&&C("diff")},[L,l]);let A=L&&x?.status==="deleted",O=(0,n.useCallback)(o=>{a&&o&&a(en(e,t),o.startLine,o.endLine)},[t,e,a]);if((0,n.useEffect)(()=>{let e=()=>{let e=F.current,t="source"===S&&!w;P(a&&t&&e?s2(e,window.getSelection()):null)};if(e(),a&&"source"===S&&!w)return document.addEventListener("selectionchange",e),()=>document.removeEventListener("selectionchange",e)},[u?.content,a,w,S]),(0,n.useEffect)(()=>{if(!a||"source"!==S||w)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=F.current,r=o?s2(o,window.getSelection()):null;r&&(e.preventDefault(),O(r))};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[O,a,w,S]),k)return(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-muted)",fontSize:13},children:p("desktop.loadingFile")});if(A&&!u)return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,r.jsx)("div",{style:{padding:"5px 16px",borderBottom:"1px solid var(--border)",color:"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:11},title:e,children:en(e,t)}),(0,r.jsx)("div",{style:{flex:1,overflow:"auto",background:"var(--bg)"},children:(0,r.jsx)(it,{patch:x.patch})})]});if(y)return(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"#f87171",fontSize:13},children:y});if(!u)return null;let H="html"===u.language,B="markdown"===u.language,U=(c=(d=et(e).replace(/\/+$/,"")).lastIndexOf("/"))<0?"":0===c?"/":2===c&&/^[a-zA-Z]:\//.test(d)?d.slice(0,3):d.slice(0,c),_=u.content.split("\n"),q=null!==h&&h!==u.content||L;return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,r.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,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},title:e,children:en(e,t)}),(0,r.jsx)("span",{style:{marginLeft:"auto"},children:u.language}),"source"===S&&(0,r.jsx)("span",{children:p("desktop.lines",{count:_.length})}),(0,r.jsx)("span",{children:s9(u.size)}),q&&(0,r.jsxs)("div",{style:{display:"flex",borderRadius:5,overflow:"hidden",border:"1px solid var(--border)"},children:[(0,r.jsx)("button",{onClick:()=>C("source"),style:{padding:"2px 8px",fontSize:11,border:"none",cursor:"pointer",background:"source"===S?"var(--bg-selected)":"var(--bg-hover)",color:"source"===S?"var(--text)":"var(--text-muted)",fontWeight:"source"===S?600:400},children:p("desktop.source")}),(0,r.jsxs)("button",{onClick:()=>C("diff"),style:{padding:"2px 8px",fontSize:11,border:"none",borderLeft:"1px solid var(--border)",cursor:"pointer",background:"diff"===S?"var(--bg-selected)":"var(--bg-hover)",color:"diff"===S?"var(--text)":"var(--text-muted)",fontWeight:"diff"===S?600:400},children:[p("desktop.diff")," ",z>0&&(0,r.jsxs)("span",{style:{color:"var(--git-status-added)",marginLeft:2},children:["+",z]})]})]}),"source"===S&&!w&&(0,r.jsx)("button",{onClick:()=>R(e=>!e),title:p(T?"desktop.disableWordWrap":"desktop.enableWordWrap"),style:{padding:"2px 8px",fontSize:11,cursor:"pointer",background:T?"var(--bg-selected)":"var(--bg-hover)",color:T?"var(--text)":"var(--text-muted)",border:"1px solid var(--border)",borderRadius:5,fontWeight:T?600:400},children:p("desktop.wrap")}),H&&"source"===S&&(0,r.jsxs)("div",{style:{display:"flex",borderRadius:5,overflow:"hidden",border:"1px solid var(--border)"},children:[(0,r.jsx)("button",{onClick:()=>j(!1),style:{padding:"2px 8px",fontSize:11,border:"none",cursor:"pointer",background:w?"var(--bg-hover)":"var(--bg-selected)",color:w?"var(--text-muted)":"var(--text)",fontWeight:w?400:600},children:p("desktop.code")}),(0,r.jsx)("button",{onClick:()=>j(!0),style:{padding:"2px 8px",fontSize:11,border:"none",borderLeft:"1px solid var(--border)",cursor:"pointer",background:w?"var(--bg-selected)":"var(--bg-hover)",color:w?"var(--text)":"var(--text-muted)",fontWeight:w?600:400},children:p("desktop.preview")})]}),B&&"source"===S&&(0,r.jsxs)("div",{style:{display:"flex",borderRadius:5,overflow:"hidden",border:"1px solid var(--border)"},children:[(0,r.jsx)("button",{onClick:()=>j(!0),style:{padding:"2px 8px",fontSize:11,border:"none",cursor:"pointer",background:w?"var(--bg-selected)":"var(--bg-hover)",color:w?"var(--text)":"var(--text-muted)",fontWeight:w?600:400},children:p("desktop.preview")}),(0,r.jsx)("button",{onClick:()=>j(!1),style:{padding:"2px 8px",fontSize:11,border:"none",borderLeft:"1px solid var(--border)",cursor:"pointer",background:w?"var(--bg-hover)":"var(--bg-selected)",color:w?"var(--text-muted)":"var(--text)",fontWeight:w?400:600},children:p("desktop.raw")})]}),(i||a)&&(0,r.jsx)("button",{type:"button",onPointerDown:e=>e.preventDefault(),onClick:()=>{M&&a?O(M):i?.(en(e,t),!1)},title:M?p("desktop.mentionSelectedLines",{start:M.startLine,end:M.endLine}):p("desktop.mentionFile"),"aria-label":M?p("desktop.mentionSelectedLines",{start:M.startLine,end:M.endLine}):p("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,r.jsx)(s6,{filePath:e,sourceSessionId:o})]}),(0,r.jsx)("div",{ref:F,style:{flex:1,overflow:"auto",background:"var(--bg)"},children:"diff"===S&&q?L?(0,r.jsx)(it,{patch:x.patch}):(0,r.jsx)(ie,{oldContent:h,newContent:u.content}):H&&w?(0,r.jsx)("iframe",{srcDoc:u.content,sandbox:"allow-scripts",style:{width:"100%",height:"100%",border:"none",background:"var(--bg)"},title:p("desktop.htmlPreview")}):B&&w?(0,r.jsx)("div",{className:"markdown-body markdown-file-preview",style:{padding:"24px 32px"},children:(0,r.jsx)(tu.oz,{remarkPlugins:tZ,rehypePlugins:tQ,components:{h1:({children:e})=>(0,r.jsx)("h1",{id:tJ(e),children:e}),h2:({children:e})=>(0,r.jsx)("h2",{id:tJ(e),children:e}),h3:({children:e})=>(0,r.jsx)("h3",{id:tJ(e),children:e}),code({className:e,children:t,...o}){let n=e?.replace("language-","").toLowerCase()??"",s=String(t);return e?.includes("language-")||s.includes("\n")?"mermaid"===n?(0,r.jsx)(os,{code:s.replace(/\n$/,"")}):(0,r.jsx)(ol,{code:s.replace(/\n$/,""),lang:n}):(0,r.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,r.jsx)(r.Fragment,{children:e}),a({href:e,children:o,...n}){delete n.node;let i="text-(--accent-blue) underline underline-offset-2 hover:text-(--accent-blue)/80",a=s?ts(e,U,t??U):null;return a&&s?(0,r.jsx)("a",{href:e,...n,className:i,onClick:e=>{if(e.defaultPrevented||0!==e.button||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey)return;let t=e.currentTarget.getAttribute("target");t&&"_self"!==t||(e.preventDefault(),s(a))},children:o}):(0,r.jsx)("a",{href:e,...n,className:i,target:"_blank",rel:"noopener noreferrer",children:o})},table:({children:e})=>(0,r.jsx)("div",{className:"my-3 rounded-lg overflow-hidden border border-(--border)",children:(0,r.jsx)("div",{className:"overflow-x-auto",children:(0,r.jsx)("table",{className:"w-full text-sm border-collapse [&_tr:last-child>td]:border-b-0",children:e})})})},children:N})}):(0,r.jsx)(tg.A,{language:"text"===u.language?"plaintext":u.language,style:t0,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:T,children:u.content})})]})}let il={running:"var(--accent)",completed:"#22c55e",failed:"#ef4444",stopped:"#d97706"},id={running:"desktop.subagentsStatusRunning",completed:"desktop.subagentsStatusCompleted",failed:"desktop.subagentsStatusFailed",stopped:"desktop.subagentsStatusStopped"};function ic({agent:e,selected:t,onSelect:o}){let[s,i]=(0,n.useState)(!1),{t:a}=(0,E.s)(),[l,d]=(0,n.useState)(()=>Date.now());(0,n.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=il[e.status];return(0,r.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,r.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,r.jsx)("span",{style:{flexShrink:0,fontSize:10,fontFamily:"var(--font-mono)",fontWeight:600,color:"var(--text-dim)"},children:e.agentType}),(0,r.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,r.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,r.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),r=t%60;return r>0?`${o}m ${r}s`:`${o}m`}(c)}),(0,r.jsx)("span",{style:{flexShrink:0,fontSize:10,color:u},children:a(id[e.status])})]})}function ip({subagents:e,onSelect:t,selectedId:o}){let{t:s}=(0,E.s)(),[i,a]=(0,n.useState)(!0),l=e.filter(e=>"running"===e.status).length;return 0===e.length?(0,r.jsx)("div",{style:{padding:"18px 14px",fontSize:12,color:"var(--text-dim)",textAlign:"center"},children:s("desktop.subagentsEmpty")}):(0,r.jsxs)("section",{style:{flex:1,minHeight:0,display:"flex",flexDirection:"column",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",flexShrink:0,padding:"6px 10px",borderBottom:"1px solid var(--border)"},children:[(0,r.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,r.jsx)(k.K,{size:9,weight:"regular",style:{transform:i?"rotate(90deg)":"none",transition:"transform 0.15s",flexShrink:0},"aria-hidden":"true"}),(0,r.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:s("desktop.subagentsPanelTitle")})]}),l>0&&(0,r.jsxs)("span",{style:{marginRight:4,fontSize:10,fontFamily:"var(--font-mono)",color:"var(--accent)"},children:["● ",l," ",s("desktop.subagentsStatusRunning")]})]}),i&&(0,r.jsx)("div",{style:{flex:1,minHeight:0,overflowY:"auto",overflowX:"hidden",padding:"4px 0 8px"},children:e.map(e=>(0,r.jsx)(ic,{agent:e,selected:e.id===o,onSelect:t},e.id))})]})}var iu=o(31597);let ig={user:{label:"User",color:"var(--accent)"},assistant:{label:"Assistant",color:"var(--text)"},toolResult:{label:"Result",color:"var(--text-dim)"},bashExecution:{label:"Bash",color:"var(--text-muted)"}};function ih({line:e}){let t=ig[e.role]??ig.toolResult;return(0,r.jsxs)("div",{style:{marginBottom:6},children:[(0,r.jsxs)("div",{style:{fontSize:10.5,fontWeight:600,color:t.color,marginBottom:2,fontFamily:"var(--font-mono)"},children:["[",t.label,"]"]}),(0,r.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 ix({agent:e,cwd:t,onBack:o}){let{t:s}=(0,E.s)(),[i,a]=(0,n.useState)([]),[l,d]=(0,n.useState)(!0),[c,p]=(0,n.useState)(null),u=(0,n.useRef)(null),g=(0,n.useRef)(!0),h=(0,n.useCallback)(async(o=!1)=>{if(e.id&&t){o||d(!0);try{let r=new URLSearchParams({id:e.id,cwd:t}),n=await fetch(`/api/subagents/transcript?${r}`),s=await n.json();if(!n.ok||s.error){o||p(s.error??`HTTP ${n.status}`);return}a(s.lines??[]),p(null)}catch(e){o||p(e instanceof Error?e.message:String(e))}finally{d(!1)}}},[e.id,t]);(0,n.useEffect)(()=>{h()},[h]),(0,n.useEffect)(()=>{if("running"!==e.status)return;let t=setInterval(()=>void h(!0),2e3);return()=>clearInterval(t)},[e.status,h]),(0,n.useEffect)(()=>{let e=u.current;e&&g.current&&(e.scrollTop=e.scrollHeight)},[i]);let f=e.completedAt?e.completedAt-e.startedAt:void 0,x=e.tokens?.total??e.tokens?.input??e.tokens?.output,m="completed"===e.status?"#22c55e":"failed"===e.status?"#ef4444":"stopped"===e.status?"#d97706":"var(--accent)";return(0,r.jsxs)("div",{style:{flex:1,minHeight:0,display:"flex",flexDirection:"column"},children:[(0,r.jsxs)("div",{style:{flexShrink:0,borderBottom:"1px solid var(--border)",background:"var(--bg-panel)",padding:"6px 8px"},children:[(0,r.jsx)("div",{style:{display:"flex",alignItems:"center",gap:8},children:(0,r.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,r.jsx)(iu.Z,{size:12,"aria-hidden":"true"}),s("desktop.subagentsBack")]})}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6,marginTop:4,minWidth:0},children:[(0,r.jsx)("span",{"aria-hidden":"true",style:{width:8,height:8,flexShrink:0,borderRadius:"50%",background:m,boxShadow:"running"===e.status?`0 0 0 0 ${m}`:"none",animation:"running"===e.status?"subagent-pulse 1.4s ease-out infinite":"none"}}),(0,r.jsx)("span",{style:{fontSize:12,fontWeight:700,color:"var(--text)",fontFamily:"var(--font-mono)",flexShrink:0},children:e.agentType}),(0,r.jsx)("span",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:11.5,color:"var(--text-muted)"},children:e.description})]}),(0,r.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,r.jsxs)("span",{children:[e.toolUses," tool",1===e.toolUses?"":"s"]}),void 0!==x&&x>0&&(0,r.jsxs)("span",{children:[void 0===x?"":x>=1e6?`${(x/1e6).toFixed(1)}M`:x>=1e3?`${(x/1e3).toFixed(1)}k`:`${x}`," tokens"]}),void 0!==f&&(0,r.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),r=t%60;return r>0?`${o}m ${r}s`:`${o}m`}(f)}),(0,r.jsx)("span",{style:{color:m},children:s(`desktop.subagentsStatus${"running"===e.status?"Running":"completed"===e.status?"Completed":"failed"===e.status?"Failed":"Stopped"}`)})]})]}),(0,r.jsx)("div",{ref:u,onScroll:e=>{let t=e.currentTarget;g.current=t.scrollHeight-t.scrollTop-t.clientHeight<40},style:{flex:1,minHeight:0,overflowY:"auto",overflowX:"hidden",padding:"8px 10px",background:"var(--bg)"},children:l?(0,r.jsxs)("div",{style:{fontSize:12,color:"var(--text-dim)",padding:"12px 4px"},children:[s("desktop.loading"),"…"]}):c?(0,r.jsx)("div",{style:{fontSize:12,color:"#ef4444",padding:"12px 4px"},children:c}):0===i.length?(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-dim)",padding:"12px 4px"},children:s("running"===e.status?"desktop.subagentsWaitingFirstMessage":"desktop.subagentsNoTranscript")}):(0,r.jsx)("div",{style:{paddingBottom:8},children:i.map((e,t)=>(0,r.jsx)(ih,{line:e},t))})})]})}function im({tabs:e,activeTabId:t,onSelectTab:o,onCloseTab:s}){let{t:i}=(0,E.s)(),[a,l]=(0,n.useState)(null);return(0,r.jsx)("div",{style:{display:"flex",alignItems:"flex-end",background:"var(--bg-panel)",overflowX:"auto",flexShrink:0,height:36},children:e.map(e=>{let n=e.id===t;return(0,r.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:n?"var(--bg)":"var(--bg-panel)",cursor:"pointer",fontSize:12,color:n?"var(--text)":"var(--text-muted)",whiteSpace:"nowrap",maxWidth:180,minWidth:80,flexShrink:0,userSelect:"none",transition:"background 0.1s, color 0.1s"},children:[(0,r.jsx)("span",{style:{flexShrink:0,opacity:n?1:.7,display:"flex",alignItems:"center"},children:ee(e.label,13)}),(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",flex:1,fontWeight:n?500:400},title:e.filePath,children:e.label}),(0,r.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,r.jsx)(c.X,{size:11,"aria-hidden":"true"})})]},e.id)})})}var ik=o(27289),iv=o(93534),iy=o(45781),ib=o(68731),iw=o(93912),ij=o(23675),iS=o(48716),iC=o(47013),iT=o(51265);let iR={"restore-script":"restore","generate-cmd":"cmd",keep:"keep","keep-with-warning":"warning",manual:"manual"};function iz({cwd:e}){let{t}=(0,E.s)(),o=(0,n.useRef)(null),[s,i]=(0,n.useState)(!0),[a,l]=(0,n.useState)(!1),[d,c]=(0,n.useState)(!1),[p,u]=(0,n.useState)(null),[g,h]=(0,n.useState)(null),[f,x]=(0,n.useState)(new Set),[m,k]=(0,n.useState)(new Set),[v,y]=(0,n.useState)(!1),[b,w]=(0,n.useState)(null),[j,S]=(0,n.useState)(!1),[C,T]=(0,n.useState)(null),[R,z]=(0,n.useState)([]),[I,M]=(0,n.useState)(""),[P,D]=(0,n.useState)(null),[F,W]=(0,n.useState)(null);(0,n.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 $=(0,n.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="?([^";]+)"?/),r=URL.createObjectURL(t),n=document.createElement("a");n.href=r,n.download=o?.[1]??"pi-backup.zip",document.body.appendChild(n),n.click(),n.remove(),URL.revokeObjectURL(r)}catch{u(String(t("desktop.backupExportFailed")))}finally{c(!1)}},[s,a,t]),N=(0,n.useCallback)(async e=>{if(e){w(null),T(null),h(null);try{let o=new FormData;o.append("phase","parse"),o.append("file",e);let r=await fetch("/api/backup/import",{method:"POST",body:o}),n=await r.json();if(!r.ok||n.error)return void w(n.error??`HTTP ${r.status}`);if("preview"!==n.phase||!n.preview)return void w(String(t("desktop.backupImportFailed")));h(n),x(new Set(n.preview.categories)),k(new Set),y(!1)}catch{w(String(t("desktop.backupImportFailed")))}}},[t]),L=(0,n.useCallback)(async()=>{if(g){S(!0),w(null);try{let e=new FormData;e.append("phase","restore"),e.append("token",g.token),e.append("selections",JSON.stringify({categories:[...f],skippedMcpServers:[...m],reinstallNpm:v}));let r=await fetch("/api/backup/import",{method:"POST",body:e}),n=await r.json();if(!r.ok||n.error)return void w(n.error??`HTTP ${r.status}`);if("report"!==n.phase||!n.report)return void w(String(t("desktop.backupRestoreFailed")));T(n.report),h(null),o.current&&(o.current.value="")}catch{w(String(t("desktop.backupRestoreFailed")))}finally{S(!1)}}},[g,f,m,v,t]),A=(0,n.useCallback)(async o=>{if(o.installPrompt&&e){D(o.name),W(null);try{let t=I.indexOf("/"),r=t>0?I.slice(0,t):void 0,n=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:r,modelId:n})}),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{D(null)}}},[e,I,t]),O=e=>"win32"===e?"Windows":"darwin"===e?"macOS":"Linux";return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",flex:1,minWidth:0,minHeight:0,overflowY:"auto"},children:[(0,r.jsx)("header",{style:{padding:"18px 22px 14px",borderBottom:"1px solid var(--border)"},children:(0,r.jsx)("h1",{style:{margin:0,fontSize:16,fontWeight:700,color:"var(--text)"},children:t("desktop.backup")})}),(0,r.jsxs)("section",{style:{padding:"18px 22px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("h2",{style:{margin:0,fontSize:13,fontWeight:600,color:"var(--text)"},children:t("desktop.backupExportTitle")}),(0,r.jsx)("p",{style:{margin:"6px 0 12px",fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:t("desktop.backupExportDescription")}),(0,r.jsxs)("label",{style:{display:"flex",gap:8,alignItems:"flex-start",cursor:"pointer",marginBottom:8},children:[(0,r.jsx)("input",{type:"checkbox",checked:s,onChange:e=>i(e.target.checked),style:{marginTop:2}}),(0,r.jsxs)("span",{style:{fontSize:12,color:"var(--text)"},children:[t("desktop.backupIncludeSecrets"),(0,r.jsx)("span",{style:{display:"block",fontSize:11,color:"#ef4444"},children:t("desktop.backupSecretsWarning")})]})]}),(0,r.jsxs)("label",{style:{display:"flex",gap:8,alignItems:"flex-start",cursor:"pointer",marginBottom:14},children:[(0,r.jsx)("input",{type:"checkbox",checked:a,onChange:e=>l(e.target.checked),style:{marginTop:2}}),(0,r.jsxs)("span",{style:{fontSize:12,color:"var(--text)"},children:[t("desktop.backupIncludeSessions"),(0,r.jsx)("span",{style:{display:"block",fontSize:11,color:"var(--text-dim)"},children:t("desktop.backupSessionsHint")})]})]}),(0,r.jsxs)("button",{type:"button",onClick:$,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,r.jsx)(iC.f,{size:15,"aria-hidden":"true"}),d?t("desktop.backupExporting"):t("desktop.backupExportButton")]}),p&&(0,r.jsx)("p",{style:{margin:"8px 0 0",fontSize:11,color:"#ef4444"},children:p})]}),(0,r.jsxs)("section",{style:{padding:"18px 22px"},children:[(0,r.jsx)("h2",{style:{margin:0,fontSize:13,fontWeight:600,color:"var(--text)"},children:t("desktop.backupImportTitle")}),(0,r.jsx)("p",{style:{margin:"6px 0 12px",fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:t("desktop.backupImportDescription")}),(0,r.jsx)("input",{ref:o,type:"file",accept:".zip,application/zip",onChange:e=>N(e.target.files?.[0]),style:{display:"none"}}),(0,r.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,r.jsx)(iT._,{size:15,"aria-hidden":"true"}),t("desktop.backupImportButton")]}),b&&(0,r.jsx)("p",{style:{margin:"0 0 10px",fontSize:11,color:"#ef4444",lineHeight:1.5},children:b}),g&&(0,r.jsxs)("div",{style:{border:"1px solid var(--border)",borderRadius:8,padding:14,background:"var(--bg-panel)",display:"flex",flexDirection:"column",gap:12},children:[(0,r.jsxs)("div",{style:{fontSize:12,color:"var(--text-muted)",lineHeight:1.6},children:[(0,r.jsxs)("span",{style:{color:"var(--text)",fontWeight:600},children:[t("desktop.backupManifest"),":"]})," ",new Date(g.preview.manifest.createdAt).toLocaleString()," \xb7 ",O(g.preview.manifest.sourcePlatform)," →",O(navigator.platform.includes("Win")?"win32":navigator.platform.includes("Linux")?"linux":"darwin")," \xb7 pi-web ",g.preview.manifest.piWebVersion,g.preview.manifest.includeSecrets?"":` \xb7 ${t("desktop.backupNoSecrets")}`]}),(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{style:{fontSize:11,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:6},children:t("desktop.backupCategories")}),(0,r.jsx)("div",{style:{display:"flex",gap:14,flexWrap:"wrap"},children:g.preview.categories.map(e=>(0,r.jsxs)("label",{style:{display:"flex",gap:6,alignItems:"center",cursor:"pointer",fontSize:12,color:"var(--text)"},children:[(0,r.jsx)("input",{type:"checkbox",checked:f.has(e),onChange:t=>{let o=new Set(f);t.target.checked?o.add(e):o.delete(e),x(o)}}),t(`desktop.backupCategory${e}`)]},e))})]}),g.preview.servers.length>0&&(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{style:{fontSize:11,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:6},children:t("desktop.backupMcpServers")}),(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:g.preview.servers.map(o=>(0,r.jsxs)("div",{style:{display:"flex",alignItems:"flex-start",gap:8,fontSize:12},children:[(0,r.jsx)("input",{type:"checkbox",checked:!m.has(o.name),onChange:e=>{let t=new Set(m);e.target.checked?t.delete(o.name):t.add(o.name),k(t)},style:{marginTop:2}}),(0,r.jsxs)("div",{style:{flex:1,minWidth:0,display:"flex",flexDirection:"column",gap:2},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[(0,r.jsx)("code",{style:{fontSize:11,fontFamily:"var(--font-mono)",color:"var(--text)"},children:o.name}),(0,r.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:iR[o.action]})]}),(0,r.jsxs)("div",{style:{fontSize:11,color:"var(--text-dim)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[(0,r.jsx)("code",{style:{fontFamily:"var(--font-mono)"},children:o.original.command}),o.adapted&&o.adapted.command!==o.original.command&&(0,r.jsxs)(r.Fragment,{children:[" → ",(0,r.jsx)("code",{style:{fontFamily:"var(--font-mono)",color:"var(--text)"},children:o.adapted.command})]})]}),o.reason&&(0,r.jsx)("div",{style:{fontSize:11,color:"#ef4444"},children:o.reason}),"manual"===o.action&&o.installPrompt&&e&&(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,marginTop:2,flexWrap:"wrap"},children:[(0,r.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,r.jsxs)("option",{value:`${e.provider}/${e.id}`,children:[e.provider,"/",e.name||e.id]},`${e.provider}/${e.id}`))}),(0,r.jsx)("button",{type:"button",disabled:P===o.name,onClick:()=>A(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")}),F?.server===o.name&&(0,r.jsx)("a",{href:`?session=${encodeURIComponent(F.sessionId)}`,style:{fontSize:11,color:"var(--accent)"},children:t("desktop.backupOpenSession")})]})]})]},o.name))})]}),g.preview.npmPackages.length>0&&(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{style:{fontSize:11,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:6},children:t("desktop.backupNpmPackages")}),(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:4,marginBottom:6},children:g.preview.npmPackages.map(e=>(0,r.jsx)("code",{style:{fontSize:11,fontFamily:"var(--font-mono)",color:"var(--text)"},children:e},e))}),(0,r.jsxs)("label",{style:{display:"flex",gap:6,alignItems:"flex-start",cursor:"pointer",fontSize:12,color:"var(--text)",lineHeight:1.4},children:[(0,r.jsx)("input",{type:"checkbox",checked:v,onChange:e=>y(e.target.checked),style:{marginTop:2}}),(0,r.jsxs)("span",{children:[t("desktop.backupReinstallNpm"),(0,r.jsx)("span",{style:{display:"block",fontSize:11,color:"var(--text-dim)"},children:t("desktop.backupReinstallNpmHint")})]})]})]}),g.preview.warnings.length>0&&(0,r.jsx)("div",{style:{fontSize:11,color:"#ef4444",lineHeight:1.5},children:g.preview.warnings.map((e,t)=>(0,r.jsxs)("div",{children:["⚠ ",e]},t))}),(0,r.jsxs)("div",{style:{display:"flex",gap:8},children:[(0,r.jsxs)("button",{type:"button",onClick:L,disabled:j||0===f.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===f.size?.5:1},children:[(0,r.jsx)(iT._,{size:15,"aria-hidden":"true"}),j?t("desktop.backupRestoring"):t("desktop.backupRestoreButton")]}),(0,r.jsx)("button",{type:"button",onClick:()=>{h(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,r.jsxs)("div",{style:{border:"1px solid var(--border)",borderRadius:8,padding:14,background:"var(--bg-panel)",display:"flex",flexDirection:"column",gap:10},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,fontSize:13,fontWeight:600,color:"var(--text)"},children:[(0,r.jsx)(oj.W,{size:16,"aria-hidden":"true"}),t("desktop.backupRestoreReport")]}),C.restored.length>0&&(0,r.jsxs)("div",{children:[(0,r.jsxs)("div",{style:{fontSize:11,fontWeight:600,color:"#4ade80",marginBottom:4},children:["✓ ",t("desktop.backupReportRestored")]}),(0,r.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,r.jsxs)("div",{children:[(0,r.jsxs)("div",{style:{fontSize:11,fontWeight:600,color:"#fbbf24",marginBottom:4},children:["\uD83D\uDD04 ",t("desktop.backupReportRestart")]}),(0,r.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,r.jsxs)("div",{children:[(0,r.jsxs)("div",{style:{fontSize:11,fontWeight:600,color:"#ef4444",marginBottom:4},children:[(0,r.jsx)(_.N,{size:12,style:{verticalAlign:-2},"aria-hidden":"true"})," ",t("desktop.backupReportManual")]}),C.manual.map((e,t)=>(0,r.jsxs)("div",{style:{fontSize:11,color:"var(--text-muted)",lineHeight:1.6},children:[(0,r.jsx)("strong",{style:{color:"var(--text)"},children:e.server}),": ",e.message]},t))]}),C.warnings.length>0&&(0,r.jsx)("div",{style:{fontSize:11,color:"#ef4444",lineHeight:1.6},children:C.warnings.map((e,t)=>(0,r.jsxs)("div",{children:["⚠ ",e]},t))}),C.needsRestart.length>0&&(0,r.jsx)("p",{style:{margin:0,fontSize:11,color:"#fbbf24",lineHeight:1.5},children:t("desktop.backupRestartHint")})]})]})]})}let iI={position:"relative",width:40,height:22,borderRadius:11,border:"none",cursor:"pointer",padding:0,flexShrink:0,transition:"background 0.18s ease",outline:"none"},iM={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 iE({checked:e,onChange:t,label:o,description:n}){return(0,r.jsxs)("label",{style:{display:"flex",alignItems:n?"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,r.jsxs)("span",{style:{flex:1,minWidth:0},children:[(0,r.jsx)("span",{style:{display:"block",fontSize:13,fontWeight:550,color:"var(--text)",lineHeight:1.4},children:o}),n&&(0,r.jsx)("span",{style:{display:"block",fontSize:11,lineHeight:1.5,color:"var(--text-muted)",marginTop:2},children:n})]}),(0,r.jsx)("button",{type:"button",role:"switch","aria-checked":e,onClick:o=>{o.preventDefault(),t(!e)},style:{...iI,background:e?"var(--accent)":"color-mix(in srgb, var(--border) 70%, var(--bg))"},children:(0,r.jsx)("span",{style:{...iM,left:e?21:3}})})]})}function iP({title:e,description:t,children:o}){return(0,r.jsxs)("section",{style:{padding:"20px 22px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("h2",{style:{margin:0,fontSize:14,fontWeight:650,color:"var(--text)"},children:e}),(0,r.jsx)("p",{style:{margin:"5px 0 14px",fontSize:12,lineHeight:1.5,color:"var(--text-muted)"},children:t}),(0,r.jsx)("div",{children:o})]})}let iD="pi-input-shortcut";function iF(){try{let e=localStorage.getItem(iD);return"ctrl-enter"===e?"ctrl-enter":"enter"}catch{return"enter"}}function iW(){let{t:e}=(0,E.s)(),[t,o]=(0,n.useState)(iF);(0,n.useEffect)(()=>{let e=()=>o(iF());return window.addEventListener("storage",e),()=>window.removeEventListener("storage",e)},[]);let s=(0,n.useCallback)(e=>{o(e);try{localStorage.setItem(iD,e),window.dispatchEvent(new StorageEvent("storage",{key:iD,newValue:e}))}catch{}},[]);return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",flex:1,minWidth:0,minHeight:0,overflowY:"auto"},children:[(0,r.jsx)("header",{style:{padding:"18px 22px 14px",borderBottom:"1px solid var(--border)"},children:(0,r.jsx)("h1",{style:{margin:0,fontSize:16,fontWeight:700,color:"var(--text)"},children:e("desktop.chat")})}),(0,r.jsx)(iP,{title:e("desktop.inputShortcut"),description:e("desktop.inputShortcutDescription"),children:(0,r.jsx)(iE,{checked:"ctrl-enter"===t,onChange:e=>s(e?"ctrl-enter":"enter"),label:e("desktop.useCtrlEnter"),description:e("desktop.useCtrlEnterDescription")})})]})}var i$=o(95650),iN=o(55803),iL=o(23602),iA=o(18613),iO=o(12779);let iH={display:"flex",gap:6,flexWrap:"wrap"};function iB(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 iU({icon:e,label:t,actions:o}){return(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:10,width:"100%"},children:[(0,r.jsx)("span",{style:{color:"var(--text-dim)",display:"inline-flex",flexShrink:0},children:e}),(0,r.jsx)("span",{style:{fontSize:11,fontWeight:700,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.06em"},children:t}),o&&(0,r.jsx)("span",{style:{display:"inline-flex",alignItems:"center",gap:12,marginLeft:"auto"},children:o})]})}let i_={display:"inline-flex",alignItems:"center",gap:6,padding:0,border:0,background:"transparent",color:"var(--accent)",fontSize:11,cursor:"pointer",whiteSpace:"nowrap"},iq={onMouseEnter:e=>{e.currentTarget.style.textDecoration="underline"},onMouseLeave:e=>{e.currentTarget.style.textDecoration="none"}};function iV({title:e,description:t,children:o}){return(0,r.jsxs)("section",{style:{padding:"20px 22px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("h2",{style:{margin:0,fontSize:14,fontWeight:650,color:"var(--text)"},children:e}),(0,r.jsx)("p",{style:{margin:"5px 0 16px",fontSize:12,lineHeight:1.5,color:"var(--text-muted)"},children:t}),o]})}function iK({depth:e}){let t=e/100;return(0,r.jsxs)("svg",{width:14,height:14,viewBox:"0 0 14 14",style:{flexShrink:0},children:[(0,r.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,r.jsx)("rect",{x:4,y:4,width:6,height:6,rx:1,style:{fill:"var(--text-dim)",opacity:.05+.35*t}})]})}function iJ({hasDark:e,hasLight:t,darkColor:o,lightColor:n,t:s}){return(0,r.jsxs)("span",{style:{display:"inline-flex",gap:3,alignItems:"center",flexShrink:0},children:[e&&(0,r.jsx)("span",{title:s("desktop.darkVariant"),style:{display:"inline-block",width:7,height:7,borderRadius:"50%",background:o??"#7c6f64"}}),t&&(0,r.jsx)("span",{title:s("desktop.lightVariant"),style:{display:"inline-block",width:7,height:7,borderRadius:"50%",background:n??"#d5c4a1",border:"1px solid rgba(0,0,0,0.1)"}})]})}function iG(){let{mode:e,resolvedMode:t,themeName:o,setMode:s,setTheme:i,previewTheme:a,clearPreview:l,isThemeCached:d,borderDepth:c,setBorderDepth:p}=tL(),{locale:u,setLocale:g,t:h}=(0,E.s)(),[f,x]=(0,n.useState)([]),[m,k]=(0,n.useState)(!0),[v,y]=(0,n.useState)(null),[b,w]=(0,n.useState)(null);(0,n.useEffect)(()=>{let e=!1;return fetch("/api/themes").then(e=>e.ok?e.json():null).then(t=>{!e&&t&&x(t.themeSets)}).catch(()=>{}).finally(()=>{e||k(!1)}),()=>{e=!0}},[]);let j=(0,n.useCallback)(e=>{y(e),i(e).finally(()=>y(null))},[i]),S=(0,n.useRef)(null),C=(0,n.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,n.useCallback)(e=>{s(e)},[s]),R=(0,n.useCallback)(()=>{window.piDesktop?.openThemeFolder()},[]),z=(0,n.useCallback)(()=>{window.piDesktop?window.piDesktop.openThemeDocs():window.open("https://pi.dev/docs/latest/themes","_blank","noopener,noreferrer")},[]);return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",flex:1,minWidth:0,minHeight:0,overflowY:"auto"},children:[(0,r.jsx)("header",{style:{padding:"18px 22px 14px",borderBottom:"1px solid var(--border)"},children:(0,r.jsx)("h1",{style:{margin:0,fontSize:16,fontWeight:700,color:"var(--text)"},children:h("desktop.display")})}),(0,r.jsxs)(iV,{title:h("desktop.theme"),description:h("desktop.themeDescription"),children:[(0,r.jsx)(iU,{icon:(0,r.jsx)(i$.p,{size:14,weight:"fill"}),label:h("desktop.colorScheme"),actions:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("button",{type:"button",onClick:R,style:i_,...iq,children:[(0,r.jsx)(iN.N,{size:12,weight:"regular","aria-hidden":"true"}),h("desktop.openThemeFolder")]}),(0,r.jsxs)("button",{type:"button",onClick:z,style:i_,...iq,children:[(0,r.jsx)(iL.B,{size:12,weight:"regular","aria-hidden":"true"}),h("desktop.learnPiThemes")]})]})}),m?(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-dim)"},children:h("desktop.loadingThemes")}):(0,r.jsxs)("div",{style:iH,children:[(0,r.jsx)("button",{type:"button",onClick:()=>j(""),disabled:null!==v,style:iB(""===o,"__default__"===b,null!==v),onMouseEnter:()=>C(""),onMouseLeave:()=>C(null),children:h("desktop.defaultTheme")}),f.map(e=>(0,r.jsxs)("button",{type:"button",onClick:()=>j(e.name),disabled:null!==v,style:iB(o===e.name,b===e.name,v===e.name),onMouseEnter:()=>C(e.name),onMouseLeave:()=>C(null),children:[e.displayName,(0,r.jsx)(iJ,{hasDark:e.hasDark,hasLight:e.hasLight,darkColor:e.accent,lightColor:e.accentLight,t:h})]},e.name))]}),(0,r.jsxs)("div",{style:{marginTop:20},children:[(0,r.jsx)(iU,{icon:(0,r.jsx)(iK,{depth:c}),label:`${h("desktop.borderVisibility")} (${c})`}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10},children:[(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",flexShrink:0},children:h("desktop.borderSubtle")}),(0,r.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,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",flexShrink:0},children:h("desktop.borderBold")})]}),(0,r.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,r.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,r.jsxs)("div",{style:{marginTop:20},children:[(0,r.jsx)(iU,{icon:"dark"===t?(0,r.jsx)(iA.A,{size:14,weight:"fill"}):(0,r.jsx)(iO.b,{size:14,weight:"fill"}),label:h("desktop.appearanceMode")}),(0,r.jsx)("div",{style:iH,children:[{value:"light",icon:(0,r.jsx)(iO.b,{size:15,weight:"light"===e?"fill":"regular"})},{value:"dark",icon:(0,r.jsx)(iA.A,{size:15,weight:"dark"===e?"fill":"regular"})},{value:"system",icon:(0,r.jsx)(iv.V,{size:15,weight:"system"===e?"fill":"regular"})}].map(t=>{let o=e===t.value;return(0,r.jsxs)("button",{type:"button",onClick:()=>T(t.value),style:iB(o,b===`mode:${t.value}`),onMouseEnter:()=>w(`mode:${t.value}`),onMouseLeave:()=>w(null),children:[t.icon,h(`desktop.${t.value}`)]},t.value)})})]}),!m&&0===f.length&&(0,r.jsxs)("p",{style:{margin:"14px 0 0",fontSize:11,color:"var(--text-dim)",lineHeight:1.5},children:[h("desktop.noCustomThemes")," ",h("desktop.noCustomThemesHint")," ",(0,r.jsx)("code",{style:{fontSize:10,background:"var(--bg-secondary)",padding:"1px 5px",borderRadius:3,fontFamily:"var(--font-mono)"},children:"~/.pi/agent/themes/*.json"})," ",h("desktop.noCustomThemesHint2")]})]}),(0,r.jsx)(iV,{title:h("desktop.language"),description:h("desktop.languageDescription"),children:(0,r.jsx)("div",{style:iH,children:["en","zh-CN"].map(e=>(0,r.jsx)("button",{type:"button",onClick:()=>g("zh-CN"===e?"zh-CN":"en"),style:iB("zh-CN"===e?"zh-CN"===u:"zh-CN"!==u,b===`lang:${e}`),onMouseEnter:()=>w(`lang:${e}`),onMouseLeave:()=>w(null),children:"en"===e?h("desktop.english"):h("desktop.chinese")},e))})})]})}var iY=o(94638);function iX({children:e}){return(0,r.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 iZ({children:e}){return(0,r.jsx)("div",{style:{padding:"0 14px"},children:(0,r.jsx)("div",{style:{borderBottom:"1px solid var(--border)"},children:e})})}function iQ({children:e}){return(0,r.jsx)("div",{style:{padding:"0 14px"},children:e})}function i0({children:e}){return(0,r.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 i1=[{value:"normal",labelKey:"modes.collabNormal"},{value:"plan",labelKey:"modes.collabPlan"},{value:"goal",labelKey:"modes.collabGoal"}],i2=[{value:"economy",labelKey:"modes.tokenEconomy"},{value:"full",labelKey:"modes.tokenFull"},{value:"delivery",labelKey:"modes.tokenDelivery"}],i4=[{value:"ask",labelKey:"modes.approvalAsk"},{value:"auto",labelKey:"modes.approvalAuto"},{value:"yolo",labelKey:"modes.approvalYolo"}];function i6({options:e,value:t,onChange:o,disabled:n,accentFor:s}){let{t:i}=(0,E.s)();return(0,r.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,r.jsx)("button",{type:"button",role:"radio","aria-checked":a,disabled:n,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:n?"not-allowed":"pointer",fontSize:11.5,fontWeight:a?650:500,opacity:n?.5:1,whiteSpace:"nowrap",transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{a||n||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{a||(e.currentTarget.style.background="none")},children:i(e.labelKey)},e.value)})})}function i5(){let{t:e}=(0,E.s)(),[t,o]=(0,n.useState)({tasksBoard:!0}),[s,i]=(0,n.useState)(null),[a,l]=(0,n.useState)(!1),[d,c]=(0,n.useState)(!1);(0,n.useEffect)(()=>{let e=!1;return(async()=>{try{let[t,r]=await Promise.all([fetch("/api/features"),fetch("/api/modes")]);if(!e&&t.ok){let e=await t.json();o(t=>({...t,...e}))}if(!e&&r.ok){let e=await r.json();i({collaborationMode:ez(e.collaborationMode),tokenMode:eI(e.tokenMode),toolApprovalMode:eM(e.toolApprovalMode),permissionRules:e.permissionRules??{allow:[],ask:[],deny:[]}})}e||l(!0)}catch{}})(),()=>{e=!0}},[]);let p=(0,n.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,n.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:ez(e.modes?.collaborationMode??t.collaborationMode),tokenMode:eI(e.modes?.tokenMode??t.tokenMode),toolApprovalMode:eM(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,r.jsx)("div",{style:{flex:1,overflow:"auto",minWidth:0,padding:"20px 22px",display:"flex",flexDirection:"column",gap:16},children:(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[a?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(iX,{children:(0,r.jsx)(iQ,{children:(0,r.jsx)(iE,{checked:t.tasksBoard,onChange:e=>void p(e),label:(0,r.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:6},children:[(0,r.jsx)(iY.x,{size:14,"aria-hidden":"true"}),e("desktop.featuresTasksBoard"),(0,r.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,r.jsxs)(iX,{children:[(0,r.jsx)(iZ,{children:(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:16,padding:"12px 0"},children:[(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:13,fontWeight:600,color:"var(--text)"},children:e("desktop.featuresCollabDefault")}),(0,r.jsx)("div",{style:{fontSize:11,color:"var(--text-muted)",marginTop:2},children:e("desktop.featuresCollabDefaultDesc")})]}),(0,r.jsx)(i6,{options:i1,value:s.collaborationMode,onChange:e=>void u({collaborationMode:e}),disabled:d})]})}),(0,r.jsx)(iZ,{children:(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:16,padding:"12px 0"},children:[(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:13,fontWeight:600,color:"var(--text)"},children:e("desktop.featuresTokenDefault")}),(0,r.jsx)("div",{style:{fontSize:11,color:"var(--text-muted)",marginTop:2},children:e("desktop.featuresTokenDefaultDesc")})]}),(0,r.jsx)(i6,{options:i2,value:s.tokenMode,onChange:e=>void u({tokenMode:e}),disabled:d})]})}),(0,r.jsx)(iQ,{children:(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:16,padding:"12px 0"},children:[(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:13,fontWeight:600,color:"var(--text)"},children:e("desktop.featuresApprovalDefault")}),(0,r.jsx)("div",{style:{fontSize:11,color:"var(--text-muted)",marginTop:2},children:e("desktop.featuresApprovalDefaultDesc")})]}),(0,r.jsx)(i6,{options:i4,value:s.toolApprovalMode,onChange:e=>void u({toolApprovalMode:e}),disabled:d,accentFor:e=>"yolo"===e?"var(--accent-red, #ef4444)":void 0})]})})]})]}):(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)"},children:e("desktop.featuresLoading")}),(0,r.jsx)(i0,{children:e("desktop.featuresDesc")}),d&&(0,r.jsx)("div",{style:{padding:"0 2px",fontSize:11,color:"var(--text-muted)"},children:e("desktop.featuresSaving")})]})})}var i3=o(76553);function i8({open:e,onClose:t,children:o}){let[s,i]=(0,n.useState)(!1),[a,l]=(0,n.useState)(!1);return((0,n.useEffect)(()=>{if(e)l(!0),requestAnimationFrame(()=>requestAnimationFrame(()=>i(!0)));else{i(!1);let e=setTimeout(()=>l(!1),250);return()=>clearTimeout(e)}},[e]),a)?(0,r.jsxs)(r.Fragment,{children:[(0,r.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,r.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,r.jsx)("div",{style:{display:"flex",justifyContent:"center",padding:"10px 0 4px",flexShrink:0},children:(0,r.jsx)("div",{style:{width:36,height:4,borderRadius:2,background:"var(--border)"}})}),(0,r.jsx)("div",{style:{flex:1,overflow:"auto",minHeight:0},children:o})]})]}):null}function i7({onSessionsChanged:e}){let{t}=(0,E.s)(),o=$(),[s,i]=(0,n.useState)(null),[a,l]=(0,n.useState)([]),[d,p]=(0,n.useState)([]),[u,g]=(0,n.useState)(new Set),[h,f]=(0,n.useState)(null),[x,m]=(0,n.useState)({imported:0,skipped:0,errors:0,total:0,done:!1}),[k,v]=(0,n.useState)([]),[y,b]=(0,n.useState)(!1),[w,j]=(0,n.useState)({done:0,total:0}),[S,C]=(0,n.useState)(!1),[T,R]=(0,n.useState)(null),[I,M]=(0,n.useState)(!1),P=(0,n.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&&(p(t.reasonix.projects),i("reasonix"))}catch(e){R(e instanceof Error?e.message:String(e))}finally{C(!1)}},[]),[D,F]=(0,n.useState)(!1);(0,n.useEffect)(()=>{D||(F(!0),P())},[D,P]);let W=(0,n.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}`);f(t.jobId)}catch(e){R(e instanceof Error?e.message:String(e))}finally{C(!1)}}},[s,u]);(0,n.useEffect)(()=>{let t;if(!h)return;let o=!0,r=async()=>{if(o)try{let n=await fetch(`/api/import/status?jobId=${encodeURIComponent(h)}`),s=await n.json();if(!o)return;m({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(r,800))}catch{o&&(t=setTimeout(r,2e3))}};return r(),()=>{o=!1,clearTimeout(t)}},[h,e]);let N=(0,n.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})}}},r=Array.from({length:Math.min(4,k.length)},o);await Promise.all(r),b(!1),e?.()},[k,e]);if(x.done&&k.length>0)return(0,r.jsxs)("div",{style:{padding:"18px 22px",display:"flex",flexDirection:"column",gap:14},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10},children:[(0,r.jsx)(oZ.r,{size:20,weight:"fill",style:{color:"#4ade80"}}),(0,r.jsx)("span",{style:{fontSize:14,fontWeight:600,color:"var(--text)"},children:t("desktop.importDone")??"导入完成"})]}),(0,r.jsxs)("div",{style:{fontSize:12,color:"var(--text-muted)",lineHeight:1.6},children:[t("desktop.importedSummary",{imported:x.imported})??`成功导入 ${x.imported} 个会话`,x.skipped>0&&(0,r.jsx)("span",{style:{marginLeft:8},children:t("desktop.importSkippedCount",{skipped:x.skipped})??`,${x.skipped} 个跳过`}),x.errors>0&&(0,r.jsx)("span",{style:{marginLeft:8,color:"#ef4444"},children:t("desktop.importErrorsCount",{errors:x.errors})??`,${x.errors} 个失败`})]}),y?(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,fontSize:12,color:"var(--text-muted)"},children:[(0,r.jsx)(B.y,{size:14,style:{animation:"spin 1s linear infinite"}}),t("desktop.importGeneratingTitles")??"正在生成标题…"," ","(",w.done,"/",w.total,")"]}):(0,r.jsxs)("button",{type:"button",onClick:N,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,r.jsx)(i3.o,{size:15}),t("desktop.importGenerateTitles")??"为导入的会话生成标题"]}),(0,r.jsx)("button",{type:"button",onClick:()=>{f(null),m({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 L=(0,r.jsxs)("div",{style:{padding:o?"12px 18px":"18px 22px",display:"flex",flexDirection:"column",gap:14},children:[T&&(0,r.jsxs)("div",{style:{display:"flex",alignItems:"flex-start",gap:8,fontSize:12,color:"#ef4444",lineHeight:1.5},children:[(0,r.jsx)(_.N,{size:14,style:{flexShrink:0,marginTop:1}}),(0,r.jsx)("span",{children:T})]}),!h&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)",lineHeight:1.6},children:t("desktop.importSessionsDesc")??"从其他 AI 编码工具导入历史对话记录到 pi-web。目前支持 Reasonix,更多工具陆续支持中。"}),(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:a.map(e=>(0,r.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,r.jsx)("input",{type:"radio",name:"import-source",value:e.key,checked:s===e.key,disabled:"available"!==e.status,onChange:()=>i(e.key)}),(0,r.jsxs)("div",{style:{flex:1},children:[(0,r.jsx)("div",{style:{fontSize:13,fontWeight:600,color:"var(--text)"},children:e.label}),"coming-soon"===e.status&&(0,r.jsx)("div",{style:{fontSize:11,color:"var(--text-dim)",marginTop:1},children:t("desktop.comingSoon")??"即将支持"})]}),"reasonix"===e.key&&d.length>0&&(0,r.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,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[(0,r.jsx)("span",{style:{fontSize:12,fontWeight:600,color:"var(--text)"},children:t("desktop.importSelectProjects")??"选择要导入的项目"}),(0,r.jsx)("button",{type:"button",onClick:()=>g(new Set(d.map(e=>e.name))),style:i9,children:t("desktop.importSelectAll")??"全选"}),(0,r.jsx)("button",{type:"button",onClick:()=>g(new Set),style:i9,children:t("desktop.importDeselectAll")??"取消全选"})]}),(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:4},children:d.map(e=>(0,r.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,r.jsx)("input",{type:"checkbox",checked:u.has(e.name),onChange:()=>{var t;return t=e.name,void g(e=>{let o=new Set(e);return o.has(t)?o.delete(t):o.add(t),o})}}),(0,r.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:500,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name}),(0,r.jsxs)("div",{style:{fontSize:11,color:"var(--text-dim)",marginTop:2},children:[e.sessions," ",t("desktop.sessions")??"会话",e.matched&&(0,r.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,r.jsxs)("span",{style:{marginLeft:8,color:"var(--text-muted)"},children:["→ ",t("desktop.importNewProject")??"新建项目"]})]})]})]},e.name))}),(0,r.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,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(B.y,{size:14,style:{animation:"spin 1s linear infinite"}})," ",t("desktop.importing")??"导入中…"]}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(z.z,{size:15})," ",t("desktop.importStart")??"开始导入"]})})]}),"reasonix"===s&&0===d.length&&!S&&(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)",padding:"12px 0"},children:t("desktop.importNoData")??"未找到 Reasonix 数据。请确认 ~/.reasonix/projects/ 目录存在且包含会话文件。"})]}),h&&!x.done&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,fontSize:12,color:"var(--text)"},children:[(0,r.jsx)(B.y,{size:14,style:{animation:"spin 1s linear infinite"}}),t("desktop.importing")??"导入中…"]}),(0,r.jsx)("div",{style:{height:6,borderRadius:3,background:"var(--bg-panel)",overflow:"hidden"},children:(0,r.jsx)("div",{style:{height:"100%",borderRadius:3,background:"var(--accent)",width:`${x.total>0?(x.imported+x.skipped+x.errors)/x.total*100:0}%`,transition:"width 0.3s ease"}})}),(0,r.jsxs)("div",{style:{fontSize:11,color:"var(--text-dim)"},children:[x.imported+x.skipped+x.errors," / ",x.total,x.skipped>0&&` \xb7 ${t("desktop.importSkippedCount",{skipped:x.skipped})??`${x.skipped} 跳过`}`]})]})]});return o?(0,r.jsxs)(r.Fragment,{children:[(0,r.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,r.jsx)(z.z,{size:16}),(0,r.jsx)("span",{style:{fontWeight:500},children:t("desktop.importSessions")??"导入会话"})]}),(0,r.jsxs)(i8,{open:I,onClose:()=>M(!1),children:[(0,r.jsxs)("div",{style:{padding:"4px 18px 14px",borderBottom:"1px solid var(--border)",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[(0,r.jsx)("span",{style:{fontSize:15,fontWeight:700,color:"var(--text)"},children:t("desktop.importSessions")??"导入会话"}),(0,r.jsx)("button",{onClick:()=>M(!1),style:ae,children:(0,r.jsx)(c.X,{size:18})})]}),L]})]}):L}let i9={background:"none",border:"none",color:"var(--accent)",fontSize:11,cursor:"pointer",padding:"2px 4px"},ae={background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",padding:4,display:"flex"},at="deepseek-vision",ao={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 ar(){return{fontSize:12,color:"var(--text-muted)"}}let an={padding:"7px 12px",border:"none",borderRadius:6,background:"var(--accent)",color:"#fff",cursor:"pointer",fontSize:12};function as({sessionId:e}){let{t}=(0,E.s)(),[o,s]=(0,n.useState)(!1),[i,a]=(0,n.useState)(null),[l,d]=(0,n.useState)(!1),[c,p]=(0,n.useState)(null),[u,g]=(0,n.useState)(!1),[h,f]=(0,n.useState)({}),[x,m]=(0,n.useState)(""),[k,v]=(0,n.useState)(""),[y,b]=(0,n.useState)("eager"),[w,j]=(0,n.useState)(!1),[S,C]=(0,n.useState)(null),[T,R]=(0,n.useState)(!1),[z,I]=(0,n.useState)(!1),[M,P]=(0,n.useState)({provider:"custom",baseUrl:"",apiKey:"",model:"",maxTokens:4096,hasApiKey:!1}),[D,F]=(0,n.useState)(""),[W,$]=(0,n.useState)(""),[N,L]=(0,n.useState)(!1),[A,O]=(0,n.useState)(null),[H,B]=(0,n.useState)(!1);(0,n.useEffect)(()=>{let e=!1;return(async()=>{a(null);try{let[t,o]=await Promise.all([fetch("/api/mcp"),fetch("/api/vision-config")]),r=await t.json();if(!t.ok||r.error)throw Error(r.error??`HTTP ${t.status}`);let n=await o.json();if(!o.ok||n.error)throw Error(n.error??`HTTP ${o.status}`);if(e)return;f(r.mcpServers??{}),m(r.filePath);let i=(r.mcpServers??{})[at];v(i?.command??""),b(i?.lifecycle==="lazy"?"lazy":"eager"),P({provider:n.provider,baseUrl:n.baseUrl,apiKey:"",model:n.model,maxTokens:n.maxTokens,hasApiKey:n.hasApiKey}),n.path&&$(n.path),s(!0)}catch(t){e||a(t instanceof Error?t.message:String(t))}})(),()=>{e=!0}},[]);let U=(0,n.useCallback)(async()=>{if(!k.trim())return void C(t("desktop.mcpVisionCommandRequired"));j(!0),C(null),R(!1),I(!1);try{let e=h[at],t={...h,[at]:{...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})}),r=await o.json();if(!o.ok||r.error)throw Error(r.error??`HTTP ${o.status}`);f(t),R(!0)}catch(e){C(e instanceof Error?e.message:String(e))}finally{j(!1)}},[h,k,y,t]),_=(0,n.useCallback)(async()=>{j(!0),C(null),R(!1),I(!1);try{let e={...h};delete e[at];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}`);f(e),v(""),b("eager"),I(!0)}catch(e){C(e instanceof Error?e.message:String(e))}finally{j(!1)}},[h]),q=(0,n.useCallback)(async()=>{L(!0),O(null),B(!1);try{let e=await fetch("/api/vision-config",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({...M,...D?{apiKey:D}:{}})}),t=await e.json();if(!e.ok||t.error)throw Error(t.error??`HTTP ${e.status}`);P({...t,apiKey:"",hasApiKey:t.hasApiKey}),F(""),B(!0)}catch(e){O(e instanceof Error?e.message:String(e))}finally{L(!1)}},[M,D]),V=(0,n.useCallback)(async()=>{if(e){d(!0),p(null),g(!1);try{let t=await fetch("/api/mcp/restart",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:e,name:at})}),o=await t.json();if(!t.ok||o.error)throw Error(o.error??`HTTP ${t.status}`);g(!0)}catch(e){p(e instanceof Error?e.message:String(e))}finally{d(!1)}}},[e]),K=!!h[at];return(0,r.jsxs)(iX,{children:[(0,r.jsx)(iZ,{children:(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:7,padding:"12px 0"},children:[(0,r.jsx)(r5.k,{size:15,"aria-hidden":"true"}),(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[(0,r.jsx)("span",{style:{fontSize:13,fontWeight:600,color:"var(--text)"},children:t("desktop.mcpVisionTitle")}),(0,r.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,r.jsx)("div",{style:{fontSize:11,color:"var(--text-muted)",marginTop:2},children:t("desktop.mcpVisionDesc")})]})]})}),o?i?(0,r.jsx)(iQ,{children:(0,r.jsx)("div",{style:{padding:"8px 0",fontSize:12,color:"#ef4444"},children:i})}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(iZ,{children:(0,r.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)",padding:"10px 0 2px"},children:t("desktop.mcpVisionRegistration")})}),(0,r.jsx)(iZ,{children:(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"minmax(120px, 180px) 1fr",gap:8,alignItems:"center",padding:"6px 0"},children:[(0,r.jsxs)("span",{style:ar(),children:[t("desktop.mcpVisionCommand")," *"]}),(0,r.jsx)("input",{value:k,onChange:e=>v(e.target.value),placeholder:"/path/to/deepseek-vision-mcp",style:ao}),(0,r.jsx)("span",{style:ar(),children:t("desktop.mcpVisionLifecycle")}),(0,r.jsxs)("select",{value:y,onChange:e=>b(e.target.value),style:{...ao,fontFamily:"var(--font-mono)"},children:[(0,r.jsx)("option",{value:"eager",children:"eager"}),(0,r.jsx)("option",{value:"lazy",children:"lazy"})]}),(0,r.jsx)("span",{style:ar(),children:t("desktop.mcpVisionTransport")}),(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)",fontFamily:"var(--font-mono)",padding:"7px 0"},children:t("desktop.mcpVisionTransportFixed")})]})}),(0,r.jsx)(iZ,{children:(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"6px 0",flexWrap:"wrap"},children:[(0,r.jsx)("button",{type:"button",onClick:()=>void U(),disabled:w,style:{...an,cursor:w?"wait":"pointer"},children:w?t("desktop.saving"):t("desktop.mcpVisionSaveReg")}),K&&(0,r.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,r.jsx)("span",{style:{color:"#22c55e",fontSize:12},children:t("desktop.mcpVisionSavedReg")}),z&&(0,r.jsx)("span",{style:{color:"#22c55e",fontSize:12},children:t("desktop.mcpVisionRemoved")}),S&&(0,r.jsx)("span",{style:{color:"#ef4444",fontSize:12},children:S})]})}),(0,r.jsx)(iZ,{children:(0,r.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)",padding:"10px 0 2px"},children:t("desktop.mcpVisionModelConfig")})}),(0,r.jsx)(iZ,{children:(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"minmax(120px, 180px) 1fr",gap:8,alignItems:"center",padding:"6px 0"},children:[(0,r.jsx)("span",{style:ar(),children:t("desktop.mcpVisionProvider")}),(0,r.jsx)("input",{value:M.provider,onChange:e=>P(t=>({...t,provider:e.target.value})),style:ao}),(0,r.jsx)("span",{style:ar(),children:t("desktop.mcpVisionBaseUrl")}),(0,r.jsx)("input",{value:M.baseUrl,onChange:e=>P(t=>({...t,baseUrl:e.target.value})),style:ao}),(0,r.jsx)("span",{style:ar(),children:t("desktop.mcpVisionApiKey")}),(0,r.jsx)("input",{type:"password",value:D,onChange:e=>F(e.target.value),placeholder:M.hasApiKey?"••••••••":"API key",style:ao}),(0,r.jsx)("span",{style:ar(),children:t("desktop.mcpVisionModel")}),(0,r.jsx)("input",{value:M.model,onChange:e=>P(t=>({...t,model:e.target.value})),style:ao}),(0,r.jsx)("span",{style:ar(),children:t("desktop.mcpVisionMaxTokens")}),(0,r.jsx)("input",{type:"number",min:1,value:M.maxTokens,onChange:e=>P(t=>({...t,maxTokens:Number(e.target.value)||1})),style:ao})]})}),(0,r.jsx)(iQ,{children:(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:8,padding:"6px 0"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:[(0,r.jsx)("button",{type:"button",onClick:()=>void q(),disabled:N,style:{...an,cursor:N?"wait":"pointer"},children:N?t("desktop.saving"):t("desktop.mcpVisionSaveModel")}),(0,r.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,r.jsx)("span",{style:{color:"#22c55e",fontSize:12},children:t("desktop.mcpVisionSavedModel")}),u&&(0,r.jsx)("span",{style:{color:"#22c55e",fontSize:12},children:t("desktop.mcpVisionRestarted")}),A&&(0,r.jsx)("span",{style:{color:"#ef4444",fontSize:12},children:A}),c&&(0,r.jsx)("span",{style:{color:"#ef4444",fontSize:12},children:c})]}),(0,r.jsxs)(i0,{children:[t("desktop.mcpVisionModelNote"),W&&(0,r.jsx)("div",{style:{marginTop:4,fontFamily:"var(--font-mono)",fontSize:10},children:W}),x&&(0,r.jsx)("div",{style:{fontFamily:"var(--font-mono)",fontSize:10},children:x})]})]})})]}):(0,r.jsx)(iQ,{children:(0,r.jsx)("div",{style:{padding:"8px 0",fontSize:12,color:"var(--text-muted)"},children:t("desktop.loading")})})]})}function ai({sessionId:e,onApplied:t}){let{t:o}=(0,E.s)(),[s,i]=(0,n.useState)(!1),[a,l]=(0,n.useState)(!1),[d,c]=(0,n.useState)(null),p=(0,n.useCallback)(async()=>{if(e){i(!0),c(null),l(!1);try{await sT(e,{type:"reload"}),l(!0),await t?.()}catch(e){c(e instanceof Error?e.message:String(e))}finally{i(!1)}}},[e,t]),u=s||!e;return(0,r.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[(0,r.jsx)("button",{type:"button",onClick:()=>void p(),disabled:u,title:o(e?"desktop.applyNowTitle":"desktop.applyNowNoSession"),style:{padding:"7px 12px",background:"none",border:"1px solid var(--border)",borderRadius:6,color:"var(--text-muted)",cursor:u?"not-allowed":"pointer",fontSize:12,opacity:u?.5:1,whiteSpace:"nowrap"},children:o(s?"desktop.applyNowApplying":"desktop.applyNow")}),a&&(0,r.jsx)("span",{style:{color:"#22c55e",fontSize:12},children:o("desktop.applyNowDone")}),d&&(0,r.jsx)("span",{style:{color:"#ef4444",fontSize:12},children:d})]})}let aa=["stdio","sse","http"],al=["eager","lazy"],ad={name:"",command:"",args:"",transport:"stdio",lifecycle:"eager",requestTimeoutMs:"",env:""},ac={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 ap(){return{fontSize:12,color:"var(--text-muted)"}}function au(e,t){return{fontSize:10,padding:"1px 6px",borderRadius:3,background:t,color:e,flexShrink:0,textTransform:"capitalize"}}function ag({sessionId:e}){let{t}=(0,E.s)(),[o,s]=(0,n.useState)({}),[i,a]=(0,n.useState)(""),[l,d]=(0,n.useState)(!1),[c,p]=(0,n.useState)(null),[u,h]=(0,n.useState)(null),[f,m]=(0,n.useState)(ad),[k,v]=(0,n.useState)(!1),[y,b]=(0,n.useState)(null),[w,S]=(0,n.useState)(!1),C=(0,n.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,n.useEffect)(()=>{C()},[C]);let T=(0,n.useCallback)(()=>{m(ad),h({name:"",isNew:!0}),b(null),S(!1)},[]),R=(0,n.useCallback)((e,t)=>{m({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),S(!1)},[]),z=(0,n.useCallback)(async()=>{if(u){v(!0),b(null),S(!1);try{let e=f.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===at)return void b(t("desktop.mcpVisionNameReserved"));let r=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:aa.includes(e.transport)?e.transport:"stdio",lifecycle:al.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}}(f);if(r.error||!r.server)return void b(r.error??"Invalid server");let n={...o};u.isNew?n[e]=r.server:(delete n[u.name],n[f.name.trim()||u.name]=r.server);let i=await fetch("/api/mcp",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({mcpServers:n})}),a=await i.json();if(!i.ok||a.error)throw Error(a.error??`HTTP ${i.status}`);s(n),h(null),S(!0)}catch(e){b(e instanceof Error?e.message:String(e))}finally{v(!1)}}},[u,f,o,t]),I=(0,n.useCallback)(async e=>{v(!0),b(null);try{let t={...o};delete t[e];let r=await fetch("/api/mcp",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({mcpServers:t})}),n=await r.json();if(!r.ok||n.error)throw Error(n.error??`HTTP ${r.status}`);s(t),S(!0)}catch(e){b(e instanceof Error?e.message:String(e))}finally{v(!1)}},[o]),M=(0,n.useCallback)((e,t)=>{m(o=>({...o,[e]:t}))},[]),P=Object.entries(o).filter(([e])=>e!==at);return(0,r.jsx)("div",{style:{flex:1,overflow:"auto",minWidth:0,padding:"20px 22px",display:"flex",flexDirection:"column",gap:16},children:(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:l?c?(0,r.jsx)("div",{style:{fontSize:12,color:"#ef4444"},children:c}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12},children:[(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:14,fontWeight:700,color:"var(--text)"},children:t("desktop.mcpServers")}),(0,r.jsx)("div",{style:{fontSize:11,color:"var(--text-dim)",fontFamily:"var(--font-mono)",marginTop:2,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:i})]}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10,flexShrink:0},children:[(0,r.jsx)(ai,{sessionId:e,onApplied:C}),(0,r.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,r.jsx)(x.c,{size:13,"aria-hidden":"true"}),t("desktop.mcpAddServer")]})]})]}),(0,r.jsx)(i0,{children:t("desktop.mcpRestartNote")}),(0,r.jsx)(as,{sessionId:e}),0!==P.length||u?P.map(([e,o])=>(0,r.jsx)(iX,{children:(0,r.jsx)(iQ,{children:(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"12px 0",minWidth:0},children:[(0,r.jsxs)("div",{style:{minWidth:0,flex:1},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[(0,r.jsx)("span",{style:{fontSize:13,fontWeight:600,color:"var(--text)",fontFamily:"var(--font-mono)"},children:e}),(0,r.jsx)("span",{style:au("var(--accent)","rgba(37,99,235,0.12)"),children:o.transport??"stdio"}),(0,r.jsx)("span",{style:au("#d97706","rgba(245,158,11,0.12)"),children:o.lifecycle??"lazy"})]}),(0,r.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,r.jsxs)("div",{style:{display:"flex",gap:6,flexShrink:0},children:[(0,r.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,r.jsx)(g.I,{size:12,"aria-hidden":"true"}),t("desktop.mcpEdit")]}),(0,r.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,r.jsx)(j.l,{size:12,"aria-hidden":"true"})})]})]})})},e)):(0,r.jsx)(iX,{children:(0,r.jsx)(iQ,{children:(0,r.jsx)("div",{style:{padding:"14px 0",fontSize:12,color:"var(--text-dim)"},children:o[at]?t("desktop.mcpEmptyOther"):t("desktop.mcpEmpty")})})}),u&&(0,r.jsxs)(iX,{children:[(0,r.jsx)(iZ,{children:(0,r.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,r.jsx)(iZ,{children:(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"minmax(150px, 220px) 1fr",gap:"8px 12px",alignItems:"center",padding:"8px 0"},children:[(0,r.jsx)("span",{style:ap(),children:t("desktop.mcpServerName")}),(0,r.jsx)("input",{value:f.name,onChange:e=>M("name",e.target.value),disabled:!u.isNew,placeholder:"my-server",style:{...ac,opacity:u.isNew?1:.5}}),(0,r.jsxs)("span",{style:ap(),children:[t("desktop.mcpCommand")," *"]}),(0,r.jsx)("input",{value:f.command,onChange:e=>M("command",e.target.value),placeholder:"npx @modelcontextprotocol/server-foo",style:ac}),(0,r.jsx)("span",{style:ap(),children:t("desktop.mcpArgs")}),(0,r.jsx)("textarea",{value:f.args,onChange:e=>M("args",e.target.value),placeholder:"--port 3000\n--verbose",rows:3,style:{...ac,resize:"vertical",lineHeight:1.5}}),(0,r.jsx)("span",{style:ap(),children:t("desktop.mcpTransport")}),(0,r.jsx)("select",{value:f.transport,onChange:e=>M("transport",e.target.value),style:{...ac,fontFamily:"var(--font-mono)"},children:aa.map(e=>(0,r.jsx)("option",{value:e,children:e},e))}),(0,r.jsx)("span",{style:ap(),children:t("desktop.mcpLifecycle")}),(0,r.jsx)("select",{value:f.lifecycle,onChange:e=>M("lifecycle",e.target.value),style:{...ac,fontFamily:"var(--font-mono)"},children:al.map(e=>(0,r.jsx)("option",{value:e,children:e},e))}),(0,r.jsx)("span",{style:ap(),children:t("desktop.mcpRequestTimeoutMs")}),(0,r.jsx)("input",{type:"number",min:1,value:f.requestTimeoutMs,onChange:e=>M("requestTimeoutMs",e.target.value),placeholder:"300000",style:ac}),(0,r.jsx)("span",{style:ap(),children:t("desktop.mcpEnv")}),(0,r.jsx)("textarea",{value:f.env,onChange:e=>M("env",e.target.value),placeholder:'{\n "API_KEY": "..."\n}',rows:3,style:{...ac,resize:"vertical",lineHeight:1.5}})]})}),(0,r.jsx)(iQ,{children:(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"10px 0"},children:[(0,r.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,r.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,r.jsx)("span",{style:{color:"#ef4444",fontSize:12},children:y})]})})]}),w&&!u&&(0,r.jsx)("div",{style:{fontSize:12,color:"#22c55e"},children:t("desktop.mcpSavedRestart")})]}):(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)"},children:t("desktop.loading")})})})}var ah=o(9210);function af(){let{t:e}=(0,E.s)(),[t,o]=(0,n.useState)(null),[s,i]=(0,n.useState)([]),[a,l]=(0,n.useState)(!0),[d,c]=(0,n.useState)(!1),[p,u]=(0,n.useState)(!1),[g,h]=(0,n.useState)(null);(0,n.useEffect)(()=>{fetch("/api/settings/title-model").then(e=>e.json()).then(e=>{o(e.value),i(e.models??[])}).catch(()=>{}).finally(()=>l(!1))},[]);let f=null!==t&&!s.some(e=>e.label===t),x=(0,n.useCallback)(async t=>{c(!0),h(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})}),r=await e.json();if(!e.ok||r.error)return void h(r.error??`HTTP ${e.status}`);o(r.value??null),u(!0),setTimeout(()=>u(!1),2e3)}catch{h(String(e("desktop.titleModelSaveError")))}finally{c(!1)}},[e]),m=[...new Set(s.map(e=>e.provider))];return(0,r.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,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:[(0,r.jsx)("span",{style:{fontSize:12,fontWeight:600,color:"var(--text)",whiteSpace:"nowrap"},children:e("desktop.titleModel")}),(0,r.jsxs)("select",{value:t??"",disabled:a||d,onChange:e=>x(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,r.jsx)("option",{value:"",children:e("desktop.titleModelFollowSession")}),f&&null!==t&&(0,r.jsxs)("option",{value:t,style:{color:"#ef4444"},children:[t,"(",e("desktop.titleModelInvalid"),")"]}),m.map(e=>(0,r.jsx)("optgroup",{label:e,children:s.filter(t=>t.provider===e).map(e=>(0,r.jsxs)("option",{value:e.label,children:[e.name||e.id,e.reasoning?"(reasoning)":""]},e.label))},e))]}),d&&(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)"},children:"…"}),!d&&p&&(0,r.jsx)("span",{style:{fontSize:11,color:"#4ade80"},children:e("desktop.titleModelSaved")})]}),(0,r.jsx)("p",{style:{margin:0,fontSize:11,color:"var(--text-muted)",lineHeight:1.5},children:e("desktop.titleModelDescription")}),g&&(0,r.jsx)("p",{style:{margin:0,fontSize:11,color:"#ef4444",lineHeight:1.5},children:g}),f&&null!==t&&(0,r.jsxs)("p",{style:{margin:0,fontSize:11,color:"#ef4444",lineHeight:1.5},children:[t,"(",e("desktop.titleModelInvalid"),")"]})]})}let ax=["name","reasoning","contextWindow","maxTokens","thinkingLevelMap","hidden"];function am(e){if(""===e.trim())return;let t=Number(e);return Number.isFinite(t)&&t>0?t:void 0}function ak(e){let t=am(e.contextWindow??""),o=am(e.maxTokens??""),r=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}:{},...r?{thinkingLevelMap:r}:{},..."boolean"==typeof e.hidden?{hidden:e.hidden}:{}}}function av({providerId:e,onRegisterFlush:t,onConfigChange:o}){let{t:s}=(0,E.s)(),i=$(),[a,l]=(0,n.useState)([]),[d,c]=(0,n.useState)({}),[p,u]=(0,n.useState)({}),[g,h]=(0,n.useState)(new Set),[f,x]=(0,n.useState)(!0),[m,k]=(0,n.useState)(!1),[v,y]=(0,n.useState)(null),[b,w]=(0,n.useState)(!1),[j,S]=(0,n.useState)(null),C=(0,n.useRef)(d),T=(0,n.useRef)(p),R=(0,n.useRef)(a),z=(0,n.useRef)(g),I=(0,n.useRef)(0),M=(0,n.useRef)(null);C.current=d,T.current=p,R.current=a,z.current=g,(0,n.useEffect)(()=>{let t=!1;return x(!0),y(null),(async()=>{try{let o=await fetch(`/api/models-config/builtin?provider=${encodeURIComponent(e)}`),r=await o.json();if(!o.ok||r.error)throw Error(r.error??`HTTP ${o.status}`);if(t)return;let n={};for(let e of r.models){let t=r.overrides[e.id]??{};n[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(r.models),c(n),u(n),h(new Set)}catch(e){t||y(e instanceof Error?e.message:String(e))}finally{t||x(!1)}})(),()=>{t=!0}},[e]);let P=(0,n.useCallback)((e,t)=>{I.current+=1,c(o=>({...o,[e]:{...o[e]??{},...t}})),h(t=>new Set(t).add(e))},[]),D=(0,n.useCallback)(async()=>{let t=M.current;if(t)return t;let r=(async()=>{let t=new Set(z.current);if(0===t.size)return;let r=I.current,n={...C.current},s={},i={};for(let e of R.current){let t=n[e.id],o=T.current[e.id];t&&(s[e.id]=ak(t)),o&&(i[e.id]=ak(o))}let a=function(e,t,o){let r={};for(let n of e){let e=t[n],s=o[n];if(!e||!s)continue;let i={};for(let t of ax){let o=e[t],r=s[t];JSON.stringify(o)!==JSON.stringify(r)&&(i[t]=void 0===o?null:o)}Object.keys(i).length>0&&(r[n]=i)}return r}(t,s,i);if(0===Object.keys(a).length)return void h(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=n[e];t&&(l[e]={...t})}T.current=l,u(l),I.current===r&&h(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=r;try{await r}finally{M.current===r&&(M.current=null)}},[o,e]);return((0,n.useEffect)(()=>{if(t)return t(e,D)??void 0},[t,e,D]),f)?(0,r.jsx)("div",{style:{borderTop:"1px solid var(--border)",marginTop:14,paddingTop:12},children:(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-dim)"},children:s("desktop.modelsLoading")})}):(0,r.jsxs)("div",{style:{borderTop:"1px solid var(--border)",marginTop:14,paddingTop:12,display:"flex",flexDirection:"column",gap:10},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)"},children:s("desktop.builtinModelsTitle")}),v&&(0,r.jsx)("p",{style:{margin:0,fontSize:11,color:"#f87171"},children:v}),0===a.length&&!v&&(0,r.jsx)("p",{style:{margin:0,fontSize:11,color:"var(--text-dim)"},children:s("desktop.builtinModelsEmpty")}),(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:8},children:a.map(e=>{let t=d[e.id]??{},o=j===e.id,n=g.has(e.id);return(0,r.jsxs)("div",{style:{border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-panel)",padding:"8px 10px"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[(0,r.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,n&&(0,r.jsx)("span",{style:{color:"var(--accent)",marginLeft:6},children:"•"})]}),(0,r.jsx)("code",{style:{fontSize:10,color:"var(--text-dim)",fontFamily:"var(--font-mono)"},children:e.id}),(t.reasoning??e.reasoning)&&(0,r.jsx)("span",{style:{fontSize:10,padding:"1px 6px",borderRadius:8,background:"var(--bg-selected)",color:"var(--text-muted)"},children:"reasoning"}),(0,r.jsxs)("span",{style:{fontSize:11,color:"var(--text-muted)"},children:[s("desktop.builtinModelsContext"),": ",(0,r.jsx)("b",{children:t.contextWindow?Number(t.contextWindow).toLocaleString():"—"})," \xb7 ",s("desktop.builtinModelsMaxTokens"),": ",(0,r.jsx)("b",{children:t.maxTokens?Number(t.maxTokens).toLocaleString():"—"})]})]}),o&&(0,r.jsxs)("div",{style:{marginTop:10,display:"flex",flexDirection:"column",gap:10},children:[(0,r.jsxs)("label",{style:{display:"flex",gap:6,alignItems:"center",fontSize:12,color:"var(--text)",width:"100%"},children:[s("desktop.modelsName"),(0,r.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,r.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,r.jsx)("input",{type:"checkbox",checked:!0===t.hidden,onChange:t=>P(e.id,{hidden:t.target.checked})}),s("desktop.builtinModelsHide")]})]}),(0,r.jsxs)("div",{style:{display:"flex",gap:16,flexWrap:"wrap",flexDirection:i?"column":"row",alignItems:i?"flex-start":"center"},children:[(0,r.jsxs)("label",{style:{display:"flex",gap:6,alignItems:"center",fontSize:12,color:"var(--text)",cursor:"pointer"},children:[(0,r.jsx)("input",{type:"checkbox",checked:!0===t.reasoning,onChange:t=>P(e.id,{reasoning:t.target.checked})}),s("desktop.builtinModelsReasoning")]}),(0,r.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,r.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,r.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,r.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,r.jsx)("div",{style:{fontSize:11,fontWeight:600,color:"var(--text-dim)"},children:s("desktop.builtinModelsThinking")}),(0,r.jsx)(aD,{value:t.thinkingLevelMap,onChange:t=>P(e.id,{thinkingLevelMap:t})})]})]},e.id)})}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[(0,r.jsx)("button",{type:"button",onClick:()=>{D().catch(()=>{})},disabled:m||0===g.size,style:{alignSelf:"flex-start",padding:"5px 14px",background:g.size>0&&!m?"var(--accent)":"var(--bg-panel)",border:"none",borderRadius:5,color:g.size>0&&!m?"#fff":"var(--text-dim)",cursor:g.size>0&&!m?"pointer":"not-allowed",fontSize:12,fontWeight:600},children:m?s("desktop.modelsSaving"):b?s("desktop.modelsSaved"):s("desktop.modelsSave")}),g.size>0&&(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)"},children:s("desktop.builtinModelsDirty",{count:g.size})})]})]})}let ay=["openai-completions","openai-responses","anthropic-messages","google-generative-ai"];function ab(){let{t:e}=(0,E.s)();return(0,n.useCallback)((t,o)=>e(t,o),[e])}function aw({label:e,children:t}){return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,r.jsx)("label",{style:{fontSize:11,color:"var(--text-muted)",fontWeight:500},children:e}),t]})}let aj={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 aS({value:e,onChange:t,placeholder:o,mono:n}){return(0,r.jsx)("input",{value:e,onChange:e=>t(e.target.value),placeholder:o,style:{...aj,fontFamily:n?"var(--font-mono)":"inherit"}})}function aC({value:e,onChange:t,placeholder:o,mono:s,onKeyDown:i,autoComplete:a="off",spellCheck:l=!1,style:d}){let c=ab(),[p,u]=(0,n.useState)(!1);return(0,n.useEffect)(()=>{e||u(!1)},[e]),(0,r.jsxs)("div",{style:{position:"relative",width:"100%",...d},children:[(0,r.jsx)("input",{type:p?"text":"password",value:e,onChange:e=>t(e.target.value),onKeyDown:i,placeholder:o,style:{...aj,paddingRight:34,fontFamily:s?"var(--font-mono)":"inherit"},autoComplete:a,spellCheck:l}),(0,r.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,r.jsx)(ah.G,{size:15}):(0,r.jsx)(r5.b,{size:15})})]})}function aT({value:e,onChange:t,placeholder:o}){return(0,r.jsx)("input",{type:"number",value:e,onChange:e=>t(e.target.value),placeholder:o,style:aj})}function aR({value:e,onChange:t,options:o,required:n}){let s=ab();return(0,r.jsxs)("select",{value:e,onChange:e=>t(e.target.value),style:{...aj,color:e?"var(--text)":"var(--text-dim)"},children:[!n&&(0,r.jsx)("option",{value:"",children:s("desktop.modelsInheritNone")}),o.map(e=>(0,r.jsx)("option",{value:e,children:e},e))]})}function az({label:e,checked:t,onChange:o}){return(0,r.jsxs)("label",{style:{display:"flex",alignItems:"center",gap:6,cursor:"pointer",fontSize:12,color:"var(--text-muted)"},children:[(0,r.jsx)("input",{type:"checkbox",checked:t,onChange:e=>o(e.target.checked),style:{width:13,height:13,accentColor:"var(--accent)",cursor:"pointer"}}),e]})}function aI({children:e}){return(0,r.jsx)("div",{style:{fontSize:11,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:2},children:e})}function aM({name:e,provider:t,onChange:o,onRename:s,onDelete:i,onAddModels:a}){let l=ab(),[d,c]=(0,n.useState)(e),[p,u]=(0,n.useState)({phase:"idle"}),[g,h]=(0,n.useState)(""),[f,x]=(0,n.useState)([]),m=(0,n.useRef)(0),k=(0,n.useRef)(null);(0,n.useEffect)(()=>c(e),[e]);let v=(e,r)=>o({...t,[e]:r});(0,n.useEffect)(()=>{t.api||o({...t,api:"openai-completions"})},[t.api]),(0,n.useEffect)(()=>{m.current+=1,u({phase:"idle"}),h(""),x([])},[e,t.baseUrl,t.api,t.apiKey]);let y=(0,n.useCallback)(async()=>{if(!t.baseUrl?.trim()||"loading"===p.phase)return;let o=++m.current;u({phase:"loading"}),x([]);try{let r=await fetch("/api/models-config/discover",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({providerName:e,provider:{...t,models:void 0}})}),n=await r.json();if(o!==m.current)return;if(!r.ok||n.error||!n.models)return void u({phase:"error",message:n.error??`HTTP ${r.status}`});u({phase:"success",models:n.models,endpoint:n.endpoint??t.baseUrl})}catch(e){if(o!==m.current)return;u({phase:"error",message:e instanceof Error?e.message:String(e)})}},[p.phase,e,t]),b=new Set((t.models??[]).map(e=>e.id)),w="success"===p.phase?p.models:[],j=g.trim().toLocaleLowerCase(),S=w.filter(e=>!j||e.id.toLocaleLowerCase().includes(j)||e.name?.toLocaleLowerCase().includes(j)),C=S.slice(0,300),T=C.filter(e=>!b.has(e.id)).map(e=>e.id),R=f.filter(e=>!b.has(e)).length,z=T.length>0&&T.every(e=>f.includes(e)),I=!z&&T.some(e=>f.includes(e));return(0,n.useEffect)(()=>{k.current&&(k.current.indeterminate=I)},[I]),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[(0,r.jsx)(aI,{children:l("desktop.modelsProvider")}),(0,r.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:l("desktop.delete")})]}),(0,r.jsxs)(aw,{label:l("desktop.modelsProviderName"),children:[(0,r.jsx)(aS,{value:d,onChange:c,placeholder:"provider-name",mono:!0}),d!==e&&d.trim()&&(0,r.jsx)("button",{onClick:()=>s(d.trim()),style:{marginTop:4,padding:"3px 10px",background:"var(--accent)",border:"none",borderRadius:4,color:"#fff",cursor:"pointer",fontSize:11,alignSelf:"flex-start"},children:l("desktop.rename")})]}),(0,r.jsx)(aw,{label:l("desktop.modelsBaseUrl"),children:(0,r.jsx)(aS,{value:t.baseUrl??"",onChange:e=>v("baseUrl",e||void 0),placeholder:"http(s)://host:port/v1",mono:!0})}),(0,r.jsxs)(aw,{label:l("desktop.modelsApiKey"),children:[(0,r.jsx)(aC,{value:t.apiKey??"",onChange:e=>v("apiKey",e||void 0),placeholder:l("desktop.modelsApiKeyPlaceholder"),mono:!0}),(0,r.jsx)("span",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:l("desktop.modelsApiKeyHelp")})]}),(0,r.jsx)(aw,{label:l("desktop.modelsApi"),children:(0,r.jsx)(aR,{value:t.api??"openai-completions",onChange:e=>v("api",e),options:ay,required:!0})}),(0,r.jsxs)("div",{style:{borderTop:"1px solid var(--border)",paddingTop:14,display:"flex",flexDirection:"column",gap:10},children:["success"!==p.phase&&(0,r.jsx)("button",{onClick:y,disabled:!t.baseUrl?.trim()||"loading"===p.phase,style:{alignSelf:"flex-start",height:30,padding:"0 12px",border:"1px solid var(--border)",borderRadius:5,background:"var(--bg-panel)",color:t.baseUrl?.trim()&&"loading"!==p.phase?"var(--text-muted)":"var(--text-dim)",cursor:t.baseUrl?.trim()&&"loading"!==p.phase?"pointer":"not-allowed",fontSize:11},children:"loading"===p.phase?l("desktop.modelsDiscoveryFetching"):l("desktop.modelsDiscoveryFetch")}),"error"===p.phase&&(0,r.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:p.message}),"success"===p.phase&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("input",{value:g,onChange:e=>h(e.target.value),placeholder:l("desktop.modelsDiscoveryFilterPlaceholder",{count:p.models.length}),"aria-label":l("desktop.modelsDiscoveryFilter"),style:{...aj,width:"100%",minWidth:0}}),(0,r.jsxs)("div",{style:{maxHeight:220,overflowY:"auto",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-panel)"},children:[(0,r.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:T.length?"pointer":"default",color:"var(--text-muted)",fontSize:10,fontWeight:600},children:[(0,r.jsx)("input",{ref:k,type:"checkbox",checked:z,disabled:0===T.length,onChange:()=>{let e=new Set(T);x(t=>z?t.filter(t=>!e.has(t)):Array.from(new Set([...t,...T])))},style:{width:13,height:13,accentColor:"var(--accent)",flexShrink:0}}),l("desktop.modelsDiscoverySelectShown")]}),0===C.length?(0,r.jsx)("div",{style:{padding:12,color:"var(--text-dim)",fontSize:11},children:l("desktop.modelsDiscoveryNoMatches")}):C.map((e,t)=>{let o=b.has(e.id),n=f.includes(e.id);return(0,r.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,r.jsx)("input",{type:"checkbox",checked:n||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,r.jsxs)("span",{style:{minWidth:0,flex:1},children:[(0,r.jsx)("span",{style:{display:"block",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text)",fontSize:11},children:e.name??e.id}),e.name&&(0,r.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,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:10},children:l("desktop.modelsDiscoveryAdded")})]},e.id)})]}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:10},children:[(0,r.jsx)("span",{title:p.endpoint,style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontSize:10},children:S.length>C.length?l("desktop.modelsDiscoveryShowing",{shown:C.length,total:S.length}):l("desktop.modelsDiscoveryFetched",{count:p.models.length})}),(0,r.jsx)("button",{onClick:()=>{if("success"!==p.phase)return;let e=new Set(f),t=p.models.filter(t=>e.has(t.id)&&!b.has(t.id));0!==t.length&&(a(t),x([]))},disabled:0===R,style:{height:28,padding:"0 11px",border:"none",borderRadius:5,background:R?"var(--accent)":"var(--bg-panel)",color:R?"#fff":"var(--text-dim)",cursor:R?"pointer":"not-allowed",fontSize:11,fontWeight:600,whiteSpace:"nowrap"},children:R?l("desktop.modelsDiscoveryAddSelectedCount",{count:R}):l("desktop.modelsDiscoveryAddSelected")})]})]})]})]})}let aE=["off","minimal","low","medium","high","xhigh","max"],aP={off:"var(--text-dim)",minimal:"var(--text-muted)",low:"#60a5fa",medium:"#a78bfa",high:"#f472b6",xhigh:"#fb923c",max:"#ef4444"};function aD({value:e,onChange:t}){let o=ab(),n=e??{},s=(e,o)=>{let r={...n};"omit"===o?delete r[e]:r[e]=o,t(Object.keys(r).length?r:void 0)};return(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:2},children:aE.map(e=>{let t=n[e],i=e in n?null===t?"null":"string":"omit",a="string"==typeof t?t:"",l=aP[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,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"5px 4px",borderRadius:6,background:"transparent",border:"1px solid transparent"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:5,width:68,flexShrink:0},children:[(0,r.jsx)("span",{style:{width:6,height:6,borderRadius:"50%",background:l,flexShrink:0,opacity:"null"===i?.3:1}}),(0,r.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,r.jsxs)("div",{style:{display:"flex",borderRadius:5,border:"1px solid var(--border)",overflow:"hidden",flexShrink:0},children:[(0,r.jsx)("button",{onClick:()=>s(e,"omit"),style:{...d,..."omit"===i?c:{}},children:o("desktop.modelsDefault")}),(0,r.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,r.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,r.jsx)("button",{onClick:()=>s(e,a||e),style:{...d,..."string"===i?c:{},borderRight:"1px solid var(--border)",flexShrink:0},children:o("desktop.modelsCustom")}),(0,r.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 aF={thinkingFormat:"deepseek",requiresReasoningContentOnAssistantMessages:!0};function aW({providerName:e,provider:t,model:o,onChange:s,onDelete:i}){let a=ab(),[l,d]=(0,n.useState)({phase:"idle"}),[c,p]=(0,n.useState)({phase:"idle"}),g=(0,n.useRef)(0),h=(0,n.useRef)(null),f=(e,t)=>s({...o,[e]:t}),x=(()=>{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,n.useEffect)(()=>{d({phase:"idle"})},[e,t.baseUrl,t.api,t.apiKey,o.id,o.api]);let m=(0,n.useCallback)(async()=>{if(o.id.trim()&&"testing"!==l.phase){d({phase:"testing"});try{let r=await fetch("/api/models-config/test",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({providerName:e,provider:t,model:o})}),n=await r.json();if(!r.ok||!n.ok)return void d({phase:"error",message:n.error??`HTTP ${r.status}`,latencyMs:n.latencyMs,status:n.status});d({phase:"success",latencyMs:n.latencyMs,status:n.status,responseText:n.responseText})}catch(e){d({phase:"error",message:e instanceof Error?e.message:String(e)})}}},[o,t,e,l.phase]);(0,n.useEffect)(()=>{g.current+=1,p({phase:"idle"}),h.current=null},[e,t.baseUrl,o.id]);let k=(0,n.useCallback)(async()=>{let r=o.id.trim();if(!r||"loading"===c.phase)return;let n=++g.current;p({phase:"loading"});try{let i=new URLSearchParams({q:r,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(n!==g.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},r=0;if(!e.name?.trim()&&t.name&&(o.name=t.name,r+=1),void 0===e.reasoning&&!0===t.reasoning&&(o.reasoning=!0,r+=1),!e.input?.length&&t.input?.length&&(o.input=[...t.input],r+=1),void 0===e.contextWindow&&void 0!==t.contextWindow&&(o.contextWindow=t.contextWindow,r+=1),void 0===e.maxTokens&&void 0!==t.maxTokens&&(o.maxTokens=t.maxTokens,r+=1),t.cost){let n={...e.cost??{}},s=!1;for(let e of["input","output","cacheRead","cacheWrite"])void 0===n[e]&&void 0!==t.cost[e]&&(n[e]=t.cost[e],s=!0,r+=1);s&&(o.cost=n)}return{model:o,appliedCount:r}}(o,l.recommendation.preset);d.appliedCount>0&&(h.current=o,s(d.model)),p({phase:"success",recommendation:l.recommendation,appliedCount:d.appliedCount})}catch(e){if(n!==g.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,r=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`${r} \xb7 ${e}`}let n="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`${r} \xb7 ${n}`})(),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,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[(0,r.jsx)(aI,{children:a("desktop.modelsModelSection")}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[x&&(0,r.jsx)("span",{title:x,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:x}),(0,r.jsxs)("button",{onClick:m,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,r.jsx)(u.S,{size:11}),"testing"===l.phase?a("desktop.modelsTesting"):"success"===l.phase?a("desktop.modelsOk"):a("desktop.modelsTest")]}),(0,r.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,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10},children:[(0,r.jsx)(aw,{label:a("desktop.modelsIdRequired"),children:(0,r.jsx)(aS,{value:o.id,onChange:e=>f("id",e),placeholder:"model-id",mono:!0})}),(0,r.jsx)(aw,{label:a("desktop.modelsName"),children:(0,r.jsx)(aS,{value:o.name??"",onChange:e=>f("name",e||void 0),placeholder:a("desktop.modelsDisplayName")})})]}),(0,r.jsxs)("div",{style:{padding:"10px 0",borderTop:"1px solid var(--border)",borderBottom:"1px solid var(--border)"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[(0,r.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,r.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,r.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,r.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:y}),"success"===c.phase&&h.current&&(0,r.jsx)("button",{onClick:()=>{let e=h.current;e&&(h.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,r.jsx)(aw,{label:a("desktop.modelsApiOverride"),children:(0,r.jsx)(aR,{value:o.api??"",onChange:e=>f("api",e||void 0),options:ay})}),(0,r.jsxs)("div",{style:{display:"flex",gap:20,flexWrap:"wrap"},children:[(0,r.jsx)(az,{label:a("desktop.modelsReasoningThinking"),checked:o.reasoning??!1,onChange:e=>f("reasoning",e||void 0)}),(0,r.jsx)(az,{label:a("desktop.modelsImageInput"),checked:o.input?.includes("image")??!1,onChange:e=>f("input",e?["text","image"]:void 0)})]}),o.reasoning&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(az,{label:a("desktop.modelsDeepSeekCompat"),checked:o.compat?.thinkingFormat==="deepseek",onChange:e=>s(function(e,t){if(t)return{...e,compat:{...e.compat??{},...aF}};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,r.jsxs)("div",{children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:8},children:[(0,r.jsx)(aI,{children:a("desktop.modelsThinkingLevelMap")}),o.thinkingLevelMap&&(0,r.jsx)("button",{onClick:()=>f("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,r.jsx)(aD,{value:o.thinkingLevelMap,onChange:e=>f("thinkingLevelMap",e)})]})]}),(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10},children:[(0,r.jsx)(aw,{label:a("desktop.modelsContextWindow"),children:(0,r.jsx)(aT,{value:void 0!==o.contextWindow?String(o.contextWindow):"",onChange:e=>f("contextWindow",e?parseInt(e):void 0),placeholder:"128000"})}),(0,r.jsx)(aw,{label:a("desktop.modelsMaxOutputTokens"),children:(0,r.jsx)(aT,{value:void 0!==o.maxTokens?String(o.maxTokens):"",onChange:e=>f("maxTokens",e?parseInt(e):void 0),placeholder:"16384"})})]}),(0,r.jsxs)("div",{children:[(0,r.jsx)(aI,{children:a("desktop.modelsCostPerMillionTokens")}),(0,r.jsx)("div",{style:{marginTop:8,display:"grid",gridTemplateColumns:"1fr 1fr 1fr 1fr",gap:8},children:["input","output","cacheRead","cacheWrite"].map(e=>(0,r.jsx)(aw,{label:e,children:(0,r.jsx)(aT,{value:o.cost?.[e]!==void 0?String(o.cost[e]):"",onChange:t=>{let r;return r=parseFloat(t),void s({...o,cost:{...o.cost??{},[e]:isNaN(r)?void 0:r}})},placeholder:"0"})},e))})]})]})}function a$({provider:e,onRefresh:t,onRegisterBuiltinFlush:o,onBuiltinProviderChange:s}){let i=ab(),[a,l]=(0,n.useState)({phase:"idle"}),[d,c]=(0,n.useState)(""),p=(0,n.useRef)(null),u=(0,n.useRef)(null);(0,n.useEffect)(()=>{("auth"===a.phase||"prompt"===a.phase)&&setTimeout(()=>u.current?.focus(),50)},[a.phase]),(0,n.useEffect)(()=>{l({phase:"idle"}),c(""),p.current?.close(),p.current=null},[e.id]),(0,n.useEffect)(()=>()=>{p.current?.close()},[]);let g=(0,n.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 r=JSON.parse(e.data);"auth"===r.type?(l({phase:"auth",url:r.url,instructions:r.instructions??null,token:r.token}),window.open(r.url,"_blank","noopener,noreferrer")):"device_code"===r.type?(l({phase:"device_code",userCode:r.userCode,verificationUri:r.verificationUri,intervalSeconds:r.intervalSeconds??null,expiresInSeconds:r.expiresInSeconds??null}),window.open(r.verificationUri,"_blank","noopener,noreferrer")):"prompt_request"===r.type?l({phase:"prompt",message:r.message,placeholder:r.placeholder??null,token:r.token}):"select_request"===r.type?l({phase:"select",message:r.message,options:r.options??[],token:r.token}):"progress"===r.type?l({phase:"progress",message:r.message}):"success"===r.type?(o.close(),l({phase:"success"}),t()):"error"===r.type?(o.close(),l({phase:"error",message:r.message})):"cancelled"===r.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]),h=(0,n.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]),f=(0,n.useCallback)(async(t,o)=>{if(o.trim()){l({phase:"progress",message:i("desktop.modelsVerifying")});try{let r=await fetch(`/api/auth/login/${encodeURIComponent(e.id)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t,code:o.trim()})});if(!r.ok){let e=await r.json().catch(()=>({}));l({phase:"error",message:e.error??i("desktop.modelsServerError",{status:r.status})});return}c("")}catch(e){l({phase:"error",message:e instanceof Error?e.message:i("desktop.modelsNetworkError")})}}},[e.id,i]),x=(0,n.useCallback)(async(t,o)=>{l({phase:"progress",message:i("desktop.modelsContinuing")});try{let r=await fetch(`/api/auth/login/${encodeURIComponent(e.id)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t,code:o})});if(!r.ok){let e=await r.json().catch(()=>({}));l({phase:"error",message:e.error??i("desktop.modelsServerError",{status:r.status})})}}catch(e){l({phase:"error",message:e instanceof Error?e.message:i("desktop.modelsNetworkError")})}},[e.id,i]),m="connecting"===a.phase||"progress"===a.phase||"auth"===a.phase||"device_code"===a.phase||"prompt"===a.phase||"select"===a.phase;return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[(0,r.jsx)(aI,{children:i("desktop.modelsSubscription")}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:e.loggedIn?"#4ade80":"var(--border)",display:"inline-block"}}),(0,r.jsx)("span",{style:{fontSize:11,color:e.loggedIn?"#4ade80":"var(--text-dim)"},children:e.loggedIn?i("desktop.modelsConnected"):i("desktop.modelsNotConnected")})]})]}),(0,r.jsxs)("div",{style:{minHeight:48},children:["idle"===a.phase&&(0,r.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,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)"},children:i("desktop.modelsOpeningBrowser")}),"select"===a.phase&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:a.message}),(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:a.options.map(e=>(0,r.jsx)("button",{onClick:()=>x(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,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[(0,r.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,r.jsxs)("p",{style:{margin:0,fontSize:11,color:"var(--text-dim)",lineHeight:1.5},children:[i("desktop.modelsBrowserDidNotOpen")," ",(0,r.jsx)("a",{href:a.url,target:"_blank",rel:"noopener noreferrer",style:{color:"var(--accent)",wordBreak:"break-all"},children:i("desktop.modelsOpenLoginPage")}),"."]}),(0,r.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,r.jsx)("input",{ref:u,value:d,onChange:e=>c(e.target.value),onKeyDown:e=>{"Enter"===e.key&&f(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,r.jsx)("button",{onClick:()=>f(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,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:i("desktop.modelsOpenVerificationPage")}),(0,r.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,r.jsxs)("p",{style:{margin:0,fontSize:11,color:"var(--text-dim)",lineHeight:1.5},children:[(0,r.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,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)"},children:a.message}),"success"===a.phase&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"#4ade80"},children:i("desktop.modelsConnectedSuccessfully")}),"error"===a.phase&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"#f87171"},children:a.message})]}),(0,r.jsx)("div",{style:{display:"flex",gap:8},children:m?(0,r.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,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("button",{onClick:g,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,r.jsx)("button",{onClick:h,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,r.jsx)(av,{providerId:e.id,onRegisterFlush:o,onConfigChange:s})]})}function aN({provider:e,onRefresh:t,onRegisterBuiltinFlush:o,onBuiltinProviderChange:s}){let i=ab(),[a,l]=(0,n.useState)(""),[d,c]=(0,n.useState)(!1),[p,g]=(0,n.useState)(!1),[h,f]=(0,n.useState)(null),[x,m]=(0,n.useState)(!1);(0,n.useEffect)(()=>{l(""),f(null),m(!1)},[e.id]);let k=(0,n.useCallback)(async()=>{if(a.trim()){c(!0),f(null),m(!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()})}),r=await o.json();!o.ok||r.error?f(r.error??`HTTP ${o.status}`):(l(""),m(!0),setTimeout(()=>m(!1),2e3),t())}catch(e){f(String(e))}finally{c(!1)}}},[a,e.id,t]),v=(0,n.useCallback)(async()=>{g(!0),f(null);try{let t=await fetch(`/api/auth/api-key/${encodeURIComponent(e.id)}`,{method:"DELETE"}),o=await t.json();(!t.ok||o.error)&&f(409===t.status?i("desktop.modelsAuthenticationStateChanged"):o.error??`HTTP ${t.status}`)}catch(e){f(String(e))}finally{t(),g(!1)}},[e.id,t,i]);return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[(0,r.jsx)(aI,{children:i("desktop.modelsApiKey")}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:e.configured?"#4ade80":"var(--border)",display:"inline-block"}}),(0,r.jsx)("span",{style:{fontSize:11,color:e.configured?"#4ade80":"var(--text-dim)"},children:e.configured?i("desktop.modelsConfigured"):i("desktop.modelsNotConfigured")})]})]}),(0,r.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,r.jsx)(aw,{label:i("desktop.modelsApiKey"),children:(0,r.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,r.jsx)(aC,{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,r.jsxs)("button",{onClick:k,disabled:d||!a.trim()||x,style:{padding:"6px 12px",background:x?"#16a34a":a.trim()?"var(--accent)":"var(--bg-panel)",border:"none",borderRadius:5,color:a.trim()||x?"#fff":"var(--text-dim)",cursor:d||!a.trim()||x?"not-allowed":"pointer",fontSize:12,fontWeight:600,flexShrink:0,display:"flex",alignItems:"center",gap:5},children:[x&&(0,r.jsx)(u.S,{size:12}),x?i("desktop.modelsSaved"):d?i("desktop.modelsSaving"):i("desktop.modelsSave")]})]})}),h&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"#f87171"},children:h}),e.configured&&(0,r.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,r.jsx)(av,{providerId:e.id,onRegisterFlush:o,onConfigChange:s})]})}function aL({oauthProviders:e,apiKeyProviders:t,onSelectOAuth:o,onSelectApiKey:s,onAddCustom:i,onClose:a}){let l=ab(),[c,p]=(0,n.useState)(""),u=(0,n.useRef)(null);(0,n.useEffect)(()=>{setTimeout(()=>u.current?.focus(),30)},[]);let g=c.trim().toLowerCase(),h=e.filter(e=>!e.loggedIn&&(!g||e.name.toLowerCase().includes(g))),f=t.filter(e=>!e.configured&&(!g||e.displayName.toLowerCase().includes(g)||e.id.toLowerCase().includes(g))),m=!g||"custom".includes(g)||"openai-compatible".includes(g)||"anthropic-compatible".includes(g),k=h.length+f.length+ +!!m,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,r.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,r.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,r.jsxs)("div",{style:{padding:"10px 14px",borderBottom:"1px solid var(--border)",flexShrink:0,display:"flex",alignItems:"center",gap:8},children:[(0,r.jsx)(d.$,{size:13,style:{color:"var(--text-dim)",flexShrink:0}}),(0,r.jsx)("input",{ref:u,value:c,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,r.jsx)("div",{style:{flex:1,overflowY:"auto",padding:14},children:0===k?(0,r.jsx)("div",{style:{padding:"20px 0",fontSize:12,color:"var(--text-dim)",textAlign:"center"},children:l("desktop.modelsNoProvidersMatch")}):(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(min(240px, 100%), 1fr))",gap:8},children:[m&&(0,r.jsx)("div",{style:{gridColumn:"1 / -1",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:l("desktop.modelsCustom")}),m&&(0,r.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,r.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)",lineHeight:1.3,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:l("desktop.modelsCompatibleProvider")}),(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:l("desktop.modelsCustomEndpointFormat")})]}),(0,r.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,r.jsx)(x.c,{size:13,style:{color:"var(--text-dim)"}})})]}),h.length>0&&(0,r.jsx)("div",{style:{gridColumn:"1 / -1",paddingTop:6*!!m,fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:l("desktop.modelsSubscriptions")}),h.map(e=>(0,r.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,r.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)",lineHeight:1.3,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name}),(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:"OAuth"})]}),(0,r.jsx)(n$,{id:e.id,size:28})]},e.id)),f.length>0&&(0,r.jsx)("div",{style:{gridColumn:"1 / -1",paddingTop:6*(h.length>0),fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:l("desktop.modelsApiKey")}),f.map(e=>(0,r.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,r.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)",lineHeight:1.3,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.displayName}),(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:l("desktop.modelsCount",{count:e.modelCount})})]}),(0,r.jsx)(n$,{id:e.id,size:28})]},e.id))]})})]})})}function aA({embedded:e=!1,sessionId:t,onCloseAction:o,onSavedAction:s,onRegisterFlush:i}){let a=ab(),l=$(),[d,c]=(0,n.useState)({providers:{}}),[p,g]=(0,n.useState)(!0),[h,f]=(0,n.useState)(!1),[x,m]=(0,n.useState)(null),[k,v]=(0,n.useState)(!1),[y,b]=(0,n.useState)(null),[w,j]=(0,n.useState)([]),[S,T]=(0,n.useState)([]),[R,z]=(0,n.useState)(!1),[I,M]=(0,n.useState)({oauth:!1,apiKey:!1}),E=(0,n.useRef)({providers:{}}),P=(0,n.useRef)(new Map),D=(0,n.useRef)(0),F=(0,n.useRef)(!1);E.current=d;let W=(0,n.useCallback)(e=>{let t=e(E.current);return E.current=t,D.current+=1,c(t),t},[]),N=(0,n.useCallback)(()=>{fetch("/api/auth/combined").then(e=>e.json()).then(e=>{j(e.oauth??[]),T(e.apiKey??[])}).catch(()=>{}).finally(()=>M({oauth:!0,apiKey:!0}))},[]),L=(0,n.useCallback)((e,t)=>(P.current.set(e,t),()=>{P.current.get(e)===t&&P.current.delete(e)}),[]),A=(0,n.useCallback)(async()=>{for(let e of[...P.current.values()])await e()},[]);(0,n.useEffect)(()=>{if(i)return i(A)??void 0},[A,i]);let O=(0,n.useCallback)((e,t)=>{W(o=>{let r={...o.providers??{}};return t?r[e]=t:delete r[e],{...o,providers:r}}),s?.()},[s,W]),H=(0,n.useCallback)(async e=>{if(!F.current){F.current=!0,m(null);try{await A(),b(e)}catch(e){m(e instanceof Error?e.message:String(e))}finally{F.current=!1}}},[A]);(0,n.useEffect)(()=>{fetch("/api/models-config").then(e=>e.json()).then(e=>{let t=e.providers?e:{...e,providers:{}};E.current=t,D.current+=1,c(t)}).catch(()=>{let e={providers:{}};E.current=e,D.current+=1,c(e)}).finally(()=>g(!1)),N()},[N]);let B=(0,n.useCallback)(async()=>{if(!F.current){F.current=!0,m(null);try{await A();let e="new-provider",t=1;for(;E.current.providers?.[e];)e=`new-provider-${t++}`;W(t=>({...t,providers:{...t.providers??{},[e]:{api:"openai-completions"}}})),b({type:"provider",name:e})}catch(e){m(e instanceof Error?e.message:String(e))}finally{F.current=!1}}},[A,W]),U=(0,n.useCallback)((e,t)=>{W(o=>({...o,providers:{...o.providers??{},[e]:t}}))},[W]),_=(0,n.useCallback)((e,t)=>{W(o=>{let r=Object.entries(o.providers??{}),n=r.findIndex(([t])=>t===e);return -1===n?o:(r[n]=[t,r[n][1]],{...o,providers:Object.fromEntries(r)})}),b(o=>o?"provider"===o.type&&o.name===e?{type:"provider",name:t}:"model"===o.type&&o.providerName===e?{...o,providerName:t}:o:o)},[W]),q=(0,n.useCallback)(e=>{let t=Object.keys(W(t=>{let o={...t.providers??{}};return delete o[e],{...t,providers:o}}).providers??{});b(t.length>0?{type:"provider",name:t[0]}:null)},[W]),V=(0,n.useCallback)(async e=>{if(!F.current){F.current=!0,m(null);try{await A();let t=W(t=>{let o=t.providers?.[e]??{},r=[...o.models??[],{id:""}];return{...t,providers:{...t.providers??{},[e]:{...o,models:r}}}}),o=(t.providers?.[e]?.models?.length??1)-1;b({type:"model",providerName:e,index:o})}catch(e){m(e instanceof Error?e.message:String(e))}finally{F.current=!1}}},[A,W]),K=(0,n.useCallback)((e,t)=>{W(o=>{let r=o.providers?.[e]??{},n=[...r.models??[]],s=new Set(n.map(e=>e.id));for(let e of t)s.has(e.id)||(s.add(e.id),n.push({id:e.id,name:e.name}));return{...o,providers:{...o.providers??{},[e]:{...r,models:n}}}})},[W]),J=(0,n.useCallback)((e,t,o)=>{W(r=>{let n=r.providers?.[e]??{},s=[...n.models??[]];return s[t]=o,{...r,providers:{...r.providers??{},[e]:{...n,models:s}}}})},[W]),G=(0,n.useCallback)(async(e,t)=>{if(!F.current){F.current=!0,m(null);try{await A(),W(o=>{let r=o.providers?.[e]??{},n=[...r.models??[]];return n.splice(t,1),{...o,providers:{...o.providers??{},[e]:{...r,models:n.length?n:void 0}}}}),b({type:"provider",name:e})}catch(e){m(e instanceof Error?e.message:String(e))}finally{F.current=!1}}},[A,W]),Y=(0,n.useCallback)(async()=>{if(!h){f(!0),m(null),v(!1);try{await A();let e=E.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&&(E.current=o.config,D.current+=1,c(o.config)),v(!0),s?.(),setTimeout(()=>v(!1),2e3)}catch(e){m(e instanceof Error?e.message:String(e))}finally{f(!1)}}},[A,s,h]),X=(0,n.useCallback)(async()=>{try{await A(),o?.()}catch(e){m(e instanceof Error?e.message:String(e))}},[A,o]),Z=Object.entries(d.providers??{}),Q=new Set([...w.map(e=>e.id),...S.map(e=>e.id)]),ee=Z.filter(([e])=>!Q.has(e)),et=w.filter(e=>e.loggedIn),eo=S.filter(e=>e.configured);(0,n.useEffect)(()=>{if(y||p||!I.oauth||!I.apiKey)return;let e=et[0]?{type:"oauth",providerId:et[0].id}:eo[0]?{type:"apikey",providerId:eo[0].id}:ee[0]?.[0]?{type:"provider",name:ee[0][0]}:null;e&&b(e)},[eo,et,ee,p,I.apiKey,I.oauth,y]);let er=(()=>{if(!y)return null;if("oauth"===y.type){let e=w.find(e=>e.id===y.providerId);return e?(0,r.jsx)(a$,{provider:e,onRefresh:N,onRegisterBuiltinFlush:L,onBuiltinProviderChange:t=>O(e.id,t)},e.id):null}if("apikey"===y.type){let e=S.find(e=>e.id===y.providerId);return e?(0,r.jsx)(aN,{provider:e,onRefresh:N,onRegisterBuiltinFlush:L,onBuiltinProviderChange:t=>O(e.id,t)},e.id):null}if("provider"===y.type){let e=d.providers?.[y.name];return e?(0,r.jsx)(aM,{name:y.name,provider:e,onChange:e=>U(y.name,e),onRename:e=>_(y.name,e),onDelete:()=>q(y.name),onAddModels:e=>K(y.name,e)},y.name):null}let e=d.providers?.[y.providerName],t=e?.models?.[y.index];return t?(0,r.jsx)(aW,{providerName:y.providerName,provider:e,model:t,onChange:e=>J(y.providerName,y.index,e),onDelete:()=>{G(y.providerName,y.index)}},`${y.providerName}-${y.index}`):null})();return(0,r.jsxs)(r.Fragment,{children:[(0,r.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||X()},children:(0,r.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,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 18px",borderBottom:"1px solid var(--border)",flexShrink:0},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"baseline",gap:10},children:[(0,r.jsx)("span",{style:{fontSize:15,fontWeight:700,color:"var(--text)"},children:a("desktop.models")}),(0,r.jsx)("code",{style:{fontSize:11,color:"var(--text-muted)",fontFamily:"var(--font-mono)"},children:"~/.pi/agent/models.json"})]}),(0,r.jsx)("button",{onClick:()=>{X()},"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,r.jsx)(af,{}),(0,r.jsxs)("div",{style:{flex:1,display:"flex",flexDirection:l?"column":"row",overflow:"hidden"},children:[(0,r.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,r.jsxs)("div",{style:{flex:1,overflowY:"auto",padding:"8px 6px"},children:[et.map(e=>{let t=y?.type==="oauth"&&y.providerId===e.id;return(0,r.jsxs)("div",{onClick:()=>{H({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,r.jsx)(n$,{id:e.id,size:16}),(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name})]},e.id)}),eo.map(e=>{let t=y?.type==="apikey"&&y.providerId===e.id;return(0,r.jsxs)("div",{onClick:()=>{H({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,r.jsx)(n$,{id:e.id,size:16}),(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.displayName})]},e.id)}),(et.length>0||eo.length>0)&&ee.length>0&&(0,r.jsx)("div",{style:{margin:"4px 8px",borderTop:"1px solid var(--border)"}}),p?(0,r.jsx)("div",{style:{padding:"10px 8px",fontSize:12,color:"var(--text-muted)"},children:a("desktop.modelsLoading")}):ee.map(([e,t])=>{let o=y?.type==="provider"&&y.name===e,n=t.models??[];return(0,r.jsxs)("div",{style:{marginBottom:2},children:[(0,r.jsxs)("div",{onClick:()=>{H({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,r.jsx)(C.G,{size:11,style:{color:"var(--text-dim)",flexShrink:0}}),(0,r.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})]}),n.map((t,o)=>{let n=y?.type==="model"&&y.providerName===e&&y.index===o;return(0,r.jsxs)("div",{onClick:()=>{H({type:"model",providerName:e,index:o})},style:{display:"flex",alignItems:"center",gap:6,padding:"5px 8px 5px 26px",borderRadius:5,cursor:"pointer",background:n?"var(--bg-selected)":"none"},onMouseEnter:e=>{n||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{n||(e.currentTarget.style.background="none")},children:[(0,r.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,r.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,r.jsx)("div",{onClick:t=>{t.stopPropagation(),V(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,r.jsx)("span",{style:{fontSize:11},children:a("desktop.modelsAddModel")})})]},e)})]}),(0,r.jsx)("div",{style:{borderTop:"1px solid var(--border)",padding:"8px 6px"},children:(0,r.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,r.jsx)("div",{style:{flex:1,overflowY:"auto",padding:20},children:p?null:er??(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-dim)",fontSize:13},children:a("desktop.modelsSelectProviderOrModel")})})]}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"flex-end",gap:10,padding:"10px 18px",borderTop:"1px solid var(--border)",flexShrink:0},children:[x&&(0,r.jsx)("span",{style:{fontSize:12,color:"#f87171",flex:1},children:x}),!e&&(0,r.jsx)("button",{onClick:()=>{X()},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,r.jsx)(ai,{sessionId:t}),(0,r.jsxs)("button",{onClick:Y,disabled:h||k,style:{position:"relative",padding:"6px 16px",minWidth:92,background:k?"#16a34a":h?"var(--bg-panel)":"var(--accent)",border:"none",borderRadius:6,color:k?"#fff":h?"var(--text-muted)":"#fff",cursor:h||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,r.jsx)(u.S,{size:14,style:{strokeDasharray:18,animation:"saved-check-draw 0.35s ease forwards",flexShrink:0}}),(0,r.jsx)("span",{children:k?a("desktop.modelsSaved"):h?a("desktop.modelsSaving"):a("desktop.modelsSave")})]})]})]})}),R&&(0,r.jsx)(aL,{oauthProviders:w,apiKeyProviders:S,onSelectOAuth:e=>{H({type:"oauth",providerId:e})},onSelectApiKey:e=>{H({type:"apikey",providerId:e})},onAddCustom:B,onClose:()=>z(!1)})]})}function aO(e){return e.replace(/^\/(?:Users|home)\/[^/]+/,"~")}function aH(e){let t=e.trim().match(/^\$?\s*pi\s+install\s+(\S+)\s*$/);return t?.[1]??e}function aB(e){return`${e.scope}\0${e.source}`}function aU(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 a_(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 aq(e){return"loaded"===e?"var(--accent)":"installed"===e?"#f59e0b":"disabled"===e?"var(--text-dim)":"#ef4444"}function aV({pkg:e}){let{t}=(0,E.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,r.jsx)("div",{style:{fontSize:12,color:"var(--text-dim)"},children:t(e.disabled?"desktop.packageDisabled":"desktop.noResolvedResources")}):(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:12},children:o.map((e,t)=>(0,r.jsxs)("div",{style:{borderTop:0===t?"none":"1px solid var(--border)",paddingTop:12*(0!==t)},children:[(0,r.jsx)("div",{style:{fontSize:10,fontWeight:700,color:"var(--text-dim)",textTransform:"uppercase",marginBottom:6},children:e.label}),(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:e.resources.map(e=>(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.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,r.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 aK({scope:e}){let{t}=(0,E.s)();return(0,r.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 aJ(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 aG({enabled:e,loading:t,onToggle:o,label:n}){return(0,r.jsx)("button",{type:"button",onClick:o,disabled:t,title:n,"aria-label":n,"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,r.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 aY({value:e,onChange:t}){let{t:o}=(0,E.s)();return(0,r.jsx)("div",{style:{display:"inline-flex",border:"1px solid var(--border)",borderRadius:7,overflow:"hidden",height:30},children:["global","project"].map(n=>{let s=e===n;return(0,r.jsx)("button",{onClick:()=>t(n),style:{width:76,border:"none",borderRight:"global"===n?"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.${n}`)},n)})})}function aX({cwd:e,source:t,scope:o,busy:s,actionError:i,onSourceChange:a,onScopeChange:l,onInstall:d}){let{t:c}=(0,E.s)(),p=(0,n.useRef)(null);return(0,n.useEffect)(()=>{p.current?.focus()},[]),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:18,maxWidth:660,minHeight:"100%"},children:[(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:5},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,flexWrap:"wrap"},children:[(0,r.jsx)("div",{style:{fontSize:14,fontWeight:700,color:"var(--text)"},children:c("desktop.addPluginTitle")}),(0,r.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,r.jsx)("div",{style:{fontSize:12,color:"var(--text-dim)",fontFamily:"var(--font-mono)"},children:"project"===o?`${aO(e)}/.pi/agent/{npm,git}`:"~/.pi/agent/{npm,git}"})]}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:7},children:[(0,r.jsx)("label",{htmlFor:"plugin-source",style:{fontSize:12,fontWeight:600,color:"var(--text-muted)"},children:c("desktop.pluginSource")}),(0,r.jsx)("input",{id:"plugin-source",ref:p,value:t,onChange:e=>a(e.target.value),onPaste:e=>{let t=e.clipboardData.getData("text"),o=aH(t);o!==t&&(e.preventDefault(),a(o))},onBlur:e=>a(aH(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,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:[(0,r.jsx)(aY,{value:o,onChange:l}),(0,r.jsx)("button",{type:"button",onClick:d,disabled:s||!t.trim(),style:{...aJ(s||!t.trim()),background:"var(--accent)",color:"white",borderColor:"var(--accent)"},children:c(s?"desktop.installing":"desktop.install")})]}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:7},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text-muted)"},children:c("desktop.examples")}),(0,r.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,r.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,r.jsx)("div",{style:{fontSize:12,color:"#ef4444",whiteSpace:"pre-wrap"},children:i})]})}function aZ({pkg:e,cwd:t,busyKey:o,actionError:n,actionMessage:s,sessionId:i,onAction:a,onReloadSession:l}){let{t:d}=(0,E.s)(),c=aB(e),p=o?.endsWith(c)??!1,u="reload"===o,g=!e.disabled;return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:20,maxWidth:680},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:12,minWidth:0,flexWrap:"wrap"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:180,flex:1},children:[(0,r.jsx)(aG,{enabled:g,loading:p||u,onToggle:()=>a(e.disabled?"enable":"disable",e),label:d(e.disabled?"desktop.enablePackage":"desktop.disablePackage")}),(0,r.jsx)(aK,{scope:e.scope}),e.disabled?(0,r.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,r.jsx)("span",{style:{fontSize:10,padding:"1px 5px",borderRadius:3,background:"rgba(245,158,11,0.12)",color:"#d97706"},children:d("desktop.filtered")}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:12,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.source})]}),(0,r.jsxs)("div",{style:{display:"flex",gap:8,flexWrap:"wrap"},children:[(0,r.jsx)("button",{onClick:()=>a("update",e),disabled:p||u,style:aJ(p||u),children:d(o===`update:${c}`?"desktop.updating":"desktop.update")}),(0,r.jsx)("button",{onClick:l,disabled:!i||u||p,style:aJ(!i||u||p),title:d(i?"desktop.reloadCurrentSession":"desktop.openSessionToReload"),children:d(u?"desktop.reloading":"desktop.reloadSession")}),(0,r.jsx)("button",{onClick:()=>a("remove",e),disabled:p||u,style:aJ(p||u,!0),children:d(o===`remove:${c}`?"desktop.removing":"desktop.remove")})]})]}),(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"minmax(96px, 130px) minmax(0, 1fr)",gap:"9px 14px",fontSize:12,lineHeight:1.45},children:[(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:d("desktop.status")}),(0,r.jsx)("div",{style:{color:aq(e.status),textTransform:"capitalize"},children:e.status}),(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:d("desktop.version")}),(0,r.jsx)("div",{style:{color:"var(--text-muted)",fontFamily:"var(--font-mono)"},children:a_(e,d)}),(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:d("desktop.package")}),(0,r.jsx)("div",{style:{color:"var(--text-muted)",fontFamily:"var(--font-mono)",overflowWrap:"anywhere"},children:e.packageName??d("desktop.unknown")}),(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:d("desktop.resources")}),(0,r.jsx)("div",{style:{color:"var(--text-muted)"},children:aU(e,d)}),(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:d("desktop.installedPath")}),(0,r.jsx)("div",{style:{color:e.installedPath?"var(--text-muted)":"#ef4444",fontFamily:"var(--font-mono)",overflowWrap:"anywhere"},children:e.installedPath?aO(e.installedPath):d("desktop.notFound")}),(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:d("desktop.cwd")}),(0,r.jsx)("div",{style:{color:"var(--text-dim)",fontFamily:"var(--font-mono)",overflowWrap:"anywhere"},children:aO(t)})]}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:700,color:"var(--text)"},children:d("desktop.resolvedResources")}),(0,r.jsx)(aV,{pkg:e})]}),s&&(0,r.jsx)("div",{style:{fontSize:12,color:"#16a34a"},children:s}),n&&(0,r.jsx)("div",{style:{fontSize:12,color:"#ef4444",whiteSpace:"pre-wrap"},children:n})]})}function aQ({cwd:e,sessionId:t,embedded:o=!1,onCloseAction:s,onReloadedAction:i}){let a=$(),{t:l}=(0,E.s)(),[d,c]=(0,n.useState)(null),[p,u]=(0,n.useState)(!0),[g,h]=(0,n.useState)(null),[f,m]=(0,n.useState)(null),[k,v]=(0,n.useState)(!1),[y,b]=(0,n.useState)(""),[w,j]=(0,n.useState)("global"),[S,C]=(0,n.useState)(null),[T,R]=(0,n.useState)(null),[z,I]=(0,n.useState)(null),M=(0,n.useMemo)(()=>d?.packages??[],[d?.packages]),P=M.find(e=>aB(e)===f)??null,D=(0,n.useMemo)(()=>["project","global"].map(e=>({scope:e,packages:M.filter(t=>t.scope===e)})).filter(e=>e.packages.length>0),[M]),F=(0,n.useCallback)(async()=>{u(!0),h(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),m(e=>e&&o.packages.some(t=>aB(t)===e)?e:o.packages[0]?aB(o.packages[0]):null)}catch(e){h(e instanceof Error?e.message:String(e))}finally{u(!1)}},[e]);(0,n.useEffect)(()=>{F()},[F]);let W=(0,n.useCallback)(async(t,o)=>{let r=aB(o);C(`${t}:${r}`),R(null),I(null);try{let r=await fetch("/api/plugins",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:t,source:o.source,scope:o.scope,cwd:e})}),n=await r.json();if(!r.ok||n.error)throw Error(n.error??`HTTP ${r.status}`);if(c(n),"remove"===t)m(n.packages[0]?aB(n.packages[0]):null),0===n.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]),N=(0,n.useCallback)(async()=>{let t=aH(y).trim();if(!t)return;let o=`${w}\0${t}`;C(`install:${o}`),R(null),I(null);try{var r;let n,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=(r=a.packages,s=(n=t.trim()).startsWith("npm:")?n.slice(4):n,r.find(e=>e.scope===w&&e.source===n)??r.find(e=>e.scope===w&&e.source===`npm:${s}`)??r.find(e=>e.scope===w&&e.source.endsWith(n)));m(d?aB(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]),L=(0,n.useCallback)(async()=>{if(t){C("reload"),R(null),I(null);try{await sT(t,{type:"reload"}),i?.(),await F(),I(l("desktop.sessionReloaded"))}catch(e){R(e instanceof Error?e.message:String(e))}finally{C(null)}}},[F,i,t,l]),A=S?.startsWith("install:")??!1;return(0,r.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,r.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,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 18px",borderBottom:"1px solid var(--border)",flexShrink:0},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"baseline",gap:10,minWidth:0},children:[(0,r.jsx)("span",{style:{fontSize:15,fontWeight:700,color:"var(--text)"},children:l("desktop.plugins")}),(0,r.jsx)("code",{style:{fontSize:11,color:"var(--text-muted)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:aO(e)})]}),(0,r.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,r.jsxs)("div",{style:{flex:1,display:"flex",flexDirection:a?"column":"row",overflow:"hidden"},children:[(0,r.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,r.jsx)("div",{style:{flex:1,overflowY:"auto",padding:"8px 6px"},children:p?(0,r.jsx)("div",{style:{padding:"10px 8px",fontSize:12,color:"var(--text-muted)"},children:l("desktop.loading")}):g?(0,r.jsx)("div",{style:{padding:"10px 8px",fontSize:11,color:"#ef4444"},children:g}):0===M.length?(0,r.jsx)("div",{style:{padding:"10px 8px",fontSize:11,color:"var(--text-dim)"},children:l("desktop.noPluginsConfigured")}):D.map(e=>(0,r.jsxs)("div",{style:{marginBottom:6},children:[(0,r.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=aB(e),o=!k&&f===t;return(0,r.jsxs)("div",{onClick:()=>{m(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,r.jsx)("span",{style:{flexShrink:0,width:7,height:7,borderRadius:"50%",background:aq(e.status)}}),(0,r.jsxs)("div",{style:{minWidth:0,flex:1},children:[(0,r.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,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",marginTop:2},children:aU(e,l)}),(e.version||e.configuredVersion)&&(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",marginTop:2},children:a_(e,l)})]})]},t)})]},e.scope))}),(0,r.jsx)("div",{style:{padding:"8px 6px",borderTop:"1px solid var(--border)",flexShrink:0},children:(0,r.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,r.jsx)(x.c,{size:13}),l("desktop.addPlugin")]})})]}),(0,r.jsx)("div",{style:{flex:1,overflowY:"auto",padding:20},children:k?(0,r.jsx)(aX,{cwd:e,source:y,scope:w,busy:A,actionError:T,onSourceChange:b,onScopeChange:j,onInstall:N}):p?null:P?(0,r.jsx)(aZ,{pkg:P,cwd:e,busyKey:S,actionError:T,actionMessage:z,sessionId:t,onAction:W,onReloadSession:L},aB(P)):(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-dim)",fontSize:13},children:l("desktop.selectPackage")})})]}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,padding:"10px 18px",borderTop:"1px solid var(--border)",flexShrink:0},children:[(0,r.jsx)("div",{style:{minWidth:0,flex:1,fontSize:11,color:"var(--text-dim)",overflow:"hidden"},children:d?.diagnostics.length?(0,r.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,r.jsx)("span",{children:d?l("desktop.pluginResourceTotals",{extensions:d.totals.extensions,skills:d.totals.skills,prompts:d.totals.prompts,themes:d.totals.themes}):""})}),(0,r.jsx)("button",{onClick:()=>void F(),disabled:p||null!==S,style:aJ(p||null!==S),children:l("desktop.refresh")}),!o&&(0,r.jsx)("button",{onClick:s,style:aJ(!1),children:l("desktop.close")})]})]})})}var a0=o(36282);function a1(){let{t:e}=(0,E.s)(),[t,o]=(0,n.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,n.useState)(!1),[a,l]=(0,n.useState)(!1),[d,c]=(0,n.useState)(null),[p,u]=(0,n.useState)(null),[g,h]=(0,n.useState)(null),[f,x]=(0,n.useState)(!1),[m,k]=(0,n.useState)(!1);(0,n.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,n.useCallback)((e,t)=>{o(o=>({...o,[e]:t})),"password"===e&&k(!0),x(!0),u(null),h(null)},[]),y=(0,n.useCallback)(async()=>{i(!0),u(null),h(null);try{let r={...t};delete r.hasPassword,m||delete r.password;let n=await fetch("/api/proxy",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)}),s=await n.json();if(n.ok){u(!0),x(!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),h(s.error||e("desktop.proxySaveFailed"))}catch(t){u(!1),h(t instanceof Error?t.message:e("desktop.proxySaveFailed"))}finally{i(!1)}},[t,m,e]),b=(0,n.useCallback)(async()=>{l(!0),c(null),f&&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)}},[f,y,e]),w=(0,n.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,r.jsxs)("div",{style:{flex:1,display:"flex",flexDirection:"column",padding:"16px 20px",overflow:"auto",gap:16},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:12,marginBottom:4},children:[(0,r.jsxs)("label",{style:{display:"flex",alignItems:"center",gap:8,fontSize:14,fontWeight:500,color:"var(--text)",cursor:"pointer"},children:[(0,r.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,r.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,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:"12px 16px",opacity:t.enabled?1:.5,pointerEvents:t.enabled?"auto":"none"},children:[(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,r.jsx)("label",{style:{fontSize:12,color:"var(--text-muted)"},children:e("desktop.proxyProtocol")}),(0,r.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,r.jsx)("option",{value:"http",children:"HTTP"}),(0,r.jsx)("option",{value:"https",children:"HTTPS"}),(0,r.jsx)("option",{value:"socks5",children:"SOCKS5"})]})]}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,r.jsx)("label",{style:{fontSize:12,color:"var(--text-muted)"},children:e("desktop.proxyHost")}),(0,r.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,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,r.jsx)("label",{style:{fontSize:12,color:"var(--text-muted)"},children:e("desktop.proxyPort")}),(0,r.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,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,r.jsx)("label",{style:{fontSize:12,color:"var(--text-muted)"},children:e("desktop.proxyUsername")}),(0,r.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,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,r.jsx)("label",{style:{fontSize:12,color:"var(--text-muted)"},children:e("desktop.proxyPassword")}),(0,r.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,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4,gridColumn:"1 / -1"},children:[(0,r.jsx)("label",{style:{fontSize:12,color:"var(--text-muted)"},children:e("desktop.proxyNoProxy")}),(0,r.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,r.jsxs)("div",{style:{display:"flex",gap:10,marginTop:4},children:[(0,r.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,r.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,r.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,r.jsx)(oZ.r,{size:16,weight:"fill"}),e("desktop.proxySaved")]}),!1===p&&g&&(0,r.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,r.jsx)(sh.J,{size:16,weight:"fill"}),g]}),d&&(0,r.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,r.jsx)(oZ.r,{size:16,weight:"fill"}):(0,r.jsx)(sh.J,{size:16,weight:"fill"}),d.message,void 0!==d.latencyMs&&(0,r.jsxs)("span",{style:{color:"var(--text-muted)",fontSize:12,marginLeft:4},children:["(",d.latencyMs,"ms)"]})]}),f&&!p&&!g&&(0,r.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,r.jsx)(a0.j,{size:12,weight:"fill"}),e("desktop.proxyUnsaved")]})]})}function a2(e){return e.replace(/^\/(?:Users|home)\/[^/]+/,"~")}function a4(e){let t=e.sourceInfo?.source,o=e.sourceInfo?.scope;return"user"===o||"user"===t?"global":"project"===o||"project"===t?"project":"path"}function a6(e){let t=a4(e);return"path"===t?t:e.install?.skillsShUrl?`${t} / skills.sh`:t}function a5(e){return e.install?`${e.install.scope}\0${e.install.package}`:null}function a3(e,t){return e?e.slice(0,8):t}function a8({enabled:e,loading:t,onToggle:o}){let{t:n}=(0,E.s)();return(0,r.jsx)("button",{onClick:o,disabled:t,title:n(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,r.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 a7({skill:e,cwd:t,onToggle:o,toggling:n,saveError:s,updateStatus:i,checkingUpdate:a,updating:l,updateError:d,onCheckUpdate:c,onUpdate:p}){let{t:u}=(0,E.s)(),g=a4(e),h=!e.disableModelInvocation;return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:20},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:7},children:[(0,r.jsx)("span",{style:{fontSize:10,padding:"1px 5px",borderRadius:3,flexShrink:0,background:"project"===g?"rgba(99,102,241,0.12)":"rgba(120,120,120,0.12)",color:"project"===g?"rgba(99,102,241,0.8)":"var(--text-dim)"},children:u(`desktop.${g}`)}),(0,r.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"===g&&e.startsWith(t)){let o=e.slice(t.length).replace(/^[/\\]/,"");return`./${o}`}return a2(e)}(e.filePath)}),(0,r.jsx)(a8,{enabled:h,loading:n,onToggle:()=>o(e)}),s&&(0,r.jsx)("span",{style:{fontSize:12,color:"#f87171",flexShrink:0},children:s})]}),!h&&(0,r.jsx)("div",{style:{marginTop:-12,color:"var(--text-dim)",fontSize:12},children:u("desktop.hiddenButInvocable")}),e.install?.skillsShUrl&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:5},children:[(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",fontWeight:500},children:u("desktop.pluginSource")}),(0,r.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,r.jsxs)("span",{style:{fontFamily:"var(--font-mono)",fontSize:12,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[e.install.skillsShUrl.replace(/^https?:\/\//,"")," ↗"]})})]}),e.install&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:7},children:[(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",fontWeight:500},children:u("desktop.version")}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:[(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:12,color:"var(--text-muted)"},children:a3(i?.currentVersion??e.install.versionHash,u("desktop.unknown"))}),e.install.canCheckForUpdates&&(0,r.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,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:12,color:"#d97706"},children:a3(i.latestVersion,u("desktop.unknown"))}),(a||i&&"update-available"!==i.state)&&(0,r.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,r.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,r.jsx)("span",{style:{fontSize:12,color:"#ef4444"},children:d})]}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:5},children:[(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",fontWeight:500},children:u("desktop.name")}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:14,color:"var(--text)"},children:e.name})]}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:5},children:[(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",fontWeight:500},children:u("desktop.description")}),(0,r.jsx)("span",{style:{fontSize:14,color:"var(--text-muted)",lineHeight:1.6},children:e.description})]})]})}function a9({cwd:e,installedPackages:t,projectResourcesLoaded:o,onInstalled:s}){let{t:i}=(0,E.s)(),[a,l]=(0,n.useState)(""),[d,c]=(0,n.useState)([]),[p,u]=(0,n.useState)(!1),[g,h]=(0,n.useState)(null),[f,x]=(0,n.useState)(null),[m,k]=(0,n.useState)(null),[v,y]=(0,n.useState)(new Set),[b,w]=(0,n.useState)("global"),j=(0,n.useRef)(null);(0,n.useEffect)(()=>{j.current?.focus()},[]),(0,n.useEffect)(()=>{o||w("global")},[o]);let S=(0,n.useCallback)(async e=>{if(e.trim()){u(!0),h(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 h(o.error);c(o.results??[]),0===(o.results??[]).length&&h(i("desktop.noSkillsFound"))}catch(e){h(String(e))}finally{u(!1)}}},[i]),C=(0,n.useCallback)(async t=>{x(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})}),r=await o.json();if(!o.ok||r.error)return void k(r.error??`HTTP ${o.status}`);y(e=>new Set(e).add(`${b}:${t}`)),s()}catch(e){k(String(e))}finally{x(null)}},[s,b,e]),T="global"===b?"~/.pi/agent/skills/":`${a2(e)}/.pi/skills/`;return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%"},children:[(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:12,marginBottom:20},children:[(0,r.jsx)("div",{style:{fontSize:14,fontWeight:600,color:"var(--text)"},children:i("desktop.addSkillTitle")}),(0,r.jsxs)("div",{style:{display:"flex",gap:8},children:[(0,r.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,r.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,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10},children:[(0,r.jsx)("div",{style:{display:"flex",borderRadius:5,border:"1px solid var(--border)",overflow:"hidden",fontSize:12,flexShrink:0},children:["global","project"].map(e=>(0,r.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,r.jsxs)("span",{style:{fontSize:12,color:"var(--text-dim)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:["→ ",T]})]}),g&&(0,r.jsx)("div",{style:{fontSize:12,color:"#f87171"},children:g}),m&&(0,r.jsx)("div",{style:{fontSize:12,color:"#f87171",wordBreak:"break-word"},children:m})]}),d.length>0?(0,r.jsx)("div",{style:{flex:1,overflowY:"auto"},children:d.map(e=>{let o=t[b].has(e.package)||v.has(`${b}:${e.package}`),n=f===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,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:14,padding:"12px 0",borderBottom:"1px solid var(--border)"},children:[(0,r.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:13,fontWeight:600,color:"var(--text)",marginBottom:3},children:l??a}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:[(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:11,color:"var(--text-dim)"},children:a}),(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",fontWeight:500},children:e.installs}),e.url&&(0,r.jsx)("a",{href:e.url,target:"_blank",rel:"noreferrer",style:{fontSize:12,color:"var(--accent)",textDecoration:"none"},children:"skills.sh ↗"})]})]}),(0,r.jsx)("button",{onClick:()=>!o&&!n&&C(e.package),disabled:o||n||null!==f,style:{flexShrink:0,padding:"5px 14px",fontSize:12,fontWeight:500,borderRadius:5,border:"1px solid var(--border)",cursor:o||n||null!==f?"not-allowed":"pointer",background:o?"rgba(34,197,94,0.1)":"none",color:o?"#16a34a":n?"var(--accent)":"var(--text-muted)",transition:"color 0.12s"},children:o?`✓ ${i("desktop.installed")}`:n?i("desktop.installing"):i("desktop.install")})]},e.package)})}):!g&&!p&&(0,r.jsxs)("div",{style:{fontSize:13,color:"var(--text-dim)",lineHeight:1.8},children:[i("desktop.skillSearchHint").split("skills.sh")[0],(0,r.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 le({cwd:e,embedded:t=!1,sessionId:o,onCloseAction:s}){let i=$(),{t:a}=(0,E.s)(),[l,d]=(0,n.useState)([]),[c,p]=(0,n.useState)(!0),[u,g]=(0,n.useState)(null),[h,f]=(0,n.useState)(null),[m,k]=(0,n.useState)(new Set),[v,y]=(0,n.useState)(null),[b,w]=(0,n.useState)(!1),[j,S]=(0,n.useState)({}),[C,T]=(0,n.useState)(new Set),[R,z]=(0,n.useState)(!1),[I,M]=(0,n.useState)(null),[P,D]=(0,n.useState)(null),[F,W]=(0,n.useState)(!0),[N,L]=(0,n.useState)({}),A=(0,n.useCallback)(async()=>{p(!0),g(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 r=o.skills??[];if(d(r),W(o.projectResourcesLoaded??!0),r.length>0&&!h){let e=r.find(e=>!e.disableModelInvocation)??r[0];f(e.filePath),e.disableModelInvocation&&L(t=>({...t,[a6(e)]:!0}))}return r}catch(e){return g(String(e)),[]}finally{p(!1)}},[e,h]);(0,n.useEffect)(()=>{S({}),D(null),A()},[e]);let O=(0,n.useCallback)(async t=>{let o=(t?[t]:l.filter(e=>!!e.install)).map(a5).filter(e=>!!e);if(0!==o.length){D(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})}),r=await o.json();if(!o.ok||r.error)throw Error(r.error??`HTTP ${o.status}`);S(e=>{let t={...e};for(let e of r.updates??[])t[`${e.scope}\0${e.package}`]=e;return t})}catch(e){D(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,n.useCallback)(async t=>{if(!t.install)return;let o=a5(t);M(o),D(null);try{let r=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})}),n=await r.json();if(!r.ok||n.error||!n.success)throw Error(n.error??`HTTP ${r.status}`);await A();let s=n.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){D(e instanceof Error?e.message:String(e))}finally{M(null)}},[e,A]),B=(0,n.useCallback)(async t=>{let o=!t.disableModelInvocation;k(e=>new Set(e).add(t.filePath)),y(null);try{let r=await fetch("/api/skills",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e,filePath:t.filePath,disableModelInvocation:o})}),n=await r.json();if(!r.ok||n.error)return void y(n.error??`HTTP ${r.status}`);d(e=>e.map(e=>e.filePath===t.filePath?{...e,disableModelInvocation:o}:e)),o&&L(e=>({...e,[a6(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===h)??null;return(0,r.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,r.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,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 18px",borderBottom:"1px solid var(--border)",flexShrink:0},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"baseline",gap:10},children:[(0,r.jsx)("span",{style:{fontSize:15,fontWeight:700,color:"var(--text)"},children:a("desktop.skills")}),(0,r.jsx)("code",{style:{fontSize:11,color:"var(--text-muted)",fontFamily:"var(--font-mono)",maxWidth:320,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:a2(e)})]}),(0,r.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"})]}),!F&&(0,r.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,r.jsxs)("div",{style:{flex:1,display:"flex",flexDirection:i?"column":"row",overflow:"hidden"},children:[(0,r.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,r.jsx)("div",{style:{padding:"8px 8px 0",display:"flex",justifyContent:"flex-end"},children:(0,r.jsx)(ai,{sessionId:o,onApplied:A})}),(0,r.jsx)("div",{style:{flex:1,overflowY:"auto",padding:"8px 6px"},children:c?(0,r.jsx)("div",{style:{padding:"10px 8px",fontSize:12,color:"var(--text-muted)"},children:a("desktop.loading")}):u?(0,r.jsx)("div",{style:{padding:"10px 8px",fontSize:11,color:"#f87171"},children:u}):0===l.length?(0,r.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:r}of[{key:"project / skills.sh",label:`${a("desktop.project")} / skills.sh`,matches:e=>"project"===a4(e)&&!!e.install?.skillsShUrl},{key:"project",label:a("desktop.project"),matches:e=>"project"===a4(e)&&!e.install?.skillsShUrl},{key:"global / skills.sh",label:`${a("desktop.global")} / skills.sh`,matches:e=>"global"===a4(e)&&!!e.install?.skillsShUrl},{key:"global",label:a("desktop.global"),matches:e=>"global"===a4(e)&&!e.install?.skillsShUrl},{key:"path",label:a("desktop.path"),matches:e=>"path"===a4(e)}]){let n=l.filter(r);n.length>0&&e.push({key:t,label:o,skills:n})}return e.map(({key:e,label:t,skills:o})=>{let n=o.filter(e=>!e.disableModelInvocation),s=o.filter(e=>e.disableModelInvocation),i=N[e]??!1,l=i?[...n,...s]:n;return(0,r.jsxs)("div",{style:{marginBottom:6},children:[(0,r.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,r.jsxs)("button",{type:"button",onClick:()=>L(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,r.jsx)("span",{style:{fontSize:8},children:i?"▾":"▸"}),a("desktop.dormant")," (",s.length,")"]}),l.map(e=>{let t,o,n=!b&&h===e.filePath,s=e.disableModelInvocation;return(0,r.jsxs)("div",{onClick:()=>{f(e.filePath),w(!1)},style:{display:"flex",alignItems:"center",gap:7,padding:"8px 8px",borderRadius:5,cursor:"pointer",background:n?"var(--bg-selected)":"none"},onMouseEnter:e=>{n||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{n||(e.currentTarget.style.background="none")},children:[(0,r.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,r.jsx)("span",{style:{fontSize:12,fontWeight:n?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=a5(e))?j[t]:void 0,o?.state!=="update-available"?null:(0,r.jsx)("span",{title:a("desktop.updateAvailable"),style:{color:"#d97706",fontSize:13,lineHeight:1,flexShrink:0},children:"↑"}))]},e.filePath)})]},e)})})()}),(0,r.jsx)("div",{style:{padding:"8px 6px",borderTop:"1px solid var(--border)",flexShrink:0},children:(0,r.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,r.jsx)(x.c,{size:13}),a("desktop.addSkill")]})})]}),(0,r.jsx)("div",{style:{flex:1,overflowY:"auto",padding:20},children:b?(0,r.jsx)(a9,{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:F,onInstalled:()=>{A()}}):c?null:U?(0,r.jsx)(a7,{skill:U,cwd:e,onToggle:B,toggling:m.has(U.filePath),saveError:v,updateStatus:a5(U)?j[a5(U)]:void 0,checkingUpdate:!!a5(U)&&C.has(a5(U)),updating:I===a5(U),updateError:P,onCheckUpdate:()=>void O(U),onUpdate:()=>void H(U)},U.filePath):(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-dim)",fontSize:13},children:a("desktop.selectSkill")})})]}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 18px",borderTop:"1px solid var(--border)",flexShrink:0},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10},children:[l.some(e=>!!e.install)&&(0,r.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,r.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,r.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 lt(){let{t:e}=(0,E.s)(),[t,o]=(0,n.useState)([]),[s,i]=(0,n.useState)(""),[a,l]=(0,n.useState)(""),[d,c]=(0,n.useState)(""),[p,u]=(0,n.useState)(""),[g,h]=(0,n.useState)(!0),[f,x]=(0,n.useState)(null),m=(0,n.useCallback)(async()=>{h(!0),x(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){x(e instanceof Error?e.message:String(e))}finally{h(!1)}},[]);(0,n.useEffect)(()=>{m()},[m]);let k=(0,n.useMemo)(()=>[...new Set(t.map(e=>e.source).filter(Boolean))].sort(),[t]),v=(0,n.useMemo)(()=>[...new Set(t.map(e=>e.statusCode).filter(e=>void 0!==e))].sort((e,t)=>e-t),[t]),y=(0,n.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){x(e instanceof Error?e.message:String(e))}},S=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 tA(t),x(null)}catch(e){x(e instanceof Error?e.message:String(e))}};return(0,r.jsxs)("div",{style:{flex:1,minWidth:0,minHeight:0,overflow:"auto",padding:"18px 20px",display:"flex",flexDirection:"column",gap:12},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[(0,r.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,r.jsx)("option",{value:"",children:e("desktop.logsAllLevels")}),["error","warning","info"].map(e=>(0,r.jsx)("option",{value:e,children:e},e))]}),(0,r.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,r.jsx)("option",{value:"",children:e("desktop.logsAllCodes")}),v.map(e=>(0,r.jsx)("option",{value:e,children:e},e))]}),(0,r.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,r.jsx)("option",{value:"",children:e("desktop.logsAllSources")}),k.map(e=>(0,r.jsx)("option",{value:e,children:e},e))]}),(0,r.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,r.jsx)("button",{type:"button",onClick:()=>void m(),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,r.jsx)(w.S,{size:14})}),(0,r.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,r.jsx)(j.l,{size:14})})]}),g&&(0,r.jsx)("div",{style:{color:"var(--text-muted)",fontSize:12},children:e("desktop.loading")}),f&&(0,r.jsx)("div",{style:{color:"#ef4444",fontSize:12},children:f}),!g&&!f&&0===y.length&&(0,r.jsx)("div",{style:{color:"var(--text-muted)",fontSize:12},children:e("desktop.logsEmpty")}),(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:8},children:y.map(t=>(0,r.jsxs)("details",{style:{border:"1px solid var(--border)",borderRadius:7,background:"var(--bg-panel)",padding:"8px 10px"},children:[(0,r.jsxs)("summary",{style:{cursor:"pointer",color:"error"===t.level?"#ef4444":"warning"===t.level?"#f59e0b":"var(--text)",fontSize:12},children:[(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",marginRight:8},children:t.statusCode??"—"}),(0,r.jsx)("span",{style:{marginRight:8},children:new Date(t.timestamp).toLocaleString()}),(0,r.jsx)("span",{style:{overflowWrap:"anywhere"},children:t.message.length>180?`${t.message.slice(0,180)}…`:t.message})]}),(0,r.jsxs)("div",{style:{padding:"8px 0 0 18px",color:"var(--text-muted)",fontSize:11,lineHeight:1.5,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:[(0,r.jsxs)("div",{children:[t.source,t.provider?` \xb7 ${t.provider}`:"",t.model?` \xb7 ${t.model}`:""]}),(0,r.jsx)("div",{style:{marginTop:5,maxHeight:260,overflow:"auto"},children:t.message}),t.details&&(0,r.jsx)("div",{style:{marginTop:5,maxHeight:260,overflow:"auto"},children:t.details}),(0,r.jsx)("button",{type:"button",onClick:()=>void S(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 lo={padding:"7px 9px",background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:6,color:"var(--text)",fontSize:12,width:"100%"},lr={padding:"6px 12px",border:"none",borderRadius:6,background:"var(--accent)",color:"#fff",cursor:"pointer",fontSize:12};function ln(){let{t:e}=(0,E.s)(),[t,o]=(0,n.useState)([]),[s,i]=(0,n.useState)(!0),[a,l]=(0,n.useState)(null),[d,p]=(0,n.useState)(""),[u,h]=(0,n.useState)(""),[f,m]=(0,n.useState)(!1),[k,v]=(0,n.useState)(null),y=(0,n.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,n.useEffect)(()=>{y()},[y]);let b=(0,n.useCallback)(()=>{window.dispatchEvent(new Event("pi:snippets-changed"))},[]),w=()=>{l(null),p(""),h(""),v(null)},S=(0,n.useCallback)(async()=>{let t=d.trim();if(!t)return void v(e("desktop.snippetNameRequired"));m(!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{m(!1)}},[a,d,u,y,b,e]),C=(0,n.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,r.jsxs)(iX,{children:[(0,r.jsx)(iZ,{children:(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:7,padding:"12px 0"},children:[(0,r.jsx)(rP.c,{size:15,"aria-hidden":"true"}),(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{style:{fontSize:13,fontWeight:600,color:"var(--text)"},children:e("desktop.snippets")}),(0,r.jsx)("div",{style:{fontSize:11,color:"var(--text-muted)",marginTop:2},children:e("desktop.snippetsDesc")})]})]})}),(0,r.jsx)(iZ,{children:(0,r.jsxs)("div",{style:{width:"100%"},children:[(0,r.jsxs)("div",{style:{display:"flex",gap:6,flexWrap:"wrap",marginBottom:8},children:[(0,r.jsx)("button",{type:"button",onClick:w,style:lr,children:(0,r.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:5},children:[(0,r.jsx)(x.F,{size:13})," ",e("desktop.snippetNew")]})}),a&&(0,r.jsx)("button",{type:"button",onClick:w,style:{...lr,background:"var(--bg-hover)",color:"var(--text-muted)"},children:(0,r.jsx)(c.X,{size:13})})]}),(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"minmax(120px, 200px) 1fr",gap:8,alignItems:"start",marginBottom:8},children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",display:"block",marginBottom:4},children:e("desktop.snippetName")}),(0,r.jsx)("input",{value:d,onChange:e=>p(e.target.value),placeholder:"#name",style:lo})]}),(0,r.jsxs)("div",{children:[(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",display:"block",marginBottom:4},children:e("desktop.snippetContent")}),(0,r.jsx)("textarea",{value:u,onChange:e=>h(e.target.value),rows:3,style:{...lo,resize:"vertical",fontFamily:"var(--font-mono)",fontSize:11}})]})]}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10,marginBottom:10},children:[(0,r.jsx)("button",{type:"button",onClick:()=>void S(),disabled:f,style:{...lr,cursor:f?"wait":"pointer"},children:e("desktop.snippetSave")}),k&&(0,r.jsx)("span",{style:{color:"var(--status-error, #ef4444)",fontSize:12},children:k})]}),s?(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-dim)"},children:e("desktop.loadingThemes")}):0===t.length?(0,r.jsx)(i0,{children:e("desktop.snippetEmpty")}):(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:4},children:t.map(t=>(0,r.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,r.jsx)("span",{style:{color:"var(--accent)",fontFamily:"var(--font-mono)",fontSize:11},children:"#"}),(0,r.jsx)("span",{style:{fontWeight:600,fontSize:12,flexShrink:0},children:t.name}),(0,r.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,r.jsx)("button",{type:"button",onClick:()=>{l(t),p(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,r.jsx)(g.I,{size:13})}),(0,r.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,r.jsx)(j.l,{size:13})})]},t.id))})]})}),(0,r.jsx)(iQ,{children:(0,r.jsx)(i0,{children:e("desktop.snippetHint")})})]})}let ls=["async","group","smart"],li=["full","compact","custom"],la=["all","background","off"],ll={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 ld(){return{fontSize:12,color:"var(--text-muted)"}}function lc({cwd:e,sessionId:t}){let{t:o}=(0,E.s)(),[s,i]=(0,n.useState)({}),[a,l]=(0,n.useState)([]),[d,c]=(0,n.useState)(""),[p,u]=(0,n.useState)(!1),[g,h]=(0,n.useState)(null),[f,x]=(0,n.useState)(!1),[m,k]=(0,n.useState)(null),[v,y]=(0,n.useState)(!1),[b,w]=(0,n.useState)([]),[j,S]=(0,n.useState)({}),C=(0,n.useCallback)(async()=>{h(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){h(e instanceof Error?e.message:String(e))}finally{u(!0)}},[]);(0,n.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,n.useEffect)(()=>{C()},[C]);let T=(0,n.useCallback)((e,t)=>{i(o=>({...o,[e]:t})),y(!1),k(null)},[]),R=(0,n.useCallback)(async()=>{x(!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{x(!1)}},[s]),z=(0,n.useRef)({}),I=(0,n.useCallback)(async(e,t)=>{let o=(z.current[e]??0)+1;z.current[e]=o,S(t=>({...t,[e]:"saving"}));try{let r=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 n=await r.json();if(!r.ok||n.error)throw Error(n.error??`HTTP ${r.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,r.jsx)(iZ,{children:(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"minmax(150px, 240px) 1fr",gap:"8px 12px",alignItems:"center",padding:"8px 0"},children:[(0,r.jsx)("span",{style:ld(),children:o(t)}),(0,r.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:ll})]})},e),P=(e,t,n)=>(0,r.jsx)(iZ,{children:(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"minmax(150px, 240px) 1fr",gap:"8px 12px",alignItems:"center",padding:"8px 0"},children:[(0,r.jsx)("span",{style:ld(),children:o(t)}),(0,r.jsx)("select",{value:s[e]??n[0],onChange:t=>T(e,t.target.value),style:{...ll,fontFamily:"var(--font-mono)"},children:n.map(e=>(0,r.jsx)("option",{value:e,children:e},e))})]})},e),D=(e,t,n)=>(0,r.jsx)(iZ,{children:(0,r.jsx)(iE,{checked:s[e]??!1,onChange:t=>T(e,t),label:o(t),description:n?o(n):void 0})},e);return(0,r.jsx)("div",{style:{flex:1,overflow:"auto",minWidth:0,padding:"20px 22px",display:"flex",flexDirection:"column",gap:16},children:(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:p?g?(0,r.jsx)("div",{style:{fontSize:12,color:"#ef4444"},children:g}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:14,fontWeight:700,color:"var(--text)"},children:o("desktop.subagents")}),(0,r.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,r.jsx)(i0,{children:o("desktop.subagentsDesc")}),(0,r.jsxs)(iX,{children:[M("maxConcurrent","desktop.subagentsMaxConcurrent"),M("defaultMaxTurns","desktop.subagentsDefaultMaxTurns"),M("graceTurns","desktop.subagentsGraceTurns"),P("defaultJoinMode","desktop.subagentsJoinMode",ls),P("widgetMode","desktop.subagentsWidgetMode",la),P("toolDescriptionMode","desktop.subagentsToolDescMode",li),D("schedulingEnabled","desktop.subagentsScheduling","desktop.subagentsSchedulingDesc"),D("scopeModels","desktop.subagentsScopeModels","desktop.subagentsScopeModelsDesc"),D("disableDefaultAgents","desktop.subagentsDisableDefault","desktop.subagentsDisableDefaultDesc"),D("fleetView","desktop.subagentsFleetView","desktop.subagentsFleetViewDesc"),(0,r.jsx)(iQ,{children:D("outputTranscript","desktop.subagentsOutputTranscript","desktop.subagentsOutputTranscriptDesc")})]}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10},children:[(0,r.jsx)("button",{type:"button",onClick:()=>void R(),disabled:f,style:{padding:"7px 12px",border:"none",borderRadius:6,background:"var(--accent)",color:"#fff",cursor:f?"wait":"pointer",fontSize:12},children:f?o("desktop.saving"):o("desktop.mcpSave")}),v&&(0,r.jsx)("span",{style:{color:"#22c55e",fontSize:12},children:o("desktop.subagentsSaved")}),m&&(0,r.jsx)("span",{style:{color:"#ef4444",fontSize:12},children:m}),(0,r.jsx)(ai,{sessionId:t})]}),a.length>0&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:7,fontSize:13,fontWeight:600,color:"var(--text)"},children:[(0,r.jsx)(iS.d,{size:15,"aria-hidden":"true"}),o("desktop.subagentsDiscovered")]}),(0,r.jsx)(iX,{children:a.map((e,t)=>(0,r.jsx)(iQ,{children:(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:3,padding:t===a.length-1?"12px 0":"12px 0 0"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[(0,r.jsx)("span",{style:{fontSize:12.5,fontWeight:600,color:"var(--text)",fontFamily:"var(--font-mono)"},children:e.name}),e.displayName&&(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-muted)"},children:e.displayName}),e.model&&(0,r.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,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6,flexWrap:"wrap"},children:[(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-muted)"},children:o("desktop.subagentsModel")}),(0,r.jsxs)("select",{value:e.model??"",onChange:t=>void I(e.name,t.target.value||null),style:{...ll,width:"min(260px, 100%)",maxWidth:260},children:[(0,r.jsx)("option",{value:"",children:o("desktop.subagentsModelDefault")}),e.model&&!b.some(t=>`${t.provider}/${t.id}`===e.model)&&(0,r.jsx)("option",{value:e.model,children:e.model}),b.map(e=>(0,r.jsxs)("option",{value:`${e.provider}/${e.id}`,children:[e.name,"(",e.provider,"/",e.id,")"]},`${e.provider}/${e.id}`))]}),"saving"===j[e.name]&&(0,r.jsxs)("span",{style:{fontSize:10,color:"var(--text-dim)"},children:[o("desktop.saving"),"…"]}),"saved"===j[e.name]&&(0,r.jsx)("span",{style:{fontSize:10,color:"#22c55e"},children:o("desktop.subagentsSaved")}),j[e.name]?.startsWith("error:")&&(0,r.jsx)("span",{style:{fontSize:10,color:"#ef4444"},children:j[e.name].slice(6)})]}),e.description&&(0,r.jsx)("div",{style:{fontSize:11,color:"var(--text-muted)",lineHeight:1.5},children:e.description})]})},e.name))})]})]}):(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)"},children:o("desktop.loading")})})})}function lp(e){return null==e?"—":sc(e)}function lu({sessionId:e,cwd:t}){let{t:o}=(0,E.s)(),[s,i]=(0,n.useState)(null),[a,l]=(0,n.useState)(null),[d,c]=(0,n.useState)(!1);(0,n.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,n.useCallback)(async()=>{c(!0);try{let e=await fetch("/api/usage");e.ok&&l(await e.json())}catch{}finally{c(!1)}},[]);(0,n.useEffect)(()=>{p()},[p]);let u=(0,n.useMemo)(()=>a?.daily.slice(-14)??[],[a]),g=(0,n.useMemo)(()=>u.reduce((e,t)=>Math.max(e,t.tokens),0),[u]);return(0,r.jsxs)("div",{style:{flex:1,overflow:"auto",minWidth:0,padding:"16px 20px",display:"flex",flexDirection:"column",gap:16},children:[(0,r.jsx)("h3",{style:{margin:0,fontSize:15,fontWeight:600,color:"var(--text)"},children:o("desktop.usage")}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text-muted)"},children:o("desktop.usageSession")}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:12},children:[e?(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:12,borderRadius:12,border:"1px solid var(--border)",padding:16},children:s?(0,r.jsx)(r.Fragment,{children:(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:16},children:[(0,r.jsxs)("svg",{width:72,height:72,viewBox:"0 0 72 72",style:{flexShrink:0},children:[(0,r.jsx)("circle",{cx:36,cy:36,r:30,fill:"none",stroke:"var(--border)",strokeWidth:7}),(0,r.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,r.jsx)("text",{x:36,y:41,textAnchor:"middle",fontSize:15,fontWeight:700,fill:"var(--text)",children:null!=s.percent?`${s.percent.toFixed(0)}%`:"?"})]}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:3},children:[(0,r.jsx)("span",{style:{fontSize:13,color:"var(--text)"},children:o("desktop.usageContext",{used:lp(s.tokens),window:lp(s.contextWindow)})}),(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)"},children:o("desktop.usageContextHint")})]})]})}):(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)"},children:o("desktop.usageNoSessionData")})}):(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)"},children:o("desktop.usageNoSession")}),t&&(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:t})]})]}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text-muted)"},children:o("desktop.usageGlobal")}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,r.jsx)("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(140px, 1fr))",gap:10},children:[{label:o("desktop.usageTotal"),value:lp(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,r.jsxs)("div",{style:{borderRadius:12,border:"1px solid var(--border)",padding:"12px 14px",background:"var(--bg-panel)"},children:[(0,r.jsx)("div",{style:{fontSize:11,color:"var(--text-muted)",marginBottom:4},children:e.label}),(0,r.jsx)("div",{style:{fontSize:18,fontWeight:700,color:"var(--text)"},children:e.value}),(0,r.jsx)("div",{style:{fontSize:10.5,color:"var(--text-dim)",marginTop:2},children:e.sub})]},e.label))}),(0,r.jsxs)("div",{style:{borderRadius:12,border:"1px solid var(--border)",padding:"14px 16px"},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)",marginBottom:10},children:o("desktop.usageDaily")}),0===u.length?(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)"},children:o(d?"desktop.featuresLoading":"desktop.usageNoData")}):(0,r.jsx)("div",{style:{display:"flex",alignItems:"flex-end",gap:6,height:96,overflowX:"auto"},children:u.map(e=>{let t=g>0?Math.max(4,Math.round(e.tokens/g*72)):4;return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",gap:4,flexShrink:0},children:[(0,r.jsx)("div",{style:{fontSize:9,color:"var(--text-dim)"},children:e.tokens>0?lp(e.tokens):""}),(0,r.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}: ${lp(e.tokens)}`}),(0,r.jsx)("div",{style:{fontSize:9,color:"var(--text-dim)"},children:e.day.slice(5)})]},e.day)})})]}),(0,r.jsxs)("div",{style:{borderRadius:12,border:"1px solid var(--border)",overflow:"hidden"},children:[(0,r.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,r.jsx)("div",{style:{padding:"14px",fontSize:12,color:"var(--text-muted)"},children:o("desktop.usageNoData")}):(a?.sessions??[]).slice(0,12).map(e=>(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"8px 14px",borderBottom:"1px solid var(--border)"},children:[(0,r.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,r.jsx)("span",{style:{flexShrink:0,fontSize:11,color:"var(--text-muted)",fontFamily:"var(--font-mono)"},children:lp(e.tokens)})]},e.path))]})]})]})]})}function lg(){let{t:e}=(0,E.s)(),[t,o]=(0,n.useState)(!1),[s,i]=(0,n.useState)("");(0,n.useEffect)(()=>{o(new URLSearchParams(window.location.search).has("piweb_connected")),i(window.location.host)},[]);let a=(0,n.useCallback)(()=>{window.location.href="piweb-switch://manage"},[]);return t?(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",flex:1,minWidth:0,minHeight:0,overflowY:"auto"},children:[(0,r.jsx)("header",{style:{padding:"18px 22px 14px",borderBottom:"1px solid var(--border)"},children:(0,r.jsx)("h1",{style:{margin:0,fontSize:16,fontWeight:700,color:"var(--text)"},children:e("desktop.server")})}),(0,r.jsxs)("div",{style:{padding:"18px 22px",display:"flex",flexDirection:"column",gap:14},children:[(0,r.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,r.jsx)(ik.X,{size:18,color:"var(--accent)"}),(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)"},children:e("desktop.serverCurrent")}),(0,r.jsx)("div",{style:{fontSize:14,fontWeight:600,color:"var(--text)",fontFamily:"var(--font-mono)",wordBreak:"break-all"},children:s})]})]}),(0,r.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,r.jsx)(i3.o,{size:16}),e("desktop.serverSwitch")]}),(0,r.jsx)("p",{style:{margin:0,fontSize:12.5,lineHeight:1.7,color:"var(--text-muted)"},children:e("desktop.serverSwitchHint")})]})]}):null}let lh=[{id:"server",labelKey:"desktop.server",Icon:ik.X},{id:"display",labelKey:"desktop.display",Icon:iv.V},{id:"chat",labelKey:"desktop.chat",Icon:iy.W},{id:"models",labelKey:"desktop.models",Icon:C.f},{id:"skills",labelKey:"desktop.skills",Icon:T.B},{id:"plugins",labelKey:"desktop.plugins",Icon:R.F},{id:"proxy",labelKey:"desktop.proxy",Icon:ib.l},{id:"features",labelKey:"desktop.features",Icon:p.l},{id:"logs",labelKey:"desktop.logs",Icon:v.B},{id:"snippets",labelKey:"desktop.snippets",Icon:rP.c},{id:"usage",labelKey:"desktop.usage",Icon:iw._},{id:"mcp",labelKey:"desktop.mcp",Icon:ij.b},{id:"subagents",labelKey:"desktop.subagents",Icon:iS.d},{id:"backup",labelKey:"desktop.backup",Icon:oj.W},{id:"import",labelKey:"desktop.importSessions",Icon:z.z}];function lf({initialTab:e="models",cwd:t,sessionId:o,onCloseAction:s,onModelsSavedAction:i,onSessionReloadedAction:a,onSessionsChanged:l}){let d=$(),{t:p}=(0,E.s)(),[u,g]=(0,n.useState)("skills"===e||"plugins"===e?t?e:"display":e),[h,f]=(0,n.useState)(!1);(0,n.useEffect)(()=>{f(new URLSearchParams(window.location.search).has("piweb_connected"))},[]);let x=h?lh:lh.filter(({id:e})=>"server"!==e),[m,k]=(0,n.useState)(!1),[v,y]=(0,n.useState)(null),b=(0,n.useRef)(new Set),w=(0,n.useCallback)(e=>(b.current.add(e),()=>{b.current.delete(e)}),[]),j=(0,n.useCallback)(async()=>{if(!m){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)}}},[m,s]);return(0,r.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,r.jsxs)("section",{role:"dialog","aria-modal":"true","aria-label":p("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,r.jsxs)("header",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 18px",borderBottom:"1px solid var(--border)",flexShrink:0},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"baseline",gap:10,minWidth:0},children:[(0,r.jsx)("span",{style:{fontSize:15,fontWeight:700,color:"var(--text)"},children:p("desktop.settings")}),"models"===u?(0,r.jsx)("code",{style:{fontSize:11,color:"var(--text-muted)",fontFamily:"var(--font-mono)"},children:"~/.pi/agent/models.json"}):t&&(0,r.jsx)("code",{style:{fontSize:11,color:"var(--text-muted)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:t})]}),(0,r.jsx)("button",{type:"button",onClick:()=>{j()},disabled:m,title:p("desktop.closeSettings"),"aria-label":p("desktop.closeSettings"),style:{background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",padding:4,display:"flex"},children:(0,r.jsx)(c.X,{size:18,"aria-hidden":"true"})})]}),(0,r.jsxs)("div",{style:{flex:1,display:"flex",flexDirection:d?"column":"row",minHeight:0,overflow:"hidden",pointerEvents:m?"none":void 0},children:[(0,r.jsx)("nav",{"aria-label":p("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:x.filter(({id:e})=>!(d&&"import"===e)).map(({id:e,labelKey:o,Icon:n})=>{let s=("skills"===e||"plugins"===e)&&!t,i=u===e;return(0,r.jsxs)("button",{type:"button",disabled:s,onClick:()=>g(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:p(o),"aria-label":p(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,r.jsx)(n,{size:16,"aria-hidden":"true"}),!d&&(0,r.jsx)("span",{children:p(o)})]},e)})}),(0,r.jsx)("div",{style:{display:"server"===u?"flex":"none",flex:1,minWidth:0,minHeight:0},children:(0,r.jsx)(lg,{})}),(0,r.jsx)("div",{style:{display:"display"===u?"flex":"none",flex:1,minWidth:0,minHeight:0},children:(0,r.jsx)(iG,{})}),(0,r.jsx)("div",{style:{display:"chat"===u?"flex":"none",flex:1,minWidth:0,minHeight:0},children:(0,r.jsx)(iW,{})}),(0,r.jsx)("div",{style:{display:"models"===u?"flex":"none",flex:1,minWidth:0,minHeight:0},children:(0,r.jsx)(aA,{embedded:!0,sessionId:o,onSavedAction:i,onRegisterFlush:w})}),t&&(0,r.jsx)("div",{style:{display:"skills"===u?"flex":"none",flex:1,minWidth:0,minHeight:0},children:(0,r.jsx)(le,{cwd:t,embedded:!0,sessionId:o})}),t&&(0,r.jsx)("div",{style:{display:"plugins"===u?"flex":"none",flex:1,minWidth:0,minHeight:0},children:(0,r.jsx)(aQ,{cwd:t,sessionId:o,embedded:!0,onReloadedAction:a})}),(0,r.jsx)("div",{style:{display:"proxy"===u?"flex":"none",flex:1,minWidth:0,minHeight:0},children:(0,r.jsx)(a1,{})}),(0,r.jsx)("div",{style:{display:"features"===u?"flex":"none",flex:1,minWidth:0,minHeight:0},children:(0,r.jsx)(i5,{})}),(0,r.jsx)("div",{style:{display:"logs"===u?"flex":"none",flex:1,minWidth:0,minHeight:0},children:(0,r.jsx)(lt,{})}),(0,r.jsx)("div",{style:{display:"snippets"===u?"flex":"none",flex:1,minWidth:0,minHeight:0},children:(0,r.jsx)(ln,{})}),(0,r.jsx)("div",{style:{display:"usage"===u?"flex":"none",flex:1,minWidth:0,minHeight:0},children:(0,r.jsx)(lu,{sessionId:o,cwd:t})}),(0,r.jsx)("div",{style:{display:"mcp"===u?"flex":"none",flex:1,minWidth:0,minHeight:0},children:(0,r.jsx)(ag,{sessionId:o})}),(0,r.jsx)("div",{style:{display:"subagents"===u?"flex":"none",flex:1,minWidth:0,minHeight:0},children:(0,r.jsx)(lc,{cwd:t,sessionId:o})}),(0,r.jsx)("div",{style:{display:"backup"===u?"flex":"none",flex:1,minWidth:0,minHeight:0},children:(0,r.jsx)(iz,{cwd:t})}),(0,r.jsx)("div",{style:{display:"import"===u?"flex":"none",flex:1,minWidth:0,minHeight:0,overflowY:"auto"},children:(0,r.jsx)(i7,{onSessionsChanged:l})})]}),v&&(0,r.jsx)("div",{style:{padding:"6px 18px",borderTop:"1px solid var(--border)",color:"#f87171",fontSize:11},children:v})]})})}let lx=new Set(["awaiting_input","review","failed"]),lm=(0,n.createContext)(null);function lk(){let e=(0,n.useContext)(lm);if(!e)throw Error("useTasksView must be used within TasksViewProvider");return e}function lv({children:e}){let{t}=(0,E.s)(),o=(0,n.useRef)(t);(0,n.useEffect)(()=>{o.current=t},[t]);let[s,i]=(0,n.useState)([]),[a,l]=(0,n.useState)([]),d=(0,n.useRef)(0),c=(0,n.useCallback)(async()=>{let e=++d.current;try{let t=await (0,r2.Wt)(),o=(await Promise.all(t.map(e=>(0,r2.Vk)(e).catch(()=>[])))).flat().sort((e,t)=>t.id-e.id);if(e!==d.current)return;l(e=>ly(e,t)?e:t),i(e=>ly(e,o)?e:o)}catch{}},[]);(0,n.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 r=()=>{"visible"===document.visibilityState&&c()},n=()=>void c();document.addEventListener("visibilitychange",r),window.addEventListener("online",n);let s=setInterval(()=>void c(),6e4);return()=>{t=!0,e?.close(),document.removeEventListener("visibilitychange",r),window.removeEventListener("online",n),clearInterval(s)}},[c]);let p=(0,n.useMemo)(()=>s.filter(e=>lx.has(e.status)&&null==e.archivedAt).length,[s]),u=(0,n.useRef)(null);(0,n.useEffect)(()=>{let e=u.current;if((u.current=new Map(s.map(e=>[e.id,e.status])),e&&0!==s.length)&&"Notification"in window){for(let 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 r=()=>{try{new Notification(e,{body:t,tag:"pi-tasks"})}catch{}o()};"granted"===Notification.permission?r():"denied"!==Notification.permission?Notification.requestPermission().then(e=>{"granted"===e?r():o()}):o()})}("Pi Web Tasks",e)}catch{}}},[s,t]);let g=(0,n.useMemo)(()=>({tasks:s,projects:a,attentionCount:p,refetch:c}),[s,a,p,c]);return(0,r.jsx)(lm.Provider,{value:g,children:e})}function ly(e,t){return JSON.stringify(e)===JSON.stringify(t)}var lb=o(4539),lw=o(12449),lj=o(2571);let lS=["todo","inProgress","attention","done"];function lC(e){return"review"===e.status&&0===e.filesChanged}function lT(){return{defaultAgentType:null,modeId:null,configValues:{},autoProcess:!0,maxConcurrent:1,mergeStrategy:"merge",deleteWorktreeDefault:!0,preflightCommand:null,initCommand:null,stagePrompts:null}}let lR=["todo","inProgress","attention","done"],lz={todo:{id:"todo",marker:"var(--text-dim)"},inProgress:{id:"inProgress",marker:"var(--accent)"},attention:{id:"attention",marker:"#f59e0b"},done:{id:"done",marker:"#10b981"}};var lI=o(54775),lM=o(98998),lE=o(36668);function lP({task:e}){let{t}=(0,E.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)),n={display:"inline-flex",alignItems:"center",gap:4,borderRadius:999,padding:"2px 8px",fontSize:10,fontWeight:600,lineHeight:1.4,flexShrink:0,whiteSpace:"nowrap"};switch(e.status){case"queued":case"preparing":case"running":case"merging":return(0,r.jsxs)("span",{style:{...n,color:"var(--accent)"},children:[(0,r.jsx)(lI.N,{size:11,className:"pi-spin",style:{animation:"pi-spin 1s linear infinite"},"aria-hidden":"true"}),o]});case"awaiting_input":case"review":return(0,r.jsx)("span",{style:{...n,border:"1px solid rgba(245,158,11,0.45)",background:"rgba(245,158,11,0.08)",color:"#d97706"},children:o});case"done":return(0,r.jsxs)("span",{style:{...n,background:"rgba(16,185,129,0.12)",color:"#059669"},children:[(0,r.jsx)(u.J,{size:10,weight:"bold","aria-hidden":"true"}),o]});case"failed":return(0,r.jsx)("span",{style:{...n,background:"rgba(239,68,68,0.12)",color:"#dc2626"},children:o});default:return(0,r.jsx)("span",{style:{...n,background:"var(--bg-hover)",color:"var(--text-muted)"},children:o})}}function lD({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,r.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,r.jsx)(lI.N,{size:10,style:{animation:"pi-spin 1s linear infinite"},"aria-hidden":"true"}):"passed"===t.status?(0,r.jsx)(oZ.r,{size:10,"aria-hidden":"true"}):(0,r.jsx)(sh.J,{size:10,"aria-hidden":"true"}),(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:t.command})]})}function lF({task:e,folderName:t,now:o,onOpen:n,onStart:s,onCancel:i,onRetry:a,onRequeue:l,onViewSession:d,onMerge:c,onArchive:p,onEdit:g}){let{t:h}=(0,E.s)(),f=null!=e.archivedAt,x="running"===e.status||"awaiting_input"===e.status||"merging"===e.status,m=null!=e.filesChanged&&e.filesChanged>0?(0,r.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:3,fontFamily:"var(--font-mono)",fontSize:10},children:[(0,r.jsxs)("span",{style:{color:"#059669"},children:["+",e.additions??0]}),(0,r.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 r=Math.floor(Math.max(0,t-o)/6e4);if(r<1)return"now";if(r<60)return`${r}m`;let n=Math.floor(r/60);if(n<24)return`${n}h`;let s=Math.floor(n/24);return`${s}d`}(e.finishedAt??e.settledAt??e.startedAt??e.createdAt,o),{primary:v,more:y}=(()=>{let t=[],o=null;if(f)return{primary:o={icon:sx.T,label:h("tasks.actionUnarchive"),onClick:p},more:t};switch(e.status){case"todo":o={icon:lj.j,label:h("tasks.actionStart"),onClick:s},t.push({icon:rD.S,label:h("tasks.actionEdit"),onClick:g});break;case"queued":case"preparing":case"running":case"awaiting_input":o={icon:lM.k,label:h("tasks.actionCancel"),onClick:i};break;case"review":o=lC(e)?{icon:u.J,label:h("tasks.actionComplete"),onClick:c}:{icon:lE.r,label:h("tasks.actionMerge"),onClick:c};break;case"merging":break;case"failed":o={icon:w.S,label:h("tasks.actionRetry"),onClick:a},t.push({icon:rD.S,label:h("tasks.actionEdit"),onClick:g}),t.push({icon:sx.T,label:h("tasks.actionArchive"),onClick:p});break;case"done":o={icon:sx.T,label:h("tasks.actionArchive"),onClick:p};break;case"canceled":o={icon:oQ.f,label:h("tasks.actionRequeue"),onClick:l},t.push({icon:sx.T,label:h("tasks.actionArchive"),onClick:p})}return{primary:o,more:t}})(),b=[...y];return null!=e.conversationId&&b.push({icon:oX.y,label:h("tasks.actionViewSession"),onClick:d}),(0,r.jsxs)("div",{role:"button",tabIndex:0,onClick:n,onKeyDown:e=>{("Enter"===e.key||" "===e.key)&&(e.preventDefault(),n())},style:{display:"flex",flexDirection:"column",cursor:"pointer",borderRadius:12,border:"1px solid color-mix(in srgb, var(--border) 85%, transparent)",background:"var(--bg-panel)",padding:12,textAlign:"left",transition:"border-color 0.12s",opacity:f?.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,r.jsxs)("div",{style:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:8},children:[(0,r.jsx)("span",{style:{minWidth:0,overflowWrap:"break-word",fontSize:13,fontWeight:500,lineHeight:1.4},children:e.title}),(0,r.jsx)(lP,{task:e})]}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:"2px 6px",marginTop:6,fontSize:11,color:"var(--text-muted)"},children:[t?(0,r.jsx)("span",{style:{maxWidth:160,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:t}):null,t&&e.workBranch?(0,r.jsx)("span",{style:{opacity:.5},children:"/"}):null,e.workBranch?(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:10,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",maxWidth:180},children:e.workBranch}):null,(t||e.workBranch)&&(m||k)?(0,r.jsx)("span",{style:{opacity:.5},children:"\xb7"}):null,m,m&&k?(0,r.jsx)("span",{style:{opacity:.5},children:"\xb7"}):null,k?(0,r.jsx)("span",{style:{flexShrink:0},children:k}):null,(0,r.jsx)(lD,{task:e})]}),e.lastError&&("failed"===e.status||"review"===e.status)?(0,r.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,r.jsx)(oS.t,{size:13,style:{flexShrink:0},"aria-hidden":"true"}),(0,r.jsx)("span",{style:{minWidth:0,flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.lastError}),(0,r.jsx)("button",{type:"button",style:{flexShrink:0,fontWeight:600,background:"none",border:"none",cursor:"pointer",color:"inherit",fontSize:11,textDecoration:"underline"},onClick:e=>{e.stopPropagation(),n()},children:h("tasks.errorView")})]}):null,"review"===e.status&&e.resultSummary?(0,r.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,x&&e.latestProgress?(0,r.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,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6,marginTop:12,paddingTop:12,borderTop:"1px solid var(--border)"},children:[v?(0,r.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,r.jsx)(v.icon,{size:12,weight:"bold","aria-hidden":"true"}),v.label]}):null,(0,r.jsx)("div",{style:{flex:1}}),b.map(e=>(0,r.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,r.jsx)(e.icon,{size:13,"aria-hidden":"true"})},e.label))]}):null]})}function lW({open:e,onOpenChange:t,task:o}){let{t:s}=(0,E.s)(),{refetch:i}=lk(),[a,l]=(0,n.useState)(""),[d,p]=(0,n.useState)(!1);if((0,n.useEffect)(()=>{e&&(l(""),p(!1))},[e,o]),!e||!o)return null;let u=async()=>{if(!d){p(!0);try{await (0,r2.oQ)(o.id,o.projectRoot,"cancel",{reason:a.trim()||null}),t(!1),i()}catch(e){console.error("cancel failed",e)}finally{p(!1)}}};return(0,r.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,r.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,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"14px 16px 0"},children:[(0,r.jsx)("h3",{style:{fontSize:15,fontWeight:600,margin:0},children:s("tasks.cancelTitle")}),(0,r.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,r.jsx)(c.X,{size:16,"aria-hidden":"true"})})]}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:12,padding:"14px 16px 16px"},children:[(0,r.jsx)("p",{style:{margin:0,fontSize:12,lineHeight:1.5,color:"var(--text-muted)"},children:s("tasks.cancelDescription")}),(0,r.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:5},children:[(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)"},children:s("tasks.cancelReasonLabel")}),(0,r.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,r.jsxs)("div",{style:{display:"flex",justifyContent:"flex-end",gap:8,marginTop:4},children:[(0,r.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,r.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 l$({open:e,onOpenChange:t,task:o}){let{t:s}=(0,E.s)(),{refetch:i}=lk(),[a,l]=(0,n.useState)(!0),[d,p]=(0,n.useState)(!1),u=o?.worktreePath!=null;if((0,n.useEffect)(()=>{if(!e||!o)return;p(!1);let t=!1;return(0,r2.CG)(o.projectRoot).then(e=>{t||l(e.deleteWorktreeDefault)}).catch(()=>{t||l(!0)}),()=>{t=!0}},[e,o]),!e||!o)return null;let g=async()=>{if(!d){p(!0);try{await (0,r2.ZX)(o.id,o.projectRoot,u&&a),t(!1),i()}catch(e){console.error("complete failed",e)}finally{p(!1)}}};return(0,r.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,r.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,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"14px 16px 0"},children:[(0,r.jsx)("h3",{style:{fontSize:15,fontWeight:600,margin:0},children:s("tasks.completeTitle")}),(0,r.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,r.jsx)(c.X,{size:16,"aria-hidden":"true"})})]}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:12,padding:"14px 16px 16px"},children:[(0,r.jsx)("p",{style:{margin:0,fontSize:12,lineHeight:1.5,color:"var(--text-muted)"},children:s("tasks.completeDescription")}),u?(0,r.jsxs)("label",{style:{display:"flex",alignItems:"center",gap:8,fontSize:13,cursor:"pointer"},children:[(0,r.jsx)("input",{type:"checkbox",checked:a,onChange:e=>l(e.target.checked),style:{accentColor:"var(--accent)"}}),s("tasks.completeDeleteWorktree")]}):null,(0,r.jsxs)("div",{style:{display:"flex",justifyContent:"flex-end",gap:8,marginTop:4},children:[(0,r.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,r.jsx)("button",{type:"button",onClick:()=>void g(),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 lN=o(51285),lL=o(16894);function lA({open:e,onOpenChange:t,task:o,onViewSession:s,onMerge:i,onEdit:a,onCancel:l,onRetry:d,onRequeue:p,onComplete:g}){let{t:h}=(0,E.s)(),{refetch:f}=lk(),[x,k]=(0,n.useState)([]),[v,y]=(0,n.useState)([]),[b,S]=(0,n.useState)(null),[C,T]=(0,n.useState)(null),[R,z]=(0,n.useState)(!1),[I,M]=(0,n.useState)(!1),[P,D]=(0,n.useState)(""),[F,W]=(0,n.useState)(!1),[$,N]=(0,n.useState)(!1),[L,A]=(0,n.useState)(!1),O=o?.id??null,H=o?.projectRoot??null,B=(0,n.useCallback)(async()=>{if(null==O||null==H)return;let[e,t]=await Promise.all([(0,r2.HB)(H,O).catch(()=>[]),o?.worktreePath?(0,r2.JH)(H,O).then(e=>e.files).catch(()=>[]):Promise.resolve([])]);k(e),y(t)},[O,H,o?.worktreePath]);(0,n.useEffect)(()=>{if(!e||null==O)return;k([]),y([]),M(!1),D(""),B();let t=window.setInterval(()=>void B(),5e3);return()=>window.clearInterval(t)},[e,O,B]);let U=(0,n.useCallback)(async e=>{A(!0);try{await e()}catch(e){console.error("detail action failed",e)}finally{A(!1),f()}},[f]),_=(0,n.useCallback)(async e=>{if(null!=H&&null!=O){z(!0);try{let t=await (0,r2.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,r2.bH)(o.id,H,$)),t(!1))},V=async()=>{null!=o&&null!=H&&P.trim()&&(await U(()=>(0,r2.in)(o.id,H,P.trim())),M(!1),D(""))};if(!e||null==o||null==H)return null;let K=[];if(null==o.archivedAt)switch(o.status){case"todo":K.push({label:h("tasks.actionStart"),icon:lj.j,onClick:()=>void U(()=>(0,r2.oQ)(o.id,H,"start")),filled:!0}),K.push({label:h("tasks.actionEdit"),icon:rD.S,onClick:()=>a(o)});break;case"queued":case"preparing":case"running":case"awaiting_input":K.push({label:h("tasks.actionCancel"),icon:lM.k,onClick:()=>l(o),danger:!0});break;case"review":K.push({label:lC(o)?h("tasks.actionComplete"):h("tasks.actionMerge"),icon:lC(o)?u.J:lN.Y,onClick:()=>lC(o)?g(o):i(o),filled:!0}),K.push({label:h("tasks.actionReturn"),icon:oQ.f,onClick:()=>M(!0)});break;case"failed":K.push({label:h("tasks.actionRetry"),icon:w.S,onClick:()=>d(o),filled:!0}),K.push({label:h("tasks.actionEdit"),icon:rD.S,onClick:()=>a(o)});break;case"done":K.push({label:h("tasks.actionArchive"),icon:sx.T,onClick:()=>void U(()=>(0,r2.et)(o.id,H,!0))});break;case"canceled":K.push({label:h("tasks.actionRequeue"),icon:oQ.f,onClick:()=>p(o),filled:!0})}else K.push({label:h("tasks.actionUnarchive"),icon:sx.T,onClick:()=>void U(()=>(0,r2.et)(o.id,H,!1))});return null!=o.conversationId&&K.push({label:h("tasks.actionViewSession"),icon:oX.y,onClick:()=>s(o)}),(0,r.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,r.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,r.jsxs)("div",{style:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:12,padding:"16px 16px 0"},children:[(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("h3",{style:{margin:0,fontSize:15,fontWeight:600,lineHeight:1.4,overflowWrap:"break-word"},children:o.title}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,marginTop:6},children:[(0,r.jsx)(lP,{task:o}),o.workBranch?(0,r.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:4,fontFamily:"var(--font-mono)",fontSize:11,color:"var(--text-muted)"},children:[(0,r.jsx)(m.Z,{size:12,"aria-hidden":"true"}),o.workBranch]}):null]})]}),(0,r.jsx)("button",{type:"button",onClick:()=>t(!1),"aria-label":h("i18n.close"),style:{background:"none",border:"none",cursor:"pointer",color:"var(--text-muted)",padding:4,display:"flex",flexShrink:0},children:(0,r.jsx)(c.X,{size:16,"aria-hidden":"true"})})]}),(0,r.jsx)("div",{style:{display:"flex",flexWrap:"wrap",gap:8,padding:"14px 16px 0"},children:K.map(e=>{let t,o;return(0,r.jsxs)("button",{type:"button",onClick:e.onClick,disabled:L,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,r.jsx)(e.icon,{size:13,weight:"bold","aria-hidden":"true"}),e.label]},e.label)})}),I&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:8,padding:"12px 16px 0"},children:[(0,r.jsx)("textarea",{value:P,onChange:e=>D(e.target.value),placeholder:h("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,r.jsxs)("div",{style:{display:"flex",justifyContent:"flex-end",gap:8},children:[(0,r.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:h("i18n.cancel")}),(0,r.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:h("tasks.returnSubmit")})]})]}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:6,padding:"14px 16px 0",fontSize:12,color:"var(--text-muted)"},children:[(0,r.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,r.jsx)("span",{style:{flexShrink:0,color:"var(--text-dim)",width:64},children:h("tasks.metaProject")}),(0,r.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontFamily:"var(--font-mono)",fontSize:11},children:o.projectRoot})]}),o.createdAt?(0,r.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,r.jsx)("span",{style:{flexShrink:0,color:"var(--text-dim)",width:64},children:h("tasks.metaCreated")}),(0,r.jsx)("span",{children:new Date(o.createdAt).toLocaleString()})]}):null,o.mergeCommit?(0,r.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,r.jsx)("span",{style:{flexShrink:0,color:"var(--text-dim)",width:64},children:h("tasks.metaCommit")}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:11},children:o.mergeCommit})]}):null]}),v.length>0&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4,padding:"14px 16px 0"},children:[(0,r.jsx)("span",{style:{fontSize:11,fontWeight:600,color:"var(--text-muted)",textTransform:"uppercase",letterSpacing:"0.05em"},children:h("tasks.changedFiles")}),(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:2,maxHeight:140,overflowY:"auto"},children:v.map(e=>(0,r.jsxs)("button",{type:"button",onClick:()=>{var t;S(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,r.jsx)(lL.o,{size:13,style:{flexShrink:0,color:"var(--text-muted)"},"aria-hidden":"true"}),(0,r.jsx)("span",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontFamily:"var(--font-mono)",fontSize:11},children:e.file}),(0,r.jsxs)("span",{style:{fontFamily:"var(--font-mono)",fontSize:10,color:"#059669",flexShrink:0},children:["+",e.additions]}),(0,r.jsxs)("span",{style:{fontFamily:"var(--font-mono)",fontSize:10,color:"#dc2626",flexShrink:0},children:["-",e.deletions]})]},e.file))})]}),null!=b&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:6,padding:"12px 16px 0",minHeight:0,flexShrink:0},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[(0,r.jsx)("span",{style:{fontSize:11,fontWeight:600,color:"var(--text-muted)"},children:h("tasks.diff")}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:10,color:"var(--text-muted)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1},children:b}),(0,r.jsx)("button",{type:"button",onClick:()=>S(null),style:{background:"none",border:"none",cursor:"pointer",color:"var(--text-muted)",padding:2,display:"flex"},children:(0,r.jsx)(c.X,{size:12,"aria-hidden":"true"})})]}),R?(0,r.jsx)("div",{style:{fontSize:11,color:"var(--text-muted)",padding:8},children:h("tasks.loading")}):C?(0,r.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,r.jsx)("div",{style:{color:o},children:e||" "},t)})}):(0,r.jsx)("div",{style:{fontSize:11,color:"var(--text-muted)",padding:8},children:h("tasks.noDiff")})]}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4,padding:"14px 16px 0",flex:1,minHeight:0},children:[(0,r.jsx)("span",{style:{fontSize:11,fontWeight:600,color:"var(--text-muted)",textTransform:"uppercase",letterSpacing:"0.05em"},children:h("tasks.timeline")}),(0,r.jsx)("div",{style:{flex:1,minHeight:0,overflowY:"auto",paddingBottom:8},children:0===x.length?(0,r.jsx)("div",{style:{fontSize:11,color:"var(--text-dim)",padding:8},children:h("tasks.noEvents")}):(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:2},children:[...x].reverse().map(e=>{var t;let o,n;return(0,r.jsxs)("div",{style:{display:"flex",gap:8,padding:"4px 6px",borderRadius:6,fontSize:11},children:[(0,r.jsx)("span",{style:{color:"var(--text-dim)",flexShrink:0,fontFamily:"var(--font-mono)",fontSize:10,paddingTop:1},children:new Date(e.createdAt).toLocaleTimeString()}),(0,r.jsx)("span",{style:{color:"var(--text)",flexShrink:0,fontWeight:500},children:(t=e.kind,(n=h(o=`tasks.event_${t}`))===o?t:n)}),e.payload?.feedback?(0,r.jsx)("span",{style:{color:"var(--text-muted)",fontStyle:"italic",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:String(e.payload.feedback)}):null]},e.id)})})})]}),(0,r.jsx)("div",{style:{display:"flex",alignItems:"center",justifyContent:"flex-end",gap:8,padding:"10px 16px",borderTop:"1px solid var(--border)",flexShrink:0},children:F?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("label",{style:{display:"flex",alignItems:"center",gap:6,fontSize:12,cursor:"pointer"},children:[(0,r.jsx)("input",{type:"checkbox",checked:$,onChange:e=>N(e.target.checked),style:{accentColor:"var(--accent)"}}),h("tasks.deleteWorktree")]}),(0,r.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:h("i18n.cancel")}),(0,r.jsx)("button",{type:"button",onClick:()=>void q(),disabled:L,style:{padding:"6px 14px",borderRadius:8,background:"#dc2626",color:"#fff",border:"none",fontSize:12,fontWeight:600,cursor:"pointer"},children:h("tasks.deleteConfirm")})]}):(0,r.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,r.jsx)(j.l,{size:13,"aria-hidden":"true"}),h("tasks.delete")]})})]})})}var lO=o(17757);function lH({open:e,onOpenChange:t,task:o,defaultProject:s,projects:i,prefillTitle:a,prefillPrompt:l,onSubmit:d}){let{t:p}=(0,E.s)(),[u,g]=(0,n.useState)(""),[h,f]=(0,n.useState)(""),[x,m]=(0,n.useState)(""),[k,v]=(0,n.useState)([]),[y,b]=(0,n.useState)(""),[w,S]=(0,n.useState)(!1),C=(0,n.useRef)(!1);if((0,n.useEffect)(()=>{if(!e){C.current=!1;return}C.current||(C.current=!0,g(o?.projectRoot??s??i[0]??""),f(o?.title??a??""),m(o?.config?.prompt??l??""),(0,r2.VB)().then(v).catch(()=>void 0))},[e,o,s,i,a,l]),!e)return null;let T=async()=>{if(u&&h.trim()&&!w){S(!0);try{await d(u,h.trim(),{prompt:x.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{S(!1)}}},R=async()=>{if(y.trim()&&h.trim())try{await (0,r2.nY)({name:y.trim(),title:h.trim(),config:{prompt:x.trim()}}),b(""),(0,r2.VB)().then(v).catch(()=>void 0)}catch(e){console.error("save template failed",e)}},z=async e=>{try{await (0,r2.B_)(e),(0,r2.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,r.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,r.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,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"14px 16px 0"},children:[(0,r.jsx)("h3",{style:{fontSize:15,fontWeight:600,margin:0},children:o?p("tasks.editTitle"):p("tasks.newTitle")}),(0,r.jsx)("button",{type:"button",onClick:()=>t(!1),"aria-label":p("i18n.close"),style:{background:"none",border:"none",cursor:"pointer",color:"var(--text-muted)",padding:4,display:"flex"},children:(0,r.jsx)(c.X,{size:16,"aria-hidden":"true"})})]}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:12,padding:"14px 16px 16px"},children:[k.length>0&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,r.jsx)("span",{style:{fontSize:11,fontWeight:600,color:"var(--text-muted)",textTransform:"uppercase",letterSpacing:"0.05em"},children:p("tasks.templates")}),(0,r.jsx)("div",{style:{display:"flex",flexWrap:"wrap",gap:6},children:k.map(e=>(0,r.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:4,borderRadius:999,background:"var(--bg-hover)",padding:"3px 8px",fontSize:11},children:[(0,r.jsx)("button",{type:"button",onClick:()=>{f(e.title),m(e.config?.prompt??"")},style:{background:"none",border:"none",cursor:"pointer",color:"var(--text)",fontSize:11,padding:0},children:e.name}),(0,r.jsx)("button",{type:"button",onClick:()=>void z(e.id),"aria-label":p("tasks.deleteTemplate"),style:{background:"none",border:"none",cursor:"pointer",color:"var(--text-dim)",padding:0,display:"flex"},children:(0,r.jsx)(j.l,{size:10,"aria-hidden":"true"})})]},e.id))})]}),(0,r.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,r.jsx)("span",{style:{fontSize:12,fontWeight:500,color:"var(--text)"},children:p("tasks.fieldProject")}),(0,r.jsx)("select",{value:u,onChange:e=>g(e.target.value),style:I,children:i.map(e=>(0,r.jsx)("option",{value:e,children:e.split("/").filter(Boolean).pop()??e},e))})]}),(0,r.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,r.jsx)("span",{style:{fontSize:12,fontWeight:500,color:"var(--text)"},children:p("tasks.fieldTitle")}),(0,r.jsx)("input",{value:h,onChange:e=>f(e.target.value),placeholder:p("tasks.fieldTitlePlaceholder"),style:I,autoFocus:!0})]}),(0,r.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,r.jsx)("span",{style:{fontSize:12,fontWeight:500,color:"var(--text)"},children:p("tasks.fieldPrompt")}),(0,r.jsx)("textarea",{value:x,onChange:e=>m(e.target.value),placeholder:p("tasks.fieldPromptPlaceholder"),rows:6,style:{...I,resize:"vertical",fontFamily:"inherit",lineHeight:1.5}})]}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6},children:[(0,r.jsx)("input",{value:y,onChange:e=>b(e.target.value),placeholder:p("tasks.templateNamePlaceholder"),style:{...I,flex:1}}),(0,r.jsxs)("button",{type:"button",onClick:()=>void R(),disabled:!y.trim()||!h.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,r.jsx)(lO.D,{size:13,"aria-hidden":"true"}),p("tasks.saveAsTemplate")]})]}),(0,r.jsxs)("div",{style:{display:"flex",justifyContent:"flex-end",gap:8,marginTop:4},children:[(0,r.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:p("i18n.cancel")}),(0,r.jsx)("button",{type:"button",onClick:()=>void T(),disabled:!u||!h.trim()||w,style:{padding:"8px 16px",borderRadius:8,background:"var(--accent)",color:"#fff",border:"none",fontSize:12,fontWeight:600,cursor:"pointer"},children:p("tasks.save")})]})]})]})})}function lB({open:e,onOpenChange:t,task:o}){let{t:s}=(0,E.s)(),{refetch:i}=lk(),[a,l]=(0,n.useState)(!0),[d,p]=(0,n.useState)(""),[u,g]=(0,n.useState)(!0),[h,f]=(0,n.useState)(!1);if((0,n.useEffect)(()=>{e&&o&&(l(!0),p(o.title),f(!1),(0,r2.CG)(o.projectRoot).then(e=>g(e.deleteWorktreeDefault)).catch(()=>g(!0)))},[e,o]),!e||!o)return null;let x=async()=>{if((a||d.trim())&&!h){f(!0);try{await (0,r2.oB)(o.id,o.projectRoot,a?null:d.trim(),u),t(!1),i()}catch(e){console.error("merge failed",e)}finally{f(!1)}}};return(0,r.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,r.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,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"14px 16px 0"},children:[(0,r.jsx)("h3",{style:{fontSize:15,fontWeight:600,margin:0},children:s("tasks.mergeTitle")}),(0,r.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,r.jsx)(c.X,{size:16,"aria-hidden":"true"})})]}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:12,padding:"14px 16px 16px"},children:[(0,r.jsxs)("label",{style:{display:"flex",alignItems:"center",gap:8,fontSize:13,cursor:"pointer"},children:[(0,r.jsx)("input",{type:"radio",checked:a,onChange:()=>l(!0),style:{accentColor:"var(--accent)"}}),s("tasks.mergeAutoMessage")]}),(0,r.jsxs)("label",{style:{display:"flex",alignItems:"center",gap:8,fontSize:13,cursor:"pointer"},children:[(0,r.jsx)("input",{type:"radio",checked:!a,onChange:()=>l(!1),style:{accentColor:"var(--accent)"}}),s("tasks.mergeManualMessage")]}),!a&&(0,r.jsx)("input",{value:d,onChange:e=>p(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,r.jsxs)("label",{style:{display:"flex",alignItems:"center",gap:8,fontSize:13,cursor:"pointer"},children:[(0,r.jsx)("input",{type:"checkbox",checked:u,onChange:e=>g(e.target.checked),style:{accentColor:"var(--accent)"}}),s("tasks.mergeDeleteWorktree")]}),(0,r.jsxs)("div",{style:{display:"flex",justifyContent:"flex-end",gap:8,marginTop:4},children:[(0,r.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,r.jsx)("button",{type:"button",onClick:()=>void x(),disabled:!a&&!d.trim()||h,style:{padding:"8px 16px",borderRadius:8,background:"var(--accent)",color:"#fff",border:"none",fontSize:12,fontWeight:600,cursor:"pointer"},children:s("tasks.mergeConfirm")})]})]})]})})}function lU({open:e,onOpenChange:t,task:o,kind:s}){let{t:i}=(0,E.s)(),{refetch:a}=lk(),[l,d]=(0,n.useState)(""),[p,u]=(0,n.useState)(!1);if((0,n.useEffect)(()=>{e&&(d(""),u(!1))},[e,o]),!e||!o)return null;let g="retry"===s,h=async()=>{if(!p){u(!0);try{await (0,r2.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,r.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,r.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,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"14px 16px 0"},children:[(0,r.jsx)("h3",{style:{fontSize:15,fontWeight:600,margin:0},children:i(g?"tasks.restartTitleRetry":"tasks.restartTitleRequeue")}),(0,r.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,r.jsx)(c.X,{size:16,"aria-hidden":"true"})})]}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:12,padding:"14px 16px 16px"},children:[(0,r.jsx)("p",{style:{margin:0,fontSize:12,lineHeight:1.5,color:"var(--text-muted)"},children:i("tasks.restartDescription")}),(0,r.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:5},children:[(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)"},children:i("tasks.actionAddNote")}),(0,r.jsx)("textarea",{value:l,onChange:e=>d(e.target.value),placeholder:i(g?"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,r.jsxs)("div",{style:{display:"flex",justifyContent:"flex-end",gap:8,marginTop:4},children:[(0,r.jsx)("button",{type:"button",onClick:()=>t(!1),disabled:p,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,r.jsx)("button",{type:"button",onClick:()=>void h(),disabled:p,style:{padding:"8px 16px",borderRadius:8,background:"var(--accent)",color:"#fff",border:"none",fontSize:12,fontWeight:600,cursor:"pointer"},children:i(g?"tasks.actionRetry":"tasks.actionRequeue")})]})]})]})})}let l_=["work","retry","return","merge"];function lq({open:e,onOpenChange:t,projectRoot:o}){let{t:s}=(0,E.s)(),{projects:i}=lk(),[a,l]=(0,n.useState)(""),[d,p]=(0,n.useState)(()=>lT()),[u,g]=(0,n.useState)(!1),[h,f]=(0,n.useState)(!1);if((0,n.useEffect)(()=>{if(!e)return;let t=o??i[0]??"";l(t),t&&(0,r2.Pf)(t).then(e=>{g(null!=e),p(e??lT())}).catch(()=>{g(!1),p(lT())})},[e,o,i]),!e)return null;let x=(e,t)=>{p(o=>({...o,[e]:t}))},m=async()=>{if(a&&!h){f(!0);try{await (0,r2.eA)(a,d),g(!0),t(!1)}catch(e){console.error("save settings failed",e)}finally{f(!1)}}},k=async()=>{if(a)try{await (0,r2.E)(a),g(!1),p(lT())}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,r.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,r.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,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"14px 16px 0"},children:[(0,r.jsx)("h3",{style:{fontSize:15,fontWeight:600,margin:0},children:s("tasks.settingsTitle")}),(0,r.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,r.jsx)(c.X,{size:16,"aria-hidden":"true"})})]}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:10,padding:"14px 16px 16px"},children:[(0,r.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,r.jsx)("span",{style:{fontSize:12,fontWeight:500},children:s("tasks.settingsProject")}),(0,r.jsx)("select",{value:a,onChange:e=>l(e.target.value),style:v,children:i.map(e=>(0,r.jsx)("option",{value:e,children:e.split("/").filter(Boolean).pop()??e},e))})]}),a?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("div",{style:y,children:[(0,r.jsx)("span",{style:{fontSize:12},children:s("tasks.settingsAutoProcess")}),(0,r.jsx)("input",{type:"checkbox",checked:d.autoProcess,onChange:e=>x("autoProcess",e.target.checked),style:{accentColor:"var(--accent)"}})]}),(0,r.jsxs)("div",{style:y,children:[(0,r.jsx)("span",{style:{fontSize:12},children:s("tasks.settingsMaxConcurrent")}),(0,r.jsx)("input",{type:"number",min:0,value:d.maxConcurrent,onChange:e=>x("maxConcurrent",Math.max(0,Number(e.target.value)||0)),style:{...v,width:90}})]}),(0,r.jsxs)("div",{style:y,children:[(0,r.jsx)("span",{style:{fontSize:12},children:s("tasks.settingsMergeStrategy")}),(0,r.jsxs)("select",{value:d.mergeStrategy,onChange:e=>x("mergeStrategy",e.target.value),style:{...v,width:140},children:[(0,r.jsx)("option",{value:"merge",children:s("tasks.mergeStrategyMerge")}),(0,r.jsx)("option",{value:"squash",children:s("tasks.mergeStrategySquash")})]})]}),(0,r.jsxs)("div",{style:y,children:[(0,r.jsx)("span",{style:{fontSize:12},children:s("tasks.settingsDeleteWorktree")}),(0,r.jsx)("input",{type:"checkbox",checked:d.deleteWorktreeDefault,onChange:e=>x("deleteWorktreeDefault",e.target.checked),style:{accentColor:"var(--accent)"}})]}),(0,r.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,r.jsx)("span",{style:{fontSize:12},children:s("tasks.settingsPreflightCommand")}),(0,r.jsx)("input",{value:d.preflightCommand??"",onChange:e=>x("preflightCommand",e.target.value||null),placeholder:s("tasks.settingsPreflightPlaceholder"),style:{...v,fontFamily:"var(--font-mono)",fontSize:11}})]}),(0,r.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,r.jsx)("span",{style:{fontSize:12},children:s("tasks.settingsInitCommand")}),(0,r.jsx)("input",{value:d.initCommand??"",onChange:e=>x("initCommand",e.target.value||null),placeholder:s("tasks.settingsInitPlaceholder"),style:{...v,fontFamily:"var(--font-mono)",fontSize:11}})]}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:6,paddingTop:4},children:[(0,r.jsx)("span",{style:{fontSize:12,fontWeight:500},children:s("tasks.settingsStagePrompts")}),l_.map(e=>(0,r.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-muted)"},children:s(`tasks.stage.${e}`)}),(0,r.jsx)("input",{value:d.stagePrompts?.[e]??"",onChange:t=>x("stagePrompts",{...d.stagePrompts??{},[e]:t.target.value}),style:{...v,fontSize:11}})]},e))]}),u&&(0,r.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,r.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)",padding:8},children:s("tasks.settingsNoProject")}),(0,r.jsxs)("div",{style:{display:"flex",justifyContent:"flex-end",gap:8,marginTop:4},children:[(0,r.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,r.jsx)("button",{type:"button",onClick:()=>void m(),disabled:!a||h,style:{padding:"8px 16px",borderRadius:8,background:"var(--accent)",color:"#fff",border:"none",fontSize:12,fontWeight:600,cursor:"pointer"},children:s("tasks.save")})]})]})]})})}function lV({open:e,onOpenChange:t,task:o}){let{t:s}=(0,E.s)();return((0,n.useEffect)(()=>{if(!e)return},[e,o]),e&&o)?(0,r.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,r.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,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"14px 16px 0"},children:[(0,r.jsx)("h3",{style:{fontSize:15,fontWeight:600,margin:0},children:s("tasks.sessionTitle")}),(0,r.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,r.jsx)(c.X,{size:16,"aria-hidden":"true"})})]}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:10,padding:"14px 16px 16px",fontSize:12},children:[(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:8,padding:10},children:[(0,r.jsx)("span",{style:{color:"var(--text-muted)"},children:s("tasks.sessionId")}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:11,overflowWrap:"anywhere"},children:o.conversationId??"—"})]}),o.sessionFile?(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:8,padding:10},children:[(0,r.jsx)("span",{style:{color:"var(--text-muted)"},children:s("tasks.sessionFile")}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:11,overflowWrap:"anywhere"},children:o.sessionFile})]}):null,(0,r.jsx)("div",{style:{fontSize:11,color:"var(--text-muted)",lineHeight:1.6},children:s("tasks.sessionHint")}),(0,r.jsx)("div",{style:{display:"flex",justifyContent:"flex-end",marginTop:4},children:(0,r.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 lK="__all__",lJ="pi-tasks-board-filter",lG={showCanceled:!1,showArchived:!1},lY="pi:open-task-settings";function lX(){let{t:e}=(0,E.s)(),{attentionCount:t}=lk();return(0,r.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,r.jsxs)("h1",{style:{margin:0,display:"flex",alignItems:"center",gap:6,fontSize:13,fontWeight:600},children:[(0,r.jsx)(iY.x,{size:15,color:"var(--text-muted)","aria-hidden":"true"}),e("tasks.title"),(0,r.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,r.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,r.jsx)("div",{style:{flex:1}}),(0,r.jsxs)("button",{type:"button",onClick:()=>window.dispatchEvent(new Event(lY)),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,r.jsx)(lb.O,{size:13,"aria-hidden":"true"}),e("tasks.settingsTitle")]})]})}function lZ({activeProject:e}){let{t}=(0,E.s)(),{tasks:s,projects:i,refetch:a}=lk(),[d,c]=(0,n.useState)(null),[p,u]=(0,n.useState)(()=>(function(){try{let e=window.localStorage.getItem(lJ);if(e){let t=JSON.parse(e);return{showCanceled:t.showCanceled??!1,showArchived:t.showArchived??!1}}}catch{}return lG})()),[g,h]=(0,n.useState)(!1);(0,n.useEffect)(()=>{try{window.localStorage.setItem(lJ,JSON.stringify(p))}catch{}},[p]);let[f,m]=(0,n.useState)(null),[k,v]=(0,n.useState)(!1),y=(0,n.useRef)(null),b=(0,n.useRef)({x:0,y:0}),w=(0,n.useRef)(null),j=(0,n.useRef)(null),[S,C]=(0,n.useState)(null),T=(0,n.useRef)(null);T.current=S;let R=(0,n.useRef)(!1),z=(0,n.useRef)(!1),[I,M]=(0,n.useState)(()=>Date.now());(0,n.useEffect)(()=>{let e=window.setInterval(()=>M(Date.now()),6e4);return()=>window.clearInterval(e)},[]);let[P,D]=(0,n.useState)(!1),[F,W]=(0,n.useState)(null),[$,N]=(0,n.useState)(null);(0,n.useEffect)(()=>{let e=()=>{let e,t=(e=re,re=null,e);t&&(W(null),N(t),D(!0))};return e(),window.addEventListener(o9,e),()=>window.removeEventListener(o9,e)},[]);let[L,A]=(0,n.useState)(null),[O,H]=(0,n.useState)(null),[B,U]=(0,n.useState)(!1),[_,q]=(0,n.useState)(null),[V,K]=(0,n.useState)(!1),[J,G]=(0,n.useState)(null),[Y,X]=(0,n.useState)("retry"),[Z,Q]=(0,n.useState)(!1),[ee,et]=(0,n.useState)(null),[eo,er]=(0,n.useState)(!1),[en,es]=(0,n.useState)(!1),[ei,ea]=(0,n.useState)(null),[el,ed]=(0,n.useState)(!1);(0,n.useEffect)(()=>{let e=()=>es(!0);return window.addEventListener(lY,e),()=>window.removeEventListener(lY,e)},[]);let ec=(0,n.useMemo)(()=>null==d?s:s.filter(e=>e.projectRoot===d),[s,d]),ep=(0,n.useMemo)(()=>(function(e,t,o=!1){let r={todo:[],inProgress:[],attention:[],done:[]};for(let n of e)("canceled"!==n.status||t)&&(null==n.archivedAt||o)&&r[function(e){switch(e){case"todo":case"queued":return"todo";case"preparing":case"running":return"inProgress";case"awaiting_input":case"review":case"merging":case"failed":return"attention";case"done":case"canceled":return"done"}}(n.status)].push(n);for(let e of lS)r[e].sort((e,t)=>(t.updatedAt??"").localeCompare(e.updatedAt??""));return r})(ec,p.showCanceled,p.showArchived),[ec,p]),eu=(0,n.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]),eg=(0,n.useMemo)(()=>s.find(e=>e.id===L)??null,[s,L]),eh=(0,n.useMemo)(()=>s.find(e=>e.id===ei)??null,[s,ei]),ef=(0,n.useCallback)(async e=>{try{await e()}catch(e){console.error("task action failed",e)}finally{a()}},[a]),ex=(0,n.useCallback)(e=>{null!=e.conversationId&&(ea(e.id),ed(!0))},[ea,ed]),em=(0,n.useCallback)(e=>{H(e),U(!0)},[H,U]),ek=(0,n.useCallback)(()=>{W(null),D(!0)},[W,D]),ev=(0,n.useCallback)((e,t)=>{let o=w.current,r=y.current;o&&r&&(o.style.transform=`translate3d(${e-r.dx}px, ${t-r.dy}px, 0)`)},[]),ey=e=>{let t=e.currentTarget.getBoundingClientRect();y.current={dx:e.clientX-t.left,dy:e.clientY-t.top,width:t.width}},eb=(0,n.useCallback)(e=>{if(m(null),v(!1),e){R.current=!1;return}requestAnimationFrame(()=>{R.current=!1})},[m,v]),ew=(0,n.useCallback)(()=>{z.current=!0,C(null),eb(!0)},[eb,C]);(0,n.useEffect)(()=>{if(!f)return;let e=()=>{document.hidden&&ew()};return window.addEventListener("blur",ew),document.addEventListener("visibilitychange",e),()=>{window.removeEventListener("blur",ew),document.removeEventListener("visibilitychange",e)}},[f,ew]),(0,n.useEffect)(()=>{f&&!eu.some(e=>e.id===f.task.id)&&ew()},[f,eu,ew]);let ej=(0,n.useCallback)((e,t,o)=>{if(z.current){eb(!0),C(null);return}let r=j.current?.getBoundingClientRect(),n=null!=r&&t>=r.left&&t<=r.right&&o>=r.top&&o<=r.bottom;if(eb(!1),n){C(null);let t=s.find(t=>t.id===e.id);t?.status==="todo"&&null!=d&&ef(()=>(0,r2.oQ)(e.id,e.projectRoot,"start"));return}let i=T.current;null!=d&&null!=i&&(async()=>{try{await (0,r2.Lu)(d,i)}catch(e){console.error("reorder failed",e)}await a(),C(null)})()},[ef,eb,d,a,s]),eS=(0,n.useCallback)(()=>{ef(async()=>{let e=await (0,r2.a5)(d);e>0&&console.log(`started ${e} tasks`)})},[ef,d]),eC=(0,n.useCallback)(()=>{let e=ep.done.filter(e=>null==e.archivedAt);0!==e.length&&ef(()=>Promise.all(e.map(e=>(0,r2.et)(e.id,e.projectRoot,!0))))},[ef,ep.done]),eT=+(p.showCanceled!==lG.showCanceled)+ +(p.showArchived!==lG.showArchived),eR=s.length>0,ez=(0,n.useMemo)(()=>{let t=new Set(i);return e&&t.add(e),[...t].sort()},[i,e]),eI=(0,n.useMemo)(()=>{let e=new Map;for(let t of ez)e.set(t,t.split("/").filter(Boolean).pop()??t);return e},[ez]);return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",minHeight:0},children:[eR&&(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:8,padding:"14px 16px 8px"},children:[(0,r.jsxs)("select",{value:d??lK,onChange:e=>c(e.target.value===lK?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,r.jsx)("option",{value:lK,children:t("tasks.allFolders")}),ez.map(e=>(0,r.jsx)("option",{value:e,children:eI.get(e)??e},e))]}),(0,r.jsxs)("div",{style:{position:"relative"},children:[(0,r.jsxs)("button",{type:"button",onClick:()=>h(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,r.jsx)(lw.n,{size:13,"aria-hidden":"true"}),t("tasks.filter"),eT>0?(0,r.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]}),g&&(0,r.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,r.jsxs)("label",{style:{display:"flex",alignItems:"center",gap:8,padding:"6px 8px",borderRadius:8,cursor:"pointer",fontSize:12},children:[(0,r.jsx)("input",{type:"checkbox",checked:p[e],onChange:t=>u(o=>({...o,[e]:t.target.checked})),style:{accentColor:"var(--accent)"}}),t]},e))})]}),(0,r.jsx)("div",{style:{flex:1}}),(0,r.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,r.jsx)(lj.j,{size:13,"aria-hidden":"true"}),t("tasks.startAll")]}),(0,r.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,r.jsx)(x.F,{size:13,weight:"bold","aria-hidden":"true"}),t("tasks.new")]})]}),eR?(0,r.jsx)("div",{style:{flex:1,minHeight:0,overflowX:"auto"},children:(0,r.jsx)("div",{style:{display:"grid",gridTemplateColumns:"repeat(4, minmax(0, 1fr))",gap:16,minWidth:"56rem",height:"100%",padding:"4px 16px 16px"},children:lR.map(e=>{let o="todo"===e?eu:ep[e],n=lz[e],s=e=>(0,r.jsx)(lF,{task:e,folderName:e.projectRoot?eI.get(e.projectRoot)??null:null,now:I,onOpen:()=>{R.current||A(e.id)},onStart:()=>void ef(()=>(0,r2.oQ)(e.id,e.projectRoot,"start")),onCancel:()=>{q(e),K(!0)},onRetry:()=>{G(e),X("retry"),Q(!0)},onRequeue:()=>{G(e),X("requeue"),Q(!0)},onViewSession:()=>ex(e),onMerge:()=>{lC(e)?(et(e),er(!0)):em(e)},onArchive:()=>void ef(()=>(0,r2.et)(e.id,e.projectRoot,null==e.archivedAt)),onEdit:()=>{W(e),D(!0)}},e.id);return(0,r.jsxs)("div",{ref:"inProgress"===e?j:void 0,style:{display:"flex",flexDirection:"column",minHeight:0,gap:8},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,height:24,flexShrink:0,padding:"0 2px"},children:[(0,r.jsx)("span",{style:{width:3,height:14,borderRadius:999,background:n.marker,flexShrink:0},"aria-hidden":"true"}),(0,r.jsx)("h2",{style:{fontSize:12,fontWeight:600,color:"var(--text)"},children:t(`tasks.col${e[0].toUpperCase()}${e.slice(1)}`)}),(0,r.jsx)("span",{style:{borderRadius:999,background:"var(--bg-hover)",padding:"1px 8px",fontSize:10,fontWeight:600,color:"var(--text-muted)"},children:o.length}),(0,r.jsx)("div",{style:{flex:1}}),"done"===e&&ep.done.some(e=>null==e.archivedAt)?(0,r.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,r.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&&f?k?{borderColor:"var(--accent)",background:"rgba(37,99,235,0.08)"}:{borderColor:"var(--accent)"}:{}},children:(0,r.jsx)("p",{style:{fontSize:12,color:"var(--text-muted)"},children:t(`tasks.emptyCol${e[0].toUpperCase()}${e.slice(1)}`)})}):(0,r.jsx)("div",{style:{flex:1,minHeight:0,overflowY:"auto",borderRadius:12,transition:"background 0.15s, box-shadow 0.15s",..."inProgress"===e&&f?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,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:16,paddingBottom:4},children:o.map(t=>"todo"===e?(0,r.jsx)("div",{draggable:!0,onDragStart:e=>{var o,r;e.dataTransfer.effectAllowed="move",o=e.clientX,r=e.clientY,R.current=!0,z.current=!1,b.current={x:o,y:r},m({task:t,width:y.current?.width??280})},onDrag:e=>{var t,o;let r,n;return b.current={x:t=e.clientX,y:o=e.clientY},ev(t,o),void((n=null!=(r=j.current?.getBoundingClientRect())&&t>=r.left&&t<=r.right&&o>=r.top&&o<=r.bottom)!==k&&v(n))},onDragEnd:e=>ej(t,e.clientX,e.clientY),onPointerDown:ey,style:{cursor:"grab",opacity:f?.task.id===t.id?.4:1},children:s(t)},t.id):(0,r.jsx)("div",{children:s(t)},t.id))})})]},e)})})}):(0,r.jsxs)("div",{style:{flex:1,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:12,padding:32,textAlign:"center"},children:[(0,r.jsx)(iY.x,{size:40,color:"var(--text-dim)",opacity:.4,"aria-hidden":"true"}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,r.jsx)("p",{style:{fontSize:14,fontWeight:500,color:"var(--text)"},children:t("tasks.empty")}),(0,r.jsx)("p",{style:{maxWidth:320,fontSize:12,color:"var(--text-muted)",lineHeight:1.6},children:t("tasks.emptyHint")})]}),(0,r.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,r.jsx)(x.F,{size:13,weight:"bold","aria-hidden":"true"}),t("tasks.new")]})]}),(0,r.jsx)(lH,{open:P,onOpenChange:D,task:F,defaultProject:$?.projectRoot??d??e??null,projects:ez,prefillTitle:$?$.text.slice(0,80):void 0,prefillPrompt:$?$.text:void 0,onSubmit:async(e,t,r)=>{await ef(async()=>{let{createTaskApi:n}=await Promise.resolve().then(o.bind(o,23084)),{updateTaskApi:s}=await Promise.resolve().then(o.bind(o,23084));F?await s(F.id,e,{title:t,config:r}):await n({projectRoot:e,title:t,config:r})}),D(!1),N(null)}}),(0,r.jsx)(lA,{open:null!=L,onOpenChange:e=>{e||A(null)},task:eg,onViewSession:ex,onMerge:em,onEdit:e=>{W(e),D(!0)},onCancel:e=>{q(e),K(!0)},onRetry:e=>{G(e),X("retry"),Q(!0)},onRequeue:e=>{G(e),X("requeue"),Q(!0)},onComplete:e=>{et(e),er(!0)}}),(0,r.jsx)(lB,{open:B,onOpenChange:U,task:O}),(0,r.jsx)(lW,{open:V,onOpenChange:K,task:_}),(0,r.jsx)(lU,{open:Z,onOpenChange:Q,task:J,kind:Y}),(0,r.jsx)(l$,{open:eo,onOpenChange:er,task:ee}),(0,r.jsx)(lV,{open:el&&null!=eh,onOpenChange:ed,task:eh}),(0,r.jsx)(lq,{open:en,onOpenChange:es,projectRoot:d}),f?(0,l.createPortal)((0,r.jsx)("div",{ref:w,style:{position:"fixed",left:0,top:0,zIndex:999,pointerEvents:"none",width:f.width,willChange:"transform"},"aria-hidden":"true",children:(0,r.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,r.jsxs)("div",{style:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:8},children:[(0,r.jsx)("span",{style:{minWidth:0,overflowWrap:"break-word",fontSize:13,fontWeight:500},children:f.task.title}),(0,r.jsx)(lP,{task:f.task})]}),k?(0,r.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:4,fontSize:11,fontWeight:600,color:"var(--accent)"},children:[(0,r.jsx)(lj.j,{size:11,weight:"bold","aria-hidden":"true"}),t("tasks.dropToStart")]}):null]})}),document.body):null]})}var lQ=o(62235);function l0({isDark:e,toggleTheme:t,translate:o}){let[s,i]=(0,n.useState)(!1);(0,n.useEffect)(()=>{i(!0)},[]);let a=o(s?e?"desktop.switchToLight":"desktop.switchToDark":"desktop.switchToLight");return(0,r.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,r.jsx)(iO.b,{size:16,"aria-hidden":"true"}):(0,r.jsx)(iA.A,{size:16,"aria-hidden":"true"}):(0,r.jsx)(iO.b,{size:16,"aria-hidden":"true"})})}function l1({topBarRef:e,sidebarOpen:t,onSidebarToggle:o,isDark:s,toggleTheme:i,isMobile:a,showTasks:l,tasksBoardEnabled:d,onToggleTasks:c,systemPrompt:p,activeTopPanel:g,topPanelPos:h,sessionStats:f,contextUsage:x,copiedSessionField:m,onCopySessionField:k,rightPanelOpen:y,onToggleFilePanel:b,onOpenSettings:w,sessionTitle:j,onWorkspaceControlsHostChange:S,onTitleRightHostChange:C}){let T,R,z,I,M,P,D,F,{t:W}=(0,E.s)(),[$,N]=(0,n.useState)(!1),[L,A]=(0,n.useState)(!1);return(0,n.useEffect)(()=>{try{A(new URLSearchParams(window.location.search).has("piweb_connected"))}catch{A(!1)}},[]),(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("div",{ref:e,className:"app-title-bar",style:{display:"flex",alignItems:"center",flexShrink:0,borderBottom:"1px solid var(--border)",height:36,background:"var(--bg-panel)",position:"relative",zIndex:600},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",minWidth:0,height:"100%",flex:"0 1 auto"},children:[(0,r.jsx)("button",{className:"app-no-drag",onClick:o,title:t?W("desktop.hideSidebar"):W("desktop.showSidebar"),"aria-label":t?W("desktop.hideSidebar"):W("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,r.jsx)(lQ.V,{size:16,"aria-hidden":"true"}):(0,r.jsx)(v.B,{size:16,"aria-hidden":"true"})}),(0,r.jsx)("div",{className:"app-no-drag",ref:S,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,r.jsxs)("div",{className:"app-title-drag",style:{flex:1,minWidth:0,display:"flex",alignItems:"center",justifyContent:"center",height:"100%",padding:"0 12px",userSelect:"none"},children:[j&&(0,r.jsx)("button",{type:"button",onClick:()=>{a&&N(!0)},title:a?j:void 0,style:{display:"block",maxWidth:"100%",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:j}),(0,r.jsx)("div",{className:"app-no-drag",ref:C,style:{flexShrink:0,display:"flex",alignItems:"center",marginLeft:4}})]}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"flex-end",minWidth:0,height:"100%",flexShrink:0},children:[!a&&d&&(0,r.jsx)("button",{className:"app-no-drag",onClick:c,title:l?W("desktop.hideTaskBoard"):W("desktop.showTaskBoard"),"aria-label":l?W("desktop.hideTaskBoard"):W("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,r.jsx)(iY.x,{size:16,"aria-hidden":"true"})}),(0,r.jsx)("button",{className:"app-no-drag",onClick:b,title:y?W("desktop.hideFilePanel"):W("desktop.showFilePanel"),"aria-label":y?W("desktop.hideFilePanel"):W("desktop.showFilePanel"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:36,height:36,padding:0,background:y?"var(--bg-selected)":"none",border:"none",color:y?"var(--text)":"var(--text-muted)",cursor:"pointer",flexShrink:0,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background=y?"var(--bg-selected)":"none",e.currentTarget.style.color=y?"var(--text)":"var(--text-muted)"},children:(0,r.jsx)(lQ.V,{size:16,"aria-hidden":"true",style:{transform:"scaleX(-1)"}})}),(0,r.jsx)(l0,{isDark:s,toggleTheme:i,translate:W}),L&&(0,r.jsx)("button",{className:"app-no-drag",type:"button",onClick:()=>{window.location.href="piweb-switch://manage"},title:W("desktop.serverSwitch"),"aria-label":W("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,r.jsx)(ik.X,{size:16,"aria-hidden":"true"})}),(0,r.jsx)("button",{className:"app-no-drag",type:"button",onClick:w,title:W("desktop.settings"),"aria-label":W("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,r.jsx)(lb.O,{size:16,"aria-hidden":"true"})})]})]}),g&&h&&(0,r.jsxs)("div",{style:{position:"fixed",top:h.top,left:h.left,width:h.width,maxHeight:`calc(100dvh - ${h.top}px)`,overflowY:"auto",zIndex:500},children:["system"===g&&(0,r.jsx)("div",{style:{background:"var(--bg-panel)",borderBottom:"1px solid var(--border)"},children:p?(0,r.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,r.jsx)("div",{style:{padding:"10px 16px",fontSize:12,color:"var(--text-muted)",fontStyle:"italic"},children:"System prompt is empty (tools are disabled)"}):(0,r.jsx)("div",{style:{padding:"10px 16px",fontSize:12,color:"var(--text-muted)",fontStyle:"italic"},children:"Send a message to load the system prompt"})}),"session"===g&&(0,r.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:f?(T=[...f.sessionName?[{label:W("desktop.name"),value:f.sessionName,copyField:null}]:[],{label:W("desktop.sessionInfoFile"),value:f.sessionFile??W("desktop.sessionInfoInMemory"),copyField:"file"},{label:W("desktop.sessionInfoId"),value:f.sessionId,copyField:"id"}],R=[[W("desktop.sessionInfoUser"),f.userMessages.toLocaleString()],[W("desktop.sessionInfoAssistant"),f.assistantMessages.toLocaleString()],[W("desktop.sessionInfoToolCalls"),f.toolCalls.toLocaleString()],[W("desktop.sessionInfoToolResults"),f.toolResults.toLocaleString()],[W("desktop.sessionInfoTotal"),f.totalMessages.toLocaleString()]],z=[[W("desktop.sessionInfoInput"),f.tokens.input.toLocaleString()],[W("desktop.sessionInfoOutput"),f.tokens.output.toLocaleString()],...f.tokens.cacheRead>0?[[W("desktop.sessionInfoCacheRead"),f.tokens.cacheRead.toLocaleString()]]:[],...f.tokens.cacheWrite>0?[[W("desktop.sessionInfoCacheWrite"),f.tokens.cacheWrite.toLocaleString()]]:[],[W("desktop.sessionInfoTotal"),f.tokens.total.toLocaleString()]],I=x??f.contextUsage,P=[...f.cost>0?[[W("desktop.sessionInfoCost"),`$${f.cost.toFixed(4)}`]]:[],...I?.contextWindow?[[W("desktop.sessionInfoContext"),`${null!==I.percent?`${I.percent.toFixed(1)}%`:"?"} / ${(M=I.contextWindow)>=1e6?`${(M/1e6).toFixed(1)}M`:M>=1e3?`${(M/1e3).toFixed(0)}k`:String(M)}`]]:[]],D=(e,t,o="left",n=!1)=>(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:11,fontWeight:700,color:"var(--text)",marginBottom:6},children:e}),(0,r.jsx)("div",{style:{display:"grid",gridTemplateColumns:n?"max-content max-content":"auto minmax(0, 1fr)",columnGap:n?14:12,rowGap:4,justifyContent:n?"start":void 0},children:t.map(([t,s])=>(0,r.jsxs)("div",{style:{display:"contents"},children:[(0,r.jsx)("div",{style:{color:"var(--text-dim)",whiteSpace:"nowrap"},children:t}),(0,r.jsx)("div",{style:{color:"var(--text-muted)",minWidth:0,overflowWrap:n?"normal":"anywhere",textAlign:o,whiteSpace:"right"===o?"nowrap":"normal"},children:s})]},`${e}:${t}`))})]}),F=(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:11,fontWeight:700,color:"var(--text)",marginBottom:6},children:W("desktop.sessionInfoTitle")}),(0,r.jsx)("div",{style:{display:"grid",gridTemplateColumns:"auto minmax(0, 1fr) auto",columnGap:12,rowGap:8,alignItems:"start"},children:T.map(e=>{var t,o;let n;return(0,r.jsxs)("div",{style:{display:"contents"},children:[(0,r.jsx)("div",{style:{color:"var(--text-dim)",whiteSpace:"nowrap"},children:e.label}),(0,r.jsx)("div",{style:{color:"var(--text-muted)",minWidth:0,overflowWrap:"anywhere",wordBreak:"break-word",whiteSpace:"normal"},children:e.value}),(0,r.jsx)("div",{children:e.copyField?(t=e.copyField,o=e.value,n=m===t,(0,r.jsx)("button",{type:"button",title:n?W("desktop.copied"):"file"===t?W("desktop.copyFilePath"):W("desktop.copySessionId"),onClick:()=>k(t,o),style:{alignSelf:"start",display:"inline-flex",alignItems:"center",justifyContent:"center",width:22,height:22,marginTop:-2,color:n?"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=n?"var(--accent)":"var(--text-dim)",e.currentTarget.style.borderColor="var(--border)",e.currentTarget.style.background="transparent"},children:n?(0,r.jsx)(u.J,{size:12,"aria-hidden":"true"}):(0,r.jsx)(tp.Q,{size:12,"aria-hidden":"true"})})):null})]},`session-info:${e.label}`)})})]}),(0,r.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:[F,D(W("desktop.sessionInfoMessages"),R),D(W("desktop.sessionInfoTokens"),[...z,...P],"right",!0)]})):(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)",fontStyle:"italic"},children:W("desktop.sendMessageForSessionInfo")})})]}),$&&j&&(0,r.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&&N(!1)},children:(0,r.jsx)("div",{role:"dialog","aria-label":j,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:j})})]})}function l2({cwd:e,busy:t,error:o,onCancelAction:n,onConfirmAction:s}){let{t:i}=(0,E.s)();return(0,r.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||n()},children:(0,r.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,r.jsxs)("div",{style:{display:"flex",gap:12,padding:"18px 18px 14px"},children:[(0,r.jsx)(o8.o,{size:21,weight:"duotone",color:"var(--accent-orange)",style:{flexShrink:0,marginTop:1},"aria-hidden":"true"}),(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("h2",{id:"project-trust-title",style:{margin:0,fontSize:15,fontWeight:700,color:"var(--text)"},children:i("desktop.trustProjectTitle")}),(0,r.jsx)("p",{style:{margin:"7px 0 0",fontSize:12,lineHeight:1.6,color:"var(--text-muted)"},children:i("desktop.trustProjectBody")}),(0,r.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,r.jsx)("div",{role:"alert",style:{marginTop:10,color:"var(--accent-red)",fontSize:12,lineHeight:1.5},children:o})]})]}),(0,r.jsxs)("footer",{style:{display:"flex",justifyContent:"flex-end",gap:8,padding:"10px 18px",borderTop:"1px solid var(--border)"},children:[(0,r.jsx)("button",{type:"button",onClick:n,disabled:t,style:{height:32,padding:"0 12px",border:"1px solid var(--border)",borderRadius:5,background:"transparent",color:"var(--text-muted)",cursor:t?"not-allowed":"pointer",fontSize:12},children:i("desktop.cancel")}),(0,r.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 l4(e,t,o){let r=Number.isFinite(e)?e:t,n=Math.max(t,o);return Math.round(Math.max(t,Math.min(n,r)))}function l6(e){return l4(.42*e,360,640)}function l5(e,t){try{window.localStorage.setItem(e,String(t))}catch{}}function l3(e){let{ariaLabel:t,cssVariable:o,defaultWidth:r,getDefaultWidth:s,getMaxWidth:i,growthDirection:a,maxWidth:l,minWidth:d,storageKey:c,widthRef:p}=e,u=(0,n.useRef)(null),g=(0,n.useRef)(null),h=(0,n.useRef)(!1),[f,x]=(0,n.useState)(r),[m,k]=(0,n.useState)(!1),v=(0,n.useCallback)(()=>Math.min(l,Math.max(d,i())),[i,l,d]),y=(0,n.useCallback)(e=>l4(e,d,v()),[v,d]),b=(0,n.useCallback)(e=>{p.current=e;let t=`${e}px`;u.current?.style.setProperty(o,t),u.current?.parentElement?.style.setProperty(o,t)},[o,p]),w=(0,n.useCallback)((e,t={})=>{let{forcePersist:o=!1,persist:r=!0}=t,n=y(e),s=n!==p.current;return b(n),x(n),r&&(s||o)&&l5(c,n),n},[b,y,c,p]),j=(0,n.useCallback)(e=>{document.body.style.cursor=e.previousCursor,document.body.style.userSelect=e.previousUserSelect},[]),S=(0,n.useCallback)(e=>{let t=g.current;if(t&&t.pointerId===e){g.current=null,j(t),k(!1),w(p.current,{forcePersist:!0});try{t.target.hasPointerCapture(e)&&t.target.releasePointerCapture(e)}catch{}}},[w,j,p]),C=(0,n.useCallback)(e=>{if("mouse"===e.pointerType&&0!==e.button)return;e.preventDefault(),e.stopPropagation();let t=g.current;t&&S(t.pointerId);let o=e.currentTarget;o.focus({preventScroll:!0}),o.setPointerCapture(e.pointerId),g.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)},[S,p]),T=(0,n.useCallback)(e=>{let t=g.current;if(!t||t.pointerId!==e.pointerId)return;if("mouse"===e.pointerType&&0===e.buttons)return void S(e.pointerId);e.preventDefault();let o="right"===a?1:-1,r=y(t.startWidth+(e.clientX-t.startX)*o);b(r),e.currentTarget.setAttribute("aria-valuenow",String(r)),e.currentTarget.setAttribute("aria-valuetext",`${r} px`)},[b,y,S,a]),R=(0,n.useCallback)(e=>{S(e.pointerId)},[S]),z=(0,n.useCallback)(e=>{S(e.pointerId)},[S]),I=(0,n.useCallback)(e=>{S(e.pointerId)},[S]),M=(0,n.useCallback)(()=>{w(s?.()??r,{forcePersist:!0})},[w,r,s]),E=(0,n.useCallback)(()=>{w(p.current)},[w,p]),P=(0,n.useCallback)(e=>{let t=e.shiftKey?32:12,o="right"===a?"ArrowRight":"ArrowLeft",r="right"===a?"ArrowLeft":"ArrowRight";e.key===o?(e.preventDefault(),w(p.current+t,{forcePersist:!0})):e.key===r?(e.preventDefault(),w(p.current-t,{forcePersist:!0})):"Home"===e.key?(e.preventDefault(),w(d,{forcePersist:!0})):"End"===e.key?(e.preventDefault(),w(v(),{forcePersist:!0})):"Enter"===e.key&&(e.preventDefault(),M())},[w,v,a,d,M,p]);return(0,n.useEffect)(()=>{if(h.current)return;h.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=w(e??s?.()??r,{persist:!1});null!==e&&e!==t&&l5(c,t)},[w,r,s,c]),(0,n.useEffect)(()=>{if(!h.current)return;w(p.current);let e=()=>{w(p.current)};return window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[w,p]),(0,n.useEffect)(()=>{if(!m)return;let e=()=>{let e=g.current;e&&S(e.pointerId)},t=()=>{"visible"!==document.visibilityState&&e()};return window.addEventListener("blur",e),document.addEventListener("visibilitychange",t),()=>{window.removeEventListener("blur",e),document.removeEventListener("visibilitychange",t)}},[S,m]),(0,n.useEffect)(()=>()=>{let e=g.current;e&&(g.current=null,j(e))},[j]),{isResizing:m,panelRef:u,reclampWidth:E,separatorProps:{"aria-label":t,"aria-orientation":"vertical","aria-valuemax":v(),"aria-valuemin":d,"aria-valuenow":f,"aria-valuetext":`${f} px`,onDoubleClick:M,onKeyDown:P,onLostPointerCapture:I,onPointerCancel:z,onPointerDown:C,onPointerMove:T,onPointerUp:R,role:"separator",tabIndex:0},width:f}}function l8(){let e,t,o=(0,i.useRouter)(),l=(0,i.useSearchParams)(),d=(0,n.useMemo)(()=>{let e;return{requestedCwd:e=l.get("cwd")?.trim()||null,sessionId:e?null:l.get("session")}},[l]),{isDark:c,toggleTheme:p}=tL(),{t:u}=(0,E.s)(),g=$(),[h,f]=(0,n.useState)(null),[x,m]=(0,n.useState)(null),[k,v]=(0,n.useState)(0),[y,b]=(0,n.useState)(0),[w,j]=(0,n.useState)(0),[S,C]=(0,n.useState)(!1),[T,R]=(0,n.useState)("models"),[z,I]=(0,n.useState)(0),[M,P]=(0,n.useState)(null),[D,F]=(0,n.useState)(!1),[W,N]=(0,n.useState)(!1),[L,A]=(0,n.useState)(null),[O,H]=(0,n.useState)(!0),[B,U]=(0,n.useState)(!1);(0,n.useEffect)(()=>{g&&H(!1)},[g]),(0,n.useEffect)(()=>{U(!0)},[]);let _=(0,n.useRef)(null),q=(0,n.useRef)(null),[V,K]=(0,n.useState)(null),[J,G]=(0,n.useState)(null),[Y,X]=(0,n.useState)(null),[Z,Q]=(0,n.useState)(null),ee=(0,n.useCallback)(e=>{Q(e)},[]),[et,eo]=(0,n.useState)(null),en=(0,n.useCallback)(e=>{eo(e)},[]),[es,ei]=(0,n.useState)([]),ea=(0,n.useCallback)(e=>{ei(e)},[]),el=es.filter(e=>"running"===e.status).length,[ed,ec]=(0,n.useState)(null),ep=(0,n.useRef)(null),eu=(0,n.useCallback)((e,t)=>{tA(t).then(()=>{ep.current&&clearTimeout(ep.current),ec(e),ep.current=setTimeout(()=>ec(null),1400)})},[]);(0,n.useEffect)(()=>()=>{ep.current&&clearTimeout(ep.current)},[]);let[eg,eh]=(0,n.useState)(null),ef=(0,n.useCallback)(e=>{eh(e)},[]),[ex,em]=(0,n.useState)(null),[ek,ev]=(0,n.useState)(null),ey=(0,n.useCallback)(()=>{g&&H(!1),em("session")},[g]),eb=(0,n.useCallback)(()=>{g&&em(null),H(e=>!e)},[g]);(0,n.useEffect)(()=>{if(!ex||!q.current)return;let e=()=>{let e=q.current.getBoundingClientRect();ev({top:e.bottom,left:e.left,width:e.width})};e();let t=new ResizeObserver(e);return t.observe(q.current),()=>t.disconnect()},[ex]);let[ew,ej]=(0,n.useState)([]),[eC,eT]=(0,n.useState)(null),[eR,ez]=(0,n.useState)(!1),[eI,eM]=(0,n.useState)(!1),[eE,eP]=(0,n.useState)(null),eD=(0,n.useCallback)(e=>{eP(e??null),eM(!0),ez(!0),g&&H(!1)},[g]),eF=(0,n.useCallback)(()=>{eM(!1),eP(null)},[]),eW=(0,n.useRef)(260),eN=(0,n.useRef)(l6(1366)),eL=(0,n.useCallback)(()=>l6(window.innerWidth),[]),eA=(0,n.useCallback)(()=>(function(e){let{viewportWidth:t,rightPanelOpen:o,rightPanelWidth:r}=e;if(t<=640)return 480;let n=t<960;return Math.min(480,t-(n?320:420)-(!n&&o?r:0))})({viewportWidth:window.innerWidth,rightPanelOpen:eR,rightPanelWidth:eN.current}),[eR]),eO=(0,n.useCallback)(()=>(function(e){let{viewportWidth:t,sidebarOpen:o,sidebarWidth:r}=e;return t<960?1200:Math.min(1200,t-420-(o?r:0))})({viewportWidth:window.innerWidth,sidebarOpen:O,sidebarWidth:eW.current}),[O]),eH=l3({ariaLabel:u("desktop.resizeSidebar"),cssVariable:"--sidebar-width",defaultWidth:260,getMaxWidth:eA,growthDirection:"right",maxWidth:480,minWidth:180,storageKey:"pi-sidebar-width",widthRef:eW}),eB=l3({ariaLabel:u("desktop.resizeFilePanel"),cssVariable:"--right-panel-width",defaultWidth:l6(1366),getDefaultWidth:eL,getMaxWidth:eO,growthDirection:"left",maxWidth:1200,minWidth:300,storageKey:"pi-right-panel-width",widthRef:eN}),eU=eH.reclampWidth,e_=eB.reclampWidth;(0,n.useEffect)(()=>{eR&&(eU(),e_())},[e_,eU,eR]);let eq=(0,n.useCallback)((e,t)=>{_.current?.insertText(r1(e,t))},[]),eV=(0,n.useCallback)(e=>{let t=e.map(e=>r1(e,!1)).join("");t&&_.current?.insertText(t)},[]),eJ=(0,n.useCallback)((e,t,o)=>{let r,n,s,i;_.current?.insertText((r=Math.max(1,Math.min(t,o)),n=Math.max(1,Math.max(t,o)),s=e.includes(" ")?`@"${e}"`:`@${e}`,i=r===n?`:${r}`:`:${r}-${n}`,`${s}${i} `))},[]),[eG,eY]=(0,n.useState)(()=>d.sessionId),[eX,eZ]=(0,n.useState)(null),[eQ,e0]=(0,n.useState)(()=>d.requestedCwd?"validating":"idle"),[e1,e2]=(0,n.useState)(null),[e4,e6]=(0,n.useState)(()=>!eG),e5=(0,n.useRef)(!1),e3=(0,n.useRef)(new Map),[e8,e7]=(0,n.useState)(null),e9=(0,n.useRef)("");(0,n.useEffect)(()=>{let e=`${d.requestedCwd??""}|${d.sessionId??""}`;e9.current!==e&&(e9.current=e,eY(d.sessionId),e6(!d.sessionId),d.requestedCwd||e0("idle"),e2(null))},[d]),(0,n.useEffect)(()=>{let e=d.requestedCwd;if(!e)return;let t=new AbortController;return e0("validating"),e2(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}`);e5.current=!0,m(t.cwd),e0("ready")}).catch(e=>{t.signal.aborted||(e2(e instanceof Error?e.message:String(e)),e0("error"))}),()=>t.abort()},[d]);let te=(0,n.useCallback)((e,t)=>{if(!e)return;if(eZ(e),e5.current&&h&&eS(h.projectRoot??h.cwd,t??e)){if(e5.current=!1,h){let e=h.projectRoot??h.cwd;e&&e3.current.set(e,h.id)}return}e5.current=!1;let o=t??e;if(h&&eS(h.projectRoot??h.cwd,o)){(h.projectRoot??h.cwd)&&e3.current.set(o,h.id);return}if(h){let e=h.projectRoot??h.cwd;e&&e3.current.set(e,h.id)}f(null),m(t=>t&&t!==e?null:t),b(e=>e+1),Q(null),em(null),window.history.replaceState(null,"","/");let r=e3.current.get(o);e7(r?{projectRoot:o,sessionId:r}:null)},[h]);(0,n.useEffect)(()=>{let e=eX?er(eX)||eX:null;document.title=e?`${e} — Pi Agent Web`:"Pi Agent Web"},[eX]);let tt=(0,n.useCallback)((e,t=!1)=>{if(t||e7(null),!t&&h){let t=eS(h.projectRoot??h.cwd,e.projectRoot??e.cwd);if(h.id===e.id&&t){g&&H(!1);return}}let o=e.projectRoot??e.cwd;o&&e3.current.set(o,e.id),m(null),f(e),b(e=>e+1),Q(null),e6(!0),g&&!t&&H(!1),t&&(e5.current=!0),t||window.history.replaceState(null,"",`?session=${encodeURIComponent(e.id)}`)},[g,h]),to=(0,n.useRef)(()=>{});(0,n.useEffect)(()=>{to.current=tt},[tt]);let tr=(0,n.useCallback)(e=>{fetch("/api/sessions").then(e=>e.ok?e.json():null).then(t=>{let o=t?.sessions.find(t=>t.id===e);o&&f(t=>!t||t.id!==e||t.projectRoot&&t.name?t:o)}).catch(()=>{})},[]);(0,n.useEffect)(()=>{if(!e8)return;let{projectRoot:e,sessionId:t}=e8;to.current({path:"",id:t,cwd:e,created:"",modified:"",messageCount:0,firstMessage:"",projectRoot:e},!0),tr(t),window.history.replaceState(null,"",`?session=${encodeURIComponent(t)}`),e7(null)},[e8,tr]);let tn=(0,n.useCallback)((e,t)=>{e7(null),f(null),m(t),b(e=>e+1),Q(null),em(null),g&&H(!1),window.history.replaceState(null,"","/")},[o,g]);!function(e){let{onNewSession:t,activeCwd:o}=e;(0,n.useEffect)(()=>{let e=e=>{if("Escape"===e.key){if(!a)return;let t=e.target?.tagName;if("TEXTAREA"===t||"INPUT"===t)return;e.preventDefault(),a();return}if("n"===e.key&&e.ctrlKey&&e.altKey){if(!o||!t)return;e.preventDefault(),t(o)}};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[o,t])}({onNewSession:e=>tn(`kb-${Date.now()}`,e),activeCwd:eX});let ts=(0,n.useCallback)(e=>{m(null),e7(null);let t=e.projectRoot??e.cwd;t&&e3.current.set(t,e.id),f(e),e.cwd&&eZ(e.cwd),v(e=>e+1),tr(e.id),window.history.replaceState(null,"",`?session=${encodeURIComponent(e.id)}`),window.setTimeout(()=>v(e=>e+1),1200)},[o,tr]),ti=(0,n.useCallback)(()=>{v(e=>e+1),j(e=>e+1)},[]),ta=(0,n.useCallback)(e=>{v(e=>e+1),b(e=>e+1),m(null),e7(null),f(t=>{let o={...t??{path:"",cwd:"",created:"",modified:"",messageCount:0,firstMessage:""},id:e},r=o.projectRoot??o.cwd;return r&&e3.current.set(r,e),o}),tr(e),window.history.replaceState(null,"",`?session=${encodeURIComponent(e)}`)},[o,tr]),tl=(0,n.useCallback)(()=>{e6(!0)},[]),td=(0,n.useCallback)(e=>{if(v(e=>e+1),h?.id===e){let e=h.cwd;f(null),m(e??null),b(e=>e+1),Q(null),em(null),window.history.replaceState(null,"","/")}},[o,h]),tc=(0,n.useCallback)((e,t,o,r)=>{let n="string"==typeof o||null===o?o:void 0,s="object"==typeof o&&null!==o?o:r,i=`file:${e}`;ej(o=>{let r=o.find(e=>e.id===i);return r?n&&r.sourceSessionId!==n||s?.initialDisplayMode&&r.initialDisplayMode!==s.initialDisplayMode?o.map(e=>e.id===i?{...e,sourceSessionId:n??e.sourceSessionId,initialDisplayMode:s?.initialDisplayMode??e.initialDisplayMode}:e):o:[...o,{id:i,label:t,filePath:e,sourceSessionId:n,initialDisplayMode:s?.initialDisplayMode}]}),eT(i),ez(!0),g&&H(!1)},[g]),tp=(0,n.useCallback)(e=>{tc(e,er(e),h?.id??null)},[tc,h?.id]),tu=(0,n.useCallback)(e=>{ej(t=>{let o=t.filter(t=>t.id!==e);return 0===o.length&&ez(!1),o}),eT(t=>{if(t!==e)return t;let o=ew.filter(t=>t.id!==e);return o.length>0?o[o.length-1].id:null})},[ew]),tg=h?e$(h.name||et?.sessionName)||h.firstMessage.slice(0,50)||h.id.slice(0,12):(e=eX??x)?e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e:null,th=(0,n.useCallback)(()=>{h&&window.open(`/api/sessions/${encodeURIComponent(h.id)}/export?inline=1`,"_blank","noopener,noreferrer")},[h]),tf=x??(null===h&&eX?eX:null),tx="validating"!==eQ&&"error"!==eQ&&(null!==h||null!==tf),tm=h?.cwd??tf,[tk,tv]=(0,n.useState)(!1),ty=(0,n.useCallback)(()=>{g||tv(e=>!e)},[g]),[tb,tw]=(0,n.useState)(!0);(0,n.useEffect)(()=>{let e=!1,t=()=>fetch("/api/features").then(e=>e.ok?e.json():null).then(t=>{!e&&t&&"boolean"==typeof t.tasksBoard&&(tw(t.tasksBoard),t.tasksBoard||tv(!1))}).catch(()=>{});t();let o=()=>t();return window.addEventListener("pi:features-changed",o),()=>{e=!0,window.removeEventListener("pi:features-changed",o)}},[]);let tj=e4&&!tx;(0,n.useEffect)(()=>{let e=()=>{g||tv(!0)};return window.addEventListener(sU,e),()=>window.removeEventListener(sU,e)},[g]),(0,n.useEffect)(()=>{if(P(null),F(!1),A(null),!tm)return;let e=new AbortController;return fetch(`/api/project-trust?cwd=${encodeURIComponent(tm)}`,{signal:e.signal}).then(async e=>{let t=await e.json();if(!e.ok||t.error)throw Error(t.error??`HTTP ${e.status}`);P(t)}).catch(e=>{e instanceof DOMException&&"AbortError"===e.name||console.error("Failed to load project trust:",e)}),()=>e.abort()},[tm]);let tS=(0,n.useCallback)(async()=>{if(tm&&!W){N(!0),A(null);try{let e=await fetch("/api/project-trust",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:tm})}),t=await e.json();if(!e.ok||t.error)throw Error(t.error??`HTTP ${e.status}`);P(t),F(!1),I(e=>e+1),b(e=>e+1)}catch(e){A(e instanceof Error?e.message:String(e))}finally{N(!1)}}},[W,tm]),tC=ew.find(e=>e.id===eC)??null,tT=eX??h?.cwd??x,tR=(0,n.useCallback)(e=>{R(e),C(!0)},[]),tz=(0,r.jsx)(r.Fragment,{children:(0,r.jsx)(eK,{selectedSessionId:h?.id??null,onSelectSession:tt,onNewSession:tn,initialSessionId:eG,onInitialRestoreDone:tl,refreshKey:k,onSessionDeleted:td,selectedCwd:h?.cwd??x??null,onCwdChange:te,onOpenFile:tc,selectedSessionStats:et,onOpenSettings:e=>{tR(["models","skills","plugins","chat","features","logs"].includes(e)?e:"models")},explorerRefreshKey:w,onAtMention:eq,onAtMentions:eV,workspaceControlsHosts:{title:V,welcome:Y,titleRight:J},showWorkspaceControls:!0})});return(0,r.jsxs)(lv,{children:[(0,r.jsx)("style",{children:`
|
|
37
37
|
@media (max-width: 640px) {
|
|
38
38
|
.sidebar-overlay-backdrop.sidebar-mobile-pending {
|
|
39
39
|
opacity: 0 !important;
|