@hyperdreamer/pi-webui 1.14.0 → 1.15.0
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/dist/client/assets/{CodeViewer-BEbclxBf.js → CodeViewer-BGClPFoI.js} +1 -1
- package/dist/client/assets/{UnifiedDiffViewer-DXWhrIST.js → UnifiedDiffViewer-I9Fc0TRx.js} +1 -1
- package/dist/client/assets/{index-2EIg2vwJ.js → index-DEhtRZU8.js} +56 -56
- package/dist/client/index.html +1 -1
- package/dist/pi-webui-plugins/workspace-tasks/config.js +79 -0
- package/dist/pi-webui-plugins/workspace-tasks/tasksPanelElement.js +926 -142
- package/dist/pi-webui-plugins/workspace-tasks/workspaceTasksClient.js +204 -9
- package/dist/server/sessions/piSessionService.js +22 -12
- package/dist/server/sessions/piSessionService.js.map +1 -1
- package/dist/server/sessions/sessionCommandService.js +38 -0
- package/dist/server/sessions/sessionCommandService.js.map +1 -1
- package/docs/plugins.md +42 -2
- package/package.json +1 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./CodeViewer-
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./CodeViewer-BGClPFoI.js","./vendor-editor-core-vyMPzMNA.js","./vendor-editor-languages-DlEQaRIv.js","./vendor-editor-legacy-CYBnW6ZU.js"])))=>i.map(i=>d[i]);
|
|
2
2
|
import{$ as e,A as t,J as n,P as r,Q as i,S as a,X as o,Y as s,d as c,et as l,f as u,it as d,j as f,l as p,p as m,q as ee,rt as te,tt as ne,u as re}from"./vendor-editor-core-vyMPzMNA.js";import{a as ie,o as ae,s as oe}from"./vendor-editor-languages-DlEQaRIv.js";import{n as se,t as ce}from"./vendor-terminal-D8k4UKM2.js";var le=Object.defineProperty,ue=(e,t)=>{let n={};for(var r in e)le(n,r,{get:e[r],enumerable:!0});return t||le(n,Symbol.toStringTag,{value:`Module`}),n};(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),e.crossOrigin===`use-credentials`?t.credentials=`include`:e.crossOrigin===`anonymous`?t.credentials=`omit`:t.credentials=`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var de=globalThis,fe=de.ShadowRoot&&(de.ShadyCSS===void 0||de.ShadyCSS.nativeShadow)&&`adoptedStyleSheets`in Document.prototype&&`replace`in CSSStyleSheet.prototype,pe=Symbol(),me=new WeakMap,he=class{constructor(e,t,n){if(this._$cssResult$=!0,n!==pe)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=e,this.t=t}get styleSheet(){let e=this.o,t=this.t;if(fe&&e===void 0){let n=t!==void 0&&t.length===1;n&&(e=me.get(t)),e===void 0&&((this.o=e=new CSSStyleSheet).replaceSync(this.cssText),n&&me.set(t,e))}return e}toString(){return this.cssText}},ge=e=>new he(typeof e==`string`?e:e+``,void 0,pe),h=(e,...t)=>new he(e.length===1?e[0]:t.reduce((t,n,r)=>t+(e=>{if(!0===e._$cssResult$)return e.cssText;if(typeof e==`number`)return e;throw Error(`Value passed to 'css' function must be a 'css' function result: `+e+`. Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.`)})(n)+e[r+1],e[0]),e,pe),_e=(e,t)=>{if(fe)e.adoptedStyleSheets=t.map(e=>e instanceof CSSStyleSheet?e:e.styleSheet);else for(let n of t){let t=document.createElement(`style`),r=de.litNonce;r!==void 0&&t.setAttribute(`nonce`,r),t.textContent=n.cssText,e.appendChild(t)}},ve=fe?e=>e:e=>e instanceof CSSStyleSheet?(e=>{let t=``;for(let n of e.cssRules)t+=n.cssText;return ge(t)})(e):e,{is:ye,defineProperty:be,getOwnPropertyDescriptor:xe,getOwnPropertyNames:Se,getOwnPropertySymbols:Ce,getPrototypeOf:we}=Object,Te=globalThis,Ee=Te.trustedTypes,De=Ee?Ee.emptyScript:``,Oe=Te.reactiveElementPolyfillSupport,ke=(e,t)=>e,Ae={toAttribute(e,t){switch(t){case Boolean:e=e?De:null;break;case Object:case Array:e=e==null?e:JSON.stringify(e)}return e},fromAttribute(e,t){let n=e;switch(t){case Boolean:n=e!==null;break;case Number:n=e===null?null:Number(e);break;case Object:case Array:try{n=JSON.parse(e)}catch{n=null}}return n}},je=(e,t)=>!ye(e,t),Me={attribute:!0,type:String,converter:Ae,reflect:!1,useDefault:!1,hasChanged:je};Symbol.metadata??=Symbol(`metadata`),Te.litPropertyMetadata??=new WeakMap;var Ne=class extends HTMLElement{static addInitializer(e){this._$Ei(),(this.l??=[]).push(e)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(e,t=Me){if(t.state&&(t.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(e)&&((t=Object.create(t)).wrapped=!0),this.elementProperties.set(e,t),!t.noAccessor){let n=Symbol(),r=this.getPropertyDescriptor(e,n,t);r!==void 0&&be(this.prototype,e,r)}}static getPropertyDescriptor(e,t,n){let{get:r,set:i}=xe(this.prototype,e)??{get(){return this[t]},set(e){this[t]=e}};return{get:r,set(t){let a=r?.call(this);i?.call(this,t),this.requestUpdate(e,a,n)},configurable:!0,enumerable:!0}}static getPropertyOptions(e){return this.elementProperties.get(e)??Me}static _$Ei(){if(this.hasOwnProperty(ke(`elementProperties`)))return;let e=we(this);e.finalize(),e.l!==void 0&&(this.l=[...e.l]),this.elementProperties=new Map(e.elementProperties)}static finalize(){if(this.hasOwnProperty(ke(`finalized`)))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(ke(`properties`))){let e=this.properties,t=[...Se(e),...Ce(e)];for(let n of t)this.createProperty(n,e[n])}let e=this[Symbol.metadata];if(e!==null){let t=litPropertyMetadata.get(e);if(t!==void 0)for(let[e,n]of t)this.elementProperties.set(e,n)}this._$Eh=new Map;for(let[e,t]of this.elementProperties){let n=this._$Eu(e,t);n!==void 0&&this._$Eh.set(n,e)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(e){let t=[];if(Array.isArray(e)){let n=new Set(e.flat(1/0).reverse());for(let e of n)t.unshift(ve(e))}else e!==void 0&&t.push(ve(e));return t}static _$Eu(e,t){let n=t.attribute;return!1===n?void 0:typeof n==`string`?n:typeof e==`string`?e.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){this._$ES=new Promise(e=>this.enableUpdating=e),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach(e=>e(this))}addController(e){(this._$EO??=new Set).add(e),this.renderRoot!==void 0&&this.isConnected&&e.hostConnected?.()}removeController(e){this._$EO?.delete(e)}_$E_(){let e=new Map,t=this.constructor.elementProperties;for(let n of t.keys())this.hasOwnProperty(n)&&(e.set(n,this[n]),delete this[n]);e.size>0&&(this._$Ep=e)}createRenderRoot(){let e=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return _e(e,this.constructor.elementStyles),e}connectedCallback(){this.renderRoot??=this.createRenderRoot(),this.enableUpdating(!0),this._$EO?.forEach(e=>e.hostConnected?.())}enableUpdating(e){}disconnectedCallback(){this._$EO?.forEach(e=>e.hostDisconnected?.())}attributeChangedCallback(e,t,n){this._$AK(e,n)}_$ET(e,t){let n=this.constructor.elementProperties.get(e),r=this.constructor._$Eu(e,n);if(r!==void 0&&!0===n.reflect){let i=(n.converter?.toAttribute===void 0?Ae:n.converter).toAttribute(t,n.type);this._$Em=e,i==null?this.removeAttribute(r):this.setAttribute(r,i),this._$Em=null}}_$AK(e,t){let n=this.constructor,r=n._$Eh.get(e);if(r!==void 0&&this._$Em!==r){let e=n.getPropertyOptions(r),i=typeof e.converter==`function`?{fromAttribute:e.converter}:e.converter?.fromAttribute===void 0?Ae:e.converter;this._$Em=r;let a=i.fromAttribute(t,e.type);this[r]=a??this._$Ej?.get(r)??a,this._$Em=null}}requestUpdate(e,t,n,r=!1,i){if(e!==void 0){let a=this.constructor;if(!1===r&&(i=this[e]),n??=a.getPropertyOptions(e),!((n.hasChanged??je)(i,t)||n.useDefault&&n.reflect&&i===this._$Ej?.get(e)&&!this.hasAttribute(a._$Eu(e,n))))return;this.C(e,t,n)}!1===this.isUpdatePending&&(this._$ES=this._$EP())}C(e,t,{useDefault:n,reflect:r,wrapped:i},a){n&&!(this._$Ej??=new Map).has(e)&&(this._$Ej.set(e,a??t??this[e]),!0!==i||a!==void 0)||(this._$AL.has(e)||(this.hasUpdated||n||(t=void 0),this._$AL.set(e,t)),!0===r&&this._$Em!==e&&(this._$Eq??=new Set).add(e))}async _$EP(){this.isUpdatePending=!0;try{await this._$ES}catch(e){Promise.reject(e)}let e=this.scheduleUpdate();return e!=null&&await e,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??=this.createRenderRoot(),this._$Ep){for(let[e,t]of this._$Ep)this[e]=t;this._$Ep=void 0}let e=this.constructor.elementProperties;if(e.size>0)for(let[t,n]of e){let{wrapped:e}=n,r=this[t];!0!==e||this._$AL.has(t)||r===void 0||this.C(t,void 0,n,r)}}let e=!1,t=this._$AL;try{e=this.shouldUpdate(t),e?(this.willUpdate(t),this._$EO?.forEach(e=>e.hostUpdate?.()),this.update(t)):this._$EM()}catch(t){throw e=!1,this._$EM(),t}e&&this._$AE(t)}willUpdate(e){}_$AE(e){this._$EO?.forEach(e=>e.hostUpdated?.()),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(e)),this.updated(e)}_$EM(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(e){return!0}update(e){this._$Eq&&=this._$Eq.forEach(e=>this._$ET(e,this[e])),this._$EM()}updated(e){}firstUpdated(e){}};Ne.elementStyles=[],Ne.shadowRootOptions={mode:`open`},Ne[ke(`elementProperties`)]=new Map,Ne[ke(`finalized`)]=new Map,Oe?.({ReactiveElement:Ne}),(Te.reactiveElementVersions??=[]).push(`2.1.2`);var Pe=globalThis,Fe=e=>e,Ie=Pe.trustedTypes,Le=Ie?Ie.createPolicy(`lit-html`,{createHTML:e=>e}):void 0,Re=`$lit$`,ze=`lit$${Math.random().toFixed(9).slice(2)}$`,Be=`?`+ze,Ve=`<${Be}>`,He=document,Ue=()=>He.createComment(``),We=e=>e===null||typeof e!=`object`&&typeof e!=`function`,Ge=Array.isArray,Ke=e=>Ge(e)||typeof e?.[Symbol.iterator]==`function`,qe=`[
|
|
3
3
|
\f\r]`,Je=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,Ye=/-->/g,Xe=/>/g,Ze=RegExp(`>|${qe}(?:([^\\s"'>=/]+)(${qe}*=${qe}*(?:[^ \t\n\f\r"'\`<>=]|("|')|))|$)`,`g`),Qe=/'/g,$e=/"/g,et=/^(?:script|style|textarea|title)$/i,tt=e=>(t,...n)=>({_$litType$:e,strings:t,values:n}),g=tt(1),_=tt(2),nt=Symbol.for(`lit-noChange`),v=Symbol.for(`lit-nothing`),rt=new WeakMap,it=He.createTreeWalker(He,129);function at(e,t){if(!Ge(e)||!e.hasOwnProperty(`raw`))throw Error(`invalid template strings array`);return Le===void 0?t:Le.createHTML(t)}var ot=(e,t)=>{let n=e.length-1,r=[],i,a=t===2?`<svg>`:t===3?`<math>`:``,o=Je;for(let t=0;t<n;t++){let n=e[t],s,c,l=-1,u=0;for(;u<n.length&&(o.lastIndex=u,c=o.exec(n),c!==null);)u=o.lastIndex,o===Je?c[1]===`!--`?o=Ye:c[1]===void 0?c[2]===void 0?c[3]!==void 0&&(o=Ze):(et.test(c[2])&&(i=RegExp(`</`+c[2],`g`)),o=Ze):o=Xe:o===Ze?c[0]===`>`?(o=i??Je,l=-1):c[1]===void 0?l=-2:(l=o.lastIndex-c[2].length,s=c[1],o=c[3]===void 0?Ze:c[3]===`"`?$e:Qe):o===$e||o===Qe?o=Ze:o===Ye||o===Xe?o=Je:(o=Ze,i=void 0);let d=o===Ze&&e[t+1].startsWith(`/>`)?` `:``;a+=o===Je?n+Ve:l>=0?(r.push(s),n.slice(0,l)+Re+n.slice(l)+ze+d):n+ze+(l===-2?t:d)}return[at(e,a+(e[n]||`<?>`)+(t===2?`</svg>`:t===3?`</math>`:``)),r]},st=class e{constructor({strings:t,_$litType$:n},r){let i;this.parts=[];let a=0,o=0,s=t.length-1,c=this.parts,[l,u]=ot(t,n);if(this.el=e.createElement(l,r),it.currentNode=this.el.content,n===2||n===3){let e=this.el.content.firstChild;e.replaceWith(...e.childNodes)}for(;(i=it.nextNode())!==null&&c.length<s;){if(i.nodeType===1){if(i.hasAttributes())for(let e of i.getAttributeNames())if(e.endsWith(Re)){let t=u[o++],n=i.getAttribute(e).split(ze),r=/([.?@])?(.*)/.exec(t);c.push({type:1,index:a,name:r[2],strings:n,ctor:r[1]===`.`?ft:r[1]===`?`?pt:r[1]===`@`?mt:dt}),i.removeAttribute(e)}else e.startsWith(ze)&&(c.push({type:6,index:a}),i.removeAttribute(e));if(et.test(i.tagName)){let e=i.textContent.split(ze),t=e.length-1;if(t>0){i.textContent=Ie?Ie.emptyScript:``;for(let n=0;n<t;n++)i.append(e[n],Ue()),it.nextNode(),c.push({type:2,index:++a});i.append(e[t],Ue())}}}else if(i.nodeType===8)if(i.data===Be)c.push({type:2,index:a});else{let e=-1;for(;(e=i.data.indexOf(ze,e+1))!==-1;)c.push({type:7,index:a}),e+=ze.length-1}a++}}static createElement(e,t){let n=He.createElement(`template`);return n.innerHTML=e,n}};function ct(e,t,n=e,r){if(t===nt)return t;let i=r===void 0?n._$Cl:n._$Co?.[r],a=We(t)?void 0:t._$litDirective$;return i?.constructor!==a&&(i?._$AO?.(!1),a===void 0?i=void 0:(i=new a(e),i._$AT(e,n,r)),r===void 0?n._$Cl=i:(n._$Co??=[])[r]=i),i!==void 0&&(t=ct(e,i._$AS(e,t.values),i,r)),t}var lt=class{constructor(e,t){this._$AV=[],this._$AN=void 0,this._$AD=e,this._$AM=t}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(e){let{el:{content:t},parts:n}=this._$AD,r=(e?.creationScope??He).importNode(t,!0);it.currentNode=r;let i=it.nextNode(),a=0,o=0,s=n[0];for(;s!==void 0;){if(a===s.index){let t;s.type===2?t=new ut(i,i.nextSibling,this,e):s.type===1?t=new s.ctor(i,s.name,s.strings,this,e):s.type===6&&(t=new ht(i,this,e)),this._$AV.push(t),s=n[++o]}a!==s?.index&&(i=it.nextNode(),a++)}return it.currentNode=He,r}p(e){let t=0;for(let n of this._$AV)n!==void 0&&(n.strings===void 0?n._$AI(e[t]):(n._$AI(e,n,t),t+=n.strings.length-2)),t++}},ut=class e{get _$AU(){return this._$AM?._$AU??this._$Cv}constructor(e,t,n,r){this.type=2,this._$AH=v,this._$AN=void 0,this._$AA=e,this._$AB=t,this._$AM=n,this.options=r,this._$Cv=r?.isConnected??!0}get parentNode(){let e=this._$AA.parentNode,t=this._$AM;return t!==void 0&&e?.nodeType===11&&(e=t.parentNode),e}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(e,t=this){e=ct(this,e,t),We(e)?e===v||e==null||e===``?(this._$AH!==v&&this._$AR(),this._$AH=v):e!==this._$AH&&e!==nt&&this._(e):e._$litType$===void 0?e.nodeType===void 0?Ke(e)?this.k(e):this._(e):this.T(e):this.$(e)}O(e){return this._$AA.parentNode.insertBefore(e,this._$AB)}T(e){this._$AH!==e&&(this._$AR(),this._$AH=this.O(e))}_(e){this._$AH!==v&&We(this._$AH)?this._$AA.nextSibling.data=e:this.T(He.createTextNode(e)),this._$AH=e}$(e){let{values:t,_$litType$:n}=e,r=typeof n==`number`?this._$AC(e):(n.el===void 0&&(n.el=st.createElement(at(n.h,n.h[0]),this.options)),n);if(this._$AH?._$AD===r)this._$AH.p(t);else{let e=new lt(r,this),n=e.u(this.options);e.p(t),this.T(n),this._$AH=e}}_$AC(e){let t=rt.get(e.strings);return t===void 0&&rt.set(e.strings,t=new st(e)),t}k(t){Ge(this._$AH)||(this._$AH=[],this._$AR());let n=this._$AH,r,i=0;for(let a of t)i===n.length?n.push(r=new e(this.O(Ue()),this.O(Ue()),this,this.options)):r=n[i],r._$AI(a),i++;i<n.length&&(this._$AR(r&&r._$AB.nextSibling,i),n.length=i)}_$AR(e=this._$AA.nextSibling,t){for(this._$AP?.(!1,!0,t);e!==this._$AB;){let t=Fe(e).nextSibling;Fe(e).remove(),e=t}}setConnected(e){this._$AM===void 0&&(this._$Cv=e,this._$AP?.(e))}},dt=class{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(e,t,n,r,i){this.type=1,this._$AH=v,this._$AN=void 0,this.element=e,this.name=t,this._$AM=r,this.options=i,n.length>2||n[0]!==``||n[1]!==``?(this._$AH=Array(n.length-1).fill(new String),this.strings=n):this._$AH=v}_$AI(e,t=this,n,r){let i=this.strings,a=!1;if(i===void 0)e=ct(this,e,t,0),a=!We(e)||e!==this._$AH&&e!==nt,a&&(this._$AH=e);else{let r=e,o,s;for(e=i[0],o=0;o<i.length-1;o++)s=ct(this,r[n+o],t,o),s===nt&&(s=this._$AH[o]),a||=!We(s)||s!==this._$AH[o],s===v?e=v:e!==v&&(e+=(s??``)+i[o+1]),this._$AH[o]=s}a&&!r&&this.j(e)}j(e){e===v?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,e??``)}},ft=class extends dt{constructor(){super(...arguments),this.type=3}j(e){this.element[this.name]=e===v?void 0:e}},pt=class extends dt{constructor(){super(...arguments),this.type=4}j(e){this.element.toggleAttribute(this.name,!!e&&e!==v)}},mt=class extends dt{constructor(e,t,n,r,i){super(e,t,n,r,i),this.type=5}_$AI(e,t=this){if((e=ct(this,e,t,0)??v)===nt)return;let n=this._$AH,r=e===v&&n!==v||e.capture!==n.capture||e.once!==n.once||e.passive!==n.passive,i=e!==v&&(n===v||r);r&&this.element.removeEventListener(this.name,this,n),i&&this.element.addEventListener(this.name,this,e),this._$AH=e}handleEvent(e){typeof this._$AH==`function`?this._$AH.call(this.options?.host??this.element,e):this._$AH.handleEvent(e)}},ht=class{constructor(e,t,n){this.element=e,this.type=6,this._$AN=void 0,this._$AM=t,this.options=n}get _$AU(){return this._$AM._$AU}_$AI(e){ct(this,e)}},gt={M:Re,P:ze,A:Be,C:1,L:ot,R:lt,D:Ke,V:ct,I:ut,H:dt,N:pt,U:mt,B:ft,F:ht},_t=Pe.litHtmlPolyfillSupport;_t?.(st,ut),(Pe.litHtmlVersions??=[]).push(`3.3.3`);var vt=(e,t,n)=>{let r=n?.renderBefore??t,i=r._$litPart$;if(i===void 0){let e=n?.renderBefore??null;r._$litPart$=i=new ut(t.insertBefore(Ue(),e),e,void 0,n??{})}return i._$AI(e),i},yt=globalThis,y=class extends Ne{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){let e=super.createRenderRoot();return this.renderOptions.renderBefore??=e.firstChild,e}update(e){let t=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(e),this._$Do=vt(t,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return nt}};y._$litElement$=!0,y.finalized=!0,yt.litElementHydrateSupport?.({LitElement:y});var bt=yt.litElementPolyfillSupport;bt?.({LitElement:y}),(yt.litElementVersions??=[]).push(`4.2.2`);var xt={ATTRIBUTE:1,CHILD:2,PROPERTY:3,BOOLEAN_ATTRIBUTE:4,EVENT:5,ELEMENT:6},St=e=>(...t)=>({_$litDirective$:e,values:t}),Ct=class{constructor(e){}get _$AU(){return this._$AM._$AU}_$AT(e,t,n){this._$Ct=e,this._$AM=t,this._$Ci=n}_$AS(e,t){return this.update(e,t)}update(e,t){return this.render(...t)}},{I:wt}=gt,Tt=e=>e,Et=()=>document.createComment(``),Dt=(e,t,n)=>{let r=e._$AA.parentNode,i=t===void 0?e._$AB:t._$AA;if(n===void 0)n=new wt(r.insertBefore(Et(),i),r.insertBefore(Et(),i),e,e.options);else{let t=n._$AB.nextSibling,a=n._$AM,o=a!==e;if(o){let t;n._$AQ?.(e),n._$AM=e,n._$AP!==void 0&&(t=e._$AU)!==a._$AU&&n._$AP(t)}if(t!==i||o){let e=n._$AA;for(;e!==t;){let t=Tt(e).nextSibling;Tt(r).insertBefore(e,i),e=t}}}return n},Ot=(e,t,n=e)=>(e._$AI(t,n),e),kt={},At=(e,t=kt)=>e._$AH=t,jt=e=>e._$AH,Mt=e=>{e._$AR(),e._$AA.remove()},Nt=St(class extends Ct{constructor(){super(...arguments),this.key=v}render(e,t){return this.key=e,t}update(e,[t,n]){return t!==this.key&&(At(e),this.key=t),n}}),b=e=>(t,n)=>{n===void 0?customElements.define(e,t):n.addInitializer(()=>{customElements.define(e,t)})},Pt={attribute:!0,type:String,converter:Ae,reflect:!1,hasChanged:je},Ft=(e=Pt,t,n)=>{let{kind:r,metadata:i}=n,a=globalThis.litPropertyMetadata.get(i);if(a===void 0&&globalThis.litPropertyMetadata.set(i,a=new Map),r===`setter`&&((e=Object.create(e)).wrapped=!0),a.set(n.name,e),r===`accessor`){let{name:r}=n;return{set(n){let i=t.get.call(this);t.set.call(this,n),this.requestUpdate(r,i,e,!0,n)},init(t){return t!==void 0&&this.C(r,void 0,e,t),t}}}if(r===`setter`){let{name:r}=n;return function(n){let i=this[r];t.call(this,n),this.requestUpdate(r,i,e,!0,n)}}throw Error(`Unsupported decorator location: `+r)};function x(e){return(t,n)=>typeof n==`object`?Ft(e,t,n):((e,t,n)=>{let r=t.hasOwnProperty(n);return t.constructor.createProperty(n,e),r?Object.getOwnPropertyDescriptor(t,n):void 0})(e,t,n)}function S(e){return x({...e,state:!0,attribute:!1})}var It=(e,t,n)=>(n.configurable=!0,n.enumerable=!0,Reflect.decorate&&typeof t!=`object`&&Object.defineProperty(e,t,n),n);function C(e,t){return(n,r,i)=>{let a=t=>t.renderRoot?.querySelector(e)??null;if(t){let{get:e,set:t}=typeof r==`object`?n:i??(()=>{let e=Symbol();return{get(){return this[e]},set(t){this[e]=t}}})();return It(n,r,{get(){let n=e.call(this);return n===void 0&&(n=a(this),(n!==null||this.hasUpdated)&&t.call(this,n)),n}})}return It(n,r,{get(){return a(this)}})}}var w={sessionsDeleteArchived:`sessions.deleteArchived`,sessionsBulkMutations:`sessions.bulkMutations`,sessionsCleanup:`sessions.cleanup`,sessionsReload:`sessions.reload`,sessionsClearQueue:`sessions.clearQueue`,sessionsMessageActions:`sessions.messageActions`,sessionsSystemPrompt:`sessions.systemPrompt`,sessionsPersistedState:`sessions.persistedState`,sessionsNotifications:`sessions.notifications`,sessionsUnread:`sessions.unread`,promptAttachments:`prompt.attachments`,workspaceFileSuggestions:`workspace.fileSuggestions`,piPackagesManage:`piPackages.manage`,selectedMachineSettings:`settings.selectedMachine`,agentProfileConfig:`settings.agentProfile`,modelTierSettings:`settings.modelTiers`,utilityModelSettings:`settings.utilityModels`,sessionsModelPolicy:`sessions.modelPolicy`,sessionsModelPolicyDefaults:`sessions.modelPolicyDefaults`,sessionsModelPolicyStarterSelection:`sessions.modelPolicyStarterSelection`,sessionsReorder:`sessions.reorder`,projectUsageStatistics:`project.usageStatistics`},Lt=[`economy`,`fast`,`standard`,`advanced`,`capable`,`frontier`],Rt=[`lightweight`,`context`],zt=1e3,Bt=1e3,Vt=32*1024,Ht=8*1024,Ut=1e4;function Wt(e,t=Kt()){let n=new URL(t.viteBaseUrl,t.documentBaseUrl);return new URL(qt(e),n).toString()}function Gt(e,t=Kt()){let n=new URL(Wt(e,t));if(n.protocol===`http:`)n.protocol=`ws:`;else if(n.protocol===`https:`)n.protocol=`wss:`;else throw Error(`Cannot create a WebSocket URL from ${n.protocol}`);return n.toString()}function Kt(){return{viteBaseUrl:`./`,documentBaseUrl:document.baseURI}}function qt(e){return e.startsWith(`/`)?`.${e}`:e}var Jt=class extends Error{constructor(e,t){super(e),this.status=t,this.name=`HttpRequestError`}};async function T(e,t,n){let r=new Headers(n?.headers);n?.body!==void 0&&!r.has(`content-type`)&&r.set(`content-type`,`application/json`);let i=await fetch(Wt(e),{...n,headers:r});if(!i.ok)throw new Jt(Yt(await i.json().catch(()=>({})))??i.statusText,i.status);return t(await i.json())}function Yt(e){if(Xt(e))return typeof e.error==`string`?e.error:void 0}function Xt(e){return typeof e==`object`&&!!e}function Zt(e){return(e.split(/[\\/]/u).at(-1)?.toLowerCase()??e.toLowerCase()).replace(/(?:\.[cm]?js|\.exe|\.cmd)$/iu,``)===`pi`}function Qt(e){return!e.includes(`/`)&&!e.includes(`\\`)&&Zt(e)}var $t=new Set([`schemaVersion`,`revision`,`command`,`dir`,`sessionDirEnvKeys`]),en=/^sha256:[0-9a-f]{64}$/u,tn=/^[A-Za-z0-9_][A-Za-z0-9._+-]*$/u,nn=new Set([`PI_WEBUI_AGENT_SESSION_DIR`,`PI_CODING_AGENT_SESSION_DIR`]);function rn(e){if(!ln(e)||Object.keys(e).some(e=>!$t.has(e)))return;let t=e.schemaVersion,n=e.revision,r=e.command,i=e.dir,a=e.sessionDirEnvKeys;if(t===1&&!(typeof n!=`string`||!en.test(n))&&!(typeof r!=`string`||!an(r))&&!(typeof i!=`string`||!on(i))&&cn(a)&&new Set(a).size===a.length&&!(a[0]!==`PI_WEBUI_AGENT_SESSION_DIR`||a.some(e=>!nn.has(e))))return Object.freeze({schemaVersion:t,revision:n,command:r,dir:i,sessionDirEnvKeys:Object.freeze([...a])})}function an(e){return e!==e.trim()||/[\s;&|`$<>]/u.test(e)?!1:on(e)?!e.endsWith(`/`)&&!e.endsWith(`\\`):tn.test(e)}function on(e){if(e===``||e!==e.trim()||sn(e))return!1;let t=e.replace(/\\/g,`/`);return t.startsWith(`/`)||/^[A-Za-z]:\//u.test(t)}function sn(e){for(let t of e){let e=t.charCodeAt(0);if(e<32||e===127)return!0}return!1}function cn(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`&&e!==``)}function ln(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var un=Object.values(w),dn=new Set(un);w.sessionsDeleteArchived,w.sessionsBulkMutations,w.sessionsCleanup,w.sessionsReload,w.sessionsClearQueue,w.sessionsMessageActions,w.sessionsSystemPrompt,w.sessionsPersistedState,w.sessionsNotifications,w.sessionsUnread,w.promptAttachments,w.workspaceFileSuggestions,w.piPackagesManage,w.selectedMachineSettings,w.agentProfileConfig,w.modelTierSettings,w.utilityModelSettings,w.sessionsModelPolicy,w.sessionsModelPolicyDefaults,w.sessionsModelPolicyStarterSelection,w.sessionsReorder,w.sessionsDeleteArchived,w.sessionsBulkMutations,w.sessionsCleanup,w.sessionsReload,w.sessionsClearQueue,w.sessionsMessageActions,w.sessionsSystemPrompt,w.sessionsPersistedState,w.sessionsNotifications,w.sessionsUnread,w.promptAttachments,w.modelTierSettings,w.utilityModelSettings,w.sessionsModelPolicy,w.sessionsModelPolicyDefaults,w.sessionsModelPolicyStarterSelection,w.sessionsReorder,w.projectUsageStatistics,w.sessionsDeleteArchived,w.sessionsBulkMutations,w.sessionsCleanup,w.sessionsReload,w.sessionsClearQueue,w.sessionsMessageActions,w.sessionsSystemPrompt,w.sessionsPersistedState,w.sessionsNotifications,w.sessionsUnread,w.promptAttachments,w.workspaceFileSuggestions,w.piPackagesManage,w.selectedMachineSettings,w.agentProfileConfig,w.modelTierSettings,w.utilityModelSettings,w.sessionsModelPolicy,w.sessionsModelPolicyDefaults,w.sessionsModelPolicyStarterSelection,w.sessionsReorder,w.projectUsageStatistics;function fn(e){return typeof e==`string`&&dn.has(e)}function E(e,t){return e?.capabilities?.includes(t)===!0}function pn(e){if(!(!Array.isArray(e)||!e.every(e=>typeof e==`string`)))return e.filter(fn)}var mn=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u;function hn(e){return mn.test(e)}function gn(e){try{let t=Intl.getCanonicalLocales(e);return t.length===1?t[0]:void 0}catch{return}}var _n=4e3;function vn(e){return{...e?.voice===void 0?{}:{voice:e.voice},rate:e?.rate??0}}function yn(e){let t=e.replace(/\r\n|\r/gu,`
|
|
4
4
|
`).replace(/(?!\t|\n)\p{Cc}/gu,``),n=t.slice(0,_n);if(n.length===4e3){let e=n.charCodeAt(n.length-1),r=t.charCodeAt(_n);e>=55296&&e<=56319&&r>=56320&&r<=57343&&(n=n.slice(0,-1))}return n.trimEnd()}var bn=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u;function xn(e){return bn.test(e)}var Sn=[`off`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`];function Cn(e){return Sn.some(t=>t===e)}function wn(e){return e===void 0||e===``?`off`:e}function Tn(e,t){let n=t.length>=2?t:Sn,r=n.length-1,i=wn(e),a=n.indexOf(i);return{total:r,filled:a<=0?0:Math.min(a,r)}}var En=/^\s*([!#$%&'*+.^_`|~0-9A-Za-z-]+)\/([!#$%&'*+.^_`|~0-9A-Za-z-]+)(?:\s*;\s*([!#$%&'*+.^_`|~0-9A-Za-z-]+)\s*=\s*([!#$%&'*+.^_`|~0-9A-Za-z.-]+))?\s*$/u;function Dn(e){if(e===void 0)return;let t=En.exec(e);if(t===null)return;let n=t[1]?.toLowerCase(),r=t[2]?.toLowerCase(),i=t[3]?.toLowerCase(),a=t[4]?.toLowerCase(),o=n===void 0||r===void 0?void 0:`${n}/${r}`;if(o===`audio/webm`&&i===`codecs`&&a===`opus`)return`audio/webm;codecs=opus`;if(o===`audio/ogg`&&i===`codecs`&&a===`opus`)return`audio/ogg;codecs=opus`;if(o===`audio/mp4`&&i===`codecs`&&a===`mp4a.40.2`)return`audio/mp4;codecs=mp4a.40.2`;if(o===`audio/mp4`&&i===void 0)return`audio/mp4`}function On(e){return typeof e==`object`&&!!e}function D(e){if(!On(e))throw Error(`Expected object response`);return e}function O(e,t){let n=e[t];if(typeof n!=`string`)throw Error(`Expected string field: ${t}`);return n}function k(e,t){let n=e[t];if(n!==void 0){if(typeof n!=`string`)throw Error(`Expected optional string field: ${t}`);return n}}function A(e,t){let n=e[t];if(typeof n!=`number`)throw Error(`Expected number field: ${t}`);return n}function j(e,t){let n=e[t];if(typeof n!=`boolean`)throw Error(`Expected boolean field: ${t}`);return n}function M(e){return t=>{if(!Array.isArray(t))throw Error(`Expected array response`);return t.map(e)}}function kn(e){let t=yr(e,`host speech status`);xr(t,[`available`,`reason`,`voices`],`host speech status`);let n=j(t,`available`),r=Object.hasOwn(t,`reason`)?Ho(t,`reason`):void 0;if(!n&&r===void 0)throw Error(`Unavailable host speech status requires a reason`);let i=An(t.voices);return{available:n,...P(`reason`,r),voices:i}}function An(e){if(!Array.isArray(e))throw Error(`Expected host speech voices array`);let t=e.map(jn),n=new Set;for(let e of t){if(n.has(e.name))throw Error(`Duplicate host speech voice name`);n.add(e.name)}return t}function jn(e){let t=yr(e,`host speech voice`);xr(t,[`name`,`language`,`variant`],`host speech voice`);let n=Object.hasOwn(t,`variant`)?Ho(t,`variant`):void 0;return{name:Ho(t,`name`),language:Ho(t,`language`),...P(`variant`,n)}}function Mn(e){let t=yr(e,`host speech terminal result`);xr(t,[`runId`,`outcome`],`host speech terminal result`);let n=Fn(t,`runId`),r=t.outcome;if(r!==`ended`&&r!==`canceled`)throw Error(`Invalid host speech terminal outcome`);return{runId:n,outcome:r}}function Nn(e){let t=yr(e,`host speech stop response`);return xr(t,[`runId`,`stopped`],`host speech stop response`),{runId:Fn(t,`runId`),stopped:j(t,`stopped`)}}function Pn(e){let t=yr(e,`speech input transcription response`);xr(t,[`text`],`speech input transcription response`);let n=Ho(t,`text`);if(new TextEncoder().encode(n).byteLength>1048576)throw Error(`Speech input transcription exceeds the maximum size`);return{text:n}}function Fn(e,t){let n=O(e,t);if(!xn(n))throw Error(`Invalid host speech run ID field: ${t}`);return n}function In(e){if(!Array.isArray(e))throw Error(`Expected array response`);return e}function Ln(e,t){if(!Array.isArray(e)||!e.every(e=>typeof e==`string`))throw Error(`Expected string array field: ${t}`);return e}function Rn(e){if(!On(e)||typeof e.kind!=`string`)throw Error(`Invalid memory snapshot response`);if(e.kind===`unavailable`)return{kind:`unavailable`};if(e.kind!==`data`)throw Error(`Invalid memory snapshot response`);return{kind:`data`,globalEntries:zn(e.globalEntries),projectEntries:zn(e.projectEntries),...typeof e.projectUnavailableMessage==`string`?{projectUnavailableMessage:e.projectUnavailableMessage}:{}}}function zn(e){if(!Array.isArray(e))throw Error(`Invalid memory snapshot response`);return e.map(e=>{if(!On(e)||typeof e.id!=`string`||typeof e.content!=`string`)throw Error(`Invalid memory snapshot response`);return{id:e.id,content:e.content,...typeof e.category==`string`?{category:e.category}:{},...typeof e.created==`string`?{created:e.created}:{},...typeof e.last==`string`?{last:e.last}:{},...typeof e.failureReason==`string`?{failureReason:e.failureReason}:{}}})}function Bn(e){if(!On(e)||typeof e.kind!=`string`)throw Error(`Invalid learned skills snapshot response`);if(e.kind===`unavailable`)return{kind:`unavailable`};if(e.kind!==`data`)throw Error(`Invalid learned skills snapshot response`);let t=e.projectUnavailableMessage;if(t!==void 0&&typeof t!=`string`)throw Error(`Invalid learned skills snapshot response`);return{kind:`data`,globalSkills:Vn(e.globalSkills),projectSkills:Vn(e.projectSkills),...t===void 0?{}:{projectUnavailableMessage:t}}}function Vn(e){if(!Array.isArray(e))throw Error(`Invalid learned skills snapshot response`);return e.map(Hn)}function Hn(e){let t=D(e),n=N(t,`version`),r=k(t,`created`),i=k(t,`updated`);return{id:O(t,`id`),name:O(t,`name`),description:O(t,`description`),filePath:O(t,`filePath`),...n===void 0?{}:{version:n},...r===void 0?{}:{created:r},...i===void 0?{}:{updated:i}}}function Un(e){if(Array.isArray(e))return{messages:e,start:0,total:e.length};let t=D(e);return{messages:In(t.messages),start:A(t,`start`),total:A(t,`total`)}}function Wn(e){let t=D(e);return M(Gn)(t.machines)}function Gn(e){let t=D(e),n=Jn(t,`kind`),r=k(t,`baseUrl`),i=Yn(t,`status`),a=k(t,`statusMessage`);return{id:O(t,`id`),name:O(t,`name`),kind:n,...r===void 0?{}:{baseUrl:r},createdAt:O(t,`createdAt`),updatedAt:O(t,`updatedAt`),...i===void 0?{}:{status:i},...a===void 0?{}:{statusMessage:a}}}function Kn(e){let t=D(e),n=Yn(t,`status`),r=k(t,`error`);return{machineId:O(t,`machineId`),ok:j(t,`ok`),checkedAt:O(t,`checkedAt`),...n===void 0?{}:{status:n},...t.web===void 0?{}:{web:Eo(t.web)},...t.sessiond===void 0?{}:{sessiond:Eo(t.sessiond)},...r===void 0?{}:{error:r}}}function qn(e){let t=D(e),n=k(t,`error`);return{machineId:O(t,`machineId`),ok:j(t,`ok`),checkedAt:O(t,`checkedAt`),...P(`packageName`,k(t,`packageName`)),...P(`generatedAt`,k(t,`generatedAt`)),...t.components===void 0?{}:{components:wo(t.components)},...t.capabilities===void 0?{}:{capabilities:Mo(t.capabilities)},...n===void 0?{}:{error:n}}}function Jn(e,t){let n=O(e,t);if(n!==`local`&&n!==`remote`)throw Error(`Expected machine kind field: ${t}`);return n}function Yn(e,t){let n=k(e,t);if(n!==void 0){if(n!==`unknown`&&n!==`online`&&n!==`offline`&&n!==`error`)throw Error(`Expected machine status field: ${t}`);return n}}function Xn(e){let t=D(e),n=bo(t.pinned,`pinned`);return{id:O(t,`id`),name:O(t,`name`),path:O(t,`path`),createdAt:O(t,`createdAt`),...n===void 0?{}:{pinned:n}}}function Zn(e){let t=D(e),n=O(t,`lastUsedAt`),r=new Date(n);if(!Number.isFinite(r.getTime())||r.toISOString()!==n)throw Error(`Invalid canonical recent project timestamp`);return{id:O(t,`id`),name:O(t,`name`),path:O(t,`path`),lastUsedAt:n}}function Qn(e){let t=Br(e,Zn,20,`recentProjects`),n=new Set,r=new Set;for(let e of t){if(n.has(e.id))throw Error(`Duplicate recent project id`);if(r.has(e.path))throw Error(`Duplicate recent project path`);n.add(e.id),r.add(e.path)}return t}function $n(e){let t=D(e),n=k(t,`branch`);return{id:O(t,`id`),projectId:O(t,`projectId`),path:O(t,`path`),label:O(t,`label`),...n===void 0?{}:{branch:n},isMain:j(t,`isMain`),isGitRepo:j(t,`isGitRepo`),isGitWorktree:j(t,`isGitWorktree`),...P(`effectiveConfig`,er(t.effectiveConfig))}}function er(e){if(e!==void 0){if(!On(e)||Array.isArray(e))throw Error(`Invalid workspace effectiveConfig field`);return{...P(`uploads`,Xa(e.uploads))}}}function tr(e){let t=D(e),n=k(t,`name`),r=bo(t.persisted,`persisted`),i=k(t,`parentSessionPath`),a=k(t,`archivedAt`),o=bo(t.pinned,`pinned`),s=t.creationSource===`session-list-plus`?t.creationSource:void 0,c=t.manualOrder===void 0?void 0:Ur(t,`manualOrder`);return{id:O(t,`id`),path:O(t,`path`),cwd:O(t,`cwd`),...r===void 0?{}:{persisted:r},...n===void 0?{}:{name:n},created:O(t,`created`),modified:O(t,`modified`),messageCount:A(t,`messageCount`),firstMessage:O(t,`firstMessage`),...i===void 0?{}:{parentSessionPath:i},...t.archived===!0?{archived:!0}:{},...a===void 0?{}:{archivedAt:a},...o===void 0?{}:{pinned:o},...s===void 0?{}:{creationSource:s},...c===void 0?{}:{manualOrder:c}}}function nr(e){let t=D(e);return{id:O(t,`id`),cwd:O(t,`cwd`),manualOrder:Ur(t,`manualOrder`)}}function rr(e){let t=D(e);return{orderedSessions:M(nr)(t.orderedSessions)}}function ir(e){if(e!==`info`&&e!==`warning`&&e!==`error`)throw Error(`Invalid session warning severity`);return e}function ar(e){if(e!==void 0)return{id:O(D(e),`id`)}}function or(e){let t=D(e),n=ar(t.dismiss);return{severity:ir(t.severity),message:O(t,`message`),...P(`source`,k(t,`source`)),...P(`path`,k(t,`path`)),...n===void 0?{}:{dismiss:n}}}function sr(e){return e===void 0?{}:{warnings:M(or)(e)}}function cr(e){let t=D(e);return{sessionId:O(t,`sessionId`),...P(`persisted`,bo(t.persisted,`persisted`)),isStreaming:j(t,`isStreaming`),isCompacting:j(t,`isCompacting`),isBashRunning:j(t,`isBashRunning`),pendingMessageCount:A(t,`pendingMessageCount`),queuedMessages:t.queuedMessages===void 0?[]:M(ni)(t.queuedMessages),...P(`messageCount`,N(t,`messageCount`)),tokens:ri(t.tokens),cost:A(t,`cost`),...Ji(t.generation),...ai(t.model),...P(`modelPolicy`,t.modelPolicy===void 0?void 0:mr(t.modelPolicy)),...Yi(t.contextUsage),...P(`thinkingLevel`,k(t,`thinkingLevel`)),...sr(t.warnings)}}function lr(e){let t=yr(e,`session model policy response`);if(xr(t,[`contractVersion`,`policy`,`session`],`session model policy response`),t.contractVersion!==1)throw Error(`Invalid session model policy contract version`);let n=cr(t.session);if(!Object.hasOwn(t,`policy`)){let e=n.modelPolicy?.blockedReason;if(e===void 0||e.trim()===``)throw Error(`Expected non-blank string field: blockedReason`);return{contractVersion:1,session:n}}return{contractVersion:1,policy:ur(t.policy),session:n}}function ur(e){let t=yr(e,`session model policy`);xr(t,[`mode`,`exact`,`tier`],`session model policy`);let n=_r(t.mode),r=vr(t,`session model policy`);if(n===`tiered`&&r===void 0)throw Error(`Tiered session model policy requires a tier`);return{mode:n,exact:hr(t.exact),...P(`tier`,r)}}function dr(e){let t=yr(e,`starter model policy preference`);xr(t,[`mode`,`tier`],`starter model policy preference`);let n=_r(t.mode),r=vr(t,`starter model policy preference`);if(n===`tiered`&&r===void 0)throw Error(`Tiered starter model policy preference requires a tier`);return{mode:n,...P(`tier`,r)}}function fr(e){let t=yr(e,`starter model policy preference`);return Object.hasOwn(t,`exact`)?pr(t):dr(t)}function pr(e){let t=yr(e,`confirmed starter model policy preference`);xr(t,[`mode`,`exact`,`tier`],`confirmed starter model policy preference`);let n=_r(t.mode),r=vr(t,`confirmed starter model policy preference`);if(n===`tiered`&&r===void 0)throw Error(`Tiered confirmed starter model policy preference requires a tier`);return{mode:n,exact:hr(t.exact),...P(`tier`,r)}}function mr(e){let t=yr(e,`session model policy status`);xr(t,[`mode`,`tier`,`resolved`,`ladderValid`,`blockedReason`],`session model policy status`);let n=_r(t.mode),r=vr(t,`session model policy status`);if(n===`tiered`&&r===void 0)throw Error(`Tiered session model policy status requires a tier`);return{mode:n,...P(`tier`,r),resolved:hr(t.resolved),ladderValid:j(t,`ladderValid`),...P(`blockedReason`,k(t,`blockedReason`))}}function hr(e){let t=yr(e,`exact selection`);return xr(t,[`model`,`thinkingLevel`],`exact selection`),{model:gr(t.model),thinkingLevel:Ho(t,`thinkingLevel`)}}function gr(e){let t=yr(e,`model reference`);return xr(t,[`provider`,`id`],`model reference`),{provider:Ho(t,`provider`),id:Ho(t,`id`)}}function _r(e){if(e!==`exact`&&e!==`tiered`)throw Error(`Invalid session model policy mode`);return e}function vr(e,t){if(!Object.hasOwn(e,`tier`))return;let n=e.tier;if(typeof n!=`string`||!Fa(n))throw Error(`Invalid ${t} tier`);return n}function yr(e,t){if(!br(e))throw Error(`Expected ${t} object`);return e}function br(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Reflect.getPrototypeOf(e);return t===Object.prototype||t===null}function xr(e,t,n){let r=Object.keys(e).find(e=>!t.includes(e));if(r!==void 0)throw Error(`Invalid ${n} field: ${r}`)}function Sr(e){let t=D(e);return{seq:A(t,`seq`),partial:t.partial??null}}function Cr(e){let t=k(D(e),`systemPrompt`);return t===void 0?{}:{systemPrompt:t}}function wr(e){let t=D(e),n=Ur(t,`catalogRevision`),r=Br(t.sessions,Er,Bt,`sessions`);if(Dr(r),Or(r),r.some(e=>e.completionOrder>n))throw Error(`Session unread completion order exceeds catalog revision`);return{catalogId:kr(t,`catalogId`,512),catalogRevision:n,sessions:r}}function Tr(e){let t=D(e);if(t.type!==`sessions.unread`)throw Error(`Invalid session unread event type`);let n=kr(t,`sessionId`,512),r=kr(t,`cwd`,Vt),i=Ar(t,`catalogRevision`),a=t.unread===null?null:Er(t.unread);if(a!==null&&(a.sessionId!==n||a.cwd!==r))throw Error(`Session unread event identity mismatch`);if(a!==null&&a.completionOrder>i)throw Error(`Session unread completion order exceeds catalog revision`);return{type:`sessions.unread`,catalogId:kr(t,`catalogId`,512),catalogRevision:i,sessionId:n,cwd:r,unread:a}}function Er(e){let t=D(e),n=kr(t,`completedAt`,64),r=new Date(n);if(!Number.isFinite(r.getTime())||r.toISOString()!==n)throw Error(`Invalid canonical session unread completion time`);return{sessionId:kr(t,`sessionId`,512),cwd:kr(t,`cwd`,Vt),completionOrder:Ar(t,`completionOrder`),completedAt:n}}function Dr(e){let t=e.map(e=>JSON.stringify([e.sessionId,e.cwd]));if(new Set(t).size!==t.length)throw Error(`Duplicate session unread identity`);let n=e.map(e=>e.completionOrder);if(new Set(n).size!==n.length)throw Error(`Duplicate session unread completion order`)}function Or(e){for(let t=1;t<e.length;t+=1){let n=e[t-1],r=e[t];if(n===void 0||r===void 0||n.completionOrder<=r.completionOrder)throw Error(`Session unread summaries are not newest-first`)}}function kr(e,t,n){let r=Hr(e,t);if(r.length>n)throw Error(`String field exceeds limit: ${t}`);return r}function Ar(e,t){let n=Ur(e,t);if(n===0)throw Error(`Expected positive safe integer field: ${t}`);return n}function jr(e){let t=D(e),n=Nr(t.summary),r=Br(t.notifications,Pr,100,`notifications`);if(Wr(r),Gr(r),n.retainedCount!==r.length)throw Error(`Notification snapshot retained count mismatch`);if(n.highestSeverity!==qr(r))throw Error(`Notification snapshot severity mismatch`);let i=Fr(t.dismissThrough),a=r[0]?.order??0;if(i.order!==a)throw Error(`Notification snapshot dismiss cutoff mismatch`);if(i.overflowWatermark<n.discardedCount)throw Error(`Notification snapshot overflow cutoff mismatch`);return{daemonInstanceId:Hr(t,`daemonInstanceId`),catalogRevision:Ur(t,`catalogRevision`),summary:n,notifications:r,dismissThrough:i}}function Mr(e){let t=D(e);if(t.type!==`notifications.inbox`)throw Error(`Invalid notification inbox event type`);let n=Nr(t.summary),r=Fr(t.dismissThrough);if(r.overflowWatermark<n.discardedCount)throw Error(`Notification event overflow cutoff mismatch`);let i=Ir(t.delta);if(i.kind===`cleared`&&!Kr(n))throw Error(`Notification clear event summary mismatch`);if(i.kind===`added`&&n.retainedCount===0)throw Error(`Notification add event summary mismatch`);return{type:`notifications.inbox`,daemonInstanceId:Hr(t,`daemonInstanceId`),catalogRevision:Ur(t,`catalogRevision`),summary:n,dismissThrough:r,delta:i}}function Nr(e){let t=D(e),n=Ur(t,`retainedCount`);if(n>100)throw Error(`Notification retained count exceeds limit`);let r=Ur(t,`discardedCount`),i=Rr(t.highestSeverity);if(n===0!=(i===void 0))throw Error(`Notification summary severity mismatch`);return{sessionId:Hr(t,`sessionId`),cwd:Hr(t,`cwd`),inboxRevision:Ur(t,`inboxRevision`),retainedCount:n,discardedCount:r,...i===void 0?{}:{highestSeverity:i}}}function Pr(e){let t=D(e),n=O(t,`message`);if(new TextEncoder().encode(n).byteLength>8192)throw Error(`Notification message exceeds byte limit`);let r=O(t,`receivedAt`);if(!Number.isFinite(Date.parse(r)))throw Error(`Invalid notification receive time`);let i=Ur(t,`order`);if(i===0)throw Error(`Invalid notification order`);return{id:Hr(t,`id`),message:n,truncated:j(t,`truncated`),severity:Lr(t.severity),receivedAt:r,order:i}}function Fr(e){let t=D(e);return{order:Ur(t,`order`),overflowWatermark:Ur(t,`overflowWatermark`)}}function Ir(e){let t=D(e);switch(t.kind){case`added`:{let e=k(t,`evictedNotificationId`);return{kind:`added`,notification:Pr(t.notification),...e===void 0?{}:{evictedNotificationId:e}}}case`dismissed`:{let e=Br(t.notificationIds,Vr,100,`notificationIds`);if(new Set(e).size!==e.length)throw Error(`Duplicate dismissed notification id`);return{kind:`dismissed`,notificationIds:e}}case`cleared`:return{kind:`cleared`,reason:zr(t.reason)};case`resync`:return{kind:`resync`};default:throw Error(`Invalid notification inbox delta`)}}function Lr(e){if(e!==`info`&&e!==`warning`&&e!==`error`)throw Error(`Invalid notification severity`);return e}function Rr(e){return e===void 0?void 0:Lr(e)}function zr(e){switch(e){case`runtime-close`:case`archive`:case`delete`:case`restore`:case`archive-reconcile`:case`replacement`:case`initialization-failed`:case`service-dispose`:return e;default:throw Error(`Invalid notification clear reason`)}}function Br(e,t,n,r){if(!Array.isArray(e))throw Error(`Expected array field: ${r}`);if(e.length>n)throw Error(`Array field exceeds limit: ${r}`);return e.map(t)}function Vr(e){if(typeof e!=`string`||e===``)throw Error(`Expected non-empty string`);return e}function Hr(e,t){let n=O(e,t);if(n===``)throw Error(`Expected non-empty string field: ${t}`);return n}function Ur(e,t){let n=e[t];if(typeof n!=`number`||!Number.isSafeInteger(n)||n<0)throw Error(`Expected non-negative safe integer field: ${t}`);return n}function Wr(e){if(new Set(e.map(e=>e.id)).size!==e.length)throw Error(`Duplicate notification id`);if(new Set(e.map(e=>e.order)).size!==e.length)throw Error(`Duplicate notification order`)}function Gr(e){for(let t=1;t<e.length;t+=1){let n=e[t-1],r=e[t];if(n===void 0||r===void 0||n.order<=r.order)throw Error(`Notifications are not newest-first`)}}function Kr(e){return e.retainedCount===0&&e.discardedCount===0}function qr(e){let t;for(let n of e){if(n.severity===`error`)return`error`;n.severity===`warning`?t=`warning`:t??=`info`}return t}function Jr(e){let t=D(e),n=t.skippedBusySessionIds===void 0?void 0:Ln(t.skippedBusySessionIds,`skippedBusySessionIds`);return{generatedAt:O(t,`generatedAt`),thresholds:$r(t.thresholds),projects:M(ei)(t.projects),totals:ti(t.totals),...n===void 0?{}:{skippedBusySessionIds:n}}}function Yr(e){let t=D(e);return{...Jr(t),archivedSessionIds:Ln(t.archivedSessionIds,`archivedSessionIds`),deletedSessionIds:Ln(t.deletedSessionIds,`deletedSessionIds`)}}function Xr(e){let t=D(e);if(t.archived!==!0)throw Error(`Expected bulk archived response`);return{archived:!0,archivedSessionIds:Ln(t.archivedSessionIds,`archivedSessionIds`),failures:M(Qr)(t.failures),generatedAt:O(t,`generatedAt`)}}function Zr(e){let t=D(e);if(t.deleted!==!0)throw Error(`Expected bulk deleted response`);return{deleted:!0,deletedSessionIds:Ln(t.deletedSessionIds,`deletedSessionIds`),failures:M(Qr)(t.failures),generatedAt:O(t,`generatedAt`)}}function Qr(e){let t=D(e);return{sessionId:O(t,`sessionId`),error:O(t,`error`)}}function $r(e){let t=D(e);return{...P(`archiveIdleDays`,N(t,`archiveIdleDays`)),...P(`deleteArchivedDays`,N(t,`deleteArchivedDays`))}}function ei(e){let t=D(e);return{cwd:O(t,`cwd`),archiveCount:A(t,`archiveCount`),deleteCount:A(t,`deleteCount`)}}function ti(e){let t=D(e);return{archiveCount:A(t,`archiveCount`),deleteCount:A(t,`deleteCount`)}}function ni(e){let t=D(e),n=O(t,`kind`);if(n!==`steer`&&n!==`followUp`)throw Error(`Invalid queued message kind`);return{kind:n,text:O(t,`text`)}}function ri(e){let t=D(e);return{input:A(t,`input`),output:A(t,`output`),cacheRead:A(t,`cacheRead`),cacheWrite:A(t,`cacheWrite`),total:A(t,`total`)}}function ii(e){let t=D(e);return{...P(`provider`,k(t,`provider`)),...P(`id`,k(t,`id`)),...P(`name`,k(t,`name`)),...P(`contextWindow`,N(t,`contextWindow`)),...P(`reasoning`,t.reasoning)}}function ai(e){return e===void 0?{}:{model:ii(e)}}function oi(e){let t=D(e);return{models:M(ii)(t.models)}}function si(e){let t=D(e),n=t.starterModelPolicyPreference===void 0?void 0:dr(t.starterModelPolicyPreference),r=k(t,`starterModelPolicyPreferenceError`);if(n!==void 0&&r!==void 0)throw Error(`Session defaults cannot contain both a starter preference and preference error`);return{...t.model===void 0?{}:{model:ii(t.model)},thinkingLevel:O(t,`thinkingLevel`),models:M(ii)(t.models),thinkingLevels:Ln(t.thinkingLevels,`thinkingLevels`),...P(`starterModelPolicyPreference`,n),...P(`starterModelPolicyPreferenceError`,r)}}function ci(e){let t=yr(e,`version-two session defaults response`);if(xr(t,[`starterModelPolicyContractVersion`,`model`,`thinkingLevel`,`models`,`thinkingLevels`,`starterModelPolicyPreference`,`starterModelPolicyPreferenceError`],`version-two session defaults response`),t.starterModelPolicyContractVersion!==2)throw Error(`Invalid starter model policy contract version`);let n=t.starterModelPolicyPreference===void 0?void 0:fr(t.starterModelPolicyPreference),r=k(t,`starterModelPolicyPreferenceError`);if(n!==void 0&&r!==void 0)throw Error(`Session defaults cannot contain both a starter preference and preference error`);return{starterModelPolicyContractVersion:2,...t.model===void 0?{}:{model:ii(t.model)},thinkingLevel:O(t,`thinkingLevel`),models:M(ii)(t.models),thinkingLevels:Ln(t.thinkingLevels,`thinkingLevels`),...P(`starterModelPolicyPreference`,n),...P(`starterModelPolicyPreferenceError`,r)}}function li(e){let t=fi(e,`models configuration`),n=t.providers;if(n===void 0)return{...t,providers:{}};let r=fi(n,`models configuration providers`),i={};for(let[e,t]of Object.entries(r))i[e]=ui(t);return{...t,providers:i}}function ui(e){let t=fi(e,`models configuration provider`),n={};for(let[e,r]of Object.entries(t))n[e]=r;let r=k(t,`baseUrl`);r!==void 0&&(n.baseUrl=r);let i=k(t,`api`);i!==void 0&&(n.api=i);let a=k(t,`apiKey`);a!==void 0&&(n.apiKey=a);let o=pi(t.headers,`models configuration provider headers`);o!==void 0&&(n.headers=mi(o,`models configuration provider headers`));let s=pi(t.compat,`models configuration provider compatibility`);s!==void 0&&(n.compat={...s});let c=pi(t.modelOverrides,`models configuration provider model overrides`);c!==void 0&&(n.modelOverrides={...c});let l=t.models;if(l!==void 0){if(!Array.isArray(l))throw Error(`Expected models configuration models array`);n.models=l.map(di)}return n}function di(e){let t=fi(e,`models configuration model`),n={id:O(t,`id`)};for(let[e,r]of Object.entries(t))n[e]=r;n.id=O(t,`id`);let r=k(t,`name`);r!==void 0&&(n.name=r);let i=k(t,`api`);i!==void 0&&(n.api=i);let a=as(t,`reasoning`);a!==void 0&&(n.reasoning=a);let o=pi(t.thinkingLevelMap,`models configuration thinking level map`);o!==void 0&&(n.thinkingLevelMap=hi(o));let s=t.input;if(s!==void 0){if(!Array.isArray(s)||!s.every(e=>typeof e==`string`))throw Error(`Expected models configuration model input array of strings`);n.input=[...s]}let c=N(t,`contextWindow`);c!==void 0&&(n.contextWindow=c);let l=N(t,`maxTokens`);l!==void 0&&(n.maxTokens=l);let u=pi(t.cost,`models configuration model cost`);u!==void 0&&(n.cost=gi(u));let d=pi(t.compat,`models configuration model compatibility`);return d!==void 0&&(n.compat={...d}),n}function fi(e,t){if(!On(e)||Array.isArray(e))throw Error(`Expected ${t} object`);return e}function pi(e,t){if(e!==void 0)return fi(e,t)}function mi(e,t){let n={};for(let[r,i]of Object.entries(e)){if(typeof i!=`string`)throw Error(`Expected ${t} values to be strings`);n[r]=i}return n}function hi(e){let t={};for(let[n,r]of Object.entries(e)){if(r!==null&&typeof r!=`string`)throw Error(`Expected models configuration thinking level map values to be strings or null`);t[n]=r}return t}function gi(e){let t={};for(let n of[`input`,`output`,`cacheRead`,`cacheWrite`]){let r=e[n];if(r!==void 0){if(typeof r!=`number`)throw Error(`Expected models configuration model cost ${n} to be a number`);t[n]=r}}return t}function _i(e){if(D(e).success!==!0)throw Error(`Expected successful models configuration save`);return{success:!0}}function vi(e){let t=D(e);return{models:M(yi)(t.models)}}function yi(e){let t=D(e),n=O(t,`id`),r=k(t,`name`);return r===void 0?{id:n}:{id:n,name:r}}function bi(e){let t=D(e),n=j(t,`ok`),r=k(t,`error`),i=t.latencyMs===void 0?void 0:A(t,`latencyMs`),a=t.status===void 0?void 0:A(t,`status`),o=k(t,`responseText`);return{ok:n,...r===void 0?{}:{error:r},...i===void 0?{}:{latencyMs:i},...a===void 0?{}:{status:a},...o===void 0?{}:{responseText:o}}}function xi(e){let t=D(e);return{skills:M(Si)(t.skills)}}function Si(e){let t=D(e),n=D(t.sourceInfo),r=k(n,`source`),i=k(n,`scope`);return{name:O(t,`name`),description:O(t,`description`),filePath:O(t,`filePath`),baseDir:O(t,`baseDir`),disableModelInvocation:j(t,`disableModelInvocation`),sourceInfo:{...r===void 0?{}:{source:r},...i===void 0?{}:{scope:i}},...t.install===void 0?{}:{install:Ci(t.install)}}}function Ci(e){let t=D(e),n=k(t,`sourceType`),r=k(t,`skillsShUrl`),i=k(t,`skillPath`),a=k(t,`ref`),o=k(t,`versionHash`);return{package:O(t,`package`),scope:wi(t.scope),source:O(t,`source`),...n===void 0?{}:{sourceType:n},...r===void 0?{}:{skillsShUrl:r},...i===void 0?{}:{skillPath:i},...a===void 0?{}:{ref:a},...o===void 0?{}:{versionHash:o},canCheckForUpdates:j(t,`canCheckForUpdates`)}}function wi(e){if(e!==`global`&&e!==`project`)throw Error(`Expected skill install scope`);return e}function Ti(e){if(D(e).success!==!0)throw Error(`Expected successful Skills mutation`);return{success:!0}}function Ei(e){let t=D(e);return{results:M(Di)(t.results)}}function Di(e){let t=D(e);return{package:O(t,`package`),installs:O(t,`installs`),url:O(t,`url`)}}function Oi(e){let t=D(e);return{updates:M(ki)(t.updates)}}function ki(e){let t=D(e),n=k(t,`currentVersion`),r=k(t,`latestVersion`),i=k(t,`message`);return{package:O(t,`package`),scope:wi(t.scope),state:Ai(t.state),...n===void 0?{}:{currentVersion:n},...r===void 0?{}:{latestVersion:r},...i===void 0?{}:{message:i}}}function Ai(e){if(e!==`up-to-date`&&e!==`update-available`&&e!==`unsupported`&&e!==`error`)throw Error(`Expected skill update state`);return e}function ji(e){let t=D(e);if(t.success!==!0)throw Error(`Expected successful Skills update`);let n=k(t,`output`);return{success:!0,...t.skill===void 0?{}:{skill:Si(t.skill)},...n===void 0?{}:{output:n}}}function Mi(e){if(typeof e!=`string`)throw Error(`Invalid thinking level`);return e}function Ni(e){let t=D(e);return{levels:M(Mi)(t.levels)}}function Pi(e){if(e!==`oauth`&&e!==`api_key`)throw Error(`Invalid auth type`);return e}function Fi(e){if(e!==`stored`&&e!==`runtime`&&e!==`environment`&&e!==`fallback`&&e!==`models_json_key`&&e!==`models_json_command`)throw Error(`Invalid auth status source`);return e}function Ii(e){let t=D(e),n=t.source===void 0?void 0:Fi(t.source);return{configured:j(t,`configured`),...P(`source`,n),...P(`label`,k(t,`label`))}}function Li(e){let t=D(e),n=t.loginFlow;if(n!==void 0&&n!==`interactive`)throw Error(`Invalid auth provider login flow`);return{id:O(t,`id`),name:O(t,`name`),authType:Pi(t.authType),status:Ii(t.status),...n===void 0?{}:{loginFlow:n}}}function Ri(e){let t=D(e);return{providers:M(Li)(t.providers)}}function zi(e){let t=D(e);return{flowId:O(t,`flowId`),providerId:O(t,`providerId`),providerName:O(t,`providerName`),status:Bi(t.status),progress:M(e=>{if(typeof e!=`string`)throw Error(`Expected progress item string`);return e})(t.progress),...P(`error`,k(t,`error`)),...P(`auth`,Vi(t.auth)),...P(`prompt`,Ui(t.prompt)),...P(`select`,Gi(t.select)),...P(`info`,Ki(t.info))}}function Bi(e){if(e!==`running`&&e!==`complete`&&e!==`error`&&e!==`cancelled`)throw Error(`Invalid OAuth flow status`);return e}function Vi(e){if(e===void 0)return;let t=D(e);return{url:O(t,`url`),...P(`instructions`,k(t,`instructions`)),...P(`deviceCode`,Hi(t.deviceCode))}}function Hi(e){if(e===void 0)return;let t=D(e);return{userCode:O(t,`userCode`),...P(`intervalSeconds`,N(t,`intervalSeconds`)),...P(`expiresInSeconds`,N(t,`expiresInSeconds`))}}function Ui(e){if(e===void 0)return;let t=D(e),n=O(t,`kind`);if(n!==`prompt`&&n!==`manual`)throw Error(`Invalid OAuth prompt kind`);let r=t.promptType===void 0?n===`manual`?`manual_code`:`text`:Wi(t.promptType);return{requestId:O(t,`requestId`),message:O(t,`message`),kind:n,promptType:r,...P(`placeholder`,k(t,`placeholder`)),...P(`allowEmpty`,as(t,`allowEmpty`))}}function Wi(e){if(e!==`text`&&e!==`secret`&&e!==`manual_code`)throw Error(`Invalid OAuth prompt type`);return e}function Gi(e){if(e===void 0)return;let t=D(e);return{requestId:O(t,`requestId`),message:O(t,`message`),options:M(Wo)(t.options)}}function Ki(e){if(e!==void 0)return M(e=>{let t=D(e);return{message:O(t,`message`),...P(`links`,t.links===void 0?void 0:M(qi)(t.links))}})(e)}function qi(e){let t=D(e);return{url:O(t,`url`),...P(`label`,k(t,`label`))}}function Ji(e){if(e===void 0)return{};let t=D(e);return{generation:{outputTokens:A(t,`outputTokens`),...P(`tokensPerSecond`,N(t,`tokensPerSecond`)),...P(`estimated`,as(t,`estimated`))}}}function Yi(e){if(e===void 0)return{};let t=D(e);return{contextUsage:{tokens:os(t,`tokens`),contextWindow:A(t,`contextWindow`),percent:os(t,`percent`)}}}function Xi(e){let t=D(e),n=O(t,`source`);if(n!==`extension`&&n!==`prompt`&&n!==`skill`&&n!==`builtin`)throw Error(`Invalid command source`);return{name:O(t,`name`),source:n,...P(`description`,k(t,`description`))}}function Zi(e){let t=D(e),n=O(t,`kind`);if(n!==`tracked`&&n!==`untracked`&&n!==`other`)throw Error(`Invalid file kind`);return{path:O(t,`path`),kind:n}}function Qi(e){let t=D(e);return{path:O(t,`path`),entries:M($i)(t.entries),scannedAt:O(t,`scannedAt`),truncated:j(t,`truncated`)}}function $i(e){let t=D(e),n=O(t,`type`);if(n!==`file`&&n!==`directory`&&n!==`symlink`)throw Error(`Invalid file tree entry type`);return{name:O(t,`name`),path:O(t,`path`),type:n,...P(`size`,N(t,`size`)),...P(`modifiedAt`,k(t,`modifiedAt`))}}function ea(e){let t=D(e),n=O(t,`encoding`);if(n!==`utf8`)throw Error(`Invalid file encoding`);return{path:O(t,`path`),...P(`language`,k(t,`language`)),...P(`mediaType`,ia(t.mediaType)),...P(`mimeType`,k(t,`mimeType`)),encoding:n,size:A(t,`size`),modifiedAt:O(t,`modifiedAt`),content:O(t,`content`),truncated:j(t,`truncated`),binary:j(t,`binary`)}}function ta(e){let t=D(e);return{path:O(t,`path`),size:A(t,`size`),modifiedAt:O(t,`modifiedAt`),created:j(t,`created`)}}function na(e){let t=D(e);return{path:O(t,`path`),existed:j(t,`existed`)}}function ra(e){let t=D(e);return{fromPath:O(t,`fromPath`),toPath:O(t,`toPath`),size:A(t,`size`),modifiedAt:O(t,`modifiedAt`)}}function ia(e){if(e!==void 0){if(e!==`image`)throw Error(`Invalid file media type`);return e}}function aa(e){let t=D(e);return{isGitRepo:j(t,`isGitRepo`),hash:O(t,`hash`),...P(`branch`,k(t,`branch`)),...P(`latestTag`,k(t,`latestTag`)),...P(`upstream`,k(t,`upstream`)),...P(`ahead`,N(t,`ahead`)),...P(`behind`,N(t,`behind`)),files:M(oa)(t.files)}}function oa(e){let t=D(e);return{path:O(t,`path`),...P(`oldPath`,k(t,`oldPath`)),index:sa(t.index),workingTree:sa(t.workingTree)}}function sa(e){switch(e){case`unmodified`:case`modified`:case`added`:case`deleted`:case`renamed`:case`copied`:case`untracked`:case`ignored`:case`conflicted`:return e;default:throw Error(`Invalid git file state`)}}function ca(e){let t=D(e);return{...P(`path`,k(t,`path`)),staged:j(t,`staged`),hash:O(t,`hash`),diff:O(t,`diff`),truncated:j(t,`truncated`)}}function la(e){let t=D(e);return{id:O(t,`id`),cwd:O(t,`cwd`),name:O(t,`name`),createdAt:O(t,`createdAt`),exited:j(t,`exited`),...P(`exitCode`,N(t,`exitCode`)),...P(`commandRunId`,k(t,`commandRunId`))}}function ua(e){let t=D(e);return{id:O(t,`id`),origin:O(t,`origin`),projectId:O(t,`projectId`),workspaceId:O(t,`workspaceId`),terminalId:O(t,`terminalId`),title:O(t,`title`),command:O(t,`command`),status:da(t.status),...P(`exitCode`,N(t,`exitCode`)),createdAt:O(t,`createdAt`),...P(`startedAt`,k(t,`startedAt`)),...P(`completedAt`,k(t,`completedAt`)),metadata:fa(t.metadata,`metadata`)}}function da(e){if(e!==`queued`&&e!==`running`&&e!==`succeeded`&&e!==`failed`)throw Error(`Invalid terminal command run status`);return e}function fa(e,t){let n=D(e);return Object.fromEntries(Object.entries(n).map(([e,n])=>{if(typeof n!=`string`)throw Error(`Expected string record field: ${t}.${e}`);return[e,n]}))}function pa(e){let t=D(e);return{cwd:O(t,`cwd`),hasSessionActivity:j(t,`hasSessionActivity`),hasTerminalActivity:j(t,`hasTerminalActivity`),updatedAt:O(t,`updatedAt`)}}function ma(e){let t=D(e);return{workspaces:M(pa)(t.workspaces),generatedAt:O(t,`generatedAt`)}}function ha(e){let t=La(e,`utility model settings response`),n=Object.keys(t).find(e=>!va(e));if(n!==void 0)throw Error(`Invalid utility model settings response field: ${n}`);if(t.contractVersion===1)return ga(t);if(t.contractVersion===2)return _a(t);throw Error(`Invalid utility model settings contract version`)}function ga(e){let t=k(e,`configError`);return{contractVersion:1,settings:ya(e.settings),models:M(Sa)(e.models),slots:wa(e.slots),valid:j(e,`valid`),...P(`configError`,t)}}function _a(e){let t=k(e,`configError`);return{contractVersion:2,settings:ba(e.settings),models:M(Ca)(e.models),slots:wa(e.slots),valid:j(e,`valid`),...P(`configError`,t)}}function va(e){return e===`contractVersion`||e===`settings`||e===`models`||e===`slots`||e===`valid`||e===`configError`}function ya(e){let t=La(e,`settings`),n=Object.keys(t).find(e=>!Ea(e));if(n!==void 0)throw Error(`Invalid utility model settings field: settings.${n}`);return{...P(`lightweight`,t.lightweight===void 0?void 0:ja(t.lightweight,`settings.lightweight`)),...P(`context`,t.context===void 0?void 0:ja(t.context,`settings.context`))}}function ba(e){let t=La(e,`settings`),n=Object.keys(t).find(e=>!Ea(e));if(n!==void 0)throw Error(`Invalid utility model settings field: settings.${n}`);return{...P(`lightweight`,t.lightweight===void 0?void 0:xa(t.lightweight,`settings.lightweight`)),...P(`context`,t.context===void 0?void 0:xa(t.context,`settings.context`))}}function xa(e,t){let n=La(e,t),r=Object.keys(n).find(e=>e!==`provider`&&e!==`id`&&e!==`thinkingLevel`);if(r!==void 0)throw Error(`Invalid utility model binding field: ${t}.${r}`);let i=Hr(n,`provider`),a=Hr(n,`id`),o=k(n,`thinkingLevel`);if(o===void 0)return{provider:i,id:a};if(!Cn(o))throw Error(`Invalid utility model thinking level: ${t}.thinkingLevel`);return{provider:i,id:a,thinkingLevel:o}}function Sa(e){let t=La(e,`models`),n=Object.keys(t).find(e=>e!==`model`&&e!==`name`);if(n!==void 0)throw Error(`Invalid utility model option field: models.${n}`);return{model:ja(t.model,`models.model`),...P(`name`,k(t,`name`))}}function Ca(e){let t=La(e,`models`),n=Object.keys(t).find(e=>e!==`model`&&e!==`name`&&e!==`thinkingLevels`);if(n!==void 0)throw Error(`Invalid utility model option field: models.${n}`);let r=Ln(t.thinkingLevels,`models.thinkingLevels`).map(e=>{if(!Cn(e))throw Error(`Invalid utility model thinking levels: models.thinkingLevels`);return e});return{model:ja(t.model,`models.model`),...P(`name`,k(t,`name`)),thinkingLevels:r}}function wa(e){let t=Da(e,`slots`);return{lightweight:Ta(t.lightweight,`slots.lightweight`),context:Ta(t.context,`slots.context`)}}function Ta(e,t){let n=La(e,t),r=Object.keys(n).find(e=>e!==`valid`&&e!==`reason`);if(r!==void 0)throw Error(`Invalid utility model validation field: ${t}.${r}`);return{valid:j(n,`valid`),...P(`reason`,k(n,`reason`))}}function Ea(e){return Rt.some(t=>t===e)}function Da(e,t){let n=La(e,t),r=Object.keys(n).find(e=>!Ea(e));if(r!==void 0)throw Error(`Invalid utility model ${t} field: unknown slot ${r}`);let i=Rt.find(e=>n[e]===void 0);if(i!==void 0)throw Error(`Invalid utility model ${t} field: missing slot ${i}`);return n}function Oa(e){let t=D(e);if(t.contractVersion!==1)throw Error(`Invalid model-tier settings contract version`);let n=t.ladder===void 0?void 0:ka(t.ladder),r=k(t,`configError`);return{contractVersion:1,...P(`ladder`,n),models:M(Ma)(t.models),rows:Na(t.rows),valid:j(t,`valid`),...P(`configError`,r)}}function ka(e){let t=Ia(e,`ladder`);return{economy:Aa(t.economy,`ladder.economy`),fast:Aa(t.fast,`ladder.fast`),standard:Aa(t.standard,`ladder.standard`),advanced:Aa(t.advanced,`ladder.advanced`),capable:Aa(t.capable,`ladder.capable`),frontier:Aa(t.frontier,`ladder.frontier`)}}function Aa(e,t){let n=La(e,t),r=Object.keys(n).find(e=>e!==`model`&&e!==`thinkingLevel`);if(r!==void 0)throw Error(`Invalid model-tier entry field: ${t}.${r}`);return{model:ja(n.model,`${t}.model`),thinkingLevel:Hr(n,`thinkingLevel`)}}function ja(e,t){let n=La(e,t),r=Object.keys(n).find(e=>e!==`provider`&&e!==`id`);if(r!==void 0)throw Error(`Invalid model reference field: ${t}.${r}`);return{provider:Hr(n,`provider`),id:Hr(n,`id`)}}function Ma(e){let t=La(e,`models`);return{model:ja(t.model,`models.model`),...P(`name`,k(t,`name`)),thinkingLevels:Ln(t.thinkingLevels,`models.thinkingLevels`)}}function Na(e){let t=Ia(e,`rows`);return{economy:Pa(t.economy,`rows.economy`),fast:Pa(t.fast,`rows.fast`),standard:Pa(t.standard,`rows.standard`),advanced:Pa(t.advanced,`rows.advanced`),capable:Pa(t.capable,`rows.capable`),frontier:Pa(t.frontier,`rows.frontier`)}}function Pa(e,t){let n=La(e,t),r=Object.keys(n).find(e=>e!==`valid`&&e!==`reason`);if(r!==void 0)throw Error(`Invalid model-tier row field: ${t}.${r}`);return{valid:j(n,`valid`),...P(`reason`,k(n,`reason`))}}function Fa(e){return Lt.some(t=>t===e)}function Ia(e,t){let n=La(e,t),r=Object.keys(n).find(e=>!Fa(e));if(r!==void 0)throw Error(`Invalid model-tier ${t} field: unknown tier ${r}`);let i=Lt.find(e=>n[e]===void 0);if(i!==void 0)throw Error(`Invalid model-tier ${t} field: missing tier ${i}`);return n}function La(e,t){if(!On(e)||Array.isArray(e))throw Error(`Expected object field: ${t}`);return e}function Ra(e){let t=D(e);return{path:O(t,`path`),exists:j(t,`exists`),config:Wa(t.config),effectiveConfig:Wa(t.effectiveConfig),envOverrides:to(t.envOverrides)}}function za(e){let t=yr(e,`speech input settings response`);if(xr(t,[`contractVersion`,`revision`,`settings`,`credential`],`speech input settings response`),t.contractVersion!==1)throw Error(`Invalid speech input settings contract version`);let n=O(t,`revision`);if(!hn(n))throw Error(`Invalid speech input settings revision`);return{contractVersion:1,revision:n,settings:Ba(t.settings),credential:Ua(t.credential)}}function Ba(e){let t=La(e,`speech input settings`);xr(t,[`provider`,`language`,`cloud`],`speech input settings`);let n=t.provider;if(n!==`auto`&&n!==`browser`&&n!==`cloud`)throw Error(`Invalid speech input settings provider`);let r=k(t,`language`);if(r!==void 0&&gn(r)!==r)throw Error(`Invalid speech input settings language`);return{provider:n,...P(`language`,r),cloud:Va(t.cloud)}}function Va(e){let t=La(e,`speech input cloud settings`);xr(t,[`baseUrl`,`model`],`speech input cloud settings`);let n=Ho(t,`baseUrl`);if(!Ha(n))throw Error(`Invalid speech input cloud base URL`);return{baseUrl:n,model:Ho(t,`model`)}}function Ha(e){try{let t=new URL(e);return t.protocol===`https:`&&t.username===``&&t.password===``&&t.search===``&&t.hash===``}catch{return!1}}function Ua(e){let t=La(e,`speech input credential status`);xr(t,[`configured`,`source`,`resolution`],`speech input credential status`);let n=j(t,`configured`),r=t.source,i=t.resolution;if(typeof i!=`string`)throw Error(`Invalid speech input credential status`);if(!n){if(r!==void 0||i!==`missing`)throw Error(`Invalid speech input credential status`);return{configured:!1,resolution:`missing`}}if(r!==`literal`&&r!==`environment`&&r!==`command`)throw Error(`Invalid speech input credential status`);if(r===`command`){if(i!==`unchecked`)throw Error(`Invalid speech input credential status`)}else if(r===`literal`){if(i!==`resolved`)throw Error(`Invalid speech input credential status`)}else if(i!==`resolved`&&i!==`unresolved`)throw Error(`Invalid speech input credential status`);return{configured:!0,source:r,resolution:i}}function Wa(e){let t=D(e);return{...P(`host`,k(t,`host`)),...P(`port`,N(t,`port`)),...P(`allowedHosts`,qa(t.allowedHosts)),...P(`shortcuts`,$a(t.shortcuts)),...P(`plugins`,eo(t.plugins)),...P(`pathAccess`,Ja(t.pathAccess)),...P(`uploads`,Xa(t.uploads)),...P(`maxUploadBytes`,N(t,`maxUploadBytes`)),...P(`agent`,Ga(t.agent)),...P(`tts`,Ka(t.tts)),...P(`spawnSessions`,as(t,`spawnSessions`)),...P(`subsessions`,as(t,`subsessions`))}}function Ga(e){if(e!==void 0){if(!On(e)||Array.isArray(e))throw Error(`Invalid PI WEBUI agent field`);return{...P(`command`,k(e,`command`)),...P(`dir`,k(e,`dir`))}}}function Ka(e){if(e===void 0)return;if(!On(e)||Array.isArray(e))throw Error(`Invalid PI WEBUI tts field`);xr(e,[`voice`,`rate`],`PI WEBUI tts`);let t=k(e,`voice`)?.trim();if(t===``)throw Error(`Invalid PI WEBUI tts voice field`);let n=N(e,`rate`);if(n!==void 0&&(!Number.isInteger(n)||n<-100||n>100))throw Error(`Invalid PI WEBUI tts rate field`);return{...P(`voice`,t),...P(`rate`,n)}}function qa(e){if(e!==void 0){if(e===!0)return!0;if(Za(e))return e;throw Error(`Invalid PI WEBUI allowedHosts field`)}}function Ja(e){if(e===void 0)return;if(!On(e))throw Error(`Invalid PI WEBUI pathAccess field`);let t=e.allowedPaths;return{...P(`allowedPaths`,Ya(t,`pathAccess.allowedPaths`))}}function Ya(e,t){if(e!==void 0){if(Qa(e))return e;throw Error(`Invalid PI WEBUI ${t} field`)}}function Xa(e){if(e!==void 0){if(!On(e)||Array.isArray(e))throw Error(`Invalid PI WEBUI uploads field`);return{...P(`defaultFolder`,k(e,`defaultFolder`))}}}function Za(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`)}function Qa(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`&&e!==``)}function $a(e){if(e!==void 0){if(!On(e)||Array.isArray(e))throw Error(`Invalid PI WEBUI shortcuts field`);return Object.fromEntries(Object.entries(e).map(([e,t])=>{if(t!==null&&(typeof t!=`string`||t===``))throw Error(`Invalid PI WEBUI shortcut field`);return[e,t]}))}}function eo(e){if(e!==void 0){if(!On(e)||Array.isArray(e))throw Error(`Invalid PI WEBUI plugins field`);return Object.fromEntries(Object.entries(e).map(([e,t])=>{if(!On(t)||Array.isArray(t))throw Error(`Invalid PI WEBUI plugin config field`);let n=t.enabled;if(n!==void 0&&typeof n!=`boolean`)throw Error(`Invalid PI WEBUI plugin enabled field`);let r=t.settings;if(r!==void 0&&(!On(r)||Array.isArray(r)))throw Error(`Invalid PI WEBUI plugin settings field`);return[e,t]}))}}function to(e){let t=D(e);return{host:j(t,`host`),port:j(t,`port`),allowedHosts:j(t,`allowedHosts`),spawnSessions:j(t,`spawnSessions`),subsessions:j(t,`subsessions`),agentCommand:as(t,`agentCommand`)??!1,agentDir:as(t,`agentDir`)??!1,...no(t),agentSessionDir:as(t,`agentSessionDir`)??!1}}function no(e){let t=e.agentDirSource;if(t===void 0)return{};if(t!==`pi-webui`&&t!==`pi-compatibility`)throw Error(`Invalid PI WEBUI agentDirSource field`);return{agentDirSource:t}}function ro(e){let t=D(e);return{packages:M(ao)(t.packages)}}function io(e){let t=D(e),n=k(t,`source`),r=t.scope===void 0?void 0:oo(t.scope),i=bo(t.removed,`removed`);return{action:so(t.action),...P(`source`,n),...P(`scope`,r),...P(`removed`,i),packages:M(ao)(t.packages)}}function ao(e){let t=D(e);return{source:O(t,`source`),scope:oo(t.scope),filtered:j(t,`filtered`),...P(`installedPath`,k(t,`installedPath`))}}function oo(e){if(e!==`user`&&e!==`project`)throw Error(`Invalid Pi package scope`);return e}function so(e){if(e!==`install`&&e!==`remove`&&e!==`update`)throw Error(`Invalid Pi package mutation action`);return e}function co(e){let t=D(e);return{packages:M(lo)(t.packages),totals:po(t.totals),diagnostics:M(go)(t.diagnostics)}}function lo(e){let t=D(e);return{source:O(t,`source`),scope:uo(t.scope),filtered:j(t,`filtered`),disabled:j(t,`disabled`),...P(`installedPath`,k(t,`installedPath`)),...P(`packageName`,k(t,`packageName`)),...P(`version`,k(t,`version`)),...P(`configuredVersion`,k(t,`configuredVersion`)),counts:po(t.counts),resources:M(mo)(t.resources),status:fo(t.status)}}function uo(e){if(e!==`global`&&e!==`project`)throw Error(`Invalid Pi package plugin scope`);return e}function fo(e){if(e!==`loaded`&&e!==`installed`&&e!==`missing`&&e!==`disabled`)throw Error(`Invalid Pi package plugin status`);return e}function po(e){let t=D(e);return{extensions:A(t,`extensions`),skills:A(t,`skills`),prompts:A(t,`prompts`),themes:A(t,`themes`)}}function mo(e){let t=D(e);return{kind:ho(t.kind),name:O(t,`name`),path:O(t,`path`),relativePath:O(t,`relativePath`)}}function ho(e){if(e!==`extension`&&e!==`skill`&&e!==`prompt`&&e!==`theme`)throw Error(`Invalid Pi package plugin resource kind`);return e}function go(e){let t=D(e),n=t.type;if(n!==`warning`&&n!==`error`)throw Error(`Invalid Pi package plugin diagnostic type`);return{type:n,message:O(t,`message`),...P(`source`,k(t,`source`)),...P(`path`,k(t,`path`))}}function _o(e){let t=D(e);return{plugins:M(vo)(t.plugins)}}function vo(e){let t=D(e);return{id:O(t,`id`),module:O(t,`module`),source:O(t,`source`),scope:yo(t.scope),machineSpecific:bo(t.machineSpecific,`machineSpecific`)??!1,enabled:j(t,`enabled`)}}function yo(e){if(e!==`bundled`&&e!==`local`&&e!==`user`&&e!==`project`)throw Error(`Invalid PI WEBUI plugin scope`);return e}function bo(e,t){if(e!==void 0){if(typeof e!=`boolean`)throw Error(`Expected optional boolean field: ${t}`);return e}}function xo(e){let t=D(e);return{packageName:O(t,`packageName`),generatedAt:O(t,`generatedAt`),components:Co(t.components),release:Oo(t.release),commands:ko(t.commands),messages:M(Ao)(t.messages)}}function So(e){let t=D(e);return{packageName:O(t,`packageName`),generatedAt:O(t,`generatedAt`),components:wo(t.components),capabilities:Mo(t.capabilities)}}function Co(e){let t=D(e);return{web:Eo(t.web),sessiond:Eo(t.sessiond)}}function wo(e){let t=D(e);return{web:To(t.web),sessiond:To(t.sessiond)}}function To(e){let t=D(e),n=jo(t.component),r=t.activeAgentProfile,i=r===void 0?void 0:rn(r);if(r!==void 0&&(n!==`sessiond`||i===void 0))throw Error(`Invalid active agent profile descriptor`);return{component:n,label:O(t,`label`),...P(`runtimeVersion`,k(t,`runtimeVersion`)),available:j(t,`available`),capabilities:Mo(t.capabilities),...P(`activeAgentProfile`,i),...P(`error`,k(t,`error`))}}function Eo(e){let t=D(e);return{component:jo(t.component),label:O(t,`label`),...P(`runtimeVersion`,k(t,`runtimeVersion`)),...P(`installedVersion`,k(t,`installedVersion`)),stale:j(t,`stale`),available:j(t,`available`),...P(`installation`,Do(t.installation)),...P(`error`,k(t,`error`))}}function Do(e){if(e===void 0)return;let t=D(e),n=O(t,`kind`);if(n!==`pi-package`&&n!==`npm-global`&&n!==`local`&&n!==`docker`&&n!==`unknown`)throw Error(`Invalid PI WEBUI installation kind`);let r=t.scope;if(r!==void 0&&r!==`user`&&r!==`project`)throw Error(`Invalid PI WEBUI installation scope`);let i=t.dockerMode;if(i!==void 0&&i!==`runtime`&&i!==`dev`)throw Error(`Invalid PI WEBUI Docker mode`);return{kind:n,...P(`path`,k(t,`path`)),...P(`source`,k(t,`source`)),...r===void 0?{}:{scope:r},...P(`npmRoot`,k(t,`npmRoot`)),...i===void 0?{}:{dockerMode:i}}}function Oo(e){let t=D(e);return{packageName:O(t,`packageName`),...P(`latestVersion`,k(t,`latestVersion`)),updateAvailable:j(t,`updateAvailable`),...P(`checkedAt`,k(t,`checkedAt`)),...t.skipped===!0?{skipped:!0}:{},...P(`error`,k(t,`error`))}}function ko(e){let t=D(e);return{...P(`update`,k(t,`update`)),...P(`restart`,k(t,`restart`)),...P(`restartWeb`,k(t,`restartWeb`)),...P(`restartSessiond`,k(t,`restartSessiond`)),...P(`status`,k(t,`status`))}}function Ao(e){let t=D(e);return{id:O(t,`id`),severity:No(t.severity),title:O(t,`title`),body:O(t,`body`),...P(`command`,k(t,`command`))}}function jo(e){if(e!==`web`&&e!==`sessiond`)throw Error(`Invalid PI WEBUI service component`);return e}function Mo(e){let t=pn(e);if(t===void 0)throw Error(`Invalid PI WEBUI capabilities`);return t}function No(e){if(e!==`info`&&e!==`warning`&&e!==`error`)throw Error(`Invalid PI WEBUI status severity`);return e}function Po(e){let t=D(e),n=O(t,`type`);if(n===`unsupported`)return{type:n,message:O(t,`message`)};if(n===`select`)return{type:n,requestId:O(t,`requestId`),title:O(t,`title`),options:M(Wo)(t.options)};if(n===`tree`)return{type:n,tree:Fo(t.tree)};if(n===`done`)return{type:n,...P(`message`,k(t,`message`)),...Go(t.session),...P(`promptDraft`,k(t,`promptDraft`))};throw Error(`Invalid command result type`)}function Fo(e){let t=D(e),n=M(Io)(t.nodes),r=new Set(n.map(e=>e.id));if(r.size!==n.length)throw Error(`Duplicate session tree node id`);let i=Vo(t,`activeLeafId`);if(i!==null&&!r.has(i))throw Error(`Invalid session tree activeLeafId`);return{nodes:n,activeLeafId:i,activePathIds:Uo(t.activePathIds,`activePathIds`)}}function Io(e){let t=D(e);return{id:Ho(t,`id`),parentId:Vo(t,`parentId`),kind:Lo(t.kind),summary:O(t,`summary`),...P(`timestamp`,k(t,`timestamp`)),...P(`label`,k(t,`label`))}}function Lo(e){switch(e){case`user`:case`assistant`:case`tool-result`:case`bash`:case`custom-message`:case`compaction`:case`branch-summary`:case`model-change`:case`thinking-level-change`:case`session-info`:case`label`:case`custom`:case`other`:return e;default:throw Error(`Invalid session tree node kind`)}}function Ro(e){let t=D(e),n=j(t,`cancelled`);if(Object.hasOwn(t,`summaryEntry`))throw Error(`Invalid session tree navigation result field: summaryEntry`);if(n){Bo(t,`editorText`,`session tree cancellation result`);let e=t.aborted;if(e!==void 0&&typeof e!=`boolean`)throw Error(`Expected optional boolean field: aborted`);return{cancelled:n,...e===void 0?{}:{aborted:e}}}return Bo(t,`aborted`,`session tree navigation result`),{cancelled:n,...P(`editorText`,k(t,`editorText`))}}function zo(e){let t=D(e);return j(t,`cancelled`)?(Bo(t,`session`,`session fork cancellation result`),{cancelled:!0}):{cancelled:!1,session:tr(t.session)}}function Bo(e,t,n){if(Object.hasOwn(e,t))throw Error(`Invalid ${n} field: ${t}`)}function Vo(e,t){let n=e[t];if(n!==null&&typeof n!=`string`)throw Error(`Expected string or null field: ${t}`);if(typeof n==`string`&&n.trim()===``)throw Error(`Expected non-blank string or null field: ${t}`);return n}function Ho(e,t){let n=O(e,t);if(n.trim()===``)throw Error(`Expected non-blank string field: ${t}`);return n}function Uo(e,t){let n=Ln(e,t);if(n.some(e=>e.trim()===``))throw Error(`Expected non-blank string array field: ${t}`);return n}function Wo(e){let t=D(e);return{value:O(t,`value`),label:O(t,`label`),...P(`description`,k(t,`description`))}}function Go(e){return e===void 0?{}:{session:tr(e)}}function Ko(e){if(D(e).accepted!==!0)throw Error(`Expected accepted response`);return{accepted:!0}}function qo(e){let t=D(e);return M(Jo)(t.attachments)}function Jo(e){let t=D(e);return{path:O(t,`path`),mimeType:O(t,`mimeType`),size:A(t,`size`)}}function Yo(e){if(D(e).closed!==!0)throw Error(`Expected closed response`);return{closed:!0}}function Xo(e){if(typeof e!=`string`)throw Error(`Expected string value`);return e}function Zo(e){let t=D(e);return{closedProjectIds:M(Xo)(t.closedProjectIds)}}function Qo(e){if(D(e).aborted!==!0)throw Error(`Expected aborted response`);return{aborted:!0}}function $o(e){if(D(e).stopped!==!0)throw Error(`Expected stopped response`);return{stopped:!0}}function es(e){let t=D(e);if(t.archived!==!0)throw Error(`Expected archived response`);let n=t.sessionIds===void 0?void 0:Ln(t.sessionIds,`sessionIds`),r=N(t,`archivedCount`),i=N(t,`skippedAlreadyArchivedCount`);return{archived:!0,...n===void 0?{}:{sessionIds:n},...r===void 0?{}:{archivedCount:r},...i===void 0?{}:{skippedAlreadyArchivedCount:i}}}function ts(e){if(D(e).restored!==!0)throw Error(`Expected restored response`);return{restored:!0}}function ns(e){if(D(e).deleted!==!0)throw Error(`Expected deleted response`);return{deleted:!0}}function rs(e){if(D(e).detached!==!0)throw Error(`Expected detached response`);return{detached:!0}}function is(e){if(D(e).reloaded!==!0)throw Error(`Expected reloaded response`);return{reloaded:!0}}function as(e,t){let n=e[t];if(n!==void 0){if(typeof n!=`boolean`)throw Error(`Invalid PI WEBUI ${t} field`);return n}}function N(e,t){let n=e[t];if(n!==void 0){if(typeof n!=`number`)throw Error(`Expected optional number field: ${t}`);return n}}function os(e,t){let n=e[t];if(n===null)return null;if(typeof n!=`number`)throw Error(`Expected number|null field: ${t}`);return n}function P(e,t){return t===void 0?{}:{[e]:t}}function ss(e){let t=D(e),n=D(t.memory),r=D(t.network);return{generatedAt:O(t,`generatedAt`),memory:{totalBytes:A(n,`totalBytes`),usedBytes:A(n,`usedBytes`),freeBytes:A(n,`freeBytes`),usagePercent:A(n,`usagePercent`)},network:us(r)}}function cs(e){let t=D(e),n=D(t.os),r=D(t.cpu),i=D(t.memory),a=D(t.network),o=t.gpu,s;if(o!=null){let e=D(o),t={name:O(e,`name`)},n=k(e,`driverVersion`);n!==void 0&&(t.driverVersion=n);let r=N(e,`memoryTotalBytes`);r!==void 0&&(t.memoryTotalBytes=r);let i=N(e,`memoryUsedBytes`);i!==void 0&&(t.memoryUsedBytes=i);let a=N(e,`utilizationPercent`);a!==void 0&&(t.utilizationPercent=a);let c=N(e,`temperatureCelsius`);c!==void 0&&(t.temperatureCelsius=c),s=t}let c={generatedAt:O(t,`generatedAt`),os:{platform:O(n,`platform`),release:O(n,`release`),arch:O(n,`arch`),uptimeSeconds:A(n,`uptimeSeconds`)},cpu:{model:O(r,`model`),cores:A(r,`cores`),usagePercent:A(r,`usagePercent`)},memory:{totalBytes:A(i,`totalBytes`),usedBytes:A(i,`usedBytes`),freeBytes:A(i,`freeBytes`),usagePercent:A(i,`usagePercent`)},network:ls(a)};s!==void 0&&(c.gpu=s);let l=k(t,`piVersion`);l!==void 0&&(c.piVersion=l);let u=k(t,`piWebUiVersion`);return u!==void 0&&(c.piWebUiVersion=u),c}function ls(e){let t={hostname:O(e,`hostname`),localIpv4Addresses:Ln(e.localIpv4Addresses,`localIpv4Addresses`),...us(e)},n=k(e,`publicIpv4`);n!==void 0&&(t.publicIpv4=n);let r=k(e,`publicIpv6`);return r!==void 0&&(t.publicIpv6=r),t}function us(e){let t={},n=N(e,`downloadSpeedBytesPerSecond`);n!==void 0&&(t.downloadSpeedBytesPerSecond=n);let r=N(e,`uploadSpeedBytesPerSecond`);return r!==void 0&&(t.uploadSpeedBytesPerSecond=r),t}function ds(e){let t=yr(e,`project usage count response`);return xr(t,[`sessionCount`],`project usage count response`),{sessionCount:Ur(t,`sessionCount`)}}function fs(e){let t=D(e);return{input:A(t,`input`),output:A(t,`output`),cacheRead:A(t,`cacheRead`),cacheWrite:A(t,`cacheWrite`),cost:A(t,`cost`),sessionCount:A(t,`sessionCount`)}}function ps(e){let t=D(e),n=D(t.buckets);return{projectPath:O(t,`projectPath`),buckets:{live:fs(n.live),retired:fs(n.retired),archived:fs(n.archived)},total:fs(t.total),generatedAt:O(t,`generatedAt`)}}function ms(e){return typeof e==`string`?e:e.id}function hs(e){return typeof e==`string`?void 0:e.cwd}function gs(e,t,n,r){let i=new URLSearchParams;r?.path!==void 0&&i.set(`path`,r.path),r?.staged===!0&&i.set(`staged`,`true`);let a=i.toString();return`api/machines/${encodeURIComponent(e)}/projects/${encodeURIComponent(t)}/workspaces/${encodeURIComponent(n)}/git/diff${a?`?${a}`:``}`}function _s(e,t,n=`local`){let r=new URLSearchParams,i=hs(e);i!==void 0&&i!==``&&r.set(`cwd`,i),t?.limit!==void 0&&r.set(`limit`,String(t.limit)),t?.before!==void 0&&r.set(`before`,String(t.before));let a=r.toString();return`api/machines/${encodeURIComponent(n)}/sessions/${encodeURIComponent(ms(e))}/messages${a===``?``:`?${a}`}`}function vs(e,t=`local`){let n=new URLSearchParams,r=hs(e);r!==void 0&&r!==``&&n.set(`cwd`,r);let i=n.toString();return`api/machines/${encodeURIComponent(t)}/sessions/${encodeURIComponent(ms(e))}/export${i===``?``:`?${i}`}`}function ys(e,t,n,r){let i=new URLSearchParams({path:n});return r?.createDirs===!1&&i.set(`createDirs`,`false`),r?.overwrite===!1&&i.set(`overwrite`,`false`),Wt(`${`api/machines/${encodeURIComponent(r?.machineId??`local`)}`}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?${i.toString()}`)}function bs(e,t,n,r){let i=new URLSearchParams;return i.set(`path`,n),r?.modifiedAt!==void 0&&i.set(`v`,r.modifiedAt),Wt(`${`api/machines/${encodeURIComponent(r?.machineId??`local`)}`}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file/preview?${i.toString()}`)}var F=(e=`local`)=>`api/machines/${encodeURIComponent(e)}`,xs=e=>e===void 0?void 0:{signal:e};function Ss(e){return typeof e==`string`?e:e.id}function Cs(e){return typeof e==`string`?void 0:e.cwd}function ws(e,t=`local`){return`${F(t)}/sessions/${encodeURIComponent(Ss(e))}`}function I(e,t,n=`local`){return`${ws(e,n)}/${t}`}function Ts(e,t,n=`local`){return`${I(e,t,n)}${Ds(e)}`}function Es(e,t=`local`){return`${ws(e,t)}${Ds(e)}`}function Ds(e){let t=Cs(e);return t===void 0||t===``?``:`?${new URLSearchParams({cwd:t}).toString()}`}function L(e,t={}){let n=Cs(e);return JSON.stringify(n===void 0||n===``?t:{cwd:n,...t})}function Os(e){return JSON.stringify({sessions:e.map(ks)})}function ks(e){let t=Ss(e),n=Cs(e);return n===void 0||n===``?{id:t}:{id:t,cwd:n}}function As(e){return e===`local`?`api/pi-webui/status`:`${F(e)}/pi-webui/status`}var js={piWebUiStatus:(e=`local`)=>T(As(e),xo),checkForUpdates:(e=`local`)=>T(`${As(e)}?refresh=1`,xo,{cache:`no-store`}),piWebUiRuntime:()=>T(`api/pi-webui/runtime`,So),systemInfo:(e=`local`)=>T(`${F(e)}/pi-webui/system-info`,cs),systemMetrics:(e=`local`)=>T(`${F(e)}/pi-webui/system-metrics`,ss,{cache:`no-store`})},Ms={status:()=>T(`api/tts`,kn,{cache:`no-store`}),speak:(e,t)=>T(`api/tts/speak`,Mn,{method:`POST`,body:JSON.stringify(e),...t===void 0?{}:{signal:t}}),stop:e=>T(`api/tts/stop`,Nn,{method:`POST`,body:JSON.stringify({runId:e})})},Ns={settings:()=>T(`api/speech-input/settings`,za,{cache:`no-store`}),saveSettings:e=>T(`api/speech-input/settings`,za,{method:`PUT`,body:JSON.stringify(e)}),transcribe:(e,t,n)=>T(`api/speech-input/transcribe`,Pn,{method:`POST`,body:e,headers:{"content-type":t},...n===void 0?{}:{signal:n}})},Ps={machines:()=>T(`api/machines`,Wn),addMachine:e=>T(`api/machines`,Gn,{method:`POST`,body:JSON.stringify(e)}),deleteMachine:e=>T(`api/machines/${encodeURIComponent(e)}`,e=>e,{method:`DELETE`}),health:e=>T(`api/machines/${encodeURIComponent(e)}/health`,Kn),runtime:(e,t=!1)=>T(`api/machines/${encodeURIComponent(e)}/runtime${t?`?refresh=1`:``}`,qn,t?{cache:`no-store`}:{})};function Fs(e,t=`local`){let n=new URLSearchParams({projectPath:e});return`${F(t)}/agent-memory/snapshot?${n.toString()}`}var Is={snapshot:(e,t=`local`)=>T(Fs(e,t),Rn,{cache:`no-store`})};function Ls(e,t=`local`){let n=new URLSearchParams({projectPath:e});return`${F(t)}/agent-skills/snapshot?${n.toString()}`}var Rs={snapshot:(e,t=`local`)=>T(Ls(e,t),Bn,{cache:`no-store`})};function zs(e){return e===void 0?`api/config`:`${F(e)}/config`}function Bs(e){return e===void 0?`api/plugins`:`${F(e)}/plugins`}var Vs={config:e=>T(zs(e),Ra),saveConfig:(e,t)=>T(zs(t),Ra,{method:`PUT`,body:JSON.stringify({config:e})})},Hs={plugins:e=>T(Bs(e),_o)};function Us(e=`local`){return`${F(e)}/models-config`}var Ws={config:(e=`local`)=>T(Us(e),li),save:(e,t=`local`)=>T(Us(t),_i,{method:`PUT`,body:JSON.stringify(e)}),test:(e,t=`local`)=>T(`${Us(t)}/test`,bi,{method:`POST`,body:JSON.stringify(e)}),discover:(e,t=`local`)=>T(`${Us(t)}/discover`,vi,{method:`POST`,body:JSON.stringify(e)})};function Gs(e=`local`){return`${F(e)}/model-tiers`}var Ks={settings:(e=`local`)=>T(Gs(e),Oa),save:(e,t=`local`)=>T(Gs(t),Oa,{method:`PUT`,body:JSON.stringify({ladder:e})})};function qs(e=`local`){return`${F(e)}/utility-models`}function Js(e,t){if(t===2)return e;let n={};for(let t of Rt){if(!Object.prototype.hasOwnProperty.call(e,t))continue;let r=e[t];r===null?n[t]=null:r!==void 0&&(n[t]={provider:r.provider,id:r.id})}return n}var Ys={settings:(e=`local`)=>T(qs(e),ha),save:(e,t,n=`local`)=>T(qs(n),ha,{method:`PUT`,body:JSON.stringify({settings:Js(e,t)})})};function Xs(e=`local`){return`${F(e)}/skills`}function Zs(e,t=`local`){return`${Xs(t)}?${new URLSearchParams({cwd:e}).toString()}`}var Qs={list:(e,t=`local`)=>T(Zs(e,t),xi),toggle:(e,t=`local`)=>T(Xs(t),Ti,{method:`PATCH`,body:JSON.stringify(e)}),search:(e,t=`local`)=>T(`${Xs(t)}/search`,Ei,{method:`POST`,body:JSON.stringify(e)}),install:(e,t=`local`)=>T(`${Xs(t)}/install`,Ti,{method:`POST`,body:JSON.stringify(e)}),check:(e,t=`local`)=>T(`${Xs(t)}/check`,Oi,{method:`POST`,body:JSON.stringify(e)}),update:(e,t=`local`)=>T(`${Xs(t)}/update`,ji,{method:`POST`,body:JSON.stringify(e)})};function $s(e=``,t){let n=t===void 0?`api/pi-packages`:`${F(t)}/pi-packages`;return e===``?n:`${n}/${e}`}var ec={packages:e=>T($s(``,e),ro),install:(e,t)=>{let n={source:e};return T($s(`install`,t),io,{method:`POST`,body:JSON.stringify(n)})},remove:(e,t,n)=>{let r=t===void 0?{source:e}:{source:e,scope:t};return T($s(`remove`,n),io,{method:`POST`,body:JSON.stringify(r)})},update:(e,t)=>{let n=e===void 0?void 0:{source:e};return T($s(`update`,t),io,{method:`POST`,...n===void 0?{}:{body:JSON.stringify(n)}})}};function tc(e=`local`){return`${F(e)}/package-plugins`}function nc(e,t=`local`){return`${tc(t)}?${new URLSearchParams({cwd:e}).toString()}`}var rc={list:(e,t=`local`)=>T(nc(e,t),co),mutate:(e,t=`local`)=>T(tc(t),co,{method:`POST`,body:JSON.stringify(e)})},ic={workspaceActivity:(e=`local`)=>T(`${F(e)}/activity`,ma)},ac={projects:(e=`local`)=>T(`${F(e)}/projects`,M(Xn)),addProject:(e,t,n,r=`local`)=>T(`${F(r)}/projects`,Xn,{method:`POST`,body:JSON.stringify({path:e,name:t,create:n})}),closeProject:(e,t=`local`)=>T(`${F(t)}/projects/${encodeURIComponent(e)}`,Yo,{method:`DELETE`}),closeProjectTree:(e,t=`local`)=>T(`${F(t)}/projects/${encodeURIComponent(e)}/close-tree`,Zo,{method:`POST`}),pinProject:(e,t=`local`)=>T(`${F(t)}/projects/${encodeURIComponent(e)}/pin`,M(Xn),{method:`POST`}),unpinProject:(e,t=`local`)=>T(`${F(t)}/projects/${encodeURIComponent(e)}/unpin`,M(Xn),{method:`POST`}),projectDirectories:(e,t=`local`)=>T(`${F(t)}/project-directories?q=${encodeURIComponent(e)}`,M(Zi)),projectUsageCount:(e,t=`local`)=>T(`${F(t)}/sessions/project-usage/count`,ds,{method:`POST`,body:JSON.stringify(e)}),projectUsage:(e,t=`local`)=>T(`${F(t)}/sessions/project-usage`,ps,{method:`POST`,body:JSON.stringify(e)})},oc={recentProjects:(e=`local`)=>T(`${F(e)}/recent-projects`,Qn),recordRecentProject:(e,t=`local`)=>T(`${F(t)}/projects/${encodeURIComponent(e)}/recent`,Qn,{method:`POST`}),removeRecentProject:(e,t=`local`)=>T(`${F(t)}/recent-projects/${encodeURIComponent(e)}`,Qn,{method:`DELETE`})},sc={workspaces:(e,t=`local`,n)=>T(`${F(t)}/projects/${encodeURIComponent(e)}/workspaces`,M($n),xs(n)),deleteWorkspace:(e,t,n=`local`)=>T(`${F(n)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}`,ua,{method:`DELETE`}),workspaceTree:(e,t,n=``,r=`local`)=>T(`${F(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/tree?path=${encodeURIComponent(n)}`,Qi),workspaceFile:(e,t,n,r=`local`)=>T(`${F(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?path=${encodeURIComponent(n)}`,ea),writeWorkspaceFile:(e,t,n,r,i,a=`local`)=>{let o=new URLSearchParams({path:n});i?.createDirs===!1&&o.set(`createDirs`,`false`),i?.overwrite===!1&&o.set(`overwrite`,`false`);let s=r instanceof Uint8Array,c=s?new Uint8Array(r):new TextEncoder().encode(r);return T(`${F(a)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?${o.toString()}`,ta,{method:`PUT`,body:c,headers:{"Content-Type":s?`application/octet-stream`:`text/plain`}})},deleteWorkspaceFile:(e,t,n,r=`local`)=>{let i=new URLSearchParams({path:n});return T(`${F(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?${i.toString()}`,na,{method:`DELETE`})},moveWorkspaceFile:(e,t,n,r,i,a=`local`)=>{let o=new URLSearchParams({fromPath:n,toPath:r});return i?.createDirs===!1&&o.set(`createDirs`,`false`),i?.overwrite===!0&&o.set(`overwrite`,`true`),T(`${F(a)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file/move?${o.toString()}`,ra,{method:`POST`})}},cc={sessions:(e,t=`local`,n)=>T(`${F(t)}/sessions?cwd=${encodeURIComponent(e)}`,M(tr),xs(n)),reorder:(e,t,n=`local`)=>T(I(e,`reorder`,n),rr,{method:`POST`,body:JSON.stringify(t)}),unreadCatalog:(e=`local`)=>T(`${F(e)}/sessions/unread`,wr,{cache:`no-store`}),acknowledgeUnread:(e,t,n,r=`local`)=>{let i={cwd:e.cwd,catalogId:t,throughCompletionOrder:n};return T(I(e,`unread/acknowledge`,r),wr,{method:`POST`,body:JSON.stringify(i)})},notificationInbox:(e,t=`local`)=>T(Ts(e,`notifications`,t),jr),dismissNotification:(e,t,n,r=`local`)=>T(I(e,`notifications/dismiss`,r),jr,{method:`POST`,body:L(e,{daemonInstanceId:t,notificationId:n})}),dismissAllNotifications:(e,t,n,r=`local`)=>T(I(e,`notifications/dismiss-all`,r),jr,{method:`POST`,body:L(e,{daemonInstanceId:t,throughOrder:n.order,throughOverflowWatermark:n.overflowWatermark})}),startSession:(e,t=`local`,n)=>T(`${F(t)}/sessions`,tr,{method:`POST`,body:JSON.stringify({cwd:e,...n===void 0?{}:{modelPolicy:n}})}),startPlusSession:(e,t,n=`local`)=>T(`${F(n)}/sessions`,tr,{method:`POST`,body:JSON.stringify({cwd:e,creationSource:`session-list-plus`,initialModelPolicy:t})}),sessionDefaults:(e,t=`local`)=>T(`${F(t)}/session-defaults?cwd=${encodeURIComponent(e)}`,si),sessionDefaultsV2:(e,t=`local`)=>{let n=new URLSearchParams({cwd:e,starterModelPolicyContract:`2`});return T(`${F(t)}/session-defaults?${n.toString()}`,ci)},updateSessionDefaults:(e,t,n=`local`)=>T(`${F(n)}/session-defaults`,si,{method:`PUT`,body:JSON.stringify({cwd:e,...t})}),cleanupPreview:(e,t=`local`)=>T(`${F(t)}/sessions/cleanup/preview`,Jr,{method:`POST`,body:JSON.stringify(e)}),cleanup:(e,t=`local`)=>T(`${F(t)}/sessions/cleanup`,Yr,{method:`POST`,body:JSON.stringify(e)}),forceCleanup:(e=`local`)=>T(`${F(e)}/sessions/cleanup/force`,Yr,{method:`POST`}),archiveMany:(e,t=`local`)=>T(`${F(t)}/sessions/bulk/archive`,Xr,{method:`POST`,body:Os(e)}),deleteArchivedMany:(e,t=`local`)=>T(`${F(t)}/sessions/bulk/delete-archived`,Zr,{method:`POST`,body:Os(e)}),messages:(e,t,n=`local`,r)=>T(_s(e,t,n),Un,xs(r)),status:(e,t=`local`,n)=>T(Ts(e,`status`,t),cr,xs(n)),systemPrompt:(e,t=`local`)=>T(Ts(e,`system-prompt`,t),Cr),streamSnapshot:(e,t=`local`,n)=>T(Ts(e,`stream-snapshot`,t),Sr,xs(n)),clearQueue:(e,t=`local`)=>T(I(e,`queue/clear`,t),cr,{method:`POST`,body:L(e)}),dismissWarning:(e,t,n=`local`)=>T(I(e,`warnings/dismiss`,n),cr,{method:`POST`,body:L(e,{dismissId:t})}),modelPolicy:(e,t=`local`)=>T(Ts(e,`model-policy`,t),lr),rememberCurrentModelPolicy:(e,t=`local`)=>T(Ts(e,`model-policy/remember`,t),pr,{method:`POST`}),setModelPolicy:(e,t,n=`local`)=>T(I(e,`model-policy`,n),lr,{method:`PUT`,body:L(e,{policy:t})}),models:(e,t=`local`)=>T(Ts(e,`models`,t),oi),setModel:(e,t,n,r=`local`)=>T(I(e,`model`,r),cr,{method:`POST`,body:L(e,{provider:t,modelId:n})}),cycleModel:(e,t,n=`local`)=>T(I(e,`model/cycle`,n),cr,{method:`POST`,body:L(e,{direction:t})}),thinkingLevels:(e,t=`local`)=>T(Ts(e,`thinking-levels`,t),Ni),setThinkingLevel:(e,t,n=`local`)=>T(I(e,`thinking-level`,n),cr,{method:`POST`,body:L(e,{level:t})}),cycleThinkingLevel:(e,t=`local`)=>T(I(e,`thinking-level/cycle`,t),cr,{method:`POST`,body:L(e)}),commands:(e,t=`local`)=>T(Ts(e,`commands`,t),M(Xi)),prompt:(e,t,n,r=`local`,i)=>T(I(e,`prompt`,r),Ko,{method:`POST`,body:L(e,{text:t,...n===void 0?{}:{streamingBehavior:n},...i!==void 0&&i.length>0?{attachments:i}:{}})}),saveAttachments:(e,t,n=`local`,r)=>T(I(e,`attachments`,n),qo,{method:`POST`,body:L(e,{attachments:t,...r===void 0?{}:{folder:r}})}),shell:(e,t,n=`local`)=>T(I(e,`shell`,n),Ko,{method:`POST`,body:L(e,{text:t})}),runCommand:(e,t,n=`local`)=>T(I(e,`commands/run`,n),Po,{method:`POST`,body:L(e,{text:t})}),respondToCommand:(e,t,n,r=`local`)=>T(I(e,`commands/respond`,r),Po,{method:`POST`,body:L(e,{requestId:t,value:n})}),navigateTree:(e,t,n=`local`)=>T(I(e,`tree/navigate`,n),Ro,{method:`POST`,body:L(e,{targetId:t.targetId,expectedLeafId:t.expectedLeafId,summary:t.summary})}),editFromHere:(e,t,n=`local`)=>T(I(e,`messages/edit-from-here`,n),Ro,{method:`POST`,body:L(e,{entryId:t})}),forkFromHere:(e,t,n=`local`)=>T(I(e,`messages/fork`,n),zo,{method:`POST`,body:L(e,{entryId:t})}),abort:(e,t=`local`)=>T(I(e,`abort`,t),Qo,{method:`POST`,body:L(e)}),stop:(e,t=`local`)=>T(I(e,`stop`,t),$o,{method:`POST`,body:L(e)}),archive:(e,t=`local`)=>T(I(e,`archive`,t),es,{method:`POST`,body:L(e)}),archiveWithDescendants:(e,t=`local`)=>T(I(e,`archive-tree`,t),es,{method:`POST`,body:L(e)}),restore:(e,t=`local`)=>T(I(e,`restore`,t),ts,{method:`POST`,body:L(e)}),deleteArchived:(e,t=`local`)=>T(Es(e,t),ns,{method:`DELETE`}),detachParent:(e,t=`local`)=>T(I(e,`detach-parent`,t),rs,{method:`POST`,body:L(e)}),reloadSession:(e,t=`local`)=>T(I(e,`reload`,t),is,{method:`POST`,body:L(e)}),pin:(e,t=`local`)=>T(I(e,`pin`,t),tr,{method:`POST`,body:L(e)}),unpin:(e,t=`local`)=>T(I(e,`unpin`,t),tr,{method:`POST`,body:L(e)}),authProviders:e=>{let t=new URLSearchParams;e?.mode!==void 0&&t.set(`mode`,e.mode),e?.authType!==void 0&&t.set(`authType`,e.authType);let n=t.toString();return T(`${F(e?.machineId)}/auth/providers${n===``?``:`?${n}`}`,Ri)},saveApiKey:(e,t,n=`local`)=>T(`${F(n)}/auth/api-key`,Ko,{method:`POST`,body:JSON.stringify({providerId:e,key:t})}),startInteractiveApiKeyLogin:(e,t=`local`)=>T(`${F(t)}/auth/api-key/interactive`,zi,{method:`POST`,body:JSON.stringify({providerId:e})}),logoutProvider:(e,t=`local`)=>T(`${F(t)}/auth/logout`,Ko,{method:`POST`,body:JSON.stringify({providerId:e})}),startOAuthLogin:(e,t=`local`)=>T(`${F(t)}/auth/oauth`,zi,{method:`POST`,body:JSON.stringify({providerId:e})}),oauthFlow:(e,t=`local`)=>T(`${F(t)}/auth/oauth/${encodeURIComponent(e)}`,zi),respondOAuthFlow:(e,t,n,r=`local`)=>T(`${F(r)}/auth/oauth/${encodeURIComponent(e)}/respond`,zi,{method:`POST`,body:JSON.stringify({requestId:t,value:n})}),cancelOAuthFlow:(e,t=`local`)=>T(`${F(t)}/auth/oauth/${encodeURIComponent(e)}/cancel`,zi,{method:`POST`})},lc={terminals:(e,t,n=`local`)=>T(`${F(n)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,M(la)),startTerminal:(e,t,n,r=`local`)=>T(`${F(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,la,{method:`POST`,body:JSON.stringify(n??{})}),closeWorkspaceTerminals:(e,t,n=`local`)=>T(`${F(n)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,Yo,{method:`DELETE`}),closeTerminal:(e,t,n,r=`local`)=>T(`${F(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(n)}`,Yo,{method:`DELETE`}),continueTerminal:(e,t,n,r=`local`)=>T(`${F(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(n)}/continue`,la,{method:`POST`}),runTerminalCommand:(e,t,n=`local`)=>T(`${F(n)}/projects/${encodeURIComponent(t.workspace.projectId)}/workspaces/${encodeURIComponent(t.workspace.id)}/terminal-command-runs`,ua,{method:`POST`,body:JSON.stringify({origin:e,title:t.title,command:t.command,metadata:t.metadata??{}})}),listCommandRuns:(e,t=`local`)=>T(`${F(t)}/terminal-command-runs${dc(e)}`,M(ua)),getCommandRun:(e,t=`local`)=>uc(e,t),cancelCommandRun:(e,t=`local`)=>T(`${F(t)}/terminal-command-runs/${encodeURIComponent(e)}/cancel`,ua,{method:`POST`})};async function uc(e,t){let n=await fetch(Wt(`${F(t)}/terminal-command-runs/${encodeURIComponent(e)}`));if(n.status!==404){if(!n.ok){let e=await n.json().catch(()=>({}));throw Error(fc(e)??n.statusText)}return ua(await n.json())}}function dc(e){if(e===void 0)return``;let t=new URLSearchParams;e.projectId!==void 0&&t.set(`projectId`,e.projectId),e.workspaceId!==void 0&&t.set(`workspaceId`,e.workspaceId),e.terminalId!==void 0&&t.set(`terminalId`,e.terminalId),e.statuses!==void 0&&e.statuses.length>0&&t.set(`statuses`,e.statuses.join(`,`)),e.metadata!==void 0&&Object.keys(e.metadata).length>0&&t.set(`metadata`,JSON.stringify(e.metadata));let n=t.toString();return n===``?``:`?${n}`}function fc(e){if(!pc(e))return;let t=e.error;return typeof t==`string`?t:void 0}function pc(e){return typeof e==`object`&&!!e}var mc={files:(e,t,n={})=>{let r=new URLSearchParams({q:t});return n.kind!==void 0&&r.set(`kind`,n.kind),n.mode!==void 0&&r.set(`mode`,n.mode),n.scope!==void 0&&r.set(`scope`,n.scope),n.workspaceScoped===!0&&n.projectId!==void 0&&n.workspaceId!==void 0?T(`${F(n.machineId)}/projects/${encodeURIComponent(n.projectId)}/workspaces/${encodeURIComponent(n.workspaceId)}/files?${r.toString()}`,M(Zi)):(r.set(`cwd`,e),T(`${F(n.machineId)}/files?${r.toString()}`,M(Zi)))}},hc={gitStatus:(e,t,n=`local`)=>T(`${F(n)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/git/status`,aa),gitDiff:(e,t,n,r=`local`)=>T(gs(r,e,t,n),ca)},gc={...js,...Ms,...Ps,...Is,learnedSkills:Rs,...Ks,utilityModels:Ys,...Vs,...Hs,...ec,...rc,...ic,...ac,...oc,...sc,...cc,...lc,...mc,...hc};function _c(e,t=`local`){let n=typeof e==`string`?void 0:e.cwd,r=n===void 0||n===``?``:`?${new URLSearchParams({cwd:n}).toString()}`,i=typeof e==`string`?e:e.id;return new WebSocket(Gt(`${bc(t)}/sessions/${encodeURIComponent(i)}/events${r}`))}function vc(e,t,n,r,i=`local`){let a=r===void 0?``:`?${new URLSearchParams({cols:String(r.cols),rows:String(r.rows)}).toString()}`;return new WebSocket(Gt(`${bc(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(n)}/socket${a}`))}function yc(e=`local`){return new WebSocket(Gt(`${bc(e)}/events`))}function bc(e){return`api/machines/${encodeURIComponent(e)}`}var xc=`.pi-webui/uploads`,Sc=class extends Error{constructor(e=`Workspace upload cancelled`){super(e),this.name=`WorkspaceUploadCancelledError`}},Cc=class extends Error{constructor(e,t){super(Pc(e)),this.name=`WorkspaceUploadBatchError`,this.failures=e.map(e=>({...e})),this.responses=t.map(e=>({...e}))}};function wc(e){return e?.uploads?.defaultFolder??`.pi-webui/uploads`}function Tc(e,t){return e?.uploads?.defaultFolder??t}function Ec(e,t){let n=Lc(e,`upload destination`,{allowEmpty:!0}),r=Lc(t,`upload file name`,{allowEmpty:!1});return n===``?r:`${n}/${r}`}function Dc(e,t,n,r={}){let i=r.xhrFactory?.()??new XMLHttpRequest,a=!1,o=!1;return{promise:new Promise((s,c)=>{let l=e=>{a||(a=!0,c(e))},u=e=>{a||(a=!0,s(e))};i.open(`PUT`,ys(e,t,n.path,Ac(r)),!0),i.responseType=`json`,i.setRequestHeader(`Content-Type`,(n.contentType??n.file.type)||`application/octet-stream`),i.upload.onprogress=e=>{r.onProgress?.(jc(e,n.file.size))},i.onload=()=>{if(i.status>=200&&i.status<300){try{r.onProgress?.({loaded:n.file.size,total:n.file.size,percent:1,lengthComputable:!0}),u(ta(zc(i)))}catch(e){l(e instanceof Error?e:Error(String(e)))}return}l(Error(Bc(i)))},i.onerror=()=>{l(Error(`Workspace upload failed`))},i.onabort=()=>{l(new Sc(o?void 0:`Workspace upload aborted`))},i.send(n.file)}),cancel:()=>{a||(o=!0,i.abort())}}}function Oc(e,t,n,r={}){let i=r.destinationFolder??`.pi-webui/uploads`,a=n.map((e,t)=>({index:t,name:e.name,path:Ec(i,e.name),loaded:0,total:e.size,percent:Nc(0,e.size),lengthComputable:!0,done:!1})),o,s=0,c={requested:!1},l=()=>{r.onProgress?.(Mc(a,s,a.every(e=>e.done)))};return{promise:(async()=>{let i=[],u=[];for(let d=0;d<n.length;d+=1){if(c.requested)throw new Sc;s=d;let f=n[d],p=a[d];if(!(f===void 0||p===void 0)){o=Dc(e,t,{path:p.path,file:f},{...kc(r),onProgress:e=>{p.total=e.total,p.loaded=Math.min(e.loaded,p.total),p.percent=e.percent,p.lengthComputable=e.lengthComputable,l()}});try{let e=await o.promise;p.loaded=p.total,p.percent=1,p.lengthComputable=!0,p.done=!0,i.push(e),l()}catch(e){if(Ic(e,c))throw e;let t=Fc(e);p.loaded=p.total,p.percent=1,p.lengthComputable=!0,p.done=!0,p.error=t,u.push({index:d,name:f.name,path:p.path,error:t}),l()}finally{o=void 0}}}if(u.length>0)throw new Cc(u,i);return i})(),cancel:()=>{c.requested=!0,o?.cancel()}}}function kc(e){return{...e.createDirs===void 0?{}:{createDirs:e.createDirs},...e.overwrite===void 0?{}:{overwrite:e.overwrite},...e.machineId===void 0?{}:{machineId:e.machineId},...e.xhrFactory===void 0?{}:{xhrFactory:e.xhrFactory}}}function Ac(e){return{...e.createDirs===void 0?{}:{createDirs:e.createDirs},...e.overwrite===void 0?{}:{overwrite:e.overwrite},...e.machineId===void 0?{}:{machineId:e.machineId}}}function jc(e,t){let n=e.lengthComputable?e.total:t;return{loaded:e.loaded,total:n,percent:Nc(e.loaded,n),lengthComputable:e.lengthComputable}}function Mc(e,t,n){let r=e.reduce((e,t)=>e+t.total,0),i=e.reduce((e,t)=>e+t.loaded,0);return{currentFileIndex:t,files:e.map(e=>({...e})),loaded:i,total:r,percent:Nc(i,r),done:n}}function Nc(e,t){return t<=0?e<=0?0:1:Math.max(0,Math.min(1,e/t))}function Pc(e){return e.length===1?e[0]?.error??`Workspace upload failed`:`${String(e.length)} files failed to upload`}function Fc(e){return e instanceof Error?e.message:String(e)}function Ic(e,t){return t.requested||e instanceof Sc}function Lc(e,t,n){let r=e.trim();if(r===``){if(n.allowEmpty)return``;throw Error(`${t} must not be empty`)}if(Rc(r))throw Error(`${t} must be workspace-relative`);let i=r.split(/[\\/]+/u).filter(e=>e!==``&&e!==`.`);if(i.length===0){if(n.allowEmpty)return``;throw Error(`${t} must not be empty`)}if(i.some(e=>e===`..`))throw Error(`${t} must not contain path traversal`);return i.join(`/`)}function Rc(e){let t=e.replace(/\\/g,`/`);return t.startsWith(`/`)||/^[A-Za-z]:\//u.test(t)}function zc(e){return e.response!==void 0&&e.response!==null&&e.response!==``?e.response:e.responseText===``?{}:JSON.parse(e.responseText)}function Bc(e){let t=Vc(e);return Hc(t)&&typeof t.error==`string`?t.error:e.statusText||`HTTP ${String(e.status)}`}function Vc(e){try{return zc(e)}catch{return}}function Hc(e){return typeof e==`object`&&!!e}function Uc(e){return e.closesActionPalette===!0}function Wc(e){return{mode:e.mode,exact:Cl(e.exact),...e.tier===void 0?{}:{tier:e.tier}}}function Gc(e){let t=Kc(e);if(t.mode!==`tiered`||t.tier!==void 0)return t;let n=e.catalog?.rows;return n===void 0||!Object.hasOwn(n,`standard`)||!n.standard.valid?t:{...t,tier:`standard`}}function Kc(e){if(e.policy!==void 0)return Wc(e.policy);let t=e.liveResolved;return t===void 0?{mode:`exact`,exact:{model:{provider:``,id:``},thinkingLevel:``}}:{mode:`exact`,exact:Cl(t)}}function qc(e){let t=e.model?.provider,n=e.model?.id;if(!(t===void 0||n===void 0||!Sl(t)||!Sl(n))&&Sl(e.thinkingLevel))return{model:{provider:t,id:n},thinkingLevel:e.thinkingLevel}}function Jc(e){let t=qc(e)??pl(),n=e.starterModelPolicyPreference;return ul(e)?dl(n)?{mode:n.mode,exact:Cl(n.exact),...n.tier===void 0?{}:{tier:n.tier}}:n===void 0?{mode:`tiered`,exact:Cl(t),tier:`standard`}:ll(n,t,n.mode):ll(n,t,`exact`)}function Yc(e,t){let n=qc(t);return n===void 0||e.mode===`tiered`||Zc(e.exact,n)?e:{...e,exact:Cl(n)}}function Xc(e){if(!(e.mode===`tiered`&&e.tier===void 0))return{mode:e.mode,...e.tier===void 0?{}:{tier:e.tier}}}function Zc(e,t){return e.model.provider===t.model.provider&&e.model.id===t.model.id&&e.thinkingLevel===t.thinkingLevel}function Qc(e,t){return{...e,mode:`tiered`,tier:t}}function $c(e){return{...e,mode:`exact`}}function el(e,t){let n=t.thinkingLevels.includes(e.exact.thinkingLevel)?e.exact.thinkingLevel:``;return{...e,exact:{model:{...t.model},thinkingLevel:n}}}function tl(e,t){return{...e,exact:{...e.exact,thinkingLevel:t}}}function nl(e,t){if(e.mode===`exact`)return ol(e.exact,t.models)?{mode:`exact`,exact:Cl(e.exact)}:void 0;let n=e.tier;if(!(n===void 0||!t.valid||!yl(t)||!bl(t,n)))return{mode:`tiered`,tier:n}}function rl(e,t){return t!==void 0&&nl(e,t)!==void 0}function il(e,t,n){let r=ml(e);if(fl(t)||e.mode!==`tiered`||gl(e.exact)||!_l(e.tier)||!yl(n)||!bl(n,e.tier))return r;let i=n.ladder?.[e.tier];return i===void 0||!gl(i)?r:{...r,exact:Cl(i)}}function al(e,t){let n=e.mode===`exact`?sl(e.exact,t):cl(e,t);if(n.kind===`blocked`)return n;let r=hl(e.exact);return r===void 0?{kind:`ready`,initialModelPolicy:{mode:e.mode,exact:Cl(e.exact),...e.tier===void 0?{}:{tier:e.tier}},resolved:Cl(n.resolved)}:{kind:`blocked`,reason:r}}function ol(e,t){return hl(e)===void 0&&t.find(t=>xl(t.model,e.model))?.thinkingLevels.includes(e.thinkingLevel)===!0}function sl(e,t){let n=hl(e);if(n!==void 0)return{kind:`blocked`,reason:n};let r=t.models.find(t=>xl(t.model,e.model));return r===void 0?{kind:`blocked`,reason:`Selected provider/model is unavailable`}:r.thinkingLevels.includes(e.thinkingLevel)?{kind:`ready`,resolved:Cl(e)}:{kind:`blocked`,reason:`Selected thinking level is unsupported by the selected model`}}function cl(e,t){let n=e.tier;if(!_l(n))return{kind:`blocked`,reason:vl(void 0,t)};let r=Object.hasOwn(t.rows,n)?t.rows[n]:void 0;if(r?.valid!==!0)return{kind:`blocked`,reason:vl(r,t)};let i=t.ladder?.[n];return i===void 0||!gl(i)?{kind:`blocked`,reason:vl(r,t)}:{kind:`ready`,resolved:Cl(i)}}function ll(e,t,n){return{mode:e?.mode??n,exact:Cl(t),...e?.tier===void 0?{}:{tier:e.tier}}}function ul(e){return`starterModelPolicyContractVersion`in e}function dl(e){return e!==void 0&&Object.hasOwn(e,`exact`)}function fl(e){return ul(e)&&dl(e.starterModelPolicyPreference)}function pl(){return{model:{provider:``,id:``},thinkingLevel:``}}function ml(e){return{mode:e.mode,exact:Cl(e.exact),...e.tier===void 0?{}:{tier:e.tier}}}function hl(e){return gl(e)?void 0:`Choose a provider, model, and thinking level before starting`}function gl(e){return Sl(e.model.provider)&&Sl(e.model.id)&&Sl(e.thinkingLevel)}function _l(e){return e!==void 0&&Lt.includes(e)}function vl(e,t){return e?.reason!==void 0&&Sl(e.reason)?e.reason:t.configError!==void 0&&Sl(t.configError)?t.configError:`Selected model tier is unavailable`}function yl(e){let t=e.ladder;return t!==void 0&&Lt.every(e=>Object.hasOwn(t,e))}function bl(e,t){return Object.hasOwn(e.rows,t)&&e.rows[t].valid}function xl(e,t){return e.provider===t.provider&&e.id===t.id}function Sl(e){return e.trim()!==``}function Cl(e){return{model:{...e.model},thinkingLevel:e.thinkingLevel}}function wl(e){return{kind:`policy-blocked`,scope:e}}function Tl(e,t,n){return{kind:e,message:t,scope:n}}function El(e,t,n){if(e===void 0||!Ol(e,t))return;let r=e.kind===`policy-blocked`?n:e.message;return r===void 0||r===``?void 0:r}function Dl(e,t,n){return Ol(e,t)?e.kind!==`policy-blocked`||n!==void 0&&n!==``:!1}function Ol(e,t){return t!==void 0&&e.scope.machineId===t.machineId&&e.scope.workspaceId===t.workspaceId}var kl={economy:`Economy`,fast:`Fast`,standard:`Standard`,advanced:`Advanced`,capable:`Capable`,frontier:`Frontier`},Al=Sn;function jl(e){return`${e.provider}/${e.id}`}function Ml(e){let t=e.thinkingLevel.trim()===``?`no thinking level`:e.thinkingLevel;return`${jl(e.model)} · ${t}`}var Nl={off:`No reasoning`,minimal:`Very brief reasoning (~1k tokens)`,low:`Light reasoning (~2k tokens)`,medium:`Moderate reasoning (~8k tokens)`,high:`Deep reasoning (~16k tokens)`,xhigh:`Maximum reasoning (~32k tokens)`};function Pl(e){let t=new Set(e.supported),n=new Set,r=[];for(let t of[...e.supported,...e.all])n.has(t)||(n.add(t),r.push(t));let i=e=>{let t=Al.findIndex(t=>t===e);return t===-1?Al.length:t};return r.map((e,t)=>({level:e,index:t})).sort((e,t)=>{let n=i(e.level)-i(t.level);return n===0?e.index-t.index:n}).map(({level:n})=>({level:n,supported:t.has(n),selected:n===e.selected,...Nl[n]===void 0?{}:{description:Nl[n]}}))}function Fl(){return{sessions:[],projectSessions:[],clientQueuedSessionMessages:{},startingSessionCount:0,isLoadingSessions:!1,selectedNotificationInbox:void 0,treeDialog:void 0,fileTree:[],expandedDirs:{},selectedFilePath:void 0,selectedFileContent:void 0,fileTreeStale:!1,gitStatus:void 0,selectedDiffPath:void 0,selectedDiff:void 0,selectedStagedDiff:void 0,gitStale:!1,memory:{kind:`loading`},learnedSkills:{kind:`loading`},selectedTerminalId:void 0,error:``}}function Il(){return{machines:[],selectedMachine:void 0,isLoadingMachines:!1,machineStatuses:{},machineRuntimes:{},projects:[],workspaces:[],sessions:[],projectSessions:[],messages:[],messagePageStart:0,messagePageEnd:0,messagePageTotal:0,isLoadingEarlierMessages:!1,sendingPrompts:{},clientQueuedSessionMessages:{},startingSessionCount:0,isLoadingProjects:!1,isLoadingWorkspaces:!1,isLoadingSessions:!1,selectedProject:void 0,selectedWorkspace:void 0,selectedSession:void 0,status:void 0,activity:void 0,availableThinkingLevels:[],modelPolicy:void 0,isLoadingModelPolicy:!1,isSavingModelPolicy:!1,modelPolicyError:void 0,sessionStatuses:{},sessionActivities:{},workspaceActivities:{},machineActivities:{},selectedNotificationInbox:void 0,workspacesByProjectId:{},workspaceDeletionRuns:{},commandDialog:void 0,treeDialog:void 0,modelDialog:void 0,thinkingDialog:void 0,themeDialog:void 0,authDialog:void 0,actionPaletteOpen:!1,projectDialogOpen:!1,machineDialogOpen:!1,workspaceTool:`core:workspace.files`,mainView:`chat`,fileTree:[],expandedDirs:{},selectedFilePath:void 0,selectedFileContent:void 0,fileTreeStale:!1,workspaceUploadBatches:{},gitStatus:void 0,selectedDiffPath:void 0,selectedDiff:void 0,selectedStagedDiff:void 0,gitStale:!1,memory:{kind:`loading`},learnedSkills:{kind:`loading`},activeTerminalCount:0,selectedTerminalId:void 0,piWebUiStatus:void 0,error:``}}function Ll(e,t){return t?.phase===`active`||e?.isStreaming===!0||e?.isBashRunning===!0||e?.isCompacting===!0||(e?.pendingMessageCount??0)>0}function Rl(e){return e!==void 0&&(e.hasSessionActivity||e.hasTerminalActivity)}function zl(e,t){return`${e}:${t}`}function Bl(e,t){return`${e}:${t}`}function R(e){return e.selectedMachine?.id??`local`}var Vl=class{constructor(){this.pendingByKey=new Map}request(e,t){let n=this.pendingByKey.get(e);if(n!==void 0)return n.latestRefresh=t,n.started&&(n.trailing=!0),n.promise;let r={promise:Promise.resolve(),latestRefresh:t,started:!1,trailing:!1};return r.promise=Promise.resolve().then(async()=>{let e,t;do{r.trailing=!1;let n=r.latestRefresh;r.started=!0,t=!1;try{await n()}catch(n){e=n,t=!0}}while(this.hasTrailingRequest(r));if(t)throw e}).finally(()=>{this.pendingByKey.get(e)===r&&this.pendingByKey.delete(e)}),this.pendingByKey.set(e,r),r.promise}hasTrailingRequest(e){return e.trailing}},Hl=class{constructor(e,t,n={}){this.getState=e,this.setState=t,this.refreshes=new Vl,this.api=n.api??ic,this.onActivityApplied=n.onActivityApplied}refresh(e=R(this.getState())){return this.refreshes.request(e,async()=>{this.applyMachineActivitySnapshot(e,Ul(await this.api.workspaceActivity(e)))})}applyWorkspaceActivity(e,t=R(this.getState())){let n=this.getState(),r=R(n)===t,i=n.machineActivities[t]??(r?n.workspaceActivities:{});if(!Gl(i,e))return;let a=Wl(i,e);this.setState({machineActivities:{...n.machineActivities,[t]:a},...r?{workspaceActivities:a}:{}}),this.onActivityApplied?.(t)}applyMachineActivitySnapshot(e,t){let n=this.getState();this.setState({machineActivities:{...n.machineActivities,[e]:t},...R(n)===e?{workspaceActivities:t}:{}}),this.onActivityApplied?.(e)}};function Ul(e){let t={};for(let n of e.workspaces)Rl(n)&&(t[n.cwd]=n);return t}function Wl(e,t){let n={...e};return Rl(t)?(n[t.cwd]=t,n):Object.fromEntries(Object.entries(n).filter(([e])=>e!==t.cwd))}function Gl(e,t){let n=e[t.cwd];return n===void 0?Rl(t):n.hasSessionActivity!==t.hasSessionActivity||n.hasTerminalActivity!==t.hasTerminalActivity}var Kl=class{constructor(e,t,n,r={}){this.getState=e,this.setState=t,this.applyStatus=n,this.oauthOperationGeneration=0,this.pollGeneration=0,this.api=r.api??gc,this.pollIntervalMs=r.pollIntervalMs??1e3}dispose(){this.oauthOperationGeneration+=1,this.stopPolling()}handleSlashCommand(e){let t=Jl(e);return t===void 0?!1:(t.command===`login`?this.openLogin(t.providerId):this.openLogout(t.providerId),!0)}async openLogin(e){if(e!==void 0&&e!==``){await this.openLoginProvider(e);return}this.setState({authDialog:{step:`method`}})}async chooseLoginMethod(e){try{let{providers:t}=await this.api.authProviders({mode:`login`,authType:e,machineId:R(this.getState())});this.setState({authDialog:{step:`providers`,mode:`login`,authType:e,providers:t}})}catch(e){this.setState({error:String(e)})}}async selectLoginProvider(e,t){let n=this.getState().authDialog;if(n?.step!==`providers`)return;let r=n.providers.find(n=>n.id===e&&(t===void 0||n.authType===t));r!==void 0&&(r.authType===`oauth`||r.loginFlow===`interactive`?await this.startLoginFlow(r):this.setState({authDialog:{step:`apiKey`,provider:r,value:``}}))}updateApiKey(e){let t=this.getState().authDialog;if(t?.step!==`apiKey`)return;let n={...t};delete n.error,this.setState({authDialog:{...n,value:e}})}async saveApiKey(){let e=this.getState().authDialog;if(e?.step!==`apiKey`)return;let t=e.value.trim();if(t===``){this.setState({authDialog:{...e,error:`API key is required`}});return}let n={...e};delete n.error,this.setState({authDialog:{...n,saving:!0}});try{await this.api.saveApiKey(e.provider.id,t,R(this.getState())),this.closeDialog(),this.refreshStatus()}catch(t){this.setState({authDialog:{...e,saving:!1,error:String(t)}})}}async openLogout(e){try{let{providers:t}=await this.api.authProviders({mode:`logout`,machineId:R(this.getState())});if(e!==void 0&&e!==``){let n=t.find(t=>t.id===e);n!==void 0&&!this.rejectRemoteOAuth(`logout`,n)?await this.logoutProvider(n.id):n===void 0&&this.setState({error:`No stored credentials for ${e}`});return}this.setState({authDialog:{step:`logout`,providers:t}})}catch(e){this.setState({error:String(e)})}}async logoutProvider(e){let t=this.getState().authDialog,n=t?.step===`logout`?t.providers.find(t=>t.id===e):void 0;if(!(n!==void 0&&this.rejectRemoteOAuth(`logout`,n)))try{await this.api.logoutProvider(e,R(this.getState())),this.closeDialog(),this.refreshStatus()}catch(e){this.setState({error:String(e)})}}updateOAuthInput(e){let t=this.getState().authDialog;if(t?.step!==`oauth`)return;let n={...t};delete n.error,this.setState({authDialog:{...n,inputValue:e}})}async respondOAuth(e){let t=this.getState().authDialog;if(t?.step!==`oauth`)return;let n=t.flow.prompt??t.flow.select;if(n===void 0)return;let r=this.oauthOperationGeneration,i=t.flow.flowId,a=n.requestId,o=e??t.inputValue??``,s={...t};delete s.error,this.setState({authDialog:{...s,responding:!0}});try{let e=await this.api.respondOAuthFlow(i,a,o,t.machineId),n=this.currentOAuthDialog(r,i);if(e.flowId!==i||n===void 0||ql(n.flow)!==a)return;this.updateOAuthFlow(e,n.machineId)}catch(e){let t=this.currentOAuthDialog(r,i);if(t===void 0||ql(t.flow)!==a)return;this.setState({authDialog:{...t,responding:!1,error:String(e)}})}}async cancelOAuth(){let e=this.getState().authDialog;if(e?.step!==`oauth`){this.closeDialog();return}let t=e.flow.flowId,n=e.machineId;this.closeDialog();try{await this.api.cancelOAuthFlow(t,n)}catch{}}closeDialog(){this.oauthOperationGeneration+=1,this.stopPolling(),this.setState({authDialog:void 0})}async openLoginProvider(e){try{let{providers:t}=await this.api.authProviders({mode:`login`,machineId:R(this.getState())}),n=t.filter(t=>t.id===e);if(n.length===0){this.setState({error:`Auth provider not found: ${e}`});return}if(n.length>1){this.setState({authDialog:{step:`providers`,mode:`login`,providers:n}});return}let r=n[0];if(r===void 0)return;r.authType===`oauth`||r.loginFlow===`interactive`?await this.startLoginFlow(r):this.setState({authDialog:{step:`apiKey`,provider:r,value:``}})}catch(e){this.setState({error:String(e)})}}async startLoginFlow(e){if(this.rejectRemoteOAuth(`login`,e))return;let t=++this.oauthOperationGeneration;this.stopPolling();try{let n=R(this.getState()),r=e.authType===`oauth`?await this.api.startOAuthLogin(e.id,n):await this.api.startInteractiveApiKeyLogin(e.id,n);if(t!==this.oauthOperationGeneration){if(r.status===`running`)try{await this.api.cancelOAuthFlow(r.flowId,n)}catch{}return}this.updateOAuthFlow(r,n),r.status===`running`&&this.startPolling(r.flowId,n)}catch(e){t===this.oauthOperationGeneration&&this.setState({error:String(e)})}}rejectRemoteOAuth(e,t){let n=this.getState().selectedMachine;if(t.authType!==`oauth`||n?.kind!==`remote`)return!1;let r=n.baseUrl??`that remote PI WEBUI instance`;return this.setState({error:`OAuth ${e} for remote machines must be configured directly on ${r}.`}),!0}updateOAuthFlow(e,t){if(e.status===`complete`){this.stopPolling(),this.closeDialog(),this.refreshStatus(t);return}(e.status===`error`||e.status===`cancelled`)&&(this.oauthOperationGeneration+=1,this.stopPolling());let n=this.getState().authDialog,r=n?.step===`oauth`&&n.flow.flowId===e.flowId?n.inputValue??``:``,i=n?.step===`oauth`?ql(n.flow):void 0,a=ql(e),o=i!==void 0&&i===a,s=o?r:``,c=o&&n?.step===`oauth`?n.responding===!0:!1;this.setState({authDialog:{step:`oauth`,flow:e,machineId:t,inputValue:s,responding:c}})}startPolling(e,t){this.stopPolling();let n=this.oauthOperationGeneration,r=this.pollGeneration;this.pollTimer=window.setInterval(()=>{this.poll(e,t,n,r)},this.pollIntervalMs)}stopPolling(){this.pollGeneration+=1,this.pollTimer!==void 0&&(window.clearInterval(this.pollTimer),this.pollTimer=void 0)}async poll(e,t,n,r){if(r!==this.pollGeneration)return;let i=this.currentOAuthDialog(n,e);if(i?.machineId!==t){this.stopPolling();return}let a=ql(i.flow);try{let i=await this.api.oauthFlow(e,t),o=this.currentOAuthDialog(n,e);if(i.flowId!==e||r!==this.pollGeneration||o?.machineId!==t||ql(o.flow)!==a)return;this.updateOAuthFlow(i,t)}catch(i){let o=this.currentOAuthDialog(n,e);if(r!==this.pollGeneration||o?.machineId!==t||ql(o.flow)!==a)return;this.stopPolling(),this.setState({authDialog:{...o,error:String(i)}})}}currentOAuthDialog(e,t){if(e!==this.oauthOperationGeneration)return;let n=this.getState().authDialog;return n?.step===`oauth`&&n.flow.flowId===t?n:void 0}async refreshStatus(e=R(this.getState())){let t=this.selectedSessionForMachine(e);if(t!==void 0)try{let n=await this.api.status(t,e),r=this.selectedSessionForMachine(e);if(r?.id!==t.id||r.cwd!==t.cwd)return;this.applyStatus(n)}catch{}}selectedSessionForMachine(e){let t=this.getState();if(R(t)!==e)return;let n=t.selectedSession;if(!(n===void 0||n.archived===!0))return n}};function ql(e){return e.prompt?.requestId??e.select?.requestId}function Jl(e){let t=e.trim(),n=/^\/(login|logout)(?:\s+(\S+))?\s*$/u.exec(t);if(n===null)return;let r=n[1];if(r!==`login`&&r!==`logout`)return;let i=n[2];return i===void 0||i===``?{command:r}:{command:r,providerId:i}}function Yl(e){return e.replaceAll(`:`,`.`)}function Xl(e){let t=new URLSearchParams(window.location.search),n=`${e}--`,r={};for(let[e,i]of t.entries()){if(!e.startsWith(n))continue;let t=e.slice(n.length),a=r[t];a===void 0?r[t]=i:Array.isArray(a)?a.push(i):r[t]=[a,i]}return r}function Zl(e,t){let n=Xl(e)[t];return Array.isArray(n)?n[0]:n===``?void 0:n}function Ql(e,t,n,r){let i=new URL(window.location.href),a=`${e}--${t}`;if(i.searchParams.delete(a),n!=null&&n!==``)if(Array.isArray(n))for(let e of n)i.searchParams.append(a,String(e));else i.searchParams.set(a,String(n));$l(i,r)}function $l(e,t){`${e.pathname}${e.search}${e.hash}`!=`${window.location.pathname}${window.location.search}${window.location.hash}`&&(t?.replace===!0?window.history.replaceState({},``,e):window.history.pushState({},``,e))}function eu(e){let t=e.files.map((t,n)=>{let r=t.size;return{index:n,name:t.name,path:Ec(e.destinationFolder,t.name),size:t.size,loaded:0,total:r,percent:ou(0,r),lengthComputable:!0,status:n===0?`uploading`:`pending`}}),n=t.reduce((e,t)=>e+t.total,0);return{id:e.id,projectId:e.projectId,workspaceId:e.workspaceId,machineId:e.machineId,destinationFolder:e.destinationFolder,overwrite:e.overwrite,createDirs:e.createDirs,files:t,currentFileIndex:t.length===0?-1:0,loaded:0,total:n,percent:ou(0,n),status:`uploading`,startedAt:e.startedAt}}function tu(e,t){let n=new Map(t.files.map(e=>[e.index,e])),r=e.files.map(e=>{let r=n.get(e.index);if(r===void 0)return e;let i={...e,path:r.path,loaded:r.loaded,total:r.total,percent:r.percent,lengthComputable:r.lengthComputable,status:r.error===void 0?r.done?`completed`:t.currentFileIndex===e.index?`uploading`:e.status:`error`};return r.error===void 0?delete i.error:i.error=r.error,i});return{...e,files:r,currentFileIndex:t.currentFileIndex,loaded:t.loaded,total:t.total,percent:t.percent}}function nu(e,t,n){let r=e.files.map((e,n)=>{let r=t[n];return{...e,...r===void 0?{}:{path:r.path,response:r},loaded:e.total,percent:1,lengthComputable:!0,status:`completed`}}),i=au(r);return{...e,files:r,currentFileIndex:r.length===0?-1:r.length-1,...i,status:`completed`,completedAt:n}}function ru(e,t,n){let r=e.files.map(n=>n.status===`completed`||n.status===`error`?n:n.status===`uploading`||n.index===e.currentFileIndex?{...n,status:`error`,error:t}:{...n,status:`cancelled`,error:`Not uploaded because an earlier file failed.`});return{...e,files:r,...au(r),status:`error`,error:t,completedAt:n}}function iu(e,t){let n=`Upload cancelled`,r=e.files.map(e=>e.status===`completed`||e.status===`error`?e:{...e,status:`cancelled`,error:n});return{...e,files:r,...au(r),status:`cancelled`,error:n,completedAt:t}}function au(e){let t=e.reduce((e,t)=>e+t.total,0);return{loaded:t,total:t,percent:e.length===0?0:1}}function ou(e,t){return t<=0?e<=0?0:1:Math.max(0,Math.min(1,e/t))}var su=Yl(`core:workspace.files`),cu=class{constructor(e,t,n,r={}){this.getState=e,this.setState=t,this.updateUrl=n,this.uploadTasks=new Map,this.uploadBatchSequence=0,this.api=r.api??gc,this.uploadWorkspaceFiles=r.uploadWorkspaceFiles??Oc,this.createUploadBatchId=r.createUploadBatchId??(()=>(this.uploadBatchSequence+=1,`workspace-upload-${String(this.uploadBatchSequence)}`)),this.now=r.now??(()=>new Date().toISOString())}async refreshFiles(){let e=this.getState().selectedProject,t=this.getState().selectedWorkspace;if(!(e===void 0||t===void 0))try{let n=R(this.getState()),r=await this.api.workspaceTree(e.id,t.id,``,n),i={...this.getState().expandedDirs};await Promise.all(Object.keys(i).map(async r=>{i[r]=(await this.api.workspaceTree(e.id,t.id,r,n)).entries})),this.setState({fileTree:r.entries,expandedDirs:i,fileTreeStale:!1,error:``})}catch(e){this.setState({error:String(e)})}}async expandDir(e){let t=this.getState().selectedProject,n=this.getState().selectedWorkspace;if(!(t===void 0||n===void 0)){if(this.getState().expandedDirs[e]!==void 0){this.setState({expandedDirs:fu(this.getState().expandedDirs,e)});return}try{let r=await this.api.workspaceTree(t.id,n.id,e,R(this.getState()));this.setState({expandedDirs:{...this.getState().expandedDirs,[e]:r.entries},error:``})}catch(e){this.setState({error:String(e)})}}}async selectFile(e){this.setState({selectedFilePath:e,selectedFileContent:void 0,workspaceTool:`core:workspace.files`,mainView:this.getState().mainView===`chat`?`chat`:`core:workspace.files`}),Ql(su,`file`,e),this.updateUrl({replace:!0}),await this.restoreFile(e)}async restoreFile(e){let t=this.getState().selectedProject,n=this.getState().selectedWorkspace;if(!(t===void 0||n===void 0)){this.setState({selectedFilePath:e,selectedFileContent:void 0});try{let r=await this.api.workspaceFile(t.id,n.id,e,R(this.getState()));this.getState().selectedFilePath===e&&this.setState({selectedFileContent:r,error:``})}catch(t){if(this.getState().selectedFilePath!==e)return;if(lu(t)){this.setState({selectedFilePath:void 0,selectedFileContent:void 0,error:``}),Ql(su,`file`,void 0,{replace:!0}),this.updateUrl({replace:!0});return}this.setState({error:String(t)})}}}startWorkspaceUpload(e,t){let n=this.getState().selectedProject,r=this.getState().selectedWorkspace;if(n===void 0||r===void 0){this.setState({error:`Select a workspace before uploading files.`});return}if(e.length===0)return;let i=R(this.getState()),a=t.overwrite??!1,o=t.createDirs??!0,s;try{s=eu({id:this.createUploadBatchId(),projectId:n.id,workspaceId:r.id,machineId:i,destinationFolder:t.destinationFolder,overwrite:a,createDirs:o,files:e,startedAt:this.now()})}catch(e){this.setState({error:String(e)});return}this.setUploadBatch(s);let c;try{c=this.uploadWorkspaceFiles(n.id,r.id,e,{destinationFolder:t.destinationFolder,machineId:i,overwrite:a,createDirs:o,onProgress:e=>{this.updateUploadProgress(s.id,e)}})}catch(e){return this.failUploadBatch(s.id,e),{batchId:s.id,done:Promise.resolve()}}this.uploadTasks.set(s.id,c);let l=c.promise.then(async e=>{await this.completeUploadBatch(s.id,e,t)}).catch(async e=>{await this.handleUploadFailure(s.id,e,t)}).finally(()=>{this.uploadTasks.delete(s.id)});return{batchId:s.id,done:l}}cancelWorkspaceUpload(e){let t=this.getUploadBatch(e);t?.status===`uploading`&&(this.setUploadBatch(iu(t,this.now())),this.uploadTasks.get(e)?.cancel())}clearWorkspaceUpload(e){this.uploadTasks.get(e)?.cancel(),this.uploadTasks.delete(e),this.setState({workspaceUploadBatches:fu(this.getState().workspaceUploadBatches,e)})}updateUploadProgress(e,t){let n=this.getUploadBatch(e);n?.status===`uploading`&&this.setUploadBatch(tu(n,t))}async completeUploadBatch(e,t,n){let r=this.getUploadBatch(e);if(r?.status!==`uploading`||(this.setUploadBatch(nu(r,t,this.now()),{error:``}),!this.isCurrentWorkspaceBatch(r)))return;await this.refreshFiles();let i=t[0]?.path;n.selectUploadedFile!==!1&&i!==void 0&&this.isCurrentWorkspaceBatch(r)&&await this.selectFile(i)}async handleUploadFailure(e,t,n){let r=this.failUploadBatch(e,t);if(!(t instanceof Cc)||t.responses.length===0||r===void 0||!this.isCurrentWorkspaceBatch(r))return;await this.refreshFiles();let i=t.responses[0]?.path;n.selectUploadedFile!==!1&&i!==void 0&&this.isCurrentWorkspaceBatch(r)&&await this.selectFile(i)}failUploadBatch(e,t){let n=this.getUploadBatch(e);if(n?.status!==`uploading`)return;if(uu(t)){let e=iu(n,this.now());return this.setUploadBatch(e),e}let r=du(t),i=ru(n,r,this.now());return this.setUploadBatch(i,{error:r}),i}getUploadBatch(e){return this.getState().workspaceUploadBatches[e]}setUploadBatch(e,t={}){this.setState({workspaceUploadBatches:{...this.getState().workspaceUploadBatches,[e.id]:e},...t})}isCurrentWorkspaceBatch(e){let t=this.getState();return t.selectedProject?.id===e.projectId&&t.selectedWorkspace?.id===e.workspaceId&&R(t)===e.machineId}};function lu(e){let t=String(e);return t.includes(`Path does not exist`)||t.includes(`ENOENT`)||t.includes(`no such file or directory`)}function uu(e){return e instanceof Sc}function du(e){return e instanceof Error?e.message:String(e)}function fu(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>e!==t))}var pu=Yl(`core:workspace.git`),mu=class{constructor(e,t,n){this.getState=e,this.setState=t,this.updateUrl=n,this.statusRequest=0,this.diffRequest=0}dispose(){this.pollTimer!==void 0&&window.clearInterval(this.pollTimer),this.pollTimer=void 0,this.pollingScope=void 0,this.statusRequest+=1,this.diffRequest+=1}async refreshGit(e={}){let t=this.getState().selectedProject,n=this.getState().selectedWorkspace;if(t===void 0||n===void 0)return;let r=R(this.getState()),i=++this.statusRequest;this.diffRequest+=1;try{let a=await gc.gitStatus(t.id,n.id,r);if(i!==this.statusRequest||!this.isCurrentWorkspace(t,n,r))return;this.setState({gitStatus:a,gitStale:!1,...e.reportError===!1?{}:{error:``}});let o=this.getState().selectedDiffPath;o!==void 0&&(a.files.some(e=>e.path===o)?await this.refreshDiff(o,e):(this.setState({selectedDiffPath:void 0,selectedDiff:void 0,selectedStagedDiff:void 0}),Ql(pu,`diff`,void 0,{replace:!0})))}catch(a){if(i!==this.statusRequest||!this.isCurrentWorkspace(t,n,r))return;e.reportError!==!1&&this.setState({error:String(a)})}}async selectDiff(e){this.setState({selectedDiffPath:e,selectedDiff:void 0,selectedStagedDiff:void 0,workspaceTool:`core:workspace.git`,mainView:this.getState().mainView===`chat`?`chat`:`core:workspace.git`}),Ql(pu,`diff`,e),this.updateUrl({replace:!0}),await this.refreshDiff(e)}async restoreDiff(e){this.setState({selectedDiffPath:e,selectedDiff:void 0,selectedStagedDiff:void 0}),await this.refreshDiff(e)}async refreshDiff(e,t={}){let n=this.getState().selectedProject,r=this.getState().selectedWorkspace;if(n===void 0||r===void 0)return;let i=R(this.getState()),a=++this.diffRequest;try{let[o,s]=await Promise.all([gc.gitDiff(n.id,r.id,{path:e},i),gc.gitDiff(n.id,r.id,{path:e,staged:!0},i)]);if(a!==this.diffRequest||!this.isCurrentWorkspace(n,r,i))return;this.setState({selectedDiff:o,selectedStagedDiff:s,...t.reportError===!1?{}:{error:``}})}catch(e){if(a!==this.diffRequest||!this.isCurrentWorkspace(n,r,i))return;t.reportError!==!1&&this.setState({error:String(e)})}}updatePolling(){let e=this.currentPollingScope();e===this.pollingScope&&this.pollTimer!==void 0||(this.dispose(),e!==void 0&&(this.pollingScope=e,this.refreshGit({reportError:!1}),this.pollTimer=window.setInterval(()=>{this.refreshGit({reportError:!1})},8e3)))}currentPollingScope(){let e=this.getState();if(!(e.selectedProject===void 0||e.selectedWorkspace?.isGitRepo!==!0))return JSON.stringify([R(e),e.selectedProject.id,e.selectedWorkspace.id])}isCurrentWorkspace(e,t,n){let r=this.getState();return R(r)===n&&r.selectedProject?.id===e.id&&r.selectedWorkspace?.id===t.id&&r.selectedWorkspace.projectId===t.projectId}},hu=3e4,gu={setTimeout:(e,t)=>window.setTimeout(e,t),clearTimeout:e=>{window.clearTimeout(e)}},_u=class{constructor(e,t,n={}){this.getState=e,this.setState=t,this.generation=0,this.nextRequestId=0,this.observing=!1,this.fetchSnapshot=n.snapshot??Rs.snapshot,this.timer=n.timer??gu,this.pollIntervalMs=n.pollIntervalMs??hu}updatePolling(e=!0){if(!e){this.stopObserving();return}this.observing=!0;let t=this.currentScope();if(t===void 0){this.invalidateScope();return}if(this.scope?.key!==t.key){this.startScope(t);return}this.inFlight?.generation===this.generation&&this.inFlight.scopeKey===t.key||this.pollTimer===void 0&&this.startRequest(t)}async refresh(){if(!this.observing)return;let e=this.currentScope();if(e===void 0){this.invalidateScope();return}if(this.scope?.key!==e.key){await this.startScope(e);return}this.clearPollTimer(),await this.startRequest(e)}dispose(){this.observing=!1,this.invalidateScope()}startScope(e){return this.invalidateScope(),this.scope=e,this.setState({learnedSkills:{kind:`loading`}}),this.startRequest(e)}startRequest(e){let t=this.inFlight;if(t?.generation===this.generation&&t.scopeKey===e.key)return t.promise;let n=this.generation,r=++this.nextRequestId,i={generation:n,requestId:r,scopeKey:e.key,promise:Promise.resolve()};this.inFlight=i;let a=this.load(e,n,r);return i.promise=a,a}async load(e,t,n){try{let n=await this.fetchSnapshot(e.workspacePath,e.machineId);if(!this.isCurrent(e,t))return;let r=vu(n);this.setState({learnedSkills:r}),r.kind===`unavailable`&&this.stopObserving()}catch(n){if(!this.isCurrent(e,t))return;this.applyFailure(String(n))}finally{let r=this.inFlight?.requestId===n;r&&(this.inFlight=void 0),r&&this.isCurrent(e,t)&&this.scheduleNext(e,t)}}applyFailure(e){let t=this.getState().learnedSkills;if(t.kind===`data`){this.setState({learnedSkills:{...t,refreshError:e}});return}this.setState({learnedSkills:{kind:`error`,message:e}})}scheduleNext(e,t){this.clearPollTimer(),this.pollTimer=this.timer.setTimeout(()=>{this.pollTimer=void 0,!(!this.observing||!this.isCurrent(e,t))&&this.startRequest(e)},this.pollIntervalMs)}stopObserving(){this.observing&&(this.observing=!1,this.invalidateScope())}invalidateScope(){this.clearPollTimer(),this.scope=void 0,this.inFlight=void 0,this.generation+=1}clearPollTimer(){this.pollTimer!==void 0&&(this.timer.clearTimeout(this.pollTimer),this.pollTimer=void 0)}currentScope(){let e=this.getState(),t=e.selectedProject,n=e.selectedWorkspace;if(t===void 0||n===void 0)return;let r=R(e);return{key:JSON.stringify([r,t.id,n.id,n.path]),machineId:r,projectId:t.id,workspaceId:n.id,workspacePath:n.path}}isCurrent(e,t){if(!this.observing||t!==this.generation||this.scope?.key!==e.key)return!1;let n=this.currentScope();return n?.machineId===e.machineId&&n.projectId===e.projectId&&n.workspaceId===e.workspaceId&&n.workspacePath===e.workspacePath}};function vu(e){return e.kind===`unavailable`?{kind:`unavailable`}:{kind:`data`,globalSkills:e.globalSkills,projectSkills:e.projectSkills,...e.projectUnavailableMessage===void 0?{}:{projectUnavailableMessage:e.projectUnavailableMessage}}}var yu=3e4,bu={setTimeout:(e,t)=>window.setTimeout(e,t),clearTimeout:e=>{window.clearTimeout(e)}},xu=class{constructor(e,t,n={}){this.getState=e,this.setState=t,this.generation=0,this.nextRequestId=0,this.observing=!1,this.fetchSnapshot=n.snapshot??Is.snapshot,this.timer=n.timer??bu,this.pollIntervalMs=n.pollIntervalMs??yu}updatePolling(e=!0){if(!e){this.stopObserving();return}this.observing=!0;let t=this.currentScope();if(t===void 0){this.invalidateScope();return}if(this.scope?.key!==t.key){this.startScope(t);return}this.inFlight?.generation===this.generation&&this.inFlight.scopeKey===t.key||this.pollTimer===void 0&&this.startRequest(t)}async refresh(){if(!this.observing)return;let e=this.currentScope();if(e===void 0){this.invalidateScope();return}if(this.scope?.key!==e.key){await this.startScope(e);return}this.clearPollTimer(),await this.startRequest(e)}dispose(){this.observing=!1,this.invalidateScope()}startScope(e){return this.invalidateScope(),this.scope=e,this.setState({memory:{kind:`loading`}}),this.startRequest(e)}startRequest(e){let t=this.inFlight;if(t?.generation===this.generation&&t.scopeKey===e.key)return t.promise;let n=this.generation,r=++this.nextRequestId,i={generation:n,requestId:r,scopeKey:e.key,promise:Promise.resolve()};this.inFlight=i;let a=this.load(e,n,r);return i.promise=a,a}async load(e,t,n){try{let n=await this.fetchSnapshot(e.workspacePath,e.machineId);if(!this.isCurrent(e,t))return;let r=Su(n);this.setState({memory:r}),r.kind===`unavailable`&&this.stopObserving()}catch(n){if(!this.isCurrent(e,t))return;this.applyFailure(String(n))}finally{let r=this.inFlight?.requestId===n;r&&(this.inFlight=void 0),r&&this.isCurrent(e,t)&&this.scheduleNext(e,t)}}applyFailure(e){let t=this.getState().memory;if(t.kind===`data`){this.setState({memory:{...t,refreshError:e}});return}this.setState({memory:{kind:`error`,message:e}})}scheduleNext(e,t){this.clearPollTimer(),this.pollTimer=this.timer.setTimeout(()=>{this.pollTimer=void 0,!(!this.observing||!this.isCurrent(e,t))&&this.startRequest(e)},this.pollIntervalMs)}stopObserving(){this.observing&&(this.observing=!1,this.invalidateScope())}invalidateScope(){this.clearPollTimer(),this.scope=void 0,this.inFlight=void 0,this.generation+=1}clearPollTimer(){this.pollTimer!==void 0&&(this.timer.clearTimeout(this.pollTimer),this.pollTimer=void 0)}currentScope(){let e=this.getState(),t=e.selectedProject,n=e.selectedWorkspace;if(t===void 0||n===void 0)return;let r=R(e);return{key:JSON.stringify([r,t.id,n.id,n.path]),machineId:r,projectId:t.id,workspaceId:n.id,workspacePath:n.path}}isCurrent(e,t){if(!this.observing||t!==this.generation||this.scope?.key!==e.key)return!1;let n=this.currentScope();return n?.machineId===e.machineId&&n.projectId===e.projectId&&n.workspaceId===e.workspaceId&&n.workspacePath===e.workspacePath}};function Su(e){return e.kind===`unavailable`?{kind:`unavailable`}:{kind:`data`,globalEntries:e.globalEntries,projectEntries:e.projectEntries,...e.projectUnavailableMessage===void 0?{}:{projectUnavailableMessage:e.projectUnavailableMessage}}}function Cu(e){let t=[],n=[];for(let r of e)ku(r.index)&&t.push(Ou(r,`staged`,r.index)),Au(r.workingTree)&&n.push(Ou(r,`unstaged`,r.workingTree));return{staged:t,unstaged:n}}function wu(e){let t=Cu(e);return new Set([...t.staged,...t.unstaged].map(e=>e.path)).size}function Tu(e){switch(e){case`modified`:return`M`;case`added`:return`A`;case`deleted`:return`D`;case`renamed`:return`R`;case`copied`:return`C`;case`untracked`:return`?`;case`conflicted`:return`U`;case`ignored`:return`!`;case`unmodified`:return``}}function Eu(e){switch(e){case`modified`:return`Modified`;case`added`:return`Added`;case`deleted`:return`Deleted`;case`renamed`:return`Renamed`;case`copied`:return`Copied`;case`untracked`:return`Untracked`;case`conflicted`:return`Conflicted`;case`ignored`:return`Ignored`;case`unmodified`:return`Unmodified`}}function Du(e){return e.oldPath===void 0?e.path:`${e.oldPath} → ${e.path}`}function Ou(e,t,n){return{id:`${t}:${e.path}`,path:e.path,...e.oldPath===void 0?{}:{oldPath:e.oldPath},scope:t,state:n}}function ku(e){return e!==`unmodified`&&e!==`untracked`&&e!==`ignored`&&e!==`conflicted`}function Au(e){return e!==`unmodified`&&e!==`ignored`}var ju=class{constructor(e,t,n,r){this.getState=e,this.setState=t,this.updateUrl=n,this.projects=r,this.runtimeRefreshSeqByMachine=new Map}async loadMachines(e){this.setState({error:``,isLoadingMachines:!0});try{let t=await gc.machines(),n=await this.selectInitialMachine(t,e),r=new Set(t.map(e=>e.id));this.setState({machines:t,selectedMachine:n,machineActivities:Nu(this.getState().machineActivities,r),machineRuntimes:Nu(this.getState().machineRuntimes,r)}),this.refreshMachineHealthFor(t),this.refreshMachineRuntimeFor(t)}catch(e){this.setState({error:String(e)})}finally{this.setState({isLoadingMachines:!1})}}async selectMachine(e,t={}){this.getState().selectedMachine?.id!==e.id&&(this.setState({selectedMachine:e,projects:[],workspaces:[],isLoadingWorkspaces:!1,selectedProject:void 0,selectedWorkspace:void 0,selectedSession:void 0,messages:[],messagePageStart:0,messagePageTotal:0,status:void 0,activity:void 0,sessionStatuses:{},sessionActivities:{},sendingPrompts:{},workspaceActivities:{},workspacesByProjectId:{},workspaceDeletionRuns:{},activeTerminalCount:0,...Fl()}),t.updateUrl!==!1&&this.updateUrl(),await this.projects.loadProjects(),this.refreshMachineHealth(e.id),this.refreshMachineRuntime(e.id))}async addMachine(e){this.setState({error:``});try{let t=await gc.addMachine(e);return this.setState({machines:[...this.getState().machines.filter(e=>e.id!==t.id),t]}),await this.selectMachine(t),t}catch(e){this.setState({error:String(e)});return}}async deleteMachine(e=this.getState().selectedMachine,t={}){if(e!==void 0){if(e.kind===`local`){this.setState({error:`The local machine cannot be removed.`});return}try{let n=this.getState().selectedMachine?.id===e.id;await gc.deleteMachine(e.id);let r=this.getState().machines.filter(t=>t.id!==e.id),i=r.find(e=>e.id===`local`)??r[0];return this.setState({machines:r,machineStatuses:Mu(this.getState().machineStatuses,e.id),machineRuntimes:Mu(this.getState().machineRuntimes,e.id),machineActivities:Mu(this.getState().machineActivities,e.id)}),n&&i!==void 0?(t.selectFallback===!1||await this.selectMachine(i),i):void 0}catch(e){this.setState({error:String(e)});return}}}async refreshMachineHealth(e=this.getState().selectedMachine?.id??`local`){try{let t=await gc.health(e);return this.setState({machineStatuses:{...this.getState().machineStatuses,[t.machineId]:t}}),t}catch(e){this.setState({error:String(e)});return}}async refreshMachineRuntime(e=this.getState().selectedMachine?.id??`local`){let t=(this.runtimeRefreshSeqByMachine.get(e)??0)+1;this.runtimeRefreshSeqByMachine.set(e,t);try{let n=await gc.runtime(e,!0);return this.runtimeRefreshSeqByMachine.get(e)===t?(this.setState({machineRuntimes:{...this.getState().machineRuntimes,[n.machineId]:n}}),n):void 0}catch(n){this.runtimeRefreshSeqByMachine.get(e)===t&&this.setState({error:String(n)});return}}async selectInitialMachine(e,t){let n=e.find(e=>e.id===(t??`local`));if(n===void 0)return this.localMachine(e);if(n.kind!==`remote`)return n;let r=await this.safeRemoteHealth(n);return this.setState({machineStatuses:{...this.getState().machineStatuses,[r.machineId]:r},...r.ok?{}:{error:`${n.name} is unavailable; reconnecting…`}}),n}async safeRemoteHealth(e){try{return await gc.health(e.id)}catch(t){return{machineId:e.id,ok:!1,checkedAt:new Date().toISOString(),status:`offline`,error:t instanceof Error?t.message:String(t)}}}localMachine(e){return e.find(e=>e.id===`local`)??e[0]}async refreshMachineHealthFor(e){let t=await Promise.allSettled(e.map(e=>gc.health(e.id))),n=Object.fromEntries(t.flatMap(e=>e.status===`fulfilled`?[[e.value.machineId,e.value]]:[]));Object.keys(n).length>0&&this.setState({machineStatuses:{...this.getState().machineStatuses,...n}})}async refreshMachineRuntimeFor(e){let t=await Promise.allSettled(e.map(e=>gc.runtime(e.id))),n=Object.fromEntries(t.flatMap(e=>e.status===`fulfilled`?[[e.value.machineId,e.value]]:[]));Object.keys(n).length>0&&this.setState({machineRuntimes:{...this.getState().machineRuntimes,...n}})}};function Mu(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>e!==t))}function Nu(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>t.has(e)))}var Pu=`~/workspace`,Fu=class{constructor(e,t,n,r={}){this.getState=e,this.setState=t,this.workspaces=n,this.projectCatalogOperationSequence=0,this.pinMutationQueueByMachine=new Map,this.latestPinMutationOrderByMachine=new Map,this.api=r.api??gc,this.onProjectsApplied=r.onProjectsApplied}async loadProjects(){let e=R(this.getState()),t=++this.projectCatalogOperationSequence;this.setState({error:``,isLoadingProjects:!0});try{let n=await this.api.projects(e);if(!this.isCurrentProjectCatalogOperation(e,t))return!1;let r;if(n.length===0){if(r=await this.api.addProject(Pu,void 0,!0,e),!this.isCurrentProjectCatalogOperation(e,t))return!1;n=[r]}let i=new Set(n.map(e=>e.id)),a=Object.fromEntries(Object.entries(this.getState().workspacesByProjectId).filter(([e])=>i.has(e))),o=this.getState().selectedProject,s=o!==void 0&&n.some(e=>e.id===o.id&&e.path!==o.path);return this.setState({projects:n,workspacesByProjectId:a}),s&&this.workspaces.clearSelection(),this.onProjectsApplied?.(e),r!==void 0&&await this.workspaces.selectProject(r),!0}catch(n){return this.isCurrentProjectCatalogOperation(e,t)&&this.setState({error:String(n)}),!1}finally{this.isCurrentProjectCatalogOperation(e,t)&&this.setState({isLoadingProjects:!1})}}async addProject(e,t){if(e.trim()===``)return;let n=R(this.getState()),r=++this.projectCatalogOperationSequence;this.setState({isLoadingProjects:!1});try{let i=await this.api.addProject(e.trim(),void 0,t,n);if(R(this.getState())!==n)return;if(!this.isCurrentProjectCatalogOperation(n,r)){this.setState({projectDialogOpen:!1}),await this.loadProjects();return}let a=this.getState().projects;this.setState({projects:[...a.filter(e=>e.id!==i.id),i],projectDialogOpen:!1}),this.onProjectsApplied?.(n),await this.workspaces.selectProject(i)}catch(e){this.isCurrentProjectCatalogOperation(n,r)&&this.setState({error:String(e)})}}async addRegisteredProject(e,t){if(e.trim()===``)throw Error(`Project path is required`);let n=R(this.getState()),r=++this.projectCatalogOperationSequence;this.setState({isLoadingProjects:!1});try{let i=await this.api.addProject(e,t,!1,n);if(R(this.getState())!==n)return i;if(!this.isCurrentProjectCatalogOperation(n,r))return await this.loadProjects(),i;let a=this.getState().projects;return this.setState({projects:[...a.filter(e=>e.id!==i.id),i]}),this.onProjectsApplied?.(n),await this.workspaces.selectProject(i),i}catch(e){throw e instanceof Error?e:Error(String(e))}}async closeProject(e){let t=R(this.getState());try{if(await this.api.closeProject(e,t),R(this.getState())!==t)return;this.workspaces.forgetProject(e);let n=this.getState();this.setState({projects:n.projects.filter(t=>t.id!==e)}),this.onProjectsApplied?.(t),n.selectedProject?.id===e&&this.workspaces.clearSelection()}catch(e){R(this.getState())===t&&this.setState({error:String(e)})}}async closeProjectTree(e){let t=R(this.getState()),n=++this.projectCatalogOperationSequence;this.setState({isLoadingProjects:!1});try{let{closedProjectIds:r}=await this.api.closeProjectTree(e,t);if(R(this.getState())!==t)return;for(let e of r)this.workspaces.forgetProject(e);let i=this.getState(),a=new Set(r);this.setState({projects:i.projects.filter(e=>!a.has(e.id))}),this.onProjectsApplied?.(t),i.selectedProject!==void 0&&a.has(i.selectedProject.id)&&this.workspaces.clearSelection(),this.isCurrentProjectCatalogOperation(t,n)||await this.loadProjects()}catch(e){this.isCurrentProjectCatalogOperation(t,n)&&this.setState({error:String(e)})}}async pinProject(e){await this.applyPinChange(e,t=>this.api.pinProject(e,t))}async unpinProject(e){await this.applyPinChange(e,t=>this.api.unpinProject(e,t))}async applyPinChange(e,t){let n=R(this.getState()),r=++this.projectCatalogOperationSequence;this.setState({isLoadingProjects:!1});let i=(this.latestPinMutationOrderByMachine.get(n)??0)+1;this.latestPinMutationOrderByMachine.set(n,i);let a=this.pinMutationQueueByMachine.get(n),o=a===void 0?this.runPinChange(n,r,i,t):a.catch(()=>void 0).then(async()=>{await this.runPinChange(n,r,i,t)});this.pinMutationQueueByMachine.set(n,o);try{await o}finally{this.cleanupPinMutationQueue(n,i,o)}}async runPinChange(e,t,n,r){try{let i=await r(e);if(!this.isLatestPinMutation(e,n))return;this.isCurrentProjectCatalogOperation(e,t)?this.setState({projects:i}):R(this.getState())===e&&await this.loadProjects()}catch(r){this.isCurrentPinMutation(e,t,n)&&this.setState({error:String(r)})}}isCurrentProjectCatalogOperation(e,t){return R(this.getState())===e&&this.projectCatalogOperationSequence===t}isLatestPinMutation(e,t){return this.latestPinMutationOrderByMachine.get(e)===t}isCurrentPinMutation(e,t,n){return this.isCurrentProjectCatalogOperation(e,t)&&this.isLatestPinMutation(e,n)}cleanupPinMutationQueue(e,t,n){this.pinMutationQueueByMachine.get(e)===n&&(this.pinMutationQueueByMachine.delete(e),this.latestPinMutationOrderByMachine.get(e)===t&&this.latestPinMutationOrderByMachine.delete(e))}},Iu=5e3,Lu=`reconcile selected project catalog`,Ru={setTimeout:(e,t)=>window.setTimeout(e,t),clearTimeout:e=>{window.clearTimeout(e)}},zu=class{constructor(e,t){this.getState=e,this.generation=0,this.nextRequestId=0,this.observing=!1,this.listWorkspaces=t.workspaces??sc.workspaces,this.applySnapshot=t.applySnapshot,this.timer=t.timer??Ru,this.pollIntervalMs=t.pollIntervalMs??Iu,this.onBackgroundError=t.onBackgroundError,this.captureTopologyRequest=t.captureTopologyRequest}updatePolling(e=!0){if(!e){this.stopObserving();return}this.observing=!0;let t=this.currentScope();if(t===void 0){this.invalidateScope();return}let n=this.retargetScope(t);this.inFlight===void 0&&(!n&&this.pollTimer!==void 0||this.scheduleNext(t,this.generation))}refresh(){if(!this.observing)return Promise.resolve();let e=this.currentScope();if(e===void 0)return this.invalidateScope(),Promise.resolve();this.retargetScope(e),this.clearPollTimer();let t=this.generation,n=this.inFlight;return n===void 0?this.startRequest(e,t):n.generation===t&&n.scopeKey===e.key?n.promise:this.queueImmediateRefresh(e,t)}dispose(){this.observing=!1,this.invalidateScope()}retargetScope(e){return this.scope?.key===e.key?(this.scope=e,!1):(this.clearPollTimer(),this.clearQueuedImmediateRefresh(),this.scope=e,this.generation+=1,!0)}startRequest(e,t){let n=this.inFlight;if(n!==void 0)return n.generation===t&&n.scopeKey===e.key?n.promise:this.queueImmediateRefresh(e,t);let r=++this.nextRequestId,i,a=new Promise(e=>{i=e});if(i===void 0)throw Error(`Project catalog request promise was not initialized`);return this.inFlight={generation:t,requestId:r,scopeKey:e.key,promise:a},this.load(e,t,r).then(i,i),a}async load(e,t,n){try{let n=this.captureTopologyRequest?.({machineId:e.machineId,projectId:e.project.id,projectPath:e.project.path}),r=await this.listWorkspaces(e.project.id,e.machineId);if(!this.isCurrent(e,t))return;await this.applySnapshot({machineId:e.machineId,project:e.project,workspaces:r,...n===void 0?{}:{topologyRequest:n}})}catch(n){this.isCurrent(e,t)&&this.reportBackgroundError(n)}finally{this.finishRequest(n)}}finishRequest(e){if(this.inFlight?.requestId!==e)return;this.inFlight=void 0;let t=this.queuedImmediateRefresh;if(t!==void 0){if(this.queuedImmediateRefresh=void 0,this.isCurrent(t.scope,t.generation)){this.startRequest(t.scope,t.generation).then(()=>{t.resolve()},()=>{t.resolve()});return}t.resolve()}let n=this.scope;n!==void 0&&this.isCurrent(n,this.generation)&&this.scheduleNext(n,this.generation)}queueImmediateRefresh(e,t){let n=this.queuedImmediateRefresh;if(n?.generation===t&&n.scope.key===e.key)return n.promise;this.clearQueuedImmediateRefresh();let r,i=new Promise(e=>{r=e});if(r===void 0)throw Error(`Queued project catalog refresh promise was not initialized`);return this.queuedImmediateRefresh={generation:t,scope:e,promise:i,resolve:r},i}scheduleNext(e,t){this.isCurrent(e,t)&&(this.clearPollTimer(),this.pollTimer=this.timer.setTimeout(()=>{this.pollTimer=void 0,!(!this.isCurrent(e,t)||this.inFlight!==void 0)&&this.startRequest(e,t)},this.pollIntervalMs))}stopObserving(){this.observing=!1,this.invalidateScope()}invalidateScope(){this.clearPollTimer(),this.clearQueuedImmediateRefresh(),this.scope=void 0,this.generation+=1}clearPollTimer(){this.pollTimer!==void 0&&(this.timer.clearTimeout(this.pollTimer),this.pollTimer=void 0)}clearQueuedImmediateRefresh(){let e=this.queuedImmediateRefresh;this.queuedImmediateRefresh=void 0,e?.resolve()}currentScope(){let e=this.getState(),t=e.selectedProject;if(t===void 0||e.isLoadingWorkspaces)return;let n=R(e);return{key:JSON.stringify([n,t.id,t.path]),machineId:n,project:t}}isCurrent(e,t){return!this.observing||t!==this.generation||this.scope?.key!==e.key?!1:this.currentScope()?.key===e.key}reportBackgroundError(e){if(this.onBackgroundError!==void 0)try{this.onBackgroundError(Lu,e)}catch{}}},Bu=`record recent project`,Vu=class{constructor(e){this.deps=e,this.current={kind:`loading`},this.queuesByMachine=new Map,this.authoritativeProjectIdByMachine=new Map,this.latestIntentByMachine=new Map,this.generation=0,this.api=e.api??oc}get state(){return this.current}async load(){let e=this.deps.machineId(),t=++this.generation;this.latestIntentByMachine.delete(e),this.authoritativeProjectIdByMachine.delete(e),this.publish({kind:`loading`}),await this.enqueue(e,async()=>{this.authoritativeProjectIdByMachine.delete(e);try{let n=await this.api.recentProjects(e);if(this.isStale(t,e))return;this.publish({kind:`ready`,entries:n})}catch(n){if(this.isStale(t,e))return;this.publish({kind:`failed`,message:Hu(n)})}})}retry(){return this.load()}recordWork(e,t=this.deps.machineId()){if(this.latestIntentByMachine.get(t)?.projectId===e)return;let n={projectId:e};this.latestIntentByMachine.set(t,n);let r=this.generation;this.enqueue(t,async()=>{if(this.authoritativeProjectIdByMachine.get(t)!==e)try{let n=await this.api.recordRecentProject(e,t);if(this.authoritativeProjectIdByMachine.set(t,e),this.isStale(r,t))return;this.publish({kind:`ready`,entries:n})}catch(e){this.latestIntentByMachine.get(t)===n&&this.latestIntentByMachine.delete(t),this.deps.onBackgroundError?.(Bu,e)}})}async removeEntry(e){let t=this.deps.machineId();this.latestIntentByMachine.delete(t),this.authoritativeProjectIdByMachine.delete(t);let n=this.generation,r;if(await this.enqueue(t,async()=>{try{let r=await this.api.removeRecentProject(e,t);this.authoritativeProjectIdByMachine.delete(t),this.isStale(n,t)||this.publish({kind:`ready`,entries:r})}catch(e){r=e instanceof Error?e:Error(String(e))}}),r!==void 0)throw r;return{kind:`removed`}}enqueue(e,t){let n=(this.queuesByMachine.get(e)??Promise.resolve()).then(t,t),r=n.catch(()=>void 0);return this.queuesByMachine.set(e,r),r.then(()=>{this.queuesByMachine.get(e)===r&&this.queuesByMachine.delete(e)}),n}isStale(e,t){return e!==this.generation||t!==this.deps.machineId()}publish(e){this.current=e,this.deps.onChange(e)}};function Hu(e){return e instanceof Error?e.message:String(e)}function Uu(e,t){return t[e.path]}function Wu(e){if(e?.hasSessionActivity===!0)return`session`;if(e?.hasTerminalActivity===!0)return`terminal`}function Gu(e,t,n){return Ju(Yu(e,t,n))}function Ku(e,t,n){return t.some(t=>t.projectId===e.id&&t.path===n)||n===e.path||n.startsWith(`${e.path}/`)}function qu(e){return Ju(Object.values(e??{}))}function Ju(e){if(e.some(e=>e.hasSessionActivity))return`session`;if(e.some(e=>e.hasTerminalActivity))return`terminal`}function Yu(e,t,n){return Object.values(n).filter(n=>Ku(e,t,n.cwd))}var Xu=class{constructor(e,t,n={}){this.getState=e,this.setState=t,this.machineGeneration=0,this.activityMachineGeneration=-1,this.projectTopologyGeneration=0,this.nextCwdActivation=0,this.observedActiveCwds=new Set,this.cwdActivations=new Map,this.attemptedCwdActivations=new Map,this.api=n.api??sc,this.onProjectTopology=n.onProjectTopology,this.captureTopologyRequest=n.captureTopologyRequest,this.onError=n.onError}handleActivityApplied(e){return R(this.getState())===e?(this.activityMachineGeneration=this.machineGeneration,this.reconcile(e)):Promise.resolve()}handleProjectsApplied(e){return R(this.getState())!==e||(this.projectTopologyGeneration+=1,this.attemptedCwdActivations.clear(),this.activePass=void 0,this.activityMachineGeneration!==this.machineGeneration)?Promise.resolve():this.reconcile(e)}handleSelectedMachineChanged(){this.machineGeneration+=1,this.projectTopologyGeneration+=1,this.observedActiveCwds.clear(),this.cwdActivations.clear(),this.attemptedCwdActivations.clear(),this.activePass=void 0}reconcile(e){let t=this.getState();if(R(t)!==e)return Promise.resolve();let n=this.syncActiveCwds(t),r=new Map([...n].filter(([e,n])=>!Zu(t.projects,t.workspacesByProjectId,e)&&this.attemptedCwdActivations.get(e)!==n)),i=this.activePass;if(i!==void 0)return(i.machineGeneration!==this.machineGeneration||i.projectTopologyGeneration!==this.projectTopologyGeneration||[...r].some(([e,t])=>i.cwdActivations.get(e)!==t))&&(i.trailingRequested=!0),i.promise;if(r.size===0||t.projects.length===0)return Promise.resolve();let a={machineGeneration:this.machineGeneration,projectTopologyGeneration:this.projectTopologyGeneration,machineId:e,projects:t.projects.map(e=>({id:e.id,path:e.path,startingWorkspaces:t.workspacesByProjectId[e.id]})),cwdActivations:r,trailingRequested:!1,promise:Promise.resolve()};return this.activePass=a,a.promise=this.runPass(a),a.promise}async runPass(e){if(await Promise.all(e.projects.map(async t=>{try{let n=this.captureTopologyRequest?.({machineId:e.machineId,projectId:t.id,projectPath:t.path}),r=await this.api.workspaces(t.id,e.machineId);await this.applyProjectWorkspaces(e,t,r,n)}catch(n){this.isPassScopeCurrent(e)&&this.reportError({machineId:e.machineId,projectId:t.id,error:n})}})),this.activePass!==e)return;let t=this.getState(),n=this.syncActiveCwds(t);for(let[r,i]of e.cwdActivations)n.get(r)===i&&!Zu(t.projects,t.workspacesByProjectId,r)&&this.attemptedCwdActivations.set(r,i);let r=e.trailingRequested;this.activePass=void 0,r&&await this.reconcile(R(this.getState()))}async applyProjectWorkspaces(e,t,n,r){if(this.activePass!==e||!this.isPassScopeCurrent(e))return;let i=this.getState();if(i.projects.find(e=>e.id===t.id)?.path===t.path&&!(r===void 0&&i.workspacesByProjectId[t.id]!==t.startingWorkspaces)){if(this.onProjectTopology!==void 0){await this.onProjectTopology({machineId:e.machineId,projectId:t.id,projectPath:t.path,workspaces:n,...r===void 0?{}:{topologyRequest:r}});return}this.setState({workspacesByProjectId:{...this.getState().workspacesByProjectId,[t.id]:n}})}}isPassScopeCurrent(e){return e.machineGeneration===this.machineGeneration&&e.projectTopologyGeneration===this.projectTopologyGeneration&&R(this.getState())===e.machineId}syncActiveCwds(e){let t=new Set(Object.values(e.workspaceActivities).filter(Rl).map(e=>e.cwd));for(let e of this.observedActiveCwds)t.has(e)||(this.cwdActivations.delete(e),this.attemptedCwdActivations.delete(e));for(let e of t)this.observedActiveCwds.has(e)||(this.nextCwdActivation+=1,this.cwdActivations.set(e,this.nextCwdActivation),this.attemptedCwdActivations.delete(e));return this.observedActiveCwds=t,new Map([...t].map(e=>[e,this.cwdActivations.get(e)??0]))}reportError(e){if(this.onError!==void 0)try{this.onError(e)}catch{}}};function Zu(e,t,n){return e.some(e=>Ku(e,t[e.id]??[],n))}var Qu=class{constructor(e,t,n={}){this.getState=e,this.setState=t,this.requestSequence=0,this.api=n.api??js,this.onRefreshError=n.onRefreshError??(()=>void 0)}async refresh(){let e=R(this.getState());if(this.pendingUpdateCheck?.machineId===e)return;let t=++this.requestSequence;try{let n=await this.api.piWebUiStatus(e);this.isCurrent(e,t)&&this.setState({piWebUiStatus:n})}catch(n){if(!this.isCurrent(e,t))return;this.setState({piWebUiStatus:void 0}),this.onRefreshError(e,n)}}checkForUpdates(){let e=R(this.getState()),t=this.pendingUpdateCheck;if(t?.machineId===e)return t.promise;let n=++this.requestSequence,r=this.api.checkForUpdates(e).then(t=>{this.isCurrent(e,n)&&(this.setState({piWebUiStatus:t}),$u(t))}).catch(t=>{if(this.isCurrent(e,n))throw t}).finally(()=>{this.pendingUpdateCheck?.requestSequence===n&&(this.pendingUpdateCheck=void 0)});return this.pendingUpdateCheck={machineId:e,requestSequence:n,promise:r},r}isCurrent(e,t){return R(this.getState())===e&&t===this.requestSequence}};function $u(e){if(e.release.error!==void 0)throw Error(`PI WEBUI update check failed: ${e.release.error}`);if(e.release.skipped===!0)throw Error(`PI WEBUI update check was skipped because remote version checks are disabled by offline/version-check settings`)}var ed=`pi-webui:cached-new-sessions:v1`,td=`browserCachedNew`,nd=`local`;function rd(){try{return typeof localStorage>`u`?void 0:localStorage}catch{return}}function id(e,t=nd,n=rd()){if(e.messageCount!==0||e.archived===!0)return;let r=ud(n).filter(n=>n.id!==e.id||n.machineId!==t);dd([ad(e,t),...r],n)}function ad(e,t=nd){return{...e,browserCachedNew:!0,machineId:t}}function od(e,t=nd,n=rd()){dd(ud(n).filter(n=>n.id!==e||n.machineId!==t),n)}function sd(e,t,n=nd,r=rd()){let i=new Set(t.map(e=>e.id)),a=ud(r),o=a.filter(e=>e.machineId!==n||!i.has(e.id));return o.length!==a.length&&dd(o,r),[...o.filter(t=>t.machineId===n&&t.cwd===e),...t]}function cd(e){return e!==void 0&&pd(e)&&e.browserCachedNew===!0}function ld(e){return{id:e.id,path:e.path,cwd:e.cwd,...e.persisted===void 0?{}:{persisted:e.persisted},...e.name===void 0?{}:{name:e.name},created:e.created,modified:e.modified,messageCount:e.messageCount,firstMessage:e.firstMessage,...e.parentSessionPath===void 0?{}:{parentSessionPath:e.parentSessionPath},...`machineId`in e&&typeof e.machineId==`string`?{machineId:e.machineId}:{machineId:nd},...e.archived===!0?{archived:!0}:{},...e.archivedAt===void 0?{}:{archivedAt:e.archivedAt},...e.creationSource===void 0?{}:{creationSource:e.creationSource}}}function ud(e=rd()){try{let t=e?.getItem(ed);if(t==null||t===``)return[];let n=JSON.parse(t);return Array.isArray(n)?n.flatMap(e=>fd(e)):[]}catch{return[]}}function dd(e,t=rd()){try{e.length===0?t?.removeItem(ed):t?.setItem(ed,JSON.stringify(e))}catch{}}function fd(e){if(!md(e))return[];let t=hd(e,`id`),n=hd(e,`path`),r=hd(e,`cwd`),i=hd(e,`created`),a=hd(e,`modified`),o=hd(e,`firstMessage`),s=_d(e,`messageCount`);if(t===void 0||n===void 0||r===void 0||i===void 0||a===void 0||o===void 0||s!==0)return[];let c=gd(e,`name`),l=gd(e,`parentSessionPath`),u=gd(e,`machineId`)??nd,d=e.creationSource===`session-list-plus`?e.creationSource:void 0;return[{id:t,path:n,cwd:r,...c===void 0?{}:{name:c},created:i,modified:a,messageCount:s,firstMessage:o,...l===void 0?{}:{parentSessionPath:l},...d===void 0?{}:{creationSource:d},machineId:u,browserCachedNew:!0}]}function pd(e){return td in e}function md(e){return typeof e==`object`&&!!e}function hd(e,t){let n=e[t];return typeof n==`string`?n:void 0}function gd(e,t){let n=e[t];return n===void 0||typeof n!=`string`?void 0:n}function _d(e,t){let n=e[t];return typeof n==`number`?n:void 0}function vd(e){return Ld(e.flatMap(Cd)).filter(e=>e.parts.length>0)}function yd(e,t){return{role:e,parts:[{type:`text`,text:t}]}}function bd(e,t){let n=kd(t),r=z(t,`entryId`),i=z(t,`previousAssistantEntryId`),a=Kd(t,`canFork`);return{...e,...n===void 0?{}:{meta:n},...r===void 0?{}:{entryId:r},...i===void 0?{}:{previousAssistantEntryId:i},...a===void 0?{}:{canFork:a}}}function xd(e,t,n){if(n===``)return e;let r=e.at(-1),i=r?.parts.at(-1);return r?.role===t&&i?.type===`text`?[...e.slice(0,-1),{...r,parts:[...r.parts.slice(0,-1),{...i,text:i.text+n}]}]:r?.role===t?[...e.slice(0,-1),{...r,parts:[...r.parts,{type:`text`,text:n}]}]:[...e,yd(t,n)]}function Sd(e,t){if(t===``)return e;let n=e.at(-1),r=n?.parts.at(-1);return n?.role===`assistant`&&r?.type===`thinking`?[...e.slice(0,-1),{...n,parts:[...n.parts.slice(0,-1),{...r,text:r.text+t}]}]:n?.role===`assistant`?[...e.slice(0,-1),{...n,parts:[...n.parts,{type:`thinking`,text:t}]}]:[...e,{role:`assistant`,parts:[{type:`thinking`,text:t}]}]}function Cd(e){if(Td(e))return[e];if(z(e,`role`)===`bashExecution`)return[bd(Md(e),e)];let t=Nd(z(e,`role`)),n=Pd(Gd(e,`content`),e),r=t===`user`?Ed(n):void 0;if(r!==void 0)return r.map(t=>bd(t,e));let i=Od(e);if(t===`tool`)return[bd({role:t,parts:n,...i===void 0?{}:{source:i}},e)];let a=n.filter(e=>e.type!==`empty`),o=t===`assistant`&&a.length>0&&a.every(e=>e.type===`skillRead`)?`skill`:t,s=a.length>0?[bd({role:o,parts:a,...i===void 0?{}:{source:i}},e)]:[],c=wd(e);return c===void 0?s:[...s,bd(c,e)]}function wd(e){if(z(e,`role`)!==`assistant`||z(e,`stopReason`)!==`error`)return;let t=z(e,`errorMessage`)?.trim();return yd(`system`,`Model response failed: ${t===void 0||t===``?`The model returned an error.`:t}`)}function Td(e){let t=z(e,`role`);return(t===`user`||t===`assistant`||t===`tool`||t===`system`||t===`bash`||t===`skill`)&&Array.isArray(Gd(e,`parts`))}function Ed(e){if(e.length!==1||e[0]?.type!==`text`)return;let t=Dd(e[0].text);if(t!==void 0)return[{role:`user`,parts:[{type:`skillInvocation`,name:t.name,location:t.location,content:t.content}]},...t.userMessage===void 0?[]:[{role:`user`,parts:[{type:`text`,text:t.userMessage}]}]]}function Dd(e){let t=/^<skill name="([^"]+)" location="([^"]+)">\n([\s\S]*?)\n<\/skill>(?:\n\n([\s\S]+))?$/.exec(e);if(t===null)return;let n=t[4]?.trim();return{name:t[1]??`skill`,location:t[2]??``,content:t[3]??``,...n===void 0||n===``?{}:{userMessage:n}}}function Od(e){let t=z(e,`source`);if(t===`compaction`||t===`branch_summary`)return t}function kd(e){let t=Ad(Gd(e,`timestamp`)),n=jd(e);if(!(t===void 0&&n===void 0))return{...t===void 0?{}:{timestamp:t},...n===void 0?{}:{model:n}}}function Ad(e){if(typeof e==`number`&&Number.isFinite(e))return new Date(e).toISOString();if(typeof e!=`string`||e===``)return;let t=Date.parse(e);return Number.isFinite(t)?new Date(t).toISOString():void 0}function jd(e){if(z(e,`role`)!==`assistant`)return;let t=z(e,`provider`),n=z(e,`model`),r=z(e,`responseModel`);if(!((t===void 0||t===``)&&(n===void 0||n===``)&&(r===void 0||r===``)))return{...t===void 0||t===``?{}:{provider:t},...n===void 0||n===``?{}:{id:n},...r===void 0||r===``?{}:{responseId:r}}}function Md(e){let t=z(e,`command`)??``,n=Kd(e,`excludeFromContext`)===!0?[`excluded from context`,``,`$ ${t}`]:[`$ ${t}`],r=Gd(e,`output`);r!=null&&n.push(``,Jd(r));let i=Gd(e,`exitCode`);i!=null&&n.push(``,`exit ${Jd(i)}`),Kd(e,`cancelled`)===!0&&n.push(``,`cancelled`),Kd(e,`truncated`)===!0&&n.push(``,`output truncated`);let a=z(e,`fullOutputPath`);return a!==void 0&&a!==``&&n.push(``,`full output: ${a}`),{role:`bash`,parts:[{type:`text`,text:n.join(`
|
|
@@ -1211,7 +1211,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
1211
1211
|
.review-file span { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
1212
1212
|
.dialog-error { border: 1px solid var(--pi-danger); border-radius: 8px; background: color-mix(in srgb, var(--pi-danger) 10%, transparent); color: var(--pi-danger); padding: 9px; line-height: 1.35; overflow-wrap: anywhere; }
|
|
1213
1213
|
footer { display: flex; justify-content: flex-end; gap: 8px; padding-top: 4px; }
|
|
1214
|
-
`]}};H([x({attribute:!1})],cb.prototype,`context`,void 0),H([C(`#workspace-upload-input`)],cb.prototype,`uploadInput`,void 0),H([S()],cb.prototype,`pendingUpload`,void 0),H([S()],cb.prototype,`destinationFolder`,void 0),H([S()],cb.prototype,`overwrite`,void 0),H([S()],cb.prototype,`createDirs`,void 0),H([S()],cb.prototype,`formError`,void 0),H([S()],cb.prototype,`dragActive`,void 0),cb=H([b(`workspace-files-panel`)],cb);function lb(e,t){return Object.values(e).filter(e=>e.projectId===t.projectId&&e.workspaceId===t.workspaceId&&e.machineId===t.machineId).sort((e,t)=>t.startedAt.localeCompare(e.startedAt))}function ub(e,t){if(e.length===0)return`Choose at least one file to upload.`;for(let n of e)try{Ec(t,n.name)}catch(e){return e instanceof Error?e.message:String(e)}}function db(e){return{destinationFolder:e,createDirs:!0,overwrite:!1}}function fb(e){let t=e.selectedFileContent;if(e.selectedFilePath===void 0||e.selectedFilePath===``)return`Select a file.`;if(t===void 0)return`Loading ${e.selectedFilePath}…`;if(t.mediaType!==`image`&&t.binary)return`Binary file: ${t.path} · ${Tb(t.size)}`}function pb(e,t){if(t.length!==0)return e.onStartWorkspaceUpload(t,{destinationFolder:e.workspaceUploadDefaultFolder,createDirs:!0,overwrite:!1,selectUploadedFile:!0})}function mb(e){return`${e.machine.id}:${e.workspace.projectId}:${e.workspace.id}`}function hb(e){return e==null?[]:Array.from(e)}function gb(e){return Array.from(e.dataTransfer?.types??[]).includes(`Files`)}function _b(e){let t=e.filter(e=>e.status===`uploading`).length;return t===0?`${String(e.length)} recent`:`${String(t)} uploading`}function vb(e){let t=e.files.length,n=t===1?`file`:`files`;switch(e.status){case`completed`:return`Uploaded ${String(t)} ${n}`;case`error`:return`Upload failed for ${String(t)} ${n}`;case`cancelled`:return`Upload cancelled for ${String(t)} ${n}`;case`uploading`:return`Uploading ${String(t)} ${n}`}}function yb(e){switch(e.status){case`completed`:return`Done`;case`error`:return`Failed`;case`cancelled`:return`Cancelled`;case`uploading`:return Cb(e.percent)}}function bb(e){return e.status===`uploading`?e.percent:1}function xb(e){switch(e.status){case`pending`:return`Pending`;case`uploading`:return Cb(e.percent);case`completed`:return`Done`;case`error`:return`Error`;case`cancelled`:return`Cancelled`}}function Sb(e){return e.error===void 0?e.response===void 0?`${e.path} · ${Tb(e.loaded)} / ${Tb(e.total)}`:`Wrote ${e.response.path}`:e.error}function Cb(e){return`${String(Math.round(Math.max(0,Math.min(1,e))*100))}%`}function wb(){sb(()=>import(`./CodeViewer-
|
|
1214
|
+
`]}};H([x({attribute:!1})],cb.prototype,`context`,void 0),H([C(`#workspace-upload-input`)],cb.prototype,`uploadInput`,void 0),H([S()],cb.prototype,`pendingUpload`,void 0),H([S()],cb.prototype,`destinationFolder`,void 0),H([S()],cb.prototype,`overwrite`,void 0),H([S()],cb.prototype,`createDirs`,void 0),H([S()],cb.prototype,`formError`,void 0),H([S()],cb.prototype,`dragActive`,void 0),cb=H([b(`workspace-files-panel`)],cb);function lb(e,t){return Object.values(e).filter(e=>e.projectId===t.projectId&&e.workspaceId===t.workspaceId&&e.machineId===t.machineId).sort((e,t)=>t.startedAt.localeCompare(e.startedAt))}function ub(e,t){if(e.length===0)return`Choose at least one file to upload.`;for(let n of e)try{Ec(t,n.name)}catch(e){return e instanceof Error?e.message:String(e)}}function db(e){return{destinationFolder:e,createDirs:!0,overwrite:!1}}function fb(e){let t=e.selectedFileContent;if(e.selectedFilePath===void 0||e.selectedFilePath===``)return`Select a file.`;if(t===void 0)return`Loading ${e.selectedFilePath}…`;if(t.mediaType!==`image`&&t.binary)return`Binary file: ${t.path} · ${Tb(t.size)}`}function pb(e,t){if(t.length!==0)return e.onStartWorkspaceUpload(t,{destinationFolder:e.workspaceUploadDefaultFolder,createDirs:!0,overwrite:!1,selectUploadedFile:!0})}function mb(e){return`${e.machine.id}:${e.workspace.projectId}:${e.workspace.id}`}function hb(e){return e==null?[]:Array.from(e)}function gb(e){return Array.from(e.dataTransfer?.types??[]).includes(`Files`)}function _b(e){let t=e.filter(e=>e.status===`uploading`).length;return t===0?`${String(e.length)} recent`:`${String(t)} uploading`}function vb(e){let t=e.files.length,n=t===1?`file`:`files`;switch(e.status){case`completed`:return`Uploaded ${String(t)} ${n}`;case`error`:return`Upload failed for ${String(t)} ${n}`;case`cancelled`:return`Upload cancelled for ${String(t)} ${n}`;case`uploading`:return`Uploading ${String(t)} ${n}`}}function yb(e){switch(e.status){case`completed`:return`Done`;case`error`:return`Failed`;case`cancelled`:return`Cancelled`;case`uploading`:return Cb(e.percent)}}function bb(e){return e.status===`uploading`?e.percent:1}function xb(e){switch(e.status){case`pending`:return`Pending`;case`uploading`:return Cb(e.percent);case`completed`:return`Done`;case`error`:return`Error`;case`cancelled`:return`Cancelled`}}function Sb(e){return e.error===void 0?e.response===void 0?`${e.path} · ${Tb(e.loaded)} / ${Tb(e.total)}`:`Wrote ${e.response.path}`:e.error}function Cb(e){return`${String(Math.round(Math.max(0,Math.min(1,e))*100))}%`}function wb(){sb(()=>import(`./CodeViewer-BGClPFoI.js`),__vite__mapDeps([0,1,2,3]),import.meta.url)}function Tb(e){if(!Number.isFinite(e)||e<0)return`0 B`;if(e<1024)return`${String(e)} B`;let t=e/1024;if(t<1024)return`${Eb(t)} KB`;let n=t/1024;return n<1024?`${Eb(n)} MB`:`${Eb(n/1024)} GB`}function Eb(e){return e>=10?String(Math.round(e)):e.toFixed(1)}var Db=2e3,Ob=class extends y{constructor(...e){super(...e),this.loading=!1,this.error=``,this.dynamicMetricsRequest=0,this.dynamicMetricsRefreshInFlight=!1}willUpdate(e){if(!e.has(`context`))return;let t=this.context?.machine.id;if(t===void 0){this.stopDynamicMetricsPolling(),this.machineId=void 0;return}t!==this.machineId&&(this.stopDynamicMetricsPolling(),this.machineId=t,this.loadSystemInfo(t))}async loadSystemInfo(e=this.machineId){if(e!==void 0){this.loading=!0,this.error=``;try{let t=await js.systemInfo(e);this.isCurrentMachine(e)&&(this.systemInfo=t,this.isConnected&&this.startDynamicMetricsPolling())}catch(t){this.isCurrentMachine(e)&&(this.error=t instanceof Error?t.message:String(t))}finally{this.isCurrentMachine(e)&&(this.loading=!1)}}}connectedCallback(){super.connectedCallback(),this.startDynamicMetricsPolling()}disconnectedCallback(){this.stopDynamicMetricsPolling(),super.disconnectedCallback()}startDynamicMetricsPolling(){let e=this.machineId;e===void 0||this.systemInfo===void 0||this.dynamicMetricsTimer!==void 0||(this.dynamicMetricsPollingMachineId=e,this.dynamicMetricsTimer=window.setInterval(()=>{this.refreshDynamicMetrics(e)},Db))}stopDynamicMetricsPolling(){this.dynamicMetricsTimer!==void 0&&window.clearInterval(this.dynamicMetricsTimer),this.dynamicMetricsTimer=void 0,this.dynamicMetricsPollingMachineId=void 0,this.dynamicMetricsRequest+=1,this.dynamicMetricsRefreshInFlight=!1}async refreshDynamicMetrics(e){if(this.loading||this.error!==``||this.dynamicMetricsRefreshInFlight||this.dynamicMetricsPollingMachineId!==e)return;this.dynamicMetricsRefreshInFlight=!0;let t=++this.dynamicMetricsRequest;try{let n=await js.systemMetrics(e);if(!this.isCurrentDynamicMetricsRequest(e,t))return;this.applyDynamicMetrics(n)}catch{}finally{t===this.dynamicMetricsRequest&&(this.dynamicMetricsRefreshInFlight=!1)}}isCurrentDynamicMetricsRequest(e,t){return t===this.dynamicMetricsRequest&&this.dynamicMetricsPollingMachineId===e&&this.isCurrentMachine(e)}applyDynamicMetrics(e){let t=this.systemInfo;t!==void 0&&(this.systemInfo={...t,memory:e.memory,network:{...t.network,...e.network}})}isCurrentMachine(e){return this.machineId===e&&this.context?.machine.id===e}render(){if(this.loading)return g`<section class="info-panel"><p class="muted">Loading system information…</p></section>`;if(this.error!==``)return g`<section class="info-panel">
|
|
1215
1215
|
<p class="error-text">Failed to load system information: ${this.error}</p>
|
|
1216
1216
|
<button @click=${()=>{this.loadSystemInfo()}}>Retry</button>
|
|
1217
1217
|
</section>`;let e=this.systemInfo;return e===void 0?g`<section class="info-panel"><p class="muted">System information unavailable.</p></section>`:g`<section class="info-panel">
|
|
@@ -1465,7 +1465,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
1465
1465
|
<div class="viewer-header"><strong>${e.path??`diff`}</strong><small>${e.staged?`staged`:`unstaged`}${e.truncated?` · truncated`:``}</small></div>
|
|
1466
1466
|
<unified-diff-viewer .diff=${e.diff}></unified-diff-viewer>
|
|
1467
1467
|
</section>
|
|
1468
|
-
`}function Vb(){sb(()=>import(`./UnifiedDiffViewer-
|
|
1468
|
+
`}function Vb(){sb(()=>import(`./UnifiedDiffViewer-I9Fc0TRx.js`),[],import.meta.url)}function Hb(){sb(()=>Promise.resolve().then(()=>TI),void 0,import.meta.url)}function Ub(e){return g`<workspace-info-panel .context=${e}></workspace-info-panel>`}function Wb(e){let t=Gb(e);return g`
|
|
1469
1469
|
<p class="summary">
|
|
1470
1470
|
<span class="summary-branch">${t.branch}</span>
|
|
1471
1471
|
${t.latestTag===void 0?null:g`<span class="summary-tag" aria-label=${`Latest tag ${t.latestTag}`}>${t.latestTag}</span>`}
|
|
@@ -6179,9 +6179,9 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
6179
6179
|
<h2>${e.title}</h2>
|
|
6180
6180
|
${e.body===void 0?null:g`<p>${e.body}</p>`}
|
|
6181
6181
|
</section>
|
|
6182
|
-
`}workspaceHeaderFrameClass(){return`workspace-header-scroll-frame${this.workspaceHeaderCanScrollLeft?` can-scroll-left`:``}${this.workspaceHeaderCanScrollRight?` can-scroll-right`:``}`}observeWorkspaceHeaderStrip(){let e=this.workspaceHeaderStripElement();this.observedWorkspaceHeaderStrip!==e&&(this.workspaceHeaderResizeObserver?.disconnect(),this.observedWorkspaceHeaderStrip=e,this.workspaceHeaderResizeObserver=void 0,!(e===void 0||typeof ResizeObserver>`u`)&&(this.workspaceHeaderResizeObserver=new ResizeObserver(()=>{this.updateWorkspaceHeaderScrollState()}),this.workspaceHeaderResizeObserver.observe(e)))}updateWorkspaceHeaderScrollState(){let e=this.workspaceHeaderStripElement(),t=e===void 0?0:Math.max(0,e.scrollWidth-e.clientWidth),n=e!==void 0&&e.scrollLeft>1,r=e!==void 0&&t-e.scrollLeft>1;this.workspaceHeaderCanScrollLeft!==n&&(this.workspaceHeaderCanScrollLeft=n),this.workspaceHeaderCanScrollRight!==r&&(this.workspaceHeaderCanScrollRight=r)}workspaceHeaderStripElement(){let e=this.workspaceHeaderStrip;return e instanceof HTMLElement?e:void 0}static{this.styles=Xy}};H([x({attribute:!1})],NF.prototype,`tabs`,void 0),H([x({attribute:!1})],NF.prototype,`emptyState`,void 0),H([x()],NF.prototype,`tool`,void 0),H([x({attribute:!1})],NF.prototype,`hiddenTools`,void 0),H([x({type:Boolean})],NF.prototype,`hideToolTabs`,void 0),H([x({attribute:!1})],NF.prototype,`onSelectTool`,void 0),H([C(`.workspace-header-strip`)],NF.prototype,`workspaceHeaderStrip`,void 0),H([S()],NF.prototype,`workspaceHeaderCanScrollLeft`,void 0),H([S()],NF.prototype,`workspaceHeaderCanScrollRight`,void 0),NF=H([b(`workspace-panel`)],NF);function PF(e,t){return t.find(t=>t.path===e.path)}
|
|
6182
|
+
`}workspaceHeaderFrameClass(){return`workspace-header-scroll-frame${this.workspaceHeaderCanScrollLeft?` can-scroll-left`:``}${this.workspaceHeaderCanScrollRight?` can-scroll-right`:``}`}observeWorkspaceHeaderStrip(){let e=this.workspaceHeaderStripElement();this.observedWorkspaceHeaderStrip!==e&&(this.workspaceHeaderResizeObserver?.disconnect(),this.observedWorkspaceHeaderStrip=e,this.workspaceHeaderResizeObserver=void 0,!(e===void 0||typeof ResizeObserver>`u`)&&(this.workspaceHeaderResizeObserver=new ResizeObserver(()=>{this.updateWorkspaceHeaderScrollState()}),this.workspaceHeaderResizeObserver.observe(e)))}updateWorkspaceHeaderScrollState(){let e=this.workspaceHeaderStripElement(),t=e===void 0?0:Math.max(0,e.scrollWidth-e.clientWidth),n=e!==void 0&&e.scrollLeft>1,r=e!==void 0&&t-e.scrollLeft>1;this.workspaceHeaderCanScrollLeft!==n&&(this.workspaceHeaderCanScrollLeft=n),this.workspaceHeaderCanScrollRight!==r&&(this.workspaceHeaderCanScrollRight=r)}workspaceHeaderStripElement(){let e=this.workspaceHeaderStrip;return e instanceof HTMLElement?e:void 0}static{this.styles=Xy}};H([x({attribute:!1})],NF.prototype,`tabs`,void 0),H([x({attribute:!1})],NF.prototype,`emptyState`,void 0),H([x()],NF.prototype,`tool`,void 0),H([x({attribute:!1})],NF.prototype,`hiddenTools`,void 0),H([x({type:Boolean})],NF.prototype,`hideToolTabs`,void 0),H([x({attribute:!1})],NF.prototype,`onSelectTool`,void 0),H([C(`.workspace-header-strip`)],NF.prototype,`workspaceHeaderStrip`,void 0),H([S()],NF.prototype,`workspaceHeaderCanScrollLeft`,void 0),H([S()],NF.prototype,`workspaceHeaderCanScrollRight`,void 0),NF=H([b(`workspace-panel`)],NF);function PF(e,t){return t.find(t=>t.path===e.path)}function FF(e,t,n,r){let i=[],a=[];for(let o of e){let e=PF(o,t);e!==void 0&&Gu(e,n[e.id]??[],r)!==void 0?i.push(o):a.push(o)}return[...i,...a]}var IF=class extends y{constructor(...e){super(...e),this.state={kind:`loading`},this.projects=[],this.workspacesByProjectId={},this.activities={}}render(){return this.state.kind===`loading`?g`<p class="muted" role="status">Loading recent projects…</p>`:this.state.kind===`failed`?this.renderFailure(this.state.message):this.state.entries.length===0?g`<p class="muted recent-projects-empty" role="status" tabindex="-1">No recent projects</p>`:g`
|
|
6183
6183
|
<div class="list-body recent-projects-list">
|
|
6184
|
-
${this.state.entries.
|
|
6184
|
+
${KC(FF(this.state.entries,this.projects,this.workspacesByProjectId,this.activities),e=>e.id,(e,t)=>this.renderEntry(e,t))}
|
|
6185
6185
|
</div>
|
|
6186
6186
|
`}renderFailure(e){return g`
|
|
6187
6187
|
<div class="recent-projects-failure" role="status">
|
|
@@ -6251,7 +6251,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
6251
6251
|
@media (hover: none) {
|
|
6252
6252
|
.recent-project-remove { opacity: 1; pointer-events: auto; }
|
|
6253
6253
|
}
|
|
6254
|
-
`]}};H([x({attribute:!1})],
|
|
6254
|
+
`]}};H([x({attribute:!1})],IF.prototype,`state`,void 0),H([x({attribute:!1})],IF.prototype,`projects`,void 0),H([x({attribute:!1})],IF.prototype,`workspacesByProjectId`,void 0),H([x({attribute:!1})],IF.prototype,`activities`,void 0),H([x({attribute:!1})],IF.prototype,`selectedProjectId`,void 0),H([x({attribute:!1})],IF.prototype,`onOpenRegistered`,void 0),H([x({attribute:!1})],IF.prototype,`onOpenClosed`,void 0),H([x({attribute:!1})],IF.prototype,`onRemoveRequested`,void 0),H([x({attribute:!1})],IF.prototype,`onRetry`,void 0),IF=H([b(`recent-projects-panel`)],IF);var LF=class extends y{constructor(...e){super(...e),this.initialView=`closed-actions`,this.view=`closed-actions`,this.busy=!1,this.requestRemoval=()=>{this.view=`removal-confirmation`,this.failure=void 0,this.updateComplete.then(()=>{this.cancelButton?.focus()})},this.handleCancel=e=>{e.preventDefault(),!this.busy&&this.onClose()},this.handleBackdropClick=e=>{e.target===e.currentTarget&&(this.busy||this.onClose())}}willUpdate(e){(e.has(`entry`)||e.has(`initialView`))&&(this.view=this.initialView,this.failure=void 0)}firstUpdated(){let e=this.nativeDialog;e?.isConnected===!0&&(e.showModal(),this.view===`removal-confirmation`?this.cancelButton?.focus():this.reopenButton?.focus())}disconnectedCallback(){this.close(),super.disconnectedCallback()}close(){let e=this.nativeDialog;e?.open===!0&&e.close()}render(){return g`
|
|
6255
6255
|
<dialog
|
|
6256
6256
|
class="recent-project-backdrop"
|
|
6257
6257
|
aria-modal="true"
|
|
@@ -6300,10 +6300,10 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
6300
6300
|
button:focus-visible { outline: 2px solid var(--pi-accent); outline-offset: 2px; }
|
|
6301
6301
|
.recent-project-confirm-remove { border-color: color-mix(in srgb, var(--pi-danger) 45%, transparent); background: color-mix(in srgb, var(--pi-danger) 14%, transparent); color: var(--pi-danger); }
|
|
6302
6302
|
.recent-project-confirm-remove:hover:not(:disabled) { border-color: var(--pi-danger); background: color-mix(in srgb, var(--pi-danger) 24%, transparent); }
|
|
6303
|
-
`}};H([x({attribute:!1})],
|
|
6304
|
-
`),lines:p,physicalLineCount:f.length,viewportLine:Math.min(d,Math.max(0,e.viewportY))}}function
|
|
6303
|
+
`}};H([x({attribute:!1})],LF.prototype,`entry`,void 0),H([x({attribute:!1})],LF.prototype,`initialView`,void 0),H([x({attribute:!1})],LF.prototype,`onReopen`,void 0),H([x({attribute:!1})],LF.prototype,`onRemove`,void 0),H([x({attribute:!1})],LF.prototype,`onClose`,void 0),H([C(`dialog`)],LF.prototype,`nativeDialog`,void 0),H([C(`.recent-project-reopen`)],LF.prototype,`reopenButton`,void 0),H([C(`.recent-project-cancel`)],LF.prototype,`cancelButton`,void 0),H([S()],LF.prototype,`view`,void 0),H([S()],LF.prototype,`busy`,void 0),H([S()],LF.prototype,`failure`,void 0),LF=H([b(`recent-project-dialog`)],LF);var RF=`important`,zF=` !important`,BF=St(class extends Ct{constructor(e){if(super(e),e.type!==xt.ATTRIBUTE||e.name!==`style`||e.strings?.length>2)throw Error("The `styleMap` directive must be used in the `style` attribute and must be the only part in the attribute.")}render(e){return Object.keys(e).reduce((t,n)=>{let r=e[n];return r==null?t:t+`${n=n.includes(`-`)?n:n.replace(/(?:^(webkit|moz|ms|o)|)(?=[A-Z])/g,`-$&`).toLowerCase()}:${r};`},``)}update(e,[t]){let{style:n}=e.element;if(this.ft===void 0)return this.ft=new Set(Object.keys(t)),this.render(t);for(let e of this.ft)t[e]??(this.ft.delete(e),e.includes(`-`)?n.removeProperty(e):n[e]=null);for(let e in t){let r=t[e];if(r!=null){this.ft.add(e);let t=typeof r==`string`&&r.endsWith(zF);e.includes(`-`)||t?n.setProperty(e,t?r.slice(0,-11):r,t?RF:``):n[e]=r}}return nt}}),VF=`#ffffff`,HF=`#000000`,UF=[`#2e3436`,`#cc0000`,`#4e9a06`,`#c4a000`,`#3465a4`,`#75507b`,`#06989a`,`#d3d7cf`,`#555753`,`#ef2929`,`#8ae234`,`#fce94f`,`#729fcf`,`#ad7fa8`,`#34e2e2`,`#eeeeec`],WF=[`black`,`red`,`green`,`yellow`,`blue`,`magenta`,`cyan`,`white`,`brightBlack`,`brightRed`,`brightGreen`,`brightYellow`,`brightBlue`,`brightMagenta`,`brightCyan`,`brightWhite`],GF={black:UF[0],red:UF[1],green:UF[2],yellow:UF[3],blue:UF[4],magenta:UF[5],cyan:UF[6],white:UF[7],brightBlack:UF[8],brightRed:UF[9],brightGreen:UF[10],brightYellow:UF[11],brightBlue:UF[12],brightMagenta:UF[13],brightCyan:UF[14],brightWhite:UF[15]};function KF(e,t,n={}){let r=Math.max(0,Math.floor(t));if(e.length<=0||r===0)return{text:``,lines:[],physicalLineCount:0,viewportLine:0};let i=eI(n.theme),a=n.theme?.foreground??VF,o=n.theme?.background??HF,s=[],c=e.getNullCell(),l=-1;for(let t=0;t<e.length;t+=1){let u=e.getLine(t);if(u===void 0){s.push({text:``,runs:[],wrapped:!1});continue}let d=qF(u,r,c,{palette:i,foreground:a,background:o,drawBoldTextInBrightColors:n.drawBoldTextInBrightColors!==!1});s.push(d),(d.text!==``||d.runs.some(e=>e.style.background!==o))&&(l=t)}let u=Math.min(e.length-1,Math.max(0,e.baseY+e.cursorY)),d=Math.max(l,u),f=s.slice(0,d+1),p=[];for(let e of f){let t=p.at(-1);if(e.wrapped&&t!==void 0){t.text+=e.text,ZF(t.runs,e.runs);continue}p.push({text:e.text,runs:e.runs.map(e=>({text:e.text,style:e.style}))})}return{text:p.map(e=>e.text).join(`
|
|
6304
|
+
`),lines:p,physicalLineCount:f.length,viewportLine:Math.min(d,Math.max(0,e.viewportY))}}function qF(e,t,n,r){let i=[],a=Math.min(t,e.length);for(let t=0;t<a;t+=1){let a=e.getCell(t,n);if(a===void 0){i.push({text:` `,meaningful:!1,style:XF(r)});continue}let o=a.getWidth();if(o===0)continue;let s=a.getChars();i.push({text:s===``?` `.repeat(Math.max(1,o)):s,meaningful:s!==``||!a.isAttributeDefault(),style:JF(a,r)})}let o=i.length-1;for(;o>=0&&i[o]?.meaningful!==!0;)--o;let s=[],c=``;for(let e=0;e<=o;e+=1){let t=i[e];t!==void 0&&(c+=t.text,QF(s,{text:t.text,style:t.style}))}return{text:c,runs:s,wrapped:e.isWrapped}}function JF(e,t){let n=e.isInverse()!==0,r=YF(e,`foreground`,t),i=YF(e,`background`,t);if(n&&([r,i]=[i,r]),e.isBold()!==0&&t.drawBoldTextInBrightColors){let i=n?e.isBgPalette()?e.getBgColor():void 0:e.isFgPalette()?e.getFgColor():void 0;i!==void 0&&i>=0&&i<8&&(r=t.palette[i+8]??r)}return{foreground:r,background:i,bold:e.isBold()!==0,italic:e.isItalic()!==0,dim:e.isDim()!==0,underline:e.isUnderline()!==0,invisible:e.isInvisible()!==0,strikethrough:e.isStrikethrough()!==0,overline:e.isOverline()!==0}}function YF(e,t,n){let r=t===`foreground`?e.isFgRGB():e.isBgRGB(),i=t===`foreground`?e.isFgPalette():e.isBgPalette(),a=t===`foreground`?e.getFgColor():e.getBgColor();return r?tI(a):i?n.palette[a]??(t===`foreground`?n.foreground:n.background):t===`foreground`?n.foreground:n.background}function XF(e){return{foreground:e.foreground,background:e.background,bold:!1,italic:!1,dim:!1,underline:!1,invisible:!1,strikethrough:!1,overline:!1}}function ZF(e,t){for(let n of t)QF(e,n)}function QF(e,t){if(t.text===``)return;let n=e.at(-1);if(n!==void 0&&$F(n.style,t.style)){n.text+=t.text;return}e.push({text:t.text,style:t.style})}function $F(e,t){return e.foreground===t.foreground&&e.background===t.background&&e.bold===t.bold&&e.italic===t.italic&&e.dim===t.dim&&e.underline===t.underline&&e.invisible===t.invisible&&e.strikethrough===t.strikethrough&&e.overline===t.overline}function eI(e){let t=[...UF];for(let n=0;n<WF.length;n+=1){let r=WF[n];if(r===void 0)continue;let i=e?.[r];typeof i==`string`&&(t[n]=i)}let n=[0,95,135,175,215,255];for(let e=0;e<216;e+=1){let r=n[Math.floor(e/36)%6]??0,i=n[Math.floor(e/6)%6]??0,a=n[e%6]??0;t.push(nI(r,i,a))}for(let e=0;e<24;e+=1){let n=8+e*10;t.push(nI(n,n,n))}for(let n=0;n<Math.min(e?.extendedAnsi?.length??0,240);n+=1){let r=e?.extendedAnsi?.[n];r!==void 0&&(t[n+16]=r)}return t}function tI(e){return`#${(e&16777215).toString(16).padStart(6,`0`)}`}function nI(e,t,n){return`#${e.toString(16).padStart(2,`0`)}${t.toString(16).padStart(2,`0`)}${n.toString(16).padStart(2,`0`)}`}var rI=`pi-webui.terminal.softKeys`,iI=`(pointer: coarse), (max-width: 760px)`;function aI(e,t){return e??t}function oI(e){if(e===`true`)return!0;if(e===`false`)return!1}function sI(){return typeof window<`u`&&`matchMedia`in window?window.matchMedia(iI):void 0}function cI(e){return e?.matches===!0}function lI(e=sI()){return aI(dI(),cI(e))}function uI(){return dI()!==void 0}function dI(e=pI()){if(e!==void 0)try{return oI(e.getItem(rI))}catch{return}}function fI(e,t=pI()){if(t!==void 0)try{t.setItem(rI,String(e))}catch{}}function pI(){if(!(typeof window>`u`))try{return window.localStorage}catch{return}}var mI=[{id:`escape`,label:`Esc`,ariaLabel:`Escape`,title:`Send Escape`},{id:`tab`,label:`Tab`,ariaLabel:`Tab`,title:`Send Tab`},{id:`ctrl-c`,label:`Ctrl+C`,ariaLabel:`Control C`,title:`Interrupt the foreground process`},{id:`ctrl-d`,label:`Ctrl+D`,ariaLabel:`Control D`,title:`Send EOF / close input`},{id:`ctrl-z`,label:`Ctrl+Z`,ariaLabel:`Control Z`,title:`Suspend the foreground process`},{id:`ctrl-l`,label:`Ctrl+L`,ariaLabel:`Control L`,title:`Clear / redraw the terminal`},{id:`ctrl-r`,label:`Ctrl+R`,ariaLabel:`Control R`,title:`Reverse search history`},{id:`ctrl-u`,label:`Ctrl+U`,ariaLabel:`Control U`,title:`Delete to the start of the line`},{id:`ctrl-w`,label:`Ctrl+W`,ariaLabel:`Control W`,title:`Delete the previous word`},{id:`arrow-left`,label:`←`,ariaLabel:`Left arrow`,title:`Move left`},{id:`arrow-up`,label:`↑`,ariaLabel:`Up arrow`,title:`Move up / previous command`},{id:`arrow-down`,label:`↓`,ariaLabel:`Down arrow`,title:`Move down / next command`},{id:`arrow-right`,label:`→`,ariaLabel:`Right arrow`,title:`Move right`},{id:`home`,label:`Home`,ariaLabel:`Home`,title:`Move to the start`},{id:`end`,label:`End`,ariaLabel:`End`,title:`Move to the end`},{id:`page-up`,label:`PgUp`,ariaLabel:`Page up`,title:`Page up`},{id:`page-down`,label:`PgDn`,ariaLabel:`Page down`,title:`Page down`},{id:`delete`,label:`Del`,ariaLabel:`Delete`,title:`Delete forward`},{id:`backspace`,label:`⌫`,ariaLabel:`Backspace`,title:`Backspace`},{id:`meta-backward-word`,label:`M-B`,ariaLabel:`Meta B`,title:`Move backward one word`},{id:`meta-forward-word`,label:`M-F`,ariaLabel:`Meta F`,title:`Move forward one word`}],hI=`\x1B`,gI=``;function _I(e,t){switch(e){case`escape`:return hI;case`tab`:return` `;case`ctrl-c`:return vI(`c`);case`ctrl-d`:return vI(`d`);case`ctrl-z`:return vI(`z`);case`ctrl-l`:return vI(`l`);case`ctrl-r`:return vI(`r`);case`ctrl-u`:return vI(`u`);case`ctrl-w`:return vI(`w`);case`arrow-left`:return yI(`D`,t);case`arrow-up`:return yI(`A`,t);case`arrow-down`:return yI(`B`,t);case`arrow-right`:return yI(`C`,t);case`home`:return bI(`H`,t);case`end`:return bI(`F`,t);case`page-up`:return`${hI}[5~`;case`page-down`:return`${hI}[6~`;case`delete`:return`${hI}[3~`;case`backspace`:return gI;case`meta-backward-word`:return`${hI}b`;case`meta-forward-word`:return`${hI}f`}}function vI(e){return String.fromCharCode(e.toUpperCase().charCodeAt(0)-64)}function yI(e,t){return t?.applicationCursorKeysMode===!0?`${hI}O${e}`:`${hI}[${e}`}function bI(e,t){return t?.applicationCursorKeysMode===!0?`${hI}O${e}`:`${hI}[${e}`}var xI=8,SI=500,CI=class extends y{constructor(...e){super(...e),this.refocusOnClick=!0,this.onInput=()=>void 0,this.lastPointerFinishedAt=0}sendSoftKey(e,t){this.onInput(_I(e.id,this.modes),t)}onSoftKeyPointerDown(e,t){e.pointerType===`mouse`&&e.button!==0||(e.preventDefault(),this.pointerStart={pointerId:e.pointerId,key:t,clientX:e.clientX,clientY:e.clientY})}onSoftKeyPointerMove(e){let t=this.pointerStart;t?.pointerId===e.pointerId&&wI(t,e)&&this.finishSoftKeyPointer()}onSoftKeyPointerUp(e,t){let n=this.pointerStart;n?.pointerId===e.pointerId&&(e.preventDefault(),this.finishSoftKeyPointer(),!(n.key.id!==t.id||wI(n,e))&&this.sendSoftKey(t,{refocus:e.pointerType===`mouse`}))}onSoftKeyPointerCancel(e){this.pointerStart?.pointerId===e.pointerId&&this.finishSoftKeyPointer()}finishSoftKeyPointer(){this.pointerStart=void 0,this.lastPointerFinishedAt=Date.now()}onSoftKeyClick(e,t){if(Date.now()-this.lastPointerFinishedAt<SI){e.preventDefault();return}this.sendSoftKey(t,{refocus:this.refocusOnClick})}render(){return g`
|
|
6305
6305
|
<div class="terminal-soft-keys" role="toolbar" aria-label="Terminal soft keys">
|
|
6306
|
-
${
|
|
6306
|
+
${mI.map(e=>g`
|
|
6307
6307
|
<button
|
|
6308
6308
|
type="button"
|
|
6309
6309
|
class="soft-key"
|
|
@@ -6323,7 +6323,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
6323
6323
|
.terminal-soft-keys::-webkit-scrollbar { display: none; }
|
|
6324
6324
|
button { display: inline-flex; align-items: center; gap: 6px; flex: 0 0 auto; max-width: none; min-height: 34px; border: 1px solid var(--pi-border); border-radius: 7px; background: var(--pi-surface); color: var(--pi-text); padding: 6px 9px; font: 12px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; cursor: pointer; touch-action: pan-x; -webkit-touch-callout: none; user-select: none; }
|
|
6325
6325
|
button:disabled { opacity: .5; cursor: not-allowed; }
|
|
6326
|
-
`}};H([x({attribute:!1})],SI.prototype,`modes`,void 0),H([x({type:Boolean})],SI.prototype,`refocusOnClick`,void 0),H([x({attribute:!1})],SI.prototype,`onInput`,void 0),SI=H([b(`terminal-soft-keys`)],SI);function CI(e,t){return Math.hypot(t.clientX-e.clientX,t.clientY-e.clientY)>bI}var wI=ue({TerminalPanel:()=>Z,filterTerminalInput:()=>zI,terminalBackgroundWithOpacity:()=>GI}),TI={allowTransparency:!0,cursorBlink:!0,convertEol:!0,fontFamily:`ui-monospace, SFMono-Regular, Menlo, Consolas, monospace`,fontSize:13},EI={cols:100,rows:30},DI=1e3,OI=500,kI=5e3,AI=1.6,jI=`--pi-terminal-effective-bg`,MI=`--pi-terminal-ui-opacity`,Z=class extends y{constructor(...e){super(...e),this.machineId=`local`,this.autoStart=!1,this.fontSize=13,this.bgOpacity=100,this.onSelectTerminal=()=>void 0,this.terminals=[],this.commandRuns=[],this.loading=!1,this.visible=!1,this.cancellingRunIds=[],this.continuingTerminalIds=[],this.defaultSoftKeysEnvironment=!1,this.softKeysEnabled=cI(),this.suppressTerminalInput=!1,this.terminalReconnectDelay=OI,this.softKeysDefaultEnvironmentMedia=oI(),this.softKeysPreferenceStored=lI(),this.onSoftKeysDefaultEnvironmentChange=()=>{this.syncDefaultSoftKeysEnvironment()}}connectedCallback(){super.connectedCallback(),this.syncTerminalBackground(),this.syncDefaultSoftKeysEnvironment(),this.softKeysDefaultEnvironmentMedia?.addEventListener(`change`,this.onSoftKeysDefaultEnvironmentChange),this.themeObserver=new MutationObserver(()=>{this.applyTerminalTheme()}),this.themeObserver.observe(document.documentElement,{attributes:!0,attributeFilter:[`class`,`style`,`data-theme`]})}firstUpdated(){this.intersectionObserver=new IntersectionObserver(e=>{this.visible=e[0]?.isIntersecting===!0}),this.intersectionObserver.observe(this)}disconnectedCallback(){this.intersectionObserver?.disconnect(),this.intersectionObserver=void 0,this.themeObserver?.disconnect(),this.themeObserver=void 0,this.softKeysDefaultEnvironmentMedia?.removeEventListener(`change`,this.onSoftKeysDefaultEnvironmentChange),this.updateCommandRunPolling(!1),this.disposeTerminalView(),super.disconnectedCallback()}syncDefaultSoftKeysEnvironment(){let e=sI(this.softKeysDefaultEnvironmentMedia),t=this.softKeysEnabled;this.defaultSoftKeysEnvironment=e,this.softKeysPreferenceStored||(this.softKeysEnabled=e),this.softKeysEnabled!==t&&this.scheduleFitAndNotify()}scheduleFitAndNotify(){this.updateComplete.then(()=>{this.fitAndNotify()})}willUpdate(e){e.has(`bgOpacity`)&&this.syncTerminalBackground();let t=this.workspace===void 0?void 0:JSON.stringify([this.machineId,this.workspace.path]);if(t!==this.observedWorkspaceScope){this.observedWorkspaceScope=t,this.loadedCwd=void 0,this.autoStartConsumedCwd=void 0,this.terminals=[],this.commandRuns=[],this.selectedId=void 0,this.cancellingRunIds=[],this.continuingTerminalIds=[],this.updateCommandRunPolling(!1),this.disposeTerminalView();return}if(e.has(`selectedTerminalId`)){if(e.get(`selectedTerminalId`)!==void 0&&this.selectedTerminalId===void 0){this.loadedCwd=void 0,this.selectTerminalIdInView(void 0);return}this.applyRequestedTerminalSelection()}}updated(e){this.visible?this.hasPendingCommandRuns()&&this.updateCommandRunPolling(!0):this.updateCommandRunPolling(!1),this.loadVisibleWorkspaceTerminals(),e.has(`selectedTerminalId`)&&this.shouldReloadForRequestedTerminal()&&this.loadTerminals(),e.has(`fontSize`)&&this.terminal!==void 0&&(this.terminal.options.fontSize=this.fontSize,this.fitAndNotify()),e.has(`bgOpacity`)&&this.applyTerminalTheme(),this.ensureTerminalView()}loadVisibleWorkspaceTerminals(){let e=this.workspace?.path;!this.visible||e===void 0||e===this.loadedCwd||(this.loadedCwd=e,this.loadTerminals())}async loadTerminals(){this.loading=!0,this.error=void 0;try{let e=this.workspace;if(e===void 0)return;let t=this.consumeAutoStart(),[n,r]=await Promise.all([lc.terminals(e.projectId,e.id,this.machineId),lc.listCommandRuns({projectId:e.projectId,workspaceId:e.id},this.machineId)]);this.terminals=n,this.commandRuns=r,this.selectPreferredLoadedTerminal({replaceUrl:!0}),this.updateCommandRunPolling(this.hasPendingCommandRuns(r)),n.length===0&&t&&await this.startTerminal()}catch(e){this.error=e instanceof Error?e.message:String(e)}finally{this.loading=!1}}applyRequestedTerminalSelection(){this.selectedTerminalId!==void 0&&!this.terminals.some(e=>e.id===this.selectedTerminalId)||this.selectPreferredLoadedTerminal({replaceUrl:!0})}consumeAutoStart(){let e=this.workspace?.path;return!this.autoStart||e===void 0||this.autoStartConsumedCwd===e?!1:(this.autoStartConsumedCwd=e,!0)}shouldReloadForRequestedTerminal(){let e=this.workspace?.path;return this.visible&&e!==void 0&&e===this.loadedCwd&&this.selectedTerminalId!==void 0&&!this.loading&&!this.terminals.some(e=>e.id===this.selectedTerminalId)}selectPreferredLoadedTerminal(e){let t=K_(this.terminals,{targetTerminalId:this.selectedTerminalId});t===void 0&&this.selectedTerminalId!==void 0&&(t=q_(this.terminals)),this.selectTerminalIdInView(t?.id),(t?.id!==this.selectedTerminalId||t===void 0&&this.selectedTerminalId!==void 0)&&this.onSelectTerminal(t?.id,{replace:e?.replaceUrl===!0})}selectTerminalIdInView(e){this.selectedId!==e&&(this.selectedId=e,this.disposeTerminalView())}async startTerminal(){let e=this.workspace;if(e===void 0)return;let t=this.machineId,n=this.onStarted;this.error=void 0;try{let r=this.measureTerminalSize()??EI,i=await lc.startTerminal(e.projectId,e.id,r,t);this.terminals=[...this.terminals,i],this.selectTerminal(i.id),n?.()}catch(e){this.error=e instanceof Error?e.message:String(e)}}async closeTerminal(e,t){t.stopPropagation();try{if(this.workspace===void 0)return;await lc.closeTerminal(this.workspace.projectId,this.workspace.id,e,this.machineId);let t=this.terminals.filter(t=>t.id!==e);if(this.terminals=t,this.selectedId===e||this.selectedTerminalId===e){let e=q_(t)?.id;this.selectTerminalIdInView(e),this.onSelectTerminal(e,{replace:!0})}}catch(e){this.error=e instanceof Error?e.message:String(e)}}selectTerminal(e){this.selectedId!==e&&this.selectTerminalIdInView(e),this.onSelectTerminal(e)}selectedTerminalInfo(){return this.terminals.find(e=>e.id===this.selectedId)}selectedCommandRun(){let e=this.selectedTerminalInfo()?.commandRunId;if(e!==void 0)return this.commandRuns.find(t=>t.id===e)}async loadCommandRuns(){let e=this.workspace;if(e!==void 0)try{let t=await lc.listCommandRuns({projectId:e.projectId,workspaceId:e.id},this.machineId);this.commandRuns=t,this.cancellingRunIds=this.cancellingRunIds.filter(e=>t.some(t=>t.id===e&&II(t))),this.updateCommandRunPolling(this.hasPendingCommandRuns(t))}catch(e){this.error=e instanceof Error?e.message:String(e)}}updateCommandRunPolling(e){if(e&&this.commandRunPollTimer===void 0){this.commandRunPollTimer=window.setInterval(()=>{this.loadCommandRuns()},DI);return}!e&&this.commandRunPollTimer!==void 0&&(window.clearInterval(this.commandRunPollTimer),this.commandRunPollTimer=void 0)}hasPendingCommandRuns(e=this.commandRuns){return e.some(II)}async cancelCommandRun(e){if(!(!II(e)||this.cancellingRunIds.includes(e.id))){this.error=void 0,this.cancellingRunIds=[...this.cancellingRunIds,e.id];try{await lc.cancelCommandRun(e.id,this.machineId),await this.loadCommandRuns()}catch(e){this.error=e instanceof Error?e.message:String(e)}finally{this.cancellingRunIds=this.cancellingRunIds.filter(t=>t!==e.id)}}}async continueTerminal(e){if(!(this.workspace===void 0||this.continuingTerminalIds.includes(e))){this.error=void 0,this.continuingTerminalIds=[...this.continuingTerminalIds,e];try{let t=await lc.continueTerminal(this.workspace.projectId,this.workspace.id,e,this.machineId);this.terminals=this.terminals.map(n=>n.id===e?t:n),this.socket===void 0&&this.disposeTerminalView(),this.fitAndNotify(),this.terminal?.focus()}catch(e){this.error=e instanceof Error?e.message:String(e)}finally{this.continuingTerminalIds=this.continuingTerminalIds.filter(t=>t!==e)}}}ensureTerminalView(){let e=this.workspace,t=this.terminalHostElement();if(!this.visible||this.terminal!==void 0||this.selectedId===void 0||t===void 0||e===void 0)return;let n=new se(VI(this)),r=new ce;n.loadAddon(r),n.open(t),this.terminal=n,this.fitAddon=r,this.resizeObserver=new ResizeObserver(()=>{this.fitAndNotify()}),this.resizeObserver.observe(t),n.onData(e=>{this.suppressTerminalInput||this.copySnapshot!==void 0||this.sendTerminalInput(e)});let i=this.fitTerminal();this.connectSocket(e.projectId,e.id,this.selectedId,n,i),requestAnimationFrame(()=>{this.fitAndNotify()}),n.focus()}connectSocket(e,t,n,r,i){let a=vc(e,t,n,i,this.machineId);a.binaryType=`arraybuffer`,this.socket=a,a.addEventListener(`open`,()=>{this.socket===a&&(this.terminalReconnectDelay=OI,this.fitAndNotify())}),a.addEventListener(`message`,e=>{this.handleSocketMessage(e.data,n,r)}),a.addEventListener(`close`,()=>{if(this.socket!==a||(this.socket=void 0,this.terminals.some(e=>e.id===n&&e.exited)))return;this.terminalReconnectTimer!==void 0&&window.clearTimeout(this.terminalReconnectTimer);let o=this.terminalReconnectDelay;this.terminalReconnectDelay=Math.min(this.terminalReconnectDelay*AI,kI),this.terminalReconnectTimer=window.setTimeout(()=>{this.terminalReconnectTimer=void 0,!(this.socket!==void 0||this.terminals.some(e=>e.id===n&&e.exited))&&this.connectSocket(e,t,n,r,i)},o)})}async handleSocketMessage(e,t,n){try{let r=RI(await BI(e));r.type===`output`&&this.writeTerminalOutput(n,r.data,r.replay===!0),r.type===`exit`&&(n.writeln(`\r\n[process exited${r.exitCode===void 0?``:` with code ${String(r.exitCode)}`}]`),this.terminals=this.terminals.map(e=>e.id===t?{...e,exited:!0,...r.exitCode===void 0?{}:{exitCode:r.exitCode}}:e),this.loadCommandRuns()),r.type===`error`&&n.writeln(`\r\n[terminal error: ${r.message}]`)}catch(e){n.writeln(`\r\n[terminal error: ${e instanceof Error?e.message:String(e)}]`)}}writeTerminalOutput(e,t,n){if(!n){e.write(t);return}this.suppressTerminalInput=!0,e.reset(),e.write(`\x1Bc`+t,()=>{this.suppressTerminalInput=!1})}fitAndNotify(){let e=this.fitTerminal();e!==void 0&&this.send({type:`resize`,...e})}fitTerminal(){if(this.fitAddon===void 0||this.terminal===void 0)return;let e=KI(this.fitAddon.proposeDimensions());if(e!==void 0)return this.fitAddon.fit(),e}measureTerminalSize(){let e=this.fitTerminal();if(e!==void 0)return e;let t=this.terminalHostElement();if(this.terminal!==void 0||t===void 0)return;let n=new se(VI(this)),r=new ce;n.loadAddon(r),n.open(t);let i=KI(r.proposeDimensions());return n.dispose(),i}terminalHostElement(){let e=this.terminalHost;return e instanceof HTMLDivElement?e:void 0}applyTerminalTheme(){this.syncTerminalBackground(),this.terminal!==void 0&&(this.terminal.options.theme=HI(this))}syncTerminalBackground(){let e=WI(this.bgOpacity),t=GI(UI(this,`--pi-terminal-bg`,`#05070a`),e);this.style.setProperty(jI,t),this.style.setProperty(MI,`${String(e)}%`)}sendTerminalInput(e){let t=zI(e);t!==``&&this.send({type:`input`,data:t})}sendSoftKeyInput(e,t){this.copySnapshot===void 0&&(this.sendTerminalInput(e),t.refocus&&this.focusTerminal())}focusTerminal(){let e=this.terminal;e!==void 0&&(e.focus(),requestAnimationFrame(()=>{e.focus()}))}send(e){this.socket?.readyState===WebSocket.OPEN&&(this.socket.send(JSON.stringify(e)),e.type===`input`&&this.onInput?.())}disposeTerminalView(){this.resizeObserver?.disconnect(),this.resizeObserver=void 0,this.terminalReconnectTimer!==void 0&&(window.clearTimeout(this.terminalReconnectTimer),this.terminalReconnectTimer=void 0),this.terminalReconnectDelay=OI;let e=this.socket;this.socket=void 0,e?.close(),this.terminal?.dispose(),this.terminal=void 0,this.fitAddon=void 0,this.copySnapshot=void 0,this.copyStatus=void 0}renderCommandRunNotice(){let e=this.selectedCommandRun();if(e===void 0)return null;let t=this.selectedTerminalInfo();if(II(e)){let t=this.cancellingRunIds.includes(e.id);return g`
|
|
6326
|
+
`}};H([x({attribute:!1})],CI.prototype,`modes`,void 0),H([x({type:Boolean})],CI.prototype,`refocusOnClick`,void 0),H([x({attribute:!1})],CI.prototype,`onInput`,void 0),CI=H([b(`terminal-soft-keys`)],CI);function wI(e,t){return Math.hypot(t.clientX-e.clientX,t.clientY-e.clientY)>xI}var TI=ue({TerminalPanel:()=>Z,filterTerminalInput:()=>BI,terminalBackgroundWithOpacity:()=>KI}),EI={allowTransparency:!0,cursorBlink:!0,convertEol:!0,fontFamily:`ui-monospace, SFMono-Regular, Menlo, Consolas, monospace`,fontSize:13},DI={cols:100,rows:30},OI=1e3,kI=500,AI=5e3,jI=1.6,MI=`--pi-terminal-effective-bg`,NI=`--pi-terminal-ui-opacity`,Z=class extends y{constructor(...e){super(...e),this.machineId=`local`,this.autoStart=!1,this.fontSize=13,this.bgOpacity=100,this.onSelectTerminal=()=>void 0,this.terminals=[],this.commandRuns=[],this.loading=!1,this.visible=!1,this.cancellingRunIds=[],this.continuingTerminalIds=[],this.defaultSoftKeysEnvironment=!1,this.softKeysEnabled=lI(),this.suppressTerminalInput=!1,this.terminalReconnectDelay=kI,this.softKeysDefaultEnvironmentMedia=sI(),this.softKeysPreferenceStored=uI(),this.onSoftKeysDefaultEnvironmentChange=()=>{this.syncDefaultSoftKeysEnvironment()}}connectedCallback(){super.connectedCallback(),this.syncTerminalBackground(),this.syncDefaultSoftKeysEnvironment(),this.softKeysDefaultEnvironmentMedia?.addEventListener(`change`,this.onSoftKeysDefaultEnvironmentChange),this.themeObserver=new MutationObserver(()=>{this.applyTerminalTheme()}),this.themeObserver.observe(document.documentElement,{attributes:!0,attributeFilter:[`class`,`style`,`data-theme`]})}firstUpdated(){this.intersectionObserver=new IntersectionObserver(e=>{this.visible=e[0]?.isIntersecting===!0}),this.intersectionObserver.observe(this)}disconnectedCallback(){this.intersectionObserver?.disconnect(),this.intersectionObserver=void 0,this.themeObserver?.disconnect(),this.themeObserver=void 0,this.softKeysDefaultEnvironmentMedia?.removeEventListener(`change`,this.onSoftKeysDefaultEnvironmentChange),this.updateCommandRunPolling(!1),this.disposeTerminalView(),super.disconnectedCallback()}syncDefaultSoftKeysEnvironment(){let e=cI(this.softKeysDefaultEnvironmentMedia),t=this.softKeysEnabled;this.defaultSoftKeysEnvironment=e,this.softKeysPreferenceStored||(this.softKeysEnabled=e),this.softKeysEnabled!==t&&this.scheduleFitAndNotify()}scheduleFitAndNotify(){this.updateComplete.then(()=>{this.fitAndNotify()})}willUpdate(e){e.has(`bgOpacity`)&&this.syncTerminalBackground();let t=this.workspace===void 0?void 0:JSON.stringify([this.machineId,this.workspace.path]);if(t!==this.observedWorkspaceScope){this.observedWorkspaceScope=t,this.loadedCwd=void 0,this.autoStartConsumedCwd=void 0,this.terminals=[],this.commandRuns=[],this.selectedId=void 0,this.cancellingRunIds=[],this.continuingTerminalIds=[],this.updateCommandRunPolling(!1),this.disposeTerminalView();return}if(e.has(`selectedTerminalId`)){if(e.get(`selectedTerminalId`)!==void 0&&this.selectedTerminalId===void 0){this.loadedCwd=void 0,this.selectTerminalIdInView(void 0);return}this.applyRequestedTerminalSelection()}}updated(e){this.visible?this.hasPendingCommandRuns()&&this.updateCommandRunPolling(!0):this.updateCommandRunPolling(!1),this.loadVisibleWorkspaceTerminals(),e.has(`selectedTerminalId`)&&this.shouldReloadForRequestedTerminal()&&this.loadTerminals(),e.has(`fontSize`)&&this.terminal!==void 0&&(this.terminal.options.fontSize=this.fontSize,this.fitAndNotify()),e.has(`bgOpacity`)&&this.applyTerminalTheme(),this.ensureTerminalView()}loadVisibleWorkspaceTerminals(){let e=this.workspace?.path;!this.visible||e===void 0||e===this.loadedCwd||(this.loadedCwd=e,this.loadTerminals())}async loadTerminals(){this.loading=!0,this.error=void 0;try{let e=this.workspace;if(e===void 0)return;let t=this.consumeAutoStart(),[n,r]=await Promise.all([lc.terminals(e.projectId,e.id,this.machineId),lc.listCommandRuns({projectId:e.projectId,workspaceId:e.id},this.machineId)]);this.terminals=n,this.commandRuns=r,this.selectPreferredLoadedTerminal({replaceUrl:!0}),this.updateCommandRunPolling(this.hasPendingCommandRuns(r)),n.length===0&&t&&await this.startTerminal()}catch(e){this.error=e instanceof Error?e.message:String(e)}finally{this.loading=!1}}applyRequestedTerminalSelection(){this.selectedTerminalId!==void 0&&!this.terminals.some(e=>e.id===this.selectedTerminalId)||this.selectPreferredLoadedTerminal({replaceUrl:!0})}consumeAutoStart(){let e=this.workspace?.path;return!this.autoStart||e===void 0||this.autoStartConsumedCwd===e?!1:(this.autoStartConsumedCwd=e,!0)}shouldReloadForRequestedTerminal(){let e=this.workspace?.path;return this.visible&&e!==void 0&&e===this.loadedCwd&&this.selectedTerminalId!==void 0&&!this.loading&&!this.terminals.some(e=>e.id===this.selectedTerminalId)}selectPreferredLoadedTerminal(e){let t=K_(this.terminals,{targetTerminalId:this.selectedTerminalId});t===void 0&&this.selectedTerminalId!==void 0&&(t=q_(this.terminals)),this.selectTerminalIdInView(t?.id),(t?.id!==this.selectedTerminalId||t===void 0&&this.selectedTerminalId!==void 0)&&this.onSelectTerminal(t?.id,{replace:e?.replaceUrl===!0})}selectTerminalIdInView(e){this.selectedId!==e&&(this.selectedId=e,this.disposeTerminalView())}async startTerminal(){let e=this.workspace;if(e===void 0)return;let t=this.machineId,n=this.onStarted;this.error=void 0;try{let r=this.measureTerminalSize()??DI,i=await lc.startTerminal(e.projectId,e.id,r,t);this.terminals=[...this.terminals,i],this.selectTerminal(i.id),n?.()}catch(e){this.error=e instanceof Error?e.message:String(e)}}async closeTerminal(e,t){t.stopPropagation();try{if(this.workspace===void 0)return;await lc.closeTerminal(this.workspace.projectId,this.workspace.id,e,this.machineId);let t=this.terminals.filter(t=>t.id!==e);if(this.terminals=t,this.selectedId===e||this.selectedTerminalId===e){let e=q_(t)?.id;this.selectTerminalIdInView(e),this.onSelectTerminal(e,{replace:!0})}}catch(e){this.error=e instanceof Error?e.message:String(e)}}selectTerminal(e){this.selectedId!==e&&this.selectTerminalIdInView(e),this.onSelectTerminal(e)}selectedTerminalInfo(){return this.terminals.find(e=>e.id===this.selectedId)}selectedCommandRun(){let e=this.selectedTerminalInfo()?.commandRunId;if(e!==void 0)return this.commandRuns.find(t=>t.id===e)}async loadCommandRuns(){let e=this.workspace;if(e!==void 0)try{let t=await lc.listCommandRuns({projectId:e.projectId,workspaceId:e.id},this.machineId);this.commandRuns=t,this.cancellingRunIds=this.cancellingRunIds.filter(e=>t.some(t=>t.id===e&&LI(t))),this.updateCommandRunPolling(this.hasPendingCommandRuns(t))}catch(e){this.error=e instanceof Error?e.message:String(e)}}updateCommandRunPolling(e){if(e&&this.commandRunPollTimer===void 0){this.commandRunPollTimer=window.setInterval(()=>{this.loadCommandRuns()},OI);return}!e&&this.commandRunPollTimer!==void 0&&(window.clearInterval(this.commandRunPollTimer),this.commandRunPollTimer=void 0)}hasPendingCommandRuns(e=this.commandRuns){return e.some(LI)}async cancelCommandRun(e){if(!(!LI(e)||this.cancellingRunIds.includes(e.id))){this.error=void 0,this.cancellingRunIds=[...this.cancellingRunIds,e.id];try{await lc.cancelCommandRun(e.id,this.machineId),await this.loadCommandRuns()}catch(e){this.error=e instanceof Error?e.message:String(e)}finally{this.cancellingRunIds=this.cancellingRunIds.filter(t=>t!==e.id)}}}async continueTerminal(e){if(!(this.workspace===void 0||this.continuingTerminalIds.includes(e))){this.error=void 0,this.continuingTerminalIds=[...this.continuingTerminalIds,e];try{let t=await lc.continueTerminal(this.workspace.projectId,this.workspace.id,e,this.machineId);this.terminals=this.terminals.map(n=>n.id===e?t:n),this.socket===void 0&&this.disposeTerminalView(),this.fitAndNotify(),this.terminal?.focus()}catch(e){this.error=e instanceof Error?e.message:String(e)}finally{this.continuingTerminalIds=this.continuingTerminalIds.filter(t=>t!==e)}}}ensureTerminalView(){let e=this.workspace,t=this.terminalHostElement();if(!this.visible||this.terminal!==void 0||this.selectedId===void 0||t===void 0||e===void 0)return;let n=new se(HI(this)),r=new ce;n.loadAddon(r),n.open(t),this.terminal=n,this.fitAddon=r,this.resizeObserver=new ResizeObserver(()=>{this.fitAndNotify()}),this.resizeObserver.observe(t),n.onData(e=>{this.suppressTerminalInput||this.copySnapshot!==void 0||this.sendTerminalInput(e)});let i=this.fitTerminal();this.connectSocket(e.projectId,e.id,this.selectedId,n,i),requestAnimationFrame(()=>{this.fitAndNotify()}),n.focus()}connectSocket(e,t,n,r,i){let a=vc(e,t,n,i,this.machineId);a.binaryType=`arraybuffer`,this.socket=a,a.addEventListener(`open`,()=>{this.socket===a&&(this.terminalReconnectDelay=kI,this.fitAndNotify())}),a.addEventListener(`message`,e=>{this.handleSocketMessage(e.data,n,r)}),a.addEventListener(`close`,()=>{if(this.socket!==a||(this.socket=void 0,this.terminals.some(e=>e.id===n&&e.exited)))return;this.terminalReconnectTimer!==void 0&&window.clearTimeout(this.terminalReconnectTimer);let o=this.terminalReconnectDelay;this.terminalReconnectDelay=Math.min(this.terminalReconnectDelay*jI,AI),this.terminalReconnectTimer=window.setTimeout(()=>{this.terminalReconnectTimer=void 0,!(this.socket!==void 0||this.terminals.some(e=>e.id===n&&e.exited))&&this.connectSocket(e,t,n,r,i)},o)})}async handleSocketMessage(e,t,n){try{let r=zI(await VI(e));r.type===`output`&&this.writeTerminalOutput(n,r.data,r.replay===!0),r.type===`exit`&&(n.writeln(`\r\n[process exited${r.exitCode===void 0?``:` with code ${String(r.exitCode)}`}]`),this.terminals=this.terminals.map(e=>e.id===t?{...e,exited:!0,...r.exitCode===void 0?{}:{exitCode:r.exitCode}}:e),this.loadCommandRuns()),r.type===`error`&&n.writeln(`\r\n[terminal error: ${r.message}]`)}catch(e){n.writeln(`\r\n[terminal error: ${e instanceof Error?e.message:String(e)}]`)}}writeTerminalOutput(e,t,n){if(!n){e.write(t);return}this.suppressTerminalInput=!0,e.reset(),e.write(`\x1Bc`+t,()=>{this.suppressTerminalInput=!1})}fitAndNotify(){let e=this.fitTerminal();e!==void 0&&this.send({type:`resize`,...e})}fitTerminal(){if(this.fitAddon===void 0||this.terminal===void 0)return;let e=qI(this.fitAddon.proposeDimensions());if(e!==void 0)return this.fitAddon.fit(),e}measureTerminalSize(){let e=this.fitTerminal();if(e!==void 0)return e;let t=this.terminalHostElement();if(this.terminal!==void 0||t===void 0)return;let n=new se(HI(this)),r=new ce;n.loadAddon(r),n.open(t);let i=qI(r.proposeDimensions());return n.dispose(),i}terminalHostElement(){let e=this.terminalHost;return e instanceof HTMLDivElement?e:void 0}applyTerminalTheme(){this.syncTerminalBackground(),this.terminal!==void 0&&(this.terminal.options.theme=UI(this))}syncTerminalBackground(){let e=GI(this.bgOpacity),t=KI(WI(this,`--pi-terminal-bg`,`#05070a`),e);this.style.setProperty(MI,t),this.style.setProperty(NI,`${String(e)}%`)}sendTerminalInput(e){let t=BI(e);t!==``&&this.send({type:`input`,data:t})}sendSoftKeyInput(e,t){this.copySnapshot===void 0&&(this.sendTerminalInput(e),t.refocus&&this.focusTerminal())}focusTerminal(){let e=this.terminal;e!==void 0&&(e.focus(),requestAnimationFrame(()=>{e.focus()}))}send(e){this.socket?.readyState===WebSocket.OPEN&&(this.socket.send(JSON.stringify(e)),e.type===`input`&&this.onInput?.())}disposeTerminalView(){this.resizeObserver?.disconnect(),this.resizeObserver=void 0,this.terminalReconnectTimer!==void 0&&(window.clearTimeout(this.terminalReconnectTimer),this.terminalReconnectTimer=void 0),this.terminalReconnectDelay=kI;let e=this.socket;this.socket=void 0,e?.close(),this.terminal?.dispose(),this.terminal=void 0,this.fitAddon=void 0,this.copySnapshot=void 0,this.copyStatus=void 0}renderCommandRunNotice(){let e=this.selectedCommandRun();if(e===void 0)return null;let t=this.selectedTerminalInfo();if(LI(e)){let t=this.cancellingRunIds.includes(e.id);return g`
|
|
6327
6327
|
<section class="command-run-notice running">
|
|
6328
6328
|
<div>
|
|
6329
6329
|
<strong>${e.title}</strong>
|
|
@@ -6335,13 +6335,13 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
6335
6335
|
`}if(t?.exited===!0){let n=this.continuingTerminalIds.includes(t.id);return g`
|
|
6336
6336
|
<section class=${`command-run-notice ${e.status}`}>
|
|
6337
6337
|
<div>
|
|
6338
|
-
<strong>${
|
|
6338
|
+
<strong>${RI(e)}</strong>
|
|
6339
6339
|
<p>Output is preserved. Continue in a shell to inspect or run follow-up commands.</p>
|
|
6340
6340
|
<code>${e.command}</code>
|
|
6341
6341
|
</div>
|
|
6342
6342
|
<button ?disabled=${n} @click=${()=>{this.continueTerminal(t.id)}}>${n?`Starting shell…`:`Continue in shell`}</button>
|
|
6343
6343
|
</section>
|
|
6344
|
-
`}return null}enterCopyMode(){this.copySnapshot===void 0&&this.captureCopySnapshot()}refreshCopyMode(){this.copySnapshot!==void 0&&this.captureCopySnapshot()}captureCopySnapshot(){let e=this.terminal;if(e===void 0)return;let t=
|
|
6344
|
+
`}return null}enterCopyMode(){this.copySnapshot===void 0&&this.captureCopySnapshot()}refreshCopyMode(){this.copySnapshot!==void 0&&this.captureCopySnapshot()}captureCopySnapshot(){let e=this.terminal;if(e===void 0)return;let t=KF(e.buffer.active,e.cols,{theme:e.options.theme,drawBoldTextInBrightColors:e.options.drawBoldTextInBrightColors});this.copySnapshot=t,this.copyStatus=void 0,e.blur(),this.updateComplete.then(()=>{let n=this.terminalCopySelector;if(n==null)return;let r=Math.max(0,t.physicalLineCount-e.rows),i=Math.min(r,t.viewportLine);n.scrollTop=(r===0?0:i/r)*Math.max(0,n.scrollHeight-n.clientHeight),this.syncCopySnapshotScroll()})}exitCopyMode(){this.copySnapshot!==void 0&&(this.copySnapshot=void 0,this.copyStatus=void 0)}syncCopySnapshotScroll(){let e=this.terminalCopySelector,t=this.terminalCopyContent;if(e==null||t==null)return;let n=Math.max(0,e.scrollHeight-e.clientHeight),r=Math.max(0,t.scrollHeight-t.clientHeight),i=Math.max(0,e.scrollWidth-e.clientWidth),a=Math.max(0,t.scrollWidth-t.clientWidth);t.scrollTop=PI(e.scrollTop,n,r),t.scrollLeft=PI(e.scrollLeft,i,a)}async copyAllSnapshotText(){let e=this.copySnapshot?.text??``;if(e===``){this.copyStatus=`No terminal output to copy.`;return}this.copyStatus=await pE(e)?`Copied all terminal output.`:`Unable to copy terminal output.`}renderCopyModeToggle(){if(this.selectedId===void 0)return null;let e=this.copySnapshot!==void 0;return g`
|
|
6345
6345
|
<button
|
|
6346
6346
|
type="button"
|
|
6347
6347
|
class=${e?`copy-mode-toggle selected`:`copy-mode-toggle`}
|
|
@@ -6364,7 +6364,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
6364
6364
|
${this.copyToolbarReplacesSoftKeys()?null:this.renderCopyModeToolbar()}
|
|
6365
6365
|
<div class="terminal-copy-layers">
|
|
6366
6366
|
<pre class="terminal-copy-content" aria-hidden="true">${e.lines.map((e,t)=>g`${t===0?null:`
|
|
6367
|
-
`}${e.runs.map(e=>g`<span style=${
|
|
6367
|
+
`}${e.runs.map(e=>g`<span style=${BF(II(e.style))}>${e.text}</span>`)}`)}</pre>
|
|
6368
6368
|
<textarea
|
|
6369
6369
|
class="terminal-copy-selector"
|
|
6370
6370
|
readonly
|
|
@@ -6379,7 +6379,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
6379
6379
|
></textarea>
|
|
6380
6380
|
</div>
|
|
6381
6381
|
</section>
|
|
6382
|
-
`}selectedTerminalAcceptsInput(){let e=this.selectedTerminalInfo();return e!==void 0&&!e.exited}copyToolbarReplacesSoftKeys(){return this.copySnapshot!==void 0&&this.selectedTerminalAcceptsInput()&&this.softKeysEnabled}renderTerminalAccessoryBar(){return this.copySnapshot===void 0?this.shouldShowSoftKeys()?this.renderSoftKeys():null:this.copyToolbarReplacesSoftKeys()?this.renderCopyModeToolbar():null}shouldShowSoftKeys(){return this.selectedTerminalAcceptsInput()&&this.softKeysEnabled}shouldShowSoftKeysToggle(){return this.copySnapshot===void 0&&this.selectedTerminalAcceptsInput()}toggleSoftKeys(){this.copySnapshot===void 0&&(this.softKeysEnabled=!this.softKeysEnabled,this.softKeysPreferenceStored=!0,
|
|
6382
|
+
`}selectedTerminalAcceptsInput(){let e=this.selectedTerminalInfo();return e!==void 0&&!e.exited}copyToolbarReplacesSoftKeys(){return this.copySnapshot!==void 0&&this.selectedTerminalAcceptsInput()&&this.softKeysEnabled}renderTerminalAccessoryBar(){return this.copySnapshot===void 0?this.shouldShowSoftKeys()?this.renderSoftKeys():null:this.copyToolbarReplacesSoftKeys()?this.renderCopyModeToolbar():null}shouldShowSoftKeys(){return this.selectedTerminalAcceptsInput()&&this.softKeysEnabled}shouldShowSoftKeysToggle(){return this.copySnapshot===void 0&&this.selectedTerminalAcceptsInput()}toggleSoftKeys(){this.copySnapshot===void 0&&(this.softKeysEnabled=!this.softKeysEnabled,this.softKeysPreferenceStored=!0,fI(this.softKeysEnabled),this.scheduleFitAndNotify())}renderSoftKeysToggle(){return this.shouldShowSoftKeysToggle()?g`
|
|
6383
6383
|
<button
|
|
6384
6384
|
type="button"
|
|
6385
6385
|
class=${this.softKeysEnabled?`soft-keys-toggle selected`:`soft-keys-toggle`}
|
|
@@ -6500,32 +6500,32 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
6500
6500
|
.error { flex: 0 0 auto; margin: 0; padding: 8px; color: var(--pi-danger); border-bottom: 1px solid var(--pi-border); background: color-mix(in srgb, var(--pi-surface) var(--pi-terminal-ui-opacity, 100%), transparent); }
|
|
6501
6501
|
.muted { margin: 10px; color: var(--pi-muted); }
|
|
6502
6502
|
.xterm { height: 100%; }
|
|
6503
|
-
`}};H([x({attribute:!1})],Z.prototype,`workspace`,void 0),H([x()],Z.prototype,`machineId`,void 0),H([x({attribute:!1})],Z.prototype,`selectedTerminalId`,void 0),H([x({type:Boolean})],Z.prototype,`autoStart`,void 0),H([x({type:Number})],Z.prototype,`fontSize`,void 0),H([x({type:Number})],Z.prototype,`bgOpacity`,void 0),H([x({attribute:!1})],Z.prototype,`onSelectTerminal`,void 0),H([x({attribute:!1})],Z.prototype,`onStarted`,void 0),H([x({attribute:!1})],Z.prototype,`onInput`,void 0),H([C(`.terminal-host`)],Z.prototype,`terminalHost`,void 0),H([C(`.terminal-copy-content`)],Z.prototype,`terminalCopyContent`,void 0),H([C(`.terminal-copy-selector`)],Z.prototype,`terminalCopySelector`,void 0),H([S()],Z.prototype,`terminals`,void 0),H([S()],Z.prototype,`commandRuns`,void 0),H([S()],Z.prototype,`selectedId`,void 0),H([S()],Z.prototype,`loading`,void 0),H([S()],Z.prototype,`error`,void 0),H([S()],Z.prototype,`visible`,void 0),H([S()],Z.prototype,`cancellingRunIds`,void 0),H([S()],Z.prototype,`continuingTerminalIds`,void 0),H([S()],Z.prototype,`defaultSoftKeysEnvironment`,void 0),H([S()],Z.prototype,`softKeysEnabled`,void 0),H([S()],Z.prototype,`copySnapshot`,void 0),H([S()],Z.prototype,`copyStatus`,void 0),Z=H([b(`terminal-panel`)],Z);function
|
|
6503
|
+
`}};H([x({attribute:!1})],Z.prototype,`workspace`,void 0),H([x()],Z.prototype,`machineId`,void 0),H([x({attribute:!1})],Z.prototype,`selectedTerminalId`,void 0),H([x({type:Boolean})],Z.prototype,`autoStart`,void 0),H([x({type:Number})],Z.prototype,`fontSize`,void 0),H([x({type:Number})],Z.prototype,`bgOpacity`,void 0),H([x({attribute:!1})],Z.prototype,`onSelectTerminal`,void 0),H([x({attribute:!1})],Z.prototype,`onStarted`,void 0),H([x({attribute:!1})],Z.prototype,`onInput`,void 0),H([C(`.terminal-host`)],Z.prototype,`terminalHost`,void 0),H([C(`.terminal-copy-content`)],Z.prototype,`terminalCopyContent`,void 0),H([C(`.terminal-copy-selector`)],Z.prototype,`terminalCopySelector`,void 0),H([S()],Z.prototype,`terminals`,void 0),H([S()],Z.prototype,`commandRuns`,void 0),H([S()],Z.prototype,`selectedId`,void 0),H([S()],Z.prototype,`loading`,void 0),H([S()],Z.prototype,`error`,void 0),H([S()],Z.prototype,`visible`,void 0),H([S()],Z.prototype,`cancellingRunIds`,void 0),H([S()],Z.prototype,`continuingTerminalIds`,void 0),H([S()],Z.prototype,`defaultSoftKeysEnvironment`,void 0),H([S()],Z.prototype,`softKeysEnabled`,void 0),H([S()],Z.prototype,`copySnapshot`,void 0),H([S()],Z.prototype,`copyStatus`,void 0),Z=H([b(`terminal-panel`)],Z);function PI(e,t,n){return t<=0||n<=0?0:Math.min(1,Math.max(0,e/t))*n}function FI(e){return/^#[\da-f]{6}$/i.test(e)?`${e}80`:`color-mix(in srgb, ${e} 50%, transparent)`}function II(e){let t=[e.underline?`underline`:void 0,e.strikethrough?`line-through`:void 0,e.overline?`overline`:void 0].filter(e=>e!==void 0).join(` `);return{color:e.invisible?`transparent`:e.dim?FI(e.foreground):e.foreground,backgroundColor:e.background,fontWeight:e.bold?`700`:void 0,fontStyle:e.italic?`italic`:void 0,textDecorationLine:t===``?void 0:t}}function LI(e){return e.status===`queued`||e.status===`running`}function RI(e){return e.status===`succeeded`?`Command succeeded${e.exitCode===void 0?``:` with exit code ${String(e.exitCode)}`}`:`Command failed${e.exitCode===void 0?``:` with exit code ${String(e.exitCode)}`}`}function zI(e){let t=JSON.parse(e);if(!YI(t))return{type:`error`,message:`Invalid terminal message`};let n=t;return n.type===`output`&&typeof n.data==`string`?{type:`output`,data:n.data,...typeof n.replay==`boolean`?{replay:n.replay}:{}}:n.type===`exit`?{type:`exit`,...typeof n.exitCode==`number`?{exitCode:n.exitCode}:{}}:n.type===`error`&&typeof n.message==`string`?{type:`error`,message:n.message}:{type:`error`,message:`Invalid terminal message`}}function BI(e){return e.replaceAll(`\x1B[I`,``).replaceAll(`\x1B[O`,``)}async function VI(e){return typeof e==`string`?e:e instanceof ArrayBuffer?new TextDecoder().decode(e):e instanceof Blob?await e.text():String(e)}function HI(e){let t=EI;return e instanceof Z?{...t,fontSize:e.fontSize,theme:UI(e)}:{...t,theme:UI(e)}}function UI(e){let t=KI(WI(e,`--pi-terminal-bg`,`#05070a`),e instanceof Z?e.bgOpacity:100);return{...GF,background:t,foreground:WI(e,`--pi-terminal-text`,`#e6edf3`),cursor:WI(e,`--pi-accent`,`#58a6ff`),selectionBackground:WI(e,`--pi-terminal-selection`,`#264f78`)}}function WI(e,t,n){let r=getComputedStyle(e).getPropertyValue(t).trim();return r===``?n:r}function GI(e){return Math.max(0,Math.min(100,e))}function KI(e,t){let n=GI(t)/100;if(n>=1||e===`transparent`)return e;let r=/^#([\da-f]{3}|[\da-f]{6})$/iu.exec(e);if(r===null)return e;let i=r[1]??``,[a=`00`,o=`00`,s=`00`]=i.length===3?[i.charAt(0).repeat(2),i.charAt(1).repeat(2),i.charAt(2).repeat(2)]:[i.slice(0,2),i.slice(2,4),i.slice(4,6)];return`rgba(${String(parseInt(a,16))}, ${String(parseInt(o,16))}, ${String(parseInt(s,16))}, ${String(n)})`}function qI(e){if(!(e===void 0||!JI(e.cols,e.rows)))return{cols:Math.floor(e.cols),rows:Math.floor(e.rows)}}function JI(e,t){return Number.isFinite(e)&&Number.isFinite(t)&&e>0&&t>0}function YI(e){return typeof e==`object`&&!!e}var XI=class extends y{constructor(...e){super(...e),this.machines=[],this.activityRailOpen=!1,this.canScrollLeft=!1,this.canScrollRight=!1,this.handleToggleActivityRail=e=>{e.stopPropagation();let t=e.currentTarget;typeof HTMLElement>`u`||!(t instanceof HTMLElement)||this.onToggleActivityRail?.(t)},this.onContextScroll=()=>{this.updateScrollState()}}disconnectedCallback(){this.contextItemsResizeObserver?.disconnect(),this.contextItemsResizeObserver=void 0,this.observedContextItems=void 0,super.disconnectedCallback()}firstUpdated(){this.observeContextItems(),this.updateScrollState()}updated(){this.observeContextItems(),this.updateScrollState()}render(){let e=ZI(this.machines),t=QI(this.machine),n=eL(this.project),r=nL(this.workspace),i=iL(this.session);return g`
|
|
6504
6504
|
<nav class=${this.contextBarClass()} aria-label="Current location">
|
|
6505
6505
|
<span class="context-bar-label">Location</span>
|
|
6506
6506
|
<ol class="context-items" @scroll=${this.onContextScroll}>
|
|
6507
6507
|
${e?g`
|
|
6508
6508
|
<li class="context-item">
|
|
6509
|
-
<button type="button" class=${this.machine===void 0?`context-chip empty`:`context-chip`} title=${
|
|
6509
|
+
<button type="button" class=${this.machine===void 0?`context-chip empty`:`context-chip`} title=${$I(this.machine)} aria-label=${`Machine: ${t}. Open machine selection.`} @click=${()=>{this.onOpenSection?.(`machines`)}}>
|
|
6510
6510
|
<span class="context-kind">Machine</span>
|
|
6511
6511
|
<span class="context-value">${t}</span>
|
|
6512
6512
|
</button>
|
|
6513
6513
|
</li>
|
|
6514
6514
|
`:null}
|
|
6515
6515
|
<li class="context-item">
|
|
6516
|
-
<button type="button" class=${this.project===void 0?`context-chip empty`:`context-chip`} title=${
|
|
6516
|
+
<button type="button" class=${this.project===void 0?`context-chip empty`:`context-chip`} title=${tL(this.project)} aria-label=${`Project: ${n}. Open project selection.`} @click=${()=>{this.onOpenSection?.(`projects`)}}>
|
|
6517
6517
|
<span class="context-kind">Project</span>
|
|
6518
6518
|
<span class="context-value">${n}</span>
|
|
6519
6519
|
</button>
|
|
6520
6520
|
</li>
|
|
6521
6521
|
<li class="context-item">
|
|
6522
|
-
<button type="button" class=${this.workspace===void 0?`context-chip empty`:`context-chip`} title=${
|
|
6522
|
+
<button type="button" class=${this.workspace===void 0?`context-chip empty`:`context-chip`} title=${rL(this.workspace)} aria-label=${`Workspace: ${r}. Open workspace selection.`} @click=${()=>{this.onOpenSection?.(`workspaces`)}}>
|
|
6523
6523
|
<span class="context-kind">Workspace</span>
|
|
6524
6524
|
<span class="context-value">${r}</span>
|
|
6525
6525
|
</button>
|
|
6526
6526
|
</li>
|
|
6527
6527
|
<li class="context-item">
|
|
6528
|
-
<button type="button" class=${this.session===void 0?`context-chip empty`:`context-chip`} title=${
|
|
6528
|
+
<button type="button" class=${this.session===void 0?`context-chip empty`:`context-chip`} title=${aL(this.session)} aria-label=${`Session: ${i}. Open session selection.`} @click=${()=>{this.onOpenSection?.(`sessions`)}}>
|
|
6529
6529
|
<span class="context-kind">Session</span>
|
|
6530
6530
|
<span class="context-value">${i}</span>
|
|
6531
6531
|
</button>
|
|
@@ -6573,7 +6573,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
6573
6573
|
.context-kind { display: none; }
|
|
6574
6574
|
.context-value { min-width: 0; overflow: visible; text-overflow: clip; white-space: nowrap; }
|
|
6575
6575
|
button { cursor: pointer; }
|
|
6576
|
-
`}};H([x({attribute:!1})],
|
|
6576
|
+
`}};H([x({attribute:!1})],XI.prototype,`machines`,void 0),H([x({attribute:!1})],XI.prototype,`machine`,void 0),H([x({attribute:!1})],XI.prototype,`project`,void 0),H([x({attribute:!1})],XI.prototype,`workspace`,void 0),H([x({attribute:!1})],XI.prototype,`session`,void 0),H([x({attribute:!1})],XI.prototype,`refreshControl`,void 0),H([x({attribute:!1})],XI.prototype,`onOpenSection`,void 0),H([x({attribute:!1})],XI.prototype,`onShowActions`,void 0),H([x({type:Boolean})],XI.prototype,`activityRailOpen`,void 0),H([x({attribute:!1})],XI.prototype,`onToggleActivityRail`,void 0),H([C(`.context-items`)],XI.prototype,`contextItems`,void 0),H([S()],XI.prototype,`canScrollLeft`,void 0),H([S()],XI.prototype,`canScrollRight`,void 0),XI=H([b(`app-context-bar`)],XI);function ZI(e){return e.length>1}function QI(e){return e===void 0?`No machine`:`${e.name}${e.kind===`remote`?` · remote`:``}`}function $I(e){return e===void 0?`No machine selected`:e.baseUrl??e.name}function eL(e){return e?.name??`No project`}function tL(e){return e===void 0?`No project selected`:`${e.name} — ${e.path}`}function nL(e){return e===void 0?`No workspace`:`${e.label}${e.isMain?` · main`:``} · ${e.path}`}function rL(e){return e===void 0?`No workspace selected`:`${e.label}${e.isMain?` · main`:``} — ${e.path}`}function iL(e){let t=e?.name?.trim(),n=e?.firstMessage.trim();return t!==void 0&&t!==``?t:n!==void 0&&n!==``?n:e===void 0?`No session`:Aw(e.id)}function aL(e){return e===void 0?`No session selected`:e.path}var oL=class extends y{constructor(...e){super(...e),this.tabs=[],this.selectedView=`chat`,this.canScrollLeft=!1,this.canScrollRight=!1,this.onMobileTabsScroll=()=>{this.updateScrollState()}}disconnectedCallback(){this.mobileTabsResizeObserver?.disconnect(),this.mobileTabsResizeObserver=void 0,this.observedMobileTabs=void 0,super.disconnectedCallback()}firstUpdated(){this.observeMobileTabs(),this.updateScrollState()}updated(){this.observeMobileTabs(),this.updateScrollState()}render(){let e=this.fallbackLabels();return g`
|
|
6577
6577
|
<div class=${this.frameClass()}>
|
|
6578
6578
|
<div class="mobile-tabs" @scroll=${this.onMobileTabsScroll}>
|
|
6579
6579
|
${this.tabs.map(t=>{let n=this.selectedView===t.id;return g`
|
|
@@ -6612,12 +6612,12 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
6612
6612
|
.tab-label { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0 0 0 0); clip-path: inset(50%); white-space: nowrap; border: 0; }
|
|
6613
6613
|
.tab-badge { min-width: 13px; padding: 0 4px; font-size: 10px; line-height: 13px; }
|
|
6614
6614
|
}
|
|
6615
|
-
`}};H([x({attribute:!1})],
|
|
6615
|
+
`}};H([x({attribute:!1})],oL.prototype,`tabs`,void 0),H([x({attribute:!1})],oL.prototype,`selectedView`,void 0),H([x({attribute:!1})],oL.prototype,`onSelect`,void 0),H([C(`.mobile-tabs`)],oL.prototype,`mobileTabs`,void 0),H([S()],oL.prototype,`canScrollLeft`,void 0),H([S()],oL.prototype,`canScrollRight`,void 0),oL=H([b(`app-mobile-main-tabs`)],oL);var sL=class extends y{constructor(...e){super(...e),this.machines=[],this.statuses={},this.activities={},this.open=!1,this.menuStyle=``,this.actionMenuStyle=``,this.onDocumentClick=e=>{e.composedPath().includes(this)||(this.open=!1,this.openActionsMachineId=void 0)}}connectedCallback(){super.connectedCallback(),document.addEventListener(`click`,this.onDocumentClick)}disconnectedCallback(){document.removeEventListener(`click`,this.onDocumentClick),super.disconnectedCallback()}updated(e){e.has(`machines`)&&this.open&&this.selectedMachine()===void 0&&(this.open=!1),e.has(`machines`)&&this.openActionsMachineId!==void 0&&!this.machines.some(e=>e.id===this.openActionsMachineId)&&(this.openActionsMachineId=void 0)}async focusSelectedOrFirst(){let e=this.switcherButton();return e!==null&&await this.openMenuAndFocusOption(e)}render(){let e=this.selectedMachine();if(e===void 0)return null;let t=cL(e,this.statuses),n=e.name;return g`
|
|
6616
6616
|
<div class="machine-switcher">
|
|
6617
6617
|
<button
|
|
6618
6618
|
type="button"
|
|
6619
6619
|
class="machine-switcher-button"
|
|
6620
|
-
title=${
|
|
6620
|
+
title=${uL(e)}
|
|
6621
6621
|
aria-label=${this.machineSwitcherAriaLabel(e)}
|
|
6622
6622
|
aria-expanded=${String(this.open)}
|
|
6623
6623
|
@click=${e=>{this.toggleMenu(e.currentTarget)}}
|
|
@@ -6628,7 +6628,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
6628
6628
|
<span class="machine-switcher-kicker">Machine</span>
|
|
6629
6629
|
<span class="machine-switcher-label">${n}</span>
|
|
6630
6630
|
</span>
|
|
6631
|
-
<span class=${`machine-status ${t}`}>${
|
|
6631
|
+
<span class=${`machine-status ${t}`}>${lL(t)}</span>
|
|
6632
6632
|
<span class="machine-chevron" aria-hidden="true">▾</span>
|
|
6633
6633
|
</button>
|
|
6634
6634
|
${this.open?g`
|
|
@@ -6637,18 +6637,18 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
6637
6637
|
</div>
|
|
6638
6638
|
`:null}
|
|
6639
6639
|
</div>
|
|
6640
|
-
`}renderMachineOption(e){let t=this.selected?.id===e.id,n=
|
|
6640
|
+
`}renderMachineOption(e){let t=this.selected?.id===e.id,n=cL(e,this.statuses),r=UC(e)&&this.onRemove!==void 0,i=this.openActionsMachineId===e.id;return g`
|
|
6641
6641
|
<div class=${`machine-option ${t?`selected`:``} ${r?``:`no-actions`}`}>
|
|
6642
6642
|
<button
|
|
6643
6643
|
type="button"
|
|
6644
6644
|
class="machine-option-main"
|
|
6645
|
-
title=${
|
|
6645
|
+
title=${uL(e)}
|
|
6646
6646
|
data-machine-id=${e.id}
|
|
6647
6647
|
@click=${()=>{this.select(e)}}
|
|
6648
6648
|
@keydown=${e=>{this.handleMachineOptionKeydown(e)}}
|
|
6649
6649
|
>
|
|
6650
6650
|
<span class="machine-option-name">${this.renderActivity(e)}<span>${e.name}</span></span>
|
|
6651
|
-
<small>${e.kind===`local`?`Local Pi WebUI`:e.baseUrl??`Remote Pi WebUI`} · ${
|
|
6651
|
+
<small>${e.kind===`local`?`Local Pi WebUI`:e.baseUrl??`Remote Pi WebUI`} · ${lL(n)}</small>
|
|
6652
6652
|
</button>
|
|
6653
6653
|
${r?g`
|
|
6654
6654
|
<div class="machine-option-actions">
|
|
@@ -6668,7 +6668,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
6668
6668
|
</div>
|
|
6669
6669
|
`:null}
|
|
6670
6670
|
</div>
|
|
6671
|
-
`}renderActivity(e){let t=
|
|
6671
|
+
`}renderActivity(e){let t=cL(e,this.statuses);if(t===`offline`||t===`error`)return;let n=qu(this.activities[e.id]);return EC(n,n===`terminal`?`Machine terminal active`:`Machine active`)}selectedMachine(){return this.selected??this.machines.find(e=>e.id===`local`)??this.machines[0]}machineSwitcherAriaLabel(e){return`Machine: ${e.name}. Switch machine.`}switcherButton(){return this.renderRoot.querySelector(`.machine-switcher-button`)}handleSwitcherButtonKeydown(e){if(e.key===`ArrowDown`||e.key===`ArrowUp`){e.preventDefault(),e.stopPropagation(),this.openMenuAndFocusOption(e.currentTarget);return}if(e.key===`ArrowRight`&&this.onFocusNextSection!==void 0){e.preventDefault(),e.stopPropagation(),this.onFocusNextSection();return}e.key===`Escape`&&this.onCancelKeyboardNavigation!==void 0&&(e.preventDefault(),e.stopPropagation(),this.onCancelKeyboardNavigation())}handleMachineOptionKeydown(e){if(e.key===`ArrowUp`){this.focusRelativeMachineOption(e.currentTarget,-1,e);return}if(e.key===`ArrowDown`){this.focusRelativeMachineOption(e.currentTarget,1,e);return}if(e.key===`Home`){this.focusIndexedMachineOption(0,e);return}if(e.key===`End`){this.focusIndexedMachineOption(-1,e);return}if(e.key===`ArrowRight`&&this.onFocusNextSection!==void 0){e.preventDefault(),e.stopPropagation(),this.open=!1,this.onFocusNextSection();return}(e.key===`ArrowLeft`||e.key===`Escape`)&&(e.preventDefault(),e.stopPropagation(),this.open=!1,this.updateComplete.then(()=>{this.focusSwitcherButton()}))}toggleMenu(e){this.menuStyle=dL(e),this.open=!this.open,this.openActionsMachineId=void 0}focusSwitcherButton(){let e=this.switcherButton();return e===null?!1:(e.focus(),!0)}async openMenuAndFocusOption(e){return this.menuStyle=dL(e),this.open=!0,this.openActionsMachineId=void 0,await this.updateComplete,this.focusSelectedMachineOption()}focusSelectedMachineOption(){let e=this.renderRoot.querySelector(`.machine-option.selected .machine-option-main`),t=this.machineOptionButtons()[0],n=e??t;return n===void 0?!1:(n.focus(),n.scrollIntoView({block:`nearest`}),!0)}focusRelativeMachineOption(e,t,n){n.preventDefault(),n.stopPropagation();let r=this.machineOptionButtons();if(r.length===0||!(e instanceof HTMLElement))return;let i=r.indexOf(e);i<0||this.focusMachineOptionAt(i+t)}focusIndexedMachineOption(e,t){t.preventDefault(),t.stopPropagation(),this.focusMachineOptionAt(e<0?this.machineOptionButtons().length-1:e)}focusMachineOptionAt(e){let t=this.machineOptionButtons(),n=t[Math.min(Math.max(e,0),t.length-1)];n?.focus(),n?.scrollIntoView({block:`nearest`})}machineOptionButtons(){return Array.from(this.renderRoot.querySelectorAll(`.machine-option-main`))}toggleActionsMenu(e,t){if(this.openActionsMachineId===e){this.openActionsMachineId=void 0;return}this.actionMenuStyle=SC(t,{constrainTo:`viewport`}),this.openActionsMachineId=e}select(e){this.open=!1,this.openActionsMachineId=void 0,this.onSelect?.(e)}removeMachine(e){this.open=!1,this.openActionsMachineId=void 0,this.onRemove?.(e)}static{this.styles=h`
|
|
6672
6672
|
:host { min-width: 0; display: block; }
|
|
6673
6673
|
.machine-switcher { min-width: 0; }
|
|
6674
6674
|
.machine-switcher-button { box-sizing: border-box; width: 100%; min-width: 0; display: flex; align-items: center; gap: 6px; border: 1px solid var(--pi-border); border-radius: 999px; background: var(--pi-surface); color: var(--pi-text); padding: 5px 8px; cursor: pointer; text-align: left; }
|
|
@@ -6701,10 +6701,10 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
6701
6701
|
.machine-option-actions-panel button:hover, .machine-option-actions-panel button:focus-visible { background: var(--pi-selection-bg); }
|
|
6702
6702
|
.machine-option-actions-panel button.danger:hover, .machine-option-actions-panel button.danger:focus-visible { background: color-mix(in srgb, var(--pi-danger) 14%, transparent); }
|
|
6703
6703
|
@keyframes pulse { 0%, 100% { opacity: .55; } 50% { opacity: 1; } }
|
|
6704
|
-
`}};H([x({attribute:!1})],
|
|
6704
|
+
`}};H([x({attribute:!1})],sL.prototype,`machines`,void 0),H([x({attribute:!1})],sL.prototype,`selected`,void 0),H([x({attribute:!1})],sL.prototype,`statuses`,void 0),H([x({attribute:!1})],sL.prototype,`activities`,void 0),H([x({attribute:!1})],sL.prototype,`onSelect`,void 0),H([x({attribute:!1})],sL.prototype,`onRemove`,void 0),H([x({attribute:!1})],sL.prototype,`onFocusNextSection`,void 0),H([x({attribute:!1})],sL.prototype,`onCancelKeyboardNavigation`,void 0),H([S()],sL.prototype,`open`,void 0),H([S()],sL.prototype,`menuStyle`,void 0),H([S()],sL.prototype,`openActionsMachineId`,void 0),H([S()],sL.prototype,`actionMenuStyle`,void 0),sL=H([b(`machine-switcher`)],sL);function cL(e,t){return t[e.id]?.status??e.status??`unknown`}function lL(e){return e===`online`?`online`:e===`offline`?`offline`:e===`error`?`error`:`unknown`}function uL(e){return e.baseUrl??e.name}function dL(e){if(typeof HTMLElement>`u`||typeof window>`u`||!(e instanceof HTMLElement))return``;let t=e.getBoundingClientRect(),n=Math.min(280,Math.max(0,window.innerWidth-16)),r=Math.min(Math.max(8,t.left),Math.max(8,window.innerWidth-8-n)),i=Math.max(0,window.innerHeight-t.bottom-8);return[`top: ${fL(t.bottom)};`,`left: ${fL(r)};`,`width: ${fL(n)};`,`max-height: ${fL(i)};`].join(` `)}function fL(e){return`${String(Math.round(e))}px`}var pL=[{id:`models`,label:`Models`},{id:`skills`,label:`Skills`},{id:`plugins`,label:`Plugins`}],Q=class extends y{constructor(...e){super(...e),this.machines=[],this.machineStatuses={},this.machineActivities={},this.projects=[],this.workspaces=[],this.sessions=[],this.projectSessions=[],this.workspaceActivities={},this.sessionActivities={},this.sessionStatuses={},this.sendingPrompts={},this.unreadSessionIds=new Set,this.workspacesByProjectId={},this.deletingWorkspaceIds=[],this.workspaceLabelItems=()=>[],this.collapsible=!1,this.compact=!1,this.machinesCollapsed=!1,this.projectsCollapsed=!1,this.workspacesCollapsed=!1,this.sessionsCollapsed=!1,this.startingSessionCount=0,this.canStartSession=!1,this.canDeleteArchivedSessions=!1,this.canReloadSessions=!1,this.canReorderSessions=!1,this.canCleanupSessions=!1,this.authoritativeSessionPersistence=!1,this.archivedDeleteUnavailableMessage=`Update and restart Pi-Web on this machine to delete archived sessions.`,this.cleanupUnavailableMessage=`Update and restart Pi-Web on this machine to clean up sessions.`,this.skillsEnabled=!1,this.pluginsEnabled=!1,this.projectStatisticsAvailable=!1}async focusSection(e){switch(await this.updateComplete,e){case`machines`:return await this.focusNavigableSection(this.compact?this.machineList:this.machineSwitcher);case`projects`:return await this.focusNavigableSection(this.projectList);case`workspaces`:return await this.focusNavigableSection(this.workspaceList);case`sessions`:return await this.focusNavigableSection(this.sessionList)}}render(){let e=this.version;return g`
|
|
6705
6705
|
<header>
|
|
6706
6706
|
<strong class="brand" aria-label=${e===void 0?`Pi WebUI`:`Pi WebUI version ${e}`}><span class="brand-symbol" aria-hidden="true">π</span><span>WebUI</span>${e===void 0?null:g`<span class="brand-version">v${e}</span>`}</strong>
|
|
6707
|
-
${
|
|
6707
|
+
${_L(this.machines)?g`
|
|
6708
6708
|
<machine-switcher
|
|
6709
6709
|
.machines=${this.machines}
|
|
6710
6710
|
.selected=${this.selectedMachine}
|
|
@@ -6721,7 +6721,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
6721
6721
|
<button title="Show Actions" aria-label="Show Actions" @click=${()=>{this.onShowActions?.()}}>Actions</button>
|
|
6722
6722
|
</div>
|
|
6723
6723
|
</header>
|
|
6724
|
-
${this.compact&&
|
|
6724
|
+
${this.compact&&_L(this.machines)?g`
|
|
6725
6725
|
<machine-list
|
|
6726
6726
|
.machines=${this.machines}
|
|
6727
6727
|
.selected=${this.selectedMachine}
|
|
@@ -6818,9 +6818,9 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
6818
6818
|
.onCancelKeyboardNavigation=${()=>{this.cancelKeyboardNavigation()}}
|
|
6819
6819
|
></session-list>
|
|
6820
6820
|
<footer class="resource-underbar" aria-label="Resources">
|
|
6821
|
-
${
|
|
6821
|
+
${pL.map(e=>mL(e,e.id===`models`?()=>{this.onOpenModels?.()}:e.id===`skills`?()=>{this.onOpenSkills?.()}:()=>{this.onOpenPlugins?.()},this.skillsEnabled,this.pluginsEnabled))}
|
|
6822
6822
|
</footer>
|
|
6823
|
-
`}async focusNavigableSection(e){return e!==void 0&&await e.focusSelectedOrFirst()}focusPreviousFrom(e){let t=
|
|
6823
|
+
`}async focusNavigableSection(e){return e!==void 0&&await e.focusSelectedOrFirst()}focusPreviousFrom(e){let t=vL(e,this.machines);t!==void 0&&this.onFocusNavigationTarget?.(t)}focusNextFrom(e){this.onFocusNavigationTarget?.(yL(e,this.machines))}cancelKeyboardNavigation(){this.onCancelKeyboardNavigation?.()}static{this.styles=h`
|
|
6824
6824
|
:host { display: flex; flex-direction: column; min-height: 0; overflow: hidden; }
|
|
6825
6825
|
:host([compact]) { flex: 1 1 auto; }
|
|
6826
6826
|
header { flex: 0 0 auto; display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 12px; border-bottom: 1px solid var(--pi-border); }
|
|
@@ -6852,12 +6852,12 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
6852
6852
|
:host([compact]) workspace-list[collapsed],
|
|
6853
6853
|
:host([compact]) session-list[collapsed] { flex: 0 0 auto; min-height: auto; overflow: hidden; }
|
|
6854
6854
|
button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
|
|
6855
|
-
`}};H([x({attribute:!1})],Q.prototype,`machines`,void 0),H([x({attribute:!1})],Q.prototype,`selectedMachine`,void 0),H([x({attribute:!1})],Q.prototype,`machineStatuses`,void 0),H([x({attribute:!1})],Q.prototype,`machineActivities`,void 0),H([x({attribute:!1})],Q.prototype,`projects`,void 0),H([x({attribute:!1})],Q.prototype,`selectedProject`,void 0),H([x({attribute:!1})],Q.prototype,`workspaces`,void 0),H([x({attribute:!1})],Q.prototype,`selectedWorkspace`,void 0),H([x({attribute:!1})],Q.prototype,`sessions`,void 0),H([x({attribute:!1})],Q.prototype,`projectSessions`,void 0),H([x({attribute:!1})],Q.prototype,`selectedSession`,void 0),H([x({attribute:!1})],Q.prototype,`workspaceActivities`,void 0),H([x({attribute:!1})],Q.prototype,`sessionActivities`,void 0),H([x({attribute:!1})],Q.prototype,`sessionStatuses`,void 0),H([x({attribute:!1})],Q.prototype,`sendingPrompts`,void 0),H([x({attribute:!1})],Q.prototype,`unreadSessionIds`,void 0),H([x({attribute:!1})],Q.prototype,`workspacesByProjectId`,void 0),H([x({attribute:!1})],Q.prototype,`deletingWorkspaceIds`,void 0),H([x({attribute:!1})],Q.prototype,`workspaceLabelItems`,void 0),H([x({type:String})],Q.prototype,`version`,void 0),H([x({attribute:!1})],Q.prototype,`refreshControl`,void 0),H([x({type:Boolean,reflect:!0})],Q.prototype,`collapsible`,void 0),H([x({type:Boolean,reflect:!0})],Q.prototype,`compact`,void 0),H([x({type:Boolean})],Q.prototype,`machinesCollapsed`,void 0),H([x({type:Boolean})],Q.prototype,`projectsCollapsed`,void 0),H([x({type:Boolean})],Q.prototype,`workspacesCollapsed`,void 0),H([x({type:Boolean})],Q.prototype,`sessionsCollapsed`,void 0),H([x({type:Number})],Q.prototype,`startingSessionCount`,void 0),H([x({type:Boolean})],Q.prototype,`canStartSession`,void 0),H([x({type:Boolean})],Q.prototype,`canDeleteArchivedSessions`,void 0),H([x({type:Boolean})],Q.prototype,`canReloadSessions`,void 0),H([x({type:Boolean})],Q.prototype,`canReorderSessions`,void 0),H([x({type:Boolean})],Q.prototype,`canCleanupSessions`,void 0),H([x({type:Boolean})],Q.prototype,`authoritativeSessionPersistence`,void 0),H([x({type:String})],Q.prototype,`archivedDeleteUnavailableMessage`,void 0),H([x({type:String})],Q.prototype,`cleanupUnavailableMessage`,void 0),H([x({attribute:!1})],Q.prototype,`onShowActions`,void 0),H([x({type:Boolean})],Q.prototype,`skillsEnabled`,void 0),H([x({type:Boolean})],Q.prototype,`pluginsEnabled`,void 0),H([x({attribute:!1})],Q.prototype,`onOpenModels`,void 0),H([x({attribute:!1})],Q.prototype,`onOpenSkills`,void 0),H([x({attribute:!1})],Q.prototype,`onOpenPlugins`,void 0),H([x({attribute:!1})],Q.prototype,`onToggleMachines`,void 0),H([x({attribute:!1})],Q.prototype,`onToggleProjects`,void 0),H([x({attribute:!1})],Q.prototype,`onToggleWorkspaces`,void 0),H([x({attribute:!1})],Q.prototype,`onToggleSessions`,void 0),H([x({attribute:!1})],Q.prototype,`onAddProject`,void 0),H([x({attribute:!1})],Q.prototype,`onOpenProjectBrowser`,void 0),H([x({attribute:!1})],Q.prototype,`onOpenSessionBrowser`,void 0),H([x({attribute:!1})],Q.prototype,`onSelectProject`,void 0),H([x({attribute:!1})],Q.prototype,`onCloseProject`,void 0),H([x({attribute:!1})],Q.prototype,`onCloseProjectTree`,void 0),H([x({attribute:!1})],Q.prototype,`onPinProject`,void 0),H([x({attribute:!1})],Q.prototype,`onUnpinProject`,void 0),H([x({attribute:!1})],Q.prototype,`onShowProjectStatistics`,void 0),H([x({type:Boolean})],Q.prototype,`projectStatisticsAvailable`,void 0),H([x({attribute:!1})],Q.prototype,`onSelectWorkspace`,void 0),H([x({attribute:!1})],Q.prototype,`onDeleteWorkspace`,void 0),H([x({attribute:!1})],Q.prototype,`onStartSession`,void 0),H([x({attribute:!1})],Q.prototype,`onSelectSession`,void 0),H([x({attribute:!1})],Q.prototype,`onRenameSessionStart`,void 0),H([x({attribute:!1})],Q.prototype,`onRenameSession`,void 0),H([x({attribute:!1})],Q.prototype,`onArchiveSession`,void 0),H([x({attribute:!1})],Q.prototype,`onArchiveSessionWithDescendants`,void 0),H([x({attribute:!1})],Q.prototype,`onArchiveSessions`,void 0),H([x({attribute:!1})],Q.prototype,`onRestoreSession`,void 0),H([x({attribute:!1})],Q.prototype,`onDeleteCachedNewSession`,void 0),H([x({attribute:!1})],Q.prototype,`onDeleteArchivedSession`,void 0),H([x({attribute:!1})],Q.prototype,`onDeleteArchivedSessions`,void 0),H([x({attribute:!1})],Q.prototype,`onDetachParentSession`,void 0),H([x({attribute:!1})],Q.prototype,`onReloadSession`,void 0),H([x({attribute:!1})],Q.prototype,`onReorderSession`,void 0),H([x({attribute:!1})],Q.prototype,`onPinSession`,void 0),H([x({attribute:!1})],Q.prototype,`onUnpinSession`,void 0),H([x({attribute:!1})],Q.prototype,`onCleanupSessions`,void 0),H([x({attribute:!1})],Q.prototype,`onArchivedCollapsed`,void 0),H([x({attribute:!1})],Q.prototype,`onSelectMachine`,void 0),H([x({attribute:!1})],Q.prototype,`onRemoveMachine`,void 0),H([x({attribute:!1})],Q.prototype,`onFocusNavigationTarget`,void 0),H([x({attribute:!1})],Q.prototype,`onCancelKeyboardNavigation`,void 0),H([C(`machine-list`)],Q.prototype,`machineList`,void 0),H([C(`machine-switcher`)],Q.prototype,`machineSwitcher`,void 0),H([C(`project-list`)],Q.prototype,`projectList`,void 0),H([C(`workspace-list`)],Q.prototype,`workspaceList`,void 0),H([C(`session-list`)],Q.prototype,`sessionList`,void 0),Q=H([b(`app-navigation-panel`)],Q);function
|
|
6856
|
-
<button type="button" ?disabled=${!
|
|
6857
|
-
${
|
|
6855
|
+
`}};H([x({attribute:!1})],Q.prototype,`machines`,void 0),H([x({attribute:!1})],Q.prototype,`selectedMachine`,void 0),H([x({attribute:!1})],Q.prototype,`machineStatuses`,void 0),H([x({attribute:!1})],Q.prototype,`machineActivities`,void 0),H([x({attribute:!1})],Q.prototype,`projects`,void 0),H([x({attribute:!1})],Q.prototype,`selectedProject`,void 0),H([x({attribute:!1})],Q.prototype,`workspaces`,void 0),H([x({attribute:!1})],Q.prototype,`selectedWorkspace`,void 0),H([x({attribute:!1})],Q.prototype,`sessions`,void 0),H([x({attribute:!1})],Q.prototype,`projectSessions`,void 0),H([x({attribute:!1})],Q.prototype,`selectedSession`,void 0),H([x({attribute:!1})],Q.prototype,`workspaceActivities`,void 0),H([x({attribute:!1})],Q.prototype,`sessionActivities`,void 0),H([x({attribute:!1})],Q.prototype,`sessionStatuses`,void 0),H([x({attribute:!1})],Q.prototype,`sendingPrompts`,void 0),H([x({attribute:!1})],Q.prototype,`unreadSessionIds`,void 0),H([x({attribute:!1})],Q.prototype,`workspacesByProjectId`,void 0),H([x({attribute:!1})],Q.prototype,`deletingWorkspaceIds`,void 0),H([x({attribute:!1})],Q.prototype,`workspaceLabelItems`,void 0),H([x({type:String})],Q.prototype,`version`,void 0),H([x({attribute:!1})],Q.prototype,`refreshControl`,void 0),H([x({type:Boolean,reflect:!0})],Q.prototype,`collapsible`,void 0),H([x({type:Boolean,reflect:!0})],Q.prototype,`compact`,void 0),H([x({type:Boolean})],Q.prototype,`machinesCollapsed`,void 0),H([x({type:Boolean})],Q.prototype,`projectsCollapsed`,void 0),H([x({type:Boolean})],Q.prototype,`workspacesCollapsed`,void 0),H([x({type:Boolean})],Q.prototype,`sessionsCollapsed`,void 0),H([x({type:Number})],Q.prototype,`startingSessionCount`,void 0),H([x({type:Boolean})],Q.prototype,`canStartSession`,void 0),H([x({type:Boolean})],Q.prototype,`canDeleteArchivedSessions`,void 0),H([x({type:Boolean})],Q.prototype,`canReloadSessions`,void 0),H([x({type:Boolean})],Q.prototype,`canReorderSessions`,void 0),H([x({type:Boolean})],Q.prototype,`canCleanupSessions`,void 0),H([x({type:Boolean})],Q.prototype,`authoritativeSessionPersistence`,void 0),H([x({type:String})],Q.prototype,`archivedDeleteUnavailableMessage`,void 0),H([x({type:String})],Q.prototype,`cleanupUnavailableMessage`,void 0),H([x({attribute:!1})],Q.prototype,`onShowActions`,void 0),H([x({type:Boolean})],Q.prototype,`skillsEnabled`,void 0),H([x({type:Boolean})],Q.prototype,`pluginsEnabled`,void 0),H([x({attribute:!1})],Q.prototype,`onOpenModels`,void 0),H([x({attribute:!1})],Q.prototype,`onOpenSkills`,void 0),H([x({attribute:!1})],Q.prototype,`onOpenPlugins`,void 0),H([x({attribute:!1})],Q.prototype,`onToggleMachines`,void 0),H([x({attribute:!1})],Q.prototype,`onToggleProjects`,void 0),H([x({attribute:!1})],Q.prototype,`onToggleWorkspaces`,void 0),H([x({attribute:!1})],Q.prototype,`onToggleSessions`,void 0),H([x({attribute:!1})],Q.prototype,`onAddProject`,void 0),H([x({attribute:!1})],Q.prototype,`onOpenProjectBrowser`,void 0),H([x({attribute:!1})],Q.prototype,`onOpenSessionBrowser`,void 0),H([x({attribute:!1})],Q.prototype,`onSelectProject`,void 0),H([x({attribute:!1})],Q.prototype,`onCloseProject`,void 0),H([x({attribute:!1})],Q.prototype,`onCloseProjectTree`,void 0),H([x({attribute:!1})],Q.prototype,`onPinProject`,void 0),H([x({attribute:!1})],Q.prototype,`onUnpinProject`,void 0),H([x({attribute:!1})],Q.prototype,`onShowProjectStatistics`,void 0),H([x({type:Boolean})],Q.prototype,`projectStatisticsAvailable`,void 0),H([x({attribute:!1})],Q.prototype,`onSelectWorkspace`,void 0),H([x({attribute:!1})],Q.prototype,`onDeleteWorkspace`,void 0),H([x({attribute:!1})],Q.prototype,`onStartSession`,void 0),H([x({attribute:!1})],Q.prototype,`onSelectSession`,void 0),H([x({attribute:!1})],Q.prototype,`onRenameSessionStart`,void 0),H([x({attribute:!1})],Q.prototype,`onRenameSession`,void 0),H([x({attribute:!1})],Q.prototype,`onArchiveSession`,void 0),H([x({attribute:!1})],Q.prototype,`onArchiveSessionWithDescendants`,void 0),H([x({attribute:!1})],Q.prototype,`onArchiveSessions`,void 0),H([x({attribute:!1})],Q.prototype,`onRestoreSession`,void 0),H([x({attribute:!1})],Q.prototype,`onDeleteCachedNewSession`,void 0),H([x({attribute:!1})],Q.prototype,`onDeleteArchivedSession`,void 0),H([x({attribute:!1})],Q.prototype,`onDeleteArchivedSessions`,void 0),H([x({attribute:!1})],Q.prototype,`onDetachParentSession`,void 0),H([x({attribute:!1})],Q.prototype,`onReloadSession`,void 0),H([x({attribute:!1})],Q.prototype,`onReorderSession`,void 0),H([x({attribute:!1})],Q.prototype,`onPinSession`,void 0),H([x({attribute:!1})],Q.prototype,`onUnpinSession`,void 0),H([x({attribute:!1})],Q.prototype,`onCleanupSessions`,void 0),H([x({attribute:!1})],Q.prototype,`onArchivedCollapsed`,void 0),H([x({attribute:!1})],Q.prototype,`onSelectMachine`,void 0),H([x({attribute:!1})],Q.prototype,`onRemoveMachine`,void 0),H([x({attribute:!1})],Q.prototype,`onFocusNavigationTarget`,void 0),H([x({attribute:!1})],Q.prototype,`onCancelKeyboardNavigation`,void 0),H([C(`machine-list`)],Q.prototype,`machineList`,void 0),H([C(`machine-switcher`)],Q.prototype,`machineSwitcher`,void 0),H([C(`project-list`)],Q.prototype,`projectList`,void 0),H([C(`workspace-list`)],Q.prototype,`workspaceList`,void 0),H([C(`session-list`)],Q.prototype,`sessionList`,void 0),Q=H([b(`app-navigation-panel`)],Q);function mL(e,t,n,r){return g`
|
|
6856
|
+
<button type="button" ?disabled=${!hL(e.id,n,r)} title=${e.label} aria-label=${e.label} @click=${t}>
|
|
6857
|
+
${gL(e.id)}
|
|
6858
6858
|
<span>${e.label}</span>
|
|
6859
6859
|
</button>
|
|
6860
|
-
`}function
|
|
6860
|
+
`}function hL(e,t=!1,n=t){return e===`models`||e===`skills`&&t||e===`plugins`&&n}function gL(e){switch(e){case`models`:return _`
|
|
6861
6861
|
<svg class="resource-underbar-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
6862
6862
|
<rect x="4" y="4" width="16" height="16" rx="2"></rect>
|
|
6863
6863
|
<rect x="9" y="9" width="6" height="6"></rect>
|
|
@@ -6875,7 +6875,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
6875
6875
|
<path d="M6 13V8a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v5a6 6 0 0 1-12 0Z"></path>
|
|
6876
6876
|
<path d="M12 19v3"></path>
|
|
6877
6877
|
</svg>
|
|
6878
|
-
`}}function
|
|
6878
|
+
`}}function _L(e){return e.length>1}function vL(e,t){let n=bL(t);return n[n.indexOf(e)-1]}function yL(e,t){let n=bL(t);return n[n.indexOf(e)+1]??`chat`}function bL(e){return Zx.filter(t=>t!==`machines`||_L(e))}var xL=new Set([`ArrowLeft`,`ArrowRight`,`Home`,`End`]),SL=420,CL=4,wL=class extends y{constructor(...e){super(...e),this.side=`navigation`,this.collapsed=!1,this.resizable=!1,this.controls=``,this.resizeLabel=`Resize panel`,this.expandLabel=`Expand panel`,this.collapseLabel=`Collapse panel`,this.lastTapAt=0}disconnectedCallback(){this.finishActiveResize(),super.disconnectedCallback()}render(){let e=this.collapsed?this.expandLabel:this.collapseLabel;return g`
|
|
6879
6879
|
${this.renderResizeHandle()}
|
|
6880
6880
|
<button
|
|
6881
6881
|
type="button"
|
|
@@ -6905,7 +6905,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
6905
6905
|
@dblclick=${e=>{this.onResizeDoubleClick(e)}}
|
|
6906
6906
|
@keydown=${e=>{this.onResizeKeyDown(e)}}
|
|
6907
6907
|
></div>
|
|
6908
|
-
`}resizeAriaValueNow(){return this.panelWidth===void 0?v:String(Math.round(this.panelWidth))}renderIcon(){return g`<svg class="edge-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d=${this.iconDirection()===`left`?`M15 18l-6-6 6-6`:`M9 18l6-6-6-6`}/></svg>`}iconDirection(){return this.side===`navigation`?this.collapsed?`right`:`left`:this.collapsed?`left`:`right`}onResizePointerDown(e){if(!this.resizable||e.button!==0)return;let t=e.currentTarget;if(!(t instanceof HTMLElement))return;let n=this.resizeStartWidth();n!==void 0&&(e.preventDefault(),e.stopPropagation(),t.setPointerCapture(e.pointerId),this.activeResize={pointerId:e.pointerId,startClientX:e.clientX,startWidth:n,handle:t,moved:!1},this.toggleAttribute(`resizing`,!0))}onResizePointerMove(e){let t=this.activeResize;t?.pointerId===e.pointerId&&(e.preventDefault(),!(Math.abs(e.clientX-t.startClientX)<=
|
|
6908
|
+
`}resizeAriaValueNow(){return this.panelWidth===void 0?v:String(Math.round(this.panelWidth))}renderIcon(){return g`<svg class="edge-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d=${this.iconDirection()===`left`?`M15 18l-6-6 6-6`:`M9 18l6-6-6-6`}/></svg>`}iconDirection(){return this.side===`navigation`?this.collapsed?`right`:`left`:this.collapsed?`left`:`right`}onResizePointerDown(e){if(!this.resizable||e.button!==0)return;let t=e.currentTarget;if(!(t instanceof HTMLElement))return;let n=this.resizeStartWidth();n!==void 0&&(e.preventDefault(),e.stopPropagation(),t.setPointerCapture(e.pointerId),this.activeResize={pointerId:e.pointerId,startClientX:e.clientX,startWidth:n,handle:t,moved:!1},this.toggleAttribute(`resizing`,!0))}onResizePointerMove(e){let t=this.activeResize;t?.pointerId===e.pointerId&&(e.preventDefault(),!(Math.abs(e.clientX-t.startClientX)<=CL)&&(t.moved=!0,this.commitPanelWidth(hS(this.side,t.startWidth,t.startClientX,e.clientX,this.resizeConstraints()))))}onResizePointerUp(e){let t=this.activeResize;t?.pointerId===e.pointerId&&(e.preventDefault(),this.finishActiveResize(),t.moved||this.registerTapForReset())}onResizePointerCancel(e){this.activeResize?.pointerId===e.pointerId&&this.finishActiveResize()}onResizeDoubleClick(e){e.preventDefault(),e.stopPropagation(),this.resetPanelSize()}onResizeKeyDown(e){if(!this.resizable||!xL.has(e.key))return;let t=this.resizeStartWidth();if(t===void 0)return;let n=gS(this.side,t,e.key,{largeStep:e.shiftKey,constraints:this.resizeConstraints()});n!==void 0&&(e.preventDefault(),e.stopPropagation(),this.commitPanelWidth(n),this.onResizeEnd?.())}registerTapForReset(){let e=Date.now();if(e-this.lastTapAt<=SL){this.lastTapAt=0,this.resetPanelSize();return}this.lastTapAt=e}resetPanelSize(){this.finishActiveResize(),this.onReset?.()}resizeStartWidth(){let e=this.onResizeStart?.()??this.panelWidth;if(e!==void 0)return _S(this.side,e,this.resizeConstraints())}commitPanelWidth(e){this.onResize?.(_S(this.side,e,this.resizeConstraints()))}finishActiveResize(){let e=this.activeResize;if(e!==void 0){try{e.handle.releasePointerCapture(e.pointerId)}catch{}this.activeResize=void 0,this.toggleAttribute(`resizing`,!1),this.onResizeEnd?.()}}resizeConstraints(){let e=pS(this.side);return{...e,minWidth:this.minWidth??e.minWidth,maxWidth:this.maxWidth??e.maxWidth}}static{this.styles=h`
|
|
6909
6909
|
:host { position: relative; min-width: 0; min-height: 0; display: flex; align-items: center; justify-content: center; overflow: visible; background: var(--pi-border-muted); z-index: 2; }
|
|
6910
6910
|
:host([side="navigation"]) { grid-column: 2; }
|
|
6911
6911
|
:host([side="workspace"]) { grid-column: 4; }
|
|
@@ -6924,7 +6924,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
6924
6924
|
@media (max-width: 760px) {
|
|
6925
6925
|
:host([side="navigation"]) { display: none; }
|
|
6926
6926
|
}
|
|
6927
|
-
`}};H([x({reflect:!0})],
|
|
6927
|
+
`}};H([x({reflect:!0})],wL.prototype,`side`,void 0),H([x({type:Boolean,reflect:!0})],wL.prototype,`collapsed`,void 0),H([x({type:Boolean})],wL.prototype,`resizable`,void 0),H([x({type:Number})],wL.prototype,`panelWidth`,void 0),H([x({type:Number})],wL.prototype,`minWidth`,void 0),H([x({type:Number})],wL.prototype,`maxWidth`,void 0),H([x()],wL.prototype,`controls`,void 0),H([x()],wL.prototype,`resizeLabel`,void 0),H([x()],wL.prototype,`expandLabel`,void 0),H([x()],wL.prototype,`collapseLabel`,void 0),H([x({attribute:!1})],wL.prototype,`onToggle`,void 0),H([x({attribute:!1})],wL.prototype,`onResizeStart`,void 0),H([x({attribute:!1})],wL.prototype,`onResize`,void 0),H([x({attribute:!1})],wL.prototype,`onResizeEnd`,void 0),H([x({attribute:!1})],wL.prototype,`onReset`,void 0),wL=H([b(`app-panel-edge-control`)],wL);var TL=class extends y{constructor(...e){super(...e),this.onReloadClick=e=>{e.stopPropagation(),this.onReload?.()}}render(){let e=`Full page reload`;return g`
|
|
6928
6928
|
<button
|
|
6929
6929
|
class="app-refresh-button"
|
|
6930
6930
|
title=${e}
|
|
@@ -6943,7 +6943,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
6943
6943
|
:host, :host * { -webkit-user-select: none; user-select: none; }
|
|
6944
6944
|
.app-refresh-button { box-sizing: border-box; width: 36px; height: 36px; display: grid; place-items: center; border: 1px solid var(--pi-border); border-radius: 999px; background: var(--pi-surface); color: var(--pi-text); padding: 0; line-height: 1; cursor: pointer; touch-action: manipulation; -webkit-touch-callout: none; }
|
|
6945
6945
|
.app-refresh-icon { width: 18px; height: 18px; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; pointer-events: none; }
|
|
6946
|
-
`}};H([x({attribute:!1})],
|
|
6946
|
+
`}};H([x({attribute:!1})],TL.prototype,`onReload`,void 0),TL=H([b(`app-refresh-control`)],TL);var EL=[`terminal`,`git-update-manager`,`theme`,`system-prompt`,`history`,`info`],DL=`file-manager`,OL=`browser`,kL=[...EL],AL=new Set(EL),jL=`pi-webui:activity-rail-order`;function ML(){return typeof localStorage>`u`?void 0:localStorage}function NL(e){return AL.has(e)}function PL(e){if(!Array.isArray(e))return;let t=[],n=new Set;for(let r of e){if(typeof r!=`string`)return;let e=r===DL?`git-update-manager`:r;if(e!==OL){if(!NL(e)||n.has(e))return;n.add(e),t.push(e)}}if(t.length===EL.length)return t;let r=[...t];if(!n.has(`git-update-manager`)){let e=r.indexOf(`terminal`);r.splice(e+1,0,`git-update-manager`)}return n.has(`info`)||r.push(`info`),r.length===EL.length?r:void 0}function FL(){try{let e=ML();if(e===void 0)return;let t=e.getItem(jL);return t===null?void 0:PL(JSON.parse(t))}catch{return}}function IL(e){try{let t=ML();if(t===void 0)return;t.setItem(jL,JSON.stringify(e))}catch{}}var LL=[`terminal`,`git-update-manager`,`theme`,`system-prompt`,`history`,`info`];function RL(e){return LL.includes(e)}function zL(e){return typeof HTMLElement<`u`&&e instanceof HTMLElement}var BL=class extends y{constructor(){super(),this.terminalCount=0,this.gitUpdateManagerCount=0,this.systemPromptEnabled=!1,this.historyEnabled=!1,this.railOrder=[...kL],this.pluginItems=[],this.compactOpen=!1,this.onDesktopMediaChange=e=>{e.matches&&this.compactOpen&&this.onCloseCompact?.(),this.requestUpdate()},this.openTerminal=()=>{this.invokeCoreAction(this.onOpenTerminal)},this.openGitUpdateManager=()=>{this.invokeCoreAction(this.onOpenGitUpdateManager)},this.openTheme=()=>{this.invokeCoreAction(this.onOpenTheme)},this.openSystemPrompt=()=>{this.invokeCoreAction(this.onOpenSystemPrompt)},this.openHistory=()=>{this.invokeCoreAction(this.onOpenHistory)},this.openInfo=()=>{this.invokeCoreAction(this.onOpenInfo)},this.openSettings=()=>{this.invokeCoreAction(this.onOpenSettings)},this.openPluginActivity=(e,t)=>{this.closeCompactBeforeAction(),zL(t)&&this.onOpenPluginActivity?.(e,t)},this.closeCompact=()=>{this.onCloseCompact?.()},this.handleCompactBackdropMouseDown=e=>{e.target===e.currentTarget&&(e.preventDefault(),this.closeCompact())},this.handleCompactKeyDown=e=>{e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),this.closeCompact())},this.onDragStart=(e,t)=>{this.dragItem=e,t.dataTransfer!==null&&(t.dataTransfer.effectAllowed=`move`,t.dataTransfer.setData(`text/plain`,e)),requestAnimationFrame(()=>{this.renderRoot.querySelector(`[data-rail-item="${e}"]`)?.classList.add(`dragging`)})},this.onDragEnd=e=>{this.dragItem=void 0,this.renderRoot.querySelector(`[data-rail-item="${e}"]`)?.classList.remove(`dragging`),this.renderRoot.querySelectorAll(`.drag-over`).forEach(e=>{e.classList.remove(`drag-over`)})},this.onRailDragOver=e=>{if(e.preventDefault(),e.dataTransfer!==null&&(e.dataTransfer.dropEffect=`move`),this.dragItem===void 0)return;let t=this.resolveDragTarget(e.target);this.renderRoot.querySelectorAll(`.drag-over`).forEach(e=>{e.classList.remove(`drag-over`)}),t!==null&&t.dataset.railItem!==this.dragItem&&t.classList.add(`drag-over`)},this.onRailDrop=e=>{if(e.preventDefault(),this.renderRoot.querySelectorAll(`.drag-over`).forEach(e=>{e.classList.remove(`drag-over`)}),this.dragItem===void 0)return;let t=this.resolveDragTarget(e.target);if(t===null||t.dataset.railItem===this.dragItem){this.dragItem=void 0;return}let n=t.dataset.railItem;if(n===void 0||!RL(n)){this.dragItem=void 0;return}let r=[...this.railOrder],i=r.indexOf(this.dragItem),a=r.indexOf(n);if(i===-1||a===-1){this.dragItem=void 0;return}r.splice(i,1),r.splice(a,0,this.dragItem),this.railOrder=r,this.onRailOrderChange?.(r),this.dragItem=void 0},typeof window<`u`&&`matchMedia`in window&&(this.desktopMedia=window.matchMedia(Ix))}connectedCallback(){super.connectedCallback(),this.desktopMedia?.addEventListener(`change`,this.onDesktopMediaChange)}disconnectedCallback(){super.disconnectedCallback(),this.desktopMedia?.removeEventListener(`change`,this.onDesktopMediaChange)}updated(e){!e.has(`compactOpen`)||!this.compactOpen||this.isDesktopRailLayout()||this.renderRoot.querySelector(`.compact-rail-close`)?.focus()}isDesktopRailLayout(){return this.desktopMedia?.matches??!0}closeCompactBeforeAction(){this.isDesktopRailLayout()||this.onCloseCompact?.()}invokeCoreAction(e){this.closeCompactBeforeAction(),e?.()}resolveDragTarget(e){if(e===null||!(e instanceof HTMLElement))return null;let t=e.closest(`[data-rail-item]`);return t instanceof HTMLElement?t:null}dndProps(e){return{draggable:`true`,"data-rail-item":e}}renderReorderableButton(e){switch(e){case`terminal`:return this.renderTerminalButton();case`git-update-manager`:return this.renderGitUpdateManagerButton();case`theme`:return this.renderThemeButton();case`system-prompt`:return this.renderSystemPromptButton();case`history`:return this.renderHistoryButton();case`info`:return this.renderInfoButton()}}renderTerminalButton(){let e=this.dndProps(`terminal`),t=this.terminalCount>0?this.terminalCount:void 0,n=t===void 0?``:`${String(t)} active terminal${t===1?``:`s`}`;return g`
|
|
6947
6947
|
<button
|
|
6948
6948
|
type="button"
|
|
6949
6949
|
class="icon-button terminal-button"
|
|
@@ -7095,7 +7095,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
7095
7095
|
${e.badge===void 0?v:g`<span class="rail-badge" aria-hidden="true">${e.badge}</span>`}
|
|
7096
7096
|
</button>
|
|
7097
7097
|
`}renderRailContents(){return g`
|
|
7098
|
-
${(this.railOrder.length===0?[...
|
|
7098
|
+
${(this.railOrder.length===0?[...kL]:this.railOrder).map(e=>this.renderReorderableButton(e))}
|
|
7099
7099
|
${this.pluginItems.length===0?v:g`
|
|
7100
7100
|
<div class="rail-plugin-separator" role="separator"></div>
|
|
7101
7101
|
${this.pluginItems.map(e=>this.renderPluginButton(e))}
|
|
@@ -7210,7 +7210,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
7210
7210
|
.compact-rail-dialog { height: 100%; }
|
|
7211
7211
|
.compact-rail-dialog .rail { box-shadow: 8px 0 24px var(--pi-shadow); }
|
|
7212
7212
|
.compact-rail-close { margin-bottom: 2px; }
|
|
7213
|
-
`}};H([x({attribute:!1})],
|
|
7213
|
+
`}};H([x({attribute:!1})],BL.prototype,`onOpenTerminal`,void 0),H([x({attribute:!1})],BL.prototype,`onOpenGitUpdateManager`,void 0),H([x({attribute:!1})],BL.prototype,`onOpenTheme`,void 0),H([x({attribute:!1})],BL.prototype,`onOpenSystemPrompt`,void 0),H([x({attribute:!1})],BL.prototype,`onOpenHistory`,void 0),H([x({attribute:!1})],BL.prototype,`onOpenInfo`,void 0),H([x({attribute:!1})],BL.prototype,`onOpenSettings`,void 0),H([x({type:Number})],BL.prototype,`terminalCount`,void 0),H([x({type:Number})],BL.prototype,`gitUpdateManagerCount`,void 0),H([x({type:Boolean})],BL.prototype,`systemPromptEnabled`,void 0),H([x({type:Boolean})],BL.prototype,`historyEnabled`,void 0),H([x({attribute:!1})],BL.prototype,`railOrder`,void 0),H([x({attribute:!1})],BL.prototype,`onRailOrderChange`,void 0),H([x({attribute:!1})],BL.prototype,`pluginItems`,void 0),H([x({attribute:!1})],BL.prototype,`onOpenPluginActivity`,void 0),H([x({type:Boolean})],BL.prototype,`compactOpen`,void 0),H([x({attribute:!1})],BL.prototype,`onCloseCompact`,void 0),BL=H([b(`activity-rail`)],BL);var VL=(e,t,n)=>{console.warn(`Plugin activity rail contribution failed`,e,t,n)},HL=class extends y{constructor(...e){super(...e),this.close=()=>{this.onClose?.()},this.handleCancel=e=>{e.preventDefault(),this.close()},this.handleBackdropClick=e=>{e.target===e.currentTarget&&this.close()}}firstUpdated(){let e=this.nativeDialog;e?.isConnected===!0&&(e.showModal(),this.closeButton?.focus())}disconnectedCallback(){let e=this.nativeDialog;e?.open===!0&&e.close(),super.disconnectedCallback()}render(){let e=uy(this.activity,this.context,this.onReportError??VL);return g`
|
|
7214
7214
|
<dialog
|
|
7215
7215
|
class="plugin-activity-backdrop"
|
|
7216
7216
|
role="dialog"
|
|
@@ -7272,7 +7272,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
7272
7272
|
header { padding-top: max(12px, env(safe-area-inset-top)); }
|
|
7273
7273
|
.plugin-activity-body { padding-bottom: max(12px, env(safe-area-inset-bottom)); }
|
|
7274
7274
|
}
|
|
7275
|
-
`}};H([x({attribute:!1})],
|
|
7275
|
+
`}};H([x({attribute:!1})],HL.prototype,`activity`,void 0),H([x({attribute:!1})],HL.prototype,`context`,void 0),H([x({attribute:!1})],HL.prototype,`onClose`,void 0),H([x({attribute:!1})],HL.prototype,`onReportError`,void 0),H([C(`dialog.plugin-activity-backdrop`)],HL.prototype,`nativeDialog`,void 0),H([C(`.plugin-activity-close`)],HL.prototype,`closeButton`,void 0),HL=H([b(`plugin-activity-dialog`)],HL);var UL=class extends y{constructor(...e){super(...e),this.machineId=`local`,this.api=hc,this.loadingStatus=!1,this.loadingDiff=!1,this.error=``,this.statusRequest=0,this.diffRequest=0,this.refresh=async()=>{let e=this.workspace;if(e===void 0)return;let t=this.machineId,n=this.selectedChange?.id,r=++this.statusRequest;this.diffRequest+=1,this.status=void 0,this.selectedDiff=void 0,this.loadingStatus=!0,this.loadingDiff=!1,this.error=``;try{let i=await this.api.gitStatus(e.projectId,e.id,t);if(r!==this.statusRequest||!this.isCurrentWorkspace(e,t))return;this.status=i,this.loadingStatus=!1,this.onStatusChange?.(i);let a=n===void 0?void 0:GL(i,n);this.selectedChange=a,a!==void 0&&await this.loadDiff(a,e,t)}catch(n){if(r!==this.statusRequest||!this.isCurrentWorkspace(e,t))return;this.status=void 0,this.selectedChange=void 0,this.selectedDiff=void 0,this.loadingStatus=!1,this.error=JL(n)}},this.selectChange=e=>{let t=this.workspace;if(t===void 0)return;let n=this.machineId;this.selectedChange=e,this.selectedDiff=void 0,this.error=``,this.loadDiff(e,t,n)},this.onViewportResize=()=>{this.bounds!==void 0&&(this.bounds=XS(this.bounds,this.viewport()))},this.handleMovePointerDown=e=>{this.startPointerInteraction(`move`,e)},this.handleResizePointerDown=e=>{this.startPointerInteraction(`resize`,e)},this.handlePointerMove=e=>{let t=this.pointerInteraction;if(t?.pointerId!==e.pointerId)return;e.preventDefault();let n={x:e.clientX-t.startClientX,y:e.clientY-t.startClientY};this.bounds=t.operation===`move`?JS(t.bounds,n,this.viewport()):YS(t.bounds,n,this.viewport())},this.handlePointerUp=e=>{this.pointerInteraction?.pointerId===e.pointerId&&(e.preventDefault(),this.finishPointerInteraction())},this.handlePointerCancel=e=>{this.pointerInteraction?.pointerId===e.pointerId&&this.finishPointerInteraction()},this.close=()=>{this.finishPointerInteraction(),this.onClose?.()}}connectedCallback(){super.connectedCallback(),window.addEventListener(`resize`,this.onViewportResize),this.ensureWorkspaceScope()}willUpdate(){this.ensureWorkspaceScope()}disconnectedCallback(){this.finishPointerInteraction(),this.statusRequest+=1,this.diffRequest+=1,window.removeEventListener(`resize`,this.onViewportResize),super.disconnectedCallback()}render(){return g`
|
|
7276
7276
|
<div class="git-update-manager-backdrop" role="dialog" aria-modal="true" aria-label="Git Update Manager">
|
|
7277
7277
|
<section class=${this.bounds===void 0?`git-update-manager-frame`:`git-update-manager-frame git-update-manager-frame-positioned`} style=${this.frameStyle()}>
|
|
7278
7278
|
<header class="git-update-manager-header">
|
|
@@ -7306,15 +7306,15 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
7306
7306
|
></div>
|
|
7307
7307
|
</section>
|
|
7308
7308
|
</div>
|
|
7309
|
-
`}ensureWorkspaceScope(){let e=
|
|
7309
|
+
`}ensureWorkspaceScope(){let e=qL(this.workspace,this.machineId);e!==this.workspaceScope&&(this.workspaceScope=e,this.statusRequest+=1,this.diffRequest+=1,this.status=void 0,this.selectedChange=void 0,this.selectedDiff=void 0,this.loadingStatus=!1,this.loadingDiff=!1,this.error=``,e!==void 0&&this.isConnected&&this.refresh())}renderChangeList(){if(this.loadingStatus)return g`<p class="git-update-manager-empty">Loading changes…</p>`;let e=this.status;if(e===void 0)return g`<p class="git-update-manager-empty">Refresh to load Git changes.</p>`;if(!e.isGitRepo)return g`<p class="git-update-manager-empty">This workspace is not a Git repository.</p>`;let t=Cu(e.files);return t.staged.length===0&&t.unstaged.length===0?g`<p class="git-update-manager-empty">No Git changes.</p>`:g`
|
|
7310
7310
|
${this.renderChangeGroup(`staged`,t.staged)}
|
|
7311
7311
|
${this.renderChangeGroup(`unstaged`,t.unstaged)}
|
|
7312
|
-
`}renderChangeGroup(e,t){if(t.length===0)return null;let n=
|
|
7312
|
+
`}renderChangeGroup(e,t){if(t.length===0)return null;let n=KL(e);return g`
|
|
7313
7313
|
<section class="git-update-manager-change-group" aria-label=${`${n} changes`}>
|
|
7314
7314
|
<h2>${n} (${String(t.length)})</h2>
|
|
7315
7315
|
${t.map(e=>this.renderChange(e))}
|
|
7316
7316
|
</section>
|
|
7317
|
-
`}renderChange(e){let t=this.selectedChange?.id===e.id,n=Du(e),r=Eu(e.state),i=
|
|
7317
|
+
`}renderChange(e){let t=this.selectedChange?.id===e.id,n=Du(e),r=Eu(e.state),i=KL(e.scope);return g`
|
|
7318
7318
|
<button
|
|
7319
7319
|
type="button"
|
|
7320
7320
|
class=${`git-update-manager-entry ${t?`selected`:``}`}
|
|
@@ -7326,13 +7326,13 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
7326
7326
|
<span class="git-update-manager-path">${n}</span>
|
|
7327
7327
|
<span class="git-update-manager-scope">${i}</span>
|
|
7328
7328
|
</button>
|
|
7329
|
-
`}renderDiffPreview(){let e=this.selectedChange;if(e===void 0)return g`<p class="git-update-manager-empty">Select a Git change to review.</p>`;if(this.error!==``)return g`<p class="git-update-manager-empty">Could not load ${Du(e)}.</p>`;if(this.loadingDiff||this.selectedDiff===void 0)return g`<p class="git-update-manager-empty">Loading ${Du(e)}…</p>`;let t=this.selectedDiff;return
|
|
7329
|
+
`}renderDiffPreview(){let e=this.selectedChange;if(e===void 0)return g`<p class="git-update-manager-empty">Select a Git change to review.</p>`;if(this.error!==``)return g`<p class="git-update-manager-empty">Could not load ${Du(e)}.</p>`;if(this.loadingDiff||this.selectedDiff===void 0)return g`<p class="git-update-manager-empty">Loading ${Du(e)}…</p>`;let t=this.selectedDiff;return WL(),g`
|
|
7330
7330
|
<header class="git-update-manager-diff-header">
|
|
7331
7331
|
<strong>${Du(e)}</strong>
|
|
7332
|
-
<small>${
|
|
7332
|
+
<small>${KL(e.scope)} · ${Eu(e.state)}${t.truncated?` · truncated`:``}</small>
|
|
7333
7333
|
</header>
|
|
7334
7334
|
<unified-diff-viewer .diff=${t.diff}></unified-diff-viewer>
|
|
7335
|
-
`}async loadDiff(e,t,n){let r=++this.diffRequest;this.loadingDiff=!0;try{let i=await this.api.gitDiff(t.projectId,t.id,{path:e.path,staged:e.scope===`staged`},n);if(r!==this.diffRequest||!this.isCurrentWorkspace(t,n)||this.selectedChange?.id!==e.id)return;this.selectedDiff=i,this.loadingDiff=!1,this.error=``}catch(i){if(r!==this.diffRequest||!this.isCurrentWorkspace(t,n)||this.selectedChange?.id!==e.id)return;this.selectedDiff=void 0,this.loadingDiff=!1,this.error=
|
|
7335
|
+
`}async loadDiff(e,t,n){let r=++this.diffRequest;this.loadingDiff=!0;try{let i=await this.api.gitDiff(t.projectId,t.id,{path:e.path,staged:e.scope===`staged`},n);if(r!==this.diffRequest||!this.isCurrentWorkspace(t,n)||this.selectedChange?.id!==e.id)return;this.selectedDiff=i,this.loadingDiff=!1,this.error=``}catch(i){if(r!==this.diffRequest||!this.isCurrentWorkspace(t,n)||this.selectedChange?.id!==e.id)return;this.selectedDiff=void 0,this.loadingDiff=!1,this.error=JL(i)}}startPointerInteraction(e,t){if(t.button!==0)return;let n=t.currentTarget;if(!(n instanceof HTMLElement))return;let r=n.closest(`.git-update-manager-frame`);if(!(r instanceof HTMLElement))return;t.preventDefault(),t.stopPropagation();let i=XS(this.boundsFromFrame(r),this.viewport());n.setPointerCapture(t.pointerId),this.bounds=i,this.pointerInteraction={operation:e,pointerId:t.pointerId,target:n,startClientX:t.clientX,startClientY:t.clientY,bounds:i}}boundsFromFrame(e){let{left:t,top:n,width:r,height:i}=e.getBoundingClientRect();return{left:t,top:n,width:r,height:i}}viewport(){return typeof window>`u`?{width:0,height:0}:{width:window.innerWidth,height:window.innerHeight}}frameStyle(){let e=this.bounds;return e===void 0?``:`left: ${String(e.left)}px; top: ${String(e.top)}px; width: ${String(e.width)}px; height: ${String(e.height)}px;`}finishPointerInteraction(){let e=this.pointerInteraction;if(e!==void 0){try{e.target.releasePointerCapture(e.pointerId)}catch{}this.pointerInteraction=void 0}}isCurrentWorkspace(e,t){return this.workspace?.id===e.id&&this.workspace.projectId===e.projectId&&this.machineId===t}static{this.styles=h`
|
|
7336
7336
|
:host { position: fixed; inset: 0; z-index: 80; color: var(--pi-text); font: 14px system-ui, sans-serif; }
|
|
7337
7337
|
.git-update-manager-backdrop { width: 100%; height: 100dvh; display: grid; place-items: center; padding: 16px; background: rgba(0, 0, 0, .48); }
|
|
7338
7338
|
.git-update-manager-frame { position: relative; display: flex; flex-direction: column; width: min(calc(100vw - 32px), 1280px); height: min(calc(100vh - 32px), 880px); overflow: hidden; border: 1px solid var(--pi-border); border-radius: 14px; background: var(--pi-bg); box-shadow: 0 20px 64px var(--pi-shadow-strong); }
|
|
@@ -7371,7 +7371,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
7371
7371
|
.git-update-manager-workspace { grid-template-columns: 1fr; grid-template-rows: minmax(190px, 40%) minmax(0, 1fr); }
|
|
7372
7372
|
.git-update-manager-entries { border-right: 0; border-bottom: 1px solid var(--pi-border); }
|
|
7373
7373
|
}
|
|
7374
|
-
`}};H([x({attribute:!1})],HL.prototype,`onClose`,void 0),H([x({attribute:!1})],HL.prototype,`onStatusChange`,void 0),H([x({attribute:!1})],HL.prototype,`workspace`,void 0),H([x()],HL.prototype,`machineId`,void 0),H([x({attribute:!1})],HL.prototype,`api`,void 0),H([S()],HL.prototype,`status`,void 0),H([S()],HL.prototype,`selectedChange`,void 0),H([S()],HL.prototype,`selectedDiff`,void 0),H([S()],HL.prototype,`loadingStatus`,void 0),H([S()],HL.prototype,`loadingDiff`,void 0),H([S()],HL.prototype,`error`,void 0),H([S()],HL.prototype,`bounds`,void 0),HL=H([b(`git-update-manager-panel`)],HL);function UL(){sb(()=>import(`./UnifiedDiffViewer-DXWhrIST.js`),[],import.meta.url)}function WL(e,t){let n=Cu(e.files);return[...n.staged,...n.unstaged].find(e=>e.id===t)}function GL(e){return e===`staged`?`Staged`:`Unstaged`}function KL(e,t){return e===void 0?void 0:JSON.stringify([t,e.projectId,e.id])}function qL(e){return e instanceof Error?e.message:String(e)}var JL=900*1e3,YL=750,XL=[1e3,3e3,8e3,15e3,3e4],ZL={capture:!0},QL=`auto:on`,$L=`auto:off`,eR=`theme:`,tR=Yl(`core:workspace.files`),nR=Yl(`core:workspace.git`),rR=Yl(`core:workspace.terminal`),iR=`workspace-memory`,aR=`workspace.memory`,oR=`workspace-memory:workspace.memory`,sR=`workspace-learned-skills`,cR=`workspace.learned-skills`,lR=`workspace-learned-skills:workspace.learned-skills`,uR=320,dR=2,fR=`(min-width: 1181px)`,pR=75,mR=`Could not remember this model policy; this session still uses it.`,$=class extends y{constructor(e={}){super(),this.state=Il(),this.sessionUnread=new Jv({onChange:e=>{R(this.state)===e&&(this.syncUnreadSessionIds(),this.syncSelectedSessionReadState())},onBackgroundError:(e,t,n)=>{console.warn(`Failed to ${e} session unread state for ${t}`,n)}}),this.unreadSessionIds=this.sessionUnread.unreadSessionIds(R(this.state),this.state.sessions),this.unreadConnected=!1,this.notifications=new hh(()=>this.state,e=>{this.setState(e)},{onBackgroundError:(e,t)=>{console.warn(e,t)}}),this.hostSpeech=new xh({onStateChange:()=>{this.hostSpeechSurfaceVisible()&&this.requestUpdate()}}),this.sessions=new gm(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},new Qp,{refreshProjectSessionCatalog:()=>this.projectCatalog.refresh(),notifications:this.notifications,onSelectedSessionReady:({machineId:e,session:t})=>{this.commitReadyChatAfterRender(e,t)},replacePromptEditorText:async({machineId:e,sessionId:t,text:n})=>{await this.updateComplete,!(R(this.state)!==e||this.state.selectedSession?.id!==t)&&this.promptEditor?.replaceText(n)},onStarterModelPolicyConfirmed:e=>{this.handleStarterModelPolicyConfirmed(e)}}),this.workspaces=new b_(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.sessions,new v_,{onBackgroundError:(e,t)=>{console.warn(`Failed to ${e}`,t)}}),this.projectCatalog=new zu(()=>this.state,{workspaces:sc.workspaces,applySnapshot:async e=>{await this.workspaces.reconcileProjectCatalog(e)},captureTopologyRequest:e=>this.workspaces.captureProjectCatalogTopologyRequest(e),onBackgroundError:(e,t)=>{console.warn(`Failed to ${e}`,t)}}),this.projectActivityOwnership=new Xu(()=>this.state,e=>{this.setState(e)},{api:sc,captureTopologyRequest:e=>this.workspaces.captureProjectCatalogTopologyRequest(e),onProjectTopology:async e=>{let t=this.state.projects.find(t=>t.id===e.projectId&&t.path===e.projectPath);t!==void 0&&await this.workspaces.reconcileProjectCatalog({machineId:e.machineId,project:t,workspaces:e.workspaces,...e.topologyRequest===void 0?{}:{topologyRequest:e.topologyRequest}})},onError:({machineId:e,projectId:t,error:n})=>{console.warn(`Failed to discover project activity ownership for ${t} on ${e}`,n)}}),this.activity=new Hl(()=>this.state,e=>{this.setState(e)},{onActivityApplied:e=>{this.projectActivityOwnership.handleActivityApplied(e)}}),this.auth=new Kl(()=>this.state,e=>{this.setState(e)},e=>{this.sessions.applySessionStatus(e)}),this.projects=new Fu(()=>this.state,e=>{this.setState(e)},this.workspaces,{onProjectsApplied:e=>{this.projectActivityOwnership.handleProjectsApplied(e),this.recentProjects.load()}}),this.machines=new ju(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.projects),this.piWebUiStatusController=new Qu(()=>this.state,e=>{this.setState(e)},{onRefreshError:(e,t)=>{console.warn(`Failed to refresh PI WEBUI status for ${e}`,t)}}),this.files=new cu(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.git=new mu(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.memory=new xu(()=>this.state,e=>{this.setState(e)}),this.learnedSkills=new _u(()=>this.state,e=>{this.setState(e)}),this.recentProjects=new Vu({machineId:()=>R(this.state),onChange:()=>{this.requestUpdate()},onBackgroundError:(e,t)=>{console.warn(`Failed to ${e}`,t)}}),this.keyboard=new X_,this.realtime=new gp,this.machineRealtimeSockets=new Map,this.unreadRuntimeRefreshes=new Map,this.activeTerminalIds=new Set,this.machineNavigation=new M_,this.terminalSelection=new G_,this.appShell=new Lx(this),this.browserResume=new Bx({onResumeSignal:()=>{this.handleBrowserResumeSignal()},refreshAfterResume:()=>this.refreshAfterBrowserResume(),onRefreshError:e=>{console.warn(`Failed to refresh after browser resume`,e)}}),this.speechInputSettingsConnected=!1,this.speechInputSettingsRequestSeq=0,this.isSpeechInputSettingsRequestCurrent=e=>this.speechInputSettingsConnected&&e===this.speechInputSettingsRequestSeq,this.speechInputSettingsChannelDispatchQueued=!1,this.speechInputSettingsChannelRefreshInFlight=!1,this.panelCollapse=new cS(this),this.panelResize=new fS(this),this.navigationSections=new aS(this,()=>this.state,()=>this.appShell.isMobileNavigationLayout),this.systemLightThemeMedia=typeof window<`u`&&`matchMedia`in window?window.matchMedia(`(prefers-color-scheme: light)`):void 0,this.refreshingWorkspaceDeletionRuns=!1,this.handledWorkspaceDeletionRunIds=new Set,this.terminalCommandRunRuntimes=new Map,this.machineNavigationRestoreSeq=0,this.navigationSelectionSeq=0,this.routeRestoreSeq=0,this.routeRestoreDepth=0,this.remoteRouteRestoreAttempt=0,this.remoteRouteRestoreInProgress=!1,this.plugins=hR(),this.reportActivityRailError=(e,t,n)=>{console.warn(`Plugin activity rail contribution failed`,e,t,n)},this.loadedMachinePluginIds=new Set,this.machinePluginLoadPromises=new Map,this.themePreference=gy()??fy,this.activeThemeId=dy,this.isRefreshingApp=!1,this.recentProjectDialogInitialView=`closed-actions`,this.recentProjectDialogGeneration=0,this.starterSessionDefaultsSeq=0,this.starterModelPolicyPreferenceReadError=``,this.starterModelPolicyPreferenceWriter=new Sv({save:async(e,t)=>{let n=await cc.updateSessionDefaults(e.cwd,{starterModelPolicyPreference:t},e.machineId),r=this.starterModelPolicyPreferenceScope();return r?.machineId===e.machineId&&r.cwd===e.cwd&&(this.starterModelPolicyPreferenceReadError=``),n},onStateChange:()=>{this.requestUpdate()}}),this.confirmedStarterModelPolicyPreferenceWriter=new Dv({remember:(e,t)=>cc.rememberCurrentModelPolicy(t,e.machineId),onStateChange:(e,t)=>{this.starterModelPolicyPreferenceScopeMatchesCurrentSelection(e)&&this.confirmedStarterModelPolicyUiGeneration===this.starterModelPolicySelectionGeneration&&(!t.saving&&t.error===void 0&&(this.starterModelPolicyPreferenceReadError=``),this.requestUpdate())}}),this.starterModelPolicySelectionGeneration=0,this.modelTierCatalogLoading=!1,this.modelTierCatalogError=``,this.activeModelPolicyApplyGeneration=0,this.modelTierCatalogSeq=0,this.modelsConfigDialogOpen=!1,this.projectBrowserOpen=!1,this.statisticsLoading=!1,this.statisticsRequestGeneration=0,this.sessionBrowserOpen=!1,this.skillsConfigDialogOpen=!1,this.pluginsConfigDialogOpen=!1,this.systemPromptDialogOpen=!1,this.gitUpdateManagerPanelOpen=!1,this.terminalModalOpen=!1,this.terminalModalMaximized=!1,this.initialTerminalModalPreferences=rC(),this.terminalModalFontSize=this.initialTerminalModalPreferences.fontSize,this.terminalModalOpacity=this.initialTerminalModalPreferences.opacity,this.initialWorkspaceTabVisibility=dC(),this.terminalTabHidden=this.initialWorkspaceTabVisibility.terminalHidden,this.infoTabHidden=this.initialWorkspaceTabVisibility.infoHidden,this.railOrder=PL()??[...OL],this.compactRailOpen=!1,this.activeActivityRailGeneration=0,this.settingsSection=NS(),this.shortcutConfig={},this.workspaceUploadDefaultFolder=wc(void 0),this.sessionWarningVisibility=ny(),this.onPopState=()=>void this.withChatScrollTransition(async()=>{this.restoreSettingsRoute(),await this.restoreRoute(!1)}),this.onPageShow=()=>{this.renegotiateUnreadMachines(),this.appShell.repairViewportPosition(),this.retryPendingRemoteRouteRestoreSoon()},this.onSystemLightThemeChange=()=>{this.themePreference.auto&&this.applyPreferredTheme(!1)},this.onTerminalModalViewportResize=()=>{this.terminalModalBounds!==void 0&&(this.terminalModalBounds=XS(this.terminalModalBounds,this.terminalModalViewport()))},this.onKeyDown=e=>{if(e.key===`Escape`&&this.promptEditor?.cancelSpeechInput()===!0){e.preventDefault(),e.stopPropagation();return}this.compactRailOpen||this.activeActivityRailId!==void 0||this.settingsSection!==void 0||this.state.treeDialog!==void 0||this.state.actionPaletteOpen||this.keyboard.handle(e,this.getDefaultActions(),{shortcuts:this.shortcutConfig})&&(e.preventDefault(),e.stopPropagation())},this.closeCompactActivityRail=()=>{if(!this.compactRailOpen)return;this.compactRailOpen=!1;let e=this.compactActivityRailLauncher;this.updateComplete.then(()=>{!this.compactRailOpen&&this.activeActivityRailId===void 0&&(e===void 0?this.currentCompactActivityRailLauncher()?.focus():this.restoreActivityRailFocus(e))})},this.toggleCompactActivityRail=e=>{this.appShell.isDesktopActivityRailLayout||(!this.compactRailOpen&&e!==void 0&&(this.compactActivityRailLauncher=e),this.compactRailOpen=!this.compactRailOpen)},this.handleSendPrompt=(e,t,n,r)=>{this.sendPrompt(e,t,n,r)},this.handleStartSessionPrompt=(e,t,n,r)=>{if(!(n!==void 0&&n.length>0)&&t===void 0&&this.auth.handleSlashCommand(e))return;if(this.starterModelPolicyBlocksStart()){let e=this.starterNoticeScope();e!==void 0&&this.publishStarterNotice(wl(e));return}this.starterNotice=void 0;let i=this.state.selectedWorkspace?.id,a=R(this.state),o=this.selectedProjectWorkTarget(a),s=this.starterModelPolicy,c=this.starterPlusModelPolicyInitializer();this.starterModelPolicySelectionSupported(a)&&c===void 0||((c===void 0?this.sessions.startSessionWithPrompt(e,t,n,r,this.starterModelPolicyStartSnapshot(),e=>{this.clearStarterModelPolicyAfterSuccessfulStart(e,i,s)}):this.sessions.startPlusSessionWithPrompt(e,t,n,r??`inline`,c,()=>void 0)).then(e=>{e&&this.recordProjectWork(o)}).catch(e=>{i!==void 0&&this.publishStarterNotice(Tl(`start-failed`,`Could not start the session. ${UR(e)}`,{machineId:a,workspaceId:i}))}),this.focusChatComposer())},this.handleSelectStarterModel=()=>{this.openStarterModelDialog()},this.handleSelectStarterThinking=()=>{this.openStarterThinkingDialog()},this.handleSelectStarterPolicyMode=async e=>{let t=this.starterModelPolicy;if(t===void 0||t.mode===e)return;if(this.starterModelPolicySelectionSupported()){let n=e===`exact`?$c(t):t.tier===void 0?{...t,mode:`tiered`}:Qc(t,t.tier);this.setStarterModelPolicyDraft(n),this.ensureModelTierCatalog(R(this.state));return}if(e===`exact`){let e=$c(t);this.setStarterModelPolicyDraft(e);let n=this.starterSessionDefaults,r=n===void 0?void 0:qc(n);r!==void 0&&Zc(e.exact,r)&&this.persistStarterModelPolicyPreference(e);return}let n=t.tier===void 0?{...t,mode:`tiered`}:Qc(t,t.tier),r=this.setStarterModelPolicyDraft(n);if(n.tier===void 0){this.ensureModelTierCatalog(R(this.state));return}let i=await this.ensureStarterModelPolicyCatalog();this.starterModelPolicy!==r||i===void 0||nl(r,i)!==void 0&&this.persistStarterModelPolicyPreference(r)},this.handleSelectStarterPolicyTier=async e=>{let t=this.starterModelPolicy,n=await this.ensureStarterModelPolicyCatalog();if(t===void 0||t!==this.starterModelPolicy||n===void 0)return;let r=Qc(t,e);if(this.starterModelPolicySelectionSupported()){this.setStarterModelPolicyDraft(r);return}nl(r,n)!==void 0&&(this.setStarterModelPolicyDraft(r),this.persistStarterModelPolicyPreference(r))},this.handleSelectStarterPolicyThinking=async e=>{await this.pickStarterThinking(e)},this.handleSelectActivePolicyMode=async e=>{let t=await this.prepareActiveModelPolicyDraft();if(!(t===void 0||t!==this.activeModelPolicyDraftForState(this.state)||t.mode===e)){if(this.cancelActiveModelPolicyApply(),e===`exact`){this.setActiveModelPolicyDraft($c(t)),this.scheduleActiveExactModelPolicyApply();return}if(t.tier===void 0){this.setActiveModelPolicyDraft({...t,mode:`tiered`});return}this.setActiveModelPolicyDraft(Qc(t,t.tier)),await this.applyActiveModelPolicyDraft()}},this.handleSelectActivePolicyTier=async e=>{let t=await this.prepareActiveModelPolicyDraft();if(t===void 0||t!==this.activeModelPolicyDraftForState(this.state))return;this.cancelActiveModelPolicyApply();let n=Qc(t,e);this.setActiveModelPolicyDraft(n),await this.applyActiveModelPolicyDraft()},this.handleSelectActivePolicyThinking=async e=>{await this.pickThinking(e)},this.handleOpenTerminalFromRail=()=>{this.closeCompactActivityRail(),this.state.selectedWorkspace!==void 0&&(this.terminalModalOpen=!0)},this.handleOpenGitUpdateManagerFromRail=()=>{this.closeCompactActivityRail(),this.state.selectedWorkspace!==void 0&&(this.gitUpdateManagerPanelOpen=!0)},this.handleCloseGitUpdateManagerPanel=()=>{this.gitUpdateManagerPanelOpen=!1},this.handleOpenThemeFromRail=()=>{this.closeCompactActivityRail(),this.openThemeDialog()},this.handleRailOrderChange=e=>{this.railOrder=e,FL(e)},this.handleCloseTerminalModal=()=>{this.finishTerminalModalPointerInteraction(),this.terminalModalOpen=!1},this.toggleTerminalModalMaximized=()=>{this.finishTerminalModalPointerInteraction(),this.terminalModalMaximized=!this.terminalModalMaximized},this.handleTerminalModalMovePointerDown=e=>{this.startTerminalModalPointerInteraction(`move`,e)},this.handleTerminalModalResizePointerDown=e=>{this.startTerminalModalPointerInteraction(`resize`,e)},this.handleTerminalModalPointerMove=e=>{let t=this.terminalModalPointerInteraction;if(t?.pointerId!==e.pointerId)return;e.preventDefault();let n={x:e.clientX-t.startClientX,y:e.clientY-t.startClientY},r=this.terminalModalViewport();this.terminalModalBounds=t.operation===`move`?JS(t.bounds,n,r):YS(t.bounds,n,r)},this.handleTerminalModalPointerUp=e=>{this.terminalModalPointerInteraction?.pointerId===e.pointerId&&(e.preventDefault(),this.finishTerminalModalPointerInteraction())},this.handleTerminalModalPointerCancel=e=>{this.terminalModalPointerInteraction?.pointerId===e.pointerId&&this.finishTerminalModalPointerInteraction()},this.adjustTerminalFontSize=e=>{let t=tC(this.terminalModalFontSize+e);t!==this.terminalModalFontSize&&(this.terminalModalFontSize=t,this.persistTerminalModalPreferences())},this.adjustTerminalOpacity=e=>{let t=nC(this.terminalModalOpacity+e);t!==this.terminalModalOpacity&&(this.terminalModalOpacity=t,this.persistTerminalModalPreferences())},this.handleStopActiveWork=()=>{this.sessions.stopActiveWork()},this.handleCompact=()=>{this.sessions.runCommand(`/compact`)},this.handleToggleHostSpeech=e=>{let t=this.state.selectedSession;if(t===void 0||R(this.state)!==`local`)return;let n=this.hostSpeech.snapshot.active;if(n?.sessionId===t.id&&n.messageKey===e.messageKey){this.hostSpeech.stop();return}this.hostSpeech.startManual({machineId:`local`,sessionId:t.id,messageKey:e.messageKey,text:e.text})},this.handleClearServerQueue=()=>{this.sessions.clearServerQueue()},this.handleEditFromHere=async(e,t)=>{let n=R(this.state),r=this.state.selectedSession?.id;try{!(await this.sessions.editFromHere(e,t)).cancelled&&r!==void 0&&R(this.state)===n&&this.state.selectedSession?.id===r&&await this.focusChatComposer()}catch{}},this.handleForkFromHere=async e=>{await this.sessions.forkFromHere(e)},this.handleDismissWarning=e=>{this.sessions.dismissWarning(e)},this.handleDismissNotification=e=>{this.notifications.dismissNotification(e)},this.handleDismissAllNotifications=()=>{this.notifications.dismissAll()},this.handleToggleWarnings=()=>{let e=sy(this.sessionWarningVisibility);e!==this.sessionWarningVisibility&&(this.sessionWarningVisibility=e,this.requestUpdate())},this.handleSelectModel=()=>{this.openModelDialog()},this.handleSelectThinking=()=>{this.openThinkingDialog()},this.speechInputSettingsApi=e.speechInputApi??Ns,this.createSpeechInputSettingsChannel=e.createSpeechInputSettingsChannel??(e=>new Kx(e))}get routeRestoreInProgress(){return this.routeRestoreDepth>0}willUpdate(){this.toggleAttribute(`pwa-display-mode`,this.appShell.isPwaDisplayMode),this.syncSessionWarningVisibility(),this.syncStarterNotice()}updated(){this.committedChatIdentity=vR(this.state),this.syncSelectedSessionReadState(),this.compactRailOpen&&this.appShell.isDesktopActivityRailLayout&&this.closeCompactActivityRail();let e=this.activeActivityRailId;e!==void 0&&this.activeActivityRailItem()===void 0&&this.closeActivityRailItem(e,this.activeActivityRailGeneration)}syncSessionWarningVisibility(){let e=this.state.selectedSession;this.sessionWarningVisibility=iy(this.sessionWarningVisibility,e===void 0?void 0:Bl(R(this.state),e.id),this.state.status===void 0?void 0:this.state.status.warnings??[])}syncSelectedSessionReadState(){let e=this.state.selectedSession;if(e===void 0)return;let t=R(this.state);this.isSessionSeen(t,e)&&this.sessionUnread.acknowledge(t,e)}async commitReadyChatAfterRender(e,t){let n=_R(e,t);await this.updateComplete,!(!this.unreadConnected||vR(this.state)!==n)&&(this.readyChatIdentity=n,this.syncSelectedSessionReadState())}syncUnreadSessionIds(){let e=this.sessionUnread.unreadSessionIds(R(this.state),this.state.sessions);LR(e,this.unreadSessionIds)||(this.unreadSessionIds=e)}syncWindowTitle(){this.disconnectWindowTitle();let e=_C(this.state.selectedProject?.name);this.windowTitleCleanup=vC(e)}disconnectWindowTitle(){this.windowTitleCleanup?.(),this.windowTitleCleanup=void 0}isSessionSeen(e,t){if(!this.unreadConnected)return!1;let n=_R(e,t);return vR(this.state)!==n||this.committedChatIdentity!==n||this.readyChatIdentity!==n||typeof document<`u`&&(document.visibilityState!==`visible`||typeof document.hasFocus==`function`&&!document.hasFocus())||this.isChatObscured()?!1:this.state.mainView===`chat`?!0:this.state.mainView===`navigation`?!this.appShell.isMobileNavigationLayout:this.isDesktopSideBySideLayout()}isChatObscured(){return this.compactRailOpen||this.activeActivityRailId!==void 0||this.settingsSection!==void 0||this.sessionCleanupDialog!==void 0||this.historyWindow!==void 0||this.modelsConfigDialogOpen||this.skillsConfigDialogOpen&&this.state.selectedWorkspace!==void 0||this.pluginsConfigDialogOpen&&this.state.selectedWorkspace!==void 0||this.systemPromptDialogOpen&&this.state.selectedSession!==void 0||this.state.actionPaletteOpen||this.projectBrowserOpen||this.statisticsProject!==void 0||this.sessionBrowserOpen||this.state.projectDialogOpen||this.state.machineDialogOpen||this.state.commandDialog!==void 0||this.state.treeDialog!==void 0||this.state.modelDialog!==void 0||this.state.thinkingDialog!==void 0||this.state.themeDialog!==void 0||this.state.authDialog!==void 0||this.gitUpdateManagerPanelOpen||this.terminalModalOpen||this.recentProjectDialogEntry!==void 0}hostSpeechSurfaceVisible(){return R(this.state)===`local`?this.settingsSection===`general`||this.state.selectedSession!==void 0&&!this.isChatObscured():!1}abandonHostSpeechIfSourceInvalid(e){let t=this.hostSpeech.snapshot.active;if(t===void 0)return;let n=e.selectedSession;if(n?.id!==t.sessionId)return;if(n.archived===!0){this.hostSpeech.stop();return}let r=h_({messages:e.messages,messagePageStart:e.messagePageStart},t.messageKey);(r===``||!this.hostSpeech.matchesActiveSource({sessionId:t.sessionId,messageKey:t.messageKey,text:r}))&&this.hostSpeech.stop()}connectedCallback(){super.connectedCallback(),this.connectSpeechInputSettings(),this.hostSpeech.select(yR(this.state)),this.hostSpeech.refreshStatus(),this.synchronizeProjectCatalogPolling(),this.unreadConnected=!0,window.addEventListener(`popstate`,this.onPopState),window.addEventListener(`pageshow`,this.onPageShow),window.addEventListener(`resize`,this.onTerminalModalViewportResize),this.browserResume.connect(),window.addEventListener(`keydown`,this.onKeyDown,ZL),this.systemLightThemeMedia?.addEventListener(`change`,this.onSystemLightThemeChange),this.applyPreferredTheme(!1),this.connectRealtime(),this.renegotiateUnreadMachines(),this.piWebUiStatusTimer=window.setInterval(()=>{this.schedulePiWebUiStatusRefresh()},JL),this.refreshWorkspaceActivity(),this.recentProjects.load(),this.loadClientConfig(),this.ensureGatewayPluginsLoaded(),this.loadProjectsAndRestoreRoute().finally(()=>{this.schedulePiWebUiStatusRefresh()}),this.syncWindowTitle()}disconnectedCallback(){this.disconnectSpeechInputSettings(),this.finishTerminalModalPointerInteraction(),this.hostSpeech.dispose(),this.unreadConnected=!1,this.committedChatIdentity=void 0,this.readyChatIdentity=void 0,this.unreadRuntimeRefreshes.clear(),this.sessionUnread.retainMachines(new Set),window.removeEventListener(`popstate`,this.onPopState),window.removeEventListener(`pageshow`,this.onPageShow),window.removeEventListener(`resize`,this.onTerminalModalViewportResize),this.browserResume.disconnect(),window.removeEventListener(`keydown`,this.onKeyDown,ZL),this.systemLightThemeMedia?.removeEventListener(`change`,this.onSystemLightThemeChange),this.keyboard.reset(),this.auth.dispose(),this.resetActiveModelPolicyDraft(),this.sessions.dispose(),this.projectCatalog.dispose(),this.notifications.dispose(),this.realtime.close(),this.closeMachineActivitySockets(),this.git.dispose(),this.memory.dispose(),this.learnedSkills.dispose(),this.piWebUiStatusTimer!==void 0&&window.clearInterval(this.piWebUiStatusTimer),this.piWebUiStatusTimer=void 0,this.clearScheduledPiWebUiStatusRefresh(),this.workspaceDeletionPollTimer!==void 0&&window.clearInterval(this.workspaceDeletionPollTimer),this.workspaceDeletionPollTimer=void 0,this.clearPendingRemoteRouteRestore(),this.disconnectWindowTitle(),super.disconnectedCallback()}setState(e){if(!IR(this.state,e))return;let t=this.state,n={...t,...e},r=yR(t),i=yR(n);bR(r,i)?t.status?.isCompacting!==!0&&n.status?.isCompacting===!0?this.hostSpeech.stop():this.abandonHostSpeechIfSourceInvalid(n):this.hostSpeech.select(i);let a=xR(t),o=CR(t),s=SR(t);this.state=n,s!==SR(this.state)&&(this.starterModelPolicySelectionGeneration+=1),a!==xR(this.state)&&this.resetActiveModelPolicyDraft(),vR(t)!==vR(this.state)&&(this.committedChatIdentity=void 0,this.readyChatIdentity=void 0),MR(t,this.state)&&this.syncSessionUnreadMachines(),this.syncUnreadSessionIds(),this.handleActivityTransition(t,this.state),this.handleWorkspaceChange(t,this.state),!this.shouldShowSessionStartScreen(t)&&this.shouldShowSessionStartScreen(this.state)&&this.state.selectedWorkspace!==void 0&&this.loadStarterSessionDefaults(this.state.selectedWorkspace),this.handleMachineChange(t,this.state),this.handleStarterModelPolicyCapabilityChange(t,this.state),NR(t,this.state)&&this.syncMachineActivitySubscriptions(),this.notifications.syncEnvironment(t,this.state),t.selectedProject?.name!==this.state.selectedProject?.name&&this.syncWindowTitle(),this.synchronizeProjectCatalogPolling();let c=CR(this.state);c!==void 0&&c!==o&&this.preloadActiveModelPolicyInputs()}synchronizeProjectCatalogPolling(){this.projectCatalog.updatePolling(!!this.isConnected)}async loadProjectsAndRestoreRoute(){this.restoreSettingsRoute();let e=OS();await this.machines.loadMachines(e.machineId);let t=this.routeForSelectedMachine(e),n=this.state.machineStatuses[t.machineId??`local`];t!==e&&this.replaceRouteAndClearWorkspaceQuery(t),await this.projects.loadProjects(),await this.withChatScrollTransition(()=>this.restoreRouteFor(t,!1)),this.shouldDeferRemoteRouteRestore(t,n)?this.deferRemoteRouteRestore(t):(this.clearPendingRemoteRouteRestore(),this.rememberCurrentMachineNavigation()),await this.refreshWorkspaceDeletionRuns()}connectSpeechInputSettings(){if(!this.speechInputSettingsConnected){this.speechInputSettingsConnected=!0;try{this.speechInputSettingsChannel=this.createSpeechInputSettingsChannel(e=>{this.handleSpeechInputSettingsChannelRevision(e)})}catch{this.speechInputSettingsChannel=void 0}this.refreshSpeechInputSettings()}}disconnectSpeechInputSettings(){!this.speechInputSettingsConnected&&this.speechInputSettingsChannel===void 0||(this.speechInputSettingsConnected=!1,this.speechInputSettingsRequestSeq+=1,this.speechInputSettingsChannelDispatchQueued=!1,this.speechInputSettingsChannelRefreshInFlight=!1,this.pendingSpeechInputSettingsChannelRevision=void 0,this.speechInputSettingsChannel?.close(),this.speechInputSettingsChannel=void 0)}async refreshSpeechInputSettings(){if(!this.speechInputSettingsConnected)return;let e=++this.speechInputSettingsRequestSeq;try{let t=await this.speechInputSettingsApi.settings();if(e!==this.speechInputSettingsRequestSeq)return;this.speechInputSettings=t}catch{}}handleSpeechInputSettingsLoaded(e){this.adoptSpeechInputSettings(e,!1)}handleSpeechInputSettingsSaved(e){this.adoptSpeechInputSettings(e,!0)}adoptSpeechInputSettings(e,t){this.speechInputSettingsConnected&&(this.speechInputSettingsRequestSeq+=1,this.speechInputSettings=e,this.pendingSpeechInputSettingsChannelRevision===e.revision&&(this.pendingSpeechInputSettingsChannelRevision=void 0),t&&this.speechInputSettingsChannel?.publish(e.revision))}handleSpeechInputSettingsChannelRevision(e){!this.speechInputSettingsConnected||e===this.speechInputSettings?.revision||(this.pendingSpeechInputSettingsChannelRevision=e,!(this.speechInputSettingsChannelRefreshInFlight||this.speechInputSettingsChannelDispatchQueued)&&(this.speechInputSettingsChannelDispatchQueued=!0,queueMicrotask(()=>{this.speechInputSettingsChannelDispatchQueued=!1,!(!this.speechInputSettingsConnected||this.speechInputSettingsChannelRefreshInFlight)&&this.refreshSpeechInputSettingsFromChannel()})))}async refreshSpeechInputSettingsFromChannel(){if(!(!this.speechInputSettingsConnected||this.speechInputSettingsChannelRefreshInFlight)&&this.pendingSpeechInputSettingsChannelRevision!==void 0){this.pendingSpeechInputSettingsChannelRevision=void 0,this.speechInputSettingsChannelRefreshInFlight=!0;try{await this.refreshSpeechInputSettings()}finally{this.speechInputSettingsChannelRefreshInFlight=!1,this.shouldRunSpeechInputSettingsChannelTrailingRefresh()&&this.refreshSpeechInputSettingsFromChannel()}}}shouldRunSpeechInputSettingsChannelTrailingRefresh(){return this.speechInputSettingsConnected&&this.pendingSpeechInputSettingsChannelRevision!==void 0}handleBrowserResumeSignal(){this.appShell.repairViewportPosition(),this.schedulePiWebUiStatusRefresh(),this.retryPendingRemoteRouteRestoreSoon()}async refreshAfterBrowserResume(){this.projectCatalog.refresh(),await this.renegotiateUnreadMachines(),await Promise.all([this.sessions.refreshSelectedSession(),this.refreshMachineActivities(),this.refreshWorkspaceDeletionRuns(),this.refreshSpeechInputSettings()])}schedulePiWebUiStatusRefresh(e=YL){this.clearScheduledPiWebUiStatusRefresh(),this.piWebUiStatusDeferredTimer=window.setTimeout(()=>{this.piWebUiStatusDeferredTimer=void 0,this.piWebUiStatusController.refresh()},e)}clearScheduledPiWebUiStatusRefresh(){this.piWebUiStatusDeferredTimer!==void 0&&(window.clearTimeout(this.piWebUiStatusDeferredTimer),this.piWebUiStatusDeferredTimer=void 0)}async refreshWorkspaceActivity(e=R(this.state)){try{await this.activity.refresh(e)}catch(t){console.warn(`Failed to refresh workspace activity for ${e}`,t)}}async refreshMachineActivities(){let e=this.state.machines.length===0?[R(this.state)]:this.state.machines.filter(e=>FR(e,this.state.machineStatuses[e.id])).map(e=>e.id);await Promise.all(e.map(e=>this.refreshWorkspaceActivity(e)))}async loadClientConfig(){try{this.applyClientConfig((await Vs.config()).effectiveConfig)}catch(e){console.warn(`Failed to load PI WEBUI config`,e)}}applyClientConfig(e){this.shortcutConfig=e.shortcuts??{},this.workspaceUploadDefaultFolder=wc(e),this.hostSpeech.configure(e.tts)}async refreshAppData(){if(!this.isRefreshingApp){this.isRefreshingApp=!0;try{await Promise.all([this.sessions.refreshSelectedSession(),this.refreshMachineActivities(),this.loadClientConfig(),this.refreshWorkspaceDeletionRuns(),this.refreshCurrentWorkspaceSurface()]),this.schedulePiWebUiStatusRefresh()}finally{this.isRefreshingApp=!1}}}async refreshCurrentWorkspaceSurface(){let e=this.state.selectedWorkspace,t=this.state.mainView!==`chat`&&this.state.mainView!==`navigation`?this.state.mainView:this.state.workspaceTool;t===`core:workspace.files`?await this.files.refreshFiles():t===`core:workspace.git`?await this.git.refreshGit():t===`core:workspace.terminal`&&e!==void 0&&await this.refreshActiveTerminals(e)}hardReloadApp(){window.location.reload()}async restoreRoute(e){await this.restoreRouteFor(OS(),e),this.rememberCurrentMachineNavigation()}async restoreRouteFor(e,t,n=this.readWorkspaceRouteSurface(e),r){let i=R(this.state),a=e.projectId===void 0||e.projectId===``?BR():n,o=++this.routeRestoreSeq;this.routeRestoreDepth+=1,this.restoringRouteTerminalId=a.selectedTerminalId;try{await this.restoreRouteMachine(e,!1);let n=this.loadPluginsForSelectedMachine();if(e.tool?.startsWith(`machine.`)===!0&&await n,!this.isCurrentRouteRestore(o))return;if(this.setState({workspaceTool:e.tool??this.state.workspaceTool,mainView:r??e.view??this.defaultRouteView(),selectedFilePath:a.selectedFilePath,selectedDiffPath:a.selectedDiffPath,selectedTerminalId:a.selectedTerminalId}),e.projectId===void 0||e.projectId===``){t&&this.updateUrl();return}if(this.routeMatchesCurrentSelection(e)){a.selectedTerminalId!==void 0&&this.rememberSelectedTerminal(a.selectedTerminalId),await this.refreshRestoredWorkspaceTool(e.tool,a.selectedFilePath),this.git.updatePolling(),t&&this.updateUrl();return}let i=this.state.projects.find(t=>t.id===e.projectId);if(!i){this.setState({selectedFilePath:void 0,selectedDiffPath:void 0,selectedTerminalId:void 0}),t&&this.updateUrl();return}if(await this.workspaces.selectProject(i,{workspaceId:e.workspaceId,sessionId:e.sessionId,updateUrl:!1}),!this.isCurrentRouteRestore(o))return;this.setState({selectedFilePath:a.selectedFilePath,selectedDiffPath:a.selectedDiffPath,selectedTerminalId:a.selectedTerminalId}),a.selectedTerminalId!==void 0&&this.rememberSelectedTerminal(a.selectedTerminalId),await this.refreshRestoredWorkspaceTool(e.tool,a.selectedFilePath),this.git.updatePolling(),t&&this.updateUrl()}finally{this.routeRestoreDepth=Math.max(0,this.routeRestoreDepth-1),this.routeRestoreDepth===0&&(this.restoringRouteTerminalId=void 0),R(this.state)!==i&&this.schedulePiWebUiStatusRefresh()}}isCurrentRouteRestore(e){return e===this.routeRestoreSeq}readWorkspaceRouteSurface(e){return e.projectId===void 0||e.projectId===``?BR():{selectedFilePath:Zl(tR,`file`),selectedDiffPath:Zl(nR,`diff`),selectedTerminalId:Zl(rR,`terminal`)}}routeForSelectedMachine(e){let t=this.state.selectedMachine?.id??`local`;return(e.machineId??`local`)===t?e:{machineId:t,projectId:void 0,workspaceId:void 0,sessionId:void 0,tool:void 0,view:void 0}}replaceRouteAndClearWorkspaceQuery(e){kS(e,{replace:!0}),Ql(tR,`file`,void 0,{replace:!0}),Ql(nR,`diff`,void 0,{replace:!0}),Ql(rR,`terminal`,void 0,{replace:!0})}shouldDeferRemoteRouteRestore(e,t=this.state.machineStatuses[e.machineId??`local`]){let n=e.machineId??`local`,r=this.state.selectedMachine;return n===`local`||r?.id!==n||r.kind!==`remote`||t?.ok!==!1?!1:e.projectId===void 0||e.projectId===``?this.state.projects.length===0:this.state.selectedProject?.id!==e.projectId}deferRemoteRouteRestore(e){this.pendingRemoteRouteRestore=e,this.remoteRouteRestoreAttempt=0,this.setRemoteRouteRestoreMessage(e),this.schedulePendingRemoteRouteRestore()}retryPendingRemoteRouteRestoreSoon(){this.pendingRemoteRouteRestore!==void 0&&this.schedulePendingRemoteRouteRestore(0)}schedulePendingRemoteRouteRestore(e=HR(this.remoteRouteRestoreAttempt)){this.pendingRemoteRouteRestore!==void 0&&(this.clearPendingRemoteRouteRestoreTimer(),this.remoteRouteRestoreTimer=window.setTimeout(()=>{this.remoteRouteRestoreTimer=void 0,this.retryPendingRemoteRouteRestore()},e))}async retryPendingRemoteRouteRestore(){if(this.remoteRouteRestoreInProgress)return;let e=this.pendingRemoteRouteRestore;if(e!==void 0){if(!this.pendingRemoteRouteRestoreStillCurrent(e)){this.clearPendingRemoteRouteRestore();return}this.remoteRouteRestoreInProgress=!0;try{let t=e.machineId??`local`,n=await this.machines.refreshMachineHealth(t);if(!this.pendingRemoteRouteRestoreStillCurrent(e))return;if(n?.ok!==!0){this.scheduleNextRemoteRouteRestoreAttempt(e);return}if(await this.machines.refreshMachineRuntime(t),!this.pendingRemoteRouteRestoreStillCurrent(e)||(await this.projects.loadProjects(),!this.pendingRemoteRouteRestoreStillCurrent(e)))return;if(this.state.error!==``){this.scheduleNextRemoteRouteRestoreAttempt(e);return}if(await this.withChatScrollTransition(()=>this.restoreRouteFor(e,!1)),!this.pendingRemoteRouteRestoreStillCurrent(e))return;this.clearPendingRemoteRouteRestore(),this.rememberCurrentMachineNavigation(),await this.refreshWorkspaceDeletionRuns()}finally{this.remoteRouteRestoreInProgress=!1}}}scheduleNextRemoteRouteRestoreAttempt(e){if(this.remoteRouteRestoreAttempt+=1,this.remoteRouteRestoreAttempt>=XL.length){this.setRemoteRouteRestoreMessage(e,{exhausted:!0}),this.clearPendingRemoteRouteRestore();return}this.setRemoteRouteRestoreMessage(e),this.schedulePendingRemoteRouteRestore()}setRemoteRouteRestoreMessage(e,t={}){let n=e.machineId??`local`,r=this.state.machines.find(e=>e.id===n)?.name??this.state.selectedMachine?.name??`Remote machine`,i=this.state.machineStatuses[n]?.error??(this.state.error===``?void 0:this.state.error),a=t.exhausted===!0?`${r} is still unavailable.`:`${r} is unavailable; reconnecting…`;this.setState({error:`${a}${i===void 0?``:` ${i}`}`})}pendingRemoteRouteRestoreStillCurrent(e){let t=e.machineId??`local`;return t!==`local`&&this.pendingRemoteRouteRestore===e&&this.state.selectedMachine?.id===t&&this.state.machines.some(e=>e.id===t)}clearPendingRemoteRouteRestore(){this.clearPendingRemoteRouteRestoreTimer(),this.pendingRemoteRouteRestore=void 0,this.remoteRouteRestoreAttempt=0}clearPendingRemoteRouteRestoreTimer(){this.remoteRouteRestoreTimer!==void 0&&(window.clearTimeout(this.remoteRouteRestoreTimer),this.remoteRouteRestoreTimer=void 0)}async restoreRouteMachine(e,t){let n=e.machineId??`local`;if(this.state.selectedMachine?.id===n)return;let r=this.state.machines.find(e=>e.id===n);r!==void 0&&await this.machines.selectMachine(r,{updateUrl:t})}routeMatchesCurrentSelection(e){return(e.machineId??`local`)===(this.state.selectedMachine?.id??`local`)&&e.workspaceId!==void 0&&e.workspaceId!==``&&this.state.selectedProject?.id===e.projectId&&this.state.selectedWorkspace?.id===e.workspaceId&&this.state.selectedSession?.id===e.sessionId}async refreshRestoredWorkspaceTool(e,t){e===`core:workspace.files`&&await this.files.refreshFiles(),e===`core:workspace.files`&&t!==void 0&&await this.files.restoreFile(t),e===`core:workspace.git`&&await this.git.refreshGit()}async withChatScrollTransition(e,t=()=>!0){this.chatView?.saveScrollPosition(),await e(),t()&&(await this.updateComplete,t()&&(await this.chatView?.updateComplete,t()&&(await KR(),t()&&(this.chatView?.restoreScrollPosition(),this.shouldAutoFocusPrompt()&&this.promptEditor?.focusInput()))))}shouldAutoFocusPrompt(){return this.appShell.shouldAutoFocusPrompt()}async withChatPrependTransition(e){await e(),await this.updateComplete,await this.chatView?.updateComplete}defaultRouteView(){return this.appShell.defaultRouteView()}updateUrl(e){this.rememberCurrentMachineNavigation(),kS({machineId:this.state.selectedMachine?.id,projectId:this.state.selectedProject?.id,workspaceId:this.state.selectedWorkspace?.id,sessionId:this.state.selectedSession?.id,tool:this.state.workspaceTool,view:this.state.mainView===`navigation`?void 0:this.state.mainView},e),this.syncWorkspaceRouteSurfaceToUrl()}rememberCurrentMachineNavigation(){this.machineNavigation.remember(P_(this.state))}syncWorkspaceRouteSurfaceToUrl(){this.writeWorkspaceRouteSurfaceToUrl(P_(this.state).surface)}writeMachineNavigationSnapshotToUrl(e,t){kS(F_(e),t),this.writeWorkspaceRouteSurfaceToUrl(e.surface)}writeWorkspaceRouteSurfaceToUrl(e){Ql(tR,`file`,e.selectedFilePath,{replace:!0}),Ql(nR,`diff`,e.selectedDiffPath,{replace:!0}),Ql(rR,`terminal`,e.selectedTerminalId,{replace:!0})}async selectMachineWithMemory(e,t={}){if(this.state.selectedMachine?.id===e.id)return;t.rememberCurrent!==!1&&!this.routeRestoreInProgress&&this.rememberCurrentMachineNavigation();let n=++this.machineNavigationRestoreSeq,r=this.machineNavigation.latest(e.id)??N_(e.id);if(await this.restoreRouteFor(F_(r),!1,r.surface,r.view),!(n!==this.machineNavigationRestoreSeq||this.state.selectedMachine?.id!==e.id)){if(this.shouldPreserveUnrestoredMachineNavigation(r)){this.machineNavigation.remember(r),this.writeMachineNavigationSnapshotToUrl(r);return}this.updateUrl()}}shouldPreserveUnrestoredMachineNavigation(e){return e.projectId!==void 0&&this.state.selectedProject?.id!==e.projectId&&this.state.error!==``}openWorkspaceTool(e){e===`core:workspace.terminal`&&(this.terminalAutoStartWorkspaceId=this.state.selectedWorkspace?.id),this.setState({workspaceTool:e,mainView:e}),this.updateUrl(),this.refreshSelectedWorkspaceTool(e),this.git.updatePolling()}openTerminal(e){e?.terminalId!==void 0&&this.selectTerminal(e.terminalId,{replace:!0}),this.openWorkspaceTool(`core:workspace.terminal`)}terminalCommandRunsForOrigin(e,t=R(this.state)){let n=VR(t,e),r=this.terminalCommandRunRuntimes.get(n);if(r!==void 0)return r;let i=BS(e,{api:{runTerminalCommand:(e,n)=>lc.runTerminalCommand(e,n,t),listCommandRuns:e=>lc.listCommandRuns(e,t),getCommandRun:e=>lc.getCommandRun(e,t)},openTerminal:(e,n)=>{this.openRuntimeTerminal(t,e,n)}}),a={...i,runCommand:async e=>{let n=await i.runCommand(e);return this.recordProjectWork({machineId:t,projectId:e.workspace.projectId}),n}};return this.terminalCommandRunRuntimes.set(n,a),a}async openRuntimeTerminal(e,t,n){return(R(this.state)!==e||t!==void 0&&(this.state.selectedWorkspace?.id!==t.id||this.state.selectedProject?.id!==t.projectId))&&(this.routeRestoreInProgress||this.rememberCurrentMachineNavigation(),await this.restoreRouteFor({machineId:e,projectId:t?.projectId,workspaceId:t?.id,sessionId:void 0,tool:`core:workspace.terminal`,view:`core:workspace.terminal`},!1,{selectedTerminalId:n?.terminalId},`core:workspace.terminal`),R(this.state)!==e)?(this.setState({error:`Machine not found for terminal command run`}),!1):(this.openTerminal(n),!0)}selectTerminal(e,t){this.rememberSelectedTerminal(e),this.setState({selectedTerminalId:e}),this.rememberCurrentMachineNavigation(),this.writeSelectedTerminalToUrl(e,t)}rememberSelectedTerminal(e){let t=this.state.selectedWorkspace;t!==void 0&&(e===void 0?this.terminalSelection.forgetWorkspace(this.terminalWorkspaceKey(t)):this.terminalSelection.rememberTerminal(this.terminalWorkspaceKey(t),e))}writeSelectedTerminalToUrl(e,t){Ql(rR,`terminal`,e,t)}terminalWorkspaceKey(e){return`${R(this.state)}:${e.path}`}selectMainView(e){if(e!==`navigation`&&e!==`chat`){this.openWorkspaceTool(e);return}this.setState({mainView:e}),this.updateUrl(),this.git.updatePolling()}openSettings(e=`general`){this.settingsSection=e,PS(e)}closeSettings(){this.settingsSection=void 0,PS(void 0)}navigateSettings(e){this.settingsSection=e,PS(e)}restoreSettingsRoute(){this.settingsSection=NS()}handleWorkspaceChange(e,t){let n=jR(e,t);if(e.selectedWorkspace?.id===t.selectedWorkspace?.id){n&&(this.synchronizeMemoryPollingForSelectedWorkspace(),this.synchronizeLearnedSkillsPollingForSelectedWorkspace());return}this.starterSessionDefaults=void 0,this.resetStarterModelPolicyForScopeChange(),this.terminalAutoStartWorkspaceId=void 0,this.activeTerminalIds.clear();let r=this.routeRestoreInProgress?this.restoringRouteTerminalId:t.selectedWorkspace===void 0?void 0:this.terminalSelection.latestTerminalId(this.terminalWorkspaceKey(t.selectedWorkspace));if(this.setState({activeTerminalCount:0,selectedTerminalId:r}),this.routeRestoreInProgress||(this.rememberCurrentMachineNavigation(),this.writeSelectedTerminalToUrl(r,{replace:!0})),t.selectedWorkspace===void 0){this.synchronizeMemoryPollingForSelectedWorkspace(),this.synchronizeLearnedSkillsPollingForSelectedWorkspace();return}this.refreshActiveTerminals(t.selectedWorkspace),this.refreshWorkspaceDeletionRuns(),this.refreshSelectedWorkspaceTool(t.workspaceTool),this.git.updatePolling(),this.synchronizeMemoryPollingForSelectedWorkspace(),this.synchronizeLearnedSkillsPollingForSelectedWorkspace()}async loadStarterSessionDefaults(e,t={}){let n=R(this.state),r=++this.starterSessionDefaultsSeq,i=this.starterModelPolicySelectionSupported(n),a=()=>r===this.starterSessionDefaultsSeq&&R(this.state)===n&&this.state.selectedWorkspace?.id===e.id&&this.state.selectedWorkspace.path===e.path&&(t.expectedSelectionGeneration===void 0||this.starterModelPolicySelectionGeneration===t.expectedSelectionGeneration);try{let r=i?await cc.sessionDefaultsV2(e.path,n):await cc.sessionDefaults(e.path,n);if(!a())return;let o=this.starterSessionDefaults;this.starterSessionDefaults=r,this.starterNotice=void 0,this.starterModelPolicyPreferenceReadError=r.starterModelPolicyPreferenceError??``;let s=this.starterModelPolicy;s===void 0||i&&!DR(o)?this.starterModelPolicy=Jc(r):i?this.starterModelPolicy=s:this.starterModelPolicy=Yc(s,r),this.completeStarterModelPolicyFromActiveTier();let c=this.starterModelPolicy;if(this.selectedMachineModelTierCatalog()===void 0&&(i||c.mode===`tiered`&&!this.modelTierCatalogLoading)){let e=this.ensureModelTierCatalog(n);t.awaitModelTierCatalog===!0&&await e}}catch(t){a()&&(console.warn(`Failed to load Pi session defaults`,t),this.publishStarterNotice(Tl(`defaults-failed`,`Could not load this workspace's model defaults. ${UR(t)}`,{machineId:n,workspaceId:e.id})))}}syncSessionUnreadMachines(){if(!this.unreadConnected){this.sessionUnread.retainMachines(new Set);return}let e=new Set(this.state.machines.map(e=>e.id));this.sessionUnread.retainMachines(e);for(let t of e){let e=this.state.machineRuntimes[t];if(e===void 0)continue;let n=this.unreadRuntimeRefreshes.has(t)||!e.ok?`unknown`:E(e,w.sessionsUnread)?`supported`:`unsupported`;this.sessionUnread.setCapability(t,n)&&this.sessionUnread.refresh(t)}}async renegotiateUnreadMachines(){if(!this.unreadConnected)return;let e=new Set(this.state.machines.map(e=>e.id));e.add(R(this.state)),await Promise.all([...e].map(async e=>{await this.renegotiateUnreadMachine(e)}))}renegotiateUnreadMachine(e){let t=this.unreadRuntimeRefreshes.get(e);if(t!==void 0)return t;this.sessionUnread.setCapability(e,`unknown`);let n=!1,r=Promise.resolve().then(async()=>{n=await this.machines.refreshMachineRuntime(e)!==void 0});this.unreadRuntimeRefreshes.set(e,r);let i=()=>{this.unreadRuntimeRefreshes.get(e)===r&&(this.unreadRuntimeRefreshes.delete(e),this.unreadConnected&&(n?this.syncSessionUnreadMachines():this.sessionUnread.setCapability(e,`unknown`)))};return r.then(i,i),r}connectRealtime(){let e=R(this.state);this.realtime.connect(t=>{this.handleRealtimeEvent(e,t)},()=>{this.renegotiateUnreadMachine(e);let t=this.state.selectedWorkspace;t!==void 0&&this.refreshActiveTerminals(t),this.refreshWorkspaceActivity(e),this.projectCatalog.refresh()},e)}syncMachineActivitySubscriptions(){let e=this.machineActivitySubscriptionIds();for(let[t,n]of this.machineRealtimeSockets.entries())e.has(t)||(n.close(),this.machineRealtimeSockets.delete(t));for(let t of e){if(this.machineRealtimeSockets.has(t))continue;let e=new gp;e.connect(e=>{this.handleMachineActivityEvent(t,e)},()=>{this.renegotiateUnreadMachine(t),this.refreshWorkspaceActivity(t)},t),this.machineRealtimeSockets.set(t,e)}}closeMachineActivitySockets(){for(let e of this.machineRealtimeSockets.values())e.close();this.machineRealtimeSockets.clear()}machineActivitySubscriptionIds(){let e=R(this.state);return new Set(this.state.machines.filter(t=>t.id!==e).filter(e=>PR(e,this.state.machineStatuses[e.id])).map(e=>e.id))}handleMachineActivityEvent(e,t){t.type===`sessions.unread`?this.sessionUnread.applyEvent(e,t):t.type===`workspace.activity`&&this.activity.applyWorkspaceActivity(t.activity,e)}handleRealtimeEvent(e,t){t.type===`sessions.unread`?this.sessionUnread.applyEvent(e,t):t.type===`workspace.activity`?this.activity.applyWorkspaceActivity(t.activity):zR(t)?(this.applyTerminalEvent(t),t.type===`terminal.exited`&&this.refreshWorkspaceDeletionRuns()):this.sessions.applyGlobalEvent(t)}applyTerminalEvent(e){let t=this.state.selectedWorkspace;t!==void 0&&(e.type===`terminal.closed`?e.cwd:e.terminal.cwd)===t.path&&(e.type===`terminal.created`&&!e.terminal.exited?this.activeTerminalIds.add(e.terminal.id):this.activeTerminalIds.delete(e.type===`terminal.closed`?e.terminalId:e.terminal.id),e.type===`terminal.closed`&&(this.terminalSelection.forgetTerminal(e.terminalId),this.state.selectedTerminalId===e.terminalId&&this.selectTerminal(void 0,{replace:!0})),this.setState({activeTerminalCount:this.activeTerminalIds.size}))}async refreshActiveTerminals(e){let t=R(this.state);try{let n=await lc.terminals(e.projectId,e.id,t);if(R(this.state)!==t||this.state.selectedWorkspace?.id!==e.id)return;this.activeTerminalIds.clear();for(let e of n)e.exited||this.activeTerminalIds.add(e.id);this.setState({activeTerminalCount:this.activeTerminalIds.size})}catch(e){this.setState({error:String(e)})}}handleActivityTransition(e,t){let n=RR(e),r=RR(t);n&&!r&&(this.setState({fileTreeStale:!0,gitStale:!0}),this.refreshSelectedWorkspaceTool(this.state.workspaceTool))}handleMachineChange(e,t){if((e.selectedMachine?.id??`local`)===(t.selectedMachine?.id??`local`))return;this.closeRecentProjectDialogForMachineChange(),this.closeProjectStatistics(),this.projectActivityOwnership.handleSelectedMachineChanged(),(this.pendingRemoteRouteRestore?.machineId??`local`)!==(t.selectedMachine?.id??`local`)&&this.clearPendingRemoteRouteRestore(),this.sessions.clearActiveSession(),this.starterSessionDefaults=void 0,this.resetStarterModelPolicyForScopeChange(),this.resetModelTierCatalogForMachineChange(),this.realtime.close(),this.connectRealtime(),this.activeTerminalIds.clear(),this.sessionCleanupDialog=void 0,this.setState({piWebUiStatus:void 0}),this.git.updatePolling(),this.recentProjects.load(),this.loadPluginsForSelectedMachine();let n=t.selectedWorkspace;n!==void 0&&this.shouldShowSessionStartScreen(t)&&this.loadStarterSessionDefaults(n)}refreshSelectedWorkspaceTool(e){e===`core:workspace.files`&&this.files.refreshFiles(),e===`core:workspace.git`&&this.git.refreshGit()}renderWorkspacePanel(){return g`
|
|
7374
|
+
`}};H([x({attribute:!1})],UL.prototype,`onClose`,void 0),H([x({attribute:!1})],UL.prototype,`onStatusChange`,void 0),H([x({attribute:!1})],UL.prototype,`workspace`,void 0),H([x()],UL.prototype,`machineId`,void 0),H([x({attribute:!1})],UL.prototype,`api`,void 0),H([S()],UL.prototype,`status`,void 0),H([S()],UL.prototype,`selectedChange`,void 0),H([S()],UL.prototype,`selectedDiff`,void 0),H([S()],UL.prototype,`loadingStatus`,void 0),H([S()],UL.prototype,`loadingDiff`,void 0),H([S()],UL.prototype,`error`,void 0),H([S()],UL.prototype,`bounds`,void 0),UL=H([b(`git-update-manager-panel`)],UL);function WL(){sb(()=>import(`./UnifiedDiffViewer-I9Fc0TRx.js`),[],import.meta.url)}function GL(e,t){let n=Cu(e.files);return[...n.staged,...n.unstaged].find(e=>e.id===t)}function KL(e){return e===`staged`?`Staged`:`Unstaged`}function qL(e,t){return e===void 0?void 0:JSON.stringify([t,e.projectId,e.id])}function JL(e){return e instanceof Error?e.message:String(e)}var YL=900*1e3,XL=750,ZL=[1e3,3e3,8e3,15e3,3e4],QL={capture:!0},$L=`auto:on`,eR=`auto:off`,tR=`theme:`,nR=Yl(`core:workspace.files`),rR=Yl(`core:workspace.git`),iR=Yl(`core:workspace.terminal`),aR=`workspace-memory`,oR=`workspace.memory`,sR=`workspace-memory:workspace.memory`,cR=`workspace-learned-skills`,lR=`workspace.learned-skills`,uR=`workspace-learned-skills:workspace.learned-skills`,dR=320,fR=2,pR=`(min-width: 1181px)`,mR=75,hR=`Could not remember this model policy; this session still uses it.`,$=class extends y{constructor(e={}){super(),this.state=Il(),this.sessionUnread=new Jv({onChange:e=>{R(this.state)===e&&(this.syncUnreadSessionIds(),this.syncSelectedSessionReadState())},onBackgroundError:(e,t,n)=>{console.warn(`Failed to ${e} session unread state for ${t}`,n)}}),this.unreadSessionIds=this.sessionUnread.unreadSessionIds(R(this.state),this.state.sessions),this.unreadConnected=!1,this.notifications=new hh(()=>this.state,e=>{this.setState(e)},{onBackgroundError:(e,t)=>{console.warn(e,t)}}),this.hostSpeech=new xh({onStateChange:()=>{this.hostSpeechSurfaceVisible()&&this.requestUpdate()}}),this.sessions=new gm(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},new Qp,{refreshProjectSessionCatalog:()=>this.projectCatalog.refresh(),notifications:this.notifications,onSelectedSessionReady:({machineId:e,session:t})=>{this.commitReadyChatAfterRender(e,t)},replacePromptEditorText:async({machineId:e,sessionId:t,text:n})=>{await this.updateComplete,!(R(this.state)!==e||this.state.selectedSession?.id!==t)&&this.promptEditor?.replaceText(n)},onStarterModelPolicyConfirmed:e=>{this.handleStarterModelPolicyConfirmed(e)}}),this.workspaces=new b_(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.sessions,new v_,{onBackgroundError:(e,t)=>{console.warn(`Failed to ${e}`,t)}}),this.projectCatalog=new zu(()=>this.state,{workspaces:sc.workspaces,applySnapshot:async e=>{await this.workspaces.reconcileProjectCatalog(e)},captureTopologyRequest:e=>this.workspaces.captureProjectCatalogTopologyRequest(e),onBackgroundError:(e,t)=>{console.warn(`Failed to ${e}`,t)}}),this.projectActivityOwnership=new Xu(()=>this.state,e=>{this.setState(e)},{api:sc,captureTopologyRequest:e=>this.workspaces.captureProjectCatalogTopologyRequest(e),onProjectTopology:async e=>{let t=this.state.projects.find(t=>t.id===e.projectId&&t.path===e.projectPath);t!==void 0&&await this.workspaces.reconcileProjectCatalog({machineId:e.machineId,project:t,workspaces:e.workspaces,...e.topologyRequest===void 0?{}:{topologyRequest:e.topologyRequest}})},onError:({machineId:e,projectId:t,error:n})=>{console.warn(`Failed to discover project activity ownership for ${t} on ${e}`,n)}}),this.activity=new Hl(()=>this.state,e=>{this.setState(e)},{onActivityApplied:e=>{this.projectActivityOwnership.handleActivityApplied(e)}}),this.auth=new Kl(()=>this.state,e=>{this.setState(e)},e=>{this.sessions.applySessionStatus(e)}),this.projects=new Fu(()=>this.state,e=>{this.setState(e)},this.workspaces,{onProjectsApplied:e=>{this.projectActivityOwnership.handleProjectsApplied(e),this.recentProjects.load()}}),this.machines=new ju(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.projects),this.piWebUiStatusController=new Qu(()=>this.state,e=>{this.setState(e)},{onRefreshError:(e,t)=>{console.warn(`Failed to refresh PI WEBUI status for ${e}`,t)}}),this.files=new cu(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.git=new mu(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.memory=new xu(()=>this.state,e=>{this.setState(e)}),this.learnedSkills=new _u(()=>this.state,e=>{this.setState(e)}),this.recentProjects=new Vu({machineId:()=>R(this.state),onChange:()=>{this.requestUpdate()},onBackgroundError:(e,t)=>{console.warn(`Failed to ${e}`,t)}}),this.keyboard=new X_,this.realtime=new gp,this.machineRealtimeSockets=new Map,this.unreadRuntimeRefreshes=new Map,this.activeTerminalIds=new Set,this.machineNavigation=new M_,this.terminalSelection=new G_,this.appShell=new Lx(this),this.browserResume=new Bx({onResumeSignal:()=>{this.handleBrowserResumeSignal()},refreshAfterResume:()=>this.refreshAfterBrowserResume(),onRefreshError:e=>{console.warn(`Failed to refresh after browser resume`,e)}}),this.speechInputSettingsConnected=!1,this.speechInputSettingsRequestSeq=0,this.isSpeechInputSettingsRequestCurrent=e=>this.speechInputSettingsConnected&&e===this.speechInputSettingsRequestSeq,this.speechInputSettingsChannelDispatchQueued=!1,this.speechInputSettingsChannelRefreshInFlight=!1,this.panelCollapse=new cS(this),this.panelResize=new fS(this),this.navigationSections=new aS(this,()=>this.state,()=>this.appShell.isMobileNavigationLayout),this.systemLightThemeMedia=typeof window<`u`&&`matchMedia`in window?window.matchMedia(`(prefers-color-scheme: light)`):void 0,this.refreshingWorkspaceDeletionRuns=!1,this.handledWorkspaceDeletionRunIds=new Set,this.terminalCommandRunRuntimes=new Map,this.machineNavigationRestoreSeq=0,this.navigationSelectionSeq=0,this.routeRestoreSeq=0,this.routeRestoreDepth=0,this.remoteRouteRestoreAttempt=0,this.remoteRouteRestoreInProgress=!1,this.plugins=gR(),this.reportActivityRailError=(e,t,n)=>{console.warn(`Plugin activity rail contribution failed`,e,t,n)},this.loadedMachinePluginIds=new Set,this.machinePluginLoadPromises=new Map,this.themePreference=gy()??fy,this.activeThemeId=dy,this.isRefreshingApp=!1,this.recentProjectDialogInitialView=`closed-actions`,this.recentProjectDialogGeneration=0,this.starterSessionDefaultsSeq=0,this.starterModelPolicyPreferenceReadError=``,this.starterModelPolicyPreferenceWriter=new Sv({save:async(e,t)=>{let n=await cc.updateSessionDefaults(e.cwd,{starterModelPolicyPreference:t},e.machineId),r=this.starterModelPolicyPreferenceScope();return r?.machineId===e.machineId&&r.cwd===e.cwd&&(this.starterModelPolicyPreferenceReadError=``),n},onStateChange:()=>{this.requestUpdate()}}),this.confirmedStarterModelPolicyPreferenceWriter=new Dv({remember:(e,t)=>cc.rememberCurrentModelPolicy(t,e.machineId),onStateChange:(e,t)=>{this.starterModelPolicyPreferenceScopeMatchesCurrentSelection(e)&&this.confirmedStarterModelPolicyUiGeneration===this.starterModelPolicySelectionGeneration&&(!t.saving&&t.error===void 0&&(this.starterModelPolicyPreferenceReadError=``),this.requestUpdate())}}),this.starterModelPolicySelectionGeneration=0,this.modelTierCatalogLoading=!1,this.modelTierCatalogError=``,this.activeModelPolicyApplyGeneration=0,this.modelTierCatalogSeq=0,this.modelsConfigDialogOpen=!1,this.projectBrowserOpen=!1,this.statisticsLoading=!1,this.statisticsRequestGeneration=0,this.sessionBrowserOpen=!1,this.skillsConfigDialogOpen=!1,this.pluginsConfigDialogOpen=!1,this.systemPromptDialogOpen=!1,this.gitUpdateManagerPanelOpen=!1,this.terminalModalOpen=!1,this.terminalModalMaximized=!1,this.initialTerminalModalPreferences=rC(),this.terminalModalFontSize=this.initialTerminalModalPreferences.fontSize,this.terminalModalOpacity=this.initialTerminalModalPreferences.opacity,this.initialWorkspaceTabVisibility=dC(),this.terminalTabHidden=this.initialWorkspaceTabVisibility.terminalHidden,this.infoTabHidden=this.initialWorkspaceTabVisibility.infoHidden,this.railOrder=FL()??[...kL],this.compactRailOpen=!1,this.activeActivityRailGeneration=0,this.settingsSection=NS(),this.shortcutConfig={},this.workspaceUploadDefaultFolder=wc(void 0),this.sessionWarningVisibility=ny(),this.onPopState=()=>void this.withChatScrollTransition(async()=>{this.restoreSettingsRoute(),await this.restoreRoute(!1)}),this.onPageShow=()=>{this.renegotiateUnreadMachines(),this.appShell.repairViewportPosition(),this.retryPendingRemoteRouteRestoreSoon()},this.onSystemLightThemeChange=()=>{this.themePreference.auto&&this.applyPreferredTheme(!1)},this.onTerminalModalViewportResize=()=>{this.terminalModalBounds!==void 0&&(this.terminalModalBounds=XS(this.terminalModalBounds,this.terminalModalViewport()))},this.onKeyDown=e=>{if(e.key===`Escape`&&this.promptEditor?.cancelSpeechInput()===!0){e.preventDefault(),e.stopPropagation();return}this.compactRailOpen||this.activeActivityRailId!==void 0||this.settingsSection!==void 0||this.state.treeDialog!==void 0||this.state.actionPaletteOpen||this.keyboard.handle(e,this.getDefaultActions(),{shortcuts:this.shortcutConfig})&&(e.preventDefault(),e.stopPropagation())},this.closeCompactActivityRail=()=>{if(!this.compactRailOpen)return;this.compactRailOpen=!1;let e=this.compactActivityRailLauncher;this.updateComplete.then(()=>{!this.compactRailOpen&&this.activeActivityRailId===void 0&&(e===void 0?this.currentCompactActivityRailLauncher()?.focus():this.restoreActivityRailFocus(e))})},this.toggleCompactActivityRail=e=>{this.appShell.isDesktopActivityRailLayout||(!this.compactRailOpen&&e!==void 0&&(this.compactActivityRailLauncher=e),this.compactRailOpen=!this.compactRailOpen)},this.handleSendPrompt=(e,t,n,r)=>{this.sendPrompt(e,t,n,r)},this.handleStartSessionPrompt=(e,t,n,r)=>{if(!(n!==void 0&&n.length>0)&&t===void 0&&this.auth.handleSlashCommand(e))return;if(this.starterModelPolicyBlocksStart()){let e=this.starterNoticeScope();e!==void 0&&this.publishStarterNotice(wl(e));return}this.starterNotice=void 0;let i=this.state.selectedWorkspace?.id,a=R(this.state),o=this.selectedProjectWorkTarget(a),s=this.starterModelPolicy,c=this.starterPlusModelPolicyInitializer();this.starterModelPolicySelectionSupported(a)&&c===void 0||((c===void 0?this.sessions.startSessionWithPrompt(e,t,n,r,this.starterModelPolicyStartSnapshot(),e=>{this.clearStarterModelPolicyAfterSuccessfulStart(e,i,s)}):this.sessions.startPlusSessionWithPrompt(e,t,n,r??`inline`,c,()=>void 0)).then(e=>{e&&this.recordProjectWork(o)}).catch(e=>{i!==void 0&&this.publishStarterNotice(Tl(`start-failed`,`Could not start the session. ${WR(e)}`,{machineId:a,workspaceId:i}))}),this.focusChatComposer())},this.handleSelectStarterModel=()=>{this.openStarterModelDialog()},this.handleSelectStarterThinking=()=>{this.openStarterThinkingDialog()},this.handleSelectStarterPolicyMode=async e=>{let t=this.starterModelPolicy;if(t===void 0||t.mode===e)return;if(this.starterModelPolicySelectionSupported()){let n=e===`exact`?$c(t):t.tier===void 0?{...t,mode:`tiered`}:Qc(t,t.tier);this.setStarterModelPolicyDraft(n),this.ensureModelTierCatalog(R(this.state));return}if(e===`exact`){let e=$c(t);this.setStarterModelPolicyDraft(e);let n=this.starterSessionDefaults,r=n===void 0?void 0:qc(n);r!==void 0&&Zc(e.exact,r)&&this.persistStarterModelPolicyPreference(e);return}let n=t.tier===void 0?{...t,mode:`tiered`}:Qc(t,t.tier),r=this.setStarterModelPolicyDraft(n);if(n.tier===void 0){this.ensureModelTierCatalog(R(this.state));return}let i=await this.ensureStarterModelPolicyCatalog();this.starterModelPolicy!==r||i===void 0||nl(r,i)!==void 0&&this.persistStarterModelPolicyPreference(r)},this.handleSelectStarterPolicyTier=async e=>{let t=this.starterModelPolicy,n=await this.ensureStarterModelPolicyCatalog();if(t===void 0||t!==this.starterModelPolicy||n===void 0)return;let r=Qc(t,e);if(this.starterModelPolicySelectionSupported()){this.setStarterModelPolicyDraft(r);return}nl(r,n)!==void 0&&(this.setStarterModelPolicyDraft(r),this.persistStarterModelPolicyPreference(r))},this.handleSelectStarterPolicyThinking=async e=>{await this.pickStarterThinking(e)},this.handleSelectActivePolicyMode=async e=>{let t=await this.prepareActiveModelPolicyDraft();if(!(t===void 0||t!==this.activeModelPolicyDraftForState(this.state)||t.mode===e)){if(this.cancelActiveModelPolicyApply(),e===`exact`){this.setActiveModelPolicyDraft($c(t)),this.scheduleActiveExactModelPolicyApply();return}if(t.tier===void 0){this.setActiveModelPolicyDraft({...t,mode:`tiered`});return}this.setActiveModelPolicyDraft(Qc(t,t.tier)),await this.applyActiveModelPolicyDraft()}},this.handleSelectActivePolicyTier=async e=>{let t=await this.prepareActiveModelPolicyDraft();if(t===void 0||t!==this.activeModelPolicyDraftForState(this.state))return;this.cancelActiveModelPolicyApply();let n=Qc(t,e);this.setActiveModelPolicyDraft(n),await this.applyActiveModelPolicyDraft()},this.handleSelectActivePolicyThinking=async e=>{await this.pickThinking(e)},this.handleOpenTerminalFromRail=()=>{this.closeCompactActivityRail(),this.state.selectedWorkspace!==void 0&&(this.terminalModalOpen=!0)},this.handleOpenGitUpdateManagerFromRail=()=>{this.closeCompactActivityRail(),this.state.selectedWorkspace!==void 0&&(this.gitUpdateManagerPanelOpen=!0)},this.handleCloseGitUpdateManagerPanel=()=>{this.gitUpdateManagerPanelOpen=!1},this.handleOpenThemeFromRail=()=>{this.closeCompactActivityRail(),this.openThemeDialog()},this.handleRailOrderChange=e=>{this.railOrder=e,IL(e)},this.handleCloseTerminalModal=()=>{this.finishTerminalModalPointerInteraction(),this.terminalModalOpen=!1},this.toggleTerminalModalMaximized=()=>{this.finishTerminalModalPointerInteraction(),this.terminalModalMaximized=!this.terminalModalMaximized},this.handleTerminalModalMovePointerDown=e=>{this.startTerminalModalPointerInteraction(`move`,e)},this.handleTerminalModalResizePointerDown=e=>{this.startTerminalModalPointerInteraction(`resize`,e)},this.handleTerminalModalPointerMove=e=>{let t=this.terminalModalPointerInteraction;if(t?.pointerId!==e.pointerId)return;e.preventDefault();let n={x:e.clientX-t.startClientX,y:e.clientY-t.startClientY},r=this.terminalModalViewport();this.terminalModalBounds=t.operation===`move`?JS(t.bounds,n,r):YS(t.bounds,n,r)},this.handleTerminalModalPointerUp=e=>{this.terminalModalPointerInteraction?.pointerId===e.pointerId&&(e.preventDefault(),this.finishTerminalModalPointerInteraction())},this.handleTerminalModalPointerCancel=e=>{this.terminalModalPointerInteraction?.pointerId===e.pointerId&&this.finishTerminalModalPointerInteraction()},this.adjustTerminalFontSize=e=>{let t=tC(this.terminalModalFontSize+e);t!==this.terminalModalFontSize&&(this.terminalModalFontSize=t,this.persistTerminalModalPreferences())},this.adjustTerminalOpacity=e=>{let t=nC(this.terminalModalOpacity+e);t!==this.terminalModalOpacity&&(this.terminalModalOpacity=t,this.persistTerminalModalPreferences())},this.handleStopActiveWork=()=>{this.sessions.stopActiveWork()},this.handleCompact=()=>{this.sessions.runCommand(`/compact`)},this.handleToggleHostSpeech=e=>{let t=this.state.selectedSession;if(t===void 0||R(this.state)!==`local`)return;let n=this.hostSpeech.snapshot.active;if(n?.sessionId===t.id&&n.messageKey===e.messageKey){this.hostSpeech.stop();return}this.hostSpeech.startManual({machineId:`local`,sessionId:t.id,messageKey:e.messageKey,text:e.text})},this.handleClearServerQueue=()=>{this.sessions.clearServerQueue()},this.handleEditFromHere=async(e,t)=>{let n=R(this.state),r=this.state.selectedSession?.id;try{!(await this.sessions.editFromHere(e,t)).cancelled&&r!==void 0&&R(this.state)===n&&this.state.selectedSession?.id===r&&await this.focusChatComposer()}catch{}},this.handleForkFromHere=async e=>{await this.sessions.forkFromHere(e)},this.handleDismissWarning=e=>{this.sessions.dismissWarning(e)},this.handleDismissNotification=e=>{this.notifications.dismissNotification(e)},this.handleDismissAllNotifications=()=>{this.notifications.dismissAll()},this.handleToggleWarnings=()=>{let e=sy(this.sessionWarningVisibility);e!==this.sessionWarningVisibility&&(this.sessionWarningVisibility=e,this.requestUpdate())},this.handleSelectModel=()=>{this.openModelDialog()},this.handleSelectThinking=()=>{this.openThinkingDialog()},this.speechInputSettingsApi=e.speechInputApi??Ns,this.createSpeechInputSettingsChannel=e.createSpeechInputSettingsChannel??(e=>new Kx(e))}get routeRestoreInProgress(){return this.routeRestoreDepth>0}willUpdate(){this.toggleAttribute(`pwa-display-mode`,this.appShell.isPwaDisplayMode),this.syncSessionWarningVisibility(),this.syncStarterNotice()}updated(){this.committedChatIdentity=yR(this.state),this.syncSelectedSessionReadState(),this.compactRailOpen&&this.appShell.isDesktopActivityRailLayout&&this.closeCompactActivityRail();let e=this.activeActivityRailId;e!==void 0&&this.activeActivityRailItem()===void 0&&this.closeActivityRailItem(e,this.activeActivityRailGeneration)}syncSessionWarningVisibility(){let e=this.state.selectedSession;this.sessionWarningVisibility=iy(this.sessionWarningVisibility,e===void 0?void 0:Bl(R(this.state),e.id),this.state.status===void 0?void 0:this.state.status.warnings??[])}syncSelectedSessionReadState(){let e=this.state.selectedSession;if(e===void 0)return;let t=R(this.state);this.isSessionSeen(t,e)&&this.sessionUnread.acknowledge(t,e)}async commitReadyChatAfterRender(e,t){let n=vR(e,t);await this.updateComplete,!(!this.unreadConnected||yR(this.state)!==n)&&(this.readyChatIdentity=n,this.syncSelectedSessionReadState())}syncUnreadSessionIds(){let e=this.sessionUnread.unreadSessionIds(R(this.state),this.state.sessions);RR(e,this.unreadSessionIds)||(this.unreadSessionIds=e)}syncWindowTitle(){this.disconnectWindowTitle();let e=_C(this.state.selectedProject?.name);this.windowTitleCleanup=vC(e)}disconnectWindowTitle(){this.windowTitleCleanup?.(),this.windowTitleCleanup=void 0}isSessionSeen(e,t){if(!this.unreadConnected)return!1;let n=vR(e,t);return yR(this.state)!==n||this.committedChatIdentity!==n||this.readyChatIdentity!==n||typeof document<`u`&&(document.visibilityState!==`visible`||typeof document.hasFocus==`function`&&!document.hasFocus())||this.isChatObscured()?!1:this.state.mainView===`chat`?!0:this.state.mainView===`navigation`?!this.appShell.isMobileNavigationLayout:this.isDesktopSideBySideLayout()}isChatObscured(){return this.compactRailOpen||this.activeActivityRailId!==void 0||this.settingsSection!==void 0||this.sessionCleanupDialog!==void 0||this.historyWindow!==void 0||this.modelsConfigDialogOpen||this.skillsConfigDialogOpen&&this.state.selectedWorkspace!==void 0||this.pluginsConfigDialogOpen&&this.state.selectedWorkspace!==void 0||this.systemPromptDialogOpen&&this.state.selectedSession!==void 0||this.state.actionPaletteOpen||this.projectBrowserOpen||this.statisticsProject!==void 0||this.sessionBrowserOpen||this.state.projectDialogOpen||this.state.machineDialogOpen||this.state.commandDialog!==void 0||this.state.treeDialog!==void 0||this.state.modelDialog!==void 0||this.state.thinkingDialog!==void 0||this.state.themeDialog!==void 0||this.state.authDialog!==void 0||this.gitUpdateManagerPanelOpen||this.terminalModalOpen||this.recentProjectDialogEntry!==void 0}hostSpeechSurfaceVisible(){return R(this.state)===`local`?this.settingsSection===`general`||this.state.selectedSession!==void 0&&!this.isChatObscured():!1}abandonHostSpeechIfSourceInvalid(e){let t=this.hostSpeech.snapshot.active;if(t===void 0)return;let n=e.selectedSession;if(n?.id!==t.sessionId)return;if(n.archived===!0){this.hostSpeech.stop();return}let r=h_({messages:e.messages,messagePageStart:e.messagePageStart},t.messageKey);(r===``||!this.hostSpeech.matchesActiveSource({sessionId:t.sessionId,messageKey:t.messageKey,text:r}))&&this.hostSpeech.stop()}connectedCallback(){super.connectedCallback(),this.connectSpeechInputSettings(),this.hostSpeech.select(bR(this.state)),this.hostSpeech.refreshStatus(),this.synchronizeProjectCatalogPolling(),this.unreadConnected=!0,window.addEventListener(`popstate`,this.onPopState),window.addEventListener(`pageshow`,this.onPageShow),window.addEventListener(`resize`,this.onTerminalModalViewportResize),this.browserResume.connect(),window.addEventListener(`keydown`,this.onKeyDown,QL),this.systemLightThemeMedia?.addEventListener(`change`,this.onSystemLightThemeChange),this.applyPreferredTheme(!1),this.connectRealtime(),this.renegotiateUnreadMachines(),this.piWebUiStatusTimer=window.setInterval(()=>{this.schedulePiWebUiStatusRefresh()},YL),this.refreshWorkspaceActivity(),this.recentProjects.load(),this.loadClientConfig(),this.ensureGatewayPluginsLoaded(),this.loadProjectsAndRestoreRoute().finally(()=>{this.schedulePiWebUiStatusRefresh()}),this.syncWindowTitle()}disconnectedCallback(){this.disconnectSpeechInputSettings(),this.finishTerminalModalPointerInteraction(),this.hostSpeech.dispose(),this.unreadConnected=!1,this.committedChatIdentity=void 0,this.readyChatIdentity=void 0,this.unreadRuntimeRefreshes.clear(),this.sessionUnread.retainMachines(new Set),window.removeEventListener(`popstate`,this.onPopState),window.removeEventListener(`pageshow`,this.onPageShow),window.removeEventListener(`resize`,this.onTerminalModalViewportResize),this.browserResume.disconnect(),window.removeEventListener(`keydown`,this.onKeyDown,QL),this.systemLightThemeMedia?.removeEventListener(`change`,this.onSystemLightThemeChange),this.keyboard.reset(),this.auth.dispose(),this.resetActiveModelPolicyDraft(),this.sessions.dispose(),this.projectCatalog.dispose(),this.notifications.dispose(),this.realtime.close(),this.closeMachineActivitySockets(),this.git.dispose(),this.memory.dispose(),this.learnedSkills.dispose(),this.piWebUiStatusTimer!==void 0&&window.clearInterval(this.piWebUiStatusTimer),this.piWebUiStatusTimer=void 0,this.clearScheduledPiWebUiStatusRefresh(),this.workspaceDeletionPollTimer!==void 0&&window.clearInterval(this.workspaceDeletionPollTimer),this.workspaceDeletionPollTimer=void 0,this.clearPendingRemoteRouteRestore(),this.disconnectWindowTitle(),super.disconnectedCallback()}setState(e){if(!LR(this.state,e))return;let t=this.state,n={...t,...e},r=bR(t),i=bR(n);xR(r,i)?t.status?.isCompacting!==!0&&n.status?.isCompacting===!0?this.hostSpeech.stop():this.abandonHostSpeechIfSourceInvalid(n):this.hostSpeech.select(i);let a=SR(t),o=wR(t),s=CR(t);this.state=n,s!==CR(this.state)&&(this.starterModelPolicySelectionGeneration+=1),a!==SR(this.state)&&this.resetActiveModelPolicyDraft(),yR(t)!==yR(this.state)&&(this.committedChatIdentity=void 0,this.readyChatIdentity=void 0),NR(t,this.state)&&this.syncSessionUnreadMachines(),this.syncUnreadSessionIds(),this.handleActivityTransition(t,this.state),this.handleWorkspaceChange(t,this.state),!this.shouldShowSessionStartScreen(t)&&this.shouldShowSessionStartScreen(this.state)&&this.state.selectedWorkspace!==void 0&&this.loadStarterSessionDefaults(this.state.selectedWorkspace),this.handleMachineChange(t,this.state),this.handleStarterModelPolicyCapabilityChange(t,this.state),PR(t,this.state)&&this.syncMachineActivitySubscriptions(),this.notifications.syncEnvironment(t,this.state),t.selectedProject?.name!==this.state.selectedProject?.name&&this.syncWindowTitle(),this.synchronizeProjectCatalogPolling();let c=wR(this.state);c!==void 0&&c!==o&&this.preloadActiveModelPolicyInputs()}synchronizeProjectCatalogPolling(){this.projectCatalog.updatePolling(!!this.isConnected)}async loadProjectsAndRestoreRoute(){this.restoreSettingsRoute();let e=OS();await this.machines.loadMachines(e.machineId);let t=this.routeForSelectedMachine(e),n=this.state.machineStatuses[t.machineId??`local`];t!==e&&this.replaceRouteAndClearWorkspaceQuery(t),await this.projects.loadProjects(),await this.withChatScrollTransition(()=>this.restoreRouteFor(t,!1)),this.shouldDeferRemoteRouteRestore(t,n)?this.deferRemoteRouteRestore(t):(this.clearPendingRemoteRouteRestore(),this.rememberCurrentMachineNavigation()),await this.refreshWorkspaceDeletionRuns()}connectSpeechInputSettings(){if(!this.speechInputSettingsConnected){this.speechInputSettingsConnected=!0;try{this.speechInputSettingsChannel=this.createSpeechInputSettingsChannel(e=>{this.handleSpeechInputSettingsChannelRevision(e)})}catch{this.speechInputSettingsChannel=void 0}this.refreshSpeechInputSettings()}}disconnectSpeechInputSettings(){!this.speechInputSettingsConnected&&this.speechInputSettingsChannel===void 0||(this.speechInputSettingsConnected=!1,this.speechInputSettingsRequestSeq+=1,this.speechInputSettingsChannelDispatchQueued=!1,this.speechInputSettingsChannelRefreshInFlight=!1,this.pendingSpeechInputSettingsChannelRevision=void 0,this.speechInputSettingsChannel?.close(),this.speechInputSettingsChannel=void 0)}async refreshSpeechInputSettings(){if(!this.speechInputSettingsConnected)return;let e=++this.speechInputSettingsRequestSeq;try{let t=await this.speechInputSettingsApi.settings();if(e!==this.speechInputSettingsRequestSeq)return;this.speechInputSettings=t}catch{}}handleSpeechInputSettingsLoaded(e){this.adoptSpeechInputSettings(e,!1)}handleSpeechInputSettingsSaved(e){this.adoptSpeechInputSettings(e,!0)}adoptSpeechInputSettings(e,t){this.speechInputSettingsConnected&&(this.speechInputSettingsRequestSeq+=1,this.speechInputSettings=e,this.pendingSpeechInputSettingsChannelRevision===e.revision&&(this.pendingSpeechInputSettingsChannelRevision=void 0),t&&this.speechInputSettingsChannel?.publish(e.revision))}handleSpeechInputSettingsChannelRevision(e){!this.speechInputSettingsConnected||e===this.speechInputSettings?.revision||(this.pendingSpeechInputSettingsChannelRevision=e,!(this.speechInputSettingsChannelRefreshInFlight||this.speechInputSettingsChannelDispatchQueued)&&(this.speechInputSettingsChannelDispatchQueued=!0,queueMicrotask(()=>{this.speechInputSettingsChannelDispatchQueued=!1,!(!this.speechInputSettingsConnected||this.speechInputSettingsChannelRefreshInFlight)&&this.refreshSpeechInputSettingsFromChannel()})))}async refreshSpeechInputSettingsFromChannel(){if(!(!this.speechInputSettingsConnected||this.speechInputSettingsChannelRefreshInFlight)&&this.pendingSpeechInputSettingsChannelRevision!==void 0){this.pendingSpeechInputSettingsChannelRevision=void 0,this.speechInputSettingsChannelRefreshInFlight=!0;try{await this.refreshSpeechInputSettings()}finally{this.speechInputSettingsChannelRefreshInFlight=!1,this.shouldRunSpeechInputSettingsChannelTrailingRefresh()&&this.refreshSpeechInputSettingsFromChannel()}}}shouldRunSpeechInputSettingsChannelTrailingRefresh(){return this.speechInputSettingsConnected&&this.pendingSpeechInputSettingsChannelRevision!==void 0}handleBrowserResumeSignal(){this.appShell.repairViewportPosition(),this.schedulePiWebUiStatusRefresh(),this.retryPendingRemoteRouteRestoreSoon()}async refreshAfterBrowserResume(){this.projectCatalog.refresh(),await this.renegotiateUnreadMachines(),await Promise.all([this.sessions.refreshSelectedSession(),this.refreshMachineActivities(),this.refreshWorkspaceDeletionRuns(),this.refreshSpeechInputSettings()])}schedulePiWebUiStatusRefresh(e=XL){this.clearScheduledPiWebUiStatusRefresh(),this.piWebUiStatusDeferredTimer=window.setTimeout(()=>{this.piWebUiStatusDeferredTimer=void 0,this.piWebUiStatusController.refresh()},e)}clearScheduledPiWebUiStatusRefresh(){this.piWebUiStatusDeferredTimer!==void 0&&(window.clearTimeout(this.piWebUiStatusDeferredTimer),this.piWebUiStatusDeferredTimer=void 0)}async refreshWorkspaceActivity(e=R(this.state)){try{await this.activity.refresh(e)}catch(t){console.warn(`Failed to refresh workspace activity for ${e}`,t)}}async refreshMachineActivities(){let e=this.state.machines.length===0?[R(this.state)]:this.state.machines.filter(e=>IR(e,this.state.machineStatuses[e.id])).map(e=>e.id);await Promise.all(e.map(e=>this.refreshWorkspaceActivity(e)))}async loadClientConfig(){try{this.applyClientConfig((await Vs.config()).effectiveConfig)}catch(e){console.warn(`Failed to load PI WEBUI config`,e)}}applyClientConfig(e){this.shortcutConfig=e.shortcuts??{},this.workspaceUploadDefaultFolder=wc(e),this.hostSpeech.configure(e.tts)}async refreshAppData(){if(!this.isRefreshingApp){this.isRefreshingApp=!0;try{await Promise.all([this.sessions.refreshSelectedSession(),this.refreshMachineActivities(),this.loadClientConfig(),this.refreshWorkspaceDeletionRuns(),this.refreshCurrentWorkspaceSurface()]),this.schedulePiWebUiStatusRefresh()}finally{this.isRefreshingApp=!1}}}async refreshCurrentWorkspaceSurface(){let e=this.state.selectedWorkspace,t=this.state.mainView!==`chat`&&this.state.mainView!==`navigation`?this.state.mainView:this.state.workspaceTool;t===`core:workspace.files`?await this.files.refreshFiles():t===`core:workspace.git`?await this.git.refreshGit():t===`core:workspace.terminal`&&e!==void 0&&await this.refreshActiveTerminals(e)}hardReloadApp(){window.location.reload()}async restoreRoute(e){await this.restoreRouteFor(OS(),e),this.rememberCurrentMachineNavigation()}async restoreRouteFor(e,t,n=this.readWorkspaceRouteSurface(e),r){let i=R(this.state),a=e.projectId===void 0||e.projectId===``?VR():n,o=++this.routeRestoreSeq;this.routeRestoreDepth+=1,this.restoringRouteTerminalId=a.selectedTerminalId;try{await this.restoreRouteMachine(e,!1);let n=this.loadPluginsForSelectedMachine();if(e.tool?.startsWith(`machine.`)===!0&&await n,!this.isCurrentRouteRestore(o))return;if(this.setState({workspaceTool:e.tool??this.state.workspaceTool,mainView:r??e.view??this.defaultRouteView(),selectedFilePath:a.selectedFilePath,selectedDiffPath:a.selectedDiffPath,selectedTerminalId:a.selectedTerminalId}),e.projectId===void 0||e.projectId===``){t&&this.updateUrl();return}if(this.routeMatchesCurrentSelection(e)){a.selectedTerminalId!==void 0&&this.rememberSelectedTerminal(a.selectedTerminalId),await this.refreshRestoredWorkspaceTool(e.tool,a.selectedFilePath),this.git.updatePolling(),t&&this.updateUrl();return}let i=this.state.projects.find(t=>t.id===e.projectId);if(!i){this.setState({selectedFilePath:void 0,selectedDiffPath:void 0,selectedTerminalId:void 0}),t&&this.updateUrl();return}if(await this.workspaces.selectProject(i,{workspaceId:e.workspaceId,sessionId:e.sessionId,updateUrl:!1}),!this.isCurrentRouteRestore(o))return;this.setState({selectedFilePath:a.selectedFilePath,selectedDiffPath:a.selectedDiffPath,selectedTerminalId:a.selectedTerminalId}),a.selectedTerminalId!==void 0&&this.rememberSelectedTerminal(a.selectedTerminalId),await this.refreshRestoredWorkspaceTool(e.tool,a.selectedFilePath),this.git.updatePolling(),t&&this.updateUrl()}finally{this.routeRestoreDepth=Math.max(0,this.routeRestoreDepth-1),this.routeRestoreDepth===0&&(this.restoringRouteTerminalId=void 0),R(this.state)!==i&&this.schedulePiWebUiStatusRefresh()}}isCurrentRouteRestore(e){return e===this.routeRestoreSeq}readWorkspaceRouteSurface(e){return e.projectId===void 0||e.projectId===``?VR():{selectedFilePath:Zl(nR,`file`),selectedDiffPath:Zl(rR,`diff`),selectedTerminalId:Zl(iR,`terminal`)}}routeForSelectedMachine(e){let t=this.state.selectedMachine?.id??`local`;return(e.machineId??`local`)===t?e:{machineId:t,projectId:void 0,workspaceId:void 0,sessionId:void 0,tool:void 0,view:void 0}}replaceRouteAndClearWorkspaceQuery(e){kS(e,{replace:!0}),Ql(nR,`file`,void 0,{replace:!0}),Ql(rR,`diff`,void 0,{replace:!0}),Ql(iR,`terminal`,void 0,{replace:!0})}shouldDeferRemoteRouteRestore(e,t=this.state.machineStatuses[e.machineId??`local`]){let n=e.machineId??`local`,r=this.state.selectedMachine;return n===`local`||r?.id!==n||r.kind!==`remote`||t?.ok!==!1?!1:e.projectId===void 0||e.projectId===``?this.state.projects.length===0:this.state.selectedProject?.id!==e.projectId}deferRemoteRouteRestore(e){this.pendingRemoteRouteRestore=e,this.remoteRouteRestoreAttempt=0,this.setRemoteRouteRestoreMessage(e),this.schedulePendingRemoteRouteRestore()}retryPendingRemoteRouteRestoreSoon(){this.pendingRemoteRouteRestore!==void 0&&this.schedulePendingRemoteRouteRestore(0)}schedulePendingRemoteRouteRestore(e=UR(this.remoteRouteRestoreAttempt)){this.pendingRemoteRouteRestore!==void 0&&(this.clearPendingRemoteRouteRestoreTimer(),this.remoteRouteRestoreTimer=window.setTimeout(()=>{this.remoteRouteRestoreTimer=void 0,this.retryPendingRemoteRouteRestore()},e))}async retryPendingRemoteRouteRestore(){if(this.remoteRouteRestoreInProgress)return;let e=this.pendingRemoteRouteRestore;if(e!==void 0){if(!this.pendingRemoteRouteRestoreStillCurrent(e)){this.clearPendingRemoteRouteRestore();return}this.remoteRouteRestoreInProgress=!0;try{let t=e.machineId??`local`,n=await this.machines.refreshMachineHealth(t);if(!this.pendingRemoteRouteRestoreStillCurrent(e))return;if(n?.ok!==!0){this.scheduleNextRemoteRouteRestoreAttempt(e);return}if(await this.machines.refreshMachineRuntime(t),!this.pendingRemoteRouteRestoreStillCurrent(e)||(await this.projects.loadProjects(),!this.pendingRemoteRouteRestoreStillCurrent(e)))return;if(this.state.error!==``){this.scheduleNextRemoteRouteRestoreAttempt(e);return}if(await this.withChatScrollTransition(()=>this.restoreRouteFor(e,!1)),!this.pendingRemoteRouteRestoreStillCurrent(e))return;this.clearPendingRemoteRouteRestore(),this.rememberCurrentMachineNavigation(),await this.refreshWorkspaceDeletionRuns()}finally{this.remoteRouteRestoreInProgress=!1}}}scheduleNextRemoteRouteRestoreAttempt(e){if(this.remoteRouteRestoreAttempt+=1,this.remoteRouteRestoreAttempt>=ZL.length){this.setRemoteRouteRestoreMessage(e,{exhausted:!0}),this.clearPendingRemoteRouteRestore();return}this.setRemoteRouteRestoreMessage(e),this.schedulePendingRemoteRouteRestore()}setRemoteRouteRestoreMessage(e,t={}){let n=e.machineId??`local`,r=this.state.machines.find(e=>e.id===n)?.name??this.state.selectedMachine?.name??`Remote machine`,i=this.state.machineStatuses[n]?.error??(this.state.error===``?void 0:this.state.error),a=t.exhausted===!0?`${r} is still unavailable.`:`${r} is unavailable; reconnecting…`;this.setState({error:`${a}${i===void 0?``:` ${i}`}`})}pendingRemoteRouteRestoreStillCurrent(e){let t=e.machineId??`local`;return t!==`local`&&this.pendingRemoteRouteRestore===e&&this.state.selectedMachine?.id===t&&this.state.machines.some(e=>e.id===t)}clearPendingRemoteRouteRestore(){this.clearPendingRemoteRouteRestoreTimer(),this.pendingRemoteRouteRestore=void 0,this.remoteRouteRestoreAttempt=0}clearPendingRemoteRouteRestoreTimer(){this.remoteRouteRestoreTimer!==void 0&&(window.clearTimeout(this.remoteRouteRestoreTimer),this.remoteRouteRestoreTimer=void 0)}async restoreRouteMachine(e,t){let n=e.machineId??`local`;if(this.state.selectedMachine?.id===n)return;let r=this.state.machines.find(e=>e.id===n);r!==void 0&&await this.machines.selectMachine(r,{updateUrl:t})}routeMatchesCurrentSelection(e){return(e.machineId??`local`)===(this.state.selectedMachine?.id??`local`)&&e.workspaceId!==void 0&&e.workspaceId!==``&&this.state.selectedProject?.id===e.projectId&&this.state.selectedWorkspace?.id===e.workspaceId&&this.state.selectedSession?.id===e.sessionId}async refreshRestoredWorkspaceTool(e,t){e===`core:workspace.files`&&await this.files.refreshFiles(),e===`core:workspace.files`&&t!==void 0&&await this.files.restoreFile(t),e===`core:workspace.git`&&await this.git.refreshGit()}async withChatScrollTransition(e,t=()=>!0){this.chatView?.saveScrollPosition(),await e(),t()&&(await this.updateComplete,t()&&(await this.chatView?.updateComplete,t()&&(await qR(),t()&&(this.chatView?.restoreScrollPosition(),this.shouldAutoFocusPrompt()&&this.promptEditor?.focusInput()))))}shouldAutoFocusPrompt(){return this.appShell.shouldAutoFocusPrompt()}async withChatPrependTransition(e){await e(),await this.updateComplete,await this.chatView?.updateComplete}defaultRouteView(){return this.appShell.defaultRouteView()}updateUrl(e){this.rememberCurrentMachineNavigation(),kS({machineId:this.state.selectedMachine?.id,projectId:this.state.selectedProject?.id,workspaceId:this.state.selectedWorkspace?.id,sessionId:this.state.selectedSession?.id,tool:this.state.workspaceTool,view:this.state.mainView===`navigation`?void 0:this.state.mainView},e),this.syncWorkspaceRouteSurfaceToUrl()}rememberCurrentMachineNavigation(){this.machineNavigation.remember(P_(this.state))}syncWorkspaceRouteSurfaceToUrl(){this.writeWorkspaceRouteSurfaceToUrl(P_(this.state).surface)}writeMachineNavigationSnapshotToUrl(e,t){kS(F_(e),t),this.writeWorkspaceRouteSurfaceToUrl(e.surface)}writeWorkspaceRouteSurfaceToUrl(e){Ql(nR,`file`,e.selectedFilePath,{replace:!0}),Ql(rR,`diff`,e.selectedDiffPath,{replace:!0}),Ql(iR,`terminal`,e.selectedTerminalId,{replace:!0})}async selectMachineWithMemory(e,t={}){if(this.state.selectedMachine?.id===e.id)return;t.rememberCurrent!==!1&&!this.routeRestoreInProgress&&this.rememberCurrentMachineNavigation();let n=++this.machineNavigationRestoreSeq,r=this.machineNavigation.latest(e.id)??N_(e.id);if(await this.restoreRouteFor(F_(r),!1,r.surface,r.view),!(n!==this.machineNavigationRestoreSeq||this.state.selectedMachine?.id!==e.id)){if(this.shouldPreserveUnrestoredMachineNavigation(r)){this.machineNavigation.remember(r),this.writeMachineNavigationSnapshotToUrl(r);return}this.updateUrl()}}shouldPreserveUnrestoredMachineNavigation(e){return e.projectId!==void 0&&this.state.selectedProject?.id!==e.projectId&&this.state.error!==``}openWorkspaceTool(e){e===`core:workspace.terminal`&&(this.terminalAutoStartWorkspaceId=this.state.selectedWorkspace?.id),this.setState({workspaceTool:e,mainView:e}),this.updateUrl(),this.refreshSelectedWorkspaceTool(e),this.git.updatePolling()}openTerminal(e){e?.terminalId!==void 0&&this.selectTerminal(e.terminalId,{replace:!0}),this.openWorkspaceTool(`core:workspace.terminal`)}terminalCommandRunsForOrigin(e,t=R(this.state)){let n=HR(t,e),r=this.terminalCommandRunRuntimes.get(n);if(r!==void 0)return r;let i=BS(e,{api:{runTerminalCommand:(e,n)=>lc.runTerminalCommand(e,n,t),listCommandRuns:e=>lc.listCommandRuns(e,t),getCommandRun:e=>lc.getCommandRun(e,t)},openTerminal:(e,n)=>{this.openRuntimeTerminal(t,e,n)}}),a={...i,runCommand:async e=>{let n=await i.runCommand(e);return this.recordProjectWork({machineId:t,projectId:e.workspace.projectId}),n}};return this.terminalCommandRunRuntimes.set(n,a),a}async openRuntimeTerminal(e,t,n){return(R(this.state)!==e||t!==void 0&&(this.state.selectedWorkspace?.id!==t.id||this.state.selectedProject?.id!==t.projectId))&&(this.routeRestoreInProgress||this.rememberCurrentMachineNavigation(),await this.restoreRouteFor({machineId:e,projectId:t?.projectId,workspaceId:t?.id,sessionId:void 0,tool:`core:workspace.terminal`,view:`core:workspace.terminal`},!1,{selectedTerminalId:n?.terminalId},`core:workspace.terminal`),R(this.state)!==e)?(this.setState({error:`Machine not found for terminal command run`}),!1):(this.openTerminal(n),!0)}selectTerminal(e,t){this.rememberSelectedTerminal(e),this.setState({selectedTerminalId:e}),this.rememberCurrentMachineNavigation(),this.writeSelectedTerminalToUrl(e,t)}rememberSelectedTerminal(e){let t=this.state.selectedWorkspace;t!==void 0&&(e===void 0?this.terminalSelection.forgetWorkspace(this.terminalWorkspaceKey(t)):this.terminalSelection.rememberTerminal(this.terminalWorkspaceKey(t),e))}writeSelectedTerminalToUrl(e,t){Ql(iR,`terminal`,e,t)}terminalWorkspaceKey(e){return`${R(this.state)}:${e.path}`}selectMainView(e){if(e!==`navigation`&&e!==`chat`){this.openWorkspaceTool(e);return}this.setState({mainView:e}),this.updateUrl(),this.git.updatePolling()}openSettings(e=`general`){this.settingsSection=e,PS(e)}closeSettings(){this.settingsSection=void 0,PS(void 0)}navigateSettings(e){this.settingsSection=e,PS(e)}restoreSettingsRoute(){this.settingsSection=NS()}handleWorkspaceChange(e,t){let n=MR(e,t);if(e.selectedWorkspace?.id===t.selectedWorkspace?.id){n&&(this.synchronizeMemoryPollingForSelectedWorkspace(),this.synchronizeLearnedSkillsPollingForSelectedWorkspace());return}this.starterSessionDefaults=void 0,this.resetStarterModelPolicyForScopeChange(),this.terminalAutoStartWorkspaceId=void 0,this.activeTerminalIds.clear();let r=this.routeRestoreInProgress?this.restoringRouteTerminalId:t.selectedWorkspace===void 0?void 0:this.terminalSelection.latestTerminalId(this.terminalWorkspaceKey(t.selectedWorkspace));if(this.setState({activeTerminalCount:0,selectedTerminalId:r}),this.routeRestoreInProgress||(this.rememberCurrentMachineNavigation(),this.writeSelectedTerminalToUrl(r,{replace:!0})),t.selectedWorkspace===void 0){this.synchronizeMemoryPollingForSelectedWorkspace(),this.synchronizeLearnedSkillsPollingForSelectedWorkspace();return}this.refreshActiveTerminals(t.selectedWorkspace),this.refreshWorkspaceDeletionRuns(),this.refreshSelectedWorkspaceTool(t.workspaceTool),this.git.updatePolling(),this.synchronizeMemoryPollingForSelectedWorkspace(),this.synchronizeLearnedSkillsPollingForSelectedWorkspace()}async loadStarterSessionDefaults(e,t={}){let n=R(this.state),r=++this.starterSessionDefaultsSeq,i=this.starterModelPolicySelectionSupported(n),a=()=>r===this.starterSessionDefaultsSeq&&R(this.state)===n&&this.state.selectedWorkspace?.id===e.id&&this.state.selectedWorkspace.path===e.path&&(t.expectedSelectionGeneration===void 0||this.starterModelPolicySelectionGeneration===t.expectedSelectionGeneration);try{let r=i?await cc.sessionDefaultsV2(e.path,n):await cc.sessionDefaults(e.path,n);if(!a())return;let o=this.starterSessionDefaults;this.starterSessionDefaults=r,this.starterNotice=void 0,this.starterModelPolicyPreferenceReadError=r.starterModelPolicyPreferenceError??``;let s=this.starterModelPolicy;s===void 0||i&&!OR(o)?this.starterModelPolicy=Jc(r):i?this.starterModelPolicy=s:this.starterModelPolicy=Yc(s,r),this.completeStarterModelPolicyFromActiveTier();let c=this.starterModelPolicy;if(this.selectedMachineModelTierCatalog()===void 0&&(i||c.mode===`tiered`&&!this.modelTierCatalogLoading)){let e=this.ensureModelTierCatalog(n);t.awaitModelTierCatalog===!0&&await e}}catch(t){a()&&(console.warn(`Failed to load Pi session defaults`,t),this.publishStarterNotice(Tl(`defaults-failed`,`Could not load this workspace's model defaults. ${WR(t)}`,{machineId:n,workspaceId:e.id})))}}syncSessionUnreadMachines(){if(!this.unreadConnected){this.sessionUnread.retainMachines(new Set);return}let e=new Set(this.state.machines.map(e=>e.id));this.sessionUnread.retainMachines(e);for(let t of e){let e=this.state.machineRuntimes[t];if(e===void 0)continue;let n=this.unreadRuntimeRefreshes.has(t)||!e.ok?`unknown`:E(e,w.sessionsUnread)?`supported`:`unsupported`;this.sessionUnread.setCapability(t,n)&&this.sessionUnread.refresh(t)}}async renegotiateUnreadMachines(){if(!this.unreadConnected)return;let e=new Set(this.state.machines.map(e=>e.id));e.add(R(this.state)),await Promise.all([...e].map(async e=>{await this.renegotiateUnreadMachine(e)}))}renegotiateUnreadMachine(e){let t=this.unreadRuntimeRefreshes.get(e);if(t!==void 0)return t;this.sessionUnread.setCapability(e,`unknown`);let n=!1,r=Promise.resolve().then(async()=>{n=await this.machines.refreshMachineRuntime(e)!==void 0});this.unreadRuntimeRefreshes.set(e,r);let i=()=>{this.unreadRuntimeRefreshes.get(e)===r&&(this.unreadRuntimeRefreshes.delete(e),this.unreadConnected&&(n?this.syncSessionUnreadMachines():this.sessionUnread.setCapability(e,`unknown`)))};return r.then(i,i),r}connectRealtime(){let e=R(this.state);this.realtime.connect(t=>{this.handleRealtimeEvent(e,t)},()=>{this.renegotiateUnreadMachine(e);let t=this.state.selectedWorkspace;t!==void 0&&this.refreshActiveTerminals(t),this.refreshWorkspaceActivity(e),this.projectCatalog.refresh()},e)}syncMachineActivitySubscriptions(){let e=this.machineActivitySubscriptionIds();for(let[t,n]of this.machineRealtimeSockets.entries())e.has(t)||(n.close(),this.machineRealtimeSockets.delete(t));for(let t of e){if(this.machineRealtimeSockets.has(t))continue;let e=new gp;e.connect(e=>{this.handleMachineActivityEvent(t,e)},()=>{this.renegotiateUnreadMachine(t),this.refreshWorkspaceActivity(t)},t),this.machineRealtimeSockets.set(t,e)}}closeMachineActivitySockets(){for(let e of this.machineRealtimeSockets.values())e.close();this.machineRealtimeSockets.clear()}machineActivitySubscriptionIds(){let e=R(this.state);return new Set(this.state.machines.filter(t=>t.id!==e).filter(e=>FR(e,this.state.machineStatuses[e.id])).map(e=>e.id))}handleMachineActivityEvent(e,t){t.type===`sessions.unread`?this.sessionUnread.applyEvent(e,t):t.type===`workspace.activity`&&this.activity.applyWorkspaceActivity(t.activity,e)}handleRealtimeEvent(e,t){t.type===`sessions.unread`?this.sessionUnread.applyEvent(e,t):t.type===`workspace.activity`?this.activity.applyWorkspaceActivity(t.activity):BR(t)?(this.applyTerminalEvent(t),t.type===`terminal.exited`&&this.refreshWorkspaceDeletionRuns()):this.sessions.applyGlobalEvent(t)}applyTerminalEvent(e){let t=this.state.selectedWorkspace;t!==void 0&&(e.type===`terminal.closed`?e.cwd:e.terminal.cwd)===t.path&&(e.type===`terminal.created`&&!e.terminal.exited?this.activeTerminalIds.add(e.terminal.id):this.activeTerminalIds.delete(e.type===`terminal.closed`?e.terminalId:e.terminal.id),e.type===`terminal.closed`&&(this.terminalSelection.forgetTerminal(e.terminalId),this.state.selectedTerminalId===e.terminalId&&this.selectTerminal(void 0,{replace:!0})),this.setState({activeTerminalCount:this.activeTerminalIds.size}))}async refreshActiveTerminals(e){let t=R(this.state);try{let n=await lc.terminals(e.projectId,e.id,t);if(R(this.state)!==t||this.state.selectedWorkspace?.id!==e.id)return;this.activeTerminalIds.clear();for(let e of n)e.exited||this.activeTerminalIds.add(e.id);this.setState({activeTerminalCount:this.activeTerminalIds.size})}catch(e){this.setState({error:String(e)})}}handleActivityTransition(e,t){let n=zR(e),r=zR(t);n&&!r&&(this.setState({fileTreeStale:!0,gitStale:!0}),this.refreshSelectedWorkspaceTool(this.state.workspaceTool))}handleMachineChange(e,t){if((e.selectedMachine?.id??`local`)===(t.selectedMachine?.id??`local`))return;this.closeRecentProjectDialogForMachineChange(),this.closeProjectStatistics(),this.projectActivityOwnership.handleSelectedMachineChanged(),(this.pendingRemoteRouteRestore?.machineId??`local`)!==(t.selectedMachine?.id??`local`)&&this.clearPendingRemoteRouteRestore(),this.sessions.clearActiveSession(),this.starterSessionDefaults=void 0,this.resetStarterModelPolicyForScopeChange(),this.resetModelTierCatalogForMachineChange(),this.realtime.close(),this.connectRealtime(),this.activeTerminalIds.clear(),this.sessionCleanupDialog=void 0,this.setState({piWebUiStatus:void 0}),this.git.updatePolling(),this.recentProjects.load(),this.loadPluginsForSelectedMachine();let n=t.selectedWorkspace;n!==void 0&&this.shouldShowSessionStartScreen(t)&&this.loadStarterSessionDefaults(n)}refreshSelectedWorkspaceTool(e){e===`core:workspace.files`&&this.files.refreshFiles(),e===`core:workspace.git`&&this.git.refreshGit()}renderWorkspacePanel(){return g`
|
|
7375
7375
|
<workspace-panel
|
|
7376
7376
|
id="workspace-panel"
|
|
7377
7377
|
.emptyState=${this.state.selectedWorkspace===void 0?this.workspacePanelEmptyState():void 0}
|
|
@@ -7428,7 +7428,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
7428
7428
|
.onResizeEnd=${()=>{this.panelResize.persistPanelSizes()}}
|
|
7429
7429
|
.onReset=${()=>{this.resetResizablePanel(`workspace`)}}
|
|
7430
7430
|
></app-panel-edge-control>
|
|
7431
|
-
`}startPanelResize(e){return e===`navigation`?this.panelCollapse.expandNavigationPanel():this.panelCollapse.expandWorkspacePanel(),this.measuredPanelWidth(e)??this.panelResize.panelWidth(e)}resizablePanelConstraints(e){let t=this.panelResize.constraints(e);return{...t,maxWidth:this.resizablePanelMaxWidth(e,t)}}resizablePanelMaxWidth(e,t){let n=this.getBoundingClientRect().width||(typeof window>`u`?0:window.innerWidth);if(n<=0)return t.maxWidth;let r=this.oppositeResizablePanelWidth(e),i=Math.floor(n-r-dR-uR);return Math.max(t.minWidth,Math.min(t.maxWidth,i))}oppositeResizablePanelWidth(e){let t=e===`navigation`?`workspace`:`navigation`;return this.isResizablePanelCollapsedOrStacked(t)?0:this.measuredPanelWidth(t)??this.panelResize.panelWidth(t)}isResizablePanelCollapsedOrStacked(e){return e===`navigation`?this.panelCollapse.navigationPanelCollapsed:this.panelCollapse.workspacePanelCollapsed||!this.isDesktopSideBySideLayout()}isDesktopSideBySideLayout(){return typeof window>`u`||!(`matchMedia`in window)||window.matchMedia(fR).matches}measuredPanelWidth(e){let t=(e===`navigation`?this.navigationPanelFrame:this.workspacePanelFrame)?.getBoundingClientRect().width;return t===void 0||t<=0?void 0:t}resetResizablePanel(e){this.panelResize.resetPanel(e)}resetResizablePanels(){this.panelResize.resetPanels()}canDeleteArchivedSessions(){let e=this.selectedMachineRuntime();return e?.ok!==!0||E(e,w.sessionsDeleteArchived)}get projectStatisticsAvailable(){let e=this.selectedMachineRuntime();return e?.ok===!0&&E(e,w.projectUsageStatistics)}canReloadSessions(){let e=this.selectedMachineRuntime();return e?.ok===!0&&E(e,w.sessionsReload)}canReorderSessions(){let e=this.selectedMachineRuntime();return e?.ok===!0&&E(e,w.sessionsReorder)}canClearServerQueue(){let e=this.selectedMachineRuntime();return e?.ok===!0&&E(e,w.sessionsClearQueue)}canMessageActions(){let e=this.selectedMachineRuntime();return e?.ok===!0&&E(e,w.sessionsMessageActions)}canViewSystemPrompt(){let e=this.selectedMachineRuntime();return e?.ok===!0&&E(e,w.sessionsSystemPrompt)}canCleanupSessions(){let e=this.selectedMachineRuntime();return e?.ok===!0&&E(e,w.sessionsCleanup)}hasAuthoritativeSessionPersistence(){return zp(this.selectedMachineRuntime())}supportsWorkspaceFileSuggestions(e=R(this.state)){if(e===`local`)return!0;let t=this.state.machineRuntimes[e];return t?.ok===!0&&E(t,w.workspaceFileSuggestions)}sessionModelPolicySupported(e=R(this.state)){return TR(this.state,e)}starterModelPolicySelectionSupported(e=R(this.state)){return ER(this.state,e)}handleStarterModelPolicyCapabilityChange(e,t){let n=R(t);if(R(e)!==n||ER(e,n)||!ER(t,n)||!this.shouldShowSessionStartScreen(t))return;let r=t.selectedWorkspace;r!==void 0&&this.loadStarterSessionDefaults(r)}starterModelPolicyPreferenceScope(){let e=this.state.selectedWorkspace;if(e!==void 0)return{machineId:R(this.state),cwd:e.path}}starterModelPolicyPreferenceScopeMatchesCurrentSelection(e){let t=this.starterModelPolicyPreferenceScope();return t?.machineId===e.machineId&&t.cwd===e.cwd}handleStarterModelPolicyConfirmed(e){let t={machineId:e.machineId,cwd:e.session.cwd},n=this.starterModelPolicyPreferenceScopeMatchesCurrentSelection(t);n&&this.state.selectedSession?.id===e.session.id&&this.state.selectedSession.cwd===e.session.cwd?(this.starterModelPolicy=Wc(e.policy),this.starterModelPolicyPreferenceReadError=``,this.confirmedStarterModelPolicyUiScope=t,this.confirmedStarterModelPolicyUiGeneration=this.starterModelPolicySelectionGeneration):n&&(this.confirmedStarterModelPolicyUiScope!==void 0||this.confirmedStarterModelPolicyUiGeneration!==void 0)&&(this.confirmedStarterModelPolicyUiScope=void 0,this.confirmedStarterModelPolicyUiGeneration=void 0,this.requestUpdate()),this.confirmedStarterModelPolicyPreferenceWriter.write(t,e.session)}starterNoticeScope(){let e=this.state.selectedWorkspace;if(e!==void 0)return{machineId:R(this.state),workspaceId:e.id}}publishStarterNotice(e){let t=this.starterNoticeScope();t?.machineId!==e.scope.machineId||t.workspaceId!==e.scope.workspaceId||(this.starterNotice=e)}syncStarterNotice(){let e=this.starterNotice;e!==void 0&&(Dl(e,this.starterNoticeScope(),this.starterModelPolicyInputs()?.status.blockedReason)||(this.starterNotice=void 0))}starterModelPolicyPreferenceSupported(e){let t=this.state.machineRuntimes[e];return t?.ok===!0&&E(t,w.sessionsModelPolicyDefaults)}persistStarterModelPolicyPreference(e){let t=this.starterModelPolicyPreferenceScope(),n=Xc(e);t===void 0||n===void 0||!this.starterModelPolicyPreferenceSupported(t.machineId)||this.starterModelPolicyPreferenceWriter.write(t,n)}loadModelTierCatalog(e){let t=this.state.selectedWorkspace?.id,n=++this.modelTierCatalogSeq,r=this.performModelTierCatalogLoad(e,t,n);this.modelTierCatalogLoad={machineId:e,workspaceId:t,promise:r};let i=()=>{this.modelTierCatalogLoad?.promise===r&&(this.modelTierCatalogLoad=void 0)};return r.then(i,i),r}async performModelTierCatalogLoad(e,t,n){let r=()=>n===this.modelTierCatalogSeq&&R(this.state)===e&&this.state.selectedWorkspace?.id===t;this.modelTierCatalogLoading=!0,this.modelTierCatalogError=``;try{let t=await Ks.settings(e);if(!r())return;this.modelTierCatalogMachineId=e,this.modelTierCatalog=t,this.completeStarterModelPolicyFromActiveTier()}catch(e){if(!r())return;this.modelTierCatalogError=UR(e)}finally{n===this.modelTierCatalogSeq&&(this.modelTierCatalogLoading=!1)}}ensureModelTierCatalog(e){if(this.selectedMachineModelTierCatalog()!==void 0)return Promise.resolve();let t=this.state.selectedWorkspace?.id,n=this.modelTierCatalogLoad;return n?.machineId===e&&n.workspaceId===t?n.promise:this.loadModelTierCatalog(e)}resetStarterModelPolicyForScopeChange(){this.starterSessionDefaultsSeq+=1,this.starterModelPolicySelectionGeneration+=1,this.starterModelPolicy=void 0,this.starterModelPolicyPreferenceReadError=``,this.starterNotice=void 0,this.modelTierCatalogError=``}resetModelTierCatalogForMachineChange(){this.modelTierCatalogSeq+=1,this.modelTierCatalogLoad=void 0,this.modelTierCatalogMachineId=void 0,this.modelTierCatalog=void 0,this.modelTierCatalogLoading=!1,this.modelTierCatalogError=``}handleModelTiersSaved(e,t){R(this.state)===e&&(this.modelTierCatalogMachineId=e,this.modelTierCatalog=t,this.modelTierCatalogError=``,this.modelTierCatalogSeq+=1,this.modelTierCatalogLoad=void 0,this.modelTierCatalogLoading=!1,this.completeStarterModelPolicyFromActiveTier(),CR(this.state)!==void 0&&this.sessions.loadModelPolicy())}completeStarterModelPolicyFromActiveTier(){let e=this.starterSessionDefaults,t=this.starterModelPolicy,n=this.selectedMachineModelTierCatalog();if(e===void 0||t===void 0||n===void 0)return;let r=il(t,e,n);OR(t,r)||(this.starterModelPolicy=r)}selectedMachineModelTierCatalog(){if(this.modelTierCatalogMachineId===R(this.state))return this.modelTierCatalog}preloadActiveModelPolicyInputs(){this.sessions.loadModelPolicy(),this.ensureModelTierCatalog(R(this.state))}async prepareActiveModelPolicyDraft(){if(!this.sessionModelPolicySupported())return;let e=xR(this.state);if(e===void 0||wR(this.state)===void 0)return;let t=this.activeModelPolicyDraftForState(this.state);if(t!==void 0)return t;let n=[];if(this.state.modelPolicy===void 0&&n.push(this.sessions.loadModelPolicy()),this.selectedMachineModelTierCatalog()===void 0&&n.push(this.ensureModelTierCatalog(R(this.state))),await Promise.all(n),xR(this.state)!==e)return;let r=this.activeModelPolicyDraftForState(this.state);if(r!==void 0)return r;let i=this.selectedMachineModelTierCatalog(),a=wR(this.state);if(i===void 0||a===void 0)return;let o=this.state.modelPolicy?.policy,s;if(o!==void 0)s=Gc({policy:o,catalog:i});else if(a.mode===`exact`)s=Gc({liveResolved:a.resolved,catalog:i});else{let e=Gc({catalog:i});s=a.tier===void 0?{...e,mode:`tiered`}:Qc(e,a.tier)}return this.activeModelPolicyDraftScope=e,this.activeModelPolicyDraft=s,s}activeModelPolicyDraftForState(e){return this.activeModelPolicyDraftScope===xR(e)?this.activeModelPolicyDraft:void 0}setActiveModelPolicyDraft(e){let t=xR(this.state);t!==void 0&&(this.activeModelPolicyDraftScope=t,this.activeModelPolicyDraft=e)}resetActiveModelPolicyDraft(){this.cancelActiveModelPolicyApply(),this.activeModelPolicyDraftScope=void 0,this.activeModelPolicyDraft=void 0}cancelActiveModelPolicyApply(){this.activeModelPolicyApplyGeneration+=1,this.activeModelPolicyApplyTimer!==void 0&&window.clearTimeout(this.activeModelPolicyApplyTimer),this.activeModelPolicyApplyTimer=void 0}scheduleActiveExactModelPolicyApply(){this.cancelActiveModelPolicyApply();let e=this.activeModelPolicyDraftForState(this.state),t=this.selectedMachineModelTierCatalog();if(e?.mode!==`exact`||!rl(e,t))return;let n=this.activeModelPolicyApplyGeneration;this.activeModelPolicyApplyTimer=window.setTimeout(()=>{n===this.activeModelPolicyApplyGeneration&&(this.activeModelPolicyApplyTimer=void 0,this.applyActiveModelPolicyDraft())},pR)}async applyActiveModelPolicyDraft(){let e=this.activeModelPolicyDraftForState(this.state),t=this.selectedMachineModelTierCatalog();if(e===void 0||!rl(e,t)||t===void 0)return;let n=nl(e,t);if(n===void 0)return;let r=this.activeModelPolicyDraftScope,i=this.state.modelPolicy;if(await this.sessions.saveModelPolicy(n),r!==xR(this.state)||this.activeModelPolicyDraft!==e)return;if(this.state.modelPolicyError!==void 0){this.activeModelPolicyDraftScope=void 0,this.activeModelPolicyDraft=void 0;return}if(this.state.modelPolicy===i)return;let a=this.state.modelPolicy?.policy;if(a===void 0){this.activeModelPolicyDraftScope=void 0,this.activeModelPolicyDraft=void 0;return}this.setActiveModelPolicyDraft(Gc({policy:a,catalog:t}))}policyThinkingOptions(e,t){let n=this.selectedMachineModelTierCatalog(),r=n?.models.find(t=>t.model.provider===e.model.provider&&t.model.id===e.model.id);return Pl({supported:n===void 0?t:r?.thinkingLevels??[],all:e.thinkingLevel===``||t.includes(e.thinkingLevel)?t:[e.thinkingLevel,...t],selected:e.thinkingLevel})}archivedDeleteUnavailableMessage(){return`Update and restart Pi-Web on ${this.state.selectedMachine?.name??`this machine`} to delete archived sessions.`}sessionCleanupUnavailableMessage(){return Vv(this.state.selectedMachine?.name)}selectedMachineRuntime(){return this.state.machineRuntimes[R(this.state)]}openSessionCleanupDialog(){this.sessionCleanupDialog={error:``}}closeSessionCleanupDialog(){this.sessionCleanupDialog=void 0}async previewSessionCleanup(e){if(!this.canCleanupSessions()){this.sessionCleanupDialog={...this.sessionCleanupDialog??{},error:this.sessionCleanupUnavailableMessage(),preview:void 0,previewRequest:void 0,result:void 0,loading:!1};return}let t=R(this.state);this.sessionCleanupDialog={...this.sessionCleanupDialog??{},loading:!0,error:``,preview:void 0,previewRequest:void 0,result:void 0};try{let n=await cc.cleanupPreview(e,t);if(R(this.state)!==t)return;this.sessionCleanupDialog={...this.sessionCleanupDialog,preview:n,previewRequest:e,result:void 0,loading:!1,error:``}}catch(e){R(this.state)===t&&(this.sessionCleanupDialog={...this.sessionCleanupDialog,loading:!1,error:`Failed to preview cleanup: ${UR(e)}`})}}async runSessionCleanup(e){let t=this.sessionCleanupDialog;if(t?.preview===void 0||Pv(t.previewRequest)!==Pv(e)){this.sessionCleanupDialog={...t??{},error:`Preview cleanup before running it.`};return}if(!this.canCleanupSessions()){this.sessionCleanupDialog={...t,error:this.sessionCleanupUnavailableMessage(),running:!1};return}let n=R(this.state);this.sessionCleanupDialog={...t,running:!0,error:``};try{let t=await cc.cleanup(e,n);if(R(this.state)!==n)return;this.sessionCleanupDialog={...this.sessionCleanupDialog,preview:t,previewRequest:e,result:t,running:!1,error:``},await this.sessions.applySessionCleanupResult(t,n)}catch(e){R(this.state)===n&&(this.sessionCleanupDialog={...this.sessionCleanupDialog,running:!1,error:`Failed to run cleanup: ${UR(e)}`})}}async runForceSessionCleanup(){let e=this.sessionCleanupDialog;if(!this.canCleanupSessions()){this.sessionCleanupDialog={...e??{},error:this.sessionCleanupUnavailableMessage(),runningForce:!1};return}let t=R(this.state);this.sessionCleanupDialog={...e??{},runningForce:!0,error:``};try{let e=await cc.forceCleanup(t);if(R(this.state)!==t)return;this.sessionCleanupDialog={...this.sessionCleanupDialog,forceCleanupResult:e,runningForce:!1,error:``},await this.sessions.applySessionCleanupResult(e,t)}catch(e){R(this.state)===t&&(this.sessionCleanupDialog={...this.sessionCleanupDialog,runningForce:!1,error:`Failed to force cleanup: ${UR(e)}`})}}renderNavigationPanel(){return g`
|
|
7431
|
+
`}startPanelResize(e){return e===`navigation`?this.panelCollapse.expandNavigationPanel():this.panelCollapse.expandWorkspacePanel(),this.measuredPanelWidth(e)??this.panelResize.panelWidth(e)}resizablePanelConstraints(e){let t=this.panelResize.constraints(e);return{...t,maxWidth:this.resizablePanelMaxWidth(e,t)}}resizablePanelMaxWidth(e,t){let n=this.getBoundingClientRect().width||(typeof window>`u`?0:window.innerWidth);if(n<=0)return t.maxWidth;let r=this.oppositeResizablePanelWidth(e),i=Math.floor(n-r-fR-dR);return Math.max(t.minWidth,Math.min(t.maxWidth,i))}oppositeResizablePanelWidth(e){let t=e===`navigation`?`workspace`:`navigation`;return this.isResizablePanelCollapsedOrStacked(t)?0:this.measuredPanelWidth(t)??this.panelResize.panelWidth(t)}isResizablePanelCollapsedOrStacked(e){return e===`navigation`?this.panelCollapse.navigationPanelCollapsed:this.panelCollapse.workspacePanelCollapsed||!this.isDesktopSideBySideLayout()}isDesktopSideBySideLayout(){return typeof window>`u`||!(`matchMedia`in window)||window.matchMedia(pR).matches}measuredPanelWidth(e){let t=(e===`navigation`?this.navigationPanelFrame:this.workspacePanelFrame)?.getBoundingClientRect().width;return t===void 0||t<=0?void 0:t}resetResizablePanel(e){this.panelResize.resetPanel(e)}resetResizablePanels(){this.panelResize.resetPanels()}canDeleteArchivedSessions(){let e=this.selectedMachineRuntime();return e?.ok!==!0||E(e,w.sessionsDeleteArchived)}get projectStatisticsAvailable(){let e=this.selectedMachineRuntime();return e?.ok===!0&&E(e,w.projectUsageStatistics)}canReloadSessions(){let e=this.selectedMachineRuntime();return e?.ok===!0&&E(e,w.sessionsReload)}canReorderSessions(){let e=this.selectedMachineRuntime();return e?.ok===!0&&E(e,w.sessionsReorder)}canClearServerQueue(){let e=this.selectedMachineRuntime();return e?.ok===!0&&E(e,w.sessionsClearQueue)}canMessageActions(){let e=this.selectedMachineRuntime();return e?.ok===!0&&E(e,w.sessionsMessageActions)}canViewSystemPrompt(){let e=this.selectedMachineRuntime();return e?.ok===!0&&E(e,w.sessionsSystemPrompt)}canCleanupSessions(){let e=this.selectedMachineRuntime();return e?.ok===!0&&E(e,w.sessionsCleanup)}hasAuthoritativeSessionPersistence(){return zp(this.selectedMachineRuntime())}supportsWorkspaceFileSuggestions(e=R(this.state)){if(e===`local`)return!0;let t=this.state.machineRuntimes[e];return t?.ok===!0&&E(t,w.workspaceFileSuggestions)}sessionModelPolicySupported(e=R(this.state)){return ER(this.state,e)}starterModelPolicySelectionSupported(e=R(this.state)){return DR(this.state,e)}handleStarterModelPolicyCapabilityChange(e,t){let n=R(t);if(R(e)!==n||DR(e,n)||!DR(t,n)||!this.shouldShowSessionStartScreen(t))return;let r=t.selectedWorkspace;r!==void 0&&this.loadStarterSessionDefaults(r)}starterModelPolicyPreferenceScope(){let e=this.state.selectedWorkspace;if(e!==void 0)return{machineId:R(this.state),cwd:e.path}}starterModelPolicyPreferenceScopeMatchesCurrentSelection(e){let t=this.starterModelPolicyPreferenceScope();return t?.machineId===e.machineId&&t.cwd===e.cwd}handleStarterModelPolicyConfirmed(e){let t={machineId:e.machineId,cwd:e.session.cwd},n=this.starterModelPolicyPreferenceScopeMatchesCurrentSelection(t);n&&this.state.selectedSession?.id===e.session.id&&this.state.selectedSession.cwd===e.session.cwd?(this.starterModelPolicy=Wc(e.policy),this.starterModelPolicyPreferenceReadError=``,this.confirmedStarterModelPolicyUiScope=t,this.confirmedStarterModelPolicyUiGeneration=this.starterModelPolicySelectionGeneration):n&&(this.confirmedStarterModelPolicyUiScope!==void 0||this.confirmedStarterModelPolicyUiGeneration!==void 0)&&(this.confirmedStarterModelPolicyUiScope=void 0,this.confirmedStarterModelPolicyUiGeneration=void 0,this.requestUpdate()),this.confirmedStarterModelPolicyPreferenceWriter.write(t,e.session)}starterNoticeScope(){let e=this.state.selectedWorkspace;if(e!==void 0)return{machineId:R(this.state),workspaceId:e.id}}publishStarterNotice(e){let t=this.starterNoticeScope();t?.machineId!==e.scope.machineId||t.workspaceId!==e.scope.workspaceId||(this.starterNotice=e)}syncStarterNotice(){let e=this.starterNotice;e!==void 0&&(Dl(e,this.starterNoticeScope(),this.starterModelPolicyInputs()?.status.blockedReason)||(this.starterNotice=void 0))}starterModelPolicyPreferenceSupported(e){let t=this.state.machineRuntimes[e];return t?.ok===!0&&E(t,w.sessionsModelPolicyDefaults)}persistStarterModelPolicyPreference(e){let t=this.starterModelPolicyPreferenceScope(),n=Xc(e);t===void 0||n===void 0||!this.starterModelPolicyPreferenceSupported(t.machineId)||this.starterModelPolicyPreferenceWriter.write(t,n)}loadModelTierCatalog(e){let t=this.state.selectedWorkspace?.id,n=++this.modelTierCatalogSeq,r=this.performModelTierCatalogLoad(e,t,n);this.modelTierCatalogLoad={machineId:e,workspaceId:t,promise:r};let i=()=>{this.modelTierCatalogLoad?.promise===r&&(this.modelTierCatalogLoad=void 0)};return r.then(i,i),r}async performModelTierCatalogLoad(e,t,n){let r=()=>n===this.modelTierCatalogSeq&&R(this.state)===e&&this.state.selectedWorkspace?.id===t;this.modelTierCatalogLoading=!0,this.modelTierCatalogError=``;try{let t=await Ks.settings(e);if(!r())return;this.modelTierCatalogMachineId=e,this.modelTierCatalog=t,this.completeStarterModelPolicyFromActiveTier()}catch(e){if(!r())return;this.modelTierCatalogError=WR(e)}finally{n===this.modelTierCatalogSeq&&(this.modelTierCatalogLoading=!1)}}ensureModelTierCatalog(e){if(this.selectedMachineModelTierCatalog()!==void 0)return Promise.resolve();let t=this.state.selectedWorkspace?.id,n=this.modelTierCatalogLoad;return n?.machineId===e&&n.workspaceId===t?n.promise:this.loadModelTierCatalog(e)}resetStarterModelPolicyForScopeChange(){this.starterSessionDefaultsSeq+=1,this.starterModelPolicySelectionGeneration+=1,this.starterModelPolicy=void 0,this.starterModelPolicyPreferenceReadError=``,this.starterNotice=void 0,this.modelTierCatalogError=``}resetModelTierCatalogForMachineChange(){this.modelTierCatalogSeq+=1,this.modelTierCatalogLoad=void 0,this.modelTierCatalogMachineId=void 0,this.modelTierCatalog=void 0,this.modelTierCatalogLoading=!1,this.modelTierCatalogError=``}handleModelTiersSaved(e,t){R(this.state)===e&&(this.modelTierCatalogMachineId=e,this.modelTierCatalog=t,this.modelTierCatalogError=``,this.modelTierCatalogSeq+=1,this.modelTierCatalogLoad=void 0,this.modelTierCatalogLoading=!1,this.completeStarterModelPolicyFromActiveTier(),wR(this.state)!==void 0&&this.sessions.loadModelPolicy())}completeStarterModelPolicyFromActiveTier(){let e=this.starterSessionDefaults,t=this.starterModelPolicy,n=this.selectedMachineModelTierCatalog();if(e===void 0||t===void 0||n===void 0)return;let r=il(t,e,n);kR(t,r)||(this.starterModelPolicy=r)}selectedMachineModelTierCatalog(){if(this.modelTierCatalogMachineId===R(this.state))return this.modelTierCatalog}preloadActiveModelPolicyInputs(){this.sessions.loadModelPolicy(),this.ensureModelTierCatalog(R(this.state))}async prepareActiveModelPolicyDraft(){if(!this.sessionModelPolicySupported())return;let e=SR(this.state);if(e===void 0||TR(this.state)===void 0)return;let t=this.activeModelPolicyDraftForState(this.state);if(t!==void 0)return t;let n=[];if(this.state.modelPolicy===void 0&&n.push(this.sessions.loadModelPolicy()),this.selectedMachineModelTierCatalog()===void 0&&n.push(this.ensureModelTierCatalog(R(this.state))),await Promise.all(n),SR(this.state)!==e)return;let r=this.activeModelPolicyDraftForState(this.state);if(r!==void 0)return r;let i=this.selectedMachineModelTierCatalog(),a=TR(this.state);if(i===void 0||a===void 0)return;let o=this.state.modelPolicy?.policy,s;if(o!==void 0)s=Gc({policy:o,catalog:i});else if(a.mode===`exact`)s=Gc({liveResolved:a.resolved,catalog:i});else{let e=Gc({catalog:i});s=a.tier===void 0?{...e,mode:`tiered`}:Qc(e,a.tier)}return this.activeModelPolicyDraftScope=e,this.activeModelPolicyDraft=s,s}activeModelPolicyDraftForState(e){return this.activeModelPolicyDraftScope===SR(e)?this.activeModelPolicyDraft:void 0}setActiveModelPolicyDraft(e){let t=SR(this.state);t!==void 0&&(this.activeModelPolicyDraftScope=t,this.activeModelPolicyDraft=e)}resetActiveModelPolicyDraft(){this.cancelActiveModelPolicyApply(),this.activeModelPolicyDraftScope=void 0,this.activeModelPolicyDraft=void 0}cancelActiveModelPolicyApply(){this.activeModelPolicyApplyGeneration+=1,this.activeModelPolicyApplyTimer!==void 0&&window.clearTimeout(this.activeModelPolicyApplyTimer),this.activeModelPolicyApplyTimer=void 0}scheduleActiveExactModelPolicyApply(){this.cancelActiveModelPolicyApply();let e=this.activeModelPolicyDraftForState(this.state),t=this.selectedMachineModelTierCatalog();if(e?.mode!==`exact`||!rl(e,t))return;let n=this.activeModelPolicyApplyGeneration;this.activeModelPolicyApplyTimer=window.setTimeout(()=>{n===this.activeModelPolicyApplyGeneration&&(this.activeModelPolicyApplyTimer=void 0,this.applyActiveModelPolicyDraft())},mR)}async applyActiveModelPolicyDraft(){let e=this.activeModelPolicyDraftForState(this.state),t=this.selectedMachineModelTierCatalog();if(e===void 0||!rl(e,t)||t===void 0)return;let n=nl(e,t);if(n===void 0)return;let r=this.activeModelPolicyDraftScope,i=this.state.modelPolicy;if(await this.sessions.saveModelPolicy(n),r!==SR(this.state)||this.activeModelPolicyDraft!==e)return;if(this.state.modelPolicyError!==void 0){this.activeModelPolicyDraftScope=void 0,this.activeModelPolicyDraft=void 0;return}if(this.state.modelPolicy===i)return;let a=this.state.modelPolicy?.policy;if(a===void 0){this.activeModelPolicyDraftScope=void 0,this.activeModelPolicyDraft=void 0;return}this.setActiveModelPolicyDraft(Gc({policy:a,catalog:t}))}policyThinkingOptions(e,t){let n=this.selectedMachineModelTierCatalog(),r=n?.models.find(t=>t.model.provider===e.model.provider&&t.model.id===e.model.id);return Pl({supported:n===void 0?t:r?.thinkingLevels??[],all:e.thinkingLevel===``||t.includes(e.thinkingLevel)?t:[e.thinkingLevel,...t],selected:e.thinkingLevel})}archivedDeleteUnavailableMessage(){return`Update and restart Pi-Web on ${this.state.selectedMachine?.name??`this machine`} to delete archived sessions.`}sessionCleanupUnavailableMessage(){return Vv(this.state.selectedMachine?.name)}selectedMachineRuntime(){return this.state.machineRuntimes[R(this.state)]}openSessionCleanupDialog(){this.sessionCleanupDialog={error:``}}closeSessionCleanupDialog(){this.sessionCleanupDialog=void 0}async previewSessionCleanup(e){if(!this.canCleanupSessions()){this.sessionCleanupDialog={...this.sessionCleanupDialog??{},error:this.sessionCleanupUnavailableMessage(),preview:void 0,previewRequest:void 0,result:void 0,loading:!1};return}let t=R(this.state);this.sessionCleanupDialog={...this.sessionCleanupDialog??{},loading:!0,error:``,preview:void 0,previewRequest:void 0,result:void 0};try{let n=await cc.cleanupPreview(e,t);if(R(this.state)!==t)return;this.sessionCleanupDialog={...this.sessionCleanupDialog,preview:n,previewRequest:e,result:void 0,loading:!1,error:``}}catch(e){R(this.state)===t&&(this.sessionCleanupDialog={...this.sessionCleanupDialog,loading:!1,error:`Failed to preview cleanup: ${WR(e)}`})}}async runSessionCleanup(e){let t=this.sessionCleanupDialog;if(t?.preview===void 0||Pv(t.previewRequest)!==Pv(e)){this.sessionCleanupDialog={...t??{},error:`Preview cleanup before running it.`};return}if(!this.canCleanupSessions()){this.sessionCleanupDialog={...t,error:this.sessionCleanupUnavailableMessage(),running:!1};return}let n=R(this.state);this.sessionCleanupDialog={...t,running:!0,error:``};try{let t=await cc.cleanup(e,n);if(R(this.state)!==n)return;this.sessionCleanupDialog={...this.sessionCleanupDialog,preview:t,previewRequest:e,result:t,running:!1,error:``},await this.sessions.applySessionCleanupResult(t,n)}catch(e){R(this.state)===n&&(this.sessionCleanupDialog={...this.sessionCleanupDialog,running:!1,error:`Failed to run cleanup: ${WR(e)}`})}}async runForceSessionCleanup(){let e=this.sessionCleanupDialog;if(!this.canCleanupSessions()){this.sessionCleanupDialog={...e??{},error:this.sessionCleanupUnavailableMessage(),runningForce:!1};return}let t=R(this.state);this.sessionCleanupDialog={...e??{},runningForce:!0,error:``};try{let e=await cc.forceCleanup(t);if(R(this.state)!==t)return;this.sessionCleanupDialog={...this.sessionCleanupDialog,forceCleanupResult:e,runningForce:!1,error:``},await this.sessions.applySessionCleanupResult(e,t)}catch(e){R(this.state)===t&&(this.sessionCleanupDialog={...this.sessionCleanupDialog,runningForce:!1,error:`Failed to force cleanup: ${WR(e)}`})}}renderNavigationPanel(){return g`
|
|
7432
7432
|
<app-navigation-panel
|
|
7433
7433
|
.machines=${this.state.machines}
|
|
7434
7434
|
.selectedMachine=${this.state.selectedMachine}
|
|
@@ -7511,7 +7511,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
7511
7511
|
.onFocusNavigationTarget=${e=>{this.focusNavigationTarget(e)}}
|
|
7512
7512
|
.onCancelKeyboardNavigation=${()=>{this.focusChatComposer()}}
|
|
7513
7513
|
></app-navigation-panel>
|
|
7514
|
-
`}canOpenSessionHistory(){let e=this.state.selectedSession;return e!==void 0&&e.persisted!==!1&&e.path!==``}openSessionHistory(){let e=this.state.selectedSession;e===void 0||!this.canOpenSessionHistory()||(this.historyWindow={machineId:R(this.state),session:e})}openNavigationSection(e){this.navigationSections.open(e,()=>{this.selectMainView(`navigation`)})}cancelPendingNavigationSelection(){this.navigationSelectionSeq+=1}async selectNavigationItem(e,t,n){let r=++this.navigationSelectionSeq,i=()=>r===this.navigationSelectionSeq;await this.withChatScrollTransition(async()=>{this.navigationSections.advanceAfterSelection(e),await n()},i),i()&&await this.focusNavigationTarget(t)}async selectSessionFromNavigation(e){if(this.state.selectedWorkspace?.path===e.cwd){await this.sessions.selectSession(e);return}let t=this.state.workspaces.find(t=>t.path===e.cwd);if(t===void 0){this.setState({error:`The session's workspace is no longer available.`});return}await this.workspaces.selectWorkspace(t,{sessionId:e.id})}async startSessionFromNavigation(){let e=++this.navigationSelectionSeq;this.navigationSections.advanceAfterSelection(`sessions`),await this.startSessionAndOpenChat(()=>e===this.navigationSelectionSeq)}async startSessionAndOpenChat(e=()=>!0){let t=this.state.selectedWorkspace;if(t===void 0)return;let n=R(this.state),r=this.starterModelPolicySelectionGeneration,i=this.starterModelPolicySelectionSupported(n),a=this.starterPlusModelPolicyInitializer();if(i&&a===void 0&&(this.starterModelPolicy===void 0||this.selectedMachineModelTierCatalog()===void 0)){if(await this.loadMissingStarterPlusModelPolicyInputs(t,n,r),!e()||this.starterModelPolicySelectionGeneration!==r)return;i=this.starterModelPolicySelectionSupported(n),a=this.starterPlusModelPolicyInitializer()}if(this.starterModelPolicyInputs()?.status.blockedReason!==void 0){let t=this.starterNoticeScope();e()&&t!==void 0&&this.publishStarterNotice(wl(t));return}if(i&&a===void 0)return;this.starterNotice=void 0;let o=t.id,s=this.starterModelPolicy;(a===void 0?this.sessions.startSession(this.starterModelPolicyStartSnapshot()):this.sessions.startPlusSession(a)).then(e=>{i||this.clearStarterModelPolicyAfterSuccessfulStart(e,o,s)}).catch(t=>{if(e()){let e={machineId:n,workspaceId:o};this.publishStarterNotice(Tl(`start-failed`,`Could not start the session. ${
|
|
7514
|
+
`}canOpenSessionHistory(){let e=this.state.selectedSession;return e!==void 0&&e.persisted!==!1&&e.path!==``}openSessionHistory(){let e=this.state.selectedSession;e===void 0||!this.canOpenSessionHistory()||(this.historyWindow={machineId:R(this.state),session:e})}openNavigationSection(e){this.navigationSections.open(e,()=>{this.selectMainView(`navigation`)})}cancelPendingNavigationSelection(){this.navigationSelectionSeq+=1}async selectNavigationItem(e,t,n){let r=++this.navigationSelectionSeq,i=()=>r===this.navigationSelectionSeq;await this.withChatScrollTransition(async()=>{this.navigationSections.advanceAfterSelection(e),await n()},i),i()&&await this.focusNavigationTarget(t)}async selectSessionFromNavigation(e){if(this.state.selectedWorkspace?.path===e.cwd){await this.sessions.selectSession(e);return}let t=this.state.workspaces.find(t=>t.path===e.cwd);if(t===void 0){this.setState({error:`The session's workspace is no longer available.`});return}await this.workspaces.selectWorkspace(t,{sessionId:e.id})}async startSessionFromNavigation(){let e=++this.navigationSelectionSeq;this.navigationSections.advanceAfterSelection(`sessions`),await this.startSessionAndOpenChat(()=>e===this.navigationSelectionSeq)}async startSessionAndOpenChat(e=()=>!0){let t=this.state.selectedWorkspace;if(t===void 0)return;let n=R(this.state),r=this.starterModelPolicySelectionGeneration,i=this.starterModelPolicySelectionSupported(n),a=this.starterPlusModelPolicyInitializer();if(i&&a===void 0&&(this.starterModelPolicy===void 0||this.selectedMachineModelTierCatalog()===void 0)){if(await this.loadMissingStarterPlusModelPolicyInputs(t,n,r),!e()||this.starterModelPolicySelectionGeneration!==r)return;i=this.starterModelPolicySelectionSupported(n),a=this.starterPlusModelPolicyInitializer()}if(this.starterModelPolicyInputs()?.status.blockedReason!==void 0){let t=this.starterNoticeScope();e()&&t!==void 0&&this.publishStarterNotice(wl(t));return}if(i&&a===void 0)return;this.starterNotice=void 0;let o=t.id,s=this.starterModelPolicy;(a===void 0?this.sessions.startSession(this.starterModelPolicyStartSnapshot()):this.sessions.startPlusSession(a)).then(e=>{i||this.clearStarterModelPolicyAfterSuccessfulStart(e,o,s)}).catch(t=>{if(e()){let e={machineId:n,workspaceId:o};this.publishStarterNotice(Tl(`start-failed`,`Could not start the session. ${WR(t)}`,e))}}),e()&&await this.focusChatComposer()}async focusNavigationTarget(e){if(e===`chat`){await this.focusChatComposer();return}await this.focusNavigationSection(e)}async focusNavigationSection(e){if(e===`machines`&&!_L(this.state.machines)){await this.focusNavigationSection(`projects`);return}this.panelCollapse.expandNavigationPanel(),this.appShell.isMobileNavigationLayout&&this.selectMainView(`navigation`),this.navigationSections.expand(e),await this.updateComplete,await qR(),await this.navigationPanel?.focusSection(e)}async focusChatComposer(){this.state.mainView!==`chat`&&this.selectMainView(`chat`),await this.updateComplete,await qR(),this.promptEditor?.focusInput()}async navigateSessionTree(e,t){let n=R(this.state),r=this.state.selectedSession?.id,i=await this.sessions.navigateTree(e,t);return!i.cancelled&&r!==void 0&&R(this.state)===n&&this.state.selectedSession?.id===r&&await this.focusChatComposer(),i}closeSessionTreeNavigator(){this.sessions.closeTreeDialog(),this.focusChatComposer()}renderSessionTreeNavigator(e){return e.treeDialog===void 0?null:g`
|
|
7515
7515
|
<session-tree-navigator
|
|
7516
7516
|
.tree=${e.treeDialog}
|
|
7517
7517
|
.onNavigate=${(e,t)=>this.navigateSessionTree(e,t)}
|
|
@@ -7526,7 +7526,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
7526
7526
|
.onRemove=${async()=>{this.isCurrentRecentProjectDialog(t,e,n)&&(await this.recentProjects.removeEntry(e.id),this.isCurrentRecentProjectDialog(t,e,n)&&this.closeRecentProjectDialog(t,e,n,`removal`))}}
|
|
7527
7527
|
.onClose=${()=>{this.closeRecentProjectDialog(t,e,n,`cancel`)}}
|
|
7528
7528
|
></recent-project-dialog>
|
|
7529
|
-
`}openRecentProjectDialog(e,t,n,r){this.recentProjectDialogGeneration+=1,this.recentProjectDialogMachineId=R(this.state),this.recentProjectDialogInitialView=t,this.recentProjectDialogCancelFocus=n,this.recentProjectDialogRemovalFocus=r,this.recentProjectDialogEntry=e}closeRecentProjectDialogForMachineChange(){let e=this.recentProjectDialogMachineId,t=this.recentProjectDialogEntry;e===void 0||t===void 0||this.closeRecentProjectDialog(e,t,this.recentProjectDialogGeneration)}isCurrentRecentProjectDialog(e,t,n){return R(this.state)===e&&this.recentProjectDialogMachineId===e&&this.recentProjectDialogEntry===t&&this.recentProjectDialogGeneration===n}closeRecentProjectDialog(e,t,n,r){if(this.recentProjectDialogMachineId!==e||this.recentProjectDialogEntry!==t||this.recentProjectDialogGeneration!==n||r!==void 0&&R(this.state)!==e)return;let i=r===`cancel`?this.recentProjectDialogCancelFocus:r===`removal`?this.recentProjectDialogRemovalFocus:void 0,a=this.renderRoot.querySelector(`recent-project-dialog`);a?.isConnected===!0&&a.close(),this.recentProjectDialogCancelFocus=void 0,this.recentProjectDialogRemovalFocus=void 0,this.recentProjectDialogMachineId=void 0,this.recentProjectDialogInitialView=`closed-actions`,this.recentProjectDialogEntry=void 0,i!==void 0&&this.updateComplete.then(()=>{this.recentProjectDialogMachineId===void 0&&this.recentProjectDialogEntry===void 0&&this.recentProjectDialogGeneration===n&&R(this.state)===e&&i()})}workspacePanels(){let e=this.state.selectedWorkspace;if(e===void 0)return[];let t=this.createWorkspacePanelContext(e);return this.plugins.getWorkspacePanels().filter(e=>e.visible?.(t)??!0)}synchronizeMemoryPollingForSelectedWorkspace(e=this.plugins.getActivityRailItems()){if(this.state.selectedWorkspace===void 0){this.memory.updatePolling(!1);return}this.synchronizeMemoryPolling(e)}synchronizeMemoryPolling(e){let t=e.some(e=>
|
|
7529
|
+
`}openRecentProjectDialog(e,t,n,r){this.recentProjectDialogGeneration+=1,this.recentProjectDialogMachineId=R(this.state),this.recentProjectDialogInitialView=t,this.recentProjectDialogCancelFocus=n,this.recentProjectDialogRemovalFocus=r,this.recentProjectDialogEntry=e}closeRecentProjectDialogForMachineChange(){let e=this.recentProjectDialogMachineId,t=this.recentProjectDialogEntry;e===void 0||t===void 0||this.closeRecentProjectDialog(e,t,this.recentProjectDialogGeneration)}isCurrentRecentProjectDialog(e,t,n){return R(this.state)===e&&this.recentProjectDialogMachineId===e&&this.recentProjectDialogEntry===t&&this.recentProjectDialogGeneration===n}closeRecentProjectDialog(e,t,n,r){if(this.recentProjectDialogMachineId!==e||this.recentProjectDialogEntry!==t||this.recentProjectDialogGeneration!==n||r!==void 0&&R(this.state)!==e)return;let i=r===`cancel`?this.recentProjectDialogCancelFocus:r===`removal`?this.recentProjectDialogRemovalFocus:void 0,a=this.renderRoot.querySelector(`recent-project-dialog`);a?.isConnected===!0&&a.close(),this.recentProjectDialogCancelFocus=void 0,this.recentProjectDialogRemovalFocus=void 0,this.recentProjectDialogMachineId=void 0,this.recentProjectDialogInitialView=`closed-actions`,this.recentProjectDialogEntry=void 0,i!==void 0&&this.updateComplete.then(()=>{this.recentProjectDialogMachineId===void 0&&this.recentProjectDialogEntry===void 0&&this.recentProjectDialogGeneration===n&&R(this.state)===e&&i()})}workspacePanels(){let e=this.state.selectedWorkspace;if(e===void 0)return[];let t=this.createWorkspacePanelContext(e);return this.plugins.getWorkspacePanels().filter(e=>e.visible?.(t)??!0)}synchronizeMemoryPollingForSelectedWorkspace(e=this.plugins.getActivityRailItems()){if(this.state.selectedWorkspace===void 0){this.memory.updatePolling(!1);return}this.synchronizeMemoryPolling(e)}synchronizeMemoryPolling(e){let t=e.some(e=>AR(e)&&cy(e,this.createActivityRailContext(e.id),this.reportActivityRailError));this.memory.updatePolling(t)}synchronizeLearnedSkillsPollingForSelectedWorkspace(e=this.plugins.getActivityRailItems()){if(this.state.selectedWorkspace===void 0){this.learnedSkills.updatePolling(!1);return}this.synchronizeLearnedSkillsPolling(e)}synchronizeLearnedSkillsPolling(e){let t=e.some(e=>jR(e)&&cy(e,this.createActivityRailContext(e.id),this.reportActivityRailError));this.learnedSkills.updatePolling(t)}visibleWorkspacePanels(){let e=this.hiddenWorkspacePanelTools();return this.workspacePanels().filter(t=>!e.includes(t.id))}hiddenWorkspacePanelTools(){let e=[];return this.terminalTabHidden&&e.push(`core:workspace.terminal`),this.infoTabHidden&&e.push(`core:workspace.info`),e}workspacePanelEmptyState(){let e=this.state.selectedProject;return this.state.isLoadingProjects?{title:`Loading projects…`,body:`Looking for projects you have added to PI WEBUI.`}:e===void 0?this.state.projects.length===0?{title:`No projects yet`,body:`Use Actions → Add Project to add a folder. Workspace tools will appear here after you choose a workspace.`}:{title:`Select a project`,body:`Choose a project from the sidebar, then select a workspace to inspect files, Git, or terminals.`}:this.state.isLoadingWorkspaces?{title:`Loading workspaces…`,body:`Preparing workspace tools for ${e.name}.`}:this.state.workspaces.length===0?{title:`No workspaces found`,body:`${e.name} does not have any available workspaces. Try selecting the project again or re-adding it.`}:{title:`Select a workspace`,body:`Choose a workspace in ${e.name} to inspect files, Git, or terminals.`}}sessionEmptyMessage(){return this.state.isLoadingProjects?`Loading projects…`:this.state.isLoadingSessions?`Loading sessions…`:this.state.selectedWorkspace===void 0?this.state.selectedProject===void 0?this.state.projects.length===0?`Add a project to start a session.`:`Select a project and workspace to start a session.`:`Select a workspace to start a session.`:`Select or start a session.`}shouldShowSessionStartScreen(e){return e.selectedWorkspace!==void 0&&e.selectedSession===void 0&&!e.isLoadingSessions&&e.sessions.every(e=>e.archived===!0)&&e.error===``}renderStarterNotice(){let e=El(this.starterNotice,this.starterNoticeScope(),this.starterModelPolicyInputs()?.status.blockedReason)??this.confirmedStarterModelPolicyWarning();return e===void 0?null:g`<p class="starter-notice" role="alert">${e}</p>`}renderSessionStartScreen(e){let t=e.selectedWorkspace;if(t===void 0)return g``;let n=this.starterSessionDefaults,r=this.starterSessionConfiguration(),i=this.selectedMachineModelTierCatalog(),a=n!==void 0&&(this.starterModelPolicySelectionSupported()?(i?.models.length??0)>0:n.models.length>0),o=n!==void 0&&n.thinkingLevels.length>0,s=this.starterModelPolicyInputs(),c=s===void 0||n===void 0?[]:this.policyThinkingOptions(this.starterModelPolicy?.exact??s.status.resolved,n.thinkingLevels);return g`
|
|
7530
7530
|
<section class="session-start-screen" aria-labelledby="session-start-heading">
|
|
7531
7531
|
<div class="session-start-content">
|
|
7532
7532
|
<p class="session-start-eyebrow">PI WEBUI · ${t.label}</p>
|
|
@@ -7538,7 +7538,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
7538
7538
|
<p class="session-start-hint">Describe a goal, paste a task, or attach a file to begin.</p>
|
|
7539
7539
|
</div>
|
|
7540
7540
|
</section>
|
|
7541
|
-
`}starterSessionConfiguration(){let e=this.starterSessionDefaults,t=this.starterModelPolicy;return e===void 0||t===void 0||!this.starterModelPolicySelectionSupported()?e:{...e,model:{provider:t.exact.model.provider,id:t.exact.model.id},thinkingLevel:t.exact.thinkingLevel}}starterModelPolicyInputs(){let e=this.starterSessionDefaults,t=this.starterModelPolicy;if(e===void 0||t===void 0||!this.sessionModelPolicySupported())return;let n=this.selectedMachineModelTierCatalog();if(this.starterModelPolicySelectionSupported()){let r=n===void 0?{kind:`blocked`,reason:this.modelTierCatalogError===``?`Loading model policy choices`:this.modelTierCatalogError}:al(t,n),i={mode:t.mode,...t.tier===void 0?{}:{tier:t.tier},resolved:r.kind===`ready`?r.resolved:t.exact,ladderValid:n?.valid??!0,...r.kind===`blocked`?{blockedReason:r.reason}:{}};return{status:i,response:{contractVersion:1,policy:t,session:{sessionId:`starter`,isStreaming:!1,isCompacting:!1,isBashRunning:!1,pendingMessageCount:0,queuedMessages:[],tokens:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0},cost:0,...e.model===void 0?{}:{model:e.model},thinkingLevel:e.thinkingLevel,modelPolicy:i}}}}let r=t.tier,i=r===void 0?void 0:n?.rows[r],a=t.mode===`tiered`&&r!==void 0&&i?.valid===!0?n?.ladder?.[r]:void 0,o=qc(e),s=t.mode===`exact`&&o!==void 0&&!Zc(t.exact,o),c=t.mode===`tiered`&&a===void 0,l={mode:t.mode,...r===void 0?{}:{tier:r},resolved:a??t.exact,ladderValid:n===void 0||n.valid,...c?{blockedReason:n?.configError??(this.modelTierCatalogError===``?`Choose a valid model tier before starting`:this.modelTierCatalogError)}:s?{blockedReason:`Choose a model and thinking level before starting`}:{}};return{status:l,response:{contractVersion:1,policy:t,session:{sessionId:`starter`,isStreaming:!1,isCompacting:!1,isBashRunning:!1,pendingMessageCount:0,queuedMessages:[],tokens:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0},cost:0,...e.model===void 0?{}:{model:e.model},thinkingLevel:e.thinkingLevel,modelPolicy:l}}}}starterModelPolicyBlocksStart(){return this.starterModelPolicyInputs()?.status.blockedReason!==void 0}starterModelPolicyError(){if(this.modelTierCatalogError!==``)return this.modelTierCatalogError;if(this.starterModelPolicySelectionSupported()){let e=this.currentConfirmedStarterModelPolicyWriterSnapshot()?.error;return e===void 0?this.starterModelPolicyPreferenceReadError:`${mR} ${e}`}let e=this.starterModelPolicyPreferenceScope(),t=e===void 0?void 0:this.starterModelPolicyPreferenceWriter.snapshot(e).error;return t===void 0?this.starterModelPolicyPreferenceReadError:`Could not remember this model policy; this session will still use it. ${t}`}currentConfirmedStarterModelPolicyWriterSnapshot(){let e=this.confirmedStarterModelPolicyUiScope;if(!(e===void 0||this.confirmedStarterModelPolicyUiGeneration!==this.starterModelPolicySelectionGeneration||!this.starterModelPolicyPreferenceScopeMatchesCurrentSelection(e)))return this.confirmedStarterModelPolicyPreferenceWriter.snapshot(e)}confirmedStarterModelPolicyWarning(){let e=this.currentConfirmedStarterModelPolicyWriterSnapshot()?.error;return e===void 0?void 0:`${mR} ${e}`}starterModelPolicyStartSnapshot(){let e=this.starterModelPolicy,t=this.starterSessionDefaults;if(e===void 0||t===void 0||!this.sessionModelPolicySupported())return;if(e.mode===`tiered`)return e.tier===void 0?void 0:{mode:`tiered`,tier:e.tier};let n=qc(t);if(!(n===void 0||Zc(n,e.exact)))return{mode:`exact`,exact:{model:{...e.exact.model},thinkingLevel:e.exact.thinkingLevel}}}starterPlusModelPolicyInitializer(){if(!this.starterModelPolicySelectionSupported())return;let e=this.starterModelPolicy,t=this.selectedMachineModelTierCatalog();if(e===void 0||t===void 0)return;let n=al(e,t);return n.kind===`ready`?n.initialModelPolicy:void 0}async loadMissingStarterPlusModelPolicyInputs(e,t,n){if(this.starterModelPolicy===void 0){await this.loadStarterSessionDefaults(e,{awaitModelTierCatalog:!0,expectedSelectionGeneration:n});return}this.selectedMachineModelTierCatalog()===void 0&&await this.ensureModelTierCatalog(t)}clearStarterModelPolicyAfterSuccessfulStart(e,t,n){!e||this.state.selectedWorkspace?.id!==t||this.starterModelPolicy!==n||(this.starterModelPolicy=void 0)}selectedProjectWorkTarget(e=R(this.state)){if(R(this.state)!==e)return;let t=this.state.selectedProject?.id;return t===void 0?void 0:{machineId:e,projectId:t}}recordProjectWork(e){e!==void 0&&this.recentProjects.recordWork(e.projectId,e.machineId)}mobilePanelBadge(e){let t=this.state.selectedWorkspace;if(t!==void 0)return e.badge?.(this.createWorkspacePanelContext(t))}mobilePanelIcon(e){switch(e.id){case`core:workspace.files`:return`files`;case`core:workspace.git`:return`git`;case`core:workspace.terminal`:return`terminal`;default:return}}workspaceLabelItems(e){return this.plugins.getWorkspaceLabelItems(this.createWorkspaceLabelContext(e))}createWorkspaceLabelContext(e){let t=gR(this.state);return{machine:t,workspace:e,state:this.state,files:this.createWorkspaceFiles(e,t.id),host:this.createWorkspaceHost()}}createWorkspaceFiles(e,t){return{readFile:n=>sc.workspaceFile(e.projectId,e.id,n,t),writeFile:async(n,r,i)=>{let a=await sc.writeWorkspaceFile(e.projectId,e.id,n,r,i,t);return this.files.refreshFiles(),a},deleteFile:async n=>{let r=await sc.deleteWorkspaceFile(e.projectId,e.id,n,t);return this.files.refreshFiles(),r},moveFile:async(n,r,i)=>{let a=await sc.moveWorkspaceFile(e.projectId,e.id,n,r,i,t);return this.files.refreshFiles(),a}}}createWorkspaceHost(){return{requestRender:()=>{this.requestUpdate()}}}createWorkspacePanelTerminal(e,t,n){let r=this.terminalCommandRunsForOrigin(n,t);return{open:n=>{this.openRuntimeTerminal(t,e,n)},runCommand:t=>r.runCommand({...t,workspace:e})}}createWorkspacePanelContext(e){let t=gR(this.state),n=t.id,r=i=>{let a=this.terminalCommandRunsForOrigin(i,n);return Cx({machine:t,workspace:e,state:this.state,files:this.createWorkspaceFiles(e,n),prompt:this.createPromptEditor(),terminal:this.createWorkspacePanelTerminal(e,n,i),openTerminal:t=>{this.openRuntimeTerminal(n,e,t)},host:this.createWorkspaceHost(),piWebUiUnstable:{terminalCommandRuns:a},fileTree:this.state.fileTree,expandedDirs:this.state.expandedDirs,selectedFilePath:this.state.selectedFilePath,selectedFileContent:this.state.selectedFileContent,fileTreeStale:this.state.fileTreeStale,gitStatus:this.state.gitStatus,selectedDiffPath:this.state.selectedDiffPath,selectedDiff:this.state.selectedDiff,selectedStagedDiff:this.state.selectedStagedDiff,gitStale:this.state.gitStale,activeTerminalCount:this.state.activeTerminalCount,selectedTerminalId:this.state.selectedTerminalId,terminalAutoStart:this.terminalAutoStartWorkspaceId===e.id,workspaceUploadDefaultFolder:Tc(e.effectiveConfig,this.workspaceUploadDefaultFolder),onRefreshFiles:()=>{this.files.refreshFiles()},onExpandDir:e=>{this.files.expandDir(e)},onSelectFile:e=>{this.files.selectFile(e)},onStartWorkspaceUpload:(e,t)=>this.files.startWorkspaceUpload(e,t),onCancelWorkspaceUpload:e=>{this.files.cancelWorkspaceUpload(e)},onClearWorkspaceUpload:e=>{this.files.clearWorkspaceUpload(e)},onRefreshGit:()=>{this.git.refreshGit()},onRefreshMemory:()=>{this.memory.refresh()},onSelectDiff:e=>{this.git.selectDiff(e)},onSelectTerminal:(e,t)=>{this.selectTerminal(e,t)}},r)};return r(`core`)}getActions(){return LS(this.getDefaultActions(),this.shortcutConfig)}getDefaultActions(){return[...this.plugins.getActions(this.createPluginRuntimeContext()),...this.sessionActions(),...this.navigationFocusActions(),...this.panelLayoutActions()]}sessionActions(){return[{id:`app.sessions.cleanup`,title:`Clean Up Sessions`,description:`Preview and manually clean up idle or archived sessions on the selected machine`,group:`Sessions`,closesActionPalette:!0,...this.canCleanupSessions()?{}:{enabled:!1,disabledReason:this.sessionCleanupUnavailableMessage()},run:()=>{this.openSessionCleanupDialog()}}]}panelLayoutActions(){return[{id:`app.layout.toggle-terminal-tab`,title:this.terminalTabHidden?`Show Terminal Tab`:`Hide Terminal Tab`,description:this.terminalTabHidden?`Show the terminal tab in the workspace panel`:`Hide the terminal tab from the workspace panel`,group:`View`,run:()=>{this.toggleTerminalTab()}},{id:`app.layout.toggle-info-tab`,title:this.infoTabHidden?`Show Info Tab`:`Hide Info Tab`,description:this.infoTabHidden?`Show the info tab in the workspace panel`:`Hide the info tab from the workspace panel`,group:`View`,run:()=>{this.toggleInfoTab()}},{id:`app.layout.reset-navigation-panel-size`,title:`Reset Navigation Panel Size`,description:`Restore the navigation panel to its default width`,group:`View`,run:()=>{this.resetResizablePanel(`navigation`)}},{id:`app.layout.reset-workspace-panel-size`,title:`Reset Workspace Panel Size`,description:`Restore the workspace panel to its default width`,group:`View`,run:()=>{this.resetResizablePanel(`workspace`)}},{id:`app.layout.reset-panel-sizes`,title:`Reset Panel Sizes`,description:`Restore all side panels to their default widths`,group:`View`,run:()=>{this.resetResizablePanels()}}]}navigationFocusActions(){return[{id:`app.navigation.focus-machines`,title:`Focus Machines`,description:`Move keyboard focus to the machine selector`,shortcut:`mod+g m`,group:`Navigation`,closesActionPalette:!0,run:()=>this.focusNavigationSection(`machines`)},{id:`app.navigation.focus-projects`,title:`Focus Projects`,description:`Move keyboard focus to the projects list`,shortcut:`mod+g p`,group:`Navigation`,closesActionPalette:!0,run:()=>this.focusNavigationSection(`projects`)},{id:`app.navigation.focus-workspaces`,title:`Focus Workspaces`,description:`Move keyboard focus to the workspaces list`,shortcut:`mod+g w`,group:`Navigation`,closesActionPalette:!0,run:()=>this.focusNavigationSection(`workspaces`)},{id:`app.navigation.focus-sessions`,title:`Focus Sessions`,description:`Move keyboard focus to the sessions list`,shortcut:`mod+g s`,group:`Navigation`,closesActionPalette:!0,run:()=>this.focusNavigationSection(`sessions`)}]}ensureGatewayPluginsLoaded(){return this.gatewayPluginLoadPromise??=this.loadExternalPlugins(),this.gatewayPluginLoadPromise}async loadExternalPlugins(){await this.registerExternalPlugins(`PI WEBUI plugins`,()=>ix())}async loadPluginsForSelectedMachine(){let e=this.state.selectedMachine;e?.kind===`remote`&&await this.loadPluginsForMachine(e)}async loadPluginsForMachine(e){if(await this.ensureGatewayPluginsLoaded(),e.kind!==`remote`||this.loadedMachinePluginIds.has(e.id))return;let t=this.machinePluginLoadPromises.get(e.id);if(t!==void 0)return t;let n=this.registerExternalPlugins(`PI WEBUI plugins from ${e.name}`,()=>ix(`api/machines/${encodeURIComponent(e.id)}/pi-webui-plugins/manifest.json`,{machineId:e.id,shouldLoadPlugin:e=>this.plugins.shouldLoadRemotePlugin(e.id,e.machineSpecific)})).then(t=>{t&&this.loadedMachinePluginIds.add(e.id)}).finally(()=>{this.machinePluginLoadPromises.delete(e.id)});this.machinePluginLoadPromises.set(e.id,n),await n}async registerExternalPlugins(e,t){try{let e=await t();for(let t of e)try{this.plugins.register(t)}catch(e){console.warn(`Failed to register PI WEBUI plugin ${t.id}`,e)}return this.synchronizeMemoryPollingForSelectedWorkspace(),this.synchronizeLearnedSkillsPollingForSelectedWorkspace(),this.applyPreferredTheme(!1),this.requestUpdate(),!0}catch(t){return console.warn(`Failed to load ${e}`,t),!1}}createPromptEditor(){return{insertText:e=>{let t=this.promptEditor?.view;if(!t)return;t.hasFocus||t.focus();let n=t.state.selection.main;t.dispatch({changes:{from:n.from,to:n.to,insert:e},selection:{anchor:n.from+e.length}})},getText:()=>this.promptEditor?.view?.state.doc.toString()??``,getSelection:()=>{let e=this.promptEditor?.view;if(!e)return null;let t=e.state.selection.main;return t.empty?null:{start:t.from,end:t.to,text:e.state.sliceDoc(t.from,t.to)}}}}createPluginRuntimeContext(){return this.createPluginRuntimeContextForOrigin(`core`,R(this.state))}createPluginRuntimeContextForOrigin(e,t){let n=e=>Sx({state:this.state,prompt:this.createPromptEditor(),piWebUiUnstable:{terminalCommandRuns:this.terminalCommandRunsForOrigin(e,t),openSettings:e=>{this.openSettings(e)}},openActionPalette:()=>{this.setState({actionPaletteOpen:!0})},focusPrompt:()=>{this.focusChatComposer()},addProject:()=>{this.openProjectDialog()},addMachine:()=>{this.openMachineDialog()},refreshSelectedMachine:async()=>{await Promise.all([this.machines.refreshMachineHealth(),this.machines.refreshMachineRuntime()])},removeSelectedMachine:()=>this.removeMachine(),openSelectedMachine:()=>{this.openSelectedMachine()},configureAuth:()=>this.auth.openLogin(),logoutAuth:()=>this.auth.openLogout(),openThemePicker:()=>{this.openThemeDialog()},selectMainView:e=>{this.selectMainView(e)},selectWorkspaceTool:e=>{this.openWorkspaceTool(e)},openTerminal:e=>{this.openTerminal(e)},refreshFiles:()=>this.files.refreshFiles(),refreshGit:()=>this.git.refreshGit(),refreshAppData:()=>this.refreshAppData(),checkForPiWebUiUpdates:()=>this.piWebUiStatusController.checkForUpdates(),reloadPage:()=>{this.hardReloadApp()},deleteWorkspace:e=>this.deleteWorkspace(e),startSession:()=>this.withChatScrollTransition(()=>this.startSessionAndOpenChat()),archiveSession:()=>this.sessions.archiveSession(),reloadSession:()=>this.sessions.reloadSession(),deleteCachedNewSession:()=>this.sessions.deleteCachedNewSession(),stopActiveWork:()=>this.sessions.stopActiveWork()},n);return n(e)}createActivityRailContext(e){let t=gR(this.state),n=this.state.selectedWorkspace,r=this.activeActivityRailId===e?this.activeActivityRailGeneration:void 0,i=a=>wx({...this.createPluginRuntimeContextForOrigin(a,t.id),machine:t,...n===void 0?{}:{workspaceScope:{workspace:n,files:this.createWorkspaceFiles(n,t.id),terminal:this.createWorkspacePanelTerminal(n,t.id,a)}},host:{requestRender:()=>{this.requestUpdate()},close:()=>{r!==void 0&&this.closeActivityRailItem(e,r)}},onRefreshMemory:()=>{this.memory.refresh()},onRefreshLearnedSkills:()=>{this.learnedSkills.refresh()}},i);return i(`core`)}activityRailItems(){let e=this.plugins.getActivityRailItems();return this.synchronizeMemoryPollingForSelectedWorkspace(e),this.synchronizeLearnedSkillsPollingForSelectedWorkspace(e),e.flatMap(e=>this.projectActivityRailItems([e],this.createActivityRailContext(e.id)))}projectActivityRailItems(e,t){return ly(e,t,this.reportActivityRailError)}activeActivityRailItem(){let e=this.activeActivityRailId;if(e===void 0)return;let t=this.resolveActivityRailItem(e);return t===void 0?void 0:{...t,generation:this.activeActivityRailGeneration}}openActivityRailItem(e,t){this.resolveActivityRailItem(e)!==void 0&&(this.closeCompactActivityRail(),this.activityRailRestoreFocus=t,this.activeActivityRailGeneration+=1,this.activeActivityRailId=e)}resolveActivityRailItem(e){let t=this.plugins.getActivityRailItems().find(t=>t.id===e);if(t===void 0)return;let n=this.createActivityRailContext(e);if(this.projectActivityRailItems([t],n).some(t=>t.id===e))return{activity:t,context:n}}closeActivityRailItem(e,t){if(this.activeActivityRailId!==e||this.activeActivityRailGeneration!==t)return;let n=this.activityRailRestoreFocus;this.activityRailRestoreFocus=void 0,this.activeActivityRailId=void 0,n!==void 0&&this.updateComplete.then(()=>{this.activeActivityRailId===void 0&&n()})}restoreActivityRailFocus(e){if(e.isConnected){e.focus();return}let t=this.compactActivityRailLauncher;if(t?.isConnected===!0){t.focus();return}this.currentCompactActivityRailLauncher()?.focus()}currentCompactActivityRailLauncher(){let e=this.renderRoot.querySelector(`app-context-bar`)?.shadowRoot?.querySelector(`.activity-rail-action-button`);return e?.isConnected===!0?e:void 0}async deleteWorkspace(e=this.state.selectedWorkspace){if(e===void 0)return;if(!x_(e)){this.setState({error:`Only secondary Git worktrees can be deleted`});return}if(My(this.state,e))return;let t=e.branch??e.label;if(!confirm(`Delete workspace ${t}?\n\nThis will run git worktree remove and delete:\n${e.path}\n\nThe Git branch will not be deleted.`))return;let n=R(this.state);try{let t=await sc.deleteWorkspace(e.projectId,e.id,n);if(R(this.state)!==n)return;this.recordWorkspaceDeletionRun(t,n);let r=await this.workspaceForCommandRun(t);if(R(this.state)!==n)return;r!==void 0&&this.openRuntimeTerminal(n,r,{terminalId:t.terminalId})}catch(e){R(this.state)===n&&this.setState({error:`Failed to start workspace deletion: ${UR(e)}`})}}async workspaceForCommandRun(e){let t=this.state.selectedProject?.id===e.projectId?this.state.workspaces:this.state.workspacesByProjectId[e.projectId];return(t===void 0||t.length===0)&&(t=await this.workspaces.refreshProjectWorkspaces(e.projectId)),t.find(t=>t.id===e.workspaceId)}recordWorkspaceDeletionRun(e,t){if(R(this.state)!==t)return;let n=Ny(e);n!==void 0&&(this.setState({workspaceDeletionRuns:{...this.state.workspaceDeletionRuns,[n]:e}}),this.updateWorkspaceDeletionPolling())}async refreshWorkspaceDeletionRuns(){if(this.refreshingWorkspaceDeletionRuns)return;let e=R(this.state),t=this.state.selectedProject;if(t===void 0){this.setState({workspaceDeletionRuns:{}}),this.updateWorkspaceDeletionPolling();return}this.refreshingWorkspaceDeletionRuns=!0;try{let n=await this.terminalCommandRunsForOrigin(`core`,e).listCommandRuns(ky(t.id));if(R(this.state)!==e)return;let r=Ay(n);this.setState({workspaceDeletionRuns:r});for(let t of Object.values(r))Py(t)||await this.handleCompletedWorkspaceDeletionRun(t,e)}catch(e){console.warn(`Failed to refresh workspace deletion runs`,e)}finally{this.refreshingWorkspaceDeletionRuns=!1,this.updateWorkspaceDeletionPolling()}}updateWorkspaceDeletionPolling(){let e=Object.values(this.state.workspaceDeletionRuns).some(Py);if(e&&this.workspaceDeletionPollTimer===void 0){this.workspaceDeletionPollTimer=window.setInterval(()=>{this.refreshWorkspaceDeletionRuns()},1e3);return}!e&&this.workspaceDeletionPollTimer!==void 0&&(window.clearInterval(this.workspaceDeletionPollTimer),this.workspaceDeletionPollTimer=void 0)}async handleCompletedWorkspaceDeletionRun(e,t=R(this.state)){if(R(this.state)!==t)return;let n=VR(t,e.id);if(this.handledWorkspaceDeletionRunIds.has(n))return;let r=Ny(e);if(r!==void 0){if(this.handledWorkspaceDeletionRunIds.add(n),e.status===`succeeded`){if(await this.workspaces.refreshAfterWorkspaceDeleted(e.projectId,r),R(this.state)!==t)return;this.setState({workspaceDeletionRuns:GR(this.state.workspaceDeletionRuns,r)}),this.updateWorkspaceDeletionPolling();return}e.status===`failed`&&(this.setState({error:`Workspace deletion failed. See terminal output.`}),this.updateWorkspaceDeletionPolling())}}openProjectBrowser(e){this.projectBrowserRestoreFocus=e,this.projectBrowserOpen=!0}async showProjectStatistics(e){let t=++this.statisticsRequestGeneration,n=R(this.state),r=()=>t===this.statisticsRequestGeneration&&R(this.state)===n;this.statisticsProject=e,this.statisticsReport=void 0,this.statisticsSessionCount=void 0,this.statisticsError=void 0,this.statisticsLoading=!0;try{let t=await sc.workspaces(e.id,n);if(!r())return;let i={projectPath:e.path,liveCwds:t.map(e=>e.path)};ac.projectUsageCount(i,n).then(({sessionCount:e})=>{r()&&this.statisticsLoading&&(this.statisticsSessionCount=e)},()=>void 0);let a=await ac.projectUsage(i,n);if(!r())return;this.statisticsReport=a}catch(e){if(!r())return;this.statisticsError=e instanceof Error?e.message:String(e)}finally{r()&&(this.statisticsLoading=!1)}}closeProjectStatistics(){this.statisticsRequestGeneration+=1,this.statisticsProject=void 0,this.statisticsReport=void 0,this.statisticsSessionCount=void 0,this.statisticsError=void 0,this.statisticsLoading=!1}closeProjectBrowser(e={}){let t=e.restoreFocus===!0?this.projectBrowserRestoreFocus:void 0;this.projectBrowserRestoreFocus=void 0,this.projectBrowserOpen=!1,t!==void 0&&this.updateComplete.then(()=>{t()})}selectProjectFromBrowser(e){this.closeProjectBrowser(),this.selectNavigationItem(`projects`,`workspaces`,()=>this.workspaces.selectProject(e))}addProjectFromBrowser(){this.closeProjectBrowser(),this.openProjectDialog()}openSessionBrowser(e){this.state.selectedProject!==void 0&&(this.sessionBrowserRestoreFocus=e,this.sessionBrowserOpen=!0)}closeSessionBrowser(e={}){let t=e.restoreFocus===!0?this.sessionBrowserRestoreFocus:void 0;this.sessionBrowserRestoreFocus=void 0,this.sessionBrowserOpen=!1,t!==void 0&&this.updateComplete.then(()=>{t()})}selectSessionFromBrowser(e){this.closeSessionBrowser(),this.selectNavigationItem(`sessions`,`chat`,()=>this.selectSessionFromNavigation(e))}openProjectDialog(){this.setState({projectDialogOpen:!0})}openMachineDialog(){this.setState({machineDialogOpen:!0,error:``})}async submitMachineDialog(e){await this.machines.addMachine(e)!==void 0&&(this.setState({machineDialogOpen:!1}),this.schedulePiWebUiStatusRefresh())}async removeMachine(e=this.state.selectedMachine){if(e===void 0||e.kind===`local`||!window.confirm(`Remove ${e.name}?\n\nThis only removes it from this PI WEBUI gateway.`))return;let t=this.state.selectedMachine?.id===e.id;t&&this.rememberCurrentMachineNavigation();let n=await this.machines.deleteMachine(e,{selectFallback:!t});this.state.machines.some(t=>t.id===e.id)||this.machineNavigation.forget(e.id),t&&n!==void 0&&await this.selectMachineWithMemory(n,{rememberCurrent:!1})}openSelectedMachine(){let e=this.state.selectedMachine;e?.kind!==`remote`||e.baseUrl===void 0||window.open(e.baseUrl,`_blank`,`noopener,noreferrer`)}runAction(e){Promise.resolve().then(()=>e.run()).catch(t=>{let n=t instanceof Error?t.message:String(t);console.warn(`Action failed: ${e.id}`,t),this.setState({error:`Action failed: ${n}`})})}async openModelDialog(){let e=await this.sessions.listModels(),t=this.state.status?.model?.provider,n=this.state.status?.model?.id,r=[...e].sort((e,t)=>{let n=e.provider??``,r=t.provider??``;return n===r?(e.id??``).localeCompare(t.id??``):n.localeCompare(r)});this.setState({modelDialog:{title:`Select Model`,...t!==void 0&&n!==void 0?{selectedValue:`${t}/${n}`}:{},options:r.map(e=>{let r=e.provider??``,i=e.id??``,a=r===t&&i===n;return{value:`${r}/${i}`,label:i+(a?` ✓ current`:``),...r===``?{}:{group:r}}})}})}async pickModel(e){this.setState({modelDialog:void 0});let t=e.indexOf(`/`);if(t<=0)return;let n=e.slice(0,t),r=e.slice(t+1);if(!this.sessionModelPolicySupported()){await this.sessions.setModel(n,r);return}let i=await this.prepareActiveModelPolicyDraft();if(i===void 0||i!==this.activeModelPolicyDraftForState(this.state)||i.mode!==`exact`)return;let a=this.selectedMachineModelTierCatalog(),o=a?.models.find(e=>e.model.provider===n&&e.model.id===r);if(o===void 0){a!==void 0&&(this.modelTierCatalogError=`Model ${n}/${r} is unavailable in the model policy catalog`);return}this.modelTierCatalogError=``,this.setActiveModelPolicyDraft(el(i,o)),this.scheduleActiveExactModelPolicyApply()}openStarterModelDialog(){let e=this.starterSessionDefaults;if(e===void 0)return;let t=this.starterModelPolicySelectionSupported(),n=t?this.starterModelPolicy?.exact:void 0,r=n?.model.provider??e.model?.provider,i=n?.model.id??e.model?.id,a=t?(this.selectedMachineModelTierCatalog()?.models??[]).map(e=>({provider:e.model.provider,id:e.model.id,...e.name===void 0?{}:{name:e.name}})):[...e.models],o=r!==void 0&&i!==void 0&&!a.some(e=>e.provider===r&&e.id===i),s=[...o?[...a,{provider:r,id:i}]:a].sort((e,t)=>{let n=e.provider??``,r=t.provider??``;return n===r?(e.id??``).localeCompare(t.id??``):n.localeCompare(r)});this.setState({modelDialog:{title:`Select Default Model`,source:`starter`,...r!==void 0&&i!==void 0?{selectedValue:`${r}/${i}`}:{},options:s.map(e=>{let t=e.provider??``,n=e.id??``,a=t===r&&n===i;return{value:`${t}/${n}`,label:n+(a?` ✓ current`:``)+(a&&o?` (unavailable)`:``),...t===``?{}:{group:t}}})}})}async pickStarterModel(e){this.setState({modelDialog:void 0});let t=e.indexOf(`/`);if(!(t<=0)){if(this.starterModelPolicySelectionSupported()){let n=this.starterModelPolicy,r=e.slice(0,t),i=e.slice(t+1),a=this.selectedMachineModelTierCatalog()?.models.find(e=>e.model.provider===r&&e.model.id===i);if(n===void 0||a===void 0)return;this.setStarterModelPolicyDraft(el(n,a));return}await this.updateStarterSessionDefaults({model:{provider:e.slice(0,t),modelId:e.slice(t+1)}})}}openThemeDialog(){let e=this.plugins.getThemes(),t=this.resolveCurrentThemePreference(e),n=t.selectedTheme?.id,r=this.themePreference.auto?$L:QL;this.setState({themeDialog:{title:`Select Theme`,selectedValue:n===void 0?r:`${eR}${n}`,options:[{value:r,label:`Auto ${this.themePreference.auto?`✓ on`:`off`}`,description:this.autoThemeDescription(t)},...e.map(e=>({value:`${eR}${e.id}`,label:this.themeOptionLabel(e,n),description:this.themeOptionDescription(e)}))]}})}pickTheme(e){if(this.setState({themeDialog:void 0}),e===QL||e===$L){let t=this.resolveCurrentThemePreference().selectedTheme?.id;if(t===void 0)return;this.themePreference={themeId:t,auto:e===QL},this.applyPreferredTheme(!0);return}if(!e.startsWith(eR))return;let t=e.slice(6),n=this.plugins.getThemes().find(e=>e.id===t);n!==void 0&&(this.themePreference={themeId:n.id,auto:this.themePreference.auto},this.applyPreferredTheme(!0))}applyPreferredTheme(e){let t=this.resolveCurrentThemePreference().activeTheme;t!==void 0&&(this.activeThemeId=t.id,vy(t),e&&_y(this.themePreference))}resolveCurrentThemePreference(e=this.plugins.getThemes()){return yy({themes:e,themePairs:this.plugins.getThemePairs(),preference:this.themePreference,prefersLight:this.systemPrefersLight()})}themePairForTheme(e){return xy(this.plugins.getThemePairs(),e)}systemPrefersLight(){return this.systemLightThemeMedia?.matches??!1}autoThemeDescription(e){return!this.themePreference.auto||e.selectedTheme===void 0?`Follow the system light/dark preference when the selected theme has a pair.`:e.selectedThemePair===void 0?`On, but the selected theme has no light/dark pair, so it will stay selected.`:`On · ${e.selectedThemePair.name} follows the system ${this.systemPrefersLight()?`light`:`dark`} preference.`}themeOptionLabel(e,t){let n=[...e.id===t?[`selected`]:[],...e.id===this.activeThemeId&&e.id!==t?[`active`]:[]];return n.length===0?e.name:`${e.name} ✓ ${n.join(` · `)}`}themeOptionDescription(e){let t=[e.colorScheme];return this.themePairForTheme(e.id)!==void 0&&t.push(`auto pair`),e.description!==void 0&&t.push(e.description),t.join(` · `)}async openThinkingDialog(){let e=await this.sessions.listThinkingLevels(),t=this.state.status?.thinkingLevel??`off`;this.setState({thinkingDialog:{title:`Select Thinking Level`,selectedValue:t,options:e.map(e=>{let n=qR(e);return{value:e,label:`${e}${e===t?` ✓ current`:``}`,...n===void 0?{}:{description:n}}})}})}async pickThinking(e){if(this.setState({thinkingDialog:void 0}),e===``)return;if(!this.sessionModelPolicySupported()){await this.sessions.setThinkingLevel(e);return}let t=await this.prepareActiveModelPolicyDraft();if(t===void 0||t!==this.activeModelPolicyDraftForState(this.state)||t.mode!==`exact`)return;let n=tl(t,e);if(this.setActiveModelPolicyDraft(n),(this.selectedMachineModelTierCatalog()?.models.find(e=>e.model.provider===n.exact.model.provider&&e.model.id===n.exact.model.id))?.thinkingLevels.includes(e)!==!0){this.cancelActiveModelPolicyApply(),this.modelTierCatalogError=`Thinking level ${e} is unsupported by ${n.exact.model.provider}/${n.exact.model.id}`;return}this.modelTierCatalogError=``,this.scheduleActiveExactModelPolicyApply()}openStarterThinkingDialog(){let e=this.starterSessionDefaults;if(e===void 0)return;let t=this.starterModelPolicySelectionSupported()?this.starterModelPolicy?.exact.thinkingLevel??e.thinkingLevel:e.thinkingLevel,n=e.thinkingLevels.includes(t)?e.thinkingLevels:[t,...e.thinkingLevels];this.setState({thinkingDialog:{title:`Select Default Thinking Level`,source:`starter`,selectedValue:t,options:n.map(e=>{let n=qR(e);return{value:e,label:`${e}${e===t?` ✓ current`:``}`,...n===void 0?{}:{description:n}}})}})}async pickStarterThinking(e){if(this.setState({thinkingDialog:void 0}),e!==``){if(this.starterModelPolicySelectionSupported()){let t=this.starterModelPolicy;t!==void 0&&this.setStarterModelPolicyDraft(tl(t,e));return}await this.updateStarterSessionDefaults({thinkingLevel:e})}}async updateStarterSessionDefaults(e){let t=this.state.selectedWorkspace;if(t===void 0)return;let n=R(this.state);try{let r=await cc.updateSessionDefaults(t.path,e,n);if(R(this.state)!==n||this.state.selectedWorkspace?.id!==t.id)return;this.starterSessionDefaults=r,this.starterNotice=void 0,this.starterModelPolicyPreferenceReadError=r.starterModelPolicyPreferenceError??``;let i=this.starterModelPolicy,a=i===void 0?Jc(r):Yc(i,r);this.starterModelPolicy=a;let o=qc(r);a.mode===`exact`&&o!==void 0&&Zc(a.exact,o)&&this.persistStarterModelPolicyPreference(a)}catch(e){R(this.state)===n&&this.state.selectedWorkspace?.id===t.id&&this.publishStarterNotice(Tl(`defaults-failed`,`Could not save this workspace's model defaults. ${UR(e)}`,{machineId:n,workspaceId:t.id}))}}sendPrompt(e,t,n,r){if(!(n!==void 0&&n.length>0)&&t===void 0&&this.auth.handleSlashCommand(e))return;let i=this.selectedProjectWorkTarget();this.sessions.send(e,t,n,r).then(e=>{e&&this.recordProjectWork(i)})}async ensureStarterModelPolicyCatalog(){let e=this.selectedMachineModelTierCatalog();return e===void 0?(await this.ensureModelTierCatalog(R(this.state)),this.selectedMachineModelTierCatalog()):e}setStarterModelPolicyDraft(e){this.starterNotice=void 0;let t={mode:e.mode,exact:{model:{...e.exact.model},thinkingLevel:e.exact.thinkingLevel},...e.tier===void 0?{}:{tier:e.tier}};return this.starterModelPolicy=t,t}applyGitUpdateManagerStatus(e,t,n){let r=this.state.selectedWorkspace;R(this.state)!==t||r?.id!==e.id||r.projectId!==e.projectId||this.setState({gitStatus:n,gitStale:!1})}startTerminalModalPointerInteraction(e,t){if(this.terminalModalMaximized||t.button!==0)return;let n=t.currentTarget;if(!(n instanceof HTMLElement))return;let r=n.closest(`.terminal-modal-frame`);if(!(r instanceof HTMLElement))return;t.preventDefault(),t.stopPropagation();let i=XS(this.terminalModalBoundsFromFrame(r),this.terminalModalViewport());n.setPointerCapture(t.pointerId),this.terminalModalBounds=i,this.terminalModalPointerInteraction={operation:e,pointerId:t.pointerId,target:n,startClientX:t.clientX,startClientY:t.clientY,bounds:i}}terminalModalBoundsFromFrame(e){let{left:t,top:n,width:r,height:i}=e.getBoundingClientRect();return{left:t,top:n,width:r,height:i}}terminalModalViewport(){return typeof window>`u`?{width:0,height:0}:{width:window.innerWidth,height:window.innerHeight}}terminalModalFrameStyle(){let e=this.terminalModalMaximized?void 0:this.terminalModalBounds,t=e===void 0?``:`; left: ${String(e.left)}px; top: ${String(e.top)}px; width: ${String(e.width)}px; height: ${String(e.height)}px`;return`--terminal-modal-opacity: ${String(this.terminalModalOpacity)}%${t};`}finishTerminalModalPointerInteraction(){let e=this.terminalModalPointerInteraction;if(e!==void 0){try{e.target.releasePointerCapture(e.pointerId)}catch{}this.terminalModalPointerInteraction=void 0}}persistTerminalModalPreferences(){iC({fontSize:this.terminalModalFontSize,opacity:this.terminalModalOpacity})}toggleTerminalTab(){this.terminalTabHidden=!this.terminalTabHidden,this.persistWorkspaceTabVisibility()}toggleInfoTab(){this.infoTabHidden=!this.infoTabHidden,this.persistWorkspaceTabVisibility()}persistWorkspaceTabVisibility(){fC({terminalHidden:this.terminalTabHidden,infoHidden:this.infoTabHidden})}activeModelPolicyInputs(e){let t=e.status?.modelPolicy;if(e.status===void 0||t===void 0||!this.sessionModelPolicySupported())return;let n=this.activeModelPolicyDraftForState(e);if(n===void 0)return{error:e.modelPolicyError??this.modelTierCatalogError,status:t,editorStatus:e.status,thinkingOptions:this.policyThinkingOptions(t.resolved,e.availableThinkingLevels)};let r=n.tier,i=r===void 0||this.selectedMachineModelTierCatalog()?.rows[r].valid!==!0?void 0:this.selectedMachineModelTierCatalog()?.ladder?.[r],a=n.mode===`exact`?n.exact:i??t.resolved,o={mode:n.mode,...r===void 0?{}:{tier:r},resolved:{model:{...a.model},thinkingLevel:a.thinkingLevel},ladderValid:t.ladderValid,...t.blockedReason===void 0?{}:{blockedReason:t.blockedReason}},s=n.exact.model.provider!==``&&n.exact.model.id!==``,c=n.mode===`exact`?{...e.status,...s?{model:{...n.exact.model}}:{},thinkingLevel:n.exact.thinkingLevel,modelPolicy:o}:{...e.status,modelPolicy:o};return{error:e.modelPolicyError??this.modelTierCatalogError,status:o,editorStatus:c,thinkingOptions:this.policyThinkingOptions(n.exact,e.availableThinkingLevels)}}renderChatView(e,t){let n=R(e)===`local`?this.hostSpeech.snapshot:void 0;return g`
|
|
7541
|
+
`}starterSessionConfiguration(){let e=this.starterSessionDefaults,t=this.starterModelPolicy;return e===void 0||t===void 0||!this.starterModelPolicySelectionSupported()?e:{...e,model:{provider:t.exact.model.provider,id:t.exact.model.id},thinkingLevel:t.exact.thinkingLevel}}starterModelPolicyInputs(){let e=this.starterSessionDefaults,t=this.starterModelPolicy;if(e===void 0||t===void 0||!this.sessionModelPolicySupported())return;let n=this.selectedMachineModelTierCatalog();if(this.starterModelPolicySelectionSupported()){let r=n===void 0?{kind:`blocked`,reason:this.modelTierCatalogError===``?`Loading model policy choices`:this.modelTierCatalogError}:al(t,n),i={mode:t.mode,...t.tier===void 0?{}:{tier:t.tier},resolved:r.kind===`ready`?r.resolved:t.exact,ladderValid:n?.valid??!0,...r.kind===`blocked`?{blockedReason:r.reason}:{}};return{status:i,response:{contractVersion:1,policy:t,session:{sessionId:`starter`,isStreaming:!1,isCompacting:!1,isBashRunning:!1,pendingMessageCount:0,queuedMessages:[],tokens:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0},cost:0,...e.model===void 0?{}:{model:e.model},thinkingLevel:e.thinkingLevel,modelPolicy:i}}}}let r=t.tier,i=r===void 0?void 0:n?.rows[r],a=t.mode===`tiered`&&r!==void 0&&i?.valid===!0?n?.ladder?.[r]:void 0,o=qc(e),s=t.mode===`exact`&&o!==void 0&&!Zc(t.exact,o),c=t.mode===`tiered`&&a===void 0,l={mode:t.mode,...r===void 0?{}:{tier:r},resolved:a??t.exact,ladderValid:n===void 0||n.valid,...c?{blockedReason:n?.configError??(this.modelTierCatalogError===``?`Choose a valid model tier before starting`:this.modelTierCatalogError)}:s?{blockedReason:`Choose a model and thinking level before starting`}:{}};return{status:l,response:{contractVersion:1,policy:t,session:{sessionId:`starter`,isStreaming:!1,isCompacting:!1,isBashRunning:!1,pendingMessageCount:0,queuedMessages:[],tokens:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0},cost:0,...e.model===void 0?{}:{model:e.model},thinkingLevel:e.thinkingLevel,modelPolicy:l}}}}starterModelPolicyBlocksStart(){return this.starterModelPolicyInputs()?.status.blockedReason!==void 0}starterModelPolicyError(){if(this.modelTierCatalogError!==``)return this.modelTierCatalogError;if(this.starterModelPolicySelectionSupported()){let e=this.currentConfirmedStarterModelPolicyWriterSnapshot()?.error;return e===void 0?this.starterModelPolicyPreferenceReadError:`${hR} ${e}`}let e=this.starterModelPolicyPreferenceScope(),t=e===void 0?void 0:this.starterModelPolicyPreferenceWriter.snapshot(e).error;return t===void 0?this.starterModelPolicyPreferenceReadError:`Could not remember this model policy; this session will still use it. ${t}`}currentConfirmedStarterModelPolicyWriterSnapshot(){let e=this.confirmedStarterModelPolicyUiScope;if(!(e===void 0||this.confirmedStarterModelPolicyUiGeneration!==this.starterModelPolicySelectionGeneration||!this.starterModelPolicyPreferenceScopeMatchesCurrentSelection(e)))return this.confirmedStarterModelPolicyPreferenceWriter.snapshot(e)}confirmedStarterModelPolicyWarning(){let e=this.currentConfirmedStarterModelPolicyWriterSnapshot()?.error;return e===void 0?void 0:`${hR} ${e}`}starterModelPolicyStartSnapshot(){let e=this.starterModelPolicy,t=this.starterSessionDefaults;if(e===void 0||t===void 0||!this.sessionModelPolicySupported())return;if(e.mode===`tiered`)return e.tier===void 0?void 0:{mode:`tiered`,tier:e.tier};let n=qc(t);if(!(n===void 0||Zc(n,e.exact)))return{mode:`exact`,exact:{model:{...e.exact.model},thinkingLevel:e.exact.thinkingLevel}}}starterPlusModelPolicyInitializer(){if(!this.starterModelPolicySelectionSupported())return;let e=this.starterModelPolicy,t=this.selectedMachineModelTierCatalog();if(e===void 0||t===void 0)return;let n=al(e,t);return n.kind===`ready`?n.initialModelPolicy:void 0}async loadMissingStarterPlusModelPolicyInputs(e,t,n){if(this.starterModelPolicy===void 0){await this.loadStarterSessionDefaults(e,{awaitModelTierCatalog:!0,expectedSelectionGeneration:n});return}this.selectedMachineModelTierCatalog()===void 0&&await this.ensureModelTierCatalog(t)}clearStarterModelPolicyAfterSuccessfulStart(e,t,n){!e||this.state.selectedWorkspace?.id!==t||this.starterModelPolicy!==n||(this.starterModelPolicy=void 0)}selectedProjectWorkTarget(e=R(this.state)){if(R(this.state)!==e)return;let t=this.state.selectedProject?.id;return t===void 0?void 0:{machineId:e,projectId:t}}recordProjectWork(e){e!==void 0&&this.recentProjects.recordWork(e.projectId,e.machineId)}mobilePanelBadge(e){let t=this.state.selectedWorkspace;if(t!==void 0)return e.badge?.(this.createWorkspacePanelContext(t))}mobilePanelIcon(e){switch(e.id){case`core:workspace.files`:return`files`;case`core:workspace.git`:return`git`;case`core:workspace.terminal`:return`terminal`;default:return}}workspaceLabelItems(e){return this.plugins.getWorkspaceLabelItems(this.createWorkspaceLabelContext(e))}createWorkspaceLabelContext(e){let t=_R(this.state);return{machine:t,workspace:e,state:this.state,files:this.createWorkspaceFiles(e,t.id),host:this.createWorkspaceHost()}}createWorkspaceFiles(e,t){return{readFile:n=>sc.workspaceFile(e.projectId,e.id,n,t),writeFile:async(n,r,i)=>{let a=await sc.writeWorkspaceFile(e.projectId,e.id,n,r,i,t);return this.files.refreshFiles(),a},deleteFile:async n=>{let r=await sc.deleteWorkspaceFile(e.projectId,e.id,n,t);return this.files.refreshFiles(),r},moveFile:async(n,r,i)=>{let a=await sc.moveWorkspaceFile(e.projectId,e.id,n,r,i,t);return this.files.refreshFiles(),a}}}createWorkspaceHost(){return{requestRender:()=>{this.requestUpdate()}}}createWorkspacePanelTerminal(e,t,n){let r=this.terminalCommandRunsForOrigin(n,t);return{open:n=>{this.openRuntimeTerminal(t,e,n)},runCommand:t=>r.runCommand({...t,workspace:e})}}createWorkspacePanelContext(e){let t=_R(this.state),n=t.id,r=i=>{let a=this.terminalCommandRunsForOrigin(i,n);return Cx({machine:t,workspace:e,state:this.state,files:this.createWorkspaceFiles(e,n),prompt:this.createPromptEditor(),terminal:this.createWorkspacePanelTerminal(e,n,i),openTerminal:t=>{this.openRuntimeTerminal(n,e,t)},host:this.createWorkspaceHost(),piWebUiUnstable:{terminalCommandRuns:a},fileTree:this.state.fileTree,expandedDirs:this.state.expandedDirs,selectedFilePath:this.state.selectedFilePath,selectedFileContent:this.state.selectedFileContent,fileTreeStale:this.state.fileTreeStale,gitStatus:this.state.gitStatus,selectedDiffPath:this.state.selectedDiffPath,selectedDiff:this.state.selectedDiff,selectedStagedDiff:this.state.selectedStagedDiff,gitStale:this.state.gitStale,activeTerminalCount:this.state.activeTerminalCount,selectedTerminalId:this.state.selectedTerminalId,terminalAutoStart:this.terminalAutoStartWorkspaceId===e.id,workspaceUploadDefaultFolder:Tc(e.effectiveConfig,this.workspaceUploadDefaultFolder),onRefreshFiles:()=>{this.files.refreshFiles()},onExpandDir:e=>{this.files.expandDir(e)},onSelectFile:e=>{this.files.selectFile(e)},onStartWorkspaceUpload:(e,t)=>this.files.startWorkspaceUpload(e,t),onCancelWorkspaceUpload:e=>{this.files.cancelWorkspaceUpload(e)},onClearWorkspaceUpload:e=>{this.files.clearWorkspaceUpload(e)},onRefreshGit:()=>{this.git.refreshGit()},onRefreshMemory:()=>{this.memory.refresh()},onSelectDiff:e=>{this.git.selectDiff(e)},onSelectTerminal:(e,t)=>{this.selectTerminal(e,t)}},r)};return r(`core`)}getActions(){return LS(this.getDefaultActions(),this.shortcutConfig)}getDefaultActions(){return[...this.plugins.getActions(this.createPluginRuntimeContext()),...this.sessionActions(),...this.navigationFocusActions(),...this.panelLayoutActions()]}sessionActions(){return[{id:`app.sessions.cleanup`,title:`Clean Up Sessions`,description:`Preview and manually clean up idle or archived sessions on the selected machine`,group:`Sessions`,closesActionPalette:!0,...this.canCleanupSessions()?{}:{enabled:!1,disabledReason:this.sessionCleanupUnavailableMessage()},run:()=>{this.openSessionCleanupDialog()}}]}panelLayoutActions(){return[{id:`app.layout.toggle-terminal-tab`,title:this.terminalTabHidden?`Show Terminal Tab`:`Hide Terminal Tab`,description:this.terminalTabHidden?`Show the terminal tab in the workspace panel`:`Hide the terminal tab from the workspace panel`,group:`View`,run:()=>{this.toggleTerminalTab()}},{id:`app.layout.toggle-info-tab`,title:this.infoTabHidden?`Show Info Tab`:`Hide Info Tab`,description:this.infoTabHidden?`Show the info tab in the workspace panel`:`Hide the info tab from the workspace panel`,group:`View`,run:()=>{this.toggleInfoTab()}},{id:`app.layout.reset-navigation-panel-size`,title:`Reset Navigation Panel Size`,description:`Restore the navigation panel to its default width`,group:`View`,run:()=>{this.resetResizablePanel(`navigation`)}},{id:`app.layout.reset-workspace-panel-size`,title:`Reset Workspace Panel Size`,description:`Restore the workspace panel to its default width`,group:`View`,run:()=>{this.resetResizablePanel(`workspace`)}},{id:`app.layout.reset-panel-sizes`,title:`Reset Panel Sizes`,description:`Restore all side panels to their default widths`,group:`View`,run:()=>{this.resetResizablePanels()}}]}navigationFocusActions(){return[{id:`app.navigation.focus-machines`,title:`Focus Machines`,description:`Move keyboard focus to the machine selector`,shortcut:`mod+g m`,group:`Navigation`,closesActionPalette:!0,run:()=>this.focusNavigationSection(`machines`)},{id:`app.navigation.focus-projects`,title:`Focus Projects`,description:`Move keyboard focus to the projects list`,shortcut:`mod+g p`,group:`Navigation`,closesActionPalette:!0,run:()=>this.focusNavigationSection(`projects`)},{id:`app.navigation.focus-workspaces`,title:`Focus Workspaces`,description:`Move keyboard focus to the workspaces list`,shortcut:`mod+g w`,group:`Navigation`,closesActionPalette:!0,run:()=>this.focusNavigationSection(`workspaces`)},{id:`app.navigation.focus-sessions`,title:`Focus Sessions`,description:`Move keyboard focus to the sessions list`,shortcut:`mod+g s`,group:`Navigation`,closesActionPalette:!0,run:()=>this.focusNavigationSection(`sessions`)}]}ensureGatewayPluginsLoaded(){return this.gatewayPluginLoadPromise??=this.loadExternalPlugins(),this.gatewayPluginLoadPromise}async loadExternalPlugins(){await this.registerExternalPlugins(`PI WEBUI plugins`,()=>ix())}async loadPluginsForSelectedMachine(){let e=this.state.selectedMachine;e?.kind===`remote`&&await this.loadPluginsForMachine(e)}async loadPluginsForMachine(e){if(await this.ensureGatewayPluginsLoaded(),e.kind!==`remote`||this.loadedMachinePluginIds.has(e.id))return;let t=this.machinePluginLoadPromises.get(e.id);if(t!==void 0)return t;let n=this.registerExternalPlugins(`PI WEBUI plugins from ${e.name}`,()=>ix(`api/machines/${encodeURIComponent(e.id)}/pi-webui-plugins/manifest.json`,{machineId:e.id,shouldLoadPlugin:e=>this.plugins.shouldLoadRemotePlugin(e.id,e.machineSpecific)})).then(t=>{t&&this.loadedMachinePluginIds.add(e.id)}).finally(()=>{this.machinePluginLoadPromises.delete(e.id)});this.machinePluginLoadPromises.set(e.id,n),await n}async registerExternalPlugins(e,t){try{let e=await t();for(let t of e)try{this.plugins.register(t)}catch(e){console.warn(`Failed to register PI WEBUI plugin ${t.id}`,e)}return this.synchronizeMemoryPollingForSelectedWorkspace(),this.synchronizeLearnedSkillsPollingForSelectedWorkspace(),this.applyPreferredTheme(!1),this.requestUpdate(),!0}catch(t){return console.warn(`Failed to load ${e}`,t),!1}}createPromptEditor(){return{insertText:e=>{let t=this.promptEditor?.view;if(!t)return;t.hasFocus||t.focus();let n=t.state.selection.main;t.dispatch({changes:{from:n.from,to:n.to,insert:e},selection:{anchor:n.from+e.length}})},getText:()=>this.promptEditor?.view?.state.doc.toString()??``,getSelection:()=>{let e=this.promptEditor?.view;if(!e)return null;let t=e.state.selection.main;return t.empty?null:{start:t.from,end:t.to,text:e.state.sliceDoc(t.from,t.to)}}}}createPluginRuntimeContext(){return this.createPluginRuntimeContextForOrigin(`core`,R(this.state))}createPluginRuntimeContextForOrigin(e,t){let n=e=>Sx({state:this.state,prompt:this.createPromptEditor(),piWebUiUnstable:{terminalCommandRuns:this.terminalCommandRunsForOrigin(e,t),openSettings:e=>{this.openSettings(e)}},openActionPalette:()=>{this.setState({actionPaletteOpen:!0})},focusPrompt:()=>{this.focusChatComposer()},addProject:()=>{this.openProjectDialog()},addMachine:()=>{this.openMachineDialog()},refreshSelectedMachine:async()=>{await Promise.all([this.machines.refreshMachineHealth(),this.machines.refreshMachineRuntime()])},removeSelectedMachine:()=>this.removeMachine(),openSelectedMachine:()=>{this.openSelectedMachine()},configureAuth:()=>this.auth.openLogin(),logoutAuth:()=>this.auth.openLogout(),openThemePicker:()=>{this.openThemeDialog()},selectMainView:e=>{this.selectMainView(e)},selectWorkspaceTool:e=>{this.openWorkspaceTool(e)},openTerminal:e=>{this.openTerminal(e)},refreshFiles:()=>this.files.refreshFiles(),refreshGit:()=>this.git.refreshGit(),refreshAppData:()=>this.refreshAppData(),checkForPiWebUiUpdates:()=>this.piWebUiStatusController.checkForUpdates(),reloadPage:()=>{this.hardReloadApp()},deleteWorkspace:e=>this.deleteWorkspace(e),startSession:()=>this.withChatScrollTransition(()=>this.startSessionAndOpenChat()),archiveSession:()=>this.sessions.archiveSession(),reloadSession:()=>this.sessions.reloadSession(),deleteCachedNewSession:()=>this.sessions.deleteCachedNewSession(),stopActiveWork:()=>this.sessions.stopActiveWork()},n);return n(e)}createActivityRailContext(e){let t=_R(this.state),n=this.state.selectedWorkspace,r=this.activeActivityRailId===e?this.activeActivityRailGeneration:void 0,i=a=>wx({...this.createPluginRuntimeContextForOrigin(a,t.id),machine:t,...n===void 0?{}:{workspaceScope:{workspace:n,files:this.createWorkspaceFiles(n,t.id),terminal:this.createWorkspacePanelTerminal(n,t.id,a)}},host:{requestRender:()=>{this.requestUpdate()},close:()=>{r!==void 0&&this.closeActivityRailItem(e,r)}},onRefreshMemory:()=>{this.memory.refresh()},onRefreshLearnedSkills:()=>{this.learnedSkills.refresh()}},i);return i(`core`)}activityRailItems(){let e=this.plugins.getActivityRailItems();return this.synchronizeMemoryPollingForSelectedWorkspace(e),this.synchronizeLearnedSkillsPollingForSelectedWorkspace(e),e.flatMap(e=>this.projectActivityRailItems([e],this.createActivityRailContext(e.id)))}projectActivityRailItems(e,t){return ly(e,t,this.reportActivityRailError)}activeActivityRailItem(){let e=this.activeActivityRailId;if(e===void 0)return;let t=this.resolveActivityRailItem(e);return t===void 0?void 0:{...t,generation:this.activeActivityRailGeneration}}openActivityRailItem(e,t){this.resolveActivityRailItem(e)!==void 0&&(this.closeCompactActivityRail(),this.activityRailRestoreFocus=t,this.activeActivityRailGeneration+=1,this.activeActivityRailId=e)}resolveActivityRailItem(e){let t=this.plugins.getActivityRailItems().find(t=>t.id===e);if(t===void 0)return;let n=this.createActivityRailContext(e);if(this.projectActivityRailItems([t],n).some(t=>t.id===e))return{activity:t,context:n}}closeActivityRailItem(e,t){if(this.activeActivityRailId!==e||this.activeActivityRailGeneration!==t)return;let n=this.activityRailRestoreFocus;this.activityRailRestoreFocus=void 0,this.activeActivityRailId=void 0,n!==void 0&&this.updateComplete.then(()=>{this.activeActivityRailId===void 0&&n()})}restoreActivityRailFocus(e){if(e.isConnected){e.focus();return}let t=this.compactActivityRailLauncher;if(t?.isConnected===!0){t.focus();return}this.currentCompactActivityRailLauncher()?.focus()}currentCompactActivityRailLauncher(){let e=this.renderRoot.querySelector(`app-context-bar`)?.shadowRoot?.querySelector(`.activity-rail-action-button`);return e?.isConnected===!0?e:void 0}async deleteWorkspace(e=this.state.selectedWorkspace){if(e===void 0)return;if(!x_(e)){this.setState({error:`Only secondary Git worktrees can be deleted`});return}if(My(this.state,e))return;let t=e.branch??e.label;if(!confirm(`Delete workspace ${t}?\n\nThis will run git worktree remove and delete:\n${e.path}\n\nThe Git branch will not be deleted.`))return;let n=R(this.state);try{let t=await sc.deleteWorkspace(e.projectId,e.id,n);if(R(this.state)!==n)return;this.recordWorkspaceDeletionRun(t,n);let r=await this.workspaceForCommandRun(t);if(R(this.state)!==n)return;r!==void 0&&this.openRuntimeTerminal(n,r,{terminalId:t.terminalId})}catch(e){R(this.state)===n&&this.setState({error:`Failed to start workspace deletion: ${WR(e)}`})}}async workspaceForCommandRun(e){let t=this.state.selectedProject?.id===e.projectId?this.state.workspaces:this.state.workspacesByProjectId[e.projectId];return(t===void 0||t.length===0)&&(t=await this.workspaces.refreshProjectWorkspaces(e.projectId)),t.find(t=>t.id===e.workspaceId)}recordWorkspaceDeletionRun(e,t){if(R(this.state)!==t)return;let n=Ny(e);n!==void 0&&(this.setState({workspaceDeletionRuns:{...this.state.workspaceDeletionRuns,[n]:e}}),this.updateWorkspaceDeletionPolling())}async refreshWorkspaceDeletionRuns(){if(this.refreshingWorkspaceDeletionRuns)return;let e=R(this.state),t=this.state.selectedProject;if(t===void 0){this.setState({workspaceDeletionRuns:{}}),this.updateWorkspaceDeletionPolling();return}this.refreshingWorkspaceDeletionRuns=!0;try{let n=await this.terminalCommandRunsForOrigin(`core`,e).listCommandRuns(ky(t.id));if(R(this.state)!==e)return;let r=Ay(n);this.setState({workspaceDeletionRuns:r});for(let t of Object.values(r))Py(t)||await this.handleCompletedWorkspaceDeletionRun(t,e)}catch(e){console.warn(`Failed to refresh workspace deletion runs`,e)}finally{this.refreshingWorkspaceDeletionRuns=!1,this.updateWorkspaceDeletionPolling()}}updateWorkspaceDeletionPolling(){let e=Object.values(this.state.workspaceDeletionRuns).some(Py);if(e&&this.workspaceDeletionPollTimer===void 0){this.workspaceDeletionPollTimer=window.setInterval(()=>{this.refreshWorkspaceDeletionRuns()},1e3);return}!e&&this.workspaceDeletionPollTimer!==void 0&&(window.clearInterval(this.workspaceDeletionPollTimer),this.workspaceDeletionPollTimer=void 0)}async handleCompletedWorkspaceDeletionRun(e,t=R(this.state)){if(R(this.state)!==t)return;let n=HR(t,e.id);if(this.handledWorkspaceDeletionRunIds.has(n))return;let r=Ny(e);if(r!==void 0){if(this.handledWorkspaceDeletionRunIds.add(n),e.status===`succeeded`){if(await this.workspaces.refreshAfterWorkspaceDeleted(e.projectId,r),R(this.state)!==t)return;this.setState({workspaceDeletionRuns:KR(this.state.workspaceDeletionRuns,r)}),this.updateWorkspaceDeletionPolling();return}e.status===`failed`&&(this.setState({error:`Workspace deletion failed. See terminal output.`}),this.updateWorkspaceDeletionPolling())}}openProjectBrowser(e){this.projectBrowserRestoreFocus=e,this.projectBrowserOpen=!0}async showProjectStatistics(e){let t=++this.statisticsRequestGeneration,n=R(this.state),r=()=>t===this.statisticsRequestGeneration&&R(this.state)===n;this.statisticsProject=e,this.statisticsReport=void 0,this.statisticsSessionCount=void 0,this.statisticsError=void 0,this.statisticsLoading=!0;try{let t=await sc.workspaces(e.id,n);if(!r())return;let i={projectPath:e.path,liveCwds:t.map(e=>e.path)};ac.projectUsageCount(i,n).then(({sessionCount:e})=>{r()&&this.statisticsLoading&&(this.statisticsSessionCount=e)},()=>void 0);let a=await ac.projectUsage(i,n);if(!r())return;this.statisticsReport=a}catch(e){if(!r())return;this.statisticsError=e instanceof Error?e.message:String(e)}finally{r()&&(this.statisticsLoading=!1)}}closeProjectStatistics(){this.statisticsRequestGeneration+=1,this.statisticsProject=void 0,this.statisticsReport=void 0,this.statisticsSessionCount=void 0,this.statisticsError=void 0,this.statisticsLoading=!1}closeProjectBrowser(e={}){let t=e.restoreFocus===!0?this.projectBrowserRestoreFocus:void 0;this.projectBrowserRestoreFocus=void 0,this.projectBrowserOpen=!1,t!==void 0&&this.updateComplete.then(()=>{t()})}selectProjectFromBrowser(e){this.closeProjectBrowser(),this.selectNavigationItem(`projects`,`workspaces`,()=>this.workspaces.selectProject(e))}addProjectFromBrowser(){this.closeProjectBrowser(),this.openProjectDialog()}openSessionBrowser(e){this.state.selectedProject!==void 0&&(this.sessionBrowserRestoreFocus=e,this.sessionBrowserOpen=!0)}closeSessionBrowser(e={}){let t=e.restoreFocus===!0?this.sessionBrowserRestoreFocus:void 0;this.sessionBrowserRestoreFocus=void 0,this.sessionBrowserOpen=!1,t!==void 0&&this.updateComplete.then(()=>{t()})}selectSessionFromBrowser(e){this.closeSessionBrowser(),this.selectNavigationItem(`sessions`,`chat`,()=>this.selectSessionFromNavigation(e))}openProjectDialog(){this.setState({projectDialogOpen:!0})}openMachineDialog(){this.setState({machineDialogOpen:!0,error:``})}async submitMachineDialog(e){await this.machines.addMachine(e)!==void 0&&(this.setState({machineDialogOpen:!1}),this.schedulePiWebUiStatusRefresh())}async removeMachine(e=this.state.selectedMachine){if(e===void 0||e.kind===`local`||!window.confirm(`Remove ${e.name}?\n\nThis only removes it from this PI WEBUI gateway.`))return;let t=this.state.selectedMachine?.id===e.id;t&&this.rememberCurrentMachineNavigation();let n=await this.machines.deleteMachine(e,{selectFallback:!t});this.state.machines.some(t=>t.id===e.id)||this.machineNavigation.forget(e.id),t&&n!==void 0&&await this.selectMachineWithMemory(n,{rememberCurrent:!1})}openSelectedMachine(){let e=this.state.selectedMachine;e?.kind!==`remote`||e.baseUrl===void 0||window.open(e.baseUrl,`_blank`,`noopener,noreferrer`)}runAction(e){Promise.resolve().then(()=>e.run()).catch(t=>{let n=t instanceof Error?t.message:String(t);console.warn(`Action failed: ${e.id}`,t),this.setState({error:`Action failed: ${n}`})})}async openModelDialog(){let e=await this.sessions.listModels(),t=this.state.status?.model?.provider,n=this.state.status?.model?.id,r=[...e].sort((e,t)=>{let n=e.provider??``,r=t.provider??``;return n===r?(e.id??``).localeCompare(t.id??``):n.localeCompare(r)});this.setState({modelDialog:{title:`Select Model`,...t!==void 0&&n!==void 0?{selectedValue:`${t}/${n}`}:{},options:r.map(e=>{let r=e.provider??``,i=e.id??``,a=r===t&&i===n;return{value:`${r}/${i}`,label:i+(a?` ✓ current`:``),...r===``?{}:{group:r}}})}})}async pickModel(e){this.setState({modelDialog:void 0});let t=e.indexOf(`/`);if(t<=0)return;let n=e.slice(0,t),r=e.slice(t+1);if(!this.sessionModelPolicySupported()){await this.sessions.setModel(n,r);return}let i=await this.prepareActiveModelPolicyDraft();if(i===void 0||i!==this.activeModelPolicyDraftForState(this.state)||i.mode!==`exact`)return;let a=this.selectedMachineModelTierCatalog(),o=a?.models.find(e=>e.model.provider===n&&e.model.id===r);if(o===void 0){a!==void 0&&(this.modelTierCatalogError=`Model ${n}/${r} is unavailable in the model policy catalog`);return}this.modelTierCatalogError=``,this.setActiveModelPolicyDraft(el(i,o)),this.scheduleActiveExactModelPolicyApply()}openStarterModelDialog(){let e=this.starterSessionDefaults;if(e===void 0)return;let t=this.starterModelPolicySelectionSupported(),n=t?this.starterModelPolicy?.exact:void 0,r=n?.model.provider??e.model?.provider,i=n?.model.id??e.model?.id,a=t?(this.selectedMachineModelTierCatalog()?.models??[]).map(e=>({provider:e.model.provider,id:e.model.id,...e.name===void 0?{}:{name:e.name}})):[...e.models],o=r!==void 0&&i!==void 0&&!a.some(e=>e.provider===r&&e.id===i),s=[...o?[...a,{provider:r,id:i}]:a].sort((e,t)=>{let n=e.provider??``,r=t.provider??``;return n===r?(e.id??``).localeCompare(t.id??``):n.localeCompare(r)});this.setState({modelDialog:{title:`Select Default Model`,source:`starter`,...r!==void 0&&i!==void 0?{selectedValue:`${r}/${i}`}:{},options:s.map(e=>{let t=e.provider??``,n=e.id??``,a=t===r&&n===i;return{value:`${t}/${n}`,label:n+(a?` ✓ current`:``)+(a&&o?` (unavailable)`:``),...t===``?{}:{group:t}}})}})}async pickStarterModel(e){this.setState({modelDialog:void 0});let t=e.indexOf(`/`);if(!(t<=0)){if(this.starterModelPolicySelectionSupported()){let n=this.starterModelPolicy,r=e.slice(0,t),i=e.slice(t+1),a=this.selectedMachineModelTierCatalog()?.models.find(e=>e.model.provider===r&&e.model.id===i);if(n===void 0||a===void 0)return;this.setStarterModelPolicyDraft(el(n,a));return}await this.updateStarterSessionDefaults({model:{provider:e.slice(0,t),modelId:e.slice(t+1)}})}}openThemeDialog(){let e=this.plugins.getThemes(),t=this.resolveCurrentThemePreference(e),n=t.selectedTheme?.id,r=this.themePreference.auto?eR:$L;this.setState({themeDialog:{title:`Select Theme`,selectedValue:n===void 0?r:`${tR}${n}`,options:[{value:r,label:`Auto ${this.themePreference.auto?`✓ on`:`off`}`,description:this.autoThemeDescription(t)},...e.map(e=>({value:`${tR}${e.id}`,label:this.themeOptionLabel(e,n),description:this.themeOptionDescription(e)}))]}})}pickTheme(e){if(this.setState({themeDialog:void 0}),e===$L||e===eR){let t=this.resolveCurrentThemePreference().selectedTheme?.id;if(t===void 0)return;this.themePreference={themeId:t,auto:e===$L},this.applyPreferredTheme(!0);return}if(!e.startsWith(tR))return;let t=e.slice(6),n=this.plugins.getThemes().find(e=>e.id===t);n!==void 0&&(this.themePreference={themeId:n.id,auto:this.themePreference.auto},this.applyPreferredTheme(!0))}applyPreferredTheme(e){let t=this.resolveCurrentThemePreference().activeTheme;t!==void 0&&(this.activeThemeId=t.id,vy(t),e&&_y(this.themePreference))}resolveCurrentThemePreference(e=this.plugins.getThemes()){return yy({themes:e,themePairs:this.plugins.getThemePairs(),preference:this.themePreference,prefersLight:this.systemPrefersLight()})}themePairForTheme(e){return xy(this.plugins.getThemePairs(),e)}systemPrefersLight(){return this.systemLightThemeMedia?.matches??!1}autoThemeDescription(e){return!this.themePreference.auto||e.selectedTheme===void 0?`Follow the system light/dark preference when the selected theme has a pair.`:e.selectedThemePair===void 0?`On, but the selected theme has no light/dark pair, so it will stay selected.`:`On · ${e.selectedThemePair.name} follows the system ${this.systemPrefersLight()?`light`:`dark`} preference.`}themeOptionLabel(e,t){let n=[...e.id===t?[`selected`]:[],...e.id===this.activeThemeId&&e.id!==t?[`active`]:[]];return n.length===0?e.name:`${e.name} ✓ ${n.join(` · `)}`}themeOptionDescription(e){let t=[e.colorScheme];return this.themePairForTheme(e.id)!==void 0&&t.push(`auto pair`),e.description!==void 0&&t.push(e.description),t.join(` · `)}async openThinkingDialog(){let e=await this.sessions.listThinkingLevels(),t=this.state.status?.thinkingLevel??`off`;this.setState({thinkingDialog:{title:`Select Thinking Level`,selectedValue:t,options:e.map(e=>{let n=JR(e);return{value:e,label:`${e}${e===t?` ✓ current`:``}`,...n===void 0?{}:{description:n}}})}})}async pickThinking(e){if(this.setState({thinkingDialog:void 0}),e===``)return;if(!this.sessionModelPolicySupported()){await this.sessions.setThinkingLevel(e);return}let t=await this.prepareActiveModelPolicyDraft();if(t===void 0||t!==this.activeModelPolicyDraftForState(this.state)||t.mode!==`exact`)return;let n=tl(t,e);if(this.setActiveModelPolicyDraft(n),(this.selectedMachineModelTierCatalog()?.models.find(e=>e.model.provider===n.exact.model.provider&&e.model.id===n.exact.model.id))?.thinkingLevels.includes(e)!==!0){this.cancelActiveModelPolicyApply(),this.modelTierCatalogError=`Thinking level ${e} is unsupported by ${n.exact.model.provider}/${n.exact.model.id}`;return}this.modelTierCatalogError=``,this.scheduleActiveExactModelPolicyApply()}openStarterThinkingDialog(){let e=this.starterSessionDefaults;if(e===void 0)return;let t=this.starterModelPolicySelectionSupported()?this.starterModelPolicy?.exact.thinkingLevel??e.thinkingLevel:e.thinkingLevel,n=e.thinkingLevels.includes(t)?e.thinkingLevels:[t,...e.thinkingLevels];this.setState({thinkingDialog:{title:`Select Default Thinking Level`,source:`starter`,selectedValue:t,options:n.map(e=>{let n=JR(e);return{value:e,label:`${e}${e===t?` ✓ current`:``}`,...n===void 0?{}:{description:n}}})}})}async pickStarterThinking(e){if(this.setState({thinkingDialog:void 0}),e!==``){if(this.starterModelPolicySelectionSupported()){let t=this.starterModelPolicy;t!==void 0&&this.setStarterModelPolicyDraft(tl(t,e));return}await this.updateStarterSessionDefaults({thinkingLevel:e})}}async updateStarterSessionDefaults(e){let t=this.state.selectedWorkspace;if(t===void 0)return;let n=R(this.state);try{let r=await cc.updateSessionDefaults(t.path,e,n);if(R(this.state)!==n||this.state.selectedWorkspace?.id!==t.id)return;this.starterSessionDefaults=r,this.starterNotice=void 0,this.starterModelPolicyPreferenceReadError=r.starterModelPolicyPreferenceError??``;let i=this.starterModelPolicy,a=i===void 0?Jc(r):Yc(i,r);this.starterModelPolicy=a;let o=qc(r);a.mode===`exact`&&o!==void 0&&Zc(a.exact,o)&&this.persistStarterModelPolicyPreference(a)}catch(e){R(this.state)===n&&this.state.selectedWorkspace?.id===t.id&&this.publishStarterNotice(Tl(`defaults-failed`,`Could not save this workspace's model defaults. ${WR(e)}`,{machineId:n,workspaceId:t.id}))}}sendPrompt(e,t,n,r){if(!(n!==void 0&&n.length>0)&&t===void 0&&this.auth.handleSlashCommand(e))return;let i=this.selectedProjectWorkTarget();this.sessions.send(e,t,n,r).then(e=>{e&&this.recordProjectWork(i)})}async ensureStarterModelPolicyCatalog(){let e=this.selectedMachineModelTierCatalog();return e===void 0?(await this.ensureModelTierCatalog(R(this.state)),this.selectedMachineModelTierCatalog()):e}setStarterModelPolicyDraft(e){this.starterNotice=void 0;let t={mode:e.mode,exact:{model:{...e.exact.model},thinkingLevel:e.exact.thinkingLevel},...e.tier===void 0?{}:{tier:e.tier}};return this.starterModelPolicy=t,t}applyGitUpdateManagerStatus(e,t,n){let r=this.state.selectedWorkspace;R(this.state)!==t||r?.id!==e.id||r.projectId!==e.projectId||this.setState({gitStatus:n,gitStale:!1})}startTerminalModalPointerInteraction(e,t){if(this.terminalModalMaximized||t.button!==0)return;let n=t.currentTarget;if(!(n instanceof HTMLElement))return;let r=n.closest(`.terminal-modal-frame`);if(!(r instanceof HTMLElement))return;t.preventDefault(),t.stopPropagation();let i=XS(this.terminalModalBoundsFromFrame(r),this.terminalModalViewport());n.setPointerCapture(t.pointerId),this.terminalModalBounds=i,this.terminalModalPointerInteraction={operation:e,pointerId:t.pointerId,target:n,startClientX:t.clientX,startClientY:t.clientY,bounds:i}}terminalModalBoundsFromFrame(e){let{left:t,top:n,width:r,height:i}=e.getBoundingClientRect();return{left:t,top:n,width:r,height:i}}terminalModalViewport(){return typeof window>`u`?{width:0,height:0}:{width:window.innerWidth,height:window.innerHeight}}terminalModalFrameStyle(){let e=this.terminalModalMaximized?void 0:this.terminalModalBounds,t=e===void 0?``:`; left: ${String(e.left)}px; top: ${String(e.top)}px; width: ${String(e.width)}px; height: ${String(e.height)}px`;return`--terminal-modal-opacity: ${String(this.terminalModalOpacity)}%${t};`}finishTerminalModalPointerInteraction(){let e=this.terminalModalPointerInteraction;if(e!==void 0){try{e.target.releasePointerCapture(e.pointerId)}catch{}this.terminalModalPointerInteraction=void 0}}persistTerminalModalPreferences(){iC({fontSize:this.terminalModalFontSize,opacity:this.terminalModalOpacity})}toggleTerminalTab(){this.terminalTabHidden=!this.terminalTabHidden,this.persistWorkspaceTabVisibility()}toggleInfoTab(){this.infoTabHidden=!this.infoTabHidden,this.persistWorkspaceTabVisibility()}persistWorkspaceTabVisibility(){fC({terminalHidden:this.terminalTabHidden,infoHidden:this.infoTabHidden})}activeModelPolicyInputs(e){let t=e.status?.modelPolicy;if(e.status===void 0||t===void 0||!this.sessionModelPolicySupported())return;let n=this.activeModelPolicyDraftForState(e);if(n===void 0)return{error:e.modelPolicyError??this.modelTierCatalogError,status:t,editorStatus:e.status,thinkingOptions:this.policyThinkingOptions(t.resolved,e.availableThinkingLevels)};let r=n.tier,i=r===void 0||this.selectedMachineModelTierCatalog()?.rows[r].valid!==!0?void 0:this.selectedMachineModelTierCatalog()?.ladder?.[r],a=n.mode===`exact`?n.exact:i??t.resolved,o={mode:n.mode,...r===void 0?{}:{tier:r},resolved:{model:{...a.model},thinkingLevel:a.thinkingLevel},ladderValid:t.ladderValid,...t.blockedReason===void 0?{}:{blockedReason:t.blockedReason}},s=n.exact.model.provider!==``&&n.exact.model.id!==``,c=n.mode===`exact`?{...e.status,...s?{model:{...n.exact.model}}:{},thinkingLevel:n.exact.thinkingLevel,modelPolicy:o}:{...e.status,modelPolicy:o};return{error:e.modelPolicyError??this.modelTierCatalogError,status:o,editorStatus:c,thinkingOptions:this.policyThinkingOptions(n.exact,e.availableThinkingLevels)}}renderChatView(e,t){let n=R(e)===`local`?this.hostSpeech.snapshot:void 0;return g`
|
|
7542
7542
|
<chat-view .sessionId=${t.id} .sessionInfo=${t} .messages=${e.messages} .messageStart=${e.messagePageStart} .messageEnd=${e.messagePageEnd} .messageTotal=${e.messagePageTotal} .hasMore=${e.messagePageStart>0} .loadingMore=${e.isLoadingEarlierMessages} .isSendingPrompt=${e.sendingPrompts[t.id]===!0} .isCompacting=${e.status?.isCompacting===!0} .pendingMessageCount=${e.status?.pendingMessageCount??0} .clientQueuedMessages=${e.clientQueuedSessionMessages[t.id]??[]} .status=${e.status} .warningCount=${this.sessionWarningVisibility.warningCount} .warningsExpanded=${this.sessionWarningVisibility.warningCount>0&&!this.sessionWarningVisibility.collapsed} .onToggleWarnings=${this.handleToggleWarnings} .activity=${e.activity} .notificationInbox=${Xm(e.selectedNotificationInbox)} .canClearServerQueue=${this.canClearServerQueue()} .onClearServerQueue=${this.handleClearServerQueue} .canMessageActions=${this.canMessageActions()&&t.archived!==!0} .onEditFromHere=${this.handleEditFromHere} .onForkFromHere=${this.handleForkFromHere} .hostSpeechStatus=${n?.status} .activeHostSpeechMessageKey=${n?.active?.messageKey??``} .hostSpeechError=${n?.error??``} .onToggleHostSpeech=${n===void 0?void 0:this.handleToggleHostSpeech} .onDismissWarning=${this.handleDismissWarning} .onDismissNotification=${this.handleDismissNotification} .onDismissAllNotifications=${this.handleDismissAllNotifications} .warningsVisible=${!this.sessionWarningVisibility.collapsed} .onLoadMore=${()=>this.withChatPrependTransition(()=>this.sessions.loadEarlierMessages())}></chat-view>
|
|
7543
7543
|
`}renderContextBar(){return this.appShell.isDesktopActivityRailLayout?null:g`
|
|
7544
7544
|
<app-context-bar
|
|
@@ -7670,7 +7670,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
7670
7670
|
<div class="mobile-navigation-panel">${this.appShell.isMobileNavigationLayout?this.renderNavigationPanel():null}</div>
|
|
7671
7671
|
${e.selectedSession?g`
|
|
7672
7672
|
${this.renderChatView(e,e.selectedSession)}
|
|
7673
|
-
<prompt-editor .sessionId=${e.selectedSession.id} .cwd=${e.selectedWorkspace?.path} .machineId=${R(e)} .projectId=${e.selectedWorkspace?.projectId} .workspaceId=${e.selectedWorkspace?.id} .workspaceScopedFileSuggestions=${this.supportsWorkspaceFileSuggestions()} .speechInputSettings=${this.speechInputSettings} .disabled=${e.selectedSession.archived===!0} .canSteer=${e.status?.isStreaming===!0} .isCompacting=${e.status?.isCompacting===!0} .canStop=${e.status?.isStreaming===!0||e.status?.isBashRunning===!0||e.status?.isCompacting===!0||(e.status?.pendingMessageCount??0)>0} .status=${i===void 0?
|
|
7673
|
+
<prompt-editor .sessionId=${e.selectedSession.id} .cwd=${e.selectedWorkspace?.path} .machineId=${R(e)} .projectId=${e.selectedWorkspace?.projectId} .workspaceId=${e.selectedWorkspace?.id} .workspaceScopedFileSuggestions=${this.supportsWorkspaceFileSuggestions()} .speechInputSettings=${this.speechInputSettings} .disabled=${e.selectedSession.archived===!0} .canSteer=${e.status?.isStreaming===!0} .isCompacting=${e.status?.isCompacting===!0} .canStop=${e.status?.isStreaming===!0||e.status?.isBashRunning===!0||e.status?.isCompacting===!0||(e.status?.pendingMessageCount??0)>0} .status=${i===void 0?GR(e.status):i.editorStatus} .availableThinkingLevels=${e.availableThinkingLevels} .modelPolicyStatus=${i?.status} .modelTierCatalog=${i===void 0?void 0:this.selectedMachineModelTierCatalog()} .policyThinkingOptions=${i?.thinkingOptions??[]} .modelPolicyLoading=${i!==void 0&&(e.isLoadingModelPolicy||this.modelTierCatalogLoading)} .modelPolicySaving=${i!==void 0&&e.isSavingModelPolicy} .modelPolicyError=${i===void 0?``:i.error} .onSelectPolicyMode=${i===void 0?void 0:this.handleSelectActivePolicyMode} .onSelectPolicyTier=${i===void 0?void 0:this.handleSelectActivePolicyTier} .onSelectPolicyThinking=${i===void 0?void 0:this.handleSelectActivePolicyThinking} .sending=${e.sendingPrompts[e.selectedSession.id]===!0} .onSend=${this.handleSendPrompt} .onStop=${this.handleStopActiveWork} .onSelectModel=${this.handleSelectModel} .onSelectThinking=${this.handleSelectThinking} .onCompact=${t?this.handleCompact:void 0}></prompt-editor>
|
|
7674
7674
|
${e.commandDialog===void 0?null:g`<command-picker .title=${e.commandDialog.title} .options=${e.commandDialog.options} .onPick=${t=>this.sessions.respondToCommand(e.commandDialog?.requestId??``,t)} .onCancel=${()=>{this.sessions.cancelCommand()}}></command-picker>`}
|
|
7675
7675
|
`:this.shouldShowSessionStartScreen(e)?this.renderSessionStartScreen(e):g`<div class="empty">${this.sessionEmptyMessage()}</div>`}
|
|
7676
7676
|
${e.modelDialog===void 0?null:g`<command-picker title=${e.modelDialog.title} .searchable=${!0} .options=${e.modelDialog.options} .selectedValue=${e.modelDialog.selectedValue} .onPick=${t=>{e.modelDialog?.source===`starter`?this.pickStarterModel(t):this.pickModel(t)}} .onCancel=${()=>{this.setState({modelDialog:void 0})}}></command-picker>`}
|
|
@@ -7734,4 +7734,4 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
7734
7734
|
${Nt(this.recentProjectDialogGeneration,this.renderRecentProjectDialog())}
|
|
7735
7735
|
${this.settingsSection===void 0?null:g`<settings-dialog .section=${this.settingsSection} .machine=${e.selectedMachine} .machineRuntime=${this.selectedMachineRuntime()} .actions=${this.getDefaultActions()} .speechInputSettings=${this.speechInputSettings} .speechInputSettingsRequestSeq=${this.speechInputSettingsRequestSeq} .isSpeechInputSettingsRequestCurrent=${this.isSpeechInputSettingsRequestCurrent} .showHostSpeechSettings=${R(e)===`local`} .hostSpeechStatus=${R(e)===`local`?this.hostSpeech.snapshot.status:void 0} .hostSpeechStatusLoading=${R(e)===`local`&&this.hostSpeech.snapshot.loadingStatus} .onReloadHostSpeech=${R(e)===`local`?()=>this.hostSpeech.refreshStatus():void 0} .onNavigate=${e=>{this.navigateSettings(e)}} .onClose=${()=>{this.closeSettings()}} .onConfigSaved=${e=>{this.applyClientConfig(e)}} .onSpeechInputSettingsLoaded=${e=>{this.handleSpeechInputSettingsLoaded(e)}} .onSpeechInputSettingsSaved=${e=>{this.handleSpeechInputSettingsSaved(e)}} .onModelTiersSaved=${(e,t)=>{this.handleModelTiersSaved(e,t)}} .onRefreshMachineRuntime=${async e=>{await this.machines.refreshMachineRuntime(e)}}></settings-dialog>`}
|
|
7736
7736
|
</div>
|
|
7737
|
-
`}static{this.styles=Yy}};H([S()],$.prototype,`state`,void 0),H([C(`chat-view`)],$.prototype,`chatView`,void 0),H([C(`prompt-editor`)],$.prototype,`promptEditor`,void 0),H([C(`app-navigation-panel`)],$.prototype,`navigationPanel`,void 0),H([C(`#navigation-panel`)],$.prototype,`navigationPanelFrame`,void 0),H([C(`#workspace-panel`)],$.prototype,`workspacePanelFrame`,void 0),H([S()],$.prototype,`unreadSessionIds`,void 0),H([S()],$.prototype,`speechInputSettings`,void 0),H([S()],$.prototype,`activeThemeId`,void 0),H([S()],$.prototype,`isRefreshingApp`,void 0),H([S()],$.prototype,`sessionCleanupDialog`,void 0),H([S()],$.prototype,`historyWindow`,void 0),H([S()],$.prototype,`recentProjectDialogEntry`,void 0),H([S()],$.prototype,`starterSessionDefaults`,void 0),H([S()],$.prototype,`starterModelPolicyPreferenceReadError`,void 0),H([S()],$.prototype,`starterNotice`,void 0),H([S()],$.prototype,`modelTierCatalog`,void 0),H([S()],$.prototype,`modelTierCatalogLoading`,void 0),H([S()],$.prototype,`modelTierCatalogError`,void 0),H([S()],$.prototype,`starterModelPolicy`,void 0),H([S()],$.prototype,`activeModelPolicyDraft`,void 0),H([S()],$.prototype,`modelsConfigDialogOpen`,void 0),H([S()],$.prototype,`projectBrowserOpen`,void 0),H([S()],$.prototype,`statisticsProject`,void 0),H([S()],$.prototype,`statisticsReport`,void 0),H([S()],$.prototype,`statisticsSessionCount`,void 0),H([S()],$.prototype,`statisticsLoading`,void 0),H([S()],$.prototype,`statisticsError`,void 0),H([S()],$.prototype,`sessionBrowserOpen`,void 0),H([S()],$.prototype,`skillsConfigDialogOpen`,void 0),H([S()],$.prototype,`pluginsConfigDialogOpen`,void 0),H([S()],$.prototype,`systemPromptDialogOpen`,void 0),H([S()],$.prototype,`gitUpdateManagerPanelOpen`,void 0),H([S()],$.prototype,`terminalModalOpen`,void 0),H([S()],$.prototype,`terminalModalBounds`,void 0),H([S()],$.prototype,`terminalModalMaximized`,void 0),H([S()],$.prototype,`terminalModalFontSize`,void 0),H([S()],$.prototype,`terminalModalOpacity`,void 0),H([S()],$.prototype,`terminalTabHidden`,void 0),H([S()],$.prototype,`infoTabHidden`,void 0),H([S()],$.prototype,`railOrder`,void 0),H([S()],$.prototype,`compactRailOpen`,void 0),H([S()],$.prototype,`activeActivityRailId`,void 0),H([S()],$.prototype,`settingsSection`,void 0),H([S()],$.prototype,`shortcutConfig`,void 0),H([S()],$.prototype,`workspaceUploadDefaultFolder`,void 0),$=H([b(`pi-webui-app`)],$);function
|
|
7737
|
+
`}static{this.styles=Yy}};H([S()],$.prototype,`state`,void 0),H([C(`chat-view`)],$.prototype,`chatView`,void 0),H([C(`prompt-editor`)],$.prototype,`promptEditor`,void 0),H([C(`app-navigation-panel`)],$.prototype,`navigationPanel`,void 0),H([C(`#navigation-panel`)],$.prototype,`navigationPanelFrame`,void 0),H([C(`#workspace-panel`)],$.prototype,`workspacePanelFrame`,void 0),H([S()],$.prototype,`unreadSessionIds`,void 0),H([S()],$.prototype,`speechInputSettings`,void 0),H([S()],$.prototype,`activeThemeId`,void 0),H([S()],$.prototype,`isRefreshingApp`,void 0),H([S()],$.prototype,`sessionCleanupDialog`,void 0),H([S()],$.prototype,`historyWindow`,void 0),H([S()],$.prototype,`recentProjectDialogEntry`,void 0),H([S()],$.prototype,`starterSessionDefaults`,void 0),H([S()],$.prototype,`starterModelPolicyPreferenceReadError`,void 0),H([S()],$.prototype,`starterNotice`,void 0),H([S()],$.prototype,`modelTierCatalog`,void 0),H([S()],$.prototype,`modelTierCatalogLoading`,void 0),H([S()],$.prototype,`modelTierCatalogError`,void 0),H([S()],$.prototype,`starterModelPolicy`,void 0),H([S()],$.prototype,`activeModelPolicyDraft`,void 0),H([S()],$.prototype,`modelsConfigDialogOpen`,void 0),H([S()],$.prototype,`projectBrowserOpen`,void 0),H([S()],$.prototype,`statisticsProject`,void 0),H([S()],$.prototype,`statisticsReport`,void 0),H([S()],$.prototype,`statisticsSessionCount`,void 0),H([S()],$.prototype,`statisticsLoading`,void 0),H([S()],$.prototype,`statisticsError`,void 0),H([S()],$.prototype,`sessionBrowserOpen`,void 0),H([S()],$.prototype,`skillsConfigDialogOpen`,void 0),H([S()],$.prototype,`pluginsConfigDialogOpen`,void 0),H([S()],$.prototype,`systemPromptDialogOpen`,void 0),H([S()],$.prototype,`gitUpdateManagerPanelOpen`,void 0),H([S()],$.prototype,`terminalModalOpen`,void 0),H([S()],$.prototype,`terminalModalBounds`,void 0),H([S()],$.prototype,`terminalModalMaximized`,void 0),H([S()],$.prototype,`terminalModalFontSize`,void 0),H([S()],$.prototype,`terminalModalOpacity`,void 0),H([S()],$.prototype,`terminalTabHidden`,void 0),H([S()],$.prototype,`infoTabHidden`,void 0),H([S()],$.prototype,`railOrder`,void 0),H([S()],$.prototype,`compactRailOpen`,void 0),H([S()],$.prototype,`activeActivityRailId`,void 0),H([S()],$.prototype,`settingsSection`,void 0),H([S()],$.prototype,`shortcutConfig`,void 0),H([S()],$.prototype,`workspaceUploadDefaultFolder`,void 0),$=H([b(`pi-webui-app`)],$);function gR(){let e=new vx;return e.register({id:`core`,plugin:qb}),e.register({id:`themes`,plugin:Qb}),e}function _R(e){let t=e.selectedMachine;return t===void 0?{id:`local`,name:`local`,kind:`local`}:{id:t.id,name:t.name,kind:t.kind}}function vR(e,t){return JSON.stringify([e,t.id,t.cwd])}function yR(e){let t=e.selectedSession;return t===void 0?void 0:vR(R(e),t)}function bR(e){let t=e.selectedSession;return t===void 0?void 0:{machineId:R(e),sessionId:t.id}}function xR(e,t){return e?.machineId===t?.machineId&&e?.sessionId===t?.sessionId}function SR(e){let t=e.selectedSession;return t===void 0?void 0:JSON.stringify([R(e),t.id,t.cwd])}function CR(e){return JSON.stringify([R(e),e.selectedWorkspace?.id,e.selectedWorkspace?.path,e.selectedSession?.id,e.selectedSession?.cwd])}function wR(e){if(TR(e)!==void 0&&ER(e,R(e)))return SR(e)}function TR(e){return e.status?.modelPolicy}function ER(e,t){if(t===`local`)return!0;let n=e.machineRuntimes[t];return n?.ok===!0&&E(n,w.sessionsModelPolicy)}function DR(e,t){let n=e.machineRuntimes[t];return n?.ok===!0&&E(n,w.sessionsModelPolicyStarterSelection)}function OR(e){return e!==void 0&&`starterModelPolicyContractVersion`in e}function kR(e,t){return e.mode===t.mode&&e.tier===t.tier&&Zc(e.exact,t.exact)}function AR(e){return e.id===sR||e.sourcePluginId===aR&&e.localId===oR}function jR(e){return e.id===uR||e.sourcePluginId===cR&&e.localId===lR}function MR(e,t){return R(e)!==R(t)||e.selectedProject?.id!==t.selectedProject?.id||e.selectedWorkspace?.id!==t.selectedWorkspace?.id||e.selectedWorkspace?.path!==t.selectedWorkspace?.path}function NR(e,t){return e.machines!==t.machines||e.machineRuntimes!==t.machineRuntimes}function PR(e,t){return e.machines!==t.machines||e.machineStatuses!==t.machineStatuses||(e.selectedMachine?.id??`local`)!==(t.selectedMachine?.id??`local`)}function FR(e,t){return IR(e,t)}function IR(e,t){if(e.kind===`local`)return!0;let n=t?.status??e.status;return n===void 0||n===`unknown`||n===`online`}function LR(e,t){return Object.entries(t).some(([t,n])=>Reflect.get(e,t)!==n)}function RR(e,t){return e.size===t.size&&[...e].every(e=>t.has(e))}function zR(e){return Ll(e.status,e.activity)}function BR(e){return e.type===`terminal.created`||e.type===`terminal.exited`||e.type===`terminal.closed`}function VR(){return{}}function HR(e,t){return JSON.stringify([e,t])}function UR(e){return ZL[Math.min(e,ZL.length-1)]??3e4}function WR(e){return e instanceof Error?e.message:String(e)}function GR(e){if(e?.modelPolicy===void 0)return e;let t={...e};return delete t.modelPolicy,t}function KR(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>e!==t))}function qR(){return new Promise(e=>requestAnimationFrame(()=>{e()}))}function JR(e){switch(e){case`off`:return`No reasoning`;case`minimal`:return`Very brief reasoning (~1k tokens)`;case`low`:return`Light reasoning (~2k tokens)`;case`medium`:return`Moderate reasoning (~8k tokens)`;case`high`:return`Deep reasoning (~16k tokens)`;case`xhigh`:return`Maximum reasoning (~32k tokens)`;default:return}}export{y as a,b as i,C as n,g as o,x as r,h as s,H as t};
|