@qt4798/pi-web 0.10.7 → 0.10.8
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 +15 -15
- package/.next/build-manifest.json +2 -2
- package/.next/required-server-files.js +1 -1
- package/.next/required-server-files.json +1 -1
- package/.next/server/app/_global-error/page_client-reference-manifest.js +1 -1
- package/.next/server/app/_global-error.html +1 -1
- package/.next/server/app/_global-error.rsc +1 -1
- package/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
- package/.next/server/app/_global-error.segments/_global-error/__PAGE__.segment.rsc +1 -1
- package/.next/server/app/_global-error.segments/_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 +15 -15
- package/.next/server/chunks/4952.js +1 -0
- package/.next/server/chunks/7915.js +1 -1
- package/.next/server/instrumentation.js +1 -1
- package/.next/server/instrumentation.js.nft.json +1 -1
- package/.next/server/middleware-build-manifest.js +1 -1
- package/.next/server/pages/404.html +1 -1
- package/.next/server/pages/500.html +1 -1
- package/.next/static/chunks/app/{page-ad0ed57b98b86121.js → page-6a831e5a72ae7e70.js} +1 -1
- package/.next/trace +9 -9
- package/.next/trace-build +1 -1
- package/package.json +1 -1
- /package/.next/static/{nawYHsRT9tos_eI6-jhCH → Vs1Zb3cVWc82OkmdFQ-CR}/_buildManifest.js +0 -0
- /package/.next/static/{nawYHsRT9tos_eI6-jhCH → Vs1Zb3cVWc82OkmdFQ-CR}/_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}`:eN)}return t.join("\n\n")}({collaborationMode:ek.current,tokenMode:ev.current,goalText:"goal"===ek.current?ew.current??void 0:void 0}),c=d||!el.current||a?"":ic,p=d||c,u=[ek.current,ev.current,el.current?"legacy-plan":"",p?String(p.length):""].join("|"),h=t?.id??"new";p&&(ej.current.sessionKey!==h||ej.current.signature!==u)?(ej.current={sessionKey:h,signature:u},s=`${p}
|
|
35
35
|
|
|
36
|
-
${o}`):s=o;let x=s,f=n?.map(e=>({type:"image",source:{type:"base64",media_type:e.mimeType,data:e.data}})),m={role:"user",content:f?.length?[...o.trim()?[{type:"text",text:o}]:[],...f]:o,timestamp:Date.now()};S(e=>[...e,m]),oo.current=iv(m),ot.current=l,"goal"!==ek.current||a||(ew.current=i,eH(e=>({...e,status:"running",goalText:i,turnsUsed:0,noProgressTurns:0,tokensUsed:0})),eU.current=!0),tV.current=!0,$(!0),tt(a?{kind:"running_command"}:{kind:"waiting_model"}),z({type:"start"}),t2.current=!0,tr(!0),t4.current=!0;let k=n?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),v=null,y=!1;try{if(g&&r){let e=tq.current??await t9.current,t=e??await ow();if(t){v=t,ob(1,o),Q&&(e4(Q),e&&await io(t,{type:"set_model",provider:Q.provider,modelId:Q.modelId}));let r=await Promise.race([oR(t).then(()=>!0).catch(()=>!1),ih(4e3).then(()=>!1)]);y=!0,await io(t,{type:"prompt",message:x,...k?.length?{images:k}:{}}),r||oA(t,l),"goal"!==ek.current||a||io(t,{type:"goal_start",goalText:i}).catch(()=>{})}else throw Error("Unable to create a session for this message")}else if(t){v=t.id;let e=await Promise.race([oR(t.id).then(()=>!0).catch(()=>!1),ih(4e3).then(()=>!1)]);y=!0,await io(t.id,{type:"prompt",message:x,...k?.length?{images:k}:{}}),e||oA(t.id,l),"goal"!==ek.current||a||io(t.id,{type:"goal_start",goalText:i}).catch(()=>{})}a&&v&&oA(v,l)}catch(t){if(console.error("Failed to send message:",t),y&&v)return void oA(v,l);if(tJ.current=!1,oC(),t instanceof ig){let e=oo.current;e&&S(t=>{let o=t[t.length-1];return o?.role==="user"&&iv(o)===e?t.slice(0,-1):t}),oM({type:"error",message:t.message})}else{let o=oo.current;o&&S(e=>{let t=e[e.length-1];return t?.role==="user"&&iv(t)===o?e.slice(0,-1):e}),e.chatInputRef?.current?.replaceMessage?.(m),oM({type:"error",message:`Failed to send message: ${t instanceof Error?t.message:String(t)}`})}oo.current=null,tV.current=!1,$(!1),tt(null),z({type:"end"})}},[g,r,Q,t,ow,oR,ob,oA,oM,oS,oC,oc]),oU=(0,n.useCallback)(async(o,r)=>{if(tV.current||tZ.current)return;let n=`${r?"!!":"!"}${o}`;tZ.current=!0,O({command:o,excludeFromContext:r}),A(!0);try{let e=tq.current??t?.id??await ow();if(!e)throw Error("Unable to create a session for the shell command");ob(1,n),await io(e,{type:"bash",command:o,excludeFromContext:r}),await ok(e)}catch(t){console.error("Failed to execute shell command:",t),oM({type:"error",message:t instanceof Error?t.message:String(t)}),e.chatInputRef?.current?.insertIfEmpty(n)}finally{tZ.current=!1,O(null),A(!1)}},[oM,ow,ok,e.chatInputRef,ob,t]),o_=(0,n.useCallback)(async()=>{let e=tq.current;if(e)try{await io(e,{type:tZ.current?"abort_bash":"abort"})}catch(e){console.error("Failed to abort:",e)}},[]),oq=(0,n.useCallback)(async e=>{let t=tq.current;if(t){eQ(e);try{let{cancelled:o,newSessionId:r}=await io(t,{type:"fork",entryId:e})??{};!o&&r&&a?.(r)}catch(e){console.error("Fork failed:",e)}finally{eQ(null)}}},[a]),oV=(0,n.useCallback)(async e=>{let t=tq.current;t&&(io(t,{type:"navigate_tree",targetId:e}).catch(()=>{}),w(e),await ov(t,e))},[ov]),oK=(0,n.useCallback)(async e=>{w(e);let t=tq.current;t&&(await ov(t,e),e&&io(t,{type:"navigate_tree",targetId:e}).catch(()=>{}))},[ov]),oJ=(0,n.useCallback)(async(e,t)=>{if(g){let o={provider:e,modelId:t};oa.current=o,ee(o),e4(o);let r=tq.current??await t9.current;if(!r)return;try{await io(r,{type:"set_model",provider:e,modelId:t})}catch(e){console.error("Failed to set model:",e)}return}let o=tq.current;if(!o)return;let r=++or.current,n=e0??x?.context.model??null;e1({provider:e,modelId:t});try{await io(o,{type:"set_model",provider:e,modelId:t})}catch(o){console.error("Failed to set model:",o),or.current===r&&(e1(n&&(n.provider!==e||n.modelId!==t)?n:null),oM({type:"error",message:o instanceof Error?o.message:String(o)}))}},[oM,e0,x?.context.model,g,ee]),oG=(0,n.useCallback)(async()=>{let e=tq.current;if(e&&!e6){e5(!0),e8(null),e9(null);try{let t=await io(e,{type:"compact"});e9(iy(t,"manual")),await ok(e,!0)}catch(e){e8(e instanceof Error?e.message:String(e)),e9(null)}finally{e5(!1)}}},[e6,ok]),oY=(0,n.useCallback)(async e=>{let o=++on.current,n=r??t?.cwd??"",s=n?`/api/models?cwd=${encodeURIComponent(n)}`:"/api/models",i=os.current;i?.abort();let a=new AbortController;os.current=a;let l=()=>a.abort();e?.aborted?a.abort():e?.addEventListener("abort",l,{once:!0});try{let e=await fetch(s,{signal:a.signal});if(!e.ok){let t=`HTTP ${e.status}`;try{let o=await e.json();o?.error&&(t=o.error)}catch{}throw Error(t)}let t=await e.json();if(o!==on.current||h!==oi.current)return;Z(null),B(t.models),V(t.thinkingLevels??{}),J(t.thinkingLevelMaps??{}),Y(t.modelScopeWarnings??[]);let r=t.modelList??[];if(_(r),g&&!tq.current){let e=(t.defaultModel?r.find(e=>e.id===t.defaultModel?.modelId&&e.provider===t.defaultModel?.provider):void 0)??r[0];eo(e?{provider:e.provider,modelId:e.id}:null);let o=e?t.thinkingLevelPins?.[`${e.provider}/${e.id}`]:void 0;null===ol.current&&eq(o??"auto")}}catch(e){if(a.signal.aborted||o!==on.current||h!==oi.current)return;Z(e instanceof Error?e.message:String(e))}finally{e?.removeEventListener("abort",l),os.current===a&&(os.current=null)}},[g,h,r,t?.cwd]),oX=(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=tq.current??await ow(),i=e=>(e.handled&&(e.error?oM({type:"error",message:e.error}):"openSessionStats"!==e.action&&oM({type:"success",message:e.message??"Command completed"})),e);try{switch(o){case"compact":{if(!s||e6)return i({handled:!0,error:"No active session to compact"});e5(!0),e8(null),e9(null);let e=await io(s,{type:"compact",...n?{customInstructions:n}:{}});return e9(iy(e,"manual")),await ok(s,!0)&&ob(),i({handled:!0,message:"Compacted context"})}case"reload":if(!s)return i({handled:!0,error:"No active session to reload"});return await io(s,{type:"reload"}),await Promise.all([ok(s,!1,!0),oy(s),oj(),oY()]),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 io(s,{type:"set_session_name",name:eA(n)}),await ok(s)&&ob(),i({handled:!0,message:`Session renamed to ${n}`});case"session":{if(!s)return i({handled:!0,error:"No active session"});let e=await io(s,{type:"get_session_stats"});return e&&tp(e),p?.(),i({handled:!0,action:"openSessionStats"})}case"copy":{if(!s)return i({handled:!0,error:"No active session"});let e=await io(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&&e5(!1)}},[oM,ow,e6,oY,ok,oj,oy,ob,p]),oZ=(0,n.useCallback)(async e=>{let t=!1;try{let o=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(o.ok){let e=await o.json(),r=e.state;if(e.running&&r&&(r.isStreaming||r.isPromptRunning||r.isBashRunning||r.isCompacting))return;t=!0}}catch{}if(t){tV.current=!1,$(!1),tt(null);return}oA(e)},[oA]),oQ=(0,n.useCallback)(async(e,t)=>{let o=tq.current;if(!o)return;let r=t?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType}));tV.current=!0,$(!0),tt(e=>e??{kind:"waiting_model"});try{await io(o,{type:"steer",message:e,...r?.length?{images:r}:{}})}catch(e){console.error("Failed to steer:",e),oZ(o)}},[oZ]),o0=(0,n.useCallback)(async(e,t,o)=>{let r=tq.current;if(!r)return;let n=o?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType}));tV.current=!0,$(!0),tt(e=>e??{kind:"waiting_model"});try{await io(r,{type:"prompt",message:e,streamingBehavior:t,...n?.length?{images:n}:{}})}catch(e){console.error("Failed to queue prompt:",e),oZ(r)}},[oZ]),o1=(0,n.useCallback)(async(e,t)=>{let o=tq.current;if(!o)return;let r=t?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType}));tV.current=!0,$(!0),tt(e=>e??{kind:"waiting_model"});try{await io(o,{type:"follow_up",message:e,...r?.length?{images:r}:{}})}catch(e){console.error("Failed to follow up:",e),oZ(o)}},[oZ]),o2=(0,n.useCallback)(async()=>{let e=tq.current;if(e)try{await io(e,{type:"abort_compaction"})}catch(e){console.error("Failed to abort compaction:",e)}},[]),o4=(0,n.useCallback)(async()=>{let t=tq.current;if(t)try{let o=await io(t,{type:"clear_queue"});tw({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),oM({type:"error",message:"Failed to recall queued messages"})}},[e.chatInputRef,oM,tw]);(0,n.useEffect)(()=>{0===tj.length&&tR(!1)},[tj.length]);let o6=(0,n.useCallback)(async(e,t,o=!1)=>{let r=tq.current;if(!r)return tj;try{let n=await io(r,{type:"resolve_recovery",keep:e,discard:t,continueRun:o}),s=n?.remaining??[];return tC(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;tK.current=!!o.isStreaming,tJ.current=!!o.isPromptRunning,tV.current=!0,$(!0),tt(ia(o)),z({type:"start"}),oT(r),!o.isStreaming&&o.isPromptRunning&&oA(r)}catch{}})(),s}catch(e){return console.error("Failed to resolve queued message recovery:",e),oM({type:"error",message:"Failed to resolve queued message recovery"}),tj}},[tj,oM,oT,oA,tC]),o5=(0,n.useCallback)(async()=>{let e=tq.current;if(!e)return null;try{return await io(e,{type:"export_queue"})}catch(e){return console.error("Failed to export queue:",e),oM({type:"error",message:"Failed to export queue"}),null}},[oM]),o3=(0,n.useCallback)(async e=>{let t=tq.current;if(!t)return null;try{let o=await io(t,{type:"import_queue",entries:e});return o&&tw(id(o)),o?.imported??0}catch(e){return console.error("Failed to import queue:",e),oM({type:"error",message:"Failed to import queue"}),null}},[oM,tw]),o8=(0,n.useCallback)(async e=>{let t=tq.current;if(!t)return null;try{let o=await io(t,{type:"stage_recovery",entries:e});return o?.pendingRecovery&&tC(o.pendingRecovery),(o?.staged??0)>0&&tR(!0),o?.staged??0}catch(e){return console.error("Failed to stage imported queue:",e),oM({type:"error",message:"Failed to stage imported queue"}),null}},[oM,tC]),o7=(0,n.useCallback)(async(e,t,o)=>{let r=tq.current;if(!r)return!1;try{let n=await io(r,{type:"move_queue",kind:e,fromIndex:t,toIndex:o});return n&&tw(id(n)),!0}catch(e){return console.error("Failed to move queued message:",e),oM({type:"error",message:e instanceof Error?e.message:"Failed to move queued message"}),!1}},[oM,tw]),o9=(0,n.useCallback)(async(e,t)=>{let o=tq.current;if(!o)return null;try{let r=await io(o,{type:"recall_queue_item",kind:e,index:t});return r&&(void 0!==r.steering||void 0!==r.followUp)&&tw(id(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),oM({type:"error",message:e instanceof Error?e.message:"Failed to recall queued message"}),null}},[oM,tw]),re=(0,n.useCallback)(async(e,t,o,r)=>{let n=tq.current;if(!n)return!1;try{let s=await io(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&&tw(id(s)),!0}catch(e){return console.error("Failed to requeue message:",e),oM({type:"error",message:e instanceof Error?e.message:"Failed to requeue message"}),!1}},[oM,tw]),rt=(0,n.useCallback)(async(e,t)=>{let o=tq.current;if(!o)return!1;try{let r=await io(o,{type:"remove_queue_item",kind:e,index:t});return r&&tw(id(r)),!0}catch(e){return console.error("Failed to remove queued message:",e),oM({type:"error",message:e instanceof Error?e.message:"Failed to remove queued message"}),!1}},[oM,tw]),rn=(0,n.useCallback)(async e=>{if(ol.current="auto"===e?null:e,eq(e),"auto"===e)return;let t=tq.current??await t9.current;if(t)try{await io(t,{type:"set_thinking_level",level:e})}catch(e){console.error("Failed to set thinking level:",e)}},[]),rs=(0,n.useCallback)(async e=>{let t=(0,ir.xG)(e);ou(e);let o=tq.current??await t9.current;if(o)try{await io(o,{type:"set_tools",toolNames:t})}catch(e){console.error("Failed to set tools:",e)}},[ou]),ri=(0,n.useRef)(0),ra=(0,n.useCallback)(async e=>{let t=tq.current??await t9.current,o=++ri.current;if(e){if(ea.current="plan"===er?"default":er,ei(!0),el.current=!0,ej.current={sessionKey:"",signature:""},t)try{if(await io(t,{type:"prompt",message:"/plan"}),ri.current!==o)return}catch(e){if(ri.current!==o)return;console.error("Failed to enter plan mode:",e)}}else if(ei(!1),el.current=!1,ej.current={sessionKey:"",signature:""},t){try{if(await io(t,{type:"prompt",message:"/plan exit"}),ri.current!==o)return}catch(e){if(ri.current!==o)return;console.error("Failed to exit plan mode:",e)}if(ri.current!==o)return;try{let e=ea.current;await io(t,{type:"set_tools",toolNames:(0,ir.xG)(e)})}catch(e){console.error("Failed to restore tools after plan exit:",e)}}},[er]),rl=(0,n.useCallback)(e=>{ec(e);let t=tq.current;if(!t){ep.current=e;return}ep.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)})},[]),rd=(0,n.useCallback)(e=>{if(rl({...eS.current,collaborationMode:eM(e)}),ek.current=eM(e),ej.current={sessionKey:"",signature:""},"goal"!==e){ew.current=null,eU.current=!1,eH(e=>"idle"===e.status?e:{...e,status:"idle",goalText:null});let e=tq.current;e&&io(e,{type:"goal_stop"}).catch(()=>{})}},[rl]),rc=(0,n.useCallback)(async e=>{rl({...eS.current,tokenMode:eE(e)});let t=tq.current??await t9.current;if(t)try{if("economy"!==e||el.current){if("economy"!==e){let e=el.current?ir.SC:(0,ir.xG)("plan"===er?"default":er);await io(t,{type:"set_tools",toolNames:e})}}else await io(t,{type:"set_tools",toolNames:[...eD]})}catch(e){console.error("Failed to apply token mode tools:",e)}},[rl,er]),rp=(0,n.useCallback)(async e=>{rl({...eS.current,toolApprovalMode:eP(e)});let t=tq.current??await t9.current;if(t)try{await io(t,{type:"set_approval_mode",mode:eP(e)})}catch(e){console.error("Failed to apply approval mode:",e)}},[rl]),ru=(0,n.useCallback)(async e=>{rl({...eS.current,permissionRules:e});let t=tq.current??await t9.current;if(t)try{await io(t,{type:"set_approval_policy",policy:e})}catch(e){console.error("Failed to apply permission rules:",e)}},[rl]),rg=(0,n.useCallback)(async(e,t,o)=>{let r=tq.current;if(r)try{await io(r,{type:"resolve_approval",id:e,approve:t,reason:o})}catch(e){console.error("Failed to resolve approval:",e)}finally{eT(t=>t.filter(t=>t.id!==e))}},[]),rh=(0,n.useCallback)(e=>{ew.current=e},[]),rx=(0,n.useCallback)(e=>{let t=e.trim();if(!t)return;ew.current=t,eH(e=>({...e,status:"running",goalText:t,turnsUsed:0,noProgressTurns:0,tokensUsed:0,startedAt:Date.now()}));let o=tq.current;o&&io(o,{type:"goal_start",goalText:t}).catch(()=>{})},[]),rf=(0,n.useCallback)(()=>{if("running"!==eB.current.status)return;eH(e=>({...e,status:"paused"}));let e=tq.current;e&&io(e,{type:"goal_pause"}).catch(()=>{})},[]),rm=(0,n.useCallback)(()=>{let e=eB.current;if("paused"!==e.status&&"blocked"!==e.status)return;eH(e=>({...e,status:"running"}));let t=tq.current;t&&io(t,{type:"goal_resume"}).catch(()=>{})},[]),rk=(0,n.useCallback)(()=>{eU.current=!1,ew.current=null,eH(e=>({...e,status:"idle",goalText:null,turnsUsed:0,noProgressTurns:0}));let e=tq.current;e&&io(e,{type:"goal_stop"}).catch(()=>{})},[]),rv=(0,n.useCallback)(e=>{let t=e.trim();if(!t)return;eH(e=>({...e,goalText:t}));let o=tq.current;o&&io(o,{type:"goal_edit",goalText:t}).catch(()=>{})},[]),ry=tz.map(e=>`${e.id}:${e.status}:${e.completedAt??""}`).join("|"),rb=(0,n.useRef)(tz);rb.current=tz,(0,n.useEffect)(()=>{u?.(rb.current)},[ry,u]),(0,n.useEffect)(()=>()=>{u?.([])},[u]),(0,n.useEffect)(()=>{tP(()=>[])},[t?.id,r??t?.cwd]);let rw=(0,n.useCallback)(()=>{let e=t7.current,t=t1.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);t6.current=n>=r-150,t3.current=Date.now()+700,e.scrollTo({top:n,behavior:"smooth"})},[]),rj=(0,n.useCallback)(e=>{e instanceof KeyboardEvent&&(!iu.has(e.key)||e.target instanceof Element&&e.target.closest("input, textarea, [contenteditable='true']"))||(t5.current=Date.now()+1200)},[]),rS=(0,n.useCallback)(()=>{let e=t7.current;if(e){let{scrollTop:t,clientHeight:o,scrollHeight:r}=e;t6.current=t+o>=r-150}if(Date.now()<t5.current){t4.current=!1;return}Date.now()<t3.current||(t4.current=!1)},[]);(0,n.useEffect)(()=>{if(tY.current=!0,t){tq.current=t.id;let e=ey.current,o=eb.current;("auto"!==e||o.allow.length||o.ask.length||o.deny.length)&&(io(t.id,{type:"set_approval_mode",mode:e}).catch(()=>{}),io(t.id,{type:"set_approval_policy",policy:o}).catch(()=>{})),ok(t.id,!0,!0).then(e=>{e?.running&&(e.state?.isBashRunning&&(tZ.current=!0,A(!0)),oy(t.id),(e.state?.isStreaming||e.state?.isPromptRunning)&&(tK.current=!!e.state.isStreaming,tJ.current=!!e.state.isPromptRunning,tV.current=!0,$(!0),tt(ia(e.state)),z({type:"start"}),oT(t.id),!e.state.isStreaming&&e.state.isPromptRunning&&oA(t.id))),e?.state&&(void 0!==e.state.isCompacting&&e5(e.state.isCompacting),void 0!==e.state.contextUsage&&eG(e.state.contextUsage??null),void 0!==e.state.systemPrompt&&eX(e.state.systemPrompt??null),void 0!==e.state.thinkingLevel&&eq(e.state.thinkingLevel??"auto"),void 0!==e.state.extensionStatuses&&tm(e.state.extensionStatuses??[]),void 0!==e.state.extensionWidgets&&tv(e.state.extensionWidgets??[]),void 0!==e.state.queuedMessages&&tw(id(e.state.queuedMessages)),void 0!==e.state.pendingRecovery&&tC(e.state.pendingRecovery??[])),e?.running||fetch(`/api/agent/${encodeURIComponent(t.id)}`).then(e=>e.ok?e.json():null).then(e=>{e&&e.running&&oy(t.id)}).catch(()=>{})})}return()=>{tY.current=!1,oc(),tA(),oS(),oC()}},[oc]),(0,n.useEffect)(()=>{c?.(eY)},[eY,c]),(0,n.useEffect)(()=>{d&&d(x?.tree??[],b,oK)},[x?.tree,b,oK,d]),(0,n.useEffect)(()=>(window.addEventListener("keydown",rj),window.addEventListener("pointerdown",rj,{passive:!0}),()=>{window.removeEventListener("keydown",rj),window.removeEventListener("pointerdown",rj)}),[rj]),(0,n.useEffect)(()=>{let e=t7.current;if(e)return e.addEventListener("wheel",rj,{passive:!0}),e.addEventListener("touchstart",rj,{passive:!0}),e.addEventListener("scroll",rS,{passive:!0}),()=>{e.removeEventListener("wheel",rj),e.removeEventListener("touchstart",rj),e.removeEventListener("scroll",rS)}},[j.length,m,rS,rj]),(0,n.useEffect)(()=>{j.length>0&&(t2.current?(t0.current=!0,t1.current&&(t2.current=!1,rw())):m||!t0.current?(m||(t0.current=!0),oO("instant")):!tV.current&&(t4.current||t6.current)&&oO("smooth"))},[j.length,m,W,oO,rw]);let rC=(0,n.useRef)(!1);(0,n.useEffect)(()=>{let e;if(m){rC.current=!1;return}if(rC.current||0===j.length)return;rC.current=!0;let t=!1,o=-1,r=0,n=()=>{if(t||tV.current||!(t4.current||t6.current))return;oO("instant");let s=t7.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,oO]),(0,n.useEffect)(()=>{let e=new AbortController;return oY(e.signal).catch(e=>{if(e instanceof DOMException&&"AbortError"===e.name)return}),()=>e.abort()},[oY,l]),(0,n.useEffect)(()=>{if(!X)return;let e=()=>{"visible"===document.visibilityState&&oY()};return document.addEventListener("visibilitychange",e),window.addEventListener("online",e),()=>{document.removeEventListener("visibilitychange",e),window.removeEventListener("online",e)}},[X,oY]),(0,n.useEffect)(()=>{if(!e3)return;let e=setTimeout(()=>e8(null),3e3);return()=>clearTimeout(e)},[e3]),(0,n.useEffect)(()=>{if(!e7)return;let e=setTimeout(()=>e9(null),6e3);return()=>clearTimeout(e)},[e7]),(0,n.useEffect)(()=>{if(0===tl.visible.length)return;let e=tl.visible.find(e=>e.exiting);if(e){let t=setTimeout(()=>{td({type:"remove",id:e.id})},180);return()=>clearTimeout(t)}if(!tl.visible[0])return;let t=setTimeout(()=>{td({type:"mark_oldest_exiting"})},5e3);return()=>clearTimeout(t)},[tl.visible]),(0,n.useEffect)(()=>{tp(null)},[j.length,eJ?.tokens,eJ?.percent,eJ?.contextWindow]);let rT=x?.tree??[];return{data:x,loading:m,error:v,activeLeafId:b,messages:j,entryIds:C,streamState:R,agentRunning:W,bashRunning:N,pendingBash:L,modelNames:H,modelList:U,modelThinkingLevels:q,modelThinkingLevelMaps:K,modelScopeWarnings:G,modelsError:X,newSessionModel:Q,toolPreset:er,thinkingLevel:e_,retryInfo:eV,contextUsage:eJ,systemPrompt:eY,forkingEntryId:eZ,isCompacting:e6,compactError:e3,compactResult:e7,currentModel:ox,displayModel:of,sessionStats:om,tokenRate:I,planMode:es,subagents:tz,collaborationMode:eh,tokenMode:ex,toolApprovalMode:ef,permissionRules:em,modeSettings:ed,approvalRequests:eC,handleCollaborationModeChange:rd,handleTokenModeChange:rc,handleToolApprovalModeChange:rp,handlePermissionRulesChange:ru,resolveApproval:rg,setActiveGoalText:rh,goalState:eO,handleGoalStart:rx,handleGoalPause:rf,handleGoalResume:rm,handleGoalStop:rk,handleGoalEdit:rv,slashCommands:tn,slashCommandsLoading:ti,queuedMessages:ty,pendingRecovery:tj,recoveryIsImport:tT,notices:tl.visible,extensionDialog:tu,extensionCustomUi:th,extensionStatuses:tf,extensionWidgets:tk,respondToExtensionUi:oz,sendExtensionCustomInput:oI,agentPhase:te,isNew:g,promptAnchorActive:to,branchTree:rT,sessionIdRef:tq,eventSourceRef:tL,messagesEndRef:t8,scrollContainerRef:t7,lastUserMsgRef:t1,pendingScrollToUserRef:t2,initialScrollDoneRef:t0,scrollUserMsgToTop:rw,handleSend:oB,executeBash:oU,handleAbort:o_,handleFork:oq,handleNavigate:oV,handleModelChange:oJ,handleCompact:oG,handleSteer:oQ,handleFollowUp:o1,handlePromptWithStreamingBehavior:o0,handleAbortCompaction:o2,handleRecallQueue:o4,resolveRecovery:o6,exportQueueData:o5,importQueueData:o3,stageQueueImport:o8,moveQueuedMessage:o7,recallQueuedMessage:o9,requeueAt:re,removeQueuedMessage:rt,handleBuiltinSlashCommand:oX,handleToolPresetChange:rs,handleThinkingLevelChange:rn,handlePlanModeChange:ra,loadTools:oy,loadSlashCommands:oj,reloadModels:oY,setActiveLeafId:w,setData:f,setMessages:S,dispatch:z,setAgentRunning:$,setForkingEntryId:eQ,handleLeafChange:oK,handleAgentEventRef:tQ}}({session:e,newSessionCwd:t,onAgentEnd:$,onSessionCreated:i,onSessionForked:a,modelsRefreshKey:d,chatInputRef:c,onBranchDataChange:p,onSystemPromptChange:u,onSessionStatsPanelOpen:x,onSubagentsChange:h}),[tM,tE]=(0,n.useState)(!1);(0,n.useEffect)(()=>{0===ef.length&&tE(!1)},[ef.length]);let{balance:tP,refresh:tD,refreshSoon:tF}=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.useRef)(null),d=(0,n.useCallback)(async()=>{s.current?.abort();let e=new AbortController;s.current=e;try{let o=await fetch("/api/deepseek/balance",{signal:e.signal,cache:"no-store"}),n=await o.json();if(!a.current)return;if(n?.available&&null!=n.totalBalance){let e=l.current;(null===e||e.available!==n.available||e.reason!==n.reason||e.currency!==n.currency||e.totalBalance!==n.totalBalance||e.grantedBalance!==n.grantedBalance||e.toppedUpBalance!==n.toppedUpBalance)&&(l.current=n,t(n)),r(!1)}else null===l.current&&r(!0)}catch{if(!a.current)return;null===l.current&&r(!0)}},[]),c=(0,n.useCallback)(()=>{i.current&&clearTimeout(i.current),i.current=setTimeout(()=>{i.current=null,d()},2e3)},[d]);return{balance:e,failed:o,refresh:d,refreshSoon:c}}(),tW=ec?.provider==="deepseek",t$=(0,n.useRef)(null);(0,n.useEffect)(()=>{tW&&tD()},[tW,tD]),(0,n.useEffect)(()=>{if(tW)for(let e=U.length-1;e>=0;e--){let t=U[e];if("assistant"!==t.role||!t.usage)continue;let o=`${e}:${_[e]??""}`;o!==t$.current&&(t$.current=o,tF());break}},[U,_,tW,tF]);let tN=(0,n.useMemo)(()=>{let e=U.findLast(e=>"assistant"===e.role&&!!e.usage);if(!e?.usage)return null;let t=e.usage;return{model:e.model??"",input:t.input??0,output:t.output??0,cacheRead:t.cacheRead??0,costCNY:ro(e.model)?rr(e.model,t):0,costUSD:ro(e.model)?0:t.cost?.total??0}},[U]),[tA,tL]=(0,n.useState)(!1),[tO,tH]=(0,n.useState)(null),tB=(0,n.useRef)(!1);(0,n.useEffect)(()=>{if(!tu){tB.current=!1;return}if(V){tB.current=!0;return}tB.current&&(tB.current=!1,tH(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}(U)??null),tL(!0))},[V,tu,U]);let tU=(0,n.useCallback)(()=>{tL(!1);let e=t_.current;"plan"===tf&&tv("normal"),tx(!1).then(()=>{e&&eG(E("tasks.planReviewExecutePrompt",{plan:e}))})},[tx,eG,E,tf,tv]),t_=(0,n.useRef)(null);(0,n.useEffect)(()=>{t_.current=tO},[tO]);let tq=(0,n.useCallback)(e=>{tL(!1),e2(e)},[e2]),tV=(0,n.useCallback)(()=>{tL(!1),"plan"===tf&&tv("normal"),tx(!1)},[tx,tf,tv]);(0,n.useEffect)(()=>{ev&&W.current!==ev.id&&(W.current=ev.id,F.current&&P.current())},[ev]),(0,n.useEffect)(()=>(l=V||K?eX:null,()=>void(l=null)),[V,K,eX]);let[tK,tJ]=(0,n.useState)(!1),[tG,tY]=(0,n.useState)(!1),[tX,tZ]=(0,n.useState)(!1),tQ=(0,n.useCallback)(()=>{let e=e_.current;if(!e)return;let t=e.scrollHeight-e.scrollTop-e.clientHeight;tJ(e.scrollTop>1),tY(t>1),tZ(t>240)},[e_]),t0=(0,n.useCallback)(()=>{window.requestAnimationFrame(()=>{let e=e_.current,t=eU.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(),tQ(),window.setTimeout(r,200)})},[eU,e_,tQ,c]);(0,n.useEffect)(()=>{let e=e_.current;if(!e)return;let t=new ResizeObserver(tQ);return t.observe(e),e.firstElementChild&&t.observe(e.firstElementChild),e.addEventListener("scroll",tQ,{passive:!0}),tQ(),()=>{e.removeEventListener("scroll",tQ),t.disconnect()}},[U.length,e_,tQ]);let t1=(0,n.useRef)(null),t2=(0,n.useRef)([]),t4=(0,n.useMemo)(()=>({getOffsetForIndex:e=>t1.current?.getOffsetForIndex(e)?.[0]??0,sizeFor:e=>{let t=t1.current;if(!t)return 0;let o=t.measurementsCache[e];return o?.size??t.options.estimateSize?.(e)??0},totalHeight:()=>t1.current?.getTotalSize()??0,refToItemIndex:e=>t2.current[e],itemCount:t2.current.length}),[]),t6=ep?[ep.sessionId,ep.sessionFile??"",ep.sessionName??"",ep.userMessages,ep.assistantMessages,ep.toolCalls,ep.toolResults,ep.totalMessages,ep.tokens.input,ep.tokens.output,ep.tokens.cacheRead,ep.tokens.cacheWrite,ep.tokens.total,ep.cost??0,ep.totalActiveMs??0].join("|"):null,t5=(0,n.useRef)(ep);t5.current=ep,(0,n.useEffect)(()=>{g?.(t5.current)},[t6,g]),(0,n.useEffect)(()=>()=>{g?.(null)},[g]);let t3=es?`${es.percent??"null"}|${es.contextWindow}|${es.tokens??"null"}`:null,t8=(0,n.useRef)(es);t8.current=es,(0,n.useEffect)(()=>{f?.(t8.current)},[t3,f]),(0,n.useEffect)(()=>()=>{f?.(null)},[f]);let{isDragOver:t7,handleDragEnter:t9,handleDragOver:oe,handleDragLeave:ot,handleDrop:oo}=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(V){let t=e.filter(e=>e.type.startsWith("image/"));t.length&&c?.current?.addImages(t);return}c?.current?.addFiles(e,t)},[V,c])),or=U.filter(e=>"user"===e.role||"assistant"===e.role),on=(0,n.useMemo)(()=>{let e=new Set,t=[];for(let r=U.length-1;r>=0&&t.length<50;r-=1){var o;let n="user"!==(o=U[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},[U]),os=(S=or.length,(C=(0,n.useRef)([])).current=Array(S).fill(null).map((e,t)=>C.current[t]??null),C),oi=eT&&0===U.length&&!q.isStreaming&&!V,oa=e?.cwd??t??void 0,ol=(0,n.useMemo)(()=>(function(e,t,o){let r=new Map;for(let t of e)"toolResult"===t.role&&r.set(t.toolCallId,t);let n=-1;for(let t=e.length-1;t>=0;t--)if("user"===e[t].role){n=t;break}let s=new Map,i=0;e.forEach((e,t)=>{("user"===e.role||"assistant"===e.role)&&s.set(t,i++)});let a=[];for(let n=0;n<e.length;){let s,i=e[n],l="custom"===i.role&&"compaction"===i.customType;if("user"!==i.role&&!l){a.push({kind:"single",idx:n}),n+=1;continue}let d=n,c=d+1;for(;c<e.length&&"user"!==e[c].role;)c+=1;let p=function(e,t,o){for(let n=o-1;n>t;n--){var r;if("assistant"===(r=e[n]).role&&tr(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}(e,d,c);if(-1===p){a.push({kind:"turn",userIdx:d,endIdx:c,startsCompactionTurn:l,finalAssistantIdx:p,visibleProcessIndices:[],processBlocks:[],finalAnswerMessage:null,writtenFiles:void 0}),n=c;continue}let u=[];for(let e=d+1;e<p;e++)u.push(e);let g=u.filter(t=>tg(e[t])),h=e[p],x=tr(h),f=x.processBlocks.length>0?th(h,x.processBlocks,{omitUsage:!0}):null,m=x.answerBlocks.length>0?th(h,x.answerBlocks):null,k=tl(e,t,g,r);if(f&&(k=k.concat(ta(h,{messageIndex:p,entryId:t[p],toolResults:r}).processBlocks)),m){let t=[];for(let o=d+1;o<=p;o++){let r=e[o];if(r?.role==="assistant")for(let e of r.content??[])t.push(e)}s=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 tp(o)}(i,o);a&&(r.has(a)||(r.add(a),n.push({filePath:a})))}return n}(t,r,o)}a.push({kind:"turn",userIdx:d,endIdx:c,startsCompactionTurn:l,finalAssistantIdx:p,visibleProcessIndices:g,processBlocks:k,finalAnswerMessage:m,writtenFiles:s}),n=c}return{toolResultsMap:r,lastUserIdx:n,visibleRefIndexByMessage:s,items:a}})(U,_,oa),[U,_,oa]),od=ec?X[`${ec.provider}:${ec.modelId}`]??null:null,oc=ec?Z[`${ec.provider}:${ec.modelId}`]??null:null,op=(0,n.useCallback)(()=>{et()},[et]),ou=(0,n.useCallback)(e=>{tx(e),e&&"plan"!==tf?tv("plan"):e||"plan"!==tf||tv("normal")},[tx,tv,tf]),og=(0,n.useCallback)(e=>{tv(e),"plan"!==e||tu?"plan"!==e&&tu&&tx(!1):tx(!0)},[tv,tx,tu]),oh=(0,r.jsx)(sH,{ref:c,onSend:eG,onBash:eY,tasksBoardEnabled:b,onAbort:eX,onSteer:V?e2:void 0,onFollowUp:V?e4:void 0,onPromptWithStreamingBehavior:V?e6:void 0,isStreaming:V,model:ec,modelNames:G,modelList:Y,modelScopeWarnings:Q,modelsError:ee,onRetryModels:op,onModelChange:e0,compactResult:ed,toolPreset:eo,onToolPresetChange:e||eT?ti:void 0,planMode:tu,onPlanModeChange:ou,collaborationMode:tf,tokenMode:tm,toolApprovalMode:tk,onCollaborationModeChange:og,onTokenModeChange:ty,onToolApprovalModeChange:tb,goalState:tS,onGoalStart:tC,onGoalPause:tT,onGoalResume:tR,onGoalStop:tz,thinkingLevel:er,onThinkingLevelChange:e||eT?td:void 0,availableThinkingLevels:od,thinkingLevelMap:oc,retryInfo:en,queuedMessages:ex,inputHistory:on,onRecallQueue:e3,onMoveQueue:te,onRecallOne:tt,onRequeueAt:to,onRemoveQueueItem:tn,slashCommands:eg,slashCommandsLoading:eh,onLoadSlashCommands:tc,onBuiltinCommand:ts,onAudioUnlock:I,draftKey:e?.id??(t?`new:${t}`:void 0),cwd:e?.cwd??t}),ox=ew.filter(e=>"belowEditor"!==e.placement),of=ew.filter(e=>"belowEditor"===e.placement),om=ea?E("desktop.compacting"):function(e,t){if(e?.kind==="running_tools"){let o=e.tools.map(e=>e.name);return 0===o.length?t("desktop.runningTool"):t("desktop.runningTools",{tools:o.length<=3?o.join(", "):`${o.slice(0,2).join(", ")} (+${o.length-2})`})}return e?.kind==="waiting_model"?t("desktop.waitingForModel"):e?.kind==="running_command"?t("desktop.runningCommand"):null}(eC,E);return H?(0,r.jsx)("div",{className:"flex h-full items-center justify-center text-text-muted",children:E("desktop.loadingSession")}):B?(0,r.jsx)("div",{className:"flex h-full items-center justify-center text-red-400",children:B}):(0,r.jsxs)("div",{className:"relative flex h-full min-w-0 flex-col overflow-hidden",onDragEnter:t9,onDragOver:oe,onDragLeave:ot,onDrop:oo,children:[t7&&(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"})]})]})]}),ev&&(0,r.jsx)(iR,{request:ev,onRespond:ej}),ey&&(0,r.jsx)(iz,{request:ey,onInput:eS}),!eT&&ef.length>0&&!tM&&(0,r.jsx)(s_,{items:ef,sessionId:e?.id,onResolve:e8,onExport:e7,onStageImport:e9,onDismiss:()=>tE(!0),mode:em?"import":"recovery"}),tw.length>0&&(0,r.jsx)(rA,{request:tw[0]??null,queuedCount:Math.max(0,tw.length-1),busy:!1,onResolve:(e,t)=>{let o=tw[0];o&&tj(o.id,e,t)}}),oi?(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:M?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:M?"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.10.6"]})]}),(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:M?16:34},children:(0,r.jsx)(iT,{notices:ek,align:"right"})}),"goal"===tf&&(0,r.jsx)(r$,{goalState:tS,onPause:tT,onResume:tR,onStop:tz,onEdit:tI}),oh,(0,r.jsx)("div",{style:{padding:"0 16px 6px",paddingRight:M?16:34,marginTop:-15},children:(0,r.jsx)(s5,{onViewFullHistory:v,cwd:oa,systemPrompt:y,sessionStats:ep,contextUsage:es,hasSession:!!e,showChat:!0,showSoundLabel:!0,soundEnabled:T,onSoundToggle:R,onCompact:e?e1:void 0,onAbortCompaction:e5,isCompacting:ea,compactError:el,isDeepSeekOfficial:tW,deepseekBalance:tP,lastTurnUsage:tN})})]})}):(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*!M,zIndex:40,padding:"0 16px",pointerEvents:"none"},children:(0,r.jsx)("div",{style:{maxWidth:820,margin:"0 auto"},children:(0,r.jsx)(iT,{notices:ek,floating:!0,align:"right"})})}),(0,r.jsxs)("div",{className:"relative flex-1 min-h-0 min-w-0",children:[(0,r.jsx)("div",{ref:e_,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)(iS,{statuses:eb}),(0,r.jsx)(iC,{widgets:ox}),(()=>{let{toolResultsMap:t,lastUserIdx:o,visibleRefIndexByMessage:n,items:s}=ol,i=(s,i={})=>{let a=i.messageOverride??U[s],l="user"===a.role&&s>0&&"assistant"===U[s-1].role?_[s-1]:void 0,d="user"===a.role||"assistant"===a.role,c=n.get(s),p=i.keyPrefix??"message",u=!1;if("assistant"===a.role){u=!0;for(let e=s+1;e<U.length;e++){let t=U[e].role;if("user"===t)break;if("assistant"===t){u=!1;break}}u&&q.isStreaming&&s===U.length-1&&(u=!1)}void 0!==i.showTimestamp&&(u=i.showTimestamp);let g=(0,r.jsx)(rd,{message:a,toolResults:t,modelNames:G,cwd:oa,onOpenFile:m,entryId:_[s],onFork:V||eT||0===s&&"user"===a.role?void 0:eZ,forking:ei===_[s],onNavigate:V?void 0:eQ,prevAssistantEntryId:V?void 0:l,onEditContent:N,onQuoteReply:L,onCreateTask:O,showTimestamp:u,prevTimestamp:s>0?U[s-1].timestamp:void 0,sessionId:e?.id??eB.current??void 0,writtenFiles:i.writtenFiles,subagents:w,onOpenSubagent:j},`${p}-view-${s}`);return d&&!1!==i.attachRef&&void 0!==c?(0,r.jsx)("div",{ref:e=>{os.current[c]=e,s===o&&(eq.current=e,e&&eV.current&&(eV.current=!1,eK.current=!0,eJ()))},children:g},`${p}-${s}`):g},a=[],l=[],d=(e,t)=>{a.push(e),l.push(t)};for(let a of s){if("single"===a.kind){d(i(a.idx),n.get(a.idx));continue}let{userIdx:s,endIdx:l,startsCompactionTurn:c,finalAssistantIdx:p}=a;if((V||q.isStreaming)&&l===U.length&&(s===o||c)){d(i(s),n.get(s));let o=q.streamingMessage?.role==="assistant",a=[],c=!o&&p>=0?p:l;for(let e=s+1;e<c;e++)tg(U[e])&&a.push(e);let u=tl(U,_,a,t),g=null;if(!o&&p>=0){let e=U[p],o=tr(e,{isStreaming:!0}),r=ta(e,{messageIndex:p,entryId:_[p],toolResults:t,isStreaming:!0});u=u.concat(r.processBlocks),o.answerBlocks.length>0&&(g=th(e,o.answerBlocks,{omitUsage:!0}))}if(o){let e=q.streamingMessage,o=tr(e,{isStreaming:!0}),r=ta(e,{messageIndex:U.length,toolResults:t,isStreaming:!0});u=u.concat(r.processBlocks),o.answerBlocks.length>0&&(g=th(e,o.answerBlocks,{omitUsage:!0}))}if(u.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=>{os.current[t]=e},children:(0,r.jsx)(nw,{blocks:u,isStreaming:V||q.isStreaming,cwd:oa,onOpenFile:m,sessionId:e?.id??eB.current??void 0,tokenRate:eu})},`live-process-group-${s}`),t)}g&&d((0,r.jsx)(rd,{message:g,isStreaming:!0,modelNames:G,cwd:oa,onOpenFile:m,onQuoteReply:L},`live-answer-${s}`),p>=0?n.get(p):void 0);continue}if(-1===p){for(let e=s;e<l;e++)d(i(e),n.get(e));continue}d(i(s),n.get(s));let{processBlocks:u,finalAnswerMessage:g,writtenFiles:h,visibleProcessIndices:x}=a;if(u.length>0){let t=x.map(e=>n.get(e)).find(e=>"number"==typeof e)??(g?void 0:n.get(p));d((0,r.jsx)("div",{ref:void 0===t?void 0:e=>{os.current[t]=e},children:(0,r.jsx)(nw,{blocks:u,isStreaming:!1,defaultExpanded:!g,onAutoExpanded:void 0,cwd:oa,onOpenFile:m,sessionId:e?.id??eB.current??void 0})},`process-group-${s}-${p}`),t)}g&&d(i(p,{messageOverride:g,writtenFiles:h}),n.get(p));for(let e=p+1;e<l;e++)d(i(e),n.get(e))}let c=[];return l.forEach((e,t)=>{void 0!==e&&(c[e]=t)}),t2.current=c,(0,r.jsx)(s8,{scrollElementRef:e_,items:a,virtualizerRef:t1})})(),om&&(ea||V&&!q.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:[om,eC?.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"}})]})}),J&&(0,r.jsx)(rd,{message:{role:"bashExecution",command:J.command,output:"",excludeFromContext:J.excludeFromContext},sessionId:e?.id??eB.current??void 0}),K&&!J&&(0,r.jsx)("div",{className:"py-2 text-[13px] text-text-muted",children:(0,r.jsx)("span",{className:"animate-[pulse_1.5s_infinite]",children:E("desktop.runningShellCommand")})}),(0,r.jsx)("div",{style:{height:96}}),(0,r.jsx)("div",{ref:eU}),(0,r.jsx)(rM,{open:tA,planText:tO,busy:V,onExecute:tU,onFeedback:tq,onExit:tV,onClose:()=>tL(!1)})]})})}),tK&&(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"}),tG&&(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"}),tX&&(0,r.jsxs)("button",{type:"button",onClick:()=>t0(),title:E("desktop.scrollToBottom"),"aria-label":E("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)(o6.Z,{size:12,weight:"bold","aria-hidden":"true"}),E("desktop.scrollToBottom")]})]}),M?null:(0,r.jsx)(ie,{messages:U,streamingMessage:q.streamingMessage,scrollContainer:e_,messageRefs:os,virtualizer:t4})]}),(0,r.jsxs)("div",{className:"relative z-10",children:[(0,r.jsx)("div",{style:{padding:"0 16px",paddingRight:M?16:34},children:(0,r.jsx)("div",{style:{maxWidth:820,margin:"0 auto"},children:(0,r.jsx)(iC,{widgets:of})})}),oh,(0,r.jsx)("div",{className:`session-info-bar-wrap${M?" is-mobile":""}`,children:(0,r.jsx)("div",{className:"session-info-bar-inner",children:(0,r.jsx)(s5,{onViewFullHistory:v,cwd:oa,systemPrompt:y,sessionStats:ep,contextUsage:es,hasSession:!!e,showChat:!0,soundEnabled:T,onSoundToggle:R,onCompact:e?e1:void 0,onAbortCompaction:e5,isCompacting:ea,compactError:el,branchTree:eL,branchActiveLeafId:eO,onBranchLeafChange:eH,isDeepSeekOfficial:tW,deepseekBalance:tP,lastTurnUsage:tN})})})]})]})]})}function iS({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 iC({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 iT({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 iR({request:e,onRespond:t}){let{t:o}=(0,D.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 iz({request:e,onInput:t}){let{t:o}=(0,D.s)(),s=(0,n.useRef)(null),i=function(e){let t=/^[┌├└╭╰][─┬┴┼]+[┐┤┘╮╯]$/,o=[];for(let r of e){let e=e8(r).trimEnd();if(t.test(e))continue;let n=r,s=te(n);("│"===s||"┃"===s)&&" "===te(n=e9(n,0))&&(n=e9(n,0));let i=function(e){let t=e7(e);for(let e=t.length-1;e>=0;e--)if(""!==t[e].char.trim())return e;return -1}(n),a=i>=0?e7(n)[i]?.char:void 0;("│"===a||"┃"===a)&&(n=e9(n,i)),o.push(function(e){let t=e;for(;;){let e=e7(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&&""===e8(o[0]).trim();)o.shift();for(;o.length>0&&""===e8(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(e6.lastIndex=0;null!==(t=e6.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=e5[r-30];else if(r>=90&&r<=97)o.color=e3[r-90];else if(r>=40&&r<=47)o.backgroundColor=e5[r-40];else if(r>=100&&r<=107)o.backgroundColor=e3[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 e5[e];if(e>=8&&e<16)return e3[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 iI={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"},iM={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 iE(e){return(e.replace(/\\/g,"/").split("/").pop()??"").toLowerCase().split(".").pop()??""}function iP(e){let t=e.nodeType===Node.ELEMENT_NODE?e:e.parentElement;return t?.closest(".file-source-line[data-line-number]")??null}function iD(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(iP(o.startContainer)?.dataset.lineNumber),n=Number(iP(o.endContainer)?.dataset.lineNumber);return Number.isInteger(r)&&Number.isInteger(n)?r<=n?{startLine:r,endLine:n}:{startLine:n,endLine:r}:null}function iF(e,t,o,r={}){let n=en(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 iW({filePath:e,sourceSessionId:t}){let{t:o}=(0,D.s)();return(0,r.jsx)("a",{href:iF(e,"download",t),download:es(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)(I.z,{size:11,"aria-hidden":"true"})})}let i$={delete:"3px solid var(--git-status-deleted)",add:"3px solid var(--git-status-added)",edit:"3px solid var(--git-status-modified)"},iN="var(--git-status-deleted-bg)",iA="var(--git-status-added-bg)",iL="var(--git-status-added)";function iO(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KB`:`${(e/1048576).toFixed(1)} MB`}function iH({oldContent:e,newContent:t}){let{t:o}=(0,D.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?iN:"added"===e.kind?iA:"transparent",o=e.block?i$[e.block]:"3px solid transparent",n="added"===e.kind?iL:"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 iB({patch:e}){let t=oX(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?iN:"added"===e.kind?iA:"transparent",o=e.block?i$[e.block]:"3px solid transparent",n="added"===e.kind?iL:"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 iU({filePath:e,cwd:t,sourceSessionId:o}){let{t:s}=(0,D.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),x=es(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(iF(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 f=iF(e,"read",o,i?{v:i}:void 0),m=null!=l?iO(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:ei(e,t)}),(0,r.jsx)("span",{style:{marginLeft:"auto"},children:x||s("desktop.image")}),c&&(0,r.jsxs)("span",{children:[c.w," \xd7 ",c.h]}),m&&(0,r.jsx)("span",{children:m}),(0,r.jsx)(iW,{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:f,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 i_({filePath:e,cwd:t,sourceSessionId:o}){let{t:s}=(0,D.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),x=es(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(iF(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 f=iF(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:ei(e,t)}),(0,r.jsx)("span",{style:{marginLeft:"auto"},children:x||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:iO(l)}),(0,r.jsx)(iW,{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:f,onLoadedMetadata:e=>p(e.currentTarget.duration),onError:()=>g(s("desktop.failedToLoadAudio")),style:{width:"100%"}},f)]})})]})}function iq({filePath:e,cwd:t,sourceSessionId:o}){let{t:s}=(0,D.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=iE(e),h="pdf"===g,x=h?iF(e,"read",o,i?{v:i}:void 0):iF(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(iF(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(iF(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:ei(e,t)}),(0,r.jsx)("span",{style:{marginLeft:"auto"},children:"docx"===g?s("desktop.docxPreview"):"pdf"}),null!=l&&(0,r.jsx)("span",{children:iO(l)}),(0,r.jsx)(iW,{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:x,sandbox:h?void 0:"allow-same-origin",title:s("desktop.previewFile",{file:es(e)}),style:{width:"100%",height:"100%",border:"none",background:h?"var(--bg)":"#eef1f5"}},x)})]})}function iV({filePath:e,cwd:t,sourceSessionId:o,onOpenFile:n,onAtMention:s,onMentionLines:i,initialDisplayMode:a}){let l;return null!==(iI[iE(e)]??null)?(0,r.jsx)(iU,{filePath:e,cwd:t,sourceSessionId:o}):null!==(iM[iE(e)]??null)?(0,r.jsx)(i_,{filePath:e,cwd:t,sourceSessionId:o}):null!==("pdf"===(l=iE(e))||"docx"===l?l:null)?(0,r.jsx)(iq,{filePath:e,cwd:t,sourceSessionId:o}):(0,r.jsx)(iK,{filePath:e,cwd:t,sourceSessionId:o,onOpenFile:n,onAtMention:s,onMentionLines:i,initialDisplayMode:a})}function iK({filePath:e,cwd:t,sourceSessionId:o,onOpenFile:s,onAtMention:i,onMentionLines:a,initialDisplayMode:l}){let d,c,{t:p}=(0,D.s)(),[u,g]=(0,n.useState)(null),[h,x]=(0,n.useState)(null),[f,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,E]=(0,n.useState)(null),P=(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(iF(e,"read",o)).then(e=>e.json()).then(e=>e.error?(b(e.error),null):(t?(g(t=>(t&&x(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),x(null),m(null),j(!1),C("source"),R(!1),I(0),P.current&&(P.current.close(),P.current=null),$(e).then(e=>{(e?.language==="markdown"||e?.language==="html")&&"diff"!==l&&j(!0)}).finally(()=>v(!1)),W(e);let t=new EventSource(iF(e,"watch",o));return P.current=t,t.addEventListener("change",()=>{$(e,!0),W(e)}),()=>{t.close(),P.current=null}},[e,$,W,l,o]);let N=(0,n.useMemo)(()=>ob(u?.content??""),[u?.content]),A=f?.supported===!0&&"string"==typeof f.patch;(0,n.useEffect)(()=>{"diff"===l&&A&&C("diff")},[A,l]);let L=A&&f?.status==="deleted",O=(0,n.useCallback)(o=>{a&&o&&a(ei(e,t),o.startLine,o.endLine)},[t,e,a]);if((0,n.useEffect)(()=>{let e=()=>{let e=F.current,t="source"===S&&!w;E(a&&t&&e?iD(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?iD(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(L&&!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:ei(e,t)}),(0,r.jsx)("div",{style:{flex:1,overflow:"auto",background:"var(--bg)"},children:(0,r.jsx)(iB,{patch:f.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=er(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||A;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:ei(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:iO(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?.(ei(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)(iW,{filePath:e,sourceSessionId:o})]}),(0,r.jsx)("div",{ref:F,style:{flex:1,overflow:"auto",background:"var(--bg)"},children:"diff"===S&&q?A?(0,r.jsx)(iB,{patch:f.patch}):(0,r.jsx)(iH,{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)(tf.oz,{remarkPlugins:oS,rehypePlugins:oC,components:{h1:({children:e})=>(0,r.jsx)("h1",{id:oy(e),children:e}),h2:({children:e})=>(0,r.jsx)("h2",{id:oy(e),children:e}),h3:({children:e})=>(0,r.jsx)("h3",{id:oy(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)(oH,{code:s.replace(/\n$/,"")}):(0,r.jsx)(o_,{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?tu(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)(tm.A,{language:"text"===u.language?"plaintext":u.language,style:oT,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 iJ={running:"var(--accent)",completed:"#22c55e",failed:"#ef4444",stopped:"#d97706"},iG={running:"desktop.subagentsStatusRunning",completed:"desktop.subagentsStatusCompleted",failed:"desktop.subagentsStatusFailed",stopped:"desktop.subagentsStatusStopped"};function iY({agent:e,selected:t,onSelect:o}){let[s,i]=(0,n.useState)(!1),{t:a}=(0,D.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=iJ[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(iG[e.status])})]})}function iX({subagents:e,onSelect:t,selectedId:o}){let{t:s}=(0,D.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)(v.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)(iY,{agent:e,selected:e.id===o,onSelect:t},e.id))})]})}let iZ={user:{color:"var(--accent)"},assistant:{color:"var(--text)"},toolResult:{color:"var(--text-dim)"},bashExecution:{color:"var(--text-muted)"}};function iQ({line:e,roleLabel:t}){let o=iZ[e.role]??iZ.toolResult;return(0,r.jsxs)("div",{style:{marginBottom:6},children:[(0,r.jsxs)("div",{style:{fontSize:10.5,fontWeight:600,color:o.color,marginBottom:2,fontFamily:"var(--font-mono)"},children:["[",t(e.role),"]"]}),(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 i0({agent:e,cwd:t,onBack:o}){let{t:s}=(0,D.s)(),a=e=>s("user"===e?"desktop.transcriptRoleUser":"assistant"===e?"desktop.transcriptRoleAssistant":"toolResult"===e?"desktop.transcriptRoleResult":"desktop.transcriptRoleBash"),[l,d]=(0,n.useState)([]),[c,p]=(0,n.useState)(!0),[u,g]=(0,n.useState)(null),h=(0,n.useRef)(null),x=(0,n.useRef)(!0),f=(0,n.useCallback)(async(o=!1)=>{if(e.id&&t){o||p(!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||g(s.error??`HTTP ${n.status}`);return}d(s.lines??[]),g(null)}catch(e){o||g(e instanceof Error?e.message:String(e))}finally{p(!1)}}},[e.id,t]);(0,n.useEffect)(()=>{f()},[f]);let m=(0,n.useRef)(e.status);(0,n.useEffect)(()=>{let t="running"===m.current;m.current=e.status,t&&"running"!==e.status&&f(!0)},[e.status]),(0,n.useEffect)(()=>{if("running"!==e.status)return;let t=setInterval(()=>void f(!0),2e3);return()=>clearInterval(t)},[e.status,f]),(0,n.useEffect)(()=>{let e=h.current;e&&x.current&&(e.scrollTop=e.scrollHeight)},[l]);let k=e.completedAt?e.completedAt-e.startedAt:void 0,v=e.tokens?.total??e.tokens?.input??e.tokens?.output,y="completed"===e.status?"#22c55e":"failed"===e.status?"#ef4444":"stopped"===e.status?"#d97706":"var(--accent)";return(0,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)(i.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:y,boxShadow:"running"===e.status?`0 0 0 0 ${y}`:"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!==v&&v>0&&(0,r.jsxs)("span",{children:[void 0===v?"":v>=1e6?`${(v/1e6).toFixed(1)}M`:v>=1e3?`${(v/1e3).toFixed(1)}k`:`${v}`," tokens"]}),void 0!==k&&(0,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`}(k)}),(0,r.jsx)("span",{style:{color:y},children:s(`desktop.subagentsStatus${"running"===e.status?"Running":"completed"===e.status?"Completed":"failed"===e.status?"Failed":"Stopped"}`)})]})]}),(0,r.jsx)("div",{ref:h,onScroll:e=>{let t=e.currentTarget;x.current=t.scrollHeight-t.scrollTop-t.clientHeight<40},style:{flex:1,minHeight:0,overflowY:"auto",overflowX:"hidden",padding:"8px 10px",background:"var(--bg)"},children:c?(0,r.jsxs)("div",{style:{fontSize:12,color:"var(--text-dim)",padding:"12px 4px"},children:[s("desktop.loading"),"…"]}):u?(0,r.jsx)("div",{style:{fontSize:12,color:"#ef4444",padding:"12px 4px"},children:u}):0===l.length?(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-dim)",padding:"12px 4px"},children:"running"===e.status?s("desktop.subagentsWaitingFirstMessage"):s("desktop.subagentsNoTranscript")}):(0,r.jsx)("div",{style:{paddingBottom:8},children:l.map((e,t)=>(0,r.jsx)(iQ,{line:e,roleLabel:a},t))})})]})}function i1({tabs:e,activeTabId:t,onSelectTab:o,onCloseTab:s}){let{t:i}=(0,D.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:eo(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)(p.X,{size:11,"aria-hidden":"true"})})]},e.id)})})}var i2=o(27289),i4=o(93534),i6=o(45781),i5=o(68731),i3=o(93912),i8=o(23675),i7=o(48716),i9=o(47013),ae=o(51265);let at={"restore-script":"restore","generate-cmd":"cmd",keep:"keep","keep-with-warning":"warning",manual:"manual"};function ao({cwd:e}){let{t}=(0,D.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),[x,f]=(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)(""),[E,P]=(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),f(new Set(n.preview.categories)),k(new Set),y(!1)}catch{w(String(t("desktop.backupImportFailed")))}}},[t]),A=(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:[...x],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,x,m,v,t]),L=(0,n.useCallback)(async o=>{if(o.installPrompt&&e){P(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{P(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)(i9.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)(ae._,{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:x.has(e),onChange:t=>{let o=new Set(x);t.target.checked?o.add(e):o.delete(e),f(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:at[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:E===o.name,onClick:()=>L(o),style:{padding:"4px 10px",fontSize:11,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:4,color:"var(--text)",cursor:E===o.name?"wait":"pointer"},children:E===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:A,disabled:j||0===x.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===x.size?.5:1},children:[(0,r.jsx)(ae._,{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)(o7.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)(V.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 ar={position:"relative",width:40,height:22,borderRadius:11,border:"none",cursor:"pointer",padding:0,flexShrink:0,transition:"background 0.18s ease",outline:"none"},an={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 as({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:{...ar,background:e?"var(--accent)":"color-mix(in srgb, var(--border) 70%, var(--bg))"},children:(0,r.jsx)("span",{style:{...an,left:e?21:3}})})]})}function ai({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 aa="pi-input-shortcut";function al(){try{let e=localStorage.getItem(aa);return"ctrl-enter"===e?"ctrl-enter":"enter"}catch{return"enter"}}function ad(){let{t:e}=(0,D.s)(),[t,o]=(0,n.useState)(al);(0,n.useEffect)(()=>{let e=()=>o(al());return window.addEventListener("storage",e),()=>window.removeEventListener("storage",e)},[]);let s=(0,n.useCallback)(e=>{o(e);try{localStorage.setItem(aa,e),window.dispatchEvent(new StorageEvent("storage",{key:aa,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)(ai,{title:e("desktop.inputShortcut"),description:e("desktop.inputShortcutDescription"),children:(0,r.jsx)(as,{checked:"ctrl-enter"===t,onChange:e=>s(e?"ctrl-enter":"enter"),label:e("desktop.useCtrlEnter"),description:e("desktop.useCtrlEnterDescription")})})]})}var ac=o(95650),ap=o(55803),au=o(23602),ag=o(18613),ah=o(12779);let ax={display:"flex",gap:6,flexWrap:"wrap"};function af(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 am({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 ak={display:"inline-flex",alignItems:"center",gap:6,padding:0,border:0,background:"transparent",color:"var(--accent)",fontSize:11,cursor:"pointer",whiteSpace:"nowrap"},av={onMouseEnter:e=>{e.currentTarget.style.textDecoration="underline"},onMouseLeave:e=>{e.currentTarget.style.textDecoration="none"}};function ay({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 ab({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 aw({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 aj(){let{mode:e,resolvedMode:t,themeName:o,setMode:s,setTheme:i,previewTheme:a,clearPreview:l,isThemeCached:d,borderDepth:c,setBorderDepth:p}=oc(),{locale:u,setLocale:g,t:h}=(0,D.s)(),[x,f]=(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&&f(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)(ay,{title:h("desktop.theme"),description:h("desktop.themeDescription"),children:[(0,r.jsx)(am,{icon:(0,r.jsx)(ac.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:ak,...av,children:[(0,r.jsx)(ap.N,{size:12,weight:"regular","aria-hidden":"true"}),h("desktop.openThemeFolder")]}),(0,r.jsxs)("button",{type:"button",onClick:z,style:ak,...av,children:[(0,r.jsx)(au.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:ax,children:[(0,r.jsx)("button",{type:"button",onClick:()=>j(""),disabled:null!==v,style:af(""===o,"__default__"===b,null!==v),onMouseEnter:()=>C(""),onMouseLeave:()=>C(null),children:h("desktop.defaultTheme")}),x.map(e=>(0,r.jsxs)("button",{type:"button",onClick:()=>j(e.name),disabled:null!==v,style:af(o===e.name,b===e.name,v===e.name),onMouseEnter:()=>C(e.name),onMouseLeave:()=>C(null),children:[e.displayName,(0,r.jsx)(aw,{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)(am,{icon:(0,r.jsx)(ab,{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)(am,{icon:"dark"===t?(0,r.jsx)(ag.A,{size:14,weight:"fill"}):(0,r.jsx)(ah.b,{size:14,weight:"fill"}),label:h("desktop.appearanceMode")}),(0,r.jsx)("div",{style:ax,children:[{value:"light",icon:(0,r.jsx)(ah.b,{size:15,weight:"light"===e?"fill":"regular"})},{value:"dark",icon:(0,r.jsx)(ag.A,{size:15,weight:"dark"===e?"fill":"regular"})},{value:"system",icon:(0,r.jsx)(i4.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:af(o,b===`mode:${t.value}`),onMouseEnter:()=>w(`mode:${t.value}`),onMouseLeave:()=>w(null),children:[t.icon,h(`desktop.${t.value}`)]},t.value)})})]}),!m&&0===x.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)(ay,{title:h("desktop.language"),description:h("desktop.languageDescription"),children:(0,r.jsx)("div",{style:ax,children:["en","zh-CN"].map(e=>(0,r.jsx)("button",{type:"button",onClick:()=>g("zh-CN"===e?"zh-CN":"en"),style:af("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 aS=o(94638);function aC({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 aT({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 aR({children:e}){return(0,r.jsx)("div",{style:{padding:"0 14px"},children:e})}function az({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 aI=[{value:"normal",labelKey:"modes.collabNormal"},{value:"plan",labelKey:"modes.collabPlan"},{value:"goal",labelKey:"modes.collabGoal"}],aM=[{value:"economy",labelKey:"modes.tokenEconomy"},{value:"full",labelKey:"modes.tokenFull"},{value:"delivery",labelKey:"modes.tokenDelivery"}],aE=[{value:"ask",labelKey:"modes.approvalAsk"},{value:"auto",labelKey:"modes.approvalAuto"},{value:"yolo",labelKey:"modes.approvalYolo"}];function aP({options:e,value:t,onChange:o,disabled:n,accentFor:s}){let{t:i}=(0,D.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 aD(){let{t:e}=(0,D.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:eM(e.collaborationMode),tokenMode:eE(e.tokenMode),toolApprovalMode:eP(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:eM(e.modes?.collaborationMode??t.collaborationMode),tokenMode:eE(e.modes?.tokenMode??t.tokenMode),toolApprovalMode:eP(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)(aC,{children:(0,r.jsx)(aR,{children:(0,r.jsx)(as,{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)(aS.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)(aC,{children:[(0,r.jsx)(aT,{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)(aP,{options:aI,value:s.collaborationMode,onChange:e=>void u({collaborationMode:e}),disabled:d})]})}),(0,r.jsx)(aT,{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)(aP,{options:aM,value:s.tokenMode,onChange:e=>void u({tokenMode:e}),disabled:d})]})}),(0,r.jsx)(aR,{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)(aP,{options:aE,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)(az,{children:e("desktop.featuresDesc")}),d&&(0,r.jsx)("div",{style:{padding:"0 2px",fontSize:11,color:"var(--text-muted)"},children:e("desktop.featuresSaving")})]})})}var aF=o(76553);function aW({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 a$({onSessionsChanged:e}){let{t}=(0,D.s)(),o=A(),[s,i]=(0,n.useState)(null),[a,l]=(0,n.useState)([]),[d,c]=(0,n.useState)([]),[u,g]=(0,n.useState)(new Set),[h,x]=(0,n.useState)(null),[f,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),[z,M]=(0,n.useState)(!1),E=(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&&(c(t.reasonix.projects),i("reasonix"))}catch(e){R(e instanceof Error?e.message:String(e))}finally{C(!1)}},[]),[P,F]=(0,n.useState)(!1);(0,n.useEffect)(()=>{P||(F(!0),E())},[P,E]);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}`);x(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 $=(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(f.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)(rz.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:f.imported})??`成功导入 ${f.imported} 个会话`,f.skipped>0&&(0,r.jsx)("span",{style:{marginLeft:8},children:t("desktop.importSkippedCount",{skipped:f.skipped})??`,${f.skipped} 个跳过`}),f.errors>0&&(0,r.jsx)("span",{style:{marginLeft:8,color:"#ef4444"},children:t("desktop.importErrorsCount",{errors:f.errors})??`,${f.errors} 个失败`})]}),y?(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,fontSize:12,color:"var(--text-muted)"},children:[(0,r.jsx)(_.y,{size:14,style:{animation:"spin 1s linear infinite"}}),t("desktop.importGeneratingTitles")??"正在生成标题…"," ","(",w.done,"/",w.total,")"]}):(0,r.jsxs)("button",{type:"button",onClick:$,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)(aF.o,{size:15}),t("desktop.importGenerateTitles")??"为导入的会话生成标题"]}),(0,r.jsx)("button",{type:"button",onClick:()=>{x(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 N=(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)(V.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:aN,children:t("desktop.importSelectAll")??"全选"}),(0,r.jsx)("button",{type:"button",onClick:()=>g(new Set),style:aN,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)(_.y,{size:14,style:{animation:"spin 1s linear infinite"}})," ",t("desktop.importing")??"导入中…"]}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(I.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&&!f.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)(_.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:`${f.total>0?(f.imported+f.skipped+f.errors)/f.total*100:0}%`,transition:"width 0.3s ease"}})}),(0,r.jsxs)("div",{style:{fontSize:11,color:"var(--text-dim)"},children:[f.imported+f.skipped+f.errors," / ",f.total,f.skipped>0&&` \xb7 ${t("desktop.importSkippedCount",{skipped:f.skipped})??`${f.skipped} 跳过`}`]})]})]});return o?(0,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)(I.z,{size:16}),(0,r.jsx)("span",{style:{fontWeight:500},children:t("desktop.importSessions")??"导入会话"})]}),(0,r.jsxs)(aW,{open:z,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:aA,children:(0,r.jsx)(p.X,{size:18})})]}),N]})]}):N}let aN={background:"none",border:"none",color:"var(--accent)",fontSize:11,cursor:"pointer",padding:"2px 4px"},aA={background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",padding:4,display:"flex"},aL="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 aH(){return{fontSize:12,color:"var(--text-muted)"}}let aB={padding:"7px 12px",border:"none",borderRadius:6,background:"var(--accent)",color:"#fff",cursor:"pointer",fontSize:12};function aU({sessionId:e}){let{t}=(0,D.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,x]=(0,n.useState)({}),[f,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,E]=(0,n.useState)({provider:"custom",baseUrl:"",apiKey:"",model:"",maxTokens:4096,hasApiKey:!1}),[P,F]=(0,n.useState)(""),[W,$]=(0,n.useState)(""),[N,A]=(0,n.useState)(!1),[L,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;x(r.mcpServers??{}),m(r.filePath);let i=(r.mcpServers??{})[aL];v(i?.command??""),b(i?.lifecycle==="lazy"?"lazy":"eager"),E({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[aL],t={...h,[aL]:{...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}`);x(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[aL];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}`);x(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()=>{A(!0),O(null),B(!1);try{let e=await fetch("/api/vision-config",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({...M,...P?{apiKey:P}:{}})}),t=await e.json();if(!e.ok||t.error)throw Error(t.error??`HTTP ${e.status}`);E({...t,apiKey:"",hasApiKey:t.hasApiKey}),F(""),B(!0)}catch(e){O(e instanceof Error?e.message:String(e))}finally{A(!1)}},[M,P]),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:aL})}),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[aL];return(0,r.jsxs)(aC,{children:[(0,r.jsx)(aT,{children:(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:7,padding:"12px 0"},children:[(0,r.jsx)(nW.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)(aR,{children:(0,r.jsx)("div",{style:{padding:"8px 0",fontSize:12,color:"#ef4444"},children:i})}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(aT,{children:(0,r.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)",padding:"10px 0 2px"},children:t("desktop.mcpVisionRegistration")})}),(0,r.jsx)(aT,{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:aH(),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:aH(),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:aH(),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)(aT,{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:{...aB,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)(aT,{children:(0,r.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)",padding:"10px 0 2px"},children:t("desktop.mcpVisionModelConfig")})}),(0,r.jsx)(aT,{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:aH(),children:t("desktop.mcpVisionProvider")}),(0,r.jsx)("input",{value:M.provider,onChange:e=>E(t=>({...t,provider:e.target.value})),style:aO}),(0,r.jsx)("span",{style:aH(),children:t("desktop.mcpVisionBaseUrl")}),(0,r.jsx)("input",{value:M.baseUrl,onChange:e=>E(t=>({...t,baseUrl:e.target.value})),style:aO}),(0,r.jsx)("span",{style:aH(),children:t("desktop.mcpVisionApiKey")}),(0,r.jsx)("input",{type:"password",value:P,onChange:e=>F(e.target.value),placeholder:M.hasApiKey?"••••••••":"API key",style:aO}),(0,r.jsx)("span",{style:aH(),children:t("desktop.mcpVisionModel")}),(0,r.jsx)("input",{value:M.model,onChange:e=>E(t=>({...t,model:e.target.value})),style:aO}),(0,r.jsx)("span",{style:aH(),children:t("desktop.mcpVisionMaxTokens")}),(0,r.jsx)("input",{type:"number",min:1,value:M.maxTokens,onChange:e=>E(t=>({...t,maxTokens:Number(e.target.value)||1})),style:aO})]})}),(0,r.jsx)(aR,{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:{...aB,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")}),L&&(0,r.jsx)("span",{style:{color:"#ef4444",fontSize:12},children:L}),c&&(0,r.jsx)("span",{style:{color:"#ef4444",fontSize:12},children:c})]}),(0,r.jsxs)(az,{children:[t("desktop.mcpVisionModelNote"),W&&(0,r.jsx)("div",{style:{marginTop:4,fontFamily:"var(--font-mono)",fontSize:10},children:W}),f&&(0,r.jsx)("div",{style:{fontFamily:"var(--font-mono)",fontSize:10},children:f})]})]})})]}):(0,r.jsx)(aR,{children:(0,r.jsx)("div",{style:{padding:"8px 0",fontSize:12,color:"var(--text-muted)"},children:t("desktop.loading")})})]})}function a_({sessionId:e,onApplied:t}){let{t:o}=(0,D.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 io(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 aq=["stdio","sse","http"],aV=["eager","lazy"],aK={name:"",command:"",args:"",transport:"stdio",lifecycle:"eager",requestTimeoutMs:"",env:""},aJ={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 aG(){return{fontSize:12,color:"var(--text-muted)"}}function aY(e,t){return{fontSize:10,padding:"1px 6px",borderRadius:3,background:t,color:e,flexShrink:0,textTransform:"capitalize"}}function aX({sessionId:e}){let{t}=(0,D.s)(),[o,s]=(0,n.useState)({}),[i,a]=(0,n.useState)(""),[l,d]=(0,n.useState)(!1),[c,p]=(0,n.useState)(null),[u,g]=(0,n.useState)(null),[x,f]=(0,n.useState)(aK),[k,v]=(0,n.useState)(!1),[y,b]=(0,n.useState)(null),[w,j]=(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)(()=>{f(aK),g({name:"",isNew:!0}),b(null),j(!1)},[]),R=(0,n.useCallback)((e,t)=>{f({name:e,command:t.command??"",args:Array.isArray(t.args)?t.args.join("\n"):"",transport:"string"==typeof t.transport?t.transport:"stdio",lifecycle:"string"==typeof t.lifecycle?t.lifecycle:"eager",requestTimeoutMs:"number"==typeof t.requestTimeoutMs?String(t.requestTimeoutMs):"",env:void 0!==t.env?JSON.stringify(t.env,null,2):""}),g({name:e,isNew:!1}),b(null),j(!1)},[]),z=(0,n.useCallback)(async()=>{if(u){v(!0),b(null),j(!1);try{let e=x.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===aL)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:aq.includes(e.transport)?e.transport:"stdio",lifecycle:aV.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}}(x);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[x.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),g(null),j(!0)}catch(e){b(e instanceof Error?e.message:String(e))}finally{v(!1)}}},[u,x,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),j(!0)}catch(e){b(e instanceof Error?e.message:String(e))}finally{v(!1)}},[o]),M=(0,n.useCallback)((e,t)=>{f(o=>({...o,[e]:t}))},[]),E=Object.entries(o).filter(([e])=>e!==aL);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)(a_,{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)(m.c,{size:13,"aria-hidden":"true"}),t("desktop.mcpAddServer")]})]})]}),(0,r.jsx)(az,{children:t("desktop.mcpRestartNote")}),(0,r.jsx)(aU,{sessionId:e}),0!==E.length||u?E.map(([e,o])=>(0,r.jsx)(aC,{children:(0,r.jsx)(aR,{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:aY("var(--accent)","rgba(37,99,235,0.12)"),children:o.transport??"stdio"}),(0,r.jsx)("span",{style:aY("#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)(h.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)(S.l,{size:12,"aria-hidden":"true"})})]})]})})},e)):(0,r.jsx)(aC,{children:(0,r.jsx)(aR,{children:(0,r.jsx)("div",{style:{padding:"14px 0",fontSize:12,color:"var(--text-dim)"},children:o[aL]?t("desktop.mcpEmptyOther"):t("desktop.mcpEmpty")})})}),u&&(0,r.jsxs)(aC,{children:[(0,r.jsx)(aT,{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)(aT,{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:aG(),children:t("desktop.mcpServerName")}),(0,r.jsx)("input",{value:x.name,onChange:e=>M("name",e.target.value),disabled:!u.isNew,placeholder:"my-server",style:{...aJ,opacity:u.isNew?1:.5}}),(0,r.jsxs)("span",{style:aG(),children:[t("desktop.mcpCommand")," *"]}),(0,r.jsx)("input",{value:x.command,onChange:e=>M("command",e.target.value),placeholder:"npx @modelcontextprotocol/server-foo",style:aJ}),(0,r.jsx)("span",{style:aG(),children:t("desktop.mcpArgs")}),(0,r.jsx)("textarea",{value:x.args,onChange:e=>M("args",e.target.value),placeholder:"--port 3000\n--verbose",rows:3,style:{...aJ,resize:"vertical",lineHeight:1.5}}),(0,r.jsx)("span",{style:aG(),children:t("desktop.mcpTransport")}),(0,r.jsx)("select",{value:x.transport,onChange:e=>M("transport",e.target.value),style:{...aJ,fontFamily:"var(--font-mono)"},children:aq.map(e=>(0,r.jsx)("option",{value:e,children:e},e))}),(0,r.jsx)("span",{style:aG(),children:t("desktop.mcpLifecycle")}),(0,r.jsx)("select",{value:x.lifecycle,onChange:e=>M("lifecycle",e.target.value),style:{...aJ,fontFamily:"var(--font-mono)"},children:aV.map(e=>(0,r.jsx)("option",{value:e,children:e},e))}),(0,r.jsx)("span",{style:aG(),children:t("desktop.mcpRequestTimeoutMs")}),(0,r.jsx)("input",{type:"number",min:1,value:x.requestTimeoutMs,onChange:e=>M("requestTimeoutMs",e.target.value),placeholder:"300000",style:aJ}),(0,r.jsx)("span",{style:aG(),children:t("desktop.mcpEnv")}),(0,r.jsx)("textarea",{value:x.env,onChange:e=>M("env",e.target.value),placeholder:'{\n "API_KEY": "..."\n}',rows:3,style:{...aJ,resize:"vertical",lineHeight:1.5}})]})}),(0,r.jsx)(aR,{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:()=>g(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 aZ=o(9210);function aQ(){let{t:e}=(0,D.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 x=null!==t&&!s.some(e=>e.label===t),f=(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=>f(e.target.value),style:{flex:1,minWidth:200,maxWidth:420,padding:"6px 9px",fontSize:12,color:"var(--text)",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:5},children:[(0,r.jsx)("option",{value:"",children:e("desktop.titleModelFollowSession")}),x&&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}),x&&null!==t&&(0,r.jsxs)("p",{style:{margin:0,fontSize:11,color:"#ef4444",lineHeight:1.5},children:[t,"(",e("desktop.titleModelInvalid"),")"]})]})}let a0=["name","reasoning","contextWindow","maxTokens","thinkingLevelMap","hidden"];function a1(e){if(""===e.trim())return;let t=Number(e);return Number.isFinite(t)&&t>0?t:void 0}function a2(e){let t=a1(e.contextWindow??""),o=a1(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 a4({providerId:e,onRegisterFlush:t,onConfigChange:o}){let{t:s}=(0,D.s)(),i=A(),[a,l]=(0,n.useState)([]),[d,c]=(0,n.useState)({}),[p,u]=(0,n.useState)({}),[g,h]=(0,n.useState)(new Set),[x,f]=(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 f(!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||f(!1)}})(),()=>{t=!0}},[e]);let E=(0,n.useCallback)((e,t)=>{I.current+=1,c(o=>({...o,[e]:{...o[e]??{},...t}})),h(t=>new Set(t).add(e))},[]),P=(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]=a2(t)),o&&(i[e.id]=a2(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 a0){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,P)??void 0},[t,e,P]),x)?(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=>E(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=>E(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=>E(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=>E(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=>E(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)(ll,{value:t.thinkingLevelMap,onChange:t=>E(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:()=>{P().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 a6=["openai-completions","openai-responses","anthropic-messages","google-generative-ai","mistral-conversations"],a5="__custom__";function a3(){let{t:e}=(0,D.s)();return(0,n.useCallback)((t,o)=>e(t,o),[e])}function a8({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 a7={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 a9({value:e,onChange:t,placeholder:o,mono:n,inputRef:s}){return(0,r.jsx)("input",{ref:s,value:e,onChange:e=>t(e.target.value),placeholder:o,style:{...a7,fontFamily:n?"var(--font-mono)":"inherit"}})}function le({value:e,onChange:t,placeholder:o,mono:s,onKeyDown:i,autoComplete:a="off",spellCheck:l=!1,style:d}){let c=a3(),[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:{...a7,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)(aZ.G,{size:15}):(0,r.jsx)(nW.b,{size:15})})]})}function lt({value:e,onChange:t,placeholder:o}){return(0,r.jsx)("input",{type:"number",value:e,onChange:e=>t(e.target.value),placeholder:o,style:a7})}function lo({value:e,onChange:t,options:o,required:n}){let s=a3();return(0,r.jsxs)("select",{value:e,onChange:e=>t(e.target.value),style:{...a7,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 lr({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 ln({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 ls({name:e,provider:t,onChange:o,onRename:s,onDelete:i,onAddModels:a,onAddModel:l}){let d=a3(),[c,p]=(0,n.useState)(e),[u,g]=(0,n.useState)({phase:"idle"}),[h,x]=(0,n.useState)(""),[f,m]=(0,n.useState)([]),k=(0,n.useRef)(0),v=(0,n.useRef)(null);(0,n.useEffect)(()=>p(e),[e]);let y=(e,r)=>o({...t,[e]:r});(0,n.useEffect)(()=>{t.api||o({...t,api:"openai-completions"})},[t.api]),(0,n.useEffect)(()=>{k.current+=1,g({phase:"idle"}),x(""),m([])},[e,t.baseUrl,t.api,t.apiKey]);let b=(0,n.useCallback)(async()=>{if(!t.baseUrl?.trim()||"loading"===u.phase)return;let o=++k.current;g({phase:"loading"}),m([]);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!==k.current)return;if(!r.ok||n.error||!n.models)return void g({phase:"error",message:n.error??`HTTP ${r.status}`});g({phase:"success",models:n.models,endpoint:n.endpoint??t.baseUrl})}catch(e){if(o!==k.current)return;g({phase:"error",message:e instanceof Error?e.message:String(e)})}},[u.phase,e,t]),w=new Set((t.models??[]).map(e=>e.id)),j="success"===u.phase?u.models:[],S=h.trim().toLocaleLowerCase(),C=j.filter(e=>!S||e.id.toLocaleLowerCase().includes(S)||e.name?.toLocaleLowerCase().includes(S)),T=C.slice(0,300),R=T.filter(e=>!w.has(e.id)).map(e=>e.id),z=f.filter(e=>!w.has(e)).length,I=R.length>0&&R.every(e=>f.includes(e)),M=!I&&R.some(e=>f.includes(e));return(0,n.useEffect)(()=>{v.current&&(v.current.indeterminate=M)},[M]),(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)(ln,{children:d("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:d("desktop.delete")})]}),(0,r.jsxs)(a8,{label:d("desktop.modelsProviderName"),children:[(0,r.jsx)(a9,{value:c,onChange:p,placeholder:"provider-name",mono:!0}),c!==e&&c.trim()&&(0,r.jsx)("button",{onClick:()=>s(c.trim()),style:{marginTop:4,padding:"3px 10px",background:"var(--accent)",border:"none",borderRadius:4,color:"#fff",cursor:"pointer",fontSize:11,alignSelf:"flex-start"},children:d("desktop.rename")})]}),(0,r.jsx)(a8,{label:d("desktop.modelsBaseUrl"),children:(0,r.jsx)(a9,{value:t.baseUrl??"",onChange:e=>y("baseUrl",e||void 0),placeholder:"http(s)://host:port/v1",mono:!0})}),(0,r.jsxs)(a8,{label:d("desktop.modelsApiKey"),children:[(0,r.jsx)(le,{value:t.apiKey??"",onChange:e=>y("apiKey",e||void 0),placeholder:d("desktop.modelsApiKeyPlaceholder"),mono:!0}),(0,r.jsx)("span",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:d("desktop.modelsApiKeyHelp")})]}),(0,r.jsx)(a8,{label:d("desktop.modelsApi"),children:(0,r.jsx)(lo,{value:t.api??"openai-completions",onChange:e=>y("api",e),options:a6,required:!0})}),(0,r.jsxs)("div",{style:{borderTop:"1px solid var(--border)",paddingTop:14,display:"flex",flexDirection:"column",gap:10},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:["success"!==u.phase&&(0,r.jsx)("button",{onClick:b,disabled:!t.baseUrl?.trim()||"loading"===u.phase,style:{height:30,padding:"0 12px",border:"1px solid var(--border)",borderRadius:5,background:"var(--bg-panel)",color:t.baseUrl?.trim()&&"loading"!==u.phase?"var(--text-muted)":"var(--text-dim)",cursor:t.baseUrl?.trim()&&"loading"!==u.phase?"pointer":"not-allowed",fontSize:11},children:"loading"===u.phase?d("desktop.modelsDiscoveryFetching"):d("desktop.modelsDiscoveryFetch")}),(0,r.jsx)("button",{onClick:l,title:d("desktop.modelsAddModelManual"),style:{height:30,padding:"0 12px",border:"none",borderRadius:5,background:"var(--accent)",color:"#fff",cursor:"pointer",fontSize:11,fontWeight:600},children:d("desktop.modelsAddModelManual")})]}),"error"===u.phase&&(0,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:u.message}),"success"===u.phase&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("input",{value:h,onChange:e=>x(e.target.value),placeholder:d("desktop.modelsDiscoveryFilterPlaceholder",{count:u.models.length}),"aria-label":d("desktop.modelsDiscoveryFilter"),style:{...a7,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:R.length?"pointer":"default",color:"var(--text-muted)",fontSize:10,fontWeight:600},children:[(0,r.jsx)("input",{ref:v,type:"checkbox",checked:I,disabled:0===R.length,onChange:()=>{let e=new Set(R);m(t=>I?t.filter(t=>!e.has(t)):Array.from(new Set([...t,...R])))},style:{width:13,height:13,accentColor:"var(--accent)",flexShrink:0}}),d("desktop.modelsDiscoverySelectShown")]}),0===T.length?(0,r.jsx)("div",{style:{padding:12,color:"var(--text-dim)",fontSize:11},children:d("desktop.modelsDiscoveryNoMatches")}):T.map((e,t)=>{let o=w.has(e.id),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 m(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:d("desktop.modelsDiscoveryAdded")})]},e.id)})]}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:10},children:[(0,r.jsx)("span",{title:u.endpoint,style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontSize:10},children:C.length>T.length?d("desktop.modelsDiscoveryShowing",{shown:T.length,total:C.length}):d("desktop.modelsDiscoveryFetched",{count:u.models.length})}),(0,r.jsx)("button",{onClick:()=>{if("success"!==u.phase)return;let e=new Set(f),t=u.models.filter(t=>e.has(t.id)&&!w.has(t.id));0!==t.length&&(a(t),m([]))},disabled:0===z,style:{height:28,padding:"0 11px",border:"none",borderRadius:5,background:z?"var(--accent)":"var(--bg-panel)",color:z?"#fff":"var(--text-dim)",cursor:z?"pointer":"not-allowed",fontSize:11,fontWeight:600,whiteSpace:"nowrap"},children:z?d("desktop.modelsDiscoveryAddSelectedCount",{count:z}):d("desktop.modelsDiscoveryAddSelected")})]})]})]})]})}let li=["off","minimal","low","medium","high","xhigh","max"],la={off:"var(--text-dim)",minimal:"var(--text-muted)",low:"#60a5fa",medium:"#a78bfa",high:"#f472b6",xhigh:"#fb923c",max:"#ef4444"};function ll({value:e,onChange:t}){let o=a3(),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:li.map(e=>{let t=n[e],i=e in n?null===t?"null":"string":"omit",a="string"==typeof t?t:"",l=la[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 ld={thinkingFormat:"deepseek",requiresReasoningContentOnAssistantMessages:!0};function lc({providerName:e,provider:t,model:o,onChange:s,onDelete:i}){let a=a3(),[l,d]=(0,n.useState)({phase:"idle"}),[c,p]=(0,n.useState)({phase:"idle"}),u=(0,n.useRef)(0),h=(0,n.useRef)(null),x=(e,t)=>s({...o,[e]:t}),f=(()=>{if("idle"===l.phase)return null;if("testing"===l.phase)return a("desktop.modelsTestingConnection");let e=[void 0!==l.latencyMs?`${l.latencyMs}ms`:null,void 0!==l.status?`HTTP ${l.status}`:null].filter(Boolean);return"success"===l.phase?[a("desktop.modelsConnected"),...e,l.responseText||null].filter(Boolean).join(" \xb7 "):[a("desktop.modelsFailed"),...e,l.message].filter(Boolean).join(" \xb7 ")})();(0,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)(()=>{u.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=++u.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!==u.current)return;if(!a.ok||l.error||!l.recommendation)return void p({phase:"error",message:l.error??`HTTP ${a.status}`});let d=function(e,t){let o={...e},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!==u.current)return;p({phase:"error",message:e instanceof Error?e.message:String(e)})}},[c.phase,o,s,t.baseUrl,e]),v=(()=>{if("success"!==c.phase)return null;let{recommendation:t,appliedCount:o}=c,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)(ln,{children:a("desktop.modelsModelSection")}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[f&&(0,r.jsx)("span",{title:f,style:{maxWidth:260,height:24,padding:"0 8px",border:`1px solid ${"error"===l.phase?"#fecaca":"success"===l.phase?"#bbf7d0":"var(--border)"}`,borderRadius:4,background:"error"===l.phase?"#fee2e2":"success"===l.phase?"#dcfce7":"#e5e7eb",color:"#111827",fontSize:11,display:"inline-flex",alignItems:"center",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",boxSizing:"border-box"},children:f}),(0,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)(g.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)(a8,{label:a("desktop.modelsIdRequired"),children:(0,r.jsx)(a9,{value:o.id,onChange:e=>x("id",e),placeholder:"model-id",mono:!0})}),(0,r.jsx)(a8,{label:a("desktop.modelsName"),children:(0,r.jsx)(a9,{value:o.name??"",onChange:e=>x("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)(a8,{label:a("desktop.modelsApiOverride"),children:(0,r.jsx)(lo,{value:o.api??"",onChange:e=>x("api",e||void 0),options:a6})}),(0,r.jsxs)("div",{style:{display:"flex",gap:20,flexWrap:"wrap"},children:[(0,r.jsx)(lr,{label:a("desktop.modelsReasoningThinking"),checked:o.reasoning??!1,onChange:e=>x("reasoning",e||void 0)}),(0,r.jsx)(lr,{label:a("desktop.modelsImageInput"),checked:o.input?.includes("image")??!1,onChange:e=>x("input",e?["text","image"]:void 0)})]}),o.reasoning&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(lr,{label:a("desktop.modelsDeepSeekCompat"),checked:o.compat?.thinkingFormat==="deepseek",onChange:e=>s(function(e,t){if(t)return{...e,compat:{...e.compat??{},...ld}};if(!e.compat)return e;let o={...e.compat};return delete o.thinkingFormat,delete o.requiresReasoningContentOnAssistantMessages,{...e,compat:Object.keys(o).length?o:void 0}}(o,e))}),(0,r.jsxs)("div",{children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:8},children:[(0,r.jsx)(ln,{children:a("desktop.modelsThinkingLevelMap")}),o.thinkingLevelMap&&(0,r.jsx)("button",{onClick:()=>x("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)(ll,{value:o.thinkingLevelMap,onChange:e=>x("thinkingLevelMap",e)})]})]}),(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10},children:[(0,r.jsx)(a8,{label:a("desktop.modelsContextWindow"),children:(0,r.jsx)(lt,{value:void 0!==o.contextWindow?String(o.contextWindow):"",onChange:e=>x("contextWindow",e?parseInt(e):void 0),placeholder:"128000"})}),(0,r.jsx)(a8,{label:a("desktop.modelsMaxOutputTokens"),children:(0,r.jsx)(lt,{value:void 0!==o.maxTokens?String(o.maxTokens):"",onChange:e=>x("maxTokens",e?parseInt(e):void 0),placeholder:"16384"})})]}),(0,r.jsxs)("div",{children:[(0,r.jsx)(ln,{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)(a8,{label:e,children:(0,r.jsx)(lt,{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 lp({provider:e,onRefresh:t,onRegisterBuiltinFlush:o,onBuiltinProviderChange:s}){let i=a3(),[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]),x=(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]),f=(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)(ln,{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:()=>f(a.token,e.id),style:{padding:"6px 9px",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:5,color:"var(--text)",cursor:"pointer",fontSize:12,textAlign:"left"},children:e.label},e.id))})]}),("auth"===a.phase||"prompt"===a.phase)&&(0,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&&x(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:()=>x(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)(a4,{providerId:e.id,onRegisterFlush:o,onConfigChange:s})]})}function lu({provider:e,onRefresh:t,onRegisterBuiltinFlush:o,onBuiltinProviderChange:s}){let i=a3(),[a,l]=(0,n.useState)(""),[d,c]=(0,n.useState)(!1),[p,u]=(0,n.useState)(!1),[h,x]=(0,n.useState)(null),[f,m]=(0,n.useState)(!1);(0,n.useEffect)(()=>{l(""),x(null),m(!1)},[e.id]);let k=(0,n.useCallback)(async()=>{if(a.trim()){c(!0),x(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?x(r.error??`HTTP ${o.status}`):(l(""),m(!0),setTimeout(()=>m(!1),2e3),t())}catch(e){x(String(e))}finally{c(!1)}}},[a,e.id,t]),v=(0,n.useCallback)(async()=>{u(!0),x(null);try{let t=await fetch(`/api/auth/api-key/${encodeURIComponent(e.id)}`,{method:"DELETE"}),o=await t.json();(!t.ok||o.error)&&x(409===t.status?i("desktop.modelsAuthenticationStateChanged"):o.error??`HTTP ${t.status}`)}catch(e){x(String(e))}finally{t(),u(!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)(ln,{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)(a8,{label:i("desktop.modelsApiKey"),children:(0,r.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,r.jsx)(le,{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()||f,style:{padding:"6px 12px",background:f?"#16a34a":a.trim()?"var(--accent)":"var(--bg-panel)",border:"none",borderRadius:5,color:a.trim()||f?"#fff":"var(--text-dim)",cursor:d||!a.trim()||f?"not-allowed":"pointer",fontSize:12,fontWeight:600,flexShrink:0,display:"flex",alignItems:"center",gap:5},children:[f&&(0,r.jsx)(g.S,{size:12}),f?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)(a4,{providerId:e.id,onRegisterFlush:o,onConfigChange:s})]})}function lg({oauthProviders:e,apiKeyProviders:t,onSelectOAuth:o,onSelectApiKey:s,onAddCustom:i,onClose:a}){let l=a3(),[d,p]=(0,n.useState)(""),u=(0,n.useRef)(null);(0,n.useEffect)(()=>{setTimeout(()=>u.current?.focus(),30)},[]);let g=d.trim().toLowerCase(),h=e.filter(e=>!e.loggedIn&&(!g||e.name.toLowerCase().includes(g))),x=t.filter(e=>!e.configured&&(!g||e.displayName.toLowerCase().includes(g)||e.id.toLowerCase().includes(g))),f=!g||"custom".includes(g)||"openai-compatible".includes(g)||"anthropic-compatible".includes(g),k=h.length+x.length+ +!!f,v={display:"flex",flexDirection:"row",alignItems:"center",gap:8,padding:"10px 12px",background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:7,boxSizing:"border-box",cursor:"pointer",minWidth:0,textAlign:"left",transition:"border-color 0.12s, background 0.12s",width:"100%"};return(0,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)(c.$,{size:13,style:{color:"var(--text-dim)",flexShrink:0}}),(0,r.jsx)("input",{ref:u,value:d,onChange:e=>p(e.target.value),onKeyDown:e=>{"Escape"===e.key&&a()},placeholder:l("desktop.modelsSearchProviders"),style:{flex:1,background:"none",border:"none",outline:"none",color:"var(--text)",fontSize:13,boxSizing:"border-box"}})]}),(0,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:[f&&(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")}),f&&(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)(m.c,{size:13,style:{color:"var(--text-dim)"}})})]}),h.length>0&&(0,r.jsx)("div",{style:{gridColumn:"1 / -1",paddingTop:6*!!f,fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:l("desktop.modelsSubscriptions")}),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)(su,{id:e.id,size:28})]},e.id)),x.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")}),x.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)(su,{id:e.id,size:28})]},e.id))]})})]})})}function lh({existingProviders:e,onCancel:t,onSubmit:o}){let s=a3(),[i,a]=(0,n.useState)(""),[l,d]=(0,n.useState)(a6[0]),[c,p]=(0,n.useState)(a6[0]),[u,g]=(0,n.useState)(""),[h,x]=(0,n.useState)(""),[f,k]=(0,n.useState)(void 0),[v,y]=(0,n.useState)(!1),[b,w]=(0,n.useState)(""),[j,S]=(0,n.useState)(""),[C,T]=(0,n.useState)(""),[R,z]=(0,n.useState)(""),I=(0,n.useRef)(null);(0,n.useEffect)(()=>{setTimeout(()=>I.current?.focus(),30)},[]);let M=!u.trim()||/^https?:\/\//i.test(u.trim());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&&t()},children:(0,r.jsxs)("div",{style:{width:480,maxWidth:"calc(100vw - 32px)",maxHeight:"min(82vh, calc(100vh - 32px))",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:10,display:"flex",flexDirection:"column",boxShadow:"0 8px 32px rgba(0,0,0,0.22)",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 16px",borderBottom:"1px solid var(--border)",flexShrink:0},children:[(0,r.jsx)("span",{style:{fontSize:14,fontWeight:700,color:"var(--text)"},children:s("desktop.modelsAddCustomTitle")}),(0,r.jsx)("button",{onClick:t,"aria-label":s("desktop.modelsClose"),title:s("desktop.modelsClose"),style:{background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",fontSize:20,lineHeight:1,padding:"2px 6px"},children:"\xd7"})]}),(0,r.jsxs)("div",{style:{padding:16,overflowY:"auto",display:"flex",flexDirection:"column",gap:14},children:[(0,r.jsx)(a8,{label:s("desktop.modelsProviderNameOptional"),children:(0,r.jsx)(a9,{value:i,onChange:a,placeholder:"new-provider",mono:!0,inputRef:I})}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,r.jsx)(ln,{children:s("desktop.modelsCallFormat")}),(0,r.jsxs)("select",{value:c,onChange:e=>{let t=e.target.value;(p(t),t===a5)?y(!0):d(t)},style:a7,children:[a6.map(e=>(0,r.jsx)("option",{value:e,children:e},e)),(0,r.jsx)("option",{value:a5,children:s("desktop.modelsCustomCallFormat")})]}),(0,r.jsx)("span",{style:{fontSize:10,color:"var(--text-dim)"},children:s("desktop.modelsCallFormatHelp")}),c===a5&&(0,r.jsx)("span",{style:{fontSize:10,color:"#d97706",lineHeight:1.4},children:s("desktop.modelsCustomCallFormatHelp")})]}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,r.jsx)(ln,{children:s("desktop.modelsImportProvider")}),(0,r.jsxs)("select",{value:R,onChange:t=>{var o;let r;return z(o=t.target.value),void((r=e.find(e=>e.name===o))&&(r.provider.api&&(d(r.provider.api),p(r.provider.api)),g(r.provider.baseUrl??""),x(r.provider.apiKey??""),k(r.provider.headers?{...r.provider.headers}:void 0)))},style:{...a7,color:R?"var(--text)":"var(--text-dim)"},children:[(0,r.jsx)("option",{value:"",children:s("desktop.modelsImportProviderPlaceholder")}),e.map(e=>(0,r.jsxs)("option",{value:e.name,children:[e.name,e.provider.api?` \xb7 ${e.provider.api}`:""]},e.name))]}),R&&(0,r.jsxs)("span",{style:{fontSize:10,color:"#4ade80"},children:[s("desktop.modelsImported"),": ",R]})]}),(0,r.jsxs)("div",{style:{borderTop:"1px solid var(--border)",paddingTop:12,display:"flex",flexDirection:"column",gap:4},children:[(0,r.jsx)(ln,{children:s("desktop.modelsFullUrl")}),v?(0,r.jsxs)("div",{style:{display:"flex",gap:6,alignItems:"center"},children:[(0,r.jsx)(a9,{value:u,onChange:g,placeholder:s("desktop.modelsUrlPlaceholder"),mono:!0}),(0,r.jsx)("button",{onClick:()=>{y(!1),g("")},title:s("desktop.modelsRemove"),style:{flexShrink:0,width:28,height:28,background:"none",border:"1px solid var(--border)",borderRadius:5,color:"var(--text-dim)",cursor:"pointer",fontSize:14,lineHeight:1,display:"flex",alignItems:"center",justifyContent:"center"},children:"\xd7"})]}):(0,r.jsxs)("button",{onClick:()=>y(!0),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:"7px 0",background:"none",border:"1px dashed var(--border)",borderRadius:5,color:"var(--text-muted)",cursor:"pointer",fontSize:12},onMouseEnter:e=>{e.currentTarget.style.borderColor="var(--accent)",e.currentTarget.style.color="var(--accent)"},onMouseLeave:e=>{e.currentTarget.style.borderColor="var(--border)",e.currentTarget.style.color="var(--text-muted)"},children:[(0,r.jsx)(m.c,{size:12}),s("desktop.modelsAddUrl")]}),u.trim()&&!M&&(0,r.jsx)("span",{style:{fontSize:10,color:"#ef4444"},children:s("desktop.modelsUrlInvalid")}),(0,r.jsxs)(a8,{label:s("desktop.modelsApiKey"),children:[(0,r.jsx)(le,{value:h,onChange:x,placeholder:s("desktop.modelsApiKeyPlaceholder"),mono:!0}),(0,r.jsx)("span",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:s("desktop.modelsApiKeyHelp")})]})]}),(0,r.jsxs)("div",{style:{borderTop:"1px solid var(--border)",paddingTop:12,display:"flex",flexDirection:"column",gap:10},children:[(0,r.jsx)(ln,{children:s("desktop.modelsCustomRequest")}),(0,r.jsxs)(a8,{label:s("desktop.modelsRequestModelId"),children:[(0,r.jsx)(a9,{value:b,onChange:w,placeholder:"model-id",mono:!0}),(0,r.jsx)("span",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:s("desktop.modelsRequestModelIdHelp")})]}),(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10},children:[(0,r.jsx)(a8,{label:s("desktop.modelsRequestContextLength"),children:(0,r.jsx)(lt,{value:j,onChange:S,placeholder:"128000"})}),(0,r.jsx)(a8,{label:s("desktop.modelsRequestOutputLength"),children:(0,r.jsx)(lt,{value:C,onChange:T,placeholder:"16384"})})]})]})]}),(0,r.jsxs)("div",{style:{display:"flex",justifyContent:"flex-end",gap:8,padding:"10px 16px",borderTop:"1px solid var(--border)",flexShrink:0},children:[(0,r.jsx)("button",{onClick:t,style:{padding:"6px 14px",background:"none",border:"1px solid var(--border)",borderRadius:6,color:"var(--text-muted)",cursor:"pointer",fontSize:13},children:s("desktop.cancel")}),(0,r.jsx)("button",{onClick:()=>{let e=b.trim()?{id:b.trim(),...parseInt(j,10)>0?{contextWindow:parseInt(j,10)}:{},...parseInt(C,10)>0?{maxTokens:parseInt(C,10)}:{}}:void 0;o({name:i.trim(),api:l,...u.trim()?{baseUrl:u.trim()}:{},...h.trim()?{apiKey:h.trim()}:{},...f?{headers:f}:{},model:e})},disabled:!M,style:{padding:"6px 16px",background:M?"var(--accent)":"var(--bg-panel)",border:"none",borderRadius:6,color:M?"#fff":"var(--text-dim)",cursor:M?"pointer":"not-allowed",fontSize:13,fontWeight:600},children:s("desktop.modelsAdd")})]})]})})}function lx({embedded:e=!1,sessionId:t,onCloseAction:o,onSavedAction:s,onRegisterFlush:i}){let a=a3(),l=A(),[d,c]=(0,n.useState)({providers:{}}),[p,u]=(0,n.useState)(!0),[h,x]=(0,n.useState)(!1),[f,m]=(0,n.useState)(null),[k,v]=(0,n.useState)(!1),[y,b]=(0,n.useState)(null),[w,j]=(0,n.useState)([]),[S,C]=(0,n.useState)([]),[R,z]=(0,n.useState)(!1),[I,M]=(0,n.useState)(!1),[E,P]=(0,n.useState)({oauth:!1,apiKey:!1}),D=(0,n.useRef)({providers:{}}),F=(0,n.useRef)(new Map),W=(0,n.useRef)(0),$=(0,n.useRef)(!1);D.current=d;let N=(0,n.useCallback)(e=>{let t=e(D.current);return D.current=t,W.current+=1,c(t),t},[]),L=(0,n.useCallback)(()=>{fetch("/api/auth/combined").then(e=>e.json()).then(e=>{j(e.oauth??[]),C(e.apiKey??[])}).catch(()=>{}).finally(()=>P({oauth:!0,apiKey:!0}))},[]),O=(0,n.useCallback)((e,t)=>(F.current.set(e,t),()=>{F.current.get(e)===t&&F.current.delete(e)}),[]),H=(0,n.useCallback)(async()=>{for(let e of[...F.current.values()])await e()},[]);(0,n.useEffect)(()=>{if(i)return i(H)??void 0},[H,i]);let B=(0,n.useCallback)((e,t)=>{N(o=>{let r={...o.providers??{}};return t?r[e]=t:delete r[e],{...o,providers:r}}),s?.()},[s,N]),U=(0,n.useCallback)(async e=>{if(!$.current){$.current=!0,m(null);try{await H(),b(e)}catch(e){m(e instanceof Error?e.message:String(e))}finally{$.current=!1}}},[H]);(0,n.useEffect)(()=>{fetch("/api/models-config").then(e=>e.json()).then(e=>{let t=e.providers?e:{...e,providers:{}};D.current=t,W.current+=1,c(t)}).catch(()=>{let e={providers:{}};D.current=e,W.current+=1,c(e)}).finally(()=>u(!1)),L()},[L]);let _=(0,n.useCallback)(async e=>{if(!$.current){$.current=!0,m(null);try{await H();let t=e.name.trim()||"new-provider",o=t,r=1;for(;D.current.providers?.[o];)o=`${t}-${r++}`;let n={api:e.api||"openai-completions",...e.baseUrl?{baseUrl:e.baseUrl}:{},...e.apiKey?{apiKey:e.apiKey}:{},...e.headers?{headers:e.headers}:{},...e.model?{models:[e.model]}:{}};N(e=>({...e,providers:{...e.providers??{},[o]:n}})),b({type:"provider",name:o}),M(!1)}catch(e){m(e instanceof Error?e.message:String(e))}finally{$.current=!1}}},[H,N]),q=(0,n.useCallback)((e,t)=>{N(o=>({...o,providers:{...o.providers??{},[e]:t}}))},[N]),V=(0,n.useCallback)((e,t)=>{N(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)},[N]),K=(0,n.useCallback)(e=>{let t=Object.keys(N(t=>{let o={...t.providers??{}};return delete o[e],{...t,providers:o}}).providers??{});b(t.length>0?{type:"provider",name:t[0]}:null)},[N]),J=(0,n.useCallback)(async e=>{if(!$.current){$.current=!0,m(null);try{await H();let t=N(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{$.current=!1}}},[H,N]),G=(0,n.useCallback)((e,t)=>{N(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}}}})},[N]),Y=(0,n.useCallback)((e,t,o)=>{N(r=>{let n=r.providers?.[e]??{},s=[...n.models??[]];return s[t]=o,{...r,providers:{...r.providers??{},[e]:{...n,models:s}}}})},[N]),X=(0,n.useCallback)(async(e,t)=>{if(!$.current){$.current=!0,m(null);try{await H(),N(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{$.current=!1}}},[H,N]),Z=(0,n.useCallback)(async()=>{if(!h){x(!0),m(null),v(!1);try{await H();let e=D.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&&(D.current=o.config,W.current+=1,c(o.config)),v(!0),s?.(),setTimeout(()=>v(!1),2e3)}catch(e){m(e instanceof Error?e.message:String(e))}finally{x(!1)}}},[H,s,h]),Q=(0,n.useCallback)(async()=>{try{await H(),o?.()}catch(e){m(e instanceof Error?e.message:String(e))}},[H,o]),ee=Object.entries(d.providers??{}),et=new Set([...w.map(e=>e.id),...S.map(e=>e.id)]),eo=ee.filter(([e])=>!et.has(e)),er=w.filter(e=>e.loggedIn),en=S.filter(e=>e.configured);(0,n.useEffect)(()=>{if(y||p||!E.oauth||!E.apiKey)return;let e=er[0]?{type:"oauth",providerId:er[0].id}:en[0]?{type:"apikey",providerId:en[0].id}:eo[0]?.[0]?{type:"provider",name:eo[0][0]}:null;e&&b(e)},[en,er,eo,p,E.apiKey,E.oauth,y]);let es=(()=>{if(!y)return null;if("oauth"===y.type){let e=w.find(e=>e.id===y.providerId);return e?(0,r.jsx)(lp,{provider:e,onRefresh:L,onRegisterBuiltinFlush:O,onBuiltinProviderChange:t=>B(e.id,t)},e.id):null}if("apikey"===y.type){let e=S.find(e=>e.id===y.providerId);return e?(0,r.jsx)(lu,{provider:e,onRefresh:L,onRegisterBuiltinFlush:O,onBuiltinProviderChange:t=>B(e.id,t)},e.id):null}if("provider"===y.type){let e=d.providers?.[y.name];return e?(0,r.jsx)(ls,{name:y.name,provider:e,onChange:e=>q(y.name,e),onRename:e=>V(y.name,e),onDelete:()=>K(y.name),onAddModels:e=>G(y.name,e),onAddModel:()=>{J(y.name)}},y.name):null}let e=d.providers?.[y.providerName],t=e?.models?.[y.index];return t?(0,r.jsx)(lc,{providerName:y.providerName,provider:e,model:t,onChange:e=>Y(y.providerName,y.index,e),onDelete:()=>{X(y.providerName,y.index)}},`${y.providerName}-${y.index}`):null})();return(0,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||Q()},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:()=>{Q()},"aria-label":a("desktop.modelsClose"),title:a("desktop.modelsClose"),style:{background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",fontSize:20,lineHeight:1,padding:"2px 6px"},children:"\xd7"})]}),(0,r.jsx)(aQ,{}),(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:[er.map(e=>{let t=y?.type==="oauth"&&y.providerId===e.id;return(0,r.jsxs)("div",{onClick:()=>{U({type:"oauth",providerId:e.id})},style:{display:"flex",alignItems:"center",gap:7,padding:"5px 8px",borderRadius:5,cursor:"pointer",background:t?"var(--bg-selected)":"none"},onMouseEnter:e=>{t||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{t||(e.currentTarget.style.background="none")},children:[(0,r.jsx)(su,{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)}),en.map(e=>{let t=y?.type==="apikey"&&y.providerId===e.id;return(0,r.jsxs)("div",{onClick:()=>{U({type:"apikey",providerId:e.id})},style:{display:"flex",alignItems:"center",gap:7,padding:"5px 8px",borderRadius:5,cursor:"pointer",background:t?"var(--bg-selected)":"none"},onMouseEnter:e=>{t||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{t||(e.currentTarget.style.background="none")},children:[(0,r.jsx)(su,{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)}),(er.length>0||en.length>0)&&eo.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")}):eo.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:()=>{U({type:"provider",name:e})},style:{display:"flex",alignItems:"center",gap:6,padding:"7px 8px",borderRadius:5,cursor:"pointer",background:o?"var(--bg-selected)":"none"},onMouseEnter:e=>{o||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{o||(e.currentTarget.style.background="none")},children:[(0,r.jsx)(T.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:()=>{U({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(),J(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:es??(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:[f&&(0,r.jsx)("span",{style:{fontSize:12,color:"#f87171",flex:1},children:f}),!e&&(0,r.jsx)("button",{onClick:()=>{Q()},style:{padding:"6px 14px",background:"none",border:"1px solid var(--border)",borderRadius:6,color:"var(--text-muted)",cursor:"pointer",fontSize:13},children:a("desktop.cancel")}),(0,r.jsx)(a_,{sessionId:t}),(0,r.jsxs)("button",{onClick:Z,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)(g.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)(lg,{oauthProviders:w,apiKeyProviders:S,onSelectOAuth:e=>{U({type:"oauth",providerId:e})},onSelectApiKey:e=>{U({type:"apikey",providerId:e})},onAddCustom:()=>{z(!1),M(!0)},onClose:()=>z(!1)}),I&&(0,r.jsx)(lh,{existingProviders:eo.map(([e,t])=>({name:e,provider:t})),onCancel:()=>M(!1),onSubmit:e=>{_(e)}})]})}function lf(e){return e.replace(/^\/(?:Users|home)\/[^/]+/,"~")}function lm(e){let t=e.trim().match(/^\$?\s*pi\s+install\s+(\S+)\s*$/);return t?.[1]??e}function lk(e){return`${e.scope}\0${e.source}`}function lv(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 ly(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 lb(e){return"loaded"===e?"var(--accent)":"installed"===e?"#f59e0b":"disabled"===e?"var(--text-dim)":"#ef4444"}function lw({pkg:e}){let{t}=(0,D.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 lj({scope:e}){let{t}=(0,D.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 lS(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 lC({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 lT({value:e,onChange:t}){let{t:o}=(0,D.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 lR({cwd:e,source:t,scope:o,busy:s,actionError:i,onSourceChange:a,onScopeChange:l,onInstall:d}){let{t:c}=(0,D.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?`${lf(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=lm(t);o!==t&&(e.preventDefault(),a(o))},onBlur:e=>a(lm(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)(lT,{value:o,onChange:l}),(0,r.jsx)("button",{type:"button",onClick:d,disabled:s||!t.trim(),style:{...lS(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 lz({pkg:e,cwd:t,busyKey:o,actionError:n,actionMessage:s,sessionId:i,onAction:a,onReloadSession:l}){let{t:d}=(0,D.s)(),c=lk(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)(lC,{enabled:g,loading:p||u,onToggle:()=>a(e.disabled?"enable":"disable",e),label:d(e.disabled?"desktop.enablePackage":"desktop.disablePackage")}),(0,r.jsx)(lj,{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:lS(p||u),children:d(o===`update:${c}`?"desktop.updating":"desktop.update")}),(0,r.jsx)("button",{onClick:l,disabled:!i||u||p,style:lS(!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:lS(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:lb(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:ly(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:lv(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?lf(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:lf(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)(lw,{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 lI({cwd:e,sessionId:t,embedded:o=!1,onCloseAction:s,onReloadedAction:i}){let a=A(),{t:l}=(0,D.s)(),[d,c]=(0,n.useState)(null),[p,u]=(0,n.useState)(!0),[g,h]=(0,n.useState)(null),[x,f]=(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]),E=M.find(e=>lk(e)===x)??null,P=(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),f(e=>e&&o.packages.some(t=>lk(t)===e)?e:o.packages[0]?lk(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=lk(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)f(n.packages[0]?lk(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]),$=(0,n.useCallback)(async()=>{let t=lm(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)));f(d?lk(d):o),v(!1),b(""),I(l("desktop.packageInstalled"))}catch(e){R(e instanceof Error?e.message:String(e))}finally{C(null)}},[e,w,y,l]),N=(0,n.useCallback)(async()=>{if(t){C("reload"),R(null),I(null);try{await io(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]),L=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:lf(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")}):P.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=lk(e),o=!k&&x===t;return(0,r.jsxs)("div",{onClick:()=>{f(t),v(!1),R(null),I(null)},style:{display:"flex",alignItems:"center",gap:7,padding:"8px 8px",borderRadius:5,cursor:"pointer",background:o?"var(--bg-selected)":"none"},onMouseEnter:e=>{o||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{o||(e.currentTarget.style.background="none")},children:[(0,r.jsx)("span",{style:{flexShrink:0,width:7,height:7,borderRadius:"50%",background:lb(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:lv(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:ly(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)(m.c,{size:13}),l("desktop.addPlugin")]})})]}),(0,r.jsx)("div",{style:{flex:1,overflowY:"auto",padding:20},children:k?(0,r.jsx)(lR,{cwd:e,source:y,scope:w,busy:L,actionError:T,onSourceChange:b,onScopeChange:j,onInstall:$}):p?null:E?(0,r.jsx)(lz,{pkg:E,cwd:e,busyKey:S,actionError:T,actionMessage:z,sessionId:t,onAction:W,onReloadSession:N},lk(E)):(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:lS(p||null!==S),children:l("desktop.refresh")}),!o&&(0,r.jsx)("button",{onClick:s,style:lS(!1),children:l("desktop.close")})]})]})})}var lM=o(36282);function lE(){let{t:e}=(0,D.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),[x,f]=(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),f(!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),f(!1),k(!1);let e=await fetch("/api/proxy");if(e.ok){let t=await e.json();o(e=>({...e,...t,password:""}))}}else u(!1),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),x&&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)}},[x,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)(rz.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)(s0.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)(rz.r,{size:16,weight:"fill"}):(0,r.jsx)(s0.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)"]})]}),x&&!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)(lM.j,{size:12,weight:"fill"}),e("desktop.proxyUnsaved")]})]})}function lP(e){return e.replace(/^\/(?:Users|home)\/[^/]+/,"~")}function lD(e){let t=e.sourceInfo?.source,o=e.sourceInfo?.scope;return"user"===o||"user"===t?"global":"project"===o||"project"===t?"project":"path"}function lF(e){let t=lD(e);return"path"===t?t:e.install?.skillsShUrl?`${t} / skills.sh`:t}function lW(e){return e.install?`${e.install.scope}\0${e.install.package}`:null}function l$(e,t){return e?e.slice(0,8):t}function lN({enabled:e,loading:t,onToggle:o}){let{t:n}=(0,D.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 lA({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,D.s)(),g=lD(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 lP(e)}(e.filePath)}),(0,r.jsx)(lN,{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:l$(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:l$(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 lL({cwd:e,installedPackages:t,projectResourcesLoaded:o,onInstalled:s}){let{t:i}=(0,D.s)(),[a,l]=(0,n.useState)(""),[d,c]=(0,n.useState)([]),[p,u]=(0,n.useState)(!1),[g,h]=(0,n.useState)(null),[x,f]=(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=>{f(t),k(null);try{let o=await fetch("/api/skills/install",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({package:t,scope:b,cwd:e})}),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{f(null)}},[s,b,e]),T="global"===b?"~/.pi/agent/skills/":`${lP(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=x===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!==x,style:{flexShrink:0,padding:"5px 14px",fontSize:12,fontWeight:500,borderRadius:5,border:"1px solid var(--border)",cursor:o||n||null!==x?"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 lO({cwd:e,embedded:t=!1,sessionId:o,onCloseAction:s}){let i=A(),{t:a}=(0,D.s)(),[l,d]=(0,n.useState)([]),[c,p]=(0,n.useState)(!0),[u,g]=(0,n.useState)(null),[h,x]=(0,n.useState)(null),[f,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),[E,P]=(0,n.useState)(null),[F,W]=(0,n.useState)(!0),[$,N]=(0,n.useState)({}),L=(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];x(e.filePath),e.disableModelInvocation&&N(t=>({...t,[lF(e)]:!0}))}return r}catch(e){return g(String(e)),[]}finally{p(!1)}},[e,h]);(0,n.useEffect)(()=>{S({}),P(null),L()},[e]);let O=(0,n.useCallback)(async t=>{let o=(t?[t]:l.filter(e=>!!e.install)).map(lW).filter(e=>!!e);if(0!==o.length){P(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){P(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=lW(t);M(o),P(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 L();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){P(e instanceof Error?e.message:String(e))}finally{M(null)}},[e,L]),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&&N(e=>({...e,[lF(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:lP(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)(a_,{sessionId:o,onApplied:L})}),(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"===lD(e)&&!!e.install?.skillsShUrl},{key:"project",label:a("desktop.project"),matches:e=>"project"===lD(e)&&!e.install?.skillsShUrl},{key:"global / skills.sh",label:`${a("desktop.global")} / skills.sh`,matches:e=>"global"===lD(e)&&!!e.install?.skillsShUrl},{key:"global",label:a("desktop.global"),matches:e=>"global"===lD(e)&&!e.install?.skillsShUrl},{key:"path",label:a("desktop.path"),matches:e=>"path"===lD(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=$[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:()=>N(t=>({...t,[e]:!i})),style:{display:"flex",alignItems:"center",gap:5,width:"100%",padding:"4px 8px 3px",border:"none",background:"transparent",color:"var(--text-dim)",cursor:"pointer",fontSize:10,fontWeight:600,letterSpacing:"0.06em",textAlign:"left",textTransform:"uppercase"},children:[(0,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:()=>{x(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=lW(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)(m.c,{size:13}),a("desktop.addSkill")]})})]}),(0,r.jsx)("div",{style:{flex:1,overflowY:"auto",padding:20},children:b?(0,r.jsx)(lL,{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:()=>{L()}}):c?null:U?(0,r.jsx)(lA,{skill:U,cwd:e,onToggle:B,toggling:f.has(U.filePath),saveError:v,updateStatus:lW(U)?j[lW(U)]:void 0,checkingUpdate:!!lW(U)&&C.has(lW(U)),updating:I===lW(U),updateError:E,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 lH(){let{t:e}=(0,D.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),[x,f]=(0,n.useState)(null),m=(0,n.useCallback)(async()=>{h(!0),f(null);try{let e=await fetch("/api/logs?limit=500"),t=await e.json();if(!e.ok)throw Error(t.error??`HTTP ${e.status}`);o(t.entries??[])}catch(e){f(e instanceof Error?e.message:String(e))}finally{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){f(e instanceof Error?e.message:String(e))}},w=async e=>{let t=[`[${e.timestamp}] ${e.level.toUpperCase()} ${e.statusCode??"—"}`,`${e.source}${e.provider?` \xb7 ${e.provider}`:""}${e.model?` \xb7 ${e.model}`:""}`,e.message,e.details].filter(Boolean).join("\n");try{await op(t),f(null)}catch(e){f(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)(j.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)(S.l,{size:14})})]}),g&&(0,r.jsx)("div",{style:{color:"var(--text-muted)",fontSize:12},children:e("desktop.loading")}),x&&(0,r.jsx)("div",{style:{color:"#ef4444",fontSize:12},children:x}),!g&&!x&&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 w(t),style:{marginTop:8,padding:"4px 7px",border:"1px solid var(--border)",borderRadius:5,background:"var(--bg)",color:"var(--text-muted)",cursor:"pointer",fontSize:11},children:e("desktop.logsCopy")})]})]},t.id))})]})}let lB={padding:"7px 9px",background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:6,color:"var(--text)",fontSize:12,width:"100%"},lU={padding:"6px 12px",border:"none",borderRadius:6,background:"var(--accent)",color:"#fff",cursor:"pointer",fontSize:12};function l_(){let{t:e}=(0,D.s)(),[t,o]=(0,n.useState)([]),[s,i]=(0,n.useState)(!0),[a,l]=(0,n.useState)(null),[d,c]=(0,n.useState)(""),[u,g]=(0,n.useState)(""),[x,f]=(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),c(""),g(""),v(null)},j=(0,n.useCallback)(async()=>{let t=d.trim();if(!t)return void v(e("desktop.snippetNameRequired"));f(!0),v(null);try{if(a){let e=await fetch(`/api/snippets/${encodeURIComponent(a.id)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:t,content:u})});if(!e.ok)throw Error(`HTTP ${e.status}`)}else{let e=await fetch("/api/snippets",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:t,content:u})});if(!e.ok)throw Error(`HTTP ${e.status}`)}await y(),b(),w()}catch(e){v(e instanceof Error?e.message:String(e))}finally{f(!1)}},[a,d,u,y,b,e]),C=(0,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)(aC,{children:[(0,r.jsx)(aT,{children:(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:7,padding:"12px 0"},children:[(0,r.jsx)(nl.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)(aT,{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:lU,children:(0,r.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:5},children:[(0,r.jsx)(m.F,{size:13})," ",e("desktop.snippetNew")]})}),a&&(0,r.jsx)("button",{type:"button",onClick:w,style:{...lU,background:"var(--bg-hover)",color:"var(--text-muted)"},children:(0,r.jsx)(p.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=>c(e.target.value),placeholder:"#name",style:lB})]}),(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=>g(e.target.value),rows:3,style:{...lB,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 j(),disabled:x,style:{...lU,cursor:x?"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)(az,{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),c(t.name),g(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)(h.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)(S.l,{size:13})})]},t.id))})]})}),(0,r.jsx)(aR,{children:(0,r.jsx)(az,{children:e("desktop.snippetHint")})})]})}let lq=["async","group","smart"],lV=["full","compact","custom"],lK=["all","background","off"],lJ={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 lG(){return{fontSize:12,color:"var(--text-muted)"}}function lY({cwd:e,sessionId:t}){let{t:o}=(0,D.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),[x,f]=(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()=>{f(!0),k(null),y(!1);try{let e=await fetch("/api/subagents",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)}),t=await e.json();if(!e.ok||t.error)throw Error(t.error??`HTTP ${e.status}`);i(t.config??{}),y(!0)}catch(e){k(e instanceof Error?e.message:String(e))}finally{f(!1)}},[s]),z=(0,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)(aT,{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:lG(),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:lJ})]})},e),E=(e,t,n)=>(0,r.jsx)(aT,{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:lG(),children:o(t)}),(0,r.jsx)("select",{value:s[e]??n[0],onChange:t=>T(e,t.target.value),style:{...lJ,fontFamily:"var(--font-mono)"},children:n.map(e=>(0,r.jsx)("option",{value:e,children:e},e))})]})},e),P=(e,t,n)=>(0,r.jsx)(aT,{children:(0,r.jsx)(as,{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)(az,{children:o("desktop.subagentsDesc")}),(0,r.jsxs)(aC,{children:[M("maxConcurrent","desktop.subagentsMaxConcurrent"),M("defaultMaxTurns","desktop.subagentsDefaultMaxTurns"),M("graceTurns","desktop.subagentsGraceTurns"),E("defaultJoinMode","desktop.subagentsJoinMode",lq),E("widgetMode","desktop.subagentsWidgetMode",lK),E("toolDescriptionMode","desktop.subagentsToolDescMode",lV),P("schedulingEnabled","desktop.subagentsScheduling","desktop.subagentsSchedulingDesc"),P("scopeModels","desktop.subagentsScopeModels","desktop.subagentsScopeModelsDesc"),P("disableDefaultAgents","desktop.subagentsDisableDefault","desktop.subagentsDisableDefaultDesc"),P("fleetView","desktop.subagentsFleetView","desktop.subagentsFleetViewDesc"),(0,r.jsx)(aR,{children:P("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:x,style:{padding:"7px 12px",border:"none",borderRadius:6,background:"var(--accent)",color:"#fff",cursor:x?"wait":"pointer",fontSize:12},children:x?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)(a_,{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)(i7.d,{size:15,"aria-hidden":"true"}),o("desktop.subagentsDiscovered")]}),(0,r.jsx)(aC,{children:a.map((e,t)=>(0,r.jsx)(aR,{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:{...lJ,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 lX(e){return null==e?"—":sY(e)}function lZ({sessionId:e,cwd:t}){let{t:o}=(0,D.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:lX(s.tokens),window:lX(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:lX(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?lX(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}: ${lX(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:lX(e.tokens)})]},e.path))]})]})]})]})}function lQ(){let{t:e}=(0,D.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)(i2.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)(aF.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 l0=[{id:"server",labelKey:"desktop.server",Icon:i2.X},{id:"display",labelKey:"desktop.display",Icon:i4.V},{id:"chat",labelKey:"desktop.chat",Icon:i6.W},{id:"models",labelKey:"desktop.models",Icon:T.f},{id:"skills",labelKey:"desktop.skills",Icon:R.B},{id:"plugins",labelKey:"desktop.plugins",Icon:z.F},{id:"proxy",labelKey:"desktop.proxy",Icon:i5.l},{id:"features",labelKey:"desktop.features",Icon:u.l},{id:"logs",labelKey:"desktop.logs",Icon:y.B},{id:"snippets",labelKey:"desktop.snippets",Icon:nl.c},{id:"usage",labelKey:"desktop.usage",Icon:i3._},{id:"mcp",labelKey:"desktop.mcp",Icon:i8.b},{id:"subagents",labelKey:"desktop.subagents",Icon:i7.d},{id:"backup",labelKey:"desktop.backup",Icon:o7.W},{id:"import",labelKey:"desktop.importSessions",Icon:I.z}];function l1({initialTab:e="models",cwd:t,sessionId:o,onCloseAction:s,onModelsSavedAction:i,onSessionReloadedAction:a,onSessionsChanged:l}){let d=A(),{t:c}=(0,D.s)(),[u,g]=(0,n.useState)("skills"===e||"plugins"===e?t?e:"display":e),[h,x]=(0,n.useState)(!1);(0,n.useEffect)(()=>{x(new URLSearchParams(window.location.search).has("piweb_connected"))},[]);let f=h?l0:l0.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":c("desktop.settings"),className:"settings-modal",style:{width:d?"calc(100vw - 16px)":1e3,maxWidth:"calc(100vw - 16px)",height:d?"calc(100dvh - 16px)":"80vh",maxHeight:"calc(100dvh - 16px)",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:10,display:"flex",flexDirection:"column",boxShadow:"0 8px 32px rgba(0,0,0,0.18)",overflow:"hidden"},children:[(0,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:c("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:c("desktop.closeSettings"),"aria-label":c("desktop.closeSettings"),style:{background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",padding:4,display:"flex"},children:(0,r.jsx)(p.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":c("desktop.settingsSections"),style:{display:"flex",flexDirection:d?"row":"column",gap:4,width:d?"100%":150,padding:8,flexShrink:0,minWidth:0,background:"var(--bg-panel)",borderRight:d?"none":"1px solid var(--border)",borderBottom:d?"1px solid var(--border)":"none",overflowX:d?"auto":void 0,overflowY:d?"hidden":void 0,WebkitOverflowScrolling:d?"touch":void 0},children:f.filter(({id:e})=>!(d&&"import"===e)).map(({id:e,labelKey:o,Icon: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:c(o),"aria-label":c(o),onMouseEnter:e=>{i||s||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{i||(e.currentTarget.style.background="none",e.currentTarget.style.color="var(--text-muted)")},children:[(0,r.jsx)(n,{size:16,"aria-hidden":"true"}),!d&&(0,r.jsx)("span",{children:c(o)})]},e)})}),(0,r.jsx)("div",{style:{display:"server"===u?"flex":"none",flex:1,minWidth:0,minHeight:0},children:(0,r.jsx)(lQ,{})}),(0,r.jsx)("div",{style:{display:"display"===u?"flex":"none",flex:1,minWidth:0,minHeight:0},children:(0,r.jsx)(aj,{})}),(0,r.jsx)("div",{style:{display:"chat"===u?"flex":"none",flex:1,minWidth:0,minHeight:0},children:(0,r.jsx)(ad,{})}),(0,r.jsx)("div",{style:{display:"models"===u?"flex":"none",flex:1,minWidth:0,minHeight:0},children:(0,r.jsx)(lx,{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)(lO,{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)(lI,{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)(lE,{})}),(0,r.jsx)("div",{style:{display:"features"===u?"flex":"none",flex:1,minWidth:0,minHeight:0},children:(0,r.jsx)(aD,{})}),(0,r.jsx)("div",{style:{display:"logs"===u?"flex":"none",flex:1,minWidth:0,minHeight:0},children:(0,r.jsx)(lH,{})}),(0,r.jsx)("div",{style:{display:"snippets"===u?"flex":"none",flex:1,minWidth:0,minHeight:0},children:(0,r.jsx)(l_,{})}),(0,r.jsx)("div",{style:{display:"usage"===u?"flex":"none",flex:1,minWidth:0,minHeight:0},children:(0,r.jsx)(lZ,{sessionId:o,cwd:t})}),(0,r.jsx)("div",{style:{display:"mcp"===u?"flex":"none",flex:1,minWidth:0,minHeight:0},children:(0,r.jsx)(aX,{sessionId:o})}),(0,r.jsx)("div",{style:{display:"subagents"===u?"flex":"none",flex:1,minWidth:0,minHeight:0},children:(0,r.jsx)(lY,{cwd:t,sessionId:o})}),(0,r.jsx)("div",{style:{display:"backup"===u?"flex":"none",flex:1,minWidth:0,minHeight:0},children:(0,r.jsx)(ao,{cwd:t})}),(0,r.jsx)("div",{style:{display:"import"===u?"flex":"none",flex:1,minWidth:0,minHeight:0,overflowY:"auto"},children:(0,r.jsx)(a$,{onSessionsChanged:l})})]}),v&&(0,r.jsx)("div",{style:{padding:"6px 18px",borderTop:"1px solid var(--border)",color:"#f87171",fontSize:11},children:v})]})})}let l2=new Set(["awaiting_input","review","failed"]),l4=(0,n.createContext)(null);function l6(){let e=(0,n.useContext)(l4);if(!e)throw Error("useTasksView must be used within TasksViewProvider");return e}function l5({children:e}){let{t}=(0,D.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,nP.Wt)(),o=(await Promise.all(t.map(e=>(0,nP.Vk)(e).catch(()=>[])))).flat().sort((e,t)=>t.id-e.id);if(e!==d.current)return;l(e=>l3(e,t)?e:t),i(e=>l3(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=>l2.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)(l4.Provider,{value:g,children:e})}function l3(e,t){return JSON.stringify(e)===JSON.stringify(t)}var l8=o(4539),l7=o(12449),l9=o(2571);let de=["todo","inProgress","attention","done"];function dt(e){return"review"===e.status&&0===e.filesChanged}function dr(){return{defaultAgentType:null,modeId:null,configValues:{},autoProcess:!0,maxConcurrent:1,mergeStrategy:"merge",deleteWorktreeDefault:!0,preflightCommand:null,initCommand:null,stagePrompts:null}}let dn=["todo","inProgress","attention","done"],ds={todo:{id:"todo",marker:"var(--text-dim)"},inProgress:{id:"inProgress",marker:"var(--accent)"},attention:{id:"attention",marker:"#f59e0b"},done:{id:"done",marker:"#10b981"}};var di=o(54775),da=o(98998),dl=o(36668);function dd({task:e}){let{t}=(0,D.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)(di.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)(g.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 dc({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)(di.N,{size:10,style:{animation:"pi-spin 1s linear infinite"},"aria-hidden":"true"}):"passed"===t.status?(0,r.jsx)(rz.r,{size:10,"aria-hidden":"true"}):(0,r.jsx)(s0.J,{size:10,"aria-hidden":"true"}),(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:t.command})]})}function dp({task:e,folderName:t,now:o,onOpen:n,onStart:s,onCancel:i,onRetry:a,onRequeue:l,onViewSession:d,onMerge:c,onArchive:p,onEdit:u}){let{t:h}=(0,D.s)(),x=null!=e.archivedAt,f="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(x)return{primary:o={icon:s2.T,label:h("tasks.actionUnarchive"),onClick:p},more:t};switch(e.status){case"todo":o={icon:l9.j,label:h("tasks.actionStart"),onClick:s},t.push({icon:nd.S,label:h("tasks.actionEdit"),onClick:u});break;case"queued":case"preparing":case"running":case"awaiting_input":o={icon:da.k,label:h("tasks.actionCancel"),onClick:i};break;case"review":o=dt(e)?{icon:g.J,label:h("tasks.actionComplete"),onClick:c}:{icon:dl.r,label:h("tasks.actionMerge"),onClick:c};break;case"merging":break;case"failed":o={icon:j.S,label:h("tasks.actionRetry"),onClick:a},t.push({icon:nd.S,label:h("tasks.actionEdit"),onClick:u}),t.push({icon:s2.T,label:h("tasks.actionArchive"),onClick:p});break;case"done":o={icon:s2.T,label:h("tasks.actionArchive"),onClick:p};break;case"canceled":o={icon:rI.f,label:h("tasks.actionRequeue"),onClick:l},t.push({icon:s2.T,label:h("tasks.actionArchive"),onClick:p})}return{primary:o,more:t}})(),b=[...y];return null!=e.conversationId&&b.push({icon:rR.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:x?.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)(dd,{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)(dc,{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)(o9.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,f&&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 du({open:e,onOpenChange:t,task:o}){let{t:s}=(0,D.s)(),{refetch:i}=l6(),[a,l]=(0,n.useState)(""),[d,c]=(0,n.useState)(!1);if((0,n.useEffect)(()=>{e&&(l(""),c(!1))},[e,o]),!e||!o)return null;let u=async()=>{if(!d){c(!0);try{await (0,nP.oQ)(o.id,o.projectRoot,"cancel",{reason:a.trim()||null}),t(!1),i()}catch(e){console.error("cancel failed",e)}finally{c(!1)}}};return(0,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)(p.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 dg({open:e,onOpenChange:t,task:o}){let{t:s}=(0,D.s)(),{refetch:i}=l6(),[a,l]=(0,n.useState)(!0),[d,c]=(0,n.useState)(!1),u=o?.worktreePath!=null;if((0,n.useEffect)(()=>{if(!e||!o)return;c(!1);let t=!1;return(0,nP.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){c(!0);try{await (0,nP.ZX)(o.id,o.projectRoot,u&&a),t(!1),i()}catch(e){console.error("complete failed",e)}finally{c(!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)(p.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 dh=o(51285),dx=o(16894);function df({open:e,onOpenChange:t,task:o,onViewSession:s,onMerge:i,onEdit:a,onCancel:l,onRetry:d,onRequeue:c,onComplete:u}){let{t:h}=(0,D.s)(),{refetch:x}=l6(),[f,m]=(0,n.useState)([]),[v,y]=(0,n.useState)([]),[b,w]=(0,n.useState)(null),[C,T]=(0,n.useState)(null),[R,z]=(0,n.useState)(!1),[I,M]=(0,n.useState)(!1),[E,P]=(0,n.useState)(""),[F,W]=(0,n.useState)(!1),[$,N]=(0,n.useState)(!1),[A,L]=(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,nP.HB)(H,O).catch(()=>[]),o?.worktreePath?(0,nP.JH)(H,O).then(e=>e.files).catch(()=>[]):Promise.resolve([])]);m(e),y(t)},[O,H,o?.worktreePath]);(0,n.useEffect)(()=>{if(!e||null==O)return;m([]),y([]),M(!1),P(""),B();let t=window.setInterval(()=>void B(),5e3);return()=>window.clearInterval(t)},[e,O,B]);let U=(0,n.useCallback)(async e=>{L(!0);try{await e()}catch(e){console.error("detail action failed",e)}finally{L(!1),x()}},[x]),_=(0,n.useCallback)(async e=>{if(null!=H&&null!=O){z(!0);try{let t=await (0,nP.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,nP.bH)(o.id,H,$)),t(!1))},V=async()=>{null!=o&&null!=H&&E.trim()&&(await U(()=>(0,nP.in)(o.id,H,E.trim())),M(!1),P(""))};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:l9.j,onClick:()=>void U(()=>(0,nP.oQ)(o.id,H,"start")),filled:!0}),K.push({label:h("tasks.actionEdit"),icon:nd.S,onClick:()=>a(o)});break;case"queued":case"preparing":case"running":case"awaiting_input":K.push({label:h("tasks.actionCancel"),icon:da.k,onClick:()=>l(o),danger:!0});break;case"review":K.push({label:dt(o)?h("tasks.actionComplete"):h("tasks.actionMerge"),icon:dt(o)?g.J:dh.Y,onClick:()=>dt(o)?u(o):i(o),filled:!0}),K.push({label:h("tasks.actionReturn"),icon:rI.f,onClick:()=>M(!0)});break;case"failed":K.push({label:h("tasks.actionRetry"),icon:j.S,onClick:()=>d(o),filled:!0}),K.push({label:h("tasks.actionEdit"),icon:nd.S,onClick:()=>a(o)});break;case"done":K.push({label:h("tasks.actionArchive"),icon:s2.T,onClick:()=>void U(()=>(0,nP.et)(o.id,H,!0))});break;case"canceled":K.push({label:h("tasks.actionRequeue"),icon:rI.f,onClick:()=>c(o),filled:!0})}else K.push({label:h("tasks.actionUnarchive"),icon:s2.T,onClick:()=>void U(()=>(0,nP.et)(o.id,H,!1))});return null!=o.conversationId&&K.push({label:h("tasks.actionViewSession"),icon:rR.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)(dd,{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)(k.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)(p.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:A,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:E,onChange:e=>P(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:!E.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;w(t=e.file),T(null),_(t)},style:{display:"flex",alignItems:"center",gap:8,textAlign:"left",padding:"4px 6px",borderRadius:6,background:"none",border:"none",color:"var(--text)",fontSize:12,cursor:"pointer"},children:[(0,r.jsx)(dx.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:()=>w(null),style:{background:"none",border:"none",cursor:"pointer",color:"var(--text-muted)",padding:2,display:"flex"},children:(0,r.jsx)(p.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===f.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:[...f].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:A,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)(S.l,{size:13,"aria-hidden":"true"}),h("tasks.delete")]})})]})})}var dm=o(17757);function dk({open:e,onOpenChange:t,task:o,defaultProject:s,projects:i,prefillTitle:a,prefillPrompt:l,onSubmit:d}){let{t:c}=(0,D.s)(),[u,g]=(0,n.useState)(""),[h,x]=(0,n.useState)(""),[f,m]=(0,n.useState)(""),[k,v]=(0,n.useState)([]),[y,b]=(0,n.useState)(""),[w,j]=(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]??""),x(o?.title??a??""),m(o?.config?.prompt??l??""),(0,nP.VB)().then(v).catch(()=>void 0))},[e,o,s,i,a,l]),!e)return null;let T=async()=>{if(u&&h.trim()&&!w){j(!0);try{await d(u,h.trim(),{prompt:f.trim(),agentType:o?.config?.agentType??null,modelId:o?.config?.modelId??null,thinkingLevel:o?.config?.thinkingLevel??null}),t(!1)}catch(e){console.error("submit task failed",e)}finally{j(!1)}}},R=async()=>{if(y.trim()&&h.trim())try{await (0,nP.nY)({name:y.trim(),title:h.trim(),config:{prompt:f.trim()}}),b(""),(0,nP.VB)().then(v).catch(()=>void 0)}catch(e){console.error("save template failed",e)}},z=async e=>{try{await (0,nP.B_)(e),(0,nP.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?c("tasks.editTitle"):c("tasks.newTitle")}),(0,r.jsx)("button",{type:"button",onClick:()=>t(!1),"aria-label":c("i18n.close"),style:{background:"none",border:"none",cursor:"pointer",color:"var(--text-muted)",padding:4,display:"flex"},children:(0,r.jsx)(p.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:c("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:()=>{x(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":c("tasks.deleteTemplate"),style:{background:"none",border:"none",cursor:"pointer",color:"var(--text-dim)",padding:0,display:"flex"},children:(0,r.jsx)(S.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:c("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:c("tasks.fieldTitle")}),(0,r.jsx)("input",{value:h,onChange:e=>x(e.target.value),placeholder:c("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:c("tasks.fieldPrompt")}),(0,r.jsx)("textarea",{value:f,onChange:e=>m(e.target.value),placeholder:c("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:c("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)(dm.D,{size:13,"aria-hidden":"true"}),c("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:c("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:c("tasks.save")})]})]})]})})}function dv({open:e,onOpenChange:t,task:o}){let{t:s}=(0,D.s)(),{refetch:i}=l6(),[a,l]=(0,n.useState)(!0),[d,c]=(0,n.useState)(""),[u,g]=(0,n.useState)(!0),[h,x]=(0,n.useState)(!1);if((0,n.useEffect)(()=>{e&&o&&(l(!0),c(o.title),x(!1),(0,nP.CG)(o.projectRoot).then(e=>g(e.deleteWorktreeDefault)).catch(()=>g(!0)))},[e,o]),!e||!o)return null;let f=async()=>{if((a||d.trim())&&!h){x(!0);try{await (0,nP.oB)(o.id,o.projectRoot,a?null:d.trim(),u),t(!1),i()}catch(e){console.error("merge failed",e)}finally{x(!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)(p.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=>c(e.target.value),placeholder:s("tasks.mergeMessagePlaceholder"),style:{width:"100%",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:8,padding:"8px 10px",color:"var(--text)",fontSize:13,outline:"none",fontFamily:"inherit"}}),(0,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 f(),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 dy({open:e,onOpenChange:t,task:o,kind:s}){let{t:i}=(0,D.s)(),{refetch:a}=l6(),[l,d]=(0,n.useState)(""),[c,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(!c){u(!0);try{await (0,nP.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)(p.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:c,style:{padding:"8px 14px",borderRadius:8,background:"none",border:"1px solid var(--border)",color:"var(--text)",fontSize:12,cursor:"pointer"},children:i("i18n.cancel")}),(0,r.jsx)("button",{type:"button",onClick:()=>void h(),disabled:c,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 db=["work","retry","return","merge"];function dw({open:e,onOpenChange:t,projectRoot:o}){let{t:s}=(0,D.s)(),{projects:i}=l6(),[a,l]=(0,n.useState)(""),[d,c]=(0,n.useState)(()=>dr()),[u,g]=(0,n.useState)(!1),[h,x]=(0,n.useState)(!1);if((0,n.useEffect)(()=>{if(!e)return;let t=o??i[0]??"";l(t),t&&(0,nP.Pf)(t).then(e=>{g(null!=e),c(e??dr())}).catch(()=>{g(!1),c(dr())})},[e,o,i]),!e)return null;let f=(e,t)=>{c(o=>({...o,[e]:t}))},m=async()=>{if(a&&!h){x(!0);try{await (0,nP.eA)(a,d),g(!0),t(!1)}catch(e){console.error("save settings failed",e)}finally{x(!1)}}},k=async()=>{if(a)try{await (0,nP.E)(a),g(!1),c(dr())}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)(p.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=>f("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=>f("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=>f("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=>f("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=>f("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=>f("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")}),db.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=>f("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 dj({open:e,onOpenChange:t,task:o}){let{t:s}=(0,D.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)(p.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 dS="__all__",dC="pi-tasks-board-filter",dT={showCanceled:!1,showArchived:!1},dR="pi:open-task-settings";function dz(){let{t:e}=(0,D.s)(),{attentionCount:t}=l6();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)(aS.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(dR)),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)(l8.O,{size:13,"aria-hidden":"true"}),e("tasks.settingsTitle")]})]})}function dI({activeProject:e}){let{t}=(0,D.s)(),{tasks:s,projects:i,refetch:a}=l6(),[l,c]=(0,n.useState)(null),[p,u]=(0,n.useState)(()=>(function(){try{let e=window.localStorage.getItem(dC);if(e){let t=JSON.parse(e);return{showCanceled:t.showCanceled??!1,showArchived:t.showArchived??!1}}}catch{}return dT})()),[g,h]=(0,n.useState)(!1);(0,n.useEffect)(()=>{try{window.localStorage.setItem(dC,JSON.stringify(p))}catch{}},[p]);let[x,f]=(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[E,P]=(0,n.useState)(!1),[F,W]=(0,n.useState)(null),[$,N]=(0,n.useState)(null);(0,n.useEffect)(()=>{let e=()=>{let e,t=(e=rO,rO=null,e);t&&(W(null),N(t),P(!0))};return e(),window.addEventListener(rL,e),()=>window.removeEventListener(rL,e)},[]);let[A,L]=(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(dR,e),()=>window.removeEventListener(dR,e)},[]);let ec=(0,n.useMemo)(()=>null==l?s:s.filter(e=>e.projectRoot===l),[s,l]),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 de)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===A)??null,[s,A]),eh=(0,n.useMemo)(()=>s.find(e=>e.id===ei)??null,[s,ei]),ex=(0,n.useCallback)(async e=>{try{await e()}catch(e){console.error("task action failed",e)}finally{a()}},[a]),ef=(0,n.useCallback)(e=>{null!=e.conversationId&&(ea(e.id),ed(!0))},[ea,ed]),em=(0,n.useCallback)(e=>{H(e),U(!0)},[H,U]),ek=(0,n.useCallback)(()=>{W(null),P(!0)},[W,P]),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(f(null),v(!1),e){R.current=!1;return}requestAnimationFrame(()=>{R.current=!1})},[f,v]),ew=(0,n.useCallback)(()=>{z.current=!0,C(null),eb(!0)},[eb,C]);(0,n.useEffect)(()=>{if(!x)return;let e=()=>{document.hidden&&ew()};return window.addEventListener("blur",ew),document.addEventListener("visibilitychange",e),()=>{window.removeEventListener("blur",ew),document.removeEventListener("visibilitychange",e)}},[x,ew]),(0,n.useEffect)(()=>{x&&!eu.some(e=>e.id===x.task.id)&&ew()},[x,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!=l&&ex(()=>(0,nP.oQ)(e.id,e.projectRoot,"start"));return}let i=T.current;null!=l&&null!=i&&(async()=>{try{await (0,nP.Lu)(l,i)}catch(e){console.error("reorder failed",e)}await a(),C(null)})()},[ex,eb,l,a,s]),eS=(0,n.useCallback)(()=>{ex(async()=>{let e=await (0,nP.a5)(l);e>0&&console.log(`started ${e} tasks`)})},[ex,l]),eC=(0,n.useCallback)(()=>{let e=ep.done.filter(e=>null==e.archivedAt);0!==e.length&&ex(()=>Promise.all(e.map(e=>(0,nP.et)(e.id,e.projectRoot,!0))))},[ex,ep.done]),eT=+(p.showCanceled!==dT.showCanceled)+ +(p.showArchived!==dT.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:l??dS,onChange:e=>c(e.target.value===dS?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:dS,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)(l7.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)(l9.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)(m.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:dn.map(e=>{let o="todo"===e?eu:ep[e],n=ds[e],s=e=>(0,r.jsx)(dp,{task:e,folderName:e.projectRoot?eI.get(e.projectRoot)??null:null,now:I,onOpen:()=>{R.current||L(e.id)},onStart:()=>void ex(()=>(0,nP.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:()=>ef(e),onMerge:()=>{dt(e)?(et(e),er(!0)):em(e)},onArchive:()=>void ex(()=>(0,nP.et)(e.id,e.projectRoot,null==e.archivedAt)),onEdit:()=>{W(e),P(!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&&x?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&&x?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},f({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:x?.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)(aS.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)(m.F,{size:13,weight:"bold","aria-hidden":"true"}),t("tasks.new")]})]}),(0,r.jsx)(dk,{open:E,onOpenChange:P,task:F,defaultProject:$?.projectRoot??l??e??null,projects:ez,prefillTitle:$?$.text.slice(0,80):void 0,prefillPrompt:$?$.text:void 0,onSubmit:async(e,t,r)=>{await ex(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})}),P(!1),N(null)}}),(0,r.jsx)(df,{open:null!=A,onOpenChange:e=>{e||L(null)},task:eg,onViewSession:ef,onMerge:em,onEdit:e=>{W(e),P(!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)(dv,{open:B,onOpenChange:U,task:O}),(0,r.jsx)(du,{open:V,onOpenChange:K,task:_}),(0,r.jsx)(dy,{open:Z,onOpenChange:Q,task:J,kind:Y}),(0,r.jsx)(dg,{open:eo,onOpenChange:er,task:ee}),(0,r.jsx)(dj,{open:el&&null!=eh,onOpenChange:ed,task:eh}),(0,r.jsx)(dw,{open:en,onOpenChange:es,projectRoot:l}),x?(0,d.createPortal)((0,r.jsx)("div",{ref:w,style:{position:"fixed",left:0,top:0,zIndex:999,pointerEvents:"none",width:x.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:x.task.title}),(0,r.jsx)(dd,{task:x.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)(l9.j,{size:11,weight:"bold","aria-hidden":"true"}),t("tasks.dropToStart")]}):null]})}),document.body):null]})}var dM=o(62235);function dE({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)(ah.b,{size:16,"aria-hidden":"true"}):(0,r.jsx)(ag.A,{size:16,"aria-hidden":"true"}):(0,r.jsx)(ah.b,{size:16,"aria-hidden":"true"})})}function dP({topBarRef:e,sidebarOpen:t,onSidebarToggle:o,isDark:s,toggleTheme:i,isMobile:a,showTasks:l,tasksBoardEnabled:d,onToggleTasks:c,systemPrompt:p,activeTopPanel:u,topPanelPos:h,sessionStats:x,contextUsage:f,copiedSessionField:m,onCopySessionField:k,rightPanelOpen:v,onToggleFilePanel:b,onOpenSettings:w,sessionTitle:j,onWorkspaceControlsHostChange:S,onTitleRightHostChange:C}){let T,R,z,I,M,E,P,F,{t:W}=(0,D.s)(),[$,N]=(0,n.useState)(!1),[A,L]=(0,n.useState)(!1);return(0,n.useEffect)(()=>{try{L(new URLSearchParams(window.location.search).has("piweb_connected"))}catch{L(!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)(dM.V,{size:16,"aria-hidden":"true"}):(0,r.jsx)(y.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)(aS.x,{size:16,"aria-hidden":"true"})}),(0,r.jsx)("button",{className:"app-no-drag",onClick:b,title:v?W("desktop.hideFilePanel"):W("desktop.showFilePanel"),"aria-label":v?W("desktop.hideFilePanel"):W("desktop.showFilePanel"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:36,height:36,padding:0,background:v?"var(--bg-selected)":"none",border:"none",color:v?"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=v?"var(--bg-selected)":"none",e.currentTarget.style.color=v?"var(--text)":"var(--text-muted)"},children:(0,r.jsx)(dM.V,{size:16,"aria-hidden":"true",style:{transform:"scaleX(-1)"}})}),(0,r.jsx)(dE,{isDark:s,toggleTheme:i,translate:W}),A&&(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)(i2.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)(l8.O,{size:16,"aria-hidden":"true"})})]})]}),u&&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"===u&&(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"===u&&(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:x?(T=[...x.sessionName?[{label:W("desktop.name"),value:x.sessionName,copyField:null}]:[],{label:W("desktop.sessionInfoFile"),value:x.sessionFile??W("desktop.sessionInfoInMemory"),copyField:"file"},{label:W("desktop.sessionInfoId"),value:x.sessionId,copyField:"id"}],R=[[W("desktop.sessionInfoUser"),x.userMessages.toLocaleString()],[W("desktop.sessionInfoAssistant"),x.assistantMessages.toLocaleString()],[W("desktop.sessionInfoToolCalls"),x.toolCalls.toLocaleString()],[W("desktop.sessionInfoToolResults"),x.toolResults.toLocaleString()],[W("desktop.sessionInfoTotal"),x.totalMessages.toLocaleString()]],z=[[W("desktop.sessionInfoInput"),x.tokens.input.toLocaleString()],[W("desktop.sessionInfoOutput"),x.tokens.output.toLocaleString()],...x.tokens.cacheRead>0?[[W("desktop.sessionInfoCacheRead"),x.tokens.cacheRead.toLocaleString()]]:[],...x.tokens.cacheWrite>0?[[W("desktop.sessionInfoCacheWrite"),x.tokens.cacheWrite.toLocaleString()]]:[],[W("desktop.sessionInfoTotal"),x.tokens.total.toLocaleString()]],I=f??x.contextUsage,E=[...x.cost>0?[[W("desktop.sessionInfoCost"),`$${x.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)}`]]:[]],P=(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)(g.J,{size:12,"aria-hidden":"true"}):(0,r.jsx)(tx.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,P(W("desktop.sessionInfoMessages"),R),P(W("desktop.sessionInfoTokens"),[...z,...E],"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 dD({cwd:e,busy:t,error:o,onCancelAction:n,onConfirmAction:s}){let{t:i}=(0,D.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)(rN.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 dF(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 dW(e){return dF(.42*e,360,640)}function d$(e,t){try{window.localStorage.setItem(e,String(t))}catch{}}function dN(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),[x,f]=(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=>dF(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),f(n),r&&(s||o)&&d$(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&&d$(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":x,"aria-valuetext":`${x} px`,onDoubleClick:M,onKeyDown:P,onLostPointerCapture:I,onPointerCancel:z,onPointerDown:C,onPointerMove:T,onPointerUp:R,role:"separator",tabIndex:0},width:x}}function dA(){let e,t,o,d=(0,a.useRouter)(),c=(0,a.useSearchParams)(),p=(0,n.useMemo)(()=>{let e;return{requestedCwd:e=c.get("cwd")?.trim()||null,sessionId:e?null:c.get("session")}},[c]),{isDark:u,toggleTheme:g}=oc(),{t:h}=(0,D.s)(),x=A(),[f,m]=(0,n.useState)(null),[k,v]=(0,n.useState)(null),[y,b]=(0,n.useState)(0),[w,j]=(0,n.useState)(0),[S,C]=(0,n.useState)(0),[T,R]=(0,n.useState)(!1),[z,I]=(0,n.useState)("models"),[M,E]=(0,n.useState)(0),[P,F]=(0,n.useState)(null),[W,$]=(0,n.useState)(!1),[N,L]=(0,n.useState)(!1),[O,H]=(0,n.useState)(null),[B,U]=(0,n.useState)(!0),[_,q]=(0,n.useState)(!1);(0,n.useEffect)(()=>{x&&U(!1)},[x]),(0,n.useEffect)(()=>{q(!0)},[]);let V=(0,n.useRef)(null),K=(0,n.useRef)(null),[J,G]=(0,n.useState)(null),[Y,X]=(0,n.useState)(null),[Z,Q]=(0,n.useState)(null),[ee,et]=(0,n.useState)(null),eo=(0,n.useCallback)(e=>{et(e)},[]),[er,en]=(0,n.useState)(null),ei=(0,n.useCallback)(e=>{en(e)},[]),[ea,el]=(0,n.useState)([]),ed=(0,n.useCallback)(e=>{el(e)},[]),ec=ea.filter(e=>"running"===e.status).length,[ep,eu]=(0,n.useState)(null),eg=(0,n.useRef)(null),eh=(0,n.useCallback)((e,t)=>{op(t).then(()=>{eg.current&&clearTimeout(eg.current),eu(e),eg.current=setTimeout(()=>eu(null),1400)})},[]);(0,n.useEffect)(()=>()=>{eg.current&&clearTimeout(eg.current)},[]);let[ex,ef]=(0,n.useState)(null),em=(0,n.useCallback)(e=>{ef(e)},[]),[ek,ev]=(0,n.useState)(null),[ey,eb]=(0,n.useState)(null),ew=(0,n.useCallback)(()=>{x&&U(!1),ev("session")},[x]),ej=(0,n.useCallback)(()=>{x&&ev(null),U(e=>!e)},[x]);(0,n.useEffect)(()=>{if(!ek||!K.current)return;let e=()=>{let e=K.current.getBoundingClientRect();eb({top:e.bottom,left:e.left,width:e.width})};e();let t=new ResizeObserver(e);return t.observe(K.current),()=>t.disconnect()},[ek]);let[eS,eC]=(0,n.useState)([]),[eR,ez]=(0,n.useState)(null),[eI,eM]=(0,n.useState)(!1),[eE,eP]=(0,n.useState)(!1),[eD,eF]=(0,n.useState)(null),eW=(0,n.useCallback)(e=>{eF(e??null),eP(!0),eM(!0),x&&U(!1)},[x]),e$=(0,n.useCallback)(()=>{eP(!1),eF(null)},[]),[eN,eL]=(0,n.useState)(null),eO=(0,n.useCallback)(e=>eL(e),[]),eH=(0,n.useCallback)(()=>eL(null),[]);(0,n.useEffect)(()=>{if(!eN)return;let e=e=>{"Escape"===e.key&&(e.stopImmediatePropagation(),e.preventDefault(),eL(null))};return window.addEventListener("keydown",e,!0),()=>window.removeEventListener("keydown",e,!0)},[eN]);let eB=(0,n.useRef)(260),eU=(0,n.useRef)(dW(1366)),e_=(0,n.useCallback)(()=>dW(window.innerWidth),[]),eq=(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:eI,rightPanelWidth:eU.current}),[eI]),eV=(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:B,sidebarWidth:eB.current}),[B]),eK=dN({ariaLabel:h("desktop.resizeSidebar"),cssVariable:"--sidebar-width",defaultWidth:260,getMaxWidth:eq,growthDirection:"right",maxWidth:480,minWidth:180,storageKey:"pi-sidebar-width",widthRef:eB}),eJ=dN({ariaLabel:h("desktop.resizeFilePanel"),cssVariable:"--right-panel-width",defaultWidth:dW(1366),getDefaultWidth:e_,getMaxWidth:eV,growthDirection:"left",maxWidth:1200,minWidth:300,storageKey:"pi-right-panel-width",widthRef:eU}),eY=eK.reclampWidth,eX=eJ.reclampWidth;(0,n.useEffect)(()=>{eI&&(eY(),eX())},[eX,eY,eI]);let eZ=(0,n.useCallback)((e,t)=>{V.current?.insertText(nE(e,t))},[]),eQ=(0,n.useCallback)(e=>{let t=e.map(e=>nE(e,!1)).join("");t&&V.current?.insertText(t)},[]),e0=(0,n.useCallback)((e,t,o)=>{let r,n,s,i;V.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} `))},[]),[e1,e2]=(0,n.useState)(()=>p.sessionId),[e4,e6]=(0,n.useState)(null),[e5,e3]=(0,n.useState)(()=>p.requestedCwd?"validating":"idle"),[e8,e7]=(0,n.useState)(null),[e9,te]=(0,n.useState)(()=>!e1),tt=(0,n.useRef)(!1),to=(0,n.useRef)(new Map),[tr,tn]=(0,n.useState)(null),ts=(0,n.useRef)("");(0,n.useEffect)(()=>{let e=`${p.requestedCwd??""}|${p.sessionId??""}`;ts.current!==e&&(ts.current=e,e2(p.sessionId),te(!p.sessionId),p.requestedCwd||e3("idle"),e7(null))},[p]),(0,n.useEffect)(()=>{let e=p.requestedCwd;if(!e)return;let t=new AbortController;return e3("validating"),e7(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}`);tt.current=!0,v(t.cwd),e3("ready")}).catch(e=>{t.signal.aborted||(e7(e instanceof Error?e.message:String(e)),e3("error"))}),()=>t.abort()},[p]);let ti=(0,n.useCallback)((e,t)=>{if(!e)return;if(e6(e),tt.current&&f&&eT(f.projectRoot??f.cwd,t??e)){if(tt.current=!1,f){let e=f.projectRoot??f.cwd;e&&to.current.set(e,f.id)}return}tt.current=!1;let o=t??e;if(f&&eT(f.projectRoot??f.cwd,o)){(f.projectRoot??f.cwd)&&to.current.set(o,f.id);return}if(f){let e=f.projectRoot??f.cwd;e&&to.current.set(e,f.id)}m(null),v(t=>t&&t!==e?null:t),j(e=>e+1),et(null),ev(null),window.history.replaceState(null,"","/");let r=to.current.get(o);tn(r?{projectRoot:o,sessionId:r}:null)},[f]);(0,n.useEffect)(()=>{let e=e4?es(e4)||e4:null;document.title=e?`${e} — Pi Agent Web`:"Pi Agent Web"},[e4]);let ta=(0,n.useCallback)((e,t=!1)=>{if(t||tn(null),!t&&f){let t=eT(f.projectRoot??f.cwd,e.projectRoot??e.cwd);if(f.id===e.id&&t){x&&U(!1);return}}let o=e.projectRoot??e.cwd;o&&to.current.set(o,e.id),v(null),m(e),j(e=>e+1),et(null),te(!0),x&&!t&&U(!1),t&&(tt.current=!0),t||window.history.replaceState(null,"",`?session=${encodeURIComponent(e.id)}`)},[x,f]),tl=(0,n.useRef)(()=>{});(0,n.useEffect)(()=>{tl.current=ta},[ta]);let td=(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&&m(t=>!t||t.id!==e||t.projectRoot&&t.name?t:o)}).catch(()=>{})},[]);(0,n.useEffect)(()=>{if(!tr)return;let{projectRoot:e,sessionId:t}=tr;tl.current({path:"",id:t,cwd:e,created:"",modified:"",messageCount:0,firstMessage:"",projectRoot:e},!0),td(t),window.history.replaceState(null,"",`?session=${encodeURIComponent(t)}`),tn(null)},[tr,td]);let tc=(0,n.useCallback)((e,t)=>{tn(null),m(null),v(t),j(e=>e+1),et(null),ev(null),x&&U(!1),window.history.replaceState(null,"","/")},[d,x]);!function(e){let{onNewSession:t,activeCwd:o}=e;(0,n.useEffect)(()=>{let e=e=>{if("Escape"===e.key){if(!l)return;let t=e.target?.tagName;if("TEXTAREA"===t||"INPUT"===t)return;e.preventDefault(),l();return}if("n"===e.key&&e.ctrlKey&&e.altKey){if(!o||!t)return;e.preventDefault(),t(o)}};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[o,t])}({onNewSession:e=>tc(`kb-${Date.now()}`,e),activeCwd:e4});let tp=(0,n.useCallback)(e=>{v(null),tn(null);let t=e.projectRoot??e.cwd;t&&to.current.set(t,e.id),m(e),e.cwd&&e6(e.cwd),b(e=>e+1),td(e.id),window.history.replaceState(null,"",`?session=${encodeURIComponent(e.id)}`),window.setTimeout(()=>b(e=>e+1),1200),window.setTimeout(()=>b(e=>e+1),4e3)},[d,td]),tu=(0,n.useCallback)(()=>{b(e=>e+1),C(e=>e+1)},[]),tg=(0,n.useCallback)(e=>{b(e=>e+1),j(e=>e+1),v(null),tn(null),m(t=>{let o={...t??{path:"",cwd:"",created:"",modified:"",messageCount:0,firstMessage:""},id:e},r=o.projectRoot??o.cwd;return r&&to.current.set(r,e),o}),td(e),window.history.replaceState(null,"",`?session=${encodeURIComponent(e)}`)},[d,td]),th=(0,n.useCallback)(()=>{te(!0)},[]),tx=(0,n.useCallback)(e=>{if(b(e=>e+1),f?.id===e){let e=f.cwd;m(null),v(e??null),j(e=>e+1),et(null),ev(null),window.history.replaceState(null,"","/")}},[d,f]),tf=(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}`;eC(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}]}),ez(i),eM(!0),x&&U(!1)},[x]),tm=(0,n.useCallback)(e=>{tf(e,es(e),f?.id??null)},[tf,f?.id]),tk=(0,n.useCallback)(e=>{eC(t=>{let o=t.filter(t=>t.id!==e);return 0===o.length&&eM(!1),o}),ez(t=>{if(t!==e)return t;let o=eS.filter(t=>t.id!==e);return o.length>0?o[o.length-1].id:null})},[eS]),tv=f?eA(f.name||er?.sessionName)||f.firstMessage.slice(0,50)||f.id.slice(0,12):(e=e4??k)?e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e:null,ty=(0,n.useCallback)(()=>{f&&window.open(`/api/sessions/${encodeURIComponent(f.id)}/export?inline=1`,"_blank","noopener,noreferrer")},[f]),tb=k??(null===f&&e4?e4:null),tw="validating"!==e5&&"error"!==e5&&(null!==f||null!==tb),tj=f?.id;(0,n.useEffect)(()=>{eN&&eL(null)},[tj,tw]);let tS=f?.cwd??tb,[tC,tT]=(0,n.useState)(!1),tR=(0,n.useCallback)(()=>{x||tT(e=>!e)},[x]),[tz,tI]=(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&&(tI(t.tasksBoard),t.tasksBoard||tT(!1))}).catch(()=>{});t();let o=()=>t();return window.addEventListener("pi:features-changed",o),()=>{e=!0,window.removeEventListener("pi:features-changed",o)}},[]);let tM=e9&&!tw;(0,n.useEffect)(()=>{let e=()=>{x||tT(!0)};return window.addEventListener(iw,e),()=>window.removeEventListener(iw,e)},[x]),(0,n.useEffect)(()=>{if(F(null),$(!1),H(null),!tS)return;let e=new AbortController;return fetch(`/api/project-trust?cwd=${encodeURIComponent(tS)}`,{signal:e.signal}).then(async e=>{let t=await e.json();if(!e.ok||t.error)throw Error(t.error??`HTTP ${e.status}`);F(t)}).catch(e=>{e instanceof DOMException&&"AbortError"===e.name||console.error("Failed to load project trust:",e)}),()=>e.abort()},[tS]);let tE=(0,n.useCallback)(async()=>{if(tS&&!N){L(!0),H(null);try{let e=await fetch("/api/project-trust",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:tS})}),t=await e.json();if(!e.ok||t.error)throw Error(t.error??`HTTP ${e.status}`);F(t),$(!1),E(e=>e+1),j(e=>e+1)}catch(e){H(e instanceof Error?e.message:String(e))}finally{L(!1)}}},[N,tS]),tP=eS.find(e=>e.id===eR)??null,tD=e4??f?.cwd??k,tF=(0,n.useCallback)(e=>{I(e),R(!0)},[]),tW=(0,r.jsx)(r.Fragment,{children:(0,r.jsx)(eG,{selectedSessionId:f?.id??null,onSelectSession:ta,onNewSession:tc,initialSessionId:e1,onInitialRestoreDone:th,refreshKey:y,onSessionDeleted:tx,selectedCwd:f?.cwd??k??null,onCwdChange:ti,onOpenFile:tf,selectedSessionStats:er,onOpenSettings:e=>{tF(["models","skills","plugins","chat","features","logs"].includes(e)?e:"models")},explorerRefreshKey:S,onAtMention:eZ,onAtMentions:eQ,workspaceControlsHosts:{title:J,welcome:Z,titleRight:Y},showWorkspaceControls:!0})});return(0,r.jsxs)(l5,{children:[(0,r.jsx)("style",{children:`
|
|
36
|
+
${o}`):s=o;let x=s,f=n?.map(e=>({type:"image",source:{type:"base64",media_type:e.mimeType,data:e.data}})),m={role:"user",content:f?.length?[...o.trim()?[{type:"text",text:o}]:[],...f]:o,timestamp:Date.now()};S(e=>[...e,m]),oo.current=iv(m),ot.current=l,"goal"!==ek.current||a||(ew.current=i,eH(e=>({...e,status:"running",goalText:i,turnsUsed:0,noProgressTurns:0,tokensUsed:0})),eU.current=!0),tV.current=!0,$(!0),tt(a?{kind:"running_command"}:{kind:"waiting_model"}),z({type:"start"}),t2.current=!0,tr(!0),t4.current=!0;let k=n?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),v=null,y=!1;try{if(g&&r){let e=tq.current??await t9.current,t=e??await ow();if(t){v=t,ob(1,o),Q&&(e4(Q),e&&await io(t,{type:"set_model",provider:Q.provider,modelId:Q.modelId}));let r=await Promise.race([oR(t).then(()=>!0).catch(()=>!1),ih(4e3).then(()=>!1)]);y=!0,await io(t,{type:"prompt",message:x,...k?.length?{images:k}:{}}),r||oA(t,l),"goal"!==ek.current||a||io(t,{type:"goal_start",goalText:i}).catch(()=>{})}else throw Error("Unable to create a session for this message")}else if(t){v=t.id;let e=await Promise.race([oR(t.id).then(()=>!0).catch(()=>!1),ih(4e3).then(()=>!1)]);y=!0,await io(t.id,{type:"prompt",message:x,...k?.length?{images:k}:{}}),e||oA(t.id,l),"goal"!==ek.current||a||io(t.id,{type:"goal_start",goalText:i}).catch(()=>{})}a&&v&&oA(v,l)}catch(t){if(console.error("Failed to send message:",t),y&&v)return void oA(v,l);if(tJ.current=!1,oC(),t instanceof ig){let e=oo.current;e&&S(t=>{let o=t[t.length-1];return o?.role==="user"&&iv(o)===e?t.slice(0,-1):t}),oM({type:"error",message:t.message})}else{let o=oo.current;o&&S(e=>{let t=e[e.length-1];return t?.role==="user"&&iv(t)===o?e.slice(0,-1):e}),e.chatInputRef?.current?.replaceMessage?.(m),oM({type:"error",message:`Failed to send message: ${t instanceof Error?t.message:String(t)}`})}oo.current=null,tV.current=!1,$(!1),tt(null),z({type:"end"})}},[g,r,Q,t,ow,oR,ob,oA,oM,oS,oC,oc]),oU=(0,n.useCallback)(async(o,r)=>{if(tV.current||tZ.current)return;let n=`${r?"!!":"!"}${o}`;tZ.current=!0,O({command:o,excludeFromContext:r}),A(!0);try{let e=tq.current??t?.id??await ow();if(!e)throw Error("Unable to create a session for the shell command");ob(1,n),await io(e,{type:"bash",command:o,excludeFromContext:r}),await ok(e)}catch(t){console.error("Failed to execute shell command:",t),oM({type:"error",message:t instanceof Error?t.message:String(t)}),e.chatInputRef?.current?.insertIfEmpty(n)}finally{tZ.current=!1,O(null),A(!1)}},[oM,ow,ok,e.chatInputRef,ob,t]),o_=(0,n.useCallback)(async()=>{let e=tq.current;if(e)try{await io(e,{type:tZ.current?"abort_bash":"abort"})}catch(e){console.error("Failed to abort:",e)}},[]),oq=(0,n.useCallback)(async e=>{let t=tq.current;if(t){eQ(e);try{let{cancelled:o,newSessionId:r}=await io(t,{type:"fork",entryId:e})??{};!o&&r&&a?.(r)}catch(e){console.error("Fork failed:",e)}finally{eQ(null)}}},[a]),oV=(0,n.useCallback)(async e=>{let t=tq.current;t&&(io(t,{type:"navigate_tree",targetId:e}).catch(()=>{}),w(e),await ov(t,e))},[ov]),oK=(0,n.useCallback)(async e=>{w(e);let t=tq.current;t&&(await ov(t,e),e&&io(t,{type:"navigate_tree",targetId:e}).catch(()=>{}))},[ov]),oJ=(0,n.useCallback)(async(e,t)=>{if(g){let o={provider:e,modelId:t};oa.current=o,ee(o),e4(o);let r=tq.current??await t9.current;if(!r)return;try{await io(r,{type:"set_model",provider:e,modelId:t})}catch(e){console.error("Failed to set model:",e)}return}let o=tq.current;if(!o)return;let r=++or.current,n=e0??x?.context.model??null;e1({provider:e,modelId:t});try{await io(o,{type:"set_model",provider:e,modelId:t})}catch(o){console.error("Failed to set model:",o),or.current===r&&(e1(n&&(n.provider!==e||n.modelId!==t)?n:null),oM({type:"error",message:o instanceof Error?o.message:String(o)}))}},[oM,e0,x?.context.model,g,ee]),oG=(0,n.useCallback)(async()=>{let e=tq.current;if(e&&!e6){e5(!0),e8(null),e9(null);try{let t=await io(e,{type:"compact"});e9(iy(t,"manual")),await ok(e,!0)}catch(e){e8(e instanceof Error?e.message:String(e)),e9(null)}finally{e5(!1)}}},[e6,ok]),oY=(0,n.useCallback)(async e=>{let o=++on.current,n=r??t?.cwd??"",s=n?`/api/models?cwd=${encodeURIComponent(n)}`:"/api/models",i=os.current;i?.abort();let a=new AbortController;os.current=a;let l=()=>a.abort();e?.aborted?a.abort():e?.addEventListener("abort",l,{once:!0});try{let e=await fetch(s,{signal:a.signal});if(!e.ok){let t=`HTTP ${e.status}`;try{let o=await e.json();o?.error&&(t=o.error)}catch{}throw Error(t)}let t=await e.json();if(o!==on.current||h!==oi.current)return;Z(null),B(t.models),V(t.thinkingLevels??{}),J(t.thinkingLevelMaps??{}),Y(t.modelScopeWarnings??[]);let r=t.modelList??[];if(_(r),g&&!tq.current){let e=(t.defaultModel?r.find(e=>e.id===t.defaultModel?.modelId&&e.provider===t.defaultModel?.provider):void 0)??r[0];eo(e?{provider:e.provider,modelId:e.id}:null);let o=e?t.thinkingLevelPins?.[`${e.provider}/${e.id}`]:void 0;null===ol.current&&eq(o??"auto")}}catch(e){if(a.signal.aborted||o!==on.current||h!==oi.current)return;Z(e instanceof Error?e.message:String(e))}finally{e?.removeEventListener("abort",l),os.current===a&&(os.current=null)}},[g,h,r,t?.cwd]),oX=(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=tq.current??await ow(),i=e=>(e.handled&&(e.error?oM({type:"error",message:e.error}):"openSessionStats"!==e.action&&oM({type:"success",message:e.message??"Command completed"})),e);try{switch(o){case"compact":{if(!s||e6)return i({handled:!0,error:"No active session to compact"});e5(!0),e8(null),e9(null);let e=await io(s,{type:"compact",...n?{customInstructions:n}:{}});return e9(iy(e,"manual")),await ok(s,!0)&&ob(),i({handled:!0,message:"Compacted context"})}case"reload":if(!s)return i({handled:!0,error:"No active session to reload"});return await io(s,{type:"reload"}),await Promise.all([ok(s,!1,!0),oy(s),oj(),oY()]),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 io(s,{type:"set_session_name",name:eA(n)}),await ok(s)&&ob(),i({handled:!0,message:`Session renamed to ${n}`});case"session":{if(!s)return i({handled:!0,error:"No active session"});let e=await io(s,{type:"get_session_stats"});return e&&tp(e),p?.(),i({handled:!0,action:"openSessionStats"})}case"copy":{if(!s)return i({handled:!0,error:"No active session"});let e=await io(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&&e5(!1)}},[oM,ow,e6,oY,ok,oj,oy,ob,p]),oZ=(0,n.useCallback)(async e=>{let t=!1;try{let o=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(o.ok){let e=await o.json(),r=e.state;if(e.running&&r&&(r.isStreaming||r.isPromptRunning||r.isBashRunning||r.isCompacting))return;t=!0}}catch{}if(t){tV.current=!1,$(!1),tt(null);return}oA(e)},[oA]),oQ=(0,n.useCallback)(async(e,t)=>{let o=tq.current;if(!o)return;let r=t?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType}));tV.current=!0,$(!0),tt(e=>e??{kind:"waiting_model"});try{await io(o,{type:"steer",message:e,...r?.length?{images:r}:{}})}catch(e){console.error("Failed to steer:",e),oZ(o)}},[oZ]),o0=(0,n.useCallback)(async(e,t,o)=>{let r=tq.current;if(!r)return;let n=o?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType}));tV.current=!0,$(!0),tt(e=>e??{kind:"waiting_model"});try{await io(r,{type:"prompt",message:e,streamingBehavior:t,...n?.length?{images:n}:{}})}catch(e){console.error("Failed to queue prompt:",e),oZ(r)}},[oZ]),o1=(0,n.useCallback)(async(e,t)=>{let o=tq.current;if(!o)return;let r=t?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType}));tV.current=!0,$(!0),tt(e=>e??{kind:"waiting_model"});try{await io(o,{type:"follow_up",message:e,...r?.length?{images:r}:{}})}catch(e){console.error("Failed to follow up:",e),oZ(o)}},[oZ]),o2=(0,n.useCallback)(async()=>{let e=tq.current;if(e)try{await io(e,{type:"abort_compaction"})}catch(e){console.error("Failed to abort compaction:",e)}},[]),o4=(0,n.useCallback)(async()=>{let t=tq.current;if(t)try{let o=await io(t,{type:"clear_queue"});tw({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),oM({type:"error",message:"Failed to recall queued messages"})}},[e.chatInputRef,oM,tw]);(0,n.useEffect)(()=>{0===tj.length&&tR(!1)},[tj.length]);let o6=(0,n.useCallback)(async(e,t,o=!1)=>{let r=tq.current;if(!r)return tj;try{let n=await io(r,{type:"resolve_recovery",keep:e,discard:t,continueRun:o}),s=n?.remaining??[];return tC(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;tK.current=!!o.isStreaming,tJ.current=!!o.isPromptRunning,tV.current=!0,$(!0),tt(ia(o)),z({type:"start"}),oT(r),!o.isStreaming&&o.isPromptRunning&&oA(r)}catch{}})(),s}catch(e){return console.error("Failed to resolve queued message recovery:",e),oM({type:"error",message:"Failed to resolve queued message recovery"}),tj}},[tj,oM,oT,oA,tC]),o5=(0,n.useCallback)(async()=>{let e=tq.current;if(!e)return null;try{return await io(e,{type:"export_queue"})}catch(e){return console.error("Failed to export queue:",e),oM({type:"error",message:"Failed to export queue"}),null}},[oM]),o3=(0,n.useCallback)(async e=>{let t=tq.current;if(!t)return null;try{let o=await io(t,{type:"import_queue",entries:e});return o&&tw(id(o)),o?.imported??0}catch(e){return console.error("Failed to import queue:",e),oM({type:"error",message:"Failed to import queue"}),null}},[oM,tw]),o8=(0,n.useCallback)(async e=>{let t=tq.current;if(!t)return null;try{let o=await io(t,{type:"stage_recovery",entries:e});return o?.pendingRecovery&&tC(o.pendingRecovery),(o?.staged??0)>0&&tR(!0),o?.staged??0}catch(e){return console.error("Failed to stage imported queue:",e),oM({type:"error",message:"Failed to stage imported queue"}),null}},[oM,tC]),o7=(0,n.useCallback)(async(e,t,o)=>{let r=tq.current;if(!r)return!1;try{let n=await io(r,{type:"move_queue",kind:e,fromIndex:t,toIndex:o});return n&&tw(id(n)),!0}catch(e){return console.error("Failed to move queued message:",e),oM({type:"error",message:e instanceof Error?e.message:"Failed to move queued message"}),!1}},[oM,tw]),o9=(0,n.useCallback)(async(e,t)=>{let o=tq.current;if(!o)return null;try{let r=await io(o,{type:"recall_queue_item",kind:e,index:t});return r&&(void 0!==r.steering||void 0!==r.followUp)&&tw(id(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),oM({type:"error",message:e instanceof Error?e.message:"Failed to recall queued message"}),null}},[oM,tw]),re=(0,n.useCallback)(async(e,t,o,r)=>{let n=tq.current;if(!n)return!1;try{let s=await io(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&&tw(id(s)),!0}catch(e){return console.error("Failed to requeue message:",e),oM({type:"error",message:e instanceof Error?e.message:"Failed to requeue message"}),!1}},[oM,tw]),rt=(0,n.useCallback)(async(e,t)=>{let o=tq.current;if(!o)return!1;try{let r=await io(o,{type:"remove_queue_item",kind:e,index:t});return r&&tw(id(r)),!0}catch(e){return console.error("Failed to remove queued message:",e),oM({type:"error",message:e instanceof Error?e.message:"Failed to remove queued message"}),!1}},[oM,tw]),rn=(0,n.useCallback)(async e=>{if(ol.current="auto"===e?null:e,eq(e),"auto"===e)return;let t=tq.current??await t9.current;if(t)try{await io(t,{type:"set_thinking_level",level:e})}catch(e){console.error("Failed to set thinking level:",e)}},[]),rs=(0,n.useCallback)(async e=>{let t=(0,ir.xG)(e);ou(e);let o=tq.current??await t9.current;if(o)try{await io(o,{type:"set_tools",toolNames:t})}catch(e){console.error("Failed to set tools:",e)}},[ou]),ri=(0,n.useRef)(0),ra=(0,n.useCallback)(async e=>{let t=tq.current??await t9.current,o=++ri.current;if(e){if(ea.current="plan"===er?"default":er,ei(!0),el.current=!0,ej.current={sessionKey:"",signature:""},t)try{if(await io(t,{type:"prompt",message:"/plan"}),ri.current!==o)return}catch(e){if(ri.current!==o)return;console.error("Failed to enter plan mode:",e)}}else if(ei(!1),el.current=!1,ej.current={sessionKey:"",signature:""},t){try{if(await io(t,{type:"prompt",message:"/plan exit"}),ri.current!==o)return}catch(e){if(ri.current!==o)return;console.error("Failed to exit plan mode:",e)}if(ri.current!==o)return;try{let e=ea.current;await io(t,{type:"set_tools",toolNames:(0,ir.xG)(e)})}catch(e){console.error("Failed to restore tools after plan exit:",e)}}},[er]),rl=(0,n.useCallback)(e=>{ec(e);let t=tq.current;if(!t){ep.current=e;return}ep.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)})},[]),rd=(0,n.useCallback)(e=>{if(rl({...eS.current,collaborationMode:eM(e)}),ek.current=eM(e),ej.current={sessionKey:"",signature:""},"goal"!==e){ew.current=null,eU.current=!1,eH(e=>"idle"===e.status?e:{...e,status:"idle",goalText:null});let e=tq.current;e&&io(e,{type:"goal_stop"}).catch(()=>{})}},[rl]),rc=(0,n.useCallback)(async e=>{rl({...eS.current,tokenMode:eE(e)});let t=tq.current??await t9.current;if(t)try{if("economy"!==e||el.current){if("economy"!==e){let e=el.current?ir.SC:(0,ir.xG)("plan"===er?"default":er);await io(t,{type:"set_tools",toolNames:e})}}else await io(t,{type:"set_tools",toolNames:[...eD]})}catch(e){console.error("Failed to apply token mode tools:",e)}},[rl,er]),rp=(0,n.useCallback)(async e=>{rl({...eS.current,toolApprovalMode:eP(e)});let t=tq.current??await t9.current;if(t)try{await io(t,{type:"set_approval_mode",mode:eP(e)})}catch(e){console.error("Failed to apply approval mode:",e)}},[rl]),ru=(0,n.useCallback)(async e=>{rl({...eS.current,permissionRules:e});let t=tq.current??await t9.current;if(t)try{await io(t,{type:"set_approval_policy",policy:e})}catch(e){console.error("Failed to apply permission rules:",e)}},[rl]),rg=(0,n.useCallback)(async(e,t,o)=>{let r=tq.current;if(r)try{await io(r,{type:"resolve_approval",id:e,approve:t,reason:o})}catch(e){console.error("Failed to resolve approval:",e)}finally{eT(t=>t.filter(t=>t.id!==e))}},[]),rh=(0,n.useCallback)(e=>{ew.current=e},[]),rx=(0,n.useCallback)(e=>{let t=e.trim();if(!t)return;ew.current=t,eH(e=>({...e,status:"running",goalText:t,turnsUsed:0,noProgressTurns:0,tokensUsed:0,startedAt:Date.now()}));let o=tq.current;o&&io(o,{type:"goal_start",goalText:t}).catch(()=>{})},[]),rf=(0,n.useCallback)(()=>{if("running"!==eB.current.status)return;eH(e=>({...e,status:"paused"}));let e=tq.current;e&&io(e,{type:"goal_pause"}).catch(()=>{})},[]),rm=(0,n.useCallback)(()=>{let e=eB.current;if("paused"!==e.status&&"blocked"!==e.status)return;eH(e=>({...e,status:"running"}));let t=tq.current;t&&io(t,{type:"goal_resume"}).catch(()=>{})},[]),rk=(0,n.useCallback)(()=>{eU.current=!1,ew.current=null,eH(e=>({...e,status:"idle",goalText:null,turnsUsed:0,noProgressTurns:0}));let e=tq.current;e&&io(e,{type:"goal_stop"}).catch(()=>{})},[]),rv=(0,n.useCallback)(e=>{let t=e.trim();if(!t)return;eH(e=>({...e,goalText:t}));let o=tq.current;o&&io(o,{type:"goal_edit",goalText:t}).catch(()=>{})},[]),ry=tz.map(e=>`${e.id}:${e.status}:${e.completedAt??""}`).join("|"),rb=(0,n.useRef)(tz);rb.current=tz,(0,n.useEffect)(()=>{u?.(rb.current)},[ry,u]),(0,n.useEffect)(()=>()=>{u?.([])},[u]),(0,n.useEffect)(()=>{tP(()=>[])},[t?.id,r??t?.cwd]);let rw=(0,n.useCallback)(()=>{let e=t7.current,t=t1.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);t6.current=n>=r-150,t3.current=Date.now()+700,e.scrollTo({top:n,behavior:"smooth"})},[]),rj=(0,n.useCallback)(e=>{e instanceof KeyboardEvent&&(!iu.has(e.key)||e.target instanceof Element&&e.target.closest("input, textarea, [contenteditable='true']"))||(t5.current=Date.now()+1200)},[]),rS=(0,n.useCallback)(()=>{let e=t7.current;if(e){let{scrollTop:t,clientHeight:o,scrollHeight:r}=e;t6.current=t+o>=r-150}if(Date.now()<t5.current){t4.current=!1;return}Date.now()<t3.current||(t4.current=!1)},[]);(0,n.useEffect)(()=>{if(tY.current=!0,t){tq.current=t.id;let e=ey.current,o=eb.current;("auto"!==e||o.allow.length||o.ask.length||o.deny.length)&&(io(t.id,{type:"set_approval_mode",mode:e}).catch(()=>{}),io(t.id,{type:"set_approval_policy",policy:o}).catch(()=>{})),ok(t.id,!0,!0).then(e=>{e?.running&&(e.state?.isBashRunning&&(tZ.current=!0,A(!0)),oy(t.id),(e.state?.isStreaming||e.state?.isPromptRunning)&&(tK.current=!!e.state.isStreaming,tJ.current=!!e.state.isPromptRunning,tV.current=!0,$(!0),tt(ia(e.state)),z({type:"start"}),oT(t.id),!e.state.isStreaming&&e.state.isPromptRunning&&oA(t.id))),e?.state&&(void 0!==e.state.isCompacting&&e5(e.state.isCompacting),void 0!==e.state.contextUsage&&eG(e.state.contextUsage??null),void 0!==e.state.systemPrompt&&eX(e.state.systemPrompt??null),void 0!==e.state.thinkingLevel&&eq(e.state.thinkingLevel??"auto"),void 0!==e.state.extensionStatuses&&tm(e.state.extensionStatuses??[]),void 0!==e.state.extensionWidgets&&tv(e.state.extensionWidgets??[]),void 0!==e.state.queuedMessages&&tw(id(e.state.queuedMessages)),void 0!==e.state.pendingRecovery&&tC(e.state.pendingRecovery??[])),e?.running||fetch(`/api/agent/${encodeURIComponent(t.id)}`).then(e=>e.ok?e.json():null).then(e=>{e&&e.running&&oy(t.id)}).catch(()=>{})})}return()=>{tY.current=!1,oc(),tA(),oS(),oC()}},[oc]),(0,n.useEffect)(()=>{c?.(eY)},[eY,c]),(0,n.useEffect)(()=>{d&&d(x?.tree??[],b,oK)},[x?.tree,b,oK,d]),(0,n.useEffect)(()=>(window.addEventListener("keydown",rj),window.addEventListener("pointerdown",rj,{passive:!0}),()=>{window.removeEventListener("keydown",rj),window.removeEventListener("pointerdown",rj)}),[rj]),(0,n.useEffect)(()=>{let e=t7.current;if(e)return e.addEventListener("wheel",rj,{passive:!0}),e.addEventListener("touchstart",rj,{passive:!0}),e.addEventListener("scroll",rS,{passive:!0}),()=>{e.removeEventListener("wheel",rj),e.removeEventListener("touchstart",rj),e.removeEventListener("scroll",rS)}},[j.length,m,rS,rj]),(0,n.useEffect)(()=>{j.length>0&&(t2.current?(t0.current=!0,t1.current&&(t2.current=!1,rw())):m||!t0.current?(m||(t0.current=!0),oO("instant")):!tV.current&&(t4.current||t6.current)&&oO("smooth"))},[j.length,m,W,oO,rw]);let rC=(0,n.useRef)(!1);(0,n.useEffect)(()=>{let e;if(m){rC.current=!1;return}if(rC.current||0===j.length)return;rC.current=!0;let t=!1,o=-1,r=0,n=()=>{if(t||tV.current||!(t4.current||t6.current))return;oO("instant");let s=t7.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,oO]),(0,n.useEffect)(()=>{let e=new AbortController;return oY(e.signal).catch(e=>{if(e instanceof DOMException&&"AbortError"===e.name)return}),()=>e.abort()},[oY,l]),(0,n.useEffect)(()=>{if(!X)return;let e=()=>{"visible"===document.visibilityState&&oY()};return document.addEventListener("visibilitychange",e),window.addEventListener("online",e),()=>{document.removeEventListener("visibilitychange",e),window.removeEventListener("online",e)}},[X,oY]),(0,n.useEffect)(()=>{if(!e3)return;let e=setTimeout(()=>e8(null),3e3);return()=>clearTimeout(e)},[e3]),(0,n.useEffect)(()=>{if(!e7)return;let e=setTimeout(()=>e9(null),6e3);return()=>clearTimeout(e)},[e7]),(0,n.useEffect)(()=>{if(0===tl.visible.length)return;let e=tl.visible.find(e=>e.exiting);if(e){let t=setTimeout(()=>{td({type:"remove",id:e.id})},180);return()=>clearTimeout(t)}if(!tl.visible[0])return;let t=setTimeout(()=>{td({type:"mark_oldest_exiting"})},5e3);return()=>clearTimeout(t)},[tl.visible]),(0,n.useEffect)(()=>{tp(null)},[j.length,eJ?.tokens,eJ?.percent,eJ?.contextWindow]);let rT=x?.tree??[];return{data:x,loading:m,error:v,activeLeafId:b,messages:j,entryIds:C,streamState:R,agentRunning:W,bashRunning:N,pendingBash:L,modelNames:H,modelList:U,modelThinkingLevels:q,modelThinkingLevelMaps:K,modelScopeWarnings:G,modelsError:X,newSessionModel:Q,toolPreset:er,thinkingLevel:e_,retryInfo:eV,contextUsage:eJ,systemPrompt:eY,forkingEntryId:eZ,isCompacting:e6,compactError:e3,compactResult:e7,currentModel:ox,displayModel:of,sessionStats:om,tokenRate:I,planMode:es,subagents:tz,collaborationMode:eh,tokenMode:ex,toolApprovalMode:ef,permissionRules:em,modeSettings:ed,approvalRequests:eC,handleCollaborationModeChange:rd,handleTokenModeChange:rc,handleToolApprovalModeChange:rp,handlePermissionRulesChange:ru,resolveApproval:rg,setActiveGoalText:rh,goalState:eO,handleGoalStart:rx,handleGoalPause:rf,handleGoalResume:rm,handleGoalStop:rk,handleGoalEdit:rv,slashCommands:tn,slashCommandsLoading:ti,queuedMessages:ty,pendingRecovery:tj,recoveryIsImport:tT,notices:tl.visible,extensionDialog:tu,extensionCustomUi:th,extensionStatuses:tf,extensionWidgets:tk,respondToExtensionUi:oz,sendExtensionCustomInput:oI,agentPhase:te,isNew:g,promptAnchorActive:to,branchTree:rT,sessionIdRef:tq,eventSourceRef:tL,messagesEndRef:t8,scrollContainerRef:t7,lastUserMsgRef:t1,pendingScrollToUserRef:t2,initialScrollDoneRef:t0,scrollUserMsgToTop:rw,handleSend:oB,executeBash:oU,handleAbort:o_,handleFork:oq,handleNavigate:oV,handleModelChange:oJ,handleCompact:oG,handleSteer:oQ,handleFollowUp:o1,handlePromptWithStreamingBehavior:o0,handleAbortCompaction:o2,handleRecallQueue:o4,resolveRecovery:o6,exportQueueData:o5,importQueueData:o3,stageQueueImport:o8,moveQueuedMessage:o7,recallQueuedMessage:o9,requeueAt:re,removeQueuedMessage:rt,handleBuiltinSlashCommand:oX,handleToolPresetChange:rs,handleThinkingLevelChange:rn,handlePlanModeChange:ra,loadTools:oy,loadSlashCommands:oj,reloadModels:oY,setActiveLeafId:w,setData:f,setMessages:S,dispatch:z,setAgentRunning:$,setForkingEntryId:eQ,handleLeafChange:oK,handleAgentEventRef:tQ}}({session:e,newSessionCwd:t,onAgentEnd:$,onSessionCreated:i,onSessionForked:a,modelsRefreshKey:d,chatInputRef:c,onBranchDataChange:p,onSystemPromptChange:u,onSessionStatsPanelOpen:x,onSubagentsChange:h}),[tM,tE]=(0,n.useState)(!1);(0,n.useEffect)(()=>{0===ef.length&&tE(!1)},[ef.length]);let{balance:tP,refresh:tD,refreshSoon:tF}=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.useRef)(null),d=(0,n.useCallback)(async()=>{s.current?.abort();let e=new AbortController;s.current=e;try{let o=await fetch("/api/deepseek/balance",{signal:e.signal,cache:"no-store"}),n=await o.json();if(!a.current)return;if(n?.available&&null!=n.totalBalance){let e=l.current;(null===e||e.available!==n.available||e.reason!==n.reason||e.currency!==n.currency||e.totalBalance!==n.totalBalance||e.grantedBalance!==n.grantedBalance||e.toppedUpBalance!==n.toppedUpBalance)&&(l.current=n,t(n)),r(!1)}else null===l.current&&r(!0)}catch{if(!a.current)return;null===l.current&&r(!0)}},[]),c=(0,n.useCallback)(()=>{i.current&&clearTimeout(i.current),i.current=setTimeout(()=>{i.current=null,d()},2e3)},[d]);return{balance:e,failed:o,refresh:d,refreshSoon:c}}(),tW=ec?.provider==="deepseek",t$=(0,n.useRef)(null);(0,n.useEffect)(()=>{tW&&tD()},[tW,tD]),(0,n.useEffect)(()=>{if(tW)for(let e=U.length-1;e>=0;e--){let t=U[e];if("assistant"!==t.role||!t.usage)continue;let o=`${e}:${_[e]??""}`;o!==t$.current&&(t$.current=o,tF());break}},[U,_,tW,tF]);let tN=(0,n.useMemo)(()=>{let e=U.findLast(e=>"assistant"===e.role&&!!e.usage);if(!e?.usage)return null;let t=e.usage;return{model:e.model??"",input:t.input??0,output:t.output??0,cacheRead:t.cacheRead??0,costCNY:ro(e.model)?rr(e.model,t):0,costUSD:ro(e.model)?0:t.cost?.total??0}},[U]),[tA,tL]=(0,n.useState)(!1),[tO,tH]=(0,n.useState)(null),tB=(0,n.useRef)(!1);(0,n.useEffect)(()=>{if(!tu){tB.current=!1;return}if(V){tB.current=!0;return}tB.current&&(tB.current=!1,tH(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}(U)??null),tL(!0))},[V,tu,U]);let tU=(0,n.useCallback)(()=>{tL(!1);let e=t_.current;"plan"===tf&&tv("normal"),tx(!1).then(()=>{e&&eG(E("tasks.planReviewExecutePrompt",{plan:e}))})},[tx,eG,E,tf,tv]),t_=(0,n.useRef)(null);(0,n.useEffect)(()=>{t_.current=tO},[tO]);let tq=(0,n.useCallback)(e=>{tL(!1),e2(e)},[e2]),tV=(0,n.useCallback)(()=>{tL(!1),"plan"===tf&&tv("normal"),tx(!1)},[tx,tf,tv]);(0,n.useEffect)(()=>{ev&&W.current!==ev.id&&(W.current=ev.id,F.current&&P.current())},[ev]),(0,n.useEffect)(()=>(l=V||K?eX:null,()=>void(l=null)),[V,K,eX]);let[tK,tJ]=(0,n.useState)(!1),[tG,tY]=(0,n.useState)(!1),[tX,tZ]=(0,n.useState)(!1),tQ=(0,n.useCallback)(()=>{let e=e_.current;if(!e)return;let t=e.scrollHeight-e.scrollTop-e.clientHeight;tJ(e.scrollTop>1),tY(t>1),tZ(t>240)},[e_]),t0=(0,n.useCallback)(()=>{window.requestAnimationFrame(()=>{let e=e_.current,t=eU.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(),tQ(),window.setTimeout(r,200)})},[eU,e_,tQ,c]);(0,n.useEffect)(()=>{let e=e_.current;if(!e)return;let t=new ResizeObserver(tQ);return t.observe(e),e.firstElementChild&&t.observe(e.firstElementChild),e.addEventListener("scroll",tQ,{passive:!0}),tQ(),()=>{e.removeEventListener("scroll",tQ),t.disconnect()}},[U.length,e_,tQ]);let t1=(0,n.useRef)(null),t2=(0,n.useRef)([]),t4=(0,n.useMemo)(()=>({getOffsetForIndex:e=>t1.current?.getOffsetForIndex(e)?.[0]??0,sizeFor:e=>{let t=t1.current;if(!t)return 0;let o=t.measurementsCache[e];return o?.size??t.options.estimateSize?.(e)??0},totalHeight:()=>t1.current?.getTotalSize()??0,refToItemIndex:e=>t2.current[e],itemCount:t2.current.length}),[]),t6=ep?[ep.sessionId,ep.sessionFile??"",ep.sessionName??"",ep.userMessages,ep.assistantMessages,ep.toolCalls,ep.toolResults,ep.totalMessages,ep.tokens.input,ep.tokens.output,ep.tokens.cacheRead,ep.tokens.cacheWrite,ep.tokens.total,ep.cost??0,ep.totalActiveMs??0].join("|"):null,t5=(0,n.useRef)(ep);t5.current=ep,(0,n.useEffect)(()=>{g?.(t5.current)},[t6,g]),(0,n.useEffect)(()=>()=>{g?.(null)},[g]);let t3=es?`${es.percent??"null"}|${es.contextWindow}|${es.tokens??"null"}`:null,t8=(0,n.useRef)(es);t8.current=es,(0,n.useEffect)(()=>{f?.(t8.current)},[t3,f]),(0,n.useEffect)(()=>()=>{f?.(null)},[f]);let{isDragOver:t7,handleDragEnter:t9,handleDragOver:oe,handleDragLeave:ot,handleDrop:oo}=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(V){let t=e.filter(e=>e.type.startsWith("image/"));t.length&&c?.current?.addImages(t);return}c?.current?.addFiles(e,t)},[V,c])),or=U.filter(e=>"user"===e.role||"assistant"===e.role),on=(0,n.useMemo)(()=>{let e=new Set,t=[];for(let r=U.length-1;r>=0&&t.length<50;r-=1){var o;let n="user"!==(o=U[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},[U]),os=(S=or.length,(C=(0,n.useRef)([])).current=Array(S).fill(null).map((e,t)=>C.current[t]??null),C),oi=eT&&0===U.length&&!q.isStreaming&&!V,oa=e?.cwd??t??void 0,ol=(0,n.useMemo)(()=>(function(e,t,o){let r=new Map;for(let t of e)"toolResult"===t.role&&r.set(t.toolCallId,t);let n=-1;for(let t=e.length-1;t>=0;t--)if("user"===e[t].role){n=t;break}let s=new Map,i=0;e.forEach((e,t)=>{("user"===e.role||"assistant"===e.role)&&s.set(t,i++)});let a=[];for(let n=0;n<e.length;){let s,i=e[n],l="custom"===i.role&&"compaction"===i.customType;if("user"!==i.role&&!l){a.push({kind:"single",idx:n}),n+=1;continue}let d=n,c=d+1;for(;c<e.length&&"user"!==e[c].role;)c+=1;let p=function(e,t,o){for(let n=o-1;n>t;n--){var r;if("assistant"===(r=e[n]).role&&tr(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}(e,d,c);if(-1===p){a.push({kind:"turn",userIdx:d,endIdx:c,startsCompactionTurn:l,finalAssistantIdx:p,visibleProcessIndices:[],processBlocks:[],finalAnswerMessage:null,writtenFiles:void 0}),n=c;continue}let u=[];for(let e=d+1;e<p;e++)u.push(e);let g=u.filter(t=>tg(e[t])),h=e[p],x=tr(h),f=x.processBlocks.length>0?th(h,x.processBlocks,{omitUsage:!0}):null,m=x.answerBlocks.length>0?th(h,x.answerBlocks):null,k=tl(e,t,g,r);if(f&&(k=k.concat(ta(h,{messageIndex:p,entryId:t[p],toolResults:r}).processBlocks)),m){let t=[];for(let o=d+1;o<=p;o++){let r=e[o];if(r?.role==="assistant")for(let e of r.content??[])t.push(e)}s=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 tp(o)}(i,o);a&&(r.has(a)||(r.add(a),n.push({filePath:a})))}return n}(t,r,o)}a.push({kind:"turn",userIdx:d,endIdx:c,startsCompactionTurn:l,finalAssistantIdx:p,visibleProcessIndices:g,processBlocks:k,finalAnswerMessage:m,writtenFiles:s}),n=c}return{toolResultsMap:r,lastUserIdx:n,visibleRefIndexByMessage:s,items:a}})(U,_,oa),[U,_,oa]),od=ec?X[`${ec.provider}:${ec.modelId}`]??null:null,oc=ec?Z[`${ec.provider}:${ec.modelId}`]??null:null,op=(0,n.useCallback)(()=>{et()},[et]),ou=(0,n.useCallback)(e=>{tx(e),e&&"plan"!==tf?tv("plan"):e||"plan"!==tf||tv("normal")},[tx,tv,tf]),og=(0,n.useCallback)(e=>{tv(e),"plan"!==e||tu?"plan"!==e&&tu&&tx(!1):tx(!0)},[tv,tx,tu]),oh=(0,r.jsx)(sH,{ref:c,onSend:eG,onBash:eY,tasksBoardEnabled:b,onAbort:eX,onSteer:V?e2:void 0,onFollowUp:V?e4:void 0,onPromptWithStreamingBehavior:V?e6:void 0,isStreaming:V,model:ec,modelNames:G,modelList:Y,modelScopeWarnings:Q,modelsError:ee,onRetryModels:op,onModelChange:e0,compactResult:ed,toolPreset:eo,onToolPresetChange:e||eT?ti:void 0,planMode:tu,onPlanModeChange:ou,collaborationMode:tf,tokenMode:tm,toolApprovalMode:tk,onCollaborationModeChange:og,onTokenModeChange:ty,onToolApprovalModeChange:tb,goalState:tS,onGoalStart:tC,onGoalPause:tT,onGoalResume:tR,onGoalStop:tz,thinkingLevel:er,onThinkingLevelChange:e||eT?td:void 0,availableThinkingLevels:od,thinkingLevelMap:oc,retryInfo:en,queuedMessages:ex,inputHistory:on,onRecallQueue:e3,onMoveQueue:te,onRecallOne:tt,onRequeueAt:to,onRemoveQueueItem:tn,slashCommands:eg,slashCommandsLoading:eh,onLoadSlashCommands:tc,onBuiltinCommand:ts,onAudioUnlock:I,draftKey:e?.id??(t?`new:${t}`:void 0),cwd:e?.cwd??t}),ox=ew.filter(e=>"belowEditor"!==e.placement),of=ew.filter(e=>"belowEditor"===e.placement),om=ea?E("desktop.compacting"):function(e,t){if(e?.kind==="running_tools"){let o=e.tools.map(e=>e.name);return 0===o.length?t("desktop.runningTool"):t("desktop.runningTools",{tools:o.length<=3?o.join(", "):`${o.slice(0,2).join(", ")} (+${o.length-2})`})}return e?.kind==="waiting_model"?t("desktop.waitingForModel"):e?.kind==="running_command"?t("desktop.runningCommand"):null}(eC,E);return H?(0,r.jsx)("div",{className:"flex h-full items-center justify-center text-text-muted",children:E("desktop.loadingSession")}):B?(0,r.jsx)("div",{className:"flex h-full items-center justify-center text-red-400",children:B}):(0,r.jsxs)("div",{className:"relative flex h-full min-w-0 flex-col overflow-hidden",onDragEnter:t9,onDragOver:oe,onDragLeave:ot,onDrop:oo,children:[t7&&(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"})]})]})]}),ev&&(0,r.jsx)(iR,{request:ev,onRespond:ej}),ey&&(0,r.jsx)(iz,{request:ey,onInput:eS}),!eT&&ef.length>0&&!tM&&(0,r.jsx)(s_,{items:ef,sessionId:e?.id,onResolve:e8,onExport:e7,onStageImport:e9,onDismiss:()=>tE(!0),mode:em?"import":"recovery"}),tw.length>0&&(0,r.jsx)(rA,{request:tw[0]??null,queuedCount:Math.max(0,tw.length-1),busy:!1,onResolve:(e,t)=>{let o=tw[0];o&&tj(o.id,e,t)}}),oi?(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:M?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:M?"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.10.8"]})]}),(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:M?16:34},children:(0,r.jsx)(iT,{notices:ek,align:"right"})}),"goal"===tf&&(0,r.jsx)(r$,{goalState:tS,onPause:tT,onResume:tR,onStop:tz,onEdit:tI}),oh,(0,r.jsx)("div",{style:{padding:"0 16px 6px",paddingRight:M?16:34,marginTop:-15},children:(0,r.jsx)(s5,{onViewFullHistory:v,cwd:oa,systemPrompt:y,sessionStats:ep,contextUsage:es,hasSession:!!e,showChat:!0,showSoundLabel:!0,soundEnabled:T,onSoundToggle:R,onCompact:e?e1:void 0,onAbortCompaction:e5,isCompacting:ea,compactError:el,isDeepSeekOfficial:tW,deepseekBalance:tP,lastTurnUsage:tN})})]})}):(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*!M,zIndex:40,padding:"0 16px",pointerEvents:"none"},children:(0,r.jsx)("div",{style:{maxWidth:820,margin:"0 auto"},children:(0,r.jsx)(iT,{notices:ek,floating:!0,align:"right"})})}),(0,r.jsxs)("div",{className:"relative flex-1 min-h-0 min-w-0",children:[(0,r.jsx)("div",{ref:e_,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)(iS,{statuses:eb}),(0,r.jsx)(iC,{widgets:ox}),(()=>{let{toolResultsMap:t,lastUserIdx:o,visibleRefIndexByMessage:n,items:s}=ol,i=(s,i={})=>{let a=i.messageOverride??U[s],l="user"===a.role&&s>0&&"assistant"===U[s-1].role?_[s-1]:void 0,d="user"===a.role||"assistant"===a.role,c=n.get(s),p=i.keyPrefix??"message",u=!1;if("assistant"===a.role){u=!0;for(let e=s+1;e<U.length;e++){let t=U[e].role;if("user"===t)break;if("assistant"===t){u=!1;break}}u&&q.isStreaming&&s===U.length-1&&(u=!1)}void 0!==i.showTimestamp&&(u=i.showTimestamp);let g=(0,r.jsx)(rd,{message:a,toolResults:t,modelNames:G,cwd:oa,onOpenFile:m,entryId:_[s],onFork:V||eT||0===s&&"user"===a.role?void 0:eZ,forking:ei===_[s],onNavigate:V?void 0:eQ,prevAssistantEntryId:V?void 0:l,onEditContent:N,onQuoteReply:L,onCreateTask:O,showTimestamp:u,prevTimestamp:s>0?U[s-1].timestamp:void 0,sessionId:e?.id??eB.current??void 0,writtenFiles:i.writtenFiles,subagents:w,onOpenSubagent:j},`${p}-view-${s}`);return d&&!1!==i.attachRef&&void 0!==c?(0,r.jsx)("div",{ref:e=>{os.current[c]=e,s===o&&(eq.current=e,e&&eV.current&&(eV.current=!1,eK.current=!0,eJ()))},children:g},`${p}-${s}`):g},a=[],l=[],d=(e,t)=>{a.push(e),l.push(t)};for(let a of s){if("single"===a.kind){d(i(a.idx),n.get(a.idx));continue}let{userIdx:s,endIdx:l,startsCompactionTurn:c,finalAssistantIdx:p}=a;if((V||q.isStreaming)&&l===U.length&&(s===o||c)){d(i(s),n.get(s));let o=q.streamingMessage?.role==="assistant",a=[],c=!o&&p>=0?p:l;for(let e=s+1;e<c;e++)tg(U[e])&&a.push(e);let u=tl(U,_,a,t),g=null;if(!o&&p>=0){let e=U[p],o=tr(e,{isStreaming:!0}),r=ta(e,{messageIndex:p,entryId:_[p],toolResults:t,isStreaming:!0});u=u.concat(r.processBlocks),o.answerBlocks.length>0&&(g=th(e,o.answerBlocks,{omitUsage:!0}))}if(o){let e=q.streamingMessage,o=tr(e,{isStreaming:!0}),r=ta(e,{messageIndex:U.length,toolResults:t,isStreaming:!0});u=u.concat(r.processBlocks),o.answerBlocks.length>0&&(g=th(e,o.answerBlocks,{omitUsage:!0}))}if(u.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=>{os.current[t]=e},children:(0,r.jsx)(nw,{blocks:u,isStreaming:V||q.isStreaming,cwd:oa,onOpenFile:m,sessionId:e?.id??eB.current??void 0,tokenRate:eu})},`live-process-group-${s}`),t)}g&&d((0,r.jsx)(rd,{message:g,isStreaming:!0,modelNames:G,cwd:oa,onOpenFile:m,onQuoteReply:L},`live-answer-${s}`),p>=0?n.get(p):void 0);continue}if(-1===p){for(let e=s;e<l;e++)d(i(e),n.get(e));continue}d(i(s),n.get(s));let{processBlocks:u,finalAnswerMessage:g,writtenFiles:h,visibleProcessIndices:x}=a;if(u.length>0){let t=x.map(e=>n.get(e)).find(e=>"number"==typeof e)??(g?void 0:n.get(p));d((0,r.jsx)("div",{ref:void 0===t?void 0:e=>{os.current[t]=e},children:(0,r.jsx)(nw,{blocks:u,isStreaming:!1,defaultExpanded:!g,onAutoExpanded:void 0,cwd:oa,onOpenFile:m,sessionId:e?.id??eB.current??void 0})},`process-group-${s}-${p}`),t)}g&&d(i(p,{messageOverride:g,writtenFiles:h}),n.get(p));for(let e=p+1;e<l;e++)d(i(e),n.get(e))}let c=[];return l.forEach((e,t)=>{void 0!==e&&(c[e]=t)}),t2.current=c,(0,r.jsx)(s8,{scrollElementRef:e_,items:a,virtualizerRef:t1})})(),om&&(ea||V&&!q.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:[om,eC?.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"}})]})}),J&&(0,r.jsx)(rd,{message:{role:"bashExecution",command:J.command,output:"",excludeFromContext:J.excludeFromContext},sessionId:e?.id??eB.current??void 0}),K&&!J&&(0,r.jsx)("div",{className:"py-2 text-[13px] text-text-muted",children:(0,r.jsx)("span",{className:"animate-[pulse_1.5s_infinite]",children:E("desktop.runningShellCommand")})}),(0,r.jsx)("div",{style:{height:96}}),(0,r.jsx)("div",{ref:eU}),(0,r.jsx)(rM,{open:tA,planText:tO,busy:V,onExecute:tU,onFeedback:tq,onExit:tV,onClose:()=>tL(!1)})]})})}),tK&&(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"}),tG&&(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"}),tX&&(0,r.jsxs)("button",{type:"button",onClick:()=>t0(),title:E("desktop.scrollToBottom"),"aria-label":E("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)(o6.Z,{size:12,weight:"bold","aria-hidden":"true"}),E("desktop.scrollToBottom")]})]}),M?null:(0,r.jsx)(ie,{messages:U,streamingMessage:q.streamingMessage,scrollContainer:e_,messageRefs:os,virtualizer:t4})]}),(0,r.jsxs)("div",{className:"relative z-10",children:[(0,r.jsx)("div",{style:{padding:"0 16px",paddingRight:M?16:34},children:(0,r.jsx)("div",{style:{maxWidth:820,margin:"0 auto"},children:(0,r.jsx)(iC,{widgets:of})})}),oh,(0,r.jsx)("div",{className:`session-info-bar-wrap${M?" is-mobile":""}`,children:(0,r.jsx)("div",{className:"session-info-bar-inner",children:(0,r.jsx)(s5,{onViewFullHistory:v,cwd:oa,systemPrompt:y,sessionStats:ep,contextUsage:es,hasSession:!!e,showChat:!0,soundEnabled:T,onSoundToggle:R,onCompact:e?e1:void 0,onAbortCompaction:e5,isCompacting:ea,compactError:el,branchTree:eL,branchActiveLeafId:eO,onBranchLeafChange:eH,isDeepSeekOfficial:tW,deepseekBalance:tP,lastTurnUsage:tN})})})]})]})]})}function iS({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 iC({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 iT({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 iR({request:e,onRespond:t}){let{t:o}=(0,D.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 iz({request:e,onInput:t}){let{t:o}=(0,D.s)(),s=(0,n.useRef)(null),i=function(e){let t=/^[┌├└╭╰][─┬┴┼]+[┐┤┘╮╯]$/,o=[];for(let r of e){let e=e8(r).trimEnd();if(t.test(e))continue;let n=r,s=te(n);("│"===s||"┃"===s)&&" "===te(n=e9(n,0))&&(n=e9(n,0));let i=function(e){let t=e7(e);for(let e=t.length-1;e>=0;e--)if(""!==t[e].char.trim())return e;return -1}(n),a=i>=0?e7(n)[i]?.char:void 0;("│"===a||"┃"===a)&&(n=e9(n,i)),o.push(function(e){let t=e;for(;;){let e=e7(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&&""===e8(o[0]).trim();)o.shift();for(;o.length>0&&""===e8(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(e6.lastIndex=0;null!==(t=e6.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=e5[r-30];else if(r>=90&&r<=97)o.color=e3[r-90];else if(r>=40&&r<=47)o.backgroundColor=e5[r-40];else if(r>=100&&r<=107)o.backgroundColor=e3[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 e5[e];if(e>=8&&e<16)return e3[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 iI={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"},iM={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 iE(e){return(e.replace(/\\/g,"/").split("/").pop()??"").toLowerCase().split(".").pop()??""}function iP(e){let t=e.nodeType===Node.ELEMENT_NODE?e:e.parentElement;return t?.closest(".file-source-line[data-line-number]")??null}function iD(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(iP(o.startContainer)?.dataset.lineNumber),n=Number(iP(o.endContainer)?.dataset.lineNumber);return Number.isInteger(r)&&Number.isInteger(n)?r<=n?{startLine:r,endLine:n}:{startLine:n,endLine:r}:null}function iF(e,t,o,r={}){let n=en(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 iW({filePath:e,sourceSessionId:t}){let{t:o}=(0,D.s)();return(0,r.jsx)("a",{href:iF(e,"download",t),download:es(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)(I.z,{size:11,"aria-hidden":"true"})})}let i$={delete:"3px solid var(--git-status-deleted)",add:"3px solid var(--git-status-added)",edit:"3px solid var(--git-status-modified)"},iN="var(--git-status-deleted-bg)",iA="var(--git-status-added-bg)",iL="var(--git-status-added)";function iO(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KB`:`${(e/1048576).toFixed(1)} MB`}function iH({oldContent:e,newContent:t}){let{t:o}=(0,D.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?iN:"added"===e.kind?iA:"transparent",o=e.block?i$[e.block]:"3px solid transparent",n="added"===e.kind?iL:"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 iB({patch:e}){let t=oX(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?iN:"added"===e.kind?iA:"transparent",o=e.block?i$[e.block]:"3px solid transparent",n="added"===e.kind?iL:"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 iU({filePath:e,cwd:t,sourceSessionId:o}){let{t:s}=(0,D.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),x=es(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(iF(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 f=iF(e,"read",o,i?{v:i}:void 0),m=null!=l?iO(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:ei(e,t)}),(0,r.jsx)("span",{style:{marginLeft:"auto"},children:x||s("desktop.image")}),c&&(0,r.jsxs)("span",{children:[c.w," \xd7 ",c.h]}),m&&(0,r.jsx)("span",{children:m}),(0,r.jsx)(iW,{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:f,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 i_({filePath:e,cwd:t,sourceSessionId:o}){let{t:s}=(0,D.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),x=es(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(iF(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 f=iF(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:ei(e,t)}),(0,r.jsx)("span",{style:{marginLeft:"auto"},children:x||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:iO(l)}),(0,r.jsx)(iW,{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:f,onLoadedMetadata:e=>p(e.currentTarget.duration),onError:()=>g(s("desktop.failedToLoadAudio")),style:{width:"100%"}},f)]})})]})}function iq({filePath:e,cwd:t,sourceSessionId:o}){let{t:s}=(0,D.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=iE(e),h="pdf"===g,x=h?iF(e,"read",o,i?{v:i}:void 0):iF(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(iF(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(iF(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:ei(e,t)}),(0,r.jsx)("span",{style:{marginLeft:"auto"},children:"docx"===g?s("desktop.docxPreview"):"pdf"}),null!=l&&(0,r.jsx)("span",{children:iO(l)}),(0,r.jsx)(iW,{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:x,sandbox:h?void 0:"allow-same-origin",title:s("desktop.previewFile",{file:es(e)}),style:{width:"100%",height:"100%",border:"none",background:h?"var(--bg)":"#eef1f5"}},x)})]})}function iV({filePath:e,cwd:t,sourceSessionId:o,onOpenFile:n,onAtMention:s,onMentionLines:i,initialDisplayMode:a}){let l;return null!==(iI[iE(e)]??null)?(0,r.jsx)(iU,{filePath:e,cwd:t,sourceSessionId:o}):null!==(iM[iE(e)]??null)?(0,r.jsx)(i_,{filePath:e,cwd:t,sourceSessionId:o}):null!==("pdf"===(l=iE(e))||"docx"===l?l:null)?(0,r.jsx)(iq,{filePath:e,cwd:t,sourceSessionId:o}):(0,r.jsx)(iK,{filePath:e,cwd:t,sourceSessionId:o,onOpenFile:n,onAtMention:s,onMentionLines:i,initialDisplayMode:a})}function iK({filePath:e,cwd:t,sourceSessionId:o,onOpenFile:s,onAtMention:i,onMentionLines:a,initialDisplayMode:l}){let d,c,{t:p}=(0,D.s)(),[u,g]=(0,n.useState)(null),[h,x]=(0,n.useState)(null),[f,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,E]=(0,n.useState)(null),P=(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(iF(e,"read",o)).then(e=>e.json()).then(e=>e.error?(b(e.error),null):(t?(g(t=>(t&&x(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),x(null),m(null),j(!1),C("source"),R(!1),I(0),P.current&&(P.current.close(),P.current=null),$(e).then(e=>{(e?.language==="markdown"||e?.language==="html")&&"diff"!==l&&j(!0)}).finally(()=>v(!1)),W(e);let t=new EventSource(iF(e,"watch",o));return P.current=t,t.addEventListener("change",()=>{$(e,!0),W(e)}),()=>{t.close(),P.current=null}},[e,$,W,l,o]);let N=(0,n.useMemo)(()=>ob(u?.content??""),[u?.content]),A=f?.supported===!0&&"string"==typeof f.patch;(0,n.useEffect)(()=>{"diff"===l&&A&&C("diff")},[A,l]);let L=A&&f?.status==="deleted",O=(0,n.useCallback)(o=>{a&&o&&a(ei(e,t),o.startLine,o.endLine)},[t,e,a]);if((0,n.useEffect)(()=>{let e=()=>{let e=F.current,t="source"===S&&!w;E(a&&t&&e?iD(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?iD(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(L&&!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:ei(e,t)}),(0,r.jsx)("div",{style:{flex:1,overflow:"auto",background:"var(--bg)"},children:(0,r.jsx)(iB,{patch:f.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=er(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||A;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:ei(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:iO(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?.(ei(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)(iW,{filePath:e,sourceSessionId:o})]}),(0,r.jsx)("div",{ref:F,style:{flex:1,overflow:"auto",background:"var(--bg)"},children:"diff"===S&&q?A?(0,r.jsx)(iB,{patch:f.patch}):(0,r.jsx)(iH,{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)(tf.oz,{remarkPlugins:oS,rehypePlugins:oC,components:{h1:({children:e})=>(0,r.jsx)("h1",{id:oy(e),children:e}),h2:({children:e})=>(0,r.jsx)("h2",{id:oy(e),children:e}),h3:({children:e})=>(0,r.jsx)("h3",{id:oy(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)(oH,{code:s.replace(/\n$/,"")}):(0,r.jsx)(o_,{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?tu(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)(tm.A,{language:"text"===u.language?"plaintext":u.language,style:oT,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 iJ={running:"var(--accent)",completed:"#22c55e",failed:"#ef4444",stopped:"#d97706"},iG={running:"desktop.subagentsStatusRunning",completed:"desktop.subagentsStatusCompleted",failed:"desktop.subagentsStatusFailed",stopped:"desktop.subagentsStatusStopped"};function iY({agent:e,selected:t,onSelect:o}){let[s,i]=(0,n.useState)(!1),{t:a}=(0,D.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=iJ[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(iG[e.status])})]})}function iX({subagents:e,onSelect:t,selectedId:o}){let{t:s}=(0,D.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)(v.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)(iY,{agent:e,selected:e.id===o,onSelect:t},e.id))})]})}let iZ={user:{color:"var(--accent)"},assistant:{color:"var(--text)"},toolResult:{color:"var(--text-dim)"},bashExecution:{color:"var(--text-muted)"}};function iQ({line:e,roleLabel:t}){let o=iZ[e.role]??iZ.toolResult;return(0,r.jsxs)("div",{style:{marginBottom:6},children:[(0,r.jsxs)("div",{style:{fontSize:10.5,fontWeight:600,color:o.color,marginBottom:2,fontFamily:"var(--font-mono)"},children:["[",t(e.role),"]"]}),(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 i0({agent:e,cwd:t,onBack:o}){let{t:s}=(0,D.s)(),a=e=>s("user"===e?"desktop.transcriptRoleUser":"assistant"===e?"desktop.transcriptRoleAssistant":"toolResult"===e?"desktop.transcriptRoleResult":"desktop.transcriptRoleBash"),[l,d]=(0,n.useState)([]),[c,p]=(0,n.useState)(!0),[u,g]=(0,n.useState)(null),h=(0,n.useRef)(null),x=(0,n.useRef)(!0),f=(0,n.useCallback)(async(o=!1)=>{if(e.id&&t){o||p(!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||g(s.error??`HTTP ${n.status}`);return}d(s.lines??[]),g(null)}catch(e){o||g(e instanceof Error?e.message:String(e))}finally{p(!1)}}},[e.id,t]);(0,n.useEffect)(()=>{f()},[f]);let m=(0,n.useRef)(e.status);(0,n.useEffect)(()=>{let t="running"===m.current;m.current=e.status,t&&"running"!==e.status&&f(!0)},[e.status]),(0,n.useEffect)(()=>{if("running"!==e.status)return;let t=setInterval(()=>void f(!0),2e3);return()=>clearInterval(t)},[e.status,f]),(0,n.useEffect)(()=>{let e=h.current;e&&x.current&&(e.scrollTop=e.scrollHeight)},[l]);let k=e.completedAt?e.completedAt-e.startedAt:void 0,v=e.tokens?.total??e.tokens?.input??e.tokens?.output,y="completed"===e.status?"#22c55e":"failed"===e.status?"#ef4444":"stopped"===e.status?"#d97706":"var(--accent)";return(0,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)(i.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:y,boxShadow:"running"===e.status?`0 0 0 0 ${y}`:"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!==v&&v>0&&(0,r.jsxs)("span",{children:[void 0===v?"":v>=1e6?`${(v/1e6).toFixed(1)}M`:v>=1e3?`${(v/1e3).toFixed(1)}k`:`${v}`," tokens"]}),void 0!==k&&(0,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`}(k)}),(0,r.jsx)("span",{style:{color:y},children:s(`desktop.subagentsStatus${"running"===e.status?"Running":"completed"===e.status?"Completed":"failed"===e.status?"Failed":"Stopped"}`)})]})]}),(0,r.jsx)("div",{ref:h,onScroll:e=>{let t=e.currentTarget;x.current=t.scrollHeight-t.scrollTop-t.clientHeight<40},style:{flex:1,minHeight:0,overflowY:"auto",overflowX:"hidden",padding:"8px 10px",background:"var(--bg)"},children:c?(0,r.jsxs)("div",{style:{fontSize:12,color:"var(--text-dim)",padding:"12px 4px"},children:[s("desktop.loading"),"…"]}):u?(0,r.jsx)("div",{style:{fontSize:12,color:"#ef4444",padding:"12px 4px"},children:u}):0===l.length?(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-dim)",padding:"12px 4px"},children:"running"===e.status?s("desktop.subagentsWaitingFirstMessage"):s("desktop.subagentsNoTranscript")}):(0,r.jsx)("div",{style:{paddingBottom:8},children:l.map((e,t)=>(0,r.jsx)(iQ,{line:e,roleLabel:a},t))})})]})}function i1({tabs:e,activeTabId:t,onSelectTab:o,onCloseTab:s}){let{t:i}=(0,D.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:eo(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)(p.X,{size:11,"aria-hidden":"true"})})]},e.id)})})}var i2=o(27289),i4=o(93534),i6=o(45781),i5=o(68731),i3=o(93912),i8=o(23675),i7=o(48716),i9=o(47013),ae=o(51265);let at={"restore-script":"restore","generate-cmd":"cmd",keep:"keep","keep-with-warning":"warning",manual:"manual"};function ao({cwd:e}){let{t}=(0,D.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),[x,f]=(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)(""),[E,P]=(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),f(new Set(n.preview.categories)),k(new Set),y(!1)}catch{w(String(t("desktop.backupImportFailed")))}}},[t]),A=(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:[...x],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,x,m,v,t]),L=(0,n.useCallback)(async o=>{if(o.installPrompt&&e){P(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{P(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)(i9.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)(ae._,{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:x.has(e),onChange:t=>{let o=new Set(x);t.target.checked?o.add(e):o.delete(e),f(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:at[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:E===o.name,onClick:()=>L(o),style:{padding:"4px 10px",fontSize:11,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:4,color:"var(--text)",cursor:E===o.name?"wait":"pointer"},children:E===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:A,disabled:j||0===x.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===x.size?.5:1},children:[(0,r.jsx)(ae._,{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)(o7.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)(V.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 ar={position:"relative",width:40,height:22,borderRadius:11,border:"none",cursor:"pointer",padding:0,flexShrink:0,transition:"background 0.18s ease",outline:"none"},an={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 as({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:{...ar,background:e?"var(--accent)":"color-mix(in srgb, var(--border) 70%, var(--bg))"},children:(0,r.jsx)("span",{style:{...an,left:e?21:3}})})]})}function ai({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 aa="pi-input-shortcut";function al(){try{let e=localStorage.getItem(aa);return"ctrl-enter"===e?"ctrl-enter":"enter"}catch{return"enter"}}function ad(){let{t:e}=(0,D.s)(),[t,o]=(0,n.useState)(al);(0,n.useEffect)(()=>{let e=()=>o(al());return window.addEventListener("storage",e),()=>window.removeEventListener("storage",e)},[]);let s=(0,n.useCallback)(e=>{o(e);try{localStorage.setItem(aa,e),window.dispatchEvent(new StorageEvent("storage",{key:aa,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)(ai,{title:e("desktop.inputShortcut"),description:e("desktop.inputShortcutDescription"),children:(0,r.jsx)(as,{checked:"ctrl-enter"===t,onChange:e=>s(e?"ctrl-enter":"enter"),label:e("desktop.useCtrlEnter"),description:e("desktop.useCtrlEnterDescription")})})]})}var ac=o(95650),ap=o(55803),au=o(23602),ag=o(18613),ah=o(12779);let ax={display:"flex",gap:6,flexWrap:"wrap"};function af(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 am({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 ak={display:"inline-flex",alignItems:"center",gap:6,padding:0,border:0,background:"transparent",color:"var(--accent)",fontSize:11,cursor:"pointer",whiteSpace:"nowrap"},av={onMouseEnter:e=>{e.currentTarget.style.textDecoration="underline"},onMouseLeave:e=>{e.currentTarget.style.textDecoration="none"}};function ay({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 ab({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 aw({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 aj(){let{mode:e,resolvedMode:t,themeName:o,setMode:s,setTheme:i,previewTheme:a,clearPreview:l,isThemeCached:d,borderDepth:c,setBorderDepth:p}=oc(),{locale:u,setLocale:g,t:h}=(0,D.s)(),[x,f]=(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&&f(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)(ay,{title:h("desktop.theme"),description:h("desktop.themeDescription"),children:[(0,r.jsx)(am,{icon:(0,r.jsx)(ac.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:ak,...av,children:[(0,r.jsx)(ap.N,{size:12,weight:"regular","aria-hidden":"true"}),h("desktop.openThemeFolder")]}),(0,r.jsxs)("button",{type:"button",onClick:z,style:ak,...av,children:[(0,r.jsx)(au.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:ax,children:[(0,r.jsx)("button",{type:"button",onClick:()=>j(""),disabled:null!==v,style:af(""===o,"__default__"===b,null!==v),onMouseEnter:()=>C(""),onMouseLeave:()=>C(null),children:h("desktop.defaultTheme")}),x.map(e=>(0,r.jsxs)("button",{type:"button",onClick:()=>j(e.name),disabled:null!==v,style:af(o===e.name,b===e.name,v===e.name),onMouseEnter:()=>C(e.name),onMouseLeave:()=>C(null),children:[e.displayName,(0,r.jsx)(aw,{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)(am,{icon:(0,r.jsx)(ab,{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)(am,{icon:"dark"===t?(0,r.jsx)(ag.A,{size:14,weight:"fill"}):(0,r.jsx)(ah.b,{size:14,weight:"fill"}),label:h("desktop.appearanceMode")}),(0,r.jsx)("div",{style:ax,children:[{value:"light",icon:(0,r.jsx)(ah.b,{size:15,weight:"light"===e?"fill":"regular"})},{value:"dark",icon:(0,r.jsx)(ag.A,{size:15,weight:"dark"===e?"fill":"regular"})},{value:"system",icon:(0,r.jsx)(i4.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:af(o,b===`mode:${t.value}`),onMouseEnter:()=>w(`mode:${t.value}`),onMouseLeave:()=>w(null),children:[t.icon,h(`desktop.${t.value}`)]},t.value)})})]}),!m&&0===x.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)(ay,{title:h("desktop.language"),description:h("desktop.languageDescription"),children:(0,r.jsx)("div",{style:ax,children:["en","zh-CN"].map(e=>(0,r.jsx)("button",{type:"button",onClick:()=>g("zh-CN"===e?"zh-CN":"en"),style:af("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 aS=o(94638);function aC({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 aT({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 aR({children:e}){return(0,r.jsx)("div",{style:{padding:"0 14px"},children:e})}function az({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 aI=[{value:"normal",labelKey:"modes.collabNormal"},{value:"plan",labelKey:"modes.collabPlan"},{value:"goal",labelKey:"modes.collabGoal"}],aM=[{value:"economy",labelKey:"modes.tokenEconomy"},{value:"full",labelKey:"modes.tokenFull"},{value:"delivery",labelKey:"modes.tokenDelivery"}],aE=[{value:"ask",labelKey:"modes.approvalAsk"},{value:"auto",labelKey:"modes.approvalAuto"},{value:"yolo",labelKey:"modes.approvalYolo"}];function aP({options:e,value:t,onChange:o,disabled:n,accentFor:s}){let{t:i}=(0,D.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 aD(){let{t:e}=(0,D.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:eM(e.collaborationMode),tokenMode:eE(e.tokenMode),toolApprovalMode:eP(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:eM(e.modes?.collaborationMode??t.collaborationMode),tokenMode:eE(e.modes?.tokenMode??t.tokenMode),toolApprovalMode:eP(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)(aC,{children:(0,r.jsx)(aR,{children:(0,r.jsx)(as,{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)(aS.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)(aC,{children:[(0,r.jsx)(aT,{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)(aP,{options:aI,value:s.collaborationMode,onChange:e=>void u({collaborationMode:e}),disabled:d})]})}),(0,r.jsx)(aT,{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)(aP,{options:aM,value:s.tokenMode,onChange:e=>void u({tokenMode:e}),disabled:d})]})}),(0,r.jsx)(aR,{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)(aP,{options:aE,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)(az,{children:e("desktop.featuresDesc")}),d&&(0,r.jsx)("div",{style:{padding:"0 2px",fontSize:11,color:"var(--text-muted)"},children:e("desktop.featuresSaving")})]})})}var aF=o(76553);function aW({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 a$({onSessionsChanged:e}){let{t}=(0,D.s)(),o=A(),[s,i]=(0,n.useState)(null),[a,l]=(0,n.useState)([]),[d,c]=(0,n.useState)([]),[u,g]=(0,n.useState)(new Set),[h,x]=(0,n.useState)(null),[f,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),[z,M]=(0,n.useState)(!1),E=(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&&(c(t.reasonix.projects),i("reasonix"))}catch(e){R(e instanceof Error?e.message:String(e))}finally{C(!1)}},[]),[P,F]=(0,n.useState)(!1);(0,n.useEffect)(()=>{P||(F(!0),E())},[P,E]);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}`);x(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 $=(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(f.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)(rz.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:f.imported})??`成功导入 ${f.imported} 个会话`,f.skipped>0&&(0,r.jsx)("span",{style:{marginLeft:8},children:t("desktop.importSkippedCount",{skipped:f.skipped})??`,${f.skipped} 个跳过`}),f.errors>0&&(0,r.jsx)("span",{style:{marginLeft:8,color:"#ef4444"},children:t("desktop.importErrorsCount",{errors:f.errors})??`,${f.errors} 个失败`})]}),y?(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,fontSize:12,color:"var(--text-muted)"},children:[(0,r.jsx)(_.y,{size:14,style:{animation:"spin 1s linear infinite"}}),t("desktop.importGeneratingTitles")??"正在生成标题…"," ","(",w.done,"/",w.total,")"]}):(0,r.jsxs)("button",{type:"button",onClick:$,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)(aF.o,{size:15}),t("desktop.importGenerateTitles")??"为导入的会话生成标题"]}),(0,r.jsx)("button",{type:"button",onClick:()=>{x(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 N=(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)(V.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:aN,children:t("desktop.importSelectAll")??"全选"}),(0,r.jsx)("button",{type:"button",onClick:()=>g(new Set),style:aN,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)(_.y,{size:14,style:{animation:"spin 1s linear infinite"}})," ",t("desktop.importing")??"导入中…"]}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(I.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&&!f.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)(_.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:`${f.total>0?(f.imported+f.skipped+f.errors)/f.total*100:0}%`,transition:"width 0.3s ease"}})}),(0,r.jsxs)("div",{style:{fontSize:11,color:"var(--text-dim)"},children:[f.imported+f.skipped+f.errors," / ",f.total,f.skipped>0&&` \xb7 ${t("desktop.importSkippedCount",{skipped:f.skipped})??`${f.skipped} 跳过`}`]})]})]});return o?(0,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)(I.z,{size:16}),(0,r.jsx)("span",{style:{fontWeight:500},children:t("desktop.importSessions")??"导入会话"})]}),(0,r.jsxs)(aW,{open:z,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:aA,children:(0,r.jsx)(p.X,{size:18})})]}),N]})]}):N}let aN={background:"none",border:"none",color:"var(--accent)",fontSize:11,cursor:"pointer",padding:"2px 4px"},aA={background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",padding:4,display:"flex"},aL="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 aH(){return{fontSize:12,color:"var(--text-muted)"}}let aB={padding:"7px 12px",border:"none",borderRadius:6,background:"var(--accent)",color:"#fff",cursor:"pointer",fontSize:12};function aU({sessionId:e}){let{t}=(0,D.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,x]=(0,n.useState)({}),[f,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,E]=(0,n.useState)({provider:"custom",baseUrl:"",apiKey:"",model:"",maxTokens:4096,hasApiKey:!1}),[P,F]=(0,n.useState)(""),[W,$]=(0,n.useState)(""),[N,A]=(0,n.useState)(!1),[L,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;x(r.mcpServers??{}),m(r.filePath);let i=(r.mcpServers??{})[aL];v(i?.command??""),b(i?.lifecycle==="lazy"?"lazy":"eager"),E({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[aL],t={...h,[aL]:{...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}`);x(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[aL];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}`);x(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()=>{A(!0),O(null),B(!1);try{let e=await fetch("/api/vision-config",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({...M,...P?{apiKey:P}:{}})}),t=await e.json();if(!e.ok||t.error)throw Error(t.error??`HTTP ${e.status}`);E({...t,apiKey:"",hasApiKey:t.hasApiKey}),F(""),B(!0)}catch(e){O(e instanceof Error?e.message:String(e))}finally{A(!1)}},[M,P]),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:aL})}),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[aL];return(0,r.jsxs)(aC,{children:[(0,r.jsx)(aT,{children:(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:7,padding:"12px 0"},children:[(0,r.jsx)(nW.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)(aR,{children:(0,r.jsx)("div",{style:{padding:"8px 0",fontSize:12,color:"#ef4444"},children:i})}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(aT,{children:(0,r.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)",padding:"10px 0 2px"},children:t("desktop.mcpVisionRegistration")})}),(0,r.jsx)(aT,{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:aH(),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:aH(),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:aH(),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)(aT,{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:{...aB,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)(aT,{children:(0,r.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)",padding:"10px 0 2px"},children:t("desktop.mcpVisionModelConfig")})}),(0,r.jsx)(aT,{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:aH(),children:t("desktop.mcpVisionProvider")}),(0,r.jsx)("input",{value:M.provider,onChange:e=>E(t=>({...t,provider:e.target.value})),style:aO}),(0,r.jsx)("span",{style:aH(),children:t("desktop.mcpVisionBaseUrl")}),(0,r.jsx)("input",{value:M.baseUrl,onChange:e=>E(t=>({...t,baseUrl:e.target.value})),style:aO}),(0,r.jsx)("span",{style:aH(),children:t("desktop.mcpVisionApiKey")}),(0,r.jsx)("input",{type:"password",value:P,onChange:e=>F(e.target.value),placeholder:M.hasApiKey?"••••••••":"API key",style:aO}),(0,r.jsx)("span",{style:aH(),children:t("desktop.mcpVisionModel")}),(0,r.jsx)("input",{value:M.model,onChange:e=>E(t=>({...t,model:e.target.value})),style:aO}),(0,r.jsx)("span",{style:aH(),children:t("desktop.mcpVisionMaxTokens")}),(0,r.jsx)("input",{type:"number",min:1,value:M.maxTokens,onChange:e=>E(t=>({...t,maxTokens:Number(e.target.value)||1})),style:aO})]})}),(0,r.jsx)(aR,{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:{...aB,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")}),L&&(0,r.jsx)("span",{style:{color:"#ef4444",fontSize:12},children:L}),c&&(0,r.jsx)("span",{style:{color:"#ef4444",fontSize:12},children:c})]}),(0,r.jsxs)(az,{children:[t("desktop.mcpVisionModelNote"),W&&(0,r.jsx)("div",{style:{marginTop:4,fontFamily:"var(--font-mono)",fontSize:10},children:W}),f&&(0,r.jsx)("div",{style:{fontFamily:"var(--font-mono)",fontSize:10},children:f})]})]})})]}):(0,r.jsx)(aR,{children:(0,r.jsx)("div",{style:{padding:"8px 0",fontSize:12,color:"var(--text-muted)"},children:t("desktop.loading")})})]})}function a_({sessionId:e,onApplied:t}){let{t:o}=(0,D.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 io(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 aq=["stdio","sse","http"],aV=["eager","lazy"],aK={name:"",command:"",args:"",transport:"stdio",lifecycle:"eager",requestTimeoutMs:"",env:""},aJ={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 aG(){return{fontSize:12,color:"var(--text-muted)"}}function aY(e,t){return{fontSize:10,padding:"1px 6px",borderRadius:3,background:t,color:e,flexShrink:0,textTransform:"capitalize"}}function aX({sessionId:e}){let{t}=(0,D.s)(),[o,s]=(0,n.useState)({}),[i,a]=(0,n.useState)(""),[l,d]=(0,n.useState)(!1),[c,p]=(0,n.useState)(null),[u,g]=(0,n.useState)(null),[x,f]=(0,n.useState)(aK),[k,v]=(0,n.useState)(!1),[y,b]=(0,n.useState)(null),[w,j]=(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)(()=>{f(aK),g({name:"",isNew:!0}),b(null),j(!1)},[]),R=(0,n.useCallback)((e,t)=>{f({name:e,command:t.command??"",args:Array.isArray(t.args)?t.args.join("\n"):"",transport:"string"==typeof t.transport?t.transport:"stdio",lifecycle:"string"==typeof t.lifecycle?t.lifecycle:"eager",requestTimeoutMs:"number"==typeof t.requestTimeoutMs?String(t.requestTimeoutMs):"",env:void 0!==t.env?JSON.stringify(t.env,null,2):""}),g({name:e,isNew:!1}),b(null),j(!1)},[]),z=(0,n.useCallback)(async()=>{if(u){v(!0),b(null),j(!1);try{let e=x.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===aL)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:aq.includes(e.transport)?e.transport:"stdio",lifecycle:aV.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}}(x);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[x.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),g(null),j(!0)}catch(e){b(e instanceof Error?e.message:String(e))}finally{v(!1)}}},[u,x,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),j(!0)}catch(e){b(e instanceof Error?e.message:String(e))}finally{v(!1)}},[o]),M=(0,n.useCallback)((e,t)=>{f(o=>({...o,[e]:t}))},[]),E=Object.entries(o).filter(([e])=>e!==aL);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)(a_,{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)(m.c,{size:13,"aria-hidden":"true"}),t("desktop.mcpAddServer")]})]})]}),(0,r.jsx)(az,{children:t("desktop.mcpRestartNote")}),(0,r.jsx)(aU,{sessionId:e}),0!==E.length||u?E.map(([e,o])=>(0,r.jsx)(aC,{children:(0,r.jsx)(aR,{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:aY("var(--accent)","rgba(37,99,235,0.12)"),children:o.transport??"stdio"}),(0,r.jsx)("span",{style:aY("#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)(h.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)(S.l,{size:12,"aria-hidden":"true"})})]})]})})},e)):(0,r.jsx)(aC,{children:(0,r.jsx)(aR,{children:(0,r.jsx)("div",{style:{padding:"14px 0",fontSize:12,color:"var(--text-dim)"},children:o[aL]?t("desktop.mcpEmptyOther"):t("desktop.mcpEmpty")})})}),u&&(0,r.jsxs)(aC,{children:[(0,r.jsx)(aT,{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)(aT,{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:aG(),children:t("desktop.mcpServerName")}),(0,r.jsx)("input",{value:x.name,onChange:e=>M("name",e.target.value),disabled:!u.isNew,placeholder:"my-server",style:{...aJ,opacity:u.isNew?1:.5}}),(0,r.jsxs)("span",{style:aG(),children:[t("desktop.mcpCommand")," *"]}),(0,r.jsx)("input",{value:x.command,onChange:e=>M("command",e.target.value),placeholder:"npx @modelcontextprotocol/server-foo",style:aJ}),(0,r.jsx)("span",{style:aG(),children:t("desktop.mcpArgs")}),(0,r.jsx)("textarea",{value:x.args,onChange:e=>M("args",e.target.value),placeholder:"--port 3000\n--verbose",rows:3,style:{...aJ,resize:"vertical",lineHeight:1.5}}),(0,r.jsx)("span",{style:aG(),children:t("desktop.mcpTransport")}),(0,r.jsx)("select",{value:x.transport,onChange:e=>M("transport",e.target.value),style:{...aJ,fontFamily:"var(--font-mono)"},children:aq.map(e=>(0,r.jsx)("option",{value:e,children:e},e))}),(0,r.jsx)("span",{style:aG(),children:t("desktop.mcpLifecycle")}),(0,r.jsx)("select",{value:x.lifecycle,onChange:e=>M("lifecycle",e.target.value),style:{...aJ,fontFamily:"var(--font-mono)"},children:aV.map(e=>(0,r.jsx)("option",{value:e,children:e},e))}),(0,r.jsx)("span",{style:aG(),children:t("desktop.mcpRequestTimeoutMs")}),(0,r.jsx)("input",{type:"number",min:1,value:x.requestTimeoutMs,onChange:e=>M("requestTimeoutMs",e.target.value),placeholder:"300000",style:aJ}),(0,r.jsx)("span",{style:aG(),children:t("desktop.mcpEnv")}),(0,r.jsx)("textarea",{value:x.env,onChange:e=>M("env",e.target.value),placeholder:'{\n "API_KEY": "..."\n}',rows:3,style:{...aJ,resize:"vertical",lineHeight:1.5}})]})}),(0,r.jsx)(aR,{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:()=>g(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 aZ=o(9210);function aQ(){let{t:e}=(0,D.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 x=null!==t&&!s.some(e=>e.label===t),f=(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=>f(e.target.value),style:{flex:1,minWidth:200,maxWidth:420,padding:"6px 9px",fontSize:12,color:"var(--text)",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:5},children:[(0,r.jsx)("option",{value:"",children:e("desktop.titleModelFollowSession")}),x&&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}),x&&null!==t&&(0,r.jsxs)("p",{style:{margin:0,fontSize:11,color:"#ef4444",lineHeight:1.5},children:[t,"(",e("desktop.titleModelInvalid"),")"]})]})}let a0=["name","reasoning","contextWindow","maxTokens","thinkingLevelMap","hidden"];function a1(e){if(""===e.trim())return;let t=Number(e);return Number.isFinite(t)&&t>0?t:void 0}function a2(e){let t=a1(e.contextWindow??""),o=a1(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 a4({providerId:e,onRegisterFlush:t,onConfigChange:o}){let{t:s}=(0,D.s)(),i=A(),[a,l]=(0,n.useState)([]),[d,c]=(0,n.useState)({}),[p,u]=(0,n.useState)({}),[g,h]=(0,n.useState)(new Set),[x,f]=(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 f(!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||f(!1)}})(),()=>{t=!0}},[e]);let E=(0,n.useCallback)((e,t)=>{I.current+=1,c(o=>({...o,[e]:{...o[e]??{},...t}})),h(t=>new Set(t).add(e))},[]),P=(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]=a2(t)),o&&(i[e.id]=a2(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 a0){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,P)??void 0},[t,e,P]),x)?(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=>E(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=>E(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=>E(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=>E(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=>E(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)(ll,{value:t.thinkingLevelMap,onChange:t=>E(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:()=>{P().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 a6=["openai-completions","openai-responses","anthropic-messages","google-generative-ai","mistral-conversations"],a5="__custom__";function a3(){let{t:e}=(0,D.s)();return(0,n.useCallback)((t,o)=>e(t,o),[e])}function a8({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 a7={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 a9({value:e,onChange:t,placeholder:o,mono:n,inputRef:s}){return(0,r.jsx)("input",{ref:s,value:e,onChange:e=>t(e.target.value),placeholder:o,style:{...a7,fontFamily:n?"var(--font-mono)":"inherit"}})}function le({value:e,onChange:t,placeholder:o,mono:s,onKeyDown:i,autoComplete:a="off",spellCheck:l=!1,style:d}){let c=a3(),[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:{...a7,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)(aZ.G,{size:15}):(0,r.jsx)(nW.b,{size:15})})]})}function lt({value:e,onChange:t,placeholder:o}){return(0,r.jsx)("input",{type:"number",value:e,onChange:e=>t(e.target.value),placeholder:o,style:a7})}function lo({value:e,onChange:t,options:o,required:n}){let s=a3();return(0,r.jsxs)("select",{value:e,onChange:e=>t(e.target.value),style:{...a7,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 lr({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 ln({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 ls({name:e,provider:t,onChange:o,onRename:s,onDelete:i,onAddModels:a,onAddModel:l}){let d=a3(),[c,p]=(0,n.useState)(e),[u,g]=(0,n.useState)({phase:"idle"}),[h,x]=(0,n.useState)(""),[f,m]=(0,n.useState)([]),k=(0,n.useRef)(0),v=(0,n.useRef)(null);(0,n.useEffect)(()=>p(e),[e]);let y=(e,r)=>o({...t,[e]:r});(0,n.useEffect)(()=>{t.api||o({...t,api:"openai-completions"})},[t.api]),(0,n.useEffect)(()=>{k.current+=1,g({phase:"idle"}),x(""),m([])},[e,t.baseUrl,t.api,t.apiKey]);let b=(0,n.useCallback)(async()=>{if(!t.baseUrl?.trim()||"loading"===u.phase)return;let o=++k.current;g({phase:"loading"}),m([]);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!==k.current)return;if(!r.ok||n.error||!n.models)return void g({phase:"error",message:n.error??`HTTP ${r.status}`});g({phase:"success",models:n.models,endpoint:n.endpoint??t.baseUrl})}catch(e){if(o!==k.current)return;g({phase:"error",message:e instanceof Error?e.message:String(e)})}},[u.phase,e,t]),w=new Set((t.models??[]).map(e=>e.id)),j="success"===u.phase?u.models:[],S=h.trim().toLocaleLowerCase(),C=j.filter(e=>!S||e.id.toLocaleLowerCase().includes(S)||e.name?.toLocaleLowerCase().includes(S)),T=C.slice(0,300),R=T.filter(e=>!w.has(e.id)).map(e=>e.id),z=f.filter(e=>!w.has(e)).length,I=R.length>0&&R.every(e=>f.includes(e)),M=!I&&R.some(e=>f.includes(e));return(0,n.useEffect)(()=>{v.current&&(v.current.indeterminate=M)},[M]),(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)(ln,{children:d("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:d("desktop.delete")})]}),(0,r.jsxs)(a8,{label:d("desktop.modelsProviderName"),children:[(0,r.jsx)(a9,{value:c,onChange:p,placeholder:"provider-name",mono:!0}),c!==e&&c.trim()&&(0,r.jsx)("button",{onClick:()=>s(c.trim()),style:{marginTop:4,padding:"3px 10px",background:"var(--accent)",border:"none",borderRadius:4,color:"#fff",cursor:"pointer",fontSize:11,alignSelf:"flex-start"},children:d("desktop.rename")})]}),(0,r.jsx)(a8,{label:d("desktop.modelsBaseUrl"),children:(0,r.jsx)(a9,{value:t.baseUrl??"",onChange:e=>y("baseUrl",e||void 0),placeholder:"http(s)://host:port/v1",mono:!0})}),(0,r.jsxs)(a8,{label:d("desktop.modelsApiKey"),children:[(0,r.jsx)(le,{value:t.apiKey??"",onChange:e=>y("apiKey",e||void 0),placeholder:d("desktop.modelsApiKeyPlaceholder"),mono:!0}),(0,r.jsx)("span",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:d("desktop.modelsApiKeyHelp")})]}),(0,r.jsx)(a8,{label:d("desktop.modelsApi"),children:(0,r.jsx)(lo,{value:t.api??"openai-completions",onChange:e=>y("api",e),options:a6,required:!0})}),(0,r.jsxs)("div",{style:{borderTop:"1px solid var(--border)",paddingTop:14,display:"flex",flexDirection:"column",gap:10},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:["success"!==u.phase&&(0,r.jsx)("button",{onClick:b,disabled:!t.baseUrl?.trim()||"loading"===u.phase,style:{height:30,padding:"0 12px",border:"1px solid var(--border)",borderRadius:5,background:"var(--bg-panel)",color:t.baseUrl?.trim()&&"loading"!==u.phase?"var(--text-muted)":"var(--text-dim)",cursor:t.baseUrl?.trim()&&"loading"!==u.phase?"pointer":"not-allowed",fontSize:11},children:"loading"===u.phase?d("desktop.modelsDiscoveryFetching"):d("desktop.modelsDiscoveryFetch")}),(0,r.jsx)("button",{onClick:l,title:d("desktop.modelsAddModelManual"),style:{height:30,padding:"0 12px",border:"none",borderRadius:5,background:"var(--accent)",color:"#fff",cursor:"pointer",fontSize:11,fontWeight:600},children:d("desktop.modelsAddModelManual")})]}),"error"===u.phase&&(0,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:u.message}),"success"===u.phase&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("input",{value:h,onChange:e=>x(e.target.value),placeholder:d("desktop.modelsDiscoveryFilterPlaceholder",{count:u.models.length}),"aria-label":d("desktop.modelsDiscoveryFilter"),style:{...a7,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:R.length?"pointer":"default",color:"var(--text-muted)",fontSize:10,fontWeight:600},children:[(0,r.jsx)("input",{ref:v,type:"checkbox",checked:I,disabled:0===R.length,onChange:()=>{let e=new Set(R);m(t=>I?t.filter(t=>!e.has(t)):Array.from(new Set([...t,...R])))},style:{width:13,height:13,accentColor:"var(--accent)",flexShrink:0}}),d("desktop.modelsDiscoverySelectShown")]}),0===T.length?(0,r.jsx)("div",{style:{padding:12,color:"var(--text-dim)",fontSize:11},children:d("desktop.modelsDiscoveryNoMatches")}):T.map((e,t)=>{let o=w.has(e.id),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 m(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:d("desktop.modelsDiscoveryAdded")})]},e.id)})]}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:10},children:[(0,r.jsx)("span",{title:u.endpoint,style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontSize:10},children:C.length>T.length?d("desktop.modelsDiscoveryShowing",{shown:T.length,total:C.length}):d("desktop.modelsDiscoveryFetched",{count:u.models.length})}),(0,r.jsx)("button",{onClick:()=>{if("success"!==u.phase)return;let e=new Set(f),t=u.models.filter(t=>e.has(t.id)&&!w.has(t.id));0!==t.length&&(a(t),m([]))},disabled:0===z,style:{height:28,padding:"0 11px",border:"none",borderRadius:5,background:z?"var(--accent)":"var(--bg-panel)",color:z?"#fff":"var(--text-dim)",cursor:z?"pointer":"not-allowed",fontSize:11,fontWeight:600,whiteSpace:"nowrap"},children:z?d("desktop.modelsDiscoveryAddSelectedCount",{count:z}):d("desktop.modelsDiscoveryAddSelected")})]})]})]})]})}let li=["off","minimal","low","medium","high","xhigh","max"],la={off:"var(--text-dim)",minimal:"var(--text-muted)",low:"#60a5fa",medium:"#a78bfa",high:"#f472b6",xhigh:"#fb923c",max:"#ef4444"};function ll({value:e,onChange:t}){let o=a3(),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:li.map(e=>{let t=n[e],i=e in n?null===t?"null":"string":"omit",a="string"==typeof t?t:"",l=la[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 ld={thinkingFormat:"deepseek",requiresReasoningContentOnAssistantMessages:!0};function lc({providerName:e,provider:t,model:o,onChange:s,onDelete:i}){let a=a3(),[l,d]=(0,n.useState)({phase:"idle"}),[c,p]=(0,n.useState)({phase:"idle"}),u=(0,n.useRef)(0),h=(0,n.useRef)(null),x=(e,t)=>s({...o,[e]:t}),f=(()=>{if("idle"===l.phase)return null;if("testing"===l.phase)return a("desktop.modelsTestingConnection");let e=[void 0!==l.latencyMs?`${l.latencyMs}ms`:null,void 0!==l.status?`HTTP ${l.status}`:null].filter(Boolean);return"success"===l.phase?[a("desktop.modelsConnected"),...e,l.responseText||null].filter(Boolean).join(" \xb7 "):[a("desktop.modelsFailed"),...e,l.message].filter(Boolean).join(" \xb7 ")})();(0,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)(()=>{u.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=++u.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!==u.current)return;if(!a.ok||l.error||!l.recommendation)return void p({phase:"error",message:l.error??`HTTP ${a.status}`});let d=function(e,t){let o={...e},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!==u.current)return;p({phase:"error",message:e instanceof Error?e.message:String(e)})}},[c.phase,o,s,t.baseUrl,e]),v=(()=>{if("success"!==c.phase)return null;let{recommendation:t,appliedCount:o}=c,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)(ln,{children:a("desktop.modelsModelSection")}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[f&&(0,r.jsx)("span",{title:f,style:{maxWidth:260,height:24,padding:"0 8px",border:`1px solid ${"error"===l.phase?"#fecaca":"success"===l.phase?"#bbf7d0":"var(--border)"}`,borderRadius:4,background:"error"===l.phase?"#fee2e2":"success"===l.phase?"#dcfce7":"#e5e7eb",color:"#111827",fontSize:11,display:"inline-flex",alignItems:"center",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",boxSizing:"border-box"},children:f}),(0,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)(g.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)(a8,{label:a("desktop.modelsIdRequired"),children:(0,r.jsx)(a9,{value:o.id,onChange:e=>x("id",e),placeholder:"model-id",mono:!0})}),(0,r.jsx)(a8,{label:a("desktop.modelsName"),children:(0,r.jsx)(a9,{value:o.name??"",onChange:e=>x("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)(a8,{label:a("desktop.modelsApiOverride"),children:(0,r.jsx)(lo,{value:o.api??"",onChange:e=>x("api",e||void 0),options:a6})}),(0,r.jsxs)("div",{style:{display:"flex",gap:20,flexWrap:"wrap"},children:[(0,r.jsx)(lr,{label:a("desktop.modelsReasoningThinking"),checked:o.reasoning??!1,onChange:e=>x("reasoning",e||void 0)}),(0,r.jsx)(lr,{label:a("desktop.modelsImageInput"),checked:o.input?.includes("image")??!1,onChange:e=>x("input",e?["text","image"]:void 0)})]}),o.reasoning&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(lr,{label:a("desktop.modelsDeepSeekCompat"),checked:o.compat?.thinkingFormat==="deepseek",onChange:e=>s(function(e,t){if(t)return{...e,compat:{...e.compat??{},...ld}};if(!e.compat)return e;let o={...e.compat};return delete o.thinkingFormat,delete o.requiresReasoningContentOnAssistantMessages,{...e,compat:Object.keys(o).length?o:void 0}}(o,e))}),(0,r.jsxs)("div",{children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:8},children:[(0,r.jsx)(ln,{children:a("desktop.modelsThinkingLevelMap")}),o.thinkingLevelMap&&(0,r.jsx)("button",{onClick:()=>x("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)(ll,{value:o.thinkingLevelMap,onChange:e=>x("thinkingLevelMap",e)})]})]}),(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10},children:[(0,r.jsx)(a8,{label:a("desktop.modelsContextWindow"),children:(0,r.jsx)(lt,{value:void 0!==o.contextWindow?String(o.contextWindow):"",onChange:e=>x("contextWindow",e?parseInt(e):void 0),placeholder:"128000"})}),(0,r.jsx)(a8,{label:a("desktop.modelsMaxOutputTokens"),children:(0,r.jsx)(lt,{value:void 0!==o.maxTokens?String(o.maxTokens):"",onChange:e=>x("maxTokens",e?parseInt(e):void 0),placeholder:"16384"})})]}),(0,r.jsxs)("div",{children:[(0,r.jsx)(ln,{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)(a8,{label:e,children:(0,r.jsx)(lt,{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 lp({provider:e,onRefresh:t,onRegisterBuiltinFlush:o,onBuiltinProviderChange:s}){let i=a3(),[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]),x=(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]),f=(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)(ln,{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:()=>f(a.token,e.id),style:{padding:"6px 9px",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:5,color:"var(--text)",cursor:"pointer",fontSize:12,textAlign:"left"},children:e.label},e.id))})]}),("auth"===a.phase||"prompt"===a.phase)&&(0,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&&x(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:()=>x(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)(a4,{providerId:e.id,onRegisterFlush:o,onConfigChange:s})]})}function lu({provider:e,onRefresh:t,onRegisterBuiltinFlush:o,onBuiltinProviderChange:s}){let i=a3(),[a,l]=(0,n.useState)(""),[d,c]=(0,n.useState)(!1),[p,u]=(0,n.useState)(!1),[h,x]=(0,n.useState)(null),[f,m]=(0,n.useState)(!1);(0,n.useEffect)(()=>{l(""),x(null),m(!1)},[e.id]);let k=(0,n.useCallback)(async()=>{if(a.trim()){c(!0),x(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?x(r.error??`HTTP ${o.status}`):(l(""),m(!0),setTimeout(()=>m(!1),2e3),t())}catch(e){x(String(e))}finally{c(!1)}}},[a,e.id,t]),v=(0,n.useCallback)(async()=>{u(!0),x(null);try{let t=await fetch(`/api/auth/api-key/${encodeURIComponent(e.id)}`,{method:"DELETE"}),o=await t.json();(!t.ok||o.error)&&x(409===t.status?i("desktop.modelsAuthenticationStateChanged"):o.error??`HTTP ${t.status}`)}catch(e){x(String(e))}finally{t(),u(!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)(ln,{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)(a8,{label:i("desktop.modelsApiKey"),children:(0,r.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,r.jsx)(le,{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()||f,style:{padding:"6px 12px",background:f?"#16a34a":a.trim()?"var(--accent)":"var(--bg-panel)",border:"none",borderRadius:5,color:a.trim()||f?"#fff":"var(--text-dim)",cursor:d||!a.trim()||f?"not-allowed":"pointer",fontSize:12,fontWeight:600,flexShrink:0,display:"flex",alignItems:"center",gap:5},children:[f&&(0,r.jsx)(g.S,{size:12}),f?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)(a4,{providerId:e.id,onRegisterFlush:o,onConfigChange:s})]})}function lg({oauthProviders:e,apiKeyProviders:t,onSelectOAuth:o,onSelectApiKey:s,onAddCustom:i,onClose:a}){let l=a3(),[d,p]=(0,n.useState)(""),u=(0,n.useRef)(null);(0,n.useEffect)(()=>{setTimeout(()=>u.current?.focus(),30)},[]);let g=d.trim().toLowerCase(),h=e.filter(e=>!e.loggedIn&&(!g||e.name.toLowerCase().includes(g))),x=t.filter(e=>!e.configured&&(!g||e.displayName.toLowerCase().includes(g)||e.id.toLowerCase().includes(g))),f=!g||"custom".includes(g)||"openai-compatible".includes(g)||"anthropic-compatible".includes(g),k=h.length+x.length+ +!!f,v={display:"flex",flexDirection:"row",alignItems:"center",gap:8,padding:"10px 12px",background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:7,boxSizing:"border-box",cursor:"pointer",minWidth:0,textAlign:"left",transition:"border-color 0.12s, background 0.12s",width:"100%"};return(0,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)(c.$,{size:13,style:{color:"var(--text-dim)",flexShrink:0}}),(0,r.jsx)("input",{ref:u,value:d,onChange:e=>p(e.target.value),onKeyDown:e=>{"Escape"===e.key&&a()},placeholder:l("desktop.modelsSearchProviders"),style:{flex:1,background:"none",border:"none",outline:"none",color:"var(--text)",fontSize:13,boxSizing:"border-box"}})]}),(0,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:[f&&(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")}),f&&(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)(m.c,{size:13,style:{color:"var(--text-dim)"}})})]}),h.length>0&&(0,r.jsx)("div",{style:{gridColumn:"1 / -1",paddingTop:6*!!f,fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:l("desktop.modelsSubscriptions")}),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)(su,{id:e.id,size:28})]},e.id)),x.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")}),x.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)(su,{id:e.id,size:28})]},e.id))]})})]})})}function lh({existingProviders:e,onCancel:t,onSubmit:o}){let s=a3(),[i,a]=(0,n.useState)(""),[l,d]=(0,n.useState)(a6[0]),[c,p]=(0,n.useState)(a6[0]),[u,g]=(0,n.useState)(""),[h,x]=(0,n.useState)(""),[f,k]=(0,n.useState)(void 0),[v,y]=(0,n.useState)(!1),[b,w]=(0,n.useState)(""),[j,S]=(0,n.useState)(""),[C,T]=(0,n.useState)(""),[R,z]=(0,n.useState)(""),I=(0,n.useRef)(null);(0,n.useEffect)(()=>{setTimeout(()=>I.current?.focus(),30)},[]);let M=!u.trim()||/^https?:\/\//i.test(u.trim());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&&t()},children:(0,r.jsxs)("div",{style:{width:480,maxWidth:"calc(100vw - 32px)",maxHeight:"min(82vh, calc(100vh - 32px))",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:10,display:"flex",flexDirection:"column",boxShadow:"0 8px 32px rgba(0,0,0,0.22)",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 16px",borderBottom:"1px solid var(--border)",flexShrink:0},children:[(0,r.jsx)("span",{style:{fontSize:14,fontWeight:700,color:"var(--text)"},children:s("desktop.modelsAddCustomTitle")}),(0,r.jsx)("button",{onClick:t,"aria-label":s("desktop.modelsClose"),title:s("desktop.modelsClose"),style:{background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",fontSize:20,lineHeight:1,padding:"2px 6px"},children:"\xd7"})]}),(0,r.jsxs)("div",{style:{padding:16,overflowY:"auto",display:"flex",flexDirection:"column",gap:14},children:[(0,r.jsx)(a8,{label:s("desktop.modelsProviderNameOptional"),children:(0,r.jsx)(a9,{value:i,onChange:a,placeholder:"new-provider",mono:!0,inputRef:I})}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,r.jsx)(ln,{children:s("desktop.modelsCallFormat")}),(0,r.jsxs)("select",{value:c,onChange:e=>{let t=e.target.value;(p(t),t===a5)?y(!0):d(t)},style:a7,children:[a6.map(e=>(0,r.jsx)("option",{value:e,children:e},e)),(0,r.jsx)("option",{value:a5,children:s("desktop.modelsCustomCallFormat")})]}),(0,r.jsx)("span",{style:{fontSize:10,color:"var(--text-dim)"},children:s("desktop.modelsCallFormatHelp")}),c===a5&&(0,r.jsx)("span",{style:{fontSize:10,color:"#d97706",lineHeight:1.4},children:s("desktop.modelsCustomCallFormatHelp")})]}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,r.jsx)(ln,{children:s("desktop.modelsImportProvider")}),(0,r.jsxs)("select",{value:R,onChange:t=>{var o;let r;return z(o=t.target.value),void((r=e.find(e=>e.name===o))&&(r.provider.api&&(d(r.provider.api),p(r.provider.api)),g(r.provider.baseUrl??""),x(r.provider.apiKey??""),k(r.provider.headers?{...r.provider.headers}:void 0)))},style:{...a7,color:R?"var(--text)":"var(--text-dim)"},children:[(0,r.jsx)("option",{value:"",children:s("desktop.modelsImportProviderPlaceholder")}),e.map(e=>(0,r.jsxs)("option",{value:e.name,children:[e.name,e.provider.api?` \xb7 ${e.provider.api}`:""]},e.name))]}),R&&(0,r.jsxs)("span",{style:{fontSize:10,color:"#4ade80"},children:[s("desktop.modelsImported"),": ",R]})]}),(0,r.jsxs)("div",{style:{borderTop:"1px solid var(--border)",paddingTop:12,display:"flex",flexDirection:"column",gap:4},children:[(0,r.jsx)(ln,{children:s("desktop.modelsFullUrl")}),v?(0,r.jsxs)("div",{style:{display:"flex",gap:6,alignItems:"center"},children:[(0,r.jsx)(a9,{value:u,onChange:g,placeholder:s("desktop.modelsUrlPlaceholder"),mono:!0}),(0,r.jsx)("button",{onClick:()=>{y(!1),g("")},title:s("desktop.modelsRemove"),style:{flexShrink:0,width:28,height:28,background:"none",border:"1px solid var(--border)",borderRadius:5,color:"var(--text-dim)",cursor:"pointer",fontSize:14,lineHeight:1,display:"flex",alignItems:"center",justifyContent:"center"},children:"\xd7"})]}):(0,r.jsxs)("button",{onClick:()=>y(!0),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:"7px 0",background:"none",border:"1px dashed var(--border)",borderRadius:5,color:"var(--text-muted)",cursor:"pointer",fontSize:12},onMouseEnter:e=>{e.currentTarget.style.borderColor="var(--accent)",e.currentTarget.style.color="var(--accent)"},onMouseLeave:e=>{e.currentTarget.style.borderColor="var(--border)",e.currentTarget.style.color="var(--text-muted)"},children:[(0,r.jsx)(m.c,{size:12}),s("desktop.modelsAddUrl")]}),u.trim()&&!M&&(0,r.jsx)("span",{style:{fontSize:10,color:"#ef4444"},children:s("desktop.modelsUrlInvalid")}),(0,r.jsxs)(a8,{label:s("desktop.modelsApiKey"),children:[(0,r.jsx)(le,{value:h,onChange:x,placeholder:s("desktop.modelsApiKeyPlaceholder"),mono:!0}),(0,r.jsx)("span",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:s("desktop.modelsApiKeyHelp")})]})]}),(0,r.jsxs)("div",{style:{borderTop:"1px solid var(--border)",paddingTop:12,display:"flex",flexDirection:"column",gap:10},children:[(0,r.jsx)(ln,{children:s("desktop.modelsCustomRequest")}),(0,r.jsxs)(a8,{label:s("desktop.modelsRequestModelId"),children:[(0,r.jsx)(a9,{value:b,onChange:w,placeholder:"model-id",mono:!0}),(0,r.jsx)("span",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:s("desktop.modelsRequestModelIdHelp")})]}),(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10},children:[(0,r.jsx)(a8,{label:s("desktop.modelsRequestContextLength"),children:(0,r.jsx)(lt,{value:j,onChange:S,placeholder:"128000"})}),(0,r.jsx)(a8,{label:s("desktop.modelsRequestOutputLength"),children:(0,r.jsx)(lt,{value:C,onChange:T,placeholder:"16384"})})]})]})]}),(0,r.jsxs)("div",{style:{display:"flex",justifyContent:"flex-end",gap:8,padding:"10px 16px",borderTop:"1px solid var(--border)",flexShrink:0},children:[(0,r.jsx)("button",{onClick:t,style:{padding:"6px 14px",background:"none",border:"1px solid var(--border)",borderRadius:6,color:"var(--text-muted)",cursor:"pointer",fontSize:13},children:s("desktop.cancel")}),(0,r.jsx)("button",{onClick:()=>{let e=b.trim()?{id:b.trim(),...parseInt(j,10)>0?{contextWindow:parseInt(j,10)}:{},...parseInt(C,10)>0?{maxTokens:parseInt(C,10)}:{}}:void 0;o({name:i.trim(),api:l,...u.trim()?{baseUrl:u.trim()}:{},...h.trim()?{apiKey:h.trim()}:{},...f?{headers:f}:{},model:e})},disabled:!M,style:{padding:"6px 16px",background:M?"var(--accent)":"var(--bg-panel)",border:"none",borderRadius:6,color:M?"#fff":"var(--text-dim)",cursor:M?"pointer":"not-allowed",fontSize:13,fontWeight:600},children:s("desktop.modelsAdd")})]})]})})}function lx({embedded:e=!1,sessionId:t,onCloseAction:o,onSavedAction:s,onRegisterFlush:i}){let a=a3(),l=A(),[d,c]=(0,n.useState)({providers:{}}),[p,u]=(0,n.useState)(!0),[h,x]=(0,n.useState)(!1),[f,m]=(0,n.useState)(null),[k,v]=(0,n.useState)(!1),[y,b]=(0,n.useState)(null),[w,j]=(0,n.useState)([]),[S,C]=(0,n.useState)([]),[R,z]=(0,n.useState)(!1),[I,M]=(0,n.useState)(!1),[E,P]=(0,n.useState)({oauth:!1,apiKey:!1}),D=(0,n.useRef)({providers:{}}),F=(0,n.useRef)(new Map),W=(0,n.useRef)(0),$=(0,n.useRef)(!1);D.current=d;let N=(0,n.useCallback)(e=>{let t=e(D.current);return D.current=t,W.current+=1,c(t),t},[]),L=(0,n.useCallback)(()=>{fetch("/api/auth/combined").then(e=>e.json()).then(e=>{j(e.oauth??[]),C(e.apiKey??[])}).catch(()=>{}).finally(()=>P({oauth:!0,apiKey:!0}))},[]),O=(0,n.useCallback)((e,t)=>(F.current.set(e,t),()=>{F.current.get(e)===t&&F.current.delete(e)}),[]),H=(0,n.useCallback)(async()=>{for(let e of[...F.current.values()])await e()},[]);(0,n.useEffect)(()=>{if(i)return i(H)??void 0},[H,i]);let B=(0,n.useCallback)((e,t)=>{N(o=>{let r={...o.providers??{}};return t?r[e]=t:delete r[e],{...o,providers:r}}),s?.()},[s,N]),U=(0,n.useCallback)(async e=>{if(!$.current){$.current=!0,m(null);try{await H(),b(e)}catch(e){m(e instanceof Error?e.message:String(e))}finally{$.current=!1}}},[H]);(0,n.useEffect)(()=>{fetch("/api/models-config").then(e=>e.json()).then(e=>{let t=e.providers?e:{...e,providers:{}};D.current=t,W.current+=1,c(t)}).catch(()=>{let e={providers:{}};D.current=e,W.current+=1,c(e)}).finally(()=>u(!1)),L()},[L]);let _=(0,n.useCallback)(async e=>{if(!$.current){$.current=!0,m(null);try{await H();let t=e.name.trim()||"new-provider",o=t,r=1;for(;D.current.providers?.[o];)o=`${t}-${r++}`;let n={api:e.api||"openai-completions",...e.baseUrl?{baseUrl:e.baseUrl}:{},...e.apiKey?{apiKey:e.apiKey}:{},...e.headers?{headers:e.headers}:{},...e.model?{models:[e.model]}:{}};N(e=>({...e,providers:{...e.providers??{},[o]:n}})),b({type:"provider",name:o}),M(!1)}catch(e){m(e instanceof Error?e.message:String(e))}finally{$.current=!1}}},[H,N]),q=(0,n.useCallback)((e,t)=>{N(o=>({...o,providers:{...o.providers??{},[e]:t}}))},[N]),V=(0,n.useCallback)((e,t)=>{N(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)},[N]),K=(0,n.useCallback)(e=>{let t=Object.keys(N(t=>{let o={...t.providers??{}};return delete o[e],{...t,providers:o}}).providers??{});b(t.length>0?{type:"provider",name:t[0]}:null)},[N]),J=(0,n.useCallback)(async e=>{if(!$.current){$.current=!0,m(null);try{await H();let t=N(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{$.current=!1}}},[H,N]),G=(0,n.useCallback)((e,t)=>{N(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}}}})},[N]),Y=(0,n.useCallback)((e,t,o)=>{N(r=>{let n=r.providers?.[e]??{},s=[...n.models??[]];return s[t]=o,{...r,providers:{...r.providers??{},[e]:{...n,models:s}}}})},[N]),X=(0,n.useCallback)(async(e,t)=>{if(!$.current){$.current=!0,m(null);try{await H(),N(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{$.current=!1}}},[H,N]),Z=(0,n.useCallback)(async()=>{if(!h){x(!0),m(null),v(!1);try{await H();let e=D.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&&(D.current=o.config,W.current+=1,c(o.config)),v(!0),s?.(),setTimeout(()=>v(!1),2e3)}catch(e){m(e instanceof Error?e.message:String(e))}finally{x(!1)}}},[H,s,h]),Q=(0,n.useCallback)(async()=>{try{await H(),o?.()}catch(e){m(e instanceof Error?e.message:String(e))}},[H,o]),ee=Object.entries(d.providers??{}),et=new Set([...w.map(e=>e.id),...S.map(e=>e.id)]),eo=ee.filter(([e])=>!et.has(e)),er=w.filter(e=>e.loggedIn),en=S.filter(e=>e.configured);(0,n.useEffect)(()=>{if(y||p||!E.oauth||!E.apiKey)return;let e=er[0]?{type:"oauth",providerId:er[0].id}:en[0]?{type:"apikey",providerId:en[0].id}:eo[0]?.[0]?{type:"provider",name:eo[0][0]}:null;e&&b(e)},[en,er,eo,p,E.apiKey,E.oauth,y]);let es=(()=>{if(!y)return null;if("oauth"===y.type){let e=w.find(e=>e.id===y.providerId);return e?(0,r.jsx)(lp,{provider:e,onRefresh:L,onRegisterBuiltinFlush:O,onBuiltinProviderChange:t=>B(e.id,t)},e.id):null}if("apikey"===y.type){let e=S.find(e=>e.id===y.providerId);return e?(0,r.jsx)(lu,{provider:e,onRefresh:L,onRegisterBuiltinFlush:O,onBuiltinProviderChange:t=>B(e.id,t)},e.id):null}if("provider"===y.type){let e=d.providers?.[y.name];return e?(0,r.jsx)(ls,{name:y.name,provider:e,onChange:e=>q(y.name,e),onRename:e=>V(y.name,e),onDelete:()=>K(y.name),onAddModels:e=>G(y.name,e),onAddModel:()=>{J(y.name)}},y.name):null}let e=d.providers?.[y.providerName],t=e?.models?.[y.index];return t?(0,r.jsx)(lc,{providerName:y.providerName,provider:e,model:t,onChange:e=>Y(y.providerName,y.index,e),onDelete:()=>{X(y.providerName,y.index)}},`${y.providerName}-${y.index}`):null})();return(0,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||Q()},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:()=>{Q()},"aria-label":a("desktop.modelsClose"),title:a("desktop.modelsClose"),style:{background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",fontSize:20,lineHeight:1,padding:"2px 6px"},children:"\xd7"})]}),(0,r.jsx)(aQ,{}),(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:[er.map(e=>{let t=y?.type==="oauth"&&y.providerId===e.id;return(0,r.jsxs)("div",{onClick:()=>{U({type:"oauth",providerId:e.id})},style:{display:"flex",alignItems:"center",gap:7,padding:"5px 8px",borderRadius:5,cursor:"pointer",background:t?"var(--bg-selected)":"none"},onMouseEnter:e=>{t||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{t||(e.currentTarget.style.background="none")},children:[(0,r.jsx)(su,{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)}),en.map(e=>{let t=y?.type==="apikey"&&y.providerId===e.id;return(0,r.jsxs)("div",{onClick:()=>{U({type:"apikey",providerId:e.id})},style:{display:"flex",alignItems:"center",gap:7,padding:"5px 8px",borderRadius:5,cursor:"pointer",background:t?"var(--bg-selected)":"none"},onMouseEnter:e=>{t||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{t||(e.currentTarget.style.background="none")},children:[(0,r.jsx)(su,{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)}),(er.length>0||en.length>0)&&eo.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")}):eo.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:()=>{U({type:"provider",name:e})},style:{display:"flex",alignItems:"center",gap:6,padding:"7px 8px",borderRadius:5,cursor:"pointer",background:o?"var(--bg-selected)":"none"},onMouseEnter:e=>{o||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{o||(e.currentTarget.style.background="none")},children:[(0,r.jsx)(T.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:()=>{U({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(),J(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:es??(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:[f&&(0,r.jsx)("span",{style:{fontSize:12,color:"#f87171",flex:1},children:f}),!e&&(0,r.jsx)("button",{onClick:()=>{Q()},style:{padding:"6px 14px",background:"none",border:"1px solid var(--border)",borderRadius:6,color:"var(--text-muted)",cursor:"pointer",fontSize:13},children:a("desktop.cancel")}),(0,r.jsx)(a_,{sessionId:t}),(0,r.jsxs)("button",{onClick:Z,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)(g.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)(lg,{oauthProviders:w,apiKeyProviders:S,onSelectOAuth:e=>{U({type:"oauth",providerId:e})},onSelectApiKey:e=>{U({type:"apikey",providerId:e})},onAddCustom:()=>{z(!1),M(!0)},onClose:()=>z(!1)}),I&&(0,r.jsx)(lh,{existingProviders:eo.map(([e,t])=>({name:e,provider:t})),onCancel:()=>M(!1),onSubmit:e=>{_(e)}})]})}function lf(e){return e.replace(/^\/(?:Users|home)\/[^/]+/,"~")}function lm(e){let t=e.trim().match(/^\$?\s*pi\s+install\s+(\S+)\s*$/);return t?.[1]??e}function lk(e){return`${e.scope}\0${e.source}`}function lv(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 ly(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 lb(e){return"loaded"===e?"var(--accent)":"installed"===e?"#f59e0b":"disabled"===e?"var(--text-dim)":"#ef4444"}function lw({pkg:e}){let{t}=(0,D.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 lj({scope:e}){let{t}=(0,D.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 lS(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 lC({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 lT({value:e,onChange:t}){let{t:o}=(0,D.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 lR({cwd:e,source:t,scope:o,busy:s,actionError:i,onSourceChange:a,onScopeChange:l,onInstall:d}){let{t:c}=(0,D.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?`${lf(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=lm(t);o!==t&&(e.preventDefault(),a(o))},onBlur:e=>a(lm(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)(lT,{value:o,onChange:l}),(0,r.jsx)("button",{type:"button",onClick:d,disabled:s||!t.trim(),style:{...lS(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 lz({pkg:e,cwd:t,busyKey:o,actionError:n,actionMessage:s,sessionId:i,onAction:a,onReloadSession:l}){let{t:d}=(0,D.s)(),c=lk(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)(lC,{enabled:g,loading:p||u,onToggle:()=>a(e.disabled?"enable":"disable",e),label:d(e.disabled?"desktop.enablePackage":"desktop.disablePackage")}),(0,r.jsx)(lj,{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:lS(p||u),children:d(o===`update:${c}`?"desktop.updating":"desktop.update")}),(0,r.jsx)("button",{onClick:l,disabled:!i||u||p,style:lS(!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:lS(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:lb(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:ly(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:lv(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?lf(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:lf(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)(lw,{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 lI({cwd:e,sessionId:t,embedded:o=!1,onCloseAction:s,onReloadedAction:i}){let a=A(),{t:l}=(0,D.s)(),[d,c]=(0,n.useState)(null),[p,u]=(0,n.useState)(!0),[g,h]=(0,n.useState)(null),[x,f]=(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]),E=M.find(e=>lk(e)===x)??null,P=(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),f(e=>e&&o.packages.some(t=>lk(t)===e)?e:o.packages[0]?lk(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=lk(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)f(n.packages[0]?lk(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]),$=(0,n.useCallback)(async()=>{let t=lm(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)));f(d?lk(d):o),v(!1),b(""),I(l("desktop.packageInstalled"))}catch(e){R(e instanceof Error?e.message:String(e))}finally{C(null)}},[e,w,y,l]),N=(0,n.useCallback)(async()=>{if(t){C("reload"),R(null),I(null);try{await io(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]),L=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:lf(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")}):P.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=lk(e),o=!k&&x===t;return(0,r.jsxs)("div",{onClick:()=>{f(t),v(!1),R(null),I(null)},style:{display:"flex",alignItems:"center",gap:7,padding:"8px 8px",borderRadius:5,cursor:"pointer",background:o?"var(--bg-selected)":"none"},onMouseEnter:e=>{o||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{o||(e.currentTarget.style.background="none")},children:[(0,r.jsx)("span",{style:{flexShrink:0,width:7,height:7,borderRadius:"50%",background:lb(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:lv(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:ly(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)(m.c,{size:13}),l("desktop.addPlugin")]})})]}),(0,r.jsx)("div",{style:{flex:1,overflowY:"auto",padding:20},children:k?(0,r.jsx)(lR,{cwd:e,source:y,scope:w,busy:L,actionError:T,onSourceChange:b,onScopeChange:j,onInstall:$}):p?null:E?(0,r.jsx)(lz,{pkg:E,cwd:e,busyKey:S,actionError:T,actionMessage:z,sessionId:t,onAction:W,onReloadSession:N},lk(E)):(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:lS(p||null!==S),children:l("desktop.refresh")}),!o&&(0,r.jsx)("button",{onClick:s,style:lS(!1),children:l("desktop.close")})]})]})})}var lM=o(36282);function lE(){let{t:e}=(0,D.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),[x,f]=(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),f(!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),f(!1),k(!1);let e=await fetch("/api/proxy");if(e.ok){let t=await e.json();o(e=>({...e,...t,password:""}))}}else u(!1),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),x&&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)}},[x,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)(rz.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)(s0.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)(rz.r,{size:16,weight:"fill"}):(0,r.jsx)(s0.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)"]})]}),x&&!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)(lM.j,{size:12,weight:"fill"}),e("desktop.proxyUnsaved")]})]})}function lP(e){return e.replace(/^\/(?:Users|home)\/[^/]+/,"~")}function lD(e){let t=e.sourceInfo?.source,o=e.sourceInfo?.scope;return"user"===o||"user"===t?"global":"project"===o||"project"===t?"project":"path"}function lF(e){let t=lD(e);return"path"===t?t:e.install?.skillsShUrl?`${t} / skills.sh`:t}function lW(e){return e.install?`${e.install.scope}\0${e.install.package}`:null}function l$(e,t){return e?e.slice(0,8):t}function lN({enabled:e,loading:t,onToggle:o}){let{t:n}=(0,D.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 lA({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,D.s)(),g=lD(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 lP(e)}(e.filePath)}),(0,r.jsx)(lN,{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:l$(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:l$(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 lL({cwd:e,installedPackages:t,projectResourcesLoaded:o,onInstalled:s}){let{t:i}=(0,D.s)(),[a,l]=(0,n.useState)(""),[d,c]=(0,n.useState)([]),[p,u]=(0,n.useState)(!1),[g,h]=(0,n.useState)(null),[x,f]=(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=>{f(t),k(null);try{let o=await fetch("/api/skills/install",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({package:t,scope:b,cwd:e})}),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{f(null)}},[s,b,e]),T="global"===b?"~/.pi/agent/skills/":`${lP(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=x===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!==x,style:{flexShrink:0,padding:"5px 14px",fontSize:12,fontWeight:500,borderRadius:5,border:"1px solid var(--border)",cursor:o||n||null!==x?"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 lO({cwd:e,embedded:t=!1,sessionId:o,onCloseAction:s}){let i=A(),{t:a}=(0,D.s)(),[l,d]=(0,n.useState)([]),[c,p]=(0,n.useState)(!0),[u,g]=(0,n.useState)(null),[h,x]=(0,n.useState)(null),[f,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),[E,P]=(0,n.useState)(null),[F,W]=(0,n.useState)(!0),[$,N]=(0,n.useState)({}),L=(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];x(e.filePath),e.disableModelInvocation&&N(t=>({...t,[lF(e)]:!0}))}return r}catch(e){return g(String(e)),[]}finally{p(!1)}},[e,h]);(0,n.useEffect)(()=>{S({}),P(null),L()},[e]);let O=(0,n.useCallback)(async t=>{let o=(t?[t]:l.filter(e=>!!e.install)).map(lW).filter(e=>!!e);if(0!==o.length){P(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){P(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=lW(t);M(o),P(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 L();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){P(e instanceof Error?e.message:String(e))}finally{M(null)}},[e,L]),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&&N(e=>({...e,[lF(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:lP(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)(a_,{sessionId:o,onApplied:L})}),(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"===lD(e)&&!!e.install?.skillsShUrl},{key:"project",label:a("desktop.project"),matches:e=>"project"===lD(e)&&!e.install?.skillsShUrl},{key:"global / skills.sh",label:`${a("desktop.global")} / skills.sh`,matches:e=>"global"===lD(e)&&!!e.install?.skillsShUrl},{key:"global",label:a("desktop.global"),matches:e=>"global"===lD(e)&&!e.install?.skillsShUrl},{key:"path",label:a("desktop.path"),matches:e=>"path"===lD(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=$[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:()=>N(t=>({...t,[e]:!i})),style:{display:"flex",alignItems:"center",gap:5,width:"100%",padding:"4px 8px 3px",border:"none",background:"transparent",color:"var(--text-dim)",cursor:"pointer",fontSize:10,fontWeight:600,letterSpacing:"0.06em",textAlign:"left",textTransform:"uppercase"},children:[(0,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:()=>{x(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=lW(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)(m.c,{size:13}),a("desktop.addSkill")]})})]}),(0,r.jsx)("div",{style:{flex:1,overflowY:"auto",padding:20},children:b?(0,r.jsx)(lL,{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:()=>{L()}}):c?null:U?(0,r.jsx)(lA,{skill:U,cwd:e,onToggle:B,toggling:f.has(U.filePath),saveError:v,updateStatus:lW(U)?j[lW(U)]:void 0,checkingUpdate:!!lW(U)&&C.has(lW(U)),updating:I===lW(U),updateError:E,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 lH(){let{t:e}=(0,D.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),[x,f]=(0,n.useState)(null),m=(0,n.useCallback)(async()=>{h(!0),f(null);try{let e=await fetch("/api/logs?limit=500"),t=await e.json();if(!e.ok)throw Error(t.error??`HTTP ${e.status}`);o(t.entries??[])}catch(e){f(e instanceof Error?e.message:String(e))}finally{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){f(e instanceof Error?e.message:String(e))}},w=async e=>{let t=[`[${e.timestamp}] ${e.level.toUpperCase()} ${e.statusCode??"—"}`,`${e.source}${e.provider?` \xb7 ${e.provider}`:""}${e.model?` \xb7 ${e.model}`:""}`,e.message,e.details].filter(Boolean).join("\n");try{await op(t),f(null)}catch(e){f(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)(j.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)(S.l,{size:14})})]}),g&&(0,r.jsx)("div",{style:{color:"var(--text-muted)",fontSize:12},children:e("desktop.loading")}),x&&(0,r.jsx)("div",{style:{color:"#ef4444",fontSize:12},children:x}),!g&&!x&&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 w(t),style:{marginTop:8,padding:"4px 7px",border:"1px solid var(--border)",borderRadius:5,background:"var(--bg)",color:"var(--text-muted)",cursor:"pointer",fontSize:11},children:e("desktop.logsCopy")})]})]},t.id))})]})}let lB={padding:"7px 9px",background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:6,color:"var(--text)",fontSize:12,width:"100%"},lU={padding:"6px 12px",border:"none",borderRadius:6,background:"var(--accent)",color:"#fff",cursor:"pointer",fontSize:12};function l_(){let{t:e}=(0,D.s)(),[t,o]=(0,n.useState)([]),[s,i]=(0,n.useState)(!0),[a,l]=(0,n.useState)(null),[d,c]=(0,n.useState)(""),[u,g]=(0,n.useState)(""),[x,f]=(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),c(""),g(""),v(null)},j=(0,n.useCallback)(async()=>{let t=d.trim();if(!t)return void v(e("desktop.snippetNameRequired"));f(!0),v(null);try{if(a){let e=await fetch(`/api/snippets/${encodeURIComponent(a.id)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:t,content:u})});if(!e.ok)throw Error(`HTTP ${e.status}`)}else{let e=await fetch("/api/snippets",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:t,content:u})});if(!e.ok)throw Error(`HTTP ${e.status}`)}await y(),b(),w()}catch(e){v(e instanceof Error?e.message:String(e))}finally{f(!1)}},[a,d,u,y,b,e]),C=(0,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)(aC,{children:[(0,r.jsx)(aT,{children:(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:7,padding:"12px 0"},children:[(0,r.jsx)(nl.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)(aT,{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:lU,children:(0,r.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:5},children:[(0,r.jsx)(m.F,{size:13})," ",e("desktop.snippetNew")]})}),a&&(0,r.jsx)("button",{type:"button",onClick:w,style:{...lU,background:"var(--bg-hover)",color:"var(--text-muted)"},children:(0,r.jsx)(p.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=>c(e.target.value),placeholder:"#name",style:lB})]}),(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=>g(e.target.value),rows:3,style:{...lB,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 j(),disabled:x,style:{...lU,cursor:x?"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)(az,{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),c(t.name),g(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)(h.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)(S.l,{size:13})})]},t.id))})]})}),(0,r.jsx)(aR,{children:(0,r.jsx)(az,{children:e("desktop.snippetHint")})})]})}let lq=["async","group","smart"],lV=["full","compact","custom"],lK=["all","background","off"],lJ={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 lG(){return{fontSize:12,color:"var(--text-muted)"}}function lY({cwd:e,sessionId:t}){let{t:o}=(0,D.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),[x,f]=(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()=>{f(!0),k(null),y(!1);try{let e=await fetch("/api/subagents",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)}),t=await e.json();if(!e.ok||t.error)throw Error(t.error??`HTTP ${e.status}`);i(t.config??{}),y(!0)}catch(e){k(e instanceof Error?e.message:String(e))}finally{f(!1)}},[s]),z=(0,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)(aT,{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:lG(),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:lJ})]})},e),E=(e,t,n)=>(0,r.jsx)(aT,{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:lG(),children:o(t)}),(0,r.jsx)("select",{value:s[e]??n[0],onChange:t=>T(e,t.target.value),style:{...lJ,fontFamily:"var(--font-mono)"},children:n.map(e=>(0,r.jsx)("option",{value:e,children:e},e))})]})},e),P=(e,t,n)=>(0,r.jsx)(aT,{children:(0,r.jsx)(as,{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)(az,{children:o("desktop.subagentsDesc")}),(0,r.jsxs)(aC,{children:[M("maxConcurrent","desktop.subagentsMaxConcurrent"),M("defaultMaxTurns","desktop.subagentsDefaultMaxTurns"),M("graceTurns","desktop.subagentsGraceTurns"),E("defaultJoinMode","desktop.subagentsJoinMode",lq),E("widgetMode","desktop.subagentsWidgetMode",lK),E("toolDescriptionMode","desktop.subagentsToolDescMode",lV),P("schedulingEnabled","desktop.subagentsScheduling","desktop.subagentsSchedulingDesc"),P("scopeModels","desktop.subagentsScopeModels","desktop.subagentsScopeModelsDesc"),P("disableDefaultAgents","desktop.subagentsDisableDefault","desktop.subagentsDisableDefaultDesc"),P("fleetView","desktop.subagentsFleetView","desktop.subagentsFleetViewDesc"),(0,r.jsx)(aR,{children:P("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:x,style:{padding:"7px 12px",border:"none",borderRadius:6,background:"var(--accent)",color:"#fff",cursor:x?"wait":"pointer",fontSize:12},children:x?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)(a_,{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)(i7.d,{size:15,"aria-hidden":"true"}),o("desktop.subagentsDiscovered")]}),(0,r.jsx)(aC,{children:a.map((e,t)=>(0,r.jsx)(aR,{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:{...lJ,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 lX(e){return null==e?"—":sY(e)}function lZ({sessionId:e,cwd:t}){let{t:o}=(0,D.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:lX(s.tokens),window:lX(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:lX(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?lX(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}: ${lX(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:lX(e.tokens)})]},e.path))]})]})]})]})}function lQ(){let{t:e}=(0,D.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)(i2.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)(aF.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 l0=[{id:"server",labelKey:"desktop.server",Icon:i2.X},{id:"display",labelKey:"desktop.display",Icon:i4.V},{id:"chat",labelKey:"desktop.chat",Icon:i6.W},{id:"models",labelKey:"desktop.models",Icon:T.f},{id:"skills",labelKey:"desktop.skills",Icon:R.B},{id:"plugins",labelKey:"desktop.plugins",Icon:z.F},{id:"proxy",labelKey:"desktop.proxy",Icon:i5.l},{id:"features",labelKey:"desktop.features",Icon:u.l},{id:"logs",labelKey:"desktop.logs",Icon:y.B},{id:"snippets",labelKey:"desktop.snippets",Icon:nl.c},{id:"usage",labelKey:"desktop.usage",Icon:i3._},{id:"mcp",labelKey:"desktop.mcp",Icon:i8.b},{id:"subagents",labelKey:"desktop.subagents",Icon:i7.d},{id:"backup",labelKey:"desktop.backup",Icon:o7.W},{id:"import",labelKey:"desktop.importSessions",Icon:I.z}];function l1({initialTab:e="models",cwd:t,sessionId:o,onCloseAction:s,onModelsSavedAction:i,onSessionReloadedAction:a,onSessionsChanged:l}){let d=A(),{t:c}=(0,D.s)(),[u,g]=(0,n.useState)("skills"===e||"plugins"===e?t?e:"display":e),[h,x]=(0,n.useState)(!1);(0,n.useEffect)(()=>{x(new URLSearchParams(window.location.search).has("piweb_connected"))},[]);let f=h?l0:l0.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":c("desktop.settings"),className:"settings-modal",style:{width:d?"calc(100vw - 16px)":1e3,maxWidth:"calc(100vw - 16px)",height:d?"calc(100dvh - 16px)":"80vh",maxHeight:"calc(100dvh - 16px)",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:10,display:"flex",flexDirection:"column",boxShadow:"0 8px 32px rgba(0,0,0,0.18)",overflow:"hidden"},children:[(0,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:c("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:c("desktop.closeSettings"),"aria-label":c("desktop.closeSettings"),style:{background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",padding:4,display:"flex"},children:(0,r.jsx)(p.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":c("desktop.settingsSections"),style:{display:"flex",flexDirection:d?"row":"column",gap:4,width:d?"100%":150,padding:8,flexShrink:0,minWidth:0,background:"var(--bg-panel)",borderRight:d?"none":"1px solid var(--border)",borderBottom:d?"1px solid var(--border)":"none",overflowX:d?"auto":void 0,overflowY:d?"hidden":void 0,WebkitOverflowScrolling:d?"touch":void 0},children:f.filter(({id:e})=>!(d&&"import"===e)).map(({id:e,labelKey:o,Icon: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:c(o),"aria-label":c(o),onMouseEnter:e=>{i||s||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{i||(e.currentTarget.style.background="none",e.currentTarget.style.color="var(--text-muted)")},children:[(0,r.jsx)(n,{size:16,"aria-hidden":"true"}),!d&&(0,r.jsx)("span",{children:c(o)})]},e)})}),(0,r.jsx)("div",{style:{display:"server"===u?"flex":"none",flex:1,minWidth:0,minHeight:0},children:(0,r.jsx)(lQ,{})}),(0,r.jsx)("div",{style:{display:"display"===u?"flex":"none",flex:1,minWidth:0,minHeight:0},children:(0,r.jsx)(aj,{})}),(0,r.jsx)("div",{style:{display:"chat"===u?"flex":"none",flex:1,minWidth:0,minHeight:0},children:(0,r.jsx)(ad,{})}),(0,r.jsx)("div",{style:{display:"models"===u?"flex":"none",flex:1,minWidth:0,minHeight:0},children:(0,r.jsx)(lx,{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)(lO,{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)(lI,{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)(lE,{})}),(0,r.jsx)("div",{style:{display:"features"===u?"flex":"none",flex:1,minWidth:0,minHeight:0},children:(0,r.jsx)(aD,{})}),(0,r.jsx)("div",{style:{display:"logs"===u?"flex":"none",flex:1,minWidth:0,minHeight:0},children:(0,r.jsx)(lH,{})}),(0,r.jsx)("div",{style:{display:"snippets"===u?"flex":"none",flex:1,minWidth:0,minHeight:0},children:(0,r.jsx)(l_,{})}),(0,r.jsx)("div",{style:{display:"usage"===u?"flex":"none",flex:1,minWidth:0,minHeight:0},children:(0,r.jsx)(lZ,{sessionId:o,cwd:t})}),(0,r.jsx)("div",{style:{display:"mcp"===u?"flex":"none",flex:1,minWidth:0,minHeight:0},children:(0,r.jsx)(aX,{sessionId:o})}),(0,r.jsx)("div",{style:{display:"subagents"===u?"flex":"none",flex:1,minWidth:0,minHeight:0},children:(0,r.jsx)(lY,{cwd:t,sessionId:o})}),(0,r.jsx)("div",{style:{display:"backup"===u?"flex":"none",flex:1,minWidth:0,minHeight:0},children:(0,r.jsx)(ao,{cwd:t})}),(0,r.jsx)("div",{style:{display:"import"===u?"flex":"none",flex:1,minWidth:0,minHeight:0,overflowY:"auto"},children:(0,r.jsx)(a$,{onSessionsChanged:l})})]}),v&&(0,r.jsx)("div",{style:{padding:"6px 18px",borderTop:"1px solid var(--border)",color:"#f87171",fontSize:11},children:v})]})})}let l2=new Set(["awaiting_input","review","failed"]),l4=(0,n.createContext)(null);function l6(){let e=(0,n.useContext)(l4);if(!e)throw Error("useTasksView must be used within TasksViewProvider");return e}function l5({children:e}){let{t}=(0,D.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,nP.Wt)(),o=(await Promise.all(t.map(e=>(0,nP.Vk)(e).catch(()=>[])))).flat().sort((e,t)=>t.id-e.id);if(e!==d.current)return;l(e=>l3(e,t)?e:t),i(e=>l3(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=>l2.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)(l4.Provider,{value:g,children:e})}function l3(e,t){return JSON.stringify(e)===JSON.stringify(t)}var l8=o(4539),l7=o(12449),l9=o(2571);let de=["todo","inProgress","attention","done"];function dt(e){return"review"===e.status&&0===e.filesChanged}function dr(){return{defaultAgentType:null,modeId:null,configValues:{},autoProcess:!0,maxConcurrent:1,mergeStrategy:"merge",deleteWorktreeDefault:!0,preflightCommand:null,initCommand:null,stagePrompts:null}}let dn=["todo","inProgress","attention","done"],ds={todo:{id:"todo",marker:"var(--text-dim)"},inProgress:{id:"inProgress",marker:"var(--accent)"},attention:{id:"attention",marker:"#f59e0b"},done:{id:"done",marker:"#10b981"}};var di=o(54775),da=o(98998),dl=o(36668);function dd({task:e}){let{t}=(0,D.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)(di.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)(g.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 dc({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)(di.N,{size:10,style:{animation:"pi-spin 1s linear infinite"},"aria-hidden":"true"}):"passed"===t.status?(0,r.jsx)(rz.r,{size:10,"aria-hidden":"true"}):(0,r.jsx)(s0.J,{size:10,"aria-hidden":"true"}),(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:t.command})]})}function dp({task:e,folderName:t,now:o,onOpen:n,onStart:s,onCancel:i,onRetry:a,onRequeue:l,onViewSession:d,onMerge:c,onArchive:p,onEdit:u}){let{t:h}=(0,D.s)(),x=null!=e.archivedAt,f="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(x)return{primary:o={icon:s2.T,label:h("tasks.actionUnarchive"),onClick:p},more:t};switch(e.status){case"todo":o={icon:l9.j,label:h("tasks.actionStart"),onClick:s},t.push({icon:nd.S,label:h("tasks.actionEdit"),onClick:u});break;case"queued":case"preparing":case"running":case"awaiting_input":o={icon:da.k,label:h("tasks.actionCancel"),onClick:i};break;case"review":o=dt(e)?{icon:g.J,label:h("tasks.actionComplete"),onClick:c}:{icon:dl.r,label:h("tasks.actionMerge"),onClick:c};break;case"merging":break;case"failed":o={icon:j.S,label:h("tasks.actionRetry"),onClick:a},t.push({icon:nd.S,label:h("tasks.actionEdit"),onClick:u}),t.push({icon:s2.T,label:h("tasks.actionArchive"),onClick:p});break;case"done":o={icon:s2.T,label:h("tasks.actionArchive"),onClick:p};break;case"canceled":o={icon:rI.f,label:h("tasks.actionRequeue"),onClick:l},t.push({icon:s2.T,label:h("tasks.actionArchive"),onClick:p})}return{primary:o,more:t}})(),b=[...y];return null!=e.conversationId&&b.push({icon:rR.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:x?.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)(dd,{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)(dc,{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)(o9.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,f&&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 du({open:e,onOpenChange:t,task:o}){let{t:s}=(0,D.s)(),{refetch:i}=l6(),[a,l]=(0,n.useState)(""),[d,c]=(0,n.useState)(!1);if((0,n.useEffect)(()=>{e&&(l(""),c(!1))},[e,o]),!e||!o)return null;let u=async()=>{if(!d){c(!0);try{await (0,nP.oQ)(o.id,o.projectRoot,"cancel",{reason:a.trim()||null}),t(!1),i()}catch(e){console.error("cancel failed",e)}finally{c(!1)}}};return(0,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)(p.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 dg({open:e,onOpenChange:t,task:o}){let{t:s}=(0,D.s)(),{refetch:i}=l6(),[a,l]=(0,n.useState)(!0),[d,c]=(0,n.useState)(!1),u=o?.worktreePath!=null;if((0,n.useEffect)(()=>{if(!e||!o)return;c(!1);let t=!1;return(0,nP.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){c(!0);try{await (0,nP.ZX)(o.id,o.projectRoot,u&&a),t(!1),i()}catch(e){console.error("complete failed",e)}finally{c(!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)(p.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 dh=o(51285),dx=o(16894);function df({open:e,onOpenChange:t,task:o,onViewSession:s,onMerge:i,onEdit:a,onCancel:l,onRetry:d,onRequeue:c,onComplete:u}){let{t:h}=(0,D.s)(),{refetch:x}=l6(),[f,m]=(0,n.useState)([]),[v,y]=(0,n.useState)([]),[b,w]=(0,n.useState)(null),[C,T]=(0,n.useState)(null),[R,z]=(0,n.useState)(!1),[I,M]=(0,n.useState)(!1),[E,P]=(0,n.useState)(""),[F,W]=(0,n.useState)(!1),[$,N]=(0,n.useState)(!1),[A,L]=(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,nP.HB)(H,O).catch(()=>[]),o?.worktreePath?(0,nP.JH)(H,O).then(e=>e.files).catch(()=>[]):Promise.resolve([])]);m(e),y(t)},[O,H,o?.worktreePath]);(0,n.useEffect)(()=>{if(!e||null==O)return;m([]),y([]),M(!1),P(""),B();let t=window.setInterval(()=>void B(),5e3);return()=>window.clearInterval(t)},[e,O,B]);let U=(0,n.useCallback)(async e=>{L(!0);try{await e()}catch(e){console.error("detail action failed",e)}finally{L(!1),x()}},[x]),_=(0,n.useCallback)(async e=>{if(null!=H&&null!=O){z(!0);try{let t=await (0,nP.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,nP.bH)(o.id,H,$)),t(!1))},V=async()=>{null!=o&&null!=H&&E.trim()&&(await U(()=>(0,nP.in)(o.id,H,E.trim())),M(!1),P(""))};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:l9.j,onClick:()=>void U(()=>(0,nP.oQ)(o.id,H,"start")),filled:!0}),K.push({label:h("tasks.actionEdit"),icon:nd.S,onClick:()=>a(o)});break;case"queued":case"preparing":case"running":case"awaiting_input":K.push({label:h("tasks.actionCancel"),icon:da.k,onClick:()=>l(o),danger:!0});break;case"review":K.push({label:dt(o)?h("tasks.actionComplete"):h("tasks.actionMerge"),icon:dt(o)?g.J:dh.Y,onClick:()=>dt(o)?u(o):i(o),filled:!0}),K.push({label:h("tasks.actionReturn"),icon:rI.f,onClick:()=>M(!0)});break;case"failed":K.push({label:h("tasks.actionRetry"),icon:j.S,onClick:()=>d(o),filled:!0}),K.push({label:h("tasks.actionEdit"),icon:nd.S,onClick:()=>a(o)});break;case"done":K.push({label:h("tasks.actionArchive"),icon:s2.T,onClick:()=>void U(()=>(0,nP.et)(o.id,H,!0))});break;case"canceled":K.push({label:h("tasks.actionRequeue"),icon:rI.f,onClick:()=>c(o),filled:!0})}else K.push({label:h("tasks.actionUnarchive"),icon:s2.T,onClick:()=>void U(()=>(0,nP.et)(o.id,H,!1))});return null!=o.conversationId&&K.push({label:h("tasks.actionViewSession"),icon:rR.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)(dd,{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)(k.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)(p.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:A,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:E,onChange:e=>P(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:!E.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;w(t=e.file),T(null),_(t)},style:{display:"flex",alignItems:"center",gap:8,textAlign:"left",padding:"4px 6px",borderRadius:6,background:"none",border:"none",color:"var(--text)",fontSize:12,cursor:"pointer"},children:[(0,r.jsx)(dx.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:()=>w(null),style:{background:"none",border:"none",cursor:"pointer",color:"var(--text-muted)",padding:2,display:"flex"},children:(0,r.jsx)(p.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===f.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:[...f].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:A,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)(S.l,{size:13,"aria-hidden":"true"}),h("tasks.delete")]})})]})})}var dm=o(17757);function dk({open:e,onOpenChange:t,task:o,defaultProject:s,projects:i,prefillTitle:a,prefillPrompt:l,onSubmit:d}){let{t:c}=(0,D.s)(),[u,g]=(0,n.useState)(""),[h,x]=(0,n.useState)(""),[f,m]=(0,n.useState)(""),[k,v]=(0,n.useState)([]),[y,b]=(0,n.useState)(""),[w,j]=(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]??""),x(o?.title??a??""),m(o?.config?.prompt??l??""),(0,nP.VB)().then(v).catch(()=>void 0))},[e,o,s,i,a,l]),!e)return null;let T=async()=>{if(u&&h.trim()&&!w){j(!0);try{await d(u,h.trim(),{prompt:f.trim(),agentType:o?.config?.agentType??null,modelId:o?.config?.modelId??null,thinkingLevel:o?.config?.thinkingLevel??null}),t(!1)}catch(e){console.error("submit task failed",e)}finally{j(!1)}}},R=async()=>{if(y.trim()&&h.trim())try{await (0,nP.nY)({name:y.trim(),title:h.trim(),config:{prompt:f.trim()}}),b(""),(0,nP.VB)().then(v).catch(()=>void 0)}catch(e){console.error("save template failed",e)}},z=async e=>{try{await (0,nP.B_)(e),(0,nP.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?c("tasks.editTitle"):c("tasks.newTitle")}),(0,r.jsx)("button",{type:"button",onClick:()=>t(!1),"aria-label":c("i18n.close"),style:{background:"none",border:"none",cursor:"pointer",color:"var(--text-muted)",padding:4,display:"flex"},children:(0,r.jsx)(p.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:c("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:()=>{x(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":c("tasks.deleteTemplate"),style:{background:"none",border:"none",cursor:"pointer",color:"var(--text-dim)",padding:0,display:"flex"},children:(0,r.jsx)(S.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:c("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:c("tasks.fieldTitle")}),(0,r.jsx)("input",{value:h,onChange:e=>x(e.target.value),placeholder:c("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:c("tasks.fieldPrompt")}),(0,r.jsx)("textarea",{value:f,onChange:e=>m(e.target.value),placeholder:c("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:c("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)(dm.D,{size:13,"aria-hidden":"true"}),c("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:c("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:c("tasks.save")})]})]})]})})}function dv({open:e,onOpenChange:t,task:o}){let{t:s}=(0,D.s)(),{refetch:i}=l6(),[a,l]=(0,n.useState)(!0),[d,c]=(0,n.useState)(""),[u,g]=(0,n.useState)(!0),[h,x]=(0,n.useState)(!1);if((0,n.useEffect)(()=>{e&&o&&(l(!0),c(o.title),x(!1),(0,nP.CG)(o.projectRoot).then(e=>g(e.deleteWorktreeDefault)).catch(()=>g(!0)))},[e,o]),!e||!o)return null;let f=async()=>{if((a||d.trim())&&!h){x(!0);try{await (0,nP.oB)(o.id,o.projectRoot,a?null:d.trim(),u),t(!1),i()}catch(e){console.error("merge failed",e)}finally{x(!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)(p.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=>c(e.target.value),placeholder:s("tasks.mergeMessagePlaceholder"),style:{width:"100%",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:8,padding:"8px 10px",color:"var(--text)",fontSize:13,outline:"none",fontFamily:"inherit"}}),(0,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 f(),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 dy({open:e,onOpenChange:t,task:o,kind:s}){let{t:i}=(0,D.s)(),{refetch:a}=l6(),[l,d]=(0,n.useState)(""),[c,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(!c){u(!0);try{await (0,nP.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)(p.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:c,style:{padding:"8px 14px",borderRadius:8,background:"none",border:"1px solid var(--border)",color:"var(--text)",fontSize:12,cursor:"pointer"},children:i("i18n.cancel")}),(0,r.jsx)("button",{type:"button",onClick:()=>void h(),disabled:c,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 db=["work","retry","return","merge"];function dw({open:e,onOpenChange:t,projectRoot:o}){let{t:s}=(0,D.s)(),{projects:i}=l6(),[a,l]=(0,n.useState)(""),[d,c]=(0,n.useState)(()=>dr()),[u,g]=(0,n.useState)(!1),[h,x]=(0,n.useState)(!1);if((0,n.useEffect)(()=>{if(!e)return;let t=o??i[0]??"";l(t),t&&(0,nP.Pf)(t).then(e=>{g(null!=e),c(e??dr())}).catch(()=>{g(!1),c(dr())})},[e,o,i]),!e)return null;let f=(e,t)=>{c(o=>({...o,[e]:t}))},m=async()=>{if(a&&!h){x(!0);try{await (0,nP.eA)(a,d),g(!0),t(!1)}catch(e){console.error("save settings failed",e)}finally{x(!1)}}},k=async()=>{if(a)try{await (0,nP.E)(a),g(!1),c(dr())}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)(p.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=>f("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=>f("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=>f("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=>f("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=>f("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=>f("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")}),db.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=>f("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 dj({open:e,onOpenChange:t,task:o}){let{t:s}=(0,D.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)(p.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 dS="__all__",dC="pi-tasks-board-filter",dT={showCanceled:!1,showArchived:!1},dR="pi:open-task-settings";function dz(){let{t:e}=(0,D.s)(),{attentionCount:t}=l6();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)(aS.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(dR)),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)(l8.O,{size:13,"aria-hidden":"true"}),e("tasks.settingsTitle")]})]})}function dI({activeProject:e}){let{t}=(0,D.s)(),{tasks:s,projects:i,refetch:a}=l6(),[l,c]=(0,n.useState)(null),[p,u]=(0,n.useState)(()=>(function(){try{let e=window.localStorage.getItem(dC);if(e){let t=JSON.parse(e);return{showCanceled:t.showCanceled??!1,showArchived:t.showArchived??!1}}}catch{}return dT})()),[g,h]=(0,n.useState)(!1);(0,n.useEffect)(()=>{try{window.localStorage.setItem(dC,JSON.stringify(p))}catch{}},[p]);let[x,f]=(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[E,P]=(0,n.useState)(!1),[F,W]=(0,n.useState)(null),[$,N]=(0,n.useState)(null);(0,n.useEffect)(()=>{let e=()=>{let e,t=(e=rO,rO=null,e);t&&(W(null),N(t),P(!0))};return e(),window.addEventListener(rL,e),()=>window.removeEventListener(rL,e)},[]);let[A,L]=(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(dR,e),()=>window.removeEventListener(dR,e)},[]);let ec=(0,n.useMemo)(()=>null==l?s:s.filter(e=>e.projectRoot===l),[s,l]),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 de)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===A)??null,[s,A]),eh=(0,n.useMemo)(()=>s.find(e=>e.id===ei)??null,[s,ei]),ex=(0,n.useCallback)(async e=>{try{await e()}catch(e){console.error("task action failed",e)}finally{a()}},[a]),ef=(0,n.useCallback)(e=>{null!=e.conversationId&&(ea(e.id),ed(!0))},[ea,ed]),em=(0,n.useCallback)(e=>{H(e),U(!0)},[H,U]),ek=(0,n.useCallback)(()=>{W(null),P(!0)},[W,P]),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(f(null),v(!1),e){R.current=!1;return}requestAnimationFrame(()=>{R.current=!1})},[f,v]),ew=(0,n.useCallback)(()=>{z.current=!0,C(null),eb(!0)},[eb,C]);(0,n.useEffect)(()=>{if(!x)return;let e=()=>{document.hidden&&ew()};return window.addEventListener("blur",ew),document.addEventListener("visibilitychange",e),()=>{window.removeEventListener("blur",ew),document.removeEventListener("visibilitychange",e)}},[x,ew]),(0,n.useEffect)(()=>{x&&!eu.some(e=>e.id===x.task.id)&&ew()},[x,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!=l&&ex(()=>(0,nP.oQ)(e.id,e.projectRoot,"start"));return}let i=T.current;null!=l&&null!=i&&(async()=>{try{await (0,nP.Lu)(l,i)}catch(e){console.error("reorder failed",e)}await a(),C(null)})()},[ex,eb,l,a,s]),eS=(0,n.useCallback)(()=>{ex(async()=>{let e=await (0,nP.a5)(l);e>0&&console.log(`started ${e} tasks`)})},[ex,l]),eC=(0,n.useCallback)(()=>{let e=ep.done.filter(e=>null==e.archivedAt);0!==e.length&&ex(()=>Promise.all(e.map(e=>(0,nP.et)(e.id,e.projectRoot,!0))))},[ex,ep.done]),eT=+(p.showCanceled!==dT.showCanceled)+ +(p.showArchived!==dT.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:l??dS,onChange:e=>c(e.target.value===dS?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:dS,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)(l7.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)(l9.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)(m.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:dn.map(e=>{let o="todo"===e?eu:ep[e],n=ds[e],s=e=>(0,r.jsx)(dp,{task:e,folderName:e.projectRoot?eI.get(e.projectRoot)??null:null,now:I,onOpen:()=>{R.current||L(e.id)},onStart:()=>void ex(()=>(0,nP.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:()=>ef(e),onMerge:()=>{dt(e)?(et(e),er(!0)):em(e)},onArchive:()=>void ex(()=>(0,nP.et)(e.id,e.projectRoot,null==e.archivedAt)),onEdit:()=>{W(e),P(!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&&x?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&&x?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},f({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:x?.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)(aS.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)(m.F,{size:13,weight:"bold","aria-hidden":"true"}),t("tasks.new")]})]}),(0,r.jsx)(dk,{open:E,onOpenChange:P,task:F,defaultProject:$?.projectRoot??l??e??null,projects:ez,prefillTitle:$?$.text.slice(0,80):void 0,prefillPrompt:$?$.text:void 0,onSubmit:async(e,t,r)=>{await ex(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})}),P(!1),N(null)}}),(0,r.jsx)(df,{open:null!=A,onOpenChange:e=>{e||L(null)},task:eg,onViewSession:ef,onMerge:em,onEdit:e=>{W(e),P(!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)(dv,{open:B,onOpenChange:U,task:O}),(0,r.jsx)(du,{open:V,onOpenChange:K,task:_}),(0,r.jsx)(dy,{open:Z,onOpenChange:Q,task:J,kind:Y}),(0,r.jsx)(dg,{open:eo,onOpenChange:er,task:ee}),(0,r.jsx)(dj,{open:el&&null!=eh,onOpenChange:ed,task:eh}),(0,r.jsx)(dw,{open:en,onOpenChange:es,projectRoot:l}),x?(0,d.createPortal)((0,r.jsx)("div",{ref:w,style:{position:"fixed",left:0,top:0,zIndex:999,pointerEvents:"none",width:x.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:x.task.title}),(0,r.jsx)(dd,{task:x.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)(l9.j,{size:11,weight:"bold","aria-hidden":"true"}),t("tasks.dropToStart")]}):null]})}),document.body):null]})}var dM=o(62235);function dE({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)(ah.b,{size:16,"aria-hidden":"true"}):(0,r.jsx)(ag.A,{size:16,"aria-hidden":"true"}):(0,r.jsx)(ah.b,{size:16,"aria-hidden":"true"})})}function dP({topBarRef:e,sidebarOpen:t,onSidebarToggle:o,isDark:s,toggleTheme:i,isMobile:a,showTasks:l,tasksBoardEnabled:d,onToggleTasks:c,systemPrompt:p,activeTopPanel:u,topPanelPos:h,sessionStats:x,contextUsage:f,copiedSessionField:m,onCopySessionField:k,rightPanelOpen:v,onToggleFilePanel:b,onOpenSettings:w,sessionTitle:j,onWorkspaceControlsHostChange:S,onTitleRightHostChange:C}){let T,R,z,I,M,E,P,F,{t:W}=(0,D.s)(),[$,N]=(0,n.useState)(!1),[A,L]=(0,n.useState)(!1);return(0,n.useEffect)(()=>{try{L(new URLSearchParams(window.location.search).has("piweb_connected"))}catch{L(!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)(dM.V,{size:16,"aria-hidden":"true"}):(0,r.jsx)(y.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)(aS.x,{size:16,"aria-hidden":"true"})}),(0,r.jsx)("button",{className:"app-no-drag",onClick:b,title:v?W("desktop.hideFilePanel"):W("desktop.showFilePanel"),"aria-label":v?W("desktop.hideFilePanel"):W("desktop.showFilePanel"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:36,height:36,padding:0,background:v?"var(--bg-selected)":"none",border:"none",color:v?"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=v?"var(--bg-selected)":"none",e.currentTarget.style.color=v?"var(--text)":"var(--text-muted)"},children:(0,r.jsx)(dM.V,{size:16,"aria-hidden":"true",style:{transform:"scaleX(-1)"}})}),(0,r.jsx)(dE,{isDark:s,toggleTheme:i,translate:W}),A&&(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)(i2.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)(l8.O,{size:16,"aria-hidden":"true"})})]})]}),u&&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"===u&&(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"===u&&(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:x?(T=[...x.sessionName?[{label:W("desktop.name"),value:x.sessionName,copyField:null}]:[],{label:W("desktop.sessionInfoFile"),value:x.sessionFile??W("desktop.sessionInfoInMemory"),copyField:"file"},{label:W("desktop.sessionInfoId"),value:x.sessionId,copyField:"id"}],R=[[W("desktop.sessionInfoUser"),x.userMessages.toLocaleString()],[W("desktop.sessionInfoAssistant"),x.assistantMessages.toLocaleString()],[W("desktop.sessionInfoToolCalls"),x.toolCalls.toLocaleString()],[W("desktop.sessionInfoToolResults"),x.toolResults.toLocaleString()],[W("desktop.sessionInfoTotal"),x.totalMessages.toLocaleString()]],z=[[W("desktop.sessionInfoInput"),x.tokens.input.toLocaleString()],[W("desktop.sessionInfoOutput"),x.tokens.output.toLocaleString()],...x.tokens.cacheRead>0?[[W("desktop.sessionInfoCacheRead"),x.tokens.cacheRead.toLocaleString()]]:[],...x.tokens.cacheWrite>0?[[W("desktop.sessionInfoCacheWrite"),x.tokens.cacheWrite.toLocaleString()]]:[],[W("desktop.sessionInfoTotal"),x.tokens.total.toLocaleString()]],I=f??x.contextUsage,E=[...x.cost>0?[[W("desktop.sessionInfoCost"),`$${x.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)}`]]:[]],P=(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)(g.J,{size:12,"aria-hidden":"true"}):(0,r.jsx)(tx.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,P(W("desktop.sessionInfoMessages"),R),P(W("desktop.sessionInfoTokens"),[...z,...E],"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 dD({cwd:e,busy:t,error:o,onCancelAction:n,onConfirmAction:s}){let{t:i}=(0,D.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)(rN.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 dF(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 dW(e){return dF(.42*e,360,640)}function d$(e,t){try{window.localStorage.setItem(e,String(t))}catch{}}function dN(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),[x,f]=(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=>dF(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),f(n),r&&(s||o)&&d$(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&&d$(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":x,"aria-valuetext":`${x} px`,onDoubleClick:M,onKeyDown:P,onLostPointerCapture:I,onPointerCancel:z,onPointerDown:C,onPointerMove:T,onPointerUp:R,role:"separator",tabIndex:0},width:x}}function dA(){let e,t,o,d=(0,a.useRouter)(),c=(0,a.useSearchParams)(),p=(0,n.useMemo)(()=>{let e;return{requestedCwd:e=c.get("cwd")?.trim()||null,sessionId:e?null:c.get("session")}},[c]),{isDark:u,toggleTheme:g}=oc(),{t:h}=(0,D.s)(),x=A(),[f,m]=(0,n.useState)(null),[k,v]=(0,n.useState)(null),[y,b]=(0,n.useState)(0),[w,j]=(0,n.useState)(0),[S,C]=(0,n.useState)(0),[T,R]=(0,n.useState)(!1),[z,I]=(0,n.useState)("models"),[M,E]=(0,n.useState)(0),[P,F]=(0,n.useState)(null),[W,$]=(0,n.useState)(!1),[N,L]=(0,n.useState)(!1),[O,H]=(0,n.useState)(null),[B,U]=(0,n.useState)(!0),[_,q]=(0,n.useState)(!1);(0,n.useEffect)(()=>{x&&U(!1)},[x]),(0,n.useEffect)(()=>{q(!0)},[]);let V=(0,n.useRef)(null),K=(0,n.useRef)(null),[J,G]=(0,n.useState)(null),[Y,X]=(0,n.useState)(null),[Z,Q]=(0,n.useState)(null),[ee,et]=(0,n.useState)(null),eo=(0,n.useCallback)(e=>{et(e)},[]),[er,en]=(0,n.useState)(null),ei=(0,n.useCallback)(e=>{en(e)},[]),[ea,el]=(0,n.useState)([]),ed=(0,n.useCallback)(e=>{el(e)},[]),ec=ea.filter(e=>"running"===e.status).length,[ep,eu]=(0,n.useState)(null),eg=(0,n.useRef)(null),eh=(0,n.useCallback)((e,t)=>{op(t).then(()=>{eg.current&&clearTimeout(eg.current),eu(e),eg.current=setTimeout(()=>eu(null),1400)})},[]);(0,n.useEffect)(()=>()=>{eg.current&&clearTimeout(eg.current)},[]);let[ex,ef]=(0,n.useState)(null),em=(0,n.useCallback)(e=>{ef(e)},[]),[ek,ev]=(0,n.useState)(null),[ey,eb]=(0,n.useState)(null),ew=(0,n.useCallback)(()=>{x&&U(!1),ev("session")},[x]),ej=(0,n.useCallback)(()=>{x&&ev(null),U(e=>!e)},[x]);(0,n.useEffect)(()=>{if(!ek||!K.current)return;let e=()=>{let e=K.current.getBoundingClientRect();eb({top:e.bottom,left:e.left,width:e.width})};e();let t=new ResizeObserver(e);return t.observe(K.current),()=>t.disconnect()},[ek]);let[eS,eC]=(0,n.useState)([]),[eR,ez]=(0,n.useState)(null),[eI,eM]=(0,n.useState)(!1),[eE,eP]=(0,n.useState)(!1),[eD,eF]=(0,n.useState)(null),eW=(0,n.useCallback)(e=>{eF(e??null),eP(!0),eM(!0),x&&U(!1)},[x]),e$=(0,n.useCallback)(()=>{eP(!1),eF(null)},[]),[eN,eL]=(0,n.useState)(null),eO=(0,n.useCallback)(e=>eL(e),[]),eH=(0,n.useCallback)(()=>eL(null),[]);(0,n.useEffect)(()=>{if(!eN)return;let e=e=>{"Escape"===e.key&&(e.stopImmediatePropagation(),e.preventDefault(),eL(null))};return window.addEventListener("keydown",e,!0),()=>window.removeEventListener("keydown",e,!0)},[eN]);let eB=(0,n.useRef)(260),eU=(0,n.useRef)(dW(1366)),e_=(0,n.useCallback)(()=>dW(window.innerWidth),[]),eq=(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:eI,rightPanelWidth:eU.current}),[eI]),eV=(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:B,sidebarWidth:eB.current}),[B]),eK=dN({ariaLabel:h("desktop.resizeSidebar"),cssVariable:"--sidebar-width",defaultWidth:260,getMaxWidth:eq,growthDirection:"right",maxWidth:480,minWidth:180,storageKey:"pi-sidebar-width",widthRef:eB}),eJ=dN({ariaLabel:h("desktop.resizeFilePanel"),cssVariable:"--right-panel-width",defaultWidth:dW(1366),getDefaultWidth:e_,getMaxWidth:eV,growthDirection:"left",maxWidth:1200,minWidth:300,storageKey:"pi-right-panel-width",widthRef:eU}),eY=eK.reclampWidth,eX=eJ.reclampWidth;(0,n.useEffect)(()=>{eI&&(eY(),eX())},[eX,eY,eI]);let eZ=(0,n.useCallback)((e,t)=>{V.current?.insertText(nE(e,t))},[]),eQ=(0,n.useCallback)(e=>{let t=e.map(e=>nE(e,!1)).join("");t&&V.current?.insertText(t)},[]),e0=(0,n.useCallback)((e,t,o)=>{let r,n,s,i;V.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} `))},[]),[e1,e2]=(0,n.useState)(()=>p.sessionId),[e4,e6]=(0,n.useState)(null),[e5,e3]=(0,n.useState)(()=>p.requestedCwd?"validating":"idle"),[e8,e7]=(0,n.useState)(null),[e9,te]=(0,n.useState)(()=>!e1),tt=(0,n.useRef)(!1),to=(0,n.useRef)(new Map),[tr,tn]=(0,n.useState)(null),ts=(0,n.useRef)("");(0,n.useEffect)(()=>{let e=`${p.requestedCwd??""}|${p.sessionId??""}`;ts.current!==e&&(ts.current=e,e2(p.sessionId),te(!p.sessionId),p.requestedCwd||e3("idle"),e7(null))},[p]),(0,n.useEffect)(()=>{let e=p.requestedCwd;if(!e)return;let t=new AbortController;return e3("validating"),e7(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}`);tt.current=!0,v(t.cwd),e3("ready")}).catch(e=>{t.signal.aborted||(e7(e instanceof Error?e.message:String(e)),e3("error"))}),()=>t.abort()},[p]);let ti=(0,n.useCallback)((e,t)=>{if(!e)return;if(e6(e),tt.current&&f&&eT(f.projectRoot??f.cwd,t??e)){if(tt.current=!1,f){let e=f.projectRoot??f.cwd;e&&to.current.set(e,f.id)}return}tt.current=!1;let o=t??e;if(f&&eT(f.projectRoot??f.cwd,o)){(f.projectRoot??f.cwd)&&to.current.set(o,f.id);return}if(f){let e=f.projectRoot??f.cwd;e&&to.current.set(e,f.id)}m(null),v(t=>t&&t!==e?null:t),j(e=>e+1),et(null),ev(null),window.history.replaceState(null,"","/");let r=to.current.get(o);tn(r?{projectRoot:o,sessionId:r}:null)},[f]);(0,n.useEffect)(()=>{let e=e4?es(e4)||e4:null;document.title=e?`${e} — Pi Agent Web`:"Pi Agent Web"},[e4]);let ta=(0,n.useCallback)((e,t=!1)=>{if(t||tn(null),!t&&f){let t=eT(f.projectRoot??f.cwd,e.projectRoot??e.cwd);if(f.id===e.id&&t){x&&U(!1);return}}let o=e.projectRoot??e.cwd;o&&to.current.set(o,e.id),v(null),m(e),j(e=>e+1),et(null),te(!0),x&&!t&&U(!1),t&&(tt.current=!0),t||window.history.replaceState(null,"",`?session=${encodeURIComponent(e.id)}`)},[x,f]),tl=(0,n.useRef)(()=>{});(0,n.useEffect)(()=>{tl.current=ta},[ta]);let td=(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&&m(t=>!t||t.id!==e||t.projectRoot&&t.name?t:o)}).catch(()=>{})},[]);(0,n.useEffect)(()=>{if(!tr)return;let{projectRoot:e,sessionId:t}=tr;tl.current({path:"",id:t,cwd:e,created:"",modified:"",messageCount:0,firstMessage:"",projectRoot:e},!0),td(t),window.history.replaceState(null,"",`?session=${encodeURIComponent(t)}`),tn(null)},[tr,td]);let tc=(0,n.useCallback)((e,t)=>{tn(null),m(null),v(t),j(e=>e+1),et(null),ev(null),x&&U(!1),window.history.replaceState(null,"","/")},[d,x]);!function(e){let{onNewSession:t,activeCwd:o}=e;(0,n.useEffect)(()=>{let e=e=>{if("Escape"===e.key){if(!l)return;let t=e.target?.tagName;if("TEXTAREA"===t||"INPUT"===t)return;e.preventDefault(),l();return}if("n"===e.key&&e.ctrlKey&&e.altKey){if(!o||!t)return;e.preventDefault(),t(o)}};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[o,t])}({onNewSession:e=>tc(`kb-${Date.now()}`,e),activeCwd:e4});let tp=(0,n.useCallback)(e=>{v(null),tn(null);let t=e.projectRoot??e.cwd;t&&to.current.set(t,e.id),m(e),e.cwd&&e6(e.cwd),b(e=>e+1),td(e.id),window.history.replaceState(null,"",`?session=${encodeURIComponent(e.id)}`),window.setTimeout(()=>b(e=>e+1),1200),window.setTimeout(()=>b(e=>e+1),4e3)},[d,td]),tu=(0,n.useCallback)(()=>{b(e=>e+1),C(e=>e+1)},[]),tg=(0,n.useCallback)(e=>{b(e=>e+1),j(e=>e+1),v(null),tn(null),m(t=>{let o={...t??{path:"",cwd:"",created:"",modified:"",messageCount:0,firstMessage:""},id:e},r=o.projectRoot??o.cwd;return r&&to.current.set(r,e),o}),td(e),window.history.replaceState(null,"",`?session=${encodeURIComponent(e)}`)},[d,td]),th=(0,n.useCallback)(()=>{te(!0)},[]),tx=(0,n.useCallback)(e=>{if(b(e=>e+1),f?.id===e){let e=f.cwd;m(null),v(e??null),j(e=>e+1),et(null),ev(null),window.history.replaceState(null,"","/")}},[d,f]),tf=(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}`;eC(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}]}),ez(i),eM(!0),x&&U(!1)},[x]),tm=(0,n.useCallback)(e=>{tf(e,es(e),f?.id??null)},[tf,f?.id]),tk=(0,n.useCallback)(e=>{eC(t=>{let o=t.filter(t=>t.id!==e);return 0===o.length&&eM(!1),o}),ez(t=>{if(t!==e)return t;let o=eS.filter(t=>t.id!==e);return o.length>0?o[o.length-1].id:null})},[eS]),tv=f?eA(f.name||er?.sessionName)||f.firstMessage.slice(0,50)||f.id.slice(0,12):(e=e4??k)?e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e:null,ty=(0,n.useCallback)(()=>{f&&window.open(`/api/sessions/${encodeURIComponent(f.id)}/export?inline=1`,"_blank","noopener,noreferrer")},[f]),tb=k??(null===f&&e4?e4:null),tw="validating"!==e5&&"error"!==e5&&(null!==f||null!==tb),tj=f?.id;(0,n.useEffect)(()=>{eN&&eL(null)},[tj,tw]);let tS=f?.cwd??tb,[tC,tT]=(0,n.useState)(!1),tR=(0,n.useCallback)(()=>{x||tT(e=>!e)},[x]),[tz,tI]=(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&&(tI(t.tasksBoard),t.tasksBoard||tT(!1))}).catch(()=>{});t();let o=()=>t();return window.addEventListener("pi:features-changed",o),()=>{e=!0,window.removeEventListener("pi:features-changed",o)}},[]);let tM=e9&&!tw;(0,n.useEffect)(()=>{let e=()=>{x||tT(!0)};return window.addEventListener(iw,e),()=>window.removeEventListener(iw,e)},[x]),(0,n.useEffect)(()=>{if(F(null),$(!1),H(null),!tS)return;let e=new AbortController;return fetch(`/api/project-trust?cwd=${encodeURIComponent(tS)}`,{signal:e.signal}).then(async e=>{let t=await e.json();if(!e.ok||t.error)throw Error(t.error??`HTTP ${e.status}`);F(t)}).catch(e=>{e instanceof DOMException&&"AbortError"===e.name||console.error("Failed to load project trust:",e)}),()=>e.abort()},[tS]);let tE=(0,n.useCallback)(async()=>{if(tS&&!N){L(!0),H(null);try{let e=await fetch("/api/project-trust",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:tS})}),t=await e.json();if(!e.ok||t.error)throw Error(t.error??`HTTP ${e.status}`);F(t),$(!1),E(e=>e+1),j(e=>e+1)}catch(e){H(e instanceof Error?e.message:String(e))}finally{L(!1)}}},[N,tS]),tP=eS.find(e=>e.id===eR)??null,tD=e4??f?.cwd??k,tF=(0,n.useCallback)(e=>{I(e),R(!0)},[]),tW=(0,r.jsx)(r.Fragment,{children:(0,r.jsx)(eG,{selectedSessionId:f?.id??null,onSelectSession:ta,onNewSession:tc,initialSessionId:e1,onInitialRestoreDone:th,refreshKey:y,onSessionDeleted:tx,selectedCwd:f?.cwd??k??null,onCwdChange:ti,onOpenFile:tf,selectedSessionStats:er,onOpenSettings:e=>{tF(["models","skills","plugins","chat","features","logs"].includes(e)?e:"models")},explorerRefreshKey:S,onAtMention:eZ,onAtMentions:eQ,workspaceControlsHosts:{title:J,welcome:Z,titleRight:Y},showWorkspaceControls:!0})});return(0,r.jsxs)(l5,{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;
|