@eezd/pi-web 0.17.0-custom.3 → 0.17.0-custom.4
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 +13 -13
- package/.next/build-manifest.json +2 -2
- package/.next/prerender-manifest.json +3 -3
- package/.next/required-server-files.js +1 -1
- package/.next/required-server-files.json +1 -1
- package/.next/server/app/_global-error/page_client-reference-manifest.js +1 -1
- package/.next/server/app/_global-error.html +1 -1
- package/.next/server/app/_global-error.rsc +1 -1
- package/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
- package/.next/server/app/_global-error.segments/_global-error/__PAGE__.segment.rsc +1 -1
- package/.next/server/app/_global-error.segments/_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 +3 -3
- package/.next/server/app/_not-found.segments/_full.segment.rsc +3 -3
- package/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +3 -3
- package/.next/server/app/_not-found.segments/_tree.segment.rsc +2 -2
- package/.next/server/app/api/app-update/route.js +1 -1
- package/.next/server/app/index.html +1 -1
- package/.next/server/app/index.rsc +4 -4
- package/.next/server/app/index.segments/__PAGE__.segment.rsc +4 -4
- package/.next/server/app/index.segments/_full.segment.rsc +4 -4
- package/.next/server/app/index.segments/_tree.segment.rsc +2 -2
- package/.next/server/app/login/page_client-reference-manifest.js +1 -1
- package/.next/server/app/login.html +1 -1
- package/.next/server/app/login.rsc +3 -3
- package/.next/server/app/login.segments/_full.segment.rsc +3 -3
- package/.next/server/app/login.segments/_tree.segment.rsc +2 -2
- package/.next/server/app/login.segments/login/__PAGE__.segment.rsc +3 -3
- 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 +13 -13
- package/.next/server/middleware-build-manifest.js +1 -1
- package/.next/server/pages/404.html +1 -1
- package/.next/server/pages/500.html +1 -1
- package/.next/server/preview-props.json +3 -3
- package/.next/server/route-cache/APP_PAGE/c6377dd9ce6a1c2cd100eb4344e843eb4639b9ed26f84643f77680e9eb454c4b/$/index.html +1 -1
- package/.next/server/route-cache/APP_PAGE/c6377dd9ce6a1c2cd100eb4344e843eb4639b9ed26f84643f77680e9eb454c4b/$/index.meta +1 -1
- package/.next/server/route-cache/APP_PAGE/c6377dd9ce6a1c2cd100eb4344e843eb4639b9ed26f84643f77680e9eb454c4b/$/index.rsc +4 -4
- package/.next/server/route-cache/APP_PAGE/c6377dd9ce6a1c2cd100eb4344e843eb4639b9ed26f84643f77680e9eb454c4b/$/index.segments/__PAGE__.segment.rsc +4 -4
- package/.next/server/route-cache/APP_PAGE/c6377dd9ce6a1c2cd100eb4344e843eb4639b9ed26f84643f77680e9eb454c4b/$/index.segments/_full.segment.rsc +4 -4
- package/.next/server/route-cache/APP_PAGE/c6377dd9ce6a1c2cd100eb4344e843eb4639b9ed26f84643f77680e9eb454c4b/$/index.segments/_tree.segment.rsc +2 -2
- package/.next/server/server-reference-manifest.json +1 -1
- package/.next/static/chunks/app/{layout-1daeb3e8cc2e3493.js → layout-690d61706d75b155.js} +1 -1
- package/.next/static/chunks/app/{page-ac3fa1f0061f8cf6.js → page-1da0cb7e99d29979.js} +3 -3
- package/.next/static/css/{93cf980bee047c9c.css → 1754997741d435bb.css} +1 -1
- package/.next/trace +188 -187
- package/.next/trace-build +1 -1
- package/package.json +2 -2
- /package/.next/static/{35CWubAbK7BUsJKQld6VI → 8CGVcbxFHnRG56r0g0kJA}/_buildManifest.js +0 -0
- /package/.next/static/{35CWubAbK7BUsJKQld6VI → 8CGVcbxFHnRG56r0g0kJA}/_ssgManifest.js +0 -0
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[8974],{5284:e=>{e.exports={lock:"LockToggle_lock__hI4qs"}},14755:(e,t,n)=>{"use strict";n.d(t,{Q8:()=>r,YO:()=>h,getPresetFromTools:()=>p,kU:()=>o,kt:()=>d,sn:()=>u,xG:()=>f});let r="configured",i=["configured","none","read-only","default","full"],s=[],o=["read","grep","find","ls"],l=["read","bash","edit","write"],a=["bash","read","edit","write","grep","find","ls"],d=["read","grep","find","ls","edit","write","bash"],c=new Set([...a,"powershell"]);function u(e){return"string"==typeof e&&i.includes(e)}function p(e){return h(e.filter(e=>e.active).map(e=>e.name))}function h(e){if(0===e.length)return"none";let t=e.map(e=>"powershell"===e?"bash":e).filter(e=>c.has(e)).sort().join(",");return t===[...o].sort().join(",")?"read-only":t===[...l].sort().join(",")?"default":t===[...a].sort().join(",")?"full":"default"}function f(e){if(e!==r)return"none"===e?[...s]:"read-only"===e?[...o]:"full"===e?[...a]:[...l]}},42927:(e,t,n)=>{Promise.resolve().then(n.bind(n,44678)),Promise.resolve().then(n.bind(n,21278))},44678:(e,t,n)=>{"use strict";n.d(t,{AppShell:()=>wj});var r=n(95155),i=n(12115),s=n(73321);let o=null;function l(e,t,n){if(e.name&&"Side chat"!==e.name)return e.name;let r=n.filter(e=>e.relation?.kind==="side").sort((e,t)=>e.created.localeCompare(t.created)||e.id.localeCompare(t.id)).findIndex(t=>t.id===e.id);return r<0?t:`${t} ${r+1}`}function a(e){return e?.kind==="subagent"||e?.kind==="side"}function d(e){let t=function(e){let t=new Map(e.map(e=>[e.id,e])),n=new Map;for(let r of e){if(n.has(r.id))continue;let e=[],i=new Set,s=r.id,o=null;for(;;){if(n.has(s)){o=n.get(s)??null;break}if(i.has(s))break;i.add(s),e.push(s);let r=t.get(s);if(!r)break;if(!a(r.relation)){o=r.id;break}s=r.relation.parentSessionId}for(let t of e)n.set(t,o)}return n}(e),n=new Map;for(let t of e)a(t.relation)||n.set(t.id,{root:t,subagents:[],latestModified:t.modified});for(let r of e){if(!a(r.relation))continue;let e=t.get(r.id),i=e?n.get(e):void 0;i&&(i.subagents.push(r),r.modified>i.latestModified&&(i.latestModified=r.modified))}return[...n.values()].sort((e,t)=>t.latestModified.localeCompare(e.latestModified))}function c(e,t){return t?d(e).find(e=>e.root.id===t||e.subagents.some(e=>e.id===t))??null:null}function u(e,t){return e.filter(e=>t.has(e.id)).length}function p(e){return`?session=${encodeURIComponent(e)}`}let h="pi-web:last-open-by-workspace";function f(){try{return window.localStorage}catch{return null}}function m(e){let t=e.getItem(h);if(!t)return{};try{let e=JSON.parse(t);return null===e||"object"!=typeof e||Array.isArray(e)?{}:e}catch{return{}}}function g(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:f();if(t)try{let n=m(t);if(!(e in n))return;delete n[e],0===Object.keys(n).length?t.removeItem(h):t.setItem(h,JSON.stringify(n))}catch{}}function x(e){return e.projectKey??e.projectRoot??e.cwd}function v(e){let t=new Map;for(let n of e){let e=n.projectRoot??n.cwd;if(!e)continue;let r=x(n),i=t.get(r);(!i||n.modified>i.modified)&&t.set(r,{root:e,modified:n.modified})}return[...t.entries()].sort((e,t)=>t[1].modified.localeCompare(e[1].modified)).map(e=>{let[t,{root:n}]=e;return{key:t,root:n}})}let b=/^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/,y=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);function w(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function k(e){return"number"==typeof e&&Number.isFinite(e)&&e>=0}function j(e){return"string"==typeof e&&b.test(e)}function S(e){return"string"==typeof e&&e.length>0&&e.length<=4096&&"__proto__"!==e}let C=/[\u0000-\u001f\u007f-\u009f\u2028\u2029]/;function N(e){if(null===e)return null;if("string"!=typeof e)return;let t=e.trim();return t?C.test(t)||[...t].length>80?void 0:t:null}let E=new TextEncoder;function $(e){return E.encode(JSON.stringify(e)).length+1}function I(e){let t=1;for(let n of e)t+=$(n);return t}function M(e,t){return e<=1e3&&t<=262144}function T(e){let t=[],n=1;for(let r of e){if(t.length>=1e3)break;let e=$(r);n+e>262144||(t.push(r),n+=e)}return t}function R(e,t){return E.encode(JSON.stringify(e)).length+E.encode(JSON.stringify(t)).length+2}function A(e,t){return e<=1e3&&t<=262144}function L(){return{version:1,revision:0,sessions:{},projects:{}}}function z(e){let t=Object.entries(e);return t.length<=2e3?e:(t.sort((e,t)=>t[1]-e[1]),Object.fromEntries(t.slice(0,2e3)))}function P(e,t,n){let r=y(e,t)?e[t]:void 0;return void 0===n.pinnedAt&&void 0===n.archivedAt?!!r&&(delete e[t],!0):(r?.pinnedAt!==n.pinnedAt||r?.archivedAt!==n.archivedAt)&&(e[t]=n,!0)}function W(e,t){var n;return n=e.projectOrder??[],!(n.length===t.length&&n.every((e,n)=>e===t[n]))&&(0===t.length?delete e.projectOrder:e.projectOrder=t,!0)}function O(e,t){let n=new Set(e),r=[];for(let e of t)n.has(e)||(n.add(e),r.push(e));return r}function F(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:500,n=Math.max(1,Math.floor(t)),r=[];for(let t=0;t<e.length;t+=n)r.push(e.slice(t,t+n));return r}let D={desktop:{"pinned-header":28,session:28,"pinned-more":26,group:28,"group-more":26,"group-empty":28,spacer:8,"footer-open":28,"footer-archived":28,"archive-group":28},mobile:{"pinned-header":44,session:44,"pinned-more":36,group:44,"group-more":36,"group-empty":44,spacer:8,"footer-open":44,"footer-archived":44,"archive-group":44}},B="pinned";function H(e,t){return Object.hasOwn(e.sessions,t)?e.sessions[t]:void 0}function _(e){return"number"==typeof e&&Number.isFinite(e)?e:null}function U(e,t){return e===t?0:e>t?-1:1}function K(e){return[e.root.id,...e.subagents.map(e=>e.id)]}function q(e,t){return 0!==t.size&&(t.has(e.root.id)||e.subagents.some(e=>t.has(e.id)))}function V(e,t,n){let r=_(H(t,e.root.id)?.archivedAt);if(null===r||q(e,n))return!1;if(e.root.detailsPending)return!0;let i=Date.parse(e.root.modified);return Number.isNaN(i)||r>=i}function Z(e,t,n){return null!==_(H(t,e.root.id)?.pinnedAt)&&!V(e,t,n)}function J(e){let t=e.replace(/[\\/]+$/,"");if(!t)return e.charAt(0);let n=Math.max(t.lastIndexOf("/"),t.lastIndexOf("\\"));return t.slice(n+1)}function Y(e,t){if(Object.hasOwn(t,e.key)){let n=t[e.key];if("boolean"==typeof n)return n}return e.current||e.pinned}function G(e,t){var n;return{running:q(e,t.runningIds),awaiting:!!t.awaitingIds&&q(e,t.awaitingIds),unread:q(e,t.unreadIds),selected:!!(n=t.selectedSessionId)&&(e.root.id===n||e.subagents.some(e=>e.id===n)),transient:!0===e.root.transient}}function X(e,t){let n=0,r=0,i=0;for(let s of e)t.awaitingIds&&q(s,t.awaitingIds)?r++:q(s,t.runningIds)&&n++,q(s,t.unreadIds)&&i++;return{running:n,awaiting:r,unread:i}}function Q(e){return x(e.root)}function ee(e,t){let n=new Map,r=new Map;return{noteFamily(e){let t=Q(e);n.has(t)||n.set(t,e.root.projectRoot??e.root.cwd)},get(i){let s,o=r.get(i);if(o)return o;let l=Object.hasOwn(e.projects,i)?e.projects[i]:void 0,a=null!==t&&t.key===i,d=n.get(i)??(a?t.root:void 0)??l?.root??i,c=((s=e.projectNames)&&y(s,i)?s[i]:void 0)??null,u={key:i,root:d,name:c??J(d),customName:c,pinned:void 0!==l,current:a};return r.set(i,u),u}}}function et(e,t,n,r){return{kind:"session",key:`session:${t}:${e.root.id}`,family:e,context:t,project:n,status:G(e,r)}}function en(e,t,n,r){let i=e.map((e,n)=>{if(n<t)return!1;let i=G(e,r);return i.running||i.unread||i.selected}),s=t+n,o=0,l=e.filter((e,n)=>n<t||!!i[n]||n<s&&(o++,!0)),a=Math.max(t,Math.min(s,e.length));for(let t=0;a<e.length&&t<20;a++)!i[a]&&t++;return{visible:l,revealed:o,nextShown:a-t}}function er(e,t){if(!Object.hasOwn(e,t))return 0;let n=e[t];return"number"==typeof n&&Number.isFinite(n)&&n>0?Math.floor(n):0}function ei(e,t){if(!Object.hasOwn(e,t))return e;let n={...e};return delete n[t],n}function es(e,t,n){let r=e-t,i=n>0;return r>0||i?{hidden:r,canShowLess:i}:null}function eo(e,t,n,r){let i=r-n,s=[];for(let n of d(e.sessions)){if(Q(n)!==t||V(n,e.uiState,e.runningIds)||Z(n,e.uiState,e.runningIds))continue;let r=G(n,e);if(r.running||r.unread||r.selected||r.transient)continue;let o=Date.parse(n.latestModified);Number.isNaN(o)||o>=i||s.push(n.root.id)}return s}function el(e,t){let n=[],r=0;for(let i of d(e.sessions))if(Q(i)===t&&!i.root.transient){if(q(i,e.runningIds)||e.awaitingIds&&q(i,e.awaitingIds)){r++;continue}n.push(i.root.id)}return{ids:n,running:r}}function ea(e,t,n){let r=e.find(e=>e.key===t);if(!r)return null;let i=e.filter(e=>e.pinned===r.pinned),s=i.indexOf(r),o=i["up"===n?s-1:s+1];return o?{anchorKey:o.key,position:"up"===n?"before":"after"}:null}function ed(e,t,n,r,i){if(!Number.isInteger(t)||t<0||t>=e.length-1)return null;let s=e[t],o=e[t+1];return"start"===i?s===n?null:s:s>=n&&o<=n+r?null:"nearest"===i&&o>n&&s<n+r?s<n||o-s>r?s:o-r:Math.max(0,s-Math.max(0,(r-(o-s))/2))}let ec="pi-web:sidebar-tab",eu="pi-web:sidebar-groups-v2",ep="pi-web:sidebar-groups",eh="pi-web:sidebar-archive-collapsed",ef="pi-web:sidebar-pins-collapsed",em="pi-web:sidebar-files-show-ignored",eg="pi-web:sidebar-files-collapsed",ex="pi-web:sidebar-changes-view-mode",ev="pi-web:sidebar-non-git-cwds",eb=["pi-web:file-explorer:open","pi-web:sidebar-session-pane-height",ep];function ey(){try{return window.localStorage}catch{return null}}function ew(e){let t={};if(null===e||"object"!=typeof e||Array.isArray(e))return t;for(let[n,r]of Object.entries(e))"__proto__"!==n&&"boolean"==typeof r&&(t[n]=r);return t}function ek(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:ey();if(t)try{let n=Object.entries(ew(e)),r=n.length>300?n.slice(n.length-300):n;t.setItem(eu,JSON.stringify(Object.fromEntries(r)))}catch{}}function ej(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:ey();if(t)try{t.setItem(eh,JSON.stringify([...new Set(e)].slice(-300)))}catch{}}function eS(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:ey();if(t)try{t.setItem(ef,String(e))}catch{}}function eC(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:ey();if(!e)return[];try{let t=e.getItem(ev),n=null===t?[]:JSON.parse(t);if(!Array.isArray(n))return[];return n.filter(e=>"string"==typeof e&&""!==e).slice(-50)}catch{return[]}}async function eN(e,t){let n={deletedRoots:[],deleted:[],running:[],error:null};for(let r=0;r<e.length;r+=500){let i=e.slice(r,r+500);try{let e=await t("/api/sessions/delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({ids:i})}),r=await e.json().catch(()=>({}));if(!e.ok||!Array.isArray(r.deleted)){n.error=r.error??`HTTP ${e.status}`;break}let s=new Set(r.deleted);n.deleted.push(...r.deleted),n.deletedRoots.push(...i.filter(e=>s.has(e))),n.running.push(...r.running??[])}catch(e){n.error=e instanceof Error?e.message:String(e);break}}return n}function eE(e){return e.replace(/^\/(?:Users|home)\/[^/]+/,"~")}function e$(e,t){let n=t.replace(/[/\\]+$/,"");return n&&(e===n||e.startsWith(`${n}/`)||e.startsWith(`${n}\\`))?`./${e.slice(n.length).replace(/^[/\\]/,"")}`:eE(e)}let eI=/ · [0-9a-f]{4}$/;function eM(e){let t=eI.exec(e);return t&&0!==t.index?{base:e.slice(0,t.index),suffix:t[0]}:null}function eT(e,t){return{cwd:e.current&&t?t:e.root,projectKey:e.key,projectRoot:e.root}}function eR(e){let t=e.project;return!t||e.projects.some(e=>e.key===t.key)?[...e.projects]:[t,...e.projects]}function eA(e,t){let{key:n,root:r}=e,i=t&&Object.hasOwn(t,n)?t[n]:void 0;return void 0===i?{key:n,root:r}:{key:n,root:r,alias:i}}function eL(e){let t=e.map(e=>({choice:e,name:e.alias??J(e.root)})),n=new Map;for(let{name:e}of t)n.set(e,(n.get(e)??0)+1);return t.map(e=>{let t,r,{choice:i,name:s}=e;return{choice:i,name:s,note:void 0===i.alias&&(n.get(s)??0)>1&&(r=Math.max((t=i.root.replace(/[\\/]+$/,"")).lastIndexOf("/"),t.lastIndexOf("\\")))>0?J(t.slice(0,r)):null}})}let ez={awaiting:"#d97706",unread:"#0891b2"};function eP(e){return Number.isFinite(e)?Math.max(0,Math.floor(e)):0}let eW=null,eO=null,eF=new Map;function eD(){return[...document.querySelectorAll('link[rel="icon"]')]}async function eB(e,t){let n=await (!eO&&(eO=new Promise(e=>{let t=new Image;t.onload=()=>e(t),t.onerror=()=>e(null),t.src="/icons/icon-192.png"})),eO);if(!n||eW!==t)return;let r=document.createElement("canvas");r.width=192,r.height=192;let i=r.getContext("2d");if(!i)return;i.clearRect(0,0,192,192),i.drawImage(n,0,0,192,192);let s=e.count>1,o=s?56:42,l=192-o-10,a=o+10;if(i.beginPath(),i.arc(l,a,o,0,2*Math.PI),i.fillStyle=ez[e.kind],i.fill(),i.lineWidth=10,i.strokeStyle="#ffffff",i.stroke(),s&&(i.fillStyle="#ffffff",i.font=`bold ${e.count>9?56:68}px system-ui, sans-serif`,i.textAlign="center",i.textBaseline="middle",i.fillText(String(e.count),l,a+4)),eW!==t)return;let d=r.toDataURL("image/png");for(let e of eD())e.href=d}function eH(e){return e.isComposing||229===e.keyCode}function e_(e,t){let n=e.activeElement;return!!t&&(!n||n===e.body)&&(t.focus({preventScroll:!0}),!0)}let eU=Symbol.for("pi-web:page-id");function eK(){let e=globalThis,t=e[eU];if("string"==typeof t)return t;let n=`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`;return e[eU]=n,n}let eq=new Set,eV=1;function eZ(e){let t=e.source.deref();return t&&2!==t.readyState?t:void 0}function eJ(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null;for(let e of eq)eZ(e)||eq.delete(e);let r={id:eV++,kind:e,label:n,source:new WeakRef(t),createdAt:Date.now(),opens:0,errors:0,lastOpenAt:null,lastErrorAt:null};return eq.add(r),"function"==typeof t.addEventListener&&(t.addEventListener("open",()=>{r.opens+=1,r.lastOpenAt=Date.now()}),t.addEventListener("error",()=>{r.errors+=1,r.lastErrorAt=Date.now()})),t}function eY(){let e=[];for(let t of eq){let n=eZ(t);if(!n){eq.delete(t);continue}e.push({id:t.id,kind:t.kind,label:t.label,state:1===n.readyState?"open":"connecting",createdAt:t.createdAt,opens:t.opens,errors:t.errors,lastOpenAt:t.lastOpenAt,lastErrorAt:t.lastErrorAt})}return e}let eG={trackingSince:null,lastHiddenAt:null,lastVisibleAt:null,hiddenCount:0};function eX(){"u">typeof document&&("hidden"===document.visibilityState?(eG.lastHiddenAt=Date.now(),eG.hiddenCount+=1):eG.lastVisibleAt=Date.now())}function eQ(){return{state:"u">typeof document&&"hidden"===document.visibilityState?"hidden":"visible",trackingSince:eG.trackingSince,lastHiddenAt:eG.lastHiddenAt,lastVisibleAt:eG.lastVisibleAt,hiddenCount:eG.hiddenCount}}let e0={count:0,failures:0,last:null};function e1(){return{...e0,last:e0.last?{...e0.last}:null}}function e2(){if("u"<typeof performance||"function"!=typeof performance.getEntriesByType)return null;let e=performance.getEntriesByType("navigation")[0],t=e?.nextHopProtocol;return t||("u">typeof location&&"http:"===location.protocol?"http/1.1":null)}let e4="pi-web:unread-session-ids";function e8(e){return"number"==typeof e&&Number.isFinite(e)&&e>=0}function e3(e){let t,n=new Map;if(!e)return n;try{t=JSON.parse(e)}catch{return n}if(Array.isArray(t))for(let e of t)"string"==typeof e&&n.set(e,0);else if("object"==typeof t&&null!==t)for(let[e,r]of Object.entries(t))e8(r)&&n.set(e,r);return n}function e5(e,t){if(!t||0===e.size)return e;let n=null;for(let[i,s]of e){var r;void 0!==(r=Object.prototype.hasOwnProperty.call(t,i)?t[i]:void 0)&&r>=s&&(n??=new Map(e)).delete(i)}return n??e}let e6=["pointerdown","keydown","wheel","touchstart"],e9=null,e7=0,te=null;function tt(){return"u">typeof document&&"visible"===document.visibilityState&&document.hasFocus()}function tn(){return e9??=function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:12e4,r=null,i=!1,s=new Set,o=e=>null!==r&&e-r<n,l=t=>{let n=e()&&o(t),r=n&&!i;if(i=n,r)for(let e of[...s])try{e()}catch(e){console.error(e)}};return{noteInput(){let e=t();o(e)||(i=!1),r=e,l(e)},notePageChange(){let e=t();o(e)||(i=!1),l(e)},isAttended:()=>e()&&o(t()),onAttended:e=>(s.add(e),()=>s.delete(e))}}(tt,()=>performance.now())}function tr(){return 0!==e7&&tn().isAttended()}let ti="pi-web:sidebar-files-placement",ts="below";function to(){try{var e;return e=window.localStorage.getItem(ti),"tab"===e?"tab":ts}catch{return ts}}let tl=null,ta=new Set;function td(){return null===tl&&(tl=to()),tl}function tc(){ta.forEach(e=>e())}function tu(e){if(null!==e.key&&e.key!==ti)return;let t=to();t!==tl&&(tl=t,tc())}function tp(e){return 0===ta.size&&(window.addEventListener("storage",tu),tl=to()),ta.add(e),()=>{ta.delete(e),0===ta.size&&window.removeEventListener("storage",tu)}}function th(e){if(e!==td()){tl=e;try{window.localStorage.setItem(ti,e)}catch{}tc()}}function tf(){return(0,i.useSyncExternalStore)(tp,td,()=>ts)}var tm=n(21278);let tg="(max-width: 640px)",tx="(max-width: 480px)";function tv(e,t){if(!window.matchMedia)return()=>{};let n=window.matchMedia(e);return n.addEventListener("change",t),()=>n.removeEventListener("change",t)}function tb(e){return!!window.matchMedia&&window.matchMedia(e).matches}let ty=e=>tv(tg,e),tw=()=>tb(tg),tk=e=>tv(tx,e),tj=()=>tb(tx);function tS(){return!1}function tC(){return(0,i.useSyncExternalStore)(ty,tw,tS)}function tN(e,t,n){let r=Number.isFinite(e)?e:t,i=Math.max(t,n);return Math.round(Math.max(t,Math.min(i,r)))}function tE(e,t){try{window.localStorage.setItem(e,String(t))}catch{}}function t$(e){let{ariaLabel:t,axis:n="horizontal",cssVariable:r,defaultWidth:s,getDefaultWidth:o,getMaxWidth:l,growthDirection:a,maxWidth:d,minWidth:c,persistClamp:u=!0,storageKey:p,widthRef:h}=e,f=(0,i.useRef)(null),m=(0,i.useRef)(null),g=(0,i.useRef)(!1),x=(0,i.useRef)(s),[v,b]=(0,i.useState)(s),[y,w]=(0,i.useState)(!1),[k,j]=(0,i.useState)(!1);(0,i.useEffect)(()=>{j(!0)},[]);let S=(0,i.useCallback)(()=>Math.min(d,Math.max(c,l())),[l,d,c]),C=(0,i.useCallback)(e=>tN(e,c,S()),[S,c]),N=(0,i.useCallback)(e=>{h.current=e,f.current?.style.setProperty(r,`${e}px`)},[r,h]),E=(0,i.useCallback)(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},{forcePersist:n=!1,persist:r=!0}=t,i=C(e),s=i!==h.current;return N(i),b(i),u?r&&(s||n)&&tE(p,i):n&&(x.current=tN(e,c,d),tE(p,x.current)),i},[N,C,d,c,u,p,h]),$=(0,i.useCallback)(()=>{E(u||m.current?h.current:x.current)},[E,u,h]),I=(0,i.useCallback)(e=>{document.body.style.cursor=e.previousCursor,document.body.style.userSelect=e.previousUserSelect},[]),M=(0,i.useCallback)(e=>{let t=m.current;if(t&&t.pointerId===e){m.current=null,I(t),w(!1),E(h.current,{forcePersist:u||h.current!==t.startWidth});try{t.target.hasPointerCapture(e)&&t.target.releasePointerCapture(e)}catch{}}},[E,u,I,h]),T=(0,i.useCallback)(e=>{if("mouse"===e.pointerType&&0!==e.button)return;e.preventDefault(),e.stopPropagation();let t=m.current;t&&M(t.pointerId);let r=e.currentTarget;r.focus({preventScroll:!0}),r.setPointerCapture(e.pointerId),m.current={pointerId:e.pointerId,startPosition:"vertical"===n?e.clientY:e.clientX,startWidth:h.current,target:r,previousCursor:document.body.style.cursor,previousUserSelect:document.body.style.userSelect},document.body.style.cursor="vertical"===n?"row-resize":"col-resize",document.body.style.userSelect="none",w(!0)},[n,M,h]),R=(0,i.useCallback)(e=>{let t=m.current;if(!t||t.pointerId!==e.pointerId)return;if("mouse"===e.pointerType&&0===e.buttons)return void M(e.pointerId);e.preventDefault();let r="right"===a||"down"===a?1:-1,i="vertical"===n?e.clientY:e.clientX,s=C(t.startWidth+(i-t.startPosition)*r);N(s),e.currentTarget.setAttribute("aria-valuenow",String(s)),e.currentTarget.setAttribute("aria-valuetext",`${s} px`)},[N,n,C,M,a]),A=(0,i.useCallback)(e=>{M(e.pointerId)},[M]),L=(0,i.useCallback)(e=>{M(e.pointerId)},[M]),z=(0,i.useCallback)(e=>{M(e.pointerId)},[M]),P=(0,i.useCallback)(()=>{E(o?.()??s,{forcePersist:!0})},[E,s,o]),W=(0,i.useCallback)(e=>{let t=e.shiftKey?32:12,r="right"===a||"down"===a,i="vertical"===n?"ArrowDown":"ArrowRight",s="vertical"===n?"ArrowUp":"ArrowLeft",o=u?h.current:Math.max(h.current,x.current);e.key===(r?i:s)?(e.preventDefault(),E(o+t,{forcePersist:!0})):e.key===(r?s:i)?(e.preventDefault(),E(h.current-t,{forcePersist:!0})):"Home"===e.key?(e.preventDefault(),E(c,{forcePersist:!0})):"End"===e.key?(e.preventDefault(),E(Math.max(o,S()),{forcePersist:!0})):"Enter"===e.key&&(e.preventDefault(),P())},[n,E,S,a,c,u,P,h]);return(0,i.useEffect)(()=>{if(g.current)return;g.current=!0;let e=function(e){try{let t=window.localStorage.getItem(e);if(null===t)return null;let n=Number.parseInt(t,10);return Number.isFinite(n)?n:null}catch{return null}}(p),t=e??o?.()??s;if(!u){x.current=tN(t,c,d),E(x.current,{persist:!1});return}let n=E(t,{persist:!1});null!==e&&e!==n&&tE(p,n)},[E,s,o,d,c,u,p]),(0,i.useEffect)(()=>{if(!g.current)return;$();let e=()=>{$()};return window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[$]),(0,i.useEffect)(()=>{if(!y)return;let e=()=>{let e=m.current;e&&M(e.pointerId)},t=()=>{"visible"!==document.visibilityState&&e()};return window.addEventListener("blur",e),document.addEventListener("visibilitychange",t),()=>{window.removeEventListener("blur",e),document.removeEventListener("visibilitychange",t)}},[M,y]),(0,i.useEffect)(()=>()=>{let e=m.current;e&&(m.current=null,I(e))},[I]),{isResizing:y,panelRef:f,reclampWidth:$,resetWidth:P,separatorProps:{"aria-label":t,"aria-orientation":"vertical"===n?"horizontal":"vertical","aria-valuemax":k?S():d,"aria-valuemin":c,"aria-valuenow":v,"aria-valuetext":`${v} px`,onDoubleClick:P,onKeyDown:W,onLostPointerCapture:z,onPointerCancel:L,onPointerDown:T,onPointerMove:R,onPointerUp:A,role:"separator",tabIndex:0},width:v}}function tI(e){let t=!(arguments.length>1)||void 0===arguments[1]||arguments[1];(0,i.useEffect)(()=>{if(!t)return;let n=null,r=null,i=!1,s=null,o=()=>{null!==s&&(clearTimeout(s),s=null)},l=()=>{n&&(o(),n.classList.add("scrollbar-visible"))},a=()=>{n&&(o(),s=setTimeout(()=>{s=null,n?.classList.remove("scrollbar-visible")},500))},d=()=>{l(),a()},c=()=>{if(!i){if(!(n=e.current)){r=requestAnimationFrame(c);return}n.addEventListener("pointerenter",l),n.addEventListener("pointerleave",a),n.addEventListener("scroll",d)}};return c(),()=>{i=!0,null!==r&&cancelAnimationFrame(r),n?.removeEventListener("pointerenter",l),n?.removeEventListener("pointerleave",a),n?.removeEventListener("scroll",d),o(),n?.classList.remove("scrollbar-visible")}},[t,e])}let tM="/api/sessions/ui-state";async function tT(e){try{let t=await e.json();if(t&&"object"==typeof t&&"string"==typeof t.error)return t.error}catch{}return`HTTP ${e.status}`}function tR(e){return e instanceof Error?e.message:String(e)}async function tA(e){if(!e.ok)throw Error(await tT(e));let t=await e.json(),n=t&&"object"==typeof t?function(e){if(!w(e)||void 0!==e.version&&1!==e.version||void 0!==e.sessions&&!w(e.sessions)||void 0!==e.projects&&!w(e.projects))return null;let t=L(),n=e.revision;for(let[r,i]of("number"==typeof n&&Number.isSafeInteger(n)&&n>=0&&(t.revision=n),Object.entries(e.sessions??{}))){if(!j(r))continue;let e=function(e){if(!w(e))return null;let t={};return k(e.pinnedAt)&&(t.pinnedAt=e.pinnedAt),k(e.archivedAt)&&(t.archivedAt=e.archivedAt),void 0===t.pinnedAt&&void 0===t.archivedAt?null:t}(i);e&&(t.sessions[r]=e)}for(let[n,r]of Object.entries(e.projects??{})){if(!S(n))continue;let e=w(r)&&k(r.pinnedAt)&&S(r.root)?{pinnedAt:r.pinnedAt,root:r.root}:null;e&&(t.projects[n]=e)}if(Array.isArray(e.projectOrder)){let n=new Set,r=T(e.projectOrder.filter(e=>!(!S(e)||n.has(e))&&(n.add(e),!0)));r.length>0&&(t.projectOrder=r)}if(w(e.projectNames)){let n={},r=0,i=1;for(let[t,s]of Object.entries(e.projectNames)){let e=N(s);if(!S(t)||"string"!=typeof e)continue;let o=R(t,e);A(r+1,i+o)&&(n[t]=e,r++,i+=o)}r>0&&(t.projectNames=n)}if(w(e.readAt)){let n={};for(let[t,r]of Object.entries(e.readAt))j(t)&&k(r)&&(n[t]=r);let r=z(n);Object.keys(r).length>0&&(t.readAt=r)}return t}(t.state):null;if(!n)throw Error("Invalid session UI state response");return n}function tL(){let[e,t]=(0,i.useState)(null),n=(0,i.useRef)(null),r=(0,i.useCallback)(()=>{null!==n.current&&(clearTimeout(n.current),n.current=null)},[]),s=(0,i.useCallback)(()=>{r(),t(null)},[r]),o=(0,i.useCallback)(e=>{(r(),function(){try{return window.matchMedia?.("(prefers-reduced-motion: reduce)").matches===!0}catch{return!1}}())?t(null):(t(e),n.current=setTimeout(()=>{n.current=null,t(null)},300))},[r]);return(0,i.useEffect)(()=>r,[r]),{phase:e,start:o,end:s}}var tz=n(47650);let tP={overflow:"hidden",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:10,boxShadow:"0 8px 32px rgba(0,0,0,0.18)"},tW={height:36,padding:"0 10px",border:"1px solid var(--border)",borderRadius:6,outline:"none",background:"var(--bg-panel)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:12},tO={padding:"6px 16px",borderRadius:6,fontSize:13},tF={...tO,border:0,background:"var(--accent)",color:"var(--accent-contrast)",fontWeight:600},tD={...tO,border:"1px solid var(--border)",background:"none",color:"var(--text-muted)"};async function tB(e){let t=e?`?path=${encodeURIComponent(e)}`:"",n=await fetch(`/api/cwd/browse${t}`),r=await n.json();if(!n.ok||r.error)throw Error(r.error??`HTTP ${n.status}`);return r}async function tH(e,t){let n=await fetch("/api/cwd/browse",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:e,name:t})}),r=await n.json();if(!n.ok||r.error||!r.path)throw Error(r.error??`HTTP ${n.status}`);return r.path}function t_(){return(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.3","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M1.5 3h4l1.5 2h7.5v7.5h-13z"})})}function tU(){return(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("rect",{x:"2",y:"3",width:"12",height:"10",rx:"1.5"}),(0,r.jsx)("path",{d:"M2 9h12"}),(0,r.jsx)("circle",{cx:"11.5",cy:"11",r:"0.6",fill:"currentColor",stroke:"none"})]})}function tK(e){let{onCancel:t,onSelect:n,initialPath:s,busy:o=!1,error:l}=e,{t:a}=(0,tm.s)(),[d,c]=(0,i.useState)(null),[u,p]=(0,i.useState)(""),[h,f]=(0,i.useState)(null),[m,g]=(0,i.useState)(s??""),[x,v]=(0,i.useState)([]),[b,y]=(0,i.useState)(null),[w,k]=(0,i.useState)(null),[j,S]=(0,i.useState)(!0),[C,N]=(0,i.useState)(!1),[E,$]=(0,i.useState)(""),[I,M]=(0,i.useState)(null),[T,R]=(0,i.useState)(!1),A=(0,i.useRef)(!1),L=(0,i.useRef)(!1),z=(0,i.useRef)(null),P=(0,i.useRef)(!1),W=(0,i.useCallback)(async e=>{S(!0),k(null);try{let t=await tB(e),n=t.path??e??"/";return p(n),f(t.parentPath??null),g(n),v(t.directories??[]),y(t.drives??null),n}catch(e){return k(e instanceof Error?e.message:String(e)),null}finally{S(!1)}},[]);(0,i.useEffect)(()=>{c(document.body),W(s||void 0)},[s,W]),(0,i.useEffect)(()=>(P.current=!0,()=>{P.current=!1}),[]),(0,i.useEffect)(()=>{(w||l)&&z.current?.focus()},[w,l]);let O=()=>{T||(N(!1),$(""),M(null))},F=async()=>{let e=E.trim();if(u&&e&&!T){R(!0),M(null);try{let t=await tH(u,e);N(!1),$(""),await W(t)}catch(e){M(e instanceof Error?e.message:String(e))}finally{R(!1)}}},D=m.trim(),B=D!==u,H=!!D&&!o&&!j,_=!!u&&!B&&!o&&!j,U=!!h||/^[a-zA-Z]:[\\/]?$/.test(u),K=async()=>{let e=B?await W(D):u;e&&P.current&&n(e)};return d?(0,tz.createPortal)((0,r.jsx)("div",{className:"directory-picker-backdrop",role:"dialog","aria-modal":"true","aria-label":a("directoryPicker.selectDirectory"),onPointerDown:e=>{A.current=e.target===e.currentTarget},onClick:e=>{let n=A.current;A.current=!1,n&&e.target===e.currentTarget&&!o&&t()},onPointerCancel:()=>{A.current=!1},onKeyDown:e=>{!e.nativeEvent.isComposing&&229!==e.keyCode&&("Escape"!==e.key||o||t())},style:{position:"fixed",inset:0,zIndex:1e3,display:"flex",alignItems:"center",justifyContent:"center",background:"rgba(0,0,0,0.35)"},children:(0,r.jsxs)("div",{className:"directory-picker-panel",style:{...tP,position:"relative",width:520,maxWidth:"calc(100vw - 16px)",height:"min(620px, calc(100dvh - 16px))",maxHeight:"calc(100dvh - 16px)",display:"flex",flexDirection:"column"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",flexShrink:0,padding:"12px 18px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("div",{style:{minWidth:0,flex:1},children:(0,r.jsx)("div",{style:{color:"var(--text)",fontWeight:700,fontSize:15},children:a("directoryPicker.selectDirectory")})}),(0,r.jsx)("button",{type:"button",onClick:t,disabled:o,title:a("i18n.close"),"aria-label":a("i18n.close"),style:{padding:"2px 6px",border:0,background:"none",color:"var(--text-muted)",fontSize:20,lineHeight:1,cursor:o?"default":"pointer",opacity:o?.5:1},children:"\xd7"})]}),(0,r.jsxs)("form",{onSubmit:e=>{e.preventDefault();let t=m.trim();t&&W(t)},style:{display:"flex",alignItems:"center",gap:8,flexShrink:0,padding:"10px 14px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("button",{className:"directory-picker-back",type:"button",onClick:()=>void W(h??void 0),disabled:j||!U,title:a("directoryPicker.goToParent"),"aria-label":a("directoryPicker.goToParent"),style:{width:36,height:36,padding:0,display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-hover)",color:"var(--text-muted)",cursor:U?"pointer":"default",opacity:U?1:.45},children:(0,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m18 15-6-6-6 6"})})}),(0,r.jsx)("label",{htmlFor:"directory-path",style:{position:"absolute",width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",border:0},children:a("directoryPicker.directoryPath")}),(0,r.jsx)("input",{ref:z,className:"directory-picker-path",id:"directory-path",type:"text",value:m,placeholder:a("directoryPicker.pathPlaceholder"),autoFocus:!0,autoComplete:"off",spellCheck:!1,onChange:e=>{g(e.target.value),k(null)},style:{...tW,minWidth:0,flex:1}}),(0,r.jsx)("button",{className:"directory-picker-action",type:"submit",disabled:j||!m.trim(),title:a("directoryPicker.goToDirectory"),style:{minWidth:58,height:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-hover)",color:"var(--text-muted)",cursor:j||!m.trim()?"default":"pointer",opacity:j||!m.trim()?.6:1},children:a("directoryPicker.go")})]}),(0,r.jsxs)("div",{className:"directory-picker-list",style:{flex:1,minHeight:0,overflow:"auto",padding:"8px 10px"},children:[j?(0,r.jsx)("div",{style:{padding:8,color:"var(--text-dim)",fontSize:11},children:a("directoryPicker.loadingDirectories")}):null!==b?(0,r.jsx)(r.Fragment,{children:b.length>0?b.map(e=>(0,r.jsxs)("button",{className:"directory-picker-entry",type:"button",onClick:()=>void W(e.path),title:e.path,style:{width:"100%",minHeight:34,display:"flex",alignItems:"center",gap:7,padding:"6px 8px",border:0,borderRadius:5,background:"none",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontFamily:"var(--font-mono)",fontSize:11},children:[(0,r.jsx)(tU,{}),(0,r.jsx)("span",{children:e.name})]},e.path)):(0,r.jsx)("div",{style:{padding:8,color:"var(--text-dim)",fontSize:11},children:a("directoryPicker.noDrives")})}):x.length>0?x.map(e=>(0,r.jsxs)("button",{className:"directory-picker-entry",type:"button",onClick:()=>void W(e.path),title:e.path,style:{width:"100%",minHeight:30,display:"flex",alignItems:"center",gap:7,padding:"5px 8px",border:0,borderRadius:5,background:"none",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontFamily:"var(--font-mono)",fontSize:11},children:[(0,r.jsx)(t_,{}),(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name})]},e.path)):(0,r.jsx)("div",{style:{padding:8,color:"var(--text-dim)",fontSize:11},children:a("directoryPicker.noSubdirectories")}),(w||l)&&(0,r.jsx)("div",{style:{padding:"8px",color:"#dc2626",fontSize:11},children:w??l})]}),(0,r.jsxs)("div",{className:"directory-picker-footer",style:{display:"flex",justifyContent:"flex-end",alignItems:"center",gap:10,flexShrink:0,padding:"10px 18px",borderTop:"1px solid var(--border)"},children:[(0,r.jsx)("button",{className:"directory-picker-action",type:"button",onClick:()=>{N(!0),M(null)},disabled:!_,style:{...tD,marginRight:"auto",opacity:_?1:.6,cursor:_?"pointer":"default"},children:a("directoryPicker.newDirectory")}),(0,r.jsx)("button",{className:"directory-picker-action",type:"button",onClick:t,disabled:o,style:{...tD,cursor:o?"default":"pointer"},children:a("i18n.cancel")}),(0,r.jsx)("button",{className:"directory-picker-action",type:"button",onClick:()=>void K(),disabled:!H,title:B&&D?a("directoryPicker.selectTypedPath",{path:D}):a("directoryPicker.selectCurrentDirectory"),style:{...tF,opacity:H?1:.6,cursor:H?"pointer":"default"},children:a(o?"i18n.checking":"directoryPicker.selectThisFolder")})]}),C&&(0,r.jsx)("div",{style:{position:"absolute",inset:0,zIndex:1,display:"flex",alignItems:"center",justifyContent:"center",padding:12,background:"rgba(0,0,0,0.35)"},onPointerDown:e=>{L.current=e.target===e.currentTarget},onClick:e=>{let t=L.current;L.current=!1,t&&e.target===e.currentTarget&&O()},onPointerCancel:()=>{L.current=!1},onKeyDown:e=>{e.stopPropagation(),e.nativeEvent.isComposing||229===e.keyCode||"Escape"===e.key&&O()},children:(0,r.jsxs)("form",{role:"dialog","aria-modal":"true","aria-label":a("directoryPicker.createDirectory"),onSubmit:e=>{e.preventDefault(),F()},style:{...tP,width:400,maxWidth:"100%"},children:[(0,r.jsx)("div",{style:{padding:"12px 18px",borderBottom:"1px solid var(--border)",color:"var(--text)",fontSize:15,fontWeight:700},children:a("directoryPicker.createDirectory")}),(0,r.jsxs)("div",{style:{padding:"12px 18px"},children:[(0,r.jsx)("label",{htmlFor:"new-directory-name",style:{display:"block",marginBottom:6,color:"var(--text-muted)",fontSize:11},children:a("directoryPicker.directoryName")}),(0,r.jsx)("input",{id:"new-directory-name",value:E,autoFocus:!0,autoComplete:"off",spellCheck:!1,placeholder:a("directoryPicker.directoryNamePlaceholder"),onChange:e=>{$(e.target.value),M(null)},disabled:T,className:"directory-picker-path",style:{...tW,width:"100%",boxSizing:"border-box"}}),I&&(0,r.jsx)("div",{style:{marginTop:7,color:"#dc2626",fontSize:11,lineHeight:1.35},children:I}),(0,r.jsxs)("div",{style:{display:"flex",gap:6,marginTop:10},children:[(0,r.jsx)("button",{className:"directory-picker-action",type:"submit",disabled:T||!E.trim(),style:{...tF,flex:1,opacity:T?.65:1,cursor:T||!E.trim()?"default":"pointer"},children:a(T?"directoryPicker.creating":"directoryPicker.create")}),(0,r.jsx)("button",{className:"directory-picker-action",type:"button",onClick:O,disabled:T,style:{...tD,flex:1,cursor:T?"default":"pointer"},children:a("i18n.cancel")})]})]})]})})]})}),d):null}function tq(e){let{onClick:t,title:n}=e;return(0,r.jsx)("button",{type:"button",onClick:t,title:n,"aria-label":n,style:{width:24,height:24,padding:0,display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,border:"none",borderRadius:4,background:"none",color:"var(--text-dim)",cursor:"pointer"},onMouseEnter:e=>{e.currentTarget.style.color="var(--text-muted)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.color="var(--text-dim)",e.currentTarget.style.background="none"},children:(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"m6 6 12 12"}),(0,r.jsx)("path",{d:"m18 6-12 12"})]})})}let tV="/icons/catppuccin";function tZ(e){let{name:t,size:n=14}=e,i={width:n,height:n,"--catppuccin-icon-light":`url(${tV}/latte/${t}.svg)`,"--catppuccin-icon-dark":`url(${tV}/mocha/${t}.svg)`};return(0,r.jsx)("span",{"aria-hidden":"true",className:"catppuccin-file-icon",style:i})}function tJ(e){let{size:t=14,open:n=!1}=e;return(0,r.jsx)(tZ,{name:n?"_folder_open":"_folder",size:t})}function tY(e){let{size:t=14}=e;return(0,r.jsx)(tZ,{name:"_file",size:t})}let tG={ts:"typescript",tsx:"typescript-react",js:"javascript",mjs:"javascript",cjs:"javascript",jsx:"javascript-react",py:"python",json:"json",jsonl:"json",css:"css",less:"css",scss:"sass",html:"html",htm:"html",md:"markdown",mdx:"markdown",yaml:"yaml",yml:"yaml",toml:"toml",sh:"bash",bash:"bash",zsh:"bash",fish:"bash",rs:"rust",go:"go",sql:"database",graphql:"graphql",gql:"graphql",tf:"terraform",hcl:"terraform",docx:"ms-word",pdf:"pdf",lock:"lock"};function tX(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:14,n=e.toLowerCase(),i="dockerfile"===n||n.startsWith("dockerfile.")?"docker":".env"===n||n.startsWith(".env.")?"env":[".gitignore",".gitattributes",".gitmodules"].includes(n)?"git":"package-lock.json"===n?"npm-lock":"bun.lock"===n?"bun-lock":["next.config.js","next.config.mjs","next.config.cjs","next.config.ts"].includes(n)?"next":[".eslintrc",".eslintrc.js",".eslintrc.json",".eslintrc.yml","eslint.config.mjs","eslint.config.js"].includes(n)?"eslint":["yarn.lock","pnpm-lock.yaml","cargo.lock"].includes(n)?"lock":n.endsWith(".config.ts")||n.endsWith(".config.js")||n.endsWith(".config.mjs")||n.endsWith(".config.cjs")?"config":void 0;if(i)return(0,r.jsx)(tZ,{name:i,size:t});let s=tG[n.split(".").pop()??""];return s?(0,r.jsx)(tZ,{name:s,size:t}):(0,r.jsx)(tY,{size:t})}function tQ(e){return/^[a-zA-Z]:[\\/]/.test(e)||e.startsWith("\\\\")?e.replace(/\\/g,"/"):e}function t0(e){let t=tQ(e),n=t.split("/").filter(Boolean);return t.startsWith("//")&&n.length>0&&(n[0]=`//${n[0]}`),n.map(encodeURIComponent).join("/")}function t1(e){let t=tQ(e).replace(/\/+$/,"");return t.split("/").pop()??t}function t2(e){let t=tQ(e).replace(/\/+$/,""),n=t.lastIndexOf("/");return n<0?"":0===n?"/":2===n&&/^[a-zA-Z]:\//.test(t)?t.slice(0,3):t.slice(0,n)}function t4(e,t){if(!t)return e;let n=tQ(e),r=tQ(t).replace(/\/$/,"");return n.startsWith(r+"/")?n.slice(r.length+1):e}function t8(e,t){return`${tQ(e).replace(/\/$/,"")}/${t}`}function t3(e){let t=/(?:^|\s)@"([^"\n]*)$/.exec(e);if(t)return{start:e.length-(t[1].length+2),query:t[1],quoted:!0};let n=/(?:^|\s)@([^\s"]*)$/.exec(e);return n?{start:e.length-(n[1].length+1),query:n[1],quoted:!1}:null}function t5(e){let t=0;for(let n=0;n<e.length;n++)"/"===e[n]&&t++;return t}function t6(e,t){if(!e)return!0;let n=0;for(let r=0;r<t.length&&n<e.length;r++)t[r]===e[n]&&n++;return n===e.length}function t9(e,t){let n=t?`${e}/`:e;return n.includes(" ")?`@"${n}" `:`@${n} `}function t7(e,t,n,r){return new Promise((i,s)=>{let o=new FormData;t.forEach(e=>o.append("files",e,e.name));let l=new XMLHttpRequest;l.open("POST",`/api/files/${t0(e)}?type=upload&conflict=${n}`),l.upload.onprogress=e=>{r&&e.lengthComputable&&e.total>0&&r(Math.round(e.loaded/e.total*100))},l.onerror=()=>s(Error("Network error while uploading files")),l.onabort=()=>s(Error("Upload cancelled")),l.onload=()=>{let e={};try{e=JSON.parse(l.responseText)}catch{l.responseText&&(e.error=l.responseText)}i({status:l.status,data:e})},l.send(o)})}function ne(e){let t=[],n=new Map;for(let r of e){let e=r.split("/"),i=t,s="";for(let t=0;t<e.length;t++){s=s?`${s}/${e[t]}`:e[t];let r=n.get(s);r||(r={name:e[t],path:s,isDir:t<e.length-1,children:[]},n.set(s,r),i.push(r)),i=r.children}}let r=e=>{e.sort((e,t)=>e.isDir!==t.isDir?e.isDir?-1:1:e.name.localeCompare(t.name)),e.forEach(e=>r(e.children))};return r(t),t}function nt(e){return Array.from(e.dataTransfer.items).some(e=>"file"===e.kind)}function nn(e){let t=[];for(let n of Array.from(e.items)){if("file"!==n.kind)continue;let e=n.webkitGetAsEntry?.();if(e?.isDirectory){t.push({kind:"folder",name:e.name});continue}let r=n.getAsFile();r&&t.push({kind:"file",file:r})}return t.length>0?t:Array.from(e.files).map(e=>({kind:"file",file:e}))}let nr=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:20,t=new Map;return{save(n,r){if(t.delete(n),0!==r.size)for(let i of(t.set(n,new Set(r)),t.keys())){if(t.size<=e)break;t.delete(i)}},restore:e=>new Set(t.get(e))}}();async function ni(e,t){let n=`${t} (HTTP ${e.status})`;try{let t=await e.json();t.error&&(n=t.error)}catch{}return Error(n)}async function ns(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],n=t0(e),r=await fetch(`/api/files/${n}?type=list${t?"&hidden=1":""}`);if(!r.ok)throw await ni(r,"Failed to load files");return((await r.json()).entries??[]).map(t=>({name:t.name,fullPath:t8(e,t.name),isDir:t.isDir,size:t.size,children:t.isDir?[]:void 0,loaded:!t.isDir,outsideLinkTarget:t.outsideLinkTarget,outsideLinkEncloses:t.outsideLinkEncloses,hidden:t.hidden}))}async function no(e,t){let n=await fetch(`/api/files/${t0(e)}?type=allow-link`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({target:t})});if(!n.ok)throw await ni(n,"Failed to allow the linked folder")}async function nl(e,t){let n=new URLSearchParams({cwd:e}),r=await fetch(`/api/git/status?${n.toString()}`,{signal:t});if(!r.ok)throw Error(`Failed to load Git status (HTTP ${r.status})`);return r.json()}let na={modified:"files.modified",added:"files.added",deleted:"files.deleted",renamed:"files.renamed",untracked:"files.untracked",conflict:"files.conflict"},nd={modified:"#d6a84b",added:"#4ade80",deleted:"#f87171",renamed:"#60a5fa",untracked:"#4ade80",conflict:"#f87171"};function nc(e){let{status:t,t:n}=e;return(0,r.jsx)("span",{title:n(na[t.status]),"aria-label":n(na[t.status]),style:{width:14,height:14,flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center",color:nd[t.status],fontFamily:"var(--font-mono)",fontSize:11,fontWeight:600},children:t.code})}function nu(e){let{size:t=11}=e;return(0,r.jsxs)("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"4"}),(0,r.jsx)("path",{d:"M16 8v5a3 3 0 0 0 6 0v-1a10 10 0 1 0-4 8"})]})}function np(e){let{size:t=11}=e;return(0,r.jsxs)("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M15 3h6v6"}),(0,r.jsx)("path",{d:"M10 14 21 3"}),(0,r.jsx)("path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"})]})}let nh={ignored:"files.hiddenIgnored",excluded:"files.hiddenExcluded"};function nf(e){let{node:t,depth:n,cwd:s,onOpenFile:o,onAtMention:l,expandedPaths:a,onToggleExpanded:d,refreshToken:c,highlightedPaths:u,gitStatusByPath:p,changedDirectoryPaths:h,showHidden:f=!1,parentHidden:m,dropTargetPath:g,onDropFiles:x,onDropTargetChange:v,t:b}=e,y=a.has(t.fullPath),w=t.hidden??m,k=t.isDir&&g===t.fullPath,j=u.has(t.fullPath),S=tQ(t.fullPath),C=p.get(S),N=t.isDir&&(void 0!==C||h.has(S)),[E,$]=(0,i.useState)(t.children??[]),[I,M]=(0,i.useState)(t.loaded??!1),[T,R]=(0,i.useState)(!1),[A,L]=(0,i.useState)(null),[z,P]=(0,i.useState)(!1),[W,O]=(0,i.useState)(null),[F,D]=(0,i.useState)(!1),[B,H]=(0,i.useState)(null),_=t.outsideLinkTarget&&t.outsideLinkTarget!==W?t.outsideLinkTarget:null;(0,i.useEffect)(()=>{O(null),H(null)},[t.outsideLinkTarget]);let U=(0,i.useCallback)(async function(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];if(!I||e){R(!0),L(null);try{let e=await ns(t.fullPath,f);$(e),M(!0)}catch(e){L(e instanceof Error?e.message:String(e))}finally{R(!1)}}},[I,t.fullPath,f]),K=(0,i.useRef)(f);(0,i.useEffect)(()=>{K.current===f||(K.current=f,I&&(y&&!_?U(!0):M(!1)))},[f]),(0,i.useEffect)(()=>{t.isDir&&y&&!I&&!_&&U()},[]),(0,i.useEffect)(()=>{void 0!==c&&I&&!_&&(y?U(!0):M(!1))},[c]);let q=(0,i.useCallback)(()=>{if(t.isDir){let e=!y;d(t.fullPath,e),!e||I||_||U()}else o(t.fullPath,t.name)},[t.isDir,t.fullPath,t.name,I,y,_,U,o,d]),V=(0,i.useCallback)(async e=>{if((e.stopPropagation(),_)&&(!t.outsideLinkEncloses||window.confirm(b("files.allowEnclosingLinkConfirm",{target:_})))){D(!0),H(null);try{await no(t.fullPath,_),O(_),await U(!0)}catch(e){H(e instanceof Error?e.message:String(e))}finally{D(!1)}}},[t.fullPath,t.outsideLinkEncloses,_,U,b]);return(0,r.jsxs)("div",{children:[(0,r.jsxs)("div",{onClick:q,onMouseEnter:()=>P(!0),onMouseLeave:()=>P(!1),onDragOver:t.isDir?e=>{e.dataTransfer.types.includes("Files")&&(e.preventDefault(),e.stopPropagation(),e.dataTransfer.dropEffect="copy",v?.(t.fullPath))}:void 0,onDrop:t.isDir?e=>{e.dataTransfer.types.includes("Files")&&(e.preventDefault(),e.stopPropagation(),v?.(null),x?.(t.fullPath,nn(e.dataTransfer)))}:void 0,style:{position:"relative",display:"flex",alignItems:"center",gap:4,paddingLeft:8+14*n,paddingRight:8,height:"var(--file-row-height)",cursor:"pointer",background:k?"color-mix(in srgb, var(--accent) 16%, transparent)":z?"var(--bg-hover)":"transparent",outline:k?"1px dashed var(--accent)":"none",outlineOffset:-1,borderRadius:4,userSelect:"none"},children:[t.isDir&&(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--text-dim)",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,transform:y?"rotate(90deg)":"none",transition:"transform 0.1s"},children:(0,r.jsx)("polyline",{points:"3 2 7 5 3 8"})}),!t.isDir&&(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),(0,r.jsx)("span",{style:{flexShrink:0,display:"flex",alignItems:"center",opacity:w?.55:1},children:t.isDir?(0,r.jsx)(tJ,{size:14,open:y}):tX(t.name,14)}),(0,r.jsx)("span",{"data-hidden-reason":w,style:{fontSize:12,color:w?"var(--text-muted)":"var(--text)",opacity:w?.55:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1},title:w?`${t.fullPath}
|
|
2
|
-
${b(nh[w])}`:t.fullPath,children:t.name}),!z&&_&&(0,r.jsx)("span",{title:b("files.outsideLink",{target:_}),"aria-label":b("files.outsideLink",{target:_}),style:{width:14,height:14,flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-dim)"},children:(0,r.jsx)(np,{})}),j&&(0,r.jsx)("span",{title:b("files.newlyUploaded"),"aria-label":b("files.newlyUploaded"),style:{width:14,height:14,flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center"},children:(0,r.jsx)("span",{style:{width:6,height:6,borderRadius:"50%",background:"#3b82f6"}})}),!z&&!t.isDir&&C&&(0,r.jsx)(nc,{status:C,t:b}),!z&&N&&(0,r.jsx)("span",{title:b("files.containsChangedFiles"),"aria-label":b("files.containsChangedFiles"),style:{width:14,height:14,flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center"},children:(0,r.jsx)("span",{style:{width:6,height:6,borderRadius:"50%",background:"#d6a84b"}})}),T&&(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"var(--text-dim)",strokeWidth:"2",strokeLinecap:"round",children:(0,r.jsx)("path",{d:"M12 2v4M12 18v4M4.93 4.93l2.83 2.83M16.24 16.24l2.83 2.83M2 12h4M18 12h4"})}),l&&z&&(0,r.jsxs)("button",{onClick:e=>{e.stopPropagation(),l(t4(t.fullPath,s),t.isDir)},title:b("files.insertPath"),style:{position:"absolute",right:t.isDir?4:28,top:"50%",transform:"translateY(-50%)",display:"flex",alignItems:"center",justifyContent:"center",gap:4,padding:"0 8px",height:"calc(var(--file-row-height) - 4px)",background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:4,color:"var(--accent)",cursor:"pointer",fontSize:11,fontWeight:600,whiteSpace:"nowrap"},children:[(0,r.jsx)(nu,{}),b("files.mention")]}),z&&!t.isDir&&(0,r.jsx)("a",{href:`/api/files/${t0(t.fullPath)}?type=download`,download:!0,onClick:e=>e.stopPropagation(),title:b("files.download"),style:{position:"absolute",right:4,top:"50%",transform:"translateY(-50%)",display:"flex",alignItems:"center",justifyContent:"center",gap:4,padding:"0 5px",height:"calc(var(--file-row-height) - 4px)",background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:4,color:"var(--text-muted)",cursor:"pointer",fontSize:11,fontWeight:600,whiteSpace:"nowrap",textDecoration:"none"},children:(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),(0,r.jsx)("polyline",{points:"7 10 12 15 17 10"}),(0,r.jsx)("line",{x1:"12",y1:"15",x2:"12",y2:"3"})]})})]}),t.isDir&&y&&_&&(0,r.jsxs)("div",{style:{paddingLeft:8+(n+1)*14,paddingRight:8,paddingTop:3,paddingBottom:5,display:"flex",flexDirection:"column",alignItems:"flex-start",gap:4,fontSize:11,color:"var(--text-dim)"},children:[(0,r.jsx)("span",{style:{wordBreak:"break-all"},children:b("files.outsideLink",{target:_})}),t.outsideLinkEncloses&&(0,r.jsx)("span",{style:{color:"#f59e0b"},children:b("files.outsideLinkEncloses")}),(0,r.jsx)("button",{type:"button",onClick:V,disabled:F,title:b("files.allowOutsideLinkTitle",{target:_}),style:{height:"calc(var(--file-row-height) - 4px)",padding:"0 8px",background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:4,color:"var(--accent)",cursor:F?"default":"pointer",opacity:F?.6:1,fontSize:11,fontWeight:600,whiteSpace:"nowrap"},children:b("files.allowOutsideLink")}),B&&(0,r.jsx)("span",{role:"alert",style:{color:"#f87171",wordBreak:"break-word"},children:B})]}),t.isDir&&y&&!_&&(0,r.jsxs)("div",{children:[E.map(e=>(0,r.jsx)(nf,{node:e,depth:n+1,cwd:s,onOpenFile:o,onAtMention:l,expandedPaths:a,onToggleExpanded:d,refreshToken:c,highlightedPaths:u,gitStatusByPath:p,changedDirectoryPaths:h,showHidden:f,parentHidden:w,dropTargetPath:g,onDropFiles:x,onDropTargetChange:v,t:b},e.fullPath)),0===E.length&&I&&!A&&(0,r.jsx)("div",{style:{paddingLeft:8+(n+1)*14,fontSize:11,color:"var(--text-dim)",height:22,display:"flex",alignItems:"center"},children:"empty"}),A&&(0,r.jsx)("div",{role:"alert",style:{paddingLeft:8+(n+1)*14,paddingRight:8,paddingTop:3,paddingBottom:3,fontSize:11,color:"#f87171",wordBreak:"break-word"},children:A})]})]})}function nm(e){let{status:t,cwd:n,onOpenFile:s,onAtMention:o,t:l,depth:a=0,treeMode:d=!1}=e,[c,u]=(0,i.useState)(!1),p=t1(t.filePath),h=t4(t.filePath,n),f=h.lastIndexOf("/"),m=!d&&f>=0?h.slice(0,f+1):"",g=d?p:f>=0?h.slice(f+1):h;return(0,r.jsxs)("div",{onClick:()=>s(t.filePath,p,{modeHint:"diff"}),onMouseEnter:()=>u(!0),onMouseLeave:()=>u(!1),title:t.filePath,style:{display:"flex",alignItems:"center",gap:d?4:6,paddingLeft:d?8+14*a:10,paddingRight:8,height:"var(--file-row-height)",cursor:"pointer",background:c?"var(--bg-hover)":"transparent",borderRadius:4,userSelect:"none",position:"relative"},children:[(0,r.jsx)(nc,{status:t,t:l}),d&&(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),(0,r.jsx)("span",{style:{flexShrink:0,display:"flex",alignItems:"center",opacity:.85},children:tX(p,13)}),(0,r.jsxs)("span",{title:t.filePath,style:{fontSize:12,color:"var(--text)",display:"flex",alignItems:"center",minWidth:0,flex:1},children:[m&&(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:"0 1 auto",minWidth:0,color:"var(--text-dim)"},children:m}),(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flexShrink:+!!d,maxWidth:"100%"},children:g})]}),o&&c&&(0,r.jsxs)("button",{onClick:e=>{e.stopPropagation(),o(h,!1)},title:l("files.insertPath"),style:{position:"absolute",right:4,top:"50%",transform:"translateY(-50%)",display:"flex",alignItems:"center",justifyContent:"center",gap:4,padding:"0 8px",height:"calc(var(--file-row-height) - 4px)",background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:4,color:"var(--accent)",cursor:"pointer",fontSize:11,fontWeight:600,whiteSpace:"nowrap"},children:[(0,r.jsx)(nu,{}),l("files.mention")]})]})}function ng(e){let{node:t,depth:n,open:s,onToggle:o}=e,[l,a]=(0,i.useState)(!1);return(0,r.jsxs)("div",{onClick:()=>o(t.path,!s),onMouseEnter:()=>a(!0),onMouseLeave:()=>a(!1),title:t.path,style:{display:"flex",alignItems:"center",gap:4,paddingLeft:8+14*n,paddingRight:8,height:"var(--file-row-height)",cursor:"pointer",background:l?"var(--bg-hover)":"transparent",borderRadius:4,userSelect:"none"},children:[(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--text-dim)",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,transform:s?"rotate(90deg)":"none",transition:"transform 0.1s"},"aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"3 2 7 5 3 8"})}),(0,r.jsx)("span",{style:{flexShrink:0,display:"flex",alignItems:"center"},children:(0,r.jsx)(tJ,{size:14,open:s})}),(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1},children:t.name})]})}function nx(e){let{nodes:t,depth:n,cwd:i,statusByPath:s,collapsedPaths:o,onToggleExpanded:l,onOpenFile:a,onAtMention:d,t:c}=e;return(0,r.jsx)(r.Fragment,{children:t.map(e=>{if(e.isDir){let t=!o.has(e.path);return(0,r.jsxs)("div",{children:[(0,r.jsx)(ng,{node:e,depth:n,open:t,onToggle:l}),t&&(0,r.jsx)(nx,{nodes:e.children,depth:n+1,cwd:i,statusByPath:s,collapsedPaths:o,onToggleExpanded:l,onOpenFile:a,onAtMention:d,t:c})]},`dir:${e.path}`)}let t=s.get(e.path);return t?(0,r.jsx)(nm,{status:t,cwd:i,onOpenFile:a,onAtMention:d,t:c,depth:n,treeMode:!0},t.filePath):null})})}function nv(e){let{mode:t}=e;return"tree"===t?(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M8 6h13"}),(0,r.jsx)("path",{d:"M8 12h13"}),(0,r.jsx)("path",{d:"M8 18h13"}),(0,r.jsx)("path",{d:"M3 6h.01"}),(0,r.jsx)("path",{d:"M3 12h.01"}),(0,r.jsx)("path",{d:"M3 18h.01"})]}):(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M6 3v12"}),(0,r.jsx)("path",{d:"M18 9a3 3 0 1 0 0-6 3 3 0 0 0 0 6z"}),(0,r.jsx)("path",{d:"M6 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6z"}),(0,r.jsx)("path",{d:"M18 21a3 3 0 1 0 0-6 3 3 0 0 0 0 6z"}),(0,r.jsx)("path",{d:"M9 12h6"}),(0,r.jsx)("path",{d:"M12 12v3"})]})}let nb=(0,i.forwardRef)(function(e,t){let{cwd:n,onOpenFile:s,refreshKey:o,onAtMention:l,onAtMentions:a,onUploadBusyChange:d,changesCollapsed:c,onChangesCountChange:u,fileSearchOpen:p=!1,onFileSearchOpenChange:h,showHidden:f=!1}=e,{t:m}=(0,tm.s)(),[g,x]=(0,i.useState)([]),[v,b]=(0,i.useState)(!0),[y,w]=(0,i.useState)(null),[k,j]=(0,i.useState)(new Set),[S,C]=(0,i.useState)(0),[N,E]=(0,i.useState)(new Set),[$,I]=(0,i.useState)([]),[M,T]=(0,i.useState)({additions:0,deletions:0}),[R,A]=(0,i.useState)("list"),[L,z]=(0,i.useState)(()=>new Set),[P,W]=(0,i.useState)("idle"),[O,F]=(0,i.useState)(0),[D,B]=(0,i.useState)(null),[H,_]=(0,i.useState)(null),[U,K]=(0,i.useState)(null),[q,V]=(0,i.useState)(""),[Z,J]=(0,i.useState)([]),[Y,G]=(0,i.useState)(!1),[X,Q]=(0,i.useState)(!1),[ee,et]=(0,i.useState)(new Set),en=(0,i.useRef)(null),[er,ei]=(0,i.useState)(!1),[es,eo]=(0,i.useState)(null),el=(0,i.useRef)(0),ea=(0,i.useRef)(null),ed=(0,i.useRef)(k),ec=(0,i.useRef)(null),eu=`${o??0}:${S}`,ep="idle"!==P,eh=q.trim().length>0;(0,i.useEffect)(()=>{if(!p)return;let e=q.trim();if(!e){J([]),G(!1),Q(!1);return}let t=new AbortController;G(!0),Q(!1);let r=setTimeout(()=>{fetch(`/api/file-index?cwd=${encodeURIComponent(n)}&q=${encodeURIComponent(e)}`,{signal:t.signal}).then(e=>e.ok?e.json():Promise.reject(Error("Search failed"))).then(e=>J((e.matches??[]).filter(e=>!e.isDir).map(e=>e.path))).catch(()=>{t.signal.aborted||(J([]),Q(!0))}).finally(()=>{t.signal.aborted||G(!1)})},150);return()=>{clearTimeout(r),t.abort()}},[n,p,q]),(0,i.useEffect)(()=>{p&&en.current?.focus()},[p]),(0,i.useEffect)(()=>{if(0===Z.length)return;let e=new Set;for(let t of Z){let r=t.split("/"),i="";for(let t=0;t<r.length-1;t++)i=i?`${i}/${r[t]}`:r[t],e.add(t8(n,i))}et(t=>{let n=!1,r=new Set(t);for(let t of e)r.has(t)||(r.add(t),n=!0);return n?r:t})},[n,Z]);let ef=(0,i.useMemo)(()=>{let e=t=>({name:t.name,fullPath:t8(n,t.path),isDir:t.isDir,size:0,children:t.children.map(e),loaded:!0});return ne(Z).map(e)},[n,Z]),em=(0,i.useMemo)(()=>new Map($.map(e=>[tQ(e.filePath),e])),[$]),eg=(0,i.useMemo)(()=>{let e=new Set,t=tQ(n).replace(/\/$/,"");for(let n of $){let r=t2(tQ(n.filePath));for(;(r===t||r.startsWith(`${t}/`))&&(e.add(r),r!==t);){let e=t2(r);if(e===r)break;r=e}}return e},[n,$]),ev=(0,i.useMemo)(()=>new Map($.map(e=>[tQ(t4(e.filePath,n)).replace(/^\/+/,""),e])),[n,$]),eb=(0,i.useMemo)(()=>ne([...ev.keys()]),[ev]),ew=(0,i.useCallback)((e,t)=>{j(n=>{let r=new Set(n);return t?r.add(e):r.delete(e),r})},[]),ek=(0,i.useCallback)((e,t)=>{let n=e.uploaded??[];_({directory:t,uploaded:n,skipped:e.skipped??[],errors:e.errors??[]}),n.length>0&&(E(new Set(n.map(e=>t8(t,e)))),C(e=>e+1))},[]),ej=(0,i.useCallback)(async(e,t,n)=>{K(null),B(null),F(0),W("uploading");try{let{status:r,data:i}=await t7(n,e,t,F);if(409===r&&i.conflicts?.length)return void K({directory:n,files:e,conflicts:i.conflicts,nonReplaceable:i.nonReplaceable??[]});if(r<200||r>=300)throw Error(i.error??`Upload failed (HTTP ${r})`);F(100),ek(i,n)}catch(e){B(e instanceof Error?e.message:String(e))}finally{W("idle")}},[ek]),eS=(0,i.useCallback)(async(e,t)=>{if(0!==e.length&&!ep){_(null),E(new Set),K(null),B(null),F(0),W("checking");try{let n=await fetch(`/api/files/${t0(t)}?type=upload-check`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({fileNames:e.map(e=>e.name)})}),r=await n.json().catch(()=>({}));if(!n.ok)throw Error(r.error??`Upload check failed (HTTP ${n.status})`);if(r.conflicts?.length)return void K({directory:t,files:e,conflicts:r.conflicts,nonReplaceable:r.nonReplaceable??[]});await ej(e,"error",t)}catch(e){B(e instanceof Error?e.message:String(e))}finally{W("idle")}}},[ej,ep]),eC=(0,i.useCallback)(e=>{let t=Array.from(e.target.files??[]);e.target.value="",eS(t,n)},[n,eS]);(0,i.useImperativeHandle)(t,()=>({openUploadPicker(){ep||ec.current?.click()}}),[ep]);let eN=(0,i.useCallback)(()=>{el.current=0,ei(!1),eo(null)},[]),eE=(0,i.useCallback)(e=>{e.dataTransfer.types.includes("Files")&&(e.preventDefault(),el.current+=1,ei(!0))},[]),e$=(0,i.useCallback)(e=>{e.dataTransfer.types.includes("Files")&&(e.preventDefault(),e.dataTransfer.dropEffect="copy",eo(e=>null===e?e:null))},[]),eI=(0,i.useCallback)(()=>{el.current<=0||(el.current-=1,0===el.current&&(el.current=0,ei(!1),eo(null)))},[]),eM=(0,i.useCallback)((e,t)=>{eN();let n=t.flatMap(e=>"file"===e.kind?[e.file]:[]),r=t.flatMap(e=>"folder"===e.kind?[e.name]:[]);eS(n,e).then(()=>{if(0===r.length)return;let e=m("chat.dropFoldersUnsupported",{names:r.join(", ")});B(t=>t&&n.length>0?t:e)})},[eS,eN,m]),eT=(0,i.useCallback)(e=>{e.dataTransfer.types.includes("Files")&&(e.preventDefault(),e.stopPropagation(),eM(es??n,nn(e.dataTransfer)))},[n,es,eM]),eR=(0,i.useCallback)(e=>{eo(t=>t===e?t:e)},[]);(0,i.useEffect)(()=>{d?.(ep)},[d,ep]),(0,i.useEffect)(()=>()=>d?.(!1),[d]),(0,i.useEffect)(()=>{ed.current=k},[k]),(0,i.useEffect)(()=>()=>{null!==ea.current&&nr.save(ea.current,ed.current)},[]),(0,i.useEffect)(()=>{let e=ea.current,t=e!==n;if(ea.current=n,t){null!==e&&nr.save(e,ed.current);let t=nr.restore(n);ed.current=t,j(t),E(new Set),_(null),K(null),B(null)}b(t),w(null);let r=!1;return ns(n,f).then(e=>{r||x(e)}).catch(e=>{r||w(e instanceof Error?e.message:String(e))}).finally(()=>{r||b(!1)}),()=>{r=!0}},[n,o,S,f]),(0,i.useEffect)(()=>{let e=()=>C(e=>e+1);return window.addEventListener("focus",e),()=>window.removeEventListener("focus",e)},[]),(0,i.useEffect)(()=>{let e=!1,t=new AbortController;return nl(n,t.signal).then(t=>{e||(I(t.isGitRepository?t.files:[]),T(t.isGitRepository?{additions:t.additions,deletions:t.deletions}:{additions:0,deletions:0}))}).catch(()=>{e||(I([]),T({additions:0,deletions:0}))}),()=>{e=!0,t.abort()}},[n,o,S]),(0,i.useEffect)(()=>{u?.($.length)},[$,u]),(0,i.useEffect)(()=>{A(function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:ey();if(!e)return"list";try{return"tree"===e.getItem(ex)?"tree":"list"}catch{return"list"}}())},[]);let eA=(0,i.useCallback)((e,t)=>{z(n=>{let r=new Set(n);return t?r.delete(e):r.add(e),r})},[]),eL=(0,i.useCallback)(()=>{A(e=>{let t="list"===e?"tree":"list";return!function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:ey();if(t)try{t.setItem(ex,e)}catch{}}(t),t})},[]),ez=ep||null!==U||null!==D||null!==H,eP=(0,i.useCallback)(()=>{H&&0!==H.uploaded.length&&a?.(H.uploaded.map(e=>t4(t8(H.directory,e),n)))},[n,a,H]);return(0,r.jsxs)("div",{style:{minHeight:"100%"},onDragEnter:eE,onDragOver:e$,onDragLeave:eI,onDrop:eT,children:[(0,r.jsx)("input",{ref:ec,type:"file",multiple:!0,hidden:!0,onChange:eC}),ez&&(0,r.jsxs)("div",{style:{padding:"6px 8px",borderBottom:"1px solid var(--border)"},children:[ep&&(0,r.jsxs)("div",{role:"status","aria-live":"polite","aria-label":"checking"===P?m("files.checking"):m("files.uploading",{progress:O}),children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,minHeight:14,color:"var(--text-muted)"},children:["checking"===P?(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",style:{animation:"spin 0.8s linear infinite"},"aria-hidden":"true",children:(0,r.jsx)("path",{d:"M21 12a9 9 0 1 1-5.7-8.4"})}):(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M12 16V4"}),(0,r.jsx)("path",{d:"m7 9 5-5 5 5"}),(0,r.jsx)("path",{d:"M5 20h14"})]}),"uploading"===P&&(0,r.jsxs)("span",{style:{fontSize:10},children:[O,"%"]})]}),"uploading"===P&&(0,r.jsx)("div",{style:{height:3,marginTop:4,overflow:"hidden",borderRadius:2,background:"var(--border)"},children:(0,r.jsx)("div",{style:{width:`${O}%`,height:"100%",background:"var(--text-muted)",transition:"width 120ms ease"}})})]}),U&&(0,r.jsxs)("div",{role:"alert",style:{padding:7,border:"1px solid color-mix(in srgb, #f59e0b 55%, var(--border))",borderRadius:4,background:"color-mix(in srgb, #f59e0b 9%, var(--bg-panel))"},children:[(0,r.jsx)("div",{style:{fontSize:11,color:"var(--text)",lineHeight:1.35,overflowWrap:"anywhere"},children:m("files.conflictSummary",{count:U.conflicts.length,countSuffix:1===U.conflicts.length?"":"s",files:U.conflicts.join(", ")})}),U.nonReplaceable.length>0&&(0,r.jsx)("div",{style:{marginTop:3,fontSize:10,color:"#f59e0b",lineHeight:1.35,overflowWrap:"anywhere"},children:m("files.cannotReplace",{files:U.nonReplaceable.join(", ")})}),(0,r.jsxs)("div",{style:{display:"flex",gap:5,marginTop:7},children:[(0,r.jsx)("button",{type:"button",onClick:()=>void ej(U.files,"overwrite",U.directory),style:{height:22,padding:"0 7px",border:"1px solid #ef4444",borderRadius:4,background:"transparent",color:"#ef4444",cursor:"pointer",fontSize:10},children:m("files.replace")}),(0,r.jsx)("button",{type:"button",onClick:()=>void ej(U.files,"skip",U.directory),style:{height:22,padding:"0 7px",border:"1px solid var(--border)",borderRadius:4,background:"var(--bg-panel)",color:"var(--text)",cursor:"pointer",fontSize:10},children:m("files.skipExisting")}),(0,r.jsx)("button",{type:"button",onClick:()=>K(null),style:{height:22,padding:"0 7px",border:"none",borderRadius:4,background:"transparent",color:"var(--text-muted)",cursor:"pointer",fontSize:10},children:m("files.cancel")})]})]}),D&&(0,r.jsxs)("div",{role:"alert",style:{display:"flex",alignItems:"flex-start",gap:6,fontSize:11,lineHeight:1.35,color:"#f87171"},children:[(0,r.jsx)("span",{style:{minWidth:0,flex:1,overflowWrap:"anywhere"},children:D}),(0,r.jsx)(tq,{onClick:()=>B(null),title:m("files.dismissError")})]}),H&&(0,r.jsxs)("div",{"aria-live":"polite",children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,minHeight:22,fontSize:11},children:[(0,r.jsxs)("div",{style:{minWidth:0,flex:1,display:"flex",alignItems:"center",gap:8},children:[H.uploaded.length>0&&(0,r.jsxs)("span",{title:m("files.uploadedCount",{count:H.uploaded.length}),"aria-label":m("files.uploadedCount",{count:H.uploaded.length}),style:{display:"flex",alignItems:"center",gap:3,color:"#22c55e"},children:[(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.4",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m5 12 4 4L19 6"})}),(0,r.jsx)("span",{children:H.uploaded.length})]}),H.skipped.length>0&&(0,r.jsxs)("span",{title:m("files.skippedCount",{count:H.skipped.length}),"aria-label":m("files.skippedCount",{count:H.skipped.length}),style:{display:"flex",alignItems:"center",gap:3,color:"var(--text-dim)"},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"9"}),(0,r.jsx)("path",{d:"M8 12h8"})]}),(0,r.jsx)("span",{children:H.skipped.length})]}),H.errors.length>0&&(0,r.jsxs)("span",{title:m("files.failedCount",{count:H.errors.length}),"aria-label":m("files.failedCount",{count:H.errors.length}),style:{display:"flex",alignItems:"center",gap:3,color:"#f87171"},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M12 3 2.5 20h19L12 3Z"}),(0,r.jsx)("path",{d:"M12 9v4"}),(0,r.jsx)("path",{d:"M12 17h.01"})]}),(0,r.jsx)("span",{children:H.errors.length})]})]}),H.uploaded.length>0&&a&&(0,r.jsxs)("button",{type:"button",onClick:eP,title:1===H.uploaded.length?m("files.addUploadedFile"):m("files.addAllUploadedFiles"),"aria-label":1===H.uploaded.length?m("files.addUploadedFile"):m("files.addAllUploadedFiles"),style:{height:22,padding:"0 7px",display:"flex",alignItems:"center",justifyContent:"center",gap:4,flexShrink:0,border:"1px solid var(--border)",borderRadius:4,background:"var(--bg-panel)",color:"var(--accent)",cursor:"pointer",fontSize:11,fontWeight:600,whiteSpace:"nowrap"},children:[(0,r.jsx)(nu,{}),m("files.mention")]}),(0,r.jsx)(tq,{onClick:()=>_(null),title:m("files.dismissUploadResults")})]}),H.errors.map(e=>(0,r.jsxs)("div",{title:e.error,style:{display:"flex",alignItems:"center",gap:4,marginTop:3,minWidth:0,fontSize:10,color:"#f87171"},children:[(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},"aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"9"}),(0,r.jsx)("path",{d:"M12 8v5"}),(0,r.jsx)("path",{d:"M12 17h.01"})]}),(0,r.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name})]},e.name))]})]}),p&&(0,r.jsxs)("div",{style:{padding:"2px 8px 6px"},children:[(0,r.jsxs)("div",{style:{position:"relative"},children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{position:"absolute",left:8,top:"50%",transform:"translateY(-50%)",color:"var(--text-dim)",pointerEvents:"none"},children:[(0,r.jsx)("circle",{cx:"11",cy:"11",r:"7"}),(0,r.jsx)("path",{d:"m20 20-4-4"})]}),(0,r.jsx)("input",{ref:en,id:"file-search-input",value:q,onChange:e=>V(e.target.value),onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),h?.(!1))},placeholder:m("sidebar.searchFilesPlaceholder"),"aria-label":m("sidebar.searchFiles"),style:{width:"100%",boxSizing:"border-box",padding:"6px 24px",border:"1px solid var(--border)",borderRadius:8,outline:"none",background:"var(--bg)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:11}}),q&&(0,r.jsx)("button",{type:"button",onClick:()=>V(""),title:m("sidebar.clearSearch"),"aria-label":m("sidebar.clearSearch"),style:{position:"absolute",right:4,top:"50%",transform:"translateY(-50%)",display:"flex",alignItems:"center",justifyContent:"center",width:18,height:18,padding:0,border:"none",borderRadius:4,background:"none",color:"var(--text-dim)",cursor:"pointer"},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-dim)"},children:(0,r.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.4",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M18 6 6 18"}),(0,r.jsx)("path",{d:"m6 6 12 12"})]})})]}),eh&&(0,r.jsxs)("div",{style:{paddingTop:3},children:[Y&&(0,r.jsx)("div",{role:"status",style:{padding:"6px 2px",fontSize:10,color:"var(--text-dim)"},children:m("sidebar.searchingFiles")}),!Y&&X&&(0,r.jsx)("div",{role:"alert",style:{padding:"6px 2px",fontSize:10,color:"#f87171"},children:m("i18n.networkError")}),!Y&&!X&&0===Z.length&&(0,r.jsx)("div",{style:{padding:"6px 2px",fontSize:10,color:"var(--text-dim)"},children:m("sidebar.noMatchingFiles")}),!Y&&!X&&Z.length>0&&(0,r.jsx)("div",{children:ef.map(e=>(0,r.jsx)(nf,{node:e,depth:0,cwd:n,onOpenFile:s,onAtMention:l,expandedPaths:ee,onToggleExpanded:(e,t)=>{et(n=>{let r=new Set(n);return t?r.add(e):r.delete(e),r})},highlightedPaths:N,gitStatusByPath:em,changedDirectoryPaths:eg,dropTargetPath:es,onDropFiles:eM,onDropTargetChange:eR,t:m},`${q}:${e.fullPath}`))})]})]}),!c&&$.length>0&&(0,r.jsxs)("div",{style:{padding:"0 4px 2px"},children:[(0,r.jsxs)("div",{"aria-label":m("files.changeStats",{count:$.length,additions:M.additions,deletions:M.deletions}),style:{display:"flex",alignItems:"center",gap:6,height:24,padding:"0 6px 0 10px",fontSize:12},children:[(0,r.jsx)("span",{style:{color:"var(--text-dim)"},children:m("files.changedCount",{count:$.length})}),(0,r.jsxs)("span",{style:{color:nd.added,fontFamily:"var(--font-mono)"},children:["+",M.additions]}),(0,r.jsxs)("span",{style:{color:nd.deleted,fontFamily:"var(--font-mono)"},children:["-",M.deletions]}),(0,r.jsx)("span",{style:{flex:1}}),(0,r.jsx)("button",{type:"button",onClick:eL,title:"list"===R?m("files.viewAsTree"):m("files.viewAsList"),"aria-label":"list"===R?m("files.viewAsTree"):m("files.viewAsList"),"aria-pressed":"tree"===R,style:{display:"flex",alignItems:"center",justifyContent:"center",width:22,height:22,padding:0,border:"none",borderRadius:4,background:"transparent",color:"var(--text-dim)",cursor:"pointer",flexShrink:0},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-dim)"},children:(0,r.jsx)(nv,{mode:R})})]}),"tree"===R?(0,r.jsx)(nx,{nodes:eb,depth:0,cwd:n,statusByPath:ev,collapsedPaths:L,onToggleExpanded:eA,onOpenFile:s,onAtMention:l,t:m}):$.map(e=>(0,r.jsx)(nm,{status:e,cwd:n,onOpenFile:s,onAtMention:l,t:m},e.filePath))]}),(c||0===$.length)&&(!p||!eh)&&(0,r.jsxs)("div",{style:{padding:"2px 4px"},children:[v?(0,r.jsx)("div",{style:{padding:"8px 12px",fontSize:11,color:"var(--text-dim)"},children:m("files.loading")}):y?(0,r.jsx)("div",{style:{padding:"8px 12px",fontSize:11,color:"#f87171"},children:y}):g.map(e=>(0,r.jsx)(nf,{node:e,depth:0,cwd:n,onOpenFile:s,onAtMention:l,expandedPaths:k,onToggleExpanded:ew,refreshToken:eu,highlightedPaths:N,gitStatusByPath:em,changedDirectoryPaths:eg,showHidden:f,dropTargetPath:es,onDropFiles:eM,onDropTargetChange:eR,t:m},e.fullPath)),!v&&!y&&0===g.length&&(0,r.jsx)("div",{style:{padding:"8px 12px",fontSize:11,color:"var(--text-dim)"},children:m("files.noFiles")})]}),er&&(0,r.jsxs)("div",{role:"status","aria-live":"polite",style:{position:"sticky",bottom:0,zIndex:1,display:"flex",alignItems:"center",gap:6,padding:"6px 8px",borderTop:"1px solid var(--border)",background:"var(--bg-panel)",fontSize:11,color:"var(--accent)",userSelect:"none",pointerEvents:"none"},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0},children:[(0,r.jsx)("path",{d:"M12 16V4"}),(0,r.jsx)("path",{d:"m7 9 5-5 5 5"}),(0,r.jsx)("path",{d:"M5 20h14"})]}),m("files.dropToUpload",{directory:es?t4(es,n)||es:t1(n)||n})]})]})}),ny="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*";function nw(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:Math.random,r=4*e.length;if(t>=r)return e;let i=Math.floor(t/r*e.length),s="";for(let t=0;t<e.length;t++){let r=e[t];s+=" "===r||t<i?r:ny[Math.floor(n()*ny.length)]}return s}function nk(e){let{onWidthChange:t}=e,{t:n}=(0,tm.s)(),[s,o]=(0,i.useState)(!1),l=(0,i.useRef)(null),a="0.17.0-custom.3",d="1.5.2",c=function(e){let[t,n]=(0,i.useState)(e),r=(0,i.useRef)(e);return(0,i.useEffect)(()=>{if(r.current===e)return;if(r.current=e,window.matchMedia?.("(prefers-reduced-motion: reduce)").matches)return void n(e);let t=4*e.length,i=0,s=0,o=()=>{n(nw(e,i+=1)),i<t&&(s=requestAnimationFrame(o))};return n(nw(e,0)),s=requestAnimationFrame(o),()=>cancelAnimationFrame(s)},[e]),t}(s?`${a??"0.0.0"}p${d??"0.0.0"}`:"Pi Web");return(0,i.useLayoutEffect)(()=>{t?.()},[c.length,t]),(0,i.useEffect)(()=>()=>{l.current&&clearTimeout(l.current)},[]),(0,r.jsx)("button",{type:"button",className:`sidebar-brand${s?" is-version":""}`,"aria-label":n("sidebar.brandLabel",{app:a??"0.0.0",pi:d??"0.0.0"}),onClick:()=>{(l.current&&clearTimeout(l.current),l.current=null,s)?o(!1):(o(!0),l.current=setTimeout(()=>{l.current=null,o(!1)},3e3))},children:c})}var nj=n(2730);let nS=/^<skill name="([^"\n]+)" location="([^"\n]+)">\nReferences are relative to [^\n]+\.\n\n([\s\S]*)\n<\/skill>(?:\n\n([\s\S]+))?$/;function nC(e){let t=e.match(nS);if(!t)return null;let[,n,,,r]=t;return r?`/skill:${n} ${r}`:`/skill:${n}`}let nN={desktop:32,mobile:48};function nE(e,t,n,r){return Math.hypot(n-e,r-t)}function n$(e){return e.getClientRects().length>0}function nI(e){let{size:t=13,className:n,label:i,strokeWidth:s=2,children:o}=e;return(0,r.jsx)("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:s,strokeLinecap:"round",strokeLinejoin:"round",className:n,...i?{role:"img","aria-label":i}:{"aria-hidden":!0},children:o})}function nM(e){return(0,r.jsx)(nI,{...e,children:(0,r.jsx)("path",{d:"M12 5v14M5 12h14"})})}function nT(e){return(0,r.jsxs)(nI,{...e,children:[(0,r.jsx)("circle",{cx:"5",cy:"12",r:"1.4",fill:"currentColor",stroke:"none"}),(0,r.jsx)("circle",{cx:"12",cy:"12",r:"1.4",fill:"currentColor",stroke:"none"}),(0,r.jsx)("circle",{cx:"19",cy:"12",r:"1.4",fill:"currentColor",stroke:"none"})]})}function nR(e){return(0,r.jsxs)(nI,{...e,children:[(0,r.jsx)("rect",{x:"3",y:"4",width:"18",height:"5",rx:"1"}),(0,r.jsx)("path",{d:"M5 9v9a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V9"}),(0,r.jsx)("path",{d:"M10 13h4"})]})}function nA(e){return(0,r.jsxs)(nI,{...e,children:[(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 3-6.7L3 8"}),(0,r.jsx)("path",{d:"M3 3v5h5"})]})}function nL(e){return(0,r.jsxs)(nI,{...e,children:[(0,r.jsx)("path",{d:"M12 17v5"}),(0,r.jsx)("path",{d:"M9 10.8a2 2 0 0 1-1.1 1.8l-1.8.9A2 2 0 0 0 5 15.2V16a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-.8a2 2 0 0 0-1.1-1.8l-1.8-.9a2 2 0 0 1-1.1-1.8V7a1 1 0 0 1 1-1 2 2 0 0 0 0-4H8a2 2 0 0 0 0 4 1 1 0 0 1 1 1z"})]})}function nz(e){return(0,r.jsxs)(nI,{...e,children:[(0,r.jsx)("path",{d:"M12 17v5"}),(0,r.jsx)("path",{d:"M15 9.3V7a1 1 0 0 1 1-1 2 2 0 0 0 0-4H8.5"}),(0,r.jsx)("path",{d:"m2 2 20 20"}),(0,r.jsx)("path",{d:"M9 9v1.8a2 2 0 0 1-1.1 1.8l-1.8.9A2 2 0 0 0 5 15.2V16a1 1 0 0 0 1 1h11"})]})}function nP(e){let{strokeWidth:t,...n}=e;return(0,r.jsx)(nI,{...n,strokeWidth:t,children:(0,r.jsx)("path",{d:"m9 6 6 6-6 6"})})}function nW(e){return(0,r.jsxs)(nI,{...e,children:[(0,r.jsx)("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),(0,r.jsx)("circle",{cx:"18",cy:"6",r:"3"}),(0,r.jsx)("circle",{cx:"6",cy:"18",r:"3"}),(0,r.jsx)("path",{d:"M18 9a9 9 0 0 1-9 9"})]})}function nO(e){return(0,r.jsxs)(nI,{...e,children:[(0,r.jsx)("circle",{cx:"6",cy:"5",r:"2.5"}),(0,r.jsx)("circle",{cx:"18",cy:"5",r:"2.5"}),(0,r.jsx)("circle",{cx:"12",cy:"19",r:"2.5"}),(0,r.jsx)("path",{d:"M6 7.5v1.5a3 3 0 0 0 3 3h6a3 3 0 0 0 3-3V7.5"}),(0,r.jsx)("path",{d:"M12 12v4.5"})]})}function nF(e){return(0,r.jsxs)(nI,{...e,children:[(0,r.jsx)("path",{d:"M14 4h6v6"}),(0,r.jsx)("path",{d:"M20 4 11 13"}),(0,r.jsx)("path",{d:"M18 14v4a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4"})]})}function nD(e){return(0,r.jsxs)(nI,{...e,children:[(0,r.jsx)("path",{d:"M3 6h18"}),(0,r.jsx)("path",{d:"M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"}),(0,r.jsx)("path",{d:"M10 11v6M14 11v6"}),(0,r.jsx)("path",{d:"M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"})]})}function nB(e){return(0,r.jsx)(nI,{...e,children:(0,r.jsx)("path",{d:"M17 3a2.83 2.83 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5Z"})})}function nH(e){return(0,r.jsx)(nI,{...e,children:(0,r.jsx)("circle",{cx:"12",cy:"12",r:"4.5",fill:"currentColor",stroke:"none"})})}function n_(e){return(0,r.jsx)(nI,{...e,children:(0,r.jsx)("circle",{cx:"12",cy:"12",r:"4.5"})})}function nU(e){return(0,r.jsx)(nI,{...e,children:(0,r.jsx)("path",{d:"M20 6 9 17l-5-5"})})}function nK(e){return(0,r.jsx)(nI,{...e,children:(0,r.jsx)("path",{d:"M18 6 6 18M6 6l12 12"})})}function nq(e){return(0,r.jsx)(nI,{...e,children:(0,r.jsx)("path",{d:"M3 8a2 2 0 0 1 2-2h3.4l1.9 1.9H19a2 2 0 0 1 2 2V17a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2Z"})})}function nV(e){return(0,r.jsxs)(nI,{...e,children:[(0,r.jsx)("path",{d:"M3 8a2 2 0 0 1 2-2h3.4l1.9 1.9H19a2 2 0 0 1 2 2V17a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2Z"}),(0,r.jsx)("path",{d:"M12 11v5M9.5 13.5h5"})]})}function nZ(e){return(0,r.jsxs)(nI,{...e,children:[(0,r.jsx)("polyline",{points:"4 17 10 11 4 5"}),(0,r.jsx)("line",{x1:"12",y1:"19",x2:"20",y2:"19"})]})}function nJ(e){return(0,r.jsxs)(nI,{...e,children:[(0,r.jsx)("circle",{cx:"11",cy:"11",r:"7"}),(0,r.jsx)("path",{d:"m20 20-4-4"})]})}function nY(e){return(0,r.jsxs)(nI,{...e,children:[(0,r.jsx)("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),(0,r.jsx)("path",{d:"m17 8-5-5-5 5"}),(0,r.jsx)("path",{d:"M12 3v12"})]})}function nG(e){return(0,r.jsxs)(nI,{...e,children:[(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),(0,r.jsx)("path",{d:"M3 3v5h5"})]})}function nX(e){return(0,r.jsxs)(nI,{...e,children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"3"}),(0,r.jsx)("path",{d:"M3 12h6M15 12h6"})]})}function nQ(e){return(0,r.jsxs)(nI,{...e,children:[(0,r.jsx)("path",{d:"M2 12s3.6-7 10-7 10 7 10 7-3.6 7-10 7S2 12 2 12Z"}),(0,r.jsx)("circle",{cx:"12",cy:"12",r:"3"})]})}function n0(e){return(0,r.jsx)(nI,{...e,children:(0,r.jsx)("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}function n1(e){let{className:t,...n}=e;return(0,r.jsx)(nI,{...n,strokeWidth:2.8,className:t?`sidebar-spin ${t}`:"sidebar-spin",children:(0,r.jsx)("path",{d:"M21 12a9 9 0 1 1-3.8-7.4"})})}function n2(e){let t=nC(e.firstMessage)??e.firstMessage;return e.name||t.slice(0,50)||e.id.slice(0,12)}function n4(e){return e.nativeEvent.isComposing||229===e.keyCode}function n8(e){let{rows:t,layout:n,emptyLabel:s,loading:o,error:l,renamingRootId:a,renamingProjectKey:d,confirmDeleteRootId:c,activeMenuRowKey:u,reveal:p}=e,{t:h}=(0,tm.s)(),f=(0,i.useRef)(e);f.current=e;let m=(0,i.useRef)(null),g=(0,i.useRef)(null),x=(0,i.useRef)(null),v=(0,i.useRef)(null);tI(g);let[b,y]=(0,i.useState)(0),[w,k]=(0,i.useState)(0),[j,S]=(0,i.useState)(null),[C,N]=(0,i.useState)(()=>Date.now()),E=(0,i.useRef)(null),$=(0,i.useCallback)(()=>{null===E.current&&(E.current=requestAnimationFrame(()=>{E.current=null;let e=g.current;e&&y(e.scrollTop)}))},[]);(0,i.useLayoutEffect)(()=>{let e=g.current;if(!e)return;let t=()=>{let t=`${Math.max(0,e.offsetWidth-e.clientWidth)}px`;e.style.setProperty("--session-tree-scrollbar",t),e.offsetWidth>0&&e.closest(".session-sidebar")?.style.setProperty("--session-tree-scrollbar",t)};if(t(),k(e.clientHeight),y(e.scrollTop),"u"<typeof ResizeObserver)return;let n=new ResizeObserver(()=>{t(),k(e.clientHeight),y(e.scrollTop)});return n.observe(e),()=>n.disconnect()},[]),(0,i.useEffect)(()=>()=>{null!==E.current&&cancelAnimationFrame(E.current)},[]),(0,i.useEffect)(()=>{let e=window.setInterval(()=>N(Date.now()),6e4);return()=>window.clearInterval(e)},[]);let I=(0,i.useCallback)(e=>{let t=e.target instanceof Element?e.target.closest("[data-row-key]"):null;S(t?.getAttribute("data-row-key")??null)},[]),M=(0,i.useCallback)(e=>{e.currentTarget.contains(e.relatedTarget)||S(null)},[]),T=(0,i.useMemo)(()=>(function(e,t){let n=D[t],r=Array(e.length+1);r[0]=0;for(let t=0;t<e.length;t++)r[t+1]=r[t]+n[e[t].kind];return r})(t,n),[t,n]),R=!!e.onMoveGroup,A=(0,i.useMemo)(()=>{let e={pinned:0,other:0};for(let n of t)"group"===n.kind&&e[n.project.pinned?"pinned":"other"]++;return e},[t]),L=function(e){let{rows:t,offsets:n,enabled:r}=e,s=(0,i.useRef)(e);s.current=e;let o=(0,i.useMemo)(()=>(function(e,t){let n=[],r=0;for(;r<e.length;){var i;let s=e[r];if("group"!==s.kind){r++;continue}let o=r;for(;o>0&&"spacer"===e[o-1].kind;)o--;let l=r+1;for(;l<e.length&&("group-more"===(i=e[l]).kind||"group-empty"===i.kind||"session"===i.kind&&"group"===i.context);)l++;let a=l;for(;a<e.length&&"spacer"===e[a].kind;)a++;n.push({key:s.project.key,pinned:s.project.pinned,top:t[r],bottom:t[l],gapAbove:t[r]-t[o],gapBelow:t[a]-t[l]}),r=l}return n})(t,n),[t,n]),l=(0,i.useRef)(o);l.current=o;let a=(0,i.useRef)(null),d=(0,i.useRef)(0),[c,u]=(0,i.useState)(null),p=(0,i.useMemo)(()=>{let e=e=>{u("armed"===e.phase||"dragging"===e.phase?{projectKey:e.projectKey,phase:e.phase,drop:e.drop}:null)},t=e=>{let t=s.current.innerRef.current;return t?function(e,t,n){let r=e.find(e=>e.key===t);if(!r)return null;let i=e.filter(e=>e.pinned===r.pinned),s=i.indexOf(r),o=i.filter(e=>e!==r);if(0===o.length)return null;let l=o.filter(e=>(e.top+e.bottom)/2<n).length;if(l===s)return null;let a=o[o.length-1],d=Math.max(3,l<o.length?o[l].top-o[l].gapAbove/2:a.bottom+a.gapBelow/2);return l>0?{anchorKey:o[l-1].key,position:"after",lineY:d}:{anchorKey:o[0].key,position:"before",lineY:d}}(l.current,e.projectKey,e.clientY-t.getBoundingClientRect().top):null},n=()=>{let e=a.current,t=s.current.ghostRef.current,n=s.current.treeRef.current,r=s.current.innerRef.current,i=s.current.scrollRef.current;if(!e?.ghost||!t||!n||!i)return;let o=n.getBoundingClientRect().top,l=i.getBoundingClientRect(),d=t.offsetHeight,c=function(e){let{pointerY:t,lineY:n,ghostHeight:r,pointerGap:i,lineGap:s,minTop:o,maxTop:l}=e,a=Math.max(o,l),d=t-i-r,c=null!==n&&n>=o&&n<=a+r?n:null,u=e=>e>=o&&e<=a,p=e=>null!==c&&e>c-s-r&&e<c+s,h=null===c?[d,o,t+i,a]:[d,c-s-r,o,t+i,c+s,a],f=e=>{let t=null;for(let n of h)e(n)&&(null===t||Math.abs(n-d)<Math.abs(t-d))&&(t=n);return t};return f(e=>u(e)&&!(e>d&&e<t+i)&&!p(e))??f(e=>u(e)&&!p(e))??Math.min(a,Math.max(o,d))}({pointerY:e.clientY,lineY:e.drop&&r?r.getBoundingClientRect().top+e.drop.lineY:null,ghostHeight:d,pointerGap:"mouse"===e.pointerType?8:28,lineGap:8,minTop:l.top,maxTop:l.bottom-d});t.style.top=`${c-o}px`,t.style.left=`${e.ghost.left}px`},r=e=>{null!==e.timer&&window.clearTimeout(e.timer),null!==e.frame&&cancelAnimationFrame(e.frame),e.timer=null,e.frame=null,s.current.scrollRef.current?.removeEventListener("scroll",p);try{e.element.hasPointerCapture(e.pointerId)&&e.element.releasePointerCapture(e.pointerId)}catch{}},i=()=>{let e=a.current;e&&(a.current=null,r(e),window.removeEventListener("pointermove",g,!0),window.removeEventListener("pointerup",x,!0),window.removeEventListener("pointercancel",v,!0),window.removeEventListener("pointerdown",b,!0),window.removeEventListener("keydown",y,!0),window.removeEventListener("contextmenu",w,!0),window.removeEventListener("blur",k),document.removeEventListener("visibilitychange",j),u(null))},o=()=>{let e=a.current;if(e){if("armed"!==e.phase&&"dragging"!==e.phase){"pending"===e.phase&&i();return}e.phase="cancelled",e.drop=null,r(e),u(null)}},c=function(){var r;let i=arguments.length>0&&void 0!==arguments[0]&&arguments[0],l=a.current;if(!l||"dragging"!==l.phase)return;let d=s.current.scrollRef.current;if(!d||!n$(d))return void o();let c=t(l),u=i||c!==(r=l.drop)&&(null===c||null===r||c.anchorKey!==r.anchorKey||c.position!==r.position||c.lineY!==r.lineY);l.drop=c,n(),u&&e(l)};function p(){c()}let h=()=>{let e=a.current;if(!e||"dragging"!==e.phase)return;e.frame=null;let t=s.current.scrollRef.current;if(!t||!n$(t))return void o();let n=t.getBoundingClientRect(),r=function(e,t,n,r){let i=Math.min(r,(n-t)/2);if(!(i>0)||!Number.isFinite(e))return 0;let s=e=>Math.ceil(14*Math.min(1,e/i));return e<t+i?-s(t+i-e):e>n-i?s(e-(n-i)):0}(e.clientY,n.top,n.bottom,nN[s.current.layout]);if(0!==r){let n=Math.min(Math.max(0,(s.current.offsets[s.current.offsets.length-1]??0)-t.clientHeight),Math.max(0,t.scrollTop+r));n!==t.scrollTop&&(t.scrollTop=n,e.expectedScrollTop=t.scrollTop,c())}a.current===e&&"dragging"===e.phase&&(e.frame=requestAnimationFrame(h))},f=e=>{let t=s.current.scrollRef.current,n=s.current.treeRef.current;if(!t||!n||!n$(t)||!e.element.isConnected)return void o();if(e.phase="dragging","touch"!==e.pointerType)try{e.element.setPointerCapture(e.pointerId)}catch{}e.ghost={left:e.element.getBoundingClientRect().left-n.getBoundingClientRect().left+4},e.expectedScrollTop=t.scrollTop,t.addEventListener("scroll",p,{passive:!0}),e.frame=requestAnimationFrame(h),c(!0)},m=()=>{let t=a.current;t&&"pending"===t.phase&&(t.timer=null,t.phase="armed",t.armX=t.clientX,t.armY=t.clientY,t.expectedScrollTop=s.current.scrollRef.current?.scrollTop??0,e(t))};function g(e){let t=a.current;if(!t||e.pointerId!==t.pointerId)return;if("mouse"===t.pointerType&&0===e.buttons)return void i();t.clientX=e.clientX,t.clientY=e.clientY;let n=nE(t.startX,t.startY,e.clientX,e.clientY);switch(t.phase){case"pending":"mouse"===t.pointerType?n>=4&&f(t):n>8&&i();break;case"armed":nE(t.armX,t.armY,e.clientX,e.clientY)>=4&&f(t);break;case"dragging":c()}}function x(e){let n=a.current;if(n&&e.pointerId===n.pointerId){if("dragging"===n.phase){n.clientX=e.clientX,n.clientY=e.clientY;let r=t(n);r&&s.current.onMove(n.projectKey,r.anchorKey,r.position)}"pending"!==n.phase&&(d.current=e.timeStamp+600),i()}}function v(e){a.current&&e.pointerId===a.current.pointerId&&i()}function b(e){a.current&&e.pointerId!==a.current.pointerId&&o()}function y(e){let t=a.current;t&&"Escape"===e.key&&("armed"===t.phase||"dragging"===t.phase)&&(e.preventDefault(),e.stopPropagation(),o())}function w(e){let t=a.current;if(t){if("pending"===t.phase)return void i();e.preventDefault(),e.stopPropagation()}}function k(){i()}function j(){"hidden"===document.visibilityState&&i()}return{handlers:{onPointerDown(e,t){if(!s.current.enabled||a.current||!e.isPrimary||0!==e.button||e.ctrlKey||e.target instanceof Element&&e.target.closest(".session-tree-group-actions"))return;let n=e.currentTarget,r={pointerId:e.pointerId,pointerType:e.pointerType,projectKey:t,element:n,startX:e.clientX,startY:e.clientY,armX:e.clientX,armY:e.clientY,clientX:e.clientX,clientY:e.clientY,phase:"pending",timer:null,frame:null,expectedScrollTop:0,drop:null,ghost:null};a.current=r,window.addEventListener("pointermove",g,!0),window.addEventListener("pointerup",x,!0),window.addEventListener("pointercancel",v,!0),window.addEventListener("pointerdown",b,!0),window.addEventListener("keydown",y,!0),window.addEventListener("contextmenu",w,!0),window.addEventListener("blur",k),document.addEventListener("visibilitychange",j),"mouse"!==e.pointerType&&(r.timer=window.setTimeout(m,350))},onTouchMove(e){let t=a.current;if(!t||"armed"!==t.phase&&"dragging"!==t.phase)return;if(e.cancelable)return void e.preventDefault();let n=s.current.scrollRef.current;n&&n.scrollTop!==t.expectedScrollTop&&i()}},cancel:o,teardown:i,updateDrag:c,placeGhost:n}},[]);(0,i.useLayoutEffect)(()=>{let e=a.current;e&&("armed"===e.phase||"dragging"===e.phase)&&(t.some(t=>"group"===t.kind&&t.project.key===e.projectKey)?p.updateDrag():p.cancel())},[t,n,p]),(0,i.useEffect)(()=>{r||p.cancel()},[r,p]);let h=c?.phase==="dragging";(0,i.useLayoutEffect)(()=>{h&&p.placeGhost()},[h,p]),(0,i.useEffect)(()=>()=>p.teardown(),[p]);let f=(0,i.useCallback)(e=>{let t=d.current;0===t||(d.current=0,e.timeStamp>t||(e.preventDefault(),e.stopPropagation()))},[]),m=(0,i.useCallback)(()=>{d.current=0},[]);return{view:(0,i.useMemo)(()=>{if(!c)return null;let e="dragging"===c.phase?o.find(e=>e.key===c.projectKey)??null:null;return{...c,source:e}},[c,o]),handlers:p.handlers,onClickCapture:f,onPointerDownCapture:m}}({rows:t,offsets:T,layout:n,enabled:R&&!o,scrollRef:g,innerRef:x,treeRef:m,ghostRef:v,onMove:(e,t,n)=>f.current.onMoveGroup?.(e,t,n)}),z=L.view,P=z?`group:${z.projectKey}`:null,[W,O]=(0,i.useState)(null),F=p&&p.id!==W?p:null,H=F?.rowKey??null,_=(0,i.useMemo)(()=>{let e=[];return t.forEach((t,n)=>{t.key===j||t.key===u||t.key===H||t.key===P||"session"===t.kind&&(t.family.root.id===a||t.family.root.id===c)?e.push(n):"group"===t.kind&&t.project.key===d&&e.push(n)}),e},[t,j,u,H,P,a,d,c]),U=(0,i.useMemo)(()=>o?[]:function(e,t,n,r){let i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:[],s=Math.max(0,e.length-1),o=Number.isFinite(t)?Math.max(0,t):0,l=Number.isFinite(n)&&n>0?n:600,a=Number.isFinite(r)&&r>0?r:0,d=o-a,c=o+l+a,u=0,p=s;for(;u<p;){let t=u+p>>>1;e[t+1]>d?p=t:u=t+1}let h=u;for(u=h,p=s;u<p;){let t=u+p>>>1;e[t]>=c?p=t:u=t+1}let f=u,m=[];for(let e=h;e<f;e++)m.push(e);if(0===i.length)return m;let g=i.filter(e=>Number.isInteger(e)&&e>=0&&e<s&&(e<h||e>=f));return 0===g.length?m:[...new Set([...m,...g])].sort((e,t)=>e-t)}(T,b,w,240,_),[o,T,b,w,_]),K=(0,i.useRef)(null),q=(0,i.useRef)(null),V=(0,i.useCallback)((e,t,n,r)=>{let i=document.activeElement===r,s=i&&r.matches(":focus-visible");K.current={rowKey:e,fallbackKey:t===B?"pinned-header":`group:${t}`,focus:i,scroll:"less"===n||s},"more"===n?f.current.onShowMore(t):f.current.onShowLess(t)},[]);(0,i.useLayoutEffect)(()=>{let e=K.current;if(!e)return;K.current=null;let n=g.current,r=t.findIndex(t=>t.key===e.rowKey);if(r<0&&(r=t.findIndex(t=>t.key===e.fallbackKey)),e.scroll&&n&&r>=0){let e=ed(T,r,n.scrollTop,n.clientHeight);null!==e&&(n.scrollTop=e),y(n.scrollTop)}e.focus&&(q.current={rowKey:e.rowKey,fallbackKey:e.fallbackKey,tries:0})},[t,T]);let Z=(0,i.useRef)(null);(0,i.useLayoutEffect)(()=>{if(!F)return;let e=t.findIndex(e=>e.key===F.rowKey),n=function(e,t,n,r){let i=e?.id===t.id?e:{id:t.id,misses:0};if(!(r-t.at<=3e3))return{misses:i,action:"drop"};if(n)return{misses:i,action:"reveal"};let s={id:t.id,misses:i.misses+1};return{misses:s,action:s.misses>=3?"drop":"wait"}}(Z.current,F,e>=0,Date.now());if(Z.current=n.misses,"wait"!==n.action){if("reveal"===n.action){let t=g.current;if(t&&t.getClientRects().length>0){let n=ed(T,e,t.scrollTop,t.clientHeight,F.block);null!==n&&(t.scrollTop=n),y(t.scrollTop)}F.takeFocusFrom&&(q.current={rowKey:F.rowKey,fallbackKey:F.rowKey,tries:0,takeFocusFrom:F.takeFocusFrom})}O(F.id),f.current.onRevealHandled?.(F.id)}},[F,t,T]),(0,i.useLayoutEffect)(()=>{let e=q.current;if(!e)return;let t=document.activeElement;if(t&&t!==document.body&&document.contains(t)&&!e.takeFocusFrom?.(t)){q.current=null;return}let n=g.current,r=e=>n?.querySelector(`[data-row-key="${CSS.escape(e)}"]`)??null,i=r(e.rowKey),s=i?.querySelector('[data-more-action="more"]')??i?.querySelector("a[href], button")??r(e.fallbackKey)?.querySelector("a[href], button");s?(s.focus({preventScroll:!0}),q.current=null):++e.tries>2&&(q.current=null)},[U]);let J=t.some(e=>"session"===e.kind||"group"===e.kind||"archive-group"===e.kind),Y=!o&&!l&&null!==s&&!J,G=z?.source??null,X=z?.drop?.lineY??null,Q=z?.phase==="dragging"?t.find(e=>"group"===e.kind&&e.project.key===z.projectKey)?.project??null:null;return(0,r.jsxs)("div",{ref:m,className:`session-tree${"mobile"===n?" is-mobile":""}${Q?" is-group-dragging":""}`,children:[o&&(0,r.jsx)("div",{className:"session-tree-message",children:h("sidebar.loading")}),l&&(0,r.jsx)("div",{className:"session-tree-message is-error",children:l}),Y&&(0,r.jsx)("div",{className:"session-tree-message",children:s}),(0,r.jsx)("div",{ref:g,className:"session-tree-scroll scrollbar-subtle",onScroll:$,onFocus:I,onBlur:M,onPointerDownCapture:L.onPointerDownCapture,onClickCapture:L.onClickCapture,children:!o&&(0,r.jsxs)("div",{ref:x,className:"session-tree-inner",style:{height:T[t.length]},children:[U.map(e=>{let i=t[e];if("spacer"===i.kind)return null;let s=T[e],o=T[e+1]-s,l=i.key===u;if("session"===i.kind)return(0,r.jsx)(n5,{row:i,layout:n,top:s,height:o,now:C,renaming:i.family.root.id===a,confirming:i.family.root.id===c,menuOpen:l,handlers:f},i.key);if("archive-group"===i.kind)return(0,r.jsx)(rn,{row:i,top:s,height:o,menuOpen:l,handlers:f},i.key);if("group"===i.kind){let e=i.project.key===d;return(0,r.jsx)(re,{row:i,top:s,height:o,menuOpen:l,renaming:e,canDrag:R&&!e&&A[i.project.pinned?"pinned":"other"]>1,dragPhase:z?.projectKey===i.project.key?z.phase:null,drag:L.handlers,handlers:f},i.key)}return(0,r.jsx)(rt,{row:i,top:s,height:o,handlers:f,onMoreAction:V},i.key)}),G&&(0,r.jsx)("div",{className:"session-tree-drag-source","aria-hidden":"true",style:{top:G.top,height:G.bottom-G.top}}),null!==X&&(0,r.jsx)("div",{className:"session-tree-drop-line","aria-hidden":"true",style:{top:X}})]})}),Q&&(0,r.jsx)("div",{ref:v,className:"session-tree-drag-ghost","aria-hidden":"true",children:(0,r.jsx)("span",{className:"session-tree-group-name",children:Q.name})})]})}function n3(e,t){return{top:e,height:t}}let n5=(0,i.memo)(function(e){let t,n,{row:i,layout:s,top:o,height:l,now:a,renaming:d,confirming:c,menuOpen:u,handlers:h}=e,{locale:f,t:m}=(0,tm.s)(),{family:g,context:x,status:v}=i,b=g.root,y=n2(b),w=new Date(a),k=["session-tree-row session-tree-session",v.selected?"is-selected":"",v.running?"is-running":"","archive"===x?"is-archived":"",u?"is-menu-open":"",c?"is-confirming":"",d?"is-renaming":""].filter(Boolean).join(" ");if(c){let e=y.slice(0,22)+(y.length>22?"…":"");return(0,r.jsx)("div",{className:k,style:n3(o,l),"data-row-key":i.key,onKeyDown:e=>{"Escape"!==e.key||n4(e)||(e.preventDefault(),e.stopPropagation(),h.current.onDeleteCancel())},children:(0,r.jsx)(n9,{label:m("sidebar.deleteSession",{title:e}),deleteLabel:m("sidebar.delete"),cancelLabel:m("sidebar.cancel"),onConfirm:e=>{e.stopPropagation(),h.current.onDeleteConfirm(g,e)},onCancel:e=>{e.stopPropagation(),h.current.onDeleteCancel()}})})}if(d)return(0,r.jsx)("div",{className:k,style:n3(o,l),"data-row-key":i.key,children:(0,r.jsx)(n6,{initialValue:y,label:m("sidebar.rename"),onCommit:e=>h.current.onRenameCommit(g,e),onCancel:()=>h.current.onRenameCancel()})});let j=b.isWorktree&&b.branch?b.branch:null,S=b.name&&b.relation?.kind==="fork"?eM(b.name):null,C=b.detailsPending?"…":m("sidebar.messagesCount",{count:b.messageCount}),N=`${y}
|
|
2
|
+
${b(nh[w])}`:t.fullPath,children:t.name}),!z&&_&&(0,r.jsx)("span",{title:b("files.outsideLink",{target:_}),"aria-label":b("files.outsideLink",{target:_}),style:{width:14,height:14,flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-dim)"},children:(0,r.jsx)(np,{})}),j&&(0,r.jsx)("span",{title:b("files.newlyUploaded"),"aria-label":b("files.newlyUploaded"),style:{width:14,height:14,flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center"},children:(0,r.jsx)("span",{style:{width:6,height:6,borderRadius:"50%",background:"#3b82f6"}})}),!z&&!t.isDir&&C&&(0,r.jsx)(nc,{status:C,t:b}),!z&&N&&(0,r.jsx)("span",{title:b("files.containsChangedFiles"),"aria-label":b("files.containsChangedFiles"),style:{width:14,height:14,flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center"},children:(0,r.jsx)("span",{style:{width:6,height:6,borderRadius:"50%",background:"#d6a84b"}})}),T&&(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"var(--text-dim)",strokeWidth:"2",strokeLinecap:"round",children:(0,r.jsx)("path",{d:"M12 2v4M12 18v4M4.93 4.93l2.83 2.83M16.24 16.24l2.83 2.83M2 12h4M18 12h4"})}),l&&z&&(0,r.jsxs)("button",{onClick:e=>{e.stopPropagation(),l(t4(t.fullPath,s),t.isDir)},title:b("files.insertPath"),style:{position:"absolute",right:t.isDir?4:28,top:"50%",transform:"translateY(-50%)",display:"flex",alignItems:"center",justifyContent:"center",gap:4,padding:"0 8px",height:"calc(var(--file-row-height) - 4px)",background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:4,color:"var(--accent)",cursor:"pointer",fontSize:11,fontWeight:600,whiteSpace:"nowrap"},children:[(0,r.jsx)(nu,{}),b("files.mention")]}),z&&!t.isDir&&(0,r.jsx)("a",{href:`/api/files/${t0(t.fullPath)}?type=download`,download:!0,onClick:e=>e.stopPropagation(),title:b("files.download"),style:{position:"absolute",right:4,top:"50%",transform:"translateY(-50%)",display:"flex",alignItems:"center",justifyContent:"center",gap:4,padding:"0 5px",height:"calc(var(--file-row-height) - 4px)",background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:4,color:"var(--text-muted)",cursor:"pointer",fontSize:11,fontWeight:600,whiteSpace:"nowrap",textDecoration:"none"},children:(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),(0,r.jsx)("polyline",{points:"7 10 12 15 17 10"}),(0,r.jsx)("line",{x1:"12",y1:"15",x2:"12",y2:"3"})]})})]}),t.isDir&&y&&_&&(0,r.jsxs)("div",{style:{paddingLeft:8+(n+1)*14,paddingRight:8,paddingTop:3,paddingBottom:5,display:"flex",flexDirection:"column",alignItems:"flex-start",gap:4,fontSize:11,color:"var(--text-dim)"},children:[(0,r.jsx)("span",{style:{wordBreak:"break-all"},children:b("files.outsideLink",{target:_})}),t.outsideLinkEncloses&&(0,r.jsx)("span",{style:{color:"#f59e0b"},children:b("files.outsideLinkEncloses")}),(0,r.jsx)("button",{type:"button",onClick:V,disabled:F,title:b("files.allowOutsideLinkTitle",{target:_}),style:{height:"calc(var(--file-row-height) - 4px)",padding:"0 8px",background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:4,color:"var(--accent)",cursor:F?"default":"pointer",opacity:F?.6:1,fontSize:11,fontWeight:600,whiteSpace:"nowrap"},children:b("files.allowOutsideLink")}),B&&(0,r.jsx)("span",{role:"alert",style:{color:"#f87171",wordBreak:"break-word"},children:B})]}),t.isDir&&y&&!_&&(0,r.jsxs)("div",{children:[E.map(e=>(0,r.jsx)(nf,{node:e,depth:n+1,cwd:s,onOpenFile:o,onAtMention:l,expandedPaths:a,onToggleExpanded:d,refreshToken:c,highlightedPaths:u,gitStatusByPath:p,changedDirectoryPaths:h,showHidden:f,parentHidden:w,dropTargetPath:g,onDropFiles:x,onDropTargetChange:v,t:b},e.fullPath)),0===E.length&&I&&!A&&(0,r.jsx)("div",{style:{paddingLeft:8+(n+1)*14,fontSize:11,color:"var(--text-dim)",height:22,display:"flex",alignItems:"center"},children:"empty"}),A&&(0,r.jsx)("div",{role:"alert",style:{paddingLeft:8+(n+1)*14,paddingRight:8,paddingTop:3,paddingBottom:3,fontSize:11,color:"#f87171",wordBreak:"break-word"},children:A})]})]})}function nm(e){let{status:t,cwd:n,onOpenFile:s,onAtMention:o,t:l,depth:a=0,treeMode:d=!1}=e,[c,u]=(0,i.useState)(!1),p=t1(t.filePath),h=t4(t.filePath,n),f=h.lastIndexOf("/"),m=!d&&f>=0?h.slice(0,f+1):"",g=d?p:f>=0?h.slice(f+1):h;return(0,r.jsxs)("div",{onClick:()=>s(t.filePath,p,{modeHint:"diff"}),onMouseEnter:()=>u(!0),onMouseLeave:()=>u(!1),title:t.filePath,style:{display:"flex",alignItems:"center",gap:d?4:6,paddingLeft:d?8+14*a:10,paddingRight:8,height:"var(--file-row-height)",cursor:"pointer",background:c?"var(--bg-hover)":"transparent",borderRadius:4,userSelect:"none",position:"relative"},children:[(0,r.jsx)(nc,{status:t,t:l}),d&&(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),(0,r.jsx)("span",{style:{flexShrink:0,display:"flex",alignItems:"center",opacity:.85},children:tX(p,13)}),(0,r.jsxs)("span",{title:t.filePath,style:{fontSize:12,color:"var(--text)",display:"flex",alignItems:"center",minWidth:0,flex:1},children:[m&&(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:"0 1 auto",minWidth:0,color:"var(--text-dim)"},children:m}),(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flexShrink:+!!d,maxWidth:"100%"},children:g})]}),o&&c&&(0,r.jsxs)("button",{onClick:e=>{e.stopPropagation(),o(h,!1)},title:l("files.insertPath"),style:{position:"absolute",right:4,top:"50%",transform:"translateY(-50%)",display:"flex",alignItems:"center",justifyContent:"center",gap:4,padding:"0 8px",height:"calc(var(--file-row-height) - 4px)",background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:4,color:"var(--accent)",cursor:"pointer",fontSize:11,fontWeight:600,whiteSpace:"nowrap"},children:[(0,r.jsx)(nu,{}),l("files.mention")]})]})}function ng(e){let{node:t,depth:n,open:s,onToggle:o}=e,[l,a]=(0,i.useState)(!1);return(0,r.jsxs)("div",{onClick:()=>o(t.path,!s),onMouseEnter:()=>a(!0),onMouseLeave:()=>a(!1),title:t.path,style:{display:"flex",alignItems:"center",gap:4,paddingLeft:8+14*n,paddingRight:8,height:"var(--file-row-height)",cursor:"pointer",background:l?"var(--bg-hover)":"transparent",borderRadius:4,userSelect:"none"},children:[(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--text-dim)",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,transform:s?"rotate(90deg)":"none",transition:"transform 0.1s"},"aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"3 2 7 5 3 8"})}),(0,r.jsx)("span",{style:{flexShrink:0,display:"flex",alignItems:"center"},children:(0,r.jsx)(tJ,{size:14,open:s})}),(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1},children:t.name})]})}function nx(e){let{nodes:t,depth:n,cwd:i,statusByPath:s,collapsedPaths:o,onToggleExpanded:l,onOpenFile:a,onAtMention:d,t:c}=e;return(0,r.jsx)(r.Fragment,{children:t.map(e=>{if(e.isDir){let t=!o.has(e.path);return(0,r.jsxs)("div",{children:[(0,r.jsx)(ng,{node:e,depth:n,open:t,onToggle:l}),t&&(0,r.jsx)(nx,{nodes:e.children,depth:n+1,cwd:i,statusByPath:s,collapsedPaths:o,onToggleExpanded:l,onOpenFile:a,onAtMention:d,t:c})]},`dir:${e.path}`)}let t=s.get(e.path);return t?(0,r.jsx)(nm,{status:t,cwd:i,onOpenFile:a,onAtMention:d,t:c,depth:n,treeMode:!0},t.filePath):null})})}function nv(e){let{mode:t}=e;return"tree"===t?(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M8 6h13"}),(0,r.jsx)("path",{d:"M8 12h13"}),(0,r.jsx)("path",{d:"M8 18h13"}),(0,r.jsx)("path",{d:"M3 6h.01"}),(0,r.jsx)("path",{d:"M3 12h.01"}),(0,r.jsx)("path",{d:"M3 18h.01"})]}):(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M6 3v12"}),(0,r.jsx)("path",{d:"M18 9a3 3 0 1 0 0-6 3 3 0 0 0 0 6z"}),(0,r.jsx)("path",{d:"M6 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6z"}),(0,r.jsx)("path",{d:"M18 21a3 3 0 1 0 0-6 3 3 0 0 0 0 6z"}),(0,r.jsx)("path",{d:"M9 12h6"}),(0,r.jsx)("path",{d:"M12 12v3"})]})}let nb=(0,i.forwardRef)(function(e,t){let{cwd:n,onOpenFile:s,refreshKey:o,onAtMention:l,onAtMentions:a,onUploadBusyChange:d,changesCollapsed:c,onChangesCountChange:u,fileSearchOpen:p=!1,onFileSearchOpenChange:h,showHidden:f=!1}=e,{t:m}=(0,tm.s)(),[g,x]=(0,i.useState)([]),[v,b]=(0,i.useState)(!0),[y,w]=(0,i.useState)(null),[k,j]=(0,i.useState)(new Set),[S,C]=(0,i.useState)(0),[N,E]=(0,i.useState)(new Set),[$,I]=(0,i.useState)([]),[M,T]=(0,i.useState)({additions:0,deletions:0}),[R,A]=(0,i.useState)("list"),[L,z]=(0,i.useState)(()=>new Set),[P,W]=(0,i.useState)("idle"),[O,F]=(0,i.useState)(0),[D,B]=(0,i.useState)(null),[H,_]=(0,i.useState)(null),[U,K]=(0,i.useState)(null),[q,V]=(0,i.useState)(""),[Z,J]=(0,i.useState)([]),[Y,G]=(0,i.useState)(!1),[X,Q]=(0,i.useState)(!1),[ee,et]=(0,i.useState)(new Set),en=(0,i.useRef)(null),[er,ei]=(0,i.useState)(!1),[es,eo]=(0,i.useState)(null),el=(0,i.useRef)(0),ea=(0,i.useRef)(null),ed=(0,i.useRef)(k),ec=(0,i.useRef)(null),eu=`${o??0}:${S}`,ep="idle"!==P,eh=q.trim().length>0;(0,i.useEffect)(()=>{if(!p)return;let e=q.trim();if(!e){J([]),G(!1),Q(!1);return}let t=new AbortController;G(!0),Q(!1);let r=setTimeout(()=>{fetch(`/api/file-index?cwd=${encodeURIComponent(n)}&q=${encodeURIComponent(e)}`,{signal:t.signal}).then(e=>e.ok?e.json():Promise.reject(Error("Search failed"))).then(e=>J((e.matches??[]).filter(e=>!e.isDir).map(e=>e.path))).catch(()=>{t.signal.aborted||(J([]),Q(!0))}).finally(()=>{t.signal.aborted||G(!1)})},150);return()=>{clearTimeout(r),t.abort()}},[n,p,q]),(0,i.useEffect)(()=>{p&&en.current?.focus()},[p]),(0,i.useEffect)(()=>{if(0===Z.length)return;let e=new Set;for(let t of Z){let r=t.split("/"),i="";for(let t=0;t<r.length-1;t++)i=i?`${i}/${r[t]}`:r[t],e.add(t8(n,i))}et(t=>{let n=!1,r=new Set(t);for(let t of e)r.has(t)||(r.add(t),n=!0);return n?r:t})},[n,Z]);let ef=(0,i.useMemo)(()=>{let e=t=>({name:t.name,fullPath:t8(n,t.path),isDir:t.isDir,size:0,children:t.children.map(e),loaded:!0});return ne(Z).map(e)},[n,Z]),em=(0,i.useMemo)(()=>new Map($.map(e=>[tQ(e.filePath),e])),[$]),eg=(0,i.useMemo)(()=>{let e=new Set,t=tQ(n).replace(/\/$/,"");for(let n of $){let r=t2(tQ(n.filePath));for(;(r===t||r.startsWith(`${t}/`))&&(e.add(r),r!==t);){let e=t2(r);if(e===r)break;r=e}}return e},[n,$]),ev=(0,i.useMemo)(()=>new Map($.map(e=>[tQ(t4(e.filePath,n)).replace(/^\/+/,""),e])),[n,$]),eb=(0,i.useMemo)(()=>ne([...ev.keys()]),[ev]),ew=(0,i.useCallback)((e,t)=>{j(n=>{let r=new Set(n);return t?r.add(e):r.delete(e),r})},[]),ek=(0,i.useCallback)((e,t)=>{let n=e.uploaded??[];_({directory:t,uploaded:n,skipped:e.skipped??[],errors:e.errors??[]}),n.length>0&&(E(new Set(n.map(e=>t8(t,e)))),C(e=>e+1))},[]),ej=(0,i.useCallback)(async(e,t,n)=>{K(null),B(null),F(0),W("uploading");try{let{status:r,data:i}=await t7(n,e,t,F);if(409===r&&i.conflicts?.length)return void K({directory:n,files:e,conflicts:i.conflicts,nonReplaceable:i.nonReplaceable??[]});if(r<200||r>=300)throw Error(i.error??`Upload failed (HTTP ${r})`);F(100),ek(i,n)}catch(e){B(e instanceof Error?e.message:String(e))}finally{W("idle")}},[ek]),eS=(0,i.useCallback)(async(e,t)=>{if(0!==e.length&&!ep){_(null),E(new Set),K(null),B(null),F(0),W("checking");try{let n=await fetch(`/api/files/${t0(t)}?type=upload-check`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({fileNames:e.map(e=>e.name)})}),r=await n.json().catch(()=>({}));if(!n.ok)throw Error(r.error??`Upload check failed (HTTP ${n.status})`);if(r.conflicts?.length)return void K({directory:t,files:e,conflicts:r.conflicts,nonReplaceable:r.nonReplaceable??[]});await ej(e,"error",t)}catch(e){B(e instanceof Error?e.message:String(e))}finally{W("idle")}}},[ej,ep]),eC=(0,i.useCallback)(e=>{let t=Array.from(e.target.files??[]);e.target.value="",eS(t,n)},[n,eS]);(0,i.useImperativeHandle)(t,()=>({openUploadPicker(){ep||ec.current?.click()}}),[ep]);let eN=(0,i.useCallback)(()=>{el.current=0,ei(!1),eo(null)},[]),eE=(0,i.useCallback)(e=>{e.dataTransfer.types.includes("Files")&&(e.preventDefault(),el.current+=1,ei(!0))},[]),e$=(0,i.useCallback)(e=>{e.dataTransfer.types.includes("Files")&&(e.preventDefault(),e.dataTransfer.dropEffect="copy",eo(e=>null===e?e:null))},[]),eI=(0,i.useCallback)(()=>{el.current<=0||(el.current-=1,0===el.current&&(el.current=0,ei(!1),eo(null)))},[]),eM=(0,i.useCallback)((e,t)=>{eN();let n=t.flatMap(e=>"file"===e.kind?[e.file]:[]),r=t.flatMap(e=>"folder"===e.kind?[e.name]:[]);eS(n,e).then(()=>{if(0===r.length)return;let e=m("chat.dropFoldersUnsupported",{names:r.join(", ")});B(t=>t&&n.length>0?t:e)})},[eS,eN,m]),eT=(0,i.useCallback)(e=>{e.dataTransfer.types.includes("Files")&&(e.preventDefault(),e.stopPropagation(),eM(es??n,nn(e.dataTransfer)))},[n,es,eM]),eR=(0,i.useCallback)(e=>{eo(t=>t===e?t:e)},[]);(0,i.useEffect)(()=>{d?.(ep)},[d,ep]),(0,i.useEffect)(()=>()=>d?.(!1),[d]),(0,i.useEffect)(()=>{ed.current=k},[k]),(0,i.useEffect)(()=>()=>{null!==ea.current&&nr.save(ea.current,ed.current)},[]),(0,i.useEffect)(()=>{let e=ea.current,t=e!==n;if(ea.current=n,t){null!==e&&nr.save(e,ed.current);let t=nr.restore(n);ed.current=t,j(t),E(new Set),_(null),K(null),B(null)}b(t),w(null);let r=!1;return ns(n,f).then(e=>{r||x(e)}).catch(e=>{r||w(e instanceof Error?e.message:String(e))}).finally(()=>{r||b(!1)}),()=>{r=!0}},[n,o,S,f]),(0,i.useEffect)(()=>{let e=()=>C(e=>e+1);return window.addEventListener("focus",e),()=>window.removeEventListener("focus",e)},[]),(0,i.useEffect)(()=>{let e=!1,t=new AbortController;return nl(n,t.signal).then(t=>{e||(I(t.isGitRepository?t.files:[]),T(t.isGitRepository?{additions:t.additions,deletions:t.deletions}:{additions:0,deletions:0}))}).catch(()=>{e||(I([]),T({additions:0,deletions:0}))}),()=>{e=!0,t.abort()}},[n,o,S]),(0,i.useEffect)(()=>{u?.($.length)},[$,u]),(0,i.useEffect)(()=>{A(function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:ey();if(!e)return"list";try{return"tree"===e.getItem(ex)?"tree":"list"}catch{return"list"}}())},[]);let eA=(0,i.useCallback)((e,t)=>{z(n=>{let r=new Set(n);return t?r.delete(e):r.add(e),r})},[]),eL=(0,i.useCallback)(()=>{A(e=>{let t="list"===e?"tree":"list";return!function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:ey();if(t)try{t.setItem(ex,e)}catch{}}(t),t})},[]),ez=ep||null!==U||null!==D||null!==H,eP=(0,i.useCallback)(()=>{H&&0!==H.uploaded.length&&a?.(H.uploaded.map(e=>t4(t8(H.directory,e),n)))},[n,a,H]);return(0,r.jsxs)("div",{style:{minHeight:"100%"},onDragEnter:eE,onDragOver:e$,onDragLeave:eI,onDrop:eT,children:[(0,r.jsx)("input",{ref:ec,type:"file",multiple:!0,hidden:!0,onChange:eC}),ez&&(0,r.jsxs)("div",{style:{padding:"6px 8px",borderBottom:"1px solid var(--border)"},children:[ep&&(0,r.jsxs)("div",{role:"status","aria-live":"polite","aria-label":"checking"===P?m("files.checking"):m("files.uploading",{progress:O}),children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,minHeight:14,color:"var(--text-muted)"},children:["checking"===P?(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",style:{animation:"spin 0.8s linear infinite"},"aria-hidden":"true",children:(0,r.jsx)("path",{d:"M21 12a9 9 0 1 1-5.7-8.4"})}):(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M12 16V4"}),(0,r.jsx)("path",{d:"m7 9 5-5 5 5"}),(0,r.jsx)("path",{d:"M5 20h14"})]}),"uploading"===P&&(0,r.jsxs)("span",{style:{fontSize:10},children:[O,"%"]})]}),"uploading"===P&&(0,r.jsx)("div",{style:{height:3,marginTop:4,overflow:"hidden",borderRadius:2,background:"var(--border)"},children:(0,r.jsx)("div",{style:{width:`${O}%`,height:"100%",background:"var(--text-muted)",transition:"width 120ms ease"}})})]}),U&&(0,r.jsxs)("div",{role:"alert",style:{padding:7,border:"1px solid color-mix(in srgb, #f59e0b 55%, var(--border))",borderRadius:4,background:"color-mix(in srgb, #f59e0b 9%, var(--bg-panel))"},children:[(0,r.jsx)("div",{style:{fontSize:11,color:"var(--text)",lineHeight:1.35,overflowWrap:"anywhere"},children:m("files.conflictSummary",{count:U.conflicts.length,countSuffix:1===U.conflicts.length?"":"s",files:U.conflicts.join(", ")})}),U.nonReplaceable.length>0&&(0,r.jsx)("div",{style:{marginTop:3,fontSize:10,color:"#f59e0b",lineHeight:1.35,overflowWrap:"anywhere"},children:m("files.cannotReplace",{files:U.nonReplaceable.join(", ")})}),(0,r.jsxs)("div",{style:{display:"flex",gap:5,marginTop:7},children:[(0,r.jsx)("button",{type:"button",onClick:()=>void ej(U.files,"overwrite",U.directory),style:{height:22,padding:"0 7px",border:"1px solid #ef4444",borderRadius:4,background:"transparent",color:"#ef4444",cursor:"pointer",fontSize:10},children:m("files.replace")}),(0,r.jsx)("button",{type:"button",onClick:()=>void ej(U.files,"skip",U.directory),style:{height:22,padding:"0 7px",border:"1px solid var(--border)",borderRadius:4,background:"var(--bg-panel)",color:"var(--text)",cursor:"pointer",fontSize:10},children:m("files.skipExisting")}),(0,r.jsx)("button",{type:"button",onClick:()=>K(null),style:{height:22,padding:"0 7px",border:"none",borderRadius:4,background:"transparent",color:"var(--text-muted)",cursor:"pointer",fontSize:10},children:m("files.cancel")})]})]}),D&&(0,r.jsxs)("div",{role:"alert",style:{display:"flex",alignItems:"flex-start",gap:6,fontSize:11,lineHeight:1.35,color:"#f87171"},children:[(0,r.jsx)("span",{style:{minWidth:0,flex:1,overflowWrap:"anywhere"},children:D}),(0,r.jsx)(tq,{onClick:()=>B(null),title:m("files.dismissError")})]}),H&&(0,r.jsxs)("div",{"aria-live":"polite",children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,minHeight:22,fontSize:11},children:[(0,r.jsxs)("div",{style:{minWidth:0,flex:1,display:"flex",alignItems:"center",gap:8},children:[H.uploaded.length>0&&(0,r.jsxs)("span",{title:m("files.uploadedCount",{count:H.uploaded.length}),"aria-label":m("files.uploadedCount",{count:H.uploaded.length}),style:{display:"flex",alignItems:"center",gap:3,color:"#22c55e"},children:[(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.4",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m5 12 4 4L19 6"})}),(0,r.jsx)("span",{children:H.uploaded.length})]}),H.skipped.length>0&&(0,r.jsxs)("span",{title:m("files.skippedCount",{count:H.skipped.length}),"aria-label":m("files.skippedCount",{count:H.skipped.length}),style:{display:"flex",alignItems:"center",gap:3,color:"var(--text-dim)"},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"9"}),(0,r.jsx)("path",{d:"M8 12h8"})]}),(0,r.jsx)("span",{children:H.skipped.length})]}),H.errors.length>0&&(0,r.jsxs)("span",{title:m("files.failedCount",{count:H.errors.length}),"aria-label":m("files.failedCount",{count:H.errors.length}),style:{display:"flex",alignItems:"center",gap:3,color:"#f87171"},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M12 3 2.5 20h19L12 3Z"}),(0,r.jsx)("path",{d:"M12 9v4"}),(0,r.jsx)("path",{d:"M12 17h.01"})]}),(0,r.jsx)("span",{children:H.errors.length})]})]}),H.uploaded.length>0&&a&&(0,r.jsxs)("button",{type:"button",onClick:eP,title:1===H.uploaded.length?m("files.addUploadedFile"):m("files.addAllUploadedFiles"),"aria-label":1===H.uploaded.length?m("files.addUploadedFile"):m("files.addAllUploadedFiles"),style:{height:22,padding:"0 7px",display:"flex",alignItems:"center",justifyContent:"center",gap:4,flexShrink:0,border:"1px solid var(--border)",borderRadius:4,background:"var(--bg-panel)",color:"var(--accent)",cursor:"pointer",fontSize:11,fontWeight:600,whiteSpace:"nowrap"},children:[(0,r.jsx)(nu,{}),m("files.mention")]}),(0,r.jsx)(tq,{onClick:()=>_(null),title:m("files.dismissUploadResults")})]}),H.errors.map(e=>(0,r.jsxs)("div",{title:e.error,style:{display:"flex",alignItems:"center",gap:4,marginTop:3,minWidth:0,fontSize:10,color:"#f87171"},children:[(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},"aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"9"}),(0,r.jsx)("path",{d:"M12 8v5"}),(0,r.jsx)("path",{d:"M12 17h.01"})]}),(0,r.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name})]},e.name))]})]}),p&&(0,r.jsxs)("div",{style:{padding:"2px 8px 6px"},children:[(0,r.jsxs)("div",{style:{position:"relative"},children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{position:"absolute",left:8,top:"50%",transform:"translateY(-50%)",color:"var(--text-dim)",pointerEvents:"none"},children:[(0,r.jsx)("circle",{cx:"11",cy:"11",r:"7"}),(0,r.jsx)("path",{d:"m20 20-4-4"})]}),(0,r.jsx)("input",{ref:en,id:"file-search-input",value:q,onChange:e=>V(e.target.value),onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),h?.(!1))},placeholder:m("sidebar.searchFilesPlaceholder"),"aria-label":m("sidebar.searchFiles"),style:{width:"100%",boxSizing:"border-box",padding:"6px 24px",border:"1px solid var(--border)",borderRadius:8,outline:"none",background:"var(--bg)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:11}}),q&&(0,r.jsx)("button",{type:"button",onClick:()=>V(""),title:m("sidebar.clearSearch"),"aria-label":m("sidebar.clearSearch"),style:{position:"absolute",right:4,top:"50%",transform:"translateY(-50%)",display:"flex",alignItems:"center",justifyContent:"center",width:18,height:18,padding:0,border:"none",borderRadius:4,background:"none",color:"var(--text-dim)",cursor:"pointer"},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-dim)"},children:(0,r.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.4",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M18 6 6 18"}),(0,r.jsx)("path",{d:"m6 6 12 12"})]})})]}),eh&&(0,r.jsxs)("div",{style:{paddingTop:3},children:[Y&&(0,r.jsx)("div",{role:"status",style:{padding:"6px 2px",fontSize:10,color:"var(--text-dim)"},children:m("sidebar.searchingFiles")}),!Y&&X&&(0,r.jsx)("div",{role:"alert",style:{padding:"6px 2px",fontSize:10,color:"#f87171"},children:m("i18n.networkError")}),!Y&&!X&&0===Z.length&&(0,r.jsx)("div",{style:{padding:"6px 2px",fontSize:10,color:"var(--text-dim)"},children:m("sidebar.noMatchingFiles")}),!Y&&!X&&Z.length>0&&(0,r.jsx)("div",{children:ef.map(e=>(0,r.jsx)(nf,{node:e,depth:0,cwd:n,onOpenFile:s,onAtMention:l,expandedPaths:ee,onToggleExpanded:(e,t)=>{et(n=>{let r=new Set(n);return t?r.add(e):r.delete(e),r})},highlightedPaths:N,gitStatusByPath:em,changedDirectoryPaths:eg,dropTargetPath:es,onDropFiles:eM,onDropTargetChange:eR,t:m},`${q}:${e.fullPath}`))})]})]}),!c&&$.length>0&&(0,r.jsxs)("div",{style:{padding:"0 4px 2px"},children:[(0,r.jsxs)("div",{"aria-label":m("files.changeStats",{count:$.length,additions:M.additions,deletions:M.deletions}),style:{display:"flex",alignItems:"center",gap:6,height:24,padding:"0 6px 0 10px",fontSize:12},children:[(0,r.jsx)("span",{style:{color:"var(--text-dim)"},children:m("files.changedCount",{count:$.length})}),(0,r.jsxs)("span",{style:{color:nd.added,fontFamily:"var(--font-mono)"},children:["+",M.additions]}),(0,r.jsxs)("span",{style:{color:nd.deleted,fontFamily:"var(--font-mono)"},children:["-",M.deletions]}),(0,r.jsx)("span",{style:{flex:1}}),(0,r.jsx)("button",{type:"button",onClick:eL,title:"list"===R?m("files.viewAsTree"):m("files.viewAsList"),"aria-label":"list"===R?m("files.viewAsTree"):m("files.viewAsList"),"aria-pressed":"tree"===R,style:{display:"flex",alignItems:"center",justifyContent:"center",width:22,height:22,padding:0,border:"none",borderRadius:4,background:"transparent",color:"var(--text-dim)",cursor:"pointer",flexShrink:0},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-dim)"},children:(0,r.jsx)(nv,{mode:R})})]}),"tree"===R?(0,r.jsx)(nx,{nodes:eb,depth:0,cwd:n,statusByPath:ev,collapsedPaths:L,onToggleExpanded:eA,onOpenFile:s,onAtMention:l,t:m}):$.map(e=>(0,r.jsx)(nm,{status:e,cwd:n,onOpenFile:s,onAtMention:l,t:m},e.filePath))]}),(c||0===$.length)&&(!p||!eh)&&(0,r.jsxs)("div",{style:{padding:"2px 4px"},children:[v?(0,r.jsx)("div",{style:{padding:"8px 12px",fontSize:11,color:"var(--text-dim)"},children:m("files.loading")}):y?(0,r.jsx)("div",{style:{padding:"8px 12px",fontSize:11,color:"#f87171"},children:y}):g.map(e=>(0,r.jsx)(nf,{node:e,depth:0,cwd:n,onOpenFile:s,onAtMention:l,expandedPaths:k,onToggleExpanded:ew,refreshToken:eu,highlightedPaths:N,gitStatusByPath:em,changedDirectoryPaths:eg,showHidden:f,dropTargetPath:es,onDropFiles:eM,onDropTargetChange:eR,t:m},e.fullPath)),!v&&!y&&0===g.length&&(0,r.jsx)("div",{style:{padding:"8px 12px",fontSize:11,color:"var(--text-dim)"},children:m("files.noFiles")})]}),er&&(0,r.jsxs)("div",{role:"status","aria-live":"polite",style:{position:"sticky",bottom:0,zIndex:1,display:"flex",alignItems:"center",gap:6,padding:"6px 8px",borderTop:"1px solid var(--border)",background:"var(--bg-panel)",fontSize:11,color:"var(--accent)",userSelect:"none",pointerEvents:"none"},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0},children:[(0,r.jsx)("path",{d:"M12 16V4"}),(0,r.jsx)("path",{d:"m7 9 5-5 5 5"}),(0,r.jsx)("path",{d:"M5 20h14"})]}),m("files.dropToUpload",{directory:es?t4(es,n)||es:t1(n)||n})]})]})}),ny="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*";function nw(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:Math.random,r=4*e.length;if(t>=r)return e;let i=Math.floor(t/r*e.length),s="";for(let t=0;t<e.length;t++){let r=e[t];s+=" "===r||t<i?r:ny[Math.floor(n()*ny.length)]}return s}function nk(e){let{onWidthChange:t}=e,{t:n}=(0,tm.s)(),[s,o]=(0,i.useState)(!1),l=(0,i.useRef)(null),a="0.17.0-custom.4",d="1.5.2",c=function(e){let[t,n]=(0,i.useState)(e),r=(0,i.useRef)(e);return(0,i.useEffect)(()=>{if(r.current===e)return;if(r.current=e,window.matchMedia?.("(prefers-reduced-motion: reduce)").matches)return void n(e);let t=4*e.length,i=0,s=0,o=()=>{n(nw(e,i+=1)),i<t&&(s=requestAnimationFrame(o))};return n(nw(e,0)),s=requestAnimationFrame(o),()=>cancelAnimationFrame(s)},[e]),t}(s?`${a??"0.0.0"}p${d??"0.0.0"}`:"Pi Web");return(0,i.useLayoutEffect)(()=>{t?.()},[c.length,t]),(0,i.useEffect)(()=>()=>{l.current&&clearTimeout(l.current)},[]),(0,r.jsx)("button",{type:"button",className:`sidebar-brand${s?" is-version":""}`,"aria-label":n("sidebar.brandLabel",{app:a??"0.0.0",pi:d??"0.0.0"}),onClick:()=>{(l.current&&clearTimeout(l.current),l.current=null,s)?o(!1):(o(!0),l.current=setTimeout(()=>{l.current=null,o(!1)},3e3))},children:c})}var nj=n(2730);let nS=/^<skill name="([^"\n]+)" location="([^"\n]+)">\nReferences are relative to [^\n]+\.\n\n([\s\S]*)\n<\/skill>(?:\n\n([\s\S]+))?$/;function nC(e){let t=e.match(nS);if(!t)return null;let[,n,,,r]=t;return r?`/skill:${n} ${r}`:`/skill:${n}`}let nN={desktop:32,mobile:48};function nE(e,t,n,r){return Math.hypot(n-e,r-t)}function n$(e){return e.getClientRects().length>0}function nI(e){let{size:t=13,className:n,label:i,strokeWidth:s=2,children:o}=e;return(0,r.jsx)("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:s,strokeLinecap:"round",strokeLinejoin:"round",className:n,...i?{role:"img","aria-label":i}:{"aria-hidden":!0},children:o})}function nM(e){return(0,r.jsx)(nI,{...e,children:(0,r.jsx)("path",{d:"M12 5v14M5 12h14"})})}function nT(e){return(0,r.jsxs)(nI,{...e,children:[(0,r.jsx)("circle",{cx:"5",cy:"12",r:"1.4",fill:"currentColor",stroke:"none"}),(0,r.jsx)("circle",{cx:"12",cy:"12",r:"1.4",fill:"currentColor",stroke:"none"}),(0,r.jsx)("circle",{cx:"19",cy:"12",r:"1.4",fill:"currentColor",stroke:"none"})]})}function nR(e){return(0,r.jsxs)(nI,{...e,children:[(0,r.jsx)("rect",{x:"3",y:"4",width:"18",height:"5",rx:"1"}),(0,r.jsx)("path",{d:"M5 9v9a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V9"}),(0,r.jsx)("path",{d:"M10 13h4"})]})}function nA(e){return(0,r.jsxs)(nI,{...e,children:[(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 3-6.7L3 8"}),(0,r.jsx)("path",{d:"M3 3v5h5"})]})}function nL(e){return(0,r.jsxs)(nI,{...e,children:[(0,r.jsx)("path",{d:"M12 17v5"}),(0,r.jsx)("path",{d:"M9 10.8a2 2 0 0 1-1.1 1.8l-1.8.9A2 2 0 0 0 5 15.2V16a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-.8a2 2 0 0 0-1.1-1.8l-1.8-.9a2 2 0 0 1-1.1-1.8V7a1 1 0 0 1 1-1 2 2 0 0 0 0-4H8a2 2 0 0 0 0 4 1 1 0 0 1 1 1z"})]})}function nz(e){return(0,r.jsxs)(nI,{...e,children:[(0,r.jsx)("path",{d:"M12 17v5"}),(0,r.jsx)("path",{d:"M15 9.3V7a1 1 0 0 1 1-1 2 2 0 0 0 0-4H8.5"}),(0,r.jsx)("path",{d:"m2 2 20 20"}),(0,r.jsx)("path",{d:"M9 9v1.8a2 2 0 0 1-1.1 1.8l-1.8.9A2 2 0 0 0 5 15.2V16a1 1 0 0 0 1 1h11"})]})}function nP(e){let{strokeWidth:t,...n}=e;return(0,r.jsx)(nI,{...n,strokeWidth:t,children:(0,r.jsx)("path",{d:"m9 6 6 6-6 6"})})}function nW(e){return(0,r.jsxs)(nI,{...e,children:[(0,r.jsx)("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),(0,r.jsx)("circle",{cx:"18",cy:"6",r:"3"}),(0,r.jsx)("circle",{cx:"6",cy:"18",r:"3"}),(0,r.jsx)("path",{d:"M18 9a9 9 0 0 1-9 9"})]})}function nO(e){return(0,r.jsxs)(nI,{...e,children:[(0,r.jsx)("circle",{cx:"6",cy:"5",r:"2.5"}),(0,r.jsx)("circle",{cx:"18",cy:"5",r:"2.5"}),(0,r.jsx)("circle",{cx:"12",cy:"19",r:"2.5"}),(0,r.jsx)("path",{d:"M6 7.5v1.5a3 3 0 0 0 3 3h6a3 3 0 0 0 3-3V7.5"}),(0,r.jsx)("path",{d:"M12 12v4.5"})]})}function nF(e){return(0,r.jsxs)(nI,{...e,children:[(0,r.jsx)("path",{d:"M14 4h6v6"}),(0,r.jsx)("path",{d:"M20 4 11 13"}),(0,r.jsx)("path",{d:"M18 14v4a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4"})]})}function nD(e){return(0,r.jsxs)(nI,{...e,children:[(0,r.jsx)("path",{d:"M3 6h18"}),(0,r.jsx)("path",{d:"M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"}),(0,r.jsx)("path",{d:"M10 11v6M14 11v6"}),(0,r.jsx)("path",{d:"M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"})]})}function nB(e){return(0,r.jsx)(nI,{...e,children:(0,r.jsx)("path",{d:"M17 3a2.83 2.83 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5Z"})})}function nH(e){return(0,r.jsx)(nI,{...e,children:(0,r.jsx)("circle",{cx:"12",cy:"12",r:"4.5",fill:"currentColor",stroke:"none"})})}function n_(e){return(0,r.jsx)(nI,{...e,children:(0,r.jsx)("circle",{cx:"12",cy:"12",r:"4.5"})})}function nU(e){return(0,r.jsx)(nI,{...e,children:(0,r.jsx)("path",{d:"M20 6 9 17l-5-5"})})}function nK(e){return(0,r.jsx)(nI,{...e,children:(0,r.jsx)("path",{d:"M18 6 6 18M6 6l12 12"})})}function nq(e){return(0,r.jsx)(nI,{...e,children:(0,r.jsx)("path",{d:"M3 8a2 2 0 0 1 2-2h3.4l1.9 1.9H19a2 2 0 0 1 2 2V17a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2Z"})})}function nV(e){return(0,r.jsxs)(nI,{...e,children:[(0,r.jsx)("path",{d:"M3 8a2 2 0 0 1 2-2h3.4l1.9 1.9H19a2 2 0 0 1 2 2V17a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2Z"}),(0,r.jsx)("path",{d:"M12 11v5M9.5 13.5h5"})]})}function nZ(e){return(0,r.jsxs)(nI,{...e,children:[(0,r.jsx)("polyline",{points:"4 17 10 11 4 5"}),(0,r.jsx)("line",{x1:"12",y1:"19",x2:"20",y2:"19"})]})}function nJ(e){return(0,r.jsxs)(nI,{...e,children:[(0,r.jsx)("circle",{cx:"11",cy:"11",r:"7"}),(0,r.jsx)("path",{d:"m20 20-4-4"})]})}function nY(e){return(0,r.jsxs)(nI,{...e,children:[(0,r.jsx)("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),(0,r.jsx)("path",{d:"m17 8-5-5-5 5"}),(0,r.jsx)("path",{d:"M12 3v12"})]})}function nG(e){return(0,r.jsxs)(nI,{...e,children:[(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),(0,r.jsx)("path",{d:"M3 3v5h5"})]})}function nX(e){return(0,r.jsxs)(nI,{...e,children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"3"}),(0,r.jsx)("path",{d:"M3 12h6M15 12h6"})]})}function nQ(e){return(0,r.jsxs)(nI,{...e,children:[(0,r.jsx)("path",{d:"M2 12s3.6-7 10-7 10 7 10 7-3.6 7-10 7S2 12 2 12Z"}),(0,r.jsx)("circle",{cx:"12",cy:"12",r:"3"})]})}function n0(e){return(0,r.jsx)(nI,{...e,children:(0,r.jsx)("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}function n1(e){let{className:t,...n}=e;return(0,r.jsx)(nI,{...n,strokeWidth:2.8,className:t?`sidebar-spin ${t}`:"sidebar-spin",children:(0,r.jsx)("path",{d:"M21 12a9 9 0 1 1-3.8-7.4"})})}function n2(e){let t=nC(e.firstMessage)??e.firstMessage;return e.name||t.slice(0,50)||e.id.slice(0,12)}function n4(e){return e.nativeEvent.isComposing||229===e.keyCode}function n8(e){let{rows:t,layout:n,emptyLabel:s,loading:o,error:l,renamingRootId:a,renamingProjectKey:d,confirmDeleteRootId:c,activeMenuRowKey:u,reveal:p}=e,{t:h}=(0,tm.s)(),f=(0,i.useRef)(e);f.current=e;let m=(0,i.useRef)(null),g=(0,i.useRef)(null),x=(0,i.useRef)(null),v=(0,i.useRef)(null);tI(g);let[b,y]=(0,i.useState)(0),[w,k]=(0,i.useState)(0),[j,S]=(0,i.useState)(null),[C,N]=(0,i.useState)(()=>Date.now()),E=(0,i.useRef)(null),$=(0,i.useCallback)(()=>{null===E.current&&(E.current=requestAnimationFrame(()=>{E.current=null;let e=g.current;e&&y(e.scrollTop)}))},[]);(0,i.useLayoutEffect)(()=>{let e=g.current;if(!e)return;let t=()=>{let t=`${Math.max(0,e.offsetWidth-e.clientWidth)}px`;e.style.setProperty("--session-tree-scrollbar",t),e.offsetWidth>0&&e.closest(".session-sidebar")?.style.setProperty("--session-tree-scrollbar",t)};if(t(),k(e.clientHeight),y(e.scrollTop),"u"<typeof ResizeObserver)return;let n=new ResizeObserver(()=>{t(),k(e.clientHeight),y(e.scrollTop)});return n.observe(e),()=>n.disconnect()},[]),(0,i.useEffect)(()=>()=>{null!==E.current&&cancelAnimationFrame(E.current)},[]),(0,i.useEffect)(()=>{let e=window.setInterval(()=>N(Date.now()),6e4);return()=>window.clearInterval(e)},[]);let I=(0,i.useCallback)(e=>{let t=e.target instanceof Element?e.target.closest("[data-row-key]"):null;S(t?.getAttribute("data-row-key")??null)},[]),M=(0,i.useCallback)(e=>{e.currentTarget.contains(e.relatedTarget)||S(null)},[]),T=(0,i.useMemo)(()=>(function(e,t){let n=D[t],r=Array(e.length+1);r[0]=0;for(let t=0;t<e.length;t++)r[t+1]=r[t]+n[e[t].kind];return r})(t,n),[t,n]),R=!!e.onMoveGroup,A=(0,i.useMemo)(()=>{let e={pinned:0,other:0};for(let n of t)"group"===n.kind&&e[n.project.pinned?"pinned":"other"]++;return e},[t]),L=function(e){let{rows:t,offsets:n,enabled:r}=e,s=(0,i.useRef)(e);s.current=e;let o=(0,i.useMemo)(()=>(function(e,t){let n=[],r=0;for(;r<e.length;){var i;let s=e[r];if("group"!==s.kind){r++;continue}let o=r;for(;o>0&&"spacer"===e[o-1].kind;)o--;let l=r+1;for(;l<e.length&&("group-more"===(i=e[l]).kind||"group-empty"===i.kind||"session"===i.kind&&"group"===i.context);)l++;let a=l;for(;a<e.length&&"spacer"===e[a].kind;)a++;n.push({key:s.project.key,pinned:s.project.pinned,top:t[r],bottom:t[l],gapAbove:t[r]-t[o],gapBelow:t[a]-t[l]}),r=l}return n})(t,n),[t,n]),l=(0,i.useRef)(o);l.current=o;let a=(0,i.useRef)(null),d=(0,i.useRef)(0),[c,u]=(0,i.useState)(null),p=(0,i.useMemo)(()=>{let e=e=>{u("armed"===e.phase||"dragging"===e.phase?{projectKey:e.projectKey,phase:e.phase,drop:e.drop}:null)},t=e=>{let t=s.current.innerRef.current;return t?function(e,t,n){let r=e.find(e=>e.key===t);if(!r)return null;let i=e.filter(e=>e.pinned===r.pinned),s=i.indexOf(r),o=i.filter(e=>e!==r);if(0===o.length)return null;let l=o.filter(e=>(e.top+e.bottom)/2<n).length;if(l===s)return null;let a=o[o.length-1],d=Math.max(3,l<o.length?o[l].top-o[l].gapAbove/2:a.bottom+a.gapBelow/2);return l>0?{anchorKey:o[l-1].key,position:"after",lineY:d}:{anchorKey:o[0].key,position:"before",lineY:d}}(l.current,e.projectKey,e.clientY-t.getBoundingClientRect().top):null},n=()=>{let e=a.current,t=s.current.ghostRef.current,n=s.current.treeRef.current,r=s.current.innerRef.current,i=s.current.scrollRef.current;if(!e?.ghost||!t||!n||!i)return;let o=n.getBoundingClientRect().top,l=i.getBoundingClientRect(),d=t.offsetHeight,c=function(e){let{pointerY:t,lineY:n,ghostHeight:r,pointerGap:i,lineGap:s,minTop:o,maxTop:l}=e,a=Math.max(o,l),d=t-i-r,c=null!==n&&n>=o&&n<=a+r?n:null,u=e=>e>=o&&e<=a,p=e=>null!==c&&e>c-s-r&&e<c+s,h=null===c?[d,o,t+i,a]:[d,c-s-r,o,t+i,c+s,a],f=e=>{let t=null;for(let n of h)e(n)&&(null===t||Math.abs(n-d)<Math.abs(t-d))&&(t=n);return t};return f(e=>u(e)&&!(e>d&&e<t+i)&&!p(e))??f(e=>u(e)&&!p(e))??Math.min(a,Math.max(o,d))}({pointerY:e.clientY,lineY:e.drop&&r?r.getBoundingClientRect().top+e.drop.lineY:null,ghostHeight:d,pointerGap:"mouse"===e.pointerType?8:28,lineGap:8,minTop:l.top,maxTop:l.bottom-d});t.style.top=`${c-o}px`,t.style.left=`${e.ghost.left}px`},r=e=>{null!==e.timer&&window.clearTimeout(e.timer),null!==e.frame&&cancelAnimationFrame(e.frame),e.timer=null,e.frame=null,s.current.scrollRef.current?.removeEventListener("scroll",p);try{e.element.hasPointerCapture(e.pointerId)&&e.element.releasePointerCapture(e.pointerId)}catch{}},i=()=>{let e=a.current;e&&(a.current=null,r(e),window.removeEventListener("pointermove",g,!0),window.removeEventListener("pointerup",x,!0),window.removeEventListener("pointercancel",v,!0),window.removeEventListener("pointerdown",b,!0),window.removeEventListener("keydown",y,!0),window.removeEventListener("contextmenu",w,!0),window.removeEventListener("blur",k),document.removeEventListener("visibilitychange",j),u(null))},o=()=>{let e=a.current;if(e){if("armed"!==e.phase&&"dragging"!==e.phase){"pending"===e.phase&&i();return}e.phase="cancelled",e.drop=null,r(e),u(null)}},c=function(){var r;let i=arguments.length>0&&void 0!==arguments[0]&&arguments[0],l=a.current;if(!l||"dragging"!==l.phase)return;let d=s.current.scrollRef.current;if(!d||!n$(d))return void o();let c=t(l),u=i||c!==(r=l.drop)&&(null===c||null===r||c.anchorKey!==r.anchorKey||c.position!==r.position||c.lineY!==r.lineY);l.drop=c,n(),u&&e(l)};function p(){c()}let h=()=>{let e=a.current;if(!e||"dragging"!==e.phase)return;e.frame=null;let t=s.current.scrollRef.current;if(!t||!n$(t))return void o();let n=t.getBoundingClientRect(),r=function(e,t,n,r){let i=Math.min(r,(n-t)/2);if(!(i>0)||!Number.isFinite(e))return 0;let s=e=>Math.ceil(14*Math.min(1,e/i));return e<t+i?-s(t+i-e):e>n-i?s(e-(n-i)):0}(e.clientY,n.top,n.bottom,nN[s.current.layout]);if(0!==r){let n=Math.min(Math.max(0,(s.current.offsets[s.current.offsets.length-1]??0)-t.clientHeight),Math.max(0,t.scrollTop+r));n!==t.scrollTop&&(t.scrollTop=n,e.expectedScrollTop=t.scrollTop,c())}a.current===e&&"dragging"===e.phase&&(e.frame=requestAnimationFrame(h))},f=e=>{let t=s.current.scrollRef.current,n=s.current.treeRef.current;if(!t||!n||!n$(t)||!e.element.isConnected)return void o();if(e.phase="dragging","touch"!==e.pointerType)try{e.element.setPointerCapture(e.pointerId)}catch{}e.ghost={left:e.element.getBoundingClientRect().left-n.getBoundingClientRect().left+4},e.expectedScrollTop=t.scrollTop,t.addEventListener("scroll",p,{passive:!0}),e.frame=requestAnimationFrame(h),c(!0)},m=()=>{let t=a.current;t&&"pending"===t.phase&&(t.timer=null,t.phase="armed",t.armX=t.clientX,t.armY=t.clientY,t.expectedScrollTop=s.current.scrollRef.current?.scrollTop??0,e(t))};function g(e){let t=a.current;if(!t||e.pointerId!==t.pointerId)return;if("mouse"===t.pointerType&&0===e.buttons)return void i();t.clientX=e.clientX,t.clientY=e.clientY;let n=nE(t.startX,t.startY,e.clientX,e.clientY);switch(t.phase){case"pending":"mouse"===t.pointerType?n>=4&&f(t):n>8&&i();break;case"armed":nE(t.armX,t.armY,e.clientX,e.clientY)>=4&&f(t);break;case"dragging":c()}}function x(e){let n=a.current;if(n&&e.pointerId===n.pointerId){if("dragging"===n.phase){n.clientX=e.clientX,n.clientY=e.clientY;let r=t(n);r&&s.current.onMove(n.projectKey,r.anchorKey,r.position)}"pending"!==n.phase&&(d.current=e.timeStamp+600),i()}}function v(e){a.current&&e.pointerId===a.current.pointerId&&i()}function b(e){a.current&&e.pointerId!==a.current.pointerId&&o()}function y(e){let t=a.current;t&&"Escape"===e.key&&("armed"===t.phase||"dragging"===t.phase)&&(e.preventDefault(),e.stopPropagation(),o())}function w(e){let t=a.current;if(t){if("pending"===t.phase)return void i();e.preventDefault(),e.stopPropagation()}}function k(){i()}function j(){"hidden"===document.visibilityState&&i()}return{handlers:{onPointerDown(e,t){if(!s.current.enabled||a.current||!e.isPrimary||0!==e.button||e.ctrlKey||e.target instanceof Element&&e.target.closest(".session-tree-group-actions"))return;let n=e.currentTarget,r={pointerId:e.pointerId,pointerType:e.pointerType,projectKey:t,element:n,startX:e.clientX,startY:e.clientY,armX:e.clientX,armY:e.clientY,clientX:e.clientX,clientY:e.clientY,phase:"pending",timer:null,frame:null,expectedScrollTop:0,drop:null,ghost:null};a.current=r,window.addEventListener("pointermove",g,!0),window.addEventListener("pointerup",x,!0),window.addEventListener("pointercancel",v,!0),window.addEventListener("pointerdown",b,!0),window.addEventListener("keydown",y,!0),window.addEventListener("contextmenu",w,!0),window.addEventListener("blur",k),document.addEventListener("visibilitychange",j),"mouse"!==e.pointerType&&(r.timer=window.setTimeout(m,350))},onTouchMove(e){let t=a.current;if(!t||"armed"!==t.phase&&"dragging"!==t.phase)return;if(e.cancelable)return void e.preventDefault();let n=s.current.scrollRef.current;n&&n.scrollTop!==t.expectedScrollTop&&i()}},cancel:o,teardown:i,updateDrag:c,placeGhost:n}},[]);(0,i.useLayoutEffect)(()=>{let e=a.current;e&&("armed"===e.phase||"dragging"===e.phase)&&(t.some(t=>"group"===t.kind&&t.project.key===e.projectKey)?p.updateDrag():p.cancel())},[t,n,p]),(0,i.useEffect)(()=>{r||p.cancel()},[r,p]);let h=c?.phase==="dragging";(0,i.useLayoutEffect)(()=>{h&&p.placeGhost()},[h,p]),(0,i.useEffect)(()=>()=>p.teardown(),[p]);let f=(0,i.useCallback)(e=>{let t=d.current;0===t||(d.current=0,e.timeStamp>t||(e.preventDefault(),e.stopPropagation()))},[]),m=(0,i.useCallback)(()=>{d.current=0},[]);return{view:(0,i.useMemo)(()=>{if(!c)return null;let e="dragging"===c.phase?o.find(e=>e.key===c.projectKey)??null:null;return{...c,source:e}},[c,o]),handlers:p.handlers,onClickCapture:f,onPointerDownCapture:m}}({rows:t,offsets:T,layout:n,enabled:R&&!o,scrollRef:g,innerRef:x,treeRef:m,ghostRef:v,onMove:(e,t,n)=>f.current.onMoveGroup?.(e,t,n)}),z=L.view,P=z?`group:${z.projectKey}`:null,[W,O]=(0,i.useState)(null),F=p&&p.id!==W?p:null,H=F?.rowKey??null,_=(0,i.useMemo)(()=>{let e=[];return t.forEach((t,n)=>{t.key===j||t.key===u||t.key===H||t.key===P||"session"===t.kind&&(t.family.root.id===a||t.family.root.id===c)?e.push(n):"group"===t.kind&&t.project.key===d&&e.push(n)}),e},[t,j,u,H,P,a,d,c]),U=(0,i.useMemo)(()=>o?[]:function(e,t,n,r){let i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:[],s=Math.max(0,e.length-1),o=Number.isFinite(t)?Math.max(0,t):0,l=Number.isFinite(n)&&n>0?n:600,a=Number.isFinite(r)&&r>0?r:0,d=o-a,c=o+l+a,u=0,p=s;for(;u<p;){let t=u+p>>>1;e[t+1]>d?p=t:u=t+1}let h=u;for(u=h,p=s;u<p;){let t=u+p>>>1;e[t]>=c?p=t:u=t+1}let f=u,m=[];for(let e=h;e<f;e++)m.push(e);if(0===i.length)return m;let g=i.filter(e=>Number.isInteger(e)&&e>=0&&e<s&&(e<h||e>=f));return 0===g.length?m:[...new Set([...m,...g])].sort((e,t)=>e-t)}(T,b,w,240,_),[o,T,b,w,_]),K=(0,i.useRef)(null),q=(0,i.useRef)(null),V=(0,i.useCallback)((e,t,n,r)=>{let i=document.activeElement===r,s=i&&r.matches(":focus-visible");K.current={rowKey:e,fallbackKey:t===B?"pinned-header":`group:${t}`,focus:i,scroll:"less"===n||s},"more"===n?f.current.onShowMore(t):f.current.onShowLess(t)},[]);(0,i.useLayoutEffect)(()=>{let e=K.current;if(!e)return;K.current=null;let n=g.current,r=t.findIndex(t=>t.key===e.rowKey);if(r<0&&(r=t.findIndex(t=>t.key===e.fallbackKey)),e.scroll&&n&&r>=0){let e=ed(T,r,n.scrollTop,n.clientHeight);null!==e&&(n.scrollTop=e),y(n.scrollTop)}e.focus&&(q.current={rowKey:e.rowKey,fallbackKey:e.fallbackKey,tries:0})},[t,T]);let Z=(0,i.useRef)(null);(0,i.useLayoutEffect)(()=>{if(!F)return;let e=t.findIndex(e=>e.key===F.rowKey),n=function(e,t,n,r){let i=e?.id===t.id?e:{id:t.id,misses:0};if(!(r-t.at<=3e3))return{misses:i,action:"drop"};if(n)return{misses:i,action:"reveal"};let s={id:t.id,misses:i.misses+1};return{misses:s,action:s.misses>=3?"drop":"wait"}}(Z.current,F,e>=0,Date.now());if(Z.current=n.misses,"wait"!==n.action){if("reveal"===n.action){let t=g.current;if(t&&t.getClientRects().length>0){let n=ed(T,e,t.scrollTop,t.clientHeight,F.block);null!==n&&(t.scrollTop=n),y(t.scrollTop)}F.takeFocusFrom&&(q.current={rowKey:F.rowKey,fallbackKey:F.rowKey,tries:0,takeFocusFrom:F.takeFocusFrom})}O(F.id),f.current.onRevealHandled?.(F.id)}},[F,t,T]),(0,i.useLayoutEffect)(()=>{let e=q.current;if(!e)return;let t=document.activeElement;if(t&&t!==document.body&&document.contains(t)&&!e.takeFocusFrom?.(t)){q.current=null;return}let n=g.current,r=e=>n?.querySelector(`[data-row-key="${CSS.escape(e)}"]`)??null,i=r(e.rowKey),s=i?.querySelector('[data-more-action="more"]')??i?.querySelector("a[href], button")??r(e.fallbackKey)?.querySelector("a[href], button");s?(s.focus({preventScroll:!0}),q.current=null):++e.tries>2&&(q.current=null)},[U]);let J=t.some(e=>"session"===e.kind||"group"===e.kind||"archive-group"===e.kind),Y=!o&&!l&&null!==s&&!J,G=z?.source??null,X=z?.drop?.lineY??null,Q=z?.phase==="dragging"?t.find(e=>"group"===e.kind&&e.project.key===z.projectKey)?.project??null:null;return(0,r.jsxs)("div",{ref:m,className:`session-tree${"mobile"===n?" is-mobile":""}${Q?" is-group-dragging":""}`,children:[o&&(0,r.jsx)("div",{className:"session-tree-message",children:h("sidebar.loading")}),l&&(0,r.jsx)("div",{className:"session-tree-message is-error",children:l}),Y&&(0,r.jsx)("div",{className:"session-tree-message",children:s}),(0,r.jsx)("div",{ref:g,className:"session-tree-scroll scrollbar-subtle",onScroll:$,onFocus:I,onBlur:M,onPointerDownCapture:L.onPointerDownCapture,onClickCapture:L.onClickCapture,children:!o&&(0,r.jsxs)("div",{ref:x,className:"session-tree-inner",style:{height:T[t.length]},children:[U.map(e=>{let i=t[e];if("spacer"===i.kind)return null;let s=T[e],o=T[e+1]-s,l=i.key===u;if("session"===i.kind)return(0,r.jsx)(n5,{row:i,layout:n,top:s,height:o,now:C,renaming:i.family.root.id===a,confirming:i.family.root.id===c,menuOpen:l,handlers:f},i.key);if("archive-group"===i.kind)return(0,r.jsx)(rn,{row:i,top:s,height:o,menuOpen:l,handlers:f},i.key);if("group"===i.kind){let e=i.project.key===d;return(0,r.jsx)(re,{row:i,top:s,height:o,menuOpen:l,renaming:e,canDrag:R&&!e&&A[i.project.pinned?"pinned":"other"]>1,dragPhase:z?.projectKey===i.project.key?z.phase:null,drag:L.handlers,handlers:f},i.key)}return(0,r.jsx)(rt,{row:i,top:s,height:o,handlers:f,onMoreAction:V},i.key)}),G&&(0,r.jsx)("div",{className:"session-tree-drag-source","aria-hidden":"true",style:{top:G.top,height:G.bottom-G.top}}),null!==X&&(0,r.jsx)("div",{className:"session-tree-drop-line","aria-hidden":"true",style:{top:X}})]})}),Q&&(0,r.jsx)("div",{ref:v,className:"session-tree-drag-ghost","aria-hidden":"true",children:(0,r.jsx)("span",{className:"session-tree-group-name",children:Q.name})})]})}function n3(e,t){return{top:e,height:t}}let n5=(0,i.memo)(function(e){let t,n,{row:i,layout:s,top:o,height:l,now:a,renaming:d,confirming:c,menuOpen:u,handlers:h}=e,{locale:f,t:m}=(0,tm.s)(),{family:g,context:x,status:v}=i,b=g.root,y=n2(b),w=new Date(a),k=["session-tree-row session-tree-session",v.selected?"is-selected":"",v.running?"is-running":"","archive"===x?"is-archived":"",u?"is-menu-open":"",c?"is-confirming":"",d?"is-renaming":""].filter(Boolean).join(" ");if(c){let e=y.slice(0,22)+(y.length>22?"…":"");return(0,r.jsx)("div",{className:k,style:n3(o,l),"data-row-key":i.key,onKeyDown:e=>{"Escape"!==e.key||n4(e)||(e.preventDefault(),e.stopPropagation(),h.current.onDeleteCancel())},children:(0,r.jsx)(n9,{label:m("sidebar.deleteSession",{title:e}),deleteLabel:m("sidebar.delete"),cancelLabel:m("sidebar.cancel"),onConfirm:e=>{e.stopPropagation(),h.current.onDeleteConfirm(g,e)},onCancel:e=>{e.stopPropagation(),h.current.onDeleteCancel()}})})}if(d)return(0,r.jsx)("div",{className:k,style:n3(o,l),"data-row-key":i.key,children:(0,r.jsx)(n6,{initialValue:y,label:m("sidebar.rename"),onCommit:e=>h.current.onRenameCommit(g,e),onCancel:()=>h.current.onRenameCancel()})});let j=b.isWorktree&&b.branch?b.branch:null,S=b.name&&b.relation?.kind==="fork"?eM(b.name):null,C=b.detailsPending?"…":m("sidebar.messagesCount",{count:b.messageCount}),N=`${y}
|
|
3
3
|
${C} \xb7 ${(0,nj.fw)(b.modified,f,w)}${j?` \xb7 ⑂ ${j}`:""}`,E="";v.awaiting?(t=(0,r.jsx)("span",{className:"session-tree-awaiting",role:"img","aria-label":m("sidebar.agentAwaitingInput")}),E=" is-awaiting",n=m("sidebar.agentAwaitingInput")):v.running?(t=(0,r.jsx)(n1,{size:12,label:m("sidebar.agentRunning")}),E=" is-running",n=m("sidebar.agentRunning")):v.unread?(t=(0,r.jsx)("span",{className:"session-tree-unread",role:"img","aria-label":m("sidebar.newSessionActivity")}),E=" is-unread",n=m("sidebar.newActivity")):t="pinned"===x?(0,r.jsx)("span",{className:"session-tree-project",children:i.project.name}):(0,nj.Rg)(g.latestModified,f,w);let $="desktop"===s&&("archive"===x||!v.running),I=(0,r.jsxs)(r.Fragment,{children:[S?(0,r.jsxs)("span",{className:"session-tree-title has-fork-suffix",children:[(0,r.jsx)("span",{className:"session-tree-title-base",children:S.base}),(0,r.jsx)("span",{className:"session-tree-title-suffix",children:S.suffix})]}):(0,r.jsx)("span",{className:"session-tree-title",children:y}),j&&(0,r.jsxs)("span",{className:"session-tree-branch",children:[(0,r.jsx)(nW,{size:10,className:"session-tree-branch-icon"}),j]}),(0,r.jsx)("span",{className:`session-tree-meta${E}`,title:n,children:t})]});return(0,r.jsxs)("div",{className:k,style:n3(o,l),"data-row-key":i.key,onClick:()=>h.current.onSelectFamily(g),onContextMenu:e=>h.current.onRowContextMenu(i,e),children:[v.transient?(0,r.jsx)("button",{type:"button",className:"session-tree-main",title:N,"aria-current":v.selected?"true":void 0,children:I}):(0,r.jsx)("a",{className:"session-tree-main",href:p(b.id),title:N,"aria-current":v.selected?"true":void 0,onClick:e=>{e.stopPropagation(),e.defaultPrevented||0!==e.button||e.ctrlKey||e.metaKey||e.shiftKey||e.altKey||(e.preventDefault(),h.current.onSelectFamily(g))},children:I}),!v.transient&&(0,r.jsxs)("span",{className:"session-tree-actions",children:[$&&("archive"===x?(0,r.jsx)("button",{type:"button",className:"session-tree-action session-tree-quick-action","aria-label":m("sidebar.restore"),title:m("sidebar.restore"),onClick:e=>{e.stopPropagation(),h.current.onRestoreFamily(g)},children:(0,r.jsx)(nA,{size:13})}):(0,r.jsx)("button",{type:"button",className:"session-tree-action session-tree-quick-action","aria-label":m("sidebar.archive"),title:m("sidebar.archive"),onClick:e=>{e.stopPropagation(),h.current.onArchiveFamily(g)},children:(0,r.jsx)(nR,{size:13})})),(0,r.jsx)("button",{type:"button",className:`session-tree-action session-tree-more-action${u?" is-active":""}`,"aria-label":m("sidebar.moreActions"),title:m("sidebar.moreActions"),"aria-haspopup":"menu","aria-expanded":u,onClick:e=>{let t;e.stopPropagation();let n=e.currentTarget;h.current.onOpenRowMenu(i,{kind:"rect",rect:{left:(t=n.getBoundingClientRect()).left,top:t.top,right:t.right,bottom:t.bottom},align:"end"},n)},children:(0,r.jsx)(nT,{size:14})})]})]})});function n6(e){let{initialValue:t,label:n,maxLength:s,onCommit:o,onCancel:l}=e,[a,d]=(0,i.useState)(t),c=(0,i.useRef)(null),u=(0,i.useRef)(!1);(0,i.useEffect)(()=>{let e=c.current;e&&(e.focus(),e.select())},[]);let p=e=>{u.current||(u.current=!0,o(e))};return(0,r.jsx)("input",{ref:c,className:"session-tree-rename",value:a,"aria-label":n,maxLength:s,onChange:e=>d(e.target.value),onBlur:e=>p(e.currentTarget.value),onKeyDown:e=>{if(!n4(e)){if("Enter"===e.key)e.preventDefault(),p(e.currentTarget.value);else if("Escape"===e.key){if(e.preventDefault(),e.stopPropagation(),u.current)return;u.current=!0,l()}}}})}function n9(e){let{label:t,deleteLabel:n,cancelLabel:s,onConfirm:o,onCancel:l}=e,a=(0,i.useRef)(null);return(0,i.useEffect)(()=>{let e=document.activeElement;e&&e!==document.body||a.current?.focus()},[]),(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{className:"session-tree-confirm-text",children:t}),(0,r.jsxs)("button",{type:"button",className:"session-tree-confirm-delete",onClick:o,children:[(0,r.jsx)(nD,{size:12}),n]}),(0,r.jsx)("button",{ref:a,type:"button",className:"session-tree-confirm-cancel",onClick:l,children:s})]})}function n7(e){let{running:t,awaiting:n=0,unread:i,t:s}=e;return 0===t&&0===n&&0===i?null:(0,r.jsxs)("span",{className:"session-tree-summary",children:[t>0&&(0,r.jsxs)("span",{className:"session-tree-summary-running",role:"img",title:s("sidebar.agentRunning"),"aria-label":`${s("sidebar.agentRunning")} (${t})`,children:[(0,r.jsx)(n1,{size:10}),t]}),n>0&&(0,r.jsxs)("span",{className:"session-tree-summary-awaiting",role:"img",title:s("sidebar.agentAwaitingInput"),"aria-label":`${s("sidebar.agentAwaitingInput")} (${n})`,children:[(0,r.jsx)("span",{className:"session-tree-summary-dot is-awaiting"}),n]}),i>0&&(0,r.jsxs)("span",{className:"session-tree-summary-unread",role:"img",title:s("sidebar.newSessionActivity"),"aria-label":`${s("sidebar.newSessionActivity")} (${i})`,children:[(0,r.jsx)("span",{className:"session-tree-summary-dot"}),i]})]})}let re=(0,i.memo)(function(e){let{row:t,top:n,height:s,menuOpen:o,renaming:l,canDrag:a,dragPhase:d,drag:c,handlers:u}=e,{t:p}=(0,tm.s)(),{project:h,expanded:f}=t,m=(0,i.useRef)(null),g=["session-tree-row session-tree-group",h.current?"is-current":"",o?"is-active":"","armed"===d?"is-drag-armed":""].filter(Boolean).join(" ");return((0,i.useEffect)(()=>{let e=m.current;if(!a||!e)return;let t=e=>c.onTouchMove(e);return e.addEventListener("touchmove",t,{passive:!1}),()=>e.removeEventListener("touchmove",t)},[a,c]),l)?(0,r.jsx)("div",{ref:m,className:`${g} is-renaming`,style:n3(n,s),"data-row-key":t.key,children:(0,r.jsx)(n6,{initialValue:h.name,label:p("sidebar.projectName"),maxLength:80,onCommit:e=>u.current.onRenameProjectCommit(h,e),onCancel:()=>u.current.onRenameProjectCancel()})}):(0,r.jsxs)("div",{ref:m,className:g,style:n3(n,s),"data-row-key":t.key,onPointerDown:a?e=>c.onPointerDown(e,h.key):void 0,children:[(0,r.jsxs)("button",{type:"button",className:"session-tree-group-toggle","aria-expanded":f,title:h.root,onClick:e=>u.current.onToggleGroup(h.key,e.altKey),children:[(0,r.jsx)(nP,{size:12,strokeWidth:3,className:`session-tree-chevron${f?" is-open":""}`}),(0,r.jsx)("span",{className:"session-tree-group-name",children:h.name}),h.pinned&&(0,r.jsx)(nL,{size:10,className:"session-tree-group-pin",label:p("sidebar.pinnedProject")}),!f&&(0,r.jsx)(n7,{running:t.running,awaiting:t.awaiting,unread:t.unread,t:p})]}),(0,r.jsxs)("span",{className:"session-tree-group-actions",children:[(0,r.jsx)("button",{type:"button",className:"session-tree-group-action","aria-label":p("sidebar.newSessionInProject",{name:h.name}),title:p("sidebar.newSessionInProject",{name:h.name}),onClick:e=>{e.stopPropagation(),u.current.onGroupNew(h)},children:(0,r.jsx)(nM,{size:13})}),(0,r.jsx)("button",{type:"button",className:`session-tree-group-action${o?" is-active":""}`,"aria-label":p("sidebar.projectActions",{name:h.name}),title:p("sidebar.projectActions",{name:h.name}),"aria-haspopup":"menu","aria-expanded":o,onClick:e=>{e.stopPropagation(),u.current.onGroupMenu(h,e.currentTarget)},children:(0,r.jsx)(nT,{size:13})})]})]})}),rt=(0,i.memo)(function(e){let{row:t,top:n,height:i,handlers:s,onMoreAction:o}=e,{t:l}=(0,tm.s)(),a=n3(n,i);switch(t.kind){case"pinned-header":return(0,r.jsx)("div",{className:"session-tree-row session-tree-pinned-header",style:a,"data-row-key":t.key,children:(0,r.jsxs)("button",{type:"button",className:"session-tree-pinned-toggle","aria-expanded":!t.collapsed,onClick:()=>s.current.onTogglePinned(),children:[(0,r.jsx)(nP,{size:12,strokeWidth:3,className:`session-tree-chevron${t.collapsed?"":" is-open"}`}),(0,r.jsx)("span",{className:"session-tree-pinned-label",children:l("sidebar.pinned")}),(0,r.jsxs)("span",{className:"session-tree-pinned-count",children:["\xb7 ",t.count]}),t.collapsed&&t.running>0&&(0,r.jsx)("span",{className:"session-tree-pinned-dot is-running",role:"img",title:l("sidebar.agentRunning"),"aria-label":`${l("sidebar.agentRunning")} (${t.running})`}),t.collapsed&&t.awaiting>0&&(0,r.jsx)("span",{className:"session-tree-pinned-dot is-awaiting",role:"img",title:l("sidebar.agentAwaitingInput"),"aria-label":`${l("sidebar.agentAwaitingInput")} (${t.awaiting})`}),t.collapsed&&t.unread>0&&(0,r.jsx)("span",{className:"session-tree-pinned-dot is-unread",role:"img",title:l("sidebar.newSessionActivity"),"aria-label":`${l("sidebar.newSessionActivity")} (${t.unread})`})]})});case"pinned-more":case"group-more":{let e="pinned-more"===t.kind?B:t.projectKey;return(0,r.jsxs)("div",{className:"session-tree-row session-tree-more",style:a,"data-row-key":t.key,children:[t.hidden>0&&(0,r.jsx)("button",{type:"button",className:"session-tree-more-toggle","data-more-action":"more",onClick:n=>o(t.key,e,"more",n.currentTarget),children:l("sidebar.showMore",{count:t.hidden})}),t.canShowLess&&(0,r.jsx)("button",{type:"button",className:"session-tree-more-toggle","data-more-action":"less",onClick:n=>o(t.key,e,"less",n.currentTarget),children:l("sidebar.showLess")})]})}case"group-empty":return(0,r.jsxs)("div",{className:"session-tree-row session-tree-group-empty",style:a,"data-row-key":t.key,children:[(0,r.jsx)("span",{className:"session-tree-group-empty-label",children:l("sidebar.noLiveSessions")}),!t.project.pinned&&(0,r.jsx)("button",{type:"button",className:"session-tree-more-toggle",onClick:()=>s.current.onPinEmptyGroup(t.project),children:l("sidebar.pinToKeep")})]});case"footer-open":return(0,r.jsx)("div",{className:"session-tree-row session-tree-footer",style:a,"data-row-key":t.key,children:(0,r.jsxs)("button",{type:"button",className:"session-tree-footer-button",onClick:e=>s.current.onOpenOtherProject(e.currentTarget),children:[(0,r.jsx)(nV,{size:12}),(0,r.jsx)("span",{className:"session-tree-footer-label",children:l("sidebar.openOtherProject")})]})});case"footer-archived":return(0,r.jsx)("div",{className:"session-tree-row session-tree-footer",style:a,"data-row-key":t.key,children:(0,r.jsxs)("button",{type:"button",className:"session-tree-footer-button",onClick:()=>s.current.onOpenArchive(),children:[(0,r.jsx)(nR,{size:12}),(0,r.jsx)("span",{className:"session-tree-footer-label",children:l("sidebar.archivedCount",{count:t.count})}),(0,r.jsx)(nP,{size:10,className:"session-tree-footer-chevron"})]})})}}),rn=(0,i.memo)(function(e){let{row:t,top:n,height:i,menuOpen:s,handlers:o}=e,{t:l}=(0,tm.s)(),{project:a,expanded:d}=t,c=["session-tree-row session-tree-group session-tree-archive-group",a.current?"is-current":"",s?"is-active":""].filter(Boolean).join(" ");return(0,r.jsxs)("div",{className:c,style:n3(n,i),"data-row-key":t.key,children:[(0,r.jsxs)("button",{type:"button",className:"session-tree-group-toggle","aria-expanded":d,title:a.root,onClick:e=>o.current.onToggleArchiveGroup?.(a.key,e.altKey),children:[(0,r.jsx)(nP,{size:12,strokeWidth:3,className:`session-tree-chevron${d?" is-open":""}`}),(0,r.jsx)("span",{className:"session-tree-group-name",children:a.name}),(0,r.jsxs)("span",{className:"session-tree-archive-group-count",children:["\xb7 ",t.count]})]}),(0,r.jsx)("span",{className:"session-tree-group-actions",children:(0,r.jsx)("button",{type:"button",className:`session-tree-group-action${s?" is-active":""}`,"aria-label":l("sidebar.archivedProjectActions",{name:a.name}),title:l("sidebar.archivedProjectActions",{name:a.name}),"aria-haspopup":"menu","aria-expanded":s,onClick:e=>{e.stopPropagation(),o.current.onArchiveGroupMenu?.(a,e.currentTarget)},children:(0,r.jsx)(nT,{size:13})})})]})}),rr="[data-sidebar-menu-filter]",ri="[data-sidebar-menu-autofocus]",rs="button, input, textarea, select, a[href], [tabindex]";function ro(e){return i.Children.toArray(e).length>0}function rl(e){return"item"===e.type&&void 0!==e.checked}function ra(e){return e.getClientRects().length>0}function rd(e){return!e.disabled&&"true"!==e.getAttribute("aria-disabled")&&ra(e)}function rc(e){return Array.from(e.querySelectorAll("[data-sidebar-menu-item]")).filter(rd)}function ru(e){let t=Array.from(e.querySelectorAll(ri)).find(rd);if(t)return t;let n=rc(e);return n.length>0?n[0]:Array.from(e.querySelectorAll(rs)).filter(e=>e.tabIndex>=0&&rd(e))[0]??null}function rp(e){e.stopPropagation()}let rh={onClick:rp,onDoubleClick:rp,onMouseDown:rp,onMouseUp:rp,onPointerDown:rp,onPointerUp:rp,onKeyDown:rp,onKeyUp:rp,onFocus:rp,onBlur:rp,onContextMenu:function(e){e.preventDefault(),e.stopPropagation()}};function rf(e,t){return n=>{"Enter"!==n.key||n.nativeEvent.isComposing||229===n.keyCode||(n.preventDefault(),t(e,n.shiftKey))}}function rm(e){let{item:t,onActivate:n}=e,i=void 0!==t.checked,s=["sidebar-menu-item",i?"is-choice":"",t.danger?"is-danger":"",t.checked?"is-checked":""].filter(Boolean).join(" "),o=["sidebar-menu-label",t.mono?"is-mono":"",t.path?"is-path":""].filter(Boolean).join(" "),l=null;t.disabled&&t.disabledReason?l=(0,r.jsx)("span",{className:"sidebar-menu-note",children:t.disabledReason}):t.note?l=(0,r.jsx)("span",{className:"sidebar-menu-note",children:t.note}):t.shortcut&&(l=(0,r.jsx)("kbd",{className:"sidebar-menu-shortcut",children:t.shortcut}));let a=(0,r.jsxs)("button",{type:"button",role:i?"menuitemradio":"menuitem","aria-checked":i?t.checked:void 0,"aria-disabled":!!t.disabled||void 0,"aria-keyshortcuts":t.shortcut&&!t.disabled?t.shortcut.toUpperCase():void 0,tabIndex:-1,title:t.title,"data-sidebar-menu-item":"",className:s,onClick:e=>n(t,e.shiftKey),onKeyDown:rf(t,n),children:[(0,r.jsx)("span",{className:"sidebar-menu-icon",children:i?t.checked?(0,r.jsx)(nU,{size:13}):null:t.icon}),(0,r.jsx)("span",{className:o,children:t.path?(0,r.jsx)("span",{children:t.label}):t.label}),t.badge,l]}),d=t.secondary;return d?(0,r.jsxs)("div",{className:i?"sidebar-menu-row is-choice":"sidebar-menu-row",role:"none",children:[a,(0,r.jsx)("button",{type:"button",role:"menuitem","aria-label":d.label,"aria-disabled":!!d.disabled||void 0,tabIndex:-1,title:d.label,"data-sidebar-menu-item":"",className:d.danger?"sidebar-menu-secondary is-danger":"sidebar-menu-secondary",onClick:e=>n(d,e.shiftKey),onKeyDown:rf(d,n),children:d.icon})]}):a}function rg(e){var t;let n,{sheet:i,ariaLabel:s,title:o,items:l,filter:a,filterQuery:d="",onFilterQueryChange:c,children:u,cancelLabel:p,focusCancel:h=!1,width:f=208,classic:m=!1,footer:g,surfaceRef:x,onActivate:v,onClose:b}=e,y=ro(u),w=!y&&ro(g),k=void 0!==a&&!y&&function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:8;return(e??[]).filter(rl).length>=t}(l,a.minChoices),j=k?(t=l??[],(n=d.trim().toLowerCase())?t.filter(e=>"item"!==e.type||void 0===e.checked||[e.label,e.note,e.title].some(e=>e?.toLowerCase().includes(n))):[...t]):l??[],S=j.map(e=>"separator"===e.type?(0,r.jsx)("div",{className:"sidebar-menu-separator",role:"separator"},e.id):"header"===e.type?(0,r.jsx)("div",{className:"sidebar-menu-header",role:"presentation",children:e.label},e.id):"custom"===e.type?(0,r.jsx)("div",{className:"sidebar-menu-custom",role:"none",children:e.content},e.id):(0,r.jsx)(rm,{item:e,onActivate:v},e.id)),C=y?u:k||w?(0,r.jsxs)(r.Fragment,{children:[k&&(0,r.jsx)("div",{className:"sidebar-menu-filter",children:(0,r.jsx)("input",{className:"sidebar-menu-filter-input",value:d,placeholder:a.placeholder,"aria-label":a.placeholder,autoComplete:"off",spellCheck:!1,"data-sidebar-menu-filter":"","data-sidebar-menu-autofocus":i?void 0:"",onChange:e=>c?.(e.target.value)})}),k&&(0,r.jsx)("div",{role:"status",children:d.trim()&&!j.some(rl)&&(0,r.jsx)("div",{className:"sidebar-menu-empty",children:a.emptyLabel})}),(0,r.jsx)("div",{role:"menu","aria-label":s,children:S}),w&&g]}):S,N=y||k||w?void 0:"menu";return i?(0,r.jsxs)("div",{className:"sidebar-sheet-layer",...rh,children:[(0,r.jsx)("div",{className:"sidebar-sheet-backdrop","aria-hidden":"true",onClick:()=>b("outside")}),(0,r.jsxs)("div",{ref:x,className:"sidebar-sheet",role:"dialog","aria-modal":"true","aria-label":s,children:[o?(0,r.jsx)("div",{className:"sidebar-sheet-title",children:o}):null,(0,r.jsx)("div",{className:"sidebar-sheet-body",role:N,"aria-label":N?s:void 0,children:C}),(0,r.jsx)("button",{type:"button",className:"sidebar-sheet-cancel","data-sidebar-menu-autofocus":h?"":void 0,onClick:()=>b("cancel"),children:p})]})]}):(0,r.jsx)("div",{ref:x,className:m?"sidebar-menu is-classic":"sidebar-menu",role:N??"dialog","aria-label":s,style:{width:f},...rh,children:C})}function rx(e){let{open:t,anchor:n,sheet:s,ariaLabel:o,title:l,items:a,filter:d,children:c,cancelLabel:u,focusCancel:p,onClose:h,returnFocusTo:f,width:m,classic:g=!1,footer:x,focusKey:v=""}=e,[b,y]=(0,i.useState)(null),[w,k]=(0,i.useState)(""),j=(0,i.useRef)(w);j.current=w;let S=(0,i.useRef)(null),C=(0,i.useRef)(h);C.current=h;let N=(0,i.useRef)(a);N.current=a;let E=(0,i.useRef)(f??null);E.current=f??null;let $=(0,i.useRef)(n);$.current=n,(0,i.useEffect)(()=>{y(document.body)},[]);let I=t&&null!==b&&(s||null!==n),M=ro(c),T=n?JSON.stringify(n):"",R=(e,t)=>{if(e.disabled)return;let n=!1;e.onSelect({shiftKey:t,keepOpen:()=>{n=!0}}),n||C.current("select")},A=(0,i.useRef)(R);A.current=R,(0,i.useLayoutEffect)(()=>{let e=S.current;if(!I||s||!e)return;let t=window.visualViewport,n=()=>{let n=$.current;if(!n)return;let r=e.getBoundingClientRect(),{left:i,top:s}=function(e,t,n){let r,i,s=arguments.length>3&&void 0!==arguments[3]?arguments[3]:8,o=n.left+s,l=n.top+s,a=n.left+n.width-s,d=n.top+n.height-s;if("point"===e.kind)r=e.x+t.width>a&&e.x-t.width>=o?e.x-t.width:e.x,i=e.y+t.height>d&&e.y-t.height>=l?e.y-t.height:e.y;else{let{rect:n}=e;r="end"===e.align?n.right-t.width:n.left;let s=n.bottom+4,o=n.top-4-t.height;i=s+t.height>d&&o>=l?o:s}return{left:Math.max(o,Math.min(r,a-t.width)),top:Math.max(l,Math.min(i,d-t.height))}}(n,{width:r.width,height:r.height},{left:t?.offsetLeft??0,top:t?.offsetTop??0,width:t?.width??window.innerWidth,height:t?.height??window.innerHeight});e.style.left=`${i}px`,e.style.top=`${s}px`};n();let r="u"<typeof ResizeObserver?null:new ResizeObserver(n);return r?.observe(e),window.addEventListener("resize",n),t?.addEventListener("resize",n),t?.addEventListener("scroll",n),()=>{r?.disconnect(),window.removeEventListener("resize",n),t?.removeEventListener("resize",n),t?.removeEventListener("scroll",n)}},[I,s,T,M]),(0,i.useEffect)(()=>{k("")},[I,M]);let L=(0,i.useRef)(!1);return((0,i.useLayoutEffect)(()=>{let e=S.current;if(!I||!e){L.current=!1;return}let t=!L.current;L.current=!0,(t?ru(e):Array.from(e.querySelectorAll(ri)).filter(e=>!e.matches(rr)&&rd(e))[0]??ru(e))?.focus({preventScroll:!0})},[I,s,M,v]),(0,i.useLayoutEffect)(()=>{let e=S.current;if(!I||!e)return;let t=E.current;return()=>{let n=document.activeElement;if(n&&n!==document.body&&!e.contains(n))return;let r=function(e){if(!e||!e.isConnected)return null;if(ra(e))return e;let t=e.closest("[data-row-key]");if(!t)return null;for(let e of Array.from(t.querySelectorAll(rs)))if(e.tabIndex>=0&&rd(e))return e;return null}(t);r&&(r.focus({preventScroll:!0}),t&&r!==t&&ra(t)&&t.focus({preventScroll:!0}))}},[I,s]),(0,i.useEffect)(()=>{if(!I)return;let e=e=>{let t=S.current;if(!t||e.isComposing||229===e.keyCode)return;if("Escape"===e.key){e.preventDefault(),e.stopPropagation();let n=t.querySelector(rr);if(n&&j.current){k(""),n.focus({preventScroll:!0});return}C.current("escape");return}let n=e.target instanceof Element?e.target:null,r=null!==n&&t.contains(n),i=null===n||n===document.body||n===document.documentElement;if(!r&&!i)return;if("Tab"===e.key){var s;let i,o;r&&(s=e.shiftKey,i=Array.from(t.querySelectorAll(rs)).filter(e=>e!==n&&e.tabIndex>=0&&rd(e)),o=s?Node.DOCUMENT_POSITION_PRECEDING:Node.DOCUMENT_POSITION_FOLLOWING,i.some(e=>(n.compareDocumentPosition(e)&o)!=0))||C.current("outside");return}let o=("ArrowDown"===e.key||"ArrowUp"===e.key)&&n?.matches(rr);if(r&&function(e){if(!e)return!1;if(e.isContentEditable)return!0;let t=e.tagName;return"TEXTAREA"===t||"SELECT"===t||"INPUT"===t&&!["button","checkbox","radio","range","reset","submit","image","color","file"].includes((e.type||"text").toLowerCase())}(n)&&!o)return;if("ArrowDown"===e.key||"ArrowUp"===e.key||"Home"===e.key||"End"===e.key){let r,i=rc(t);if(0===i.length)return;e.preventDefault(),e.stopPropagation();let s=n?i.indexOf(n):-1;r="Home"===e.key?0:"End"===e.key?i.length-1:"ArrowDown"===e.key?s<0?0:(s+1)%i.length:s<0?i.length-1:(s-1+i.length)%i.length,i[r].focus({preventScroll:!1});return}if(1!==e.key.length||e.ctrlKey||e.metaKey||e.altKey)return;let l=function(e,t){if(!e||1!==t.length)return null;let n=t.toLowerCase();for(let t of e)if("item"===t.type&&!t.disabled&&t.shortcut&&t.shortcut.toLowerCase()===n)return t;return null}(N.current,e.key);l&&!M&&(e.preventDefault(),e.stopPropagation(),A.current(l,e.shiftKey))};return document.addEventListener("keydown",e,!0),()=>document.removeEventListener("keydown",e,!0)},[I,M]),(0,i.useEffect)(()=>{if(!I||s)return;let e=e=>{let t=S.current,n=e.target instanceof Node?e.target:null;if(!t||n&&t.contains(n))return;let r=E.current;r&&n&&0===e.button&&r.contains(n)&&function(e){let t=e.ownerDocument,n=t.defaultView;if(!n)return;let r=0,i=()=>{t.removeEventListener("click",s,!0),n.clearTimeout(r)};function s(t){i(),t.target instanceof Node&&e.contains(t.target)&&(t.preventDefault(),t.stopPropagation())}t.addEventListener("click",s,!0),r=n.setTimeout(i,1e3)}(r),C.current("outside")};return document.addEventListener("pointerdown",e,!0),()=>document.removeEventListener("pointerdown",e,!0)},[I,s]),I&&b)?(0,tz.createPortal)((0,r.jsx)(rg,{sheet:s,ariaLabel:o,title:l,items:a,filter:d,filterQuery:w,onFilterQueryChange:k,cancelLabel:u,focusCancel:p,width:m,classic:g,footer:x,surfaceRef:S,onActivate:(e,t)=>A.current(e,t),onClose:e=>C.current(e),children:c}),b):null}function rv(e){let{heading:t,busy:n,error:s,showCancel:o,onCreate:l,onCancel:a}=e,{t:d}=(0,tm.s)(),[c,u]=(0,i.useState)(""),p=c.trim(),h=()=>{p&&!n&&l(p)};return(0,r.jsxs)("div",{className:"sidebar-worktree-form",children:[t&&(0,r.jsx)("div",{className:"sidebar-menu-header",children:t}),(0,r.jsx)("input",{className:"sidebar-worktree-input","data-sidebar-menu-autofocus":"",value:c,readOnly:n,placeholder:d("sidebar.branchName"),"aria-label":d("sidebar.branchName"),onChange:e=>u(e.target.value),onKeyDown:e=>{"Enter"!==e.key||e.nativeEvent.isComposing||229===e.keyCode||(e.preventDefault(),h())}}),(0,r.jsxs)("div",{className:"sidebar-worktree-form-buttons",children:[(0,r.jsx)("button",{type:"button",className:"sidebar-worktree-create",disabled:n||!p,onClick:h,children:d(n?"sidebar.creating":"sidebar.create")}),o&&(0,r.jsx)("button",{type:"button",className:"sidebar-worktree-cancel",onClick:a,children:d("sidebar.cancel")})]}),s&&(0,r.jsx)("div",{className:"sidebar-worktree-error",role:"alert",children:s})]})}function rb(e,t){return t&&e.startsWith(t)?`~${e.slice(t.length)}`:e}function ry(e){return e.branch??J(e.path)}function rw(e){let{heading:t,dirty:n,busy:i,error:s,showCancel:o,onForce:l,onCancel:a}=e,{t:d}=(0,tm.s)();return(0,r.jsxs)("div",{className:"sidebar-worktree-form",children:[t&&(0,r.jsx)("div",{className:"sidebar-menu-header",children:t}),n&&(0,r.jsx)("div",{className:"sidebar-worktree-message",children:d("sidebar.forceRemoveCheckout")}),(n||o)&&(0,r.jsxs)("div",{className:"sidebar-worktree-form-buttons",children:[n&&(0,r.jsx)("button",{type:"button",className:"sidebar-worktree-force",disabled:i,onClick:l,children:d("sidebar.force")}),o&&(0,r.jsx)("button",{type:"button",className:"sidebar-worktree-cancel","data-sidebar-menu-autofocus":"",onClick:a,children:d("sidebar.cancel")})]}),s&&(0,r.jsx)("div",{className:"sidebar-worktree-error",role:"alert",children:s})]})}function rk(e){let{busy:t,onForce:n,onCancel:s}=e,{t:o}=(0,tm.s)(),l=(0,i.useId)();return(0,r.jsxs)("div",{className:"sidebar-worktree-confirm",children:[(0,r.jsx)("span",{id:l,className:"sidebar-worktree-confirm-text",title:o("sidebar.forceRemoveCheckout"),children:o("sidebar.forceRemoveCheckout")}),(0,r.jsx)("button",{type:"button",role:"menuitem",tabIndex:-1,"data-sidebar-menu-item":"","aria-describedby":l,"aria-disabled":!!t||void 0,className:"sidebar-worktree-force",onClick:()=>{t||n()},children:o("sidebar.force")}),(0,r.jsx)("button",{type:"button",role:"menuitem",tabIndex:-1,"data-sidebar-menu-item":"","data-sidebar-menu-autofocus":"",className:"sidebar-worktree-cancel",onClick:s,children:o("sidebar.cancel")})]})}function rj(e){let t,n,{layout:s,context:o,mobile:l,label:a,placeholder:d="",homeDir:c,projectActivity:u,worktreeHint:p=null,newWorktreeTitle:h,handleRef:f,onPick:m,onUseDefaultDirectory:g,onOpenFolder:x,onRefreshWorktrees:v,onCreateWorktree:b,onRemoveWorktree:y}=e,{t:w}=(0,tm.s)(),[k,j]=(0,i.useState)(null),S=(0,i.useRef)(k);S.current=k;let C=(0,i.useRef)(0),N=(0,i.useRef)(null),E=(0,i.useRef)(null),$=(0,i.useRef)(!1),I=(0,i.useRef)(m);I.current=m;let M="inline"!==s,T=!M,R=!l,{project:A,worktrees:L}=o,z=(t=o.worktrees??[]).find(e=>e.path===o.currentWorktreePath)??t.find(e=>e.isMain)??null,P=T&&A?eL(eR(o)).find(e=>{let{choice:t}=e;return t.key===A.key}):void 0;(0,i.useEffect)(()=>($.current=!0,()=>{$.current=!1}),[]);let W=()=>(C.current+=1,C.current),O=()=>j(null),F=(e,t)=>{let n=t.getBoundingClientRect(),r=Math.max(M?220:"project"===e?260:240,Math.round(n.width));j({id:W(),kind:e,anchor:{kind:"rect",rect:{left:n.left,top:n.top,right:n.right,bottom:n.bottom},align:"row"===s&&"worktree"===e?"end":"start"},opener:t,width:r,body:null,removing:!1}),"worktree"===e&&v()},D=(0,i.useRef)(F);D.current=F,(0,i.useImperativeHandle)(f,()=>({button:e=>("worktree"===e?E:N).current,openMenu:e=>{let t=("worktree"===e?E:N).current;t&&D.current(e,t)}}),[]);let B=(e,t)=>{j(n=>n?.id===e?t(n):n)},H=e=>{let t=W();j(n=>n?.kind==="worktree"?{...n,id:t,body:e,removing:!1}:n)},_=async e=>{let t,n=S.current;if(!n||n.body?.kind!=="create"||!A)return;let{id:r}=n,i=(e,t)=>{B(r,n=>({...n,body:{kind:"create",busy:e,error:t}}))};i(!0,null);try{t=await b(A,e)}catch(e){t={error:e instanceof Error?e.message:String(e)}}$.current&&("error"in t?i(!1,t.error):S.current?.id===r&&(j(null),I.current({cwd:t.path,projectKey:A.key,projectRoot:A.root},"worktree")))},U=async(e,t)=>{let n,r=S.current;if(!r||!A||!y)return;let{id:i}=r;B(i,e=>({...e,removing:!0,body:e.body?.kind==="remove"?{...e.body,busy:!0,error:null}:e.body}));try{n=await y(A,e.path,t)}catch(e){n={error:e instanceof Error?e.message:String(e)}}$.current&&B(i,t=>{if("removed"===n)return{...t,removing:!1,body:null};let r="dirty"===n||t.body?.kind==="remove"&&t.body.dirty;return{...t,removing:!1,body:{kind:"remove",worktree:e,dirty:r,busy:!1,error:"dirty"===n?null:n.error}}})},K=()=>[...(L??[]).map(e=>R&&q?.kind==="remove"&&q.dirty&&q.worktree.path===e.path?{type:"custom",id:`worktree:${e.path}`,content:(0,r.jsx)(rk,{busy:q.busy,onForce:()=>{U(e,!0)},onCancel:()=>H(null)})}:{type:"item",id:`worktree:${e.path}`,label:R?e.branch??rb(e.path,c):ry(e),mono:R,path:R,note:e.isMain?w("sidebar.main"):void 0,title:e.path,checked:e.path===z?.path,secondary:y&&!e.isMain?{label:w("sidebar.removeWorktreeTitle",{path:e.path}),icon:(0,r.jsx)(nD,{size:12}),danger:!0,disabled:k?.removing,onSelect:t=>{let{keepOpen:n}=t;n(),U(e,!1)}}:void 0,onSelect:()=>{A&&e.path!==z?.path&&m({cwd:e.path,projectKey:A.key,projectRoot:A.root},"worktree")}}),...R?[]:[{type:"separator",id:"separator"}],...R&&q?.kind==="create"?[]:[{type:"item",id:"new-worktree",label:w("sidebar.newWorktree"),icon:(0,r.jsx)(nM,{size:13}),onSelect:e=>{let{keepOpen:t}=e;t(),H({kind:"create",busy:!1,error:null})}}]],q=k?.kind==="worktree"?k.body:null,V="",Z=null,Y=null;if(R&&k?.kind==="worktree")V=w("sidebar.switchWorktree"),n=K(),q?.kind==="create"?Y=(0,r.jsx)(rv,{heading:null,busy:q.busy,error:q.error,showCancel:!0,onCreate:e=>{_(e)},onCancel:()=>H(null)}):q?.kind==="remove"&&q.error&&(Y=(0,r.jsx)("div",{className:"sidebar-worktree-error",role:"alert",children:q.error}));else if(q?.kind==="create")V=h,Z=(0,r.jsx)(rv,{heading:l?null:V,busy:q.busy,error:q.error,showCancel:!l,onCreate:e=>{_(e)},onCancel:O});else if(q?.kind==="remove")V=w("sidebar.removeWorktreeHeading",{name:ry(q.worktree)}),Z=(0,r.jsx)(rw,{heading:l?null:V,dirty:q.dirty,busy:q.busy,error:q.error,showCancel:!l,onForce:()=>{U(q.worktree,!0)},onCancel:O});else if(k?.kind==="project"){let e,t;V=w("workspace.project"),t=(e=eL(eR(o)).map(e=>{let{choice:t,name:n,note:i}=e,s=u?.get(t.key),o=R&&void 0===t.alias;return{type:"item",id:`project:${t.key}`,label:o?rb(t.root,c):n,note:o?void 0:i??void 0,mono:R,path:o,title:t.root,checked:t.key===A?.key,badge:s?(0,r.jsx)(n7,{running:s.running,unread:s.unread,t:w}):void 0,onSelect:()=>{t.key===A?.key&&L||m({cwd:t.root,projectKey:t.key,projectRoot:t.root},"project")}}})).length>0?[{type:"separator",id:"separator"}]:[],n=[...e,...t,{type:"item",id:"default-directory",label:w("sidebar.useDefaultDirectory"),icon:(0,r.jsx)(nq,{size:13}),onSelect:()=>g()},{type:"item",id:"open-folder",label:w(R?"sidebar.customPath":"sidebar.openOtherProject"),icon:R?(0,r.jsx)(nM,{size:13}):(0,r.jsx)(nV,{size:13}),onSelect:()=>x(k?.opener??null)}]}else k?.kind==="worktree"&&(V=w("sidebar.switchWorktree"),n=K());let G=k?.kind==="project"?{placeholder:w("sidebar.filterProjects"),emptyLabel:w("sidebar.noMatchingProjects"),minChoices:R?9:void 0}:{placeholder:w("sidebar.filterWorktrees"),emptyLabel:w("sidebar.noMatchingWorktrees")},X=M&&void 0!==u&&[...u].some(e=>{let[t,{running:n,unread:r}]=e;return t!==A?.key&&(n>0||r>0)});return(0,r.jsxs)("div",{className:`project-picker is-${s}`,role:"group","aria-label":a,children:[(0,r.jsxs)("button",{ref:N,type:"button",className:A?"project-picker-button is-project":"project-picker-button is-project is-empty",title:A?.root??"","aria-haspopup":"menu","aria-expanded":k?.kind==="project",onClick:e=>F("project",e.currentTarget),children:[T&&(0,r.jsx)(nq,{size:12,className:"project-picker-icon"}),T&&A?(0,r.jsxs)("span",{className:"project-picker-name",children:[void 0===A.alias&&P?.note&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{className:"project-picker-parent",children:P.note}),"/"]}),(0,r.jsx)("span",{className:"project-picker-leaf",children:A.alias??P?.name??J(A.root)})]}):A?.alias!==void 0?(0,r.jsx)("span",{className:"project-picker-label is-alias",children:A.alias}):A?(0,r.jsx)("span",{className:"project-picker-path",children:(0,r.jsx)("span",{children:rb(A.root,c)})}):(0,r.jsx)("span",{className:"project-picker-label",children:d}),X&&(0,r.jsx)("span",{className:"project-picker-activity",role:"img",title:w("sidebar.newActivity"),"aria-label":w("sidebar.newActivity")}),T&&(0,r.jsx)(nP,{size:9,className:"project-picker-chevron sidebar-icon-down"})]}),L&&(0,r.jsxs)("button",{ref:E,type:"button",className:"project-picker-button",title:z?w("sidebar.worktreePath",{path:z.path}):w("sidebar.switchWorktree"),"aria-haspopup":"menu","aria-expanded":k?.kind==="worktree",onClick:e=>F("worktree",e.currentTarget),children:[(0,r.jsx)(nW,{size:11,className:z&&!z.isMain?"project-picker-icon is-linked":"project-picker-icon"}),(0,r.jsx)("span",{className:"project-picker-path",children:(0,r.jsx)("span",{children:z?z.branch??rb(z.path,c):"…"})}),z?.isMain&&"stacked"===s&&(0,r.jsx)("span",{className:"project-picker-note",children:w("sidebar.main")}),M&&L.length>1&&(0,r.jsx)("span",{className:"project-picker-note",children:L.length}),(0,r.jsx)(nP,{size:9,className:"project-picker-chevron sidebar-icon-down"})]}),!L&&M&&p&&(0,r.jsxs)("button",{type:"button","aria-disabled":"true",tabIndex:-1,title:p.title,className:"project-picker-button is-inactive",children:[(0,r.jsx)(nW,{size:11,className:"project-picker-icon"}),(0,r.jsx)("span",{className:"project-picker-label",children:p.label})]}),(0,r.jsx)(rx,{open:null!==k,anchor:k?.anchor??null,sheet:l,ariaLabel:V,title:V,items:n,filter:G,cancelLabel:w("sidebar.cancel"),focusCancel:q?.kind==="remove",onClose:O,returnFocusTo:k?.opener??null,width:k?.width,classic:R,footer:Y,focusKey:q?`${q.kind}:${"remove"===q.kind&&q.dirty}`:"list",children:Z})]})}function rS(e,t,n){if(e.relation?.kind!=="side")return null;let r=e.relation.parentSessionId,i=t.find(e=>e.id===r),s=i?.name||i?.firstMessage||void 0,o=t.filter(e=>e.relation?.kind==="side"&&e.relation.parentSessionId===r),a=o.some(t=>t.id===e.id)?o:[...o,e];return{parentSessionId:r,...s?{parentTitle:s}:{},label:l(e,n,a)}}function rC(e){let{open:t,query:n,children:s,selectedSessionId:o,onSelectSession:l,onSelectSideChat:a,sessions:d,archivedSessionIds:c,projectNames:u}=e,{t:p,locale:h}=(0,tm.s)(),[f,m]=(0,i.useState)({query:""}),g=n.trim(),v=f.query===g?f.response:void 0,b=f.query===g&&f.failed;return(0,i.useEffect)(()=>{if(!t||!g)return;let e=new AbortController;m({query:g});let n=setTimeout(async()=>{try{let t=await fetch(`/api/sessions/search?${new URLSearchParams({q:g})}`,{signal:e.signal});if(!t.ok)throw Error(`HTTP ${t.status}`);let n=await t.json();e.signal.aborted||m({query:g,response:n})}catch{e.signal.aborted||m({query:g,failed:!0})}},300);return()=>{clearTimeout(n),e.abort()}},[t,g]),t&&g?(0,r.jsxs)("div",{className:"min-h-20 flex-1 overflow-y-auto","aria-busy":!v&&!b,children:[(0,r.jsx)("div",{role:"status",className:"px-3 py-2 text-xs text-text-muted",children:b?p("sidebar.sessionSearchFailed"):v?0===v.results.length?p("sidebar.sessionSearchEmpty"):p("sidebar.sessionSearchCount",{count:v.results.length}):p("sidebar.sessionSearching")}),v?.truncated&&(0,r.jsx)("div",{role:"status",className:"px-3 pb-2 text-xs text-text-muted",children:p("sidebar.sessionSearchPartial")}),v?.results.map(e=>{let t,n,{session:i,entryId:s,blockIndex:f,titleMatch:m,before:g,match:v,after:b}=e,y=i.relation?.kind==="side"?i.relation:null,w=y?rS(i,d,p("agentSwitcher.sideChat")):null,k=w?w.label:i.name||i.firstMessage;return(0,r.jsxs)("button",{type:"button",onClick:()=>{y&&i.id!==o?a(i):l(i,s,f)},"aria-current":i.id===o?"true":void 0,className:`block w-full cursor-pointer border-b border-border px-3 py-2 text-left hover:bg-bg-hover focus-visible:outline-2 focus-visible:outline-accent ${i.id===o?"bg-bg-selected":""}`,children:[(0,r.jsxs)("span",{className:"flex min-w-0 items-center gap-1.5",children:[(0,r.jsx)("span",{className:"min-w-0 truncate text-xs font-medium text-text",children:m?(0,r.jsxs)(r.Fragment,{children:[g,(0,r.jsx)("mark",{className:"rounded-sm bg-accent/20 text-text",children:v}),b]}):k}),c?.has(i.id)&&(0,r.jsx)("span",{className:"shrink-0 rounded-[4px] border border-border px-1 text-[10px] leading-[14px] text-text-dim",children:p("sidebar.archived")})]}),w&&(0,r.jsx)("span",{className:"mt-1 block truncate text-[10px] text-text-dim",title:w.parentTitle,children:w.parentTitle?p("sidebar.sideChatOf",{name:w.parentTitle}):p("agentSwitcher.sideChat")}),(0,r.jsxs)("span",{className:"mt-1 flex min-w-0 gap-2 text-[10px] text-text-dim",children:[(0,r.jsxs)("span",{className:"min-w-0 flex-1 truncate",title:i.cwd,children:[(0,r.jsx)("span",{className:"font-medium text-text-muted",children:(t=x(i),n=i.projectRoot??i.cwd,u&&Object.hasOwn(u,t)?u[t]:J(n))}),i.cwd!==(i.projectRoot??i.cwd)&&` \xb7 ${i.cwd}`]}),(0,r.jsx)("span",{className:"shrink-0",children:(0,nj.fw)(i.modified,h)})]}),!m&&(0,r.jsxs)("span",{className:"mt-1 block text-xs leading-relaxed wrap-anywhere text-text-muted",children:[g,(0,r.jsx)("mark",{className:"rounded-sm bg-accent/20 text-text",children:v}),b]})]},i.id)})]}):s}function rN(e){let{toast:t,dismissLabel:n,durationMs:s,onDismissRef:o}=e,l=(0,i.useRef)(null),[a,d]=(0,i.useState)(!1),[c,u]=(0,i.useState)(!1),p=a||c;return(0,i.useLayoutEffect)(()=>{let e=l.current;e&&window.matchMedia?.("(hover: hover)").matches&&e.matches(":hover")&&d(!0)},[]),(0,i.useEffect)(()=>{if(p)return;let e=window.setTimeout(()=>o.current(),s);return()=>window.clearTimeout(e)},[p,s,o]),(0,r.jsxs)("div",{ref:l,className:"sidebar-toast",onPointerEnter:e=>{"mouse"===e.pointerType&&d(!0)},onPointerLeave:()=>d(!1),onFocus:()=>u(!0),onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||u(!1)},children:[t.tail?(0,r.jsxs)("span",{className:"sidebar-toast-message has-tail",title:t.message+t.tail,children:[(0,r.jsx)("span",{className:"sidebar-toast-message-head",children:t.message}),(0,r.jsx)("span",{className:"sidebar-toast-message-tail",children:t.tail})]}):(0,r.jsx)("span",{className:"sidebar-toast-message",title:t.message,children:t.message}),t.actions.map(e=>(0,r.jsx)("button",{type:"button",className:"sidebar-toast-action",onClick:()=>{o.current(),e.onClick()},children:e.label},e.id)),(0,r.jsx)("button",{type:"button",className:"sidebar-toast-dismiss","aria-label":n,title:n,onClick:()=>o.current(),children:(0,r.jsx)(nK,{size:12})})]})}function rE(e){let{toast:t,onDismiss:n,dismissLabel:s,durationMs:o=1e4}=e,l=(0,i.useRef)(n);return l.current=n,(0,r.jsx)("div",{className:"sidebar-toast-region",role:"status","aria-live":"polite",children:t?(0,r.jsx)(rN,{toast:t,dismissLabel:s,durationMs:o,onDismissRef:l},t.id):null})}let r$={remote:"sidebar.openInExplorerRemoteOnly","unsupported-platform":"sidebar.openInExplorerUnsupported"};function rI(e){let{ref:t,onClick:n,title:i,disabled:s,pressed:o,expanded:l,controls:a,done:d,className:c,children:u}=e;return(0,r.jsx)("button",{ref:t,type:"button",onClick:n,disabled:s,title:i,"aria-label":i,"aria-pressed":o,"aria-expanded":l,"aria-controls":a,className:`sidebar-tool-button${o||l?" is-active":""}${d?" is-done":""}${c?` ${c}`:""}`,children:u})}let rM="pi-web:last-custom-cwd",rT={"open-new-tab":"sidebar.openInNewTab",pin:"sidebar.pin",unpin:"sidebar.unpin",rename:"sidebar.rename",fork:"sidebar.fork","mark-read":"sidebar.markRead","mark-unread":"sidebar.markUnread",archive:"sidebar.archive",unarchive:"sidebar.unarchive",delete:"sidebar.delete"};function rR(){try{return window.localStorage.getItem(rM)??""}catch{return""}}function rA(e,t){let n=new Set(t);if(n.size!==e.size)return n;for(let t of n)if(!e.has(t))return n;return e}function rL(e,t){return e.length>t?`${e.slice(0,t)}…`:e}function rz(e){let t=document.activeElement;e&&t instanceof HTMLElement&&t!==document.body&&(0===t.getClientRects().length||null!==t.closest("[inert]"))?e.focus({preventScroll:!0}):e_(document,e)}function rP(e,t){let n=e.getBoundingClientRect();return{kind:"rect",rect:{left:n.left,top:n.top,right:n.right,bottom:n.bottom},align:t}}function rW(e){var t,n,s;let o,l,u,h,f,m,g,b,{selectedSessionId:w,onSelectSession:k,onSelectSideChat:j,onNewSession:S,controlRef:C,onNewSessionContextChange:E,initialSessionId:D,initialSessionLinked:q,skipInitialProjectSelection:G,onInitialRestoreDone:ed,refreshKey:ex,onSessionDeleted:e$,selectedCwd:eI,onCwdChange:eR,onOpenFile:eL,onOpenTerminal:ez,explorerRefreshKey:eO,onExplorerRefresh:eH,onAtMention:eU,onAtMentions:eK,onBackgroundTaskDone:eq,hiddenFinishedSessionIds:eV,onRunningSessionIdsChange:eZ,onSessionsChange:eJ}=e,{t:eY}=(0,tm.s)(),eG=tC(),[eX,eQ]=(0,i.useState)([]),e1=(0,i.useRef)(null),e2=(0,i.useRef)(0),[e9,tt]=(0,i.useState)(!0),[ti,ts]=(0,i.useState)(!1),[to,tl]=(0,i.useState)(null),[ta,td]=(0,i.useState)(null),[tc,tu]=(0,i.useState)(""),[tp,th]=(0,i.useState)(!1),[tg,tx]=(0,i.useState)(rR),[tv,tb]=(0,i.useState)(null),[ty,tw]=(0,i.useState)(!1),[tk,tj]=(0,i.useState)(null),tS=(0,i.useRef)(null),[tN,tE]=(0,i.useState)(null),[tT,tz]=(0,i.useState)(null),tP=(0,i.useRef)(null);tP.current??=new Set(eC());let[tW,tO]=(0,i.useState)(0),[tF,tD]=(0,i.useState)(!1),[tB,tH]=(0,i.useState)(!1),[t_,tU]=(0,i.useState)(!1),[tV,tZ]=(0,i.useState)(""),[tJ,tY]=(0,i.useState)(0),[tG,tX]=(0,i.useState)(!0),[tQ,t0]=(0,i.useState)(!1),[t1,t2]=(0,i.useState)(!1),[t4,t8]=(0,i.useState)(null),[t3,t5]=(0,i.useState)(null),[t6,t9]=(0,i.useState)(()=>new Set),[t7,ne]=(0,i.useState)(()=>new Set),[nt,nn]=(0,i.useState)(()=>new Set),[nr,ni]=(0,i.useState)(()=>(function(){try{return e3(window.localStorage.getItem(e4))}catch{return new Map}})()),ns=(0,i.useRef)(new Set),no=(0,i.useRef)(new Set),nl=(0,i.useRef)({latest:null,before:null}),na=(0,i.useRef)(null);na.current??=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:Date.now,t=0;return{note(e,n,r){e8(e)&&Number.isFinite(n)&&Number.isFinite(r)&&(t=e-(n+r)/2)},toServer(){let n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:e();return n+t}}}();let nd=(0,i.useRef)(new Set),nc=(0,i.useRef)(new Set),nu=(0,i.useRef)(new Set),np=(0,i.useRef)(new Set),nh=(0,i.useRef)(!1),nf=(0,i.useRef)(null),nm=(0,i.useRef)(null),ng=(0,i.useRef)(null),nx=tf(),nv=!eG&&"below"===nx,[ny,nw]=(0,i.useState)("sessions"),[nj,nS]=(0,i.useState)(!1),nC=(0,i.useRef)(null),nN=(0,i.useRef)(null),nE=(0,i.useRef)(null),n$=(0,i.useRef)(null),nI=(0,i.useRef)(new WeakMap),[nW,nK]=(0,i.useState)({}),[nV,n1]=(0,i.useState)(()=>new Set),[n4,n3]=(0,i.useState)({}),[n5,n6]=(0,i.useState)(!1),[n9,n7]=(0,i.useState)(!1),[re,rt]=(0,i.useState)([]),[rn,rr]=(0,i.useState)(!1),{phase:ri,start:rs,end:ro}=tL(),{phase:rl,start:ra,end:rd}=tL(),rc=(0,i.useRef)(nj);rc.current=nj;let ru=(0,i.useRef)(rn);ru.current=rn;let rp=(0,i.useCallback)(e=>{e!==ru.current&&ra(e?"in":"out"),rr(e)},[ra]),rh=(o=nj&&"out"===ri,l=!nj&&"in"===ri,{bodyHidden:nj&&!o,bodyInert:o,moving:o||l,open:!nj&&!l}),rf=(u=rn&&"in"===rl,h=!rn&&"out"===rl,{mainHidden:rn&&!u,mainInert:u,archiveMounted:rn||h,archiveInert:h,archiveClass:u?"is-entering":h?"is-leaving":null}),[rm,rg]=(0,i.useState)(null),[rv,rb]=(0,i.useState)(null),[ry,rw]=(0,i.useState)(null),[rk,rS]=(0,i.useState)(null),[rN,rW]=(0,i.useState)(null),rO=(0,i.useRef)(0),rF=(0,i.useCallback)(e=>{rW(t=>t?.id===e?null:t)},[]),[rD,rB]=(0,i.useState)(null),rH=(0,i.useCallback)(e=>{rB(t=>t?.id===e?null:t)},[]),r_=(0,i.useRef)(w);r_.current=w;let[rU,rK]=(0,i.useState)(null),rq=(0,i.useRef)(0),rV=(0,i.useCallback)(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[],n=arguments.length>2?arguments[2]:void 0;rq.current+=1,rK({id:rq.current,message:e,...n?{tail:n}:{},actions:t})},[]),[rZ,rJ]=(0,i.useState)(0),rY=(0,i.useRef)(0),rG=(0,i.useRef)(null),[rX,rQ]=(0,i.useState)(0),r0=(0,i.useRef)(null),r1=(0,i.useRef)(null),r2=(0,i.useRef)(null),r4=(0,i.useRef)(null),[r8,r3]=(0,i.useState)(0),r5=(0,i.useCallback)(e=>{r4.current=e,r3(e=>e+1)},[]);(0,i.useEffect)(()=>{let e=r4.current;r4.current=null,e&&e_(document,e())},[r8]);let{state:r6,loaded:r9,synced:r7,error:ie,apply:it,snapshot:ir,noteRevision:ii}=function(){let[e,t]=(0,i.useState)(L),[n,r]=(0,i.useState)(!1),[s,o]=(0,i.useState)(!1),[l,a]=(0,i.useState)(null),d=(0,i.useRef)(e),c=(0,i.useRef)(e),u=(0,i.useRef)([]),p=(0,i.useRef)(Promise.resolve()),h=(0,i.useRef)(0),f=(0,i.useRef)(null),m=(0,i.useCallback)(()=>{let e=d.current;for(let{request:t,now:n}of u.current)e=function(e,t,n){var r,i,s,o;let l=function(e){let t={};for(let[n,r]of Object.entries(e.sessions))t[n]={...r};let n={};for(let[t,r]of Object.entries(e.projects))n[t]={...r};let r={...e,sessions:t,projects:n};return e.projectOrder&&(r.projectOrder=[...e.projectOrder]),e.projectNames&&(r.projectNames={...e.projectNames}),e.readAt&&(r.readAt={...e.readAt}),r}(e),a=!1;switch(t.action){case"set":for(let e of t.ids){let r=y(l.sessions,e)?l.sessions[e]:void 0;P(l.sessions,e,function(e,t,n){let r={...e};return"pinned"in t?t.pinned?(void 0===r.pinnedAt||void 0!==r.archivedAt)&&(r.pinnedAt=n,delete r.archivedAt):delete r.pinnedAt:t.archived?(r.archivedAt=n,delete r.pinnedAt):delete r.archivedAt,r}(r,t,n))&&(a=!0)}break;case"restore":for(let e of t.entries){let t={};null!==e.pinnedAt&&(t.pinnedAt=e.pinnedAt),null!==e.archivedAt&&(t.archivedAt=e.archivedAt),P(l.sessions,e.id,t)&&(a=!0)}break;case"pin-project":{let{projectKey:e,root:o}=t,d=y(l.projects,e)?l.projects[e]:void 0;if(t.pinned?d?.root!==o&&(l.projects[e]={pinnedAt:n,root:o},a=!0):d&&(delete l.projects[e],a=!0),(t.pinned?void 0===d:void 0!==d)&&l.projectOrder){let n,o,d=(r=l.projectOrder,i=l.projects,s=t.pinned,o=r.filter(t=>t!==e),s?(n=0,o.forEach((e,t)=>{y(i,e)&&(n=t+1)})):(n=o.findIndex(e=>!y(i,e)))<0&&(n=o.length),o.splice(n,0,e),o);M(d.length,I(d))&&W(l,d)&&(a=!0)}break}case"add-projects":W(l,function(e,t){let n=O(e,t),r=e.length,i=I(e),s=n.length;for(;s>0;){let e=$(n[s-1]);if(!M(r+1,i+e))break;r++,i+=e,s--}return[...n.slice(s),...e]}(l.projectOrder??[],t.keys))&&(a=!0);break;case"move-project":{let e,n,{projectKey:r,anchorKey:i,position:s,add:d}=t,c=l.projectOrder??[];W(l,function(e,t){let n=e.length,r=I(e);if(M(n,r))return e;let i=new Set;for(let s=e.length-1;s>=0&&!M(n,r);s--)t.has(e[s])||(i.add(s),n--,r-=$(e[s]));let s=e.filter((e,t)=>!i.has(t));return M(n,r)?s:T(s)}((o=[...O(c,d),...c],(e=o.filter(e=>e!==r)).includes(i)||e.unshift(i),n=e.indexOf(i),e.splice("before"===s?n:n+1,0,r),e),new Set([r,i,...d])))&&(a=!0);break}case"rename-project":{let e=N(t.name);void 0!==e&&function(e,t,n){let r={...e.projectNames};if((y(r,t)?r[t]:void 0)===(n??void 0))return!1;if(null===n)delete r[t];else if(r[t]=n,!A(Object.keys(r).length,function(e){let t=1;for(let[n,r]of Object.entries(e))t+=R(n,r);return t}(r)))return!1;return 0===Object.keys(r).length?delete e.projectNames:e.projectNames=r,!0}(l,t.projectKey,e)&&(a=!0);break}case"read":{let e={...l.readAt};for(let r of t.ids){let t=y(e,r)?e[r]:void 0;void 0!==t&&t>=n||(e[r]=n,a=!0)}a&&(l.readAt=z(e))}}return{state:l,changed:a}}(e,t,n).state;c.current=e,t(e)},[]),g=(0,i.useCallback)(async e=>{let t=++h.current;f.current=t;try{let n=await fetch(tM,{cache:"no-store"}),i=await tA(n);if(t!==h.current)return;d.current=i,m(),e||a(null),r(!0),o(!0)}catch(e){if(t!==h.current)return;a(tR(e)),r(!0)}finally{f.current===t&&(f.current=null)}},[m]),x=(0,i.useCallback)(()=>g(!1),[g]),v=(0,i.useCallback)(e=>{"number"!=typeof e||!Number.isFinite(e)||u.current.length>0||e===d.current.revision||(null===f.current||f.current!==h.current)&&x()},[x]),b=(0,i.useCallback)(e=>{let t={request:e,now:Date.now()};u.current=[...u.current,t],m();let n=async()=>{let n=!1;try{let t=await fetch(tM,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),cache:"no-store"}),i=await tA(t);h.current++,d.current=i,a(null),r(!0),o(!0),n=!0}catch(e){a(tR(e))}return u.current=u.current.filter(e=>e!==t),m(),n||await g(!0),n},i=p.current.then(n,n);return p.current=i,i},[g,m]),w=(0,i.useCallback)(e=>(function(e,t){let n=new Set,r=[];for(let i of t){if(n.has(i))continue;n.add(i);let t=y(e.sessions,i)?e.sessions[i]:void 0;r.push({id:i,pinnedAt:t?.pinnedAt??null,archivedAt:t?.archivedAt??null})}return r})(c.current,e),[]);return(0,i.useEffect)(()=>{x()},[x]),(0,i.useMemo)(()=>({state:e,loaded:n,synced:s,error:l,refresh:x,noteRevision:v,apply:b,snapshot:w}),[e,n,s,l,x,v,b,w])}(),is=r6.readAt,io=(0,i.useMemo)(()=>new Set(e5(nr,is).keys()),[nr,is]);(0,i.useEffect)(()=>{ni(e=>e5(e,is))},[is,nr]);let il=(0,i.useRef)({allSessions:eX,readAt:is,unreadMarks:nr,runningSessionIds:t6,subagentsActiveSessionIds:nt});il.current={allSessions:eX,readAt:is,unreadMarks:nr,runningSessionIds:t6,subagentsActiveSessionIds:nt};let ia=(0,i.useCallback)(e=>{let t=nc.current,n=[...new Set(e)].filter(e=>!t.has(e));if(0!==n.length){for(let e of n)t.add(e);it({action:"read",ids:n}).then(e=>{for(let r of n)t.delete(r),e&&nd.current.delete(r)})}},[it]),id=(0,i.useCallback)((e,t)=>{var n;let r=il.current;if(r.runningSessionIds.has(e)||r.subagentsActiveSessionIds.has(e))return;if(!tr()){t&&nd.current.add(e);return}let i=r.allSessions.find(t=>t.id===e),s=i?Date.parse(i.modified):0/0;((n={readAt:r.readAt&&Object.prototype.hasOwnProperty.call(r.readAt,e)?r.readAt[e]:void 0,modifiedMs:Number.isFinite(s)?s:void 0,marked:t,pending:nd.current.has(e)}).marked||n.pending||void 0===n.readAt||void 0!==n.modifiedMs&&n.modifiedMs>n.readAt)&&ia([e])},[ia]);(0,i.useEffect)(()=>{var e;let t,n;return e=()=>{let e=r_.current;e&&id(e,!1)},t=tn().onAttended(e),0==e7++&&(te=function(){let e=tn(),t=()=>e.noteInput(),n=()=>e.notePageChange(),r={capture:!0,passive:!0};for(let e of e6)window.addEventListener(e,t,r);return window.addEventListener("focus",n),window.addEventListener("blur",n),document.addEventListener("visibilitychange",n),()=>{for(let e of e6)window.removeEventListener(e,t,r);window.removeEventListener("focus",n),window.removeEventListener("blur",n),document.removeEventListener("visibilitychange",n)}}()),n=!1,()=>{n||(n=!0,t(),0==--e7&&(te?.(),te=null))}},[id]);let ic=(0,i.useRef)(null),iu=(0,i.useRef)(null);tI(iu);let ip=(0,i.useRef)(null),ih=(0,i.useRef)(null),im=(0,i.useRef)(320),ig=(0,i.useCallback)(()=>{let e=ih.current,t=ic.current;return e&&t&&0!==e.clientHeight?e.clientHeight-t.offsetHeight:window.innerHeight-36},[]),ix=(0,i.useCallback)(()=>Math.round(.45*ig()),[ig]),iv=(0,i.useCallback)(()=>ig()-120,[ig]),ib=t$({ariaLabel:eY("sidebar.resizeFiles"),axis:"vertical",cssVariable:"--sidebar-files-height",defaultWidth:320,getDefaultWidth:ix,getMaxWidth:iv,growthDirection:"up",maxWidth:2e3,minWidth:220,persistClamp:!1,storageKey:"pi-web:sidebar-files-height",widthRef:im}),iy=ib.panelRef,iw=(0,i.useCallback)(e=>{ih.current=e,iy.current=e},[iy]),ik=ib.reclampWidth;(0,i.useEffect)(()=>{let e=ih.current;if(!nv||!e||"u"<typeof ResizeObserver)return;let t=new ResizeObserver(()=>ik());return t.observe(e),()=>t.disconnect()},[ik,nv]),(0,i.useEffect)(()=>{let e=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:ey();if(!e)return"sessions";try{return"files"===e.getItem(ec)?"files":"sessions"}catch{return"sessions"}}();"sessions"!==e&&nw(e);let t=function(){let e,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:ey();if(!t)return{};try{let e=t.getItem(eu);if(null!==e)return ew(JSON.parse(e))}catch{return{}}try{let n=t.getItem(ep);if(null===n)return{};e=ew(JSON.parse(n))}catch{e={}}let n=Object.fromEntries(Object.entries(e).filter(e=>{let[,t]=e;return!t}));return ek(n,t),n}();Object.keys(t).length>0&&nK(t),function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:ey();if(!e)return!1;try{return"true"===e.getItem(ef)}catch{return!1}}()&&n6(!0);let n=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:ey();if(!e)return[];try{let t=e.getItem(eh),n=null===t?[]:JSON.parse(t);if(!Array.isArray(n))return[];let r=n.filter(e=>"string"==typeof e&&""!==e);return[...new Set(r)].slice(-300)}catch{return[]}}();n.length>0&&rt(n),function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:ey();if(!e)return!1;try{return"true"===e.getItem(eg)}catch{return!1}}()&&nS(!0),function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:ey();if(!e)return!1;try{return"true"===e.getItem(em)}catch{return!1}}()&&t0(!0),n7(!0),function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:ey();if(e)for(let t of eb)try{e.removeItem?.(t)}catch{}}()},[]);let ij=(0,i.useCallback)(async function(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0],t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],n=arguments.length>2&&void 0!==arguments[2]&&arguments[2],r=++e2.current;try{e&&tt(!0);let i=await fetch(n?"/api/sessions?summary=1":t?"/api/sessions?force=1":"/api/sessions",{cache:"no-store"});if(!i.ok)throw Error(`HTTP ${i.status}`);let s=await i.json();if(r!==e2.current)return;e1.current=s.sessionListVersion,eQ(s.sessions),n||ts(!0),nh.current||(nu.current=new Set(s.completionNotificationSuppressedSessionIds??[]),nl.current={latest:Date.now(),before:nl.current.latest},t9(e=>rA(e,s.runningSessionIds??[])),ne(e=>rA(e,s.awaitingInputSessionIds??[])));let o=new Set(s.sessions.filter(e=>!a(e.relation)).map(e=>e.id));ni(e=>{if(0===e.size)return e;let t=new Map([...e].filter(e=>{let[t]=e;return o.has(t)}));return t.size===e.size?e:t}),tl(null)}catch(e){r===e2.current&&tl(String(e))}finally{r===e2.current&&tt(!1)}},[]),iS=(0,i.useRef)(!1);(0,i.useEffect)(()=>{let e=!iS.current;iS.current=!0;let t=!0;return e?ij(!0,!1,!0).then(()=>{t&&(nf.current=setTimeout(()=>{nf.current=null,t&&ij(!1,!0)},750))}):ij(),()=>{t=!1,nf.current&&(clearTimeout(nf.current),nf.current=null)}},[ij,ex]),(0,i.useEffect)(()=>{let e=!1;return fetch("/api/open-in-explorer").then(e=>e.ok?e.json():null).then(t=>{!e&&t&&t8(t)}).catch(()=>{}),()=>{e=!0}},[]),(0,i.useEffect)(()=>{t5(null)},[ta,eI]);let iC=(0,i.useCallback)(async()=>{let e=ta??eI;if(!e)return!1;try{let t=await fetch("/api/open-in-explorer",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e})});if(t.ok)return t5(null),!1;let n=await t.json().catch(()=>({}));t5(n.error??`HTTP ${t.status}`)}catch(e){t5(e instanceof Error?e.message:String(e))}return!0},[ta,eI]),iN=eY(t4?.platform==="darwin"?"sidebar.openInFinder":t4?.platform==="win32"?"sidebar.openInExplorer":"sidebar.openInFileManager"),iE=t4?.supported===!1,i$=t3?eY(r$[t3]??t3):null;(0,i.useEffect)(()=>{try{let e=0===nr.size?null:JSON.stringify(Object.fromEntries(nr));null===e?window.localStorage.removeItem(e4):window.localStorage.setItem(e4,e)}catch{}},[nr]),(0,i.useEffect)(()=>{let e=e=>{(null===e.key||e.key===e4)&&ni(t=>(function(e,t){if(e.size!==t.size)return t;for(let[n,r]of t)if(e.get(n)!==r)return t;return e})(t,e3(e.newValue)))};return window.addEventListener("storage",e),()=>window.removeEventListener("storage",e)},[]),(0,i.useEffect)(()=>{let e=!1,t=null,n=null,r=()=>{t&&clearTimeout(t),t=null},i=async()=>{if(e||"visible"!==document.visibilityState)return;let s=new AbortController;n?.abort(),n=s;let o=Date.now(),l=null,a="error",d=null;try{let t=await fetch("/api/agent/running",{cache:"no-store",signal:s.signal});if(d=t.status,!t.ok)return;a="ok";let r=await t.json();if(l=Date.now(),e||n!==s)return;nh.current=!0,"number"==typeof r.serverNow&&na.current?.note(r.serverNow,o,l),nl.current={latest:o,before:nl.current.latest},nu.current=new Set(r.completionNotificationSuppressedSessionIds??[]),t9(e=>rA(e,r.runningSessionIds??[])),ne(e=>rA(e,r.awaitingInputSessionIds??[])),nn(e=>rA(e,r.subagentsActiveSessionIds??[])),ii(r.sessionUiStateRevision),r.sessionListVersion!==e1.current&&await ij()}catch{a=s.signal.aborted?"aborted":"error"}finally{n===s&&(n=null),r(),e||"visible"!==document.visibilityState||(t=setTimeout(()=>void i(),2500)),function(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null,i=Date.now();e0.count+=1,"error"===t&&(e0.failures+=1),e0.last={at:i,durationMs:Math.max(0,(r??i)-e),outcome:t,httpStatus:n}}(o,a,d,l)}},s=()=>{"visible"===document.visibilityState?i():(r(),n?.abort(),n=null)};return i(),document.addEventListener("visibilitychange",s),()=>{e=!0,r(),n?.abort(),document.removeEventListener("visibilitychange",s)}},[ij,ii]),(0,i.useEffect)(()=>{eZ?.(t6)},[eZ,t6]),(0,i.useEffect)(()=>{eJ?.(eX)},[eX,eJ]),(0,i.useEffect)(()=>{!function(e){let t,n;if("u"<typeof document)return;let r=(n=(t=eP(e.awaiting))+eP(e.unread))<=0?null:{kind:t>0?"awaiting":"unread",count:Math.min(n,99)},i=r?`${r.kind}:${r.count}`:"none";if(i!==eW){if(eW=i,!r){for(let[e,t]of eF)e.href=t;return}for(let e of eD())eF.has(e)||eF.set(e,e.href);eB(r,i)}}({awaiting:t7.size,unread:function(e,t){if(!t||0===t.size)return e.size;let n=0;for(let r of t)e.has(r)||(n+=1);return e.size+n}(io,eV)})},[t7,io,eV]),(0,i.useEffect)(()=>{let e=ns.current,t=[...e].filter(e=>!t6.has(e)&&e!==w),n=new Set([...t6,...nt]),r=[...no.current].filter(e=>!n.has(e)&&e!==w),i=new Set(eX.filter(e=>a(e.relation)).map(e=>e.id)),s=r.filter(e=>!np.current.has(e)&&!i.has(e)),o=[...t6].filter(t=>!e.has(t));if(s.length>0||o.length>0){let e=nl.current.before,t=na.current.toServer(e??void 0);ni(e=>{let n=new Map(e);return t6.forEach(e=>n.delete(e)),s.forEach(e=>n.set(e,t)),n})}w&&no.current.has(w)&&!n.has(w)&&(tr()?ia([w]):nd.current.add(w));let l=o.some(e=>!eX.some(t=>t.id===e));if((t.length>0||l)&&ij(),s.length>0){let e=nl.current.before??Date.now()-5e3;eq?.(s,e)}ns.current=t6,no.current=n;let d=np.current;np.current=new Set([...n].filter(e=>nu.current.has(e)||i.has(e)||d.has(e)&&!t6.has(e)))},[t6,nt,w,eX,ij,eq,ia]),(0,i.useEffect)(()=>{if(!w)return;let e=il.current.unreadMarks.has(w);id(w,e),e&&ni(e=>{if(!e.has(w))return e;let t=new Map(e);return t.delete(w),t})},[w,id]),(0,i.useEffect)(()=>{void 0!==eO&&tO(e=>e+1)},[eO]),(0,i.useEffect)(()=>{fetch("/api/home").then(e=>e.json()).then(e=>{e.home&&tu(e.home)}).catch(()=>{})},[]);let iI=(0,i.useRef)(!1),iM=(0,i.useCallback)(e=>e?function(e,t){let{validated:n,listing:r,sessions:i}=t;if(n?.cwd===e)return{root:n.root,key:n.key};if(r?.forCwd===e||r?.isTopLevel&&r.worktrees.some(t=>t.path===e))return{root:r.projectRoot,key:r.projectKey};let s=i.find(t=>t.cwd===e||(t.projectRoot??t.cwd)===e);return s?{root:s.projectRoot??s.cwd,key:x(s)}:{root:e,key:e}}(e,{validated:tk,listing:tN,sessions:eX}):null,[tk,tN,eX]),iT=(0,i.useMemo)(()=>iM(ta),[iM,ta]),iR=(0,i.useRef)(null);(0,i.useEffect)(()=>{let e=iM(ta),t=iR.current;(t?.cwd!==ta||t.key!==(e?.key??null))&&(iR.current={cwd:ta,key:e?.key??null},eR?.(ta,e?.root??null,e?.key??null))},[ta,eR,iM]);let iA=(0,i.useRef)(null);(0,i.useEffect)(()=>{if(!eI){iA.current=null;return}eI!==iA.current&&(iA.current=eI,td(eI))},[eI]);let[iL,iz]=(0,i.useState)(0);(0,i.useLayoutEffect)(()=>{if(!ta){tE(null),tz(null);return}let e=!1;return tz(ta),fetch(`/api/worktrees?cwd=${encodeURIComponent(ta)}`).then(e=>e.json()).then(t=>{if(!e){if(tz(null),t.error||!t.projectRoot)return void tE(null);t.isGit?tP.current?.delete(ta):tP.current?.add(ta),function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:ey();if(!n||!e)return;let r=eC(n),i=r.indexOf(e);if(t?-1===i:-1!==i&&i===r.length-1)return;let s=r.filter(t=>t!==e);t||s.push(e);try{n.setItem(ev,JSON.stringify(s.slice(-50)))}catch{}}(ta,!!t.isGit),tE({forCwd:ta,projectRoot:t.projectRoot,projectKey:t.projectKey??t.projectRoot,isGit:t.isGit??!1,isTopLevel:t.isTopLevel??!1,currentWorktreePath:t.currentWorktreePath??null,worktrees:t.worktrees??[]})}}).catch(()=>{e||(tz(null),tE(null))}),()=>{e=!0}},[ta,iL,ex]),(0,i.useEffect)(()=>{if(0!==eX.length&&!G&&null===ta){if(D&&!iI.current){iI.current=!0;let e=eX.find(e=>e.id===D);if(e){td(e.cwd),k(e,!0);return}ed?.(),q&&rV(eY("sidebar.sessionNotFound"))}let e=v(eX);e.length>0&&td(e[0].root)}},[eX,ta,D,q,G,k,ed,rV,eY]);let iP=tN?tN.worktrees.find(e=>e.path===ta)??(tN.forCwd===ta&&tN.currentWorktreePath?tN.worktrees.find(e=>e.path===tN.currentWorktreePath):void 0)??tN.worktrees.find(e=>e.isMain):void 0,iW=iP?.path??null,iO=(0,i.useCallback)(async function(e){let{remember:t=!0,purpose:n=tp}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=(e??tg).trim();if(r&&!ty){tw(!0),tb(null);try{let e=await fetch("/api/cwd/validate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:r})}),s=await e.json().catch(()=>({}));if(!e.ok||s.error||!s.cwd||!s.projectRoot||!s.projectKey)return void tb(s.error??`HTTP ${e.status}`);if(t){var i=s.cwd;try{window.localStorage.setItem(rM,i)}catch{}tx(s.cwd)}if(th(!1),"new-session"===n){let e=r1.current,t=r2.current;r1.current=null,r2.current=null,e?.({cwd:s.cwd,projectKey:s.projectKey,projectRoot:s.projectRoot}),r5(()=>t?.isConnected?t:null);return}tj({cwd:s.cwd,root:s.projectRoot,key:s.projectKey}),td(s.cwd)}catch(e){tb(e instanceof Error?e.message:String(e))}finally{tw(!1)}}},[tp,tg,ty,r5]),iF=(0,i.useCallback)(()=>{th("files"),tb(null)},[]),iD=(0,i.useCallback)(async function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"files";try{let t=await fetch("/api/default-cwd",{method:"POST"}),n=await t.json();n.cwd&&await iO(n.cwd,{remember:!1,purpose:e})}catch{}},[iO]),iB=(0,i.useRef)(iD);iB.current=iD;let iH=(0,i.useCallback)(async(e,t)=>{try{let r=await fetch("/api/worktrees",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e.root,branch:t})}),i=await r.json().catch(()=>({}));if(!r.ok||i.error||!i.path){var n;let e,t=(n=r.status,(e="branch_in_use"===i.code?"sidebar.worktreeBranchInUse":"branch_worktree_missing"===i.code?"sidebar.worktreeBranchMissing":null)&&i.branch&&i.worktreePath?{key:e,params:{branch:i.branch,path:i.worktreePath}}:{error:i.error??`HTTP ${n}`});return"key"in t?{error:eY(t.key,{...t.params,path:eE(t.params.path)})}:t}let s=i.path;return tE(n=>n&&n.projectKey===e.key&&!n.worktrees.some(e=>e.path===s)?{...n,worktrees:[...n.worktrees,{path:s,branch:t,isMain:!1}]}:n),iz(e=>e+1),{path:s}}catch(e){return{error:e instanceof Error?e.message:String(e)}}},[eY]),i_=(0,i.useCallback)(async(e,t,n)=>{try{let r=await fetch("/api/worktrees",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e.root,path:t,force:n})}),i=await r.json().catch(()=>({}));if(!r.ok){if(i.dirty&&!n)return"dirty";return{error:i.error??`HTTP ${r.status}`}}return iW===t&&td(e.root),iz(e=>e+1),"removed"}catch(e){return{error:e instanceof Error?e.message:String(e)}}},[iW]),iU=(0,i.useCallback)(()=>iz(e=>e+1),[]),iK=(0,i.useCallback)(e=>{let{cwd:t,projectKey:n,projectRoot:r}=e;n&&r&&tj({cwd:t,root:r,key:n}),td(t)},[]),iq=(0,i.useCallback)((e,t,n,r)=>{eQ(t=>t.some(t=>t.id===e.id)?t:[e,...t]),e.cwd&&td(e.cwd),k(e,!1,t,n,r)},[k]),iV=(0,i.useCallback)(e=>{let{cwd:t,projectKey:n,projectRoot:r,carryComposer:i}=e;n&&r&&tj({cwd:t,root:r,key:n}),td(t),S?.("function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}-${Math.random().toString(36).slice(2)}`,t,n,i?{carryComposer:!0}:void 0)},[S]),iZ=(0,i.useRef)(iV);iZ.current=iV,(0,i.useImperativeHandle)(C,()=>({startNewSessionIn:e=>iZ.current(e),openFolderForNewSession:(e,t)=>{r1.current=e,r2.current=t,tb(null),th("new-session")},openDefaultDirectoryForNewSession:e=>{r1.current=e,r2.current=null,iB.current("new-session")},refreshWorktrees:iU,createWorktree:iH}),[iH,iU]);let iJ=(0,i.useCallback)(()=>{ta&&iV({cwd:ta})},[ta,iV]),iY=(0,i.useMemo)(()=>v(eX),[eX]),iG=(0,i.useMemo)(()=>d(eX),[eX]),iX=(0,i.useMemo)(()=>new Map(iG.map(e=>[e.root.id,e])),[iG]),iQ=(0,i.useMemo)(()=>{let e=new Set,t=new Map;for(let n of iG){if(!V(n,r6,t6))continue;for(let t of K(n))e.add(t);let r=x(n.root);t.set(r,(t.get(r)??0)+1)}return{ids:e,countByProject:t}},[iG,r6,t6]),i0=(0,i.useMemo)(()=>(function(e,t,n){let r=new Map;for(let i of e){let e=x(i);if(!e)continue;let s=r.get(e);s||(s={running:0,unread:0},r.set(e,s)),t.has(i.id)&&s.running++,n.has(i.id)&&s.unread++}return r})(0===iQ.ids.size?eX:eX.filter(e=>!iQ.ids.has(e.id)),t6,io),[eX,iQ,t6,io]),i1=!!(tN?.isGit&&tN.isTopLevel&&ta&&iT?.key===tN.projectKey),i2=ta&&tN?.isGit&&iT?.key===tN.projectKey&&!i1?{label:eY("sidebar.openRepoRoot"),title:eY("sidebar.openRepoRootTitle")}:null,i4=!!(ta&&tT===ta),i8=i2??(!i4||i1||ta&&tP.current?.has(ta)?null:{label:eY("sidebar.worktrees"),title:eY("sidebar.checkingWorktrees")}),i3=iT?.key??null,i5=iT?.root??null,i6=(0,i.useMemo)(()=>i3&&i5?{key:i3,root:i5}:null,[i3,i5]),i9=(0,i.useMemo)(()=>0===nV.size?nW:Object.fromEntries([...[...nV].filter(e=>!Object.hasOwn(nW,e)).map(e=>[e,!0]),...Object.entries(nW)]),[nW,nV]),i7=(0,i.useMemo)(()=>(function(e){let{uiState:t,runningIds:n,currentProject:r}=e,i=d(e.sessions),s=ee(t,r),o=0,l=[],a=new Map,c=new Map,u=new Set;for(let e of i){if(V(e,t,n)){o++;continue}s.noteFamily(e);let r=Q(e),i=function(e){let t=Date.parse(e);return Number.isNaN(t)?-1/0:t}(e.latestModified);if(c.set(r,Math.max(c.get(r)??-1/0,i)),e.root.transient||u.add(r),Z(e,t,n)){l.push(e);continue}let d=a.get(r);d?d.push(e):a.set(r,[e])}let p=[{kind:"spacer",key:"top-spacer"}];if(l.length>0){let n=e=>_(H(t,e.root.id)?.pinnedAt)??0,r=l.map((e,t)=>({family:e,index:t})).sort((e,t)=>U(n(e.family),n(t.family))||e.index-t.index).map(e=>{let{family:t}=e;return t}),{running:i,awaiting:o,unread:a}=X(r,e);if(p.push({kind:"pinned-header",key:"pinned-header",count:r.length,collapsed:e.pinnedCollapsed,running:i,awaiting:o,unread:a}),!e.pinnedCollapsed){let{visible:t,revealed:n,nextShown:i}=en(r,8,er(e.moreShown,B),e);for(let n of t)p.push(et(n,"pinned",s.get(Q(n)),e));let o=es(r.length,t.length,n);o&&p.push({kind:"pinned-more",key:"pinned-more",...o,nextShown:i})}p.push({kind:"spacer",key:"pinned-spacer"})}let h=[...a.keys()],f=new Set(h),m=e=>{f.has(e)||(f.add(e),h.push(e))};for(let e of(r&&m(r.key),Object.keys(t.projects)))m(e);let g=h.map(e=>s.get(e)),x=new Map;(t.projectOrder??[]).forEach((e,t)=>{x.has(e)||x.set(e,t)});let v=e=>e.pinned||u.has(e.key),b=(e,t)=>[...e.filter(e=>{let{project:t}=e;return!x.has(t.key)}).sort((e,n)=>Number(v(e.project))-Number(v(n.project))||t(e,n)),...e.filter(e=>{let{project:t}=e;return x.has(t.key)}).sort((e,t)=>(x.get(e.project.key)??0)-(x.get(t.project.key)??0))].map(e=>{let{project:t}=e;return t}),y=e=>c.get(e.key)??(e.current?1/0:-1/0),w=e=>_(t.projects[e.key]?.pinnedAt)??0,k=g.map((e,t)=>({project:e,index:t})),j=b(k.filter(e=>{let{project:t}=e;return t.pinned}),(e,t)=>U(w(t.project),w(e.project))||e.index-t.index),S=b(k.filter(e=>{let{project:t}=e;return!t.pinned}),(e,t)=>U(y(e.project),y(t.project))||e.index-t.index),C=[...j,...S],N=e=>e.filter(e=>!x.has(e.key)).map(e=>e.key),E={pinned:N(j),other:N(S)},$=C.filter(e=>!x.has(e.key)&&v(e)).map(e=>e.key);for(let[t,n]of C.entries()){t>0&&p.push({kind:"spacer",key:`group-spacer:${n.key}`});let r=a.get(n.key)??[],i=Y(n,e.groupExpansion),{running:s,awaiting:o,unread:l}=X(r,e);if(p.push({kind:"group",key:`group:${n.key}`,project:n,expanded:i,running:s,awaiting:o,unread:l}),i)if(0===r.length)p.push({kind:"group-empty",key:`empty:${n.key}`,project:n});else{let{visible:t,revealed:i,nextShown:s}=en(r,6,er(e.moreShown,n.key),e);for(let r of t)p.push(et(r,"group",n,e));let o=es(r.length,t.length,i);o&&p.push({kind:"group-more",key:`more:${n.key}`,projectKey:n.key,...o,nextShown:s})}}return C.length>0&&p.push({kind:"spacer",key:"footer-spacer"}),p.push({kind:"footer-open",key:"footer-open"}),o>0&&p.push({kind:"footer-archived",key:"footer-archived",count:o}),{rows:p,projects:C,archivedCount:o,unorderedKeysByBand:E,projectKeysToRecord:$}})({sessions:eX,uiState:r6,runningIds:t6,awaitingIds:t7,unreadIds:io,selectedSessionId:w,currentProject:i6,groupExpansion:i9,moreShown:n4,pinnedCollapsed:n5}),[eX,r6,t6,t7,io,w,i6,i9,n4,n5]),se=rf.archiveMounted,st=(0,i.useMemo)(()=>new Set(re),[re]),sn=(0,i.useMemo)(()=>se?function(e){let{uiState:t,runningIds:n}=e,r=ee(t,e.currentProject),i=new Map;for(let s of d(e.sessions)){if(!V(s,t,n))continue;r.noteFamily(s);let e=_(H(t,s.root.id)?.archivedAt)??0,o=Q(s),l=i.get(o);l?(l.families.push({family:s,archivedAt:e}),l.newest=Math.max(l.newest,e)):i.set(o,{newest:e,families:[{family:s,archivedAt:e}]})}let s=[];for(let{key:t,group:n}of[...i.entries()].map((e,t)=>{let[n,r]=e;return{key:n,group:r,index:t}}).sort((e,t)=>U(e.group.newest,t.group.newest)||e.index-t.index)){let i=r.get(t),o=!e.collapsed?.has(t);if(s.push({kind:"archive-group",key:`archive:${t}`,project:i,count:n.families.length,expanded:o}),o)for(let{family:t}of n.families.map((e,t)=>({...e,index:t})).sort((e,t)=>U(e.archivedAt,t.archivedAt)||e.index-t.index))s.push(et(t,"archive",i,e))}return s}({sessions:eX,uiState:r6,runningIds:t6,awaitingIds:t7,unreadIds:io,selectedSessionId:w,currentProject:i6,collapsed:st}):[],[se,eX,r6,t6,t7,io,w,i6,st]),sr=(0,i.useMemo)(()=>sn.flatMap(e=>"archive-group"===e.kind?[e]:[]),[sn]),si=(0,i.useMemo)(()=>new Map(i7.projects.map(e=>[e.key,e])),[i7.projects]),ss=(0,i.useRef)(new Set),so=i7.projectKeysToRecord,sl=r6.projectOrder?.length??0;(0,i.useEffect)(()=>{if(e9||!r7||!ti||sl>=1e3)return;let e=ss.current,t=function(e,t){let n=e.length;for(;n>0&&e.length-n<500&&!t.has(e[n-1]);)n--;return e.slice(n)}(so,e);if(0!==t.length){for(let n of t)e.add(n);it({action:"add-projects",keys:t})}},[it,e9,so,ti,sl,r7]);let sa=r6.projectNames,sd=(0,i.useMemo)(()=>(function(e,t,n){let r=new Set,i=[];for(let s of[...e,...t])r.has(s.key)||(r.add(s.key),i.push(eA(s,n)));return i})(i7.projects,iY,sa),[i7.projects,iY,sa]),sc=(0,i.useMemo)(()=>{if(!ta||!iT)return null;let e=i1&&null!==tN;return{cwd:ta,project:eA(iT,sa),worktrees:e?tN.worktrees.map(e=>{let{path:t,branch:n,isMain:r}=e;return{path:t,branch:n,isMain:r}}):null,currentWorktreePath:e?iW:null,projects:sd}},[ta,iT,i1,tN,iW,sd,sa]),su=(0,i.useRef)(sc);su.current=sc;let sp=sc?JSON.stringify([sc.cwd,sc.project.key,sc.project.root,sc.project.alias??null,sc.currentWorktreePath,sc.worktrees?.map(e=>[e.path,e.branch,e.isMain])??null,sc.projects.map(e=>[e.key,e.root,e.alias??null])]):"";(0,i.useEffect)(()=>{E?.(su.current)},[sp,E]);let sh=(0,i.useRef)(i3);(0,i.useLayoutEffect)(()=>{let e=sh.current;if(sh.current=i3,null===e||e===i3)return;let t=si.get(e);n1(e=>!t||t.current||t.pinned||e.has(t.key)||Object.hasOwn(nW,t.key)?e:new Set(e).add(t.key))},[i3,nW,si]);let sf=(0,i.useCallback)((e,t)=>{nK(e),ek(e),n1(e=>(function(e,t){if(0===e.size)return e;if(null===t)return new Set;if(!t.some(t=>e.has(t)))return e;let n=new Set(e);for(let e of t)n.delete(e);return n})(e,t)),n3(n=>(function(e,t,n){let r=(n??Object.keys(t)).filter(n=>!1===t[n]&&Object.hasOwn(e,n));if(0===r.length)return e;let i={...e};for(let e of r)delete i[e];return i})(n,e,t))},[]),sm=(0,i.useCallback)(()=>(nE.current?.hidden?nN:nC).current??ip.current,[]),sg=(0,i.useCallback)(e=>{let t=nE.current;for(let n of["pinned","group","archive"]){let r=CSS.escape(`session:${n}:${e}`),i=t?.querySelector(`[data-row-key="${r}"] .session-tree-main`);if(i&&i.getClientRects().length>0)return i}return sm()},[sm]),sx=(0,i.useCallback)(e=>{let t=CSS.escape(`group:${e}`),n=nE.current?.querySelector(`[data-row-key="${t}"] .session-tree-group-toggle`);return n&&n.getClientRects().length>0?n:sm()},[sm]),sv=(0,i.useCallback)(async e=>{let t=await it(e);return t||rJ(e=>e+1),t},[it]);(0,i.useEffect)(()=>{rZ!==rY.current&&(rY.current=rZ,rV(eY("sidebar.uiStateFailed",{error:ie??""})))},[rZ,ie,rV,eY]);let sb=(0,i.useCallback)((e,t,n)=>{let r=si.get(e),i=si.get(t);r&&i&&r!==i&&r.pinned===i.pinned&&(sv({action:"move-project",projectKey:e,anchorKey:t,position:n,add:i7.unorderedKeysByBand[r.pinned?"pinned":"other"].slice(-500)}),rO.current+=1,rW({id:rO.current,at:Date.now(),rowKey:`group:${e}`}))},[sv,i7.unorderedKeysByBand,si]),sy=(0,i.useCallback)(e=>{nv||(nw(e),function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:ey();if(t)try{t.setItem(ec,e)}catch{}}(e))},[nv]),sw=(0,i.useCallback)(e=>{e!==rc.current&&rs(e?"out":"in"),nS(e),function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:ey();if(t)try{t.setItem(eg,String(e))}catch{}}(e)},[rs]),sk=(0,i.useCallback)(e=>{let t=e.target;t instanceof Element&&nI.current.set(t,t.scrollTop)},[]);(0,i.useLayoutEffect)(()=>{for(let e of[nE.current,n$.current])if(e&&!e.hidden)for(let t of e.querySelectorAll(".session-tree-scroll, .sidebar-files-scroll")){let e=nI.current.get(t);void 0!==e&&t.scrollTop!==e&&(t.scrollTop=e)}},[ny,rn,nv,nj]);let sj=(0,i.useCallback)(e=>{if(rS(null),rp(!0),tU(!1),sy("sessions"),void 0!==e){if(re.includes(e)){let t=re.filter(t=>t!==e);rt(t),ej(t)}rO.current+=1,rB({id:rO.current,at:Date.now(),rowKey:`archive:${e}`,block:"start"})}},[re,rp,sy]),sS=(0,i.useRef)(null),sC=(0,i.useRef)(rn),sN=(0,i.useRef)(null);(0,i.useEffect)(()=>{if(sC.current===rn)return;if(sC.current=rn,rn)return void rz(sS.current);let e=nE.current?.querySelector('[data-row-key="footer-archived"] button'),t=e&&e.getClientRects().length>0?e:sm();rz(t),t&&document.activeElement===t&&(sN.current=t)},[rn,sm]);let sE=(0,i.useRef)(null),s$=(0,i.useRef)(nv);(0,i.useLayoutEffect)(()=>{if(s$.current===nv)return;s$.current=nv;let e=sE.current;e&&(!e.isConnected||0===e.getClientRects().length)&&rz(sm())},[nv,sm]);let sI=e=>{if("ArrowLeft"!==e.key&&"ArrowRight"!==e.key&&"Home"!==e.key&&"End"!==e.key)return;e.preventDefault();let t="Home"===e.key?"sessions":"End"===e.key||"sessions"===ny?"files":"sessions";sy(t),("sessions"===t?nC:nN).current?.focus()},sM=(0,i.useCallback)((e,t)=>{sv({action:"set",ids:[e.root.id],pinned:t})},[sv]),sT=(0,i.useCallback)((e,t)=>{var n;if(t){let t=il.current.unreadMarks;ia([e.root.id,...K(e).filter(e=>t.has(e))])}let r=il.current.readAt,i=r&&Object.prototype.hasOwnProperty.call(r,e.root.id)?r[e.root.id]:void 0,s=(n=na.current.toServer(),void 0===i?n:Math.max(n,i+1));ni(n=>{let r=new Map(n);if(t)for(let t of K(e))r.delete(t);else r.set(e.root.id,s);return r})},[ia]),sR=(0,i.useCallback)(e=>{0!==e.length&&ni(t=>{let n=new Map(t);for(let[t,r]of e)t===r_.current||n.has(t)||n.set(t,r);return n.size===t.size?t:n})},[]),sA=(0,i.useCallback)(e=>{let t=e.filter(e=>!e.root.transient);if(0===t.length)return;let n=ir(t.map(e=>e.root.id)),r=t.flatMap(e=>K(e)),i=r.flatMap(e=>{let t=nr.get(e);return void 0!==t&&io.has(e)?[[e,t]]:[]});for(let e of F(t))sv({action:"set",ids:e.map(e=>e.root.id),archived:!0}).then(t=>{if(t||0===i.length)return;let n=new Set(e.flatMap(e=>K(e)));sR(i.filter(e=>{let[t]=e;return n.has(t)}))});i.length>0&&ni(e=>{let t=new Map(e);for(let e of r)t.delete(e);return t}),rV(1===t.length?eY("sidebar.archivedToast",{title:rL(n2(t[0].root),28)}):eY("sidebar.archivedManyToast",{count:t.length}),[{id:"undo",label:eY("sidebar.undo"),onClick:()=>{for(let e of F(n))sv({action:"restore",entries:e});sR(i),r5(()=>sg(t[0].root.id))}},{id:"view",label:eY("sidebar.viewArchive"),onClick:()=>sj()}])},[sv,r5,sg,sj,sR,rV,ir,eY,nr,io]),sL=(0,i.useCallback)(e=>{K(e).some(e=>t6.has(e))||sA([e])},[sA,t6]),sz=(0,i.useCallback)(e=>{if(0===e.length)return;let t=e.map(e=>e.root.id),n=ir(t);for(let e of F(t))sv({action:"set",ids:e,archived:!1});rV(1===e.length?eY("sidebar.restoredToast",{title:rL(n2(e[0].root),28)}):eY("sidebar.restoredManyToast",{count:e.length}),[{id:"undo",label:eY("sidebar.undo"),onClick:()=>{for(let e of F(n))sv({action:"restore",entries:e});r5(()=>sg(e[0].root.id))}}])},[sv,sg,r5,rV,ir,eY]),sP=(0,i.useCallback)(e=>sz([e]),[sz]),sW=(0,i.useCallback)(e=>{e.root.transient||(rw(null),rg(e.root.id))},[]),sO=(0,i.useCallback)(async(e,t)=>{let n=e.root,r=n2(n),i=t.trim();if(rg(e=>e===n.id?null:e),t!==r&&i!==(n.name??""))try{await fetch(`/api/sessions/${encodeURIComponent(n.id)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:i})}),ij()}catch{}},[ij]),sF=(0,i.useCallback)(e=>{rb(e.key)},[]),sD=(0,i.useCallback)(e=>{rb(t=>t===e?null:t),r5(()=>sx(e))},[r5,sx]),sB=(0,i.useCallback)((e,t)=>{sD(e.key);let n=function(e,t){let n=t.trim();if(n===e.name)return null;let r=""===n||n===J(e.root);return r&&null===e.customName?null:{action:"rename-project",projectKey:e.key,name:r?null:n}}(e,t);n&&sv(n)},[sv,sD]),sH=(0,i.useCallback)(async e=>{let t=e.root;if(!t.transient){rw(e=>e===t.id?null:e);try{await fetch(`/api/sessions/${encodeURIComponent(t.id)}`,{method:"DELETE"}),e$?.(t.id),ij()}catch{}}},[ij,e$]),s_=(0,i.useCallback)((e,t)=>{t?sH(e):(rg(null),rw(e.root.id))},[sH]),sU=(nv||"sessions"===ny)&&!rn&&!(t_&&""!==tV.trim()),sK=(0,i.useRef)(null),sq=(0,i.useRef)(null),sV=(0,i.useRef)(null);(0,i.useEffect)(()=>{w!==sq.current&&(sq.current=w,sK.current=w);let e=sK.current;if(!e||e9||!r9||!n9||!sU)return;sK.current=null;let t=sV.current;sV.current=null;let n=function(e,t){let n=c(e.sessions,t);if(!n||V(n,e.uiState,e.runningIds))return null;let r=Q(n);if(Z(n,e.uiState,e.runningIds))return{rowKey:`session:pinned:${n.root.id}`,projectKey:r,unfoldPinned:e.pinnedCollapsed,unfoldGroup:!1};let i=Object.hasOwn(e.groupExpansion,r)&&!1===e.groupExpansion[r];return{rowKey:`session:group:${n.root.id}`,projectKey:r,unfoldPinned:!1,unfoldGroup:i}}({sessions:eX,uiState:r6,runningIds:t6,groupExpansion:i9,pinnedCollapsed:n5},e);if(n){if(n.unfoldPinned&&(n6(!1),eS(!1)),n.unfoldGroup){let e={...nW};delete e[n.projectKey],e[n.projectKey]=!0,sf(e,[n.projectKey])}rO.current+=1,rW({id:rO.current,at:Date.now(),rowKey:n.rowKey,block:"nearest",...t?.sessionId===e?{takeFocusFrom:t.takeFocusFrom}:{}})}},[w,eX,r6,t6,i9,nW,n5,e9,r9,n9,sU,sf]);let sZ=(e,t)=>{if(sN.current=null,rn){let e=nE.current?.querySelector(".sidebar-sessions-view .session-tree-scroll");e&&nI.current.delete(e),rp(!1)}let n=t?`[data-row-key="${CSS.escape(t)}"]`:null;sV.current={sessionId:e.id,takeFocusFrom:e=>null!==n&&null!==e.closest(n)||e===sN.current},iq(e,void 0,void 0,{keepSidebarOpen:null!==t}),ij()},sJ=(0,i.useRef)(sZ);sJ.current=sZ;let sY=(0,i.useRef)(new Set),sG=(0,i.useCallback)(async e=>{let t=e.family.root;if(t.transient||sY.current.has(t.id))return;sY.current.add(t.id);let n=r_.current;try{var r;let i,s,o=await fetch(`/api/sessions/${encodeURIComponent(t.id)}/fork`,{method:"POST",headers:{"Content-Type":"application/json"},body:"{}"}),l=await o.json().catch(()=>({}));if(!o.ok||!l.session){let{key:e,params:t}=function(e,t){switch(e){case"not_found":return{key:"sidebar.forkNotFound"};case"unsaved":return{key:"sidebar.forkUnsaved"};case"empty":return{key:"sidebar.forkEmpty"};case"subagent":case"request-denied":return{key:"sidebar.forkUnavailable"};default:return{key:"sidebar.forkFailed",params:{error:t}}}}(l.code,l.error??`HTTP ${o.status}`);rV(eY(e,t)),"not_found"===l.code&&ij();return}let a=l.session,d=n2(a),{head:c,tail:u}=(r=eY("sidebar.forkedToast",{title:d}),((s=(i=eM(d)?.suffix)?r.lastIndexOf(i):-1)>0?{head:r.slice(0,s),tail:r.slice(s)}:null)??{head:eY("sidebar.forkedToast",{title:rL(d,28)}),tail:void 0});if(r_.current!==n){eQ(e=>e.some(e=>e.id===a.id)?e:[a,...e]);let e=na.current.toServer();ni(t=>new Map(t).set(a.id,e)),ij(),rV(c,[{id:"open",label:eY("sidebar.open"),onClick:()=>sJ.current(a,null)}],u);return}sJ.current(a,e.key),rV(c,[],u)}catch(e){rV(eY("sidebar.forkFailed",{error:e instanceof Error?e.message:String(e)}))}finally{sY.current.delete(t.id)}},[ij,rV,eY]),sX=(0,i.useCallback)(e=>{e.root.transient||window.open(p(e.root.id),"_blank","noopener,noreferrer")},[]),sQ=(0,i.useCallback)((e,t,n)=>{e.status.transient||rS({kind:"row",row:e,anchor:t,opener:n})},[]),s0=(0,i.useCallback)((e,t)=>{let n=e.family.root;if(n.id===rm||n.id===ry)return;if(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:window,n=new CustomEvent("pi-web:session-row-contextmenu",{cancelable:!0,detail:e});return!t.dispatchEvent(n)}({id:n.id,path:n.path,cwd:n.cwd,name:n.name,clientX:t.clientX,clientY:t.clientY,refresh:()=>{ij()}})){t.preventDefault(),t.stopPropagation();return}if(n.transient)return;t.preventDefault();let r=t.currentTarget instanceof HTMLElement?t.currentTarget:null,i=0===t.clientX&&0===t.clientY&&r?rP(r,"start"):{kind:"point",x:t.clientX,y:t.clientY},s=document.activeElement,o=s instanceof HTMLElement&&null!==r&&r.contains(s);r0.current=!o&&s instanceof HTMLElement&&s!==document.body?s:null,sQ(e,i,o?s:null)},[ry,ij,sQ,rm]),s1=(0,i.useMemo)(()=>({sessions:eX,uiState:r6,runningIds:t6,awaitingIds:t7,unreadIds:io,selectedSessionId:w}),[eX,r6,t6,t7,io,w]),s2=(0,i.useCallback)((e,t)=>{let n=eo(s1,e.key,6048e5,Date.now()).length;rS({kind:"group",project:e,olderCount:n,anchor:rP(t,"end"),opener:t})},[s1]),s4=(0,i.useCallback)(e=>{sA(eo(s1,e.key,6048e5,Date.now()).flatMap(e=>{let t=iX.get(e);return t?[t]:[]}))},[sA,iX,s1]),s8=(0,i.useCallback)((e,t)=>{rS(n=>n?.kind==="group"&&n.project.key===e?{...n,askDelete:t}:n)},[]),s3=(0,i.useRef)(new Set),s5=(0,i.useCallback)(async(e,t,n)=>{if(rS(null),!(0===t.length||s3.current.has(e))){s3.current.add(e),rV(eY("sidebar.deletingSessions"));try{let e=await eN(t,fetch);for(let t of e.deleted)e$?.(t);if(ij().then(()=>r5(n)),null!==e.error)return void rV(eY("sidebar.deleteFailed",{error:e.error}));let r=e.deletedRoots.length,i=[1===r?eY("sidebar.deletedOneToast"):eY("sidebar.deletedManyToast",{count:r})];e.running.length>0&&i.push(eY("sidebar.keptRunningToast",{count:e.running.length})),rV(i.join(" \xb7 "))}finally{s3.current.delete(e)}}},[r5,ij,e$,rV,eY]),s6=(0,i.useCallback)(e=>{let{ids:t}=el(s1,e.key);s5(`project:${e.key}`,t,()=>sx(e.key))},[s5,sx,s1]),s9=(0,i.useCallback)(e=>{let t=null===e?null:CSS.escape(`archive:${e}`),n=null===t?null:nE.current?.querySelector(`[data-row-key="${t}"] .session-tree-group-toggle`);if(n&&n.getClientRects().length>0)return n;let r=sS.current;return r&&r.getClientRects().length>0?r:sm()},[sm]),s7=(0,i.useCallback)(e=>e.flatMap(e=>{let t=iX.get(e);return t?[t]:[]}),[iX]),oe=(0,i.useCallback)((e,t)=>{rS({kind:"archive-group",project:e,anchor:rP(t,"end"),opener:t})},[]),ot=(0,i.useCallback)(e=>{rS(t=>t?.kind==="archive"?null:{kind:"archive",anchor:rP(e,"end"),opener:e})},[]),on=(0,i.useCallback)(e=>{rS(t=>t?.kind==="archive"?{...t,askDelete:e}:t?.kind==="archive-group"?{...t,askDelete:void 0!==e}:t)},[]),or=(0,i.useCallback)(e=>(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=[];for(let r of d(e.sessions))if((void 0===t.projectKey||Q(r)===t.projectKey)&&V(r,e.uiState,e.runningIds)){if(void 0!==t.archivedBefore){let n=_(H(e.uiState,r.root.id)?.archivedAt);if(null===n||n>=t.archivedBefore)continue}n.push(r.root.id)}return n})(s1,"all"===e?{}:"old"===e?{archivedBefore:Date.now()-2592e6}:e),[s1]),oi=(0,i.useCallback)(e=>{let t=or(e);s5("string"==typeof e?`archive:${e}`:`archive-project:${e.projectKey}`,t,()=>"string"==typeof e?s9(null):s9(e.projectKey))},[or,s9,s5]),os=(0,i.useCallback)(e=>{rt(e),ej(e)},[]),oo=(0,i.useCallback)(e=>{let t=sr.map(e=>e.project.key),n=re.filter(e=>!t.includes(e));os(e?n:[...n,...t])},[re,sr,os]),ol=(0,i.useCallback)((e,t)=>{let n=re.includes(e);if(t)return void oo(n);let r=re.filter(t=>t!==e);os(n?r:[...r,e])},[re,os,oo]),oa=(0,i.useCallback)(e=>{rS(null),iV(eT(e,ta))},[ta,iV]),od=(0,i.useCallback)(()=>rS(null),[]);(0,i.useEffect)(()=>{if(null!==rk)return;let e=r0.current;if(r0.current=null,!e?.isConnected)return;let t=document.activeElement;t&&t!==document.body||e.focus({preventScroll:!0})},[rk]);let oc=rn?sn:i7.rows;(0,i.useEffect)(()=>{rk?.kind!=="row"||oc.some(e=>e.key===rk.row.key)||rS(null),rk?.kind!=="archive-group"||oc.some(e=>e.key===`archive:${rk.project.key}`)||rS(null)},[rk,oc]);let ou=rk?.kind==="row"?oc.find(e=>"session"===e.kind&&e.key===rk.row.key)??rk.row:null,op=(0,i.useCallback)(e=>{iq(e.root)},[iq]),oh=(0,i.useCallback)(e=>{let t={...nW};for(let n of i7.projects)delete t[n.key],t[n.key]=e(n);sf(t,null)},[nW,i7.projects,sf]),of=(0,i.useCallback)((e,t)=>{let n=si.get(e);if(!n)return;let r=!Y(n,i9);if(t)return void oh(()=>r);let i={...nW};delete i[e],i[e]=r,sf(i,[e])},[nW,si,sf,oh,i9]),om=(0,i.useCallback)(e=>{let t=i7.rows.find(t=>"group-more"===t.kind&&t.projectKey===e||"pinned-more"===t.kind&&e===B);(t?.kind==="group-more"||t?.kind==="pinned-more")&&n3(n=>{var r;return r=t.nextShown,{...n,[e]:Math.max(er(n,e),Math.floor(r))}})},[i7.rows]),og=(0,i.useCallback)(e=>{n3(t=>ei(t,e))},[]),ox=(0,i.useCallback)(e=>{rG.current=e,rQ(e=>e+1),nv?sw(!1):sy("files")},[sw,nv,sy]),ov=nv?rh.open:"files"===ny;(0,i.useEffect)(()=>{let e=rG.current;e&&ov&&(rG.current=null,"project-list"===e?tS.current?.openMenu("project"):"file-search"===e?document.getElementById("file-search-input")?.focus({preventScroll:!0}):tS.current?.button("project")?.focus({preventScroll:!0}))},[ov,rX]);let ob=e=>{let{heading:t,headingTitle:n,notes:i,count:s,onConfirm:o,onCancel:l}=e;return(0,r.jsxs)("div",{className:"sidebar-menu-question",children:[(0,r.jsx)("div",{className:"sidebar-menu-header",title:n,children:t}),i.map(e=>(0,r.jsx)("p",{className:"sidebar-menu-question-text",children:e},e)),(0,r.jsxs)("div",{className:"sidebar-menu-question-buttons",children:[(0,r.jsx)("button",{type:"button",className:"sidebar-menu-question-confirm",disabled:0===s,onClick:o,children:eY("sidebar.deleteCount",{count:s})}),!eG&&(0,r.jsx)("button",{type:"button",className:"sidebar-menu-question-cancel","data-sidebar-menu-autofocus":"",onClick:l,children:eY("sidebar.cancel")})]})]})},oy=(e,t)=>ob({heading:t?eY("sidebar.deleteArchivedInProjectHeading",{name:t.name}):eY("old"===e?"sidebar.deleteOldArchivedHeading":"sidebar.deleteAllArchivedHeading"),headingTitle:t?.root,notes:[eY("sidebar.deleteArchivedMessage")],count:or(e).length,onConfirm:()=>oi(e),onCancel:()=>on(void 0)}),ow="",ok=null;if(rk?.kind==="row"&&ou)m=n2(ou.family.root),ow=eY("sidebar.sessionActions"),b=(function(e,t){if(t.transient)return[];let n={kind:"action",id:"open-new-tab",shortcut:"T"};return"archive"===e?[{kind:"action",id:"unarchive",shortcut:"A"},{kind:"action",id:"pin",shortcut:"P"},{kind:"action",id:"rename",shortcut:"R"},{kind:"action",id:"fork",shortcut:"F"},n,{kind:"separator"},{kind:"action",id:"delete",shortcut:"D"}]:[{kind:"action",id:"pinned"===e?"unpin":"pin",shortcut:"P"},{kind:"action",id:"rename",shortcut:"R"},{kind:"action",id:"fork",shortcut:"F"},{kind:"action",id:t.unread?"mark-read":"mark-unread",shortcut:"U"},t.running?{kind:"action",id:"archive",shortcut:"A",disabledReason:"running"}:{kind:"action",id:"archive",shortcut:"A"},n,{kind:"separator"},{kind:"action",id:"delete",shortcut:"D"}]})(ou.context,ou.status).map((e,t)=>{if("separator"===e.kind)return{type:"separator",id:`separator-${t}`};let n=eY(rT[e.id]);return{type:"item",id:e.id,label:"delete"===e.id?`${n}…`:n,icon:function(e){switch(e){case"open-new-tab":return(0,r.jsx)(nF,{});case"pin":return(0,r.jsx)(nL,{});case"unpin":return(0,r.jsx)(nz,{});case"rename":return(0,r.jsx)(nB,{});case"fork":return(0,r.jsx)(nO,{});case"mark-read":return(0,r.jsx)(n_,{});case"mark-unread":return(0,r.jsx)(nH,{});case"archive":return(0,r.jsx)(nR,{});case"unarchive":return(0,r.jsx)(nA,{});case"delete":return(0,r.jsx)(nD,{})}}(e.id),shortcut:e.shortcut,danger:"delete"===e.id,disabled:void 0!==e.disabledReason,disabledReason:"running"===e.disabledReason?eY("sidebar.cannotArchiveRunning"):void 0,onSelect:t=>{let{shiftKey:n}=t;return((e,t,n)=>{let{family:r}=t;switch(e){case"open-new-tab":sX(r);break;case"pin":sM(r,!0);break;case"unpin":sM(r,!1);break;case"rename":sW(r);break;case"fork":sG(t);break;case"mark-read":sT(r,!0);break;case"mark-unread":sT(r,!1);break;case"archive":sL(r);break;case"unarchive":sP(r);break;case"delete":s_(r,n)}})(e.id,ou,n)}}});else if(rk?.kind==="group"){let e,t,i,o,l,a=si.get(rk.project.key)??rk.project;m=a.name,ow=eY("sidebar.projectActions",{name:a.name}),n=a,s=rk.olderCount,e=iQ.countByProject.get(n.key)??0,t=el(s1,n.key),i=ea(i7.projects,n.key,"up"),o=ea(i7.projects,n.key,"down"),l=(null===n.customName?["rename-project"]:["rename-project","reset-project-name"]).map(e=>"rename-project"===e?{type:"item",id:e,label:eY("sidebar.renameProject"),icon:(0,r.jsx)(nB,{}),onSelect:()=>sF(n)}:{type:"item",id:e,label:eY("sidebar.resetProjectName"),icon:(0,r.jsx)(nA,{}),onSelect:()=>{sv({action:"rename-project",projectKey:n.key,name:null})}}),b=[{type:"item",id:"pin-project",label:eY(n.pinned?"sidebar.unpinProject":"sidebar.pinProject"),icon:n.pinned?(0,r.jsx)(nz,{}):(0,r.jsx)(nL,{}),onSelect:()=>{sv({action:"pin-project",projectKey:n.key,root:n.root,pinned:!n.pinned})}},...l,{type:"item",id:"open-in-files",label:eY("sidebar.openInFilesTab"),icon:(0,r.jsx)(nq,{}),onSelect:()=>{n.current||td(n.root),ox("project-button")}},{type:"item",id:"open-new-tab",label:eY("sidebar.openInNewTab"),icon:(0,r.jsx)(nF,{}),shortcut:"T",onSelect:()=>(e=>{let{cwd:t}=eT(e,ta);window.open(`?cwd=${encodeURIComponent(t)}`,"_blank","noopener,noreferrer")})(n)},{type:"separator",id:"separator-layout"},{type:"item",id:"move-up",label:eY("sidebar.moveProjectUp"),icon:(0,r.jsx)(nP,{className:"sidebar-icon-up"}),disabled:null===i,onSelect:()=>{i&&sb(n.key,i.anchorKey,i.position)}},{type:"item",id:"move-down",label:eY("sidebar.moveProjectDown"),icon:(0,r.jsx)(nP,{className:"sidebar-icon-down"}),disabled:null===o,onSelect:()=>{o&&sb(n.key,o.anchorKey,o.position)}},{type:"item",id:"collapse-others",label:eY("sidebar.collapseOtherGroups"),icon:(0,r.jsx)(nP,{}),disabled:i7.projects.every(e=>Y(e,i9)===(e.key===n.key)),onSelect:()=>oh(e=>e.key===n.key)},{type:"item",id:"expand-all",label:eY("sidebar.expandAllGroups"),icon:(0,r.jsx)(nP,{className:"sidebar-icon-down"}),disabled:i7.projects.every(e=>Y(e,i9)),onSelect:()=>oh(()=>!0)},{type:"separator",id:"separator-sessions"},{type:"item",id:"archive-older",label:eY("sidebar.archiveOlderThanWeek",{count:s}),icon:(0,r.jsx)(nR,{}),disabled:0===s,onSelect:()=>s4(n)},{type:"item",id:"view-archived",label:eY("sidebar.viewArchived",{count:e}),icon:(0,r.jsx)(nR,{}),disabled:0===e,onSelect:()=>sj(n.key)},{type:"item",id:"delete-all",label:eY("sidebar.deleteProjectSessions",{count:t.ids.length}),icon:(0,r.jsx)(nD,{}),danger:!0,disabled:0===t.ids.length,onSelect:e=>{let{keepOpen:t}=e;t(),s8(n.key,!0)}}],rk.askDelete&&(ok=(e=>{let{ids:t,running:n}=el(s1,e.key);return ob({heading:eY("sidebar.deleteProjectSessionsHeading",{name:e.name}),headingTitle:e.root,notes:[eY("sidebar.deleteProjectSessionsMessage"),...n>0?[eY("sidebar.deleteProjectSessionsRunning",{count:n})]:[]],count:t.length,onConfirm:()=>s6(e),onCancel:()=>s8(e.key,!1)})})(a)),g=264}else if(rk?.kind==="archive-group"){let e,t=sr.find(e=>e.project.key===rk.project.key)?.project??rk.project;m=t.name,ow=eY("sidebar.archivedProjectActions",{name:t.name}),b=[{type:"item",id:"restore-all",label:eY("sidebar.restoreAllArchived",{count:(e=or({projectKey:t.key})).length}),icon:(0,r.jsx)(nA,{}),disabled:0===e.length,onSelect:()=>sz(s7(e))},{type:"separator",id:"separator-delete"},{type:"item",id:"delete-all",label:eY("sidebar.deleteAllArchived",{count:e.length}),icon:(0,r.jsx)(nD,{}),danger:!0,disabled:0===e.length,onSelect:e=>{let{keepOpen:t}=e;t(),on("all")}}],rk.askDelete&&(ok=oy({projectKey:t.key},t)),g=248}else if(rk?.kind==="archive"){let e,t,n;m=eY("sidebar.archived"),ow=eY("sidebar.archiveActions"),e=or("all"),t=or("old"),n=sr.filter(e=>!e.expanded).length,b=[{type:"item",id:"collapse-all",label:eY("sidebar.collapseAllGroups"),icon:(0,r.jsx)(nP,{}),disabled:n===sr.length,onSelect:()=>oo(!1)},{type:"item",id:"expand-all",label:eY("sidebar.expandAllGroups"),icon:(0,r.jsx)(nP,{className:"sidebar-icon-down"}),disabled:0===n,onSelect:()=>oo(!0)},{type:"separator",id:"separator-sessions"},{type:"item",id:"restore-all",label:eY("sidebar.restoreAllArchived",{count:e.length}),icon:(0,r.jsx)(nA,{}),disabled:0===e.length,onSelect:()=>sz(s7(e))},{type:"item",id:"delete-old",label:eY("sidebar.deleteOldArchived",{count:t.length}),icon:(0,r.jsx)(nD,{}),danger:!0,disabled:0===t.length,onSelect:e=>{let{keepOpen:t}=e;t(),on("old")}},{type:"item",id:"delete-all",label:eY("sidebar.deleteAllArchived",{count:e.length}),icon:(0,r.jsx)(nD,{}),danger:!0,disabled:0===e.length,onSelect:e=>{let{keepOpen:t}=e;t(),on("all")}}],rk.askDelete&&(ok=oy(rk.askDelete,null)),g=280}let oj={layout:eG?"mobile":"desktop",loading:e9||!r9,error:to,renamingRootId:rm,renamingProjectKey:rv,confirmDeleteRootId:ry,activeMenuRowKey:rk?.kind==="row"?rk.row.key:rk?.kind==="group"?`group:${rk.project.key}`:rk?.kind==="archive-group"?`archive:${rk.project.key}`:null,onSelectFamily:op,onToggleGroup:of,onShowMore:om,onShowLess:og,onTogglePinned:()=>{let e=!n5;n6(e),eS(e),e&&n3(e=>ei(e,B))},onArchiveFamily:sL,onRestoreFamily:sP,onOpenRowMenu:sQ,onRowContextMenu:s0,onRenameCommit:(e,t)=>{sO(e,t)},onRenameCancel:()=>rg(null),onRenameProjectCommit:sB,onRenameProjectCancel:()=>{rv&&sD(rv)},onDeleteConfirm:e=>{sH(e)},onDeleteCancel:()=>{rw(null),ry&&r5(()=>sg(ry))},onGroupNew:oa,onGroupMenu:s2,onPinEmptyGroup:e=>{sv({action:"pin-project",projectKey:e.key,root:e.root,pinned:!0}),r5(()=>sx(e.key))},onToggleArchiveGroup:ol,onArchiveGroupMenu:oe,onOpenOtherProject:()=>{ox("project-list")},onOpenArchive:()=>sj(),onMoveGroup:sb},oS=ta??eI??null,oC=oS&&tJ>0?eY("sidebar.changedFiles",{count:tJ}):void 0,oN=(0,i.useRef)(null),oE=!oS||0===tJ;(0,i.useLayoutEffect)(()=>{let e=oN.current;if(oE&&e&&sE.current===e){var t,n;let r;t=document,n=sm(),(r=function(e){let t=e=>e?.tagName==="BUTTON"&&!e.disabled;for(let n=e.nextElementSibling;n;n=n.nextElementSibling)if(t(n))return n;for(let n=e.previousElementSibling;n;n=n.previousElementSibling)if(t(n))return n;return null}(e)??n)&&t.activeElement===e?r.focus({preventScroll:!0}):e_(t,r)}},[oE,sm]);let o$=nv||"sessions"===ny,oI=!nv&&"files"===ny&&null!==oS,oM=(t=(nv?["below",eY("sidebar.new")]:["tabs",eY("sidebar.tabSessions"),eY("sidebar.tabFiles"),eY("sidebar.new"),oS&&tJ>0?tJ:"",ny]).join("\n"),f=(0,i.useCallback)(()=>{let e=ic.current;if(e){for(let t of["0","1","2"])if(e.dataset.fit=t,e.scrollWidth<=e.clientWidth)return}},[ic]),(0,i.useLayoutEffect)(()=>{let e=ic.current;if(!e)return;f();let t=new ResizeObserver(f);return t.observe(e),()=>t.disconnect()},[ic,f,t]),f),oT=i7.archivedCount,oR=nv?13:14,oA=(0,r.jsx)(rI,{onClick:()=>{oS&&ez?.(oS)},disabled:!oS||!ez,title:eY("terminal.open"),children:(0,r.jsx)(nZ,{size:oR})}),oL=(0,r.jsx)(rI,{onClick:()=>{iC().then(e=>{e&&nv&&sw(!1)})},disabled:!oS||iE,title:iE?eY(t4?.reason==="remote"?"sidebar.openInExplorerRemoteOnly":"sidebar.openInExplorerUnsupported"):iN,children:(0,r.jsx)(nq,{size:oR})}),oz=(0,r.jsx)(rI,{onClick:()=>{nv&&nj&&sw(!1),ng.current?.openUploadPicker()},disabled:!oS||tF,title:eY("sidebar.uploadFilesTitle"),children:(0,r.jsx)(nY,{size:oR})}),oP=(0,r.jsx)(rI,{onClick:()=>{eH?eH():tO(e=>e+1),t2(!0),nm.current&&clearTimeout(nm.current),nm.current=setTimeout(()=>t2(!1),2e3)},disabled:!oS,title:eY("sidebar.refreshExplorer"),done:t1,children:t1?(0,r.jsx)(nU,{size:oR}):(0,r.jsx)(nG,{size:oR})}),oW=e=>(0,r.jsx)(rI,{onClick:()=>{let e=!tQ;t0(e),function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:ey();if(t)try{t.setItem(em,String(e))}catch{}}(e)},disabled:!oS,title:eY("sidebar.showIgnoredFiles"),pressed:tQ,className:e,children:(0,r.jsx)(nQ,{size:oR})}),oO=(0,r.jsx)(rI,{ref:oN,onClick:()=>{if(nv&&nj){sw(!1),tX(!1);return}tX(e=>!e)},disabled:oE,title:eY("sidebar.changedFiles",{count:tJ}),pressed:!oE&&!tG,children:(0,r.jsx)(nX,{size:oR})});return(0,r.jsxs)("div",{ref:iw,className:`session-sidebar${nv?" is-files-below":""}${nv&&nj?" is-files-collapsed":""}${nv&&rh.moving?" is-files-folding":""}${rU?" has-toast":""}`,style:{"--sidebar-files-height":`${ib.width}px`},onFocus:e=>{sE.current=e.target},onBlur:e=>{(null!==e.relatedTarget||document.hasFocus())&&(e.currentTarget.contains(e.relatedTarget)||(sE.current=null))},children:[tp&&(0,r.jsx)(tK,{initialPath:tg,busy:ty,error:tv,onCancel:()=>{let e="new-session"===tp?r2.current:null;r1.current=null,r2.current=null,th(!1),tb(null),e&&r5(()=>e.isConnected?e:null)},onSelect:e=>void iO(e)}),(0,r.jsxs)("div",{ref:ic,className:"sidebar-header",children:[nv&&(0,r.jsx)(nk,{onWidthChange:oM}),!nv&&(0,r.jsxs)("div",{className:"sidebar-tabs-list",role:"tablist","aria-label":eY("sidebar.tabsLabel"),children:[(0,r.jsxs)("button",{ref:nC,type:"button",role:"tab",id:"session-sidebar-tab-sessions","aria-selected":"sessions"===ny,"aria-controls":"session-sidebar-panel-sessions",tabIndex:"sessions"===ny?0:-1,className:`sidebar-tab${"sessions"===ny?" is-selected":""}`,onClick:()=>sy("sessions"),onKeyDown:sI,children:[(0,r.jsx)(n0,{size:13,className:"sidebar-tab-icon"}),(0,r.jsx)("span",{className:"sidebar-tab-label",children:eY("sidebar.tabSessions")})]}),(0,r.jsxs)("button",{ref:nN,type:"button",role:"tab",id:"session-sidebar-tab-files","aria-selected":"files"===ny,"aria-controls":"session-sidebar-panel-files",tabIndex:"files"===ny?0:-1,title:oC,className:`sidebar-tab${"files"===ny?" is-selected":""}`,onClick:()=>sy("files"),onKeyDown:sI,children:[(0,r.jsx)(nq,{size:13,className:"sidebar-tab-icon"}),(0,r.jsx)("span",{className:"sidebar-tab-label",children:eY("sidebar.tabFiles")}),oS&&tJ>0&&(0,r.jsx)("span",{className:"sidebar-tab-count","aria-hidden":"true",children:tJ})]})]}),(0,r.jsx)("span",{className:"sidebar-header-spacer"}),(0,r.jsxs)("button",{type:"button",className:"sidebar-new-button",onClick:iJ,disabled:!ta,title:ta?eY("sidebar.newSessionTitle",{path:ta}):eY("sidebar.selectProject"),children:[(0,r.jsx)(nM,{size:12}),(0,r.jsx)("span",{className:"sidebar-new-label",children:eY("sidebar.new")})]}),(0,r.jsx)("button",{ref:ip,type:"button",onClick:()=>{if(oI)return void tH(e=>!e);if(!o$){sy("sessions"),tU(!0);return}tU(e=>!e)},title:oI?eY("sidebar.searchFiles"):eY("sidebar.toggleSessionSearch"),"aria-label":oI?eY("sidebar.searchFiles"):eY("sidebar.toggleSessionSearch"),"aria-expanded":oI?tB:t_,"aria-controls":oI?"file-search-input":"session-search-input",className:`sidebar-search-toggle${(oI?tB:t_)?" is-active":""}`,children:(0,r.jsx)(nJ,{size:16})})]}),(0,r.jsxs)("div",{ref:nE,id:"session-sidebar-panel-sessions",role:nv?"region":"tabpanel","aria-label":nv?eY("sidebar.tabSessions"):void 0,"aria-labelledby":nv?void 0:"session-sidebar-tab-sessions",hidden:!nv&&"sessions"!==ny,className:"sidebar-panel sidebar-sessions-panel",onScrollCapture:sk,children:[t_&&(0,r.jsx)("div",{className:"sidebar-search",children:(0,r.jsx)("input",{id:"session-search-input",type:"search",autoFocus:!0,value:tV,maxLength:200,"aria-label":eY("sidebar.searchSessions"),placeholder:eY("sidebar.searchSessions"),onChange:e=>tZ(e.target.value),onKeyDown:e=>{"Escape"!==e.key||e.nativeEvent.isComposing||229===e.keyCode||(e.stopPropagation(),tZ(""))},className:"sidebar-search-input"})}),(0,r.jsx)(rC,{open:t_,query:tV,selectedSessionId:w,onSelectSession:iq,onSelectSideChat:j,sessions:eX,archivedSessionIds:iQ.ids,projectNames:sa,children:(0,r.jsxs)("div",{className:"sidebar-sessions-views",children:[(0,r.jsx)("div",{className:"sidebar-sessions-view",hidden:rf.mainHidden,inert:rf.mainInert,children:(0,r.jsx)(n8,{...oj,rows:i7.rows,emptyLabel:eY("sidebar.noSessions"),reveal:rN,onRevealHandled:rF})}),rf.archiveMounted&&(0,r.jsxs)("div",{className:`sidebar-sessions-view sidebar-archive-view${rf.archiveClass?` ${rf.archiveClass}`:""}`,inert:rf.archiveInert,onAnimationEnd:e=>{e.target===e.currentTarget&&rd()},children:[(0,r.jsxs)("div",{className:"sidebar-archive-bar",children:[(0,r.jsxs)("button",{ref:sS,type:"button",className:"sidebar-archive-back",title:eY("sidebar.backToSessions"),"aria-label":`${eY("sidebar.backToSessions")}: ${eY("sidebar.archivedCount",{count:oT})}`,onClick:()=>rp(!1),children:[(0,r.jsx)(nP,{size:13,className:"sidebar-icon-back"}),(0,r.jsx)("span",{children:eY("sidebar.archived")}),(0,r.jsxs)("span",{className:"sidebar-archive-count",children:["\xb7 ",oT]})]}),(0,r.jsx)("button",{type:"button",className:`sidebar-archive-menu-button${rk?.kind==="archive"?" is-active":""}`,title:eY("sidebar.archiveActions"),"aria-label":eY("sidebar.archiveActions"),"aria-haspopup":"menu","aria-expanded":rk?.kind==="archive",disabled:0===sr.length,onClick:e=>ot(e.currentTarget),children:(0,r.jsx)(nT,{size:13})})]}),(0,r.jsx)(n8,{...oj,rows:sn,emptyLabel:eY("sidebar.noArchived"),reveal:rD,onRevealHandled:rH})]})]})})]}),nv&&rh.open&&(0,r.jsx)("div",{...ib.separatorProps,"aria-controls":"session-sidebar-panel-files",className:`panel-resize-handle sidebar-files-resize-handle${ib.isResizing?" is-resizing":""}`,"data-resize-handle":"sidebar-files",title:`${eY("sidebar.resizeFiles")}: ${eY("sidebar.resizeFilesHint")}`}),(0,r.jsxs)("div",{ref:n$,id:"session-sidebar-panel-files",role:nv?"region":"tabpanel","aria-label":nv?eY("sidebar.tabFiles"):void 0,"aria-labelledby":nv?void 0:"session-sidebar-tab-files",hidden:!nv&&"files"!==ny,className:"sidebar-panel sidebar-files-panel",onScrollCapture:sk,onTransitionEnd:e=>{e.target===e.currentTarget&&"height"===e.propertyName&&ro()},children:[nv&&(0,r.jsxs)("div",{className:"sidebar-files-section",children:[(0,r.jsxs)("button",{type:"button",className:"sidebar-files-section-toggle","aria-expanded":!nj,"aria-controls":"session-sidebar-files-body",title:oC,onClick:()=>sw(!nj),children:[(0,r.jsx)(nP,{size:12,strokeWidth:3,className:`session-tree-chevron${nj?"":" is-open"}`}),(0,r.jsx)("span",{className:"sidebar-files-section-label",children:eY("sidebar.tabFiles")}),oC&&(0,r.jsxs)("span",{className:"sidebar-files-section-count","aria-hidden":"true",children:["\xb7 ",tJ]})]}),(0,r.jsxs)("div",{className:"sidebar-files-keys",role:"group","aria-label":eY("sidebar.fileActions"),children:[oA,oL,oz,oP,oW(),oO,(0,r.jsx)(rI,{onClick:()=>{if(nj){tH(!0),ox("file-search");return}tH(e=>!e)},disabled:!oS,title:eY("sidebar.searchFiles"),expanded:tB,controls:"file-search-input",children:(0,r.jsx)(nJ,{size:13})})]})]}),(0,r.jsxs)("div",{id:"session-sidebar-files-body",className:"sidebar-files-body",hidden:nv&&rh.bodyHidden,inert:nv&&rh.bodyInert,children:[(0,r.jsxs)("div",{className:"sidebar-files-head",children:[(0,r.jsx)(rj,{handleRef:tS,layout:nv?"row":"stacked",context:sc??{project:null,worktrees:null,currentWorktreePath:null,projects:sd},mobile:eG,label:eY("sidebar.projectAndWorktree"),placeholder:D&&!iI.current?"":eY("sidebar.selectProject"),homeDir:tc,projectActivity:i0,worktreeHint:i8,newWorktreeTitle:eY("sidebar.createWorktreeTitle"),onPick:iK,onUseDefaultDirectory:()=>{iD()},onOpenFolder:iF,onRefreshWorktrees:iU,onCreateWorktree:iH,onRemoveWorktree:i_}),!nv&&oS&&(0,r.jsxs)("div",{className:"sidebar-files-actions",role:"group","aria-label":eY("sidebar.fileActions"),children:[ez&&oA,oL,oz,oP,oW("sidebar-files-views-start"),oO]})]}),oS&&i$&&(0,r.jsxs)("div",{role:"alert",className:"sidebar-files-error",children:[(0,r.jsx)("span",{className:"sidebar-files-error-text",children:i$}),(0,r.jsx)(tq,{onClick:()=>t5(null),title:eY("files.dismissError")})]}),(0,r.jsx)("div",{ref:iu,className:"sidebar-files-scroll scrollbar-subtle",children:oS&&(0,r.jsx)(nb,{ref:ng,cwd:oS,onOpenFile:eL??(()=>{}),refreshKey:tW,onAtMention:eU,onAtMentions:eK,onUploadBusyChange:tD,changesCollapsed:tG,onChangesCountChange:tY,fileSearchOpen:tB,onFileSearchOpenChange:tH,showHidden:tQ})})]})]}),(0,r.jsx)(rx,{open:null!==rk,anchor:rk?.anchor??null,sheet:eG,ariaLabel:ow,title:m,items:b,cancelLabel:eY("sidebar.cancel"),focusCancel:null!==ok,onClose:od,returnFocusTo:rk?.opener??null,width:g,children:ok}),(0,r.jsx)(rE,{toast:rU,onDismiss:()=>rK(null),dismissLabel:eY("sidebar.dismiss")})]})}var rO=n(5772);let rF=/\x1B(?:\][^\x07\x1B]*(?:\x07|\x1B\\)|\[[0-?]*[ -/]*[@-~]|[@-Z\\-_])/g,rD=/^\x1B(?:\][^\x07\x1B]*(?:\x07|\x1B\\)|\[[0-?]*[ -/]*[@-~]|[@-Z\\-_])/,rB=/\x1B_pi:[^\x07\x1B\n]*(?:\x07|\x1B\\)/g;function rH(e){return e.replace(rB,"").replace(rF,"")}function r_(e){let t=[],n=0;for(;n<e.length;){if(27===e.charCodeAt(n)){let t=e.slice(n).match(rD);if(t){n+=t[0].length;continue}}let r=e.codePointAt(n);if(void 0===r)break;let i=String.fromCodePoint(r);t.push({start:n,end:n+i.length,char:i}),n+=i.length}return t}function rU(e,t){let n=r_(e)[t];return n?e.slice(0,n.start)+e.slice(n.end):e}function rK(e){return r_(e)[0]?.char}let rq=/[▀-▟]/,rV=/https?:\/\/(?:\[[0-9A-Fa-f:.]+\])?[^\s<>"'`\]}。,、;:!?)」』】]*/gi,rZ=/^[.,;:!?]$/,rJ={ArrowUp:"\x1b[A",ArrowDown:"\x1b[B",ArrowRight:"\x1b[C",ArrowLeft:"\x1b[D",Home:"\x1b[H",End:"\x1b[F",Insert:"\x1b[2~",Delete:"\x1b[3~",PageUp:"\x1b[5~",PageDown:"\x1b[6~",Escape:"\x1b",Backspace:""},rY={ArrowLeft:"\x1bb",ArrowRight:"\x1bf",ArrowUp:"\x1bp",ArrowDown:"\x1bn"};function rG(e){return"custom"===e.role&&!e.display}function rX(e){return"user"===e.role||"custom"===e.role&&!rG(e)&&("compaction"===e.customType||"pi-web:subagent-notification"===e.customType||"subagent-notification"===e.customType)}function rQ(e){return"user"===e.role||"assistant"===e.role||"toolResult"===e.role}function r0(e,t){return"assistant"===e.role||t&&!rG(e)}function r1(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return"thinking"===e.type&&!e.deferred&&!t.isStreaming&&""===e.thinking.trim()}function r2(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return(e.content??[]).filter(e=>!r1(e,t))}function r4(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return t.isStreaming||"error"!==e.stopReason?null:e.errorMessage?.trim()||"Unknown provider error"}function r8(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return!t.isStreaming&&"aborted"===e.stopReason}function r3(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return!t.isStreaming&&"length"===e.stopReason}function r5(e){return(e.content??[]).some(e=>"text"===e.type?e.text.trim().length>0:"image"===e.type||"toolCall"===e.type)}function r6(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=r2(e,t),r=n.findLastIndex(e=>"text"!==e.type&&"image"!==e.type);return -1===r?{answerBlocks:n,processBlocks:[]}:{answerBlocks:n.slice(r+1),processBlocks:n.slice(0,r+1)}}function r9(e){return!e.defaultPrevented&&0===e.button&&!e.shiftKey&&!e.altKey}function r7(e){try{return decodeURIComponent(e)}catch{return e}}function ie(e){return/^[a-zA-Z]:[\\/]/.test(e)||e.startsWith("\\\\")?e.replace(/\\/g,"/"):e}function it(e){return!!e&&(/^[a-zA-Z]:[\\/]/.test(e)||e.startsWith("\\\\"))}let ir=/^\/(?:mnt\/|cygdrive\/)?([a-zA-Z])(?:\/(.*))?$/;function ii(e){if(!e.startsWith("/")||e.startsWith("//"))return e;let t=e.match(ir);if(!t)return e;let[,n,r]=t;return`${n.toUpperCase()}:/${r??""}`}function is(e){let t=ie(e),n=/^[a-zA-Z]:\//.test(t),r=t.startsWith("//"),i=t.startsWith("/")&&!n&&!r,s=n?1:2*!!r,o=[];for(let e of t.split("/"))if(e&&"."!==e){if(".."===e){o.length>s&&".."!==o[o.length-1]?o.pop():i||n||r||o.push(e);continue}o.push(e)}let l=o.join("/");return n?1===o.length?`${l}/`:l:r?`//${l}`:i?`/${l}`:l}function io(e,t){let n,r,i,s,o,l=arguments.length>2&&void 0!==arguments[2]?arguments[2]:t;if(!e)return null;let a=e.split("#",1)[0].split("?",1)[0].trim();if(!a)return null;let d=null,c=null,u=r7(a),p=u.startsWith("\\\\"),h=ie(u),f=h.toLowerCase();if(f.startsWith("/api/")||f.startsWith("/_next/")||!p&&h.startsWith("//")||/^[a-zA-Z][a-zA-Z0-9+.-]*:/i.test(h)&&!f.startsWith("file:")&&!/^[a-zA-Z]:\//.test(h))return null;if(f.startsWith("file:")?c=(d=function(e){try{let t=new URL(e);if("file:"!==t.protocol)return null;let n=r7(t.pathname);if(t.hostname)return`//${t.hostname}${n.startsWith("/")?n:`/${n}`}`;if(/^\/[a-zA-Z]:\//.test(n))return n.slice(1);return n}catch{return null}}(a))?"absolute":null:/^[a-zA-Z]:\//.test(h)?(d=h,c="absolute"):h.startsWith("/")?(d=it(t)?ii(h):h,c="absolute"):t&&!(h.startsWith("#")||h.startsWith("?"))&&(h.startsWith("./")||h.startsWith("../")||h.includes("/")||/(^|\/)\.?[^/]+\.[^/.]+$/.test(h))&&(d=`${ie(t).replace(/\/+$/,"")}/${h}`,c="relative"),!d)return null;let m=is(d).replace(/:\d+(?:(?::|-)\d+)?$/,"");return"relative"===c&&l&&(n=is(m).replace(/\/+$/,""),r=is(l).replace(/\/+$/,""),s=(i=/^[a-zA-Z]:\//.test(n)||/^[a-zA-Z]:\//.test(r))?n.toLowerCase():n,!(s===(o=i?r.toLowerCase():r)||s.startsWith(`${o}/`)))?null:m}let il=/^page=(\d+)$/i;function ia(e){if(!e)return null;let t=e.indexOf("#");if(-1===t)return null;let n=e.slice(t+1).trim().match(il);if(!n)return null;let r=Number.parseInt(n[1],10);return Number.isInteger(r)&&r>0?r:null}function id(e){let t=e.toLowerCase();return"write"===t||t.startsWith("write_")||t.endsWith(".write")||t.endsWith("_write")}function ic(e){let t=e.toLowerCase();return"edit"===t||t.startsWith("edit_")||t.endsWith(".edit")||t.endsWith("_edit")||t.includes("str_replace")||t.includes("replace_editor")}function iu(e){let t=e.toLowerCase();return"apply_patch"===t||t.startsWith("apply_patch_")||t.endsWith(".apply_patch")||t.endsWith("_apply_patch")}function ip(e,t){if(e&&"object"==typeof e&&!Array.isArray(e)){let t=e.input;if("string"==typeof t&&t.length>0)return t}return"string"==typeof t?t:""}function ih(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function im(e){if(!ih(e)||!ih(e.result))return!1;let t=e.result.failures;return Array.isArray(t)&&t.length>0}function ig(){let e=[],t=[],n=[],r=()=>({lineNo:null,text:"",type:"empty"}),i=()=>{let i=Math.max(t.length,n.length);for(let s=0;s<i;s++)e.push({type:"line",left:t[s]??r(),right:n[s]??r()});t=[],n=[]};return{rows:e,context(t,n){i(),e.push({type:"line",left:{lineNo:n,text:t,type:"context"},right:{lineNo:n,text:t,type:"context"}})},removed(e,n){t.push({lineNo:n,text:e,type:"removed"})},added(e,t){n.push({lineNo:t,text:e,type:"added"})},gap(){i(),e.length>0&&"gap"!==e[e.length-1].type&&e.push({type:"gap",count:null})},finish(){i(),e.length>0&&"gap"===e[e.length-1].type&&e.pop()}}}function ix(e){if(!e.includes("*** Begin Patch")&&!/\*\*\* (?:Add|Delete|Update) File: /.test(e))return null;let t=[],n=null,r=null,i=null;for(let s of e.split(/\r?\n/)){let e=s.match(/^\*\*\* (Add|Delete|Update) File: (.+)$/);if(e){let s=e[1]?.toLowerCase()??"update",o=(e[2]??"").trim();n?.finish(),i=s,r={oldPath:"add"===s?void 0:o,newPath:"delete"===s?void 0:o,rows:(n=ig()).rows},t.push(r);continue}if(/^\*\*\* Move to: /.test(s)){let e=s.replace(/^\*\*\* Move to: /,"").trim();r&&"update"===i&&(r.newPath=e);continue}if(!n||!r)continue;let o=n;if(!s.startsWith("*** ")){if("update"===i&&s.startsWith("@@")){o.gap();continue}if("update"===i){let e=s[0],t=s.slice(1);"+"===e?o.added(t,null):"-"===e?o.removed(t,null):" "===e?o.context(t,null):""!==s&&o.context(s,null)}else if("add"===i){if(""===s)continue;n.added(s.startsWith("+")?s.slice(1):s,null)}else if("delete"===i){if(""===s)continue;n.removed(s.startsWith("-")?s.slice(1):s,null)}}}n?.finish();let s=t.filter(e=>e.rows.length>0);return s.length>0?s:null}function iv(e){if(!e||"object"!=typeof e||Array.isArray(e))return null;let t=e.files;if(!Array.isArray(t))return null;let n=[];for(let e of t){if(!e||"object"!=typeof e||Array.isArray(e)||"string"!=typeof e.filePath||"string"!=typeof e.diff)continue;let t=ig();for(let n of e.diff.split(/\r?\n/)){let e=n.match(/^([+\- ])\s*(\d+) (.*)$/);if(!e)continue;let[,r,i,s]=e,o=Number(i);"+"===r?t.added(s,o):"-"===r?t.removed(s,o):t.context(s,o)}t.finish();let r="add"===e.operation,i="delete"===e.operation;n.push({oldPath:r?void 0:e.filePath,newPath:i?void 0:e.movePath??e.filePath,rows:t.rows})}let r=n.filter(e=>e.rows.length>0);return r.length>0?r:null}function ib(e){return e?e.map(e=>e.newPath).filter(e=>"string"==typeof e&&e.length>0):[]}function iy(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r={...e,content:t};return n.omitUsage&&(r.usage=void 0),n.omitStop&&(r.stopReason=void 0,r.errorMessage=void 0),r}function iw(e){return"number"==typeof e&&Number.isFinite(e)&&e>=0?e:void 0}function ik(e){let t=Math.max(0,Math.floor(e/1e3));if(t<60)return`${t}s`;let n=Math.floor(t/60),r=t%60;return n<60?`${n}m ${r}s`:`${Math.floor(n/60)}h ${n%60}m ${r}s`}function ij(e){let t=e.trim().split("\n").map(e=>`> ${e}`).join("\n");return`${t}
|
|
4
4
|
|
|
5
|
-
`}function iS(e){return!e.trim()||e.endsWith("\n\n")?"":e.endsWith("\n")?"\n":"\n\n"}var iC=n(32316);function iN(e){if(navigator.clipboard?.writeText)return navigator.clipboard.writeText(e);let t=document.activeElement,n=null;try{return(n=document.createElement("textarea")).value=e,n.style.position="fixed",n.style.opacity="0",document.body.appendChild(n),n.select(),document.execCommand("copy")?Promise.resolve():Promise.reject(Error("Copy was refused"))}catch(e){return Promise.reject(e)}finally{n?.remove(),t?.isConnected&&t instanceof HTMLElement&&t.focus({preventScroll:!0})}}let iE={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"},i$={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"},iI={mp4:"video/mp4",m4v:"video/mp4",webm:"video/webm",mov:"video/quicktime",ogv:"video/ogg"};function iM(e){let t=(e.replace(/\\/g,"/").split("/").pop()??"").toLowerCase(),n=t.lastIndexOf(".");return n>0?t.slice(n+1):""}function iT(e){let t;return null!==(Object.hasOwn(i$,t=iM(e))?i$[t]:null)}function iR(e){let t;return null!==(Object.hasOwn(iI,t=iM(e))?iI[t]:null)}var iA=n(88374),iL=n(5924),iz=n(94764),iP=n(63835),iW=n(54152),iO=n(31678),iF=n(6796),iD=n(98164);let iB=["obsidian","logseq","notion","vscode","vscode-insiders","cursor","zed","jetbrains","zoommtg","zoomus","msteams","slack"],iH=RegExp(`^(?:${iB.join("|")}):`,"i"),i_=iz.j.clobberPrefix??"user-content-",iU={...iz.j,clobberPrefix:i_,attributes:{...iz.j.attributes,code:[["className",/^language-./,"math-inline","math-display"]]},protocols:{...iz.j.protocols,href:[...iz.j.protocols?.href??[],"file",...iB]},strip:[...iz.j.strip||[],"iframe","object","style","form"]};function iK(e){return iH.test(e)?e:(0,iC.Lv)(e)}function iq(e){return/^file:/i.test(e)?e:iK(e)}function iV(e){return!!(e&&/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i.test(e))}function iZ(e){if(e.defaultPrevented||0!==e.button||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey)return;let t=e.currentTarget.getAttribute("href");if(!t?.startsWith("#"))return;e.preventDefault();let n=t.slice(1);if(!n)return;try{n=decodeURIComponent(n)}catch{}let r=CSS.escape(n);e.currentTarget.closest(".markdown-body")?.querySelector(`[id="${r}"], a[name="${r}"]`)?.scrollIntoView({block:"start"})}function iJ(e,t,n,r,i){let s="",o=0;for(let l=e.indexOf(t);-1!==l;l=e.indexOf(t,l+1)){if(l>0&&n.includes(e[l-1]))continue;r.lastIndex=l;let t=r.exec(e);t&&(s+=e.slice(o,l)+i(t),l=(o=r.lastIndex)-1)}return s+e.slice(o)}let iY=/`((?:[^`\n]|\\`)*?[^\\`\n])`(?!`)/y;function iG(e){let t=e.includes("\r\n")?"\r\n":"\n",n=e.split(/\r?\n/),r=[],i=null,s=0,o=null,l=new Map;for(let e=0;e<n.length;e++){var a,d;let t=n[e];if(o){r.push(t),RegExp(`</${o}\\s*>`,"i").test(t)&&(o=null);continue}let c=t.match(/^ {0,3}(`{3,}|~{3,})/);if(c){let e=c[1][0],n=c[1].length;i?e===i.marker&&n>=i.size&&/^[ \t]*$/.test(t.slice(c[0].length))&&(i=null):i={marker:e,size:n},s=0,r.push(t);continue}if(i){r.push(t);continue}let u=t.match(/<(code|pre|script|style)\b/i);if(u){let e=u[1].toLowerCase(),n=t.slice((u.index??0)+u[0].length);RegExp(`</${e}\\s*>`,"i").test(n)||(o=e),s=0,r.push(t);continue}if(/^(?: {4}|\t)/.test(t)||""===t.trim()){s=0,r.push(t);continue}if(s||(t=iJ(t,"`","\\`",iY,e=>{let[t,n]=e,r=n.replace(/\\`/g,"`");if(r===n)return t;let i="`".repeat(Math.max(...r.match(/`+/g)?.map(e=>e.length)??[0])+1);return`${i}${r}${i}`})),s||t.includes("`")){s=function(e,t){let n=t;for(let t=0;t<e.length;){if("`"!==e[t]){t++;continue}let r=t+1;for(;"`"===e[r];)r++;let i=r-t;0===n?n=i:i===n&&(n=0),t=r}return n}(t,s),r.push(t);continue}let p=t.match(/^([ ]{0,3})\\\[[ \t]*(.+?)[ \t]*\\\][ \t]*$/);if(p){let e=p[2].trim();if(e){r.push(`${p[1]}$$`,`${p[1]}${e}`,`${p[1]}$$`);continue}}let h=t.match(/^([ ]{0,3})\[[ \t]*(.+?)[ \t]*\][ \t]*$/);if(h){let e=h[2].trim();if(a=e,/\\[A-Za-z]+/.test(a)&&!/\b(?:https?|file|mailto):|\b[A-Za-z]:\\|^\\\\/i.test(a)){r.push(`${h[1]}$$`,`${h[1]}${e}`,`${h[1]}$$`);continue}}let f=t.match(/^([ ]{0,3})\\\[[ \t]*$/);if(f){let t=function(e,t){for(let n=t;n<e.length;n++){let t=e[n];if(/^ {0,3}\\\][ \t]*$/.test(t))return n;if(/^ {0,3}(`{3,}|~{3,})/.test(t)||/^ {0,3}\\\[[ \t]*$/.test(t)||/<(code|pre|script|style)\b/i.test(t))break}return -1}(n,e+1);if(-1!==t){r.push(`${f[1]}$$`,...n.slice(e+1,t).map(e=>iQ(e,f[1])),`${f[1]}$$`),e=t;continue}}let m=t.match(/^([ \t]{0,3})\$\$(.+)\$\$[ \t]*$/);if(m){let e=m[2].trim();if(e){r.push(`${m[1]}$$`,`${m[1]}${e}`,`${m[1]}$$`);continue}}let g=t.match(/^([ \t]{0,3})\$\$(.+)$/);if(g){let t=g[1],i=g[2].trimEnd();if(i&&!i.includes("$$")){let s=iX(n,e+1,t,l);if(s){r.push(`${t}$$`,`${t}${i}`);for(let i=e+1;i<s.index;i++)r.push(iQ(n[i],t));s.content&&r.push(`${t}${s.content}`),r.push(`${t}$$`),e=s.index;continue}}}let x=t.match(/^([ \t]{0,3})\$\$\s*$/);if(x){let t=x[1],i=iX(n,e+1,t,l);if(i&&(i.glued||""!==t)){r.push(`${t}$$`);for(let s=e+1;s<i.index;s++)r.push(iQ(n[s],t));i.content&&r.push(`${t}${i.content}`),r.push(`${t}$$`),e=i.index;continue}}r.push((d=t,/^\s{0,3}\[[^\]]+\]:/.test(d)||/]\s*\(/.test(d)||/<(?:!--|\/?[A-Za-z][^>]*>)/.test(d)||/\b(?:https?|file|mailto):/i.test(d)||/\b[A-Za-z]:\\/.test(d)?d:iJ(d,"\\(","\\",i0,e=>{let[t,n]=e;return n.trim()?`$${n}$`:t})))}return r.join(t)}function iX(e,t,n,r){let i=r.get(n);if(void 0!==i&&t<i)return null;for(let i=t;i<e.length;i++){var s,o,l,a;let t=e[i];if(s=t,""===(o=n)?/^ {0,3}\$\$\s*$/.test(s):s.startsWith(o)&&/^\$\$\s*$/.test(s.slice(o.length)))return{index:i,content:"",glued:!1};if(l=t,/^ {0,3}(`{3,}|~{3,})/.test(l)||/^[ \t]*(?:[-+*]|\d{1,9}[.)])(?:[ \t]+|$)/.test(l)||/^ {0,3}#{1,6}(?:[ \t]+|$)/.test(l)||/^ {0,3}>/.test(l)||/<(code|pre|script|style)\b/i.test(l)||(a=t,/^ {0,3}\$\$(?:\S|[ \t]+\S)/.test(a)))return r.set(n,i),null;let d=function(e,t){if(!e.startsWith(t))return null;let n=e.slice(t.length).match(/^(.+?)\$\$\s*$/);if(!n)return null;let r=n[1].trimEnd();return r&&!r.includes("$$")?r:null}(t,n);if(null!==d)return{index:i,content:d,glued:!0}}return r.set(n,e.length),null}function iQ(e,t){if(!t||!e||e.startsWith(" "))return e;let n=e.match(/^ */)?.[0].length??0;return n>=t.length?e:`${t.slice(n)}${e}`}let i0=/\\\(([^`\r\n$]*?[^`\r\n$\\])\\\)/y,i1={singleTilde:!1},i2=/[\u3001\u3002\u3008-\u3011\u3014-\u301B\uFF01\uFF08\uFF09\uFF0C\uFF1A\uFF1B\uFF1F\u2018\u2019\u201C\u201D\u2013\u2014\u2026\u00B7\uFF5E\u301C]/;function i4(){return(e,t)=>{var n;let r;n="string"==typeof t.value?t.value:"",(r=e=>{let t=e.children;for(let e=0;e<t.length;e++){let i=t[e];"link"===i.type&&function(e,t,n,r){if(null!=n.title||1!==n.children.length)return;let i=n.children[0];if("text"!==i.type)return;let s=n.position?.start,o=n.position?.end;if(s?.offset==null||o?.offset==null||r.slice(s.offset,o.offset)!==i.value)return;let l=i.value,a=l.search(i2);if(a<=0||!n.url.endsWith(l))return;let d=l.slice(0,a),c={line:s.line,column:s.column+a,offset:s.offset+a};n.url=n.url.slice(0,n.url.length-l.length)+d,i.value=d,n.position={start:s,end:c},e.splice(t+1,0,{type:"text",value:l.slice(a),position:{start:c,end:o}})}(t,e,i,n);let s=t[e];"children"in s&&Array.isArray(s.children)&&r(s)}})(e)}}let i8=function(){iD.A.call(this);let e=this.data(),t=e.micromarkExtensions?.at(-1),n=t?.text?.[36];for(let e of Array.isArray(n)?n:n?[n]:[]){if("mathText"!==e.name)continue;let t=e.tokenize;e.tokenize=function(e,n,r){let i=this.now();return t.call(this,e,e=>{let t=this.sliceSerialize({start:i,end:this.now()});if(t.startsWith("$")&&!t.startsWith("$$")){let n=t.slice(1,-1),i=/^\s*[+-]?(?:\d|\.\d)/.test(n),s=null!==e&&e>=48&&e<=57,o=/^\s/.test(n)!==/\s$/.test(n);if(i&&(s||o))return r(e)}return n(e)},r)}}};function i3(){return e=>{let t=e=>{("link"===e.type||"definition"===e.type)&&/^\/?[A-Za-z]:\//.test(e.url)&&(e.url=`file:///${e.url.replace(/^\//,"")}`),"children"in e&&e.children.forEach(t)};t(e)}}let i5=[[iW.A,["yaml"]],[iO.A,i1],iF.A,i4,i8,i3],i6=/[ \t]*(?:\r\n|\r|\n)[ \t]*/,i9=new Set(["root","blockquote","listItem","footnoteDefinition"]);function i7(){return{type:"lineBreak",data:{hName:"br"}}}function se(e){if(!e.children)return;let t=i9.has(e.type);e.children=e.children.map(e=>{if("html"!==e.type)return se(e),e;let n={type:"text",value:e.value??""};return t?{type:"paragraph",children:[n]}:n})}function st(e){e.children&&(e.children=e.children.flatMap(e=>"break"===e.type?[i7()]:"text"===e.type&&e.value?e.value.split(i6).flatMap((e,t)=>[...t>0?[i7()]:[],...e?[{type:"text",value:e}]:[]]):(st(e),[e])))}let sn=[...i5??[],function(){return e=>{se(e),st(e)}}],sr=[...i5??[],function(){return(e,t)=>{se(e),st(e);let n=String(t.value).split(/\r\n|\r|\n/);for(let t of e.children??[])"paragraph"===t.type&&function(e,t){if(!e.position)return;let n=e.position.start.line-1,r=()=>{let e=/^[ \t]*/.exec(t[n]??"")?.[0];return e?[{type:"text",value:e}]:[]},i=r(),s=e=>{e.children=e.children?.flatMap(e=>"lineBreak"===e.type?(n+=1,[e,...r()]):(e.children?s(e):e.position&&(n+=e.position.end.line-e.position.start.line),[e]))};s(e),e.children=[...i,...e.children??[]]}(t,n)}}],si=[[iW.A,["yaml"]],[iO.A,i1],iF.A,i4,i8,i3];function ss(){return e=>{let t=e=>{if(!e||"object"!=typeof e)return;let n=e.properties?.href;for(let r of("element"===e.type&&"string"==typeof n&&n.startsWith("#")&&n.length>1&&(e.properties.href=`#${i_}${n.slice(1)}`),e.children??[]))t(r)};t(e)}}function so(e){return"text"===e.type?e.value:"element"===e.type?e.children.map(so).join(""):""}function sl(){return e=>{let t=e=>{e.children=e.children.map(e=>{if("element"!==e.type)return e;let n="pre"===e.tagName&&1===e.children.length?e.children[0]:null,r=n?.type==="element"&&"code"===n.tagName?n.properties.className:null;return Array.isArray(r)&&r.includes("language-math")?{type:"element",tagName:"div",properties:{className:["markdown-math-display"],dataMathSource:so(e).replace(/\n$/,"")},children:[e]}:(t(e),e)})};t(e)}}let sa=[iL.A,[iP.A,iU],ss,sl,[iA.A,{throwOnError:!1,strict:!1}]],sd=[iL.A,[iP.A,iU],function(){return e=>{let t=new Map,n=e=>e.children.forEach(e=>{if("element"===e.type){if(/^h[1-6]$/.test(e.tagName)){let n=so(e).toLowerCase().replace(/[^\p{L}\p{M}\p{N}_\- ]/gu,"").replace(/ /g,"-"),r=n;for(;t.has(r);)t.set(n,t.get(n)+1),r=`${n}-${t.get(n)}`;t.set(r,0),e.properties.dataHeadingAnchor=r}n(e)}});n(e)}},sl,[iA.A,{throwOnError:!1,strict:!1}]],sc=[iL.A,[iP.A,iU],ss,[iA.A,{throwOnError:!1,strict:!1}]],su=/^ {0,3}(`{3,}|~{3,})/,sp=/^(?:[*+-]|\d{1,9}[.)])(?:[ \t]|$)/,sh=/<[A-Za-z!/?]/,sf=/`[^`]*`/g,sm=/^ {0,3}\[[^\]]+\]:/,sg=/^(`{3,}|~{3,})[ \t]*([^`\s]*)[^`]*$/;function sx(e){let{src:t,alt:n="",children:s,className:o,style:l}=e,{t:a}=(0,tm.s)(),d=a("chat.previewImage"),c=n.trim()?`${d}: ${n}`:d,[u,p]=(0,i.useState)(!1),h=(0,i.useRef)(null),f=(0,i.useRef)(null),m=(0,i.useRef)(null);(0,i.useEffect)(()=>{if(!u)return;let e=f.current;if(!e)return;let t=h.current,n=document.body.style.overflow;return document.body.style.overflow="hidden",e.showModal(),m.current?.focus({preventScroll:!0}),()=>{document.body.style.overflow=n,e.open&&e.close(),t?.isConnected&&t.focus({preventScroll:!0})}},[u]);let g=()=>{f.current?.open&&f.current.close(),p(!1)};return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("button",{ref:h,type:"button",className:o,style:{display:"block",padding:0,border:"none",background:"none",color:"inherit",cursor:"zoom-in",...l},onClick:()=>p(!0),"aria-label":c,"aria-haspopup":"dialog","aria-expanded":u,title:d,children:s}),u&&(0,r.jsxs)("dialog",{ref:f,className:"image-preview-dialog","aria-label":a("chat.previewImage"),onCancel:e=>{e.preventDefault(),e.stopPropagation(),g()},onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),e.stopPropagation(),g())},onClick:e=>{e.target===e.currentTarget&&g()},children:[(0,r.jsx)("img",{className:"image-preview-image",src:t,alt:n}),(0,r.jsx)("button",{ref:m,type:"button",className:"image-preview-close",onClick:g,"aria-label":a("chat.close"),title:a("chat.close"),children:(0,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M6 6l12 12M18 6 6 18"})})})]})]})}var sv=n(50640),sb=n(55961),sy=n(7644);let sw=[{id:"auto",label:"settings.themeSystem",scheme:null},{id:"light",label:"settings.themeLight",scheme:"light"},{id:"mist",label:"settings.themeMist",scheme:"light"},{id:"lilac",label:"settings.themeLilac",scheme:"light"},{id:"sand",label:"settings.themeSand",scheme:"light"},{id:"rose",label:"settings.themeRose",scheme:"light"},{id:"dark",label:"settings.themeDark",scheme:"dark"},{id:"pine",label:"settings.themePine",scheme:"dark"},{id:"dusk",label:"settings.themeDusk",scheme:"dark"},{id:"ember",label:"settings.themeEmber",scheme:"dark"},{id:"slate",label:"settings.themeSlate",scheme:"dark"},{id:"contrast-light",label:"settings.themeContrastLight",scheme:"light"},{id:"contrast-dark",label:"settings.themeContrastDark",scheme:"dark"},{id:"zenburn",label:"settings.themeZenburn",scheme:"dark"},{id:"powerlevel10k",label:"settings.themePowerlevel10k",scheme:"dark"},{id:"one-half-dark",label:"settings.themeOneHalfDark",scheme:"dark"}];sw.flatMap(e=>"light"===e.scheme?[e.id]:[]);let sk=sw.flatMap(e=>"dark"===e.scheme?[e.id]:[]);function sj(e){return sk.includes(e)}let sS="pi-theme",sC={preference:"auto",theme:"light"},sN=new Set,sE=null,s$=!1;function sI(){return window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}function sM(e){return"auto"===e?sI():e}function sT(e){"u">typeof document&&(document.documentElement.dataset.theme=e,document.documentElement.classList.toggle("dark",sj(e)))}function sR(){if(sE)return sE;let e=function(){try{let e=localStorage.getItem(sS);if(sw.some(t=>t.id===e))return e}catch{}return"auto"}(),t=sM(e);return sT(t),sE={preference:e,theme:t}}function sA(e,t,n){if(sT(t),n)try{localStorage.setItem(sS,e)}catch{}sE={preference:e,theme:t},sN.forEach(e=>e())}function sL(){let e=sR();if("auto"!==e.preference)return;let t=sI();t!==e.theme&&sA("auto",t,!1)}function sz(e){return sN.add(e),sR(),s$||!window.matchMedia||(window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change",sL),window.addEventListener("focus",sL),document.addEventListener("visibilitychange",()=>{"visible"===document.visibilityState&&sL()}),s$=!0),sL(),()=>{sN.delete(e)}}function sP(){return sR()}function sW(){return sC}function sO(){let e=(0,i.useSyncExternalStore)(sz,sP,sW),t=(0,i.useCallback)((e,t)=>{if(sR().preference===e)return;let n=sM(e),r=()=>{sA(e,n,!0)},i=window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;if("function"!=typeof document.startViewTransition||i)return void r();let s=t?.x??window.innerWidth/2,o=t?.y??window.innerHeight/2,l=Math.hypot(Math.max(s,window.innerWidth-s),Math.max(o,window.innerHeight-o));document.startViewTransition(r).ready.then(()=>{document.documentElement.animate({clipPath:[`circle(0px at ${s}px ${o}px)`,`circle(${l}px at ${s}px ${o}px)`]},{duration:450,easing:"cubic-bezier(0.22, 0.61, 0.36, 1)",pseudoElement:"::view-transition-new(root)"})}).catch(()=>{})},[]);return{theme:e.theme,preference:e.preference,setThemePreference:t,isDark:sj(e.theme)}}let sF={background:"#282c34",foreground:"#dcdfe4",cursor:"#ffffff",cursorAccent:"#282c34",selectionBackground:"#343a44",black:"#282c34",red:"#e06c75",green:"#98c379",yellow:"#e5c07b",blue:"#61afef",magenta:"#c678dd",cyan:"#56b6c2",white:"#dcdfe4",brightBlack:"#5a6374",brightRed:"#e06c75",brightGreen:"#98c379",brightYellow:"#e5c07b",brightBlue:"#61afef",brightMagenta:"#c678dd",brightCyan:"#56b6c2",brightWhite:"#dcdfe4"},sD={'code[class*="language-"]':{color:sF.foreground,fontFamily:"var(--font-mono)",fontWeight:"var(--font-mono-weight)",textShadow:"none"},'pre[class*="language-"]':{color:sF.foreground,backgroundColor:"var(--tool-bg)",textShadow:"none"},...Object.fromEntries(["comment","prolog","doctype","cdata"].map(e=>[e,{color:"#abb2bf"}])),...Object.fromEntries(["string","char","attr-value","inserted"].map(e=>[e,{color:sF.green}])),...Object.fromEntries(["keyword","important","regex"].map(e=>[e,{color:sF.magenta}])),...Object.fromEntries(["number","boolean","constant","symbol","class-name"].map(e=>[e,{color:sF.yellow}])),...Object.fromEntries(["function","property","builtin","attr-name"].map(e=>[e,{color:sF.blue}])),...Object.fromEntries(["operator","entity","url"].map(e=>[e,{color:sF.cyan}])),...Object.fromEntries(["tag","deleted","variable"].map(e=>[e,{color:sF.red}])),punctuation:{color:sF.foreground},bold:{fontWeight:700},italic:{fontStyle:"italic"}},sB={background:"#121212",foreground:"#eeeeee",cursor:"#5fafff",cursorAccent:"#121212",selectionBackground:"#303030",black:"#121212",red:"#ff5f5f",green:"#5fd700",yellow:"#ffd75f",blue:"#5fafff",magenta:"#af87ff",cyan:"#5fd7ff",white:"#d0d0d0",brightBlack:"#a8a8a8",brightRed:"#ff8787",brightGreen:"#87ff5f",brightYellow:"#ffff87",brightBlue:"#87d7ff",brightMagenta:"#d7afff",brightCyan:"#87ffff",brightWhite:"#ffffff"},sH={'code[class*="language-"]':{color:sB.foreground,fontFamily:"var(--font-mono)",fontWeight:"var(--font-mono-weight)",textShadow:"none"},'pre[class*="language-"]':{color:sB.foreground,backgroundColor:"var(--tool-bg)",textShadow:"none"},...Object.fromEntries(["comment","prolog","doctype","cdata"].map(e=>[e,{color:sB.brightBlack}])),...Object.fromEntries(["string","char","attr-value","inserted"].map(e=>[e,{color:sB.green}])),...Object.fromEntries(["keyword","boolean","important","regex"].map(e=>[e,{color:sB.magenta}])),...Object.fromEntries(["number","constant","symbol","attr-name"].map(e=>[e,{color:sB.yellow}])),...Object.fromEntries(["function","property","builtin"].map(e=>[e,{color:sB.blue}])),...Object.fromEntries(["operator","entity","url","class-name"].map(e=>[e,{color:sB.cyan}])),...Object.fromEntries(["tag","deleted"].map(e=>[e,{color:sB.red}])),punctuation:{color:"#bcbcbc"},variable:{color:sB.foreground},bold:{fontWeight:700},italic:{fontStyle:"italic"}};function s_(e){return"powerlevel10k"===e?sH:"one-half-dark"===e?sD:void 0}let sU=!1,sK=null;function sq(){return sU}function sV(){let e=!(arguments.length>0)||void 0===arguments[0]||arguments[0],[t,r]=(0,i.useState)(sq);return(0,i.useEffect)(()=>{if(t||!e)return;let i=!0;return(sK??=n.e(1326).then(n.bind(n,61326)).then(()=>{sU=!0},e=>{throw sK=null,e})).then(()=>{i&&r(!0)},()=>{}),()=>{i=!1}},[e,t]),t}let sZ=2e3,sJ=!1,sY=[],sG=!1;function sX(){sG=!1,sY.pop()?.(),sY.length>0&&sQ()}function sQ(){!sG&&(sG=!0,"function"==typeof window.requestIdleCallback?window.requestIdleCallback(sX,{timeout:500}):setTimeout(sX,50))}function s0(e,t){let n=URL.createObjectURL(new Blob([e],{type:"image/svg+xml;charset=utf-8"})),r=document.createElement("a");r.href=n,r.download=t,r.click(),setTimeout(()=>URL.revokeObjectURL(n),0)}function s1(e){let{code:t,isStreaming:s,defaultPreview:o=!1}=e,{isDark:l}=sO(),{t:a}=(0,tm.s)(),[d,c]=(0,i.useState)(o),[u,p]=(0,i.useState)(null),[h,f]=(0,i.useState)(!1),m=(0,i.useRef)(null),g=`${l?"dark":"light"}
|
|
5
|
+
`}function iS(e){return!e.trim()||e.endsWith("\n\n")?"":e.endsWith("\n")?"\n":"\n\n"}var iC=n(32316);function iN(e){if(navigator.clipboard?.writeText)return navigator.clipboard.writeText(e);let t=document.activeElement,n=null;try{return(n=document.createElement("textarea")).value=e,n.style.position="fixed",n.style.opacity="0",document.body.appendChild(n),n.select(),document.execCommand("copy")?Promise.resolve():Promise.reject(Error("Copy was refused"))}catch(e){return Promise.reject(e)}finally{n?.remove(),t?.isConnected&&t instanceof HTMLElement&&t.focus({preventScroll:!0})}}let iE={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"},i$={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"},iI={mp4:"video/mp4",m4v:"video/mp4",webm:"video/webm",mov:"video/quicktime",ogv:"video/ogg"};function iM(e){let t=(e.replace(/\\/g,"/").split("/").pop()??"").toLowerCase(),n=t.lastIndexOf(".");return n>0?t.slice(n+1):""}function iT(e){let t;return null!==(Object.hasOwn(i$,t=iM(e))?i$[t]:null)}function iR(e){let t;return null!==(Object.hasOwn(iI,t=iM(e))?iI[t]:null)}var iA=n(88374),iL=n(5924),iz=n(94764),iP=n(63835),iW=n(54152),iO=n(31678),iF=n(6796),iD=n(98164);let iB=["obsidian","logseq","notion","vscode","vscode-insiders","cursor","zed","jetbrains","zoommtg","zoomus","msteams","slack"],iH=RegExp(`^(?:${iB.join("|")}):`,"i"),i_=iz.j.clobberPrefix??"user-content-",iU={...iz.j,clobberPrefix:i_,attributes:{...iz.j.attributes,code:[["className",/^language-./,"math-inline","math-display"]]},protocols:{...iz.j.protocols,href:[...iz.j.protocols?.href??[],"file",...iB]},strip:[...iz.j.strip||[],"iframe","object","style","form"]};function iK(e){return iH.test(e)?e:(0,iC.Lv)(e)}function iq(e){return/^file:/i.test(e)?e:iK(e)}function iV(e){return!!(e&&/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i.test(e))}function iZ(e){if(e.defaultPrevented||0!==e.button||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey)return;let t=e.currentTarget.getAttribute("href");if(!t?.startsWith("#"))return;e.preventDefault();let n=t.slice(1);if(!n)return;try{n=decodeURIComponent(n)}catch{}let r=CSS.escape(n);e.currentTarget.closest(".markdown-body")?.querySelector(`[id="${r}"], a[name="${r}"]`)?.scrollIntoView({block:"start"})}function iJ(e,t,n,r,i){let s="",o=0;for(let l=e.indexOf(t);-1!==l;l=e.indexOf(t,l+1)){if(l>0&&n.includes(e[l-1]))continue;r.lastIndex=l;let t=r.exec(e);t&&(s+=e.slice(o,l)+i(t),l=(o=r.lastIndex)-1)}return s+e.slice(o)}let iY=/`((?:[^`\n]|\\`)*?[^\\`\n])`(?!`)/y;function iG(e){let t=e.includes("\r\n")?"\r\n":"\n",n=e.split(/\r?\n/),r=[],i=null,s=0,o=null,l=new Map;for(let e=0;e<n.length;e++){var a,d;let t=n[e];if(o){r.push(t),RegExp(`</${o}\\s*>`,"i").test(t)&&(o=null);continue}let c=t.match(/^ {0,3}(`{3,}|~{3,})/);if(c){let e=c[1][0],n=c[1].length;i?e===i.marker&&n>=i.size&&/^[ \t]*$/.test(t.slice(c[0].length))&&(i=null):i={marker:e,size:n},s=0,r.push(t);continue}if(i){r.push(t);continue}let u=t.match(/<(code|pre|script|style)\b/i);if(u){let e=u[1].toLowerCase(),n=t.slice((u.index??0)+u[0].length);RegExp(`</${e}\\s*>`,"i").test(n)||(o=e),s=0,r.push(t);continue}if(/^(?: {4}|\t)/.test(t)||""===t.trim()){s=0,r.push(t);continue}if(s||(t=iJ(t,"`","\\`",iY,e=>{let[t,n]=e,r=n.replace(/\\`/g,"`");if(r===n)return t;let i="`".repeat(Math.max(...r.match(/`+/g)?.map(e=>e.length)??[0])+1);return`${i}${r}${i}`})),s||t.includes("`")){s=function(e,t){let n=t;for(let t=0;t<e.length;){if("`"!==e[t]){t++;continue}let r=t+1;for(;"`"===e[r];)r++;let i=r-t;0===n?n=i:i===n&&(n=0),t=r}return n}(t,s),r.push(t);continue}let p=t.match(/^([ ]{0,3})\\\[[ \t]*(.+?)[ \t]*\\\][ \t]*$/);if(p){let e=p[2].trim();if(e){r.push(`${p[1]}$$`,`${p[1]}${e}`,`${p[1]}$$`);continue}}let h=t.match(/^([ ]{0,3})\[[ \t]*(.+?)[ \t]*\][ \t]*$/);if(h){let e=h[2].trim();if(a=e,/\\[A-Za-z]+/.test(a)&&!/\b(?:https?|file|mailto):|\b[A-Za-z]:\\|^\\\\/i.test(a)){r.push(`${h[1]}$$`,`${h[1]}${e}`,`${h[1]}$$`);continue}}let f=t.match(/^([ ]{0,3})\\\[[ \t]*$/);if(f){let t=function(e,t){for(let n=t;n<e.length;n++){let t=e[n];if(/^ {0,3}\\\][ \t]*$/.test(t))return n;if(/^ {0,3}(`{3,}|~{3,})/.test(t)||/^ {0,3}\\\[[ \t]*$/.test(t)||/<(code|pre|script|style)\b/i.test(t))break}return -1}(n,e+1);if(-1!==t){r.push(`${f[1]}$$`,...n.slice(e+1,t).map(e=>iQ(e,f[1])),`${f[1]}$$`),e=t;continue}}let m=t.match(/^([ \t]{0,3})\$\$(.+)\$\$[ \t]*$/);if(m){let e=m[2].trim();if(e){r.push(`${m[1]}$$`,`${m[1]}${e}`,`${m[1]}$$`);continue}}let g=t.match(/^([ \t]{0,3})\$\$(.+)$/);if(g){let t=g[1],i=g[2].trimEnd();if(i&&!i.includes("$$")){let s=iX(n,e+1,t,l);if(s){r.push(`${t}$$`,`${t}${i}`);for(let i=e+1;i<s.index;i++)r.push(iQ(n[i],t));s.content&&r.push(`${t}${s.content}`),r.push(`${t}$$`),e=s.index;continue}}}let x=t.match(/^([ \t]{0,3})\$\$\s*$/);if(x){let t=x[1],i=iX(n,e+1,t,l);if(i&&(i.glued||""!==t)){r.push(`${t}$$`);for(let s=e+1;s<i.index;s++)r.push(iQ(n[s],t));i.content&&r.push(`${t}${i.content}`),r.push(`${t}$$`),e=i.index;continue}}r.push((d=t,/^\s{0,3}\[[^\]]+\]:/.test(d)||/]\s*\(/.test(d)||/<(?:!--|\/?[A-Za-z][^>]*>)/.test(d)||/\b(?:https?|file|mailto):/i.test(d)||/\b[A-Za-z]:\\/.test(d)?d:iJ(d,"\\(","\\",i0,e=>{let[t,n]=e;return n.trim()?`$${n}$`:t})))}return r.join(t)}function iX(e,t,n,r){let i=r.get(n);if(void 0!==i&&t<i)return null;for(let i=t;i<e.length;i++){var s,o,l,a;let t=e[i];if(s=t,""===(o=n)?/^ {0,3}\$\$\s*$/.test(s):s.startsWith(o)&&/^\$\$\s*$/.test(s.slice(o.length)))return{index:i,content:"",glued:!1};if(l=t,/^ {0,3}(`{3,}|~{3,})/.test(l)||/^[ \t]*(?:[-+*]|\d{1,9}[.)])(?:[ \t]+|$)/.test(l)||/^ {0,3}#{1,6}(?:[ \t]+|$)/.test(l)||/^ {0,3}>/.test(l)||/<(code|pre|script|style)\b/i.test(l)||(a=t,/^ {0,3}\$\$(?:\S|[ \t]+\S)/.test(a)))return r.set(n,i),null;let d=function(e,t){if(!e.startsWith(t))return null;let n=e.slice(t.length).match(/^(.+?)\$\$\s*$/);if(!n)return null;let r=n[1].trimEnd();return r&&!r.includes("$$")?r:null}(t,n);if(null!==d)return{index:i,content:d,glued:!0}}return r.set(n,e.length),null}function iQ(e,t){if(!t||!e||e.startsWith(" "))return e;let n=e.match(/^ */)?.[0].length??0;return n>=t.length?e:`${t.slice(n)}${e}`}let i0=/\\\(([^`\r\n$]*?[^`\r\n$\\])\\\)/y,i1={singleTilde:!1},i2=/[\u3001\u3002\u3008-\u3011\u3014-\u301B\uFF01\uFF08\uFF09\uFF0C\uFF1A\uFF1B\uFF1F\u2018\u2019\u201C\u201D\u2013\u2014\u2026\u00B7\uFF5E\u301C]/;function i4(){return(e,t)=>{var n;let r;n="string"==typeof t.value?t.value:"",(r=e=>{let t=e.children;for(let e=0;e<t.length;e++){let i=t[e];"link"===i.type&&function(e,t,n,r){if(null!=n.title||1!==n.children.length)return;let i=n.children[0];if("text"!==i.type)return;let s=n.position?.start,o=n.position?.end;if(s?.offset==null||o?.offset==null||r.slice(s.offset,o.offset)!==i.value)return;let l=i.value,a=l.search(i2);if(a<=0||!n.url.endsWith(l))return;let d=l.slice(0,a),c={line:s.line,column:s.column+a,offset:s.offset+a};n.url=n.url.slice(0,n.url.length-l.length)+d,i.value=d,n.position={start:s,end:c},e.splice(t+1,0,{type:"text",value:l.slice(a),position:{start:c,end:o}})}(t,e,i,n);let s=t[e];"children"in s&&Array.isArray(s.children)&&r(s)}})(e)}}let i8=function(){iD.A.call(this);let e=this.data(),t=e.micromarkExtensions?.at(-1),n=t?.text?.[36];for(let e of Array.isArray(n)?n:n?[n]:[]){if("mathText"!==e.name)continue;let t=e.tokenize;e.tokenize=function(e,n,r){let i=this.now();return t.call(this,e,e=>{let t=this.sliceSerialize({start:i,end:this.now()});if(t.startsWith("$")&&!t.startsWith("$$")){let n=t.slice(1,-1),i=/^\s*[+-]?(?:\d|\.\d)/.test(n),s=null!==e&&e>=48&&e<=57,o=/^\s/.test(n)!==/\s$/.test(n);if(i&&(s||o))return r(e)}return n(e)},r)}}};function i3(){return e=>{let t=e=>{("link"===e.type||"definition"===e.type)&&/^\/?[A-Za-z]:\//.test(e.url)&&(e.url=`file:///${e.url.replace(/^\//,"")}`),"children"in e&&e.children.forEach(t)};t(e)}}let i5=[[iW.A,["yaml"]],[iO.A,i1],iF.A,i4,i8,i3],i6=/[ \t]*(?:\r\n|\r|\n)[ \t]*/,i9=new Set(["root","blockquote","listItem","footnoteDefinition"]);function i7(){return{type:"lineBreak",data:{hName:"br"}}}function se(e){if(!e.children)return;let t=i9.has(e.type);e.children=e.children.map(e=>{if("html"!==e.type)return se(e),e;let n={type:"text",value:e.value??""};return t?{type:"paragraph",children:[n]}:n})}function st(e){e.children&&(e.children=e.children.flatMap(e=>"break"===e.type?[i7()]:"text"===e.type&&e.value?e.value.split(i6).flatMap((e,t)=>[...t>0?[i7()]:[],...e?[{type:"text",value:e}]:[]]):(st(e),[e])))}let sn=[...i5??[],function(){return e=>{se(e),st(e)}}],sr=[...i5??[],function(){return(e,t)=>{se(e),st(e);let n=String(t.value).split(/\r\n|\r|\n/);for(let t of e.children??[])"paragraph"===t.type&&function(e,t){if(!e.position)return;let n=e.position.start.line-1,r=()=>{let e=/^[ \t]*/.exec(t[n]??"")?.[0];return e?[{type:"text",value:e}]:[]},i=r(),s=e=>{e.children=e.children?.flatMap(e=>"lineBreak"===e.type?(n+=1,[e,...r()]):(e.children?s(e):e.position&&(n+=e.position.end.line-e.position.start.line),[e]))};s(e),e.children=[...i,...e.children??[]]}(t,n)}}],si=[[iW.A,["yaml"]],[iO.A,i1],iF.A,i4,i8,i3];function ss(){return e=>{let t=e=>{if(!e||"object"!=typeof e)return;let n=e.properties?.href;for(let r of("element"===e.type&&"string"==typeof n&&n.startsWith("#")&&n.length>1&&(e.properties.href=`#${i_}${n.slice(1)}`),e.children??[]))t(r)};t(e)}}function so(e){return"text"===e.type?e.value:"element"===e.type?e.children.map(so).join(""):""}function sl(){return e=>{let t=e=>{e.children=e.children.map(e=>{if("element"!==e.type)return e;let n="pre"===e.tagName&&1===e.children.length?e.children[0]:null,r=n?.type==="element"&&"code"===n.tagName?n.properties.className:null;return Array.isArray(r)&&r.includes("language-math")?{type:"element",tagName:"div",properties:{className:["markdown-math-display"],dataMathSource:so(e).replace(/\n$/,"")},children:[e]}:(t(e),e)})};t(e)}}let sa=[iL.A,[iP.A,iU],ss,sl,[iA.A,{throwOnError:!1,strict:!1}]],sd=[iL.A,[iP.A,iU],function(){return e=>{let t=new Map,n=e=>e.children.forEach(e=>{if("element"===e.type){if(/^h[1-6]$/.test(e.tagName)){let n=so(e).toLowerCase().replace(/[^\p{L}\p{M}\p{N}_\- ]/gu,"").replace(/ /g,"-"),r=n;for(;t.has(r);)t.set(n,t.get(n)+1),r=`${n}-${t.get(n)}`;t.set(r,0),e.properties.dataHeadingAnchor=r}n(e)}});n(e)}},sl,[iA.A,{throwOnError:!1,strict:!1}]],sc=[iL.A,[iP.A,iU],ss,[iA.A,{throwOnError:!1,strict:!1}]],su=/^ {0,3}(`{3,}|~{3,})/,sp=/^(?:[*+-]|\d{1,9}[.)])(?:[ \t]|$)/,sh=/<[A-Za-z!/?]/,sf=/`[^`]*`/g,sm=/^ {0,3}\[[^\]]+\]:/,sg=/^(`{3,}|~{3,})[ \t]*([^`\s]*)[^`]*$/;function sx(e){let{src:t,alt:n="",children:s,className:o,style:l}=e,{t:a}=(0,tm.s)(),d=a("chat.previewImage"),c=n.trim()?`${d}: ${n}`:d,[u,p]=(0,i.useState)(!1),h=(0,i.useRef)(null),f=(0,i.useRef)(null),m=(0,i.useRef)(null);(0,i.useEffect)(()=>{if(!u)return;let e=f.current;if(!e)return;let t=h.current,n=document.body.style.overflow;return document.body.style.overflow="hidden",e.showModal(),m.current?.focus({preventScroll:!0}),()=>{document.body.style.overflow=n,e.open&&e.close(),t?.isConnected&&t.focus({preventScroll:!0})}},[u]);let g=()=>{f.current?.open&&f.current.close(),p(!1)};return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("button",{ref:h,type:"button",className:o,style:{display:"block",padding:0,border:"none",background:"none",color:"inherit",cursor:"zoom-in",...l},onClick:()=>p(!0),"aria-label":c,"aria-haspopup":"dialog","aria-expanded":u,title:d,children:s}),u&&(0,r.jsxs)("dialog",{ref:f,className:"image-preview-dialog","aria-label":a("chat.previewImage"),onCancel:e=>{e.preventDefault(),e.stopPropagation(),g()},onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),e.stopPropagation(),g())},onClick:e=>{e.target===e.currentTarget&&g()},children:[(0,r.jsx)("img",{className:"image-preview-image",src:t,alt:n}),(0,r.jsx)("button",{ref:m,type:"button",className:"image-preview-close",onClick:g,"aria-label":a("chat.close"),title:a("chat.close"),children:(0,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M6 6l12 12M18 6 6 18"})})})]})]})}var sv=n(50640),sb=n(55961),sy=n(7644);let sw=[{id:"auto",label:"settings.themeSystem",scheme:null},{id:"light",label:"settings.themeLight",scheme:"light"},{id:"mist",label:"settings.themeMist",scheme:"light"},{id:"lilac",label:"settings.themeLilac",scheme:"light"},{id:"sand",label:"settings.themeSand",scheme:"light"},{id:"rose",label:"settings.themeRose",scheme:"light"},{id:"dark",label:"settings.themeDark",scheme:"dark"},{id:"pine",label:"settings.themePine",scheme:"dark"},{id:"dusk",label:"settings.themeDusk",scheme:"dark"},{id:"ember",label:"settings.themeEmber",scheme:"dark"},{id:"slate",label:"settings.themeSlate",scheme:"dark"},{id:"contrast-light",label:"settings.themeContrastLight",scheme:"light"},{id:"contrast-dark",label:"settings.themeContrastDark",scheme:"dark"},{id:"zenburn",label:"settings.themeZenburn",scheme:"dark"},{id:"powerlevel10k",label:"settings.themePowerlevel10k",scheme:"dark"},{id:"one-half-dark",label:"settings.themeOneHalfDark",scheme:"dark"}];sw.flatMap(e=>"light"===e.scheme?[e.id]:[]);let sk=sw.flatMap(e=>"dark"===e.scheme?[e.id]:[]);function sj(e){return sk.includes(e)}let sS="pi-theme",sC={preference:"auto",theme:"light"},sN=new Set,sE=null,s$=!1;function sI(){return window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}function sM(e){return"auto"===e?sI():e}function sT(e){"u">typeof document&&(document.documentElement.dataset.theme=e,document.documentElement.classList.toggle("dark",sj(e)))}function sR(){if(sE)return sE;let e=function(){try{let e=localStorage.getItem(sS);if(sw.some(t=>t.id===e))return e}catch{}return"auto"}(),t=sM(e);return sT(t),sE={preference:e,theme:t}}function sA(e,t,n){if(sT(t),n)try{localStorage.setItem(sS,e)}catch{}sE={preference:e,theme:t},sN.forEach(e=>e())}function sL(){let e=sR();if("auto"!==e.preference)return;let t=sI();t!==e.theme&&sA("auto",t,!1)}function sz(e){return sN.add(e),sR(),s$||!window.matchMedia||(window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change",sL),window.addEventListener("focus",sL),document.addEventListener("visibilitychange",()=>{"visible"===document.visibilityState&&sL()}),s$=!0),sL(),()=>{sN.delete(e)}}function sP(){return sR()}function sW(){return sC}function sO(){let e=(0,i.useSyncExternalStore)(sz,sP,sW),t=(0,i.useCallback)((e,t)=>{if(sR().preference===e)return;let n=sM(e),r=()=>{sA(e,n,!0)},i=window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;if("function"!=typeof document.startViewTransition||i)return void r();let s=t?.x??window.innerWidth/2,o=t?.y??window.innerHeight/2,l=Math.hypot(Math.max(s,window.innerWidth-s),Math.max(o,window.innerHeight-o));document.startViewTransition(r).ready.then(()=>{document.documentElement.animate({clipPath:[`circle(0px at ${s}px ${o}px)`,`circle(${l}px at ${s}px ${o}px)`]},{duration:450,easing:"cubic-bezier(0.22, 0.61, 0.36, 1)",pseudoElement:"::view-transition-new(root)"})}).catch(()=>{})},[]);return{theme:e.theme,preference:e.preference,setThemePreference:t,isDark:sj(e.theme)}}let sF={background:"#23272e",foreground:"#dcdfe4",cursor:"#ffffff",cursorAccent:"#23272e",selectionBackground:"#343a44",black:"#282c34",red:"#e06c75",green:"#98c379",yellow:"#e5c07b",blue:"#61afef",magenta:"#c678dd",cyan:"#56b6c2",white:"#dcdfe4",brightBlack:"#5a6374",brightRed:"#e06c75",brightGreen:"#98c379",brightYellow:"#e5c07b",brightBlue:"#61afef",brightMagenta:"#c678dd",brightCyan:"#56b6c2",brightWhite:"#dcdfe4"},sD={'code[class*="language-"]':{color:sF.foreground,fontFamily:"var(--font-mono)",fontWeight:"var(--font-mono-weight)",textShadow:"none"},'pre[class*="language-"]':{color:sF.foreground,backgroundColor:"var(--tool-bg)",textShadow:"none"},...Object.fromEntries(["comment","prolog","doctype","cdata"].map(e=>[e,{color:"#abb2bf"}])),...Object.fromEntries(["string","char","attr-value","inserted"].map(e=>[e,{color:sF.green}])),...Object.fromEntries(["keyword","important","regex"].map(e=>[e,{color:sF.magenta}])),...Object.fromEntries(["number","boolean","constant","symbol","class-name"].map(e=>[e,{color:sF.yellow}])),...Object.fromEntries(["function","property","builtin","attr-name"].map(e=>[e,{color:sF.blue}])),...Object.fromEntries(["operator","entity","url"].map(e=>[e,{color:sF.cyan}])),...Object.fromEntries(["tag","deleted","variable"].map(e=>[e,{color:sF.red}])),punctuation:{color:sF.foreground},bold:{fontWeight:700},italic:{fontStyle:"italic"}},sB={background:"#121212",foreground:"#eeeeee",cursor:"#5fafff",cursorAccent:"#121212",selectionBackground:"#303030",black:"#121212",red:"#ff5f5f",green:"#5fd700",yellow:"#ffd75f",blue:"#5fafff",magenta:"#af87ff",cyan:"#5fd7ff",white:"#d0d0d0",brightBlack:"#a8a8a8",brightRed:"#ff8787",brightGreen:"#87ff5f",brightYellow:"#ffff87",brightBlue:"#87d7ff",brightMagenta:"#d7afff",brightCyan:"#87ffff",brightWhite:"#ffffff"},sH={'code[class*="language-"]':{color:sB.foreground,fontFamily:"var(--font-mono)",fontWeight:"var(--font-mono-weight)",textShadow:"none"},'pre[class*="language-"]':{color:sB.foreground,backgroundColor:"var(--tool-bg)",textShadow:"none"},...Object.fromEntries(["comment","prolog","doctype","cdata"].map(e=>[e,{color:sB.brightBlack}])),...Object.fromEntries(["string","char","attr-value","inserted"].map(e=>[e,{color:sB.green}])),...Object.fromEntries(["keyword","boolean","important","regex"].map(e=>[e,{color:sB.magenta}])),...Object.fromEntries(["number","constant","symbol","attr-name"].map(e=>[e,{color:sB.yellow}])),...Object.fromEntries(["function","property","builtin"].map(e=>[e,{color:sB.blue}])),...Object.fromEntries(["operator","entity","url","class-name"].map(e=>[e,{color:sB.cyan}])),...Object.fromEntries(["tag","deleted"].map(e=>[e,{color:sB.red}])),punctuation:{color:"#bcbcbc"},variable:{color:sB.foreground},bold:{fontWeight:700},italic:{fontStyle:"italic"}};function s_(e){return"powerlevel10k"===e?sH:"one-half-dark"===e?sD:void 0}let sU=!1,sK=null;function sq(){return sU}function sV(){let e=!(arguments.length>0)||void 0===arguments[0]||arguments[0],[t,r]=(0,i.useState)(sq);return(0,i.useEffect)(()=>{if(t||!e)return;let i=!0;return(sK??=n.e(1326).then(n.bind(n,61326)).then(()=>{sU=!0},e=>{throw sK=null,e})).then(()=>{i&&r(!0)},()=>{}),()=>{i=!1}},[e,t]),t}let sZ=2e3,sJ=!1,sY=[],sG=!1;function sX(){sG=!1,sY.pop()?.(),sY.length>0&&sQ()}function sQ(){!sG&&(sG=!0,"function"==typeof window.requestIdleCallback?window.requestIdleCallback(sX,{timeout:500}):setTimeout(sX,50))}function s0(e,t){let n=URL.createObjectURL(new Blob([e],{type:"image/svg+xml;charset=utf-8"})),r=document.createElement("a");r.href=n,r.download=t,r.click(),setTimeout(()=>URL.revokeObjectURL(n),0)}function s1(e){let{code:t,isStreaming:s,defaultPreview:o=!1}=e,{isDark:l}=sO(),{t:a}=(0,tm.s)(),[d,c]=(0,i.useState)(o),[u,p]=(0,i.useState)(null),[h,f]=(0,i.useState)(!1),m=(0,i.useRef)(null),g=`${l?"dark":"light"}
|
|
6
6
|
${t}`,x=d&&!s;(0,i.useEffect)(()=>{if(!x)return;let e=!1;return p({key:g,status:"loading"}),(async()=>{let{default:r}=await Promise.all([n.e(866),n.e(8367),n.e(3308)]).then(n.bind(n,43328));if(r.initialize({startOnLoad:!1,securityLevel:"strict",suppressErrorRendering:!0,theme:l?"dark":"default"}),!await r.parse(t,{suppressErrors:!0}))throw Error("Invalid Mermaid diagram");let i="u">typeof crypto&&"randomUUID"in crypto?`mermaid-${crypto.randomUUID()}`:`mermaid-${Date.now()}-${Math.random().toString(36).slice(2)}`,s=await r.render(i,t);e||p({key:g,status:"ready",svg:s.svg})})().catch(()=>{e||p({key:g,status:"error"})}),()=>{e=!0}},[t,g,l,x]);let v=(0,i.useMemo)(()=>(0,r.jsx)(s2,{isStreaming:s,previewVisible:x,onToggle:()=>c(e=>!e),title:x?a("i18n.showMermaidSource"):a("i18n.previewMermaid")}),[s,x,a]);if(!x)return(0,r.jsx)(oe,{code:t,lang:"mermaid",headerAction:v,isStreaming:s});let b=u?.key===g&&"error"===u.status?(0,r.jsx)("div",{className:"mermaid-block mermaid-block-error",children:a("i18n.invalidMermaid")}):u?.key!==g||"ready"!==u.status?(0,r.jsx)("div",{className:"mermaid-block mermaid-block-loading","aria-label":a("i18n.renderingMermaid")}):(0,r.jsxs)(r.Fragment,{children:[!h&&(0,r.jsx)("button",{ref:m,type:"button",className:"mermaid-block mermaid-preview-button",title:a("i18n.openMermaidViewer"),"aria-label":a("i18n.openMermaidViewer"),onClick:()=>f(!0),dangerouslySetInnerHTML:{__html:u.svg}}),h&&(0,r.jsx)(s3,{title:a("i18n.mermaidDiagram"),label:a("i18n.mermaidViewer"),onClose:()=>f(!1),children:(0,r.jsx)("div",{dangerouslySetInnerHTML:{__html:u.svg}})})]});return(0,r.jsx)(s8,{lang:"mermaid",actions:(0,r.jsxs)(r.Fragment,{children:[u?.key===g&&"ready"===u.status&&(0,r.jsx)(s4,{onClick:()=>{let e=m.current?.querySelector("svg");e&&s0(new XMLSerializer().serializeToString(e),"mermaid-diagram.svg")}}),v]}),children:b})}function s2(e){let{isStreaming:t,previewVisible:n,onToggle:i,title:s}=e,{t:o}=(0,tm.s)();return(0,r.jsx)("button",{type:"button",onClick:i,disabled:t,title:t?o("i18n.previewAfterStreaming"):s,className:["markdown-code-action",n?"is-active":""].filter(Boolean).join(" "),children:o(n?"i18n.source":"i18n.preview")})}function s4(e){let{onClick:t}=e,{t:n}=(0,tm.s)();return(0,r.jsx)("button",{type:"button",className:"markdown-code-action",title:`${n("i18n.downloadFile")} (SVG)`,"aria-label":`${n("i18n.downloadFile")} (SVG)`,onClick:t,children:"SVG"})}function s8(e){let{lang:t,actions:n,children:i}=e;return(0,r.jsxs)("div",{className:"markdown-code-block",children:[(0,r.jsxs)("div",{className:"markdown-code-header",children:[(0,r.jsx)("span",{className:"markdown-code-lang",children:t}),(0,r.jsx)("div",{className:"markdown-code-actions",children:n})]}),i]})}function s3(e){let{title:t,label:n,onClose:s,children:o}=e,{t:l}=(0,tm.s)(),a=(0,i.useRef)(null),[d,c]=(0,i.useState)(1);return(0,i.useEffect)(()=>{let e=a.current;if(!e)return;let t=document.body.style.overflow;return document.body.style.overflow="hidden",e.showModal(),()=>{document.body.style.overflow=t,e.open&&e.close()}},[]),(0,r.jsx)("dialog",{ref:a,className:"mermaid-zoom-dialog","aria-label":n,onCancel:e=>{e.preventDefault(),s()},onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),s())},children:(0,r.jsxs)("div",{className:"mermaid-zoom-layout",children:[(0,r.jsxs)("div",{className:"mermaid-zoom-toolbar",children:[(0,r.jsx)("span",{className:"mermaid-zoom-title",children:t}),(0,r.jsxs)("div",{className:"mermaid-zoom-actions",children:[(0,r.jsxs)("div",{className:"mermaid-zoom-stepper",children:[(0,r.jsx)("button",{type:"button",onClick:()=>c(e=>Math.max(.5,e-.25)),disabled:d<=.5,title:l("i18n.zoomOut"),"aria-label":l("i18n.zoomOut"),children:(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M5 12h14"})})}),(0,r.jsxs)("span",{className:"mermaid-zoom-value",children:[Math.round(100*d),"%"]}),(0,r.jsx)("button",{type:"button",onClick:()=>c(e=>Math.min(3,e+.25)),disabled:d>=3,title:l("i18n.zoomIn"),"aria-label":l("i18n.zoomIn"),children:(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M12 5v14M5 12h14"})})})]}),(0,r.jsx)("button",{type:"button",className:"mermaid-zoom-icon-button",onClick:()=>c(1),title:l("i18n.fitToWidth"),"aria-label":l("i18n.fitToWidth"),children:(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M8 3H3v5M16 3h5v5M8 21H3v-5M16 21h5v-5"})})}),(0,r.jsx)("button",{type:"button",className:"mermaid-zoom-icon-button",onClick:s,title:l("i18n.close"),"aria-label":l("i18n.close"),children:(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M6 6l12 12M18 6 6 18"})})})]})]}),(0,r.jsx)("div",{className:"mermaid-zoom-viewport",onClick:e=>{e.target===e.currentTarget&&s()},children:(0,r.jsx)("div",{className:"mermaid-zoom-canvas",style:{width:`${100*d}%`},children:o})})]})})}let s5={...sy.xJ,'pre[class*="language-"]':{...sy.xJ['pre[class*="language-"]']}};function s6(e){let{rows:t,stylesheet:n,useInlineStyles:i}=e;return t.map((e,t)=>{let s=e.children??[],o=s[0]?.properties?.className.includes("react-syntax-highlighter-line-number")?s[0]:null,l={...e,properties:{...e.properties,className:[...e.properties?.className??[],"markdown-code-line-text"]},children:o?s.slice(1):s};return(0,r.jsxs)("span",{className:"markdown-code-line",children:[o&&(0,r.jsx)("span",{className:"markdown-code-line-number","data-line-number":t+1,"aria-hidden":"true",style:o.properties?.style}),(0,sv.Ay)({node:l,stylesheet:n,useInlineStyles:i,key:"text"})]},t)})}delete s5['pre[class*="language-"]'].background;let s9=(0,i.memo)(function(e){let{text:t}=e;return(0,r.jsx)("span",{className:"markdown-code-stream-chunk is-frozen",children:t})});function s7(e){let{code:t}=e,n=[],i=0,s=0;for(let e=t.indexOf("\n");-1!==e;e=t.indexOf("\n",e+1))64===(s+=1)&&(n.push(t.slice(i,e)),i=e+1,s=0);let o=t.slice(i);return(0,r.jsxs)(r.Fragment,{children:[n.map((e,t)=>(0,r.jsx)(s9,{text:e},t)),(0,r.jsx)("span",{className:"markdown-code-stream-chunk",children:o})]})}let oe=(0,i.memo)(function(e){let{code:t,lang:n,headerAction:s,isStreaming:o}=e,{isDark:l,theme:a}=sO(),{t:d}=(0,tm.s)(),[c,u]=(0,i.useState)(!1),p=sV(),[h,f]=(0,i.useState)(()=>{var e;return!o&&sq()&&(e=t.length,sJ||(sJ=!0,setTimeout(()=>{sZ=2e3,sJ=!1},0)),!(e>sZ)&&(sZ-=e,!0))});return(0,i.useEffect)(()=>{if(!o&&!h&&p){var e;return e=()=>f(!0),sY.push(e),sQ(),()=>{let t=sY.indexOf(e);-1!==t&&sY.splice(t,1)}}},[o,h,p]),(0,r.jsxs)("div",{className:"markdown-code-block",children:[(0,r.jsxs)("div",{className:"markdown-code-header",children:[(0,r.jsx)("span",{className:"markdown-code-lang",children:n||"text"}),(0,r.jsxs)("div",{className:"markdown-code-actions",children:[s,(0,r.jsx)("button",{onClick:()=>{iN(t).then(()=>{u(!0),setTimeout(()=>u(!1),1500)},()=>{})},className:"markdown-code-action",children:d(c?"i18n.copied":"i18n.copy")})]})]}),o?(0,r.jsx)("pre",{style:{margin:0,padding:"11px 13px",fontSize:"calc(12.5px + var(--chat-font-size-offset, 0px))",lineHeight:1.62,whiteSpace:"pre-wrap",overflowWrap:"anywhere",backgroundColor:"color-mix(in srgb, var(--bg) 92%, var(--bg-panel))"},children:(0,r.jsx)("code",{style:{fontFamily:"var(--font-mono)"},children:(0,r.jsx)(s7,{code:t})})}):(0,r.jsx)(sb.A,{language:h&&n||"text",style:s_(a)??(l?s5:sy.vs),showLineNumbers:!0,lineNumberStyle:{color:"var(--text-dim)",fontStyle:"normal",flexShrink:0},renderer:s6,customStyle:{margin:0,padding:"11px 13px",fontSize:"calc(12.5px + var(--chat-font-size-offset, 0px))",lineHeight:1.62,fontWeight:"var(--font-mono-weight)",border:"none",borderRadius:0,backgroundColor:"color-mix(in srgb, var(--bg) 92%, var(--bg-panel))"},codeTagProps:{style:{fontFamily:"var(--font-mono)",fontWeight:"var(--font-mono-weight)"}},children:t})]})}),ot="http://www.w3.org/2000/svg";function on(e,t){let n=t.parseFromString(e,"image/svg+xml");return n.getElementsByTagName("parsererror").length>0?null:n.documentElement}function or(e){let{code:t,isStreaming:n}=e,{t:s}=(0,tm.s)(),[o,l]=(0,i.useState)(!0),[a,d]=(0,i.useState)(!1),[c,u]=(0,i.useState)(null),[p,h]=(0,i.useState)(null),f=o&&!n,m=(0,i.useMemo)(()=>{var e;let n,r;return f&&"u">typeof DOMParser?(e=new DOMParser,r=on(n=t,e),r?.localName!=="svg"||null!==r.namespaceURI||r.hasAttribute("xmlns")||(r=on(n=t.replace(/<svg(?=[\s/>])/,`<svg xmlns="${ot}"`),e)),r?.localName==="svg"&&r.namespaceURI===ot?n:null):void 0},[t,f]),g=(0,i.useMemo)(()=>m?`data:image/svg+xml;charset=utf-8,${encodeURIComponent(m)}`:null,[m]),x=(0,i.useMemo)(()=>(0,r.jsx)(s2,{isStreaming:n,previewVisible:f,onToggle:()=>l(e=>!e),title:f?s("i18n.showSvgSource"):s("i18n.previewSvg")}),[n,f,s]);if(!f)return(0,r.jsx)(oe,{code:t,lang:"svg",headerAction:x,isStreaming:n});let v=null!==g&&c!==g,b=e=>(0,r.jsx)("img",{src:g??void 0,alt:s("i18n.svgImage"),className:[e,p===g?"is-unsized":""].filter(Boolean).join(" "),onLoad:e=>{let{naturalWidth:t,naturalHeight:n}=e.currentTarget;t&&n||h(g)},onError:()=>u(g)});return(0,r.jsx)(s8,{lang:"svg",actions:(0,r.jsxs)(r.Fragment,{children:[v&&m&&(0,r.jsx)(s4,{onClick:()=>s0(m,"image.svg")}),x]}),children:void 0===m?(0,r.jsx)("div",{className:"mermaid-block mermaid-block-loading"}):v?(0,r.jsxs)(r.Fragment,{children:[!a&&(0,r.jsx)("button",{type:"button",className:"mermaid-block mermaid-preview-button",title:s("i18n.openSvgViewer"),"aria-label":s("i18n.openSvgViewer"),onClick:()=>d(!0),children:b("svg-block-image")}),a&&(0,r.jsx)(s3,{title:s("i18n.svgImage"),label:s("i18n.svgViewer"),onClose:()=>d(!1),children:b("svg-zoom-image")})]}):(0,r.jsx)("div",{className:"mermaid-block mermaid-block-error",children:s("i18n.invalidSvg")})})}let oi=(0,i.createContext)(!1);function os(e){let{src:t,alt:n,cwd:s,...o}=e,l=(0,i.useContext)(oi);delete o.node;let a="string"==typeof t?t:void 0,d=a?io(a,s):null,c=d?`/api/files/${t0(d)}?type=read`:a,u=d??a?.split(/[?#]/,1)[0]??"",p=n?.trim()?n:void 0;if(iT(u))return(0,r.jsx)("audio",{controls:!0,preload:"metadata",src:c,"aria-label":p});if(iR(u))return(0,r.jsx)("video",{controls:!0,playsInline:!0,preload:"metadata",src:c,"aria-label":p});let h=(0,r.jsx)("img",{src:c,alt:n??"",loading:"lazy",...o});return!c||l?h:(0,r.jsx)(sx,{src:c,alt:n??"",className:"markdown-image",children:h})}function oo(e){let{source:t,children:n}=e,{t:s}=(0,tm.s)(),[o,l]=(0,i.useState)(!1);return(0,r.jsxs)("div",{className:"markdown-math-display",children:[n,(0,r.jsx)("button",{type:"button",onClick:()=>{iN(t).then(()=>{l(!0),setTimeout(()=>l(!1),1500)},()=>{})},className:"markdown-code-action markdown-math-copy",children:s(o?"i18n.copied":"i18n.copy")})]})}let ol=(0,i.memo)(function(e){let{markdown:t,remarkPlugins:n,urlTransform:i,rehypePlugins:s,components:o}=e;return(0,r.jsx)(iC.oz,{remarkPlugins:n,rehypePlugins:s,urlTransform:i,components:o,children:t})});function oa(e,t,n){return"mermaid"===e?(0,r.jsx)(s1,{code:t,isStreaming:n,defaultPreview:!0}):"svg"===e?(0,r.jsx)(or,{code:t,isStreaming:n}):(0,r.jsx)(oe,{code:t,lang:e,isStreaming:n})}let od=(0,i.memo)(function(e){let{children:t,className:n,isStreaming:s,cwd:o,onOpenFile:l,onNavigateLink:a,keepLineBreaks:d,keepTextLayout:c}=e,u=(0,i.useMemo)(()=>iG(t),[t]),p=(0,i.useMemo)(()=>s?function(e){let t=e.split("\n");if(/^---[ \t]*\r?$/.test(t[0]))return[e];let n=[],r=[],i=null,s=!1,o=!1,l=!1;for(let a of t){let t=""===a.trim();!l||t||i||s||o||!(r.length>0)||/^[ \t]/.test(a)||sp.test(a)||(n.push(r.join("\n")+"\n"),r=[]),r.push(a);let d=a.match(su);if(d){let e=d[1][0],t=d[1].length;i?e===i.marker&&t>=i.size&&/^[ \t]*\r?$/.test(a.slice(d[0].length))&&(i=null):i={marker:e,size:t}}else if(!i){if(sm.test(a))return[e];let t=a.replace(sf,"");sh.test(t)&&(o=!0),(t.match(/\$\$/g)?.length??0)%2==1&&(s=!s)}l=t}return n.push(r.join("\n")),n}(u):[u],[s,u]),h=(0,i.useMemo)(()=>({code(e){let{className:t,children:n,...i}=e,o=t?.replace("language-","").toLowerCase()??"",l=String(n);return t?.includes("language-")||l.includes("\n")?oa(o,l.replace(/\n$/,""),s):(0,r.jsx)("code",{className:"markdown-inline-code",...i,children:n})},pre(e){let{children:t}=e;return(0,r.jsx)(r.Fragment,{children:t})},a(e){let{href:t,children:n,...i}=e;if(delete i.node,a&&t&&!iV(t)){let e=()=>a(t);return(0,r.jsx)(oi.Provider,{value:!0,children:(0,r.jsx)("a",{...i,role:"link",tabIndex:0,onClick:e,onKeyDown:t=>{"Enter"===t.key&&e()},children:n})})}if(t?.startsWith("#"))return(0,r.jsx)(oi.Provider,{value:!0,children:(0,r.jsx)("a",{href:t,...i,onClick:iZ,children:n})});let s=l?io(t,o):null;return s&&l?(0,r.jsx)(oi.Provider,{value:!0,children:(0,r.jsx)("a",{href:t,...i,onClick:e=>{if(!r9(e))return;let n=e.currentTarget.getAttribute("target");n&&"_self"!==n||(e.preventDefault(),l(s,ia(t)??void 0))},children:n})}):(0,r.jsx)(oi.Provider,{value:!0,children:(0,r.jsx)("a",{href:t,...i,target:"_blank",rel:"noopener noreferrer",children:n})})},img:e=>(0,r.jsx)(os,{cwd:o,...e}),ol(e){let{node:t,start:n,style:i,...s}=e,o=String(Math.abs((n??1)+Math.max(t?.children.filter(e=>"element"===e.type&&"li"===e.tagName).length??0,1)-1)).length;return(0,r.jsx)("ol",{start:n,style:{...i,"--ol-marker-digits":Math.max(o,2)},...s})},div(e){let{node:t,children:n,...i}=e,s=t?.properties?.dataMathSource;return"string"==typeof s?(0,r.jsx)(oo,{source:s,children:n}):(0,r.jsx)("div",{...i,children:n})},table(e){let{children:t}=e;return(0,r.jsx)("div",{className:"markdown-table-frame",children:(0,r.jsx)("div",{className:"markdown-table-wrap",children:(0,r.jsx)("table",{children:t})})})}}),[o,s,l,a]);return(0,r.jsx)("div",{className:["markdown-body",n].filter(Boolean).join(" "),children:p.map((e,t)=>{let n=s?function(e){if(e.includes("\r"))return null;let t=e.split("\n"),n=t[0].match(sg);if(!n||/[\\&]/.test(n[2]))return null;let r=n[1][0],i=n[1].length,s=-1;for(let e=1;e<t.length;e+=1){let n=t[e].match(/^ {0,3}(`{3,}|~{3,})[ \t]*$/);if(n&&n[1][0]===r&&n[1].length>=i){s=e;break}}if(-1!==s&&t.slice(s+1).some(e=>""!==e.trim()))return null;let o=n[2].toLowerCase();if("math"===o)return null;let l=-1!==s?s:t.length>1&&""===t[t.length-1]?t.length-1:t.length;return{lang:o,code:t.slice(1,l).join("\n")}}(e):null;return n?(0,r.jsx)(i.Fragment,{children:oa(n.lang,n.code,!0)},t):(0,r.jsx)(ol,{markdown:e,remarkPlugins:c?sr:d?sn:i5,urlTransform:l?iq:iK,rehypePlugins:a?sd:sa,components:h},t)})})});function oc(e){let{active:t,size:n=14}=e;return(0,r.jsxs)("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0},children:[(0,r.jsx)("path",{d:"M9.5 2A5.5 5.5 0 0 0 4 7.5c0 1.7.78 3.21 2 4.21V14a1 1 0 0 0 1 1h5a1 1 0 0 0 1-1v-2.29c1.22-1 2-2.51 2-4.21A5.5 5.5 0 0 0 9.5 2z",stroke:t?"#d4a017":void 0,fill:t?"rgba(250, 204, 21, 0.18)":"none",style:{filter:t?"drop-shadow(0 0 2px rgba(250, 204, 21, 0.35))":"none"}}),(0,r.jsx)("line",{x1:"7",y1:"18",x2:"12",y2:"18"}),(0,r.jsx)("line",{x1:"8",y1:"21",x2:"11",y2:"21"})]})}let ou=/<(read-files|modified-files)>\s*([\s\S]*?)\s*<\/\1>/g,op=/(?:\r?\n){2,}((?:[ \t]*<(?:read-files|modified-files)>[ \t]*\r?\n[\s\S]*?\r?\n[ \t]*<\/(?:read-files|modified-files)>[ \t]*(?:\r?\n)?)+)\s*$/,oh=new Map;function of(e){return"number"==typeof e&&Number.isFinite(e)&&e>=0?e:void 0}function om(e,t,n){let r=t.toolCallId;if("string"!=typeof r||"string"==typeof t.parentToolCallId&&""!==t.parentToolCallId)return e;if("tool_execution_start"===t.type){if(e.has(r))return e;let i=new Map(e);return i.set(r,{startedAt:n-(of(t.elapsedMs)??0)}),i}if("tool_execution_end"===t.type){let n=of(t.durationMs);if(void 0===n)return og(e,r);let i=new Map(e);return i.set(r,{durationMs:n}),i}return e}function og(e,t){if(!e.has(t))return e;let n=new Map(e);return n.delete(t),n}function ox(e){let t=new Map([...e].filter(e=>{let[,t]=e;return"durationMs"in t}));return t.size===e.size?e:t.size?t:oh}function ov(e){let t,n=[],r=null,i=0,s=0,o=0,l=0,a=null,d=[],c=[],u=[],p=()=>({lineNo:null,text:"",type:"empty"}),h=()=>{if(!r){d=[],c=[],u=[];return}let e=Math.max(d.length,c.length);for(let t=0;t<e;t++){let e=d[t]?{lineNo:d[t].lineNo,text:d[t].text,type:"removed"}:p(),n=c[t]?{lineNo:c[t].lineNo,text:c[t].text,type:"added"}:p();r.rows.push({type:"line",left:e,right:n})}for(let e of u)r.rows.push({type:"hunk",text:e});d=[],c=[],u=[]};for(let p of e.split(/\r?\n/)){if(!(o>0||l>0)){if(p.startsWith("--- ")){h(),t=ow(p.slice(4));continue}if(p.startsWith("+++ ")){h(),r={oldPath:t,newPath:ow(p.slice(4)),rows:[]},n.push(r),a=null;continue}}let e=p.match(/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/);if(e){r||(r={rows:[]},n.push(r)),h(),i=Number(e[1]),s=Number(e[3]),o=void 0===e[2]?1:Number(e[2]),l=void 0===e[4]?1:Number(e[4]);let t=0===o?i+1:i,d=0===l?s+1:s;if(a){let e=t-a.old,n=d-a.new;(e>0||n>0)&&r.rows.push({type:"gap",count:e===n?e:null})}a={old:t+o,new:d+l},r.rows.push({type:"hunk",text:p});continue}if(!r)continue;if(p.startsWith("\\ ")){d.length||c.length?u.push(p):r.rows.push({type:"hunk",text:p});continue}let f=p[0],m=p.slice(1);" "===f?(h(),r.rows.push({type:"line",left:{lineNo:i++,text:m,type:"context"},right:{lineNo:s++,text:m,type:"context"}}),o>0&&o--,l>0&&l--):"-"===f?(d.push({lineNo:i++,text:m}),o>0&&o--):"+"===f?(c.push({lineNo:s++,text:m}),l>0&&l--):""!==p&&(h(),r.rows.push({type:"hunk",text:p}))}h();let f=n.filter(e=>e.rows.some(e=>"line"===e.type));return f.length>0?f:null}function ob(e){let t=[];for(let n of e.rows)if("hunk"!==n.type){if("gap"===n.type){t.push(n);continue}if("context"===n.left.type&&"context"===n.right.type){t.push({type:"context",text:n.right.text,oldLineNo:n.left.lineNo,newLineNo:n.right.lineNo});continue}"empty"!==n.left.type&&t.push({type:"removed",text:n.left.text,oldLineNo:n.left.lineNo,newLineNo:null}),"empty"!==n.right.type&&t.push({type:"added",text:n.right.text,oldLineNo:null,newLineNo:n.right.lineNo})}return t}function oy(e,t){return 1===e?t("diff.unchangedLine"):t("diff.unchangedLines",{count:e})}function ow(e){return e.split(" ")[0].trim()}function ok(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&"string"==typeof e.oldText&&"string"==typeof e.newText}function oj(e){if(""===e)return{lines:[],lastEnded:!1};let t=e.split(/\r\n|\r|\n/),n=t.length>1&&""===t[t.length-1];return n&&t.pop(),{lines:t,lastEnded:n}}function oS(e,t,n,r){return e.lines[t]===n.lines[r]&&(t<e.lines.length-1||e.lastEnded)===(r<n.lines.length-1||n.lastEnded)}function oC(e){if(e.length<=4e3)return e;let t=4e3,n=e.charCodeAt(t-1);return n>=55296&&n<=56319&&t--,`${e.slice(0,t)}…`}let oN=()=>({lineNo:null,text:"",type:"empty"}),oE=new Set,o$="pi-thinking-expanded",oI="pi-thinking-expanded-changed";function oM(){try{return"true"===window.localStorage.getItem(o$)}catch{return!1}}function oT(e){let{files:t,onOpenFile:n}=e,{t:i}=(0,tm.s)();return 0===t.length?null:(0,r.jsx)("div",{"aria-label":i("chat.filesWritten"),style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:6,marginTop:6},children:t.map(e=>{let{filePath:t}=e,s=t1(t);return(0,r.jsxs)("button",{type:"button",title:t,"aria-label":i("chat.openWrittenFile",{name:s}),onClick:()=>n?.(t),style:{display:"inline-flex",alignItems:"center",gap:4,padding:"2px 8px",fontSize:12,fontFamily:"var(--font-mono)",color:"var(--text)",background:"var(--bg-subtle)",border:"1px solid var(--border)",borderRadius:6,cursor:"pointer"},children:[tX(s,12),(0,r.jsx)("span",{children:s})]},t)})})}let oR="codemode",oA=new Set(["running","ok","error","cancelled"]);function oL(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function oz(e){return"number"==typeof e&&Number.isFinite(e)?e:void 0}function oP(e){if(!oL(e)||!Array.isArray(e.calls))return{calls:[],omitted:0};let t=e.calls.flatMap(e=>{let t=function(e){if(!oL(e)||"string"!=typeof e.name)return null;let t="string"==typeof e.status&&oA.has(e.status)?e.status:"ok",n=oz(e.durationMs),r=oz(e.cost);return{id:"string"==typeof e.id?e.id:"",name:e.name,args:"string"==typeof e.args?e.args:"",status:t,...void 0!==n?{durationMs:n}:{},..."string"==typeof e.error&&e.error?{error:e.error}:{},...void 0!==r&&r>0?{cost:r}:{}}}(e);return t?[t]:[]}),n=oz(e.omittedCalls);return{calls:t,omitted:void 0!==n&&n>0?Math.floor(n):0}}let oW=/^Script (completed|failed)\nWall time ([\d.]+) seconds\nOutput:\n$/;function oO(e){return`$${e>=.01?e.toFixed(2):e.toPrecision(2)}`}let oF={running:{icon:"…",color:"#d97706"},ok:{icon:"✓",color:"#16a34a"},error:{icon:"✗",color:"#f87171"},cancelled:{icon:"⊘",color:"var(--text-dim)"}};function oD(e){var t;let{call:n}=e,{t:i}=(0,tm.s)(),s=oF[n.status],o=void 0===(t=n.durationMs)?"":t<1e3?`${Math.round(t)}ms`:`${(t/1e3).toFixed(1)}s`;return(0,r.jsxs)("li",{style:{display:"flex",flexDirection:"column",gap:2,minWidth:0},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"baseline",gap:6,minWidth:0},children:[(0,r.jsx)("span",{role:"img","aria-label":i(`codemode.status.${n.status}`),title:i(`codemode.status.${n.status}`),style:{color:s.color,width:12,flexShrink:0,textAlign:"center"},children:s.icon}),(0,r.jsx)("span",{style:{color:"var(--text-muted)",fontWeight:600,flexShrink:0},children:n.name}),n.args&&(0,r.jsx)("span",{style:{color:"var(--text-dim)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1,minWidth:0},children:n.args}),o&&(0,r.jsx)("span",{style:{color:"var(--text-dim)",flexShrink:0,marginLeft:"auto",fontVariantNumeric:"tabular-nums"},children:o}),void 0!==n.cost&&(0,r.jsx)("span",{style:{color:"var(--text-dim)",flexShrink:0,fontVariantNumeric:"tabular-nums"},children:oO(n.cost)})]}),n.error&&(0,r.jsx)("div",{style:{color:"#f87171",paddingLeft:18,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:n.error})]})}function oB(e){let t,{calls:n,omitted:s,isError:o}=e,{t:l}=(0,tm.s)(),[a,d]=(0,i.useState)(!1);if(0===n.length&&0===s)return null;let c=a?0:Math.max(0,n.length-20),u=c>0?n.slice(c):n,p=(t=n.filter(e=>void 0!==e.cost)).length>1?t.reduce((e,t)=>e+(t.cost??0),0):null;return(0,r.jsxs)("div",{style:{borderTop:o?"1px solid rgba(248,113,113,0.25)":"1px solid rgba(34,197,94,0.2)",background:"var(--bg-subtle)",padding:"6px 10px",fontFamily:"var(--font-mono)",fontSize:"calc(11.5px + var(--chat-font-size-offset, 0px))",lineHeight:1.5,display:"flex",flexDirection:"column",gap:3,minWidth:0},children:[(0,r.jsx)("div",{style:{color:"var(--text-dim)",fontFamily:"inherit",fontSize:11},children:l("codemode.calls")}),s>0&&(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:l("codemode.omittedCalls",{count:s})}),c>0&&(0,r.jsx)("button",{type:"button",onClick:()=>d(!0),style:{alignSelf:"flex-start",padding:0,border:"none",background:"none",color:"var(--accent)",cursor:"pointer",font:"inherit"},children:l("codemode.showEarlierCalls",{count:c})}),(0,r.jsx)("ul",{style:{listStyle:"none",margin:0,padding:0,display:"flex",flexDirection:"column",gap:3,minWidth:0},children:u.map((e,t)=>(0,r.jsx)(oD,{call:e},e.id||`${c+t}`))}),null!==p&&(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:l("codemode.modelCost",{cost:oO(p)})})]})}function oH(e){return"string"==typeof e?e.trim()?e:null:"number"==typeof e||"boolean"==typeof e?String(e):null}function o_(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:", ";if(!Array.isArray(e))return oH(e);if(0===e.length||!e.every(e=>null===e||"object"!=typeof e))return null;let n=e.map(oH).filter(e=>null!==e);return n.length>0?n.join(t):null}var oU=n(9701);let oK=new Map,oq="transcriptNotices";function oV(e){if("object"!=typeof e||null===e)return[];let t=e[oq];return Array.isArray(t)?t:[]}function oZ(e){return e<1e3?e.toString():e<1e4?`${(e/1e3).toFixed(1)}k`:e<1e6?`${Math.round(e/1e3)}k`:e<1e7?`${(e/1e6).toFixed(1)}M`:`${Math.round(e/1e6)}M`}let oJ="#d97706";function oY(e,t){let n=t>=.01?`$${t.toFixed(2)}`:void 0;return n?e("transcriptNotice.costSuffix",{cost:n}):""}function oG(e,t){switch(t.kind){case"cache_miss":{let n={tokens:oZ(t.missedTokens),cost:oY(e,t.missedCost)};if(t.modelChanged)return e("transcriptNotice.cacheMissModelSwitch",n);if(void 0!==t.idleMinutes)return e("transcriptNotice.cacheMissIdle",{...n,minutes:t.idleMinutes});return e("transcriptNotice.cacheMiss",n)}case"cache_warm":var n;return e("transcriptNotice.cacheWarmed",{note:t.note?e("transcriptNotice.cacheWarmedNote",{note:t.note}):"",cost:(n=t.cost,`$${n.toFixed(6).replace(/(\.\d{3}\d*?)0+$/,"$1")}`)});case"summary_cost":return e("compaction"===t.source?"transcriptNotice.compactionCost":"transcriptNotice.branchSummaryCost",{tokens:oZ(t.tokens),cost:oY(e,t.cost)});case"thinking_dropped":return e(1===t.count?"transcriptNotice.thinkingDroppedOne":"transcriptNotice.thinkingDropped",{count:t.count})}}let oX=(0,i.memo)(function(e){let{notices:t}=e,{t:n}=(0,tm.s)(),i=t.filter(e=>"summary_cost"!==e.kind||"compaction"!==e.source);return 0===i.length?null:(0,r.jsx)("div",{className:"transcript-notices",style:{display:"flex",flexDirection:"column",gap:2,margin:"-6px 0 12px"},children:i.map((e,t)=>{let i="cache_warm"!==e.kind;return(0,r.jsxs)("div",{style:{display:"flex",alignItems:"flex-start",gap:6,fontSize:12,lineHeight:1.5,color:i?oJ:"var(--text-dim)",overflowWrap:"anywhere"},children:[i&&(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0,marginTop:3},children:[(0,r.jsx)("path",{d:"M10.3 3.9 1.8 18a2 2 0 0 0 1.7 3h17a2 2 0 0 0 1.7-3L13.7 3.9a2 2 0 0 0-3.4 0z"}),(0,r.jsx)("line",{x1:"12",y1:"9",x2:"12",y2:"13"}),(0,r.jsx)("line",{x1:"12",y1:"17",x2:"12.01",y2:"17"})]}),(0,r.jsx)("span",{children:oG(n,e)})]},t)})})}),oQ=/[\u3000-\u30ff\u3400-\u9fff\uf900-\ufaff\u{20000}-\u{2fa1f}\uac00-\ud7af]/u;function o0(e){let t=0,n=0;for(let r of e)oQ.test(r)?t++:n++;return t+n/4}let o1=new Map;function o2(e){let{children:t,className:n,...s}=e,{t:o}=(0,tm.s)(),[l,a]=(0,i.useState)(!1);if(t.length<=1e5)return(0,r.jsx)(od,{className:n,...s,children:t});if(!l){var d;return(0,r.jsxs)("button",{onClick:()=>a(!0),style:{display:"block",width:"100%",margin:"4px 0",padding:"7px 10px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-panel)",color:"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left"},children:["⚠ ",o("i18n.largeMessageReveal",{size:(d=t.length)>=1e6?`${(d/1e6).toFixed(1)} MB`:d>=1e3?`${Math.round(d/1e3)} KB`:`${d} B`})]})}return(0,r.jsx)("div",{className:n,style:{maxHeight:420,overflow:"auto",fontSize:"calc(12px + var(--chat-font-size-offset, 0px))",lineHeight:1.5},children:(0,r.jsx)("pre",{style:{margin:0,padding:"8px 10px",whiteSpace:"pre-wrap",wordBreak:"break-word",fontFamily:"var(--font-mono)",color:"var(--text-muted)"},children:t})})}function o4(e){if(!e)return null;let t=new Date(e),n=new Date,r=t.getFullYear()===n.getFullYear()&&t.getMonth()===n.getMonth()&&t.getDate()===n.getDate(),i=t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});if(r)return i;let s=t.toLocaleDateString([],{month:"short",day:"numeric",year:t.getFullYear()!==n.getFullYear()?"numeric":void 0});return`${s} ${i}`}function o8(e,t,n){if(t===n||"assistant"!==e.role)return!0;for(let r of e.content??[])if("toolCall"===r.type&&t?.get(r.toolCallId)!==n?.get(r.toolCallId))return!1;return!0}let o3=(0,i.memo)(function(e){let{message:t,isStreaming:n,toolResults:i,toolClocks:s,modelNames:o,cwd:l,onOpenFile:a,onOpenSubagent:d,entryId:c,searchBlock:u,onFork:p,forking:h,onEditContent:f,onCancelEdit:m,isEditing:g,showTimestamp:x,prevTimestamp:v,sessionId:b,writtenFiles:y,turnDurationMs:w,onCompact:k,isCompacting:j,compactError:S}=e;return"user"===t.role?(0,r.jsx)(o5,{message:t,cwd:l,onOpenFile:a,entryId:c,onFork:p,forking:h,onEditContent:f,onCancelEdit:m,isEditing:g}):"assistant"===t.role?(0,r.jsx)(o9,{message:t,isStreaming:n,toolResults:i,toolClocks:s,modelNames:o,cwd:l,onOpenFile:a,onOpenSubagent:d,showTimestamp:x,prevTimestamp:v,sessionId:b,entryId:c,searchBlock:u,writtenFiles:y,turnDurationMs:w,onCompact:k,isCompacting:j,compactError:S}):"toolResult"===t.role?null:"custom"===t.role?"compaction"===t.customType?(0,r.jsx)(lw,{message:t}):(0,r.jsx)(lC,{message:t,cwd:l,onOpenFile:a}):"bashExecution"===t.role?(0,r.jsx)(lW,{message:t,sessionId:b}):null},(e,t)=>e.message===t.message&&e.isStreaming===t.isStreaming&&o8(e.message,e.toolResults,t.toolResults)&&o8(e.message,e.toolClocks,t.toolClocks)&&e.modelNames===t.modelNames&&e.cwd===t.cwd&&e.onOpenFile===t.onOpenFile&&e.onOpenSubagent===t.onOpenSubagent&&e.entryId===t.entryId&&e.searchBlock===t.searchBlock&&e.onFork===t.onFork&&e.forking===t.forking&&e.onEditContent===t.onEditContent&&e.onCancelEdit===t.onCancelEdit&&e.isEditing===t.isEditing&&e.showTimestamp===t.showTimestamp&&e.prevTimestamp===t.prevTimestamp&&e.writtenFiles===t.writtenFiles&&e.turnDurationMs===t.turnDurationMs&&e.sessionId===t.sessionId&&e.onCompact===t.onCompact&&e.isCompacting===t.isCompacting&&e.compactError===t.compactError);function o5(e){let{message:t,cwd:n,onOpenFile:s,entryId:o,onFork:l,forking:a,onEditContent:d,onCancelEdit:c,isEditing:u}=e,{t:p}=(0,tm.s)(),[h,f]=(0,i.useState)(!1),[m,g]=(0,i.useState)(!1),[x,v]=(0,i.useState)(!1),b=("string"==typeof t.content?t.content:t.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n")).replace(/\r\n?/g,"\n"),y="string"==typeof t.content?[]:t.content.filter(e=>"image"===e.type),w=nC(b),k=w?.search(/\s/)??-1,j=w?-1===k?w:w.slice(0,k):"",S=w&&-1!==k?w.slice(k+1):"",C=o4(t.timestamp),N=!!o&&!!l,E=w??b,$=w?function(e,t){if("string"==typeof e.content)return{...e,content:t};let n=[],r=!1;for(let i of e.content){if("text"!==i.type){n.push(i);continue}r||(n.push({...i,text:t}),r=!0)}return r||n.unshift({type:"text",text:t}),{...e,content:n}}(t,w):t,I=y.length>0&&(0,r.jsx)("div",{style:{display:"flex",gap:6,flexWrap:"wrap",marginBottom:8*!!b},children:y.map((e,t)=>{let n=e.source?"base64"===e.source.type?`data:${e.source.media_type};base64,${e.source.data}`:e.source.url??"":e.data?`data:${e.mimeType};base64,${e.data}`:"";return(0,r.jsx)(sx,{src:n,children:(0,r.jsx)("img",{src:n,alt:"",style:{maxWidth:240,maxHeight:240,borderRadius:6,objectFit:"contain",display:"block",border:"1px solid rgba(59,130,246,0.15)"}})},t)})}),M=!!o&&!!d,T=!!u&&!!c;return(0,r.jsxs)("div",{style:{marginBottom:16,display:"flex",flexDirection:"column",alignItems:"flex-end"},onMouseEnter:()=>f(!0),onMouseLeave:()=>f(!1),children:[(0,r.jsx)("div",{style:{display:"flex",alignItems:"flex-end",gap:6,maxWidth:"85%"},children:(0,r.jsx)("div",{style:{flex:1,minWidth:0,background:u?"color-mix(in srgb, var(--accent) 14%, var(--user-bg))":"var(--user-bg)",border:u?"1px solid color-mix(in srgb, var(--accent) 62%, var(--user-bg))":"1px solid rgba(59,130,246,0.2)",boxShadow:u?"0 0 0 2px color-mix(in srgb, var(--accent) 16%, transparent)":void 0,borderRadius:12,padding:"8px 12px",fontSize:"calc(14px + var(--chat-font-size-offset, 0px))",lineHeight:1.6,color:"var(--text)",wordBreak:"break-word",maxHeight:300,overflowY:"auto"},children:w?(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:6,minWidth:0},children:[I,(0,r.jsxs)("div",{style:{display:"flex",alignItems:"flex-start",gap:8,flexWrap:"wrap"},children:[(0,r.jsxs)("button",{onClick:()=>v(e=>!e),title:p(x?"i18n.collapse":"i18n.expand"),"aria-expanded":x,style:{display:"flex",alignItems:"center",gap:6,flexShrink:0,padding:0,background:"none",border:"none",cursor:"pointer",color:"var(--accent)",fontFamily:"var(--font-mono)",fontSize:"calc(13px + var(--chat-font-size-offset, 0px))",textAlign:"left"},children:[(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:j}),(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,opacity:.75,transform:x?"rotate(180deg)":"none",transition:"transform 0.15s"},"aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"6 9 12 15 18 9"})})]}),S&&(0,r.jsx)("span",{style:{color:"var(--text)",fontSize:"calc(14px + var(--chat-font-size-offset, 0px))",lineHeight:1.6,whiteSpace:"pre-wrap",wordBreak:"break-word",minWidth:0,flex:1},children:S})]}),x&&(0,r.jsx)(od,{className:"markdown-user-message",keepLineBreaks:!0,cwd:n,onOpenFile:s,children:function(e){let t=e.match(nS);if(!t)return null;let n=t[4],r=void 0===n?9:11+n.length;return e.slice(e.indexOf("\n")+1,e.length-r)}(b)??b})]}):(0,r.jsxs)(r.Fragment,{children:[I,b&&(0,r.jsx)(o2,{className:"markdown-user-message",keepLineBreaks:!0,cwd:n,onOpenFile:s,children:b})]})})}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"flex-end",gap:6,marginTop:3},children:[(0,r.jsx)("div",{style:{display:"flex",gap:3,opacity:+!!h,pointerEvents:h?"auto":"none",transition:"opacity 0.12s"},children:(0,r.jsxs)("button",{onClick:()=>{iN(E).then(()=>{g(!0),setTimeout(()=>g(!1),1500)},()=>{})},title:p("i18n.copyMessage"),style:{display:"flex",alignItems:"center",gap:4,padding:"3px 8px",height:22,background:"none",border:"none",borderRadius:5,color:m?"var(--accent)":"var(--text-dim)",cursor:"pointer",fontSize:11,fontWeight:400,whiteSpace:"nowrap",transition:"color 0.12s"},onMouseEnter:e=>{m||(e.currentTarget.style.color="var(--accent)")},onMouseLeave:e=>{m||(e.currentTarget.style.color="var(--text-dim)")},children:[m?(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}):(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),(0,r.jsx)("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]}),(0,r.jsx)("span",{className:"message-action-label",children:p(m?"i18n.copied":"i18n.copy")})]})}),(N||M||T)&&(0,r.jsxs)("div",{style:{display:"flex",gap:3,opacity:h||a||T?1:0,pointerEvents:h||a||T?"auto":"none",transition:"opacity 0.12s"},children:[M&&!T&&(0,r.jsxs)("button",{onClick:()=>d($,o),title:p("i18n.editFromHereTitle"),style:{display:"flex",alignItems:"center",gap:4,padding:"3px 8px",height:22,background:"none",border:"none",borderRadius:5,color:"var(--text-dim)",cursor:"pointer",fontSize:11,fontWeight:400,whiteSpace:"nowrap",transition:"color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.color="var(--accent)"},onMouseLeave:e=>{e.currentTarget.style.color="var(--text-dim)"},children:[(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("polyline",{points:"15 10 20 15 15 20"}),(0,r.jsx)("path",{d:"M4 4v7a4 4 0 0 0 4 4h12"})]}),(0,r.jsx)("span",{className:"message-action-label",children:p("i18n.editFromHere")})]}),T&&(0,r.jsxs)("button",{type:"button",onClick:c,title:p("i18n.cancel"),"aria-label":p("i18n.cancel"),style:{display:"flex",alignItems:"center",gap:4,padding:"3px 8px",height:22,background:"none",border:"none",borderRadius:5,color:"var(--accent)",cursor:"pointer",fontSize:11,fontWeight:500,whiteSpace:"nowrap"},children:[(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M6 6l12 12M18 6L6 18"})}),(0,r.jsx)("span",{className:"message-action-label",children:p("i18n.cancel")})]}),N&&(0,r.jsxs)("button",{onClick:()=>{l(o,$)},disabled:a,title:p(a?"i18n.creatingSession":"i18n.newSessionTitle"),style:{display:"flex",alignItems:"center",gap:4,padding:"3px 8px",height:22,background:"none",border:"none",borderRadius:5,color:a?"var(--accent)":"var(--text-dim)",cursor:a?"not-allowed":"pointer",fontSize:11,fontWeight:400,whiteSpace:"nowrap",transition:"color 0.12s"},onMouseEnter:e=>{a||(e.currentTarget.style.color="var(--accent)")},onMouseLeave:e=>{a||(e.currentTarget.style.color="var(--text-dim)")},children:[(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),(0,r.jsx)("circle",{cx:"18",cy:"6",r:"3"}),(0,r.jsx)("circle",{cx:"6",cy:"18",r:"3"}),(0,r.jsx)("path",{d:"M18 9a9 9 0 0 1-9 9"})]}),(0,r.jsx)("span",{className:"message-action-label",children:p(a?"i18n.creating":"i18n.newSession")})]})]}),C&&(0,r.jsx)("span",{style:{fontSize:10,color:"var(--text-dim)"},children:C})]})]})}function o6(e){let{modelName:t,estimatedTokens:n=0,tps:i=null}=e,{t:s}=(0,tm.s)(),o=null!==i?i>=50?"#53b3cb":i>=30?"#9bc53d":i>=15?"#f9c22e":"#e01a4f":void 0;return(0,r.jsxs)("div",{style:{fontSize:11,lineHeight:1.5,minHeight:"calc(1.5em + 2px)",color:"var(--text-dim)",marginBottom:4,display:"flex",alignItems:"center",gap:6,fontVariantNumeric:"tabular-nums"},children:[t&&(0,r.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:t}),n>0&&(0,r.jsxs)("span",{style:{display:"flex",alignItems:"center",gap:4,flexShrink:0,whiteSpace:"nowrap",color:"var(--text)"},title:s("i18n.estimatedTokens"),children:[(0,r.jsxs)("span",{style:{display:"flex",alignItems:"center",gap:2,fontSize:11,fontWeight:400},children:[(0,r.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("line",{x1:"5",y1:"1.5",x2:"5",y2:"8.5"}),(0,r.jsx)("polyline",{points:"2 6 5 8.5 8 6"})]}),(0,r.jsx)("span",{children:n})]}),null!==i&&(0,r.jsxs)("span",{style:{marginLeft:6,padding:"1px 6px",minWidth:"calc(8ch + 1px)",boxSizing:"content-box",textAlign:"center",borderRadius:4,background:o,color:"#fff",fontSize:11,fontWeight:400},children:[i.toFixed(1)," t/s"]})]})]})}function o9(e){var t,n,s,o,l;let a,d,c,u,{message:p,isStreaming:h,toolResults:f,toolClocks:m,modelNames:g,cwd:x,onOpenFile:v,onOpenSubagent:b,showTimestamp:y,prevTimestamp:w,sessionId:k,entryId:j,searchBlock:S,writtenFiles:C,turnDurationMs:N,onCompact:E,isCompacting:$,compactError:I}=e,{t:M}=(0,tm.s)(),T=y?o4(p.timestamp):null,R=(0,i.useMemo)(()=>(p.content??[]).map((e,t)=>({block:e,originalIndex:t})).filter(e=>{let{block:t}=e;return!r1(t,{isStreaming:h})}),[p.content,h]),A=(0,i.useMemo)(()=>R.map(e=>{let{block:t}=e;return t}),[R]),L=r4(p,{isStreaming:h}),z=r8(p,{isStreaming:h}),P=r3(p,{isStreaming:h}),W=P&&!r5(p),[O,F]=(0,i.useState)(!1),[D,B]=(0,i.useState)(!1),H=(0,i.useRef)(null),_="number"!=typeof p.timestamp?null:`${p.provider??""}/${p.model??""}@${p.timestamp}`,U=(0,i.useRef)(_);U.current=_;let[K,q]=(0,i.useState)(null),V=(0,i.useRef)(R);V.current=R;let Z=(0,i.useRef)(new Map),J=(0,i.useMemo)(()=>{if(!h)return Z.current=new Map,0;let e=new Map,t=0;for(let{block:n,originalIndex:r}of R){let i="text"===n.type?n.text:"thinking"===n.type?n.thinking:"toolCall"===n.type?n.rawInput??JSON.stringify(n.input??{})??"":null;if(null===i)continue;let s=function(e,t){var n,r;if(!e||!t.startsWith(e.text))return o0(t);let i=e.tokens,s=e.text.length;return s>0&&s<t.length&&(n=e.text.charCodeAt(s-1))>=55296&&n<=56319&&(r=t.charCodeAt(s))>=56320&&r<=57343&&(i-=.25,s--),i+o0(t.slice(s))}(Z.current.get(r),i);e.set(r,{text:i,tokens:s}),t+=s}return Z.current=e,t},[R,h]),Y=(0,i.useRef)(J);Y.current=J;let G=(0,i.useRef)(new Map),[X,Q]=(0,i.useState)(new Map),ee="assistant"===p.role?lr(p.durationMs):void 0,et=(0,i.useMemo)(()=>{let e=ee??(p.timestamp&&w?p.timestamp-w:void 0);if(void 0===e)return;let t=Math.round(e/1e3);return t>0?t:void 0},[ee,p.timestamp,w]),en=(0,i.useMemo)(()=>{let e=new Map;if(!f)return e;for(let[t,n]of f){let r=lr(n.durationMs)??(n.timestamp&&p.timestamp?n.timestamp-p.timestamp:void 0);void 0!==r&&r>=li&&e.set(t,r)}return e},[f,p.timestamp]),er=A.filter(e=>"text"===e.type).map(e=>e.text).join("\n"),ei=p.usage?(s=p.usage,a=[],s.input&&a.push({icon:"up",before:"↑",text:oZ(s.input)}),s.output&&a.push({icon:"down",before:"↓",text:oZ(s.output)}),s.cacheRead&&a.push({text:`R${oZ(s.cacheRead)}`}),s.cacheWrite&&a.push({text:`W${oZ(s.cacheWrite)}`}),s.cost?.total&&a.push({text:`$${s.cost.total.toFixed(4)}`}),a):[];if(z&&ei.unshift({text:M("chat.operationAborted")},...ei.length>0?[{text:"\xb7"}]:[]),void 0!==N){let e;ei.length>0&&ei.push({text:"\xb7"});let t=ik(N);ei.push((o=M("chat.turnDuration",{time:t}),l=t,(e=o.indexOf(l))<0?{text:o}:{icon:"clock",before:o.slice(0,e),text:l,after:o.slice(e+l.length)}))}return((0,i.useEffect)(()=>{if(!h){let e=new Date().getTime();Q(t=>{let n=new Map(t);for(let[t,r]of G.current)n.has(t)||n.set(t,Math.round((e-r)/1e3));return n}),H.current=null,q(null);return}let e=setInterval(()=>{var e;let t,n=V.current,r=Date.now();n.forEach(e=>{let{originalIndex:t}=e;G.current.has(t)||G.current.set(t,r)}),Q(e=>{let t=!1,i=new Map(e);for(let e=0;e<n.length-1;e++){let s=n[e].originalIndex,o=n[e+1].originalIndex;if(!i.has(s)&&G.current.has(s)){let e=G.current.get(s),n=G.current.get(o)??r;i.set(s,Math.round((n-e)/1e3)),t=!0}}return t?i:e});let i=Y.current;if(0===i)return;H.current??=function(e,t,n){let r=null===e?void 0:oK.get(e);if(r)return r;let i={at:n,tokens:t};return null!==e&&(oK.set(e,i),oK.size>32&&oK.delete(oK.keys().next().value)),i}(U.current,i,r);let s=(e=H.current,(t=(r-e.at)/1e3)>.5?(i-e.tokens)/t:null);null!==s&&q(s)},300);return()=>clearInterval(e)},[h]),0!==A.length||h||L||P||z)?(0,r.jsxs)("div",{"data-message-role":"assistant","data-entry-id":j,style:{marginBottom:16},onMouseEnter:()=>F(!0),onMouseLeave:()=>F(!1),children:[(0,r.jsx)(o6,{modelName:p.provider?(t=p.provider,n=p.model,d=t.toLowerCase(),c=n.toLowerCase(),u=Object.entries(g??{}).flatMap(e=>{let[t,n]=e,r=t.indexOf(":");return r>0&&t.slice(0,r).toLowerCase()===d?[{id:t.slice(r+1).toLowerCase(),name:n}]:[]}),u.find(e=>e.id===c)?.name??u.find(e=>c.endsWith(`/${e.id}`))?.name??Object.entries(g??{}).find(e=>{let[t]=e;return t.toLowerCase()===c})?.[1]??`${t}/${n}`):void 0,estimatedTokens:h?Math.round(J):0,tps:h?K:null}),(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:8},children:R.map(e=>{let{block:t,originalIndex:n}=e;return(0,r.jsx)(o7,{block:t,searchTarget:t===S,toolResults:f,toolsNotRun:z||null!==L,isStreaming:h,streamingDuration:X.get(n)??("thinking"===t.type?et:void 0),toolCallDurations:en,toolClocks:m,cwd:x,onOpenFile:v,onOpenSubagent:b,sessionId:k,entryId:j,blockIndex:n},n)})}),L&&(0,r.jsxs)("div",{role:"alert",style:{marginTop:8*(A.length>0),padding:"7px 10px",border:"1px solid rgba(239,68,68,0.3)",borderRadius:6,background:"rgba(239,68,68,0.07)",color:"#ef4444",fontFamily:"var(--font-mono)",fontSize:12,lineHeight:1.5,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:["Error: ",L]}),P&&(0,r.jsxs)("div",{role:"alert",style:{marginTop:A.length>0||L?8:0,padding:"7px 10px",border:"1px solid rgba(234,179,8,0.3)",borderRadius:6,background:"rgba(234,179,8,0.07)",color:"#ca8a04",fontFamily:"var(--font-mono)",fontSize:12,lineHeight:1.5,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:[M(W?"chat.truncatedWithoutAnswer":"chat.truncatedByOutputLimit"),W&&E&&(0,r.jsx)("button",{type:"button",onClick:E,disabled:$,style:{display:"block",marginTop:8,padding:"3px 8px",border:"1px solid currentColor",borderRadius:5,background:"transparent",color:"inherit",cursor:$?"default":"pointer",font:"inherit"},children:M($?"chat.compacting":"chat.compactContext")}),W&&I&&(0,r.jsx)("div",{style:{marginTop:8,color:"#ef4444",whiteSpace:"pre-wrap"},children:I})]}),C&&C.length>0&&(0,r.jsx)(oT,{files:C,onOpenFile:v}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,marginTop:4},children:[ei.length>0&&!h&&(0,r.jsx)("div",{style:{display:"flex",flexWrap:"wrap",columnGap:7,fontSize:11,color:"var(--text-dim)",fontVariantNumeric:"tabular-nums"},children:ei.map((e,t)=>(0,r.jsxs)(i.Fragment,{children:[t>0&&" ",(0,r.jsx)(lP,{part:e})]},t))}),er&&!h&&(0,r.jsxs)("button",{onClick:()=>{iN(er).then(()=>{B(!0),setTimeout(()=>B(!1),1500)},()=>{})},title:M("i18n.copyMessage"),style:{display:"flex",alignItems:"center",gap:4,padding:"3px 8px",height:22,background:"none",border:"none",borderRadius:5,color:D?"var(--accent)":"var(--text-dim)",cursor:"pointer",fontSize:11,fontWeight:400,whiteSpace:"nowrap",opacity:+!!O,pointerEvents:O?"auto":"none",transition:"opacity 0.12s, color 0.12s"},onMouseEnter:e=>{D||(e.currentTarget.style.color="var(--accent)")},onMouseLeave:e=>{D||(e.currentTarget.style.color="var(--text-dim)")},children:[D?(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}):(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),(0,r.jsx)("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]}),(0,r.jsx)("span",{className:"message-action-label",children:M(D?"i18n.copied":"i18n.copy")})]}),T&&!h&&(0,r.jsx)("span",{style:{fontSize:10,color:"var(--text-dim)",marginLeft:"auto",whiteSpace:"nowrap"},children:T})]})]}):null}function o7(e){let{block:t,searchTarget:n,toolResults:i,toolsNotRun:s,isStreaming:o,streamingDuration:l,toolCallDurations:a,toolClocks:d,cwd:c,onOpenFile:u,onOpenSubagent:p,sessionId:h,entryId:f,blockIndex:m}=e;if("text"===t.type)return(0,r.jsx)("div",{"data-message-text":!0,"data-search-target":n||void 0,children:(0,r.jsx)(le,{block:t,isStreaming:o,cwd:c,onOpenFile:u})});if("thinking"===t.type)return(0,r.jsx)(ln,{block:t,duration:l,sessionId:h,entryId:f,blockIndex:m});if("toolCall"===t.type){let e=i?.get(t.toolCallId),n=a?.get(t.toolCallId);return(0,r.jsx)(ll,{block:t,result:e,notRun:s,duration:n,clock:d?.get(t.toolCallId),onOpenSubagent:p})}return null}function le(e){let{block:t,isStreaming:n,cwd:i,onOpenFile:s}=e;return(0,r.jsx)(o2,{isStreaming:n,cwd:i,onOpenFile:s,children:t.text})}function lt(e){let{text:t}=e,n=(0,i.useMemo)(()=>(function(e){let t=[],n=0;for(;e.length-n>8e3;){let r=n+8e3,i=r+8e3,s=e.slice(r,i+1),o=s.indexOf("\n");for(;o>=0&&/\n\r?$/.test(e.slice(r+o-2,r+o));)o=s.indexOf("\n",o+1);if(o>=0){let i=r+o;if(i===e.length-1)break;t.push({text:e.slice(n,i),lineBreak:!0}),n=i+1}else if(e.length>i){let r=e.charCodeAt(i-1),s=r>=55296&&r<=56319?i-1:i;t.push({text:e.slice(n,s),lineBreak:!1}),n=s}else break}return t.push({text:e.slice(n),lineBreak:!1}),t})(t),[t]);return 1===n.length?t:n.map((e,t)=>(0,r.jsx)("div",{children:e.text},t))}function ln(e){var t;let{block:n,duration:s,sessionId:o,entryId:l,blockIndex:a}=e,{t:d}=(0,tm.s)(),[c,u]=(0,i.useState)(oM),[p,h]=(0,i.useState)(null),[f,m]=(0,i.useState)(!1),[g,x]=(0,i.useState)(null),v=`${o}:${l}:${a}`,[b,y]=(0,i.useState)(v);b!==v&&(y(v),h(null),m(!1),x(null));let w=(0,i.useRef)(d);w.current=d;let k=(t=n.thinking,t.trimStart().match(/^[^\r\n]{0,240}/u)?.[0].trimEnd()??"");return(0,i.useEffect)(()=>{let e=()=>u(oM());return window.addEventListener(oI,e),()=>window.removeEventListener(oI,e)},[]),(0,i.useEffect)(()=>{if(!c||!n.deferred||null!==p)return;if(!o||!l)return void x(w.current("i18n.thinkingUnavailable"));let e=!1;return m(!0),x(null),(function(e,t,n){let r=`${e}:${t}:${n}`,i=o1.get(r);if(i)return o1.delete(r),o1.set(r,i),i;let s=fetch(`/api/sessions/${encodeURIComponent(e)}/entries/${encodeURIComponent(t)}/thinking?blockIndex=${n}`).then(async e=>{if(!e.ok)throw Error(`HTTP ${e.status}`);let t=await e.json();if("string"!=typeof t.thinking)throw Error("Invalid thinking response");return t.thinking}).catch(e=>{throw o1.delete(r),e});if(o1.set(r,s),o1.size>100){let e=o1.keys().next().value;e&&o1.delete(e)}return s})(o,l,a).then(t=>{e||(h(t),m(!1))}).catch(t=>{e||(x(t instanceof Error?t.message:String(t)),m(!1))}),()=>{e=!0}},[c,n.deferred,p,o,l,a]),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"flex-start",gap:6,minWidth:0,border:"1px solid var(--border)",borderRadius:7,padding:"6px 10px",background:"var(--bg)",fontFamily:"var(--font-mono)",fontSize:"calc(11px + var(--chat-font-size-offset, 0px))",lineHeight:1.5},children:[(0,r.jsxs)("button",{type:"button","aria-expanded":c,"aria-label":`${d("i18n.thinking")}${k?`: ${k}`:""}`,title:d("i18n.thinking"),onClick:()=>u(e=>!e),style:{display:"inline-flex",alignItems:"center",gap:6,width:c?14:"100%",flexShrink:+!c,minWidth:0,minHeight:"1.5em",padding:0,background:"transparent",border:"none",color:"var(--text-muted)",cursor:"pointer",font:"inherit",textAlign:"left"},children:[(0,r.jsx)(oc,{active:c}),!c&&(0,r.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:k?(0,r.jsx)(iC.oz,{allowedElements:[],unwrapDisallowed:!0,skipHtml:!0,children:k}):"..."})]}),c&&(0,r.jsx)("div",{style:{flex:1,minWidth:0,color:g?"#f87171":"var(--text-muted)",whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:f?d("i18n.loadingThinking"):g??(0,r.jsx)(lt,{text:(n.deferred?p:n.thinking)??""})}),void 0!==s&&(0,r.jsxs)("span",{style:{flexShrink:0,color:"var(--text-dim)",fontVariantNumeric:"tabular-nums"},children:[s,"s"]})]})}function lr(e){return"number"==typeof e&&Number.isFinite(e)&&e>=0?e:void 0}let li=100;function ls(e){let t=e/1e3;if(t<60)return`${t.toFixed(1)}s`;let n=Math.floor(t),r=Math.floor(n/60),i=n%60;return r<60?`${r}m ${i}s`:`${Math.floor(r/60)}h ${r%60}m ${i}s`}function lo(e){let{clock:t}=e,n="startedAt"in t,[s,o]=(0,i.useState)(()=>performance.now());(0,i.useEffect)(()=>{if(!n)return;let e=window.setInterval(()=>o(performance.now()),1e3);return()=>window.clearInterval(e)},[n]);let l="durationMs"in t?t.durationMs:Math.max(0,s-t.startedAt);return l<li?null:(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",flexShrink:0,fontVariantNumeric:"tabular-nums"},children:ls(l)})}function ll(e){var t,n,s,o;let l,{block:a,result:d,notRun:c,duration:u,clock:p,onOpenSubagent:h,resultFooter:f}=e,{t:m}=(0,tm.s)(),[g,x]=(0,i.useState)(()=>{var e;return void 0!==(e=a.toolCallId)&&oE.has(e)}),v=function(e){if(void 0!==e.rawInput||!id(e.toolName))return null;let{content:t}=e.input;return"string"!=typeof t||""===t?null:Object.keys(e.input).every(e=>lI.has(e))?t:null}(a),b=v??(s=a).rawInput??JSON.stringify(s.input,null,2),y=void 0!==a.rawInput,w=ic(a.toolName),k=d&&!d.isError?function(e){let t=e.details;if(!lv(t))return null;let n="string"==typeof t.patch?t.patch:null;if(n)return{text:n};let r="string"==typeof t.diff?t.diff:null;return r?{text:r}:null}(d):null,j=k?.text,S=(0,i.useMemo)(()=>(function(e){if(!e)return null;let t=ov(e);return t?.length===1&&lh(t[0])||null})(j),[j]),C=function(e,t){if(!iu(e.toolName))return null;let n=ix(ip(e.input,e.rawInput));if(n)return n;let r=t&&!t.isError?t.details:void 0;if(lv(r)){let e=iv(r.preview);if(e)return e}return null}(a,d),N=!g||!w||y||d||c?null:a.input,E=(0,i.useMemo)(()=>{let e=null===N?null:function(e){let t=function(e){if(!e||"object"!=typeof e||Array.isArray(e))return null;let t=e.edits;if("string"==typeof t)try{let e=JSON.parse(t);t=ok(e)?[e]:e}catch{}else ok(t)&&(t=[t]);let n=Array.isArray(t)?[...t]:[];return("string"==typeof e.oldText&&"string"==typeof e.newText&&n.push({oldText:e.oldText,newText:e.newText}),0!==n.length&&n.every(ok))?n:null}(e);if(!t)return null;let n="string"==typeof e.path?e.path:"string"==typeof e.file_path?e.file_path:void 0,r=[],i=0,s=!1,o=e=>{let t=r[r.length-1];t?.type==="gap"?t.count=null===t.count||null===e?null:t.count+e:r.push({type:"gap",count:e})},l=(e,t)=>i>=1e3?(s||o(null),s=!0,!1):(r.push({type:"line",left:e,right:t}),i++,!0),a=e=>{let t={lineNo:null,text:oC(e),type:"context"};return l(t,{...t})};for(let[e,n]of t.entries()){if(s)break;e>0&&o(null);let t=oj(n.oldText),r=oj(n.newText),i=t.lines,d=r.lines,c=0;for(;c<i.length&&c<d.length&&oS(t,c,r,c);)c++;let u=i.length,p=d.length;for(;u>c&&p>c&&oS(t,u-1,r,p-1);)u--,p--;let h=Math.max(0,c-4);h>0&&o(h);for(let e=h;e<c&&a(i[e]);e++);let f=Math.max(u-c,p-c);for(let e=0;e<f;e++){let t=c+e<u?i[c+e]:null,n=c+e<p?d[c+e]:null;if(!l(null===t?oN():{lineNo:null,text:oC(t),type:"removed"},null===n?oN():{lineNo:null,text:oC(n),type:"added"}))break}let m=i.length-u,g=Math.min(m,4);for(let e=0;e<g&&a(i[u+e]);e++);!s&&m>g&&o(m-g)}return r.some(e=>"line"===e.type)?{oldPath:n,newPath:n,rows:r}:null}(N);return e?[e]:null},[N]),$=iu(a.toolName)?0===(l=function(e){let t=[];for(let n of e.matchAll(/^\*\*\* (?:Add|Delete|Update) File: (.+)$/gm)){let e=(n[1]??"").trim();e&&!t.includes(e)&&t.push(e)}return t}(ip((o=a).input,o.rawInput))).length?null:l.join(", ").slice(0,120):null,I=a.toolName!==oR||y?null:oL(t=a.input)&&"string"==typeof t.code?t.code:null,M=null===I?null:{code:I,...oP(d?.details)},T=null!==M&&void 0!==d&&0===d.content.length,R=g&&null===v&&null===M&&null===C?function(e){if(null===e||"object"!=typeof e||Array.isArray(e))return null;let t=Object.entries(e);if(0===t.length)return null;let n=[];for(let[e,r]of t){if(null!==r&&"string"!=typeof r&&"number"!=typeof r&&"boolean"!=typeof r)return null;let t=null===r?"null":String(r);n.push({key:e,value:""===t?"(empty)":t,multiline:t.includes("\n")})}return n}(y?(0,oU.o2)(a.rawInput):a.input):null,A=function(e,t){if(!e.startsWith("mcp__")||!("object"==typeof t&&null!==t&&!Array.isArray(t)))return null;let{server:n,tool:r}=t;return"string"==typeof n&&"string"==typeof r&&n&&r?{server:n,tool:r}:null}(a.toolName,d?.details),L=d?M?function(e){let[t,...n]=e;return t?.type==="text"&&"string"==typeof t.text&&oW.test(t.text)?n:[...e]}(d.content):d.content:[],z=d?L.filter(e=>"text"===e.type).map(e=>e.text).join("\n"):null,P=A&&null!==z?function(e){let t=e.trim();if(t.length>2e5||!/^[[{]/.test(t))return e;try{let n=!1,r=JSON.parse(t,(e,t)=>("number"==typeof t&&(!Number.isFinite(t)||Number.isInteger(t)&&!Number.isSafeInteger(t))&&(n=!0),t));return n?e:JSON.stringify(r,null,2)}catch{return e}}(z):z,W=lE(L),O=null!==P&&("(no output)"===P.trim()||""===P.trim()),F=(d?.isError??!1)||iu(a.toolName)&&im(d?.details),D=(n=d?.details)&&"object"==typeof n&&"pi-web-subagent"===n.kind&&"string"==typeof n.sessionId?d.details:null,B=M?M.calls.length+M.omitted:0;return(0,r.jsxs)("div",{style:{borderRadius:7,overflow:"hidden",fontSize:12,border:F?"1px solid rgba(248,113,113,0.45)":"1px solid rgba(34,197,94,0.25)",background:F?"rgba(248,113,113,0.05)":"rgba(34,197,94,0.04)"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"stretch",minWidth:0},children:[(0,r.jsxs)("button",{onClick:()=>{var e;let t=!g;e=a.toolCallId,e&&(t?oE.add(e):oE.delete(e)),x(t)},style:{display:"flex",alignItems:"center",gap:7,flex:1,minWidth:0,padding:"6px 10px",background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left"},children:[(0,r.jsx)("span",{title:A?a.toolName:void 0,style:{color:F?"#f87171":"#16a34a",fontFamily:"var(--font-mono)",fontWeight:600,fontSize:11,flexShrink:0},children:A?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("span",{style:{fontWeight:500,opacity:.75},children:[A.server,"/"]}),A.tool]}):a.toolName}),(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:11,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1,minWidth:0},children:y?m("chat.generatingToolInput"):$??(M?function(e){for(let t of e.split(/\r?\n/)){let e=t.trim();if(e&&!e.startsWith("// @options:"))return e}return""}(M.code):function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,n=arguments.length>2?arguments[2]:void 0;if(!e||"object"!=typeof e||Array.isArray(e))return"";let r=e=>{if(e.length<=120)return e;let t=e.charCodeAt(119);return e.slice(0,t>=55296&&t<=56319?119:120)};if("grep"===n||"find"===n){let t=o_(e.pattern);if(null!==t)return r(t)}for(let t of["command","path","file_path"]){let n=o_(e[t],"command"===t?" ":", ");if(null!==n)return r(n)}if(t)return r(t);for(let t of["pattern","query"]){let n=o_(e[t]);if(null!==n)return r(n)}let i=Object.values(e);for(let e of i){let t=o_(e);if(null!==t)return r(t)}for(let e of i){let t=function e(t){if(Array.isArray(t)){let n=t.map(t=>oH(t)??e(t)).filter(e=>null!==e);return n.length>0?n.join(", "):null}if(t&&"object"==typeof t)for(let n of Object.values(t)){let t=o_(n)??e(n);if(null!==t)return t}return null}(e);if(null!==t)return r(t)}return""}(a.input,S,a.toolName))}),B>0&&(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",flexShrink:0,fontVariantNumeric:"tabular-nums"},children:1===B?m("codemode.callCountOne"):m("codemode.callCount",{count:B})}),void 0!==u?(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",flexShrink:0,fontVariantNumeric:"tabular-nums"},children:ls(u)}):p&&(0,r.jsx)(lo,{clock:p},"startedAt"in p?p.startedAt:"ended"),(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--text-dim)",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,transform:g?"rotate(180deg)":"none",transition:"transform 0.15s"},children:(0,r.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})})]}),D&&h&&(0,r.jsx)("button",{type:"button",onClick:()=>h(D.sessionId,D.description||D.profile),title:m("subagent.openTab"),"aria-label":m("subagent.openTab"),style:{width:32,display:"grid",placeItems:"center",border:"none",borderLeft:"1px solid var(--border)",background:"none",color:"var(--text-muted)",cursor:"pointer",flexShrink:0},children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("rect",{x:"5",y:"7",width:"14",height:"11",rx:"2"}),(0,r.jsx)("path",{d:"M9 11h.01M15 11h.01M9 15h6M12 7V4M10 4h4"})]})})]}),g&&(y||!w||!d&&!c&&!E)&&!C&&(R?(0,r.jsx)("div",{style:{padding:"6px 10px 8px",background:"var(--bg-subtle)",borderTop:F?"1px solid rgba(248,113,113,0.25)":"1px solid rgba(34,197,94,0.2)"},children:(0,r.jsx)(lA,{fields:R})}):(0,r.jsx)("pre",{style:{margin:0,padding:"8px 10px",color:"var(--text-muted)",fontSize:"calc(12px + var(--chat-font-size-offset, 0px))",lineHeight:1.5,overflow:"auto",background:"var(--bg-subtle)",borderTop:F?"1px solid rgba(248,113,113,0.25)":"1px solid rgba(34,197,94,0.2)",whiteSpace:"pre-wrap",wordBreak:"break-all"},children:M?M.code.replace(/\r/g,"").trimEnd():b})),g&&M&&(0,r.jsx)(oB,{calls:M.calls,omitted:M.omitted,isError:F}),W.length>0&&(0,r.jsx)(lb,{images:W,isError:F}),E&&(0,r.jsx)("div",{style:{borderTop:"1px solid rgba(34,197,94,0.15)",background:"var(--bg)"},children:(0,r.jsx)(lc,{files:E})}),g&&C&&(0,r.jsx)("div",{style:{borderTop:"1px solid rgba(34,197,94,0.15)",background:"var(--bg)"},children:(0,r.jsx)(lc,{files:C})}),g&&d&&C&&F&&(0,r.jsx)(ly,{text:P??"",isEmpty:O,isError:F}),g&&d&&!C&&!T&&(k?(0,r.jsx)(la,{diff:k}):(!O||0===W.length)&&(0,r.jsx)(ly,{text:P??"",isEmpty:O,isError:F})),g&&d&&f]})}function la(e){let{diff:t}=e;return(0,r.jsx)("div",{style:{borderTop:"1px solid rgba(34,197,94,0.15)",background:"var(--bg)"},children:(0,r.jsx)(ld,{text:t.text})})}function ld(e){let{text:t}=e,n=(0,i.useMemo)(()=>ov(t),[t]);return n?(0,r.jsx)(lc,{files:n}):(0,r.jsx)(lx,{text:t})}function lc(e){let{files:t}=e,n=tC()?"stacked":"split";return(0,r.jsx)(lu,{files:t,layout:n})}function lu(e){let{files:t,layout:n}=e,{t:i}=(0,tm.s)(),s=t.length>1;return(0,r.jsx)("div",{style:{maxHeight:560,overflowY:"auto",overflowX:"hidden",background:"var(--bg)"},children:t.map((e,t)=>(0,r.jsxs)("div",{style:{minWidth:0,borderTop:0===t?"none":"1px solid var(--border)",fontFamily:"var(--font-mono)",fontWeight:"var(--font-mono-weight)",fontSize:"calc(12px + var(--chat-font-size-offset, 0px))",lineHeight:1.55},children:[s&&"split"===n&&(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"minmax(0, 1fr) minmax(0, 1fr)",position:"sticky",top:0,zIndex:1,background:"var(--bg-panel)",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)(lm,{title:e.oldPath||i("i18n.before"),side:"left"}),(0,r.jsx)(lm,{title:e.newPath||i("i18n.after"),side:"right"})]}),s&&"stacked"===n&&lh(e)&&(0,r.jsx)("div",{title:lh(e),style:{position:"sticky",top:0,zIndex:1,padding:"5px 10px",color:"var(--text-dim)",background:"var(--bg-panel)",borderBottom:"1px solid var(--border)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:lh(e)}),"split"===n&&(0,r.jsx)("div",{style:{display:"grid",gridTemplateColumns:"minmax(0, 1fr) minmax(0, 1fr)"},children:e.rows.map((e,t)=>"hunk"===e.type?null:"gap"===e.type?(0,r.jsx)(lp,{gap:e},t):(0,r.jsxs)("div",{style:{display:"contents"},children:[(0,r.jsx)(lg,{cell:e.left,side:"left"}),(0,r.jsx)(lg,{cell:e.right,side:"right"})]},t))}),"stacked"===n&&ob(e).map((e,t)=>"gap"===e.type?(0,r.jsx)(lp,{gap:e},t):(0,r.jsx)(lf,{line:e},t))]},t))})}function lp(e){let{gap:t}=e,{t:n}=(0,tm.s)();return(0,r.jsx)("div",{style:{gridColumn:"1 / -1",padding:"0 10px",color:"var(--text-dim)",background:"var(--bg-panel)",borderTop:"1px solid var(--border)",borderBottom:"1px solid var(--border)",userSelect:"none"},children:null===t.count?"⋯":`⋯ ${oy(t.count,n)}`})}function lh(e){return e.newPath&&"/dev/null"!==e.newPath?e.newPath:e.oldPath||e.newPath||""}function lf(e){let{line:t}=e;return(0,r.jsx)(lg,{side:"right",cell:{lineNo:"removed"===t.type?t.oldLineNo:t.newLineNo,text:t.text,type:t.type}})}function lm(e){let{title:t,side:n}=e;return(0,r.jsx)("div",{title:t,style:{padding:"5px 10px",color:"var(--text-dim)",borderRight:"left"===n?"1px solid var(--border)":"none",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:t})}function lg(e){let{cell:t,side:n}=e,i="added"===t.type?"rgba(34,197,94,0.12)":"removed"===t.type?"rgba(248,113,113,0.13)":"empty"===t.type?"var(--bg-subtle)":"transparent",s="added"===t.type?"+":"removed"===t.type?"-":" ",o="added"===t.type?"#22c55e":"removed"===t.type?"#f87171":"var(--text-dim)";return(0,r.jsxs)("div",{style:{display:"flex",minWidth:0,background:i,borderRight:"left"===n?"1px solid var(--border)":"none"},children:[(0,r.jsx)("span",{style:{width:42,padding:"0 6px",textAlign:"right",color:"var(--text-dim)",userSelect:"none",background:"var(--bg-panel)",borderRight:"1px solid var(--border)",flexShrink:0},children:t.lineNo??""}),(0,r.jsx)("span",{style:{width:18,padding:"0 5px",color:o,userSelect:"none",fontWeight:"context"===t.type||"empty"===t.type?400:700,flexShrink:0},children:s}),(0,r.jsx)("span",{style:{flex:1,minWidth:0,padding:"0 10px 0 0",color:"empty"===t.type?"var(--text-dim)":"var(--text)",whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:t.text||"\xa0"})]})}function lx(e){let{text:t}=e,n=t.split(/\r?\n/);return(0,r.jsx)("div",{style:{maxHeight:520,overflowY:"auto",overflowX:"hidden",fontFamily:"var(--font-mono)",fontWeight:"var(--font-mono-weight)",fontSize:"calc(12px + var(--chat-font-size-offset, 0px))",lineHeight:1.55,minWidth:0},children:n.map((e,t)=>{let n=e.startsWith("@@")?"hunk":e.startsWith("+")&&!e.startsWith("+++")?"added":e.startsWith("-")&&!e.startsWith("---")?"removed":"context";return(0,r.jsxs)("div",{style:{display:"flex",background:"added"===n?"rgba(34,197,94,0.12)":"removed"===n?"rgba(248,113,113,0.13)":"hunk"===n?"rgba(96,165,250,0.12)":"transparent",borderLeft:"added"===n?"3px solid #22c55e":"removed"===n?"3px solid #f87171":"hunk"===n?"3px solid var(--accent)":"3px solid transparent"},children:[(0,r.jsx)("span",{style:{width:48,padding:"0 8px",color:"var(--text-dim)",background:"var(--bg-panel)",borderRight:"1px solid var(--border)",textAlign:"right",userSelect:"none",flexShrink:0},children:t+1}),(0,r.jsx)("span",{style:{padding:"0 10px",whiteSpace:"pre-wrap",overflowWrap:"anywhere",color:"added"===n?"#22c55e":"removed"===n?"#f87171":"hunk"===n?"var(--accent)":"var(--text)"},children:e||"\xa0"})]},t)})})}function lv(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function lb(e){let{images:t,isError:n}=e;return(0,r.jsx)("div",{style:{display:"flex",gap:8,flexWrap:"wrap",padding:"10px",background:"var(--bg)",borderTop:`1px solid ${n?"rgba(248,113,113,0.3)":"rgba(34,197,94,0.15)"}`},children:t.map((e,t)=>{let n=l$(e);return n?(0,r.jsx)(sx,{src:n,style:{maxWidth:"100%"},children:(0,r.jsx)("img",{src:n,alt:"",loading:"lazy",style:{display:"block",maxWidth:"min(100%, 720px)",maxHeight:520,borderRadius:6,objectFit:"contain",border:"1px solid var(--border)"}})},`${n}-${t}`):null})})}function ly(e){let{text:t,isEmpty:n,isError:i}=e,{t:s}=(0,tm.s)();return(0,r.jsx)("div",{style:{borderTop:`1px solid ${i?"rgba(248,113,113,0.3)":"rgba(34,197,94,0.15)"}`,background:i?"rgba(248,113,113,0.04)":"var(--bg-subtle)"},children:(0,r.jsx)("pre",{style:{margin:0,padding:"8px 10px",color:i?"#f87171":n?"var(--text-dim)":"var(--text-muted)",fontSize:"calc(12px + var(--chat-font-size-offset, 0px))",lineHeight:1.5,overflow:"auto",maxHeight:400,background:"var(--bg)",whiteSpace:"pre-wrap",wordBreak:"break-all",fontStyle:n?"italic":"normal",opacity:n?.6:1},children:n?s("i18n.noOutput"):t})})}function lw(e){let{message:t}=e,{t:n}=(0,tm.s)(),[s,o]=(0,i.useState)(!1),l=lN(t.content),a=o4(t.timestamp),d=t.details?.tokensBefore,c=oV(t).find(e=>"summary_cost"===e.kind&&"compaction"===e.source);return(0,r.jsx)("div",{style:{marginBottom:16},children:(0,r.jsxs)("div",{style:{border:"1px solid var(--border)",borderRadius:8,overflow:"hidden",background:"var(--bg)"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"7px 10px",borderBottom:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)"},children:[(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:11,fontWeight:650},children:"compaction"}),a&&(0,r.jsx)("span",{style:{marginLeft:"auto",color:"var(--text-dim)",fontSize:10},children:a})]}),(0,r.jsxs)("div",{style:{padding:"11px 13px 12px"},children:[(0,r.jsxs)("button",{type:"button","aria-expanded":s,title:n(s?"i18n.collapse":"i18n.expand"),onClick:()=>o(e=>!e),style:{display:"flex",alignItems:"flex-start",gap:8,width:"100%",padding:0,border:"none",background:"transparent",color:"var(--text)",cursor:"pointer",font:"inherit",textAlign:"left"},children:[(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0,marginTop:4,color:"var(--text-muted)",transform:s?"rotate(90deg)":"none",transition:"transform 0.15s"},children:(0,r.jsx)("polyline",{points:"4 2.5 7.5 6 4 9.5"})}),(0,r.jsxs)("span",{style:{minWidth:0},children:[(0,r.jsx)("span",{style:{display:"block",fontSize:"calc(15px + var(--chat-font-size-offset, 0px))",fontWeight:700,lineHeight:1.35},children:n("i18n.conversationCompacted")}),"number"==typeof d&&Number.isFinite(d)&&(0,r.jsx)("span",{style:{display:"block",marginTop:3,color:"var(--text-muted)",fontSize:"calc(13px + var(--chat-font-size-offset, 0px))",lineHeight:1.5},children:n("i18n.compactedFromTokens",{tokens:d.toLocaleString()})}),c&&(0,r.jsx)("span",{style:{display:"block",marginTop:2,color:oJ,fontSize:"calc(12px + var(--chat-font-size-offset, 0px))",lineHeight:1.5},children:oG(n,c)})]})]}),s&&(0,r.jsx)(lk,{summary:l})]})]})})}function lk(e){let{summary:t}=e,{t:n}=(0,tm.s)(),s=(0,i.useMemo)(()=>{let e,n,r,i,s;return e=[],n=[],r=t.match(op),i=r?.[1]??"",s=r?.index===void 0?t:t.slice(0,r.index),i.replace(ou,(t,r,i)=>{let s=i.split(/\r?\n/).map(e=>e.trim()).filter(Boolean);return"read-files"===r?e.push(...s):n.push(...s),""}),{body:s.trim(),readFiles:e,modifiedFiles:n}},[t]);return(0,r.jsxs)("div",{style:{marginTop:10},children:[s.body?(0,r.jsx)(od,{className:"markdown-compaction-message",children:s.body}):(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:12},children:n("i18n.noSummary")}),(0,r.jsx)(lj,{readFiles:s.readFiles,modifiedFiles:s.modifiedFiles})]})}function lj(e){let{readFiles:t,modifiedFiles:n}=e,{t:i}=(0,tm.s)();if(0===t.length+n.length)return null;let s=[];return t.length>0&&s.push(`${t.length} read`),n.length>0&&s.push(`${n.length} modified`),(0,r.jsxs)("details",{className:"compaction-file-details",children:[(0,r.jsx)("summary",{children:i("i18n.fileContext",{details:s.join(", ")})}),n.length>0&&(0,r.jsx)(lS,{title:i("i18n.modifiedFiles"),files:n}),t.length>0&&(0,r.jsx)(lS,{title:i("i18n.readFiles"),files:t})]})}function lS(e){let{title:t,files:n}=e;return(0,r.jsxs)("div",{className:"compaction-file-section",children:[(0,r.jsx)("div",{className:"compaction-file-title",children:t}),(0,r.jsx)("ul",{className:"compaction-file-list",children:n.map(e=>(0,r.jsx)("li",{children:e},e))})]})}function lC(e){let{message:t,cwd:n,onOpenFile:s}=e,{t:o}=(0,tm.s)(),[l,a]=(0,i.useState)(!0),[d,c]=(0,i.useState)(!1),[u,p]=(0,i.useState)(!1),h=lN(t.content),f=lE(t.content),m=void 0!==t.details,g=m?function(e){try{return JSON.stringify(e,null,2)}catch{return String(e)}}(t.details):"",x=t.customType||"extension",v=o4(t.timestamp);return(0,r.jsx)("div",{style:{marginBottom:16},children:(0,r.jsxs)("div",{style:{border:"1px solid var(--border)",borderRadius:8,overflow:"hidden",background:"var(--bg)"},children:[(0,r.jsx)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"7px 10px",borderBottom:l?"1px solid var(--border)":"none",background:"var(--bg-panel)",color:"var(--text-muted)",fontSize:12},children:(0,r.jsxs)("button",{type:"button",onClick:()=>a(e=>!e),"aria-expanded":l,title:o(l?"i18n.collapse":"i18n.expand"),style:{display:"flex",alignItems:"center",gap:8,minWidth:0,flex:1,padding:0,border:"none",background:"none",color:"inherit",cursor:"pointer",fontSize:"inherit",textAlign:"left"},children:[(0,r.jsx)("span",{style:{color:"var(--text-muted)",fontFamily:"var(--font-mono)",fontSize:11,fontWeight:650,flexShrink:0},children:x}),!l&&h&&(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:11,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:h.slice(0,300).replace(/\s+/g," ").trim()}),v&&(0,r.jsx)("span",{style:{marginLeft:"auto",color:"var(--text-dim)",fontSize:10,flexShrink:0},children:v}),(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--text-dim)",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0,transform:l?"rotate(180deg)":"none",transition:"transform 0.15s"},children:(0,r.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})})]})}),l&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("div",{style:{padding:"6px 9px"},children:[f.length>0&&(0,r.jsx)("div",{style:{display:"flex",gap:6,flexWrap:"wrap",marginBottom:8*!!h},children:f.map((e,t)=>{let n=l$(e);return n?(0,r.jsx)(sx,{src:n,children:(0,r.jsx)("img",{src:n,alt:"",style:{maxWidth:240,maxHeight:240,borderRadius:6,objectFit:"contain",display:"block",border:"1px solid var(--border)"}})},t):null})}),h?(0,r.jsx)(od,{className:"markdown-custom-message",keepTextLayout:!0,cwd:n,onOpenFile:s,children:h}):(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:12},children:o("i18n.noMessage")})]}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"4px 9px",borderTop:"1px solid var(--border)",background:"var(--bg-subtle)"},children:[h||g?(0,r.jsx)("button",{onClick:()=>{iN(h||g).then(()=>{p(!0),setTimeout(()=>p(!1),1500)},()=>{})},style:{padding:"3px 7px",border:"none",background:"none",color:u?"var(--accent)":"var(--text-dim)",cursor:"pointer",fontSize:11},children:o(u?"i18n.copied":"i18n.copy")}):null,m&&(0,r.jsx)("button",{onClick:()=>c(e=>!e),style:{marginLeft:"auto",padding:"3px 7px",border:"none",background:"none",color:"var(--text-dim)",cursor:"pointer",fontSize:11},children:o(d?"i18n.hideDetails":"i18n.showDetails")})]}),m&&d&&(0,r.jsx)("pre",{style:{margin:0,padding:"9px 10px",borderTop:"1px solid var(--border)",background:"var(--bg)",color:"var(--text-muted)",fontSize:"calc(12px + var(--chat-font-size-offset, 0px))",lineHeight:1.5,whiteSpace:"pre-wrap",wordBreak:"break-word",maxHeight:360,overflow:"auto",fontFamily:"var(--font-mono)"},children:g})]})]})})}function lN(e){return"string"==typeof e?e:e.filter(e=>"text"===e.type).map(e=>e.text).join("\n")}function lE(e){return"string"==typeof e?[]:e.filter(e=>"image"===e.type)}function l$(e){return e.source?"base64"===e.source.type?`data:${e.source.media_type};base64,${e.source.data}`:e.source.url??"":e.data?`data:${e.mimeType};base64,${e.data}`:""}let lI=new Set(["path","file_path","content"]),lM={padding:"4px 12px 4px 0",color:"var(--text-dim)",fontSize:"calc(11px + var(--chat-font-size-offset, 0px))",whiteSpace:"nowrap",verticalAlign:"top"},lT={padding:"4px 0",color:"var(--text-muted)",fontSize:"calc(12px + var(--chat-font-size-offset, 0px))",fontFamily:"var(--font-mono)",overflowWrap:"anywhere"},lR={margin:0,padding:"8px 10px",maxHeight:260,overflow:"auto",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg)",font:"inherit",lineHeight:1.5,whiteSpace:"pre-wrap"};function lA(e){let{fields:t}=e;return(0,r.jsx)("table",{style:{borderCollapse:"collapse"},children:(0,r.jsx)("tbody",{children:t.map(e=>(0,r.jsxs)("tr",{children:[(0,r.jsx)("td",{style:lM,children:e.key}),(0,r.jsx)("td",{style:lT,children:e.multiline?(0,r.jsx)("pre",{style:lR,children:e.value}):e.value})]},e.key))})})}let lL={up:"M6 10.5V1.5M2.5 5 6 1.5 9.5 5",down:"M6 1.5v9M2.5 7 6 10.5 9.5 7",clock:"M6 1.25a4.75 4.75 0 1 0 0 9.5 4.75 4.75 0 1 0 0-9.5M6 3.5V6l1.75 1"},lz={fontSize:0};function lP(e){let{part:t}=e;return t.icon?(0,r.jsxs)("span",{children:[t.before&&(0,r.jsx)("span",{style:lz,children:t.before}),(0,r.jsx)("svg",{width:"clock"===t.icon?10:9,height:"clock"===t.icon?10:9,viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:1.5,strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,style:{display:"inline",verticalAlign:"clock"===t.icon?"-0.1em":"-0.05em",marginRight:"clock"===t.icon?3:1},children:(0,r.jsx)("path",{d:lL[t.icon]})}),t.text,t.after&&(0,r.jsx)("span",{style:lz,children:t.after})]}):(0,r.jsx)("span",{children:t.text})}function lW(e){let{message:t,sessionId:n}=e,{t:s}=(0,tm.s)(),[o,l]=(0,i.useState)(null),[a,d]=(0,i.useState)(!1),[c,u]=(0,i.useState)(null),p=!t.output&&void 0===t.exitCode&&!t.cancelled,h=t.cancelled||void 0!==t.exitCode&&0!==t.exitCode,f=n&&t.fullOutputPath?`/api/agent/${encodeURIComponent(n)}/bash-output?path=${encodeURIComponent(t.fullOutputPath)}`:null,m=null!==o,g=o??t.output;async function x(){if(f){d(!0),u(null);try{let e=await fetch(f),t=await e.json().catch(()=>null);t?.success?l(t.data?.output??""):u(s(413===e.status?"chat.fullOutputTooLarge":"chat.fullOutputUnavailable"))}catch{u(s("chat.fullOutputUnavailable"))}finally{d(!1)}}}let v=t.excludeFromContext?"bash (local)":"bash",b={type:"toolCall",toolCallId:`bash-${t.timestamp??""}`,toolName:v,input:{command:t.command}},y=p?void 0:{role:"toolResult",toolCallId:b.toolCallId,toolName:v,content:g?[{type:"text",text:g}]:[],isError:h,timestamp:t.timestamp},w={color:"var(--accent)",fontSize:11,textDecoration:"underline"},k=t.truncated&&f?(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",alignItems:"baseline",gap:"2px 10px",padding:"5px 10px",fontSize:11,color:"var(--text-dim)",borderTop:`1px solid ${h?"rgba(248,113,113,0.3)":"rgba(34,197,94,0.15)"}`},children:[(0,r.jsx)("span",{role:"status",children:c??s(m?"chat.fullOutputShown":"chat.outputTruncated")}),!m&&(0,r.jsx)("button",{type:"button",onClick:x,disabled:a,style:{...w,background:"none",border:"none",cursor:a?"default":"pointer",padding:0},children:a?s("chat.loadingFullOutput"):s("chat.viewFullOutput")}),(0,r.jsx)("a",{href:`${f}&download=1`,style:w,children:s("chat.downloadFullOutput")})]}):null;return(0,r.jsx)("div",{style:{margin:"6px 0"},children:(0,r.jsx)(ll,{block:b,result:y,resultFooter:k})})}function lO(e){if(!e||"object"!=typeof e||"string"!=typeof e.data||"string"!=typeof e.mimeType||!e.mimeType.startsWith("image/"))return!1;let t=function(e){if(!e||e.length%4!=0)return null;let t=e.endsWith("==")?2:+!!e.endsWith("="),n=e.length-t;for(let t=0;t<n;t+=1){var r;if(!((r=e.charCodeAt(t))>=65&&r<=90||r>=97&&r<=122||r>=48&&r<=57||43===r||47===r))return null}for(let t=n;t<e.length;t+=1)if("="!==e[t])return null;return e.length/4*3-t}(e.data);return null!==t&&t<=0xa00000}let lF=new Map;function lD(e){return`parked-new:${e}`}function lB(e){return{value:e.value,images:e.images.map(e=>({...e}))}}function lH(e){return!e.value&&0===e.images.length}function l_(e){let t=lF.get(e);return t?lB(t):null}function lU(e,t){lH(t)?lF.delete(e):lF.set(e,lB(t))}function lK(e){lF.delete(e)}function lq(e,t){return e.trim()?t.trim()?`${e}
|
|
7
7
|
|
|
8
8
|
${t}`:e:t}function lV(e,t,n,r){let i=[...t??[],...r].filter(lO).slice(0,10).map(e=>{let{data:t,mimeType:n}=e;return{data:t,mimeType:n}});return{value:lq(e,n),images:i}}function lZ(e,t,n){let r=l_(e)??{value:"",images:[]},i=lV(t,n,r.value,r.images);return lU(e,i),i}function lJ(e,t,n){if(e===t)return n?lB(n):l_(t);let r=l_(e),i=n&&!lH(n)?lB(n):r??(n?lB(n):null),s=l_(t);if(lK(e),!i)return s;let o=s?lV(s.value,s.images,i.value,i.images):i;return lU(t,o),lB(o)}let lY=/^([ \t]*)([-*+])([ \t]+)(\[[ xX]\](?:[ \t]+|$))?/,lG=/^([ \t]*)(\d{1,9})([.)])([ \t]+)(\[[ xX]\](?:[ \t]+|$))?/,lX=/^([ \t]*)(\d{1,3})(、)([ \t]*)/,lQ=/^[ \t]*([-*_])(?:[ \t]*\1){2,}[ \t]*$/,l0=/^[ \t]{0,3}(`{3,}|~{3,})/;function l1(e){return"mcp"===e.name&&e.sourceInfo?.path==="builtin:mcp"}function l2(e){return"/mcp"===e.trim()}let l4="pi-enter-send-mode",l8="enter",l3=null,l5=new Set;function l6(){return null===l3&&(l3=function(){try{let e=window.localStorage.getItem(l4);return"ctrlEnter"===e?"ctrlEnter":"enter"}catch{return l8}}()),l3}function l9(e){return l5.add(e),()=>{l5.delete(e)}}function l7(e){l3=e;try{window.localStorage.setItem(l4,e)}catch{}l5.forEach(e=>e())}function ae(){return(0,i.useSyncExternalStore)(l9,l6,()=>l8)}let at="pi-chat-content-width",an="pi-chat-content-font-size",ar={width:820,fontSize:14},ai=null,as=new Set;function ao(e){let t=Number(e);return Number.isFinite(t)?Math.max(820,Math.min(2e3,Math.round(t))):820}function al(e){let t=Number(e??14);return Number.isFinite(t)?Math.max(12,Math.min(24,Math.round(t))):14}function aa(e){try{return window.localStorage.getItem(e)}catch{return null}}function ad(e){let{width:t,fontSize:n}=e;"u">typeof document&&(document.documentElement.style.setProperty("--chat-content-max-width",`${t}px`),document.documentElement.style.setProperty("--chat-content-font-size",`${n}px`))}function ac(){return ai||ad(ai={width:ao(aa(at)),fontSize:al(aa(an))}),ai}function au(e){return as.add(e),()=>{as.delete(e)}}function ap(e,t){let n="width"===e?ao(t):al(t);ad(ai={...ac(),[e]:n});try{window.localStorage.setItem("width"===e?at:an,String(n))}catch{}as.forEach(e=>e())}let ah=e=>ap("width",e),af=e=>ap("fontSize",e);function am(){return{...(0,i.useSyncExternalStore)(au,ac,()=>ar),setWidth:ah,setFontSize:af}}let ag=[{value:100,label:"settings.fontWeightThin"},{value:200,label:"settings.fontWeightExtraLight"},{value:300,label:"settings.fontWeightLight"},{value:400,label:"settings.fontWeightRegular"},{value:500,label:"settings.fontWeightMedium"},{value:600,label:"settings.fontWeightSemiBold"}],ax={ui:"pi-ui-font-family",mono:"pi-mono-font-family",uiWeight:"pi-ui-font-weight",monoWeight:"pi-mono-font-weight"},av={ui:"",mono:"",uiWeight:400,monoWeight:400};function ab(e){let t="string"==typeof e?Number(e):e;return ag.find(e=>e.value===t)?.value??400}function ay(e){return"string"==typeof e&&e.length<=500?e:""}let aw=new Set(["serif","sans-serif","monospace","cursive","fantasy","system-ui","ui-serif","ui-sans-serif","ui-monospace","ui-rounded"]),ak=["ui","mono"],aj=Object.keys(ax),aS=null,aC=new Set;function aN(){let e={...av};for(let t of ak)try{e[t]=ay(window.localStorage.getItem(ax[t]));let n=`${t}Weight`;e[n]=ab(window.localStorage.getItem(ax[n]))}catch{}return e}function aE(e){for(let t of ak){let n=`--font-${t}`,r=function(e,t){let n=ay(t).split(",").flatMap(e=>{let t=e.trim().replace(/\s+/g," "),n=t.length>=2&&('"'===t[0]||"'"===t[0])&&t.endsWith(t[0]);return(n&&(t=t.slice(1,-1).trim()),t)?[!n&&aw.has(t.toLowerCase())?t.toLowerCase():JSON.stringify(t)]:[]}).join(", ");return n?`${n}, var(--font-${e}-default)`:""}(t,e[t]);r?document.documentElement.style.setProperty(n,r):document.documentElement.style.removeProperty(n);let i=e[`${t}Weight`];400===i?document.documentElement.style.removeProperty(`${n}-weight`):document.documentElement.style.setProperty(`${n}-weight`,String(i))}}function a$(){return aS||aE(aS=aN()),aS}function aI(){aC.forEach(e=>e())}function aM(e){if(null!==e.key&&!Object.values(ax).includes(e.key))return;let t=aN(),n=a$();aj.every(e=>t[e]===n[e])||(aS=t,aE(t),aI())}function aT(e){return 0===aC.size&&window.addEventListener("storage",aM),aC.add(e),a$(),()=>{aC.delete(e),0===aC.size&&window.removeEventListener("storage",aM)}}function aR(e){let t=a$(),n=aj.filter(n=>t[n]!==e[n]);if(n.length){for(let t of(aS=e,aE(e),n))try{e[t]===av[t]?window.localStorage.removeItem(ax[t]):window.localStorage.setItem(ax[t],String(e[t]))}catch{}aI()}}function aA(e,t){aR({...a$(),[e]:ay(t)})}function aL(e,t){aR({...a$(),[`${e}Weight`]:ab(t)})}function az(e){aR({...a$(),[e]:"",[`${e}Weight`]:400})}function aP(){return{...(0,i.useSyncExternalStore)(aT,a$,()=>av),setFontPreference:aA,setFontWeight:aL,resetFontPreference:az}}function aW(e){let{filled:t,size:n}=e;return(0,r.jsx)("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:t?"currentColor":"none",stroke:"currentColor",strokeWidth:"2",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0},children:(0,r.jsx)("polygon",{points:"12 2.5 14.9 8.6 21.5 9.4 16.6 13.9 17.9 20.5 12 17.2 6.1 20.5 7.4 13.9 2.5 9.4 9.1 8.6"})})}function aO(e){let{active:t,onSelect:n,star:s,gutter:o=!!s,children:l}=e,a=tC(),[d,c]=(0,i.useState)(!1),[u,p]=(0,i.useState)(!1),h=!!(s&&!s.isDefault),f=h&&(d||u||a);return(0,r.jsxs)("div",{onMouseEnter:()=>c(!0),onMouseLeave:()=>c(!1),onFocus:()=>p(!0),onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||p(!1)},style:{position:"relative",background:t?"var(--bg-selected)":d?"var(--bg-hover)":"transparent",transition:"background 0.1s"},children:[(0,r.jsxs)("button",{type:"button",role:"option","aria-selected":t,onClick:n,style:{display:"flex",alignItems:"center",gap:8,width:"100%",minWidth:0,padding:o?"7px 36px 7px 12px":"7px 12px",border:"none",background:"none",color:t?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,fontWeight:t?600:400,textAlign:"left",whiteSpace:"nowrap"},children:[t?(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},"aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),l]}),s?.isDefault&&(0,r.jsx)("span",{role:"img","aria-label":s.defaultLabel,title:s.defaultLabel,style:{position:"absolute",top:"50%",right:6,transform:"translateY(-50%)",display:"flex",alignItems:"center",justifyContent:"center",width:24,height:24,color:"var(--text-dim)"},children:(0,r.jsx)(aW,{filled:!0,size:10})}),s&&h&&(0,r.jsx)("button",{type:"button",title:s.saveLabel,"aria-label":s.saveLabel,tabIndex:f?0:-1,onClick:e=>{e.stopPropagation(),s.onSave()},style:{position:"absolute",top:"50%",right:6,transform:"translateY(-50%)",display:"flex",alignItems:"center",justifyContent:"center",width:24,height:24,padding:0,background:"var(--bg-hover)",border:"1px solid var(--border)",borderRadius:6,color:"var(--text-muted)",cursor:"pointer",opacity:+!!f,pointerEvents:f?"auto":"none",transition:"opacity 0.1s, background 0.12s, color 0.12s, border-color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-selected)",e.currentTarget.style.color="var(--accent)",e.currentTarget.style.borderColor="rgba(37,99,235,0.35)"},onMouseLeave:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text-muted)",e.currentTarget.style.borderColor="var(--border)"},children:(0,r.jsx)(aW,{filled:!1,size:12})})]})}function aF(e){var t;let n,s,o,l,a,d,c,u,p,h,f,{options:m,value:g,onChange:x,onReselect:v,onClear:b,emptyLabel:y,selectedLabel:w,disabled:k=!1,busy:j=!1,isAutoSelection:S=!1,ariaLabel:C,variant:N="toolbar",placement:E="up",defaultValue:$,onSetDefault:I,allOptions:M,onShowAll:T}=e,{t:R}=(0,tm.s)(),A=tC(),L=(0,i.useRef)(null),z=(0,i.useRef)(null),[P,W]=(0,i.useState)(!1),[O,F]=(0,i.useState)(null),[D,B]=(0,i.useState)(""),[H,_]=(0,i.useState)(!1),U=k||j,K=H?M:m,q=(t=K??[],(n=D.trim().toLocaleLowerCase())?t.filter(e=>`${e.name} ${e.providerName??""} ${e.modelId} ${e.provider}/${e.modelId}`.toLocaleLowerCase().includes(n)):t),V=!!T||m.length>8,Z=(e,t)=>e?.find(e=>e.modelId===t.modelId&&e.provider===t.provider),J=()=>{H||T?.(),_(!H)},Y=function(e){let t=[];for(let n of e){let e=t.find(e=>e.provider===n.provider);e?(e.options.push(n),e.providerName===e.provider&&n.providerName?.trim()&&(e.providerName=n.providerName.trim())):t.push({provider:n.provider,providerName:n.providerName?.trim()||n.provider,options:[n]})}return t}(q),G=w??(g?(Z(m,g)??Z(M,g))?.name??g.modelId:y??(m.length>0?R("chat.selectModel"):R("chat.noModels")));(0,i.useEffect)(()=>{let e=e=>{L.current&&!L.current.contains(e.target)&&z.current&&!z.current.contains(e.target)&&(W(!1),B(""))};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]),(0,i.useEffect)(()=>{if(!P)return;let e=()=>{let e=L.current?.querySelector("button")?.getBoundingClientRect();e?.height&&F({top:e.top,right:e.right,bottom:e.bottom,left:e.left,width:e.width})},t=window.visualViewport,n=new MutationObserver(e);return n.observe(document.documentElement,{attributes:!0,attributeFilter:["style","data-keyboard-open"]}),window.addEventListener("resize",e),t?.addEventListener("resize",e),t?.addEventListener("scroll",e),()=>{n.disconnect(),window.removeEventListener("resize",e),t?.removeEventListener("resize",e),t?.removeEventListener("scroll",e)}},[P]),(0,i.useEffect)(()=>{U&&(W(!1),B(""))},[U]);let X="field"===N?{display:"flex",alignItems:"center",gap:7,width:"100%",minWidth:0,height:34,padding:"0 9px",overflow:"hidden",border:"1px solid var(--border)",borderRadius:5,background:U?"var(--bg-panel)":"var(--bg)",color:U?"var(--text-dim)":"var(--text)",cursor:U?"default":"pointer",fontSize:12,textAlign:"left"}:{display:"flex",alignItems:"center",justifyContent:A?"flex-start":void 0,gap:6,width:A?"100%":void 0,maxWidth:A?"100%":220,height:A?44:32,padding:A?"8px 10px":"8px 12px",overflow:"hidden",border:"none",borderRadius:9,background:P?"var(--bg-hover)":"none",color:"var(--text-muted)",cursor:U?"not-allowed":"pointer",fontSize:12,opacity:U?.5:1,transition:"background 0.12s, color 0.12s"};return(0,r.jsxs)("div",{ref:L,className:`model-selector is-${N}${U?" is-disabled":""}`,style:{position:"relative",width:"field"===N||A?"100%":void 0,minWidth:0,flex:"toolbar"===N&&A?"1 1 auto":void 0},onKeyDown:e=>{"Escape"===e.key&&P&&(e.preventDefault(),e.stopPropagation(),B(""),W(!1))},children:[(0,r.jsxs)("button",{type:"button","aria-label":C,"aria-haspopup":"listbox","aria-expanded":P,"aria-busy":j||void 0,disabled:U,title:j?R("chat.switchingModel"):U?G:m.length>0||b?R("chat.changeModel"):R("chat.noAvailableModels"),style:X,onClick:e=>{let t=e.currentTarget.getBoundingClientRect();F({top:t.top,right:t.right,bottom:t.bottom,left:t.left,width:t.width}),W(e=>(e?B(""):_(!1),!e))},onMouseEnter:e=>{U||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{if(U){e.currentTarget.style.background="field"===N?"var(--bg-panel)":"none",e.currentTarget.style.color="field"===N?"var(--text-dim)":"var(--text-muted)";return}e.currentTarget.style.background=P?"var(--bg-hover)":"field"===N?"var(--bg)":"none",e.currentTarget.style.color="field"===N?"var(--text)":"var(--text-muted)"},children:[j?(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.4",strokeLinecap:"round",style:{animation:"spin 0.8s linear infinite",flexShrink:0},"aria-hidden":"true",children:(0,r.jsx)("path",{d:"M21 12a9 9 0 1 1-2.64-6.36"})}):(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0},children:[(0,r.jsx)("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"}),(0,r.jsx)("rect",{x:"9",y:"9",width:"6",height:"6"}),(0,r.jsx)("line",{x1:"9",y1:"1",x2:"9",y2:"4"}),(0,r.jsx)("line",{x1:"15",y1:"1",x2:"15",y2:"4"}),(0,r.jsx)("line",{x1:"9",y1:"20",x2:"9",y2:"23"}),(0,r.jsx)("line",{x1:"15",y1:"20",x2:"15",y2:"23"}),(0,r.jsx)("line",{x1:"20",y1:"9",x2:"23",y2:"9"}),(0,r.jsx)("line",{x1:"20",y1:"14",x2:"23",y2:"14"}),(0,r.jsx)("line",{x1:"1",y1:"9",x2:"4",y2:"9"}),(0,r.jsx)("line",{x1:"1",y1:"14",x2:"4",y2:"14"})]}),(0,r.jsx)("span",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:G}),"field"===N&&(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0,color:"var(--text-dim)"},children:(0,r.jsx)("polyline",{points:"6 9 12 15 18 9"})})]}),P&&O&&(s=window.visualViewport?.offsetTop??0,o=window.visualViewport?.height??window.innerHeight,l=window.visualViewport?.width??window.innerWidth,d=(a=Math.min(O.top-6,s+o-8))-s-8,c=s+o-O.bottom-6-8,p=Math.max(120,Math.min((u="up"===E||d>c)?d:c,.6*o)),h=u?{top:a,transform:"translateY(-100%)"}:{top:O.bottom+6},f=A?{left:8,right:8,maxWidth:"calc(100vw - 16px)"}:{left:O.left,width:"max-content",minWidth:O.width,maxWidth:Math.max(O.width,l-O.left-8)},(0,r.jsxs)("div",{ref:z,role:"listbox","aria-label":C,style:{position:"fixed",...h,...f,zIndex:500,display:"flex",flexDirection:"column",maxHeight:p,overflow:"hidden",border:"1px solid var(--border)",borderRadius:8,background:"var(--bg)",boxShadow:u?"0 -4px 16px rgba(0,0,0,0.10)":"0 4px 16px rgba(0,0,0,0.10)"},children:[T&&(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:4,padding:"6px 8px 0",fontSize:11},children:[[!1,!0].map(e=>(0,r.jsx)("button",{type:"button","aria-pressed":H===e,onClick:()=>{H!==e&&J()},style:{padding:"2px 7px",border:"1px solid",borderColor:H===e?"var(--border)":"transparent",borderRadius:4,background:H===e?"var(--bg-hover)":"none",color:H===e?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:11},children:R(e?"chat.modelScopeAll":"chat.modelScopeScoped")},String(e))),!A&&(0,r.jsx)("span",{style:{marginLeft:"auto",color:"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:10},children:"Tab"})]}),V&&(0,r.jsx)("div",{style:{flexShrink:0,padding:"6px 8px",borderBottom:"1px solid var(--border)"},children:(0,r.jsx)("input",{value:D,onChange:e=>B(e.target.value),onKeyDown:e=>{T&&"Tab"===e.key&&(e.preventDefault(),J())},placeholder:R("chat.filterModels"),"aria-label":R("chat.filterModels"),autoFocus:!A,autoComplete:"off",spellCheck:!1,style:{boxSizing:"border-box",width:"100%",minWidth:220*!A,padding:"5px 8px",border:"1px solid var(--border)",borderRadius:5,outline:"none",background:"var(--bg)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:11}})}),(0,r.jsxs)("div",{style:{minHeight:0,overflowY:"auto"},children:[b&&!D.trim()&&(0,r.jsx)(aO,{active:!g,gutter:!!I,onSelect:()=>{W(!1),B(""),b()},children:(0,r.jsx)(aD,{label:y??R("i18n.default")})}),0===Y.length?(0,r.jsx)("div",{style:{padding:"8px 12px",color:"var(--text-dim)",fontSize:12,whiteSpace:"nowrap"},children:K?D.trim()?R("chat.noMatchingModels"):R("chat.noAvailableModels"):R("agents.modelsLoading")}):Y.map((e,t)=>(0,r.jsxs)("div",{children:[Y.length>1&&(0,r.jsx)("div",{title:e.providerName===e.provider?void 0:e.provider,style:{padding:"6px 12px 4px",borderTop:t>0||b?"1px solid var(--border)":"none",color:"var(--text-dim)",fontSize:10,fontWeight:600,letterSpacing:0,textTransform:e.providerName===e.provider?"uppercase":"none"},children:e.providerName}),e.options.map(e=>(0,r.jsx)(aO,{active:e.modelId===g?.modelId&&e.provider===g?.provider,onSelect:()=>{let t;return t=e.modelId===g?.modelId&&e.provider===g?.provider,void(W(!1),B(""),!t||S?x(e.provider,e.modelId):v?.(e.provider,e.modelId))},star:I&&(!H||Z(m,e))?{isDefault:e.modelId===$?.modelId&&e.provider===$?.provider,saveLabel:R("chat.saveDefaultModel"),defaultLabel:R("chat.defaultModel"),onSave:()=>{W(!1),B(""),I?.(e.provider,e.modelId)}}:void 0,children:(0,r.jsx)(aD,{label:e.name})},`${e.provider}:${e.modelId}`))]},e.provider))]})]}))]})}function aD(e){let{label:t}=e;return(0,r.jsx)("span",{title:t,style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis"},children:t})}let aB=["configured","chat-only","read-only","default","full"],aH={configured:"configured","chat-only":"none","read-only":"read-only",default:"default",full:"full"},a_=new Intl.Collator(void 0,{numeric:!0,sensitivity:"base"});function aU(e,t,n){return t<=0?0:((e+n)%t+t)%t}function aK(e,t,n,r){e.setRangeText(r,t,n,"end"),e.dispatchEvent(new Event("input",{bubbles:!0}))}function aq(e,t,n,r){let i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:r.length,s=e.selectionStart,o=e.selectionEnd;if(e.focus(),s===o&&t<=s&&n>=o){let i=e.value.length-(n-t)+r.length;for(let n=s-t;n>0&&e.selectionStart>t&&document.execCommand("delete");n--);if(document.execCommand("insertText",!1,r))for(let t=n-o;t>0&&e.value.length>i&&document.execCommand("forwardDelete");t--);else aK(e,t,e.selectionStart+(n-o),r)}else e.setSelectionRange(t,n),document.execCommand("insertText",!1,r)||aK(e,t,n,r);i!==r.length&&e.setSelectionRange(t+i,t+i)}function aV(e){let t=e.scrollTop;e.style.height="auto",e.style.height=`${e.value?Math.min(e.scrollHeight,200):e.clientHeight}px`,e.style.overflowY=e.value&&e.scrollHeight>e.clientHeight?"auto":"hidden",e.scrollTop=t}function aZ(e){e.selectionEnd===e.value.length&&(e.scrollTop=e.scrollHeight)}function aJ(e,t){let n=null,r=()=>{n=null,t(function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:8;return Math.max(0,Math.floor(e-t-n))}(e.getBoundingClientRect().bottom,function(e){let t=window.visualViewport?.offsetTop??0;for(let n=e.parentElement;n;n=n.parentElement){let e=window.getComputedStyle(n).overflowY;("auto"===e||"scroll"===e||"hidden"===e||"clip"===e)&&(t=Math.max(t,n.getBoundingClientRect().top+n.clientTop))}return t}(e)))},i=()=>{null!==n&&cancelAnimationFrame(n),n=requestAnimationFrame(r)};r();let s=e.parentElement,o=s?.parentElement,l="u">typeof ResizeObserver&&s?new ResizeObserver(i):null;s&&l?.observe(s),o&&l?.observe(o);let a=window.visualViewport;return a?.addEventListener("resize",i),a?.addEventListener("scroll",i),window.addEventListener("resize",i),window.addEventListener("scroll",i,!0),()=>{l?.disconnect(),a?.removeEventListener("resize",i),a?.removeEventListener("scroll",i),window.removeEventListener("resize",i),window.removeEventListener("scroll",i,!0),null!==n&&cancelAnimationFrame(n)}}let aY=["auto","off","minimal","low","medium","high","xhigh","max"],aG={auto:"chat.thinkingUseDefault",off:"chat.thinkingOff",minimal:"chat.thinkingMinimal",low:"chat.thinkingLow",medium:"chat.thinkingMedium",high:"chat.thinkingHigh",xhigh:"chat.thinkingXhigh",max:"chat.thinkingMax"};function aX(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${Math.round(e/1e3)}k`:e.toLocaleString()}let aQ=[{name:"compact",description:"chat.commandCompact",source:"builtin"},{name:"auto-compact",description:"chat.commandAutoCompact",source:"builtin"},{name:"reload",description:"chat.commandReload",source:"builtin"},{name:"name",description:"chat.commandName",source:"builtin"},{name:"session",description:"chat.commandSession",source:"builtin",availableWhileStreaming:!0},{name:"copy",description:"chat.commandCopy",source:"builtin",availableWhileStreaming:!0},{name:"clone",description:"chat.commandClone",source:"builtin"},{name:"side",description:"chat.commandSide",source:"builtin",availableWhileStreaming:!0}];function a0(e){return function(e){let t=e.trim().match(/^\/([^\s]+)(?:\s|$)/);if(t)return aQ.find(e=>e.name===t[1])}(e)?.availableWhileStreaming===!0}let a1=["builtin","extension","prompt","skill"],a2={builtin:"chat.builtIn",extension:"chat.extensions",prompt:"chat.prompts",skill:"chat.skills"},a4={builtin:0,extension:1,prompt:2,skill:3};function a8(e,t){return"builtin"===e.source?t(e.description):e.description??""}function a3(e,t){return"skill"===e.source&&!!e.name.startsWith("skill:")&&!0===t[e.name.slice(6)]}function a5(e){return{data:e.data,mimeType:e.mimeType}}function a6(e){return{...e,previewUrl:`data:${e.mimeType};base64,${e.data}`}}function a9(e){return(e??[]).filter(lO).slice(0,10).map(a6)}function a7(e){return"string"==typeof e.content?e.content:e.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n")}function de(e){return"string"==typeof e.content?[]:e.content.flatMap(e=>{if("image"!==e.type)return[];let t=e.source?.type==="base64"?e.source.data:e.data,n=e.source?.type==="base64"?e.source.media_type:e.mimeType;if("string"!=typeof t||"string"!=typeof n)return[];let r={data:t,mimeType:n};return lO(r)?[r]:[]})}function dt(e){e.previewUrl.startsWith("blob:")&&URL.revokeObjectURL(e.previewUrl)}function dn(e){let{kind:t,text:n}=e;return(0,r.jsxs)("div",{title:n,style:{display:"flex",alignItems:"center",gap:8,padding:"3px 10px",fontSize:12,color:"var(--text-muted)",minWidth:0},children:[(0,r.jsx)("span",{style:{flexShrink:0,fontSize:10,fontFamily:"var(--font-mono)",padding:"1px 7px",borderRadius:999,border:`1px solid ${"steer"===t?"color-mix(in srgb, var(--accent) 45%, transparent)":"var(--border)"}`,color:"steer"===t?"var(--accent)":"var(--text-dim)"},children:t}),(0,r.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:n})]})}function dr(e){let{tone:t,title:n,body:i,onClose:s}=e,{t:o}=(0,tm.s)(),l="error"===t?"239,68,68":"234,179,8";return(0,r.jsxs)("div",{role:"alert",style:{display:"flex",alignItems:"flex-start",gap:8,maxHeight:120,marginBottom:8,padding:"7px 10px",overflowY:"auto",border:`1px solid rgba(${l},0.3)`,borderRadius:6,background:`rgba(${l},0.07)`,color:`rgb(${l})`,fontSize:11,lineHeight:1.45},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,marginTop:1},"aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M10.3 2.9 1.8 17a2 2 0 0 0 1.7 3h17a2 2 0 0 0 1.7-3L13.7 2.9a2 2 0 0 0-3.4 0Z"}),(0,r.jsx)("line",{x1:"12",y1:"9",x2:"12",y2:"13"}),(0,r.jsx)("line",{x1:"12",y1:"17",x2:"12.01",y2:"17"})]}),(0,r.jsxs)("div",{style:{minWidth:0,flex:1},children:[(0,r.jsx)("div",{style:{fontWeight:600},children:n}),(0,r.jsx)("div",{style:{whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:i})]}),s&&(0,r.jsx)("button",{type:"button",onClick:s,"aria-label":o("sidebar.dismiss"),style:{flexShrink:0,background:"none",border:"none",padding:"0 2px",cursor:"pointer",color:"inherit",opacity:.7,fontSize:13,lineHeight:1},children:"\xd7"})]})}function di(e){let{cwd:t}=e,{t:n}=(0,tm.s)();return t?(0,r.jsx)(dr,{tone:"error",title:n("chat.cwdMissingTitle"),body:n("chat.cwdMissingBody",{cwd:t})}):null}function ds(e){let{error:t}=e,{t:n}=(0,tm.s)();return t?(0,r.jsx)(dr,{tone:"error",title:n("chat.modelError"),body:t}):null}function dl(e){let{warnings:t}=e,{t:n}=(0,tm.s)();return t&&0!==t.length?(0,r.jsx)(dr,{tone:"warning",title:n(t.length>1?"chat.modelScopeWarnings":"chat.modelScopeWarning"),body:t.join("\n")}):null}let da=(0,i.memo)((0,i.forwardRef)(function(e,t){let n,s,o,l,a,{onSend:d,onAbort:c,onSteer:u,onSideChat:p,onFollowUp:h,isStreaming:f,model:m,isAutoModelSelection:g,modelNames:x,modelList:v,modelError:b,missingCwd:y,modelScopeWarnings:w,allModelList:k,onLoadAllModels:j,onModelChange:S,modelSwitching:C,defaultModel:N,onSetDefaultModel:E,onCompact:$,onAbortCompaction:I,isCompacting:M,compactError:T,onDismissCompactError:R,compactResult:A,toolPreset:L,onToolPresetChange:z,thinkingLevel:P,isAutoThinkingSelection:W=!1,onThinkingLevelChange:O,availableThinkingLevels:F,thinkingLevelMap:D,savedDefaultThinkingLevel:B,onSetDefaultThinkingLevel:H,retryInfo:_,queuedMessages:U,inputHistory:K=[],onRecallQueue:q,slashCommands:V,slashCommandsLoading:Z,onLoadSlashCommands:J,extensionUiOpen:Y=!1,onBuiltinCommand:G,soundEnabled:X,onSoundToggle:Q,onAudioUnlock:ee,onPromptWithStreamingBehavior:et,draftKey:en,cwd:er,onAttachFiles:ei,compact:es=!1}=e,{t:eo}=(0,tm.s)(),{fontSize:el}=am(),{ui:ea,uiWeight:ed}=aP(),ec=tC(),eu=ec?44:32,ep=ae(),[eh,ef]=(0,i.useState)(()=>en?l_(en)?.value??"":""),[em,eg]=(0,i.useState)(!1),[ex,ev]=(0,i.useState)(!1),[eb,ey]=(0,i.useState)(!1),[ew,ek]=(0,i.useState)(()=>en?a9(l_(en)?.images):[]),ej=eh.trimStart(),eS=0===ew.length&&ej.startsWith("!"),eC=eS&&ej.startsWith("!!"),[eN,eE]=(0,i.useState)(!1),[e$,eI]=(0,i.useState)(0),[eM,eT]=(0,i.useState)(null),[eR,eA]=(0,i.useState)(null),[eL,ez]=(0,i.useState)(!1),[eP,eW]=(0,i.useState)(null),[eO,eF]=(0,i.useState)(0),[eD,eB]=(0,i.useState)(!1),[eH,e_]=(0,i.useState)(!1),[eU,eK]=(0,i.useState)(0),[eq,eV]=(0,i.useState)(!1),eZ=(0,i.useRef)(!1),eJ=(0,i.useRef)(null),[eY,eG]=(0,i.useState)(null),[eX,eQ]=(0,i.useState)(!1),[e0,e1]=(0,i.useState)(null),[e2,e4]=(0,i.useState)(null),e8=er&&e2?.cwd===er?e2.values:{},e3=(0,i.useRef)(null),e5=(0,i.useRef)(null),e6=(0,i.useRef)(null),e9=(0,i.useRef)(null),e7=(0,i.useRef)(null),te=(0,i.useRef)(null),tt=(0,i.useRef)(!1),tn=(0,i.useRef)(0),tr=(0,i.useRef)(null),ti=(0,i.useRef)(!1),ts=(0,i.useRef)(null),to=(0,i.useRef)([]),tl=(0,i.useRef)(null),ta=(0,i.useRef)([]),td=(0,i.useRef)([]),tc=(0,i.useRef)(null),tu=(0,i.useRef)(null),tp=(0,i.useRef)(en),th=(0,i.useRef)(eh),tf=(0,i.useRef)(ew),tg=(0,i.useRef)(0);th.current=eh,tf.current=ew,(0,i.useImperativeHandle)(t,()=>({setText(e){let t=e3.current;if(!t){th.current=e,ef(e);return}t.setSelectionRange(0,t.value.length),aq(t,0,t.value.length,e),eA(null),requestAnimationFrame(()=>aV(t))},pasteText(e){if(!e)return;let t=e3.current;t?(aq(t,t.selectionStart??t.value.length,t.selectionEnd??t.value.length,e),eA(null),requestAnimationFrame(()=>aV(t))):ef(t=>t+e)},insertIfEmpty(e){let t=e3.current;(t?t.value:eh).trim()||(th.current=e,ef(e),eA(null),requestAnimationFrame(()=>{t&&(t.focus(),aV(t),aZ(t))}))},replaceMessage(e){var t,n,r;let i=e3.current;if(t=i?i.value:eh,n=tf.current.length,r=tg.current,t.trim()||0!==n||0!==r)return;let s=a7(e),o=a9(de(e));th.current=s,tf.current=o,ef(s),eA(null),e_(!1),ek(e=>(e.forEach(dt),o)),requestAnimationFrame(()=>{i&&(i.focus(),aV(i),aZ(i))})},prependText(e){if(!e.trim())return;let t=e3.current,n=[e,t?t.value:eh].filter(e=>e.trim()).join("\n\n");th.current=n,ef(n),eA(null),requestAnimationFrame(()=>{t&&(t.focus(),t.setSelectionRange(n.length,n.length),aV(t),aZ(t))})},rekeyDraft(e,t){if(e===t)return;if(tp.current!==e)return void lJ(e,t);let n={value:th.current,images:tf.current.map(a5)},r=lJ(e,t,n)??{value:"",images:[]},i=r.value===n.value&&r.images.length===n.images.length&&r.images.every((e,t)=>e.data===n.images[t]?.data&&e.mimeType===n.images[t]?.mimeType);if(tp.current=t,i)return;let s=a9(r.images);th.current=r.value,tf.current=s,ef(r.value),ek(e=>(e.forEach(dt),s)),eA(null),e_(!1)},restoreSubmission(e,t,n){if(!e.trim()&&!t?.length)return;let r=tp.current,i=n??r,s=i===r,o=!s&&i?l_(i):null,l=lV(e,t,s?th.current:o?.value??"",s?tf.current.map(a5):o?.images??[]);if(i&&lU(i,l),!s)return;let a=t?.length?[...a9(t).slice(0,Math.max(0,10-tf.current.length)),...tf.current].slice(0,10):tf.current;th.current=l.value,tf.current=a,ef(t=>{let n=lq(e,t);return th.current=n,n}),eA(null),e_(!1),t?.length&&ek(e=>{let n=Math.max(0,10-e.length),r=a9(t).slice(0,n),i=r.length>0?[...r,...e]:e;return tf.current=i,i}),requestAnimationFrame(()=>{let e=e3.current;e&&(e.focus(),e.setSelectionRange(e.value.length,e.value.length),aV(e),aZ(e))})},focus(){let e=e3.current;e&&(e.focus(),e.setSelectionRange(e.value.length,e.value.length))},insertText(e){let t=e3.current;if(!t)return void ef(t=>t+(t?" ":"")+e);let n=t.selectionStart??t.value.length,r=t.selectionEnd??t.value.length,i=t.value.slice(0,n);aq(t,n,r,(i.length>0&&!i.endsWith(" ")?" ":"")+e),eA(null)},insertQuote(e){let t=e3.current;if(!t)return void ef(t=>t+iS(t)+e);let n=t.selectionStart??t.value.length,r=t.selectionEnd??t.value.length;aq(t,n,r,iS(t.value.slice(0,n))+e),eA(null)},addImages(e){tx(e)}}));let tx=(0,i.useCallback)(async e=>{if(es)return;let t=Math.max(0,10-tf.current.length-tg.current),n=e.filter(e=>e.type.startsWith("image/")&&e.size<=0xa00000).slice(0,t);if(n.length){tg.current+=n.length;try{let e=await Promise.all(n.map(async e=>{var t;return{...await (t=e.type,new Promise((n,r)=>{let i=new FileReader;i.onload=()=>{let e="string"==typeof i.result?i.result.split(",")[1]:void 0;e?n({data:e,mimeType:t}):r(Error("Failed to read image"))},i.onerror=r,i.readAsDataURL(e)})),previewUrl:URL.createObjectURL(e)}}));ek(t=>{let n=e.slice(0,Math.max(0,10-t.length));e.slice(n.length).forEach(dt);let r=[...t,...n];return tf.current=r,r})}finally{tg.current-=n.length}}},[es]),tv=(0,i.useCallback)(e=>{let t=Array.from(e.target.files??[]);e.target.value="",ei?ei(t):tx(t)},[ei,tx]),tb=(0,i.useCallback)(e=>{ek(t=>{let n=[...t],[r]=n.splice(e,1);return r&&dt(r),tf.current=n,n})},[]),ty=(0,i.useCallback)(()=>{tf.current=[],ek(e=>(e.forEach(dt),[]))},[]),tw=(0,i.useCallback)(()=>{th.current="",ef(""),eA(null),e_(!1),en&&lK(en),tp.current&&tp.current!==en&&lK(tp.current),ty(),e3.current&&(e3.current.style.height="auto")},[ty,en]);(0,i.useEffect)(()=>{en&&tp.current===en&&lU(en,{value:eh,images:ew.map(a5)})},[ew,en,eh]),(0,i.useEffect)(()=>{let e=tp.current;if(e===en)return;e&&lU(e,{value:th.current,images:tf.current.map(a5)});let t=en?l_(en):null;tp.current=en;let n=t?.value??"",r=a9(t?.images);th.current=n,tf.current=r,ef(n),eA(null),e_(!1),ek(e=>(e.forEach(dt),r))},[en]);let tk=(0,i.useCallback)(()=>{let e=e3.current;e&&(e.value?aV(e):(e.style.height="auto",e.style.overflowY="hidden"))},[]);(0,i.useLayoutEffect)(tk,[eh,el,ea,ed,tk]),(0,i.useEffect)(()=>{let e=e3.current;if(!e)return;let t=-1,n=new ResizeObserver(e=>{let[n]=e;n.contentRect.width!==t&&(t=n.contentRect.width,tk())});return n.observe(e),document.fonts.addEventListener("loadingdone",tk),()=>{n.disconnect(),document.fonts.removeEventListener("loadingdone",tk)}},[tk]),(0,i.useEffect)(()=>{let e=e3.current;if(!e)return;let t=t=>{if("insertLineBreak"!==t.inputType||t.isComposing)return;let n=function(e,t,n){let r;if(t!==n)return null;let i=e.lastIndexOf("\n",t-1)+1,s=e.indexOf("\n",t),o=-1===s?e.length:s,l=e.slice(i,o),a=function(e){if(lQ.test(e))return null;let t=lY.exec(e);if(t)return{indent:t[1],marker:t[2],number:null,delimiter:"",spacing:t[3],task:void 0!==t[4],length:t[0].length};let n=lG.exec(e)??lX.exec(e);return n?{indent:n[1],marker:"",number:n[2],delimiter:n[3],spacing:n[4],task:void 0!==n[5],length:n[0].length}:null}(l);return!a||t-i<a.length||function(e){let t=null;for(let n of e.split("\n")){let e=l0.exec(n)?.[1];e&&(null===t?t=e:e[0]===t[0]&&e.length>=t.length&&n.trim()===e&&(t=null))}return null!==t}(e.slice(0,i))?null:""===l.slice(a.length).trim()?{start:i,end:o,text:""}:{start:t,end:t,text:`
|
|
9
|
-
${r=null===a.number?a.marker:`${String(Number(a.number)+1).padStart(a.number.length,"0")}${a.delimiter}`,`${a.indent}${r}${a.spacing}${a.task?"[ ] ":""}`}`}}(e.value,e.selectionStart,e.selectionEnd);n&&(t.preventDefault(),e.setSelectionRange(n.start,n.end),document.execCommand(n.text?"insertText":"delete",!1,n.text))};return e.addEventListener("beforeinput",t),()=>e.removeEventListener("beforeinput",t)},[]),(0,i.useEffect)(()=>()=>{tf.current.forEach(dt)},[]),(0,i.useLayoutEffect)(()=>{if(eq){let e=e=>{e.target!==eJ.current&&(eJ.current=null)};return document.addEventListener("pointerdown",e,!0),()=>document.removeEventListener("pointerdown",e,!0)}let e=eJ.current;eJ.current=null,e?.isConnected&&document.activeElement===document.body&&!document.querySelector('[aria-modal="true"]')&&e.focus({preventScroll:!0})},[eq]);let tj=(0,i.useCallback)(async e=>{if(ew.length||!e.startsWith("/")||!G)return!1;if(eZ.current)return!0;eJ.current=document.activeElement===e3.current?e3.current:null,eZ.current=!0,eV(!0);try{var t,n;let r=await G(e);if(!r.handled)return!1;return r.error||(t=th.current,n=tf.current.length,0!==n||t.trim()!==e)||tw(),!0}finally{eZ.current=!1,eV(!1)}},[ew.length,tw,G]),tS=(0,i.useCallback)(async()=>{var e;let t=eh.trim();(t||ew.length)&&(ee?.(),(!f||a0(e=t)||l2(e))&&await tj(t)||(!f||t.startsWith("!")&&!ew.length)&&(tw(),d(t,ew.length?ew:void 0)))},[eh,ew,f,tj,d,tw,ee]),tN=!es&&eh.startsWith("/")&&!/\s/.test(eh.slice(1))?eh.slice(1).toLowerCase():null,tE=(()=>{var e;let t,n;return null===tN?[]:(e=[...f?aQ.filter(e=>e.availableWhileStreaming):aQ,...V??[]],((n=(t=e.map(e=>{let t,n;return{command:e,rank:(t=e.name.toLowerCase(),(n="skill"===e.source&&t.startsWith("skill:")?t.slice(6):t)===tN||t===tN?0:n.startsWith(tN)||t.startsWith(tN)?1:t.includes(tN)?2:3)}})).filter(e=>{let{rank:t}=e;return t<3})).length>0?n:t.filter(e=>{let{command:t}=e;return a8(t,eo).toLowerCase().includes(tN)})).sort((e,t)=>e.rank-t.rank||a4[e.command.source]-a4[t.command.source]||a_.compare(e.command.name,t.command.name)).map(e=>{let{command:t}=e;return t}))})(),{commands:t$,groups:tI}=function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"",r=0,i=a1.map(i=>{let s=e.filter(e=>e.source===i),o="skill"!==i||n?s:[...s.filter(e=>!a3(e,t)),...s.filter(e=>a3(e,t))];return{source:i,items:o.map(e=>({command:e,index:r++}))}}).filter(e=>e.items.length>0);return{commands:i.flatMap(e=>e.items.map(e=>{let{command:t}=e;return t})),groups:i}}(tE,e8,tN??""),tM=1===tE.length?eo(tN?"chat.match":"chat.command"):eo(tN?"chat.matches":"chat.commands",{count:tE.length}),tT=!!eh.trim()||ew.length>0,tR=es||ec&&f,tA=ew.length>0&&!function(e,t){if(!e)return!0;let n=t?.find(t=>t.provider===e.provider&&t.id===e.modelId);return!n||!n.input||n.input.includes("image")}(m,v)&&!eD;(0,i.useEffect)(()=>{0===ew.length&&eB(!1)},[ew.length]);let tL=(0,i.useCallback)((e,t)=>{if(!er)return void eA(null);let n=t??e.length;eA(t3(e.slice(0,n)))},[er]),tz=eR?.query??null,tP=i.useMemo(()=>null!==tz&&eY&&eY.cwd===er?function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:20,r=t.toLowerCase();if(!r)return e.slice(0,n);let i=[];for(let t of e){let e=function(e,t){let n=e.path.toLowerCase(),r=0;if(t.includes("/"))n===t?r=100:n.startsWith(t)?r=80:n.includes(t)?r=50:t6(t,n)&&(r=10);else{let e=n.lastIndexOf("/"),i=-1===e?n:n.slice(e+1);i===t?r=100:i.startsWith(t)?r=80:i.includes(t)?r=50:n.includes(t)?r=30:t6(t,n)&&(r=10)}return e.isDir&&r>0&&(r+=10),r}(t,r);e>0&&i.push({entry:t,score:e})}return i.sort((e,t)=>t.score-e.score||t5(e.entry.path)-t5(t.entry.path)||e.entry.path.localeCompare(t.entry.path)),i.slice(0,n).map(e=>e.entry)}(eY.entries,tz):[],[tz,eY,er]),tW=!!(tz&&eY?.truncated&&eY.cwd===er);(0,i.useEffect)(()=>{if(!tW||!er||!tz)return;let e=setTimeout(()=>{fetch(`/api/file-index?cwd=${encodeURIComponent(er)}&q=${encodeURIComponent(tz)}`).then(e=>{if(!e.ok)throw Error(`file search failed: ${e.status}`);return e.json()}).then(e=>e1({cwd:er,query:tz,matches:e.matches??[]})).catch(()=>{})},150);return()=>clearTimeout(e)},[tW,tz,er]);let tO=tW&&null!==e0&&e0.cwd===er&&e0.query===tz,tF=tO?e0.matches:tP,tD=null===eR?null:`${eR.start}:${+!!eR.quoted}:${eR.query}`;(0,i.useEffect)(()=>{if(null===tD){ez(!1),eF(0);return}ez(!0),eF(0)},[tD]);let tB=null!==eR;(0,i.useEffect)(()=>{if(!tB||!er)return;let e=tc.current;e&&e.cwd===er&&Date.now()-e.fetchedAt<1e4||tu.current===er||(tu.current=er,eQ(!0),fetch(`/api/file-index?cwd=${encodeURIComponent(er)}`).then(e=>{if(!e.ok)throw Error(`file index failed: ${e.status}`);return e.json()}).then(e=>{eG({cwd:er,entries:function(e){let t=new Set;for(let n of e){let e=n.indexOf("/");for(;-1!==e;)t.add(n.slice(0,e)),e=n.indexOf("/",e+1)}let n=[];for(let e of t)n.push({path:e,isDir:!0});for(let t of e)t&&n.push({path:t,isDir:!1});return n.sort((e,t)=>t5(e.path)-t5(t.path)||e.path.localeCompare(t.path)),n}(e.files??[]),truncated:!!e.truncated}),tc.current={cwd:er,fetchedAt:Date.now()}}).catch(()=>{tc.current=null}).finally(()=>{tu.current=null,eQ(!1)}))},[tB,er]);let tH=(0,i.useCallback)(e=>{if(!eR)return;let t=e3.current;if(!t)return;let n=t.selectionStart??t.value.length,r=n+(eR.quoted&&'"'===t.value[n]?1:0),i=function(e,t){let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2],r=t?`${e}/`:e,i=n||r.includes(" ");if(t){let e=i?`@"${r}"`:`@${r}`;return{text:e,cursorOffset:i?e.length-1:e.length}}let s=i?`@"${r}" `:`@${r} `;return{text:s,cursorOffset:s.length}}(e.path,e.isDir,eR.quoted),s=eR.start+i.cursorOffset;aq(t,eR.start,r,i.text,i.cursorOffset),eA(t3(t.value.slice(0,s)))},[eR]);(0,i.useEffect)(()=>{eO>=tF.length&&eF(Math.max(0,tF.length-1))},[tF.length,eO]),(0,i.useEffect)(()=>{ta.current.length=tF.length},[tF.length]),(0,i.useEffect)(()=>{eL&&ta.current[eO]?.scrollIntoView({block:"nearest",inline:"nearest"})},[eO,eL]),(0,i.useEffect)(()=>{eU>=K.length&&eK(Math.max(0,K.length-1))},[K.length,eU]),(0,i.useEffect)(()=>{td.current.length=K.length},[K.length]),(0,i.useEffect)(()=>{eH&&!Y&&td.current[eU]?.scrollIntoView({block:"nearest",inline:"nearest"})},[eU,eH,Y]);let t_=(0,i.useCallback)(e=>{ef(e),e_(!1),eK(0),eA(null),requestAnimationFrame(()=>{let t=e3.current;t&&(t.focus(),t.setSelectionRange(e.length,e.length),aV(t),aZ(t))})},[]),tU=(0,i.useCallback)(e=>{let t=`/${e.name} `;ef(t),eE(!1),eI(0),requestAnimationFrame(()=>{let e=e3.current;e&&(e.focus(),e.setSelectionRange(t.length,t.length),aV(e))})},[]),tK=(0,i.useCallback)(()=>{let e=eh.trim();e&&!ew.length&&p&&(tw(),p(e))},[eh,ew,p,tw]),tV=(0,i.useCallback)(e=>{let t=eh.trim();if(!t&&!ew.length)return;if(t.startsWith("!")&&!ew.length)return void tS();ee?.();let n=ew.length?ew:void 0,r=()=>{if(t.startsWith("/")&&et){tw(),et(t,"steer"===e?"steer":"followUp",n);return}tw(),"steer"===e&&u?u(t,n):"followup"===e&&h&&h(t,n)};!ew.length&&G&&a0(t)?tj(t):!ew.length&&G&&l2(t)?tj(t).then(e=>{e||r()},()=>r()):r()},[eh,ew,G,et,u,h,tw,ee,tj,tS]),tZ=(0,i.useCallback)(e=>{let t=t$.length-1;if(t<0)return 0;if("left"===e)return Math.max(0,e$-1);if("right"===e)return Math.min(t,e$+1);let n=to.current[e$];if(!n)return"down"===e?Math.min(t,e$+1):Math.max(0,e$-1);let r=n.getBoundingClientRect(),i=r.left+r.width/2,s=r.top+r.height/2,o=-1,l=1/0;for(let n=0;n<=t;n+=1){if(n===e$)continue;let t=to.current[n];if(!t)continue;let r=t.getBoundingClientRect(),a=r.top+r.height/2-s;if("down"===e?a<=4:a>=-4)continue;let d=1e3*Math.abs(a)+Math.abs(r.left+r.width/2-i);d<l&&(o=n,l=d)}return o>=0?o:"down"===e?Math.min(t,e$+1):Math.max(0,e$-1)},[t$.length,e$]),tY=(0,i.useCallback)(e=>{let t=e.nativeEvent,n="Enter"===e.key&&!e.shiftKey,r=ec||"ctrlEnter"===ep?n&&(e.ctrlKey||e.metaKey):n,i=ec?r:n,s=Date.now()-tn.current<100,o=tt.current||t.isComposing||229===t.keyCode;if(i&&(o||s)){s&&e.preventDefault();return}if(eH&&!Y&&!o){if("ArrowDown"===e.key){e.preventDefault(),eK(e=>Math.min(Math.max(0,K.length-1),e+1));return}if("ArrowUp"===e.key){e.preventDefault(),eK(e=>Math.max(0,e-1));return}if("Escape"===e.key){e.preventDefault(),e_(!1);return}if(("Tab"===e.key||i)&&K[eU]){e.preventDefault(),t_(K[eU]);return}}if(eN&&null!==tN&&!Y){if("ArrowDown"===e.key){e.preventDefault(),eI(tZ("down"));return}if("ArrowUp"===e.key){e.preventDefault(),eI(tZ("up"));return}if("ArrowRight"===e.key){e.preventDefault(),eI(tZ("right"));return}if("ArrowLeft"===e.key){e.preventDefault(),eI(tZ("left"));return}if("Escape"===e.key){e.preventDefault(),eE(!1);return}let t=t$[e$];if("Tab"===e.key&&t){e.preventDefault(),tU(t);return}if(i&&t){e.preventDefault(),r&&function(e,t,n){if("builtin"===t.source)return"builtin"===t.source&&e.trim()===`/${t.name}`&&(!n||!0===t.availableWhileStreaming);return l1(t)&&l2(e)}(eh,t,f)?(eE(!1),tS()):tU(t);return}}if(eL&&null!==eR&&!Y&&!o){if("ArrowDown"===e.key){e.preventDefault(),eF(e=>aU(e,tF.length,1));return}if("ArrowUp"===e.key){e.preventDefault(),eF(e=>aU(e,tF.length,-1));return}if("Escape"===e.key){e.preventDefault(),ez(!1);return}if(("Tab"===e.key||i)&&tF[eO]){e.preventDefault(),tH(tF[eO]);return}}if("ArrowUp"===e.key&&!o&&!f&&K.length>0&&0===eh.trim().length){e.preventDefault(),eE(!1),ez(!1),eK(K.length-1),e_(!0);return}if("Escape"===e.key&&!o&&f&&c){e.preventDefault(),c();return}r&&(e.preventDefault(),f&&(u||h)?tV(e.altKey&&h||!u?"followup":"steer"):tS())},[ec,ep,f,u,h,c,Y,eN,tN,t$,e$,tU,tV,tS,tZ,eL,eR,tF,eO,tH,eH,K,eU,t_,eh]),tG=(0,i.useCallback)(()=>{tr.current=null;let e=e3.current;e&&aV(e)},[]),tQ=(0,i.useCallback)(e=>{let t=Array.from(e.clipboardData?.items??[]).filter(e=>e.type.startsWith("image/"));if(!es&&t.length){e.preventDefault(),tx(t.map(e=>e.getAsFile()).filter(e=>null!==e));return}let n=e.clipboardData.getData("text/html"),r=e.clipboardData.getData("text/plain");if(r){let t=e.currentTarget,n=e.nativeEvent,i=t.selectionStart,s=t.selectionEnd,o={};tr.current=o,setTimeout(()=>{tr.current===o&&(tr.current=null,!n.defaultPrevented&&t.isConnected&&aq(t,i,s,r))},0)}if(!n||!r)return;let i=new DOMParser().parseFromString(n,"text/html"),s=function(e,t){let n="",r=0,i=!1;for(let{label:s,href:o,occurrence:l}of t){if(!s||!o)continue;let t=0;for(let n=0;n<=l&&!((t=e.indexOf(s,n?t+s.length:0))<0);n++);if(t<r)continue;let a=s.replace(/([\\[\]])/g,"\\$1"),d=o.replace(/([\\()])/g,"\\$1");n+=`${e.slice(r,t)}[${a}](${d})`,r=t+s.length,i=!0}return i?n+e.slice(r):null}(r,Array.from(i.querySelectorAll("a[href]"),e=>{let t=e.textContent??"",n=i.createRange();return n.setStart(i.body,0),n.setEndBefore(e),{label:t,href:e.getAttribute("href")?.trim()??"",occurrence:t?n.toString().split(t).length-1:0}}));if(null===s)return;let o=e.currentTarget,l=o.selectionStart,a=o.value.slice(0,l)+s+o.value.slice(o.selectionEnd);e.preventDefault(),th.current=a,ef(a),e_(!1),tL(a,l+s.length),requestAnimationFrame(()=>{o.focus(),o.setSelectionRange(l+s.length,l+s.length),aZ(o)})},[es,tx,tL]);(0,i.useEffect)(()=>{if(null===tN){eE(!1),eI(0),ti.current=!1;return}eE(!0),eI(0),!ti.current&&J&&(ti.current=!0,Promise.resolve(J()).catch(()=>{ti.current=!1}))},[tN,J]),(0,i.useEffect)(()=>{if(!eN||!er)return;let e=!1;return e4({cwd:er,values:{}}),fetch(`/api/skills?cwd=${encodeURIComponent(er)}`).then(e=>{if(!e.ok)throw Error(`skills fetch failed: ${e.status}`);return e.json()}).then(t=>{if(e)return;let n={};for(let e of t.skills??[])n[e.name]=e.disableModelInvocation;e4({cwd:er,values:n})}).catch(()=>{e||e4({cwd:er,values:{}})}),()=>{e=!0}},[eN,er]),(0,i.useEffect)(()=>{e$>=t$.length&&eI(Math.max(0,t$.length-1))},[t$.length,e$]),(0,i.useEffect)(()=>{to.current.length=t$.length},[t$.length]),(0,i.useEffect)(()=>{eN&&!Y&&to.current[e$]?.scrollIntoView({block:"nearest",inline:"nearest"})},[e$,eN,Y]),(0,i.useLayoutEffect)(()=>{if(!eN||null===tN||Y)return void eT(null);let e=ts.current;if(e)return aJ(e,e=>{eT(t=>t===e?t:e)})},[eN,tN,Y]),(0,i.useLayoutEffect)(()=>{if(!eL||null===eR||Y)return void eW(null);let e=tl.current;if(e)return aJ(e,e=>{eW(t=>t===e?t:e)})},[eL,eR,Y]);let t0=v&&v.length>0?v.map(e=>({provider:e.provider,providerName:e.providerName,modelId:e.id,name:e.name})):Object.entries(x??{}).map(e=>{let[t,n]=e;return{provider:m?.provider??"unknown",modelId:t,name:n}}),t1=A?Math.max(0,A.tokensBefore-A.estimatedTokensAfter):0,t2=A?`${A.reason&&"manual"!==A.reason?`${A.reason[0].toUpperCase()}${A.reason.slice(1)} `:eo("chat.compacted")} ${aX(A.tokensBefore)} -> ${aX(A.estimatedTokensAfter)} tokens (${eo("chat.tokensSaved",{saved:aX(t1)})})`:null,t4=P&&"auto"!==P?P:null,t8="auto"!==(n=t4??"auto")&&D?D[n]??n:n,t9=Object.entries(aH).find(e=>{let[,t]=e;return t===(L??"configured")})?.[0]??"configured",t7="chat-only"===t9?eo("chat.chatOnly"):t9;(0,i.useEffect)(()=>{let e=e=>{e5.current&&!e5.current.contains(e.target)&&eg(!1),e6.current&&!e6.current.contains(e.target)&&ev(!1),e9.current&&!e9.current.contains(e.target)&&ey(!1),!e7.current||e7.current.contains(e.target)||e3.current?.contains(e.target)||e_(!1)};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]),(0,i.useEffect)(()=>{f&&eg(!1)},[f]);let ne=(0,i.useRef)(-1/0);(0,i.useLayoutEffect)(()=>{if(f)return()=>{ne.current=performance.now()}},[f]);let nt=e=>{var t,n;return t=e.detail,n=performance.now()-ne.current,t>0&&n<600};return(0,i.useEffect)(()=>{ec||ey(!1)},[ec]),(0,r.jsxs)("fieldset",{disabled:eq,"aria-busy":eq,className:es?void 0:"chat-input-shell",style:{...es?{flexShrink:0}:{display:"flex",flexDirection:"column",minHeight:0},minWidth:0,margin:0,border:0,background:"transparent",padding:es?0:"0 16px 8px",paddingRight:es?0:ec?16:52,opacity:eq?.5:1,transition:"opacity 0.15s"},children:[!es&&(0,r.jsx)("input",{ref:te,type:"file",accept:ei?void 0:"image/*",multiple:!0,style:{display:"none"},onChange:tv}),(0,r.jsxs)("div",{style:{...es?void 0:{display:"flex",flexDirection:"column",minHeight:0,width:"100%"},maxWidth:"var(--chat-content-max-width, 820px)",margin:"0 auto"},children:[(0,r.jsx)(di,{cwd:y}),(0,r.jsx)(ds,{error:b}),(0,r.jsx)(dl,{warnings:w}),tA&&(s=v?.find(e=>e.provider===m?.provider&&e.id===m?.modelId),(0,r.jsx)(dr,{tone:"warning",title:eo("chat.imageNotSupportedTitle"),body:eo("chat.imageNotSupportedBody",{model:s?.name||m?.modelId||""}),onClose:()=>eB(!0)})),(U?.steering.length??0)+(U?.followUp.length??0)>0&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",minHeight:72,marginBottom:8,border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-panel)",padding:"5px 0"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,padding:"2px 8px 4px 10px"},children:[(0,r.jsx)("span",{style:{fontSize:10,fontFamily:"var(--font-mono)",color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:.4},children:eo("chat.queued",{count:(U?.steering.length??0)+(U?.followUp.length??0)})}),q&&(0,r.jsxs)("button",{onClick:q,title:eo("chat.recallTitle"),style:{display:"flex",alignItems:"center",gap:6,padding:"4px 12px",fontSize:12,color:"var(--text)",background:"transparent",border:"1px solid var(--border)",borderRadius:7,cursor:"pointer",transition:"background 0.12s, border-color 0.12s",whiteSpace:"nowrap"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.borderColor="color-mix(in srgb, var(--accent) 45%, var(--border))"},onMouseLeave:e=>{e.currentTarget.style.background="transparent",e.currentTarget.style.borderColor="var(--border)"},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("polyline",{points:"9 14 4 9 9 4"}),(0,r.jsx)("path",{d:"M20 20v-7a4 4 0 0 0-4-4H4"})]}),eo("chat.recall")]})]}),(0,r.jsxs)("div",{style:{maxHeight:"min(180px, calc(var(--app-viewport-height, 100dvh) * 0.25))",overflowY:"auto",overscrollBehavior:"contain"},children:[U?.steering.map((e,t)=>(0,r.jsx)(dn,{kind:"steer",text:e},`steer-${t}`)),U?.followUp.map((e,t)=>(0,r.jsx)(dn,{kind:"follow-up",text:e},`followup-${t}`))]})]}),_&&(0,r.jsxs)("div",{style:{marginBottom:8,padding:"5px 10px",background:"rgba(234,179,8,0.08)",border:"1px solid rgba(234,179,8,0.25)",borderRadius:6,fontSize:12,color:"rgba(180,130,0,0.9)",display:"flex",alignItems:"center",gap:6},children:[(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:[(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),(0,r.jsx)("path",{d:"M3 3v5h5"})]}),eo("chat.retrying",{attempt:_.attempt,max:_.maxAttempts}),_.errorMessage&&(0,r.jsxs)("span",{style:{opacity:.7,marginLeft:4},children:["— ",_.errorMessage]})]}),t2&&(0,r.jsxs)("div",{style:{marginBottom:8,padding:"5px 10px",background:"rgba(16,185,129,0.08)",border:"1px solid rgba(16,185,129,0.24)",borderRadius:6,fontSize:12,color:"rgba(5,150,105,0.95)",display:"flex",alignItems:"center",gap:6},children:[(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}),t2]}),T&&(0,r.jsxs)("div",{role:"alert",style:{display:"flex",alignItems:"flex-start",gap:6,marginBottom:8,padding:R?"3px 3px 3px 10px":"7px 10px",background:"rgba(239,68,68,0.07)",border:"1px solid rgba(239,68,68,0.3)",borderRadius:6,color:"#ef4444",fontFamily:"var(--font-mono)",fontSize:12,lineHeight:1.5},children:[(0,r.jsx)("span",{style:{minWidth:0,flex:1,padding:R?"4px 0":0,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:T}),R&&(0,r.jsx)(tq,{onClick:R,title:eo("chat.dismissCompactError")})]}),ew.length>0&&(0,r.jsx)("div",{style:{display:"flex",gap:6,marginBottom:6,flexWrap:"wrap"},children:ew.map((e,t)=>(0,r.jsxs)("div",{style:{position:"relative",flexShrink:0},children:[(0,r.jsx)(sx,{src:e.previewUrl,children:(0,r.jsx)("img",{src:e.previewUrl,alt:"",style:{width:56,height:56,objectFit:"cover",borderRadius:6,border:"1px solid var(--border)",display:"block"}})},e.previewUrl),(0,r.jsx)("button",{type:"button",onClick:()=>tb(t),style:{position:"absolute",top:-4,right:-4,width:16,height:16,borderRadius:"50%",background:"var(--bg-panel)",border:"1px solid var(--border)",display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer",padding:0,color:"var(--text-muted)"},children:(0,r.jsxs)("svg",{width:"8",height:"8",viewBox:"0 0 8 8",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",children:[(0,r.jsx)("line",{x1:"1",y1:"1",x2:"7",y2:"7"}),(0,r.jsx)("line",{x1:"7",y1:"1",x2:"1",y2:"7"})]})})]},t))}),(0,r.jsxs)("div",{style:{position:"relative",minWidth:0},children:[eH&&!Y&&K.length>0&&(0,r.jsxs)("div",{ref:e7,style:{position:"absolute",left:0,right:0,bottom:"calc(100% + 8px)",zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:8,boxShadow:"0 -6px 20px rgba(0,0,0,0.12)",overflow:"hidden",maxHeight:"min(44vh, 360px)"},children:[(0,r.jsx)("div",{title:eo("chat.inputHistory"),style:{height:30,padding:"0 10px",borderBottom:"1px solid var(--border)",display:"flex",alignItems:"center",color:"var(--text-dim)"},children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 3-6.7"}),(0,r.jsx)("path",{d:"M3 4v5h5"}),(0,r.jsx)("path",{d:"M12 7v5l3 2"})]})}),(0,r.jsx)("div",{style:{maxHeight:"calc(min(44vh, 360px) - 31px)",overflowY:"auto",padding:4},children:K.map((e,t)=>{let n=t===eU;return(0,r.jsxs)("button",{ref:e=>{td.current[t]=e},type:"button",onMouseDown:t=>{t.preventDefault(),t_(e)},onMouseEnter:()=>eK(t),style:{width:"100%",display:"flex",alignItems:"flex-start",gap:8,padding:"7px 8px",border:"none",borderRadius:6,background:n?"var(--bg-selected)":"none",color:"var(--text)",cursor:"pointer",textAlign:"left",fontSize:12.5,lineHeight:1.45},children:[(0,r.jsx)("span",{style:{flexShrink:0,fontFamily:"var(--font-mono)",fontSize:11,color:"var(--text-dim)",paddingTop:1},children:t+1}),(0,r.jsx)("span",{style:{minWidth:0,display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:2,overflow:"hidden",overflowWrap:"anywhere"},children:e})]},`${t}:${e}`)})})]}),eN&&null!==tN&&!Y&&(0,r.jsxs)("div",{ref:ts,style:{position:"absolute",left:0,right:0,bottom:"calc(100% + 8px)",zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:8,boxShadow:"0 -6px 20px rgba(0,0,0,0.12)",overflow:"hidden",boxSizing:"border-box",display:"flex",flexDirection:"column",maxHeight:null===eM?"min(72.8vh, 598px)":`min(72.8vh, 598px, ${eM}px)`},children:[(0,r.jsxs)("div",{style:{padding:"8px 10px",borderBottom:"1px solid var(--border)",display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,fontSize:11,color:"var(--text-dim)",flexShrink:0},children:[(0,r.jsx)("span",{children:Z?eo("chat.loadingCommands"):eo("chat.slashCommands",{label:tM})}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:eo("chat.tabEnter")})]}),(0,r.jsx)("div",{style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:10},children:Z||0!==tE.length?tI.map(e=>(0,r.jsxs)("section",{style:{marginBottom:12},children:[(0,r.jsxs)("div",{style:{position:"sticky",top:-10,zIndex:1,display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,padding:"4px 0 6px",background:"var(--bg)",color:"var(--text-dim)",fontSize:10,fontWeight:600,textTransform:"uppercase"},children:[(0,r.jsx)("span",{children:eo(a2[e.source])}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontWeight:500},children:e.items.length})]}),(0,r.jsx)("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(220px, 1fr))",gap:8},children:e.items.map(e=>{let{command:t,index:n}=e,i=n===e$,s=a3(t,e8);return(0,r.jsxs)("button",{ref:e=>{to.current[n]=e},type:"button",onMouseDown:e=>{e.preventDefault(),tU(t)},onMouseEnter:()=>eI(n),style:{width:"100%",minWidth:0,minHeight:58,display:"flex",flexDirection:"column",gap:4,justifyContent:"center",padding:"9px 10px",border:`1px solid ${i?"var(--accent)":"var(--border)"}`,borderRadius:7,background:i?"var(--bg-selected)":"var(--bg-panel)",color:"var(--text)",cursor:"pointer",textAlign:"left",boxShadow:i?"0 0 0 1px color-mix(in srgb, var(--accent) 28%, transparent)":"none"},children:[(0,r.jsxs)("span",{style:{fontSize:13,fontFamily:"var(--font-mono)",overflowWrap:"anywhere",wordBreak:"break-word",color:s?"var(--text-dim)":void 0},children:["/",t.name,s&&(0,r.jsx)("span",{style:{marginLeft:6,padding:"0 4px",border:"1px solid var(--border)",borderRadius:3,fontSize:9,color:"var(--text-dim)",whiteSpace:"nowrap"},children:eo("chat.dormant")})]}),t.description&&(0,r.jsx)("span",{style:{display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:2,overflow:"hidden",fontSize:11,lineHeight:1.35,color:"var(--text-dim)"},children:a8(t,eo)})]},`${t.source}:${t.name}`)})})]},e.source)):(0,r.jsx)("div",{style:{padding:"2px 2px 4px",fontSize:12,color:"var(--text-dim)"},children:eo("chat.noCommands")})})]}),eL&&null!==eR&&!Y&&(o=eX&&(!eY||eY.cwd!==er),l=1===tF.length?eo("chat.match"):eo("chat.matches",{count:tF.length}),a=eY?.truncated&&!tO?eR.query?eo("chat.searchingAll"):eo("chat.indexTruncated"):"",(0,r.jsxs)("div",{ref:tl,style:{position:"absolute",left:0,right:0,bottom:"calc(100% + 8px)",zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:8,boxShadow:"0 -6px 20px rgba(0,0,0,0.12)",overflow:"hidden",boxSizing:"border-box",display:"flex",flexDirection:"column",maxHeight:null===eP?"min(48vh, 400px)":`min(48vh, 400px, ${eP}px)`},children:[(0,r.jsxs)("div",{style:{padding:"8px 10px",borderBottom:"1px solid var(--border)",display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,fontSize:11,color:"var(--text-dim)",flexShrink:0},children:[(0,r.jsx)("span",{children:o?eo("chat.loadingFiles"):eo("chat.files",{label:l,hint:a})}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:eo("chat.tabEnter")})]}),(0,r.jsx)("div",{style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:4},children:o||0!==tF.length?tF.map((e,t)=>{let n=t===eO,i=e.path.split("/").pop()??e.path,s=e.path.slice(0,e.path.length-i.length);return(0,r.jsxs)("button",{ref:e=>{ta.current[t]=e},type:"button",onMouseDown:t=>{t.preventDefault(),tH(e)},onMouseEnter:()=>eF(t),style:{width:"100%",display:"flex",alignItems:"center",gap:8,padding:"6px 8px",border:"none",borderRadius:6,background:n?"var(--bg-selected)":"none",color:"var(--text)",cursor:"pointer",textAlign:"left",fontSize:12.5,fontFamily:"var(--font-mono)"},children:[(0,r.jsx)("span",{style:{flexShrink:0,display:"flex",alignItems:"center"},children:e.isDir?(0,r.jsx)(tJ,{size:14}):tX(i,14)}),(0,r.jsxs)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[s&&(0,r.jsx)("span",{style:{color:"var(--text-dim)"},children:s}),i,e.isDir&&(0,r.jsx)("span",{style:{color:"var(--text-dim)"},children:"/"})]})]},`${e.isDir?"d":"f"}:${e.path}`)}):(0,r.jsx)("div",{style:{padding:"6px 8px",fontSize:12,color:"var(--text-dim)"},children:tW&&!tO?eo("chat.searching"):eo("chat.noMatchingFiles")})})]})),(0,r.jsxs)("div",{className:tR?void 0:"chat-composer-row",style:{minWidth:0,display:"flex",flexDirection:tR?"column":"row",gap:8,alignItems:tR?"stretch":"center",background:"var(--bg)",border:es?"none":`1px solid ${eS?"var(--tool-bg)":f&&(u||h)?"rgba(234,179,8,0.4)":"color-mix(in srgb, var(--border) 70%, transparent)"}`,borderRadius:14*!es,padding:es?0:ec?"6px 6px 6px 12px":"10px 10px 10px 14px",boxShadow:es?"none":"0 1px 2px rgba(15,23,42,0.04), 0 8px 24px -12px rgba(15,23,42,0.10)",transition:"border-color 0.15s, background 0.15s, box-shadow 0.15s"},children:[(0,r.jsx)("textarea",{ref:e3,className:"chat-input-textarea","aria-label":es?eo("chat.askInSideChat"):void 0,value:eh,onChange:e=>{th.current=e.target.value,ef(e.target.value),e_(!1),tL(e.target.value,e.target.selectionStart)},onSelect:e=>{let t=e.currentTarget;tL(t.value,t.selectionStart)},onKeyDown:tY,onCompositionStart:()=>{tt.current=!0},onCompositionEnd:e=>{tt.current=!1,tn.current=Date.now();let t=e.currentTarget;tL(t.value,t.selectionStart)},onInput:tG,onPaste:tQ,placeholder:M?eo("chat.compactingPlaceholder"):f&&(u||h)?eo("chat.steerPlaceholder"):f?eo("chat.agentPlaceholder"):eo("chat.messagePlaceholder"),rows:1,style:{flex:tR?"none":1,minWidth:0,width:"100%",background:"none",border:"none",outline:"none",resize:"none",color:"var(--text)",fontSize:"var(--chat-content-font-size, 14px)",lineHeight:1.6,fontFamily:"inherit",minHeight:es?96:24,maxHeight:200,overflow:"auto"}}),f&&!eS?(0,r.jsxs)("div",{style:{display:"flex",alignItems:"stretch",gap:6,flexShrink:0,alignSelf:"flex-end"},children:[p&&(0,r.jsx)("button",{type:"button",onClick:tK,disabled:!eh.trim()||ew.length>0,title:eo("chat.sideChatHint"),"aria-label":eo("chat.sideChat"),className:`bg-transparent ${eh.trim()&&!ew.length?"cursor-pointer text-text-muted hover:bg-bg-hover hover:text-text":"cursor-not-allowed text-text-dim"}`,style:{width:38,display:"grid",placeItems:"center",padding:0,border:"1px solid var(--border)",borderRadius:8,transition:"background 0.12s"},children:(0,r.jsxs)("svg",{width:"17",height:"17",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M21 12a8 8 0 0 1-8 8H5.5a2 2 0 0 1-1.4-3.4A8 8 0 1 1 21 12z"}),(0,r.jsx)("path",{d:"M13 8.5v7M9.5 12h7"})]})}),u&&(0,r.jsxs)("button",{onClick:()=>tV("steer"),disabled:!tT,title:eo("chat.steerHint"),"aria-label":eo("chat.steer"),style:{display:"flex",alignItems:"center",gap:5,padding:"7px 12px",background:tT?"rgba(234,179,8,0.12)":"none",border:"1px solid rgba(234,179,8,0.35)",borderRadius:8,color:tT?"rgba(180,130,0,1)":"var(--text-dim)",cursor:tT?"pointer":"not-allowed",fontSize:13,fontWeight:600,letterSpacing:"-0.01em",transition:"background 0.12s"},children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("path",{d:"M5 1 L9 5 L5 9"}),(0,r.jsx)("line",{x1:"1",y1:"5",x2:"9",y2:"5"})]}),(0,r.jsx)("span",{className:"chat-composer-run-label",children:eo("chat.steer")})]}),h&&(0,r.jsxs)("button",{onClick:()=>tV("followup"),disabled:!tT,title:`${eo("chat.followUpHint")} (${ec?"Ctrl/Cmd+":""}Alt/Option+Enter)`,"aria-label":eo("chat.followUp"),"aria-keyshortcuts":ec?"Control+Alt+Enter Meta+Alt+Enter":"Alt+Enter",style:{display:"flex",alignItems:"center",gap:5,padding:"7px 12px",background:tT?"rgba(129,140,248,0.12)":"none",border:"1px solid rgba(129,140,248,0.35)",borderRadius:8,color:tT?"rgba(99,102,241,1)":"var(--text-dim)",cursor:tT?"pointer":"not-allowed",fontSize:13,fontWeight:600,letterSpacing:"-0.01em",transition:"background 0.12s"},children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("line",{x1:"5",y1:"1",x2:"5",y2:"6"}),(0,r.jsx)("polyline",{points:"2.5 3.5 5 1 7.5 3.5"}),(0,r.jsx)("line",{x1:"2",y1:"9",x2:"8",y2:"9"})]}),(0,r.jsx)("span",{className:"chat-composer-run-label",children:eo("chat.followUp")})]})]}):(0,r.jsxs)("button",{onClick:tS,disabled:!eh.trim()&&!ew.length,title:eo("chat.send"),"aria-label":eo("chat.send"),style:{flexShrink:0,alignSelf:"flex-end",display:"flex",alignItems:"center",justifyContent:"center",gap:6,...ec?{width:36,height:36,padding:0}:{padding:"7px 14px"},background:eh.trim()||ew.length?"var(--accent)":"var(--bg-panel)",border:"none",borderRadius:8,color:eh.trim()||ew.length?"var(--accent-contrast)":"var(--text-dim)",cursor:eh.trim()||ew.length?"pointer":"not-allowed",fontSize:13,fontWeight:600,letterSpacing:"-0.01em",boxShadow:eh.trim()||ew.length?"0 1px 3px color-mix(in srgb, var(--accent) 25%, transparent)":"none",transition:"background 0.15s, box-shadow 0.15s"},children:[(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("line",{x1:"2",y1:"7",x2:"11",y2:"7"}),(0,r.jsx)("polyline",{points:"7.5 3 12 7 7.5 11"})]}),!ec&&eo("chat.send")]})]})]}),eS&&(0,r.jsxs)("div",{className:"text-xs px-2 py-1",style:{color:eC?"var(--text-muted)":"var(--accent)",marginTop:4},children:[eo("chat.shell")," \xb7 ",eC?eo("chat.outputLocal"):eo("chat.outputModel")]}),!es&&(0,r.jsxs)("div",{className:"chat-input-controls",style:{marginTop:ec?4:8,display:ec?"grid":"flex",gridTemplateColumns:ec?"minmax(0, 1fr) auto":void 0,alignItems:"center",gap:6},children:[(0,r.jsxs)("div",{style:{flex:ec?"1 1 auto":"0 0 auto",minWidth:0,display:"flex",alignItems:"center",gap:2},children:[(0,r.jsx)("button",{onClick:()=>te.current?.click(),title:eo("chat.attachFiles"),style:{flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center",width:eu,height:eu,padding:0,background:"none",border:"none",borderRadius:9,color:ew.length?"var(--accent)":"var(--text-muted)",cursor:"pointer",opacity:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color=ew.length?"var(--accent)":"var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background="none",e.currentTarget.style.color=ew.length?"var(--accent)":"var(--text-muted)"},children:(0,r.jsxs)("svg",{width:ec?18:15,height:ec?18:15,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",ry:"2"}),(0,r.jsx)("circle",{cx:"8.5",cy:"8.5",r:"1.5"}),(0,r.jsx)("polyline",{points:"21 15 16 10 5 21"})]})}),(t0.length>0||m||b)&&S&&(0,r.jsx)(aF,{options:t0,value:m,onChange:S,onReselect:S,busy:C,isAutoSelection:g,defaultValue:N,onSetDefault:E,allOptions:k?.map(e=>({provider:e.provider,providerName:e.providerName,modelId:e.id,name:e.name})),onShowAll:j})]}),!ec&&(0,r.jsx)("div",{style:{flex:1}}),(0,r.jsxs)("div",{ref:e9,style:{flex:"0 0 auto",display:"flex",alignItems:"center",justifyContent:"flex-end",position:"relative",marginLeft:ec?0:"auto"},children:[ec&&(0,r.jsx)("button",{type:"button",title:eb?void 0:eo("chat.moreControls"),"aria-label":eo("chat.moreControls"),"aria-expanded":eb,"aria-hidden":eb||void 0,tabIndex:eb?-1:void 0,onClick:()=>{ey(!0)},style:{display:"flex",alignItems:"center",justifyContent:"center",width:"100%",height:eu,padding:"8px 10px",background:"none",border:"none",borderRadius:9,color:"var(--text-muted)",cursor:eb?"default":"pointer",fontSize:12,fontWeight:500,visibility:eb?"hidden":"visible",pointerEvents:eb?"none":"auto",transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{eb||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{eb||(e.currentTarget.style.background="none",e.currentTarget.style.color="var(--text-muted)")},children:eo("chat.moreControls")}),(0,r.jsxs)("div",{style:{display:ec?eb?"flex":"none":"flex",alignItems:"center",gap:ec?1:2,...ec?{position:"absolute",right:0,bottom:0,zIndex:60,padding:1,width:"max-content",maxWidth:"calc(100vw - 32px)",flexWrap:"nowrap",justifyContent:"flex-end",border:"1px solid color-mix(in srgb, var(--border) 72%, transparent)",borderRadius:10,background:"color-mix(in srgb, var(--bg-panel) 92%, var(--bg))",boxShadow:"0 8px 24px rgba(0,0,0,0.14)",backdropFilter:"blur(10px)"}:null},children:[O&&(0,r.jsxs)("div",{ref:e6,style:{position:"relative"},children:[(0,r.jsxs)("button",{onClick:()=>ev(e=>!e),title:f?eo("chat.currentReasoning",{level:t8}):eo("chat.changeReasoning",{level:t8}),"aria-label":eo("chat.changeReasoningLabel"),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:ec?"0 10px":"8px 12px",width:ec?"auto":void 0,height:eu,background:ex?"var(--bg-hover)":"none",border:"none",borderRadius:9,color:"var(--text-muted)",cursor:"pointer",fontSize:12,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=ex?"var(--bg-hover)":"none",e.currentTarget.style.color="var(--text-muted)"},children:[(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("path",{d:"M9.5 2A5.5 5.5 0 0 0 4 7.5c0 1.7.78 3.21 2 4.21V14a1 1 0 0 0 1 1h5a1 1 0 0 0 1-1v-2.29c1.22-1 2-2.51 2-4.21A5.5 5.5 0 0 0 9.5 2z"}),(0,r.jsx)("line",{x1:"7",y1:"18",x2:"12",y2:"18"}),(0,r.jsx)("line",{x1:"8",y1:"21",x2:"11",y2:"21"})]}),(!ec||eb)&&(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:t8})]}),ex&&(0,r.jsx)("div",{style:{position:"absolute",bottom:"calc(100% + 6px)",...ec?{left:0}:{right:0},zIndex:100,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:8,boxShadow:"0 -4px 16px rgba(0,0,0,0.10)",overflow:"hidden",minWidth:180},children:aY.filter(e=>!F||"auto"===e||F.includes(e)).map(e=>{let t="auto"===e?W:!W&&t4===e,n=eo(aG[e]),i="auto"!==e&&D?D[e]:void 0,s=null!=i&&i!==e?i:e,o=null!=i&&i!==e;return(0,r.jsxs)(aO,{active:t,onSelect:()=>{if(ev(!1),"auto"===e){W||O("auto");return}(!t||W)&&O(e)},gutter:!!H,star:H&&"auto"!==e?{isDefault:B===e,saveLabel:eo("chat.saveDefaultThinking"),defaultLabel:eo("chat.defaultThinking"),onSave:()=>{ev(!1),H(e)}}:void 0,children:[(0,r.jsxs)("span",{style:{flex:1},children:[s,o&&(0,r.jsxs)("span",{style:{fontSize:10,color:"var(--text-dim)",fontFamily:"var(--font-mono)",marginLeft:5},children:["(",e,")"]})]}),(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",marginLeft:8},children:n})]},e)})})]}),!f&&z&&(0,r.jsxs)("div",{ref:e5,style:{position:ec?"static":"relative"},children:[(0,r.jsxs)("button",{onClick:e=>{f||nt(e)||eg(e=>!e)},disabled:f,title:eo("chat.changeToolPreset")+`: ${t7}`,"aria-label":eo("chat.changeToolPreset"),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:ec?"0 10px":"8px 12px",width:ec?"auto":void 0,height:eu,background:em?"var(--bg-hover)":"none",border:"none",borderRadius:9,color:"var(--text-muted)",cursor:f?"not-allowed":"pointer",fontSize:12,opacity:f?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{f||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.background=em?"var(--bg-hover)":"none",e.currentTarget.style.color="var(--text-muted)"},children:[(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)("path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"})}),(!ec||eb)&&(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:t7})]}),em&&(0,r.jsx)("div",{style:{position:"absolute",bottom:"calc(100% + 6px)",right:0,maxWidth:ec?"calc(100vw - 16px)":void 0,zIndex:100,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:8,boxShadow:"0 -4px 16px rgba(0,0,0,0.10)",overflow:"hidden",minWidth:120},children:aB.map(e=>{let t,n=aH[e],i=(L??"configured")===n;return t="configured"===e?eo("chat.configuredTools"):"chat-only"===e?eo("chat.chatOnly"):"read-only"===e?eo("chat.readOnlyTools",{count:4}):"default"===e?eo("chat.builtInTools",{count:4}):eo("chat.allBuiltInTools"),(0,r.jsxs)("button",{onClick:()=>{eg(!1),i||z(n)},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:i?"var(--bg-selected)":"none",border:"none",color:i?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",fontWeight:i?600:400,whiteSpace:"nowrap"},onMouseEnter:e=>{i||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{i||(e.currentTarget.style.background="none")},children:[i?(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),(0,r.jsx)("span",{style:{flex:1},children:e}),(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",marginLeft:8},children:t})]},e)})})]}),(!f||M)&&$&&(0,r.jsx)("div",{children:(0,r.jsx)("button",{onClick:M?I:e=>{nt(e)||$()},style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:ec?"0 10px":"8px 12px",width:ec?"auto":void 0,height:eu,background:M?"rgba(239,68,68,0.08)":"none",border:"none",borderRadius:9,color:M?"#ef4444":"var(--text-muted)",cursor:"pointer",fontSize:12,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background=M?"rgba(239,68,68,0.16)":"var(--bg-hover)",e.currentTarget.style.color=M?"#ef4444":"var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background=M?"rgba(239,68,68,0.08)":"none",e.currentTarget.style.color=M?"#ef4444":"var(--text-muted)"},title:M?eo("chat.stopCompaction"):eo("chat.compactContext"),"aria-label":M?eo("chat.stopCompaction"):eo("chat.compactContext"),children:M?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",children:(0,r.jsx)("rect",{x:"2",y:"2",width:"6",height:"6",rx:"1",fill:"currentColor"})}),(!ec||eb)&&(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:eo("chat.compacting")})]}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("polyline",{points:"4 14 10 14 10 20"}),(0,r.jsx)("polyline",{points:"20 10 14 10 14 4"}),(0,r.jsx)("line",{x1:"10",y1:"14",x2:"3",y2:"21"}),(0,r.jsx)("line",{x1:"21",y1:"3",x2:"14",y2:"10"})]}),(!ec||eb)&&(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:eo("chat.compact")})]})})}),f&&(0,r.jsxs)("button",{onClick:c,title:eo("chat.stopAgent"),style:{display:"flex",alignItems:"center",gap:6,padding:"8px 14px",height:eu,background:"rgba(239,68,68,0.08)",border:"1px solid rgba(239,68,68,0.3)",borderRadius:9,color:"#ef4444",cursor:"pointer",fontSize:12,fontWeight:600,whiteSpace:"nowrap",letterSpacing:"-0.01em",transition:"background 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="rgba(239,68,68,0.16)"},onMouseLeave:e=>{e.currentTarget.style.background="rgba(239,68,68,0.08)"},children:[(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",children:(0,r.jsx)("rect",{x:"1.5",y:"1.5",width:"7",height:"7",rx:"1.5",fill:"currentColor"})}),eo("chat.stop")]}),void 0!==Q&&(0,r.jsx)("button",{onClick:Q,title:X?eo("chat.disableSound"):eo("chat.enableSound"),"aria-label":X?eo("chat.disableSound"):eo("chat.enableSound"),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,width:eu,height:eu,padding:0,background:"none",border:"none",borderRadius:9,color:X?"var(--text-muted)":"var(--text-dim)",cursor:"pointer",opacity:X?1:.55,transition:"background 0.12s, color 0.12s, opacity 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)",e.currentTarget.style.opacity="1"},onMouseLeave:e=>{e.currentTarget.style.background="none",e.currentTarget.style.color=X?"var(--text-muted)":"var(--text-dim)",e.currentTarget.style.opacity=X?"1":"0.55"},children:X?(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),(0,r.jsx)("path",{d:"M15.54 8.46a5 5 0 0 1 0 7.07"}),(0,r.jsx)("path",{d:"M19.07 4.93a10 10 0 0 1 0 14.14"})]}):(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),(0,r.jsx)("line",{x1:"23",y1:"9",x2:"17",y2:"15"}),(0,r.jsx)("line",{x1:"17",y1:"9",x2:"23",y2:"15"})]})}),ec&&eb&&(0,r.jsx)("button",{type:"button",title:eo("chat.collapseControls"),"aria-label":eo("chat.collapseControls"),"aria-expanded":!0,onClick:()=>{eg(!1),ev(!1),ey(!1)},style:{display:"flex",alignItems:"center",justifyContent:"center",width:ec?eu:36,height:eu,padding:0,marginLeft:0,background:"var(--bg-hover)",border:"none",borderLeft:"1px solid color-mix(in srgb, var(--border) 72%, transparent)",borderRadius:"0 9px 9px 0",color:"var(--text)",cursor:"pointer",transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-selected)"},onMouseLeave:e=>{e.currentTarget.style.background="var(--bg-hover)"},children:(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[(0,r.jsx)("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),(0,r.jsx)("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]})]})]})]})]})}));function dd(){try{return window.localStorage}catch{return null}}function dc(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:dd();if(!t)return!1;try{return"true"===t.getItem(e)}catch{return!1}}function du(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:dd();if(n)try{n.setItem(e,String(t))}catch{}}let dp="pi-web:minimap-preview-locked";function dh(e){return dc(dp,e)}var df=n(88576),dm=n.n(df),dg=n(5284),dx=n.n(dg);function dv(e){let{locked:t,iconSize:n=16,className:i,...s}=e;return(0,r.jsx)("button",{...s,type:"button","aria-pressed":t,className:i?`${dx().lock} ${i}`:dx().lock,children:(0,r.jsxs)("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("rect",{x:"4",y:"11",width:"16",height:"10",rx:"2"}),t?(0,r.jsx)("path",{d:"M8 11V7a4 4 0 0 1 8 0v4"}):(0,r.jsx)("path",{d:"M8 11V7a4 4 0 0 1 7.9-.9"})]})})}function db(e){let{level:t,children:n,headingIndex:i,onClick:s}=e;return(0,r.jsx)("button",{type:"button",className:dm().heading,"data-level":t,"data-preview-heading-index":i??void 0,disabled:null===i||!s,onClick:e=>{e.stopPropagation(),null!==i&&s?.(i)},children:n})}let dy=[...si??[],function(){return e=>{if(!Array.isArray(e.children))return;let t=e.children.filter(e=>"heading"===e.type&&"number"==typeof e.depth&&e.depth<=3);if(t.length>0){t.forEach((e,t)=>{e.data={...e.data,hProperties:{...e.data?.hProperties,"data-preview-heading-index":t}}}),e.children=t;return}let n=e.children.find(e=>"paragraph"===e.type);e.children=n?[n]:[]}}],dw=[[iA.A,{throwOnError:!1,strict:!1}]];function dk(e){let t=e?.properties,n=t?.dataPreviewHeadingIndex??t?.["data-preview-heading-index"];return"number"==typeof n?n:"string"==typeof n&&/^\d+$/.test(n)?Number(n):null}let dj=(0,i.memo)(function(e){let{markdown:t,onHeadingClick:n,onAnswerClick:s}=e,o=(0,i.useMemo)(()=>iG(t),[t]);return t?(0,r.jsx)("div",{className:dm().outline,children:(0,r.jsx)(iC.oz,{remarkPlugins:dy,rehypePlugins:dw,components:{h1:e=>{let{children:t,node:i}=e;return(0,r.jsx)(db,{level:1,headingIndex:dk(i),onClick:n,children:t})},h2:e=>{let{children:t,node:i}=e;return(0,r.jsx)(db,{level:2,headingIndex:dk(i),onClick:n,children:t})},h3:e=>{let{children:t,node:i}=e;return(0,r.jsx)(db,{level:3,headingIndex:dk(i),onClick:n,children:t})},h4:()=>null,h5:()=>null,h6:()=>null,p:e=>{let{children:t}=e;return(0,r.jsx)("button",{type:"button",className:dm().paragraph,onClick:s,children:t})},blockquote:()=>null,ul:()=>null,ol:()=>null,pre:()=>null,table:()=>null,hr:()=>null,a:e=>{let{children:t}=e;return(0,r.jsx)(r.Fragment,{children:t})},code:e=>{let{children:t}=e;return(0,r.jsx)(r.Fragment,{children:t})}},children:o})}):null}),dS=(0,i.memo)(function(e){let{messages:t,getStreamingMessage:n,scrollContainer:s,messageRefs:o,onRevealHistory:l,turnsBefore:a,turnAnchors:d}=e,{t:c}=(0,tm.s)(),[u,p]=(0,i.useState)(!1),[h,f]=(0,i.useState)([]),[m,g]=(0,i.useState)(null),[x,v]=(0,i.useState)(600),[b,y]=(0,i.useState)(!1),[w,k]=(0,i.useState)(dh),[j,S]=(0,i.useState)(null),C=(0,i.useRef)(!1),N=(0,i.useRef)(null),E=(0,i.useRef)([]),$=(0,i.useRef)({nodes:[],gap:50,fillsHeight:!1}),I=(0,i.useRef)(null),M=(0,i.useRef)(new Map),T=(0,i.useRef)(null),R=(0,i.useRef)(null),A=(0,i.useRef)(null),L=(0,i.useRef)(t);L.current=t;let z=(0,i.useRef)(d);z.current=d;let P=(0,i.useMemo)(()=>(function(e,t){if(0===e.length)return{nodes:[],gap:50,fillsHeight:!1};let n=Math.max(1,t),r=Math.max(0,n-12-48);if(1===e.length)return{nodes:[{...e[0],topRatio:12/n}],gap:50,fillsHeight:!1};let i=r/(e.length-1),s=Math.min(50,i);return{nodes:e.map((e,t)=>({...e,topRatio:(12+t*s)/n})),gap:s,fillsHeight:i<=50}})(h,x),[h,x]),{nodes:W,gap:O}=P;$.current=P;let F=(0,i.useCallback)(e=>{R.current={index:e,until:Date.now()+1600},g(e)},[]),D=(0,i.useCallback)((e,t)=>{let n=R.current;if(n&&Date.now()<n.until)return void g(n.index);R.current=null;let r=t.filter(e=>null!==e.targetTurn.scrollTop);if(0===r.length)return void g(null);let i=e.scrollTop+.3*e.clientHeight;g(r.reduce((e,t)=>Math.abs((t.targetTurn.scrollTop??0)-i)<Math.abs((e.targetTurn.scrollTop??0)-i)?t:e,r[0]).index)},[]),B=(0,i.useCallback)(()=>{let e=s.current;if(!e)return;let t=e.scrollHeight-e.clientHeight,n=E.current;p(t>20),D(e,n)},[s,D]),H=(0,i.useRef)(null),_=(0,i.useCallback)(()=>{H.current||(H.current=setTimeout(()=>{H.current=null;let e=s.current,t=N.current;if(!e||!t)return;let r=o.current,i=e.getBoundingClientRect(),l=[],a=0,d=null,c=n();for(let[t,n]of(c?[...L.current,c]:L.current).entries()){let s=!0===z.current[t];if(!s&&"assistant"!==n.role)continue;let o=null;if(r0(n,s)&&(o=r?.[a]??null,a++),s){d=null;let t=o?.getBoundingClientRect();d={userMessage:n,assistantPreviews:[],scrollTop:t?t.top-i.top+e.scrollTop:null,toolCount:0},l.push(d);continue}if(!d)continue;null===d.scrollTop&&o&&rG(d.userMessage)&&(d.scrollTop=o.getBoundingClientRect().top-i.top+e.scrollTop),d.toolCount+="assistant"===n.role&&Array.isArray(n.content)?n.content.reduce((e,t)=>e+ +("toolCall"===t.type),0):0;let c=function(e){if("assistant"!==e.role)return"";let{answerBlocks:t}=r6(e);return t.filter(e=>"text"===e.type).map(e=>e.text).join("\n\n").trim()}(n);c&&d.assistantPreviews.push({markdown:c,element:o})}let u=l.map((e,t)=>({topRatio:0,targetTurn:e,index:t}));v(t.clientHeight),E.current=u,f(u),p(e.scrollHeight-e.clientHeight>20),D(e,u);let h=A.current,m=h?u[h.nodeIndex]:null;if(h&&m){let t=void 0===h.assistantIndex?null:m.targetTurn.assistantPreviews[h.assistantIndex],n=m.targetTurn.scrollTop;if("assistant"===h.target){let r=t?.element?.getBoundingClientRect();n=r?r.top-i.top+e.scrollTop:null}else if("heading"===h.target){let r=void 0===h.headingIndex?null:t?.element?.querySelectorAll("h1, h2, h3").item(h.headingIndex),s=r?.getBoundingClientRect();n=s?s.top-i.top+e.scrollTop:null}if(null===n)return;A.current=null,F(m.index);let r=.3*e.clientHeight;e.scrollTo({top:Math.max(0,n-r),behavior:"smooth"})}},150))},[n,F,o,s,D]);(0,i.useEffect)(()=>{let e=s.current;if(e)return e.addEventListener("scroll",B,{passive:!0}),()=>e.removeEventListener("scroll",B)},[s,B]),(0,i.useEffect)(()=>{let e=s.current;if(!e)return;let t=()=>{_(),B()},n=new ResizeObserver(t);return n.observe(e),e.firstElementChild&&n.observe(e.firstElementChild),t(),()=>{n.disconnect(),H.current&&(clearTimeout(H.current),H.current=null)}},[_,s,B]),(0,i.useEffect)(()=>{let e=setTimeout(()=>{_(),B()},50);return()=>clearTimeout(e)},[t.length,d,_,B]);let U=(0,i.useCallback)((e,t)=>{let n=s.current;if(!n)return;if(F(e.index),null===e.targetTurn.scrollTop){A.current={nodeIndex:e.index,target:"user"},l();return}let r=Math.max(0,e.targetTurn.scrollTop-.3*n.clientHeight);n.scrollTo({top:r,behavior:t})},[F,l,s]),K=(0,i.useCallback)((e,t)=>{let n=s.current;if(!n)return;let r=e.targetTurn.assistantPreviews[t]?.element;if(!r){A.current={nodeIndex:e.index,target:"assistant",assistantIndex:t},l();return}let i=n.getBoundingClientRect(),o=r.getBoundingClientRect().top-i.top+n.scrollTop-.3*n.clientHeight;F(e.index),n.scrollTo({top:Math.max(0,o),behavior:"smooth"})},[F,l,s]),q=(0,i.useCallback)(e=>{let{nodes:t,gap:n,fillsHeight:r}=$.current,i=N.current?.clientHeight??0;if(0===t.length||i<=0)return null;let s=Math.max(0,Math.min(i,e*i)),o=t[0].topRatio*i,l=n>0?Math.round((s-o)/n):0,a=Math.max(0,Math.min(t.length-1,l)),d=t[a];if(!r&&Math.abs(s-d.topRatio*i)>Math.max(10,n/2))return null;return d},[]),V=(0,i.useCallback)((e,t,n)=>{let r=s.current;if(!r)return;let i=e.targetTurn.assistantPreviews[t]?.element;if(!i){A.current={nodeIndex:e.index,target:"heading",assistantIndex:t,headingIndex:n},l();return}let o=i.querySelectorAll("h1, h2, h3").item(n);if(!o)return;let a=r.getBoundingClientRect(),d=o.getBoundingClientRect().top-a.top+r.scrollTop-.3*r.clientHeight;F(e.index),r.scrollTo({top:Math.max(0,d),behavior:"smooth"})},[F,l,s]),Z=(0,i.useCallback)(()=>{T.current&&(clearTimeout(T.current),T.current=null)},[]),J=(0,i.useCallback)(()=>{w||(Z(),y(!0))},[Z,w]),Y=(0,i.useCallback)(()=>{let e=!w;k(e),du(dp,e,void 0),e&&(Z(),y(!1),S(null))},[Z,w]),G=(0,i.useCallback)(()=>{Z(),T.current=setTimeout(()=>{T.current=null,y(!1),S(null)},250)},[Z]);(0,i.useEffect)(()=>()=>Z(),[Z]);let X=(0,i.useCallback)(e=>{if(!u)return;C.current=!0,J();let t=e.currentTarget.getBoundingClientRect();S(Math.max(0,Math.min(1,(e.clientY-t.top)/t.height)));let n=(e,n)=>{let r=q(Math.max(0,Math.min(1,(e-t.top)/t.height)));r&&U(r,n)};n(e.clientY,"smooth");let r=e=>{C.current&&n(e.clientY,"auto")},i=()=>{C.current=!1,window.removeEventListener("mousemove",r),window.removeEventListener("mouseup",i)};window.addEventListener("mousemove",r),window.addEventListener("mouseup",i)},[q,U,J,u]),Q=null===j?null:q(j),ee=Q?.index??null;if((0,i.useEffect)(()=>{if(!b||null===ee)return;let e=I.current,t=M.current.get(ee);if(!e||!t)return;let n=t.offsetTop-(e.clientHeight-t.offsetHeight)/2;e.scrollTop=Math.max(0,n)},[h,b,ee]),!u)return null;let et=Math.max(1,(W.length>0?W[W.length-1].topRatio*x:12)-12);return(0,r.jsxs)("div",{ref:N,onMouseDown:X,onMouseEnter:J,onMouseLeave:G,onMouseMove:e=>{let t=e.currentTarget.getBoundingClientRect();S((e.clientY-t.top)/t.height)},style:{width:36,flexShrink:0,position:"relative",cursor:"pointer",userSelect:"none",borderLeft:"1px solid var(--border)",background:"var(--bg-panel)",overflow:"visible"},children:[a>0&&(0,r.jsx)("div",{"data-minimap-earlier":"",style:{position:"absolute",left:"50%",top:0,height:12,width:1,background:"repeating-linear-gradient(to bottom, var(--text-dim) 0 2px, transparent 2px 4px)",transform:"translateX(-50%)",zIndex:0}}),(0,r.jsx)("div",{style:{position:"absolute",left:"50%",top:12,height:et,width:1,background:"var(--border)",transform:"translateX(-50%)",zIndex:0}}),W.map(e=>{let t=b&&Q?.index===e.index,n=m===e.index;return(0,r.jsx)("div",{"data-minimap-node-index":e.index,"data-minimap-node-active":n?"":void 0,style:{position:"absolute",top:`${100*e.topRatio}%`,transform:"translateY(-50%)",left:0,right:0,height:Math.max(1,O),display:"flex",alignItems:"center",justifyContent:"center",pointerEvents:"none",zIndex:2},children:(0,r.jsx)("div",{style:{width:8,height:8,borderRadius:2,background:n?"rgba(128,128,128,0.42)":"rgba(128,128,128,0.16)",border:`1.5px solid ${n?"rgba(128,128,128,0.95)":"rgba(128,128,128,0.58)"}`,boxShadow:n?"0 0 0 2px var(--bg-panel)":"none",transition:"transform 0.1s, background 0.1s",transform:t?"scale(1.25)":"scale(1)"}})},e.index)}),(0,r.jsx)(dv,{locked:w,className:dm().lock,"data-minimap-lock":w?"on":"off",title:c(w?"chatMinimap.unlockPreview":"chatMinimap.lockPreview"),"aria-label":c("chatMinimap.lockPreview"),onMouseDown:e=>e.stopPropagation(),onClick:e=>{e.stopPropagation(),Y()}}),b&&h.length>0&&(0,r.jsxs)("div",{ref:I,className:dm().preview,"data-minimap-preview-box":"",onMouseEnter:J,onMouseDown:e=>e.stopPropagation(),onMouseMove:e=>e.stopPropagation(),children:[a>0&&(0,r.jsx)("button",{type:"button",className:dm().earlier,"data-minimap-preview-earlier":"",onClick:()=>s.current?.scrollTo({top:0,behavior:"smooth"}),children:c("chatMinimap.earlierTurns",{count:a})}),h.map(e=>{var t;let n=ee===e.index;return(0,r.jsxs)("div",{ref:t=>{t?M.current.set(e.index,t):M.current.delete(e.index)},className:dm().turn,"data-minimap-preview-index":e.index,"data-located":n?"true":void 0,children:[(0,r.jsxs)("span",{className:dm().number,children:[(0,r.jsx)("span",{"aria-hidden":"true",children:String(a+e.index+1).padStart(2,"0")}),e.targetTurn.toolCount>0&&(0,r.jsx)("span",{className:dm().toolBadge,role:"img",title:c("chatMinimap.toolCalls",{count:e.targetTurn.toolCount}),"aria-label":c("chatMinimap.toolCalls",{count:e.targetTurn.toolCount}),children:e.targetTurn.toolCount>99?"99+":e.targetTurn.toolCount})]}),(0,r.jsxs)("div",{className:dm().content,children:[(0,r.jsx)("button",{type:"button",className:dm().user,"data-minimap-preview-user":e.index,onClick:()=>{U(e,"smooth")},children:(0,r.jsx)("span",{className:dm().userText,children:rG(e.targetTurn.userMessage)?c("chatMinimap.extensionTurn",{type:e.targetTurn.userMessage.customType}):"string"==typeof(t=e.targetTurn.userMessage).content?t.content.trim():t.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n").trim()})}),e.targetTurn.assistantPreviews.map((t,n)=>(0,r.jsxs)("div",{className:dm().assistant,children:[(0,r.jsx)("button",{type:"button",className:dm().assistantJump,"data-minimap-preview-assistant":`${e.index}-${n}`,onClick:()=>K(e,n),"aria-label":c("chatMinimap.locateAssistant"),title:c("chatMinimap.locateAssistant"),children:"A"}),(0,r.jsx)(dj,{markdown:t.markdown,onAnswerClick:()=>K(e,n),onHeadingClick:t=>V(e,n,t)})]},n))]})]},e.index)})]})]})});var dC=n(42790);function dN(e){let{text:t}=e,n=(0,i.useMemo)(()=>{let e=new dC.v;e.use_classes=!0;let n=t.replace(rB,"");return e.ansi_to_html(n).replaceAll('<a href="','<a target="_blank" rel="noopener noreferrer" href="')},[t]);return(0,r.jsx)("span",{dangerouslySetInnerHTML:{__html:n}})}function dE(e){let t,n,s,{widgets:o,children:l}=e,{t:a}=(0,tm.s)(),d=(0,i.useId)(),c=(0,i.useRef)(null),u=(0,i.useRef)(new Map),[p,h]=(0,i.useState)(()=>o.find(e=>{let t=e.lines.length;return t>1&&t<=3})?.key??null),[f,m]=(0,i.useState)(()=>new Set);if((0,i.useEffect)(()=>{var e;let t=new Map(o.map(e=>[e.key,[...e.lines]])),n=(e=c.current,e?Array.from(t,t=>{let[n,r]=t,i=e.get(n);return i&&i.length===r.length?r.some((e,t)=>e!==i[t])?n:null:i?n:null}).filter(e=>null!==e):[]);for(let[e,n]of(c.current=t,u.current))t.has(e)||(clearTimeout(n),u.current.delete(e));for(let e of(m(e=>{let r=new Set(Array.from(e).filter(e=>t.has(e)));for(let e of n)r.add(e);return r.size===e.size&&Array.from(r).every(t=>e.has(t))?e:r}),n)){let t=u.current.get(e);t&&clearTimeout(t),u.current.set(e,setTimeout(()=>{u.current.delete(e),m(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n})},1100))}},[o]),(0,i.useEffect)(()=>()=>{for(let e of u.current.values())clearTimeout(e);u.current.clear()},[]),0===o.length)return null;let g=o.find(e=>e.key===p&&e.lines.length>0);return(0,r.jsxs)(r.Fragment,{children:[g&&(0,r.jsx)("div",{className:"extension-widget-panels",children:(t=o.indexOf(g),n=`${d}-trigger-${t}`,s=`${d}-panel-${t}`,(0,r.jsxs)("section",{id:s,className:"extension-widget-panel","aria-labelledby":n,children:[(0,r.jsx)("div",{className:"extension-widget-panel-heading",children:g.key}),(0,r.jsx)("pre",{className:"extension-widget-content",children:(0,r.jsx)(dN,{text:g.lines.join("\n")})})]},g.key))}),(0,r.jsxs)("div",{className:"extension-status-row",children:[(0,r.jsx)("div",{className:"extension-widget-triggers","aria-label":a("chat.extensionWidgets"),children:o.map((e,t)=>{let n=e.lines.length>0,i=n&&e.key===g?.key,s=f.has(e.key),o=a(1===e.lines.length?"chat.extensionWidgetLine":"chat.extensionWidgetLines",{count:e.lines.length}),l=a("belowEditor"===e.placement?"chat.extensionWidgetBelow":"chat.extensionWidgetAbove"),c=`${d}-trigger-${t}`,u=`${d}-panel-${t}`,p=(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{className:"extension-widget-update-pulse","aria-hidden":"true"}),(0,r.jsx)("span",{className:"extension-widget-placement","aria-hidden":"true",children:(0,r.jsx)("svg",{className:"extension-widget-placement-icon",viewBox:"0 0 8 6",width:"8",height:"6","data-direction":"belowEditor"===e.placement?"down":"up",focusable:"false",children:(0,r.jsx)("path",{d:"belowEditor"===e.placement?"M0 0h8L4 6z":"M4 0l4 6H0z"})})}),(0,r.jsx)("span",{className:"extension-widget-key",children:e.key})]});return n?(0,r.jsx)("button",{id:c,type:"button",className:`extension-widget-trigger${i?" is-expanded":""}${s?" is-updating":""}`,"aria-controls":u,"aria-expanded":i,"aria-label":`${l}: ${e.key}, ${o}`,title:`${e.key} - ${l} - ${i?a("i18n.collapse"):a("i18n.expand")}`,onClick:()=>{h(t=>{var n;return t===(n=e.key)?null:n})},children:p},e.key):(0,r.jsx)("div",{className:`extension-widget-trigger${s?" is-updating":""}`,"aria-label":`${l}: ${e.key}, ${o}`,title:`${e.key} - ${l}`,children:p},e.key)})}),l]})]})}let d$="command:";function dI(e){let{statuses:t,widgets:n=[],onCommand:i,commandsDisabled:s=!1}=e,o=function(e){let t=[];for(let n of[...e].sort((e,t)=>e.key.localeCompare(t.key))){let e=n.text.replace(/\r\n?/g,"\n").split("\n").map(e=>e.replace(/\t/g," ").replace(/ +/g," ").trim()).join("\n").trim(),r=function(e){if(!e.startsWith(d$))return null;let t=e.slice(d$.length).trim();return t.length>1&&t.startsWith("/")?t:null}(n.key);if(r){let n=rH(e).replace(/\s+/g," ").trim();t.push({kind:"command",command:r,label:n||r})}else rH(e).trim()&&t.push({kind:"text",text:e})}return t}(t);if(0===o.length&&0===n.length)return null;let l=o.some(e=>"command"===e.kind),a=o.map(e=>"text"===e.kind?rH(e.text):e.label).join(" "),d=o.length>0?(0,r.jsx)("div",{role:"status",className:"extension-status-line","aria-label":a,title:a,children:(0,r.jsx)("span",{className:"extension-status-text",children:o.map((e,t)=>"text"===e.kind?(0,r.jsx)("span",{className:"extension-status-item",children:(0,r.jsx)(dN,{text:e.text})},t):(0,r.jsx)("button",{type:"button",className:"extension-status-item extension-status-command",disabled:!i||s,title:`${e.label} \xb7 ${e.command}`,"aria-label":`${e.label} (${e.command})`,onClick:()=>i?.(e.command),children:e.label},t))})}):null;return(0,r.jsx)("div",{className:`extension-status-shelf${n.length>0?" has-widgets":""}${o.length>0?" has-status":""}${l?" has-commands":""}`,children:n.length>0?(0,r.jsx)(dE,{widgets:n,children:d}):d})}function dM(e,t){return e?.kind==="running_tools"&&e.tools.length>0?e:t?{kind:"waiting_model"}:{kind:"running_command"}}function dT(e){switch(e.method){case"select":case"confirm":case"input":case"editor":return!0;case"custom":return!0!==e.closed;default:return!1}}function dR(e,t){return e.every(e=>t.has(e.id))?e:e.filter(e=>t.has(e.id))}function dA(e,t){return e.some(e=>e.id===t)?e.filter(e=>e.id!==t):e}function dL(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function dz(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if("assistant"!==e.role)return e;let n=e.content;if(!Array.isArray(n))return e;let r=n.map(e=>(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!dL(e)||"toolCall"!==e.type)return null;let n={type:"toolCall",toolCallId:"string"==typeof e.toolCallId?e.toolCallId:"string"==typeof e.id?e.id:"",toolName:"string"==typeof e.toolName?e.toolName:"string"==typeof e.name?e.name:"",input:"object"!=typeof e.input||null===e.input||Array.isArray(e.input)?"object"!=typeof e.arguments||null===e.arguments||Array.isArray(e.arguments)?{}:e.arguments:e.input},r=t.includeStreamingRawInput?function(e){if("string"==typeof e.rawInput)return e.rawInput;if("string"==typeof e.partialJson)return e.partialJson;if("string"==typeof e.partialArgs)return e.partialArgs;let t=dL(e.customInput)?e.customInput:null,n=t&&"string"==typeof t.property?t.property:null,r=dL(e.arguments)?e.arguments:null;return n&&r&&"string"==typeof r[n]?r[n]:void 0}(e):void 0;return void 0===r?n:{...n,rawInput:r}})(e,t)??e);return{...e,content:r}}function dP(e){if(!e||"object"!=typeof e)return null;let{reason:t,cwd:n}=e;return"cwd-missing"===t&&"string"==typeof n&&n?n:null}class dW extends Error{constructor(e,t,n,r,i){super(e),this.status=t,this.code=n,this.accepted=r,this.missingCwd=i,this.name="AgentCommandError"}}function dO(e){return e instanceof dW&&"prompt_rejected"===e.code&&!1===e.accepted}function dF(e){return`/api/agent/${encodeURIComponent(e)}?systemPrompt=0`}async function dD(e,t){let n=await fetch(`/api/agent/${encodeURIComponent(e)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),r=await n.json().catch(()=>({}));if(!n.ok||r.error)throw new dW(r.error??`HTTP ${n.status}`,n.status,r.code,r.accepted,dP(r)??void 0);return r.data}let dB={not_found:"sideChat.error.notFound",unsaved:"sideChat.error.unsaved",empty:"sideChat.error.empty",subagent:"sideChat.error.subagent",side:"sideChat.error.side"};async function dH(e,t,n){let r=await fetch(`/api/sessions/${encodeURIComponent(e)}/fork`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({side:!0,...n?{name:n}:{}}),cache:"no-store"}),i=await r.json().catch(()=>null);return r.ok&&i?.sessionId&&i.session?{session:i.session}:{error:i?.code&&i.code in dB?t(dB[i.code]):i?.error??`HTTP ${r.status}`}}async function d_(e){let t=await fetch(`/api/sessions/${encodeURIComponent(e)}`,{method:"DELETE",cache:"no-store"});if(t.ok)return null;let n=await t.json().catch(()=>null);return{error:n?.error??`HTTP ${t.status}`}}function dU(){return globalThis.__piSessionViewCache||(globalThis.__piSessionViewCache=new Map),globalThis.__piSessionViewCache}let dK=new WeakMap;function dq(e){let t,n=dK.get(e);if(void 0!==n)return n;try{t=JSON.stringify(e).length}catch{t=Number.MAX_SAFE_INTEGER}return dK.set(e,t),t}function dV(e){let t=dU().get(e);return t?Date.now()-t.savedAt>6e5?(dU().delete(e),null):(dU().delete(e),dU().set(e,t),t):null}function dZ(e){if(!e.sessionId||!e.revision)return!1;let t=dU();t.delete(e.sessionId);let n={...e,savedAt:Date.now()};return!(dq(n)>0x2000000)&&(t.set(n.sessionId,n),!function(){let e=dU();for(;e.size>8;){let t=e.keys().next().value;if(void 0===t)break;e.delete(t)}let t=0;for(let n of e.values())t+=dq(n);for(;t>0x2000000&&e.size>0;){let n=e.keys().next().value;if(void 0===n)break;let r=e.get(n);e.delete(n),r&&(t-=dq(r))}}(),dU().has(n.sessionId))}function dJ(e){dU().delete(e)}var dY=n(14755);let dG="pi-tool-preset";function dX(){try{return window.localStorage}catch{return null}}function dQ(e,t){t&&(e.tokens.input+=t.input??0,e.tokens.output+=t.output??0,e.tokens.cacheRead+=t.cacheRead??0,e.tokens.cacheWrite+=t.cacheWrite??0,e.cost+=t.cost?.total??0)}function d0(e){let t={userMessages:0,assistantMessages:0,toolCalls:0,toolResults:0,totalMessages:0,tokens:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0},cost:0};for(let n of e)"custom"!==n.role&&(t.totalMessages+=1,"user"===n.role?t.userMessages+=1:"toolResult"===n.role?(t.toolResults+=1,dQ(t,n.usage)):"assistant"===n.role&&(t.assistantMessages+=1,Array.isArray(n.content)&&(t.toolCalls+=n.content.filter(e=>"toolCall"===e.type).length),dQ(t,n.usage)));return t.tokens.total=t.tokens.input+t.tokens.output+t.tokens.cacheRead+t.tokens.cacheWrite,t}function d1(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(0)}k`:String(e)}function d2(e){return e>0?e>=.01?`$${e.toFixed(2)}`:"<$0.01":null}function d4(e){if(e<=0)return"0s";let t=Math.floor(e/1e3),n=Math.floor(t/3600),r=Math.floor(t%3600/60),i=t%60;return n>0?`${n}h ${r}m`:r>0?`${r}m ${i}s`:`${i}s`}function d8(e){if(!e||"object"!=typeof e||"image"!==e.type)return"";let t=e.source;return t&&"object"==typeof t?["url"===t.type?"url":"base64","string"==typeof t.media_type?t.media_type:"","string"==typeof t.data?t.data:"","string"==typeof t.url?t.url:""].join(":"):["base64","string"==typeof e.mimeType?e.mimeType:"","string"==typeof e.data?e.data:"",""].join(":")}function d3(e){let t,n=e.content;return"string"==typeof n?JSON.stringify({text:n,images:[]}):Array.isArray(n)?JSON.stringify({text:"string"==typeof(t=e.content)?t:Array.isArray(t)?t.map(e=>e&&"object"==typeof e&&"text"===e.type&&"string"==typeof e.text?e.text:"").filter(Boolean).join("\n"):"",images:n.map(d8).filter(Boolean)}):JSON.stringify({text:"",images:[]})}let d5=(e,t)=>`live:${e??""}:${t}`;class d6 extends Error{constructor(e,t){super(t??("ready_timeout"===e?"Timed out starting the agent session. Please try again.":"Failed to connect to the agent event stream. Please try again.")),this.status=e,this.name="AgentEventConnectionError"}}class d9{constructor(e){this.options=e,this.current=null,this.retry=null,this.retryGeneration=0,this.endedSessionId=null,this.opens=0,this.retries=0,this.lastError=null,this.lastClose=null}close(e){let t=null!==this.lastError&&!(this.lastClose&&this.lastClose.at>=this.lastError.at);(this.current||this.retry||t)&&(this.lastClose={reason:e??null,at:Date.now()}),this.stopRetrying(),this.current&&this.discard(this.current,new d6("closed"))}snapshot(){let e=this.current,t=this.retry;return{sessionId:e?.sessionId??t?.sessionId??null,state:e?e.attempt.ready?"connected":"connecting":t?"retrying":"idle",readyState:e?e.source.readyState:null,openedAt:e?.openedAt??null,connectedAt:e?.connectedAt??null,lastSeenAt:e?.lastSeenAt??null,lastHeartbeatAt:e?.lastHeartbeatAt??null,events:e?.events??0,opens:this.opens,retries:this.retries,retryDueAt:t?.dueAt??null,watchdogArmed:!!(e&&null!==e.watchdog),staleAfterMs:this.options.staleAfterMs??null,lastError:this.lastError?{...this.lastError}:null,lastClose:this.lastClose?{...this.lastClose}:null}}maintain(e){if(this.endedSessionId===e||!this.options.shouldMaintain(e))return;let t=this.retryGeneration;this.ensureConnected(e).catch(n=>{t===this.retryGeneration&&(n instanceof d6?"startup_error"===n.status?this.stopRetrying():this.scheduleRetry(e):this.options.onUnexpectedError?.(n))})}async ensureConnected(e){if(this.endedSessionId===e)throw new d6("closed");for(;;){let t=this.current;if(t&&t.sessionId===e){if(t.attempt.ready&&1===t.source.readyState)return}else t=this.open(e);if(await t.attempt.promise,this.current!==t){if(this.current?.sessionId===e)continue;throw new d6("closed")}if(1===t.source.readyState)return;this.lastClose={reason:"stuck",at:Date.now()},this.discard(t,new d6("closed"))}}open(e){let t,n,r;this.current&&(this.lastClose={reason:"replaced",at:Date.now()},this.discard(this.current,new d6("closed")));try{t=this.options.createSource(e)}catch(t){let e=t instanceof Error?t.message:String(t);throw this.lastError={reason:"error",message:e,at:Date.now()},new d6("closed",e)}this.opens+=1;let i=!1,s=new Promise((e,t)=>{n=e,r=t}),o=setTimeout(()=>{this.fail(d,new d6("ready_timeout"),"ready_timeout")},this.options.readinessTimeoutMs),l={promise:s,ready:!1,succeed(){i||(i=!0,clearTimeout(o),n())},fail(e){i||(i=!0,clearTimeout(o),r(e))}},a=Date.now(),d={sessionId:e,source:t,attempt:l,watchdog:null,openedAt:a,connectedAt:null,lastSeenAt:null,lastHeartbeatAt:null,events:0};return this.current=d,t.onmessage=t=>{let n;if(this.current===d){d.lastSeenAt=Date.now();try{n=JSON.parse(t.data)}catch{return}if("session_ended"===n.type&&n.sessionId===e){this.endedSessionId=e,this.close(),this.options.onEvent(n);return}if("heartbeat"===n.type){d.lastHeartbeatAt=d.lastSeenAt;return}if("connected"===n.type){d.connectedAt??=d.lastSeenAt,l.ready=!0,l.succeed(),this.stopRetrying();let e=this.options.staleAfterMs;e&&null===d.watchdog&&(d.watchdog=setInterval(()=>{Date.now()-(d.lastSeenAt??a)>e&&this.fail(d,new d6("closed"),"stale")},Math.max(1e3,Math.floor(e/3))))}else if("startup_error"===n.type){let e="string"==typeof n.errorMessage?n.errorMessage:void 0;this.fail(d,new d6("startup_error",e),"startup_error");return}d.events+=1,this.options.onEvent(n)}},t.onerror=()=>{this.fail(d,new d6("closed"),"error")},d}fail(e,t,n){this.current===e&&(this.lastError={reason:n,message:"startup_error"===n?t.message:null,at:Date.now()},this.discard(e,t),"startup_error"===t.status?this.stopRetrying():this.scheduleRetry(e.sessionId))}discard(e,t){null!==e.watchdog&&clearInterval(e.watchdog),e.watchdog=null,e.attempt.fail(t),e.source.close(),this.current===e&&(this.current=null)}scheduleRetry(e){if(!this.options.shouldMaintain(e)||this.retry?.sessionId===e)return;this.clearRetry();let t=setTimeout(()=>{this.retry?.timer===t&&(this.retry=null,this.retries+=1,this.maintain(e))},this.options.reconnectDelayMs);this.retry={sessionId:e,timer:t,dueAt:Date.now()+this.options.reconnectDelayMs}}stopRetrying(){this.retryGeneration+=1,this.clearRetry()}clearRetry(){this.retry&&clearTimeout(this.retry.timer),this.retry=null}}function d7(e){return!!e&&"unanswered"!==e&&!!(e.running||e.awaitingInput||e.subagentsActive)}function ce(e){return"u"<typeof document?()=>{}:(document.addEventListener("visibilitychange",e),()=>document.removeEventListener("visibilitychange",e))}let ct=()=>"hidden"===document.visibilityState,cn=()=>!1;function cr(e){return("tool_execution_start"===e.type||"tool_execution_update"===e.type||"tool_execution_end"===e.type)&&"string"==typeof e.parentToolCallId&&""!==e.parentToolCallId}function ci(e){var t;return("message_start"===e.type||"message_end"===e.type)&&"object"==typeof(t=e.message)&&null!==t&&!Array.isArray(t)&&"system"===e.message.role}function cs(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}let co=/^(?:custom-ui|extension-widget):/;function cl(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:8;return e+t>=n-r}let ca={isStreaming:!1,streamingMessage:null};function cd(e,t,n){let r=e.streamingMessage;if(!r||!Number.isInteger(t)||t<0)return e;let i=[...r.content],s=n(i[t]);return s?(i[t]=s,{isStreaming:!0,streamingMessage:{...r,content:i}}):e}function cc(){let e=ca,t=new Set;return{getState:()=>e,dispatch(n){let r=function(e,t){switch(t.type){case"start":return{isStreaming:!0,streamingMessage:null};case"resume":return{...e,isStreaming:!0};case"snapshot":{let n=dz(t.message,{includeStreamingRawInput:!0});return"assistant"===n.role?{isStreaming:!0,streamingMessage:n}:e}case"delta":var n=t.event;switch(n.type){case"text_start":return cd(e,n.contentIndex,()=>({type:"text",text:""}));case"text_delta":return cd(e,n.contentIndex,e=>e?.type==="text"?{...e,text:e.text+n.delta}:null);case"text_end":return cd(e,n.contentIndex,e=>({...e?.type==="text"?e:{},type:"text",text:n.content}));case"thinking_start":return cd(e,n.contentIndex,()=>({type:"thinking",thinking:""}));case"thinking_delta":return cd(e,n.contentIndex,e=>e?.type==="thinking"?{...e,thinking:e.thinking+n.delta}:null);case"thinking_end":return cd(e,n.contentIndex,e=>({...e?.type==="thinking"?e:{},type:"thinking",thinking:n.content}));case"toolcall_start":return cd(e,n.contentIndex,e=>e?.type==="toolCall"?{...e,toolCallId:n.id??e.toolCallId,toolName:n.toolName??e.toolName,rawInput:""}:"string"!=typeof n.toolName?null:{type:"toolCall",toolCallId:n.id??"",toolName:n.toolName,input:{},rawInput:""});case"toolcall_delta":return cd(e,n.contentIndex,e=>e?.type==="toolCall"?{...e,toolCallId:n.id||e.toolCallId,toolName:n.toolName||e.toolName,rawInput:(e.rawInput??"")+n.delta}:null);case"toolcall_end":return cd(e,n.contentIndex,()=>({type:"toolCall",toolCallId:n.toolCall.id,toolName:n.toolCall.name,input:n.toolCall.arguments}));default:return e}case"end":return ca;default:return e}}(e,n);if(r!==e)for(let n of(e=r,t))n()},subscribe:e=>(t.add(e),()=>{t.delete(e)})}}function cu(e,t){let n=e.lastIndexOf(t);return -1===n?e:[...e.slice(0,n),...e.slice(n+1)]}function cp(e,t){return e.reduce((e,n)=>"user"===n.role&&d3(n)===t?e+1:e,0)}function ch(e){return{steering:e?.steering??[],followUp:e?.followUp??[]}}function cf(e){return e&&"auto"!==e?e:null}let cm=new Map,cg=[2e3,5e3,1e4],cx=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:200,t=new Set;return n=>!t.has(n)&&(t.add(n),t.size>e&&t.delete(t.values().next().value),!0)}();function cv(e){return new Promise(t=>setTimeout(t,e))}function cb(e){let t=e.findIndex(e=>!e.exiting);return -1===t?e:e.map((e,n)=>n===t?{...e,exiting:!0}:e)}function cy(e,t){switch(t.type){case"add":if(e.visible.some(e=>e.exiting)||e.visible.length>=5)return{visible:e.visible.some(e=>e.exiting)?e.visible:cb(e.visible),pending:[...e.pending,t.notice]};return{...e,visible:[...e.visible,t.notice]};case"mark_oldest_exiting":return{...e,visible:cb(e.visible)};case"remove":return function(e,t){let n=e,r=t;for(;r.length>0&&n.length<5;){let[e,...t]=r;n=[...n,e],r=t}return r.length>0&&!n.some(e=>e.exiting)&&(n=cb(n)),{visible:n,pending:r}}(e.visible.filter(e=>e.id!==t.id),e.pending);default:return e}}function cw(e,t){return e&&"object"==typeof e?"number"!=typeof e.tokensBefore||"number"!=typeof e.estimatedTokensAfter?null:{reason:t,tokensBefore:e.tokensBefore,estimatedTokensAfter:e.estimatedTokensAfter}:null}function ck(e,t){let[n,r]=(0,i.useState)(()=>t(e.getState()));return(0,i.useLayoutEffect)(()=>{let n=()=>r(t(e.getState()));return n(),e.subscribe(n)},[e,t]),n}let cj=e=>e.isStreaming,cS=e=>!!e.streamingMessage?.content.length,cC=e=>e.streamingMessage,cN="pi-web:done-chimes";function cE(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:Date.now(),r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:function(){try{return window.localStorage}catch{return null}}();if(0===e.length)return!1;if(!r)return!0;try{let i=function(e){let t=e.getItem(cN);if(!t)return{};try{let e=JSON.parse(t);if(!e||"object"!=typeof e||Array.isArray(e))return{};let n={};for(let[t,r]of Object.entries(e))"number"==typeof r&&Number.isFinite(r)&&(n[t]=r);return n}catch{return{}}}(r),s=e.filter(e=>!("number"==typeof i[e]&&i[e]>=t));if(0===s.length)return!1;for(let e of s)i[e]=n;let o=Object.entries(i).filter(e=>{let[,t]=e;return n-t<=864e5}).sort((e,t)=>t[1]-e[1]).slice(0,200);return r.setItem(cN,JSON.stringify(Object.fromEntries(o))),!0}catch{return!0}}let c$=null,cI=null;function cM(e){let{label:t}=e,[n,s]=(0,i.useState)(()=>cI);if((0,i.useEffect)(()=>{if(cI)return;let e=!1;return(c$??=fetch("/api/app-update").then(async e=>{if(!e.ok)return null;let t=await e.json();return t.updateAvailable&&t.latestVersion&&t.releaseUrl?t:null}).then(e=>(cI=e,e)).catch(()=>(c$=null,null))).then(t=>{!e&&t&&s(t)}),()=>{e=!0}},[]),!n)return null;let o=t(n.latestVersion);return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{className:"new-session-meta-arrow","aria-hidden":"true",children:"→"}),(0,r.jsxs)("a",{className:"new-session-update",href:n.releaseUrl,target:"_blank",rel:"noopener noreferrer",title:o,"aria-label":o,children:["v",n.latestVersion,(0,r.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M7 17 17 7"}),(0,r.jsx)("path",{d:"M7 7h10v10"})]})]})]})}function cT(e){let t,{messageCount:n,toolCallCount:s,durationMs:o,cacheMisses:l,defaultExpanded:a=!1,reveal:d=!1,children:c,t:u}=e,[p,h]=(0,i.useState)(a);(0,i.useLayoutEffect)(()=>{d&&h(!0)},[d]);let f=[`${n} ${u(1===n?"chat.message":"chat.messages")}`];s>0&&f.push(`${s} ${u(1===s?"chat.toolCall":"chat.toolCalls")}`),void 0!==o&&f.push(u("chat.turnDuration",{time:ik(o)}));let m=l&&!(p||d)?(t={count:l.count,tokens:oZ(l.missedTokens),cost:oY(u,l.missedCost)},u(1===l.count?"transcriptNotice.foldCacheMiss":"transcriptNotice.foldCacheMisses",t)):void 0;return(0,r.jsxs)("div",{style:{marginBottom:14},children:[(0,r.jsxs)("button",{type:"button","aria-expanded":p||d,"aria-label":[u("chat.processDetails"),...f,...m?[m]:[]].join(" \xb7 "),onClick:()=>h(e=>!e),style:{display:"flex",alignItems:"center",gap:8,width:"auto",maxWidth:"100%",minHeight:24,padding:"2px 0",border:"none",background:"transparent",color:"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left"},title:u(p?"chat.collapseProcess":"chat.expandProcess"),children:[(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,transform:p?"rotate(90deg)":"none",transition:"transform 0.15s"},children:(0,r.jsx)("polyline",{points:"4 2.5 7.5 6 4 9.5"})}),(0,r.jsxs)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[f.join(" \xb7 "),m&&(0,r.jsx)("span",{style:{color:oJ},children:` \xb7 ${m}`})]})]}),(p||d)&&(0,r.jsx)("div",{style:{marginTop:8},children:c})]})}function cR(e){let t,{session:s,searchTarget:l,onSearchTargetHandled:d,initialScrollPosition:c,onScrollPositionChange:u,sessionRunning:p,newSessionCwd:h,newSessionDraftKey:f,newSessionContextBar:m,initialNewSessionChoices:g,onNewSessionChoicesChange:x,onAgentEnd:v,onSessionEnded:b,onToolEnd:y,onAttentionNeeded:w,onSessionCreated:k,onSessionForked:j,panel:S=!1,onSideSession:C,modelsRefreshKey:N,chatInputRef:E,onBranchDataChange:$,onSystemPromptChange:I,onSystemToolsChange:M,onSystemInfoLoaderChange:T,onDebugSnapshotReaderChange:R,onSessionStatsChange:A,onSessionStatsPanelOpen:L,onOpenSettings:z,onContextUsageChange:P,onOpenFile:W,onFilesUploaded:O,onOpenSubagent:F,quoteSelectionEnabled:D=!1,initialPrompt:B,onInitialPromptConsumed:H,soundEnabled:_=!0,onSoundToggle:U,playDoneSound:K=()=>{},unlockAudio:q,holdAudio:V}=e,{t:Z}=(0,tm.s)(),J=tC(),Y=!a(s?.relation),G=(0,i.useRef)(K);G.current=K;let X=(0,i.useRef)(_);X.current=_;let Q=(0,i.useRef)(!1),ee=(0,i.useCallback)(e=>{if(Y&&X.current&&!e.aborted&&!e.subagentsActive){let e=tt.current??s?.id;(!e||cE([e],Date.now()-3e3))&&G.current()}v?.(e)},[Y,v,s?.id]),et=(0,i.useRef)(l?null:c??null),[en,er]=(0,i.useState)(()=>{let e=et.current;return e&&!e.atBottom?e:null}),[ei,es]=(0,i.useState)(!1),{loading:eo,error:el,messages:ea,activeToolResults:ed,toolClocks:ec,entryIds:eu,messageKeys:ep,historyCursor:eh,hasEarlierMessages:ef,earlierTurnCount:em,streamingStore:eg,agentRunning:ex,bashRunning:ev,pendingBash:eb,modelNames:ey,modelList:ew,modelError:ek,missingCwd:ej,modelScopeWarnings:eS,isModelScopeActive:eC,allModelList:eN,modelThinkingLevels:eE,modelThinkingLevelMaps:e$,toolPreset:eI,thinkingLevel:eM,retryInfo:eT,contextUsage:eR,forkingEntryId:eA,isCompacting:eL,compactError:ez,compactResult:eP,displayModel:eW,modelSwitching:eO,sessionStats:eF,slashCommands:eD,slashCommandsLoading:eB,queuedMessages:eH,notices:e_,extensionDialog:eq,waitingExtensionDialogCount:eV,extensionCustomUi:eZ,waitingExtensionCustomUiCount:eY,extensionStatuses:eG,extensionWidgets:eX,respondToExtensionUi:eQ,sendExtensionCustomInput:e0,setNoticePaused:e1,addNotice:e2,isAutoModelSelection:e4,isAutoThinkingSelection:e8,defaultModel:e3,savedDefaultThinkingLevel:e5,agentPhase:e6,isNew:e9,editEntryId:e7,showScrollToBottom:te,sessionIdRef:tt,scrollContainerRef:tn,lastUserMsgRef:tr,promptAnchorActive:ti,handleSend:ts,handleAbort:to,startSideChat:tl,handleFork:ta,handleEditContent:td,cancelEdit:tc,handleModelChange:tu,handleCompact:tp,handleSteer:th,handleFollowUp:tf,handlePromptWithStreamingBehavior:tg,handleAbortCompaction:tx,dismissCompactError:tv,handleRecallQueue:tb,handleBuiltinSlashCommand:ty,handleToolPresetChange:tw,handleThinkingLevelChange:tk,handleSetDefaultModel:tj,handleSetDefaultThinkingLevel:tS,loadSlashCommands:tN,loadAllModels:tE,scrollUserMsgToTop:t$,loadContext:tM,activeLeafId:tT,scrollToBottom:tR,scrollToMessage:tA}=function(e){var t;let r,s,{session:o,newSessionCwd:l,newSessionDraftKey:a,onAgentEnd:d,onSessionEnded:c,onToolEnd:u,onAttentionNeeded:p,onSessionCreated:h,onSessionForked:f,onSideSession:m,modelsRefreshKey:g,onBranchDataChange:x,onSystemPromptChange:v,onSystemToolsChange:b,onSystemInfoLoaderChange:y,onSessionStatsPanelOpen:w,onOpenSettings:k,onDebugSnapshotReaderChange:j}=e,S=null===o&&null!==l,C=S?e.initialNewSessionChoices??null:null,[N,E]=(0,i.useState)(null),[$,I]=(0,i.useState)(!S),[M,T]=(0,i.useState)(null),[R,A]=(0,i.useState)(null),[L,z]=(0,i.useState)([]),[P,W]=(0,i.useState)(new Map),[O,F]=(0,i.useState)(oh),[D,B]=(0,i.useState)([]),[H,_]=(0,i.useState)(()=>new Map),[U,K]=(0,i.useState)(null),[q,V]=(0,i.useState)(!1),[Z,J]=(0,i.useState)(0),[Y]=(0,i.useState)(cc),G=Y.dispatch,[X,Q]=(0,i.useState)(!1),[ee,et]=(0,i.useState)(!1),[en,er]=(0,i.useState)(null),[ei,es]=(0,i.useState)({}),[eo,el]=(0,i.useState)([]),[ea,ed]=(0,i.useState)(null),[ec,eu]=(0,i.useState)(null),[ep,eh]=(0,i.useState)(null),[ef,em]=(0,i.useState)([]),[eg,ex]=(0,i.useState)(!1),[ev,eb]=(0,i.useState)(null),ey=(0,i.useRef)(null),[ew,ek]=(0,i.useState)({}),[ej,eS]=(0,i.useState)({}),[eC,eN]=(0,i.useState)(()=>C?.model??null),[eE,e$]=(0,i.useState)(null),[eI,eM]=(0,i.useState)(dY.Q8),[eT,eR]=(0,i.useState)(()=>C?.thinkingLevel??null),[eA,eL]=(0,i.useState)(null),[ez,eP]=(0,i.useState)(null),[eW,eO]=(0,i.useState)(null),[eF,eD]=(0,i.useState)(null),[eB,eH]=(0,i.useState)(null),[e_,eq]=(0,i.useState)(null),[eV,eZ]=(0,i.useState)(null),eY=(0,i.useRef)(0),eG=(0,i.useRef)(0),[eX,eQ]=(0,i.useState)(null),[e0,e1]=(0,i.useState)(null),[e2,e4]=(0,i.useState)(null),[e8,e3]=(0,i.useState)(null),[e5,e6]=(0,i.useState)(null),[e9,e7]=(0,i.useState)(!1),[te,tt]=(0,i.useState)(!1),[tn,tr]=(0,i.useState)(!0),[ti,ts]=(0,i.useState)(null),[to,tl]=(0,i.useState)(null),[ta,td]=(0,i.useState)(null),[tc,tu]=(0,i.useState)(!1),[tp,th]=(0,i.useState)(!1),[tf,tm]=(0,i.useState)([]),[tg,tx]=(0,i.useState)(!1),[tv,tb]=(0,i.useReducer)(cy,{visible:[],pending:[]}),[ty,tw]=(0,i.useState)(null),[tk,tj]=(0,i.useState)([]),[tS,tC]=(0,i.useState)([]),[tN,tE]=(0,i.useState)([]),[t$,tI]=(0,i.useState)([]),[tM,tT]=(0,i.useState)({steering:[],followUp:[]}),tR=(0,i.useRef)(null),tA=(0,i.useRef)(null),tL=(0,i.useRef)(0),tz=(0,i.useRef)(!1),tP=(0,i.useRef)(!1),[tW,tO]=(0,i.useState)(0),tF=(0,i.useRef)(null),tD=(0,i.useRef)(()=>{}),tB=(0,i.useRef)({renewStartedAt:null,inFlightSince:null,requests:0,unanswered:0,errors:0,last:null}),tH=(0,i.useRef)({count:0,lastAt:null}),t_=(0,i.useRef)({count:0,lastAt:null,lastReason:null}),tU=(0,i.useRef)(null),tK=(0,i.useRef)(null),tq=(0,i.useRef)(!1),tV=(0,i.useRef)(0),tZ=(0,i.useRef)(o?.id??null),tJ=(0,i.useRef)(null),tY=(0,i.useRef)(o?.id??null),tG=(0,i.useRef)(!1),tX=(0,i.useRef)(!1),tQ=(0,i.useRef)(!1),t0=(0,i.useRef)(!1),t1=(0,i.useRef)(-1),t2=(0,i.useRef)(!1),t4=(0,i.useRef)(0),t8=(0,i.useRef)(0),t3=(0,i.useRef)(null),t5=(0,i.useRef)(!!e.deferInitialScroll),t6=(0,i.useRef)(null),t9=(0,i.useRef)(!1),t7=(0,i.useRef)(!0),ne=(0,i.useRef)(0),nt=(0,i.useRef)(null),nn=(0,i.useRef)(void 0),nr=(0,i.useRef)(void 0),ni=(0,i.useRef)(null),ns=(0,i.useRef)(null),no=(0,i.useRef)([]),nl=(0,i.useRef)(null),na=(0,i.useRef)(0),nd=(0,i.useRef)(!1),nc=(0,i.useRef)(C?.model??null),nu=(0,i.useRef)(C?.thinkingLevel??null),np=(0,i.useRef)({}),nh=(0,i.useRef)(null),nf=(0,i.useRef)(0),nm=(0,i.useRef)(null),ng=(0,i.useRef)(null),nx=(0,i.useRef)(null),nv=(0,i.useRef)(0),nb=(0,i.useRef)(null),ny=(0,i.useCallback)(()=>{ng.current=nf.current,nx.current?.runId===nf.current&&(nx.current=null)},[]),nw=(0,i.useRef)(!1),nk=(0,i.useRef)(new Map),nj=(0,i.useRef)(!0),nS=(0,i.useRef)(new Map),nC=(0,i.useRef)(null),nN=(0,i.useRef)([]),nE=(0,i.useRef)([]),n$=(0,i.useRef)(null),nI=(0,i.useRef)(null),nM=(0,i.useRef)(!1),nT=(0,i.useRef)(0);tY.current=o?.id??null,nC.current=N,nN.current=L,nE.current=D,n$.current=R,nI.current=U,nM.current=q,nT.current=Z,tq.current=te,tV.current=tk.length+tS.length;let nR=(0,i.useCallback)(e=>nj.current&&tJ.current!==e&&tZ.current===e&&(tX.current||tz.current||tY.current===e&&!tP.current),[]);tR.current||(tR.current=new d9({createSource:e=>eJ("agent",new EventSource(`/api/agent/${encodeURIComponent(e)}/events?holder=${encodeURIComponent(eK())}`),e),onEvent:e=>t3.current?.(e),shouldMaintain:nR,readinessTimeoutMs:6e4,reconnectDelayMs:1e3,staleAfterMs:75e3,onUnexpectedError:e=>{console.error("Failed to maintain the agent event stream:",e)}}));let nA=e.setToolPreset??eM,nL=o?.id;(0,i.useLayoutEffect)(()=>{(nL||S&&!tZ.current)&&nA(function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:dX();if(!e)return dY.Q8;try{let t=e.getItem(dG);return(0,dY.sn)(t)?t:dY.Q8}catch{return dY.Q8}}())},[nL,S,nA]);let nz=e.onNewSessionChoicesChange;(0,i.useEffect)(()=>{S&&nz?.({model:eC,thinkingLevel:eT})},[S,eC,eT,nz]);let nP=(0,i.useCallback)(function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"smooth",t=ni.current;t&&(t.scrollTo({top:t.scrollHeight,behavior:e}),ne.current=t.scrollTop)},[]),nW=e2??e8??N?.context.model??e5??null,nO=S?eC??eE:nW??(N?.context.messages.length===0?eE:null),nF=cf(N?.context.thinkingLevel&&"off"!==N.context.thinkingLevel?N.context.thinkingLevel:null),nD=S?eT??eA:eW??eF??nF??(N?.context.messages.length===0?eA:null),nB=o?.id??a??void 0,nH=(0,i.useCallback)(e=>{e3(e?.model?{provider:e.model.provider,modelId:e.model.id}:null),e?.thinkingLevel!==void 0&&eD(cf(e.thinkingLevel))},[]),n_=(0,i.useCallback)(e=>{if(!e)return;let t=e,n=new Set;for(;!n.has(t);){n.add(t);let e=nk.current.get(t);if(!e)break;t=e}return t},[]),nU=(0,i.useCallback)((t,n,r)=>{let i=n?.map(e=>{let{data:t,mimeType:n}=e;return{data:t,mimeType:n}}),s=n_(r);if(!nj.current&&!nd.current&&r===a)return;let o=e.chatInputRef?.current;o?o.restoreSubmission(t,i,s):s&&lZ(s,t,i)},[a,e.chatInputRef,n_]),[nK,nq]=(0,i.useState)(()=>{let e=o?.id;return e&&!l_(e)&&cm.delete(e),e&&cm.get(e)||null}),nV=(0,i.useCallback)(e=>{o?.id&&(e?cm.set(o.id,e):cm.delete(o.id),nq(e))},[o?.id]),nZ=(0,i.useCallback)((t,n)=>{o?.id&&(e.chatInputRef?.current?.replaceMessage(t),nV(n))},[e.chatInputRef,o?.id,nV]),nJ=(0,i.useCallback)(()=>nV(null),[nV]),nY=(0,i.useMemo)(()=>{let e=N?.totalActiveMs,t=eV&&eV.sessionId===N?.sessionId?eV.value:void 0,n=void 0===e&&void 0===t?void 0:Math.max(e??0,t??0);if(ty)return{...ty,totalActiveMs:n,...e_?{contextUsage:e_}:{}};let r=N?.stats,i=function(e,t,n){let r=d0(n);if(!e)return r;let i=d0(t),s=(e,t)=>Math.max(0,e-t),o={input:e.tokens.input+s(r.tokens.input,i.tokens.input),output:e.tokens.output+s(r.tokens.output,i.tokens.output),cacheRead:e.tokens.cacheRead+s(r.tokens.cacheRead,i.tokens.cacheRead),cacheWrite:e.tokens.cacheWrite+s(r.tokens.cacheWrite,i.tokens.cacheWrite),total:0};return o.total=o.input+o.output+o.cacheRead+o.cacheWrite,{userMessages:e.userMessages+s(r.userMessages,i.userMessages),assistantMessages:e.assistantMessages+s(r.assistantMessages,i.assistantMessages),toolCalls:e.toolCalls+s(r.toolCalls,i.toolCalls),toolResults:e.toolResults+s(r.toolResults,i.toolResults),totalMessages:e.totalMessages+s(r.totalMessages,i.totalMessages),tokens:o,cost:e.cost+s(r.cost,i.cost)}}(r,N?.context.messages??[],L);return 0!==i.tokens.total||0!==L.length||r?{sessionFile:N?.filePath||void 0,sessionId:tZ.current??o?.id??"",sessionName:o?.name,...i,totalActiveMs:n,...e_?{contextUsage:e_}:{}}:null},[L,ty,e_,eV,N?.sessionId,N?.context.messages,N?.filePath,N?.totalActiveMs,N?.stats,o?.id,o?.name]),nG=(0,i.useCallback)((e,t,n,r)=>{nj.current&&tZ.current===t&&nf.current===n&&!(r<=eG.current)&&(eG.current=r,e?.contextUsage!==void 0&&eq(e.contextUsage??null),"number"==typeof e?.totalActiveMs&&eZ({sessionId:t,value:e.totalActiveMs}))},[]),nX=(0,i.useCallback)(async e=>{let t=nf.current,n=++eY.current;try{let r=await fetch(dF(e));if(!r.ok)return;let i=await r.json();nG(i.state,e,t,n)}catch{}},[nG]),nQ=(0,i.useCallback)(async function(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],n=arguments.length>2&&void 0!==arguments[2]&&arguments[2],r=arguments.length>3?arguments[3]:void 0,i=r?.force?`force:${e}`:e,s=r?.force?void 0:nS.current.get(i);if(s)return await s;let o=(async()=>{let i=!1,s=++nv.current,o=!tX.current;try{t&&I(!0);let l=new URLSearchParams({deferThinking:"1",deferMedia:"1",tree:"summary"});r?.force&&l.set("force","1");let a=await fetch(`/api/sessions/${encodeURIComponent(e)}?${l}`);if(404===a.status)return t&&(E(null),A(null),z([]),B([]),K(null),V(!1),J(0),T(null)),dJ(e),null;if(!a.ok)throw Error(`HTTP ${a.status}`);let d=await a.json();if(tZ.current!==e)return null;(nb.current?.seq??0)<s&&(nb.current={sid:e,seq:s,messages:d.context.messages,entryIds:d.context.entryIds??[]});let c=dV(e),u=!!(d.snapshotRevision&&c?.revision===d.snapshotRevision&&c.entryIds.length>=(d.context.entryIds??[]).length),p=u?nN.current:d.context.messages;if(E(u?{...d,context:{...d.context,messages:nN.current,entryIds:nE.current,oldestEntryId:nI.current,hasMore:nM.current,turnsBefore:nT.current}}:d),A(d.leafId),u)dZ({sessionId:e,revision:d.snapshotRevision,messages:nN.current,entryIds:nE.current,leafId:d.leafId,oldestEntryId:nI.current,hasMore:nM.current,turnsBefore:nT.current,summaryTree:d.tree,thinkingLevel:d.context.thinkingLevel,model:d.context.model,stats:d.stats,totalActiveMs:d.totalActiveMs,loadedEntryIds:nE.current});else{let e={messages:nN.current,entryIds:nE.current},t={messages:p,entryIds:d.context.entryIds??[]};_(n=>(function(e,t){let n=new Set(t.entryIds),r=new Map([...e.aliases].filter(e=>{let[t]=e;return n.has(t)})),i=e.entryIds.length,s=e.entryIds[i-1],o=void 0===s?0:t.entryIds.indexOf(s)+1;if(0===o&&void 0!==s)return r;for(let n=0;i+n<e.messages.length;n++){var l,a;let d=t.entryIds[o+n];if(void 0===d||(l=e.messages[i+n],a=t.messages[o+n],l.role!==a.role||("user"===l.role?d3(l)!==d3(a):"custom"===l.role?l.customType!==a.customType:l.timestamp!==a.timestamp)))break;r.set(d,d5(s,n))}return r})({...e,aliases:n},t)),z(t.messages),B(t.entryIds),K(d.context.oldestEntryId),V(d.context.hasMore),J(d.context.turnsBefore??0)}if(tG.current=void 0!==d.toolNames,nA(void 0!==d.toolNames?(0,dY.YO)(d.toolNames):dY.Q8),e4(e=>nw.current?e:null),eO(null),T(null),"summary"===d.treeFormat&&d.snapshotRevision&&dZ({sessionId:e,revision:d.snapshotRevision,messages:p,entryIds:d.context.entryIds??[],leafId:d.leafId,oldestEntryId:d.context.oldestEntryId,hasMore:d.context.hasMore,turnsBefore:d.context.turnsBefore??0,summaryTree:d.tree,thinkingLevel:d.context.thinkingLevel,model:d.context.model,stats:d.stats,totalActiveMs:d.totalActiveMs,loadedEntryIds:d.context.entryIds??[]}),d.wrapperRebuilt&&(tR.current?.close("rebuilt"),tR.current?.maintain(e)),!n&&d.context.thinkingLevel&&"off"!==d.context.thinkingLevel&&eD(cf(d.context.thinkingLevel)),i=!0,o&&s>t4.current&&er(e=>e?.result?null:e),t&&I(!1),!n)return null;try{let t=nf.current,n=++eY.current,r=await fetch(`/api/sessions/${encodeURIComponent(e)}/state`);if(!r.ok)throw Error(`HTTP ${r.status}`);let i=await r.json();if(tZ.current!==e)return null;let s=i.state;return nH(s),s?(nG(s,e,t,n),void 0!==s.systemPrompt&&eQ(s.systemPrompt??null),void 0!==s.extensionStatuses&&tE(s.extensionStatuses??[]),void 0!==s.extensionWidgets&&tI(s.extensionWidgets??[]),void 0!==s.queuedMessages&&tT(ch(s.queuedMessages)),void 0!==s.autoCompactionEnabled&&tr(s.autoCompactionEnabled??!0)):i.running||tT({steering:[],followUp:[]}),i}catch(e){return console.error("Failed to load agent state:",e),null}}catch(e){return T(String(e)),"error"}finally{t&&!i&&I(!1)}})();return nS.current.set(i,o),o.finally(()=>{nS.current.get(i)===o&&nS.current.delete(i)}),await o},[nG,nA,nH]),n0=(0,i.useCallback)(async(e,t,n,r)=>{try{let i=new URLSearchParams({deferThinking:"1",deferMedia:"1"});t&&i.set("leafId",t),n&&i.set("before",n),r?.tail&&i.set("tail",String(r.tail));let s=`/api/sessions/${encodeURIComponent(e)}/context?${i}`,o=await fetch(s,{signal:r?.signal});if(!o.ok)throw Error(`HTTP ${o.status}`);let l=await o.json();if(tZ.current!==e||r?.signal?.aborted||!nj.current)return;return K(l.context.oldestEntryId),V(l.context.hasMore),J(l.context.turnsBefore??0),E(t=>{if(!t||t.sessionId!==e)return t;let r=n?{...t.context,messages:[...l.context.messages,...t.context.messages],entryIds:[...l.context.entryIds,...t.context.entryIds],oldestEntryId:l.context.oldestEntryId,hasMore:l.context.hasMore,turnsBefore:l.context.turnsBefore}:l.context;return{...t,context:r}}),n?(z(e=>[...l.context.messages,...e]),B(e=>[...l.context.entryIds,...e])):(z(l.context.messages),B(l.context.entryIds??[])),l.context}catch(e){r?.signal?.aborted||console.error("Failed to load context:",e)}},[]),n1=(0,i.useCallback)(async e=>{try{let t=await dD(e,{type:"get_tools"});if(!t||!nj.current||tZ.current!==e)return null;let{getPresetFromTools:r}=await Promise.resolve().then(n.bind(n,14755));return nA(tG.current?r(t):dY.Q8),b?.(t),t}catch(e){return console.error("Failed to load tools:",e),null}},[b,nA]),n2=(0,i.useCallback)(function(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"(no messages)",r=tZ.current;if(S&&l&&r&&!nd.current&&(nd.current=!0,a)){if(a!==r){nk.current.set(a,r);let t=e.chatInputRef?.current;t?t.rekeyDraft(a,r):lJ(a,r)}h?.({id:r,path:"",cwd:l,name:void 0,created:new Date().toISOString(),modified:new Date().toISOString(),messageCount:t,firstMessage:n,transient:!0},a)}},[S,l,a,h,e.chatInputRef]),n4=(0,i.useCallback)((e,t,n)=>{e.model&&nc.current===t&&(e6(e.model),t||e$(e.model)),e.thinkingLevel&&nu.current===n&&(eD(cf(e.thinkingLevel)),n||eL(cf(e.thinkingLevel)))},[]),n8=(0,i.useCallback)(async()=>{if(tZ.current||!S||!l)return tZ.current;if(ns.current)return ns.current;let e=(async()=>{let e=nc.current,t=nu.current;e&&e6(e);let n=(0,dY.xG)(eI);tG.current=void 0!==n;let r=await fetch("/api/agent/new",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:l,type:"ensure_session",...void 0!==n?{toolNames:n}:{},...e?{provider:e.provider,modelId:e.modelId}:{},...t?{thinkingLevel:t}:{}})});if(!r.ok){let e=await r.json().catch(()=>null),t="string"==typeof e?.error?e.error:`HTTP ${r.status}`,n=dP(e);throw n?new dW(t,r.status,void 0,void 0,n):Error(t)}let i=await r.json(),s=i.sessionId;return tZ.current=s,n4(i,e,t),s})();ns.current=e;try{return await e}finally{ns.current=null}},[n4,S,l,eI]),n3=(0,i.useCallback)(async()=>{let e=tZ.current??await n8();if(!e)return;let[t]=await Promise.all([dD(e,{type:"get_state"}),n1(e)]);nj.current&&tZ.current===e&&(nH(t),eQ(t.systemPrompt??""))},[n8,n1,nH]),n5=(0,i.useCallback)(e=>{no.current=e,tm(e)},[]),n6=(0,i.useCallback)(()=>{na.current+=1,nl.current=null,n5([])},[n5]),n9=(0,i.useCallback)(async(e,t)=>{let n=null===tY.current&&nj.current;n&&tR.current?.ensureConnected(e).catch(()=>{});try{return await t()}finally{!n||null!==tY.current||tZ.current!==e||0!==tV.current||tX.current||t2.current||tR.current?.close("grace_end")}},[]),n7=(0,i.useCallback)(()=>{let e=++na.current,t=(async()=>{let t=tZ.current??await n8();if(!t)return na.current===e&&n5([]),[];tx(!0);try{let n=await n9(t,()=>dD(t,{type:"get_commands"})),r=n?.commands??[];return na.current===e&&n5(r),r}catch(t){return console.error("Failed to load slash commands:",t),na.current===e&&n5([]),null}finally{na.current!==e&&nl.current||tx(!1)}})();nl.current=t;let n=()=>{nl.current===t&&(nl.current=null)};return t.then(n,n),t},[n8,n5,n9]),re=(0,i.useCallback)(async()=>await n7()??[],[n7]),rt=(0,i.useCallback)(async()=>{let e=nl.current,t=no.current;return!e&&t.length>0?t:await (e??n7()).catch(()=>null)??(t.length>0?t:null)},[n7]),rn=(0,i.useCallback)(()=>{tL.current+=1,tz.current=!1,tK.current=null,tA.current&&(clearTimeout(tA.current),tA.current=null)},[]),rr=(0,i.useCallback)(e=>{tR.current?.close(e)},[]),ri=(0,i.useCallback)(e=>tR.current.ensureConnected(e),[]),rs=(0,i.useCallback)(e=>{tR.current.maintain(e)},[]);(0,i.useEffect)(()=>{let e=o?.id;if(e)return nj.current=!0,tP.current=!1,rs(e),()=>{tZ.current===e&&tR.current?.close("deselected")}},[rs,o?.id]);let ro=(0,i.useCallback)(e=>{let t=tF.current;if(t?.sid===e)return t.promise;let n=new AbortController,r=setTimeout(()=>n.abort(),5e3),i={sid:e,promise:Promise.resolve(null)};return i.promise=(async()=>{let t=null,s=null,o=Date.now();tB.current.inFlightSince=o,tB.current.requests+=1;try{let r=await fetch(`/api/agent/${encodeURIComponent(e)}/lease`,{method:"POST",cache:"no-store",signal:n.signal});return t=r.status,s=r.ok?await r.json():null}catch(e){return s=n.signal.aborted||e instanceof TypeError?"unanswered":null}finally{clearTimeout(r),tF.current===i&&(tF.current=null);try{let e=tB.current,n=Date.now(),r="unanswered"===s?"unanswered":null===s?"error":"reply";"unanswered"===r&&(e.unanswered+=1),"error"===r&&(e.errors+=1);let i="object"==typeof s&&null!==s?s:null;e.inFlightSince=null,e.last={at:n,durationMs:Math.max(0,n-o),outcome:r,httpStatus:t,reply:i&&{running:!0===i.running,awaitingInput:!0===i.awaitingInput,subagentsActive:!0===i.subagentsActive}}}catch{}}})(),tF.current=i,i.promise},[]),rl=!X&&!ee&&!te&&0===tk.length&&0===tS.length;(0,i.useEffect)(()=>{let e=o?.id;if(!e||!rl)return;let t=!1,n=null,r=()=>!t&&"hidden"===document.visibilityState&&!tP.current&&tZ.current===e&&tY.current===e&&!tX.current&&!t2.current,i=async()=>{if(n=null,tU.current=null,!r())return;let t=await ro(e);if(r()){if(!("unanswered"===t||t&&!d7(t)))return void s();tP.current=!0,tH.current={count:tH.current.count+1,lastAt:Date.now()},rr("released")}},s=()=>{null===n&&(n=setTimeout(()=>void i(),3e4),tU.current=Date.now()+3e4)},l=()=>{"hidden"===document.visibilityState?s():n&&(clearTimeout(n),n=null,tU.current=null)};return"hidden"===document.visibilityState&&s(),document.addEventListener("visibilitychange",l),()=>{t=!0,n&&clearTimeout(n),tU.current=null,document.removeEventListener("visibilitychange",l)}},[rr,rl,tW,ro,o?.id]);let ra=(0,i.useCallback)(async(e,t)=>{let n=tZ.current;if(tj(t=>dA(t,e.id)),!n)return;try{await dD(n,{type:"extension_ui_response",id:e.id,...t})}catch(e){console.error("Failed to send extension UI response:",e);return}if(null!==tY.current)return;let r=nc.current,i=nu.current;try{let e=await dD(n,{type:"get_state"});if(!nj.current||tZ.current!==n||null!==tY.current)return;n4({model:e.model?{provider:e.model.provider,modelId:e.model.id}:null,thinkingLevel:e.thinkingLevel},r,i),void 0!==e.systemPrompt&&eQ(e.systemPrompt)}catch{}},[n4]),rd=(0,i.useCallback)(async(e,t)=>{let n=tZ.current;if(n)try{await dD(n,{type:"extension_ui_input",id:e.id,data:t})}catch(e){console.error("Failed to send extension custom UI input:",e)}},[]),rc=(0,i.useCallback)(e=>{let t=e.message.trim();t&&tb({type:"add",notice:{id:e.id??("u">typeof crypto&&"function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2)}`),message:t,type:e.type??"info"}})},[]),ru=(0,i.useRef)(e.t);ru.current=e.t;let rp=(0,i.useCallback)((e,t)=>ru.current(e,t),[]),rh=(0,i.useCallback)(()=>{rc({type:"warning",message:rp("chat.sendUnconfirmed")})},[rc,rp]),rf=(0,i.useCallback)(e=>{nj.current&&z(t=>cu(t,e.bubble));let t=dV(e.sid);t?.messages.includes(e.bubble)&&dZ({...t,messages:cu(t.messages,e.bubble)})},[]),rm=(0,i.useCallback)((e,t,n)=>{let r=nx.current;if(!r||r.runId!==t||r.sid!==e)return;nx.current=null;let i=nb.current,s=i?.sid===e&&i.seq>n?i:null,o=s?null===r.lastEntryIdAtSend?0:s.entryIds.indexOf(r.lastEntryIdAtSend)+1||-1:-1;s&&o>=0&&cp(s.messages.slice(o),r.key)>r.sameTextAfterSend||(nU(r.message,r.images,r.draftKey),s&&rf(r),rc(s&&!r.command&&o===s.entryIds.length?{type:"error",message:rp("chat.sendNotReceived")}:{type:"warning",message:rp("chat.sendUnconfirmed")}))},[rc,rf,nU,rp]),rg=(0,i.useCallback)(()=>{let e=nx.current;if(nx.current=null,e){if(e.parkedDraftKey){let t=e.images?.map(e=>{let{data:t,mimeType:n}=e;return{data:t,mimeType:n}});lZ(e.parkedDraftKey,e.message,t)}else nU(e.message,e.images,e.draftKey);rf(e)}},[rf,nU]),rx=(0,i.useRef)(rg);rx.current=rg;let rv=(0,i.useCallback)(t=>{switch(dT(t)&&p?.(t),t.method){case"select":case"confirm":case"input":case"editor":tj(e=>e.some(e=>e.id===t.id)?e:[...e,t]);break;case"notify":if(t.id&&!cx(t.id))break;rc({id:t.id,message:rH(t.message),type:t.notifyType??"info"});break;case"setStatus":tE(e=>{let n=e.filter(e=>e.key!==t.statusKey);return void 0!==t.statusText?[...n,{key:t.statusKey,text:t.statusText}]:n});break;case"setWidget":tI(e=>(function(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"aboveEditor";if(void 0===n)return e.filter(e=>e.key!==t);let i={key:t,lines:n,placement:r},s=e.findIndex(e=>e.key===t);return -1===s?[...e,i]:e.map((e,t)=>t===s?i:e)})(e,t.widgetKey,t.widgetLines,t.widgetPlacement));break;case"setTitle":t.title&&(document.title=rH(t.title));break;case"set_editor_text":e.chatInputRef?.current?.setText(rH(t.text));break;case"custom":tC(e=>{let n;return t.closed?dA(e,t.id):-1===(n=e.findIndex(e=>e.id===t.id))?[...e,t]:e[n]===t?e:e.map((e,r)=>r===n?t:e)})}},[rc,p,e.chatInputRef]),rb=(0,i.useCallback)(()=>{let e=tX.current;return tX.current=!1,Q(!1),td(null),eH(null),W(new Map),F(oh),G({type:"end"}),e},[G]),ry=(0,i.useCallback)(function(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return t1.current!==e&&(t1.current=e,d?.({aborted:t,...n?{subagentsActive:n}:{}}),!0)},[d]),rw=(0,i.useCallback)(e=>{if(tY.current===e)return void rn();rn(),tz.current=!0;let t=tL.current,n=async()=>{if(t===tL.current&&tZ.current===e&&tz.current)try{let r=await fetch(dF(e));if(!r.ok)throw Error(`HTTP ${r.status}`);let i=await r.json();if(t!==tL.current||tZ.current!==e||!tz.current)return;let s=i.state;if(nH(s),i.running&&s&&(s.isStreaming||s.isPromptRunning)){tz.current=!1,tA.current=null,tK.current=null,tQ.current=!!s?.isStreaming,t0.current=!!s?.isPromptRunning,tX.current=!0,Q(!0),td(e=>dM(e,!!s?.isStreaming));return}if(i.running&&s?.isCompacting){tt(!0),tA.current=setTimeout(()=>void n(),600),tK.current=Date.now()+600;return}tz.current=!1,tA.current=null,tK.current=null,rr("grace_end")}catch{if(t!==tL.current||tZ.current!==e||!tz.current)return;tA.current=setTimeout(()=>void n(),600),tK.current=Date.now()+600}};tA.current=setTimeout(()=>void n(),3e4),tK.current=Date.now()+3e4},[rn,rr,nH]),rk=(0,i.useCallback)(async function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:tZ.current,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:nf.current;if(nf.current!==t)return;let n=nv.current;try{e&&await nQ(e)}finally{if(nf.current!==t)return;e&&rm(e,t,n);let r=t0.current,i=tQ.current;t0.current=!1,tQ.current=!1,nm.current=null;let s=rb();r?ry(t):i&&s&&d?.({aborted:!1}),e&&rw(e)}},[nQ,ry,d,rw,rb,rm]),rj=(0,i.useCallback)(async(e,t)=>{await cv(800);let n=Date.now();for(;tX.current&&Date.now()-n<2e4;){if(void 0!==t&&nf.current!==t)return;try{let n=await fetch(dF(e));if(n.ok){let r=await n.json(),i=r.state;if(nH(i),!r.running||!i||!i.isStreaming&&!i.isPromptRunning)return void await rk(e,t)}}catch{}await cv(600)}},[rk,nH]),rS=(0,i.useCallback)(async e=>{let t=t8.current+1;for(t8.current=t;t2.current&&t8.current===t&&tZ.current===e;){await cv(1e3);try{let n=await fetch(dF(e));if(!n.ok)continue;let r=await n.json();if(nH(r.state),r.state?.isBashRunning)continue;if(await nQ(e),t8.current!==t||tZ.current!==e)return;t2.current=!1,et(!1),er(null);return}catch{}}},[nQ,nH]),rC=(0,i.useCallback)(async e=>{if(!tX.current||tZ.current!==e)return;let t=nf.current,n=++eY.current;try{let r=await fetch(dF(e));if(!r.ok)return;let i=await r.json();if(tZ.current!==e||nf.current!==t)return;let s=i.state;if(nG(s,e,t,n),nH(s),tt(s?.isCompacting??!1),tr(s?.autoCompactionEnabled??!0),tT(ch(s?.queuedMessages)),i.running&&s&&(s.isStreaming||s.isPromptRunning||s.isCompacting)){tQ.current=!!s.isStreaming,t0.current=!!s.isPromptRunning;return}if(!tX.current)return;s&&(void 0!==s.extensionStatuses&&tE(s.extensionStatuses??[]),void 0!==s.extensionWidgets&&tI(s.extensionWidgets??[]),fetch(`/api/agent/${encodeURIComponent(e)}`).then(e=>e.ok?e.json():null).then(t=>{t&&nj.current&&tZ.current===e&&t.state?.systemPrompt!==void 0&&eQ(t.state.systemPrompt??null)}).catch(()=>{})),await rk(e,t)}catch{}},[nG,rk,nH]);(0,i.useEffect)(()=>{if(!X)return;let e=()=>{let e=tZ.current;e&&rC(e)},t=()=>{"visible"===document.visibilityState&&e()},n=setInterval(e,15e3);return document.addEventListener("visibilitychange",t),window.addEventListener("online",e),()=>{clearInterval(n),document.removeEventListener("visibilitychange",t),window.removeEventListener("online",e)}},[X,rC]),(0,i.useEffect)(()=>{tX.current=X},[X]);let rN=(0,i.useCallback)(e=>nj.current&&tZ.current===e&&!tX.current,[]),rE=(0,i.useRef)(null),r$=(0,i.useRef)(null),rI=(0,i.useCallback)(async e=>{var t;let n,r=new URLSearchParams({deferThinking:"1",deferMedia:"1",tail:"1"}),i=await fetch(`/api/sessions/${encodeURIComponent(e)}/context?${r}`);if(!i.ok)throw Error(`HTTP ${i.status}`);let{context:s,leafId:o}=await i.json();if(!rN(e))return;let l=nE.current.at(-1),a=nN.current.at(-1),d=void 0!==l&&nN.current.length===nE.current.length?(n=(t={messages:s.messages,entryIds:s.entryIds??[]}).entryIds.lastIndexOf(l))<0?null:{messages:t.messages.slice(n+1),entryIds:t.entryIds.slice(n+1)}:null;if(!d)return void await nQ(e);if(0===d.entryIds.length)return;if(t2.current&&d.messages.some(e=>"bashExecution"===e.role)){r$.current=e;return}nE.current=[...nE.current,...d.entryIds],nN.current=[...nN.current,...d.messages],B(e=>e.at(-1)===l?[...e,...d.entryIds]:e),z(e=>e.at(-1)===a?[...e,...d.messages]:e),o&&(rE.current={base:n$.current,lastEntryId:d.entryIds.at(-1),leafId:o});let c=dV(e);c&&dZ({...c,loadedEntryIds:[...c.loadedEntryIds,...d.entryIds]})},[rN,nQ]),rM=(0,i.useRef)(rI);rM.current=rI;let rT=(0,i.useRef)(null);rT.current??=(t={pendingReads:e=>[nS.current.get(e),nS.current.get(`force:${e}`)],read:e=>rM.current(e),wanted:rN,onError:e=>console.error("Failed to read a message sent while idle:",e)},r=!1,s=null,e=>{s=e,r||(r=!0,(async()=>{try{for(;null!==s;){let e=s;if(s=null,t.wanted(e))try{await Promise.allSettled(t.pendingReads(e)),t.wanted(e)&&await t.read(e)}catch(e){t.onError?.(e)}}}finally{r=!1}})())}),t3.current=(0,i.useCallback)(t=>{if(!tJ.current)switch(t.type){case"session_ended":{let e=tZ.current;if(!e||t.sessionId!==e)return;tJ.current=e,rn(),tR.current?.close(),dJ(e),c?.(e);return}case"connected":if(G({type:"end"}),Array.isArray(t.pendingExtensionUiIds)){let e=new Set(t.pendingExtensionUiIds);tj(t=>dR(t,e)),tC(t=>dR(t,e))}F(ox),!0===t.isStreaming&&(rn(),tQ.current=!0,tX.current=!0,Q(!0),td({kind:"waiting_model"})),tZ.current&&nX(tZ.current);break;case"agent_start":ny(),rn(),tQ.current=!0,tX.current=!0,Q(!0),td({kind:"waiting_model"}),eH(null),G({type:"start"});break;case"agent_end":if(!tX.current)break;if(td(null),eH(null),G({type:"end"}),tZ.current){let e=tZ.current,t=nf.current,n=++eY.current;nQ(e),fetch(`/api/agent/${encodeURIComponent(e)}`).then(e=>e.ok?e.json():null).then(r=>{r&&nj.current&&tZ.current===e&&nf.current===t&&(nH(r.state),nG(r.state,e,t,n),r.state?.systemPrompt!==void 0&&eQ(r.state.systemPrompt??null),r.state?.extensionStatuses!==void 0&&tE(r.state.extensionStatuses??[]),r.state?.extensionWidgets!==void 0&&tI(r.state.extensionWidgets??[]),tT(ch(r.state?.queuedMessages)))}).catch(()=>{})}break;case"agent_settled":{let e=tQ.current;if(tQ.current=!1,!e||t0.current)break;let n=tZ.current,r=rb();tt(!1),n&&(nQ(n),rw(n)),r&&d?.({aborted:!0===t.aborted,...!0===t.subagentsActive?{subagentsActive:!0}:{}});break}case"prompt_done":{ny();let e=nf.current,n=t0.current;t0.current=!1,nm.current=null;let r=ry(e,!0===t.aborted,!0===t.subagentsActive);if(!n&&!r)break;let i=tZ.current;i&&nQ(i),!tQ.current&&(rb(),i&&rw(i))}break;case"prompt_error":rc({type:"error",message:t.errorMessage??"Command failed"});break;case"extension_error":var n,r;rc({type:"error",message:(n=t.extensionPath,r=t.error??"Extension command failed","string"==typeof n&&n&&!co.test(n)?`Extension "${n}" error: ${r}`:r)});break;case"message_start":case"message_update":if(!tX.current||ci(t))break;if("message_start"===t.type){let e=t.message;if(e?.role==="user")break;e?.role==="assistant"?(G({type:"snapshot",message:e}),e.content.length>0&&td(null)):e&&td(null)}else{let e=t.assistantMessageEvent;e&&(G({type:"delta",event:e}),"toolcall_start"!==e.type&&"toolcall_delta"!==e.type&&td(null))}!t9.current&&t7.current&&null===nt.current&&(nt.current=requestAnimationFrame(()=>{nt.current=null,t7.current&&nP("auto")}));break;case"message_end":{if(!tX.current){let e=t.message;e?.role==="custom"&&!rG(e)&&tZ.current&&rT.current?.(tZ.current);break}if(ci(t))break;let e=t.message;if(e&&"user"===e.role){let t=dz(e),n=d3(t),r=nm.current;nm.current=null,r&&ny(),z(e=>{let i=e[e.length-1];return r&&i?.role==="user"&&d3(i)===r?r===n?e:[...e.slice(0,-1),t]:[...e,t]})}else if(e){let n=Array.isArray(t.transcriptNotices)?t.transcriptNotices:void 0;if(z(t=>{var r;return[...t,(r=dz(e),n&&0!==n.length?{...r,[oq]:[...n]}:r)]}),"toolResult"===e.role){let t=e.toolCallId;F(e=>og(e,t))}if("assistant"===e.role){let e=tZ.current;e&&nX(e)}}G({type:"end"}),td({kind:"waiting_model"});break}case"tool_execution_start":{if(cr(t))break;let e=t.toolCallId,n=t.toolName,r=performance.now();F(e=>om(e,t,r)),td(t=>{let r=t?.kind==="running_tools"?[...t.tools]:[];return r.some(t=>t.id===e)||r.push({id:e,name:n}),{kind:"running_tools",tools:r}});break}case"tool_execution_update":{if(cr(t))break;let e=t.toolCallId,n=t.toolName,r=t.partialResult,i=r?.content;("bash"===n||"powershell"===n||n===oR)&&Array.isArray(i)&&W(t=>{let s=new Map(t);return s.set(e,{role:"toolResult",toolCallId:e,toolName:n,content:i,isError:r?.isError,details:r?.details}),s});let s=n===oR?function(e){if(!oL(e))return null;let{calls:t}=oP(e.details),n=t.findLast(e=>"running"===e.status)??t.at(-1);if(!n)return null;let r=n.args.length>120?`${n.args.slice(0,117)}...`:n.args;return r?`${n.name} ${r}`:n.name}(t.partialResult):function(e){if(!cs(e))return null;let t=e.content;if(!Array.isArray(t))return null;let n=t.filter(e=>cs(e)&&"text"===e.type&&"string"==typeof e.text).map(e=>e.text).join("\n").split(/\r?\n/),r="";for(let e=n.length-1;e>=0&&!(r=n[e].trim());e-=1);if(!r)return null;let i=r.replace(/\s+/g," ");return i.length<=500?i:`...${i.slice(-497)}`}(t.partialResult);td(t=>{let r=t?.kind==="running_tools"?[...t.tools]:[],i=r.find(t=>t.id===e),o={id:e,name:n||i?.name||"tool",progress:s??i?.progress};return{kind:"running_tools",tools:[...r.filter(t=>t.id!==e),o]}});break}case"tool_execution_end":{if(cr(t))break;let e=t.toolCallId;u?.(t.toolName);let n=performance.now();F(e=>om(e,t,n)),W(t=>{if(!t.has(e))return t;let n=new Map(t);return n.delete(e),n}),td(t=>{if(t?.kind!=="running_tools")return t;let n=t.tools.filter(t=>t.id!==e);return 0===n.length?{kind:"waiting_model"}:{kind:"running_tools",tools:n}});break}case"queue_update":ny(),tT({steering:[...t.steering??[]],followUp:[...t.followUp??[]]});break;case"auto_retry_start":case"summarization_retry_scheduled":eH({attempt:t.attempt,maxAttempts:t.maxAttempts,errorMessage:t.errorMessage});break;case"auto_retry_end":case"summarization_retry_attempt_start":case"summarization_retry_finished":eH(null);break;case"auto_compaction_start":case"compaction_start":tt(!0),ts(null),tl(null);break;case"auto_compaction_end":case"compaction_end":tt(!1),eH(null),t.errorMessage?(ts(t.errorMessage),tl(null)):!t.aborted&&(tl(cw(t.result,t.reason??"auto")),tZ.current&&nQ(tZ.current));break;case"bash_output":{let e=t.output;if(!t2.current||"string"!=typeof e)break;er(n=>n&&!n.result&&n.command===t.command?{...n,liveOutput:e}:n);break}case"editor_paste":"string"==typeof t.text&&e.chatInputRef?.current?.pasteText(rH(t.text));break;case"extension_ui_request":rv(t);break;case"extension_ui_closed":tj(e=>dA(e,t.id))}},[rc,nG,e.chatInputRef,rn,G,rv,nQ,ny,ry,d,c,u,nX,rw,nP,rb,nH]);let rR=(0,i.useCallback)(async(e,t)=>{let n=e.trim();if(!n&&!t?.length)return;let r=!t?.length&&n.startsWith("!");if(t2.current||tX.current&&!r){t2.current&&r&&rc({type:"warning",message:rp("chat.bashAlreadyRunning")}),nU(e,t,nB);return}if(nK&&(nV(null),!await nr.current?.(nK))){nV(nK),nU(e,t,nB);return}let i=!t?.length&&n.startsWith("/");if(r){let r=n.startsWith("!!"),i=(r?n.slice(2):n.slice(1)).trim();return i?void await nn.current?.(i,r):void nU(e,t,nB)}let s=nf.current+1;rn(),t0.current=!0;let a=t?.map(e=>({type:"image",source:{type:"base64",media_type:e.mimeType,data:e.data}})),d={role:"user",content:a?.length?[...e.trim()?[{type:"text",text:e}]:[],...a]:e,timestamp:Date.now()},c=d3(d),u=nE.current,p=u.at(-1)??null,h=cp(nN.current.slice(u.length),c);z(e=>[...e,d]),nm.current=c,nf.current=s,tX.current=!0,Q(!0),td(i?{kind:"running_command"}:{kind:"waiting_model"}),G({type:"start"}),t9.current=!0,tu(!0);let f=()=>{z(e=>{let t=e.lastIndexOf(d);return -1===t?e:[...e.slice(0,t),...e.slice(t+1)]}),nm.current=null},m=t?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),g=null,x=!1;try{if(S&&l){let t=tZ.current??await ns.current,n=t??await n8();if(!n)throw Error("Unable to create a session for the prompt");g=n,eC&&(e6(eC),t&&await dD(n,{type:"set_model",provider:eC.provider,modelId:eC.modelId})),nj.current&&await ri(n).catch(e=>{if(nj.current)throw e}),x=!0;let r=await dD(n,{type:"prompt",message:e,...m?.length?{images:m}:{}});r?.queued&&f(),n2(1,e)}else if(o){g=o.id,await ri(o.id),x=!0;let t=await dD(o.id,{type:"prompt",message:e,...m?.length?{images:m}:{}});t?.queued&&f()}else throw Error("No active session for the prompt");eh(null),i&&g&&rj(g,s)}catch(n){if(console.error("Failed to send message:",n),!(!x||dO(n))&&g){ng.current!==s&&(nx.current={runId:s,sid:g,message:e,images:t,draftKey:nB,parkedDraftKey:S&&l?lD(l):null,lastEntryIdAtSend:p,sameTextAfterSend:h,bubble:d,key:c,command:i},nj.current||rg()),rj(g,s);return}if(t0.current=!1,z(e=>cu(e,d)),n instanceof dW&&n.missingCwd?eh(n.missingCwd):rc({type:"error",message:n instanceof Error?n.message:String(n)}),nU(e,t,nB),nm.current=null,g)return void rC(g);tX.current=!1,rr("send_failed"),Q(!1),td(null),G({type:"end"})}},[S,l,eC,o,n8,ri,n2,rj,rc,rg,rn,rr,nB,G,rC,nU,nK,nV,rp]);nn.current=(0,i.useCallback)(async(e,t)=>{if(t2.current)return;let n=`${t?"!!":"!"}${e}`;t2.current=!0;let r=Date.now();er({command:e,excludeFromContext:t,startedAt:r}),et(!0);let i=null;try{let s=tZ.current??o?.id??await n8();if(!s)throw Error("Unable to create a session for the shell command");await ri(s).catch(()=>{});let l=await dD(s,{type:"bash",command:e,excludeFromContext:t});tX.current&&l?(i={command:e,excludeFromContext:t,startedAt:r,result:l},t4.current=nv.current):(await nQ(s),n2(1,n))}catch(e){console.error("Failed to execute shell command:",e),e instanceof dW&&"extension_reported"===e.code||rc({type:"error",message:e instanceof Error?e.message:String(e)}),nU(n,void 0,nB)}finally{t2.current=!1,er(i),et(!1);let e=r$.current;r$.current=null,e&&rT.current?.(e)}},[rc,nB,ri,n8,nQ,n2,nU,o]);let rA=en?.result;(0,i.useEffect)(()=>{if(X||!rA)return;let e=tZ.current;e&&nQ(e,!1,!1,{force:!0})},[X,rA,nQ]);let rL=(0,i.useCallback)(t=>{let n=[...t?.steering??[],...t?.followUp??[]].join("\n\n");t?.images?.length?nU(n,t.images,nB):n&&e.chatInputRef?.current?.prependText(n)},[nB,e.chatInputRef,nU]),rz=(0,i.useCallback)(async()=>{let e=tZ.current;if(e){if(t2.current&&!tX.current){try{await dD(e,{type:"abort_bash"})}catch(e){console.error("Failed to abort bash:",e)}return}try{let t=await dD(e,{type:"abort"});t&&tT({steering:[],followUp:[]}),rL(t)}catch(e){console.error("Failed to abort:",e)}}},[rL]),rP=(0,i.useCallback)(async(e,t)=>{if(t2.current)return;let n=tZ.current;if(n){e1(e);try{let{cancelled:r,newSessionId:i}=await dD(n,{type:"fork",entryId:e})??{};!r&&i&&(t&&lU(i,t),f?.(i))}catch(e){console.error("Fork failed:",e),rc({type:"error",message:e instanceof Error?e.message:String(e)})}finally{e1(null)}}},[rc,f]),rW=(0,i.useCallback)(async e=>{if(t2.current)return!1;let t=tZ.current;if(!t)return!1;try{let n=await dD(t,{type:"navigate_tree",targetId:e});if(n?.cancelled||tZ.current!==t)return!1;return await nQ(t),tZ.current===t}catch(e){return console.error("Failed to navigate:",e),!1}},[nQ]);nr.current=rW;let rO=(0,i.useCallback)(async e=>{if(t2.current||tX.current||te)return;A(e);let t=tZ.current;t&&(await n0(t,e),e&&dD(t,{type:"navigate_tree",targetId:e}).catch(()=>{}))},[te,n0]),rF=(0,i.useCallback)(async(e,t)=>{if(S){let n={provider:e,modelId:t};nc.current=n,eN(n),e6(n),null===nu.current&&eL(cf(np.current[`${e}/${t}`])??nh.current);let r=tZ.current??await ns.current;if(!r)return;try{await dD(r,{type:"set_model",provider:e,modelId:t})}catch(e){console.error("Failed to set model:",e)}return}let n=tZ.current;if(!n||nw.current)return;nw.current=!0,e4({provider:e,modelId:t}),e7(!0);let r=tX.current||t2.current,i=async()=>{let e=await fetch(dF(n)).catch(()=>null),t=e?.ok?await e.json().catch(()=>null):null;t?.state&&nj.current&&tZ.current===n&&nH(t.state)};try{let s=await dD(n,{type:"set_model",provider:e,modelId:t});e3({provider:s.provider,modelId:s.id}),nw.current=!1,r?(e4(null),await i()):await nQ(n)}catch(e){console.error("Failed to set model:",e),nw.current=!1,e4(e2),rc({type:"error",message:`Failed to switch model: ${e instanceof Error?e.message:String(e)}`}),r?await i():await nQ(n,!1,!0)}finally{nw.current=!1,e7(!1)}},[rc,e2,S,nQ,eN,nH]),rD=(0,i.useCallback)(async e=>{let t=tZ.current;if(!t||te)return!0;tt(!0),ts(null),tl(null);try{let n=await dD(t,{type:"compact",...e?{customInstructions:e}:{}});return tl(cw(n,"manual")),await nQ(t)&&n2(),!0}catch(e){return ts(e instanceof Error?e.message:String(e)),tl(null),!1}finally{tt(!1)}},[te,nQ,n2]),rB=(0,i.useCallback)(()=>ts(null),[]),r_=(0,i.useCallback)(async e=>{let t,n=l??o?.cwd??"",r=n?`/api/models?cwd=${encodeURIComponent(n)}`:"/api/models",i=null;try{let n=await fetch(r,e?{signal:e}:void 0);if(!n.ok){let e="";try{let t=await n.json();t&&"object"==typeof t&&"error"in t&&"string"==typeof t.error&&(e=t.error),i=dP(t)}catch(e){if(e instanceof DOMException&&"AbortError"===e.name)throw e}throw Error(e||`Failed to load models (HTTP ${n.status})`)}t=await n.json(),e?.throwIfAborted()}catch(t){throw e?.aborted||t instanceof DOMException&&"AbortError"===t.name||(eu(i),ed(i?null:t instanceof Error?t.message:String(t))),t}eu(null),es(t.models),ed(t.modelError??null),em(t.modelScopeWarnings??[]),ex(!!t.isScoped),eb(null),ey.current=null,ek(t.thinkingLevels??{}),eS(t.thinkingLevelMaps??{});let s=t.modelList??[];el(s);let a=t.defaultModel?s.find(e=>e.id===t.defaultModel?.modelId&&e.provider===t.defaultModel?.provider):void 0;if(e$(a?{provider:a.provider,modelId:a.id}:null),np.current=t.thinkingLevelPins??{},nh.current=cf(t.defaultThinkingLevel),eP(cf(t.savedDefaultThinkingLevel)),S&&!tZ.current){let e=nc.current,n=e&&(0===s.length||!!t.isScoped||s.some(t=>t.provider===e.provider&&t.id===e.modelId));e&&!n&&(nc.current=null,eN(null));let r=n?e:a&&{provider:a.provider,modelId:a.id},i=r&&t.thinkingLevelPins?.[`${r.provider}/${r.modelId}`];null===nu.current&&eL(cf(i)??nh.current)}},[S,l,o?.cwd]),rU=(0,i.useCallback)(()=>{if(ey.current)return;let e={};ey.current=e;let t=l??o?.cwd??"";fetch(`/api/models?scope=all${t?`&cwd=${encodeURIComponent(t)}`:""}`).then(async t=>{if(!t.ok)throw Error(`Failed to load models (HTTP ${t.status})`);let n=await t.json();ey.current===e&&(es(e=>({...n.models,...e})),ek(e=>({...n.thinkingLevels,...e})),eS(e=>({...n.thinkingLevelMaps,...e})),eb(n.modelList??[]))}).catch(t=>{ey.current===e&&(ey.current=null,rc({type:"error",message:t instanceof Error?t.message:String(t)}))})},[rc,l,o?.cwd]);(0,i.useEffect)(()=>{!eg||!nO||ev||eo.some(e=>e.provider===nO.provider&&e.id===nO.modelId)||rU()},[ev,nO,eg,rU,eo]);let rK=(0,i.useCallback)(async e=>{let t=l??o?.cwd,n=await fetch("/api/models/default",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({...t?{cwd:t}:{},...e})});if(n.ok)return;let r="";try{let e=await n.json();e&&"object"==typeof e&&"error"in e&&"string"==typeof e.error&&(r=e.error)}catch{}throw Error(r||`HTTP ${n.status}`)},[l,o?.cwd]),rq=(0,i.useCallback)(()=>{r_().catch(()=>{})},[r_]),rV=(0,i.useCallback)(async(e,t)=>{try{await rK({provider:e,modelId:t})}catch(e){rc({type:"error",message:`Failed to save default model: ${e instanceof Error?e.message:String(e)}`});return}rc({type:"success",message:`Default model: ${e}/${t}`}),e$({provider:e,modelId:t}),(nO?.provider!==e||nO?.modelId!==t)&&await rF(e,t),rq()},[rc,nO,rF,rq,rK]),rZ=(0,i.useCallback)(async(t,n)=>{let r=e.session?.relation?.kind;if("side"===r||"subagent"===r)return rp(dB[r]);let i=tZ.current;if(!i)return rp("sideChat.error.noSession");let s=await dH(i,rp,n);return"error"in s?s.error:(m?.(s.session,t),null)},[m,e.session?.relation?.kind,rp]),rJ=(0,i.useCallback)(async t=>{if(!t.startsWith("/"))return{handled:!1};let n=t.match(/^\/([^\s]+)(?:\s+([\s\S]*))?$/);if(!n)return{handled:!1};let[,r,i=""]=n,s=i.trim(),o=tZ.current??await n8(),l=e=>(e.handled&&(e.error?rc({type:"error",message:e.error}):e.action||rc({type:"success",message:e.message??"Command completed"})),e);try{switch(r){case"compact":if(!o||te)return l({handled:!0,error:"No active session to compact"});return rD(s||void 0).then(t=>{!t&&s&&e.chatInputRef?.current?.prependText(`/compact ${s}`)}),l({handled:!0,action:"compact"});case"auto-compact":{if(!o)return l({handled:!0,error:"No active session"});let e=await dD(o,{type:"get_state"}),t=!(e?.autoCompactionEnabled??!0);return await dD(o,{type:"set_auto_compaction",enabled:t}),tr(t),l({handled:!0,message:t?"Auto-compaction enabled":"Auto-compaction disabled"})}case"reload":if(!o)return l({handled:!0,error:"No active session to reload"});return await dD(o,{type:"reload"}),await Promise.all([nQ(o,!1,!0),n1(o),re(),r_()]),l({handled:!0,message:"Reloaded session resources"});case"name":if(!o)return l({handled:!0,error:"No active session to name"});if(!s)return l({handled:!0,error:"Usage: /name <name>"});return await dD(o,{type:"set_session_name",name:s}),await nQ(o)&&n2(),l({handled:!0,message:`Session renamed to ${s}`});case"session":{if(!o)return l({handled:!0,error:"No active session"});if(!w)return l({handled:!0,message:function(e,t){if(!e)return t("session.noUsage");let n=d2(e.cost);return[t(1===e.totalMessages?"session.usageSummaryOne":"session.usageSummary",{messages:e.totalMessages,tokens:d1(e.tokens.total)}),...n?[n]:[]].join(" \xb7 ")}(nY,rp)});let e=await dD(o,{type:"get_session_stats"});return e&&tw(e),w(),l({handled:!0,action:"openSessionStats"})}case"mcp":{if(s||!k)return{handled:!1};let e=await rt();if(!e||!(e.some(l1)||!e.some(e=>"mcp"===e.name)))return{handled:!1};return k("mcp"),l({handled:!0,action:"openSettings"})}case"copy":{if(!o)return l({handled:!0,error:"No active session"});let e=await dD(o,{type:"get_last_assistant_text"}),t=e?.text??"";if(!t)return l({handled:!0,error:"No assistant message to copy"});return await iN(t),l({handled:!0,message:"Copied last assistant message"})}case"clone":{if(!o)return l({handled:!0,error:"No active session to clone"});if(tX.current||t2.current)return l({handled:!0,error:"Cannot clone while the session is running"});let e=rE.current,t=await dD(o,{type:"clone",leafId:e?.base===R&&e.lastEntryId===nE.current.at(-1)?e.leafId:R});if(t?.cancelled&&t.byExtension)return{handled:!0};if(t?.cancelled||!t?.newSessionId)return l({handled:!0,error:"Cannot clone an empty or unsaved session"});let n=l({handled:!0,message:"Cloned current session branch"});return f?.(t.newSessionId),n}case"side":{let e=await rZ(s||null);return l(e?{handled:!0,error:e}:{handled:!0,action:"openSideChat"})}default:return{handled:!1}}}catch(e){return l({handled:!0,error:e instanceof Error?e.message:String(e)})}},[R,rc,n8,rD,te,r_,nQ,re,n1,n2,k,f,w,e.chatInputRef,nY,rt,rZ,rp]),rY=(0,i.useCallback)(async(e,t,n)=>{let r=tZ.current;if(nK)return void nU(e,n,nB);if(!r){nU(e,n,nB),rc({type:"error",message:"No active session for the queued message"});return}let i=n?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType}));try{await dD(r,{type:"prompt",message:e,streamingBehavior:t,...i?.length?{images:i}:{}})}catch(t){if(console.error("Failed to submit streaming prompt:",t),nU(e,n,nB),t instanceof dW&&t.missingCwd)return void eh(t.missingCwd);dO(t)?rc({type:"error",message:t.message}):rh()}},[rc,rh,nB,nK,nU]),rX=(0,i.useCallback)(async(e,t)=>{await rY(e,"steer",t)},[rY]),rQ=(0,i.useCallback)(async(e,t,n)=>{await rY(e,t,n)},[rY]),r0=(0,i.useCallback)(async(e,t)=>{await rY(e,"followUp",t)},[rY]),r1=(0,i.useCallback)(async()=>{let e=tZ.current;if(e)try{await dD(e,{type:"abort_compaction"})}catch(e){console.error("Failed to abort compaction:",e)}},[]),r2=(0,i.useCallback)(async()=>{let e=tZ.current;if(e)try{let t=await dD(e,{type:"clear_queue"});tT({steering:[],followUp:[]}),rL(t)}catch(e){console.error("Failed to recall queued messages:",e),rc({type:"error",message:"Failed to recall queued messages"})}},[rc,rL]),r4=(0,i.useCallback)(async e=>{if("auto"===e){nu.current=null,eR(null),eO(null);return}S?(nu.current=e,eR(e)):eO(e);let t=tZ.current??await ns.current;if(t)try{await dD(t,{type:"set_thinking_level",level:e}),nj.current&&tZ.current===t&&(eD(e),eO(null))}catch(e){console.error("Failed to set thinking level:",e),eO(null)}},[S]),r8=(0,i.useCallback)(async e=>{try{await rK({thinkingLevel:e})}catch(e){rc({type:"error",message:`Failed to save default reasoning level: ${e instanceof Error?e.message:String(e)}`});return}rc({type:"success",message:`Default reasoning level: ${e}`}),eP(e),nD!==e&&await r4(e),rq()},[rc,nD,r4,rq,rK]),r3=(0,i.useCallback)(async e=>{let t=(0,dY.xG)(e);!function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:dX();if(t)try{t.setItem(dG,e)}catch{}}(e),nA(e);let n=tZ.current??await ns.current;if(!n){tG.current=void 0!==t;return}try{let e=await dD(n,{type:"set_tools",...void 0!==t?{toolNames:t}:{}});tG.current=void 0!==t;let r=e?.sessionId??n;(r!==n||e?.recreated)&&(rn(),rr("set_tools"),tj([]),tC([]),tZ.current=r,e?.recreated&&tY.current===r&&rs(r)),n6(),tE([]),tI([]);let[i]=await Promise.all([dD(r,{type:"get_state"}),n1(r)]);nj.current&&tZ.current===r&&(eQ(i.systemPrompt??""),nH(i))}catch(e){console.error("Failed to set tools:",e)}},[rn,n6,rr,n1,rs,nA,nH]),r5=(0,i.useCallback)(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:16,n=ni.current;n&&(null!==nt.current&&(cancelAnimationFrame(nt.current),nt.current=null),t5.current=!0,t9.current=!1,t7.current=!1,tu(!1),n.scrollTo({top:e.getBoundingClientRect().top-n.getBoundingClientRect().top+n.scrollTop-t,behavior:"instant"}),ne.current=n.scrollTop)},[]),r6=(0,i.useCallback)(()=>{let e=ni.current,t=t6.current;if(!e||!t)return;let n=Math.min(Math.max(0,t.getBoundingClientRect().top-e.getBoundingClientRect().top+e.scrollTop-16),Math.max(0,e.scrollHeight-e.clientHeight));null!==nt.current&&(cancelAnimationFrame(nt.current),nt.current=null),t7.current=!0,ne.current=n,e.scrollTo({top:n,behavior:"auto"})},[]),r9=(0,i.useCallback)(()=>{let e=ni.current;if(e){let{scrollTop:t,clientHeight:n,scrollHeight:r}=e,i=tX.current,s=t7.current,o=function(e,t,n,r,i){let s=arguments.length>5&&void 0!==arguments[5]?arguments[5]:96;return!!cl(n,r,i)||!(n<t)&&(!!(!e&&n>t&&cl(n,r,i,s))||e)}(s,ne.current,t,n,r,i?96:8);t7.current=o,ne.current=t;let l=function(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:8;return!(n<=t)&&!cl(e,t,n,r)}(t,n,r);th(e=>e===l?e:l),!s&&o&&i?nP("auto"):o||null===nt.current||(cancelAnimationFrame(nt.current),nt.current=null)}},[nP]),r7=(0,i.useCallback)((e,t)=>{t?.running&&(n1(e),(t.state?.isStreaming||t.state?.isPromptRunning)&&(tQ.current=!!t.state.isStreaming,t0.current=!!t.state.isPromptRunning,tX.current=!0,Q(!0),td(e=>dM(e,t.state?.isStreaming===!0)),G({type:"resume"}),!t.state.isStreaming&&t.state.isPromptRunning&&rj(e)),t.state?.isBashRunning&&(t2.current=!0,et(!0),rS(e))),t?.state&&(void 0!==t.state.isCompacting&&tt(t.state.isCompacting),void 0!==t.state.systemPrompt&&eQ(t.state.systemPrompt??null),void 0!==t.state.extensionStatuses&&tE(t.state.extensionStatuses??[]),void 0!==t.state.extensionWidgets&&tI(t.state.extensionWidgets??[]),void 0!==t.state.queuedMessages&&tT(ch(t.state.queuedMessages)))},[G,n1,rS,rj]);tD.current=(e,t)=>{!tP.current||tJ.current===e||(tP.current=!1,t_.current={count:t_.current.count+1,lastAt:Date.now(),lastReason:t},tO(e=>e+1),nj.current&&tZ.current===e&&tY.current===e&&(rs(e),nQ(e,!1,!0).then(t=>{nj.current&&tZ.current===e&&r7(e,t)})))},(0,i.useEffect)(()=>{let e=o?.id;if(!e)return;let t=!1,n=tB.current,r=async()=>{let n=await ro(e);!t&&"hidden"===document.visibilityState&&d7(n)&&tD.current(e,"activity")};r();let i=setInterval(()=>void r(),3e4);n.renewStartedAt=Date.now();let s=()=>{"visible"===document.visibilityState&&(tD.current(e,"visible"),r())};return document.addEventListener("visibilitychange",s),()=>{t=!0,clearInterval(i),n.renewStartedAt=null,document.removeEventListener("visibilitychange",s)}},[ro,o?.id]),(0,i.useEffect)(()=>{if(nj.current=!0,eG.current=eY.current,o){tZ.current=o.id;let e=dV(o.id);e&&(E({sessionId:o.id,filePath:"",totalActiveMs:e.totalActiveMs??0,tree:e.summaryTree,leafId:e.leafId,context:{messages:e.messages,entryIds:e.entryIds,oldestEntryId:e.oldestEntryId,hasMore:e.hasMore,turnsBefore:e.turnsBefore,thinkingLevel:e.thinkingLevel,model:e.model},stats:e.stats}),A(e.leafId),z(e.messages),B(e.entryIds),K(e.oldestEntryId),V(e.hasMore),J(e.turnsBefore),T(null),I(!1)),nQ(o.id,!e,!0,{force:!0}).then(e=>{r7(o.id,e)})}return()=>{nj.current=!1;let e=S?a:null;e&&queueMicrotask(()=>{nj.current||nd.current||lK(e)});let t=tZ.current,n=nC.current;if(t&&n&&n.sessionId===t&&n.snapshotRevision){let e=dV(t),r=nE.current;!e||function(e,t){if(0===t.length)return!0;let n=new Set([...e.entryIds,...e.loadedEntryIds]);return t.every(e=>n.has(e))}(e,r)?dZ({sessionId:t,revision:n.snapshotRevision,messages:nN.current,entryIds:nE.current,leafId:n$.current,oldestEntryId:nI.current,hasMore:nM.current,turnsBefore:nT.current,summaryTree:n.tree,thinkingLevel:n.context.thinkingLevel,model:n.context.model,stats:n.stats,totalActiveMs:n.totalActiveMs,loadedEntryIds:nE.current}):dJ(t)}rx.current(),null!==nt.current&&(cancelAnimationFrame(nt.current),nt.current=null),t8.current+=1,rn(),rr()}},[]),(0,i.useEffect)(()=>{v?.(eX)},[eX,v]),(0,i.useEffect)(()=>(y?.(n3),()=>y?.(null)),[n3,y]);let ie=(0,i.useCallback)(()=>{let e,t=null;try{t=tR.current?.snapshot?.()??null}catch{t=null}let n=tZ.current,r=tB.current,i=t_.current;return{pageId:"string"==typeof(e=globalThis[eU])?e:null,sessionId:n,selectedSessionId:tY.current,mounted:nj.current,wantsStream:null!==n&&nR(n),connection:t,released:{active:tP.current,...tH.current},reattached:{...i},hiddenReleaseDueAt:tU.current,hiddenGraceMs:3e4,graceDueAt:tK.current,run:{agentRunning:tX.current,bashRunning:t2.current,compacting:tq.current,dialogs:tV.current},lease:{renewIntervalMs:3e4,renewStartedAt:r.renewStartedAt,inFlightSince:r.inFlightSince,requests:r.requests,unanswered:r.unanswered,errors:r.errors,last:r.last&&{...r.last,reply:r.last.reply&&{...r.last.reply}}}}},[nR]);(0,i.useEffect)(()=>(j?.(ie),()=>j?.(null)),[ie,j]);let it=X||ee||te;(0,i.useEffect)(()=>{x&&x(N?.tree??[],R,rO,it)},[N?.tree,R,rO,it,x]),(0,i.useEffect)(()=>{let e=ni.current;if(e)return ne.current=e.scrollTop,e.addEventListener("scroll",r9,{passive:!0}),()=>{e.removeEventListener("scroll",r9)}},[L.length,$,r9]),(0,i.useEffect)(()=>{X||tu(!1)},[X]),(0,i.useLayoutEffect)(()=>{L.length>0&&(t9.current?(t9.current=!1,t5.current=!0,r6()):t5.current?!tX.current&&t7.current&&nP("auto"):(t5.current=!0,nP("instant")))},[L.length,X,nP,r6]),(0,i.useEffect)(()=>{let e=new AbortController;return(async()=>{for(let t=0;;t++)try{await r_(e.signal);return}catch(n){if(e.signal.aborted||n instanceof DOMException&&"AbortError"===n.name||t>=cg.length||(await cv(cg[t]),e.signal.aborted))return}})(),()=>e.abort()},[r_,g]),(0,i.useEffect)(()=>{if(!to)return;let e=setTimeout(()=>tl(null),6e3);return()=>clearTimeout(e)},[to]);let[ir,ii]=(0,i.useState)(null),is=(0,i.useRef)(5e3),io=(0,i.useRef)(null),il=(0,i.useRef)(null);(0,i.useEffect)(()=>{if(0===tv.visible.length){il.current=null;return}let e=tv.visible.find(e=>e.exiting);if(e){let t=setTimeout(()=>{tb({type:"remove",id:e.id})},180);return()=>clearTimeout(t)}let t=tv.visible[0];if(!t||(il.current!==t.id&&(il.current=t.id,is.current=5e3),tv.visible.some(e=>e.id===ir)))return;io.current=Date.now();let n=setTimeout(()=>{tb({type:"mark_oldest_exiting"})},is.current);return()=>{clearTimeout(n),null!==io.current&&(is.current=Math.max(0,is.current-(Date.now()-io.current)),io.current=null)}},[tv.visible,ir]),(0,i.useEffect)(()=>{tw(null)},[L.length,e_?.tokens,e_?.percent,e_?.contextWindow]);let ia=nD??"auto",id=tk[0]??null,ic=Math.max(0,tk.length-1),iu=tS[0]??null,ip=Math.max(0,tS.length-1),ih=(0,i.useMemo)(()=>(function(e,t,n){let r=e[e.length-1],i=[];for(let s=0;s<t;s++){let t=e[s];i.push(void 0===t?d5(r,s-e.length):n.get(t)??t)}return i})(D,L.length,H),[D,L.length,H]);return{data:N,loading:$,error:M,activeLeafId:R,messages:L,activeToolResults:P,toolClocks:O,entryIds:D,messageKeys:ih,historyCursor:U,hasEarlierMessages:q,earlierTurnCount:Z,streamingStore:Y,agentRunning:X,modelNames:ei,modelList:eo,modelError:ea,missingCwd:ep??ec,modelScopeWarnings:ef,isModelScopeActive:eg,allModelList:ev,modelThinkingLevels:ew,modelThinkingLevelMaps:ej,newSessionModel:eC,toolPreset:eI,thinkingLevel:ia,retryInfo:eB,contextUsage:e_,systemPrompt:eX,forkingEntryId:e0,isCompacting:te,compactError:ti,compactResult:to,currentModel:nW,displayModel:nO,modelSwitching:e9,sessionStats:nY,autoCompactionEnabled:tn,slashCommands:tf,slashCommandsLoading:tg,queuedMessages:tM,notices:tv.visible,extensionDialog:id,waitingExtensionDialogCount:ic,extensionCustomUi:iu,waitingExtensionCustomUiCount:ip,extensionStatuses:tN,extensionWidgets:t$,respondToExtensionUi:ra,sendExtensionCustomInput:rd,isAutoModelSelection:S&&null===eC,isAutoThinkingSelection:S&&null===eT,defaultModel:eE,savedDefaultThinkingLevel:ez,agentPhase:ta,isNew:S,editEntryId:nK,promptAnchorActive:tc,showScrollToBottom:tp,sessionIdRef:tZ,scrollContainerRef:ni,lastUserMsgRef:t6,pendingScrollToUserRef:t9,initialScrollDoneRef:t5,handleSend:rR,handleAbort:rz,startSideChat:rZ,handleFork:rP,handleNavigate:rW,handleModelChange:rF,handleCompact:rD,handleSteer:rX,handleFollowUp:r0,handlePromptWithStreamingBehavior:rQ,handleAbortCompaction:r1,dismissCompactError:rB,handleRecallQueue:r2,handleBuiltinSlashCommand:rJ,handleEditContent:nZ,cancelEdit:nK?nJ:void 0,addNotice:rc,setNoticePaused:ii,handleToolPresetChange:r3,handleThinkingLevelChange:r4,handleSetDefaultModel:rV,handleSetDefaultThinkingLevel:r8,loadTools:n1,loadSlashCommands:re,loadAllModels:rU,setActiveLeafId:A,setData:E,setMessages:z,loadContext:n0,scrollToBottom:nP,scrollUserMsgToTop:r6,scrollToMessage:r5,dispatch:G,setAgentRunning:Q,setForkingEntryId:e1,bashRunning:ee,pendingBash:en,handleAgentEventRef:t3}}({session:s,sessionRunning:p,newSessionCwd:h,newSessionDraftKey:f,initialNewSessionChoices:g,onNewSessionChoicesChange:x,onAgentEnd:ee,onSessionEnded:b,onToolEnd:y,onAttentionNeeded:w,onSessionCreated:k,onSessionForked:j,onSideSession:C,modelsRefreshKey:N,chatInputRef:E,onBranchDataChange:$,onSystemPromptChange:I,onSystemToolsChange:M,onSystemInfoLoaderChange:T,onSessionStatsPanelOpen:L,onOpenSettings:z,onDebugSnapshotReaderChange:R,t:Z,deferInitialScroll:!!en}),tL=ck(eg,cj),tP=ck(eg,cS),tW=(0,i.useCallback)(()=>eg.getState().streamingMessage,[eg]),tO=ex||ev,tF=(0,i.useCallback)((e,t)=>{ta(e,{value:a7(t),images:de(t)})},[ta]);(0,i.useEffect)(()=>{if(ex&&V)return V()},[ex,V]);let[tD,tB]=(0,i.useState)(null),[tH,t_]=(0,i.useState)(!1),[tU,tK]=(0,i.useState)(!1),[tq,tV]=(0,i.useState)(null),tZ=(0,i.useRef)(null),tJ=(0,i.useRef)(null),tY=(0,i.useCallback)(()=>{tB(null),t_(!1),tV(null)},[]);(0,i.useEffect)(()=>{D||tY()},[D,tY]);let tG=(0,i.useCallback)(()=>{if(!D||tH)return;let e=window.getSelection(),t=e?.rangeCount?e.getRangeAt(0):null,n=t5.current;if(!e||e.isCollapsed||!t||!n||!n.contains(t.commonAncestorContainer))return void tB(null);let r=e.toString().trim();if(!r)return void tB(null);let i=t.getBoundingClientRect();tB({text:r,top:Math.min(window.innerHeight-44,i.bottom+8),left:Math.max(64,Math.min(window.innerWidth-64,i.left+i.width/2))})},[D,tH]);(0,i.useEffect)(()=>{tH&&tD&&tJ.current?.insertIfEmpty(ij(tD.text))},[tH,tD]),(0,i.useLayoutEffect)(()=>{let e=tZ.current;if(!e||!tD)return;let t=window.visualViewport,n=()=>{let n=e.getBoundingClientRect(),r=t?.offsetTop??0,i=t?.offsetLeft??0;e.style.top=`${Math.max(r+8,Math.min(tD.top,r+(t?.height??window.innerHeight)-n.height-8))}px`,e.style.left=`${Math.max(i+8,Math.min(tD.left-n.width/2,i+(t?.width??window.innerWidth)-n.width-8))}px`};n();let r=new ResizeObserver(n);return r.observe(e),window.addEventListener("resize",n),t?.addEventListener("resize",n),t?.addEventListener("scroll",n),()=>{r.disconnect(),window.removeEventListener("resize",n),t?.removeEventListener("resize",n),t?.removeEventListener("scroll",n)}},[tD,tH,tq]),(0,i.useEffect)(()=>{if(!tD)return;let e=e=>{tH||tZ.current?.contains(e.target)||tY()},t=e=>{"Escape"===e.key&&!e.isComposing&&(e.preventDefault(),e.stopPropagation(),tU||tY())};return document.addEventListener("pointerdown",e),document.addEventListener("keydown",t),()=>{document.removeEventListener("pointerdown",e),document.removeEventListener("keydown",t)}},[tD,tH,tU,tY]);let tX=(0,i.useCallback)(()=>{tD&&(E?.current?.insertQuote(ij(tD.text)),tY())},[E,tD,tY]),tQ=(0,i.useCallback)(async e=>{if(!tU&&e.trim()&&tD){tK(!0),tV(null);try{let t=await tl(e,tD.text);if(!t)return void tY();tJ.current?.restoreSubmission(e),tV(t)}catch(t){tJ.current?.restoreSubmission(e),tV(t instanceof Error?t.message:String(t))}finally{tK(!1)}}},[tD,tU,tY,tl]),t0=(0,i.useCallback)(async e=>{let t;try{t=await tl(e)}catch(e){t=e instanceof Error?e.message:String(e)}t&&(E?.current?.restoreSubmission(e),e2({type:"error",message:t}))},[e2,E,tl]),t1=(0,i.useRef)(!1);(0,i.useEffect)(()=>{eo||el||!B||t1.current||(t1.current=!0,H?.(),ts(B))},[B,eo,el,ts,H]),(0,i.useEffect)(()=>{let e=!!eq&&!Q.current;Q.current=!!eq,Y&&e&&G.current()},[Y,eq]),(0,i.useEffect)(()=>{S||(o=tO?to:null)},[S,tO,to]);let[t2,t4]=(0,i.useState)(50),[t8,t3]=(0,i.useState)(null),t5=(0,i.useRef)(null),t6=(0,i.useRef)(null),ne=(0,i.useRef)(!1),nr=(0,i.useRef)(!1),ni=(0,i.useRef)(en);ni.current=en;let[ns,no]=(0,i.useState)(null),nl=ea[eu.indexOf(ns?.entryId??"")],na=nl?.role==="assistant"?ns?.blockIndex===void 0?nl.content.find(e=>"text"===e.type):nl.content[ns.blockIndex]:void 0,nd=(0,i.useRef)({entryIds:eu,historyCursor:eh,hasEarlierMessages:ef});nd.current={entryIds:eu,historyCursor:eh,hasEarlierMessages:ef};let nc=(0,i.useRef)(null),nu=(0,i.useCallback)(async(e,t,n)=>{nc.current=t;let r=await tM(e,tT,t,n);return r||nc.current!==t||(nc.current=null),r},[tT,tM]);(0,i.useEffect)(()=>{eh!==nc.current&&(nc.current=null)},[eh]),(0,i.useLayoutEffect)(()=>{let e=s?.id,t=tn.current,n=t5.current;if(e&&u&&t&&n)return()=>{if(ni.current)return;if(cl(t.scrollTop,t.clientHeight,t.scrollHeight))return void u(e,{atBottom:!0});let r=t.getBoundingClientRect().top,i=function(e,t){let n=e[0];for(let r of e){if(r.top>t)break;n=r}return n?{anchorEntryId:n.entryId,anchorOffset:n.top-t}:null}(Array.from(n.children).flatMap(e=>{if(!(e instanceof HTMLElement)||!e.dataset.entryId)return[];let t=e.getBoundingClientRect();return[{entryId:e.dataset.entryId,top:t.top,bottom:t.bottom}]}),r);i&&u(e,{atBottom:!1,...i,oldestEntryId:nd.current.historyCursor})}},[eo,u,tn,s?.id]),(0,i.useEffect)(()=>{l&&er(null)},[l]),(0,i.useEffect)(()=>{let e=s?.id;if(!en||!e||eo||l||nr.current)return;nr.current=!0;let t=new AbortController;return(async()=>{let n=nd.current;if(n.entryIds.includes(en.anchorEntryId)){t4(e=>Math.max(e,2*n.entryIds.length)),es(!0);return}ne.current=!0;let r=n.historyCursor,i=n.hasEarlierMessages;try{for(;i&&r&&!t.signal.aborted;){let n=await nu(e,r,{signal:t.signal});if(t.signal.aborted)return;if(!n){tR("instant"),er(null);return}if(t4(e=>e+Math.max(50,2*n.messages.length)),n.entryIds.includes(en.anchorEntryId))return void es(!0);if(n.oldestEntryId===en.oldestEntryId)break;r=n.oldestEntryId,i=n.hasMore}t.signal.aborted||(tR("instant"),er(null))}finally{ne.current=!1}})(),()=>{t.abort(),er(null)}},[tT,nu,eo,en,tR,l,s?.id]),(0,i.useLayoutEffect)(()=>{let e=t5.current;if(!en||!e||l)return;let t=Array.from(e.children).find(e=>e instanceof HTMLElement&&e.dataset.entryId===en.anchorEntryId);if(t instanceof HTMLElement){tA(t,en.anchorOffset),er(null);return}ei&&(tR("instant"),er(null))},[eu,en,ei,tR,tA,l,t2]),(0,i.useEffect)(()=>{if(!l||eo)return;let e=new AbortController;return(async()=>{let t=nd.current,n=t.entryIds.includes(l.entryId);if(!n&&!tO&&t.hasEarlierMessages&&t.historyCursor&&!ne.current){ne.current=!0;let r=tn.current;r&&(t6.current=r.scrollHeight-r.scrollTop);let i=await nu(l.sessionId,t.historyCursor,{tail:200,signal:e.signal});ne.current=!1,n=!!i?.entryIds.includes(l.entryId)}e.signal.aborted||(n?(t6.current=null,t4(e=>Math.max(e,(nd.current.entryIds.length+200)*2)),no(l)):d?.(l))})(),()=>e.abort()},[l,eo,tO,nu,d,tn]),(0,i.useLayoutEffect)(()=>{if(!ns||ns!==l)return;let e=`[data-entry-id="${CSS.escape(ns.entryId)}"]`,t=tn.current?.querySelector(nl?.role==="user"?e:`${e} [data-search-target]`);t&&(tA(t),t.animate([{backgroundColor:"var(--bg-selected)"},{backgroundColor:"transparent"}],{duration:2500})),no(null),d?.(ns)},[ns,l,nl,tn,tA,d]),(0,i.useEffect)(()=>{let e=tn.current;if(!t8||!e)return;let t=new IntersectionObserver(t=>{if(!t[0]?.isIntersecting||ne.current)return;if(!ef){t6.current=e.scrollHeight-e.scrollTop,t4(e=>(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:50;return e+t})(e));return}if(!eh||eh===nc.current)return;let n=s?.id??tt.current;n&&(ne.current=!0,t6.current=e.scrollHeight-e.scrollTop,nu(n,eh).finally(()=>{ne.current=!1}))},{root:e,threshold:0});return t.observe(t8),()=>t.disconnect()},[t8,t2,eh,ef,s,nu,tt,tn]),(0,i.useEffect)(()=>{t4(e=>Math.max(e,ea.length))},[ea.length]),(0,i.useEffect)(()=>{if(null==t6.current)return;let e=tn.current;if(e){var t;t=e.scrollHeight,e.scrollTop=Math.max(0,t-t6.current),t6.current=null}},[t2,tn]);let np=eF?[eF.sessionId,eF.sessionFile??"",eF.sessionName??"",eF.userMessages,eF.assistantMessages,eF.toolCalls,eF.toolResults,eF.totalMessages,eF.tokens.input,eF.tokens.output,eF.tokens.cacheRead,eF.tokens.cacheWrite,eF.tokens.total,eF.cost??0,eF.totalActiveMs??0].join("|"):null,nh=(0,i.useRef)(eF);nh.current=eF,(0,i.useEffect)(()=>{A?.(nh.current)},[np,A]),(0,i.useEffect)(()=>()=>{A?.(null)},[A]);let nf=eR?`${eR.percent??"null"}|${eR.contextWindow}|${eR.tokens??"null"}`:null,nm=(0,i.useRef)(eR);nm.current=eR,(0,i.useEffect)(()=>{P?.(nm.current)},[nf,P]),(0,i.useEffect)(()=>()=>{P?.(null)},[P]);let ng=(0,i.useCallback)(async e=>{let t=s?.cwd??h;if(!t)return void e2({type:"warning",message:Z("chat.dropNeedsCwd")});try{var n;let r,{status:i,data:s}=await t7(t,e,"skip");if(200!==i&&207!==i)throw Error(s.error??`HTTP ${i}`);let o=s.uploaded??[],l=s.skipped??[],a=(n=[...o,...l],r=new Set(n),e.filter(e=>r.has(e.name)).map(e=>t9(e.name,!1)).join(""));for(let e of(a&&E?.current?.insertText(a),o.length>0&&(e2({type:"success",message:Z("chat.dropUploaded",{count:o.length})}),O?.()),l.length>0&&e2({type:"warning",message:Z("chat.dropAlreadyExists",{names:l.join(", ")})}),s.errors??[]))e2({type:"error",message:Z("chat.dropFailed",{message:`${e.name}: ${e.error}`})})}catch(e){e2({type:"error",message:Z("chat.dropFailed",{message:e instanceof Error?e.message:String(e)})})}},[e2,E,h,O,s?.cwd,Z]),nx=(0,i.useCallback)(e=>{let{images:t,files:n,folders:r}=function(e){let t=[],n=[],r=[];for(let i of e)"folder"===i.kind?r.push(i.name):i.file.type.startsWith("image/")?t.push(i.file):n.push(i.file);return{images:t,files:n,folders:r}}(e);t.length>0&&E?.current?.addImages(t),r.length>0&&e2({type:"warning",message:Z("chat.dropFoldersUnsupported",{names:r.join(", ")})}),n.length>0&&ng(n)},[e2,E,Z,ng]),nv=(0,i.useCallback)(e=>{nx(e.map(e=>({kind:"file",file:e})))},[nx]),{isDragOver:nb,handleDragEnter:ny,handleDragOver:nw,handleDragLeave:nk,handleDrop:nj}=function(e){let[t,n]=(0,i.useState)(!1),r=(0,i.useRef)(0),s=(0,i.useCallback)(e=>{nt(e)&&(e.preventDefault(),r.current+=1,n(!0))},[]),o=(0,i.useCallback)(e=>{nt(e)&&(e.preventDefault(),e.dataTransfer.dropEffect="copy")},[]);return{isDragOver:t,handleDragEnter:s,handleDragOver:o,handleDragLeave:(0,i.useCallback)(()=>{r.current-=1,r.current<=0&&(r.current=0,n(!1))},[]),handleDrop:(0,i.useCallback)(t=>{t.preventDefault(),r.current=0,n(!1),e(nn(t.dataTransfer))},[e])}}(nx),nS=ex||tL,nC=(0,i.useMemo)(()=>(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=e.map(rX);for(let i=0;i<e.length;){var r;if(rQ(e[i])){i+=1;continue}let s=i+1;for(;s<e.length&&!rQ(e[s]);)s+=1;let o=e[s];if((o?"assistant"===o.role:!0===t.openTail)&&(r=e[i-1],r?.role==="assistant"&&("stop"===r.stopReason||"aborted"===r.stopReason))&&!n.slice(i,s).includes(!0)){let t=-1;for(let n=s-1;n>=i;n--){if("custom"!==e[n].role){if(-1!==t)break;continue}if(-1===t&&(t=n),!rG(e[n])){t=n;break}}-1!==t&&(n[t]=!0)}i=s}return n})(ea,{openTail:nS}),[ea,nS]),nN=ea.reduce((e,t,n)=>e+ +!!r0(t,nC[n]),0),nE=(0,i.useMemo)(()=>{let e=new Map(ed);for(let t of ea)"toolResult"===t.role&&e.set(t.toolCallId,t);return e},[ed,ea]),n$=(0,i.useMemo)(()=>new WeakMap,[]),nI=(0,i.useMemo)(()=>{let e=new Set,t=[];for(let n=ea.length-1;n>=0;n-=1){let r=function(e){if("user"!==e.role)return null;if("string"==typeof e.content){let t=e.content.trim();return t.length>0?t:null}let t=e.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n").trim();return t.length>0?t:null}(ea[n]);if(!(!r||e.has(r))&&(e.add(r),t.push(r),t.length>=50))break}return t.reverse()},[ea]),nM=((t=(0,i.useRef)([])).current=Array(nN).fill(null).map((e,n)=>t.current[n]??null),t),nT=(0,i.useCallback)(()=>{t4(e=>Math.max(e,2*ea.length))},[ea.length]),nR=e9&&0===ea.length&&!tL&&!tO;tI(tn,!!s?.id||!nR);let nA=s?.cwd??h??void 0,nL=(0,i.useRef)(null),nz=(0,i.useRef)(0),nP=(0,i.useRef)(null),nW=(0,i.useRef)(!1),nO=(0,i.useRef)(null);(0,i.useLayoutEffect)(()=>{let e=nL.current;if(!ex||!ti){nO.current=null,nz.current=0,nW.current=!1,e&&(e.style.height="");return}let t=tn.current,n=t5.current,r=tr.current;if(!t||!n||!r||!e)return;let i=!1,s=()=>{var s;let o;if(i||tn.current!==t||t5.current!==n||tr.current!==r||nL.current!==e)return;let l=t.getBoundingClientRect().top,a=Math.max(0,r.getBoundingClientRect().top-l+t.scrollTop-16),d=e.getBoundingClientRect().top-l+t.scrollTop,c=(s=t.clientHeight,0===(o=Math.max(0,a))?0:Math.max(0,Math.ceil(o+s-Math.max(0,d)))),u=!nW.current;u&&(nW.current=!0),c!==nz.current&&(nz.current=c,e.style.height=c>0?`${c}px`:"",u&&c>0&&t$())};nO.current=s,s();let o="u"<typeof ResizeObserver?null:new ResizeObserver(()=>{i||null!==nP.current||(nP.current=requestAnimationFrame(()=>{nP.current=null,s()}))});return o?.observe(t),o?.observe(n),o?.observe(r),()=>{i=!0,nO.current===s&&(nO.current=null),o?.disconnect(),null!==nP.current&&(cancelAnimationFrame(nP.current),nP.current=null)}},[ex,tr,ea.length,ti,tn,t$]);let nF=(0,i.useCallback)(()=>{nO.current?.()},[]);(0,i.useLayoutEffect)(nF,[tL,tP,nF]);let nD=eW?eE[`${eW.provider}:${eW.modelId}`]??null:null,nB=eW?e$[`${eW.provider}:${eW.modelId}`]??null:null,nH=(0,r.jsx)(da,{ref:E,onSend:ts,onAbort:to,onSideChat:C&&!a(s?.relation)?t0:void 0,onSteer:ex?th:void 0,onFollowUp:ex?tf:void 0,onPromptWithStreamingBehavior:ex?tg:void 0,isStreaming:tO,model:eW,isAutoModelSelection:e4,modelNames:ey,modelList:ew,modelError:ek,missingCwd:ej,modelScopeWarnings:eS,allModelList:eN,onLoadAllModels:eC?tE:void 0,onModelChange:tu,modelSwitching:eO,defaultModel:e3,onSetDefaultModel:tj,onCompact:s||e9?tp:void 0,onAbortCompaction:tx,isCompacting:eL,compactError:ez,onDismissCompactError:tv,compactResult:eP,toolPreset:eI,onToolPresetChange:s&&!a(s.relation)||e9?tw:void 0,thinkingLevel:eM,isAutoThinkingSelection:e8,onThinkingLevelChange:s||e9?tk:void 0,availableThinkingLevels:nD,thinkingLevelMap:nB,savedDefaultThinkingLevel:e5,onSetDefaultThinkingLevel:s||e9?tS:void 0,retryInfo:eT,queuedMessages:eH,inputHistory:nI,onRecallQueue:tb,slashCommands:eD,slashCommandsLoading:eB,onLoadSlashCommands:tN,extensionUiOpen:!!(eq||eZ),onBuiltinCommand:ty,soundEnabled:_,onSoundToggle:U,onAudioUnlock:q,draftKey:s?.id??f??void 0,cwd:s?.cwd??h,onAttachFiles:nv});return eo?(0,r.jsx)("div",{className:"flex h-full items-center justify-center text-text-muted",children:Z("chat.loadingSession")}):el?(0,r.jsx)("div",{className:"flex h-full items-center justify-center text-red-400",children:el}):(0,r.jsxs)("div",{className:"chat-content relative flex h-full min-w-0 flex-col overflow-hidden",style:{paddingBottom:"env(safe-area-inset-bottom)"},onDragEnter:ny,onDragOver:nw,onDragLeave:nk,onDrop:nj,children:[nb&&(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"})]})]})]}),(0,r.jsx)("div",{style:{position:"absolute",top:12,left:0,right:36*!J,zIndex:40,display:"flex",justifyContent:"flex-end",padding:"0 16px",pointerEvents:"none"},children:(0,r.jsx)(cz,{notices:e_,floating:!0,onPauseChange:e1})}),(0,r.jsxs)("div",{className:"relative flex min-h-0 min-w-0 flex-1 overflow-hidden",children:[eq&&(0,r.jsx)(cO,{request:eq,waitingCount:eV,onRespond:eQ},eq.id),eZ&&(0,r.jsx)(cF,{request:eZ,waitingCount:eY,onInput:e0},eZ.id),!nR&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{ref:tn,className:"scrollbar-subtle min-w-0 flex-1 overflow-x-hidden overflow-y-auto pt-4 [scrollbar-gutter:stable]",style:{visibility:en?"hidden":void 0},children:(0,r.jsx)("div",{style:{minWidth:0,padding:"0 16px"},children:(0,r.jsxs)("div",{ref:t5,onPointerUp:tG,style:{width:"100%",minWidth:0,maxWidth:"var(--chat-content-max-width, 820px)",margin:"0 auto"},children:[(()=>{var e;let t,n,o=-1;for(let e=ea.length-1;e>=0;e--)if("user"===ea[e].role){o=e;break}let l=-1;for(let e=ea.length-1;e>=0;e--)if(nC[e]){l=e;break}let a=new Map,d=0;ea.forEach((e,t)=>{r0(e,nC[t])&&a.set(t,d++)});let c=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=t.messageOverride??ea[e];if("custom"===n.role&&"pi-web:side-boundary"===n.customType)return(0,r.jsx)(cA,{},"side-chat-divider");if(rG(n))return null;let l=!1===t.withNotices?[]:oV(ea[e]),d=r0(n,nC[e]),c=a.get(e),u=t.keyPrefix??"message",p=ep[e],h=!1;if("assistant"===n.role){h=!0;for(let t=e+1;t<ea.length&&!nC[t];t++)if("assistant"===ea[t].role){h=!1;break}h&&tL&&e===ea.length-1&&(h=!1)}void 0!==t.showTimestamp&&(h=t.showTimestamp);let f=(0,r.jsx)(o3,{message:n,toolResults:nE,toolClocks:ec,modelNames:ey,cwd:nA,onOpenFile:W,onOpenSubagent:F,entryId:eu[e],searchBlock:eu[e]===ns?.entryId?na:void 0,onFork:ev||e9?void 0:tF,forking:eA===eu[e],onEditContent:tO?void 0:td,onCancelEdit:tc,isEditing:e7===eu[e],showTimestamp:h,prevTimestamp:e>0?ea[e-1].timestamp:void 0,sessionId:s?.id??tt.current??void 0,writtenFiles:t.writtenFiles,turnDurationMs:t.turnDurationMs,onCompact:t.recoverTruncation?tp:void 0,isCompacting:t.recoverTruncation?eL:void 0,compactError:t.recoverTruncation?ez:void 0},`${u}-view-${p}`),m=l.length>0?(0,r.jsx)(oX,{notices:l},`${u}-notices-${p}`):null;return d&&void 0!==c?(0,r.jsxs)("div",{"data-entry-id":eu[e],ref:!1===t.attachRef?void 0:t=>{nM.current[c]=t,e===o&&(tr.current=t)},children:[f,m]},`${u}-${p}`):(0,r.jsxs)(i.Fragment,{children:[f,m]},`${u}-${p}`)},u=[];for(let e=0;e<ea.length;){let t,n=nC[e];if(!n&&0!==e){u.push(c(e)),e+=1;continue}let i=n?e:-1,s=n?e:0,o=e+1;for(;o<ea.length&&!nC[o];)o+=1;let d=function(e,t,n){for(let i=n-1;i>t;i--){var r;if("assistant"===(r=e[i]).role&&r6(r).answerBlocks.some(e=>"image"===e.type||"text"===e.type&&e.text.trim().length>0))return i}for(let r=n-1;r>t;r--)if(e[r]?.role==="assistant")return r;return -1}(ea,i,o);if(-1===d||(tO||tL)&&o===ea.length&&i===l){for(let e=s;e<o;e++)u.push(c(e));e=o;continue}n&&u.push(c(i));let p=n&&eu[i]?function(e,t,n){let r,i,s,o=iw(e[t]?.timestamp);if(void 0===o)return;for(let r=t+1;r<n&&"custom"===e[r].role;r++){let t=iw(e[r].timestamp);void 0!==t&&(o=Math.max(o,t))}let l=!1,a=0;for(let o=t+1;o<n;o++){let t=e[o];if("assistant"===t.role){var d;void 0!==i&&void 0!==s&&(a+=Math.max(0,s-i)),i=s=void 0;let e=function(e){if("assistant"!==e.role)return;let t=iw(e.timestamp),n=iw(e.durationMs);return void 0!==t&&void 0!==n?t+n:void 0}(t);l=void 0!==e,void 0!==e&&(r=Math.max(r??e,e)),void 0!==e&&"assistant"===(d=t).role&&("stop"===d.stopReason||"length"===d.stopReason)&&(i=r)}else if("toolResult"===t.role){let e=iw(t.timestamp);void 0!==e&&(r=Math.max(r??e,e))}else if(void 0!==i){let e=iw(t.timestamp);void 0!==e&&(s=Math.max(s??e,e))}}if(l&&void 0!==r)return Math.max(0,r-o-a)}(ea,i,o):void 0,h=function(e,t){let n=e.get(t);if(n)return n;let{answerBlocks:r}=r6(t),i=r.length>0||r4(t)||r3(t)||r8(t)?iy(t,r):null,s=t.content.indexOf(r[0]),o={answer:i,process:iy(t,t.content.slice(0,s<0?void 0:s),{omitUsage:!!i,omitStop:!!i})};return e.set(t,o),o}(n$,ea[d]),f=h.answer,m=[],g=0,x=0,v=!1;for(let e=i+1;e<=d;e++){let n=ea[e];if("custom"===n.role){if(rG(n))continue;v||=!!(ns&&ns.entryId===eu[e]),g+=1,m.push(c(e,{attachRef:!1,keyPrefix:"process"}));continue}if("assistant"!==n.role)continue;let i=e===d?h.process:n,s=e!==d||!f,o=r2(i);if(0===o.length){let t=s?oV(n):[];t.length>0&&m.push((0,r.jsx)(oX,{notices:t},`process-notices-${ep[e]}`));continue}t??=a.get(e),x+=o.filter(e=>"toolCall"===e.type).length,g+=1,v||=!!(ns&&eu[e]===ns.entryId&&(!na||o.includes(na))),m.push(c(e,{attachRef:!1,keyPrefix:"process",messageOverride:i,showTimestamp:!1,withNotices:s}))}if(0===g)u.push(...m);else if(m.length>0){let e=(f?.content??[]).some(e=>"image"===e.type||"text"===e.type&&e.text.trim().length>0),n=function(e){let t;for(let n of e)for(let e of oV(n))"cache_miss"===e.kind&&(t??={count:0,missedTokens:0,missedCost:0},t.count+=1,t.missedTokens+=e.missedTokens,t.missedCost+=e.missedCost);return t}(ea.slice(i+1,f?d:d+1));u.push((0,r.jsx)("div",{ref:void 0===t?void 0:e=>{nM.current[t]=e},children:(0,r.jsx)(cT,{messageCount:g,toolCallCount:x,durationMs:p,cacheMisses:n,defaultExpanded:!e,reveal:v,t:Z,children:m},e?"answered":"unanswered")},`process-group-${ep[s]}`))}if(f){let e=[];for(let t=i+1;t<=d;t++){let n=ea[t];if(n?.role==="assistant")for(let t of n.content??[])e.push(t)}let t=function(e,t){let n=e.writtenFiles;return n&&n.length===t.length&&n.every((e,n)=>e.filePath===t[n].filePath)?n:(e.writtenFiles=t,t)}(h,function(e,t,n){let r=new Set,i=[];for(let o of e){var s;if("toolCall"!==o.type||!(id(s=o.toolName)||ic(s))&&!iu(o.toolName))continue;let e=t?.get(o.toolCallId);if(e&&!e.isError)for(let t of iu(o.toolName)?function(e,t){let n=t?.details,r=function(e,t){let n=new Set;if(t&&"object"==typeof t&&!Array.isArray(t)){let e=t.preview;if(e&&"object"==typeof e&&!Array.isArray(e)){let t=e.files;if(Array.isArray(t))for(let e of t)!(!e||"object"!=typeof e||Array.isArray(e))&&"delete"===e.operation&&"string"==typeof e.filePath&&e.filePath.length>0&&n.add(e.filePath)}}for(let t of ip(e).matchAll(/^\*\*\* Delete File: (.+)$/gm)){let e=(t[1]??"").trim();e&&n.add(e)}return n}(e,n),i=function(e){if(!ih(e)||!ih(e.result))return null;let t=e.result.appliedFiles;return Array.isArray(t)?t.filter(e=>"string"==typeof e&&e.length>0):null}(n);if(i)return i.filter(e=>!r.has(e));if(im(n))return[];if(n&&"object"==typeof n&&!Array.isArray(n)){let e=ib(iv(n.preview));if(e.length>0)return e}return ib(ix(ip(e)))}(o.input,e):[function(e){if(!e)return null;let t=e.file_path??e.path;return"string"==typeof t&&t.length>0?t:null}(o.input)]){if(!t)continue;let e=function(e,t){let n;if(!e)return null;let r=it(e)||it(t),i=e=>r?e.replace(/\\/g,"/"):e,s=i(e),o=t?i(t).replace(/\/+$/,""):void 0,l=/^[a-zA-Z]:\//.test(s),a=s.startsWith("//"),d=r?ii(s):s;if(l||a||d!==s)n=d;else if(s.startsWith("/")){let e=o?.match(/^([a-zA-Z]:)(?:\/|$)/)?.[1]??o?.match(/^(\/\/[^/]+\/[^/]+)(?:\/|$)/)?.[1];n=e?`${e}${s}`:s}else{if(!o)return null;n=`${o}/${s}`}return is(n)}(t,n);e&&(r.has(e)||(r.add(e),i.push({filePath:e})))}}return i}(e,nE,nA));u.push(c(d,{messageOverride:f,writtenFiles:t,turnDurationMs:0===m.length?p:void 0,recoverTruncation:o===ea.length&&!tL&&!r5(f)}))}for(let e=d+1;e<o;e++)u.push(c(e));e=o}let{startIndex:p}=(t=Math.min(Math.max(t2,0),Math.max(e=u.length,0)),{startIndex:n=Math.max(0,e-t),hasMore:n>0}),h=p>0||ef;return(0,r.jsxs)(r.Fragment,{children:[h&&(0,r.jsx)("div",{ref:t3,className:"py-3 text-center text-xs text-text-muted",children:Z("chat.loadEarlier")}),u.slice(p)]})})(),tL&&tP&&(0,r.jsx)(cL,{store:eg,onCommit:nF,toolResults:nE,modelNames:ey,cwd:nA,onOpenFile:W,onOpenSubagent:F}),(ex||eL)&&!tP&&(e6||eL)&&(0,r.jsx)("div",{className:"break-words py-2 text-[13px] text-text-muted",children:(0,r.jsx)("span",{className:"animate-[pulse_1.5s_infinite]",children:function(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0;if(n)return r>0?t("chat.compactingQueued",{count:r}):t("chat.compacting");if(e?.kind==="running_tools"){let n=e.tools[e.tools.length-1];if(n?.progress)return`${t("chat.runningNamedTool",{name:n.name})} ${n.progress}`;let r=e.tools.map(e=>e.name);return 0===r.length?t("chat.runningTool"):1===r.length?t("chat.runningNamedTool",{name:r[0]}):r.length<=3?t("chat.runningTools",{names:r.join(", ")}):t("chat.runningToolsMore",{names:r.slice(0,2).join(", "),count:r.length-2})}return e?.kind==="waiting_model"?t("chat.waitingModel"):e?.kind==="running_command"?t("chat.runningCommand"):null}(e6,Z,eL,(eH?.steering.length??0)+(eH?.followUp.length??0))})}),ev&&!eb&&(0,r.jsx)("div",{className:"py-2 text-[13px] text-text-muted",children:(0,r.jsx)("span",{className:"animate-[pulse_1.5s_infinite]",children:Z("chat.runningCommand")})}),eb&&(0,r.jsx)(o3,{message:{role:"bashExecution",command:eb.command,output:"",...eb.result,excludeFromContext:eb.excludeFromContext,timestamp:eb.startedAt},sessionId:s?.id??tt.current??void 0,onOpenSubagent:F}),eb?.liveOutput&&!eb.result&&(0,r.jsx)("div",{"aria-live":"off",className:"rounded-md border border-border px-2.5 py-1.5 font-mono text-[12px] leading-[1.45] text-text-muted",style:{marginTop:-2,background:"var(--tool-bg)"},children:(0,r.jsx)("pre",{className:"m-0 flex flex-col justify-end overflow-hidden whitespace-pre-wrap break-words",style:{maxHeight:"29em"},children:(0,r.jsx)("span",{children:eb.liveOutput.replace(/\n+$/,"").split("\n").slice(-20).join("\n")})})}),(0,r.jsx)("div",{ref:nL,"aria-hidden":"true"})]})})}),J||en?null:(0,r.jsx)(dS,{messages:ea,getStreamingMessage:tW,scrollContainer:tn,messageRefs:nM,onRevealHistory:nT,turnsBefore:em,turnAnchors:nC})]})]}),D&&tD&&(0,tz.createPortal)((0,r.jsx)("div",{ref:tZ,role:tH?"dialog":"toolbar","aria-label":Z(tH?"chat.newQuoteChat":"chat.selectionActions"),style:{position:"fixed",top:tD.top,left:tD.left,zIndex:260,display:"flex",flexWrap:"wrap",gap:3,width:tH?"min(420px, calc(100vw - 16px))":void 0,maxWidth:"calc(100vw - 16px)",maxHeight:"calc(var(--app-viewport-height, 100dvh) - 16px)",overflowY:"auto",padding:tH?12:3,border:"1px solid var(--border)",borderRadius:6,background:"var(--bg)",boxShadow:"0 2px 10px rgba(0,0,0,0.12)"},children:tH?(0,r.jsxs)("fieldset",{disabled:tU,"aria-busy":tU,style:{width:"100%",minWidth:0,margin:0,padding:0,border:"none",display:"flex",flexDirection:"column",gap:10},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[(0,r.jsx)("span",{style:{flex:1,minWidth:0,fontSize:12,fontWeight:600},children:Z("chat.askInSideChat")}),(0,r.jsx)("button",{type:"button",className:"file-viewer-icon-button",title:Z("i18n.close"),"aria-label":Z("i18n.close"),disabled:tU,onClick:tY,style:{border:"none"},children:(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m6 6 12 12M18 6 6 18"})})})]}),(0,r.jsx)(da,{ref:tJ,compact:!0,onSend:tQ,onAbort:tY,isStreaming:!1}),tq&&(0,r.jsx)("div",{role:"alert",style:{color:"#dc2626",fontSize:12,overflowWrap:"anywhere"},children:tq})]}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("button",{type:"button",className:"file-viewer-icon-button",title:Z("chat.quoteSelection"),"aria-label":Z("chat.quoteSelection"),onPointerDown:e=>e.preventDefault(),onClick:tX,style:{width:"auto",height:35,flex:"0 0 auto",gap:5,padding:"0 10px",border:"none",fontSize:12,fontWeight:500},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M16 3a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2 1 1 0 0 1 1 1v1a2 2 0 0 1-2 2 1 1 0 0 0-1 1v2a1 1 0 0 0 1 1 6 6 0 0 0 6-6V5a2 2 0 0 0-2-2z"}),(0,r.jsx)("path",{d:"M5 3a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2 1 1 0 0 1 1 1v1a2 2 0 0 1-2 2 1 1 0 0 0-1 1v2a1 1 0 0 0 1 1 6 6 0 0 0 6-6V5a2 2 0 0 0-2-2z"})]}),(0,r.jsx)("span",{children:Z("chat.quoteSelection")})]}),C&&!a(s?.relation)&&(0,r.jsxs)("button",{type:"button",className:"file-viewer-icon-button",title:Z("chat.askInSideChat"),"aria-label":Z("chat.askInSideChat"),onPointerDown:e=>e.preventDefault(),onClick:()=>{t_(!0),window.getSelection()?.removeAllRanges()},style:{width:"auto",height:35,flex:"0 0 auto",gap:5,padding:"0 10px",border:"none",fontSize:12,fontWeight:500},children:[(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M21 12a8 8 0 0 1-8 8H5.5a2 2 0 0 1-1.4-3.4A8 8 0 1 1 21 12z"})}),(0,r.jsx)("span",{children:Z("chat.askInSideChat")})]})]})}),document.body),(0,r.jsxs)("div",{className:"relative flex min-h-0 flex-col",children:[!nR&&(0,r.jsx)("div",{style:{position:"absolute",bottom:"100%",left:0,right:36*!J,display:"flex",justifyContent:"center",paddingBottom:10,pointerEvents:"none",zIndex:20},children:(0,r.jsx)("button",{type:"button",className:`chat-scroll-to-bottom${te&&!en?" is-visible":""}`,title:Z("chat.scrollToLatest"),"aria-label":Z("chat.scrollToLatest"),onClick:()=>tR("smooth"),children:(0,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M12 5v14M5 12l7 7 7-7"})})})}),nR&&(0,r.jsx)("div",{className:"new-session-hero",style:{paddingLeft:16,paddingRight:J?16:52},children:(0,r.jsxs)("div",{className:"new-session-hero-inner",style:{maxWidth:"var(--chat-content-max-width, 820px)"},children:[(0,r.jsxs)("div",{className:"new-session-brand",children:[(0,r.jsx)(rO.A,{src:"/icons/apple-touch-icon.png",width:40,height:40,alt:"",priority:!0,className:"new-session-logo"}),(0,r.jsxs)("div",{className:"new-session-brand-text",children:[(0,r.jsx)("span",{className:"new-session-brand-name",children:"Pi Web"}),(0,r.jsxs)("span",{className:"new-session-meta",children:[(0,r.jsxs)("span",{children:["web v","0.17.0-custom.3"]}),(0,r.jsx)(cM,{label:e=>Z("appUpdate.releaseNotes",{version:e})}),(0,r.jsx)("span",{"aria-hidden":"true",children:"\xb7"}),(0,r.jsxs)("span",{className:"new-session-meta-pi",children:["pi v","1.5.2"]})]})]})]}),m]})}),nH,(0,r.jsx)(dI,{statuses:eG,widgets:eX,onCommand:ts,commandsDisabled:tO})]}),nR&&(0,r.jsx)("div",{className:"min-h-0 flex-1"})]})}function cA(){let{t:e}=(0,tm.s)();return(0,r.jsxs)("div",{role:"separator",className:"my-4 flex items-center gap-3 text-xs",style:{color:"var(--text-dim)"},children:[(0,r.jsx)("span",{className:"h-px flex-1",style:{background:"var(--border)"}}),(0,r.jsx)("span",{children:e("sideChat.divider")}),(0,r.jsx)("span",{className:"h-px flex-1",style:{background:"var(--border)"}})]})}let cL=(0,i.memo)(function(e){let{store:t,onCommit:n,toolResults:s,modelNames:o,cwd:l,onOpenFile:a,onOpenSubagent:d}=e,c=ck(t,cC);return((0,i.useLayoutEffect)(n,[c,n]),c)?(0,r.jsx)(o3,{message:c,toolResults:s,isStreaming:!0,modelNames:o,cwd:l,onOpenFile:a,onOpenSubagent:d}):null});function cz(e){let{notices:t,floating:n=!1,onPauseChange:s}=e;return 0===t.length?null:(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",alignItems:"flex-end",marginBottom:10*!n},children:t.map((e,o)=>{var l;let a,d,c,u="error"===e.type?"#ef4444":"warning"===e.type?"#d97706":"success"===e.type?"#10b981":"var(--accent)";return(0,r.jsxs)("div",{className:"notice-shelf-item",onMouseEnter:()=>s?.(e.id),onMouseLeave:e=>{e.currentTarget.contains(document.activeElement)||s?.(null)},onFocus:()=>s?.(e.id),onBlur:e=>{e.currentTarget.matches(":hover")||s?.(null)},style:{display:"flex",alignItems:"flex-start",gap:10,minHeight:60,height:"auto",maxHeight:500,pointerEvents:"auto",marginBottom:6*(o!==t.length-1),overflow:"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:n?"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:14,lineHeight:1.5,transformOrigin:"top right",animation:e.exiting?"notice-shelf-out 0.18s ease-in forwards":"notice-shelf-in 0.18s ease-out backwards",padding:"0 12px"},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:u,flexShrink:0,marginTop:25.5}}),(0,r.jsx)("span",{tabIndex:0,style:{padding:"18.5px 0",minWidth:0,maxWidth:"100%",maxHeight:498,overflowY:"auto",scrollbarWidth:"thin",whiteSpace:"pre-line",wordBreak:"break-word"},children:(l=e.message,a=[],d=(e,t)=>{if(!t)return;let n=a[a.length-1];n?.kind===e?n.text+=t:a.push({kind:e,text:t})},c=!1,l.split("\n").forEach((e,t)=>{let n=rq.test(e);t>0&&d(n&&c?"art":"text","\n"),d(n?"art":"text",e),c=n}),a).map((e,t)=>"art"===e.kind?(0,r.jsx)("span",{style:{display:"inline-block",verticalAlign:"top",maxWidth:"100%",overflowX:"auto",whiteSpace:"pre",fontFamily:"var(--font-mono)",lineHeight:1,color:"var(--text)"},children:e.text},t):(0,r.jsx)(i.Fragment,{children:(function(e){let t=[],n=0;for(let r of e.matchAll(rV)){let i=function(e){let t=0,n=0;for(let r of e)"("===r?t+=1:")"===r&&(n+=1);let r=e.length;for(;r>0;){let i=e[r-1];if(rZ.test(i))r-=1;else if(")"===i&&n>t)r-=1,n-=1;else break}return e.slice(0,r)}(r[0]);if(!/^https?:\/\/[^/]/i.test(i))continue;let s=r.index??0;s>n&&t.push({kind:"text",text:e.slice(n,s)}),t.push({kind:"link",text:i}),n=s+i.length}return n<e.length&&t.push({kind:"text",text:e.slice(n)}),t})(e.text).map((e,n)=>"link"===e.kind?(0,r.jsx)("a",{href:e.text,target:"_blank",rel:"noopener noreferrer",style:{color:"var(--accent)",textDecoration:"underline",textUnderlineOffset:2,wordBreak:"break-all"},children:e.text},`${t}-${n}`):e.text)},t))})]},e.id)})})}function cP(e){let{count:t}=e,{t:n}=(0,tm.s)();return t<=0?null:(0,r.jsx)("span",{style:{fontSize:11,fontWeight:650,color:"var(--accent)",whiteSpace:"nowrap",flexShrink:0},children:n("chat.extensionMoreWaiting",{count:t})})}function cW(e){let{expanded:t}=e;return(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:1.6,strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:t?(0,r.jsx)("path",{d:"M3.5 1v2.5H1M6.5 1v2.5H9M6.5 9v-2.5H9M3.5 9v-2.5H1"}):(0,r.jsx)("path",{d:"M1 3.5V1h2.5M6.5 1H9v2.5M9 6.5V9H6.5M3.5 9H1V6.5"})})}function cO(e){let{request:t,waitingCount:n,onRespond:s}=e,{t:o}=(0,tm.s)(),[l,a]=(0,i.useState)("editor"===t.method?t.prefill??"":""),[d,c]=(0,i.useState)(!1),u=(0,i.useRef)(null),p=(0,i.useRef)(null),[h,f]=(0,i.useState)(null),[m,g]=(0,i.useState)(!1),x=(0,i.useCallback)(()=>g(e=>!e),[]),[v,b]=(0,i.useState)(()=>Date.now()),y=(0,i.useCallback)(e=>e?.focus(),[]),w=function(e){if("select"===e.method&&e.options.length>0)return rH(e.options[0]);if("confirm"===e.method){let t=rH(e.message).split("\n").find(e=>e.trim());return t?.trim()}}(t),k=void 0===t.expiresAt?null:Math.max(0,Math.ceil((t.expiresAt-v)/1e3));(0,i.useLayoutEffect)(()=>{if(d)return;let e=u.current,t=p.current;if(!e||!t)return;let n=!1,r=()=>{if(n)return;let r=t.querySelectorAll("pre, .markdown-table-wrap");if(0===r.length)return;t.classList.add("extension-dialog-measuring");let i=Array.from(r,e=>e.scrollWidth-e.clientWidth);t.classList.remove("extension-dialog-measuring");let s=function(e,t){let n=0;for(let e of t)e>1&&e>n&&(n=e);return 0===n?null:40*Math.ceil((e+n)/40)}(e.offsetWidth,i);null!==s&&f(e=>null!==e&&e>=s?e:s)};r();let i=new MutationObserver(r);return i.observe(t,{childList:!0,subtree:!0,characterData:!0}),document.fonts?.ready.then(r),()=>{n=!0,i.disconnect()}},[d]),(0,i.useEffect)(()=>{if(void 0===t.expiresAt)return;let e=setInterval(()=>b(Date.now()),1e3);return()=>clearInterval(e)},[t.expiresAt]);let j=null!==k&&(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",whiteSpace:"nowrap",flexShrink:0},children:o("chat.extensionExpiresIn",{seconds:k})}),S=()=>{"confirm"===t.method?s(t,{confirmed:!0}):s(t,{value:l})};return(0,r.jsx)("div",{onKeyDown:e=>{"Escape"!==e.key||e.nativeEvent.isComposing||229===e.nativeEvent.keyCode||(e.preventDefault(),e.stopPropagation(),s(t,{cancelled:!0}))},style:{position:"absolute",inset:0,zIndex:90,display:"flex",alignItems:d?"flex-start":"center",justifyContent:"center",padding:20,pointerEvents:"none"},children:d?(0,r.jsxs)("button",{type:"button",onClick:()=>c(!1),"aria-expanded":!1,style:{pointerEvents:"auto",display:"flex",alignItems:"center",gap:10,maxWidth:"min(560px, 100%)",width:"100%",padding:"10px 12px",border:"1px solid var(--border)",borderRadius:8,background:"var(--bg)",boxShadow:"0 12px 32px rgba(0,0,0,0.18)",color:"var(--text)",cursor:"pointer",textAlign:"left"},children:[(0,r.jsx)("span",{style:{fontSize:11,fontWeight:650,color:"var(--accent)",flexShrink:0},children:o("chat.extensionPending")}),(0,r.jsx)("span",{style:{fontSize:13,fontWeight:600,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1,minWidth:0},children:rH(t.title)}),w&&(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-dim)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",maxWidth:"34%",flexShrink:1},children:w}),(0,r.jsx)(cP,{count:n}),j,(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",flexShrink:0},children:o("chat.extensionExpand")})]}):(0,r.jsxs)("div",{ref:u,role:"dialog","aria-label":rH(t.title),style:{pointerEvents:"auto",width:m?"100%":`min(${h??560}px, 100%)`,maxHeight:m?"100%":"min(760px, 100%)",display:"flex",flexDirection:"column",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:{flexShrink:1,minHeight:0,display:"flex",alignItems:"flex-start",gap:8,padding:"12px 14px",borderBottom:"1px solid var(--border)",maxHeight:"50vh",overflowY:"auto"},children:[(0,r.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,r.jsx)("div",{style:{color:"var(--text)",fontSize:14,fontWeight:650,lineHeight:1.45,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:rH(t.title)}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",gap:8,marginTop:3,color:"var(--text-dim)",fontSize:11,fontFamily:"var(--font-mono)"},children:[(0,r.jsx)("span",{children:o("chat.extensionRequest")}),(0,r.jsx)(cP,{count:n}),j]})]}),(0,r.jsx)("button",{type:"button",onClick:x,title:o(m?"chat.extensionRestoreSize":"chat.extensionMaximize"),"aria-label":o(m?"chat.extensionRestoreSize":"chat.extensionMaximize"),style:{display:"grid",placeItems:"center",width:28,height:28,borderRadius:6,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",cursor:"pointer",flexShrink:0},children:(0,r.jsx)(cW,{expanded:m})}),(0,r.jsx)("button",{type:"button",onClick:()=>c(!0),"aria-expanded":!0,title:o("chat.extensionCollapse"),"aria-label":o("chat.extensionCollapse"),style:{display:"grid",placeItems:"center",width:28,height:28,borderRadius:6,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",cursor:"pointer",flexShrink:0},children:(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})})})]}),(0,r.jsxs)("div",{ref:p,style:{padding:14,flex:"1 1 auto",minHeight:0,overflowY:"auto"},children:["confirm"===t.method&&(0,r.jsx)(od,{children:rH(t.message)}),"select"===t.method&&(0,r.jsx)("div",{onKeyDown:e=>{if(!["ArrowDown","ArrowRight","ArrowUp","ArrowLeft","Home","End"].includes(e.key))return;let t=Array.from(e.currentTarget.querySelectorAll("[data-extension-option]")),n=t.indexOf(e.target);if(n<0)return;e.preventDefault();let r="Home"===e.key?0:"End"===e.key?t.length-1:(n+("ArrowDown"===e.key||"ArrowRight"===e.key?1:-1)+t.length)%t.length;t[r].focus({preventScroll:!0}),t[r].scrollIntoView({block:"nearest"})},style:{display:"grid",gap:8},children:t.options.map((e,n)=>(0,r.jsx)("div",{role:"button",tabIndex:0,"data-extension-option":!0,"aria-label":rH(e),ref:0===n?y:void 0,onClick:()=>s(t,{value:e}),onKeyDown:n=>{("Enter"===n.key||" "===n.key)&&(n.preventDefault(),s(t,{value:e}))},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,overflowWrap:"anywhere",scrollMargin:14},children:(0,r.jsx)("div",{inert:!0,children:(0,r.jsx)(od,{children:rH(e)})})},e))}),"input"===t.method&&(0,r.jsx)("input",{autoFocus:!0,value:l,placeholder:t.placeholder,onChange:e=>a(e.target.value),onKeyDown:e=>{"Enter"!==e.key||e.nativeEvent.isComposing||229===e.nativeEvent.keyCode||S()},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"===t.method&&(0,r.jsx)("textarea",{autoFocus:!0,value:l,onChange:e=>a(e.target.value),onKeyDown:e=>{(e.metaKey||e.ctrlKey)&&"Enter"===e.key&&!e.nativeEvent.isComposing&&229!==e.nativeEvent.keyCode&&S()},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:{flexShrink:0,display:"flex",justifyContent:"flex-end",gap:8,padding:"10px 14px",borderTop:"1px solid var(--border)",background:"var(--bg-panel)"},children:[(0,r.jsx)("button",{autoFocus:"confirm"===t.method||"select"===t.method&&0===t.options.length,onClick:()=>s(t,{cancelled:!0}),style:{padding:"6px 10px",borderRadius:6,border:"1px solid var(--border)",background:"var(--bg)",color:"var(--text-muted)",cursor:"pointer"},children:o("chat.cancel")}),"confirm"===t.method?(0,r.jsx)("button",{onClick:S,style:{padding:"6px 10px",borderRadius:6,border:"1px solid var(--accent)",background:"var(--accent)",color:"var(--accent-contrast)",cursor:"pointer"},children:o("chat.confirm")}):"select"!==t.method?(0,r.jsx)("button",{onClick:S,style:{padding:"6px 10px",borderRadius:6,border:"1px solid var(--accent)",background:"var(--accent)",color:"var(--accent-contrast)",cursor:"pointer"},children:o("chat.submit")}):null]})]})})}function cF(e){let{request:t,waitingCount:n,onInput:s}=e,{t:o}=(0,tm.s)(),l=(0,i.useRef)(null),a=(0,i.useRef)(!1),[d,c]=(0,i.useState)(!1),u=function(e){let t=/^[┌├└╭╰][─┬┴┼]+[┐┤┘╮╯]$/,n=[];for(let r of e){let e=r.replace(rB,""),i=rH(e).trimEnd();if(t.test(i))continue;let s=e,o=rK(s);("│"===o||"┃"===o)&&" "===rK(s=rU(s,0))&&(s=rU(s,0));let l=function(e){let t=r_(e);for(let e=t.length-1;e>=0;e--)if(""!==t[e].char.trim())return e;return -1}(s),a=l>=0?r_(s)[l]?.char:void 0;("│"===a||"┃"===a)&&(s=rU(s,l)),n.push(function(e){let t=e;for(;;){let e=r_(t),n=e[e.length-1];if(!n||""!==n.char.trim())return t;t=t.slice(0,n.start)+t.slice(n.end)}}(s))}for(;n.length>0&&""===rH(n[0]).trim();)n.shift();for(;n.length>0&&""===rH(n[n.length-1]).trim();)n.pop();return n.length?n:e.map(e=>e.replace(rB,""))}(t.lines),p=u.map(rH).find(e=>e.trim())?.trim();return(0,i.useEffect)(()=>{d||l.current?.focus()},[d]),(0,r.jsx)("div",{style:{position:"absolute",inset:0,zIndex:95,display:"flex",alignItems:d?"flex-start":"center",justifyContent:"center",padding:20,pointerEvents:"none"},children:d?(0,r.jsxs)("button",{type:"button",onClick:()=>c(!1),"aria-expanded":!1,style:{pointerEvents:"auto",display:"flex",alignItems:"center",gap:10,maxWidth:"min(920px, 100%)",width:"100%",padding:"10px 12px",border:"1px solid var(--border)",borderRadius:8,background:"var(--bg)",boxShadow:"0 12px 32px rgba(0,0,0,0.18)",color:"var(--text)",cursor:"pointer",textAlign:"left"},children:[(0,r.jsx)("span",{style:{fontSize:11,fontWeight:650,color:"var(--accent)",flexShrink:0},children:o("chat.extensionPending")}),(0,r.jsx)("span",{style:{fontSize:13,fontWeight:600,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1,minWidth:0},children:o("chat.extensionPanel")}),p&&(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-dim)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",maxWidth:"34%",flexShrink:1},children:p}),(0,r.jsx)(cP,{count:n}),(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",flexShrink:0},children:o("chat.extensionExpand")})]}):(0,r.jsxs)("div",{role:"dialog",onClick:e=>{e.target.closest("button")||l.current?.focus()},style:{pointerEvents:"auto",position:"relative",width:"max-content",minWidth:"min(920px, 100%)",maxWidth:"100%",maxHeight:"min(760px, 100%)",display:"flex",flexDirection:"column",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.jsx)("textarea",{ref:l,"aria-label":o("chat.extensionInput"),autoCapitalize:"off",autoComplete:"off",autoCorrect:"off",spellCheck:!1,onKeyDown:e=>{if(a.current||e.nativeEvent.isComposing||229===e.nativeEvent.keyCode)return;let n=function(e){if(e.metaKey||e.ctrlKey&&!e.altKey&&"v"===e.key.toLowerCase())return null;if(e.ctrlKey&&!e.altKey){let t=function(e){if(1!==e.length)return null;if(" "===e)return"\0";if("/"===e||"-"===e)return"\x1f";let t=e.toUpperCase().charCodeAt(0);return t>=64&&t<=95?String.fromCharCode(31&t):"?"===e?"":null}(e.key);if(t)return t}let t=rJ[e.key],n=1+ +!!e.shiftKey+2*!!e.altKey+4*!!e.ctrlKey;if(n>1&&!(e.altKey&&!e.ctrlKey&&!e.shiftKey&&rY[e.key])){if(/^\x1b\[[ABCDHF]$/.test(t??""))return`\x1b[1;${n}${t.at(-1)}`;if(/^\x1b\[\d+~$/.test(t??""))return`${t.slice(0,-1)};${n}~`}if(e.altKey&&!e.ctrlKey){if("Backspace"===e.key)return"\x1b\x7f";let t=rY[e.key];if(t)return t;if(1===e.key.length)return`\x1b${e.key}`}return"Enter"===e.key?e.shiftKey?"\n":"\r":"Tab"===e.key?e.shiftKey?"\x1b[Z":" ":rJ[e.key]??null}(e);n&&(e.preventDefault(),e.stopPropagation(),s(t,n))},onInput:e=>{if(a.current||e.nativeEvent.isComposing)return;let n=e.currentTarget.value;e.currentTarget.value="",n&&s(t,n)},onCompositionStart:()=>{a.current=!0},onCompositionEnd:e=>{a.current=!1;let n=e.currentTarget;queueMicrotask(()=>{let e=n.value;n.value="",e&&s(t,e)})},onPaste:e=>{e.preventDefault();let n=e.clipboardData.getData("text");n&&s(t,`\x1b[200~${n}\x1b[201~`)},style:{position:"absolute",width:1,height:1,padding:0,border:0,opacity:0,pointerEvents:"none"}}),(0,r.jsxs)("div",{style:{flexShrink:0,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("chat.extensionPanel")}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[(0,r.jsx)(cP,{count:n}),(0,r.jsx)("button",{type:"button",onClick:()=>c(!0),"aria-expanded":!0,title:o("chat.extensionCollapse"),"aria-label":o("chat.extensionCollapse"),style:{display:"grid",placeItems:"center",width:28,height:28,borderRadius:6,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",cursor:"pointer",flexShrink:0},children:(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})})}),(0,r.jsx)("button",{onClick:()=>s(t,"\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("chat.close")})]})]}),(0,r.jsx)("pre",{style:{margin:0,padding:14,minHeight:0,overflow:"auto",background:"var(--bg-panel)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:13,lineHeight:1.45,whiteSpace:"pre"},children:(0,r.jsx)(dN,{text:u.join("\n")})})]})})}let cD=null,cB="";function cH(e){let{context:t,mobile:n,initialFocus:s,onInitialFocusDone:o,onPick:l,onUseDefaultDirectory:a,onOpenFolder:d,onRefreshWorktrees:c,onCreateWorktree:u}=e,{t:p}=(0,tm.s)(),[h,f]=(0,i.useState)(()=>cB),m=(0,i.useRef)(null),g=(0,i.useRef)(s),x=(0,i.useRef)(o);return x.current=o,(0,i.useEffect)(()=>{if(cB)return;let e=!1;return(cD??=fetch("/api/home").then(e=>e.json()).then(e=>cB=e.home??"").catch(()=>(cD=null,""))).then(t=>{!e&&t&&f(t)}),()=>{e=!0}},[]),(0,i.useEffect)(()=>{let e=g.current;if(!e)return;g.current=null,x.current();let t=m.current;e_(document,("worktree"===e?t?.button("worktree"):null)??t?.button("project")??null)},[]),(0,r.jsx)("div",{className:"new-session-context",children:(0,r.jsx)(rj,{handleRef:m,layout:"inline",context:t,mobile:n,label:p("workspace.newSessionContext"),homeDir:h,newWorktreeTitle:p("sidebar.newWorktreeForSession"),onPick:l,onUseDefaultDirectory:a,onOpenFolder:d,onRefreshWorktrees:c,onCreateWorktree:u})})}function c_(e){return e&&"number"==typeof e.size&&"string"==typeof e.mtime?`${e.size}:${e.mtime}`:null}function cU(e,t){return null===e||null===t||e!==t}let cK=`<script data-pi-web-polyfill="storage">
|
|
9
|
+
${r=null===a.number?a.marker:`${String(Number(a.number)+1).padStart(a.number.length,"0")}${a.delimiter}`,`${a.indent}${r}${a.spacing}${a.task?"[ ] ":""}`}`}}(e.value,e.selectionStart,e.selectionEnd);n&&(t.preventDefault(),e.setSelectionRange(n.start,n.end),document.execCommand(n.text?"insertText":"delete",!1,n.text))};return e.addEventListener("beforeinput",t),()=>e.removeEventListener("beforeinput",t)},[]),(0,i.useEffect)(()=>()=>{tf.current.forEach(dt)},[]),(0,i.useLayoutEffect)(()=>{if(eq){let e=e=>{e.target!==eJ.current&&(eJ.current=null)};return document.addEventListener("pointerdown",e,!0),()=>document.removeEventListener("pointerdown",e,!0)}let e=eJ.current;eJ.current=null,e?.isConnected&&document.activeElement===document.body&&!document.querySelector('[aria-modal="true"]')&&e.focus({preventScroll:!0})},[eq]);let tj=(0,i.useCallback)(async e=>{if(ew.length||!e.startsWith("/")||!G)return!1;if(eZ.current)return!0;eJ.current=document.activeElement===e3.current?e3.current:null,eZ.current=!0,eV(!0);try{var t,n;let r=await G(e);if(!r.handled)return!1;return r.error||(t=th.current,n=tf.current.length,0!==n||t.trim()!==e)||tw(),!0}finally{eZ.current=!1,eV(!1)}},[ew.length,tw,G]),tS=(0,i.useCallback)(async()=>{var e;let t=eh.trim();(t||ew.length)&&(ee?.(),(!f||a0(e=t)||l2(e))&&await tj(t)||(!f||t.startsWith("!")&&!ew.length)&&(tw(),d(t,ew.length?ew:void 0)))},[eh,ew,f,tj,d,tw,ee]),tN=!es&&eh.startsWith("/")&&!/\s/.test(eh.slice(1))?eh.slice(1).toLowerCase():null,tE=(()=>{var e;let t,n;return null===tN?[]:(e=[...f?aQ.filter(e=>e.availableWhileStreaming):aQ,...V??[]],((n=(t=e.map(e=>{let t,n;return{command:e,rank:(t=e.name.toLowerCase(),(n="skill"===e.source&&t.startsWith("skill:")?t.slice(6):t)===tN||t===tN?0:n.startsWith(tN)||t.startsWith(tN)?1:t.includes(tN)?2:3)}})).filter(e=>{let{rank:t}=e;return t<3})).length>0?n:t.filter(e=>{let{command:t}=e;return a8(t,eo).toLowerCase().includes(tN)})).sort((e,t)=>e.rank-t.rank||a4[e.command.source]-a4[t.command.source]||a_.compare(e.command.name,t.command.name)).map(e=>{let{command:t}=e;return t}))})(),{commands:t$,groups:tI}=function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"",r=0,i=a1.map(i=>{let s=e.filter(e=>e.source===i),o="skill"!==i||n?s:[...s.filter(e=>!a3(e,t)),...s.filter(e=>a3(e,t))];return{source:i,items:o.map(e=>({command:e,index:r++}))}}).filter(e=>e.items.length>0);return{commands:i.flatMap(e=>e.items.map(e=>{let{command:t}=e;return t})),groups:i}}(tE,e8,tN??""),tM=1===tE.length?eo(tN?"chat.match":"chat.command"):eo(tN?"chat.matches":"chat.commands",{count:tE.length}),tT=!!eh.trim()||ew.length>0,tR=es||ec&&f,tA=ew.length>0&&!function(e,t){if(!e)return!0;let n=t?.find(t=>t.provider===e.provider&&t.id===e.modelId);return!n||!n.input||n.input.includes("image")}(m,v)&&!eD;(0,i.useEffect)(()=>{0===ew.length&&eB(!1)},[ew.length]);let tL=(0,i.useCallback)((e,t)=>{if(!er)return void eA(null);let n=t??e.length;eA(t3(e.slice(0,n)))},[er]),tz=eR?.query??null,tP=i.useMemo(()=>null!==tz&&eY&&eY.cwd===er?function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:20,r=t.toLowerCase();if(!r)return e.slice(0,n);let i=[];for(let t of e){let e=function(e,t){let n=e.path.toLowerCase(),r=0;if(t.includes("/"))n===t?r=100:n.startsWith(t)?r=80:n.includes(t)?r=50:t6(t,n)&&(r=10);else{let e=n.lastIndexOf("/"),i=-1===e?n:n.slice(e+1);i===t?r=100:i.startsWith(t)?r=80:i.includes(t)?r=50:n.includes(t)?r=30:t6(t,n)&&(r=10)}return e.isDir&&r>0&&(r+=10),r}(t,r);e>0&&i.push({entry:t,score:e})}return i.sort((e,t)=>t.score-e.score||t5(e.entry.path)-t5(t.entry.path)||e.entry.path.localeCompare(t.entry.path)),i.slice(0,n).map(e=>e.entry)}(eY.entries,tz):[],[tz,eY,er]),tW=!!(tz&&eY?.truncated&&eY.cwd===er);(0,i.useEffect)(()=>{if(!tW||!er||!tz)return;let e=setTimeout(()=>{fetch(`/api/file-index?cwd=${encodeURIComponent(er)}&q=${encodeURIComponent(tz)}`).then(e=>{if(!e.ok)throw Error(`file search failed: ${e.status}`);return e.json()}).then(e=>e1({cwd:er,query:tz,matches:e.matches??[]})).catch(()=>{})},150);return()=>clearTimeout(e)},[tW,tz,er]);let tO=tW&&null!==e0&&e0.cwd===er&&e0.query===tz,tF=tO?e0.matches:tP,tD=null===eR?null:`${eR.start}:${+!!eR.quoted}:${eR.query}`;(0,i.useEffect)(()=>{if(null===tD){ez(!1),eF(0);return}ez(!0),eF(0)},[tD]);let tB=null!==eR;(0,i.useEffect)(()=>{if(!tB||!er)return;let e=tc.current;e&&e.cwd===er&&Date.now()-e.fetchedAt<1e4||tu.current===er||(tu.current=er,eQ(!0),fetch(`/api/file-index?cwd=${encodeURIComponent(er)}`).then(e=>{if(!e.ok)throw Error(`file index failed: ${e.status}`);return e.json()}).then(e=>{eG({cwd:er,entries:function(e){let t=new Set;for(let n of e){let e=n.indexOf("/");for(;-1!==e;)t.add(n.slice(0,e)),e=n.indexOf("/",e+1)}let n=[];for(let e of t)n.push({path:e,isDir:!0});for(let t of e)t&&n.push({path:t,isDir:!1});return n.sort((e,t)=>t5(e.path)-t5(t.path)||e.path.localeCompare(t.path)),n}(e.files??[]),truncated:!!e.truncated}),tc.current={cwd:er,fetchedAt:Date.now()}}).catch(()=>{tc.current=null}).finally(()=>{tu.current=null,eQ(!1)}))},[tB,er]);let tH=(0,i.useCallback)(e=>{if(!eR)return;let t=e3.current;if(!t)return;let n=t.selectionStart??t.value.length,r=n+(eR.quoted&&'"'===t.value[n]?1:0),i=function(e,t){let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2],r=t?`${e}/`:e,i=n||r.includes(" ");if(t){let e=i?`@"${r}"`:`@${r}`;return{text:e,cursorOffset:i?e.length-1:e.length}}let s=i?`@"${r}" `:`@${r} `;return{text:s,cursorOffset:s.length}}(e.path,e.isDir,eR.quoted),s=eR.start+i.cursorOffset;aq(t,eR.start,r,i.text,i.cursorOffset),eA(t3(t.value.slice(0,s)))},[eR]);(0,i.useEffect)(()=>{eO>=tF.length&&eF(Math.max(0,tF.length-1))},[tF.length,eO]),(0,i.useEffect)(()=>{ta.current.length=tF.length},[tF.length]),(0,i.useEffect)(()=>{eL&&ta.current[eO]?.scrollIntoView({block:"nearest",inline:"nearest"})},[eO,eL]),(0,i.useEffect)(()=>{eU>=K.length&&eK(Math.max(0,K.length-1))},[K.length,eU]),(0,i.useEffect)(()=>{td.current.length=K.length},[K.length]),(0,i.useEffect)(()=>{eH&&!Y&&td.current[eU]?.scrollIntoView({block:"nearest",inline:"nearest"})},[eU,eH,Y]);let t_=(0,i.useCallback)(e=>{ef(e),e_(!1),eK(0),eA(null),requestAnimationFrame(()=>{let t=e3.current;t&&(t.focus(),t.setSelectionRange(e.length,e.length),aV(t),aZ(t))})},[]),tU=(0,i.useCallback)(e=>{let t=`/${e.name} `;ef(t),eE(!1),eI(0),requestAnimationFrame(()=>{let e=e3.current;e&&(e.focus(),e.setSelectionRange(t.length,t.length),aV(e))})},[]),tK=(0,i.useCallback)(()=>{let e=eh.trim();e&&!ew.length&&p&&(tw(),p(e))},[eh,ew,p,tw]),tV=(0,i.useCallback)(e=>{let t=eh.trim();if(!t&&!ew.length)return;if(t.startsWith("!")&&!ew.length)return void tS();ee?.();let n=ew.length?ew:void 0,r=()=>{if(t.startsWith("/")&&et){tw(),et(t,"steer"===e?"steer":"followUp",n);return}tw(),"steer"===e&&u?u(t,n):"followup"===e&&h&&h(t,n)};!ew.length&&G&&a0(t)?tj(t):!ew.length&&G&&l2(t)?tj(t).then(e=>{e||r()},()=>r()):r()},[eh,ew,G,et,u,h,tw,ee,tj,tS]),tZ=(0,i.useCallback)(e=>{let t=t$.length-1;if(t<0)return 0;if("left"===e)return Math.max(0,e$-1);if("right"===e)return Math.min(t,e$+1);let n=to.current[e$];if(!n)return"down"===e?Math.min(t,e$+1):Math.max(0,e$-1);let r=n.getBoundingClientRect(),i=r.left+r.width/2,s=r.top+r.height/2,o=-1,l=1/0;for(let n=0;n<=t;n+=1){if(n===e$)continue;let t=to.current[n];if(!t)continue;let r=t.getBoundingClientRect(),a=r.top+r.height/2-s;if("down"===e?a<=4:a>=-4)continue;let d=1e3*Math.abs(a)+Math.abs(r.left+r.width/2-i);d<l&&(o=n,l=d)}return o>=0?o:"down"===e?Math.min(t,e$+1):Math.max(0,e$-1)},[t$.length,e$]),tY=(0,i.useCallback)(e=>{let t=e.nativeEvent,n="Enter"===e.key&&!e.shiftKey,r=ec||"ctrlEnter"===ep?n&&(e.ctrlKey||e.metaKey):n,i=ec?r:n,s=Date.now()-tn.current<100,o=tt.current||t.isComposing||229===t.keyCode;if(i&&(o||s)){s&&e.preventDefault();return}if(eH&&!Y&&!o){if("ArrowDown"===e.key){e.preventDefault(),eK(e=>Math.min(Math.max(0,K.length-1),e+1));return}if("ArrowUp"===e.key){e.preventDefault(),eK(e=>Math.max(0,e-1));return}if("Escape"===e.key){e.preventDefault(),e_(!1);return}if(("Tab"===e.key||i)&&K[eU]){e.preventDefault(),t_(K[eU]);return}}if(eN&&null!==tN&&!Y){if("ArrowDown"===e.key){e.preventDefault(),eI(tZ("down"));return}if("ArrowUp"===e.key){e.preventDefault(),eI(tZ("up"));return}if("ArrowRight"===e.key){e.preventDefault(),eI(tZ("right"));return}if("ArrowLeft"===e.key){e.preventDefault(),eI(tZ("left"));return}if("Escape"===e.key){e.preventDefault(),eE(!1);return}let t=t$[e$];if("Tab"===e.key&&t){e.preventDefault(),tU(t);return}if(i&&t){e.preventDefault(),r&&function(e,t,n){if("builtin"===t.source)return"builtin"===t.source&&e.trim()===`/${t.name}`&&(!n||!0===t.availableWhileStreaming);return l1(t)&&l2(e)}(eh,t,f)?(eE(!1),tS()):tU(t);return}}if(eL&&null!==eR&&!Y&&!o){if("ArrowDown"===e.key){e.preventDefault(),eF(e=>aU(e,tF.length,1));return}if("ArrowUp"===e.key){e.preventDefault(),eF(e=>aU(e,tF.length,-1));return}if("Escape"===e.key){e.preventDefault(),ez(!1);return}if(("Tab"===e.key||i)&&tF[eO]){e.preventDefault(),tH(tF[eO]);return}}if("ArrowUp"===e.key&&!o&&!f&&K.length>0&&0===eh.trim().length){e.preventDefault(),eE(!1),ez(!1),eK(K.length-1),e_(!0);return}if("Escape"===e.key&&!o&&f&&c){e.preventDefault(),c();return}r&&(e.preventDefault(),f&&(u||h)?tV(e.altKey&&h||!u?"followup":"steer"):tS())},[ec,ep,f,u,h,c,Y,eN,tN,t$,e$,tU,tV,tS,tZ,eL,eR,tF,eO,tH,eH,K,eU,t_,eh]),tG=(0,i.useCallback)(()=>{tr.current=null;let e=e3.current;e&&aV(e)},[]),tQ=(0,i.useCallback)(e=>{let t=Array.from(e.clipboardData?.items??[]).filter(e=>e.type.startsWith("image/"));if(!es&&t.length){e.preventDefault(),tx(t.map(e=>e.getAsFile()).filter(e=>null!==e));return}let n=e.clipboardData.getData("text/html"),r=e.clipboardData.getData("text/plain");if(r){let t=e.currentTarget,n=e.nativeEvent,i=t.selectionStart,s=t.selectionEnd,o={};tr.current=o,setTimeout(()=>{tr.current===o&&(tr.current=null,!n.defaultPrevented&&t.isConnected&&aq(t,i,s,r))},0)}if(!n||!r)return;let i=new DOMParser().parseFromString(n,"text/html"),s=function(e,t){let n="",r=0,i=!1;for(let{label:s,href:o,occurrence:l}of t){if(!s||!o)continue;let t=0;for(let n=0;n<=l&&!((t=e.indexOf(s,n?t+s.length:0))<0);n++);if(t<r)continue;let a=s.replace(/([\\[\]])/g,"\\$1"),d=o.replace(/([\\()])/g,"\\$1");n+=`${e.slice(r,t)}[${a}](${d})`,r=t+s.length,i=!0}return i?n+e.slice(r):null}(r,Array.from(i.querySelectorAll("a[href]"),e=>{let t=e.textContent??"",n=i.createRange();return n.setStart(i.body,0),n.setEndBefore(e),{label:t,href:e.getAttribute("href")?.trim()??"",occurrence:t?n.toString().split(t).length-1:0}}));if(null===s)return;let o=e.currentTarget,l=o.selectionStart,a=o.value.slice(0,l)+s+o.value.slice(o.selectionEnd);e.preventDefault(),th.current=a,ef(a),e_(!1),tL(a,l+s.length),requestAnimationFrame(()=>{o.focus(),o.setSelectionRange(l+s.length,l+s.length),aZ(o)})},[es,tx,tL]);(0,i.useEffect)(()=>{if(null===tN){eE(!1),eI(0),ti.current=!1;return}eE(!0),eI(0),!ti.current&&J&&(ti.current=!0,Promise.resolve(J()).catch(()=>{ti.current=!1}))},[tN,J]),(0,i.useEffect)(()=>{if(!eN||!er)return;let e=!1;return e4({cwd:er,values:{}}),fetch(`/api/skills?cwd=${encodeURIComponent(er)}`).then(e=>{if(!e.ok)throw Error(`skills fetch failed: ${e.status}`);return e.json()}).then(t=>{if(e)return;let n={};for(let e of t.skills??[])n[e.name]=e.disableModelInvocation;e4({cwd:er,values:n})}).catch(()=>{e||e4({cwd:er,values:{}})}),()=>{e=!0}},[eN,er]),(0,i.useEffect)(()=>{e$>=t$.length&&eI(Math.max(0,t$.length-1))},[t$.length,e$]),(0,i.useEffect)(()=>{to.current.length=t$.length},[t$.length]),(0,i.useEffect)(()=>{eN&&!Y&&to.current[e$]?.scrollIntoView({block:"nearest",inline:"nearest"})},[e$,eN,Y]),(0,i.useLayoutEffect)(()=>{if(!eN||null===tN||Y)return void eT(null);let e=ts.current;if(e)return aJ(e,e=>{eT(t=>t===e?t:e)})},[eN,tN,Y]),(0,i.useLayoutEffect)(()=>{if(!eL||null===eR||Y)return void eW(null);let e=tl.current;if(e)return aJ(e,e=>{eW(t=>t===e?t:e)})},[eL,eR,Y]);let t0=v&&v.length>0?v.map(e=>({provider:e.provider,providerName:e.providerName,modelId:e.id,name:e.name})):Object.entries(x??{}).map(e=>{let[t,n]=e;return{provider:m?.provider??"unknown",modelId:t,name:n}}),t1=A?Math.max(0,A.tokensBefore-A.estimatedTokensAfter):0,t2=A?`${A.reason&&"manual"!==A.reason?`${A.reason[0].toUpperCase()}${A.reason.slice(1)} `:eo("chat.compacted")} ${aX(A.tokensBefore)} -> ${aX(A.estimatedTokensAfter)} tokens (${eo("chat.tokensSaved",{saved:aX(t1)})})`:null,t4=P&&"auto"!==P?P:null,t8="auto"!==(n=t4??"auto")&&D?D[n]??n:n,t9=Object.entries(aH).find(e=>{let[,t]=e;return t===(L??"configured")})?.[0]??"configured",t7="chat-only"===t9?eo("chat.chatOnly"):t9;(0,i.useEffect)(()=>{let e=e=>{e5.current&&!e5.current.contains(e.target)&&eg(!1),e6.current&&!e6.current.contains(e.target)&&ev(!1),e9.current&&!e9.current.contains(e.target)&&ey(!1),!e7.current||e7.current.contains(e.target)||e3.current?.contains(e.target)||e_(!1)};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]),(0,i.useEffect)(()=>{f&&eg(!1)},[f]);let ne=(0,i.useRef)(-1/0);(0,i.useLayoutEffect)(()=>{if(f)return()=>{ne.current=performance.now()}},[f]);let nt=e=>{var t,n;return t=e.detail,n=performance.now()-ne.current,t>0&&n<600};return(0,i.useEffect)(()=>{ec||ey(!1)},[ec]),(0,r.jsxs)("fieldset",{disabled:eq,"aria-busy":eq,className:es?void 0:"chat-input-shell",style:{...es?{flexShrink:0}:{display:"flex",flexDirection:"column",minHeight:0},minWidth:0,margin:0,border:0,background:"transparent",padding:es?0:"0 16px 8px",paddingRight:es?0:ec?16:52,opacity:eq?.5:1,transition:"opacity 0.15s"},children:[!es&&(0,r.jsx)("input",{ref:te,type:"file",accept:ei?void 0:"image/*",multiple:!0,style:{display:"none"},onChange:tv}),(0,r.jsxs)("div",{style:{...es?void 0:{display:"flex",flexDirection:"column",minHeight:0,width:"100%"},maxWidth:"var(--chat-content-max-width, 820px)",margin:"0 auto"},children:[(0,r.jsx)(di,{cwd:y}),(0,r.jsx)(ds,{error:b}),(0,r.jsx)(dl,{warnings:w}),tA&&(s=v?.find(e=>e.provider===m?.provider&&e.id===m?.modelId),(0,r.jsx)(dr,{tone:"warning",title:eo("chat.imageNotSupportedTitle"),body:eo("chat.imageNotSupportedBody",{model:s?.name||m?.modelId||""}),onClose:()=>eB(!0)})),(U?.steering.length??0)+(U?.followUp.length??0)>0&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",minHeight:72,marginBottom:8,border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-panel)",padding:"5px 0"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,padding:"2px 8px 4px 10px"},children:[(0,r.jsx)("span",{style:{fontSize:10,fontFamily:"var(--font-mono)",color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:.4},children:eo("chat.queued",{count:(U?.steering.length??0)+(U?.followUp.length??0)})}),q&&(0,r.jsxs)("button",{onClick:q,title:eo("chat.recallTitle"),style:{display:"flex",alignItems:"center",gap:6,padding:"4px 12px",fontSize:12,color:"var(--text)",background:"transparent",border:"1px solid var(--border)",borderRadius:7,cursor:"pointer",transition:"background 0.12s, border-color 0.12s",whiteSpace:"nowrap"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.borderColor="color-mix(in srgb, var(--accent) 45%, var(--border))"},onMouseLeave:e=>{e.currentTarget.style.background="transparent",e.currentTarget.style.borderColor="var(--border)"},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("polyline",{points:"9 14 4 9 9 4"}),(0,r.jsx)("path",{d:"M20 20v-7a4 4 0 0 0-4-4H4"})]}),eo("chat.recall")]})]}),(0,r.jsxs)("div",{style:{maxHeight:"min(180px, calc(var(--app-viewport-height, 100dvh) * 0.25))",overflowY:"auto",overscrollBehavior:"contain"},children:[U?.steering.map((e,t)=>(0,r.jsx)(dn,{kind:"steer",text:e},`steer-${t}`)),U?.followUp.map((e,t)=>(0,r.jsx)(dn,{kind:"follow-up",text:e},`followup-${t}`))]})]}),_&&(0,r.jsxs)("div",{style:{marginBottom:8,padding:"5px 10px",background:"rgba(234,179,8,0.08)",border:"1px solid rgba(234,179,8,0.25)",borderRadius:6,fontSize:12,color:"rgba(180,130,0,0.9)",display:"flex",alignItems:"center",gap:6},children:[(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:[(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),(0,r.jsx)("path",{d:"M3 3v5h5"})]}),eo("chat.retrying",{attempt:_.attempt,max:_.maxAttempts}),_.errorMessage&&(0,r.jsxs)("span",{style:{opacity:.7,marginLeft:4},children:["— ",_.errorMessage]})]}),t2&&(0,r.jsxs)("div",{style:{marginBottom:8,padding:"5px 10px",background:"rgba(16,185,129,0.08)",border:"1px solid rgba(16,185,129,0.24)",borderRadius:6,fontSize:12,color:"rgba(5,150,105,0.95)",display:"flex",alignItems:"center",gap:6},children:[(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}),t2]}),T&&(0,r.jsxs)("div",{role:"alert",style:{display:"flex",alignItems:"flex-start",gap:6,marginBottom:8,padding:R?"3px 3px 3px 10px":"7px 10px",background:"rgba(239,68,68,0.07)",border:"1px solid rgba(239,68,68,0.3)",borderRadius:6,color:"#ef4444",fontFamily:"var(--font-mono)",fontSize:12,lineHeight:1.5},children:[(0,r.jsx)("span",{style:{minWidth:0,flex:1,padding:R?"4px 0":0,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:T}),R&&(0,r.jsx)(tq,{onClick:R,title:eo("chat.dismissCompactError")})]}),ew.length>0&&(0,r.jsx)("div",{style:{display:"flex",gap:6,marginBottom:6,flexWrap:"wrap"},children:ew.map((e,t)=>(0,r.jsxs)("div",{style:{position:"relative",flexShrink:0},children:[(0,r.jsx)(sx,{src:e.previewUrl,children:(0,r.jsx)("img",{src:e.previewUrl,alt:"",style:{width:56,height:56,objectFit:"cover",borderRadius:6,border:"1px solid var(--border)",display:"block"}})},e.previewUrl),(0,r.jsx)("button",{type:"button",onClick:()=>tb(t),style:{position:"absolute",top:-4,right:-4,width:16,height:16,borderRadius:"50%",background:"var(--bg-panel)",border:"1px solid var(--border)",display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer",padding:0,color:"var(--text-muted)"},children:(0,r.jsxs)("svg",{width:"8",height:"8",viewBox:"0 0 8 8",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",children:[(0,r.jsx)("line",{x1:"1",y1:"1",x2:"7",y2:"7"}),(0,r.jsx)("line",{x1:"7",y1:"1",x2:"1",y2:"7"})]})})]},t))}),(0,r.jsxs)("div",{style:{position:"relative",minWidth:0},children:[eH&&!Y&&K.length>0&&(0,r.jsxs)("div",{ref:e7,style:{position:"absolute",left:0,right:0,bottom:"calc(100% + 8px)",zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:8,boxShadow:"0 -6px 20px rgba(0,0,0,0.12)",overflow:"hidden",maxHeight:"min(44vh, 360px)"},children:[(0,r.jsx)("div",{title:eo("chat.inputHistory"),style:{height:30,padding:"0 10px",borderBottom:"1px solid var(--border)",display:"flex",alignItems:"center",color:"var(--text-dim)"},children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 3-6.7"}),(0,r.jsx)("path",{d:"M3 4v5h5"}),(0,r.jsx)("path",{d:"M12 7v5l3 2"})]})}),(0,r.jsx)("div",{style:{maxHeight:"calc(min(44vh, 360px) - 31px)",overflowY:"auto",padding:4},children:K.map((e,t)=>{let n=t===eU;return(0,r.jsxs)("button",{ref:e=>{td.current[t]=e},type:"button",onMouseDown:t=>{t.preventDefault(),t_(e)},onMouseEnter:()=>eK(t),style:{width:"100%",display:"flex",alignItems:"flex-start",gap:8,padding:"7px 8px",border:"none",borderRadius:6,background:n?"var(--bg-selected)":"none",color:"var(--text)",cursor:"pointer",textAlign:"left",fontSize:12.5,lineHeight:1.45},children:[(0,r.jsx)("span",{style:{flexShrink:0,fontFamily:"var(--font-mono)",fontSize:11,color:"var(--text-dim)",paddingTop:1},children:t+1}),(0,r.jsx)("span",{style:{minWidth:0,display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:2,overflow:"hidden",overflowWrap:"anywhere"},children:e})]},`${t}:${e}`)})})]}),eN&&null!==tN&&!Y&&(0,r.jsxs)("div",{ref:ts,style:{position:"absolute",left:0,right:0,bottom:"calc(100% + 8px)",zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:8,boxShadow:"0 -6px 20px rgba(0,0,0,0.12)",overflow:"hidden",boxSizing:"border-box",display:"flex",flexDirection:"column",maxHeight:null===eM?"min(72.8vh, 598px)":`min(72.8vh, 598px, ${eM}px)`},children:[(0,r.jsxs)("div",{style:{padding:"8px 10px",borderBottom:"1px solid var(--border)",display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,fontSize:11,color:"var(--text-dim)",flexShrink:0},children:[(0,r.jsx)("span",{children:Z?eo("chat.loadingCommands"):eo("chat.slashCommands",{label:tM})}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:eo("chat.tabEnter")})]}),(0,r.jsx)("div",{style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:10},children:Z||0!==tE.length?tI.map(e=>(0,r.jsxs)("section",{style:{marginBottom:12},children:[(0,r.jsxs)("div",{style:{position:"sticky",top:-10,zIndex:1,display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,padding:"4px 0 6px",background:"var(--bg)",color:"var(--text-dim)",fontSize:10,fontWeight:600,textTransform:"uppercase"},children:[(0,r.jsx)("span",{children:eo(a2[e.source])}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontWeight:500},children:e.items.length})]}),(0,r.jsx)("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(220px, 1fr))",gap:8},children:e.items.map(e=>{let{command:t,index:n}=e,i=n===e$,s=a3(t,e8);return(0,r.jsxs)("button",{ref:e=>{to.current[n]=e},type:"button",onMouseDown:e=>{e.preventDefault(),tU(t)},onMouseEnter:()=>eI(n),style:{width:"100%",minWidth:0,minHeight:58,display:"flex",flexDirection:"column",gap:4,justifyContent:"center",padding:"9px 10px",border:`1px solid ${i?"var(--accent)":"var(--border)"}`,borderRadius:7,background:i?"var(--bg-selected)":"var(--bg-panel)",color:"var(--text)",cursor:"pointer",textAlign:"left",boxShadow:i?"0 0 0 1px color-mix(in srgb, var(--accent) 28%, transparent)":"none"},children:[(0,r.jsxs)("span",{style:{fontSize:13,fontFamily:"var(--font-mono)",overflowWrap:"anywhere",wordBreak:"break-word",color:s?"var(--text-dim)":void 0},children:["/",t.name,s&&(0,r.jsx)("span",{style:{marginLeft:6,padding:"0 4px",border:"1px solid var(--border)",borderRadius:3,fontSize:9,color:"var(--text-dim)",whiteSpace:"nowrap"},children:eo("chat.dormant")})]}),t.description&&(0,r.jsx)("span",{style:{display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:2,overflow:"hidden",fontSize:11,lineHeight:1.35,color:"var(--text-dim)"},children:a8(t,eo)})]},`${t.source}:${t.name}`)})})]},e.source)):(0,r.jsx)("div",{style:{padding:"2px 2px 4px",fontSize:12,color:"var(--text-dim)"},children:eo("chat.noCommands")})})]}),eL&&null!==eR&&!Y&&(o=eX&&(!eY||eY.cwd!==er),l=1===tF.length?eo("chat.match"):eo("chat.matches",{count:tF.length}),a=eY?.truncated&&!tO?eR.query?eo("chat.searchingAll"):eo("chat.indexTruncated"):"",(0,r.jsxs)("div",{ref:tl,style:{position:"absolute",left:0,right:0,bottom:"calc(100% + 8px)",zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:8,boxShadow:"0 -6px 20px rgba(0,0,0,0.12)",overflow:"hidden",boxSizing:"border-box",display:"flex",flexDirection:"column",maxHeight:null===eP?"min(48vh, 400px)":`min(48vh, 400px, ${eP}px)`},children:[(0,r.jsxs)("div",{style:{padding:"8px 10px",borderBottom:"1px solid var(--border)",display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,fontSize:11,color:"var(--text-dim)",flexShrink:0},children:[(0,r.jsx)("span",{children:o?eo("chat.loadingFiles"):eo("chat.files",{label:l,hint:a})}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:eo("chat.tabEnter")})]}),(0,r.jsx)("div",{style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:4},children:o||0!==tF.length?tF.map((e,t)=>{let n=t===eO,i=e.path.split("/").pop()??e.path,s=e.path.slice(0,e.path.length-i.length);return(0,r.jsxs)("button",{ref:e=>{ta.current[t]=e},type:"button",onMouseDown:t=>{t.preventDefault(),tH(e)},onMouseEnter:()=>eF(t),style:{width:"100%",display:"flex",alignItems:"center",gap:8,padding:"6px 8px",border:"none",borderRadius:6,background:n?"var(--bg-selected)":"none",color:"var(--text)",cursor:"pointer",textAlign:"left",fontSize:12.5,fontFamily:"var(--font-mono)"},children:[(0,r.jsx)("span",{style:{flexShrink:0,display:"flex",alignItems:"center"},children:e.isDir?(0,r.jsx)(tJ,{size:14}):tX(i,14)}),(0,r.jsxs)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[s&&(0,r.jsx)("span",{style:{color:"var(--text-dim)"},children:s}),i,e.isDir&&(0,r.jsx)("span",{style:{color:"var(--text-dim)"},children:"/"})]})]},`${e.isDir?"d":"f"}:${e.path}`)}):(0,r.jsx)("div",{style:{padding:"6px 8px",fontSize:12,color:"var(--text-dim)"},children:tW&&!tO?eo("chat.searching"):eo("chat.noMatchingFiles")})})]})),(0,r.jsxs)("div",{className:tR?void 0:"chat-composer-row",style:{minWidth:0,display:"flex",flexDirection:tR?"column":"row",gap:8,alignItems:tR?"stretch":"center",background:"var(--bg)",border:es?"none":`1px solid ${eS?"var(--tool-bg)":f&&(u||h)?"rgba(234,179,8,0.4)":"color-mix(in srgb, var(--border) 70%, transparent)"}`,borderRadius:14*!es,padding:es?0:ec?"6px 6px 6px 12px":"10px 10px 10px 14px",boxShadow:es?"none":"0 1px 2px rgba(15,23,42,0.04), 0 8px 24px -12px rgba(15,23,42,0.10)",transition:"border-color 0.15s, background 0.15s, box-shadow 0.15s"},children:[(0,r.jsx)("textarea",{ref:e3,className:"chat-input-textarea","aria-label":es?eo("chat.askInSideChat"):void 0,value:eh,onChange:e=>{th.current=e.target.value,ef(e.target.value),e_(!1),tL(e.target.value,e.target.selectionStart)},onSelect:e=>{let t=e.currentTarget;tL(t.value,t.selectionStart)},onKeyDown:tY,onCompositionStart:()=>{tt.current=!0},onCompositionEnd:e=>{tt.current=!1,tn.current=Date.now();let t=e.currentTarget;tL(t.value,t.selectionStart)},onInput:tG,onPaste:tQ,placeholder:M?eo("chat.compactingPlaceholder"):f&&(u||h)?eo("chat.steerPlaceholder"):f?eo("chat.agentPlaceholder"):eo("chat.messagePlaceholder"),rows:1,style:{flex:tR?"none":1,minWidth:0,width:"100%",background:"none",border:"none",outline:"none",resize:"none",color:"var(--text)",fontSize:"var(--chat-content-font-size, 14px)",lineHeight:1.6,fontFamily:"inherit",minHeight:es?96:24,maxHeight:200,overflow:"auto"}}),f&&!eS?(0,r.jsxs)("div",{style:{display:"flex",alignItems:"stretch",gap:6,flexShrink:0,alignSelf:"flex-end"},children:[p&&(0,r.jsx)("button",{type:"button",onClick:tK,disabled:!eh.trim()||ew.length>0,title:eo("chat.sideChatHint"),"aria-label":eo("chat.sideChat"),className:`bg-transparent ${eh.trim()&&!ew.length?"cursor-pointer text-text-muted hover:bg-bg-hover hover:text-text":"cursor-not-allowed text-text-dim"}`,style:{width:38,display:"grid",placeItems:"center",padding:0,border:"1px solid var(--border)",borderRadius:8,transition:"background 0.12s"},children:(0,r.jsxs)("svg",{width:"17",height:"17",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M21 12a8 8 0 0 1-8 8H5.5a2 2 0 0 1-1.4-3.4A8 8 0 1 1 21 12z"}),(0,r.jsx)("path",{d:"M13 8.5v7M9.5 12h7"})]})}),u&&(0,r.jsxs)("button",{onClick:()=>tV("steer"),disabled:!tT,title:eo("chat.steerHint"),"aria-label":eo("chat.steer"),style:{display:"flex",alignItems:"center",gap:5,padding:"7px 12px",background:tT?"rgba(234,179,8,0.12)":"none",border:"1px solid rgba(234,179,8,0.35)",borderRadius:8,color:tT?"rgba(180,130,0,1)":"var(--text-dim)",cursor:tT?"pointer":"not-allowed",fontSize:13,fontWeight:600,letterSpacing:"-0.01em",transition:"background 0.12s"},children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("path",{d:"M5 1 L9 5 L5 9"}),(0,r.jsx)("line",{x1:"1",y1:"5",x2:"9",y2:"5"})]}),(0,r.jsx)("span",{className:"chat-composer-run-label",children:eo("chat.steer")})]}),h&&(0,r.jsxs)("button",{onClick:()=>tV("followup"),disabled:!tT,title:`${eo("chat.followUpHint")} (${ec?"Ctrl/Cmd+":""}Alt/Option+Enter)`,"aria-label":eo("chat.followUp"),"aria-keyshortcuts":ec?"Control+Alt+Enter Meta+Alt+Enter":"Alt+Enter",style:{display:"flex",alignItems:"center",gap:5,padding:"7px 12px",background:tT?"rgba(129,140,248,0.12)":"none",border:"1px solid rgba(129,140,248,0.35)",borderRadius:8,color:tT?"rgba(99,102,241,1)":"var(--text-dim)",cursor:tT?"pointer":"not-allowed",fontSize:13,fontWeight:600,letterSpacing:"-0.01em",transition:"background 0.12s"},children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("line",{x1:"5",y1:"1",x2:"5",y2:"6"}),(0,r.jsx)("polyline",{points:"2.5 3.5 5 1 7.5 3.5"}),(0,r.jsx)("line",{x1:"2",y1:"9",x2:"8",y2:"9"})]}),(0,r.jsx)("span",{className:"chat-composer-run-label",children:eo("chat.followUp")})]})]}):(0,r.jsxs)("button",{onClick:tS,disabled:!eh.trim()&&!ew.length,title:eo("chat.send"),"aria-label":eo("chat.send"),style:{flexShrink:0,alignSelf:"flex-end",display:"flex",alignItems:"center",justifyContent:"center",gap:6,...ec?{width:36,height:36,padding:0}:{padding:"7px 14px"},background:eh.trim()||ew.length?"var(--accent)":"var(--bg-panel)",border:"none",borderRadius:8,color:eh.trim()||ew.length?"var(--accent-contrast)":"var(--text-dim)",cursor:eh.trim()||ew.length?"pointer":"not-allowed",fontSize:13,fontWeight:600,letterSpacing:"-0.01em",boxShadow:eh.trim()||ew.length?"0 1px 3px color-mix(in srgb, var(--accent) 25%, transparent)":"none",transition:"background 0.15s, box-shadow 0.15s"},children:[(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("line",{x1:"2",y1:"7",x2:"11",y2:"7"}),(0,r.jsx)("polyline",{points:"7.5 3 12 7 7.5 11"})]}),!ec&&eo("chat.send")]})]})]}),eS&&(0,r.jsxs)("div",{className:"text-xs px-2 py-1",style:{color:eC?"var(--text-muted)":"var(--accent)",marginTop:4},children:[eo("chat.shell")," \xb7 ",eC?eo("chat.outputLocal"):eo("chat.outputModel")]}),!es&&(0,r.jsxs)("div",{className:"chat-input-controls",style:{marginTop:ec?4:8,display:ec?"grid":"flex",gridTemplateColumns:ec?"minmax(0, 1fr) auto":void 0,alignItems:"center",gap:6},children:[(0,r.jsxs)("div",{style:{flex:ec?"1 1 auto":"0 0 auto",minWidth:0,display:"flex",alignItems:"center",gap:2},children:[(0,r.jsx)("button",{onClick:()=>te.current?.click(),title:eo("chat.attachFiles"),style:{flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center",width:eu,height:eu,padding:0,background:"none",border:"none",borderRadius:9,color:ew.length?"var(--accent)":"var(--text-muted)",cursor:"pointer",opacity:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color=ew.length?"var(--accent)":"var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background="none",e.currentTarget.style.color=ew.length?"var(--accent)":"var(--text-muted)"},children:(0,r.jsxs)("svg",{width:ec?18:15,height:ec?18:15,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",ry:"2"}),(0,r.jsx)("circle",{cx:"8.5",cy:"8.5",r:"1.5"}),(0,r.jsx)("polyline",{points:"21 15 16 10 5 21"})]})}),(t0.length>0||m||b)&&S&&(0,r.jsx)(aF,{options:t0,value:m,onChange:S,onReselect:S,busy:C,isAutoSelection:g,defaultValue:N,onSetDefault:E,allOptions:k?.map(e=>({provider:e.provider,providerName:e.providerName,modelId:e.id,name:e.name})),onShowAll:j})]}),!ec&&(0,r.jsx)("div",{style:{flex:1}}),(0,r.jsxs)("div",{ref:e9,style:{flex:"0 0 auto",display:"flex",alignItems:"center",justifyContent:"flex-end",position:"relative",marginLeft:ec?0:"auto"},children:[ec&&(0,r.jsx)("button",{type:"button",title:eb?void 0:eo("chat.moreControls"),"aria-label":eo("chat.moreControls"),"aria-expanded":eb,"aria-hidden":eb||void 0,tabIndex:eb?-1:void 0,onClick:()=>{ey(!0)},style:{display:"flex",alignItems:"center",justifyContent:"center",width:"100%",height:eu,padding:"8px 10px",background:"none",border:"none",borderRadius:9,color:"var(--text-muted)",cursor:eb?"default":"pointer",fontSize:12,fontWeight:500,visibility:eb?"hidden":"visible",pointerEvents:eb?"none":"auto",transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{eb||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{eb||(e.currentTarget.style.background="none",e.currentTarget.style.color="var(--text-muted)")},children:eo("chat.moreControls")}),(0,r.jsxs)("div",{style:{display:ec?eb?"flex":"none":"flex",alignItems:"center",gap:ec?1:2,...ec?{position:"absolute",right:0,bottom:0,zIndex:60,padding:1,width:"max-content",maxWidth:"calc(100vw - 32px)",flexWrap:"nowrap",justifyContent:"flex-end",border:"1px solid color-mix(in srgb, var(--border) 72%, transparent)",borderRadius:10,background:"color-mix(in srgb, var(--bg-panel) 92%, var(--bg))",boxShadow:"0 8px 24px rgba(0,0,0,0.14)",backdropFilter:"blur(10px)"}:null},children:[O&&(0,r.jsxs)("div",{ref:e6,style:{position:"relative"},children:[(0,r.jsxs)("button",{onClick:()=>ev(e=>!e),title:f?eo("chat.currentReasoning",{level:t8}):eo("chat.changeReasoning",{level:t8}),"aria-label":eo("chat.changeReasoningLabel"),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:ec?"0 10px":"8px 12px",width:ec?"auto":void 0,height:eu,background:ex?"var(--bg-hover)":"none",border:"none",borderRadius:9,color:"var(--text-muted)",cursor:"pointer",fontSize:12,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=ex?"var(--bg-hover)":"none",e.currentTarget.style.color="var(--text-muted)"},children:[(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("path",{d:"M9.5 2A5.5 5.5 0 0 0 4 7.5c0 1.7.78 3.21 2 4.21V14a1 1 0 0 0 1 1h5a1 1 0 0 0 1-1v-2.29c1.22-1 2-2.51 2-4.21A5.5 5.5 0 0 0 9.5 2z"}),(0,r.jsx)("line",{x1:"7",y1:"18",x2:"12",y2:"18"}),(0,r.jsx)("line",{x1:"8",y1:"21",x2:"11",y2:"21"})]}),(!ec||eb)&&(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:t8})]}),ex&&(0,r.jsx)("div",{style:{position:"absolute",bottom:"calc(100% + 6px)",...ec?{left:0}:{right:0},zIndex:100,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:8,boxShadow:"0 -4px 16px rgba(0,0,0,0.10)",overflow:"hidden",minWidth:180},children:aY.filter(e=>!F||"auto"===e||F.includes(e)).map(e=>{let t="auto"===e?W:!W&&t4===e,n=eo(aG[e]),i="auto"!==e&&D?D[e]:void 0,s=null!=i&&i!==e?i:e,o=null!=i&&i!==e;return(0,r.jsxs)(aO,{active:t,onSelect:()=>{if(ev(!1),"auto"===e){W||O("auto");return}(!t||W)&&O(e)},gutter:!!H,star:H&&"auto"!==e?{isDefault:B===e,saveLabel:eo("chat.saveDefaultThinking"),defaultLabel:eo("chat.defaultThinking"),onSave:()=>{ev(!1),H(e)}}:void 0,children:[(0,r.jsxs)("span",{style:{flex:1},children:[s,o&&(0,r.jsxs)("span",{style:{fontSize:10,color:"var(--text-dim)",fontFamily:"var(--font-mono)",marginLeft:5},children:["(",e,")"]})]}),(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",marginLeft:8},children:n})]},e)})})]}),!f&&z&&(0,r.jsxs)("div",{ref:e5,style:{position:ec?"static":"relative"},children:[(0,r.jsxs)("button",{onClick:e=>{f||nt(e)||eg(e=>!e)},disabled:f,title:eo("chat.changeToolPreset")+`: ${t7}`,"aria-label":eo("chat.changeToolPreset"),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:ec?"0 10px":"8px 12px",width:ec?"auto":void 0,height:eu,background:em?"var(--bg-hover)":"none",border:"none",borderRadius:9,color:"var(--text-muted)",cursor:f?"not-allowed":"pointer",fontSize:12,opacity:f?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{f||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.background=em?"var(--bg-hover)":"none",e.currentTarget.style.color="var(--text-muted)"},children:[(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)("path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"})}),(!ec||eb)&&(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:t7})]}),em&&(0,r.jsx)("div",{style:{position:"absolute",bottom:"calc(100% + 6px)",right:0,maxWidth:ec?"calc(100vw - 16px)":void 0,zIndex:100,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:8,boxShadow:"0 -4px 16px rgba(0,0,0,0.10)",overflow:"hidden",minWidth:120},children:aB.map(e=>{let t,n=aH[e],i=(L??"configured")===n;return t="configured"===e?eo("chat.configuredTools"):"chat-only"===e?eo("chat.chatOnly"):"read-only"===e?eo("chat.readOnlyTools",{count:4}):"default"===e?eo("chat.builtInTools",{count:4}):eo("chat.allBuiltInTools"),(0,r.jsxs)("button",{onClick:()=>{eg(!1),i||z(n)},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:i?"var(--bg-selected)":"none",border:"none",color:i?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",fontWeight:i?600:400,whiteSpace:"nowrap"},onMouseEnter:e=>{i||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{i||(e.currentTarget.style.background="none")},children:[i?(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),(0,r.jsx)("span",{style:{flex:1},children:e}),(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",marginLeft:8},children:t})]},e)})})]}),(!f||M)&&$&&(0,r.jsx)("div",{children:(0,r.jsx)("button",{onClick:M?I:e=>{nt(e)||$()},style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:ec?"0 10px":"8px 12px",width:ec?"auto":void 0,height:eu,background:M?"rgba(239,68,68,0.08)":"none",border:"none",borderRadius:9,color:M?"#ef4444":"var(--text-muted)",cursor:"pointer",fontSize:12,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background=M?"rgba(239,68,68,0.16)":"var(--bg-hover)",e.currentTarget.style.color=M?"#ef4444":"var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background=M?"rgba(239,68,68,0.08)":"none",e.currentTarget.style.color=M?"#ef4444":"var(--text-muted)"},title:M?eo("chat.stopCompaction"):eo("chat.compactContext"),"aria-label":M?eo("chat.stopCompaction"):eo("chat.compactContext"),children:M?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",children:(0,r.jsx)("rect",{x:"2",y:"2",width:"6",height:"6",rx:"1",fill:"currentColor"})}),(!ec||eb)&&(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:eo("chat.compacting")})]}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("polyline",{points:"4 14 10 14 10 20"}),(0,r.jsx)("polyline",{points:"20 10 14 10 14 4"}),(0,r.jsx)("line",{x1:"10",y1:"14",x2:"3",y2:"21"}),(0,r.jsx)("line",{x1:"21",y1:"3",x2:"14",y2:"10"})]}),(!ec||eb)&&(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:eo("chat.compact")})]})})}),f&&(0,r.jsxs)("button",{onClick:c,title:eo("chat.stopAgent"),style:{display:"flex",alignItems:"center",gap:6,padding:"8px 14px",height:eu,background:"rgba(239,68,68,0.08)",border:"1px solid rgba(239,68,68,0.3)",borderRadius:9,color:"#ef4444",cursor:"pointer",fontSize:12,fontWeight:600,whiteSpace:"nowrap",letterSpacing:"-0.01em",transition:"background 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="rgba(239,68,68,0.16)"},onMouseLeave:e=>{e.currentTarget.style.background="rgba(239,68,68,0.08)"},children:[(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",children:(0,r.jsx)("rect",{x:"1.5",y:"1.5",width:"7",height:"7",rx:"1.5",fill:"currentColor"})}),eo("chat.stop")]}),void 0!==Q&&(0,r.jsx)("button",{onClick:Q,title:X?eo("chat.disableSound"):eo("chat.enableSound"),"aria-label":X?eo("chat.disableSound"):eo("chat.enableSound"),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,width:eu,height:eu,padding:0,background:"none",border:"none",borderRadius:9,color:X?"var(--text-muted)":"var(--text-dim)",cursor:"pointer",opacity:X?1:.55,transition:"background 0.12s, color 0.12s, opacity 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)",e.currentTarget.style.opacity="1"},onMouseLeave:e=>{e.currentTarget.style.background="none",e.currentTarget.style.color=X?"var(--text-muted)":"var(--text-dim)",e.currentTarget.style.opacity=X?"1":"0.55"},children:X?(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),(0,r.jsx)("path",{d:"M15.54 8.46a5 5 0 0 1 0 7.07"}),(0,r.jsx)("path",{d:"M19.07 4.93a10 10 0 0 1 0 14.14"})]}):(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),(0,r.jsx)("line",{x1:"23",y1:"9",x2:"17",y2:"15"}),(0,r.jsx)("line",{x1:"17",y1:"9",x2:"23",y2:"15"})]})}),ec&&eb&&(0,r.jsx)("button",{type:"button",title:eo("chat.collapseControls"),"aria-label":eo("chat.collapseControls"),"aria-expanded":!0,onClick:()=>{eg(!1),ev(!1),ey(!1)},style:{display:"flex",alignItems:"center",justifyContent:"center",width:ec?eu:36,height:eu,padding:0,marginLeft:0,background:"var(--bg-hover)",border:"none",borderLeft:"1px solid color-mix(in srgb, var(--border) 72%, transparent)",borderRadius:"0 9px 9px 0",color:"var(--text)",cursor:"pointer",transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-selected)"},onMouseLeave:e=>{e.currentTarget.style.background="var(--bg-hover)"},children:(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[(0,r.jsx)("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),(0,r.jsx)("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]})]})]})]})]})}));function dd(){try{return window.localStorage}catch{return null}}function dc(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:dd();if(!t)return!1;try{return"true"===t.getItem(e)}catch{return!1}}function du(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:dd();if(n)try{n.setItem(e,String(t))}catch{}}let dp="pi-web:minimap-preview-locked";function dh(e){return dc(dp,e)}var df=n(88576),dm=n.n(df),dg=n(5284),dx=n.n(dg);function dv(e){let{locked:t,iconSize:n=16,className:i,...s}=e;return(0,r.jsx)("button",{...s,type:"button","aria-pressed":t,className:i?`${dx().lock} ${i}`:dx().lock,children:(0,r.jsxs)("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("rect",{x:"4",y:"11",width:"16",height:"10",rx:"2"}),t?(0,r.jsx)("path",{d:"M8 11V7a4 4 0 0 1 8 0v4"}):(0,r.jsx)("path",{d:"M8 11V7a4 4 0 0 1 7.9-.9"})]})})}function db(e){let{level:t,children:n,headingIndex:i,onClick:s}=e;return(0,r.jsx)("button",{type:"button",className:dm().heading,"data-level":t,"data-preview-heading-index":i??void 0,disabled:null===i||!s,onClick:e=>{e.stopPropagation(),null!==i&&s?.(i)},children:n})}let dy=[...si??[],function(){return e=>{if(!Array.isArray(e.children))return;let t=e.children.filter(e=>"heading"===e.type&&"number"==typeof e.depth&&e.depth<=3);if(t.length>0){t.forEach((e,t)=>{e.data={...e.data,hProperties:{...e.data?.hProperties,"data-preview-heading-index":t}}}),e.children=t;return}let n=e.children.find(e=>"paragraph"===e.type);e.children=n?[n]:[]}}],dw=[[iA.A,{throwOnError:!1,strict:!1}]];function dk(e){let t=e?.properties,n=t?.dataPreviewHeadingIndex??t?.["data-preview-heading-index"];return"number"==typeof n?n:"string"==typeof n&&/^\d+$/.test(n)?Number(n):null}let dj=(0,i.memo)(function(e){let{markdown:t,onHeadingClick:n,onAnswerClick:s}=e,o=(0,i.useMemo)(()=>iG(t),[t]);return t?(0,r.jsx)("div",{className:dm().outline,children:(0,r.jsx)(iC.oz,{remarkPlugins:dy,rehypePlugins:dw,components:{h1:e=>{let{children:t,node:i}=e;return(0,r.jsx)(db,{level:1,headingIndex:dk(i),onClick:n,children:t})},h2:e=>{let{children:t,node:i}=e;return(0,r.jsx)(db,{level:2,headingIndex:dk(i),onClick:n,children:t})},h3:e=>{let{children:t,node:i}=e;return(0,r.jsx)(db,{level:3,headingIndex:dk(i),onClick:n,children:t})},h4:()=>null,h5:()=>null,h6:()=>null,p:e=>{let{children:t}=e;return(0,r.jsx)("button",{type:"button",className:dm().paragraph,onClick:s,children:t})},blockquote:()=>null,ul:()=>null,ol:()=>null,pre:()=>null,table:()=>null,hr:()=>null,a:e=>{let{children:t}=e;return(0,r.jsx)(r.Fragment,{children:t})},code:e=>{let{children:t}=e;return(0,r.jsx)(r.Fragment,{children:t})}},children:o})}):null}),dS=(0,i.memo)(function(e){let{messages:t,getStreamingMessage:n,scrollContainer:s,messageRefs:o,onRevealHistory:l,turnsBefore:a,turnAnchors:d}=e,{t:c}=(0,tm.s)(),[u,p]=(0,i.useState)(!1),[h,f]=(0,i.useState)([]),[m,g]=(0,i.useState)(null),[x,v]=(0,i.useState)(600),[b,y]=(0,i.useState)(!1),[w,k]=(0,i.useState)(dh),[j,S]=(0,i.useState)(null),C=(0,i.useRef)(!1),N=(0,i.useRef)(null),E=(0,i.useRef)([]),$=(0,i.useRef)({nodes:[],gap:50,fillsHeight:!1}),I=(0,i.useRef)(null),M=(0,i.useRef)(new Map),T=(0,i.useRef)(null),R=(0,i.useRef)(null),A=(0,i.useRef)(null),L=(0,i.useRef)(t);L.current=t;let z=(0,i.useRef)(d);z.current=d;let P=(0,i.useMemo)(()=>(function(e,t){if(0===e.length)return{nodes:[],gap:50,fillsHeight:!1};let n=Math.max(1,t),r=Math.max(0,n-12-48);if(1===e.length)return{nodes:[{...e[0],topRatio:12/n}],gap:50,fillsHeight:!1};let i=r/(e.length-1),s=Math.min(50,i);return{nodes:e.map((e,t)=>({...e,topRatio:(12+t*s)/n})),gap:s,fillsHeight:i<=50}})(h,x),[h,x]),{nodes:W,gap:O}=P;$.current=P;let F=(0,i.useCallback)(e=>{R.current={index:e,until:Date.now()+1600},g(e)},[]),D=(0,i.useCallback)((e,t)=>{let n=R.current;if(n&&Date.now()<n.until)return void g(n.index);R.current=null;let r=t.filter(e=>null!==e.targetTurn.scrollTop);if(0===r.length)return void g(null);let i=e.scrollTop+.3*e.clientHeight;g(r.reduce((e,t)=>Math.abs((t.targetTurn.scrollTop??0)-i)<Math.abs((e.targetTurn.scrollTop??0)-i)?t:e,r[0]).index)},[]),B=(0,i.useCallback)(()=>{let e=s.current;if(!e)return;let t=e.scrollHeight-e.clientHeight,n=E.current;p(t>20),D(e,n)},[s,D]),H=(0,i.useRef)(null),_=(0,i.useCallback)(()=>{H.current||(H.current=setTimeout(()=>{H.current=null;let e=s.current,t=N.current;if(!e||!t)return;let r=o.current,i=e.getBoundingClientRect(),l=[],a=0,d=null,c=n();for(let[t,n]of(c?[...L.current,c]:L.current).entries()){let s=!0===z.current[t];if(!s&&"assistant"!==n.role)continue;let o=null;if(r0(n,s)&&(o=r?.[a]??null,a++),s){d=null;let t=o?.getBoundingClientRect();d={userMessage:n,assistantPreviews:[],scrollTop:t?t.top-i.top+e.scrollTop:null,toolCount:0},l.push(d);continue}if(!d)continue;null===d.scrollTop&&o&&rG(d.userMessage)&&(d.scrollTop=o.getBoundingClientRect().top-i.top+e.scrollTop),d.toolCount+="assistant"===n.role&&Array.isArray(n.content)?n.content.reduce((e,t)=>e+ +("toolCall"===t.type),0):0;let c=function(e){if("assistant"!==e.role)return"";let{answerBlocks:t}=r6(e);return t.filter(e=>"text"===e.type).map(e=>e.text).join("\n\n").trim()}(n);c&&d.assistantPreviews.push({markdown:c,element:o})}let u=l.map((e,t)=>({topRatio:0,targetTurn:e,index:t}));v(t.clientHeight),E.current=u,f(u),p(e.scrollHeight-e.clientHeight>20),D(e,u);let h=A.current,m=h?u[h.nodeIndex]:null;if(h&&m){let t=void 0===h.assistantIndex?null:m.targetTurn.assistantPreviews[h.assistantIndex],n=m.targetTurn.scrollTop;if("assistant"===h.target){let r=t?.element?.getBoundingClientRect();n=r?r.top-i.top+e.scrollTop:null}else if("heading"===h.target){let r=void 0===h.headingIndex?null:t?.element?.querySelectorAll("h1, h2, h3").item(h.headingIndex),s=r?.getBoundingClientRect();n=s?s.top-i.top+e.scrollTop:null}if(null===n)return;A.current=null,F(m.index);let r=.3*e.clientHeight;e.scrollTo({top:Math.max(0,n-r),behavior:"smooth"})}},150))},[n,F,o,s,D]);(0,i.useEffect)(()=>{let e=s.current;if(e)return e.addEventListener("scroll",B,{passive:!0}),()=>e.removeEventListener("scroll",B)},[s,B]),(0,i.useEffect)(()=>{let e=s.current;if(!e)return;let t=()=>{_(),B()},n=new ResizeObserver(t);return n.observe(e),e.firstElementChild&&n.observe(e.firstElementChild),t(),()=>{n.disconnect(),H.current&&(clearTimeout(H.current),H.current=null)}},[_,s,B]),(0,i.useEffect)(()=>{let e=setTimeout(()=>{_(),B()},50);return()=>clearTimeout(e)},[t.length,d,_,B]);let U=(0,i.useCallback)((e,t)=>{let n=s.current;if(!n)return;if(F(e.index),null===e.targetTurn.scrollTop){A.current={nodeIndex:e.index,target:"user"},l();return}let r=Math.max(0,e.targetTurn.scrollTop-.3*n.clientHeight);n.scrollTo({top:r,behavior:t})},[F,l,s]),K=(0,i.useCallback)((e,t)=>{let n=s.current;if(!n)return;let r=e.targetTurn.assistantPreviews[t]?.element;if(!r){A.current={nodeIndex:e.index,target:"assistant",assistantIndex:t},l();return}let i=n.getBoundingClientRect(),o=r.getBoundingClientRect().top-i.top+n.scrollTop-.3*n.clientHeight;F(e.index),n.scrollTo({top:Math.max(0,o),behavior:"smooth"})},[F,l,s]),q=(0,i.useCallback)(e=>{let{nodes:t,gap:n,fillsHeight:r}=$.current,i=N.current?.clientHeight??0;if(0===t.length||i<=0)return null;let s=Math.max(0,Math.min(i,e*i)),o=t[0].topRatio*i,l=n>0?Math.round((s-o)/n):0,a=Math.max(0,Math.min(t.length-1,l)),d=t[a];if(!r&&Math.abs(s-d.topRatio*i)>Math.max(10,n/2))return null;return d},[]),V=(0,i.useCallback)((e,t,n)=>{let r=s.current;if(!r)return;let i=e.targetTurn.assistantPreviews[t]?.element;if(!i){A.current={nodeIndex:e.index,target:"heading",assistantIndex:t,headingIndex:n},l();return}let o=i.querySelectorAll("h1, h2, h3").item(n);if(!o)return;let a=r.getBoundingClientRect(),d=o.getBoundingClientRect().top-a.top+r.scrollTop-.3*r.clientHeight;F(e.index),r.scrollTo({top:Math.max(0,d),behavior:"smooth"})},[F,l,s]),Z=(0,i.useCallback)(()=>{T.current&&(clearTimeout(T.current),T.current=null)},[]),J=(0,i.useCallback)(()=>{w||(Z(),y(!0))},[Z,w]),Y=(0,i.useCallback)(()=>{let e=!w;k(e),du(dp,e,void 0),e&&(Z(),y(!1),S(null))},[Z,w]),G=(0,i.useCallback)(()=>{Z(),T.current=setTimeout(()=>{T.current=null,y(!1),S(null)},250)},[Z]);(0,i.useEffect)(()=>()=>Z(),[Z]);let X=(0,i.useCallback)(e=>{if(!u)return;C.current=!0,J();let t=e.currentTarget.getBoundingClientRect();S(Math.max(0,Math.min(1,(e.clientY-t.top)/t.height)));let n=(e,n)=>{let r=q(Math.max(0,Math.min(1,(e-t.top)/t.height)));r&&U(r,n)};n(e.clientY,"smooth");let r=e=>{C.current&&n(e.clientY,"auto")},i=()=>{C.current=!1,window.removeEventListener("mousemove",r),window.removeEventListener("mouseup",i)};window.addEventListener("mousemove",r),window.addEventListener("mouseup",i)},[q,U,J,u]),Q=null===j?null:q(j),ee=Q?.index??null;if((0,i.useEffect)(()=>{if(!b||null===ee)return;let e=I.current,t=M.current.get(ee);if(!e||!t)return;let n=t.offsetTop-(e.clientHeight-t.offsetHeight)/2;e.scrollTop=Math.max(0,n)},[h,b,ee]),!u)return null;let et=Math.max(1,(W.length>0?W[W.length-1].topRatio*x:12)-12);return(0,r.jsxs)("div",{ref:N,onMouseDown:X,onMouseEnter:J,onMouseLeave:G,onMouseMove:e=>{let t=e.currentTarget.getBoundingClientRect();S((e.clientY-t.top)/t.height)},style:{width:36,flexShrink:0,position:"relative",cursor:"pointer",userSelect:"none",borderLeft:"1px solid var(--border)",background:"var(--bg-panel)",overflow:"visible"},children:[a>0&&(0,r.jsx)("div",{"data-minimap-earlier":"",style:{position:"absolute",left:"50%",top:0,height:12,width:1,background:"repeating-linear-gradient(to bottom, var(--text-dim) 0 2px, transparent 2px 4px)",transform:"translateX(-50%)",zIndex:0}}),(0,r.jsx)("div",{style:{position:"absolute",left:"50%",top:12,height:et,width:1,background:"var(--border)",transform:"translateX(-50%)",zIndex:0}}),W.map(e=>{let t=b&&Q?.index===e.index,n=m===e.index;return(0,r.jsx)("div",{"data-minimap-node-index":e.index,"data-minimap-node-active":n?"":void 0,style:{position:"absolute",top:`${100*e.topRatio}%`,transform:"translateY(-50%)",left:0,right:0,height:Math.max(1,O),display:"flex",alignItems:"center",justifyContent:"center",pointerEvents:"none",zIndex:2},children:(0,r.jsx)("div",{style:{width:8,height:8,borderRadius:2,background:n?"rgba(128,128,128,0.42)":"rgba(128,128,128,0.16)",border:`1.5px solid ${n?"rgba(128,128,128,0.95)":"rgba(128,128,128,0.58)"}`,boxShadow:n?"0 0 0 2px var(--bg-panel)":"none",transition:"transform 0.1s, background 0.1s",transform:t?"scale(1.25)":"scale(1)"}})},e.index)}),(0,r.jsx)(dv,{locked:w,className:dm().lock,"data-minimap-lock":w?"on":"off",title:c(w?"chatMinimap.unlockPreview":"chatMinimap.lockPreview"),"aria-label":c("chatMinimap.lockPreview"),onMouseDown:e=>e.stopPropagation(),onClick:e=>{e.stopPropagation(),Y()}}),b&&h.length>0&&(0,r.jsxs)("div",{ref:I,className:dm().preview,"data-minimap-preview-box":"",onMouseEnter:J,onMouseDown:e=>e.stopPropagation(),onMouseMove:e=>e.stopPropagation(),children:[a>0&&(0,r.jsx)("button",{type:"button",className:dm().earlier,"data-minimap-preview-earlier":"",onClick:()=>s.current?.scrollTo({top:0,behavior:"smooth"}),children:c("chatMinimap.earlierTurns",{count:a})}),h.map(e=>{var t;let n=ee===e.index;return(0,r.jsxs)("div",{ref:t=>{t?M.current.set(e.index,t):M.current.delete(e.index)},className:dm().turn,"data-minimap-preview-index":e.index,"data-located":n?"true":void 0,children:[(0,r.jsxs)("span",{className:dm().number,children:[(0,r.jsx)("span",{"aria-hidden":"true",children:String(a+e.index+1).padStart(2,"0")}),e.targetTurn.toolCount>0&&(0,r.jsx)("span",{className:dm().toolBadge,role:"img",title:c("chatMinimap.toolCalls",{count:e.targetTurn.toolCount}),"aria-label":c("chatMinimap.toolCalls",{count:e.targetTurn.toolCount}),children:e.targetTurn.toolCount>99?"99+":e.targetTurn.toolCount})]}),(0,r.jsxs)("div",{className:dm().content,children:[(0,r.jsx)("button",{type:"button",className:dm().user,"data-minimap-preview-user":e.index,onClick:()=>{U(e,"smooth")},children:(0,r.jsx)("span",{className:dm().userText,children:rG(e.targetTurn.userMessage)?c("chatMinimap.extensionTurn",{type:e.targetTurn.userMessage.customType}):"string"==typeof(t=e.targetTurn.userMessage).content?t.content.trim():t.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n").trim()})}),e.targetTurn.assistantPreviews.map((t,n)=>(0,r.jsxs)("div",{className:dm().assistant,children:[(0,r.jsx)("button",{type:"button",className:dm().assistantJump,"data-minimap-preview-assistant":`${e.index}-${n}`,onClick:()=>K(e,n),"aria-label":c("chatMinimap.locateAssistant"),title:c("chatMinimap.locateAssistant"),children:"A"}),(0,r.jsx)(dj,{markdown:t.markdown,onAnswerClick:()=>K(e,n),onHeadingClick:t=>V(e,n,t)})]},n))]})]},e.index)})]})]})});var dC=n(42790);function dN(e){let{text:t}=e,n=(0,i.useMemo)(()=>{let e=new dC.v;e.use_classes=!0;let n=t.replace(rB,"");return e.ansi_to_html(n).replaceAll('<a href="','<a target="_blank" rel="noopener noreferrer" href="')},[t]);return(0,r.jsx)("span",{dangerouslySetInnerHTML:{__html:n}})}function dE(e){let t,n,s,{widgets:o,children:l}=e,{t:a}=(0,tm.s)(),d=(0,i.useId)(),c=(0,i.useRef)(null),u=(0,i.useRef)(new Map),[p,h]=(0,i.useState)(()=>o.find(e=>{let t=e.lines.length;return t>1&&t<=3})?.key??null),[f,m]=(0,i.useState)(()=>new Set);if((0,i.useEffect)(()=>{var e;let t=new Map(o.map(e=>[e.key,[...e.lines]])),n=(e=c.current,e?Array.from(t,t=>{let[n,r]=t,i=e.get(n);return i&&i.length===r.length?r.some((e,t)=>e!==i[t])?n:null:i?n:null}).filter(e=>null!==e):[]);for(let[e,n]of(c.current=t,u.current))t.has(e)||(clearTimeout(n),u.current.delete(e));for(let e of(m(e=>{let r=new Set(Array.from(e).filter(e=>t.has(e)));for(let e of n)r.add(e);return r.size===e.size&&Array.from(r).every(t=>e.has(t))?e:r}),n)){let t=u.current.get(e);t&&clearTimeout(t),u.current.set(e,setTimeout(()=>{u.current.delete(e),m(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n})},1100))}},[o]),(0,i.useEffect)(()=>()=>{for(let e of u.current.values())clearTimeout(e);u.current.clear()},[]),0===o.length)return null;let g=o.find(e=>e.key===p&&e.lines.length>0);return(0,r.jsxs)(r.Fragment,{children:[g&&(0,r.jsx)("div",{className:"extension-widget-panels",children:(t=o.indexOf(g),n=`${d}-trigger-${t}`,s=`${d}-panel-${t}`,(0,r.jsxs)("section",{id:s,className:"extension-widget-panel","aria-labelledby":n,children:[(0,r.jsx)("div",{className:"extension-widget-panel-heading",children:g.key}),(0,r.jsx)("pre",{className:"extension-widget-content",children:(0,r.jsx)(dN,{text:g.lines.join("\n")})})]},g.key))}),(0,r.jsxs)("div",{className:"extension-status-row",children:[(0,r.jsx)("div",{className:"extension-widget-triggers","aria-label":a("chat.extensionWidgets"),children:o.map((e,t)=>{let n=e.lines.length>0,i=n&&e.key===g?.key,s=f.has(e.key),o=a(1===e.lines.length?"chat.extensionWidgetLine":"chat.extensionWidgetLines",{count:e.lines.length}),l=a("belowEditor"===e.placement?"chat.extensionWidgetBelow":"chat.extensionWidgetAbove"),c=`${d}-trigger-${t}`,u=`${d}-panel-${t}`,p=(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{className:"extension-widget-update-pulse","aria-hidden":"true"}),(0,r.jsx)("span",{className:"extension-widget-placement","aria-hidden":"true",children:(0,r.jsx)("svg",{className:"extension-widget-placement-icon",viewBox:"0 0 8 6",width:"8",height:"6","data-direction":"belowEditor"===e.placement?"down":"up",focusable:"false",children:(0,r.jsx)("path",{d:"belowEditor"===e.placement?"M0 0h8L4 6z":"M4 0l4 6H0z"})})}),(0,r.jsx)("span",{className:"extension-widget-key",children:e.key})]});return n?(0,r.jsx)("button",{id:c,type:"button",className:`extension-widget-trigger${i?" is-expanded":""}${s?" is-updating":""}`,"aria-controls":u,"aria-expanded":i,"aria-label":`${l}: ${e.key}, ${o}`,title:`${e.key} - ${l} - ${i?a("i18n.collapse"):a("i18n.expand")}`,onClick:()=>{h(t=>{var n;return t===(n=e.key)?null:n})},children:p},e.key):(0,r.jsx)("div",{className:`extension-widget-trigger${s?" is-updating":""}`,"aria-label":`${l}: ${e.key}, ${o}`,title:`${e.key} - ${l}`,children:p},e.key)})}),l]})]})}let d$="command:";function dI(e){let{statuses:t,widgets:n=[],onCommand:i,commandsDisabled:s=!1}=e,o=function(e){let t=[];for(let n of[...e].sort((e,t)=>e.key.localeCompare(t.key))){let e=n.text.replace(/\r\n?/g,"\n").split("\n").map(e=>e.replace(/\t/g," ").replace(/ +/g," ").trim()).join("\n").trim(),r=function(e){if(!e.startsWith(d$))return null;let t=e.slice(d$.length).trim();return t.length>1&&t.startsWith("/")?t:null}(n.key);if(r){let n=rH(e).replace(/\s+/g," ").trim();t.push({kind:"command",command:r,label:n||r})}else rH(e).trim()&&t.push({kind:"text",text:e})}return t}(t);if(0===o.length&&0===n.length)return null;let l=o.some(e=>"command"===e.kind),a=o.map(e=>"text"===e.kind?rH(e.text):e.label).join(" "),d=o.length>0?(0,r.jsx)("div",{role:"status",className:"extension-status-line","aria-label":a,title:a,children:(0,r.jsx)("span",{className:"extension-status-text",children:o.map((e,t)=>"text"===e.kind?(0,r.jsx)("span",{className:"extension-status-item",children:(0,r.jsx)(dN,{text:e.text})},t):(0,r.jsx)("button",{type:"button",className:"extension-status-item extension-status-command",disabled:!i||s,title:`${e.label} \xb7 ${e.command}`,"aria-label":`${e.label} (${e.command})`,onClick:()=>i?.(e.command),children:e.label},t))})}):null;return(0,r.jsx)("div",{className:`extension-status-shelf${n.length>0?" has-widgets":""}${o.length>0?" has-status":""}${l?" has-commands":""}`,children:n.length>0?(0,r.jsx)(dE,{widgets:n,children:d}):d})}function dM(e,t){return e?.kind==="running_tools"&&e.tools.length>0?e:t?{kind:"waiting_model"}:{kind:"running_command"}}function dT(e){switch(e.method){case"select":case"confirm":case"input":case"editor":return!0;case"custom":return!0!==e.closed;default:return!1}}function dR(e,t){return e.every(e=>t.has(e.id))?e:e.filter(e=>t.has(e.id))}function dA(e,t){return e.some(e=>e.id===t)?e.filter(e=>e.id!==t):e}function dL(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function dz(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if("assistant"!==e.role)return e;let n=e.content;if(!Array.isArray(n))return e;let r=n.map(e=>(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!dL(e)||"toolCall"!==e.type)return null;let n={type:"toolCall",toolCallId:"string"==typeof e.toolCallId?e.toolCallId:"string"==typeof e.id?e.id:"",toolName:"string"==typeof e.toolName?e.toolName:"string"==typeof e.name?e.name:"",input:"object"!=typeof e.input||null===e.input||Array.isArray(e.input)?"object"!=typeof e.arguments||null===e.arguments||Array.isArray(e.arguments)?{}:e.arguments:e.input},r=t.includeStreamingRawInput?function(e){if("string"==typeof e.rawInput)return e.rawInput;if("string"==typeof e.partialJson)return e.partialJson;if("string"==typeof e.partialArgs)return e.partialArgs;let t=dL(e.customInput)?e.customInput:null,n=t&&"string"==typeof t.property?t.property:null,r=dL(e.arguments)?e.arguments:null;return n&&r&&"string"==typeof r[n]?r[n]:void 0}(e):void 0;return void 0===r?n:{...n,rawInput:r}})(e,t)??e);return{...e,content:r}}function dP(e){if(!e||"object"!=typeof e)return null;let{reason:t,cwd:n}=e;return"cwd-missing"===t&&"string"==typeof n&&n?n:null}class dW extends Error{constructor(e,t,n,r,i){super(e),this.status=t,this.code=n,this.accepted=r,this.missingCwd=i,this.name="AgentCommandError"}}function dO(e){return e instanceof dW&&"prompt_rejected"===e.code&&!1===e.accepted}function dF(e){return`/api/agent/${encodeURIComponent(e)}?systemPrompt=0`}async function dD(e,t){let n=await fetch(`/api/agent/${encodeURIComponent(e)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),r=await n.json().catch(()=>({}));if(!n.ok||r.error)throw new dW(r.error??`HTTP ${n.status}`,n.status,r.code,r.accepted,dP(r)??void 0);return r.data}let dB={not_found:"sideChat.error.notFound",unsaved:"sideChat.error.unsaved",empty:"sideChat.error.empty",subagent:"sideChat.error.subagent",side:"sideChat.error.side"};async function dH(e,t,n){let r=await fetch(`/api/sessions/${encodeURIComponent(e)}/fork`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({side:!0,...n?{name:n}:{}}),cache:"no-store"}),i=await r.json().catch(()=>null);return r.ok&&i?.sessionId&&i.session?{session:i.session}:{error:i?.code&&i.code in dB?t(dB[i.code]):i?.error??`HTTP ${r.status}`}}async function d_(e){let t=await fetch(`/api/sessions/${encodeURIComponent(e)}`,{method:"DELETE",cache:"no-store"});if(t.ok)return null;let n=await t.json().catch(()=>null);return{error:n?.error??`HTTP ${t.status}`}}function dU(){return globalThis.__piSessionViewCache||(globalThis.__piSessionViewCache=new Map),globalThis.__piSessionViewCache}let dK=new WeakMap;function dq(e){let t,n=dK.get(e);if(void 0!==n)return n;try{t=JSON.stringify(e).length}catch{t=Number.MAX_SAFE_INTEGER}return dK.set(e,t),t}function dV(e){let t=dU().get(e);return t?Date.now()-t.savedAt>6e5?(dU().delete(e),null):(dU().delete(e),dU().set(e,t),t):null}function dZ(e){if(!e.sessionId||!e.revision)return!1;let t=dU();t.delete(e.sessionId);let n={...e,savedAt:Date.now()};return!(dq(n)>0x2000000)&&(t.set(n.sessionId,n),!function(){let e=dU();for(;e.size>8;){let t=e.keys().next().value;if(void 0===t)break;e.delete(t)}let t=0;for(let n of e.values())t+=dq(n);for(;t>0x2000000&&e.size>0;){let n=e.keys().next().value;if(void 0===n)break;let r=e.get(n);e.delete(n),r&&(t-=dq(r))}}(),dU().has(n.sessionId))}function dJ(e){dU().delete(e)}var dY=n(14755);let dG="pi-tool-preset";function dX(){try{return window.localStorage}catch{return null}}function dQ(e,t){t&&(e.tokens.input+=t.input??0,e.tokens.output+=t.output??0,e.tokens.cacheRead+=t.cacheRead??0,e.tokens.cacheWrite+=t.cacheWrite??0,e.cost+=t.cost?.total??0)}function d0(e){let t={userMessages:0,assistantMessages:0,toolCalls:0,toolResults:0,totalMessages:0,tokens:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0},cost:0};for(let n of e)"custom"!==n.role&&(t.totalMessages+=1,"user"===n.role?t.userMessages+=1:"toolResult"===n.role?(t.toolResults+=1,dQ(t,n.usage)):"assistant"===n.role&&(t.assistantMessages+=1,Array.isArray(n.content)&&(t.toolCalls+=n.content.filter(e=>"toolCall"===e.type).length),dQ(t,n.usage)));return t.tokens.total=t.tokens.input+t.tokens.output+t.tokens.cacheRead+t.tokens.cacheWrite,t}function d1(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(0)}k`:String(e)}function d2(e){return e>0?e>=.01?`$${e.toFixed(2)}`:"<$0.01":null}function d4(e){if(e<=0)return"0s";let t=Math.floor(e/1e3),n=Math.floor(t/3600),r=Math.floor(t%3600/60),i=t%60;return n>0?`${n}h ${r}m`:r>0?`${r}m ${i}s`:`${i}s`}function d8(e){if(!e||"object"!=typeof e||"image"!==e.type)return"";let t=e.source;return t&&"object"==typeof t?["url"===t.type?"url":"base64","string"==typeof t.media_type?t.media_type:"","string"==typeof t.data?t.data:"","string"==typeof t.url?t.url:""].join(":"):["base64","string"==typeof e.mimeType?e.mimeType:"","string"==typeof e.data?e.data:"",""].join(":")}function d3(e){let t,n=e.content;return"string"==typeof n?JSON.stringify({text:n,images:[]}):Array.isArray(n)?JSON.stringify({text:"string"==typeof(t=e.content)?t:Array.isArray(t)?t.map(e=>e&&"object"==typeof e&&"text"===e.type&&"string"==typeof e.text?e.text:"").filter(Boolean).join("\n"):"",images:n.map(d8).filter(Boolean)}):JSON.stringify({text:"",images:[]})}let d5=(e,t)=>`live:${e??""}:${t}`;class d6 extends Error{constructor(e,t){super(t??("ready_timeout"===e?"Timed out starting the agent session. Please try again.":"Failed to connect to the agent event stream. Please try again.")),this.status=e,this.name="AgentEventConnectionError"}}class d9{constructor(e){this.options=e,this.current=null,this.retry=null,this.retryGeneration=0,this.endedSessionId=null,this.opens=0,this.retries=0,this.lastError=null,this.lastClose=null}close(e){let t=null!==this.lastError&&!(this.lastClose&&this.lastClose.at>=this.lastError.at);(this.current||this.retry||t)&&(this.lastClose={reason:e??null,at:Date.now()}),this.stopRetrying(),this.current&&this.discard(this.current,new d6("closed"))}snapshot(){let e=this.current,t=this.retry;return{sessionId:e?.sessionId??t?.sessionId??null,state:e?e.attempt.ready?"connected":"connecting":t?"retrying":"idle",readyState:e?e.source.readyState:null,openedAt:e?.openedAt??null,connectedAt:e?.connectedAt??null,lastSeenAt:e?.lastSeenAt??null,lastHeartbeatAt:e?.lastHeartbeatAt??null,events:e?.events??0,opens:this.opens,retries:this.retries,retryDueAt:t?.dueAt??null,watchdogArmed:!!(e&&null!==e.watchdog),staleAfterMs:this.options.staleAfterMs??null,lastError:this.lastError?{...this.lastError}:null,lastClose:this.lastClose?{...this.lastClose}:null}}maintain(e){if(this.endedSessionId===e||!this.options.shouldMaintain(e))return;let t=this.retryGeneration;this.ensureConnected(e).catch(n=>{t===this.retryGeneration&&(n instanceof d6?"startup_error"===n.status?this.stopRetrying():this.scheduleRetry(e):this.options.onUnexpectedError?.(n))})}async ensureConnected(e){if(this.endedSessionId===e)throw new d6("closed");for(;;){let t=this.current;if(t&&t.sessionId===e){if(t.attempt.ready&&1===t.source.readyState)return}else t=this.open(e);if(await t.attempt.promise,this.current!==t){if(this.current?.sessionId===e)continue;throw new d6("closed")}if(1===t.source.readyState)return;this.lastClose={reason:"stuck",at:Date.now()},this.discard(t,new d6("closed"))}}open(e){let t,n,r;this.current&&(this.lastClose={reason:"replaced",at:Date.now()},this.discard(this.current,new d6("closed")));try{t=this.options.createSource(e)}catch(t){let e=t instanceof Error?t.message:String(t);throw this.lastError={reason:"error",message:e,at:Date.now()},new d6("closed",e)}this.opens+=1;let i=!1,s=new Promise((e,t)=>{n=e,r=t}),o=setTimeout(()=>{this.fail(d,new d6("ready_timeout"),"ready_timeout")},this.options.readinessTimeoutMs),l={promise:s,ready:!1,succeed(){i||(i=!0,clearTimeout(o),n())},fail(e){i||(i=!0,clearTimeout(o),r(e))}},a=Date.now(),d={sessionId:e,source:t,attempt:l,watchdog:null,openedAt:a,connectedAt:null,lastSeenAt:null,lastHeartbeatAt:null,events:0};return this.current=d,t.onmessage=t=>{let n;if(this.current===d){d.lastSeenAt=Date.now();try{n=JSON.parse(t.data)}catch{return}if("session_ended"===n.type&&n.sessionId===e){this.endedSessionId=e,this.close(),this.options.onEvent(n);return}if("heartbeat"===n.type){d.lastHeartbeatAt=d.lastSeenAt;return}if("connected"===n.type){d.connectedAt??=d.lastSeenAt,l.ready=!0,l.succeed(),this.stopRetrying();let e=this.options.staleAfterMs;e&&null===d.watchdog&&(d.watchdog=setInterval(()=>{Date.now()-(d.lastSeenAt??a)>e&&this.fail(d,new d6("closed"),"stale")},Math.max(1e3,Math.floor(e/3))))}else if("startup_error"===n.type){let e="string"==typeof n.errorMessage?n.errorMessage:void 0;this.fail(d,new d6("startup_error",e),"startup_error");return}d.events+=1,this.options.onEvent(n)}},t.onerror=()=>{this.fail(d,new d6("closed"),"error")},d}fail(e,t,n){this.current===e&&(this.lastError={reason:n,message:"startup_error"===n?t.message:null,at:Date.now()},this.discard(e,t),"startup_error"===t.status?this.stopRetrying():this.scheduleRetry(e.sessionId))}discard(e,t){null!==e.watchdog&&clearInterval(e.watchdog),e.watchdog=null,e.attempt.fail(t),e.source.close(),this.current===e&&(this.current=null)}scheduleRetry(e){if(!this.options.shouldMaintain(e)||this.retry?.sessionId===e)return;this.clearRetry();let t=setTimeout(()=>{this.retry?.timer===t&&(this.retry=null,this.retries+=1,this.maintain(e))},this.options.reconnectDelayMs);this.retry={sessionId:e,timer:t,dueAt:Date.now()+this.options.reconnectDelayMs}}stopRetrying(){this.retryGeneration+=1,this.clearRetry()}clearRetry(){this.retry&&clearTimeout(this.retry.timer),this.retry=null}}function d7(e){return!!e&&"unanswered"!==e&&!!(e.running||e.awaitingInput||e.subagentsActive)}function ce(e){return"u"<typeof document?()=>{}:(document.addEventListener("visibilitychange",e),()=>document.removeEventListener("visibilitychange",e))}let ct=()=>"hidden"===document.visibilityState,cn=()=>!1;function cr(e){return("tool_execution_start"===e.type||"tool_execution_update"===e.type||"tool_execution_end"===e.type)&&"string"==typeof e.parentToolCallId&&""!==e.parentToolCallId}function ci(e){var t;return("message_start"===e.type||"message_end"===e.type)&&"object"==typeof(t=e.message)&&null!==t&&!Array.isArray(t)&&"system"===e.message.role}function cs(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}let co=/^(?:custom-ui|extension-widget):/;function cl(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:8;return e+t>=n-r}let ca={isStreaming:!1,streamingMessage:null};function cd(e,t,n){let r=e.streamingMessage;if(!r||!Number.isInteger(t)||t<0)return e;let i=[...r.content],s=n(i[t]);return s?(i[t]=s,{isStreaming:!0,streamingMessage:{...r,content:i}}):e}function cc(){let e=ca,t=new Set;return{getState:()=>e,dispatch(n){let r=function(e,t){switch(t.type){case"start":return{isStreaming:!0,streamingMessage:null};case"resume":return{...e,isStreaming:!0};case"snapshot":{let n=dz(t.message,{includeStreamingRawInput:!0});return"assistant"===n.role?{isStreaming:!0,streamingMessage:n}:e}case"delta":var n=t.event;switch(n.type){case"text_start":return cd(e,n.contentIndex,()=>({type:"text",text:""}));case"text_delta":return cd(e,n.contentIndex,e=>e?.type==="text"?{...e,text:e.text+n.delta}:null);case"text_end":return cd(e,n.contentIndex,e=>({...e?.type==="text"?e:{},type:"text",text:n.content}));case"thinking_start":return cd(e,n.contentIndex,()=>({type:"thinking",thinking:""}));case"thinking_delta":return cd(e,n.contentIndex,e=>e?.type==="thinking"?{...e,thinking:e.thinking+n.delta}:null);case"thinking_end":return cd(e,n.contentIndex,e=>({...e?.type==="thinking"?e:{},type:"thinking",thinking:n.content}));case"toolcall_start":return cd(e,n.contentIndex,e=>e?.type==="toolCall"?{...e,toolCallId:n.id??e.toolCallId,toolName:n.toolName??e.toolName,rawInput:""}:"string"!=typeof n.toolName?null:{type:"toolCall",toolCallId:n.id??"",toolName:n.toolName,input:{},rawInput:""});case"toolcall_delta":return cd(e,n.contentIndex,e=>e?.type==="toolCall"?{...e,toolCallId:n.id||e.toolCallId,toolName:n.toolName||e.toolName,rawInput:(e.rawInput??"")+n.delta}:null);case"toolcall_end":return cd(e,n.contentIndex,()=>({type:"toolCall",toolCallId:n.toolCall.id,toolName:n.toolCall.name,input:n.toolCall.arguments}));default:return e}case"end":return ca;default:return e}}(e,n);if(r!==e)for(let n of(e=r,t))n()},subscribe:e=>(t.add(e),()=>{t.delete(e)})}}function cu(e,t){let n=e.lastIndexOf(t);return -1===n?e:[...e.slice(0,n),...e.slice(n+1)]}function cp(e,t){return e.reduce((e,n)=>"user"===n.role&&d3(n)===t?e+1:e,0)}function ch(e){return{steering:e?.steering??[],followUp:e?.followUp??[]}}function cf(e){return e&&"auto"!==e?e:null}let cm=new Map,cg=[2e3,5e3,1e4],cx=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:200,t=new Set;return n=>!t.has(n)&&(t.add(n),t.size>e&&t.delete(t.values().next().value),!0)}();function cv(e){return new Promise(t=>setTimeout(t,e))}function cb(e){let t=e.findIndex(e=>!e.exiting);return -1===t?e:e.map((e,n)=>n===t?{...e,exiting:!0}:e)}function cy(e,t){switch(t.type){case"add":if(e.visible.some(e=>e.exiting)||e.visible.length>=5)return{visible:e.visible.some(e=>e.exiting)?e.visible:cb(e.visible),pending:[...e.pending,t.notice]};return{...e,visible:[...e.visible,t.notice]};case"mark_oldest_exiting":return{...e,visible:cb(e.visible)};case"remove":return function(e,t){let n=e,r=t;for(;r.length>0&&n.length<5;){let[e,...t]=r;n=[...n,e],r=t}return r.length>0&&!n.some(e=>e.exiting)&&(n=cb(n)),{visible:n,pending:r}}(e.visible.filter(e=>e.id!==t.id),e.pending);default:return e}}function cw(e,t){return e&&"object"==typeof e?"number"!=typeof e.tokensBefore||"number"!=typeof e.estimatedTokensAfter?null:{reason:t,tokensBefore:e.tokensBefore,estimatedTokensAfter:e.estimatedTokensAfter}:null}function ck(e,t){let[n,r]=(0,i.useState)(()=>t(e.getState()));return(0,i.useLayoutEffect)(()=>{let n=()=>r(t(e.getState()));return n(),e.subscribe(n)},[e,t]),n}let cj=e=>e.isStreaming,cS=e=>!!e.streamingMessage?.content.length,cC=e=>e.streamingMessage,cN="pi-web:done-chimes";function cE(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:Date.now(),r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:function(){try{return window.localStorage}catch{return null}}();if(0===e.length)return!1;if(!r)return!0;try{let i=function(e){let t=e.getItem(cN);if(!t)return{};try{let e=JSON.parse(t);if(!e||"object"!=typeof e||Array.isArray(e))return{};let n={};for(let[t,r]of Object.entries(e))"number"==typeof r&&Number.isFinite(r)&&(n[t]=r);return n}catch{return{}}}(r),s=e.filter(e=>!("number"==typeof i[e]&&i[e]>=t));if(0===s.length)return!1;for(let e of s)i[e]=n;let o=Object.entries(i).filter(e=>{let[,t]=e;return n-t<=864e5}).sort((e,t)=>t[1]-e[1]).slice(0,200);return r.setItem(cN,JSON.stringify(Object.fromEntries(o))),!0}catch{return!0}}let c$=null,cI=null;function cM(e){let{label:t}=e,[n,s]=(0,i.useState)(()=>cI);if((0,i.useEffect)(()=>{if(cI)return;let e=!1;return(c$??=fetch("/api/app-update").then(async e=>{if(!e.ok)return null;let t=await e.json();return t.updateAvailable&&t.latestVersion&&t.releaseUrl?t:null}).then(e=>(cI=e,e)).catch(()=>(c$=null,null))).then(t=>{!e&&t&&s(t)}),()=>{e=!0}},[]),!n)return null;let o=t(n.latestVersion);return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{className:"new-session-meta-arrow","aria-hidden":"true",children:"→"}),(0,r.jsxs)("a",{className:"new-session-update",href:n.releaseUrl,target:"_blank",rel:"noopener noreferrer",title:o,"aria-label":o,children:["v",n.latestVersion,(0,r.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M7 17 17 7"}),(0,r.jsx)("path",{d:"M7 7h10v10"})]})]})]})}function cT(e){let t,{messageCount:n,toolCallCount:s,durationMs:o,cacheMisses:l,defaultExpanded:a=!1,reveal:d=!1,children:c,t:u}=e,[p,h]=(0,i.useState)(a);(0,i.useLayoutEffect)(()=>{d&&h(!0)},[d]);let f=[`${n} ${u(1===n?"chat.message":"chat.messages")}`];s>0&&f.push(`${s} ${u(1===s?"chat.toolCall":"chat.toolCalls")}`),void 0!==o&&f.push(u("chat.turnDuration",{time:ik(o)}));let m=l&&!(p||d)?(t={count:l.count,tokens:oZ(l.missedTokens),cost:oY(u,l.missedCost)},u(1===l.count?"transcriptNotice.foldCacheMiss":"transcriptNotice.foldCacheMisses",t)):void 0;return(0,r.jsxs)("div",{style:{marginBottom:14},children:[(0,r.jsxs)("button",{type:"button","aria-expanded":p||d,"aria-label":[u("chat.processDetails"),...f,...m?[m]:[]].join(" \xb7 "),onClick:()=>h(e=>!e),style:{display:"flex",alignItems:"center",gap:8,width:"auto",maxWidth:"100%",minHeight:24,padding:"2px 0",border:"none",background:"transparent",color:"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left"},title:u(p?"chat.collapseProcess":"chat.expandProcess"),children:[(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,transform:p?"rotate(90deg)":"none",transition:"transform 0.15s"},children:(0,r.jsx)("polyline",{points:"4 2.5 7.5 6 4 9.5"})}),(0,r.jsxs)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[f.join(" \xb7 "),m&&(0,r.jsx)("span",{style:{color:oJ},children:` \xb7 ${m}`})]})]}),(p||d)&&(0,r.jsx)("div",{style:{marginTop:8},children:c})]})}function cR(e){let t,{session:s,searchTarget:l,onSearchTargetHandled:d,initialScrollPosition:c,onScrollPositionChange:u,sessionRunning:p,newSessionCwd:h,newSessionDraftKey:f,newSessionContextBar:m,initialNewSessionChoices:g,onNewSessionChoicesChange:x,onAgentEnd:v,onSessionEnded:b,onToolEnd:y,onAttentionNeeded:w,onSessionCreated:k,onSessionForked:j,panel:S=!1,onSideSession:C,modelsRefreshKey:N,chatInputRef:E,onBranchDataChange:$,onSystemPromptChange:I,onSystemToolsChange:M,onSystemInfoLoaderChange:T,onDebugSnapshotReaderChange:R,onSessionStatsChange:A,onSessionStatsPanelOpen:L,onOpenSettings:z,onContextUsageChange:P,onOpenFile:W,onFilesUploaded:O,onOpenSubagent:F,quoteSelectionEnabled:D=!1,initialPrompt:B,onInitialPromptConsumed:H,soundEnabled:_=!0,onSoundToggle:U,playDoneSound:K=()=>{},unlockAudio:q,holdAudio:V}=e,{t:Z}=(0,tm.s)(),J=tC(),Y=!a(s?.relation),G=(0,i.useRef)(K);G.current=K;let X=(0,i.useRef)(_);X.current=_;let Q=(0,i.useRef)(!1),ee=(0,i.useCallback)(e=>{if(Y&&X.current&&!e.aborted&&!e.subagentsActive){let e=tt.current??s?.id;(!e||cE([e],Date.now()-3e3))&&G.current()}v?.(e)},[Y,v,s?.id]),et=(0,i.useRef)(l?null:c??null),[en,er]=(0,i.useState)(()=>{let e=et.current;return e&&!e.atBottom?e:null}),[ei,es]=(0,i.useState)(!1),{loading:eo,error:el,messages:ea,activeToolResults:ed,toolClocks:ec,entryIds:eu,messageKeys:ep,historyCursor:eh,hasEarlierMessages:ef,earlierTurnCount:em,streamingStore:eg,agentRunning:ex,bashRunning:ev,pendingBash:eb,modelNames:ey,modelList:ew,modelError:ek,missingCwd:ej,modelScopeWarnings:eS,isModelScopeActive:eC,allModelList:eN,modelThinkingLevels:eE,modelThinkingLevelMaps:e$,toolPreset:eI,thinkingLevel:eM,retryInfo:eT,contextUsage:eR,forkingEntryId:eA,isCompacting:eL,compactError:ez,compactResult:eP,displayModel:eW,modelSwitching:eO,sessionStats:eF,slashCommands:eD,slashCommandsLoading:eB,queuedMessages:eH,notices:e_,extensionDialog:eq,waitingExtensionDialogCount:eV,extensionCustomUi:eZ,waitingExtensionCustomUiCount:eY,extensionStatuses:eG,extensionWidgets:eX,respondToExtensionUi:eQ,sendExtensionCustomInput:e0,setNoticePaused:e1,addNotice:e2,isAutoModelSelection:e4,isAutoThinkingSelection:e8,defaultModel:e3,savedDefaultThinkingLevel:e5,agentPhase:e6,isNew:e9,editEntryId:e7,showScrollToBottom:te,sessionIdRef:tt,scrollContainerRef:tn,lastUserMsgRef:tr,promptAnchorActive:ti,handleSend:ts,handleAbort:to,startSideChat:tl,handleFork:ta,handleEditContent:td,cancelEdit:tc,handleModelChange:tu,handleCompact:tp,handleSteer:th,handleFollowUp:tf,handlePromptWithStreamingBehavior:tg,handleAbortCompaction:tx,dismissCompactError:tv,handleRecallQueue:tb,handleBuiltinSlashCommand:ty,handleToolPresetChange:tw,handleThinkingLevelChange:tk,handleSetDefaultModel:tj,handleSetDefaultThinkingLevel:tS,loadSlashCommands:tN,loadAllModels:tE,scrollUserMsgToTop:t$,loadContext:tM,activeLeafId:tT,scrollToBottom:tR,scrollToMessage:tA}=function(e){var t;let r,s,{session:o,newSessionCwd:l,newSessionDraftKey:a,onAgentEnd:d,onSessionEnded:c,onToolEnd:u,onAttentionNeeded:p,onSessionCreated:h,onSessionForked:f,onSideSession:m,modelsRefreshKey:g,onBranchDataChange:x,onSystemPromptChange:v,onSystemToolsChange:b,onSystemInfoLoaderChange:y,onSessionStatsPanelOpen:w,onOpenSettings:k,onDebugSnapshotReaderChange:j}=e,S=null===o&&null!==l,C=S?e.initialNewSessionChoices??null:null,[N,E]=(0,i.useState)(null),[$,I]=(0,i.useState)(!S),[M,T]=(0,i.useState)(null),[R,A]=(0,i.useState)(null),[L,z]=(0,i.useState)([]),[P,W]=(0,i.useState)(new Map),[O,F]=(0,i.useState)(oh),[D,B]=(0,i.useState)([]),[H,_]=(0,i.useState)(()=>new Map),[U,K]=(0,i.useState)(null),[q,V]=(0,i.useState)(!1),[Z,J]=(0,i.useState)(0),[Y]=(0,i.useState)(cc),G=Y.dispatch,[X,Q]=(0,i.useState)(!1),[ee,et]=(0,i.useState)(!1),[en,er]=(0,i.useState)(null),[ei,es]=(0,i.useState)({}),[eo,el]=(0,i.useState)([]),[ea,ed]=(0,i.useState)(null),[ec,eu]=(0,i.useState)(null),[ep,eh]=(0,i.useState)(null),[ef,em]=(0,i.useState)([]),[eg,ex]=(0,i.useState)(!1),[ev,eb]=(0,i.useState)(null),ey=(0,i.useRef)(null),[ew,ek]=(0,i.useState)({}),[ej,eS]=(0,i.useState)({}),[eC,eN]=(0,i.useState)(()=>C?.model??null),[eE,e$]=(0,i.useState)(null),[eI,eM]=(0,i.useState)(dY.Q8),[eT,eR]=(0,i.useState)(()=>C?.thinkingLevel??null),[eA,eL]=(0,i.useState)(null),[ez,eP]=(0,i.useState)(null),[eW,eO]=(0,i.useState)(null),[eF,eD]=(0,i.useState)(null),[eB,eH]=(0,i.useState)(null),[e_,eq]=(0,i.useState)(null),[eV,eZ]=(0,i.useState)(null),eY=(0,i.useRef)(0),eG=(0,i.useRef)(0),[eX,eQ]=(0,i.useState)(null),[e0,e1]=(0,i.useState)(null),[e2,e4]=(0,i.useState)(null),[e8,e3]=(0,i.useState)(null),[e5,e6]=(0,i.useState)(null),[e9,e7]=(0,i.useState)(!1),[te,tt]=(0,i.useState)(!1),[tn,tr]=(0,i.useState)(!0),[ti,ts]=(0,i.useState)(null),[to,tl]=(0,i.useState)(null),[ta,td]=(0,i.useState)(null),[tc,tu]=(0,i.useState)(!1),[tp,th]=(0,i.useState)(!1),[tf,tm]=(0,i.useState)([]),[tg,tx]=(0,i.useState)(!1),[tv,tb]=(0,i.useReducer)(cy,{visible:[],pending:[]}),[ty,tw]=(0,i.useState)(null),[tk,tj]=(0,i.useState)([]),[tS,tC]=(0,i.useState)([]),[tN,tE]=(0,i.useState)([]),[t$,tI]=(0,i.useState)([]),[tM,tT]=(0,i.useState)({steering:[],followUp:[]}),tR=(0,i.useRef)(null),tA=(0,i.useRef)(null),tL=(0,i.useRef)(0),tz=(0,i.useRef)(!1),tP=(0,i.useRef)(!1),[tW,tO]=(0,i.useState)(0),tF=(0,i.useRef)(null),tD=(0,i.useRef)(()=>{}),tB=(0,i.useRef)({renewStartedAt:null,inFlightSince:null,requests:0,unanswered:0,errors:0,last:null}),tH=(0,i.useRef)({count:0,lastAt:null}),t_=(0,i.useRef)({count:0,lastAt:null,lastReason:null}),tU=(0,i.useRef)(null),tK=(0,i.useRef)(null),tq=(0,i.useRef)(!1),tV=(0,i.useRef)(0),tZ=(0,i.useRef)(o?.id??null),tJ=(0,i.useRef)(null),tY=(0,i.useRef)(o?.id??null),tG=(0,i.useRef)(!1),tX=(0,i.useRef)(!1),tQ=(0,i.useRef)(!1),t0=(0,i.useRef)(!1),t1=(0,i.useRef)(-1),t2=(0,i.useRef)(!1),t4=(0,i.useRef)(0),t8=(0,i.useRef)(0),t3=(0,i.useRef)(null),t5=(0,i.useRef)(!!e.deferInitialScroll),t6=(0,i.useRef)(null),t9=(0,i.useRef)(!1),t7=(0,i.useRef)(!0),ne=(0,i.useRef)(0),nt=(0,i.useRef)(null),nn=(0,i.useRef)(void 0),nr=(0,i.useRef)(void 0),ni=(0,i.useRef)(null),ns=(0,i.useRef)(null),no=(0,i.useRef)([]),nl=(0,i.useRef)(null),na=(0,i.useRef)(0),nd=(0,i.useRef)(!1),nc=(0,i.useRef)(C?.model??null),nu=(0,i.useRef)(C?.thinkingLevel??null),np=(0,i.useRef)({}),nh=(0,i.useRef)(null),nf=(0,i.useRef)(0),nm=(0,i.useRef)(null),ng=(0,i.useRef)(null),nx=(0,i.useRef)(null),nv=(0,i.useRef)(0),nb=(0,i.useRef)(null),ny=(0,i.useCallback)(()=>{ng.current=nf.current,nx.current?.runId===nf.current&&(nx.current=null)},[]),nw=(0,i.useRef)(!1),nk=(0,i.useRef)(new Map),nj=(0,i.useRef)(!0),nS=(0,i.useRef)(new Map),nC=(0,i.useRef)(null),nN=(0,i.useRef)([]),nE=(0,i.useRef)([]),n$=(0,i.useRef)(null),nI=(0,i.useRef)(null),nM=(0,i.useRef)(!1),nT=(0,i.useRef)(0);tY.current=o?.id??null,nC.current=N,nN.current=L,nE.current=D,n$.current=R,nI.current=U,nM.current=q,nT.current=Z,tq.current=te,tV.current=tk.length+tS.length;let nR=(0,i.useCallback)(e=>nj.current&&tJ.current!==e&&tZ.current===e&&(tX.current||tz.current||tY.current===e&&!tP.current),[]);tR.current||(tR.current=new d9({createSource:e=>eJ("agent",new EventSource(`/api/agent/${encodeURIComponent(e)}/events?holder=${encodeURIComponent(eK())}`),e),onEvent:e=>t3.current?.(e),shouldMaintain:nR,readinessTimeoutMs:6e4,reconnectDelayMs:1e3,staleAfterMs:75e3,onUnexpectedError:e=>{console.error("Failed to maintain the agent event stream:",e)}}));let nA=e.setToolPreset??eM,nL=o?.id;(0,i.useLayoutEffect)(()=>{(nL||S&&!tZ.current)&&nA(function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:dX();if(!e)return dY.Q8;try{let t=e.getItem(dG);return(0,dY.sn)(t)?t:dY.Q8}catch{return dY.Q8}}())},[nL,S,nA]);let nz=e.onNewSessionChoicesChange;(0,i.useEffect)(()=>{S&&nz?.({model:eC,thinkingLevel:eT})},[S,eC,eT,nz]);let nP=(0,i.useCallback)(function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"smooth",t=ni.current;t&&(t.scrollTo({top:t.scrollHeight,behavior:e}),ne.current=t.scrollTop)},[]),nW=e2??e8??N?.context.model??e5??null,nO=S?eC??eE:nW??(N?.context.messages.length===0?eE:null),nF=cf(N?.context.thinkingLevel&&"off"!==N.context.thinkingLevel?N.context.thinkingLevel:null),nD=S?eT??eA:eW??eF??nF??(N?.context.messages.length===0?eA:null),nB=o?.id??a??void 0,nH=(0,i.useCallback)(e=>{e3(e?.model?{provider:e.model.provider,modelId:e.model.id}:null),e?.thinkingLevel!==void 0&&eD(cf(e.thinkingLevel))},[]),n_=(0,i.useCallback)(e=>{if(!e)return;let t=e,n=new Set;for(;!n.has(t);){n.add(t);let e=nk.current.get(t);if(!e)break;t=e}return t},[]),nU=(0,i.useCallback)((t,n,r)=>{let i=n?.map(e=>{let{data:t,mimeType:n}=e;return{data:t,mimeType:n}}),s=n_(r);if(!nj.current&&!nd.current&&r===a)return;let o=e.chatInputRef?.current;o?o.restoreSubmission(t,i,s):s&&lZ(s,t,i)},[a,e.chatInputRef,n_]),[nK,nq]=(0,i.useState)(()=>{let e=o?.id;return e&&!l_(e)&&cm.delete(e),e&&cm.get(e)||null}),nV=(0,i.useCallback)(e=>{o?.id&&(e?cm.set(o.id,e):cm.delete(o.id),nq(e))},[o?.id]),nZ=(0,i.useCallback)((t,n)=>{o?.id&&(e.chatInputRef?.current?.replaceMessage(t),nV(n))},[e.chatInputRef,o?.id,nV]),nJ=(0,i.useCallback)(()=>nV(null),[nV]),nY=(0,i.useMemo)(()=>{let e=N?.totalActiveMs,t=eV&&eV.sessionId===N?.sessionId?eV.value:void 0,n=void 0===e&&void 0===t?void 0:Math.max(e??0,t??0);if(ty)return{...ty,totalActiveMs:n,...e_?{contextUsage:e_}:{}};let r=N?.stats,i=function(e,t,n){let r=d0(n);if(!e)return r;let i=d0(t),s=(e,t)=>Math.max(0,e-t),o={input:e.tokens.input+s(r.tokens.input,i.tokens.input),output:e.tokens.output+s(r.tokens.output,i.tokens.output),cacheRead:e.tokens.cacheRead+s(r.tokens.cacheRead,i.tokens.cacheRead),cacheWrite:e.tokens.cacheWrite+s(r.tokens.cacheWrite,i.tokens.cacheWrite),total:0};return o.total=o.input+o.output+o.cacheRead+o.cacheWrite,{userMessages:e.userMessages+s(r.userMessages,i.userMessages),assistantMessages:e.assistantMessages+s(r.assistantMessages,i.assistantMessages),toolCalls:e.toolCalls+s(r.toolCalls,i.toolCalls),toolResults:e.toolResults+s(r.toolResults,i.toolResults),totalMessages:e.totalMessages+s(r.totalMessages,i.totalMessages),tokens:o,cost:e.cost+s(r.cost,i.cost)}}(r,N?.context.messages??[],L);return 0!==i.tokens.total||0!==L.length||r?{sessionFile:N?.filePath||void 0,sessionId:tZ.current??o?.id??"",sessionName:o?.name,...i,totalActiveMs:n,...e_?{contextUsage:e_}:{}}:null},[L,ty,e_,eV,N?.sessionId,N?.context.messages,N?.filePath,N?.totalActiveMs,N?.stats,o?.id,o?.name]),nG=(0,i.useCallback)((e,t,n,r)=>{nj.current&&tZ.current===t&&nf.current===n&&!(r<=eG.current)&&(eG.current=r,e?.contextUsage!==void 0&&eq(e.contextUsage??null),"number"==typeof e?.totalActiveMs&&eZ({sessionId:t,value:e.totalActiveMs}))},[]),nX=(0,i.useCallback)(async e=>{let t=nf.current,n=++eY.current;try{let r=await fetch(dF(e));if(!r.ok)return;let i=await r.json();nG(i.state,e,t,n)}catch{}},[nG]),nQ=(0,i.useCallback)(async function(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],n=arguments.length>2&&void 0!==arguments[2]&&arguments[2],r=arguments.length>3?arguments[3]:void 0,i=r?.force?`force:${e}`:e,s=r?.force?void 0:nS.current.get(i);if(s)return await s;let o=(async()=>{let i=!1,s=++nv.current,o=!tX.current;try{t&&I(!0);let l=new URLSearchParams({deferThinking:"1",deferMedia:"1",tree:"summary"});r?.force&&l.set("force","1");let a=await fetch(`/api/sessions/${encodeURIComponent(e)}?${l}`);if(404===a.status)return t&&(E(null),A(null),z([]),B([]),K(null),V(!1),J(0),T(null)),dJ(e),null;if(!a.ok)throw Error(`HTTP ${a.status}`);let d=await a.json();if(tZ.current!==e)return null;(nb.current?.seq??0)<s&&(nb.current={sid:e,seq:s,messages:d.context.messages,entryIds:d.context.entryIds??[]});let c=dV(e),u=!!(d.snapshotRevision&&c?.revision===d.snapshotRevision&&c.entryIds.length>=(d.context.entryIds??[]).length),p=u?nN.current:d.context.messages;if(E(u?{...d,context:{...d.context,messages:nN.current,entryIds:nE.current,oldestEntryId:nI.current,hasMore:nM.current,turnsBefore:nT.current}}:d),A(d.leafId),u)dZ({sessionId:e,revision:d.snapshotRevision,messages:nN.current,entryIds:nE.current,leafId:d.leafId,oldestEntryId:nI.current,hasMore:nM.current,turnsBefore:nT.current,summaryTree:d.tree,thinkingLevel:d.context.thinkingLevel,model:d.context.model,stats:d.stats,totalActiveMs:d.totalActiveMs,loadedEntryIds:nE.current});else{let e={messages:nN.current,entryIds:nE.current},t={messages:p,entryIds:d.context.entryIds??[]};_(n=>(function(e,t){let n=new Set(t.entryIds),r=new Map([...e.aliases].filter(e=>{let[t]=e;return n.has(t)})),i=e.entryIds.length,s=e.entryIds[i-1],o=void 0===s?0:t.entryIds.indexOf(s)+1;if(0===o&&void 0!==s)return r;for(let n=0;i+n<e.messages.length;n++){var l,a;let d=t.entryIds[o+n];if(void 0===d||(l=e.messages[i+n],a=t.messages[o+n],l.role!==a.role||("user"===l.role?d3(l)!==d3(a):"custom"===l.role?l.customType!==a.customType:l.timestamp!==a.timestamp)))break;r.set(d,d5(s,n))}return r})({...e,aliases:n},t)),z(t.messages),B(t.entryIds),K(d.context.oldestEntryId),V(d.context.hasMore),J(d.context.turnsBefore??0)}if(tG.current=void 0!==d.toolNames,nA(void 0!==d.toolNames?(0,dY.YO)(d.toolNames):dY.Q8),e4(e=>nw.current?e:null),eO(null),T(null),"summary"===d.treeFormat&&d.snapshotRevision&&dZ({sessionId:e,revision:d.snapshotRevision,messages:p,entryIds:d.context.entryIds??[],leafId:d.leafId,oldestEntryId:d.context.oldestEntryId,hasMore:d.context.hasMore,turnsBefore:d.context.turnsBefore??0,summaryTree:d.tree,thinkingLevel:d.context.thinkingLevel,model:d.context.model,stats:d.stats,totalActiveMs:d.totalActiveMs,loadedEntryIds:d.context.entryIds??[]}),d.wrapperRebuilt&&(tR.current?.close("rebuilt"),tR.current?.maintain(e)),!n&&d.context.thinkingLevel&&"off"!==d.context.thinkingLevel&&eD(cf(d.context.thinkingLevel)),i=!0,o&&s>t4.current&&er(e=>e?.result?null:e),t&&I(!1),!n)return null;try{let t=nf.current,n=++eY.current,r=await fetch(`/api/sessions/${encodeURIComponent(e)}/state`);if(!r.ok)throw Error(`HTTP ${r.status}`);let i=await r.json();if(tZ.current!==e)return null;let s=i.state;return nH(s),s?(nG(s,e,t,n),void 0!==s.systemPrompt&&eQ(s.systemPrompt??null),void 0!==s.extensionStatuses&&tE(s.extensionStatuses??[]),void 0!==s.extensionWidgets&&tI(s.extensionWidgets??[]),void 0!==s.queuedMessages&&tT(ch(s.queuedMessages)),void 0!==s.autoCompactionEnabled&&tr(s.autoCompactionEnabled??!0)):i.running||tT({steering:[],followUp:[]}),i}catch(e){return console.error("Failed to load agent state:",e),null}}catch(e){return T(String(e)),"error"}finally{t&&!i&&I(!1)}})();return nS.current.set(i,o),o.finally(()=>{nS.current.get(i)===o&&nS.current.delete(i)}),await o},[nG,nA,nH]),n0=(0,i.useCallback)(async(e,t,n,r)=>{try{let i=new URLSearchParams({deferThinking:"1",deferMedia:"1"});t&&i.set("leafId",t),n&&i.set("before",n),r?.tail&&i.set("tail",String(r.tail));let s=`/api/sessions/${encodeURIComponent(e)}/context?${i}`,o=await fetch(s,{signal:r?.signal});if(!o.ok)throw Error(`HTTP ${o.status}`);let l=await o.json();if(tZ.current!==e||r?.signal?.aborted||!nj.current)return;return K(l.context.oldestEntryId),V(l.context.hasMore),J(l.context.turnsBefore??0),E(t=>{if(!t||t.sessionId!==e)return t;let r=n?{...t.context,messages:[...l.context.messages,...t.context.messages],entryIds:[...l.context.entryIds,...t.context.entryIds],oldestEntryId:l.context.oldestEntryId,hasMore:l.context.hasMore,turnsBefore:l.context.turnsBefore}:l.context;return{...t,context:r}}),n?(z(e=>[...l.context.messages,...e]),B(e=>[...l.context.entryIds,...e])):(z(l.context.messages),B(l.context.entryIds??[])),l.context}catch(e){r?.signal?.aborted||console.error("Failed to load context:",e)}},[]),n1=(0,i.useCallback)(async e=>{try{let t=await dD(e,{type:"get_tools"});if(!t||!nj.current||tZ.current!==e)return null;let{getPresetFromTools:r}=await Promise.resolve().then(n.bind(n,14755));return nA(tG.current?r(t):dY.Q8),b?.(t),t}catch(e){return console.error("Failed to load tools:",e),null}},[b,nA]),n2=(0,i.useCallback)(function(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"(no messages)",r=tZ.current;if(S&&l&&r&&!nd.current&&(nd.current=!0,a)){if(a!==r){nk.current.set(a,r);let t=e.chatInputRef?.current;t?t.rekeyDraft(a,r):lJ(a,r)}h?.({id:r,path:"",cwd:l,name:void 0,created:new Date().toISOString(),modified:new Date().toISOString(),messageCount:t,firstMessage:n,transient:!0},a)}},[S,l,a,h,e.chatInputRef]),n4=(0,i.useCallback)((e,t,n)=>{e.model&&nc.current===t&&(e6(e.model),t||e$(e.model)),e.thinkingLevel&&nu.current===n&&(eD(cf(e.thinkingLevel)),n||eL(cf(e.thinkingLevel)))},[]),n8=(0,i.useCallback)(async()=>{if(tZ.current||!S||!l)return tZ.current;if(ns.current)return ns.current;let e=(async()=>{let e=nc.current,t=nu.current;e&&e6(e);let n=(0,dY.xG)(eI);tG.current=void 0!==n;let r=await fetch("/api/agent/new",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:l,type:"ensure_session",...void 0!==n?{toolNames:n}:{},...e?{provider:e.provider,modelId:e.modelId}:{},...t?{thinkingLevel:t}:{}})});if(!r.ok){let e=await r.json().catch(()=>null),t="string"==typeof e?.error?e.error:`HTTP ${r.status}`,n=dP(e);throw n?new dW(t,r.status,void 0,void 0,n):Error(t)}let i=await r.json(),s=i.sessionId;return tZ.current=s,n4(i,e,t),s})();ns.current=e;try{return await e}finally{ns.current=null}},[n4,S,l,eI]),n3=(0,i.useCallback)(async()=>{let e=tZ.current??await n8();if(!e)return;let[t]=await Promise.all([dD(e,{type:"get_state"}),n1(e)]);nj.current&&tZ.current===e&&(nH(t),eQ(t.systemPrompt??""))},[n8,n1,nH]),n5=(0,i.useCallback)(e=>{no.current=e,tm(e)},[]),n6=(0,i.useCallback)(()=>{na.current+=1,nl.current=null,n5([])},[n5]),n9=(0,i.useCallback)(async(e,t)=>{let n=null===tY.current&&nj.current;n&&tR.current?.ensureConnected(e).catch(()=>{});try{return await t()}finally{!n||null!==tY.current||tZ.current!==e||0!==tV.current||tX.current||t2.current||tR.current?.close("grace_end")}},[]),n7=(0,i.useCallback)(()=>{let e=++na.current,t=(async()=>{let t=tZ.current??await n8();if(!t)return na.current===e&&n5([]),[];tx(!0);try{let n=await n9(t,()=>dD(t,{type:"get_commands"})),r=n?.commands??[];return na.current===e&&n5(r),r}catch(t){return console.error("Failed to load slash commands:",t),na.current===e&&n5([]),null}finally{na.current!==e&&nl.current||tx(!1)}})();nl.current=t;let n=()=>{nl.current===t&&(nl.current=null)};return t.then(n,n),t},[n8,n5,n9]),re=(0,i.useCallback)(async()=>await n7()??[],[n7]),rt=(0,i.useCallback)(async()=>{let e=nl.current,t=no.current;return!e&&t.length>0?t:await (e??n7()).catch(()=>null)??(t.length>0?t:null)},[n7]),rn=(0,i.useCallback)(()=>{tL.current+=1,tz.current=!1,tK.current=null,tA.current&&(clearTimeout(tA.current),tA.current=null)},[]),rr=(0,i.useCallback)(e=>{tR.current?.close(e)},[]),ri=(0,i.useCallback)(e=>tR.current.ensureConnected(e),[]),rs=(0,i.useCallback)(e=>{tR.current.maintain(e)},[]);(0,i.useEffect)(()=>{let e=o?.id;if(e)return nj.current=!0,tP.current=!1,rs(e),()=>{tZ.current===e&&tR.current?.close("deselected")}},[rs,o?.id]);let ro=(0,i.useCallback)(e=>{let t=tF.current;if(t?.sid===e)return t.promise;let n=new AbortController,r=setTimeout(()=>n.abort(),5e3),i={sid:e,promise:Promise.resolve(null)};return i.promise=(async()=>{let t=null,s=null,o=Date.now();tB.current.inFlightSince=o,tB.current.requests+=1;try{let r=await fetch(`/api/agent/${encodeURIComponent(e)}/lease`,{method:"POST",cache:"no-store",signal:n.signal});return t=r.status,s=r.ok?await r.json():null}catch(e){return s=n.signal.aborted||e instanceof TypeError?"unanswered":null}finally{clearTimeout(r),tF.current===i&&(tF.current=null);try{let e=tB.current,n=Date.now(),r="unanswered"===s?"unanswered":null===s?"error":"reply";"unanswered"===r&&(e.unanswered+=1),"error"===r&&(e.errors+=1);let i="object"==typeof s&&null!==s?s:null;e.inFlightSince=null,e.last={at:n,durationMs:Math.max(0,n-o),outcome:r,httpStatus:t,reply:i&&{running:!0===i.running,awaitingInput:!0===i.awaitingInput,subagentsActive:!0===i.subagentsActive}}}catch{}}})(),tF.current=i,i.promise},[]),rl=!X&&!ee&&!te&&0===tk.length&&0===tS.length;(0,i.useEffect)(()=>{let e=o?.id;if(!e||!rl)return;let t=!1,n=null,r=()=>!t&&"hidden"===document.visibilityState&&!tP.current&&tZ.current===e&&tY.current===e&&!tX.current&&!t2.current,i=async()=>{if(n=null,tU.current=null,!r())return;let t=await ro(e);if(r()){if(!("unanswered"===t||t&&!d7(t)))return void s();tP.current=!0,tH.current={count:tH.current.count+1,lastAt:Date.now()},rr("released")}},s=()=>{null===n&&(n=setTimeout(()=>void i(),3e4),tU.current=Date.now()+3e4)},l=()=>{"hidden"===document.visibilityState?s():n&&(clearTimeout(n),n=null,tU.current=null)};return"hidden"===document.visibilityState&&s(),document.addEventListener("visibilitychange",l),()=>{t=!0,n&&clearTimeout(n),tU.current=null,document.removeEventListener("visibilitychange",l)}},[rr,rl,tW,ro,o?.id]);let ra=(0,i.useCallback)(async(e,t)=>{let n=tZ.current;if(tj(t=>dA(t,e.id)),!n)return;try{await dD(n,{type:"extension_ui_response",id:e.id,...t})}catch(e){console.error("Failed to send extension UI response:",e);return}if(null!==tY.current)return;let r=nc.current,i=nu.current;try{let e=await dD(n,{type:"get_state"});if(!nj.current||tZ.current!==n||null!==tY.current)return;n4({model:e.model?{provider:e.model.provider,modelId:e.model.id}:null,thinkingLevel:e.thinkingLevel},r,i),void 0!==e.systemPrompt&&eQ(e.systemPrompt)}catch{}},[n4]),rd=(0,i.useCallback)(async(e,t)=>{let n=tZ.current;if(n)try{await dD(n,{type:"extension_ui_input",id:e.id,data:t})}catch(e){console.error("Failed to send extension custom UI input:",e)}},[]),rc=(0,i.useCallback)(e=>{let t=e.message.trim();t&&tb({type:"add",notice:{id:e.id??("u">typeof crypto&&"function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2)}`),message:t,type:e.type??"info"}})},[]),ru=(0,i.useRef)(e.t);ru.current=e.t;let rp=(0,i.useCallback)((e,t)=>ru.current(e,t),[]),rh=(0,i.useCallback)(()=>{rc({type:"warning",message:rp("chat.sendUnconfirmed")})},[rc,rp]),rf=(0,i.useCallback)(e=>{nj.current&&z(t=>cu(t,e.bubble));let t=dV(e.sid);t?.messages.includes(e.bubble)&&dZ({...t,messages:cu(t.messages,e.bubble)})},[]),rm=(0,i.useCallback)((e,t,n)=>{let r=nx.current;if(!r||r.runId!==t||r.sid!==e)return;nx.current=null;let i=nb.current,s=i?.sid===e&&i.seq>n?i:null,o=s?null===r.lastEntryIdAtSend?0:s.entryIds.indexOf(r.lastEntryIdAtSend)+1||-1:-1;s&&o>=0&&cp(s.messages.slice(o),r.key)>r.sameTextAfterSend||(nU(r.message,r.images,r.draftKey),s&&rf(r),rc(s&&!r.command&&o===s.entryIds.length?{type:"error",message:rp("chat.sendNotReceived")}:{type:"warning",message:rp("chat.sendUnconfirmed")}))},[rc,rf,nU,rp]),rg=(0,i.useCallback)(()=>{let e=nx.current;if(nx.current=null,e){if(e.parkedDraftKey){let t=e.images?.map(e=>{let{data:t,mimeType:n}=e;return{data:t,mimeType:n}});lZ(e.parkedDraftKey,e.message,t)}else nU(e.message,e.images,e.draftKey);rf(e)}},[rf,nU]),rx=(0,i.useRef)(rg);rx.current=rg;let rv=(0,i.useCallback)(t=>{switch(dT(t)&&p?.(t),t.method){case"select":case"confirm":case"input":case"editor":tj(e=>e.some(e=>e.id===t.id)?e:[...e,t]);break;case"notify":if(t.id&&!cx(t.id))break;rc({id:t.id,message:rH(t.message),type:t.notifyType??"info"});break;case"setStatus":tE(e=>{let n=e.filter(e=>e.key!==t.statusKey);return void 0!==t.statusText?[...n,{key:t.statusKey,text:t.statusText}]:n});break;case"setWidget":tI(e=>(function(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"aboveEditor";if(void 0===n)return e.filter(e=>e.key!==t);let i={key:t,lines:n,placement:r},s=e.findIndex(e=>e.key===t);return -1===s?[...e,i]:e.map((e,t)=>t===s?i:e)})(e,t.widgetKey,t.widgetLines,t.widgetPlacement));break;case"setTitle":t.title&&(document.title=rH(t.title));break;case"set_editor_text":e.chatInputRef?.current?.setText(rH(t.text));break;case"custom":tC(e=>{let n;return t.closed?dA(e,t.id):-1===(n=e.findIndex(e=>e.id===t.id))?[...e,t]:e[n]===t?e:e.map((e,r)=>r===n?t:e)})}},[rc,p,e.chatInputRef]),rb=(0,i.useCallback)(()=>{let e=tX.current;return tX.current=!1,Q(!1),td(null),eH(null),W(new Map),F(oh),G({type:"end"}),e},[G]),ry=(0,i.useCallback)(function(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return t1.current!==e&&(t1.current=e,d?.({aborted:t,...n?{subagentsActive:n}:{}}),!0)},[d]),rw=(0,i.useCallback)(e=>{if(tY.current===e)return void rn();rn(),tz.current=!0;let t=tL.current,n=async()=>{if(t===tL.current&&tZ.current===e&&tz.current)try{let r=await fetch(dF(e));if(!r.ok)throw Error(`HTTP ${r.status}`);let i=await r.json();if(t!==tL.current||tZ.current!==e||!tz.current)return;let s=i.state;if(nH(s),i.running&&s&&(s.isStreaming||s.isPromptRunning)){tz.current=!1,tA.current=null,tK.current=null,tQ.current=!!s?.isStreaming,t0.current=!!s?.isPromptRunning,tX.current=!0,Q(!0),td(e=>dM(e,!!s?.isStreaming));return}if(i.running&&s?.isCompacting){tt(!0),tA.current=setTimeout(()=>void n(),600),tK.current=Date.now()+600;return}tz.current=!1,tA.current=null,tK.current=null,rr("grace_end")}catch{if(t!==tL.current||tZ.current!==e||!tz.current)return;tA.current=setTimeout(()=>void n(),600),tK.current=Date.now()+600}};tA.current=setTimeout(()=>void n(),3e4),tK.current=Date.now()+3e4},[rn,rr,nH]),rk=(0,i.useCallback)(async function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:tZ.current,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:nf.current;if(nf.current!==t)return;let n=nv.current;try{e&&await nQ(e)}finally{if(nf.current!==t)return;e&&rm(e,t,n);let r=t0.current,i=tQ.current;t0.current=!1,tQ.current=!1,nm.current=null;let s=rb();r?ry(t):i&&s&&d?.({aborted:!1}),e&&rw(e)}},[nQ,ry,d,rw,rb,rm]),rj=(0,i.useCallback)(async(e,t)=>{await cv(800);let n=Date.now();for(;tX.current&&Date.now()-n<2e4;){if(void 0!==t&&nf.current!==t)return;try{let n=await fetch(dF(e));if(n.ok){let r=await n.json(),i=r.state;if(nH(i),!r.running||!i||!i.isStreaming&&!i.isPromptRunning)return void await rk(e,t)}}catch{}await cv(600)}},[rk,nH]),rS=(0,i.useCallback)(async e=>{let t=t8.current+1;for(t8.current=t;t2.current&&t8.current===t&&tZ.current===e;){await cv(1e3);try{let n=await fetch(dF(e));if(!n.ok)continue;let r=await n.json();if(nH(r.state),r.state?.isBashRunning)continue;if(await nQ(e),t8.current!==t||tZ.current!==e)return;t2.current=!1,et(!1),er(null);return}catch{}}},[nQ,nH]),rC=(0,i.useCallback)(async e=>{if(!tX.current||tZ.current!==e)return;let t=nf.current,n=++eY.current;try{let r=await fetch(dF(e));if(!r.ok)return;let i=await r.json();if(tZ.current!==e||nf.current!==t)return;let s=i.state;if(nG(s,e,t,n),nH(s),tt(s?.isCompacting??!1),tr(s?.autoCompactionEnabled??!0),tT(ch(s?.queuedMessages)),i.running&&s&&(s.isStreaming||s.isPromptRunning||s.isCompacting)){tQ.current=!!s.isStreaming,t0.current=!!s.isPromptRunning;return}if(!tX.current)return;s&&(void 0!==s.extensionStatuses&&tE(s.extensionStatuses??[]),void 0!==s.extensionWidgets&&tI(s.extensionWidgets??[]),fetch(`/api/agent/${encodeURIComponent(e)}`).then(e=>e.ok?e.json():null).then(t=>{t&&nj.current&&tZ.current===e&&t.state?.systemPrompt!==void 0&&eQ(t.state.systemPrompt??null)}).catch(()=>{})),await rk(e,t)}catch{}},[nG,rk,nH]);(0,i.useEffect)(()=>{if(!X)return;let e=()=>{let e=tZ.current;e&&rC(e)},t=()=>{"visible"===document.visibilityState&&e()},n=setInterval(e,15e3);return document.addEventListener("visibilitychange",t),window.addEventListener("online",e),()=>{clearInterval(n),document.removeEventListener("visibilitychange",t),window.removeEventListener("online",e)}},[X,rC]),(0,i.useEffect)(()=>{tX.current=X},[X]);let rN=(0,i.useCallback)(e=>nj.current&&tZ.current===e&&!tX.current,[]),rE=(0,i.useRef)(null),r$=(0,i.useRef)(null),rI=(0,i.useCallback)(async e=>{var t;let n,r=new URLSearchParams({deferThinking:"1",deferMedia:"1",tail:"1"}),i=await fetch(`/api/sessions/${encodeURIComponent(e)}/context?${r}`);if(!i.ok)throw Error(`HTTP ${i.status}`);let{context:s,leafId:o}=await i.json();if(!rN(e))return;let l=nE.current.at(-1),a=nN.current.at(-1),d=void 0!==l&&nN.current.length===nE.current.length?(n=(t={messages:s.messages,entryIds:s.entryIds??[]}).entryIds.lastIndexOf(l))<0?null:{messages:t.messages.slice(n+1),entryIds:t.entryIds.slice(n+1)}:null;if(!d)return void await nQ(e);if(0===d.entryIds.length)return;if(t2.current&&d.messages.some(e=>"bashExecution"===e.role)){r$.current=e;return}nE.current=[...nE.current,...d.entryIds],nN.current=[...nN.current,...d.messages],B(e=>e.at(-1)===l?[...e,...d.entryIds]:e),z(e=>e.at(-1)===a?[...e,...d.messages]:e),o&&(rE.current={base:n$.current,lastEntryId:d.entryIds.at(-1),leafId:o});let c=dV(e);c&&dZ({...c,loadedEntryIds:[...c.loadedEntryIds,...d.entryIds]})},[rN,nQ]),rM=(0,i.useRef)(rI);rM.current=rI;let rT=(0,i.useRef)(null);rT.current??=(t={pendingReads:e=>[nS.current.get(e),nS.current.get(`force:${e}`)],read:e=>rM.current(e),wanted:rN,onError:e=>console.error("Failed to read a message sent while idle:",e)},r=!1,s=null,e=>{s=e,r||(r=!0,(async()=>{try{for(;null!==s;){let e=s;if(s=null,t.wanted(e))try{await Promise.allSettled(t.pendingReads(e)),t.wanted(e)&&await t.read(e)}catch(e){t.onError?.(e)}}}finally{r=!1}})())}),t3.current=(0,i.useCallback)(t=>{if(!tJ.current)switch(t.type){case"session_ended":{let e=tZ.current;if(!e||t.sessionId!==e)return;tJ.current=e,rn(),tR.current?.close(),dJ(e),c?.(e);return}case"connected":if(G({type:"end"}),Array.isArray(t.pendingExtensionUiIds)){let e=new Set(t.pendingExtensionUiIds);tj(t=>dR(t,e)),tC(t=>dR(t,e))}F(ox),!0===t.isStreaming&&(rn(),tQ.current=!0,tX.current=!0,Q(!0),td({kind:"waiting_model"})),tZ.current&&nX(tZ.current);break;case"agent_start":ny(),rn(),tQ.current=!0,tX.current=!0,Q(!0),td({kind:"waiting_model"}),eH(null),G({type:"start"});break;case"agent_end":if(!tX.current)break;if(td(null),eH(null),G({type:"end"}),tZ.current){let e=tZ.current,t=nf.current,n=++eY.current;nQ(e),fetch(`/api/agent/${encodeURIComponent(e)}`).then(e=>e.ok?e.json():null).then(r=>{r&&nj.current&&tZ.current===e&&nf.current===t&&(nH(r.state),nG(r.state,e,t,n),r.state?.systemPrompt!==void 0&&eQ(r.state.systemPrompt??null),r.state?.extensionStatuses!==void 0&&tE(r.state.extensionStatuses??[]),r.state?.extensionWidgets!==void 0&&tI(r.state.extensionWidgets??[]),tT(ch(r.state?.queuedMessages)))}).catch(()=>{})}break;case"agent_settled":{let e=tQ.current;if(tQ.current=!1,!e||t0.current)break;let n=tZ.current,r=rb();tt(!1),n&&(nQ(n),rw(n)),r&&d?.({aborted:!0===t.aborted,...!0===t.subagentsActive?{subagentsActive:!0}:{}});break}case"prompt_done":{ny();let e=nf.current,n=t0.current;t0.current=!1,nm.current=null;let r=ry(e,!0===t.aborted,!0===t.subagentsActive);if(!n&&!r)break;let i=tZ.current;i&&nQ(i),!tQ.current&&(rb(),i&&rw(i))}break;case"prompt_error":rc({type:"error",message:t.errorMessage??"Command failed"});break;case"extension_error":var n,r;rc({type:"error",message:(n=t.extensionPath,r=t.error??"Extension command failed","string"==typeof n&&n&&!co.test(n)?`Extension "${n}" error: ${r}`:r)});break;case"message_start":case"message_update":if(!tX.current||ci(t))break;if("message_start"===t.type){let e=t.message;if(e?.role==="user")break;e?.role==="assistant"?(G({type:"snapshot",message:e}),e.content.length>0&&td(null)):e&&td(null)}else{let e=t.assistantMessageEvent;e&&(G({type:"delta",event:e}),"toolcall_start"!==e.type&&"toolcall_delta"!==e.type&&td(null))}!t9.current&&t7.current&&null===nt.current&&(nt.current=requestAnimationFrame(()=>{nt.current=null,t7.current&&nP("auto")}));break;case"message_end":{if(!tX.current){let e=t.message;e?.role==="custom"&&!rG(e)&&tZ.current&&rT.current?.(tZ.current);break}if(ci(t))break;let e=t.message;if(e&&"user"===e.role){let t=dz(e),n=d3(t),r=nm.current;nm.current=null,r&&ny(),z(e=>{let i=e[e.length-1];return r&&i?.role==="user"&&d3(i)===r?r===n?e:[...e.slice(0,-1),t]:[...e,t]})}else if(e){let n=Array.isArray(t.transcriptNotices)?t.transcriptNotices:void 0;if(z(t=>{var r;return[...t,(r=dz(e),n&&0!==n.length?{...r,[oq]:[...n]}:r)]}),"toolResult"===e.role){let t=e.toolCallId;F(e=>og(e,t))}if("assistant"===e.role){let e=tZ.current;e&&nX(e)}}G({type:"end"}),td({kind:"waiting_model"});break}case"tool_execution_start":{if(cr(t))break;let e=t.toolCallId,n=t.toolName,r=performance.now();F(e=>om(e,t,r)),td(t=>{let r=t?.kind==="running_tools"?[...t.tools]:[];return r.some(t=>t.id===e)||r.push({id:e,name:n}),{kind:"running_tools",tools:r}});break}case"tool_execution_update":{if(cr(t))break;let e=t.toolCallId,n=t.toolName,r=t.partialResult,i=r?.content;("bash"===n||"powershell"===n||n===oR)&&Array.isArray(i)&&W(t=>{let s=new Map(t);return s.set(e,{role:"toolResult",toolCallId:e,toolName:n,content:i,isError:r?.isError,details:r?.details}),s});let s=n===oR?function(e){if(!oL(e))return null;let{calls:t}=oP(e.details),n=t.findLast(e=>"running"===e.status)??t.at(-1);if(!n)return null;let r=n.args.length>120?`${n.args.slice(0,117)}...`:n.args;return r?`${n.name} ${r}`:n.name}(t.partialResult):function(e){if(!cs(e))return null;let t=e.content;if(!Array.isArray(t))return null;let n=t.filter(e=>cs(e)&&"text"===e.type&&"string"==typeof e.text).map(e=>e.text).join("\n").split(/\r?\n/),r="";for(let e=n.length-1;e>=0&&!(r=n[e].trim());e-=1);if(!r)return null;let i=r.replace(/\s+/g," ");return i.length<=500?i:`...${i.slice(-497)}`}(t.partialResult);td(t=>{let r=t?.kind==="running_tools"?[...t.tools]:[],i=r.find(t=>t.id===e),o={id:e,name:n||i?.name||"tool",progress:s??i?.progress};return{kind:"running_tools",tools:[...r.filter(t=>t.id!==e),o]}});break}case"tool_execution_end":{if(cr(t))break;let e=t.toolCallId;u?.(t.toolName);let n=performance.now();F(e=>om(e,t,n)),W(t=>{if(!t.has(e))return t;let n=new Map(t);return n.delete(e),n}),td(t=>{if(t?.kind!=="running_tools")return t;let n=t.tools.filter(t=>t.id!==e);return 0===n.length?{kind:"waiting_model"}:{kind:"running_tools",tools:n}});break}case"queue_update":ny(),tT({steering:[...t.steering??[]],followUp:[...t.followUp??[]]});break;case"auto_retry_start":case"summarization_retry_scheduled":eH({attempt:t.attempt,maxAttempts:t.maxAttempts,errorMessage:t.errorMessage});break;case"auto_retry_end":case"summarization_retry_attempt_start":case"summarization_retry_finished":eH(null);break;case"auto_compaction_start":case"compaction_start":tt(!0),ts(null),tl(null);break;case"auto_compaction_end":case"compaction_end":tt(!1),eH(null),t.errorMessage?(ts(t.errorMessage),tl(null)):!t.aborted&&(tl(cw(t.result,t.reason??"auto")),tZ.current&&nQ(tZ.current));break;case"bash_output":{let e=t.output;if(!t2.current||"string"!=typeof e)break;er(n=>n&&!n.result&&n.command===t.command?{...n,liveOutput:e}:n);break}case"editor_paste":"string"==typeof t.text&&e.chatInputRef?.current?.pasteText(rH(t.text));break;case"extension_ui_request":rv(t);break;case"extension_ui_closed":tj(e=>dA(e,t.id))}},[rc,nG,e.chatInputRef,rn,G,rv,nQ,ny,ry,d,c,u,nX,rw,nP,rb,nH]);let rR=(0,i.useCallback)(async(e,t)=>{let n=e.trim();if(!n&&!t?.length)return;let r=!t?.length&&n.startsWith("!");if(t2.current||tX.current&&!r){t2.current&&r&&rc({type:"warning",message:rp("chat.bashAlreadyRunning")}),nU(e,t,nB);return}if(nK&&(nV(null),!await nr.current?.(nK))){nV(nK),nU(e,t,nB);return}let i=!t?.length&&n.startsWith("/");if(r){let r=n.startsWith("!!"),i=(r?n.slice(2):n.slice(1)).trim();return i?void await nn.current?.(i,r):void nU(e,t,nB)}let s=nf.current+1;rn(),t0.current=!0;let a=t?.map(e=>({type:"image",source:{type:"base64",media_type:e.mimeType,data:e.data}})),d={role:"user",content:a?.length?[...e.trim()?[{type:"text",text:e}]:[],...a]:e,timestamp:Date.now()},c=d3(d),u=nE.current,p=u.at(-1)??null,h=cp(nN.current.slice(u.length),c);z(e=>[...e,d]),nm.current=c,nf.current=s,tX.current=!0,Q(!0),td(i?{kind:"running_command"}:{kind:"waiting_model"}),G({type:"start"}),t9.current=!0,tu(!0);let f=()=>{z(e=>{let t=e.lastIndexOf(d);return -1===t?e:[...e.slice(0,t),...e.slice(t+1)]}),nm.current=null},m=t?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),g=null,x=!1;try{if(S&&l){let t=tZ.current??await ns.current,n=t??await n8();if(!n)throw Error("Unable to create a session for the prompt");g=n,eC&&(e6(eC),t&&await dD(n,{type:"set_model",provider:eC.provider,modelId:eC.modelId})),nj.current&&await ri(n).catch(e=>{if(nj.current)throw e}),x=!0;let r=await dD(n,{type:"prompt",message:e,...m?.length?{images:m}:{}});r?.queued&&f(),n2(1,e)}else if(o){g=o.id,await ri(o.id),x=!0;let t=await dD(o.id,{type:"prompt",message:e,...m?.length?{images:m}:{}});t?.queued&&f()}else throw Error("No active session for the prompt");eh(null),i&&g&&rj(g,s)}catch(n){if(console.error("Failed to send message:",n),!(!x||dO(n))&&g){ng.current!==s&&(nx.current={runId:s,sid:g,message:e,images:t,draftKey:nB,parkedDraftKey:S&&l?lD(l):null,lastEntryIdAtSend:p,sameTextAfterSend:h,bubble:d,key:c,command:i},nj.current||rg()),rj(g,s);return}if(t0.current=!1,z(e=>cu(e,d)),n instanceof dW&&n.missingCwd?eh(n.missingCwd):rc({type:"error",message:n instanceof Error?n.message:String(n)}),nU(e,t,nB),nm.current=null,g)return void rC(g);tX.current=!1,rr("send_failed"),Q(!1),td(null),G({type:"end"})}},[S,l,eC,o,n8,ri,n2,rj,rc,rg,rn,rr,nB,G,rC,nU,nK,nV,rp]);nn.current=(0,i.useCallback)(async(e,t)=>{if(t2.current)return;let n=`${t?"!!":"!"}${e}`;t2.current=!0;let r=Date.now();er({command:e,excludeFromContext:t,startedAt:r}),et(!0);let i=null;try{let s=tZ.current??o?.id??await n8();if(!s)throw Error("Unable to create a session for the shell command");await ri(s).catch(()=>{});let l=await dD(s,{type:"bash",command:e,excludeFromContext:t});tX.current&&l?(i={command:e,excludeFromContext:t,startedAt:r,result:l},t4.current=nv.current):(await nQ(s),n2(1,n))}catch(e){console.error("Failed to execute shell command:",e),e instanceof dW&&"extension_reported"===e.code||rc({type:"error",message:e instanceof Error?e.message:String(e)}),nU(n,void 0,nB)}finally{t2.current=!1,er(i),et(!1);let e=r$.current;r$.current=null,e&&rT.current?.(e)}},[rc,nB,ri,n8,nQ,n2,nU,o]);let rA=en?.result;(0,i.useEffect)(()=>{if(X||!rA)return;let e=tZ.current;e&&nQ(e,!1,!1,{force:!0})},[X,rA,nQ]);let rL=(0,i.useCallback)(t=>{let n=[...t?.steering??[],...t?.followUp??[]].join("\n\n");t?.images?.length?nU(n,t.images,nB):n&&e.chatInputRef?.current?.prependText(n)},[nB,e.chatInputRef,nU]),rz=(0,i.useCallback)(async()=>{let e=tZ.current;if(e){if(t2.current&&!tX.current){try{await dD(e,{type:"abort_bash"})}catch(e){console.error("Failed to abort bash:",e)}return}try{let t=await dD(e,{type:"abort"});t&&tT({steering:[],followUp:[]}),rL(t)}catch(e){console.error("Failed to abort:",e)}}},[rL]),rP=(0,i.useCallback)(async(e,t)=>{if(t2.current)return;let n=tZ.current;if(n){e1(e);try{let{cancelled:r,newSessionId:i}=await dD(n,{type:"fork",entryId:e})??{};!r&&i&&(t&&lU(i,t),f?.(i))}catch(e){console.error("Fork failed:",e),rc({type:"error",message:e instanceof Error?e.message:String(e)})}finally{e1(null)}}},[rc,f]),rW=(0,i.useCallback)(async e=>{if(t2.current)return!1;let t=tZ.current;if(!t)return!1;try{let n=await dD(t,{type:"navigate_tree",targetId:e});if(n?.cancelled||tZ.current!==t)return!1;return await nQ(t),tZ.current===t}catch(e){return console.error("Failed to navigate:",e),!1}},[nQ]);nr.current=rW;let rO=(0,i.useCallback)(async e=>{if(t2.current||tX.current||te)return;A(e);let t=tZ.current;t&&(await n0(t,e),e&&dD(t,{type:"navigate_tree",targetId:e}).catch(()=>{}))},[te,n0]),rF=(0,i.useCallback)(async(e,t)=>{if(S){let n={provider:e,modelId:t};nc.current=n,eN(n),e6(n),null===nu.current&&eL(cf(np.current[`${e}/${t}`])??nh.current);let r=tZ.current??await ns.current;if(!r)return;try{await dD(r,{type:"set_model",provider:e,modelId:t})}catch(e){console.error("Failed to set model:",e)}return}let n=tZ.current;if(!n||nw.current)return;nw.current=!0,e4({provider:e,modelId:t}),e7(!0);let r=tX.current||t2.current,i=async()=>{let e=await fetch(dF(n)).catch(()=>null),t=e?.ok?await e.json().catch(()=>null):null;t?.state&&nj.current&&tZ.current===n&&nH(t.state)};try{let s=await dD(n,{type:"set_model",provider:e,modelId:t});e3({provider:s.provider,modelId:s.id}),nw.current=!1,r?(e4(null),await i()):await nQ(n)}catch(e){console.error("Failed to set model:",e),nw.current=!1,e4(e2),rc({type:"error",message:`Failed to switch model: ${e instanceof Error?e.message:String(e)}`}),r?await i():await nQ(n,!1,!0)}finally{nw.current=!1,e7(!1)}},[rc,e2,S,nQ,eN,nH]),rD=(0,i.useCallback)(async e=>{let t=tZ.current;if(!t||te)return!0;tt(!0),ts(null),tl(null);try{let n=await dD(t,{type:"compact",...e?{customInstructions:e}:{}});return tl(cw(n,"manual")),await nQ(t)&&n2(),!0}catch(e){return ts(e instanceof Error?e.message:String(e)),tl(null),!1}finally{tt(!1)}},[te,nQ,n2]),rB=(0,i.useCallback)(()=>ts(null),[]),r_=(0,i.useCallback)(async e=>{let t,n=l??o?.cwd??"",r=n?`/api/models?cwd=${encodeURIComponent(n)}`:"/api/models",i=null;try{let n=await fetch(r,e?{signal:e}:void 0);if(!n.ok){let e="";try{let t=await n.json();t&&"object"==typeof t&&"error"in t&&"string"==typeof t.error&&(e=t.error),i=dP(t)}catch(e){if(e instanceof DOMException&&"AbortError"===e.name)throw e}throw Error(e||`Failed to load models (HTTP ${n.status})`)}t=await n.json(),e?.throwIfAborted()}catch(t){throw e?.aborted||t instanceof DOMException&&"AbortError"===t.name||(eu(i),ed(i?null:t instanceof Error?t.message:String(t))),t}eu(null),es(t.models),ed(t.modelError??null),em(t.modelScopeWarnings??[]),ex(!!t.isScoped),eb(null),ey.current=null,ek(t.thinkingLevels??{}),eS(t.thinkingLevelMaps??{});let s=t.modelList??[];el(s);let a=t.defaultModel?s.find(e=>e.id===t.defaultModel?.modelId&&e.provider===t.defaultModel?.provider):void 0;if(e$(a?{provider:a.provider,modelId:a.id}:null),np.current=t.thinkingLevelPins??{},nh.current=cf(t.defaultThinkingLevel),eP(cf(t.savedDefaultThinkingLevel)),S&&!tZ.current){let e=nc.current,n=e&&(0===s.length||!!t.isScoped||s.some(t=>t.provider===e.provider&&t.id===e.modelId));e&&!n&&(nc.current=null,eN(null));let r=n?e:a&&{provider:a.provider,modelId:a.id},i=r&&t.thinkingLevelPins?.[`${r.provider}/${r.modelId}`];null===nu.current&&eL(cf(i)??nh.current)}},[S,l,o?.cwd]),rU=(0,i.useCallback)(()=>{if(ey.current)return;let e={};ey.current=e;let t=l??o?.cwd??"";fetch(`/api/models?scope=all${t?`&cwd=${encodeURIComponent(t)}`:""}`).then(async t=>{if(!t.ok)throw Error(`Failed to load models (HTTP ${t.status})`);let n=await t.json();ey.current===e&&(es(e=>({...n.models,...e})),ek(e=>({...n.thinkingLevels,...e})),eS(e=>({...n.thinkingLevelMaps,...e})),eb(n.modelList??[]))}).catch(t=>{ey.current===e&&(ey.current=null,rc({type:"error",message:t instanceof Error?t.message:String(t)}))})},[rc,l,o?.cwd]);(0,i.useEffect)(()=>{!eg||!nO||ev||eo.some(e=>e.provider===nO.provider&&e.id===nO.modelId)||rU()},[ev,nO,eg,rU,eo]);let rK=(0,i.useCallback)(async e=>{let t=l??o?.cwd,n=await fetch("/api/models/default",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({...t?{cwd:t}:{},...e})});if(n.ok)return;let r="";try{let e=await n.json();e&&"object"==typeof e&&"error"in e&&"string"==typeof e.error&&(r=e.error)}catch{}throw Error(r||`HTTP ${n.status}`)},[l,o?.cwd]),rq=(0,i.useCallback)(()=>{r_().catch(()=>{})},[r_]),rV=(0,i.useCallback)(async(e,t)=>{try{await rK({provider:e,modelId:t})}catch(e){rc({type:"error",message:`Failed to save default model: ${e instanceof Error?e.message:String(e)}`});return}rc({type:"success",message:`Default model: ${e}/${t}`}),e$({provider:e,modelId:t}),(nO?.provider!==e||nO?.modelId!==t)&&await rF(e,t),rq()},[rc,nO,rF,rq,rK]),rZ=(0,i.useCallback)(async(t,n)=>{let r=e.session?.relation?.kind;if("side"===r||"subagent"===r)return rp(dB[r]);let i=tZ.current;if(!i)return rp("sideChat.error.noSession");let s=await dH(i,rp,n);return"error"in s?s.error:(m?.(s.session,t),null)},[m,e.session?.relation?.kind,rp]),rJ=(0,i.useCallback)(async t=>{if(!t.startsWith("/"))return{handled:!1};let n=t.match(/^\/([^\s]+)(?:\s+([\s\S]*))?$/);if(!n)return{handled:!1};let[,r,i=""]=n,s=i.trim(),o=tZ.current??await n8(),l=e=>(e.handled&&(e.error?rc({type:"error",message:e.error}):e.action||rc({type:"success",message:e.message??"Command completed"})),e);try{switch(r){case"compact":if(!o||te)return l({handled:!0,error:"No active session to compact"});return rD(s||void 0).then(t=>{!t&&s&&e.chatInputRef?.current?.prependText(`/compact ${s}`)}),l({handled:!0,action:"compact"});case"auto-compact":{if(!o)return l({handled:!0,error:"No active session"});let e=await dD(o,{type:"get_state"}),t=!(e?.autoCompactionEnabled??!0);return await dD(o,{type:"set_auto_compaction",enabled:t}),tr(t),l({handled:!0,message:t?"Auto-compaction enabled":"Auto-compaction disabled"})}case"reload":if(!o)return l({handled:!0,error:"No active session to reload"});return await dD(o,{type:"reload"}),await Promise.all([nQ(o,!1,!0),n1(o),re(),r_()]),l({handled:!0,message:"Reloaded session resources"});case"name":if(!o)return l({handled:!0,error:"No active session to name"});if(!s)return l({handled:!0,error:"Usage: /name <name>"});return await dD(o,{type:"set_session_name",name:s}),await nQ(o)&&n2(),l({handled:!0,message:`Session renamed to ${s}`});case"session":{if(!o)return l({handled:!0,error:"No active session"});if(!w)return l({handled:!0,message:function(e,t){if(!e)return t("session.noUsage");let n=d2(e.cost);return[t(1===e.totalMessages?"session.usageSummaryOne":"session.usageSummary",{messages:e.totalMessages,tokens:d1(e.tokens.total)}),...n?[n]:[]].join(" \xb7 ")}(nY,rp)});let e=await dD(o,{type:"get_session_stats"});return e&&tw(e),w(),l({handled:!0,action:"openSessionStats"})}case"mcp":{if(s||!k)return{handled:!1};let e=await rt();if(!e||!(e.some(l1)||!e.some(e=>"mcp"===e.name)))return{handled:!1};return k("mcp"),l({handled:!0,action:"openSettings"})}case"copy":{if(!o)return l({handled:!0,error:"No active session"});let e=await dD(o,{type:"get_last_assistant_text"}),t=e?.text??"";if(!t)return l({handled:!0,error:"No assistant message to copy"});return await iN(t),l({handled:!0,message:"Copied last assistant message"})}case"clone":{if(!o)return l({handled:!0,error:"No active session to clone"});if(tX.current||t2.current)return l({handled:!0,error:"Cannot clone while the session is running"});let e=rE.current,t=await dD(o,{type:"clone",leafId:e?.base===R&&e.lastEntryId===nE.current.at(-1)?e.leafId:R});if(t?.cancelled&&t.byExtension)return{handled:!0};if(t?.cancelled||!t?.newSessionId)return l({handled:!0,error:"Cannot clone an empty or unsaved session"});let n=l({handled:!0,message:"Cloned current session branch"});return f?.(t.newSessionId),n}case"side":{let e=await rZ(s||null);return l(e?{handled:!0,error:e}:{handled:!0,action:"openSideChat"})}default:return{handled:!1}}}catch(e){return l({handled:!0,error:e instanceof Error?e.message:String(e)})}},[R,rc,n8,rD,te,r_,nQ,re,n1,n2,k,f,w,e.chatInputRef,nY,rt,rZ,rp]),rY=(0,i.useCallback)(async(e,t,n)=>{let r=tZ.current;if(nK)return void nU(e,n,nB);if(!r){nU(e,n,nB),rc({type:"error",message:"No active session for the queued message"});return}let i=n?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType}));try{await dD(r,{type:"prompt",message:e,streamingBehavior:t,...i?.length?{images:i}:{}})}catch(t){if(console.error("Failed to submit streaming prompt:",t),nU(e,n,nB),t instanceof dW&&t.missingCwd)return void eh(t.missingCwd);dO(t)?rc({type:"error",message:t.message}):rh()}},[rc,rh,nB,nK,nU]),rX=(0,i.useCallback)(async(e,t)=>{await rY(e,"steer",t)},[rY]),rQ=(0,i.useCallback)(async(e,t,n)=>{await rY(e,t,n)},[rY]),r0=(0,i.useCallback)(async(e,t)=>{await rY(e,"followUp",t)},[rY]),r1=(0,i.useCallback)(async()=>{let e=tZ.current;if(e)try{await dD(e,{type:"abort_compaction"})}catch(e){console.error("Failed to abort compaction:",e)}},[]),r2=(0,i.useCallback)(async()=>{let e=tZ.current;if(e)try{let t=await dD(e,{type:"clear_queue"});tT({steering:[],followUp:[]}),rL(t)}catch(e){console.error("Failed to recall queued messages:",e),rc({type:"error",message:"Failed to recall queued messages"})}},[rc,rL]),r4=(0,i.useCallback)(async e=>{if("auto"===e){nu.current=null,eR(null),eO(null);return}S?(nu.current=e,eR(e)):eO(e);let t=tZ.current??await ns.current;if(t)try{await dD(t,{type:"set_thinking_level",level:e}),nj.current&&tZ.current===t&&(eD(e),eO(null))}catch(e){console.error("Failed to set thinking level:",e),eO(null)}},[S]),r8=(0,i.useCallback)(async e=>{try{await rK({thinkingLevel:e})}catch(e){rc({type:"error",message:`Failed to save default reasoning level: ${e instanceof Error?e.message:String(e)}`});return}rc({type:"success",message:`Default reasoning level: ${e}`}),eP(e),nD!==e&&await r4(e),rq()},[rc,nD,r4,rq,rK]),r3=(0,i.useCallback)(async e=>{let t=(0,dY.xG)(e);!function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:dX();if(t)try{t.setItem(dG,e)}catch{}}(e),nA(e);let n=tZ.current??await ns.current;if(!n){tG.current=void 0!==t;return}try{let e=await dD(n,{type:"set_tools",...void 0!==t?{toolNames:t}:{}});tG.current=void 0!==t;let r=e?.sessionId??n;(r!==n||e?.recreated)&&(rn(),rr("set_tools"),tj([]),tC([]),tZ.current=r,e?.recreated&&tY.current===r&&rs(r)),n6(),tE([]),tI([]);let[i]=await Promise.all([dD(r,{type:"get_state"}),n1(r)]);nj.current&&tZ.current===r&&(eQ(i.systemPrompt??""),nH(i))}catch(e){console.error("Failed to set tools:",e)}},[rn,n6,rr,n1,rs,nA,nH]),r5=(0,i.useCallback)(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:16,n=ni.current;n&&(null!==nt.current&&(cancelAnimationFrame(nt.current),nt.current=null),t5.current=!0,t9.current=!1,t7.current=!1,tu(!1),n.scrollTo({top:e.getBoundingClientRect().top-n.getBoundingClientRect().top+n.scrollTop-t,behavior:"instant"}),ne.current=n.scrollTop)},[]),r6=(0,i.useCallback)(()=>{let e=ni.current,t=t6.current;if(!e||!t)return;let n=Math.min(Math.max(0,t.getBoundingClientRect().top-e.getBoundingClientRect().top+e.scrollTop-16),Math.max(0,e.scrollHeight-e.clientHeight));null!==nt.current&&(cancelAnimationFrame(nt.current),nt.current=null),t7.current=!0,ne.current=n,e.scrollTo({top:n,behavior:"auto"})},[]),r9=(0,i.useCallback)(()=>{let e=ni.current;if(e){let{scrollTop:t,clientHeight:n,scrollHeight:r}=e,i=tX.current,s=t7.current,o=function(e,t,n,r,i){let s=arguments.length>5&&void 0!==arguments[5]?arguments[5]:96;return!!cl(n,r,i)||!(n<t)&&(!!(!e&&n>t&&cl(n,r,i,s))||e)}(s,ne.current,t,n,r,i?96:8);t7.current=o,ne.current=t;let l=function(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:8;return!(n<=t)&&!cl(e,t,n,r)}(t,n,r);th(e=>e===l?e:l),!s&&o&&i?nP("auto"):o||null===nt.current||(cancelAnimationFrame(nt.current),nt.current=null)}},[nP]),r7=(0,i.useCallback)((e,t)=>{t?.running&&(n1(e),(t.state?.isStreaming||t.state?.isPromptRunning)&&(tQ.current=!!t.state.isStreaming,t0.current=!!t.state.isPromptRunning,tX.current=!0,Q(!0),td(e=>dM(e,t.state?.isStreaming===!0)),G({type:"resume"}),!t.state.isStreaming&&t.state.isPromptRunning&&rj(e)),t.state?.isBashRunning&&(t2.current=!0,et(!0),rS(e))),t?.state&&(void 0!==t.state.isCompacting&&tt(t.state.isCompacting),void 0!==t.state.systemPrompt&&eQ(t.state.systemPrompt??null),void 0!==t.state.extensionStatuses&&tE(t.state.extensionStatuses??[]),void 0!==t.state.extensionWidgets&&tI(t.state.extensionWidgets??[]),void 0!==t.state.queuedMessages&&tT(ch(t.state.queuedMessages)))},[G,n1,rS,rj]);tD.current=(e,t)=>{!tP.current||tJ.current===e||(tP.current=!1,t_.current={count:t_.current.count+1,lastAt:Date.now(),lastReason:t},tO(e=>e+1),nj.current&&tZ.current===e&&tY.current===e&&(rs(e),nQ(e,!1,!0).then(t=>{nj.current&&tZ.current===e&&r7(e,t)})))},(0,i.useEffect)(()=>{let e=o?.id;if(!e)return;let t=!1,n=tB.current,r=async()=>{let n=await ro(e);!t&&"hidden"===document.visibilityState&&d7(n)&&tD.current(e,"activity")};r();let i=setInterval(()=>void r(),3e4);n.renewStartedAt=Date.now();let s=()=>{"visible"===document.visibilityState&&(tD.current(e,"visible"),r())};return document.addEventListener("visibilitychange",s),()=>{t=!0,clearInterval(i),n.renewStartedAt=null,document.removeEventListener("visibilitychange",s)}},[ro,o?.id]),(0,i.useEffect)(()=>{if(nj.current=!0,eG.current=eY.current,o){tZ.current=o.id;let e=dV(o.id);e&&(E({sessionId:o.id,filePath:"",totalActiveMs:e.totalActiveMs??0,tree:e.summaryTree,leafId:e.leafId,context:{messages:e.messages,entryIds:e.entryIds,oldestEntryId:e.oldestEntryId,hasMore:e.hasMore,turnsBefore:e.turnsBefore,thinkingLevel:e.thinkingLevel,model:e.model},stats:e.stats}),A(e.leafId),z(e.messages),B(e.entryIds),K(e.oldestEntryId),V(e.hasMore),J(e.turnsBefore),T(null),I(!1)),nQ(o.id,!e,!0,{force:!0}).then(e=>{r7(o.id,e)})}return()=>{nj.current=!1;let e=S?a:null;e&&queueMicrotask(()=>{nj.current||nd.current||lK(e)});let t=tZ.current,n=nC.current;if(t&&n&&n.sessionId===t&&n.snapshotRevision){let e=dV(t),r=nE.current;!e||function(e,t){if(0===t.length)return!0;let n=new Set([...e.entryIds,...e.loadedEntryIds]);return t.every(e=>n.has(e))}(e,r)?dZ({sessionId:t,revision:n.snapshotRevision,messages:nN.current,entryIds:nE.current,leafId:n$.current,oldestEntryId:nI.current,hasMore:nM.current,turnsBefore:nT.current,summaryTree:n.tree,thinkingLevel:n.context.thinkingLevel,model:n.context.model,stats:n.stats,totalActiveMs:n.totalActiveMs,loadedEntryIds:nE.current}):dJ(t)}rx.current(),null!==nt.current&&(cancelAnimationFrame(nt.current),nt.current=null),t8.current+=1,rn(),rr()}},[]),(0,i.useEffect)(()=>{v?.(eX)},[eX,v]),(0,i.useEffect)(()=>(y?.(n3),()=>y?.(null)),[n3,y]);let ie=(0,i.useCallback)(()=>{let e,t=null;try{t=tR.current?.snapshot?.()??null}catch{t=null}let n=tZ.current,r=tB.current,i=t_.current;return{pageId:"string"==typeof(e=globalThis[eU])?e:null,sessionId:n,selectedSessionId:tY.current,mounted:nj.current,wantsStream:null!==n&&nR(n),connection:t,released:{active:tP.current,...tH.current},reattached:{...i},hiddenReleaseDueAt:tU.current,hiddenGraceMs:3e4,graceDueAt:tK.current,run:{agentRunning:tX.current,bashRunning:t2.current,compacting:tq.current,dialogs:tV.current},lease:{renewIntervalMs:3e4,renewStartedAt:r.renewStartedAt,inFlightSince:r.inFlightSince,requests:r.requests,unanswered:r.unanswered,errors:r.errors,last:r.last&&{...r.last,reply:r.last.reply&&{...r.last.reply}}}}},[nR]);(0,i.useEffect)(()=>(j?.(ie),()=>j?.(null)),[ie,j]);let it=X||ee||te;(0,i.useEffect)(()=>{x&&x(N?.tree??[],R,rO,it)},[N?.tree,R,rO,it,x]),(0,i.useEffect)(()=>{let e=ni.current;if(e)return ne.current=e.scrollTop,e.addEventListener("scroll",r9,{passive:!0}),()=>{e.removeEventListener("scroll",r9)}},[L.length,$,r9]),(0,i.useEffect)(()=>{X||tu(!1)},[X]),(0,i.useLayoutEffect)(()=>{L.length>0&&(t9.current?(t9.current=!1,t5.current=!0,r6()):t5.current?!tX.current&&t7.current&&nP("auto"):(t5.current=!0,nP("instant")))},[L.length,X,nP,r6]),(0,i.useEffect)(()=>{let e=new AbortController;return(async()=>{for(let t=0;;t++)try{await r_(e.signal);return}catch(n){if(e.signal.aborted||n instanceof DOMException&&"AbortError"===n.name||t>=cg.length||(await cv(cg[t]),e.signal.aborted))return}})(),()=>e.abort()},[r_,g]),(0,i.useEffect)(()=>{if(!to)return;let e=setTimeout(()=>tl(null),6e3);return()=>clearTimeout(e)},[to]);let[ir,ii]=(0,i.useState)(null),is=(0,i.useRef)(5e3),io=(0,i.useRef)(null),il=(0,i.useRef)(null);(0,i.useEffect)(()=>{if(0===tv.visible.length){il.current=null;return}let e=tv.visible.find(e=>e.exiting);if(e){let t=setTimeout(()=>{tb({type:"remove",id:e.id})},180);return()=>clearTimeout(t)}let t=tv.visible[0];if(!t||(il.current!==t.id&&(il.current=t.id,is.current=5e3),tv.visible.some(e=>e.id===ir)))return;io.current=Date.now();let n=setTimeout(()=>{tb({type:"mark_oldest_exiting"})},is.current);return()=>{clearTimeout(n),null!==io.current&&(is.current=Math.max(0,is.current-(Date.now()-io.current)),io.current=null)}},[tv.visible,ir]),(0,i.useEffect)(()=>{tw(null)},[L.length,e_?.tokens,e_?.percent,e_?.contextWindow]);let ia=nD??"auto",id=tk[0]??null,ic=Math.max(0,tk.length-1),iu=tS[0]??null,ip=Math.max(0,tS.length-1),ih=(0,i.useMemo)(()=>(function(e,t,n){let r=e[e.length-1],i=[];for(let s=0;s<t;s++){let t=e[s];i.push(void 0===t?d5(r,s-e.length):n.get(t)??t)}return i})(D,L.length,H),[D,L.length,H]);return{data:N,loading:$,error:M,activeLeafId:R,messages:L,activeToolResults:P,toolClocks:O,entryIds:D,messageKeys:ih,historyCursor:U,hasEarlierMessages:q,earlierTurnCount:Z,streamingStore:Y,agentRunning:X,modelNames:ei,modelList:eo,modelError:ea,missingCwd:ep??ec,modelScopeWarnings:ef,isModelScopeActive:eg,allModelList:ev,modelThinkingLevels:ew,modelThinkingLevelMaps:ej,newSessionModel:eC,toolPreset:eI,thinkingLevel:ia,retryInfo:eB,contextUsage:e_,systemPrompt:eX,forkingEntryId:e0,isCompacting:te,compactError:ti,compactResult:to,currentModel:nW,displayModel:nO,modelSwitching:e9,sessionStats:nY,autoCompactionEnabled:tn,slashCommands:tf,slashCommandsLoading:tg,queuedMessages:tM,notices:tv.visible,extensionDialog:id,waitingExtensionDialogCount:ic,extensionCustomUi:iu,waitingExtensionCustomUiCount:ip,extensionStatuses:tN,extensionWidgets:t$,respondToExtensionUi:ra,sendExtensionCustomInput:rd,isAutoModelSelection:S&&null===eC,isAutoThinkingSelection:S&&null===eT,defaultModel:eE,savedDefaultThinkingLevel:ez,agentPhase:ta,isNew:S,editEntryId:nK,promptAnchorActive:tc,showScrollToBottom:tp,sessionIdRef:tZ,scrollContainerRef:ni,lastUserMsgRef:t6,pendingScrollToUserRef:t9,initialScrollDoneRef:t5,handleSend:rR,handleAbort:rz,startSideChat:rZ,handleFork:rP,handleNavigate:rW,handleModelChange:rF,handleCompact:rD,handleSteer:rX,handleFollowUp:r0,handlePromptWithStreamingBehavior:rQ,handleAbortCompaction:r1,dismissCompactError:rB,handleRecallQueue:r2,handleBuiltinSlashCommand:rJ,handleEditContent:nZ,cancelEdit:nK?nJ:void 0,addNotice:rc,setNoticePaused:ii,handleToolPresetChange:r3,handleThinkingLevelChange:r4,handleSetDefaultModel:rV,handleSetDefaultThinkingLevel:r8,loadTools:n1,loadSlashCommands:re,loadAllModels:rU,setActiveLeafId:A,setData:E,setMessages:z,loadContext:n0,scrollToBottom:nP,scrollUserMsgToTop:r6,scrollToMessage:r5,dispatch:G,setAgentRunning:Q,setForkingEntryId:e1,bashRunning:ee,pendingBash:en,handleAgentEventRef:t3}}({session:s,sessionRunning:p,newSessionCwd:h,newSessionDraftKey:f,initialNewSessionChoices:g,onNewSessionChoicesChange:x,onAgentEnd:ee,onSessionEnded:b,onToolEnd:y,onAttentionNeeded:w,onSessionCreated:k,onSessionForked:j,onSideSession:C,modelsRefreshKey:N,chatInputRef:E,onBranchDataChange:$,onSystemPromptChange:I,onSystemToolsChange:M,onSystemInfoLoaderChange:T,onSessionStatsPanelOpen:L,onOpenSettings:z,onDebugSnapshotReaderChange:R,t:Z,deferInitialScroll:!!en}),tL=ck(eg,cj),tP=ck(eg,cS),tW=(0,i.useCallback)(()=>eg.getState().streamingMessage,[eg]),tO=ex||ev,tF=(0,i.useCallback)((e,t)=>{ta(e,{value:a7(t),images:de(t)})},[ta]);(0,i.useEffect)(()=>{if(ex&&V)return V()},[ex,V]);let[tD,tB]=(0,i.useState)(null),[tH,t_]=(0,i.useState)(!1),[tU,tK]=(0,i.useState)(!1),[tq,tV]=(0,i.useState)(null),tZ=(0,i.useRef)(null),tJ=(0,i.useRef)(null),tY=(0,i.useCallback)(()=>{tB(null),t_(!1),tV(null)},[]);(0,i.useEffect)(()=>{D||tY()},[D,tY]);let tG=(0,i.useCallback)(()=>{if(!D||tH)return;let e=window.getSelection(),t=e?.rangeCount?e.getRangeAt(0):null,n=t5.current;if(!e||e.isCollapsed||!t||!n||!n.contains(t.commonAncestorContainer))return void tB(null);let r=e.toString().trim();if(!r)return void tB(null);let i=t.getBoundingClientRect();tB({text:r,top:Math.min(window.innerHeight-44,i.bottom+8),left:Math.max(64,Math.min(window.innerWidth-64,i.left+i.width/2))})},[D,tH]);(0,i.useEffect)(()=>{tH&&tD&&tJ.current?.insertIfEmpty(ij(tD.text))},[tH,tD]),(0,i.useLayoutEffect)(()=>{let e=tZ.current;if(!e||!tD)return;let t=window.visualViewport,n=()=>{let n=e.getBoundingClientRect(),r=t?.offsetTop??0,i=t?.offsetLeft??0;e.style.top=`${Math.max(r+8,Math.min(tD.top,r+(t?.height??window.innerHeight)-n.height-8))}px`,e.style.left=`${Math.max(i+8,Math.min(tD.left-n.width/2,i+(t?.width??window.innerWidth)-n.width-8))}px`};n();let r=new ResizeObserver(n);return r.observe(e),window.addEventListener("resize",n),t?.addEventListener("resize",n),t?.addEventListener("scroll",n),()=>{r.disconnect(),window.removeEventListener("resize",n),t?.removeEventListener("resize",n),t?.removeEventListener("scroll",n)}},[tD,tH,tq]),(0,i.useEffect)(()=>{if(!tD)return;let e=e=>{tH||tZ.current?.contains(e.target)||tY()},t=e=>{"Escape"===e.key&&!e.isComposing&&(e.preventDefault(),e.stopPropagation(),tU||tY())};return document.addEventListener("pointerdown",e),document.addEventListener("keydown",t),()=>{document.removeEventListener("pointerdown",e),document.removeEventListener("keydown",t)}},[tD,tH,tU,tY]);let tX=(0,i.useCallback)(()=>{tD&&(E?.current?.insertQuote(ij(tD.text)),tY())},[E,tD,tY]),tQ=(0,i.useCallback)(async e=>{if(!tU&&e.trim()&&tD){tK(!0),tV(null);try{let t=await tl(e,tD.text);if(!t)return void tY();tJ.current?.restoreSubmission(e),tV(t)}catch(t){tJ.current?.restoreSubmission(e),tV(t instanceof Error?t.message:String(t))}finally{tK(!1)}}},[tD,tU,tY,tl]),t0=(0,i.useCallback)(async e=>{let t;try{t=await tl(e)}catch(e){t=e instanceof Error?e.message:String(e)}t&&(E?.current?.restoreSubmission(e),e2({type:"error",message:t}))},[e2,E,tl]),t1=(0,i.useRef)(!1);(0,i.useEffect)(()=>{eo||el||!B||t1.current||(t1.current=!0,H?.(),ts(B))},[B,eo,el,ts,H]),(0,i.useEffect)(()=>{let e=!!eq&&!Q.current;Q.current=!!eq,Y&&e&&G.current()},[Y,eq]),(0,i.useEffect)(()=>{S||(o=tO?to:null)},[S,tO,to]);let[t2,t4]=(0,i.useState)(50),[t8,t3]=(0,i.useState)(null),t5=(0,i.useRef)(null),t6=(0,i.useRef)(null),ne=(0,i.useRef)(!1),nr=(0,i.useRef)(!1),ni=(0,i.useRef)(en);ni.current=en;let[ns,no]=(0,i.useState)(null),nl=ea[eu.indexOf(ns?.entryId??"")],na=nl?.role==="assistant"?ns?.blockIndex===void 0?nl.content.find(e=>"text"===e.type):nl.content[ns.blockIndex]:void 0,nd=(0,i.useRef)({entryIds:eu,historyCursor:eh,hasEarlierMessages:ef});nd.current={entryIds:eu,historyCursor:eh,hasEarlierMessages:ef};let nc=(0,i.useRef)(null),nu=(0,i.useCallback)(async(e,t,n)=>{nc.current=t;let r=await tM(e,tT,t,n);return r||nc.current!==t||(nc.current=null),r},[tT,tM]);(0,i.useEffect)(()=>{eh!==nc.current&&(nc.current=null)},[eh]),(0,i.useLayoutEffect)(()=>{let e=s?.id,t=tn.current,n=t5.current;if(e&&u&&t&&n)return()=>{if(ni.current)return;if(cl(t.scrollTop,t.clientHeight,t.scrollHeight))return void u(e,{atBottom:!0});let r=t.getBoundingClientRect().top,i=function(e,t){let n=e[0];for(let r of e){if(r.top>t)break;n=r}return n?{anchorEntryId:n.entryId,anchorOffset:n.top-t}:null}(Array.from(n.children).flatMap(e=>{if(!(e instanceof HTMLElement)||!e.dataset.entryId)return[];let t=e.getBoundingClientRect();return[{entryId:e.dataset.entryId,top:t.top,bottom:t.bottom}]}),r);i&&u(e,{atBottom:!1,...i,oldestEntryId:nd.current.historyCursor})}},[eo,u,tn,s?.id]),(0,i.useEffect)(()=>{l&&er(null)},[l]),(0,i.useEffect)(()=>{let e=s?.id;if(!en||!e||eo||l||nr.current)return;nr.current=!0;let t=new AbortController;return(async()=>{let n=nd.current;if(n.entryIds.includes(en.anchorEntryId)){t4(e=>Math.max(e,2*n.entryIds.length)),es(!0);return}ne.current=!0;let r=n.historyCursor,i=n.hasEarlierMessages;try{for(;i&&r&&!t.signal.aborted;){let n=await nu(e,r,{signal:t.signal});if(t.signal.aborted)return;if(!n){tR("instant"),er(null);return}if(t4(e=>e+Math.max(50,2*n.messages.length)),n.entryIds.includes(en.anchorEntryId))return void es(!0);if(n.oldestEntryId===en.oldestEntryId)break;r=n.oldestEntryId,i=n.hasMore}t.signal.aborted||(tR("instant"),er(null))}finally{ne.current=!1}})(),()=>{t.abort(),er(null)}},[tT,nu,eo,en,tR,l,s?.id]),(0,i.useLayoutEffect)(()=>{let e=t5.current;if(!en||!e||l)return;let t=Array.from(e.children).find(e=>e instanceof HTMLElement&&e.dataset.entryId===en.anchorEntryId);if(t instanceof HTMLElement){tA(t,en.anchorOffset),er(null);return}ei&&(tR("instant"),er(null))},[eu,en,ei,tR,tA,l,t2]),(0,i.useEffect)(()=>{if(!l||eo)return;let e=new AbortController;return(async()=>{let t=nd.current,n=t.entryIds.includes(l.entryId);if(!n&&!tO&&t.hasEarlierMessages&&t.historyCursor&&!ne.current){ne.current=!0;let r=tn.current;r&&(t6.current=r.scrollHeight-r.scrollTop);let i=await nu(l.sessionId,t.historyCursor,{tail:200,signal:e.signal});ne.current=!1,n=!!i?.entryIds.includes(l.entryId)}e.signal.aborted||(n?(t6.current=null,t4(e=>Math.max(e,(nd.current.entryIds.length+200)*2)),no(l)):d?.(l))})(),()=>e.abort()},[l,eo,tO,nu,d,tn]),(0,i.useLayoutEffect)(()=>{if(!ns||ns!==l)return;let e=`[data-entry-id="${CSS.escape(ns.entryId)}"]`,t=tn.current?.querySelector(nl?.role==="user"?e:`${e} [data-search-target]`);t&&(tA(t),t.animate([{backgroundColor:"var(--bg-selected)"},{backgroundColor:"transparent"}],{duration:2500})),no(null),d?.(ns)},[ns,l,nl,tn,tA,d]),(0,i.useEffect)(()=>{let e=tn.current;if(!t8||!e)return;let t=new IntersectionObserver(t=>{if(!t[0]?.isIntersecting||ne.current)return;if(!ef){t6.current=e.scrollHeight-e.scrollTop,t4(e=>(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:50;return e+t})(e));return}if(!eh||eh===nc.current)return;let n=s?.id??tt.current;n&&(ne.current=!0,t6.current=e.scrollHeight-e.scrollTop,nu(n,eh).finally(()=>{ne.current=!1}))},{root:e,threshold:0});return t.observe(t8),()=>t.disconnect()},[t8,t2,eh,ef,s,nu,tt,tn]),(0,i.useEffect)(()=>{t4(e=>Math.max(e,ea.length))},[ea.length]),(0,i.useEffect)(()=>{if(null==t6.current)return;let e=tn.current;if(e){var t;t=e.scrollHeight,e.scrollTop=Math.max(0,t-t6.current),t6.current=null}},[t2,tn]);let np=eF?[eF.sessionId,eF.sessionFile??"",eF.sessionName??"",eF.userMessages,eF.assistantMessages,eF.toolCalls,eF.toolResults,eF.totalMessages,eF.tokens.input,eF.tokens.output,eF.tokens.cacheRead,eF.tokens.cacheWrite,eF.tokens.total,eF.cost??0,eF.totalActiveMs??0].join("|"):null,nh=(0,i.useRef)(eF);nh.current=eF,(0,i.useEffect)(()=>{A?.(nh.current)},[np,A]),(0,i.useEffect)(()=>()=>{A?.(null)},[A]);let nf=eR?`${eR.percent??"null"}|${eR.contextWindow}|${eR.tokens??"null"}`:null,nm=(0,i.useRef)(eR);nm.current=eR,(0,i.useEffect)(()=>{P?.(nm.current)},[nf,P]),(0,i.useEffect)(()=>()=>{P?.(null)},[P]);let ng=(0,i.useCallback)(async e=>{let t=s?.cwd??h;if(!t)return void e2({type:"warning",message:Z("chat.dropNeedsCwd")});try{var n;let r,{status:i,data:s}=await t7(t,e,"skip");if(200!==i&&207!==i)throw Error(s.error??`HTTP ${i}`);let o=s.uploaded??[],l=s.skipped??[],a=(n=[...o,...l],r=new Set(n),e.filter(e=>r.has(e.name)).map(e=>t9(e.name,!1)).join(""));for(let e of(a&&E?.current?.insertText(a),o.length>0&&(e2({type:"success",message:Z("chat.dropUploaded",{count:o.length})}),O?.()),l.length>0&&e2({type:"warning",message:Z("chat.dropAlreadyExists",{names:l.join(", ")})}),s.errors??[]))e2({type:"error",message:Z("chat.dropFailed",{message:`${e.name}: ${e.error}`})})}catch(e){e2({type:"error",message:Z("chat.dropFailed",{message:e instanceof Error?e.message:String(e)})})}},[e2,E,h,O,s?.cwd,Z]),nx=(0,i.useCallback)(e=>{let{images:t,files:n,folders:r}=function(e){let t=[],n=[],r=[];for(let i of e)"folder"===i.kind?r.push(i.name):i.file.type.startsWith("image/")?t.push(i.file):n.push(i.file);return{images:t,files:n,folders:r}}(e);t.length>0&&E?.current?.addImages(t),r.length>0&&e2({type:"warning",message:Z("chat.dropFoldersUnsupported",{names:r.join(", ")})}),n.length>0&&ng(n)},[e2,E,Z,ng]),nv=(0,i.useCallback)(e=>{nx(e.map(e=>({kind:"file",file:e})))},[nx]),{isDragOver:nb,handleDragEnter:ny,handleDragOver:nw,handleDragLeave:nk,handleDrop:nj}=function(e){let[t,n]=(0,i.useState)(!1),r=(0,i.useRef)(0),s=(0,i.useCallback)(e=>{nt(e)&&(e.preventDefault(),r.current+=1,n(!0))},[]),o=(0,i.useCallback)(e=>{nt(e)&&(e.preventDefault(),e.dataTransfer.dropEffect="copy")},[]);return{isDragOver:t,handleDragEnter:s,handleDragOver:o,handleDragLeave:(0,i.useCallback)(()=>{r.current-=1,r.current<=0&&(r.current=0,n(!1))},[]),handleDrop:(0,i.useCallback)(t=>{t.preventDefault(),r.current=0,n(!1),e(nn(t.dataTransfer))},[e])}}(nx),nS=ex||tL,nC=(0,i.useMemo)(()=>(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=e.map(rX);for(let i=0;i<e.length;){var r;if(rQ(e[i])){i+=1;continue}let s=i+1;for(;s<e.length&&!rQ(e[s]);)s+=1;let o=e[s];if((o?"assistant"===o.role:!0===t.openTail)&&(r=e[i-1],r?.role==="assistant"&&("stop"===r.stopReason||"aborted"===r.stopReason))&&!n.slice(i,s).includes(!0)){let t=-1;for(let n=s-1;n>=i;n--){if("custom"!==e[n].role){if(-1!==t)break;continue}if(-1===t&&(t=n),!rG(e[n])){t=n;break}}-1!==t&&(n[t]=!0)}i=s}return n})(ea,{openTail:nS}),[ea,nS]),nN=ea.reduce((e,t,n)=>e+ +!!r0(t,nC[n]),0),nE=(0,i.useMemo)(()=>{let e=new Map(ed);for(let t of ea)"toolResult"===t.role&&e.set(t.toolCallId,t);return e},[ed,ea]),n$=(0,i.useMemo)(()=>new WeakMap,[]),nI=(0,i.useMemo)(()=>{let e=new Set,t=[];for(let n=ea.length-1;n>=0;n-=1){let r=function(e){if("user"!==e.role)return null;if("string"==typeof e.content){let t=e.content.trim();return t.length>0?t:null}let t=e.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n").trim();return t.length>0?t:null}(ea[n]);if(!(!r||e.has(r))&&(e.add(r),t.push(r),t.length>=50))break}return t.reverse()},[ea]),nM=((t=(0,i.useRef)([])).current=Array(nN).fill(null).map((e,n)=>t.current[n]??null),t),nT=(0,i.useCallback)(()=>{t4(e=>Math.max(e,2*ea.length))},[ea.length]),nR=e9&&0===ea.length&&!tL&&!tO;tI(tn,!!s?.id||!nR);let nA=s?.cwd??h??void 0,nL=(0,i.useRef)(null),nz=(0,i.useRef)(0),nP=(0,i.useRef)(null),nW=(0,i.useRef)(!1),nO=(0,i.useRef)(null);(0,i.useLayoutEffect)(()=>{let e=nL.current;if(!ex||!ti){nO.current=null,nz.current=0,nW.current=!1,e&&(e.style.height="");return}let t=tn.current,n=t5.current,r=tr.current;if(!t||!n||!r||!e)return;let i=!1,s=()=>{var s;let o;if(i||tn.current!==t||t5.current!==n||tr.current!==r||nL.current!==e)return;let l=t.getBoundingClientRect().top,a=Math.max(0,r.getBoundingClientRect().top-l+t.scrollTop-16),d=e.getBoundingClientRect().top-l+t.scrollTop,c=(s=t.clientHeight,0===(o=Math.max(0,a))?0:Math.max(0,Math.ceil(o+s-Math.max(0,d)))),u=!nW.current;u&&(nW.current=!0),c!==nz.current&&(nz.current=c,e.style.height=c>0?`${c}px`:"",u&&c>0&&t$())};nO.current=s,s();let o="u"<typeof ResizeObserver?null:new ResizeObserver(()=>{i||null!==nP.current||(nP.current=requestAnimationFrame(()=>{nP.current=null,s()}))});return o?.observe(t),o?.observe(n),o?.observe(r),()=>{i=!0,nO.current===s&&(nO.current=null),o?.disconnect(),null!==nP.current&&(cancelAnimationFrame(nP.current),nP.current=null)}},[ex,tr,ea.length,ti,tn,t$]);let nF=(0,i.useCallback)(()=>{nO.current?.()},[]);(0,i.useLayoutEffect)(nF,[tL,tP,nF]);let nD=eW?eE[`${eW.provider}:${eW.modelId}`]??null:null,nB=eW?e$[`${eW.provider}:${eW.modelId}`]??null:null,nH=(0,r.jsx)(da,{ref:E,onSend:ts,onAbort:to,onSideChat:C&&!a(s?.relation)?t0:void 0,onSteer:ex?th:void 0,onFollowUp:ex?tf:void 0,onPromptWithStreamingBehavior:ex?tg:void 0,isStreaming:tO,model:eW,isAutoModelSelection:e4,modelNames:ey,modelList:ew,modelError:ek,missingCwd:ej,modelScopeWarnings:eS,allModelList:eN,onLoadAllModels:eC?tE:void 0,onModelChange:tu,modelSwitching:eO,defaultModel:e3,onSetDefaultModel:tj,onCompact:s||e9?tp:void 0,onAbortCompaction:tx,isCompacting:eL,compactError:ez,onDismissCompactError:tv,compactResult:eP,toolPreset:eI,onToolPresetChange:s&&!a(s.relation)||e9?tw:void 0,thinkingLevel:eM,isAutoThinkingSelection:e8,onThinkingLevelChange:s||e9?tk:void 0,availableThinkingLevels:nD,thinkingLevelMap:nB,savedDefaultThinkingLevel:e5,onSetDefaultThinkingLevel:s||e9?tS:void 0,retryInfo:eT,queuedMessages:eH,inputHistory:nI,onRecallQueue:tb,slashCommands:eD,slashCommandsLoading:eB,onLoadSlashCommands:tN,extensionUiOpen:!!(eq||eZ),onBuiltinCommand:ty,soundEnabled:_,onSoundToggle:U,onAudioUnlock:q,draftKey:s?.id??f??void 0,cwd:s?.cwd??h,onAttachFiles:nv});return eo?(0,r.jsx)("div",{className:"flex h-full items-center justify-center text-text-muted",children:Z("chat.loadingSession")}):el?(0,r.jsx)("div",{className:"flex h-full items-center justify-center text-red-400",children:el}):(0,r.jsxs)("div",{className:"chat-content relative flex h-full min-w-0 flex-col overflow-hidden",style:{paddingBottom:"env(safe-area-inset-bottom)"},onDragEnter:ny,onDragOver:nw,onDragLeave:nk,onDrop:nj,children:[nb&&(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"})]})]})]}),(0,r.jsx)("div",{style:{position:"absolute",top:12,left:0,right:36*!J,zIndex:40,display:"flex",justifyContent:"flex-end",padding:"0 16px",pointerEvents:"none"},children:(0,r.jsx)(cz,{notices:e_,floating:!0,onPauseChange:e1})}),(0,r.jsxs)("div",{className:"relative flex min-h-0 min-w-0 flex-1 overflow-hidden",children:[eq&&(0,r.jsx)(cO,{request:eq,waitingCount:eV,onRespond:eQ},eq.id),eZ&&(0,r.jsx)(cF,{request:eZ,waitingCount:eY,onInput:e0},eZ.id),!nR&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{ref:tn,className:"scrollbar-subtle min-w-0 flex-1 overflow-x-hidden overflow-y-auto pt-4 [scrollbar-gutter:stable]",style:{visibility:en?"hidden":void 0},children:(0,r.jsx)("div",{style:{minWidth:0,padding:"0 16px"},children:(0,r.jsxs)("div",{ref:t5,onPointerUp:tG,style:{width:"100%",minWidth:0,maxWidth:"var(--chat-content-max-width, 820px)",margin:"0 auto"},children:[(()=>{var e;let t,n,o=-1;for(let e=ea.length-1;e>=0;e--)if("user"===ea[e].role){o=e;break}let l=-1;for(let e=ea.length-1;e>=0;e--)if(nC[e]){l=e;break}let a=new Map,d=0;ea.forEach((e,t)=>{r0(e,nC[t])&&a.set(t,d++)});let c=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=t.messageOverride??ea[e];if("custom"===n.role&&"pi-web:side-boundary"===n.customType)return(0,r.jsx)(cA,{},"side-chat-divider");if(rG(n))return null;let l=!1===t.withNotices?[]:oV(ea[e]),d=r0(n,nC[e]),c=a.get(e),u=t.keyPrefix??"message",p=ep[e],h=!1;if("assistant"===n.role){h=!0;for(let t=e+1;t<ea.length&&!nC[t];t++)if("assistant"===ea[t].role){h=!1;break}h&&tL&&e===ea.length-1&&(h=!1)}void 0!==t.showTimestamp&&(h=t.showTimestamp);let f=(0,r.jsx)(o3,{message:n,toolResults:nE,toolClocks:ec,modelNames:ey,cwd:nA,onOpenFile:W,onOpenSubagent:F,entryId:eu[e],searchBlock:eu[e]===ns?.entryId?na:void 0,onFork:ev||e9?void 0:tF,forking:eA===eu[e],onEditContent:tO?void 0:td,onCancelEdit:tc,isEditing:e7===eu[e],showTimestamp:h,prevTimestamp:e>0?ea[e-1].timestamp:void 0,sessionId:s?.id??tt.current??void 0,writtenFiles:t.writtenFiles,turnDurationMs:t.turnDurationMs,onCompact:t.recoverTruncation?tp:void 0,isCompacting:t.recoverTruncation?eL:void 0,compactError:t.recoverTruncation?ez:void 0},`${u}-view-${p}`),m=l.length>0?(0,r.jsx)(oX,{notices:l},`${u}-notices-${p}`):null;return d&&void 0!==c?(0,r.jsxs)("div",{"data-entry-id":eu[e],ref:!1===t.attachRef?void 0:t=>{nM.current[c]=t,e===o&&(tr.current=t)},children:[f,m]},`${u}-${p}`):(0,r.jsxs)(i.Fragment,{children:[f,m]},`${u}-${p}`)},u=[];for(let e=0;e<ea.length;){let t,n=nC[e];if(!n&&0!==e){u.push(c(e)),e+=1;continue}let i=n?e:-1,s=n?e:0,o=e+1;for(;o<ea.length&&!nC[o];)o+=1;let d=function(e,t,n){for(let i=n-1;i>t;i--){var r;if("assistant"===(r=e[i]).role&&r6(r).answerBlocks.some(e=>"image"===e.type||"text"===e.type&&e.text.trim().length>0))return i}for(let r=n-1;r>t;r--)if(e[r]?.role==="assistant")return r;return -1}(ea,i,o);if(-1===d||(tO||tL)&&o===ea.length&&i===l){for(let e=s;e<o;e++)u.push(c(e));e=o;continue}n&&u.push(c(i));let p=n&&eu[i]?function(e,t,n){let r,i,s,o=iw(e[t]?.timestamp);if(void 0===o)return;for(let r=t+1;r<n&&"custom"===e[r].role;r++){let t=iw(e[r].timestamp);void 0!==t&&(o=Math.max(o,t))}let l=!1,a=0;for(let o=t+1;o<n;o++){let t=e[o];if("assistant"===t.role){var d;void 0!==i&&void 0!==s&&(a+=Math.max(0,s-i)),i=s=void 0;let e=function(e){if("assistant"!==e.role)return;let t=iw(e.timestamp),n=iw(e.durationMs);return void 0!==t&&void 0!==n?t+n:void 0}(t);l=void 0!==e,void 0!==e&&(r=Math.max(r??e,e)),void 0!==e&&"assistant"===(d=t).role&&("stop"===d.stopReason||"length"===d.stopReason)&&(i=r)}else if("toolResult"===t.role){let e=iw(t.timestamp);void 0!==e&&(r=Math.max(r??e,e))}else if(void 0!==i){let e=iw(t.timestamp);void 0!==e&&(s=Math.max(s??e,e))}}if(l&&void 0!==r)return Math.max(0,r-o-a)}(ea,i,o):void 0,h=function(e,t){let n=e.get(t);if(n)return n;let{answerBlocks:r}=r6(t),i=r.length>0||r4(t)||r3(t)||r8(t)?iy(t,r):null,s=t.content.indexOf(r[0]),o={answer:i,process:iy(t,t.content.slice(0,s<0?void 0:s),{omitUsage:!!i,omitStop:!!i})};return e.set(t,o),o}(n$,ea[d]),f=h.answer,m=[],g=0,x=0,v=!1;for(let e=i+1;e<=d;e++){let n=ea[e];if("custom"===n.role){if(rG(n))continue;v||=!!(ns&&ns.entryId===eu[e]),g+=1,m.push(c(e,{attachRef:!1,keyPrefix:"process"}));continue}if("assistant"!==n.role)continue;let i=e===d?h.process:n,s=e!==d||!f,o=r2(i);if(0===o.length){let t=s?oV(n):[];t.length>0&&m.push((0,r.jsx)(oX,{notices:t},`process-notices-${ep[e]}`));continue}t??=a.get(e),x+=o.filter(e=>"toolCall"===e.type).length,g+=1,v||=!!(ns&&eu[e]===ns.entryId&&(!na||o.includes(na))),m.push(c(e,{attachRef:!1,keyPrefix:"process",messageOverride:i,showTimestamp:!1,withNotices:s}))}if(0===g)u.push(...m);else if(m.length>0){let e=(f?.content??[]).some(e=>"image"===e.type||"text"===e.type&&e.text.trim().length>0),n=function(e){let t;for(let n of e)for(let e of oV(n))"cache_miss"===e.kind&&(t??={count:0,missedTokens:0,missedCost:0},t.count+=1,t.missedTokens+=e.missedTokens,t.missedCost+=e.missedCost);return t}(ea.slice(i+1,f?d:d+1));u.push((0,r.jsx)("div",{ref:void 0===t?void 0:e=>{nM.current[t]=e},children:(0,r.jsx)(cT,{messageCount:g,toolCallCount:x,durationMs:p,cacheMisses:n,defaultExpanded:!e,reveal:v,t:Z,children:m},e?"answered":"unanswered")},`process-group-${ep[s]}`))}if(f){let e=[];for(let t=i+1;t<=d;t++){let n=ea[t];if(n?.role==="assistant")for(let t of n.content??[])e.push(t)}let t=function(e,t){let n=e.writtenFiles;return n&&n.length===t.length&&n.every((e,n)=>e.filePath===t[n].filePath)?n:(e.writtenFiles=t,t)}(h,function(e,t,n){let r=new Set,i=[];for(let o of e){var s;if("toolCall"!==o.type||!(id(s=o.toolName)||ic(s))&&!iu(o.toolName))continue;let e=t?.get(o.toolCallId);if(e&&!e.isError)for(let t of iu(o.toolName)?function(e,t){let n=t?.details,r=function(e,t){let n=new Set;if(t&&"object"==typeof t&&!Array.isArray(t)){let e=t.preview;if(e&&"object"==typeof e&&!Array.isArray(e)){let t=e.files;if(Array.isArray(t))for(let e of t)!(!e||"object"!=typeof e||Array.isArray(e))&&"delete"===e.operation&&"string"==typeof e.filePath&&e.filePath.length>0&&n.add(e.filePath)}}for(let t of ip(e).matchAll(/^\*\*\* Delete File: (.+)$/gm)){let e=(t[1]??"").trim();e&&n.add(e)}return n}(e,n),i=function(e){if(!ih(e)||!ih(e.result))return null;let t=e.result.appliedFiles;return Array.isArray(t)?t.filter(e=>"string"==typeof e&&e.length>0):null}(n);if(i)return i.filter(e=>!r.has(e));if(im(n))return[];if(n&&"object"==typeof n&&!Array.isArray(n)){let e=ib(iv(n.preview));if(e.length>0)return e}return ib(ix(ip(e)))}(o.input,e):[function(e){if(!e)return null;let t=e.file_path??e.path;return"string"==typeof t&&t.length>0?t:null}(o.input)]){if(!t)continue;let e=function(e,t){let n;if(!e)return null;let r=it(e)||it(t),i=e=>r?e.replace(/\\/g,"/"):e,s=i(e),o=t?i(t).replace(/\/+$/,""):void 0,l=/^[a-zA-Z]:\//.test(s),a=s.startsWith("//"),d=r?ii(s):s;if(l||a||d!==s)n=d;else if(s.startsWith("/")){let e=o?.match(/^([a-zA-Z]:)(?:\/|$)/)?.[1]??o?.match(/^(\/\/[^/]+\/[^/]+)(?:\/|$)/)?.[1];n=e?`${e}${s}`:s}else{if(!o)return null;n=`${o}/${s}`}return is(n)}(t,n);e&&(r.has(e)||(r.add(e),i.push({filePath:e})))}}return i}(e,nE,nA));u.push(c(d,{messageOverride:f,writtenFiles:t,turnDurationMs:0===m.length?p:void 0,recoverTruncation:o===ea.length&&!tL&&!r5(f)}))}for(let e=d+1;e<o;e++)u.push(c(e));e=o}let{startIndex:p}=(t=Math.min(Math.max(t2,0),Math.max(e=u.length,0)),{startIndex:n=Math.max(0,e-t),hasMore:n>0}),h=p>0||ef;return(0,r.jsxs)(r.Fragment,{children:[h&&(0,r.jsx)("div",{ref:t3,className:"py-3 text-center text-xs text-text-muted",children:Z("chat.loadEarlier")}),u.slice(p)]})})(),tL&&tP&&(0,r.jsx)(cL,{store:eg,onCommit:nF,toolResults:nE,modelNames:ey,cwd:nA,onOpenFile:W,onOpenSubagent:F}),(ex||eL)&&!tP&&(e6||eL)&&(0,r.jsx)("div",{className:"break-words py-2 text-[13px] text-text-muted",children:(0,r.jsx)("span",{className:"animate-[pulse_1.5s_infinite]",children:function(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0;if(n)return r>0?t("chat.compactingQueued",{count:r}):t("chat.compacting");if(e?.kind==="running_tools"){let n=e.tools[e.tools.length-1];if(n?.progress)return`${t("chat.runningNamedTool",{name:n.name})} ${n.progress}`;let r=e.tools.map(e=>e.name);return 0===r.length?t("chat.runningTool"):1===r.length?t("chat.runningNamedTool",{name:r[0]}):r.length<=3?t("chat.runningTools",{names:r.join(", ")}):t("chat.runningToolsMore",{names:r.slice(0,2).join(", "),count:r.length-2})}return e?.kind==="waiting_model"?t("chat.waitingModel"):e?.kind==="running_command"?t("chat.runningCommand"):null}(e6,Z,eL,(eH?.steering.length??0)+(eH?.followUp.length??0))})}),ev&&!eb&&(0,r.jsx)("div",{className:"py-2 text-[13px] text-text-muted",children:(0,r.jsx)("span",{className:"animate-[pulse_1.5s_infinite]",children:Z("chat.runningCommand")})}),eb&&(0,r.jsx)(o3,{message:{role:"bashExecution",command:eb.command,output:"",...eb.result,excludeFromContext:eb.excludeFromContext,timestamp:eb.startedAt},sessionId:s?.id??tt.current??void 0,onOpenSubagent:F}),eb?.liveOutput&&!eb.result&&(0,r.jsx)("div",{"aria-live":"off",className:"rounded-md border border-border px-2.5 py-1.5 font-mono text-[12px] leading-[1.45] text-text-muted",style:{marginTop:-2,background:"var(--tool-bg)"},children:(0,r.jsx)("pre",{className:"m-0 flex flex-col justify-end overflow-hidden whitespace-pre-wrap break-words",style:{maxHeight:"29em"},children:(0,r.jsx)("span",{children:eb.liveOutput.replace(/\n+$/,"").split("\n").slice(-20).join("\n")})})}),(0,r.jsx)("div",{ref:nL,"aria-hidden":"true"})]})})}),J||en?null:(0,r.jsx)(dS,{messages:ea,getStreamingMessage:tW,scrollContainer:tn,messageRefs:nM,onRevealHistory:nT,turnsBefore:em,turnAnchors:nC})]})]}),D&&tD&&(0,tz.createPortal)((0,r.jsx)("div",{ref:tZ,role:tH?"dialog":"toolbar","aria-label":Z(tH?"chat.newQuoteChat":"chat.selectionActions"),style:{position:"fixed",top:tD.top,left:tD.left,zIndex:260,display:"flex",flexWrap:"wrap",gap:3,width:tH?"min(420px, calc(100vw - 16px))":void 0,maxWidth:"calc(100vw - 16px)",maxHeight:"calc(var(--app-viewport-height, 100dvh) - 16px)",overflowY:"auto",padding:tH?12:3,border:"1px solid var(--border)",borderRadius:6,background:"var(--bg)",boxShadow:"0 2px 10px rgba(0,0,0,0.12)"},children:tH?(0,r.jsxs)("fieldset",{disabled:tU,"aria-busy":tU,style:{width:"100%",minWidth:0,margin:0,padding:0,border:"none",display:"flex",flexDirection:"column",gap:10},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[(0,r.jsx)("span",{style:{flex:1,minWidth:0,fontSize:12,fontWeight:600},children:Z("chat.askInSideChat")}),(0,r.jsx)("button",{type:"button",className:"file-viewer-icon-button",title:Z("i18n.close"),"aria-label":Z("i18n.close"),disabled:tU,onClick:tY,style:{border:"none"},children:(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m6 6 12 12M18 6 6 18"})})})]}),(0,r.jsx)(da,{ref:tJ,compact:!0,onSend:tQ,onAbort:tY,isStreaming:!1}),tq&&(0,r.jsx)("div",{role:"alert",style:{color:"#dc2626",fontSize:12,overflowWrap:"anywhere"},children:tq})]}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("button",{type:"button",className:"file-viewer-icon-button",title:Z("chat.quoteSelection"),"aria-label":Z("chat.quoteSelection"),onPointerDown:e=>e.preventDefault(),onClick:tX,style:{width:"auto",height:35,flex:"0 0 auto",gap:5,padding:"0 10px",border:"none",fontSize:12,fontWeight:500},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M16 3a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2 1 1 0 0 1 1 1v1a2 2 0 0 1-2 2 1 1 0 0 0-1 1v2a1 1 0 0 0 1 1 6 6 0 0 0 6-6V5a2 2 0 0 0-2-2z"}),(0,r.jsx)("path",{d:"M5 3a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2 1 1 0 0 1 1 1v1a2 2 0 0 1-2 2 1 1 0 0 0-1 1v2a1 1 0 0 0 1 1 6 6 0 0 0 6-6V5a2 2 0 0 0-2-2z"})]}),(0,r.jsx)("span",{children:Z("chat.quoteSelection")})]}),C&&!a(s?.relation)&&(0,r.jsxs)("button",{type:"button",className:"file-viewer-icon-button",title:Z("chat.askInSideChat"),"aria-label":Z("chat.askInSideChat"),onPointerDown:e=>e.preventDefault(),onClick:()=>{t_(!0),window.getSelection()?.removeAllRanges()},style:{width:"auto",height:35,flex:"0 0 auto",gap:5,padding:"0 10px",border:"none",fontSize:12,fontWeight:500},children:[(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M21 12a8 8 0 0 1-8 8H5.5a2 2 0 0 1-1.4-3.4A8 8 0 1 1 21 12z"})}),(0,r.jsx)("span",{children:Z("chat.askInSideChat")})]})]})}),document.body),(0,r.jsxs)("div",{className:"relative flex min-h-0 flex-col",children:[!nR&&(0,r.jsx)("div",{style:{position:"absolute",bottom:"100%",left:0,right:36*!J,display:"flex",justifyContent:"center",paddingBottom:10,pointerEvents:"none",zIndex:20},children:(0,r.jsx)("button",{type:"button",className:`chat-scroll-to-bottom${te&&!en?" is-visible":""}`,title:Z("chat.scrollToLatest"),"aria-label":Z("chat.scrollToLatest"),onClick:()=>tR("smooth"),children:(0,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M12 5v14M5 12l7 7 7-7"})})})}),nR&&(0,r.jsx)("div",{className:"new-session-hero",style:{paddingLeft:16,paddingRight:J?16:52},children:(0,r.jsxs)("div",{className:"new-session-hero-inner",style:{maxWidth:"var(--chat-content-max-width, 820px)"},children:[(0,r.jsxs)("div",{className:"new-session-brand",children:[(0,r.jsx)(rO.A,{src:"/icons/apple-touch-icon.png",width:40,height:40,alt:"",priority:!0,className:"new-session-logo"}),(0,r.jsxs)("div",{className:"new-session-brand-text",children:[(0,r.jsx)("span",{className:"new-session-brand-name",children:"Pi Web"}),(0,r.jsxs)("span",{className:"new-session-meta",children:[(0,r.jsxs)("span",{children:["web v","0.17.0-custom.4"]}),(0,r.jsx)(cM,{label:e=>Z("appUpdate.releaseNotes",{version:e})}),(0,r.jsx)("span",{"aria-hidden":"true",children:"\xb7"}),(0,r.jsxs)("span",{className:"new-session-meta-pi",children:["pi v","1.5.2"]})]})]})]}),m]})}),nH,(0,r.jsx)(dI,{statuses:eG,widgets:eX,onCommand:ts,commandsDisabled:tO})]}),nR&&(0,r.jsx)("div",{className:"min-h-0 flex-1"})]})}function cA(){let{t:e}=(0,tm.s)();return(0,r.jsxs)("div",{role:"separator",className:"my-4 flex items-center gap-3 text-xs",style:{color:"var(--text-dim)"},children:[(0,r.jsx)("span",{className:"h-px flex-1",style:{background:"var(--border)"}}),(0,r.jsx)("span",{children:e("sideChat.divider")}),(0,r.jsx)("span",{className:"h-px flex-1",style:{background:"var(--border)"}})]})}let cL=(0,i.memo)(function(e){let{store:t,onCommit:n,toolResults:s,modelNames:o,cwd:l,onOpenFile:a,onOpenSubagent:d}=e,c=ck(t,cC);return((0,i.useLayoutEffect)(n,[c,n]),c)?(0,r.jsx)(o3,{message:c,toolResults:s,isStreaming:!0,modelNames:o,cwd:l,onOpenFile:a,onOpenSubagent:d}):null});function cz(e){let{notices:t,floating:n=!1,onPauseChange:s}=e;return 0===t.length?null:(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",alignItems:"flex-end",marginBottom:10*!n},children:t.map((e,o)=>{var l;let a,d,c,u="error"===e.type?"#ef4444":"warning"===e.type?"#d97706":"success"===e.type?"#10b981":"var(--accent)";return(0,r.jsxs)("div",{className:"notice-shelf-item",onMouseEnter:()=>s?.(e.id),onMouseLeave:e=>{e.currentTarget.contains(document.activeElement)||s?.(null)},onFocus:()=>s?.(e.id),onBlur:e=>{e.currentTarget.matches(":hover")||s?.(null)},style:{display:"flex",alignItems:"flex-start",gap:10,minHeight:60,height:"auto",maxHeight:500,pointerEvents:"auto",marginBottom:6*(o!==t.length-1),overflow:"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:n?"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:14,lineHeight:1.5,transformOrigin:"top right",animation:e.exiting?"notice-shelf-out 0.18s ease-in forwards":"notice-shelf-in 0.18s ease-out backwards",padding:"0 12px"},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:u,flexShrink:0,marginTop:25.5}}),(0,r.jsx)("span",{tabIndex:0,style:{padding:"18.5px 0",minWidth:0,maxWidth:"100%",maxHeight:498,overflowY:"auto",scrollbarWidth:"thin",whiteSpace:"pre-line",wordBreak:"break-word"},children:(l=e.message,a=[],d=(e,t)=>{if(!t)return;let n=a[a.length-1];n?.kind===e?n.text+=t:a.push({kind:e,text:t})},c=!1,l.split("\n").forEach((e,t)=>{let n=rq.test(e);t>0&&d(n&&c?"art":"text","\n"),d(n?"art":"text",e),c=n}),a).map((e,t)=>"art"===e.kind?(0,r.jsx)("span",{style:{display:"inline-block",verticalAlign:"top",maxWidth:"100%",overflowX:"auto",whiteSpace:"pre",fontFamily:"var(--font-mono)",lineHeight:1,color:"var(--text)"},children:e.text},t):(0,r.jsx)(i.Fragment,{children:(function(e){let t=[],n=0;for(let r of e.matchAll(rV)){let i=function(e){let t=0,n=0;for(let r of e)"("===r?t+=1:")"===r&&(n+=1);let r=e.length;for(;r>0;){let i=e[r-1];if(rZ.test(i))r-=1;else if(")"===i&&n>t)r-=1,n-=1;else break}return e.slice(0,r)}(r[0]);if(!/^https?:\/\/[^/]/i.test(i))continue;let s=r.index??0;s>n&&t.push({kind:"text",text:e.slice(n,s)}),t.push({kind:"link",text:i}),n=s+i.length}return n<e.length&&t.push({kind:"text",text:e.slice(n)}),t})(e.text).map((e,n)=>"link"===e.kind?(0,r.jsx)("a",{href:e.text,target:"_blank",rel:"noopener noreferrer",style:{color:"var(--accent)",textDecoration:"underline",textUnderlineOffset:2,wordBreak:"break-all"},children:e.text},`${t}-${n}`):e.text)},t))})]},e.id)})})}function cP(e){let{count:t}=e,{t:n}=(0,tm.s)();return t<=0?null:(0,r.jsx)("span",{style:{fontSize:11,fontWeight:650,color:"var(--accent)",whiteSpace:"nowrap",flexShrink:0},children:n("chat.extensionMoreWaiting",{count:t})})}function cW(e){let{expanded:t}=e;return(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:1.6,strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:t?(0,r.jsx)("path",{d:"M3.5 1v2.5H1M6.5 1v2.5H9M6.5 9v-2.5H9M3.5 9v-2.5H1"}):(0,r.jsx)("path",{d:"M1 3.5V1h2.5M6.5 1H9v2.5M9 6.5V9H6.5M3.5 9H1V6.5"})})}function cO(e){let{request:t,waitingCount:n,onRespond:s}=e,{t:o}=(0,tm.s)(),[l,a]=(0,i.useState)("editor"===t.method?t.prefill??"":""),[d,c]=(0,i.useState)(!1),u=(0,i.useRef)(null),p=(0,i.useRef)(null),[h,f]=(0,i.useState)(null),[m,g]=(0,i.useState)(!1),x=(0,i.useCallback)(()=>g(e=>!e),[]),[v,b]=(0,i.useState)(()=>Date.now()),y=(0,i.useCallback)(e=>e?.focus(),[]),w=function(e){if("select"===e.method&&e.options.length>0)return rH(e.options[0]);if("confirm"===e.method){let t=rH(e.message).split("\n").find(e=>e.trim());return t?.trim()}}(t),k=void 0===t.expiresAt?null:Math.max(0,Math.ceil((t.expiresAt-v)/1e3));(0,i.useLayoutEffect)(()=>{if(d)return;let e=u.current,t=p.current;if(!e||!t)return;let n=!1,r=()=>{if(n)return;let r=t.querySelectorAll("pre, .markdown-table-wrap");if(0===r.length)return;t.classList.add("extension-dialog-measuring");let i=Array.from(r,e=>e.scrollWidth-e.clientWidth);t.classList.remove("extension-dialog-measuring");let s=function(e,t){let n=0;for(let e of t)e>1&&e>n&&(n=e);return 0===n?null:40*Math.ceil((e+n)/40)}(e.offsetWidth,i);null!==s&&f(e=>null!==e&&e>=s?e:s)};r();let i=new MutationObserver(r);return i.observe(t,{childList:!0,subtree:!0,characterData:!0}),document.fonts?.ready.then(r),()=>{n=!0,i.disconnect()}},[d]),(0,i.useEffect)(()=>{if(void 0===t.expiresAt)return;let e=setInterval(()=>b(Date.now()),1e3);return()=>clearInterval(e)},[t.expiresAt]);let j=null!==k&&(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",whiteSpace:"nowrap",flexShrink:0},children:o("chat.extensionExpiresIn",{seconds:k})}),S=()=>{"confirm"===t.method?s(t,{confirmed:!0}):s(t,{value:l})};return(0,r.jsx)("div",{onKeyDown:e=>{"Escape"!==e.key||e.nativeEvent.isComposing||229===e.nativeEvent.keyCode||(e.preventDefault(),e.stopPropagation(),s(t,{cancelled:!0}))},style:{position:"absolute",inset:0,zIndex:90,display:"flex",alignItems:d?"flex-start":"center",justifyContent:"center",padding:20,pointerEvents:"none"},children:d?(0,r.jsxs)("button",{type:"button",onClick:()=>c(!1),"aria-expanded":!1,style:{pointerEvents:"auto",display:"flex",alignItems:"center",gap:10,maxWidth:"min(560px, 100%)",width:"100%",padding:"10px 12px",border:"1px solid var(--border)",borderRadius:8,background:"var(--bg)",boxShadow:"0 12px 32px rgba(0,0,0,0.18)",color:"var(--text)",cursor:"pointer",textAlign:"left"},children:[(0,r.jsx)("span",{style:{fontSize:11,fontWeight:650,color:"var(--accent)",flexShrink:0},children:o("chat.extensionPending")}),(0,r.jsx)("span",{style:{fontSize:13,fontWeight:600,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1,minWidth:0},children:rH(t.title)}),w&&(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-dim)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",maxWidth:"34%",flexShrink:1},children:w}),(0,r.jsx)(cP,{count:n}),j,(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",flexShrink:0},children:o("chat.extensionExpand")})]}):(0,r.jsxs)("div",{ref:u,role:"dialog","aria-label":rH(t.title),style:{pointerEvents:"auto",width:m?"100%":`min(${h??560}px, 100%)`,maxHeight:m?"100%":"min(760px, 100%)",display:"flex",flexDirection:"column",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:{flexShrink:1,minHeight:0,display:"flex",alignItems:"flex-start",gap:8,padding:"12px 14px",borderBottom:"1px solid var(--border)",maxHeight:"50vh",overflowY:"auto"},children:[(0,r.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,r.jsx)("div",{style:{color:"var(--text)",fontSize:14,fontWeight:650,lineHeight:1.45,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:rH(t.title)}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",gap:8,marginTop:3,color:"var(--text-dim)",fontSize:11,fontFamily:"var(--font-mono)"},children:[(0,r.jsx)("span",{children:o("chat.extensionRequest")}),(0,r.jsx)(cP,{count:n}),j]})]}),(0,r.jsx)("button",{type:"button",onClick:x,title:o(m?"chat.extensionRestoreSize":"chat.extensionMaximize"),"aria-label":o(m?"chat.extensionRestoreSize":"chat.extensionMaximize"),style:{display:"grid",placeItems:"center",width:28,height:28,borderRadius:6,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",cursor:"pointer",flexShrink:0},children:(0,r.jsx)(cW,{expanded:m})}),(0,r.jsx)("button",{type:"button",onClick:()=>c(!0),"aria-expanded":!0,title:o("chat.extensionCollapse"),"aria-label":o("chat.extensionCollapse"),style:{display:"grid",placeItems:"center",width:28,height:28,borderRadius:6,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",cursor:"pointer",flexShrink:0},children:(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})})})]}),(0,r.jsxs)("div",{ref:p,style:{padding:14,flex:"1 1 auto",minHeight:0,overflowY:"auto"},children:["confirm"===t.method&&(0,r.jsx)(od,{children:rH(t.message)}),"select"===t.method&&(0,r.jsx)("div",{onKeyDown:e=>{if(!["ArrowDown","ArrowRight","ArrowUp","ArrowLeft","Home","End"].includes(e.key))return;let t=Array.from(e.currentTarget.querySelectorAll("[data-extension-option]")),n=t.indexOf(e.target);if(n<0)return;e.preventDefault();let r="Home"===e.key?0:"End"===e.key?t.length-1:(n+("ArrowDown"===e.key||"ArrowRight"===e.key?1:-1)+t.length)%t.length;t[r].focus({preventScroll:!0}),t[r].scrollIntoView({block:"nearest"})},style:{display:"grid",gap:8},children:t.options.map((e,n)=>(0,r.jsx)("div",{role:"button",tabIndex:0,"data-extension-option":!0,"aria-label":rH(e),ref:0===n?y:void 0,onClick:()=>s(t,{value:e}),onKeyDown:n=>{("Enter"===n.key||" "===n.key)&&(n.preventDefault(),s(t,{value:e}))},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,overflowWrap:"anywhere",scrollMargin:14},children:(0,r.jsx)("div",{inert:!0,children:(0,r.jsx)(od,{children:rH(e)})})},e))}),"input"===t.method&&(0,r.jsx)("input",{autoFocus:!0,value:l,placeholder:t.placeholder,onChange:e=>a(e.target.value),onKeyDown:e=>{"Enter"!==e.key||e.nativeEvent.isComposing||229===e.nativeEvent.keyCode||S()},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"===t.method&&(0,r.jsx)("textarea",{autoFocus:!0,value:l,onChange:e=>a(e.target.value),onKeyDown:e=>{(e.metaKey||e.ctrlKey)&&"Enter"===e.key&&!e.nativeEvent.isComposing&&229!==e.nativeEvent.keyCode&&S()},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:{flexShrink:0,display:"flex",justifyContent:"flex-end",gap:8,padding:"10px 14px",borderTop:"1px solid var(--border)",background:"var(--bg-panel)"},children:[(0,r.jsx)("button",{autoFocus:"confirm"===t.method||"select"===t.method&&0===t.options.length,onClick:()=>s(t,{cancelled:!0}),style:{padding:"6px 10px",borderRadius:6,border:"1px solid var(--border)",background:"var(--bg)",color:"var(--text-muted)",cursor:"pointer"},children:o("chat.cancel")}),"confirm"===t.method?(0,r.jsx)("button",{onClick:S,style:{padding:"6px 10px",borderRadius:6,border:"1px solid var(--accent)",background:"var(--accent)",color:"var(--accent-contrast)",cursor:"pointer"},children:o("chat.confirm")}):"select"!==t.method?(0,r.jsx)("button",{onClick:S,style:{padding:"6px 10px",borderRadius:6,border:"1px solid var(--accent)",background:"var(--accent)",color:"var(--accent-contrast)",cursor:"pointer"},children:o("chat.submit")}):null]})]})})}function cF(e){let{request:t,waitingCount:n,onInput:s}=e,{t:o}=(0,tm.s)(),l=(0,i.useRef)(null),a=(0,i.useRef)(!1),[d,c]=(0,i.useState)(!1),u=function(e){let t=/^[┌├└╭╰][─┬┴┼]+[┐┤┘╮╯]$/,n=[];for(let r of e){let e=r.replace(rB,""),i=rH(e).trimEnd();if(t.test(i))continue;let s=e,o=rK(s);("│"===o||"┃"===o)&&" "===rK(s=rU(s,0))&&(s=rU(s,0));let l=function(e){let t=r_(e);for(let e=t.length-1;e>=0;e--)if(""!==t[e].char.trim())return e;return -1}(s),a=l>=0?r_(s)[l]?.char:void 0;("│"===a||"┃"===a)&&(s=rU(s,l)),n.push(function(e){let t=e;for(;;){let e=r_(t),n=e[e.length-1];if(!n||""!==n.char.trim())return t;t=t.slice(0,n.start)+t.slice(n.end)}}(s))}for(;n.length>0&&""===rH(n[0]).trim();)n.shift();for(;n.length>0&&""===rH(n[n.length-1]).trim();)n.pop();return n.length?n:e.map(e=>e.replace(rB,""))}(t.lines),p=u.map(rH).find(e=>e.trim())?.trim();return(0,i.useEffect)(()=>{d||l.current?.focus()},[d]),(0,r.jsx)("div",{style:{position:"absolute",inset:0,zIndex:95,display:"flex",alignItems:d?"flex-start":"center",justifyContent:"center",padding:20,pointerEvents:"none"},children:d?(0,r.jsxs)("button",{type:"button",onClick:()=>c(!1),"aria-expanded":!1,style:{pointerEvents:"auto",display:"flex",alignItems:"center",gap:10,maxWidth:"min(920px, 100%)",width:"100%",padding:"10px 12px",border:"1px solid var(--border)",borderRadius:8,background:"var(--bg)",boxShadow:"0 12px 32px rgba(0,0,0,0.18)",color:"var(--text)",cursor:"pointer",textAlign:"left"},children:[(0,r.jsx)("span",{style:{fontSize:11,fontWeight:650,color:"var(--accent)",flexShrink:0},children:o("chat.extensionPending")}),(0,r.jsx)("span",{style:{fontSize:13,fontWeight:600,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1,minWidth:0},children:o("chat.extensionPanel")}),p&&(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-dim)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",maxWidth:"34%",flexShrink:1},children:p}),(0,r.jsx)(cP,{count:n}),(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",flexShrink:0},children:o("chat.extensionExpand")})]}):(0,r.jsxs)("div",{role:"dialog",onClick:e=>{e.target.closest("button")||l.current?.focus()},style:{pointerEvents:"auto",position:"relative",width:"max-content",minWidth:"min(920px, 100%)",maxWidth:"100%",maxHeight:"min(760px, 100%)",display:"flex",flexDirection:"column",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.jsx)("textarea",{ref:l,"aria-label":o("chat.extensionInput"),autoCapitalize:"off",autoComplete:"off",autoCorrect:"off",spellCheck:!1,onKeyDown:e=>{if(a.current||e.nativeEvent.isComposing||229===e.nativeEvent.keyCode)return;let n=function(e){if(e.metaKey||e.ctrlKey&&!e.altKey&&"v"===e.key.toLowerCase())return null;if(e.ctrlKey&&!e.altKey){let t=function(e){if(1!==e.length)return null;if(" "===e)return"\0";if("/"===e||"-"===e)return"\x1f";let t=e.toUpperCase().charCodeAt(0);return t>=64&&t<=95?String.fromCharCode(31&t):"?"===e?"":null}(e.key);if(t)return t}let t=rJ[e.key],n=1+ +!!e.shiftKey+2*!!e.altKey+4*!!e.ctrlKey;if(n>1&&!(e.altKey&&!e.ctrlKey&&!e.shiftKey&&rY[e.key])){if(/^\x1b\[[ABCDHF]$/.test(t??""))return`\x1b[1;${n}${t.at(-1)}`;if(/^\x1b\[\d+~$/.test(t??""))return`${t.slice(0,-1)};${n}~`}if(e.altKey&&!e.ctrlKey){if("Backspace"===e.key)return"\x1b\x7f";let t=rY[e.key];if(t)return t;if(1===e.key.length)return`\x1b${e.key}`}return"Enter"===e.key?e.shiftKey?"\n":"\r":"Tab"===e.key?e.shiftKey?"\x1b[Z":" ":rJ[e.key]??null}(e);n&&(e.preventDefault(),e.stopPropagation(),s(t,n))},onInput:e=>{if(a.current||e.nativeEvent.isComposing)return;let n=e.currentTarget.value;e.currentTarget.value="",n&&s(t,n)},onCompositionStart:()=>{a.current=!0},onCompositionEnd:e=>{a.current=!1;let n=e.currentTarget;queueMicrotask(()=>{let e=n.value;n.value="",e&&s(t,e)})},onPaste:e=>{e.preventDefault();let n=e.clipboardData.getData("text");n&&s(t,`\x1b[200~${n}\x1b[201~`)},style:{position:"absolute",width:1,height:1,padding:0,border:0,opacity:0,pointerEvents:"none"}}),(0,r.jsxs)("div",{style:{flexShrink:0,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("chat.extensionPanel")}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[(0,r.jsx)(cP,{count:n}),(0,r.jsx)("button",{type:"button",onClick:()=>c(!0),"aria-expanded":!0,title:o("chat.extensionCollapse"),"aria-label":o("chat.extensionCollapse"),style:{display:"grid",placeItems:"center",width:28,height:28,borderRadius:6,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",cursor:"pointer",flexShrink:0},children:(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})})}),(0,r.jsx)("button",{onClick:()=>s(t,"\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("chat.close")})]})]}),(0,r.jsx)("pre",{style:{margin:0,padding:14,minHeight:0,overflow:"auto",background:"var(--bg-panel)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:13,lineHeight:1.45,whiteSpace:"pre"},children:(0,r.jsx)(dN,{text:u.join("\n")})})]})})}let cD=null,cB="";function cH(e){let{context:t,mobile:n,initialFocus:s,onInitialFocusDone:o,onPick:l,onUseDefaultDirectory:a,onOpenFolder:d,onRefreshWorktrees:c,onCreateWorktree:u}=e,{t:p}=(0,tm.s)(),[h,f]=(0,i.useState)(()=>cB),m=(0,i.useRef)(null),g=(0,i.useRef)(s),x=(0,i.useRef)(o);return x.current=o,(0,i.useEffect)(()=>{if(cB)return;let e=!1;return(cD??=fetch("/api/home").then(e=>e.json()).then(e=>cB=e.home??"").catch(()=>(cD=null,""))).then(t=>{!e&&t&&f(t)}),()=>{e=!0}},[]),(0,i.useEffect)(()=>{let e=g.current;if(!e)return;g.current=null,x.current();let t=m.current;e_(document,("worktree"===e?t?.button("worktree"):null)??t?.button("project")??null)},[]),(0,r.jsx)("div",{className:"new-session-context",children:(0,r.jsx)(rj,{handleRef:m,layout:"inline",context:t,mobile:n,label:p("workspace.newSessionContext"),homeDir:h,newWorktreeTitle:p("sidebar.newWorktreeForSession"),onPick:l,onUseDefaultDirectory:a,onOpenFolder:d,onRefreshWorktrees:c,onCreateWorktree:u})})}function c_(e){return e&&"number"==typeof e.size&&"string"==typeof e.mtime?`${e.size}:${e.mtime}`:null}function cU(e,t){return null===e||null===t||e!==t}let cK=`<script data-pi-web-polyfill="storage">
|
|
10
10
|
(function() {
|
|
11
11
|
function createMemoryStorage() {
|
|
12
12
|
var store = Object.create(null);
|