@hyperdreamer/pi-webui 1.12.2 → 1.12.3
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-DQVxJWsW.js → CodeViewer-BX-JhrL4.js} +1 -1
- package/dist/client/assets/{UnifiedDiffViewer-BjLQphPw.js → UnifiedDiffViewer-CFdMhoMV.js} +1 -1
- package/dist/client/assets/{index-BHTTRJX8.js → index-CcQJZHKx.js} +83 -53
- package/dist/client/index.html +1 -1
- 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-BX-JhrL4.js","./vendor-editor-core-vUi74DnD.js","./vendor-editor-languages-DoaXUodB.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,Z as s,d as c,f as l,j as u,l as d,p as f,q as p,u as m}from"./vendor-editor-core-vUi74DnD.js";import{a as ee,o as te,s as ne}from"./vendor-editor-languages-DoaXUodB.js";import{n as re,t as ie}from"./vendor-terminal-D8k4UKM2.js";var ae=Object.defineProperty,oe=(e,t)=>{let n={};for(var r in e)ae(n,r,{get:e[r],enumerable:!0});return t||ae(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 se=globalThis,ce=se.ShadowRoot&&(se.ShadyCSS===void 0||se.ShadyCSS.nativeShadow)&&`adoptedStyleSheets`in Document.prototype&&`replace`in CSSStyleSheet.prototype,le=Symbol(),ue=new WeakMap,de=class{constructor(e,t,n){if(this._$cssResult$=!0,n!==le)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(ce&&e===void 0){let n=t!==void 0&&t.length===1;n&&(e=ue.get(t)),e===void 0&&((this.o=e=new CSSStyleSheet).replaceSync(this.cssText),n&&ue.set(t,e))}return e}toString(){return this.cssText}},fe=e=>new de(typeof e==`string`?e:e+``,void 0,le),h=(e,...t)=>new de(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,le),pe=(e,t)=>{if(ce)e.adoptedStyleSheets=t.map(e=>e instanceof CSSStyleSheet?e:e.styleSheet);else for(let n of t){let t=document.createElement(`style`),r=se.litNonce;r!==void 0&&t.setAttribute(`nonce`,r),t.textContent=n.cssText,e.appendChild(t)}},me=ce?e=>e:e=>e instanceof CSSStyleSheet?(e=>{let t=``;for(let n of e.cssRules)t+=n.cssText;return fe(t)})(e):e,{is:he,defineProperty:ge,getOwnPropertyDescriptor:_e,getOwnPropertyNames:ve,getOwnPropertySymbols:ye,getPrototypeOf:be}=Object,xe=globalThis,Se=xe.trustedTypes,Ce=Se?Se.emptyScript:``,we=xe.reactiveElementPolyfillSupport,Te=(e,t)=>e,Ee={toAttribute(e,t){switch(t){case Boolean:e=e?Ce: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}},De=(e,t)=>!he(e,t),Oe={attribute:!0,type:String,converter:Ee,reflect:!1,useDefault:!1,hasChanged:De};Symbol.metadata??=Symbol(`metadata`),xe.litPropertyMetadata??=new WeakMap;var ke=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=Oe){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&&ge(this.prototype,e,r)}}static getPropertyDescriptor(e,t,n){let{get:r,set:i}=_e(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)??Oe}static _$Ei(){if(this.hasOwnProperty(Te(`elementProperties`)))return;let e=be(this);e.finalize(),e.l!==void 0&&(this.l=[...e.l]),this.elementProperties=new Map(e.elementProperties)}static finalize(){if(this.hasOwnProperty(Te(`finalized`)))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(Te(`properties`))){let e=this.properties,t=[...ve(e),...ye(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(me(e))}else e!==void 0&&t.push(me(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 pe(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?Ee: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?Ee: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??De)(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){}};ke.elementStyles=[],ke.shadowRootOptions={mode:`open`},ke[Te(`elementProperties`)]=new Map,ke[Te(`finalized`)]=new Map,we?.({ReactiveElement:ke}),(xe.reactiveElementVersions??=[]).push(`2.1.2`);var Ae=globalThis,je=e=>e,Me=Ae.trustedTypes,Ne=Me?Me.createPolicy(`lit-html`,{createHTML:e=>e}):void 0,Pe=`$lit$`,Fe=`lit$${Math.random().toFixed(9).slice(2)}$`,Ie=`?`+Fe,Le=`<${Ie}>`,Re=document,ze=()=>Re.createComment(``),Be=e=>e===null||typeof e!=`object`&&typeof e!=`function`,Ve=Array.isArray,He=e=>Ve(e)||typeof e?.[Symbol.iterator]==`function`,Ue=`[
|
|
3
3
|
\f\r]`,We=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,Ge=/-->/g,Ke=/>/g,qe=RegExp(`>|${Ue}(?:([^\\s"'>=/]+)(${Ue}*=${Ue}*(?:[^ \t\n\f\r"'\`<>=]|("|')|))|$)`,`g`),Je=/'/g,Ye=/"/g,Xe=/^(?:script|style|textarea|title)$/i,Ze=e=>(t,...n)=>({_$litType$:e,strings:t,values:n}),g=Ze(1),_=Ze(2),Qe=Symbol.for(`lit-noChange`),v=Symbol.for(`lit-nothing`),$e=new WeakMap,et=Re.createTreeWalker(Re,129);function tt(e,t){if(!Ve(e)||!e.hasOwnProperty(`raw`))throw Error(`invalid template strings array`);return Ne===void 0?t:Ne.createHTML(t)}var nt=(e,t)=>{let n=e.length-1,r=[],i,a=t===2?`<svg>`:t===3?`<math>`:``,o=We;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===We?c[1]===`!--`?o=Ge:c[1]===void 0?c[2]===void 0?c[3]!==void 0&&(o=qe):(Xe.test(c[2])&&(i=RegExp(`</`+c[2],`g`)),o=qe):o=Ke:o===qe?c[0]===`>`?(o=i??We,l=-1):c[1]===void 0?l=-2:(l=o.lastIndex-c[2].length,s=c[1],o=c[3]===void 0?qe:c[3]===`"`?Ye:Je):o===Ye||o===Je?o=qe:o===Ge||o===Ke?o=We:(o=qe,i=void 0);let d=o===qe&&e[t+1].startsWith(`/>`)?` `:``;a+=o===We?n+Le:l>=0?(r.push(s),n.slice(0,l)+Pe+n.slice(l)+Fe+d):n+Fe+(l===-2?t:d)}return[tt(e,a+(e[n]||`<?>`)+(t===2?`</svg>`:t===3?`</math>`:``)),r]},rt=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]=nt(t,n);if(this.el=e.createElement(l,r),et.currentNode=this.el.content,n===2||n===3){let e=this.el.content.firstChild;e.replaceWith(...e.childNodes)}for(;(i=et.nextNode())!==null&&c.length<s;){if(i.nodeType===1){if(i.hasAttributes())for(let e of i.getAttributeNames())if(e.endsWith(Pe)){let t=u[o++],n=i.getAttribute(e).split(Fe),r=/([.?@])?(.*)/.exec(t);c.push({type:1,index:a,name:r[2],strings:n,ctor:r[1]===`.`?ct:r[1]===`?`?lt:r[1]===`@`?ut:st}),i.removeAttribute(e)}else e.startsWith(Fe)&&(c.push({type:6,index:a}),i.removeAttribute(e));if(Xe.test(i.tagName)){let e=i.textContent.split(Fe),t=e.length-1;if(t>0){i.textContent=Me?Me.emptyScript:``;for(let n=0;n<t;n++)i.append(e[n],ze()),et.nextNode(),c.push({type:2,index:++a});i.append(e[t],ze())}}}else if(i.nodeType===8)if(i.data===Ie)c.push({type:2,index:a});else{let e=-1;for(;(e=i.data.indexOf(Fe,e+1))!==-1;)c.push({type:7,index:a}),e+=Fe.length-1}a++}}static createElement(e,t){let n=Re.createElement(`template`);return n.innerHTML=e,n}};function it(e,t,n=e,r){if(t===Qe)return t;let i=r===void 0?n._$Cl:n._$Co?.[r],a=Be(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=it(e,i._$AS(e,t.values),i,r)),t}var at=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??Re).importNode(t,!0);et.currentNode=r;let i=et.nextNode(),a=0,o=0,s=n[0];for(;s!==void 0;){if(a===s.index){let t;s.type===2?t=new ot(i,i.nextSibling,this,e):s.type===1?t=new s.ctor(i,s.name,s.strings,this,e):s.type===6&&(t=new dt(i,this,e)),this._$AV.push(t),s=n[++o]}a!==s?.index&&(i=et.nextNode(),a++)}return et.currentNode=Re,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++}},ot=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=it(this,e,t),Be(e)?e===v||e==null||e===``?(this._$AH!==v&&this._$AR(),this._$AH=v):e!==this._$AH&&e!==Qe&&this._(e):e._$litType$===void 0?e.nodeType===void 0?He(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&&Be(this._$AH)?this._$AA.nextSibling.data=e:this.T(Re.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=rt.createElement(tt(n.h,n.h[0]),this.options)),n);if(this._$AH?._$AD===r)this._$AH.p(t);else{let e=new at(r,this),n=e.u(this.options);e.p(t),this.T(n),this._$AH=e}}_$AC(e){let t=$e.get(e.strings);return t===void 0&&$e.set(e.strings,t=new rt(e)),t}k(t){Ve(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(ze()),this.O(ze()),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=je(e).nextSibling;je(e).remove(),e=t}}setConnected(e){this._$AM===void 0&&(this._$Cv=e,this._$AP?.(e))}},st=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=it(this,e,t,0),a=!Be(e)||e!==this._$AH&&e!==Qe,a&&(this._$AH=e);else{let r=e,o,s;for(e=i[0],o=0;o<i.length-1;o++)s=it(this,r[n+o],t,o),s===Qe&&(s=this._$AH[o]),a||=!Be(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??``)}},ct=class extends st{constructor(){super(...arguments),this.type=3}j(e){this.element[this.name]=e===v?void 0:e}},lt=class extends st{constructor(){super(...arguments),this.type=4}j(e){this.element.toggleAttribute(this.name,!!e&&e!==v)}},ut=class extends st{constructor(e,t,n,r,i){super(e,t,n,r,i),this.type=5}_$AI(e,t=this){if((e=it(this,e,t,0)??v)===Qe)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)}},dt=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){it(this,e)}},ft={M:Pe,P:Fe,A:Ie,C:1,L:nt,R:at,D:He,V:it,I:ot,H:st,N:lt,U:ut,B:ct,F:dt},pt=Ae.litHtmlPolyfillSupport;pt?.(rt,ot),(Ae.litHtmlVersions??=[]).push(`3.3.3`);var mt=(e,t,n)=>{let r=n?.renderBefore??t,i=r._$litPart$;if(i===void 0){let e=n?.renderBefore??null;r._$litPart$=i=new ot(t.insertBefore(ze(),e),e,void 0,n??{})}return i._$AI(e),i},ht=globalThis,y=class extends ke{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=mt(t,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return Qe}};y._$litElement$=!0,y.finalized=!0,ht.litElementHydrateSupport?.({LitElement:y});var gt=ht.litElementPolyfillSupport;gt?.({LitElement:y}),(ht.litElementVersions??=[]).push(`4.2.2`);var b=e=>(t,n)=>{n===void 0?customElements.define(e,t):n.addInitializer(()=>{customElements.define(e,t)})},_t={attribute:!0,type:String,converter:Ee,reflect:!1,hasChanged:De},vt=(e=_t,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`?vt(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 yt=(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 yt(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 yt(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`},bt=[`economy`,`fast`,`standard`,`advanced`,`capable`,`frontier`],xt=[`lightweight`,`context`],St=1e3,Ct=1e3,wt=32*1024,Tt=8*1024,Et=1e4;function Dt(e,t=kt()){let n=new URL(t.viteBaseUrl,t.documentBaseUrl);return new URL(At(e),n).toString()}function Ot(e,t=kt()){let n=new URL(Dt(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 At(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(Dt(e),{...n,headers:r});if(!i.ok)throw new jt(Mt(await i.json().catch(()=>({})))??i.statusText,i.status);return t(await i.json())}function Mt(e){if(Nt(e))return typeof e.error==`string`?e.error:void 0}function Nt(e){return typeof e==`object`&&!!e}function Pt(e){return(e.split(/[\\/]/u).at(-1)?.toLowerCase()??e.toLowerCase()).replace(/(?:\.[cm]?js|\.exe|\.cmd)$/iu,``)===`pi`}function Ft(e){return!e.includes(`/`)&&!e.includes(`\\`)&&Pt(e)}var It=new Set([`schemaVersion`,`revision`,`command`,`dir`,`sessionDirEnvKeys`]),Lt=/^sha256:[0-9a-f]{64}$/u,Rt=/^[A-Za-z0-9_][A-Za-z0-9._+-]*$/u,zt=new Set([`PI_WEBUI_AGENT_SESSION_DIR`,`PI_CODING_AGENT_SESSION_DIR`]);function Bt(e){if(!Gt(e)||Object.keys(e).some(e=>!It.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`||!Lt.test(n))&&!(typeof r!=`string`||!Vt(r))&&!(typeof i!=`string`||!Ht(i))&&Wt(a)&&new Set(a).size===a.length&&!(a[0]!==`PI_WEBUI_AGENT_SESSION_DIR`||a.some(e=>!zt.has(e))))return Object.freeze({schemaVersion:t,revision:n,command:r,dir:i,sessionDirEnvKeys:Object.freeze([...a])})}function Vt(e){return e!==e.trim()||/[\s;&|`$<>]/u.test(e)?!1:Ht(e)?!e.endsWith(`/`)&&!e.endsWith(`\\`):Rt.test(e)}function Ht(e){if(e===``||e!==e.trim()||Ut(e))return!1;let t=e.replace(/\\/g,`/`);return t.startsWith(`/`)||/^[A-Za-z]:\//u.test(t)}function Ut(e){for(let t of e){let e=t.charCodeAt(0);if(e<32||e===127)return!0}return!1}function Wt(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`&&e!==``)}function Gt(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var Kt=Object.values(w),qt=new Set(Kt);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 Jt(e){return typeof e==`string`&&qt.has(e)}function E(e,t){return e?.capabilities?.includes(t)===!0}function Yt(e){if(!(!Array.isArray(e)||!e.every(e=>typeof e==`string`)))return e.filter(Jt)}var Xt=[`off`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`];function Zt(e){return Xt.some(t=>t===e)}function Qt(e){return e===void 0||e===``?`off`:e}function $t(e,t){let n=t.length>=2?t:Xt,r=n.length-1,i=Qt(e),a=n.indexOf(i);return{total:r,filled:a<=0?0:Math.min(a,r)}}function en(e){return typeof e==`object`&&!!e}function D(e){if(!en(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 tn(e){if(!Array.isArray(e))throw Error(`Expected array response`);return e}function nn(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(!en(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:an(e.globalEntries),projectEntries:an(e.projectEntries),...typeof e.projectUnavailableMessage==`string`?{projectUnavailableMessage:e.projectUnavailableMessage}:{}}}function an(e){if(!Array.isArray(e))throw Error(`Invalid memory snapshot response`);return e.map(e=>{if(!en(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 on(e){if(!en(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:sn(e.globalSkills),projectSkills:sn(e.projectSkills),...t===void 0?{}:{projectUnavailableMessage:t}}}function sn(e){if(!Array.isArray(e))throw Error(`Invalid learned skills snapshot response`);return e.map(cn)}function cn(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 ln(e){if(Array.isArray(e))return{messages:e,start:0,total:e.length};let t=D(e);return{messages:tn(t.messages),start:A(t,`start`),total:A(t,`total`)}}function un(e){let t=D(e);return M(dn)(t.machines)}function dn(e){let t=D(e),n=mn(t,`kind`),r=k(t,`baseUrl`),i=hn(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 fn(e){let t=D(e),n=hn(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:za(t.web)},...t.sessiond===void 0?{}:{sessiond:za(t.sessiond)},...r===void 0?{}:{error:r}}}function pn(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:La(t.components)},...t.capabilities===void 0?{}:{capabilities:Ga(t.capabilities)},...n===void 0?{}:{error:n}}}function mn(e,t){let n=O(e,t);if(n!==`local`&&n!==`remote`)throw Error(`Expected machine kind field: ${t}`);return n}function hn(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 gn(e){let t=D(e),n=Na(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 _n(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 vn(e){let t=or(e,_n,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 yn(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`,bn(t.effectiveConfig))}}function bn(e){if(e!==void 0){if(!en(e)||Array.isArray(e))throw Error(`Invalid workspace effectiveConfig field`);return{...P(`uploads`,ua(e.uploads))}}}function xn(e){let t=D(e),n=k(t,`name`),r=Na(t.persisted,`persisted`),i=k(t,`parentSessionPath`),a=k(t,`archivedAt`),o=Na(t.pinned,`pinned`),s=t.creationSource===`session-list-plus`?t.creationSource:void 0,c=t.manualOrder===void 0?void 0:lr(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 Sn(e){let t=D(e);return{id:O(t,`id`),cwd:O(t,`cwd`),manualOrder:lr(t,`manualOrder`)}}function Cn(e){let t=D(e);return{orderedSessions:M(Sn)(t.orderedSessions)}}function wn(e){if(e!==`info`&&e!==`warning`&&e!==`error`)throw Error(`Invalid session warning severity`);return e}function Tn(e){if(e!==void 0)return{id:O(D(e),`id`)}}function En(e){let t=D(e),n=Tn(t.dismiss);return{severity:wn(t.severity),message:O(t,`message`),...P(`source`,k(t,`source`)),...P(`path`,k(t,`path`)),...n===void 0?{}:{dismiss:n}}}function Dn(e){return e===void 0?{}:{warnings:M(En)(e)}}function On(e){let t=D(e);return{sessionId:O(t,`sessionId`),...P(`persisted`,Na(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(Sr)(t.queuedMessages),...P(`messageCount`,N(t,`messageCount`)),tokens:Cr(t.tokens),cost:A(t,`cost`),...mi(t.generation),...Tr(t.model),...P(`modelPolicy`,t.modelPolicy===void 0?void 0:Pn(t.modelPolicy)),...hi(t.contextUsage),...P(`thinkingLevel`,k(t,`thinkingLevel`)),...Dn(t.warnings)}}function kn(e){let t=zn(e,`session model policy response`);if(Vn(t,[`contractVersion`,`policy`,`session`],`session model policy response`),t.contractVersion!==1)throw Error(`Invalid session model policy contract version`);let n=On(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:An(t.policy),session:n}}function An(e){let t=zn(e,`session model policy`);Vn(t,[`mode`,`exact`,`tier`],`session model policy`);let n=Ln(t.mode),r=Rn(t,`session model policy`);if(n===`tiered`&&r===void 0)throw Error(`Tiered session model policy requires a tier`);return{mode:n,exact:Fn(t.exact),...P(`tier`,r)}}function jn(e){let t=zn(e,`starter model policy preference`);Vn(t,[`mode`,`tier`],`starter model policy preference`);let n=Ln(t.mode),r=Rn(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 Mn(e){let t=zn(e,`starter model policy preference`);return Object.hasOwn(t,`exact`)?Nn(t):jn(t)}function Nn(e){let t=zn(e,`confirmed starter model policy preference`);Vn(t,[`mode`,`exact`,`tier`],`confirmed starter model policy preference`);let n=Ln(t.mode),r=Rn(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:Fn(t.exact),...P(`tier`,r)}}function Pn(e){let t=zn(e,`session model policy status`);Vn(t,[`mode`,`tier`,`resolved`,`ladderValid`,`blockedReason`],`session model policy status`);let n=Ln(t.mode),r=Rn(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:Fn(t.resolved),ladderValid:j(t,`ladderValid`),...P(`blockedReason`,k(t,`blockedReason`))}}function Fn(e){let t=zn(e,`exact selection`);return Vn(t,[`model`,`thinkingLevel`],`exact selection`),{model:In(t.model),thinkingLevel:to(t,`thinkingLevel`)}}function In(e){let t=zn(e,`model reference`);return Vn(t,[`provider`,`id`],`model reference`),{provider:to(t,`provider`),id:to(t,`id`)}}function Ln(e){if(e!==`exact`&&e!==`tiered`)throw Error(`Invalid session model policy mode`);return e}function Rn(e,t){if(!Object.hasOwn(e,`tier`))return;let n=e.tier;if(typeof n!=`string`||!ta(n))throw Error(`Invalid ${t} tier`);return n}function zn(e,t){if(!Bn(e))throw Error(`Expected ${t} object`);return e}function Bn(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Reflect.getPrototypeOf(e);return t===Object.prototype||t===null}function Vn(e,t,n){let r=Object.keys(e).find(e=>!t.includes(e));if(r!==void 0)throw Error(`Invalid ${n} field: ${r}`)}function Hn(e){let t=D(e);return{seq:A(t,`seq`),partial:t.partial??null}}function Un(e){let t=k(D(e),`systemPrompt`);return t===void 0?{}:{systemPrompt:t}}function Wn(e){let t=D(e),n=lr(t,`catalogRevision`),r=or(t.sessions,Kn,Ct,`sessions`);if(qn(r),Jn(r),r.some(e=>e.completionOrder>n))throw Error(`Session unread completion order exceeds catalog revision`);return{catalogId:Yn(t,`catalogId`,512),catalogRevision:n,sessions:r}}function Gn(e){let t=D(e);if(t.type!==`sessions.unread`)throw Error(`Invalid session unread event type`);let n=Yn(t,`sessionId`,512),r=Yn(t,`cwd`,wt),i=Xn(t,`catalogRevision`),a=t.unread===null?null:Kn(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:Yn(t,`catalogId`,512),catalogRevision:i,sessionId:n,cwd:r,unread:a}}function Kn(e){let t=D(e),n=Yn(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:Yn(t,`sessionId`,512),cwd:Yn(t,`cwd`,wt),completionOrder:Xn(t,`completionOrder`),completedAt:n}}function qn(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 Jn(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 Yn(e,t,n){let r=cr(e,t);if(r.length>n)throw Error(`String field exceeds limit: ${t}`);return r}function Xn(e,t){let n=lr(e,t);if(n===0)throw Error(`Expected positive safe integer field: ${t}`);return n}function Zn(e){let t=D(e),n=$n(t.summary),r=or(t.notifications,er,100,`notifications`);if(ur(r),dr(r),n.retainedCount!==r.length)throw Error(`Notification snapshot retained count mismatch`);if(n.highestSeverity!==pr(r))throw Error(`Notification snapshot severity mismatch`);let i=tr(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:cr(t,`daemonInstanceId`),catalogRevision:lr(t,`catalogRevision`),summary:n,notifications:r,dismissThrough:i}}function Qn(e){let t=D(e);if(t.type!==`notifications.inbox`)throw Error(`Invalid notification inbox event type`);let n=$n(t.summary),r=tr(t.dismissThrough);if(r.overflowWatermark<n.discardedCount)throw Error(`Notification event overflow cutoff mismatch`);let i=nr(t.delta);if(i.kind===`cleared`&&!fr(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:cr(t,`daemonInstanceId`),catalogRevision:lr(t,`catalogRevision`),summary:n,dismissThrough:r,delta:i}}function $n(e){let t=D(e),n=lr(t,`retainedCount`);if(n>100)throw Error(`Notification retained count exceeds limit`);let r=lr(t,`discardedCount`),i=ir(t.highestSeverity);if(n===0!=(i===void 0))throw Error(`Notification summary severity mismatch`);return{sessionId:cr(t,`sessionId`),cwd:cr(t,`cwd`),inboxRevision:lr(t,`inboxRevision`),retainedCount:n,discardedCount:r,...i===void 0?{}:{highestSeverity:i}}}function er(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=lr(t,`order`);if(i===0)throw Error(`Invalid notification order`);return{id:cr(t,`id`),message:n,truncated:j(t,`truncated`),severity:rr(t.severity),receivedAt:r,order:i}}function tr(e){let t=D(e);return{order:lr(t,`order`),overflowWatermark:lr(t,`overflowWatermark`)}}function nr(e){let t=D(e);switch(t.kind){case`added`:{let e=k(t,`evictedNotificationId`);return{kind:`added`,notification:er(t.notification),...e===void 0?{}:{evictedNotificationId:e}}}case`dismissed`:{let e=or(t.notificationIds,sr,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:ar(t.reason)};case`resync`:return{kind:`resync`};default:throw Error(`Invalid notification inbox delta`)}}function rr(e){if(e!==`info`&&e!==`warning`&&e!==`error`)throw Error(`Invalid notification severity`);return e}function ir(e){return e===void 0?void 0:rr(e)}function ar(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 or(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 sr(e){if(typeof e!=`string`||e===``)throw Error(`Expected non-empty string`);return e}function cr(e,t){let n=O(e,t);if(n===``)throw Error(`Expected non-empty string field: ${t}`);return n}function lr(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 ur(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 dr(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 fr(e){return e.retainedCount===0&&e.discardedCount===0}function pr(e){let t;for(let n of e){if(n.severity===`error`)return`error`;n.severity===`warning`?t=`warning`:t??=`info`}return t}function mr(e){let t=D(e),n=t.skippedBusySessionIds===void 0?void 0:nn(t.skippedBusySessionIds,`skippedBusySessionIds`);return{generatedAt:O(t,`generatedAt`),thresholds:yr(t.thresholds),projects:M(br)(t.projects),totals:xr(t.totals),...n===void 0?{}:{skippedBusySessionIds:n}}}function hr(e){let t=D(e);return{...mr(t),archivedSessionIds:nn(t.archivedSessionIds,`archivedSessionIds`),deletedSessionIds:nn(t.deletedSessionIds,`deletedSessionIds`)}}function gr(e){let t=D(e);if(t.archived!==!0)throw Error(`Expected bulk archived response`);return{archived:!0,archivedSessionIds:nn(t.archivedSessionIds,`archivedSessionIds`),failures:M(vr)(t.failures),generatedAt:O(t,`generatedAt`)}}function _r(e){let t=D(e);if(t.deleted!==!0)throw Error(`Expected bulk deleted response`);return{deleted:!0,deletedSessionIds:nn(t.deletedSessionIds,`deletedSessionIds`),failures:M(vr)(t.failures),generatedAt:O(t,`generatedAt`)}}function vr(e){let t=D(e);return{sessionId:O(t,`sessionId`),error:O(t,`error`)}}function yr(e){let t=D(e);return{...P(`archiveIdleDays`,N(t,`archiveIdleDays`)),...P(`deleteArchivedDays`,N(t,`deleteArchivedDays`))}}function br(e){let t=D(e);return{cwd:O(t,`cwd`),archiveCount:A(t,`archiveCount`),deleteCount:A(t,`deleteCount`)}}function xr(e){let t=D(e);return{archiveCount:A(t,`archiveCount`),deleteCount:A(t,`deleteCount`)}}function Sr(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 Cr(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 wr(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 Tr(e){return e===void 0?{}:{model:wr(e)}}function Er(e){let t=D(e);return{models:M(wr)(t.models)}}function Dr(e){let t=D(e),n=t.starterModelPolicyPreference===void 0?void 0:jn(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:wr(t.model)},thinkingLevel:O(t,`thinkingLevel`),models:M(wr)(t.models),thinkingLevels:nn(t.thinkingLevels,`thinkingLevels`),...P(`starterModelPolicyPreference`,n),...P(`starterModelPolicyPreferenceError`,r)}}function Or(e){let t=zn(e,`version-two session defaults response`);if(Vn(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:Mn(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:wr(t.model)},thinkingLevel:O(t,`thinkingLevel`),models:M(wr)(t.models),thinkingLevels:nn(t.thinkingLevels,`thinkingLevels`),...P(`starterModelPolicyPreference`,n),...P(`starterModelPolicyPreferenceError`,r)}}function kr(e){let t=Mr(e,`models configuration`),n=t.providers;if(n===void 0)return{...t,providers:{}};let r=Mr(n,`models configuration providers`),i={};for(let[e,t]of Object.entries(r))i[e]=Ar(t);return{...t,providers:i}}function Ar(e){let t=Mr(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=Nr(t.headers,`models configuration provider headers`);o!==void 0&&(n.headers=Pr(o,`models configuration provider headers`));let s=Nr(t.compat,`models configuration provider compatibility`);s!==void 0&&(n.compat={...s});let c=Nr(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(jr)}return n}function jr(e){let t=Mr(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=yo(t,`reasoning`);a!==void 0&&(n.reasoning=a);let o=Nr(t.thinkingLevelMap,`models configuration thinking level map`);o!==void 0&&(n.thinkingLevelMap=Fr(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=Nr(t.cost,`models configuration model cost`);u!==void 0&&(n.cost=Ir(u));let d=Nr(t.compat,`models configuration model compatibility`);return d!==void 0&&(n.compat={...d}),n}function Mr(e,t){if(!en(e)||Array.isArray(e))throw Error(`Expected ${t} object`);return e}function Nr(e,t){if(e!==void 0)return Mr(e,t)}function Pr(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 Fr(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 Ir(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 Lr(e){if(D(e).success!==!0)throw Error(`Expected successful models configuration save`);return{success:!0}}function Rr(e){let t=D(e);return{models:M(zr)(t.models)}}function zr(e){let t=D(e),n=O(t,`id`),r=k(t,`name`);return r===void 0?{id:n}:{id:n,name:r}}function Br(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 Vr(e){let t=D(e);return{skills:M(Hr)(t.skills)}}function Hr(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:Ur(t.install)}}}function Ur(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:Wr(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 Wr(e){if(e!==`global`&&e!==`project`)throw Error(`Expected skill install scope`);return e}function Gr(e){if(D(e).success!==!0)throw Error(`Expected successful Skills mutation`);return{success:!0}}function Kr(e){let t=D(e);return{results:M(qr)(t.results)}}function qr(e){let t=D(e);return{package:O(t,`package`),installs:O(t,`installs`),url:O(t,`url`)}}function Jr(e){let t=D(e);return{updates:M(Yr)(t.updates)}}function Yr(e){let t=D(e),n=k(t,`currentVersion`),r=k(t,`latestVersion`),i=k(t,`message`);return{package:O(t,`package`),scope:Wr(t.scope),state:Xr(t.state),...n===void 0?{}:{currentVersion:n},...r===void 0?{}:{latestVersion:r},...i===void 0?{}:{message:i}}}function Xr(e){if(e!==`up-to-date`&&e!==`update-available`&&e!==`unsupported`&&e!==`error`)throw Error(`Expected skill update state`);return e}function Zr(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:Hr(t.skill)},...n===void 0?{}:{output:n}}}function Qr(e){if(typeof e!=`string`)throw Error(`Invalid thinking level`);return e}function $r(e){let t=D(e);return{levels:M(Qr)(t.levels)}}function ei(e){if(e!==`oauth`&&e!==`api_key`)throw Error(`Invalid auth type`);return e}function ti(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 ni(e){let t=D(e),n=t.source===void 0?void 0:ti(t.source);return{configured:j(t,`configured`),...P(`source`,n),...P(`label`,k(t,`label`))}}function ri(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:ei(t.authType),status:ni(t.status),...n===void 0?{}:{loginFlow:n}}}function ii(e){let t=D(e);return{providers:M(ri)(t.providers)}}function ai(e){let t=D(e);return{flowId:O(t,`flowId`),providerId:O(t,`providerId`),providerName:O(t,`providerName`),status:oi(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`,si(t.auth)),...P(`prompt`,li(t.prompt)),...P(`select`,di(t.select)),...P(`info`,fi(t.info))}}function oi(e){if(e!==`running`&&e!==`complete`&&e!==`error`&&e!==`cancelled`)throw Error(`Invalid OAuth flow status`);return e}function si(e){if(e===void 0)return;let t=D(e);return{url:O(t,`url`),...P(`instructions`,k(t,`instructions`)),...P(`deviceCode`,ci(t.deviceCode))}}function ci(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 li(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`:ui(t.promptType);return{requestId:O(t,`requestId`),message:O(t,`message`),kind:n,promptType:r,...P(`placeholder`,k(t,`placeholder`)),...P(`allowEmpty`,yo(t,`allowEmpty`))}}function ui(e){if(e!==`text`&&e!==`secret`&&e!==`manual_code`)throw Error(`Invalid OAuth prompt type`);return e}function di(e){if(e===void 0)return;let t=D(e);return{requestId:O(t,`requestId`),message:O(t,`message`),options:M(ro)(t.options)}}function fi(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(pi)(t.links))}})(e)}function pi(e){let t=D(e);return{url:O(t,`url`),...P(`label`,k(t,`label`))}}function mi(e){if(e===void 0)return{};let t=D(e);return{generation:{outputTokens:A(t,`outputTokens`),...P(`tokensPerSecond`,N(t,`tokensPerSecond`)),...P(`estimated`,yo(t,`estimated`))}}}function hi(e){if(e===void 0)return{};let t=D(e);return{contextUsage:{tokens:bo(t,`tokens`),contextWindow:A(t,`contextWindow`),percent:bo(t,`percent`)}}}function gi(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 _i(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 vi(e){let t=D(e);return{path:O(t,`path`),entries:M(yi)(t.entries),scannedAt:O(t,`scannedAt`),truncated:j(t,`truncated`)}}function yi(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 bi(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`,wi(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 xi(e){let t=D(e);return{path:O(t,`path`),size:A(t,`size`),modifiedAt:O(t,`modifiedAt`),created:j(t,`created`)}}function Si(e){let t=D(e);return{path:O(t,`path`),existed:j(t,`existed`)}}function Ci(e){let t=D(e);return{fromPath:O(t,`fromPath`),toPath:O(t,`toPath`),size:A(t,`size`),modifiedAt:O(t,`modifiedAt`)}}function wi(e){if(e!==void 0){if(e!==`image`)throw Error(`Invalid file media type`);return e}}function Ti(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(Ei)(t.files)}}function Ei(e){let t=D(e);return{path:O(t,`path`),...P(`oldPath`,k(t,`oldPath`)),index:Di(t.index),workingTree:Di(t.workingTree)}}function Di(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 Oi(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 ki(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 Ai(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:ji(t.status),...P(`exitCode`,N(t,`exitCode`)),createdAt:O(t,`createdAt`),...P(`startedAt`,k(t,`startedAt`)),...P(`completedAt`,k(t,`completedAt`)),metadata:Mi(t.metadata,`metadata`)}}function ji(e){if(e!==`queued`&&e!==`running`&&e!==`succeeded`&&e!==`failed`)throw Error(`Invalid terminal command run status`);return e}function Mi(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 Ni(e){let t=D(e);return{cwd:O(t,`cwd`),hasSessionActivity:j(t,`hasSessionActivity`),hasTerminalActivity:j(t,`hasTerminalActivity`),updatedAt:O(t,`updatedAt`)}}function Pi(e){let t=D(e);return{workspaces:M(Ni)(t.workspaces),generatedAt:O(t,`generatedAt`)}}function Fi(e){let t=ra(e,`utility model settings response`),n=Object.keys(t).find(e=>!Ri(e));if(n!==void 0)throw Error(`Invalid utility model settings response field: ${n}`);if(t.contractVersion===1)return Ii(t);if(t.contractVersion===2)return Li(t);throw Error(`Invalid utility model settings contract version`)}function Ii(e){let t=k(e,`configError`);return{contractVersion:1,settings:zi(e.settings),models:M(Hi)(e.models),slots:Wi(e.slots),valid:j(e,`valid`),...P(`configError`,t)}}function Li(e){let t=k(e,`configError`);return{contractVersion:2,settings:Bi(e.settings),models:M(Ui)(e.models),slots:Wi(e.slots),valid:j(e,`valid`),...P(`configError`,t)}}function Ri(e){return e===`contractVersion`||e===`settings`||e===`models`||e===`slots`||e===`valid`||e===`configError`}function zi(e){let t=ra(e,`settings`),n=Object.keys(t).find(e=>!Ki(e));if(n!==void 0)throw Error(`Invalid utility model settings field: settings.${n}`);return{...P(`lightweight`,t.lightweight===void 0?void 0:Zi(t.lightweight,`settings.lightweight`)),...P(`context`,t.context===void 0?void 0:Zi(t.context,`settings.context`))}}function Bi(e){let t=ra(e,`settings`),n=Object.keys(t).find(e=>!Ki(e));if(n!==void 0)throw Error(`Invalid utility model settings field: settings.${n}`);return{...P(`lightweight`,t.lightweight===void 0?void 0:Vi(t.lightweight,`settings.lightweight`)),...P(`context`,t.context===void 0?void 0:Vi(t.context,`settings.context`))}}function Vi(e,t){let n=ra(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=cr(n,`provider`),a=cr(n,`id`),o=k(n,`thinkingLevel`);if(o===void 0)return{provider:i,id:a};if(!Zt(o))throw Error(`Invalid utility model thinking level: ${t}.thinkingLevel`);return{provider:i,id:a,thinkingLevel:o}}function Hi(e){let t=ra(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:Zi(t.model,`models.model`),...P(`name`,k(t,`name`))}}function Ui(e){let t=ra(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=nn(t.thinkingLevels,`models.thinkingLevels`).map(e=>{if(!Zt(e))throw Error(`Invalid utility model thinking levels: models.thinkingLevels`);return e});return{model:Zi(t.model,`models.model`),...P(`name`,k(t,`name`)),thinkingLevels:r}}function Wi(e){let t=qi(e,`slots`);return{lightweight:Gi(t.lightweight,`slots.lightweight`),context:Gi(t.context,`slots.context`)}}function Gi(e,t){let n=ra(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 Ki(e){return xt.some(t=>t===e)}function qi(e,t){let n=ra(e,t),r=Object.keys(n).find(e=>!Ki(e));if(r!==void 0)throw Error(`Invalid utility model ${t} field: unknown slot ${r}`);let i=xt.find(e=>n[e]===void 0);if(i!==void 0)throw Error(`Invalid utility model ${t} field: missing slot ${i}`);return n}function Ji(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:Yi(t.ladder),r=k(t,`configError`);return{contractVersion:1,...P(`ladder`,n),models:M(Qi)(t.models),rows:$i(t.rows),valid:j(t,`valid`),...P(`configError`,r)}}function Yi(e){let t=na(e,`ladder`);return{economy:Xi(t.economy,`ladder.economy`),fast:Xi(t.fast,`ladder.fast`),standard:Xi(t.standard,`ladder.standard`),advanced:Xi(t.advanced,`ladder.advanced`),capable:Xi(t.capable,`ladder.capable`),frontier:Xi(t.frontier,`ladder.frontier`)}}function Xi(e,t){let n=ra(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:Zi(n.model,`${t}.model`),thinkingLevel:cr(n,`thinkingLevel`)}}function Zi(e,t){let n=ra(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:cr(n,`provider`),id:cr(n,`id`)}}function Qi(e){let t=ra(e,`models`);return{model:Zi(t.model,`models.model`),...P(`name`,k(t,`name`)),thinkingLevels:nn(t.thinkingLevels,`models.thinkingLevels`)}}function $i(e){let t=na(e,`rows`);return{economy:ea(t.economy,`rows.economy`),fast:ea(t.fast,`rows.fast`),standard:ea(t.standard,`rows.standard`),advanced:ea(t.advanced,`rows.advanced`),capable:ea(t.capable,`rows.capable`),frontier:ea(t.frontier,`rows.frontier`)}}function ea(e,t){let n=ra(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 ta(e){return bt.some(t=>t===e)}function na(e,t){let n=ra(e,t),r=Object.keys(n).find(e=>!ta(e));if(r!==void 0)throw Error(`Invalid model-tier ${t} field: unknown tier ${r}`);let i=bt.find(e=>n[e]===void 0);if(i!==void 0)throw Error(`Invalid model-tier ${t} field: missing tier ${i}`);return n}function ra(e,t){if(!en(e)||Array.isArray(e))throw Error(`Expected object field: ${t}`);return e}function ia(e){let t=D(e);return{path:O(t,`path`),exists:j(t,`exists`),config:aa(t.config),effectiveConfig:aa(t.effectiveConfig),envOverrides:ha(t.envOverrides)}}function aa(e){let t=D(e);return{...P(`host`,k(t,`host`)),...P(`port`,N(t,`port`)),...P(`allowedHosts`,sa(t.allowedHosts)),...P(`shortcuts`,pa(t.shortcuts)),...P(`plugins`,ma(t.plugins)),...P(`pathAccess`,ca(t.pathAccess)),...P(`uploads`,ua(t.uploads)),...P(`maxUploadBytes`,N(t,`maxUploadBytes`)),...P(`agent`,oa(t.agent)),...P(`spawnSessions`,yo(t,`spawnSessions`)),...P(`subsessions`,yo(t,`subsessions`))}}function oa(e){if(e!==void 0){if(!en(e)||Array.isArray(e))throw Error(`Invalid PI WEBUI agent field`);return{...P(`command`,k(e,`command`)),...P(`dir`,k(e,`dir`))}}}function sa(e){if(e!==void 0){if(e===!0)return!0;if(da(e))return e;throw Error(`Invalid PI WEBUI allowedHosts field`)}}function ca(e){if(e===void 0)return;if(!en(e))throw Error(`Invalid PI WEBUI pathAccess field`);let t=e.allowedPaths;return{...P(`allowedPaths`,la(t,`pathAccess.allowedPaths`))}}function la(e,t){if(e!==void 0){if(fa(e))return e;throw Error(`Invalid PI WEBUI ${t} field`)}}function ua(e){if(e!==void 0){if(!en(e)||Array.isArray(e))throw Error(`Invalid PI WEBUI uploads field`);return{...P(`defaultFolder`,k(e,`defaultFolder`))}}}function da(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`)}function fa(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`&&e!==``)}function pa(e){if(e!==void 0){if(!en(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 ma(e){if(e!==void 0){if(!en(e)||Array.isArray(e))throw Error(`Invalid PI WEBUI plugins field`);return Object.fromEntries(Object.entries(e).map(([e,t])=>{if(!en(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&&(!en(r)||Array.isArray(r)))throw Error(`Invalid PI WEBUI plugin settings field`);return[e,t]}))}}function ha(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:yo(t,`agentCommand`)??!1,agentDir:yo(t,`agentDir`)??!1,...ga(t),agentSessionDir:yo(t,`agentSessionDir`)??!1}}function ga(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 _a(e){let t=D(e);return{packages:M(ya)(t.packages)}}function va(e){let t=D(e),n=k(t,`source`),r=t.scope===void 0?void 0:ba(t.scope),i=Na(t.removed,`removed`);return{action:xa(t.action),...P(`source`,n),...P(`scope`,r),...P(`removed`,i),packages:M(ya)(t.packages)}}function ya(e){let t=D(e);return{source:O(t,`source`),scope:ba(t.scope),filtered:j(t,`filtered`),...P(`installedPath`,k(t,`installedPath`))}}function ba(e){if(e!==`user`&&e!==`project`)throw Error(`Invalid Pi package scope`);return e}function xa(e){if(e!==`install`&&e!==`remove`&&e!==`update`)throw Error(`Invalid Pi package mutation action`);return e}function Sa(e){let t=D(e);return{packages:M(Ca)(t.packages),totals:Ea(t.totals),diagnostics:M(ka)(t.diagnostics)}}function Ca(e){let t=D(e);return{source:O(t,`source`),scope:wa(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:Ea(t.counts),resources:M(Da)(t.resources),status:Ta(t.status)}}function wa(e){if(e!==`global`&&e!==`project`)throw Error(`Invalid Pi package plugin scope`);return e}function Ta(e){if(e!==`loaded`&&e!==`installed`&&e!==`missing`&&e!==`disabled`)throw Error(`Invalid Pi package plugin status`);return e}function Ea(e){let t=D(e);return{extensions:A(t,`extensions`),skills:A(t,`skills`),prompts:A(t,`prompts`),themes:A(t,`themes`)}}function Da(e){let t=D(e);return{kind:Oa(t.kind),name:O(t,`name`),path:O(t,`path`),relativePath:O(t,`relativePath`)}}function Oa(e){if(e!==`extension`&&e!==`skill`&&e!==`prompt`&&e!==`theme`)throw Error(`Invalid Pi package plugin resource kind`);return e}function ka(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 Aa(e){let t=D(e);return{plugins:M(ja)(t.plugins)}}function ja(e){let t=D(e);return{id:O(t,`id`),module:O(t,`module`),source:O(t,`source`),scope:Ma(t.scope),machineSpecific:Na(t.machineSpecific,`machineSpecific`)??!1,enabled:j(t,`enabled`)}}function Ma(e){if(e!==`bundled`&&e!==`local`&&e!==`user`&&e!==`project`)throw Error(`Invalid PI WEBUI plugin scope`);return e}function Na(e,t){if(e!==void 0){if(typeof e!=`boolean`)throw Error(`Expected optional boolean field: ${t}`);return e}}function Pa(e){let t=D(e);return{packageName:O(t,`packageName`),generatedAt:O(t,`generatedAt`),components:Ia(t.components),release:Va(t.release),commands:Ha(t.commands),messages:M(Ua)(t.messages)}}function Fa(e){let t=D(e);return{packageName:O(t,`packageName`),generatedAt:O(t,`generatedAt`),components:La(t.components),capabilities:Ga(t.capabilities)}}function Ia(e){let t=D(e);return{web:za(t.web),sessiond:za(t.sessiond)}}function La(e){let t=D(e);return{web:Ra(t.web),sessiond:Ra(t.sessiond)}}function Ra(e){let t=D(e),n=Wa(t.component),r=t.activeAgentProfile,i=r===void 0?void 0:Bt(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:Ga(t.capabilities),...P(`activeAgentProfile`,i),...P(`error`,k(t,`error`))}}function za(e){let t=D(e);return{component:Wa(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`,Ba(t.installation)),...P(`error`,k(t,`error`))}}function Ba(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 Va(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 Ha(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 Ua(e){let t=D(e);return{id:O(t,`id`),severity:Ka(t.severity),title:O(t,`title`),body:O(t,`body`),...P(`command`,k(t,`command`))}}function Wa(e){if(e!==`web`&&e!==`sessiond`)throw Error(`Invalid PI WEBUI service component`);return e}function Ga(e){let t=Yt(e);if(t===void 0)throw Error(`Invalid PI WEBUI capabilities`);return t}function Ka(e){if(e!==`info`&&e!==`warning`&&e!==`error`)throw Error(`Invalid PI WEBUI status severity`);return e}function qa(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(ro)(t.options)};if(n===`tree`)return{type:n,tree:Ja(t.tree)};if(n===`done`)return{type:n,...P(`message`,k(t,`message`)),...io(t.session),...P(`promptDraft`,k(t,`promptDraft`))};throw Error(`Invalid command result type`)}function Ja(e){let t=D(e),n=M(Ya)(t.nodes),r=new Set(n.map(e=>e.id));if(r.size!==n.length)throw Error(`Duplicate session tree node id`);let i=eo(t,`activeLeafId`);if(i!==null&&!r.has(i))throw Error(`Invalid session tree activeLeafId`);return{nodes:n,activeLeafId:i,activePathIds:no(t.activePathIds,`activePathIds`)}}function Ya(e){let t=D(e);return{id:to(t,`id`),parentId:eo(t,`parentId`),kind:Xa(t.kind),summary:O(t,`summary`),...P(`timestamp`,k(t,`timestamp`)),...P(`label`,k(t,`label`))}}function Xa(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 Za(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){$a(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 $a(t,`aborted`,`session tree navigation result`),{cancelled:n,...P(`editorText`,k(t,`editorText`))}}function Qa(e){let t=D(e);return j(t,`cancelled`)?($a(t,`session`,`session fork cancellation result`),{cancelled:!0}):{cancelled:!1,session:xn(t.session)}}function $a(e,t,n){if(Object.hasOwn(e,t))throw Error(`Invalid ${n} field: ${t}`)}function eo(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 to(e,t){let n=O(e,t);if(n.trim()===``)throw Error(`Expected non-blank string field: ${t}`);return n}function no(e,t){let n=nn(e,t);if(n.some(e=>e.trim()===``))throw Error(`Expected non-blank string array field: ${t}`);return n}function ro(e){let t=D(e);return{value:O(t,`value`),label:O(t,`label`),...P(`description`,k(t,`description`))}}function io(e){return e===void 0?{}:{session:xn(e)}}function ao(e){if(D(e).accepted!==!0)throw Error(`Expected accepted response`);return{accepted:!0}}function oo(e){let t=D(e);return M(so)(t.attachments)}function so(e){let t=D(e);return{path:O(t,`path`),mimeType:O(t,`mimeType`),size:A(t,`size`)}}function co(e){if(D(e).closed!==!0)throw Error(`Expected closed response`);return{closed:!0}}function lo(e){if(typeof e!=`string`)throw Error(`Expected string value`);return e}function uo(e){let t=D(e);return{closedProjectIds:M(lo)(t.closedProjectIds)}}function fo(e){if(D(e).aborted!==!0)throw Error(`Expected aborted response`);return{aborted:!0}}function po(e){if(D(e).stopped!==!0)throw Error(`Expected stopped response`);return{stopped:!0}}function mo(e){let t=D(e);if(t.archived!==!0)throw Error(`Expected archived response`);let n=t.sessionIds===void 0?void 0:nn(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 ho(e){if(D(e).restored!==!0)throw Error(`Expected restored response`);return{restored:!0}}function go(e){if(D(e).deleted!==!0)throw Error(`Expected deleted response`);return{deleted:!0}}function _o(e){if(D(e).detached!==!0)throw Error(`Expected detached response`);return{detached:!0}}function vo(e){if(D(e).reloaded!==!0)throw Error(`Expected reloaded response`);return{reloaded:!0}}function yo(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 bo(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 xo(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:wo(r)}}function So(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:Co(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 Co(e){let t={hostname:O(e,`hostname`),localIpv4Addresses:nn(e.localIpv4Addresses,`localIpv4Addresses`),...wo(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 wo(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 To(e){let t=zn(e,`project usage count response`);return Vn(t,[`sessionCount`],`project usage count response`),{sessionCount:lr(t,`sessionCount`)}}function Eo(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 Do(e){let t=D(e),n=D(t.buckets);return{projectPath:O(t,`projectPath`),buckets:{live:Eo(n.live),retired:Eo(n.retired),archived:Eo(n.archived)},total:Eo(t.total),generatedAt:O(t,`generatedAt`)}}function Oo(e){return typeof e==`string`?e:e.id}function ko(e){return typeof e==`string`?void 0:e.cwd}function Ao(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 jo(e,t,n=`local`){let r=new URLSearchParams,i=ko(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(Oo(e))}/messages${a===``?``:`?${a}`}`}function Mo(e,t=`local`){let n=new URLSearchParams,r=ko(e);r!==void 0&&r!==``&&n.set(`cwd`,r);let i=n.toString();return`api/machines/${encodeURIComponent(t)}/sessions/${encodeURIComponent(Oo(e))}/export${i===``?``:`?${i}`}`}function No(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`),Dt(`${`api/machines/${encodeURIComponent(r?.machineId??`local`)}`}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?${i.toString()}`)}function Po(e,t,n,r){let i=new URLSearchParams;return i.set(`path`,n),r?.modifiedAt!==void 0&&i.set(`v`,r.modifiedAt),Dt(`${`api/machines/${encodeURIComponent(r?.machineId??`local`)}`}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file/preview?${i.toString()}`)}var F=(e=`local`)=>`api/machines/${encodeURIComponent(e)}`,Fo=e=>e===void 0?void 0:{signal:e};function Io(e){return typeof e==`string`?e:e.id}function Lo(e){return typeof e==`string`?void 0:e.cwd}function Ro(e,t=`local`){return`${F(t)}/sessions/${encodeURIComponent(Io(e))}`}function I(e,t,n=`local`){return`${Ro(e,n)}/${t}`}function zo(e,t,n=`local`){return`${I(e,t,n)}${Vo(e)}`}function Bo(e,t=`local`){return`${Ro(e,t)}${Vo(e)}`}function Vo(e){let t=Lo(e);return t===void 0||t===``?``:`?${new URLSearchParams({cwd:t}).toString()}`}function L(e,t={}){let n=Lo(e);return JSON.stringify(n===void 0||n===``?t:{cwd:n,...t})}function Ho(e){return JSON.stringify({sessions:e.map(Uo)})}function Uo(e){let t=Io(e),n=Lo(e);return n===void 0||n===``?{id:t}:{id:t,cwd:n}}function Wo(e){return e===`local`?`api/pi-webui/status`:`${F(e)}/pi-webui/status`}var Go={piWebUiStatus:(e=`local`)=>T(Wo(e),Pa),checkForUpdates:(e=`local`)=>T(`${Wo(e)}?refresh=1`,Pa,{cache:`no-store`}),piWebUiRuntime:()=>T(`api/pi-webui/runtime`,Fa),systemInfo:(e=`local`)=>T(`${F(e)}/pi-webui/system-info`,So),systemMetrics:(e=`local`)=>T(`${F(e)}/pi-webui/system-metrics`,xo,{cache:`no-store`})},Ko={machines:()=>T(`api/machines`,un),addMachine:e=>T(`api/machines`,dn,{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`,fn),runtime:(e,t=!1)=>T(`api/machines/${encodeURIComponent(e)}/runtime${t?`?refresh=1`:``}`,pn,t?{cache:`no-store`}:{})};function qo(e,t=`local`){let n=new URLSearchParams({projectPath:e});return`${F(t)}/agent-memory/snapshot?${n.toString()}`}var Jo={snapshot:(e,t=`local`)=>T(qo(e,t),rn,{cache:`no-store`})};function Yo(e,t=`local`){let n=new URLSearchParams({projectPath:e});return`${F(t)}/agent-skills/snapshot?${n.toString()}`}var Xo={snapshot:(e,t=`local`)=>T(Yo(e,t),on,{cache:`no-store`})};function Zo(e){return e===void 0?`api/config`:`${F(e)}/config`}function Qo(e){return e===void 0?`api/plugins`:`${F(e)}/plugins`}var $o={config:e=>T(Zo(e),ia),saveConfig:(e,t)=>T(Zo(t),ia,{method:`PUT`,body:JSON.stringify({config:e})})},es={plugins:e=>T(Qo(e),Aa)};function ts(e=`local`){return`${F(e)}/models-config`}var ns={config:(e=`local`)=>T(ts(e),kr),save:(e,t=`local`)=>T(ts(t),Lr,{method:`PUT`,body:JSON.stringify(e)}),test:(e,t=`local`)=>T(`${ts(t)}/test`,Br,{method:`POST`,body:JSON.stringify(e)}),discover:(e,t=`local`)=>T(`${ts(t)}/discover`,Rr,{method:`POST`,body:JSON.stringify(e)})};function rs(e=`local`){return`${F(e)}/model-tiers`}var is={settings:(e=`local`)=>T(rs(e),Ji),save:(e,t=`local`)=>T(rs(t),Ji,{method:`PUT`,body:JSON.stringify({ladder:e})})};function as(e=`local`){return`${F(e)}/utility-models`}function os(e,t){if(t===2)return e;let n={};for(let t of xt){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 ss={settings:(e=`local`)=>T(as(e),Fi),save:(e,t,n=`local`)=>T(as(n),Fi,{method:`PUT`,body:JSON.stringify({settings:os(e,t)})})};function cs(e=`local`){return`${F(e)}/skills`}function ls(e,t=`local`){return`${cs(t)}?${new URLSearchParams({cwd:e}).toString()}`}var us={list:(e,t=`local`)=>T(ls(e,t),Vr),toggle:(e,t=`local`)=>T(cs(t),Gr,{method:`PATCH`,body:JSON.stringify(e)}),search:(e,t=`local`)=>T(`${cs(t)}/search`,Kr,{method:`POST`,body:JSON.stringify(e)}),install:(e,t=`local`)=>T(`${cs(t)}/install`,Gr,{method:`POST`,body:JSON.stringify(e)}),check:(e,t=`local`)=>T(`${cs(t)}/check`,Jr,{method:`POST`,body:JSON.stringify(e)}),update:(e,t=`local`)=>T(`${cs(t)}/update`,Zr,{method:`POST`,body:JSON.stringify(e)})};function ds(e=``,t){let n=t===void 0?`api/pi-packages`:`${F(t)}/pi-packages`;return e===``?n:`${n}/${e}`}var fs={packages:e=>T(ds(``,e),_a),install:(e,t)=>{let n={source:e};return T(ds(`install`,t),va,{method:`POST`,body:JSON.stringify(n)})},remove:(e,t,n)=>{let r=t===void 0?{source:e}:{source:e,scope:t};return T(ds(`remove`,n),va,{method:`POST`,body:JSON.stringify(r)})},update:(e,t)=>{let n=e===void 0?void 0:{source:e};return T(ds(`update`,t),va,{method:`POST`,...n===void 0?{}:{body:JSON.stringify(n)}})}};function ps(e=`local`){return`${F(e)}/package-plugins`}function ms(e,t=`local`){return`${ps(t)}?${new URLSearchParams({cwd:e}).toString()}`}var hs={list:(e,t=`local`)=>T(ms(e,t),Sa),mutate:(e,t=`local`)=>T(ps(t),Sa,{method:`POST`,body:JSON.stringify(e)})},gs={workspaceActivity:(e=`local`)=>T(`${F(e)}/activity`,Pi)},_s={projects:(e=`local`)=>T(`${F(e)}/projects`,M(gn)),addProject:(e,t,n,r=`local`)=>T(`${F(r)}/projects`,gn,{method:`POST`,body:JSON.stringify({path:e,name:t,create:n})}),closeProject:(e,t=`local`)=>T(`${F(t)}/projects/${encodeURIComponent(e)}`,co,{method:`DELETE`}),closeProjectTree:(e,t=`local`)=>T(`${F(t)}/projects/${encodeURIComponent(e)}/close-tree`,uo,{method:`POST`}),pinProject:(e,t=`local`)=>T(`${F(t)}/projects/${encodeURIComponent(e)}/pin`,M(gn),{method:`POST`}),unpinProject:(e,t=`local`)=>T(`${F(t)}/projects/${encodeURIComponent(e)}/unpin`,M(gn),{method:`POST`}),projectDirectories:(e,t=`local`)=>T(`${F(t)}/project-directories?q=${encodeURIComponent(e)}`,M(_i)),projectUsageCount:(e,t=`local`)=>T(`${F(t)}/sessions/project-usage/count`,To,{method:`POST`,body:JSON.stringify(e)}),projectUsage:(e,t=`local`)=>T(`${F(t)}/sessions/project-usage`,Do,{method:`POST`,body:JSON.stringify(e)})},vs={recentProjects:(e=`local`)=>T(`${F(e)}/recent-projects`,vn),recordRecentProject:(e,t=`local`)=>T(`${F(t)}/projects/${encodeURIComponent(e)}/recent`,vn,{method:`POST`}),removeRecentProject:(e,t=`local`)=>T(`${F(t)}/recent-projects/${encodeURIComponent(e)}`,vn,{method:`DELETE`})},ys={workspaces:(e,t=`local`,n)=>T(`${F(t)}/projects/${encodeURIComponent(e)}/workspaces`,M(yn),Fo(n)),deleteWorkspace:(e,t,n=`local`)=>T(`${F(n)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}`,Ai,{method:`DELETE`}),workspaceTree:(e,t,n=``,r=`local`)=>T(`${F(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/tree?path=${encodeURIComponent(n)}`,vi),workspaceFile:(e,t,n,r=`local`)=>T(`${F(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?path=${encodeURIComponent(n)}`,bi),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()}`,xi,{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()}`,Si,{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()}`,Ci,{method:`POST`})}},bs={sessions:(e,t=`local`,n)=>T(`${F(t)}/sessions?cwd=${encodeURIComponent(e)}`,M(xn),Fo(n)),reorder:(e,t,n=`local`)=>T(I(e,`reorder`,n),Cn,{method:`POST`,body:JSON.stringify(t)}),unreadCatalog:(e=`local`)=>T(`${F(e)}/sessions/unread`,Wn,{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),Wn,{method:`POST`,body:JSON.stringify(i)})},notificationInbox:(e,t=`local`)=>T(zo(e,`notifications`,t),Zn),dismissNotification:(e,t,n,r=`local`)=>T(I(e,`notifications/dismiss`,r),Zn,{method:`POST`,body:L(e,{daemonInstanceId:t,notificationId:n})}),dismissAllNotifications:(e,t,n,r=`local`)=>T(I(e,`notifications/dismiss-all`,r),Zn,{method:`POST`,body:L(e,{daemonInstanceId:t,throughOrder:n.order,throughOverflowWatermark:n.overflowWatermark})}),startSession:(e,t=`local`,n)=>T(`${F(t)}/sessions`,xn,{method:`POST`,body:JSON.stringify({cwd:e,...n===void 0?{}:{modelPolicy:n}})}),startPlusSession:(e,t,n=`local`)=>T(`${F(n)}/sessions`,xn,{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)}`,Dr),sessionDefaultsV2:(e,t=`local`)=>{let n=new URLSearchParams({cwd:e,starterModelPolicyContract:`2`});return T(`${F(t)}/session-defaults?${n.toString()}`,Or)},updateSessionDefaults:(e,t,n=`local`)=>T(`${F(n)}/session-defaults`,Dr,{method:`PUT`,body:JSON.stringify({cwd:e,...t})}),cleanupPreview:(e,t=`local`)=>T(`${F(t)}/sessions/cleanup/preview`,mr,{method:`POST`,body:JSON.stringify(e)}),cleanup:(e,t=`local`)=>T(`${F(t)}/sessions/cleanup`,hr,{method:`POST`,body:JSON.stringify(e)}),forceCleanup:(e=`local`)=>T(`${F(e)}/sessions/cleanup/force`,hr,{method:`POST`}),archiveMany:(e,t=`local`)=>T(`${F(t)}/sessions/bulk/archive`,gr,{method:`POST`,body:Ho(e)}),deleteArchivedMany:(e,t=`local`)=>T(`${F(t)}/sessions/bulk/delete-archived`,_r,{method:`POST`,body:Ho(e)}),messages:(e,t,n=`local`,r)=>T(jo(e,t,n),ln,Fo(r)),status:(e,t=`local`,n)=>T(zo(e,`status`,t),On,Fo(n)),systemPrompt:(e,t=`local`)=>T(zo(e,`system-prompt`,t),Un),streamSnapshot:(e,t=`local`,n)=>T(zo(e,`stream-snapshot`,t),Hn,Fo(n)),clearQueue:(e,t=`local`)=>T(I(e,`queue/clear`,t),On,{method:`POST`,body:L(e)}),dismissWarning:(e,t,n=`local`)=>T(I(e,`warnings/dismiss`,n),On,{method:`POST`,body:L(e,{dismissId:t})}),modelPolicy:(e,t=`local`)=>T(zo(e,`model-policy`,t),kn),rememberCurrentModelPolicy:(e,t=`local`)=>T(zo(e,`model-policy/remember`,t),Nn,{method:`POST`}),setModelPolicy:(e,t,n=`local`)=>T(I(e,`model-policy`,n),kn,{method:`PUT`,body:L(e,{policy:t})}),models:(e,t=`local`)=>T(zo(e,`models`,t),Er),setModel:(e,t,n,r=`local`)=>T(I(e,`model`,r),On,{method:`POST`,body:L(e,{provider:t,modelId:n})}),cycleModel:(e,t,n=`local`)=>T(I(e,`model/cycle`,n),On,{method:`POST`,body:L(e,{direction:t})}),thinkingLevels:(e,t=`local`)=>T(zo(e,`thinking-levels`,t),$r),setThinkingLevel:(e,t,n=`local`)=>T(I(e,`thinking-level`,n),On,{method:`POST`,body:L(e,{level:t})}),cycleThinkingLevel:(e,t=`local`)=>T(I(e,`thinking-level/cycle`,t),On,{method:`POST`,body:L(e)}),commands:(e,t=`local`)=>T(zo(e,`commands`,t),M(gi)),prompt:(e,t,n,r=`local`,i)=>T(I(e,`prompt`,r),ao,{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),oo,{method:`POST`,body:L(e,{attachments:t,...r===void 0?{}:{folder:r}})}),shell:(e,t,n=`local`)=>T(I(e,`shell`,n),ao,{method:`POST`,body:L(e,{text:t})}),runCommand:(e,t,n=`local`)=>T(I(e,`commands/run`,n),qa,{method:`POST`,body:L(e,{text:t})}),respondToCommand:(e,t,n,r=`local`)=>T(I(e,`commands/respond`,r),qa,{method:`POST`,body:L(e,{requestId:t,value:n})}),navigateTree:(e,t,n=`local`)=>T(I(e,`tree/navigate`,n),Za,{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),Za,{method:`POST`,body:L(e,{entryId:t})}),forkFromHere:(e,t,n=`local`)=>T(I(e,`messages/fork`,n),Qa,{method:`POST`,body:L(e,{entryId:t})}),abort:(e,t=`local`)=>T(I(e,`abort`,t),fo,{method:`POST`,body:L(e)}),stop:(e,t=`local`)=>T(I(e,`stop`,t),po,{method:`POST`,body:L(e)}),archive:(e,t=`local`)=>T(I(e,`archive`,t),mo,{method:`POST`,body:L(e)}),archiveWithDescendants:(e,t=`local`)=>T(I(e,`archive-tree`,t),mo,{method:`POST`,body:L(e)}),restore:(e,t=`local`)=>T(I(e,`restore`,t),ho,{method:`POST`,body:L(e)}),deleteArchived:(e,t=`local`)=>T(Bo(e,t),go,{method:`DELETE`}),detachParent:(e,t=`local`)=>T(I(e,`detach-parent`,t),_o,{method:`POST`,body:L(e)}),reloadSession:(e,t=`local`)=>T(I(e,`reload`,t),vo,{method:`POST`,body:L(e)}),pin:(e,t=`local`)=>T(I(e,`pin`,t),xn,{method:`POST`,body:L(e)}),unpin:(e,t=`local`)=>T(I(e,`unpin`,t),xn,{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}`}`,ii)},saveApiKey:(e,t,n=`local`)=>T(`${F(n)}/auth/api-key`,ao,{method:`POST`,body:JSON.stringify({providerId:e,key:t})}),startInteractiveApiKeyLogin:(e,t=`local`)=>T(`${F(t)}/auth/api-key/interactive`,ai,{method:`POST`,body:JSON.stringify({providerId:e})}),logoutProvider:(e,t=`local`)=>T(`${F(t)}/auth/logout`,ao,{method:`POST`,body:JSON.stringify({providerId:e})}),startOAuthLogin:(e,t=`local`)=>T(`${F(t)}/auth/oauth`,ai,{method:`POST`,body:JSON.stringify({providerId:e})}),oauthFlow:(e,t=`local`)=>T(`${F(t)}/auth/oauth/${encodeURIComponent(e)}`,ai),respondOAuthFlow:(e,t,n,r=`local`)=>T(`${F(r)}/auth/oauth/${encodeURIComponent(e)}/respond`,ai,{method:`POST`,body:JSON.stringify({requestId:t,value:n})}),cancelOAuthFlow:(e,t=`local`)=>T(`${F(t)}/auth/oauth/${encodeURIComponent(e)}/cancel`,ai,{method:`POST`})},xs={terminals:(e,t,n=`local`)=>T(`${F(n)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,M(ki)),startTerminal:(e,t,n,r=`local`)=>T(`${F(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,ki,{method:`POST`,body:JSON.stringify(n??{})}),closeWorkspaceTerminals:(e,t,n=`local`)=>T(`${F(n)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,co,{method:`DELETE`}),closeTerminal:(e,t,n,r=`local`)=>T(`${F(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(n)}`,co,{method:`DELETE`}),continueTerminal:(e,t,n,r=`local`)=>T(`${F(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(n)}/continue`,ki,{method:`POST`}),runTerminalCommand:(e,t,n=`local`)=>T(`${F(n)}/projects/${encodeURIComponent(t.workspace.projectId)}/workspaces/${encodeURIComponent(t.workspace.id)}/terminal-command-runs`,Ai,{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${Cs(e)}`,M(Ai)),getCommandRun:(e,t=`local`)=>Ss(e,t),cancelCommandRun:(e,t=`local`)=>T(`${F(t)}/terminal-command-runs/${encodeURIComponent(e)}/cancel`,Ai,{method:`POST`})};async function Ss(e,t){let n=await fetch(Dt(`${F(t)}/terminal-command-runs/${encodeURIComponent(e)}`));if(n.status!==404){if(!n.ok){let e=await n.json().catch(()=>({}));throw Error(ws(e)??n.statusText)}return Ai(await n.json())}}function Cs(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 ws(e){if(!Ts(e))return;let t=e.error;return typeof t==`string`?t:void 0}function Ts(e){return typeof e==`object`&&!!e}var Es={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(_i)):(r.set(`cwd`,e),T(`${F(n.machineId)}/files?${r.toString()}`,M(_i)))}},Ds={gitStatus:(e,t,n=`local`)=>T(`${F(n)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/git/status`,Ti),gitDiff:(e,t,n,r=`local`)=>T(Ao(r,e,t,n),Oi)},Os={...Go,...Ko,...Jo,learnedSkills:Xo,...is,utilityModels:ss,...$o,...es,...fs,...hs,...gs,..._s,...vs,...ys,...bs,...xs,...Es,...Ds};function ks(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(Ot(`${Ms(t)}/sessions/${encodeURIComponent(i)}/events${r}`))}function As(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(Ot(`${Ms(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(n)}/socket${a}`))}function js(e=`local`){return new WebSocket(Ot(`${Ms(e)}/events`))}function Ms(e){return`api/machines/${encodeURIComponent(e)}`}var Ns=`.pi-webui/uploads`,Ps=class extends Error{constructor(e=`Workspace upload cancelled`){super(e),this.name=`WorkspaceUploadCancelledError`}},Fs=class extends Error{constructor(e,t){super(Ks(e)),this.name=`WorkspaceUploadBatchError`,this.failures=e.map(e=>({...e})),this.responses=t.map(e=>({...e}))}};function Is(e){return e?.uploads?.defaultFolder??`.pi-webui/uploads`}function Ls(e,t){return e?.uploads?.defaultFolder??t}function Rs(e,t){let n=Ys(e,`upload destination`,{allowEmpty:!0}),r=Ys(t,`upload file name`,{allowEmpty:!1});return n===``?r:`${n}/${r}`}function zs(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`,No(e,t,n.path,Hs(r)),!0),i.responseType=`json`,i.setRequestHeader(`Content-Type`,(n.contentType??n.file.type)||`application/octet-stream`),i.upload.onprogress=e=>{r.onProgress?.(Us(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(xi(Zs(i)))}catch(e){l(e instanceof Error?e:Error(String(e)))}return}l(Error(Qs(i)))},i.onerror=()=>{l(Error(`Workspace upload failed`))},i.onabort=()=>{l(new Ps(o?void 0:`Workspace upload aborted`))},i.send(n.file)}),cancel:()=>{a||(o=!0,i.abort())}}}function Bs(e,t,n,r={}){let i=r.destinationFolder??`.pi-webui/uploads`,a=n.map((e,t)=>({index:t,name:e.name,path:Rs(i,e.name),loaded:0,total:e.size,percent:Gs(0,e.size),lengthComputable:!0,done:!1})),o,s=0,c={requested:!1},l=()=>{r.onProgress?.(Ws(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 Ps;s=d;let f=n[d],p=a[d];if(!(f===void 0||p===void 0)){o=zs(e,t,{path:p.path,file:f},{...Vs(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(Js(e,c))throw e;let t=qs(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 Fs(u,i);return i})(),cancel:()=>{c.requested=!0,o?.cancel()}}}function Vs(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 Hs(e){return{...e.createDirs===void 0?{}:{createDirs:e.createDirs},...e.overwrite===void 0?{}:{overwrite:e.overwrite},...e.machineId===void 0?{}:{machineId:e.machineId}}}function Us(e,t){let n=e.lengthComputable?e.total:t;return{loaded:e.loaded,total:n,percent:Gs(e.loaded,n),lengthComputable:e.lengthComputable}}function Ws(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:Gs(i,r),done:n}}function Gs(e,t){return t<=0?e<=0?0:1:Math.max(0,Math.min(1,e/t))}function Ks(e){return e.length===1?e[0]?.error??`Workspace upload failed`:`${String(e.length)} files failed to upload`}function qs(e){return e instanceof Error?e.message:String(e)}function Js(e,t){return t.requested||e instanceof Ps}function Ys(e,t,n){let r=e.trim();if(r===``){if(n.allowEmpty)return``;throw Error(`${t} must not be empty`)}if(Xs(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 Xs(e){let t=e.replace(/\\/g,`/`);return t.startsWith(`/`)||/^[A-Za-z]:\//u.test(t)}function Zs(e){return e.response!==void 0&&e.response!==null&&e.response!==``?e.response:e.responseText===``?{}:JSON.parse(e.responseText)}function Qs(e){let t=$s(e);return ec(t)&&typeof t.error==`string`?t.error:e.statusText||`HTTP ${String(e.status)}`}function $s(e){try{return Zs(e)}catch{return}}function ec(e){return typeof e==`object`&&!!e}function tc(e){return e.closesActionPalette===!0}function nc(e){return{mode:e.mode,exact:Fc(e.exact),...e.tier===void 0?{}:{tier:e.tier}}}function rc(e){let t=ic(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 ic(e){if(e.policy!==void 0)return nc(e.policy);let t=e.liveResolved;return t===void 0?{mode:`exact`,exact:{model:{provider:``,id:``},thinkingLevel:``}}:{mode:`exact`,exact:Fc(t)}}function ac(e){let t=e.model?.provider,n=e.model?.id;if(!(t===void 0||n===void 0||!Pc(t)||!Pc(n))&&Pc(e.thinkingLevel))return{model:{provider:t,id:n},thinkingLevel:e.thinkingLevel}}function oc(e){let t=ac(e)??Tc(),n=e.starterModelPolicyPreference;return Sc(e)?Cc(n)?{mode:n.mode,exact:Fc(n.exact),...n.tier===void 0?{}:{tier:n.tier}}:n===void 0?{mode:`tiered`,exact:Fc(t),tier:`standard`}:xc(n,t,n.mode):xc(n,t,`exact`)}function sc(e,t){let n=ac(t);return n===void 0||e.mode===`tiered`||lc(e.exact,n)?e:{...e,exact:Fc(n)}}function cc(e){if(!(e.mode===`tiered`&&e.tier===void 0))return{mode:e.mode,...e.tier===void 0?{}:{tier:e.tier}}}function lc(e,t){return e.model.provider===t.model.provider&&e.model.id===t.model.id&&e.thinkingLevel===t.thinkingLevel}function uc(e,t){return{...e,mode:`tiered`,tier:t}}function dc(e){return{...e,mode:`exact`}}function fc(e,t){let n=t.thinkingLevels.includes(e.exact.thinkingLevel)?e.exact.thinkingLevel:``;return{...e,exact:{model:{...t.model},thinkingLevel:n}}}function pc(e,t){return{...e,exact:{...e.exact,thinkingLevel:t}}}function mc(e,t){if(e.mode===`exact`)return vc(e.exact,t.models)?{mode:`exact`,exact:Fc(e.exact)}:void 0;let n=e.tier;if(!(n===void 0||!t.valid||!jc(t)||!Mc(t,n)))return{mode:`tiered`,tier:n}}function hc(e,t){return t!==void 0&&mc(e,t)!==void 0}function gc(e,t,n){let r=Ec(e);if(wc(t)||e.mode!==`tiered`||Oc(e.exact)||!kc(e.tier)||!jc(n)||!Mc(n,e.tier))return r;let i=n.ladder?.[e.tier];return i===void 0||!Oc(i)?r:{...r,exact:Fc(i)}}function _c(e,t){let n=e.mode===`exact`?yc(e.exact,t):bc(e,t);if(n.kind===`blocked`)return n;let r=Dc(e.exact);return r===void 0?{kind:`ready`,initialModelPolicy:{mode:e.mode,exact:Fc(e.exact),...e.tier===void 0?{}:{tier:e.tier}},resolved:Fc(n.resolved)}:{kind:`blocked`,reason:r}}function vc(e,t){return Dc(e)===void 0&&t.find(t=>Nc(t.model,e.model))?.thinkingLevels.includes(e.thinkingLevel)===!0}function yc(e,t){let n=Dc(e);if(n!==void 0)return{kind:`blocked`,reason:n};let r=t.models.find(t=>Nc(t.model,e.model));return r===void 0?{kind:`blocked`,reason:`Selected provider/model is unavailable`}:r.thinkingLevels.includes(e.thinkingLevel)?{kind:`ready`,resolved:Fc(e)}:{kind:`blocked`,reason:`Selected thinking level is unsupported by the selected model`}}function bc(e,t){let n=e.tier;if(!kc(n))return{kind:`blocked`,reason:Ac(void 0,t)};let r=Object.hasOwn(t.rows,n)?t.rows[n]:void 0;if(r?.valid!==!0)return{kind:`blocked`,reason:Ac(r,t)};let i=t.ladder?.[n];return i===void 0||!Oc(i)?{kind:`blocked`,reason:Ac(r,t)}:{kind:`ready`,resolved:Fc(i)}}function xc(e,t,n){return{mode:e?.mode??n,exact:Fc(t),...e?.tier===void 0?{}:{tier:e.tier}}}function Sc(e){return`starterModelPolicyContractVersion`in e}function Cc(e){return e!==void 0&&Object.hasOwn(e,`exact`)}function wc(e){return Sc(e)&&Cc(e.starterModelPolicyPreference)}function Tc(){return{model:{provider:``,id:``},thinkingLevel:``}}function Ec(e){return{mode:e.mode,exact:Fc(e.exact),...e.tier===void 0?{}:{tier:e.tier}}}function Dc(e){return Oc(e)?void 0:`Choose a provider, model, and thinking level before starting`}function Oc(e){return Pc(e.model.provider)&&Pc(e.model.id)&&Pc(e.thinkingLevel)}function kc(e){return e!==void 0&&bt.includes(e)}function Ac(e,t){return e?.reason!==void 0&&Pc(e.reason)?e.reason:t.configError!==void 0&&Pc(t.configError)?t.configError:`Selected model tier is unavailable`}function jc(e){let t=e.ladder;return t!==void 0&&bt.every(e=>Object.hasOwn(t,e))}function Mc(e,t){return Object.hasOwn(e.rows,t)&&e.rows[t].valid}function Nc(e,t){return e.provider===t.provider&&e.id===t.id}function Pc(e){return e.trim()!==``}function Fc(e){return{model:{...e.model},thinkingLevel:e.thinkingLevel}}function Ic(e){return{kind:`policy-blocked`,scope:e}}function Lc(e,t,n){return{kind:e,message:t,scope:n}}function Rc(e,t,n){if(e===void 0||!Bc(e,t))return;let r=e.kind===`policy-blocked`?n:e.message;return r===void 0||r===``?void 0:r}function zc(e,t,n){return Bc(e,t)?e.kind!==`policy-blocked`||n!==void 0&&n!==``:!1}function Bc(e,t){return t!==void 0&&e.scope.machineId===t.machineId&&e.scope.workspaceId===t.workspaceId}var Vc={economy:`Economy`,fast:`Fast`,standard:`Standard`,advanced:`Advanced`,capable:`Capable`,frontier:`Frontier`},Hc=Xt;function Uc(e){return`${e.provider}/${e.id}`}function Wc(e){let t=e.thinkingLevel.trim()===``?`no thinking level`:e.thinkingLevel;return`${Uc(e.model)} · ${t}`}var Gc={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 Kc(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=Hc.findIndex(t=>t===e);return t===-1?Hc.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,...Gc[n]===void 0?{}:{description:Gc[n]}}))}function qc(){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 Jc(){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 Yc(e,t){return t?.phase===`active`||e?.isStreaming===!0||e?.isBashRunning===!0||e?.isCompacting===!0||(e?.pendingMessageCount??0)>0}function Xc(e){return e!==void 0&&(e.hasSessionActivity||e.hasTerminalActivity)}function Zc(e,t){return`${e}:${t}`}function Qc(e,t){return`${e}:${t}`}function R(e){return e.selectedMachine?.id??`local`}var $c=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}},el=class{constructor(e,t,n={}){this.getState=e,this.setState=t,this.refreshes=new $c,this.api=n.api??gs,this.onActivityApplied=n.onActivityApplied}refresh(e=R(this.getState())){return this.refreshes.request(e,async()=>{this.applyMachineActivitySnapshot(e,tl(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(!rl(i,e))return;let a=nl(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 tl(e){let t={};for(let n of e.workspaces)Xc(n)&&(t[n.cwd]=n);return t}function nl(e,t){let n={...e};return Xc(t)?(n[t.cwd]=t,n):Object.fromEntries(Object.entries(n).filter(([e])=>e!==t.cwd))}function rl(e,t){let n=e[t.cwd];return n===void 0?Xc(t):n.hasSessionActivity!==t.hasSessionActivity||n.hasTerminalActivity!==t.hasTerminalActivity}var il=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??Os,this.pollIntervalMs=r.pollIntervalMs??1e3}dispose(){this.oauthOperationGeneration+=1,this.stopPolling()}handleSlashCommand(e){let t=ol(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||al(n.flow)!==a)return;this.updateOAuthFlow(e,n.machineId)}catch(e){let t=this.currentOAuthDialog(r,i);if(t===void 0||al(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`?al(n.flow):void 0,a=al(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=al(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||al(o.flow)!==a)return;this.updateOAuthFlow(i,t)}catch(i){let o=this.currentOAuthDialog(n,e);if(r!==this.pollGeneration||o?.machineId!==t||al(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 al(e){return e.prompt?.requestId??e.select?.requestId}function ol(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 sl(e){return e.replaceAll(`:`,`.`)}function cl(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 ll(e,t){let n=cl(e)[t];return Array.isArray(n)?n[0]:n===``?void 0:n}function ul(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));dl(i,r)}function dl(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 fl(e){let t=e.files.map((t,n)=>{let r=t.size;return{index:n,name:t.name,path:Rs(e.destinationFolder,t.name),size:t.size,loaded:0,total:r,percent:vl(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:vl(0,n),status:`uploading`,startedAt:e.startedAt}}function pl(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 ml(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=_l(r);return{...e,files:r,currentFileIndex:r.length===0?-1:r.length-1,...i,status:`completed`,completedAt:n}}function hl(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,..._l(r),status:`error`,error:t,completedAt:n}}function gl(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,..._l(r),status:`cancelled`,error:n,completedAt:t}}function _l(e){let t=e.reduce((e,t)=>e+t.total,0);return{loaded:t,total:t,percent:e.length===0?0:1}}function vl(e,t){return t<=0?e<=0?0:1:Math.max(0,Math.min(1,e/t))}var yl=sl(`core:workspace.files`),bl=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??Os,this.uploadWorkspaceFiles=r.uploadWorkspaceFiles??Bs,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:wl(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`}),ul(yl,`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(xl(t)){this.setState({selectedFilePath:void 0,selectedFileContent:void 0,error:``}),ul(yl,`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=fl({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(gl(t,this.now())),this.uploadTasks.get(e)?.cancel())}clearWorkspaceUpload(e){this.uploadTasks.get(e)?.cancel(),this.uploadTasks.delete(e),this.setState({workspaceUploadBatches:wl(this.getState().workspaceUploadBatches,e)})}updateUploadProgress(e,t){let n=this.getUploadBatch(e);n?.status===`uploading`&&this.setUploadBatch(pl(n,t))}async completeUploadBatch(e,t,n){let r=this.getUploadBatch(e);if(r?.status!==`uploading`||(this.setUploadBatch(ml(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 Fs)||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(Sl(t)){let e=gl(n,this.now());return this.setUploadBatch(e),e}let r=Cl(t),i=hl(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 xl(e){let t=String(e);return t.includes(`Path does not exist`)||t.includes(`ENOENT`)||t.includes(`no such file or directory`)}function Sl(e){return e instanceof Ps}function Cl(e){return e instanceof Error?e.message:String(e)}function wl(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>e!==t))}var Tl=sl(`core:workspace.git`),El=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 Os.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}),ul(Tl,`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`}),ul(Tl,`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([Os.gitDiff(n.id,r.id,{path:e},i),Os.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}},Dl=3e4,Ol={setTimeout:(e,t)=>window.setTimeout(e,t),clearTimeout:e=>{window.clearTimeout(e)}},kl=class{constructor(e,t,n={}){this.getState=e,this.setState=t,this.generation=0,this.nextRequestId=0,this.observing=!1,this.fetchSnapshot=n.snapshot??Xo.snapshot,this.timer=n.timer??Ol,this.pollIntervalMs=n.pollIntervalMs??Dl}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=Al(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 Al(e){return e.kind===`unavailable`?{kind:`unavailable`}:{kind:`data`,globalSkills:e.globalSkills,projectSkills:e.projectSkills,...e.projectUnavailableMessage===void 0?{}:{projectUnavailableMessage:e.projectUnavailableMessage}}}var jl=3e4,Ml={setTimeout:(e,t)=>window.setTimeout(e,t),clearTimeout:e=>{window.clearTimeout(e)}},Nl=class{constructor(e,t,n={}){this.getState=e,this.setState=t,this.generation=0,this.nextRequestId=0,this.observing=!1,this.fetchSnapshot=n.snapshot??Jo.snapshot,this.timer=n.timer??Ml,this.pollIntervalMs=n.pollIntervalMs??jl}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=Pl(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 Pl(e){return e.kind===`unavailable`?{kind:`unavailable`}:{kind:`data`,globalEntries:e.globalEntries,projectEntries:e.projectEntries,...e.projectUnavailableMessage===void 0?{}:{projectUnavailableMessage:e.projectUnavailableMessage}}}function Fl(e){let t=[],n=[];for(let r of e)Vl(r.index)&&t.push(Bl(r,`staged`,r.index)),Hl(r.workingTree)&&n.push(Bl(r,`unstaged`,r.workingTree));return{staged:t,unstaged:n}}function Il(e){let t=Fl(e);return new Set([...t.staged,...t.unstaged].map(e=>e.path)).size}function Ll(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 Rl(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 zl(e){return e.oldPath===void 0?e.path:`${e.oldPath} → ${e.path}`}function Bl(e,t,n){return{id:`${t}:${e.path}`,path:e.path,...e.oldPath===void 0?{}:{oldPath:e.oldPath},scope:t,state:n}}function Vl(e){return e!==`unmodified`&&e!==`untracked`&&e!==`ignored`&&e!==`conflicted`}function Hl(e){return e!==`unmodified`&&e!==`ignored`}var Ul=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 Os.machines(),n=await this.selectInitialMachine(t,e),r=new Set(t.map(e=>e.id));this.setState({machines:t,selectedMachine:n,machineActivities:Gl(this.getState().machineActivities,r),machineRuntimes:Gl(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,...qc()}),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 Os.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 Os.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:Wl(this.getState().machineStatuses,e.id),machineRuntimes:Wl(this.getState().machineRuntimes,e.id),machineActivities:Wl(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 Os.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 Os.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 Os.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=>Os.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=>Os.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 Wl(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>e!==t))}function Gl(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>t.has(e)))}var Kl=`~/workspace`,ql=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??Os,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(Kl,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))}},Jl=5e3,Yl=`reconcile selected project catalog`,Xl={setTimeout:(e,t)=>window.setTimeout(e,t),clearTimeout:e=>{window.clearTimeout(e)}},Zl=class{constructor(e,t){this.getState=e,this.generation=0,this.nextRequestId=0,this.observing=!1,this.listWorkspaces=t.workspaces??ys.workspaces,this.applySnapshot=t.applySnapshot,this.timer=t.timer??Xl,this.pollIntervalMs=t.pollIntervalMs??Jl,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(Yl,e)}catch{}}},Ql=`record recent project`,$l=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??vs}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:eu(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?.(Ql,e)}})}async removeEntry(e){let t=this.deps.machineId();this.latestIntentByMachine.delete(t),this.authoritativeProjectIdByMachine.delete(t);let n=this.generation,r,i;if(await this.enqueue(t,async()=>{try{let i=await this.api.removeRecentProject(e,t);this.authoritativeProjectIdByMachine.delete(t),this.isStale(n,t)||this.publish({kind:`ready`,entries:i}),r={kind:`removed`}}catch(e){if(e instanceof jt&&e.status===409&&await this.reconcileRemovalConflict(t)){r={kind:`registered-conflict`,error:e};return}i=e instanceof Error?e:Error(String(e))}}),i!==void 0)throw i;if(r===void 0)throw Error(`Recent project removal completed without an outcome`);return r}async reconcileRemovalConflict(e){let t=Promise.resolve().then(()=>this.deps.reconcileProjects?.(e)),n=Promise.resolve().then(()=>this.api.recentProjects(e)),[r,i]=await Promise.allSettled([t,n]);return r.status!==`fulfilled`||r.value===!1||i.status!==`fulfilled`?!1:(this.authoritativeProjectIdByMachine.delete(e),e===this.deps.machineId()&&this.publish({kind:`ready`,entries:i.value}),!0)}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 eu(e){return e instanceof Error?e.message:String(e)}function tu(e,t){return t[e.path]}function nu(e){if(e?.hasSessionActivity===!0)return`session`;if(e?.hasTerminalActivity===!0)return`terminal`}function ru(e,t,n){return ou(su(e,t,n))}function iu(e,t,n){return t.some(t=>t.projectId===e.id&&t.path===n)||n===e.path||n.startsWith(`${e.path}/`)}function au(e){return ou(Object.values(e??{}))}function ou(e){if(e.some(e=>e.hasSessionActivity))return`session`;if(e.some(e=>e.hasTerminalActivity))return`terminal`}function su(e,t,n){return Object.values(n).filter(n=>iu(e,t,n.cwd))}var cu=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??ys,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])=>!lu(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&&!lu(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(Xc).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 lu(e,t,n){return e.some(e=>iu(e,t[e.id]??[],n))}var uu=class{constructor(e,t,n={}){this.getState=e,this.setState=t,this.requestSequence=0,this.api=n.api??Go,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}),du(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 du(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 fu=`pi-webui:cached-new-sessions:v1`,pu=`browserCachedNew`,mu=`local`;function hu(){try{return typeof localStorage>`u`?void 0:localStorage}catch{return}}function gu(e,t=mu,n=hu()){if(e.messageCount!==0||e.archived===!0)return;let r=Su(n).filter(n=>n.id!==e.id||n.machineId!==t);Cu([_u(e,t),...r],n)}function _u(e,t=mu){return{...e,browserCachedNew:!0,machineId:t}}function vu(e,t=mu,n=hu()){Cu(Su(n).filter(n=>n.id!==e||n.machineId!==t),n)}function yu(e,t,n=mu,r=hu()){let i=new Set(t.map(e=>e.id)),a=Su(r),o=a.filter(e=>e.machineId!==n||!i.has(e.id));return o.length!==a.length&&Cu(o,r),[...o.filter(t=>t.machineId===n&&t.cwd===e),...t]}function bu(e){return e!==void 0&&Tu(e)&&e.browserCachedNew===!0}function xu(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:mu},...e.archived===!0?{archived:!0}:{},...e.archivedAt===void 0?{}:{archivedAt:e.archivedAt},...e.creationSource===void 0?{}:{creationSource:e.creationSource}}}function Su(e=hu()){try{let t=e?.getItem(fu);if(t==null||t===``)return[];let n=JSON.parse(t);return Array.isArray(n)?n.flatMap(e=>wu(e)):[]}catch{return[]}}function Cu(e,t=hu()){try{e.length===0?t?.removeItem(fu):t?.setItem(fu,JSON.stringify(e))}catch{}}function wu(e){if(!Eu(e))return[];let t=Du(e,`id`),n=Du(e,`path`),r=Du(e,`cwd`),i=Du(e,`created`),a=Du(e,`modified`),o=Du(e,`firstMessage`),s=ku(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=Ou(e,`name`),l=Ou(e,`parentSessionPath`),u=Ou(e,`machineId`)??mu,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 Tu(e){return pu in e}function Eu(e){return typeof e==`object`&&!!e}function Du(e,t){let n=e[t];return typeof n==`string`?n:void 0}function Ou(e,t){let n=e[t];return n===void 0||typeof n!=`string`?void 0:n}function ku(e,t){let n=e[t];return typeof n==`number`?n:void 0}function Au(e){return Yu(e.flatMap(Fu)).filter(e=>e.parts.length>0)}function ju(e,t){return{role:e,parts:[{type:`text`,text:t}]}}function Mu(e,t){let n=Vu(t),r=z(t,`entryId`),i=z(t,`previousAssistantEntryId`),a=id(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 Nu(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,ju(t,n)]}function Pu(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 Fu(e){if(Lu(e))return[e];if(z(e,`role`)===`bashExecution`)return[Mu(Wu(e),e)];let t=Gu(z(e,`role`)),n=Ku(rd(e,`content`),e),r=t===`user`?Ru(n):void 0;if(r!==void 0)return r.map(t=>Mu(t,e));let i=Bu(e);if(t===`tool`)return[Mu({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?[Mu({role:o,parts:a,...i===void 0?{}:{source:i}},e)]:[],c=Iu(e);return c===void 0?s:[...s,Mu(c,e)]}function Iu(e){if(z(e,`role`)!==`assistant`||z(e,`stopReason`)!==`error`)return;let t=z(e,`errorMessage`)?.trim();return ju(`system`,`Model response failed: ${t===void 0||t===``?`The model returned an error.`:t}`)}function Lu(e){let t=z(e,`role`);return(t===`user`||t===`assistant`||t===`tool`||t===`system`||t===`bash`||t===`skill`)&&Array.isArray(rd(e,`parts`))}function Ru(e){if(e.length!==1||e[0]?.type!==`text`)return;let t=zu(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 zu(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 Bu(e){let t=z(e,`source`);if(t===`compaction`||t===`branch_summary`)return t}function Vu(e){let t=Hu(rd(e,`timestamp`)),n=Uu(e);if(!(t===void 0&&n===void 0))return{...t===void 0?{}:{timestamp:t},...n===void 0?{}:{model:n}}}function Hu(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 Uu(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 Wu(e){let t=z(e,`command`)??``,n=id(e,`excludeFromContext`)===!0?[`excluded from context`,``,`$ ${t}`]:[`$ ${t}`],r=rd(e,`output`);r!=null&&n.push(``,od(r));let i=rd(e,`exitCode`);i!=null&&n.push(``,`exit ${od(i)}`),id(e,`cancelled`)===!0&&n.push(``,`cancelled`),id(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(`
|
|
4
4
|
`)}]}}function Gu(e){return e===`assistant`?`assistant`:e===`user`?`user`:e===`toolResult`?`tool`:`system`}function Ku(e,t){return typeof e==`string`?e===``?[]:[{type:`text`,text:e}]:Array.isArray(e)?e.flatMap(e=>{let t=z(e,`type`),n=z(e,`text`);if(t===`text`)return n!==void 0&&n!==``?[{type:`text`,text:n}]:[];if(t===`thinking`){let t=z(e,`thinking`)??n;return t!==void 0&&t!==``?[{type:`thinking`,text:t}]:[]}if(t===`toolCall`){let t=z(e,`name`)??`tool`,n=rd(e,`arguments`),r=z(e,`id`),i=t===`read`?Ju(z(n,`path`)):void 0;return i===void 0?[{type:`toolCall`,...r===void 0?{}:{toolCallId:r},toolName:t,summary:ed(n),...n===void 0?{}:{args:n}}]:[{type:`skillRead`,...i,...r===void 0?{}:{toolCallId:r}}]}if(t===`image`){let t=z(e,`data`),n=z(e,`mimeType`);return t!==void 0&&t!==``&&n!==void 0&&n!==``?[{type:`image`,mimeType:n,data:t}]:[{type:`text`,text:`[image]`}]}return $u(e)}).map(e=>e.type===`text`&&z(t,`role`)===`toolResult`?qu(e.text,t):e):$u(e)}function qu(e,t){let n=z(t,`toolCallId`),r=rd(t,`content`),i=rd(t,`details`);return{type:`toolResult`,...n===void 0?{}:{toolCallId:n},toolName:z(t,`toolName`)??`tool`,text:e,...r===void 0?{}:{content:r},...i===void 0?{}:{details:i},isError:id(t,`isError`)===!0}}function Ju(e){if(e===void 0||e===``)return;let t=e.replace(/\\/g,`/`);if(!t.endsWith(`/SKILL.md`)&&t!==`SKILL.md`)return;let n=t.split(`/`).at(-2);if(!(n===void 0||n===``))return{name:n,path:e}}function Yu(e){let t=[],n=new Map;for(let r of e){let e=[],i={...r.entryId===void 0?{}:{entryId:r.entryId},...r.previousAssistantEntryId===void 0?{}:{previousAssistantEntryId:r.previousAssistantEntryId},...r.canFork===void 0?{}:{canFork:r.canFork},...r.source===void 0?{}:{source:r.source},...r.meta===void 0?{}:{meta:r.meta}},a=()=>{e.length!==0&&(t.push({role:r.role,parts:e,...i}),e=[])};for(let o of r.parts){if(o.type===`toolCall`){a();let e=Xu(o),r=t.length;t.push({role:`tool`,parts:[e],...i}),e.toolCallId!==void 0&&n.set(e.toolCallId,{lineIndex:r,partIndex:0});continue}if(o.type===`toolResult`){let e=o.toolCallId===void 0?void 0:n.get(o.toolCallId);if(e!==void 0&&Zu(t,e,o)){n.delete(o.toolCallId??``);continue}}e.push(o)}a()}return t}function Xu(e){return{type:`toolExecution`,...e.toolCallId===void 0?{}:{toolCallId:e.toolCallId},toolName:e.toolName,summary:e.summary,...e.args===void 0?{}:{args:e.args},status:`pending`}}function Zu(e,t,n){let r=e[t.lineIndex],i=r?.parts[t.partIndex];if(r===void 0||i?.type!==`toolExecution`)return!1;let a=Qu(n.details)??i.preview,o={...i,status:n.isError?`error`:`success`,resultText:n.text,...n.content===void 0?{}:{content:n.content},...n.details===void 0?{}:{details:n.details},...a===void 0?{}:{preview:a}};return e[t.lineIndex]={...r,parts:[...r.parts.slice(0,t.partIndex),o,...r.parts.slice(t.partIndex+1)]},!0}function Qu(e){let t=rd(e,`preview`);if(!nd(t))return;let n=z(t,`diff`),r=z(t,`error`),i=ad(t,`firstChangedLine`);if(!(n===void 0&&r===void 0&&i===void 0))return{...n===void 0?{}:{diff:n},...r===void 0?{}:{error:r},...i===void 0?{}:{firstChangedLine:i}}}function $u(e){return e==null?[]:typeof e==`object`?[{type:`text`,text:ed(e)}]:[{type:`text`,text:od(e)}]}function ed(e){if(!nd(e))return od(e);let t=z(e,`command`);if(t!==void 0)return t;let n=z(e,`path`);if(n!==void 0)return n;if(typeof e.oldText==`string`&&typeof e.newText==`string`)return`edit text replacement`;let r=e.edits;return Array.isArray(r)?`${String(r.length)} edit${r.length===1?``:`s`}`:Object.entries(e).filter(([,e])=>e!=null).slice(0,3).map(([e,t])=>`${e}: ${td(t)}`).join(` · `)}function td(e){return typeof e==`string`?e.length>80?`${e.slice(0,77)}…`:e:typeof e==`number`||typeof e==`boolean`?String(e):Array.isArray(e)?`${String(e.length)} item${e.length===1?``:`s`}`:typeof e==`object`&&e?`object`:``}function nd(e){return typeof e==`object`&&!!e}function rd(e,t){return nd(e)?e[t]:void 0}function z(e,t){let n=rd(e,t);return typeof n==`string`?n:void 0}function id(e,t){let n=rd(e,t);return typeof n==`boolean`?n:void 0}function ad(e,t){let n=rd(e,t);return typeof n==`number`&&Number.isFinite(n)?n:void 0}function od(e){return e==null?``:typeof e==`string`?e:typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`?String(e):``}var sd=new class{constructor(){this.scopes=new Map,this.migratedScopes=new Map,this.attachmentSeq=0}read(e){let t=this.scopes.get(e);return t===void 0?{attachments:[]}:this.readScope(t)}write(e,t){let n=this.findScopeState(e)??this.createScopeState(e);this.writeScope(n,t)}openScope(e){return this.scopeHandle(this.findScopeState(e)??this.createScopeState(e))}findScope(e){let t=this.findScopeState(e);return t===void 0?void 0:this.scopeHandle(t)}clear(e){let t=this.findScopeState(e);t!==void 0&&this.invalidateScope(t)}move(e,t){if(e===t){let t=this.findScopeState(e);t!==void 0&&(t.draft=void 0);return}let n=this.findScopeState(e),r=this.findScopeState(t);if(n===void 0){r!==void 0&&this.invalidateScope(r);return}r!==void 0&&r!==n&&this.invalidateScope(r),this.removeCanonicalMapping(n),n.currentKey=t,n.valid=!0,this.scopes.set(t,n),this.migratedScopes.set(e,n)}nextAttachmentId(){return this.attachmentSeq+=1,`attachment-${String(this.attachmentSeq)}`}hasEntry(e){return this.scopes.get(e)?.draft!==void 0}createScopeState(e){let t={currentKey:e,valid:!0,draft:void 0};return this.scopes.set(e,t),this.migratedScopes.delete(e),t}findScopeState(e){let t=this.scopes.get(e);if(t!==void 0)return t.valid?t:void 0;let n=this.migratedScopes.get(e);if(n!==void 0){if(!n.valid){this.migratedScopes.delete(e);return}return n}}scopeHandle(e){return{currentKey:()=>e.valid?e.currentKey:void 0,read:()=>this.readScope(e),write:t=>{this.writeScope(e,t)},clear:()=>{this.invalidateScope(e)},beginCapture:()=>({complete:(t,n)=>this.completeCapture(e,t,n)})}}readScope(e){return!e.valid||e.draft===void 0?{attachments:[]}:{attachments:[...e.draft.attachments],...e.draft.error===void 0?{}:{error:e.draft.error}}}writeScope(e,t){if(e.valid){if(t.attachments.length===0&&t.error===void 0){e.draft=void 0;return}e.draft={attachments:[...t.attachments],...t.error===void 0?{}:{error:t.error}}}}completeCapture(e,t,n){if(!e.valid)return;let r={attachments:[...e.draft?.attachments??[],...t.map(e=>({id:this.nextAttachmentId(),...e}))],...n===void 0?{}:{error:n}};return this.writeScope(e,r),this.readScope(e)}removeCanonicalMapping(e){for(let[t,n]of this.scopes)n===e&&this.scopes.delete(t)}invalidateScope(e){e.valid=!1,e.draft=void 0,this.removeCanonicalMapping(e);for(let[t,n]of this.migratedScopes)n===e&&this.migratedScopes.delete(t)}},cd=`pi-webui:prompt-draft:`;function ld(e){return`${cd}${e}`}function ud(){try{return typeof localStorage>`u`?void 0:localStorage}catch{return}}function dd(e,t=ud()){try{return t?.getItem(ld(e))??``}catch{return``}}function fd(e,t,n=ud()){try{t?n?.setItem(ld(e),t):n?.removeItem(ld(e))}catch{}}function pd(e,t=ud()){try{t?.removeItem(ld(e))}catch{}}function md(e,t,n=ud()){let r=dd(e,n);r!==``&&(fd(t,r,n),pd(e,n))}function hd(e,t){return ju(`bash`,`${t===!0?`excluded from context
|
|
@@ -1135,7 +1135,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
1135
1135
|
.review-file span { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
1136
1136
|
.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; }
|
|
1137
1137
|
footer { display: flex; justify-content: flex-end; gap: 8px; padding-top: 4px; }
|
|
1138
|
-
`]}};B([x({attribute:!1})],C_.prototype,`context`,void 0),B([C(`#workspace-upload-input`)],C_.prototype,`uploadInput`,void 0),B([S()],C_.prototype,`pendingUpload`,void 0),B([S()],C_.prototype,`destinationFolder`,void 0),B([S()],C_.prototype,`overwrite`,void 0),B([S()],C_.prototype,`createDirs`,void 0),B([S()],C_.prototype,`formError`,void 0),B([S()],C_.prototype,`dragActive`,void 0),C_=B([b(`workspace-files-panel`)],C_);function w_(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 T_(e,t){if(e.length===0)return`Choose at least one file to upload.`;for(let n of e)try{Rs(t,n.name)}catch(e){return e instanceof Error?e.message:String(e)}}function E_(e){return{destinationFolder:e,createDirs:!0,overwrite:!1}}function D_(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} · ${B_(t.size)}`}function O_(e,t){if(t.length!==0)return e.onStartWorkspaceUpload(t,{destinationFolder:e.workspaceUploadDefaultFolder,createDirs:!0,overwrite:!1,selectUploadedFile:!0})}function k_(e){return`${e.machine.id}:${e.workspace.projectId}:${e.workspace.id}`}function A_(e){return e==null?[]:Array.from(e)}function j_(e){return Array.from(e.dataTransfer?.types??[]).includes(`Files`)}function M_(e){let t=e.filter(e=>e.status===`uploading`).length;return t===0?`${String(e.length)} recent`:`${String(t)} uploading`}function N_(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 P_(e){switch(e.status){case`completed`:return`Done`;case`error`:return`Failed`;case`cancelled`:return`Cancelled`;case`uploading`:return R_(e.percent)}}function F_(e){return e.status===`uploading`?e.percent:1}function I_(e){switch(e.status){case`pending`:return`Pending`;case`uploading`:return R_(e.percent);case`completed`:return`Done`;case`error`:return`Error`;case`cancelled`:return`Cancelled`}}function L_(e){return e.error===void 0?e.response===void 0?`${e.path} · ${B_(e.loaded)} / ${B_(e.total)}`:`Wrote ${e.response.path}`:e.error}function R_(e){return`${String(Math.round(Math.max(0,Math.min(1,e))*100))}%`}function z_(){S_(()=>import(`./CodeViewer-
|
|
1138
|
+
`]}};B([x({attribute:!1})],C_.prototype,`context`,void 0),B([C(`#workspace-upload-input`)],C_.prototype,`uploadInput`,void 0),B([S()],C_.prototype,`pendingUpload`,void 0),B([S()],C_.prototype,`destinationFolder`,void 0),B([S()],C_.prototype,`overwrite`,void 0),B([S()],C_.prototype,`createDirs`,void 0),B([S()],C_.prototype,`formError`,void 0),B([S()],C_.prototype,`dragActive`,void 0),C_=B([b(`workspace-files-panel`)],C_);function w_(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 T_(e,t){if(e.length===0)return`Choose at least one file to upload.`;for(let n of e)try{Rs(t,n.name)}catch(e){return e instanceof Error?e.message:String(e)}}function E_(e){return{destinationFolder:e,createDirs:!0,overwrite:!1}}function D_(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} · ${B_(t.size)}`}function O_(e,t){if(t.length!==0)return e.onStartWorkspaceUpload(t,{destinationFolder:e.workspaceUploadDefaultFolder,createDirs:!0,overwrite:!1,selectUploadedFile:!0})}function k_(e){return`${e.machine.id}:${e.workspace.projectId}:${e.workspace.id}`}function A_(e){return e==null?[]:Array.from(e)}function j_(e){return Array.from(e.dataTransfer?.types??[]).includes(`Files`)}function M_(e){let t=e.filter(e=>e.status===`uploading`).length;return t===0?`${String(e.length)} recent`:`${String(t)} uploading`}function N_(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 P_(e){switch(e.status){case`completed`:return`Done`;case`error`:return`Failed`;case`cancelled`:return`Cancelled`;case`uploading`:return R_(e.percent)}}function F_(e){return e.status===`uploading`?e.percent:1}function I_(e){switch(e.status){case`pending`:return`Pending`;case`uploading`:return R_(e.percent);case`completed`:return`Done`;case`error`:return`Error`;case`cancelled`:return`Cancelled`}}function L_(e){return e.error===void 0?e.response===void 0?`${e.path} · ${B_(e.loaded)} / ${B_(e.total)}`:`Wrote ${e.response.path}`:e.error}function R_(e){return`${String(Math.round(Math.max(0,Math.min(1,e))*100))}%`}function z_(){S_(()=>import(`./CodeViewer-BX-JhrL4.js`),__vite__mapDeps([0,1,2,3]),import.meta.url)}function B_(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`${V_(t)} KB`;let n=t/1024;return n<1024?`${V_(n)} MB`:`${V_(n/1024)} GB`}function V_(e){return e>=10?String(Math.round(e)):e.toFixed(1)}var H_=2e3,U_=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 Go.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)},H_))}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 Go.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">
|
|
1139
1139
|
<p class="error-text">Failed to load system information: ${this.error}</p>
|
|
1140
1140
|
<button @click=${()=>{this.loadSystemInfo()}}>Retry</button>
|
|
1141
1141
|
</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">
|
|
@@ -1389,7 +1389,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
1389
1389
|
<div class="viewer-header"><strong>${e.path??`diff`}</strong><small>${e.staged?`staged`:`unstaged`}${e.truncated?` · truncated`:``}</small></div>
|
|
1390
1390
|
<unified-diff-viewer .diff=${e.diff}></unified-diff-viewer>
|
|
1391
1391
|
</section>
|
|
1392
|
-
`}function nv(){S_(()=>import(`./UnifiedDiffViewer-
|
|
1392
|
+
`}function nv(){S_(()=>import(`./UnifiedDiffViewer-CFdMhoMV.js`),[],import.meta.url)}function rv(){S_(()=>Promise.resolve().then(()=>PN),void 0,import.meta.url)}function iv(e){return g`<workspace-info-panel .context=${e}></workspace-info-panel>`}function av(e){let t=ov(e);return g`
|
|
1393
1393
|
<p class="summary">
|
|
1394
1394
|
<span class="summary-branch">${t.branch}</span>
|
|
1395
1395
|
${t.latestTag===void 0?null:g`<span class="summary-tag" aria-label=${`Latest tag ${t.latestTag}`}>${t.latestTag}</span>`}
|
|
@@ -6028,10 +6028,40 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
6028
6028
|
/* The shared small rule truncates with ellipsis; history paths must wrap. */
|
|
6029
6029
|
.recent-project-path { overflow: visible; text-overflow: clip; overflow-wrap: anywhere; white-space: normal; }
|
|
6030
6030
|
.recent-project-status { flex: 0 0 auto; color: var(--pi-warning); font-size: 12px; }
|
|
6031
|
-
`]}};B([x({attribute:!1})],GM.prototype,`state`,void 0),B([x({attribute:!1})],GM.prototype,`projects`,void 0),B([x({attribute:!1})],GM.prototype,`workspacesByProjectId`,void 0),B([x({attribute:!1})],GM.prototype,`activities`,void 0),B([x({attribute:!1})],GM.prototype,`selectedProjectId`,void 0),B([x({attribute:!1})],GM.prototype,`onOpenRegistered`,void 0),B([x({attribute:!1})],GM.prototype,`onOpenClosed`,void 0),B([x({attribute:!1})],GM.prototype,`onRetry`,void 0),GM=B([b(`recent-projects-panel`)],GM);var KM
|
|
6032
|
-
|
|
6031
|
+
`]}};B([x({attribute:!1})],GM.prototype,`state`,void 0),B([x({attribute:!1})],GM.prototype,`projects`,void 0),B([x({attribute:!1})],GM.prototype,`workspacesByProjectId`,void 0),B([x({attribute:!1})],GM.prototype,`activities`,void 0),B([x({attribute:!1})],GM.prototype,`selectedProjectId`,void 0),B([x({attribute:!1})],GM.prototype,`onOpenRegistered`,void 0),B([x({attribute:!1})],GM.prototype,`onOpenClosed`,void 0),B([x({attribute:!1})],GM.prototype,`onRetry`,void 0),GM=B([b(`recent-projects-panel`)],GM);var KM=class extends y{constructor(...e){super(...e),this.busy=!1,this.handleCancel=e=>{e.preventDefault(),this.onClose()},this.handleBackdropClick=e=>{e.target===e.currentTarget&&this.onClose()}}firstUpdated(){let e=this.nativeDialog;e?.isConnected===!0&&(e.showModal(),this.reopenButton?.focus())}disconnectedCallback(){this.close(),super.disconnectedCallback()}close(){let e=this.nativeDialog;e?.open===!0&&e.close()}render(){return g`
|
|
6032
|
+
<dialog
|
|
6033
|
+
class="closed-recent-backdrop"
|
|
6034
|
+
aria-modal="true"
|
|
6035
|
+
aria-label=${`Recent project ${this.entry.name}`}
|
|
6036
|
+
@cancel=${this.handleCancel}
|
|
6037
|
+
@click=${this.handleBackdropClick}
|
|
6038
|
+
>
|
|
6039
|
+
<section class="closed-recent-frame">
|
|
6040
|
+
<h2>${this.entry.name}</h2>
|
|
6041
|
+
<p class="closed-recent-path">${this.entry.path}</p>
|
|
6042
|
+
<p class="muted">This project is no longer registered in PI WEBUI.</p>
|
|
6043
|
+
${this.failure===void 0?null:g`<p class="closed-recent-error" role="status">${this.failure}</p>`}
|
|
6044
|
+
<div class="closed-recent-actions">
|
|
6045
|
+
<button class="closed-recent-reopen" type="button" ?disabled=${this.busy} @click=${()=>{this.run(this.onReopen)}}>Reopen</button>
|
|
6046
|
+
<button class="closed-recent-remove" type="button" ?disabled=${this.busy} @click=${()=>{this.run(this.onRemove)}}>Remove from history</button>
|
|
6047
|
+
<button class="closed-recent-cancel" type="button" @click=${()=>{this.onClose()}}>Cancel</button>
|
|
6048
|
+
</div>
|
|
6049
|
+
</section>
|
|
6050
|
+
</dialog>
|
|
6051
|
+
`}async run(e){if(!this.busy){this.busy=!0,this.failure=void 0;try{await e(this.entry),this.onClose()}catch(e){this.failure=e instanceof Error?e.message:String(e)}finally{this.busy=!1}}}static{this.styles=h`
|
|
6052
|
+
:host { position: fixed; inset: 0; z-index: 70; display: block; color: var(--pi-text); font: 14px system-ui, sans-serif; }
|
|
6053
|
+
dialog { max-width: calc(100vw - 24px); border: 0; padding: 0; background: transparent; }
|
|
6054
|
+
dialog::backdrop { background: var(--pi-overlay); }
|
|
6055
|
+
.closed-recent-frame { box-sizing: border-box; width: min(480px, 92vw); max-width: calc(100vw - 24px); display: grid; gap: 12px; padding: 20px; border: 1px solid var(--pi-border); border-radius: 12px; background: var(--pi-bg); box-shadow: 0 20px 64px var(--pi-shadow-strong); }
|
|
6056
|
+
h2, p { margin: 0; }
|
|
6057
|
+
.closed-recent-path { overflow-wrap: anywhere; color: var(--pi-muted); }
|
|
6058
|
+
.closed-recent-error { color: var(--pi-danger); }
|
|
6059
|
+
.closed-recent-actions { display: flex; flex-wrap: wrap; gap: 8px; }
|
|
6060
|
+
button:focus-visible { outline: 2px solid var(--pi-accent); outline-offset: 2px; }
|
|
6061
|
+
`}};B([x({attribute:!1})],KM.prototype,`entry`,void 0),B([x({attribute:!1})],KM.prototype,`onReopen`,void 0),B([x({attribute:!1})],KM.prototype,`onRemove`,void 0),B([x({attribute:!1})],KM.prototype,`onClose`,void 0),B([C(`dialog`)],KM.prototype,`nativeDialog`,void 0),B([C(`.closed-recent-reopen`)],KM.prototype,`reopenButton`,void 0),B([S()],KM.prototype,`busy`,void 0),B([S()],KM.prototype,`failure`,void 0),KM=B([b(`closed-recent-project-dialog`)],KM);var qM=`important`,JM=` !important`,YM=tx(class extends nx{constructor(e){if(super(e),e.type!==ex.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(JM);e.includes(`-`)||t?n.setProperty(e,t?r.slice(0,-11):r,t?qM:``):n[e]=r}}return Qe}}),XM=`#ffffff`,ZM=`#000000`,QM=[`#2e3436`,`#cc0000`,`#4e9a06`,`#c4a000`,`#3465a4`,`#75507b`,`#06989a`,`#d3d7cf`,`#555753`,`#ef2929`,`#8ae234`,`#fce94f`,`#729fcf`,`#ad7fa8`,`#34e2e2`,`#eeeeec`],$M=[`black`,`red`,`green`,`yellow`,`blue`,`magenta`,`cyan`,`white`,`brightBlack`,`brightRed`,`brightGreen`,`brightYellow`,`brightBlue`,`brightMagenta`,`brightCyan`,`brightWhite`],eN={black:QM[0],red:QM[1],green:QM[2],yellow:QM[3],blue:QM[4],magenta:QM[5],cyan:QM[6],white:QM[7],brightBlack:QM[8],brightRed:QM[9],brightGreen:QM[10],brightYellow:QM[11],brightBlue:QM[12],brightMagenta:QM[13],brightCyan:QM[14],brightWhite:QM[15]};function tN(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=lN(n.theme),a=n.theme?.foreground??XM,o=n.theme?.background??ZM,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=nN(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,oN(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(`
|
|
6062
|
+
`),lines:p,physicalLineCount:f.length,viewportLine:Math.min(d,Math.max(0,e.viewportY))}}function nN(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:aN(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:rN(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,sN(s,{text:t.text,style:t.style}))}return{text:c,runs:s,wrapped:e.isWrapped}}function rN(e,t){let n=e.isInverse()!==0,r=iN(e,`foreground`,t),i=iN(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 iN(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?uN(a):i?n.palette[a]??(t===`foreground`?n.foreground:n.background):t===`foreground`?n.foreground:n.background}function aN(e){return{foreground:e.foreground,background:e.background,bold:!1,italic:!1,dim:!1,underline:!1,invisible:!1,strikethrough:!1,overline:!1}}function oN(e,t){for(let n of t)sN(e,n)}function sN(e,t){if(t.text===``)return;let n=e.at(-1);if(n!==void 0&&cN(n.style,t.style)){n.text+=t.text;return}e.push({text:t.text,style:t.style})}function cN(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 lN(e){let t=[...QM];for(let n=0;n<$M.length;n+=1){let r=$M[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(dN(r,i,a))}for(let e=0;e<24;e+=1){let n=8+e*10;t.push(dN(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 uN(e){return`#${(e&16777215).toString(16).padStart(6,`0`)}`}function dN(e,t,n){return`#${e.toString(16).padStart(2,`0`)}${t.toString(16).padStart(2,`0`)}${n.toString(16).padStart(2,`0`)}`}var fN=`pi-webui.terminal.softKeys`,pN=`(pointer: coarse), (max-width: 760px)`;function mN(e,t){return e??t}function hN(e){if(e===`true`)return!0;if(e===`false`)return!1}function gN(){return typeof window<`u`&&`matchMedia`in window?window.matchMedia(pN):void 0}function _N(e){return e?.matches===!0}function vN(e=gN()){return mN(bN(),_N(e))}function yN(){return bN()!==void 0}function bN(e=SN()){if(e!==void 0)try{return hN(e.getItem(fN))}catch{return}}function xN(e,t=SN()){if(t!==void 0)try{t.setItem(fN,String(e))}catch{}}function SN(){if(!(typeof window>`u`))try{return window.localStorage}catch{return}}var CN=[{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`}],wN=`\x1B`,TN=``;function EN(e,t){switch(e){case`escape`:return wN;case`tab`:return` `;case`ctrl-c`:return DN(`c`);case`ctrl-d`:return DN(`d`);case`ctrl-z`:return DN(`z`);case`ctrl-l`:return DN(`l`);case`ctrl-r`:return DN(`r`);case`ctrl-u`:return DN(`u`);case`ctrl-w`:return DN(`w`);case`arrow-left`:return ON(`D`,t);case`arrow-up`:return ON(`A`,t);case`arrow-down`:return ON(`B`,t);case`arrow-right`:return ON(`C`,t);case`home`:return kN(`H`,t);case`end`:return kN(`F`,t);case`page-up`:return`${wN}[5~`;case`page-down`:return`${wN}[6~`;case`delete`:return`${wN}[3~`;case`backspace`:return TN;case`meta-backward-word`:return`${wN}b`;case`meta-forward-word`:return`${wN}f`}}function DN(e){return String.fromCharCode(e.toUpperCase().charCodeAt(0)-64)}function ON(e,t){return t?.applicationCursorKeysMode===!0?`${wN}O${e}`:`${wN}[${e}`}function kN(e,t){return t?.applicationCursorKeysMode===!0?`${wN}O${e}`:`${wN}[${e}`}var AN=8,jN=500,MN=class extends y{constructor(...e){super(...e),this.refocusOnClick=!0,this.onInput=()=>void 0,this.lastPointerFinishedAt=0}sendSoftKey(e,t){this.onInput(EN(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&&NN(t,e)&&this.finishSoftKeyPointer()}onSoftKeyPointerUp(e,t){let n=this.pointerStart;n?.pointerId===e.pointerId&&(e.preventDefault(),this.finishSoftKeyPointer(),!(n.key.id!==t.id||NN(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<jN){e.preventDefault();return}this.sendSoftKey(t,{refocus:this.refocusOnClick})}render(){return g`
|
|
6033
6063
|
<div class="terminal-soft-keys" role="toolbar" aria-label="Terminal soft keys">
|
|
6034
|
-
${
|
|
6064
|
+
${CN.map(e=>g`
|
|
6035
6065
|
<button
|
|
6036
6066
|
type="button"
|
|
6037
6067
|
class="soft-key"
|
|
@@ -6051,7 +6081,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
6051
6081
|
.terminal-soft-keys::-webkit-scrollbar { display: none; }
|
|
6052
6082
|
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; }
|
|
6053
6083
|
button:disabled { opacity: .5; cursor: not-allowed; }
|
|
6054
|
-
`}};B([x({attribute:!1})],jN.prototype,`modes`,void 0),B([x({type:Boolean})],jN.prototype,`refocusOnClick`,void 0),B([x({attribute:!1})],jN.prototype,`onInput`,void 0),jN=B([b(`terminal-soft-keys`)],jN);function MN(e,t){return Math.hypot(t.clientX-e.clientX,t.clientY-e.clientY)>kN}var NN=oe({TerminalPanel:()=>Z,filterTerminalInput:()=>JN,terminalBackgroundWithOpacity:()=>eP}),PN={allowTransparency:!0,cursorBlink:!0,convertEol:!0,fontFamily:`ui-monospace, SFMono-Regular, Menlo, Consolas, monospace`,fontSize:13},FN={cols:100,rows:30},IN=1e3,LN=500,RN=5e3,zN=1.6,BN=`--pi-terminal-effective-bg`,VN=`--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=_N(),this.suppressTerminalInput=!1,this.terminalReconnectDelay=LN,this.softKeysDefaultEnvironmentMedia=hN(),this.softKeysPreferenceStored=vN(),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=gN(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([xs.terminals(e.projectId,e.id,this.machineId),xs.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=sh(this.terminals,{targetTerminalId:this.selectedTerminalId});t===void 0&&this.selectedTerminalId!==void 0&&(t=ch(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()??FN,i=await xs.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 xs.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=ch(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 xs.listCommandRuns({projectId:e.projectId,workspaceId:e.id},this.machineId);this.commandRuns=t,this.cancellingRunIds=this.cancellingRunIds.filter(e=>t.some(t=>t.id===e&&GN(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()},IN);return}!e&&this.commandRunPollTimer!==void 0&&(window.clearInterval(this.commandRunPollTimer),this.commandRunPollTimer=void 0)}hasPendingCommandRuns(e=this.commandRuns){return e.some(GN)}async cancelCommandRun(e){if(!(!GN(e)||this.cancellingRunIds.includes(e.id))){this.error=void 0,this.cancellingRunIds=[...this.cancellingRunIds,e.id];try{await xs.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 xs.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 re(XN(this)),r=new ie;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=As(e,t,n,i,this.machineId);a.binaryType=`arraybuffer`,this.socket=a,a.addEventListener(`open`,()=>{this.socket===a&&(this.terminalReconnectDelay=LN,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*zN,RN),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=qN(await YN(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=tP(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 re(XN(this)),r=new ie;n.loadAddon(r),n.open(t);let i=tP(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=ZN(this))}syncTerminalBackground(){let e=$N(this.bgOpacity),t=eP(QN(this,`--pi-terminal-bg`,`#05070a`),e);this.style.setProperty(BN,t),this.style.setProperty(VN,`${String(e)}%`)}sendTerminalInput(e){let t=JN(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=LN;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(GN(e)){let t=this.cancellingRunIds.includes(e.id);return g`
|
|
6084
|
+
`}};B([x({attribute:!1})],MN.prototype,`modes`,void 0),B([x({type:Boolean})],MN.prototype,`refocusOnClick`,void 0),B([x({attribute:!1})],MN.prototype,`onInput`,void 0),MN=B([b(`terminal-soft-keys`)],MN);function NN(e,t){return Math.hypot(t.clientX-e.clientX,t.clientY-e.clientY)>AN}var PN=oe({TerminalPanel:()=>Z,filterTerminalInput:()=>YN,terminalBackgroundWithOpacity:()=>tP}),FN={allowTransparency:!0,cursorBlink:!0,convertEol:!0,fontFamily:`ui-monospace, SFMono-Regular, Menlo, Consolas, monospace`,fontSize:13},IN={cols:100,rows:30},LN=1e3,RN=500,zN=5e3,BN=1.6,VN=`--pi-terminal-effective-bg`,HN=`--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=vN(),this.suppressTerminalInput=!1,this.terminalReconnectDelay=RN,this.softKeysDefaultEnvironmentMedia=gN(),this.softKeysPreferenceStored=yN(),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=_N(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([xs.terminals(e.projectId,e.id,this.machineId),xs.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=sh(this.terminals,{targetTerminalId:this.selectedTerminalId});t===void 0&&this.selectedTerminalId!==void 0&&(t=ch(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()??IN,i=await xs.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 xs.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=ch(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 xs.listCommandRuns({projectId:e.projectId,workspaceId:e.id},this.machineId);this.commandRuns=t,this.cancellingRunIds=this.cancellingRunIds.filter(e=>t.some(t=>t.id===e&&KN(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()},LN);return}!e&&this.commandRunPollTimer!==void 0&&(window.clearInterval(this.commandRunPollTimer),this.commandRunPollTimer=void 0)}hasPendingCommandRuns(e=this.commandRuns){return e.some(KN)}async cancelCommandRun(e){if(!(!KN(e)||this.cancellingRunIds.includes(e.id))){this.error=void 0,this.cancellingRunIds=[...this.cancellingRunIds,e.id];try{await xs.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 xs.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 re(ZN(this)),r=new ie;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=As(e,t,n,i,this.machineId);a.binaryType=`arraybuffer`,this.socket=a,a.addEventListener(`open`,()=>{this.socket===a&&(this.terminalReconnectDelay=RN,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*BN,zN),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=JN(await XN(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=nP(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 re(ZN(this)),r=new ie;n.loadAddon(r),n.open(t);let i=nP(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=QN(this))}syncTerminalBackground(){let e=eP(this.bgOpacity),t=tP($N(this,`--pi-terminal-bg`,`#05070a`),e);this.style.setProperty(VN,t),this.style.setProperty(HN,`${String(e)}%`)}sendTerminalInput(e){let t=YN(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=RN;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(KN(e)){let t=this.cancellingRunIds.includes(e.id);return g`
|
|
6055
6085
|
<section class="command-run-notice running">
|
|
6056
6086
|
<div>
|
|
6057
6087
|
<strong>${e.title}</strong>
|
|
@@ -6063,13 +6093,13 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
6063
6093
|
`}if(t?.exited===!0){let n=this.continuingTerminalIds.includes(t.id);return g`
|
|
6064
6094
|
<section class=${`command-run-notice ${e.status}`}>
|
|
6065
6095
|
<div>
|
|
6066
|
-
<strong>${
|
|
6096
|
+
<strong>${qN(e)}</strong>
|
|
6067
6097
|
<p>Output is preserved. Continue in a shell to inspect or run follow-up commands.</p>
|
|
6068
6098
|
<code>${e.command}</code>
|
|
6069
6099
|
</div>
|
|
6070
6100
|
<button ?disabled=${n} @click=${()=>{this.continueTerminal(t.id)}}>${n?`Starting shell…`:`Continue in shell`}</button>
|
|
6071
6101
|
</section>
|
|
6072
|
-
`}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=
|
|
6102
|
+
`}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=tN(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=UN(e.scrollTop,n,r),t.scrollLeft=UN(e.scrollLeft,i,a)}async copyAllSnapshotText(){let e=this.copySnapshot?.text??``;if(e===``){this.copyStatus=`No terminal output to copy.`;return}this.copyStatus=await NC(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`
|
|
6073
6103
|
<button
|
|
6074
6104
|
type="button"
|
|
6075
6105
|
class=${e?`copy-mode-toggle selected`:`copy-mode-toggle`}
|
|
@@ -6092,7 +6122,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
6092
6122
|
${this.copyToolbarReplacesSoftKeys()?null:this.renderCopyModeToolbar()}
|
|
6093
6123
|
<div class="terminal-copy-layers">
|
|
6094
6124
|
<pre class="terminal-copy-content" aria-hidden="true">${e.lines.map((e,t)=>g`${t===0?null:`
|
|
6095
|
-
`}${e.runs.map(e=>g`<span style=${
|
|
6125
|
+
`}${e.runs.map(e=>g`<span style=${YM(GN(e.style))}>${e.text}</span>`)}`)}</pre>
|
|
6096
6126
|
<textarea
|
|
6097
6127
|
class="terminal-copy-selector"
|
|
6098
6128
|
readonly
|
|
@@ -6107,7 +6137,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
6107
6137
|
></textarea>
|
|
6108
6138
|
</div>
|
|
6109
6139
|
</section>
|
|
6110
|
-
`}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,
|
|
6140
|
+
`}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,xN(this.softKeysEnabled),this.scheduleFitAndNotify())}renderSoftKeysToggle(){return this.shouldShowSoftKeysToggle()?g`
|
|
6111
6141
|
<button
|
|
6112
6142
|
type="button"
|
|
6113
6143
|
class=${this.softKeysEnabled?`soft-keys-toggle selected`:`soft-keys-toggle`}
|
|
@@ -6228,32 +6258,32 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
6228
6258
|
.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); }
|
|
6229
6259
|
.muted { margin: 10px; color: var(--pi-muted); }
|
|
6230
6260
|
.xterm { height: 100%; }
|
|
6231
|
-
`}};B([x({attribute:!1})],Z.prototype,`workspace`,void 0),B([x()],Z.prototype,`machineId`,void 0),B([x({attribute:!1})],Z.prototype,`selectedTerminalId`,void 0),B([x({type:Boolean})],Z.prototype,`autoStart`,void 0),B([x({type:Number})],Z.prototype,`fontSize`,void 0),B([x({type:Number})],Z.prototype,`bgOpacity`,void 0),B([x({attribute:!1})],Z.prototype,`onSelectTerminal`,void 0),B([x({attribute:!1})],Z.prototype,`onStarted`,void 0),B([x({attribute:!1})],Z.prototype,`onInput`,void 0),B([C(`.terminal-host`)],Z.prototype,`terminalHost`,void 0),B([C(`.terminal-copy-content`)],Z.prototype,`terminalCopyContent`,void 0),B([C(`.terminal-copy-selector`)],Z.prototype,`terminalCopySelector`,void 0),B([S()],Z.prototype,`terminals`,void 0),B([S()],Z.prototype,`commandRuns`,void 0),B([S()],Z.prototype,`selectedId`,void 0),B([S()],Z.prototype,`loading`,void 0),B([S()],Z.prototype,`error`,void 0),B([S()],Z.prototype,`visible`,void 0),B([S()],Z.prototype,`cancellingRunIds`,void 0),B([S()],Z.prototype,`continuingTerminalIds`,void 0),B([S()],Z.prototype,`defaultSoftKeysEnvironment`,void 0),B([S()],Z.prototype,`softKeysEnabled`,void 0),B([S()],Z.prototype,`copySnapshot`,void 0),B([S()],Z.prototype,`copyStatus`,void 0),Z=B([b(`terminal-panel`)],Z);function
|
|
6261
|
+
`}};B([x({attribute:!1})],Z.prototype,`workspace`,void 0),B([x()],Z.prototype,`machineId`,void 0),B([x({attribute:!1})],Z.prototype,`selectedTerminalId`,void 0),B([x({type:Boolean})],Z.prototype,`autoStart`,void 0),B([x({type:Number})],Z.prototype,`fontSize`,void 0),B([x({type:Number})],Z.prototype,`bgOpacity`,void 0),B([x({attribute:!1})],Z.prototype,`onSelectTerminal`,void 0),B([x({attribute:!1})],Z.prototype,`onStarted`,void 0),B([x({attribute:!1})],Z.prototype,`onInput`,void 0),B([C(`.terminal-host`)],Z.prototype,`terminalHost`,void 0),B([C(`.terminal-copy-content`)],Z.prototype,`terminalCopyContent`,void 0),B([C(`.terminal-copy-selector`)],Z.prototype,`terminalCopySelector`,void 0),B([S()],Z.prototype,`terminals`,void 0),B([S()],Z.prototype,`commandRuns`,void 0),B([S()],Z.prototype,`selectedId`,void 0),B([S()],Z.prototype,`loading`,void 0),B([S()],Z.prototype,`error`,void 0),B([S()],Z.prototype,`visible`,void 0),B([S()],Z.prototype,`cancellingRunIds`,void 0),B([S()],Z.prototype,`continuingTerminalIds`,void 0),B([S()],Z.prototype,`defaultSoftKeysEnvironment`,void 0),B([S()],Z.prototype,`softKeysEnabled`,void 0),B([S()],Z.prototype,`copySnapshot`,void 0),B([S()],Z.prototype,`copyStatus`,void 0),Z=B([b(`terminal-panel`)],Z);function UN(e,t,n){return t<=0||n<=0?0:Math.min(1,Math.max(0,e/t))*n}function WN(e){return/^#[\da-f]{6}$/i.test(e)?`${e}80`:`color-mix(in srgb, ${e} 50%, transparent)`}function GN(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?WN(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 KN(e){return e.status===`queued`||e.status===`running`}function qN(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 JN(e){let t=JSON.parse(e);if(!iP(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 YN(e){return e.replaceAll(`\x1B[I`,``).replaceAll(`\x1B[O`,``)}async function XN(e){return typeof e==`string`?e:e instanceof ArrayBuffer?new TextDecoder().decode(e):e instanceof Blob?await e.text():String(e)}function ZN(e){let t=FN;return e instanceof Z?{...t,fontSize:e.fontSize,theme:QN(e)}:{...t,theme:QN(e)}}function QN(e){let t=tP($N(e,`--pi-terminal-bg`,`#05070a`),e instanceof Z?e.bgOpacity:100);return{...eN,background:t,foreground:$N(e,`--pi-terminal-text`,`#e6edf3`),cursor:$N(e,`--pi-accent`,`#58a6ff`),selectionBackground:$N(e,`--pi-terminal-selection`,`#264f78`)}}function $N(e,t,n){let r=getComputedStyle(e).getPropertyValue(t).trim();return r===``?n:r}function eP(e){return Math.max(0,Math.min(100,e))}function tP(e,t){let n=eP(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 nP(e){if(!(e===void 0||!rP(e.cols,e.rows)))return{cols:Math.floor(e.cols),rows:Math.floor(e.rows)}}function rP(e,t){return Number.isFinite(e)&&Number.isFinite(t)&&e>0&&t>0}function iP(e){return typeof e==`object`&&!!e}var aP=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=oP(this.machines),t=sP(this.machine),n=lP(this.project),r=dP(this.workspace),i=pP(this.session);return g`
|
|
6232
6262
|
<nav class=${this.contextBarClass()} aria-label="Current location">
|
|
6233
6263
|
<span class="context-bar-label">Location</span>
|
|
6234
6264
|
<ol class="context-items" @scroll=${this.onContextScroll}>
|
|
6235
6265
|
${e?g`
|
|
6236
6266
|
<li class="context-item">
|
|
6237
|
-
<button type="button" class=${this.machine===void 0?`context-chip empty`:`context-chip`} title=${
|
|
6267
|
+
<button type="button" class=${this.machine===void 0?`context-chip empty`:`context-chip`} title=${cP(this.machine)} aria-label=${`Machine: ${t}. Open machine selection.`} @click=${()=>{this.onOpenSection?.(`machines`)}}>
|
|
6238
6268
|
<span class="context-kind">Machine</span>
|
|
6239
6269
|
<span class="context-value">${t}</span>
|
|
6240
6270
|
</button>
|
|
6241
6271
|
</li>
|
|
6242
6272
|
`:null}
|
|
6243
6273
|
<li class="context-item">
|
|
6244
|
-
<button type="button" class=${this.project===void 0?`context-chip empty`:`context-chip`} title=${
|
|
6274
|
+
<button type="button" class=${this.project===void 0?`context-chip empty`:`context-chip`} title=${uP(this.project)} aria-label=${`Project: ${n}. Open project selection.`} @click=${()=>{this.onOpenSection?.(`projects`)}}>
|
|
6245
6275
|
<span class="context-kind">Project</span>
|
|
6246
6276
|
<span class="context-value">${n}</span>
|
|
6247
6277
|
</button>
|
|
6248
6278
|
</li>
|
|
6249
6279
|
<li class="context-item">
|
|
6250
|
-
<button type="button" class=${this.workspace===void 0?`context-chip empty`:`context-chip`} title=${
|
|
6280
|
+
<button type="button" class=${this.workspace===void 0?`context-chip empty`:`context-chip`} title=${fP(this.workspace)} aria-label=${`Workspace: ${r}. Open workspace selection.`} @click=${()=>{this.onOpenSection?.(`workspaces`)}}>
|
|
6251
6281
|
<span class="context-kind">Workspace</span>
|
|
6252
6282
|
<span class="context-value">${r}</span>
|
|
6253
6283
|
</button>
|
|
6254
6284
|
</li>
|
|
6255
6285
|
<li class="context-item">
|
|
6256
|
-
<button type="button" class=${this.session===void 0?`context-chip empty`:`context-chip`} title=${
|
|
6286
|
+
<button type="button" class=${this.session===void 0?`context-chip empty`:`context-chip`} title=${mP(this.session)} aria-label=${`Session: ${i}. Open session selection.`} @click=${()=>{this.onOpenSection?.(`sessions`)}}>
|
|
6257
6287
|
<span class="context-kind">Session</span>
|
|
6258
6288
|
<span class="context-value">${i}</span>
|
|
6259
6289
|
</button>
|
|
@@ -6301,7 +6331,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
6301
6331
|
.context-kind { display: none; }
|
|
6302
6332
|
.context-value { min-width: 0; overflow: visible; text-overflow: clip; white-space: nowrap; }
|
|
6303
6333
|
button { cursor: pointer; }
|
|
6304
|
-
`}};B([x({attribute:!1})],
|
|
6334
|
+
`}};B([x({attribute:!1})],aP.prototype,`machines`,void 0),B([x({attribute:!1})],aP.prototype,`machine`,void 0),B([x({attribute:!1})],aP.prototype,`project`,void 0),B([x({attribute:!1})],aP.prototype,`workspace`,void 0),B([x({attribute:!1})],aP.prototype,`session`,void 0),B([x({attribute:!1})],aP.prototype,`refreshControl`,void 0),B([x({attribute:!1})],aP.prototype,`onOpenSection`,void 0),B([x({attribute:!1})],aP.prototype,`onShowActions`,void 0),B([x({type:Boolean})],aP.prototype,`activityRailOpen`,void 0),B([x({attribute:!1})],aP.prototype,`onToggleActivityRail`,void 0),B([C(`.context-items`)],aP.prototype,`contextItems`,void 0),B([S()],aP.prototype,`canScrollLeft`,void 0),B([S()],aP.prototype,`canScrollRight`,void 0),aP=B([b(`app-context-bar`)],aP);function oP(e){return e.length>1}function sP(e){return e===void 0?`No machine`:`${e.name}${e.kind===`remote`?` · remote`:``}`}function cP(e){return e===void 0?`No machine selected`:e.baseUrl??e.name}function lP(e){return e?.name??`No project`}function uP(e){return e===void 0?`No project selected`:`${e.name} — ${e.path}`}function dP(e){return e===void 0?`No workspace`:`${e.label}${e.isMain?` · main`:``} · ${e.path}`}function fP(e){return e===void 0?`No workspace selected`:`${e.label}${e.isMain?` · main`:``} — ${e.path}`}function pP(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`:Xx(e.id)}function mP(e){return e===void 0?`No session selected`:e.path}var hP=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`
|
|
6305
6335
|
<div class=${this.frameClass()}>
|
|
6306
6336
|
<div class="mobile-tabs" @scroll=${this.onMobileTabsScroll}>
|
|
6307
6337
|
${this.tabs.map(t=>{let n=this.selectedView===t.id;return g`
|
|
@@ -6340,12 +6370,12 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
6340
6370
|
.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; }
|
|
6341
6371
|
.tab-badge { min-width: 13px; padding: 0 4px; font-size: 10px; line-height: 13px; }
|
|
6342
6372
|
}
|
|
6343
|
-
`}};B([x({attribute:!1})],
|
|
6373
|
+
`}};B([x({attribute:!1})],hP.prototype,`tabs`,void 0),B([x({attribute:!1})],hP.prototype,`selectedView`,void 0),B([x({attribute:!1})],hP.prototype,`onSelect`,void 0),B([C(`.mobile-tabs`)],hP.prototype,`mobileTabs`,void 0),B([S()],hP.prototype,`canScrollLeft`,void 0),B([S()],hP.prototype,`canScrollRight`,void 0),hP=B([b(`app-mobile-main-tabs`)],hP);var gP=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=_P(e,this.statuses),n=e.name;return g`
|
|
6344
6374
|
<div class="machine-switcher">
|
|
6345
6375
|
<button
|
|
6346
6376
|
type="button"
|
|
6347
6377
|
class="machine-switcher-button"
|
|
6348
|
-
title=${
|
|
6378
|
+
title=${yP(e)}
|
|
6349
6379
|
aria-label=${this.machineSwitcherAriaLabel(e)}
|
|
6350
6380
|
aria-expanded=${String(this.open)}
|
|
6351
6381
|
@click=${e=>{this.toggleMenu(e.currentTarget)}}
|
|
@@ -6356,7 +6386,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
6356
6386
|
<span class="machine-switcher-kicker">Machine</span>
|
|
6357
6387
|
<span class="machine-switcher-label">${n}</span>
|
|
6358
6388
|
</span>
|
|
6359
|
-
<span class=${`machine-status ${t}`}>${
|
|
6389
|
+
<span class=${`machine-status ${t}`}>${vP(t)}</span>
|
|
6360
6390
|
<span class="machine-chevron" aria-hidden="true">▾</span>
|
|
6361
6391
|
</button>
|
|
6362
6392
|
${this.open?g`
|
|
@@ -6365,18 +6395,18 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
6365
6395
|
</div>
|
|
6366
6396
|
`:null}
|
|
6367
6397
|
</div>
|
|
6368
|
-
`}renderMachineOption(e){let t=this.selected?.id===e.id,n=
|
|
6398
|
+
`}renderMachineOption(e){let t=this.selected?.id===e.id,n=_P(e,this.statuses),r=Qb(e)&&this.onRemove!==void 0,i=this.openActionsMachineId===e.id;return g`
|
|
6369
6399
|
<div class=${`machine-option ${t?`selected`:``} ${r?``:`no-actions`}`}>
|
|
6370
6400
|
<button
|
|
6371
6401
|
type="button"
|
|
6372
6402
|
class="machine-option-main"
|
|
6373
|
-
title=${
|
|
6403
|
+
title=${yP(e)}
|
|
6374
6404
|
data-machine-id=${e.id}
|
|
6375
6405
|
@click=${()=>{this.select(e)}}
|
|
6376
6406
|
@keydown=${e=>{this.handleMachineOptionKeydown(e)}}
|
|
6377
6407
|
>
|
|
6378
6408
|
<span class="machine-option-name">${this.renderActivity(e)}<span>${e.name}</span></span>
|
|
6379
|
-
<small>${e.kind===`local`?`Local Pi WebUI`:e.baseUrl??`Remote Pi WebUI`} · ${
|
|
6409
|
+
<small>${e.kind===`local`?`Local Pi WebUI`:e.baseUrl??`Remote Pi WebUI`} · ${vP(n)}</small>
|
|
6380
6410
|
</button>
|
|
6381
6411
|
${r?g`
|
|
6382
6412
|
<div class="machine-option-actions">
|
|
@@ -6396,7 +6426,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
6396
6426
|
</div>
|
|
6397
6427
|
`:null}
|
|
6398
6428
|
</div>
|
|
6399
|
-
`}renderActivity(e){let t=
|
|
6429
|
+
`}renderActivity(e){let t=_P(e,this.statuses);if(t===`offline`||t===`error`)return;let n=au(this.activities[e.id]);return Fb(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=bP(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=bP(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=jb(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`
|
|
6400
6430
|
:host { min-width: 0; display: block; }
|
|
6401
6431
|
.machine-switcher { min-width: 0; }
|
|
6402
6432
|
.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; }
|
|
@@ -6429,10 +6459,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
6429
6459
|
.machine-option-actions-panel button:hover, .machine-option-actions-panel button:focus-visible { background: var(--pi-selection-bg); }
|
|
6430
6460
|
.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); }
|
|
6431
6461
|
@keyframes pulse { 0%, 100% { opacity: .55; } 50% { opacity: 1; } }
|
|
6432
|
-
`}};B([x({attribute:!1})],
|
|
6462
|
+
`}};B([x({attribute:!1})],gP.prototype,`machines`,void 0),B([x({attribute:!1})],gP.prototype,`selected`,void 0),B([x({attribute:!1})],gP.prototype,`statuses`,void 0),B([x({attribute:!1})],gP.prototype,`activities`,void 0),B([x({attribute:!1})],gP.prototype,`onSelect`,void 0),B([x({attribute:!1})],gP.prototype,`onRemove`,void 0),B([x({attribute:!1})],gP.prototype,`onFocusNextSection`,void 0),B([x({attribute:!1})],gP.prototype,`onCancelKeyboardNavigation`,void 0),B([S()],gP.prototype,`open`,void 0),B([S()],gP.prototype,`menuStyle`,void 0),B([S()],gP.prototype,`openActionsMachineId`,void 0),B([S()],gP.prototype,`actionMenuStyle`,void 0),gP=B([b(`machine-switcher`)],gP);function _P(e,t){return t[e.id]?.status??e.status??`unknown`}function vP(e){return e===`online`?`online`:e===`offline`?`offline`:e===`error`?`error`:`unknown`}function yP(e){return e.baseUrl??e.name}function bP(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: ${xP(t.bottom)};`,`left: ${xP(r)};`,`width: ${xP(n)};`,`max-height: ${xP(i)};`].join(` `)}function xP(e){return`${String(Math.round(e))}px`}var SP=[{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`
|
|
6433
6463
|
<header>
|
|
6434
6464
|
<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>
|
|
6435
|
-
${
|
|
6465
|
+
${EP(this.machines)?g`
|
|
6436
6466
|
<machine-switcher
|
|
6437
6467
|
.machines=${this.machines}
|
|
6438
6468
|
.selected=${this.selectedMachine}
|
|
@@ -6449,7 +6479,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
6449
6479
|
<button title="Show Actions" aria-label="Show Actions" @click=${()=>{this.onShowActions?.()}}>Actions</button>
|
|
6450
6480
|
</div>
|
|
6451
6481
|
</header>
|
|
6452
|
-
${this.compact&&
|
|
6482
|
+
${this.compact&&EP(this.machines)?g`
|
|
6453
6483
|
<machine-list
|
|
6454
6484
|
.machines=${this.machines}
|
|
6455
6485
|
.selected=${this.selectedMachine}
|
|
@@ -6546,9 +6576,9 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
6546
6576
|
.onCancelKeyboardNavigation=${()=>{this.cancelKeyboardNavigation()}}
|
|
6547
6577
|
></session-list>
|
|
6548
6578
|
<footer class="resource-underbar" aria-label="Resources">
|
|
6549
|
-
${
|
|
6579
|
+
${SP.map(e=>CP(e,e.id===`models`?()=>{this.onOpenModels?.()}:e.id===`skills`?()=>{this.onOpenSkills?.()}:()=>{this.onOpenPlugins?.()},this.skillsEnabled,this.pluginsEnabled))}
|
|
6550
6580
|
</footer>
|
|
6551
|
-
`}async focusNavigableSection(e){return e!==void 0&&await e.focusSelectedOrFirst()}focusPreviousFrom(e){let t=
|
|
6581
|
+
`}async focusNavigableSection(e){return e!==void 0&&await e.focusSelectedOrFirst()}focusPreviousFrom(e){let t=DP(e,this.machines);t!==void 0&&this.onFocusNavigationTarget?.(t)}focusNextFrom(e){this.onFocusNavigationTarget?.(OP(e,this.machines))}cancelKeyboardNavigation(){this.onCancelKeyboardNavigation?.()}static{this.styles=h`
|
|
6552
6582
|
:host { display: flex; flex-direction: column; min-height: 0; overflow: hidden; }
|
|
6553
6583
|
:host([compact]) { flex: 1 1 auto; }
|
|
6554
6584
|
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); }
|
|
@@ -6580,12 +6610,12 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
6580
6610
|
:host([compact]) workspace-list[collapsed],
|
|
6581
6611
|
:host([compact]) session-list[collapsed] { flex: 0 0 auto; min-height: auto; overflow: hidden; }
|
|
6582
6612
|
button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
|
|
6583
|
-
`}};B([x({attribute:!1})],Q.prototype,`machines`,void 0),B([x({attribute:!1})],Q.prototype,`selectedMachine`,void 0),B([x({attribute:!1})],Q.prototype,`machineStatuses`,void 0),B([x({attribute:!1})],Q.prototype,`machineActivities`,void 0),B([x({attribute:!1})],Q.prototype,`projects`,void 0),B([x({attribute:!1})],Q.prototype,`selectedProject`,void 0),B([x({attribute:!1})],Q.prototype,`workspaces`,void 0),B([x({attribute:!1})],Q.prototype,`selectedWorkspace`,void 0),B([x({attribute:!1})],Q.prototype,`sessions`,void 0),B([x({attribute:!1})],Q.prototype,`projectSessions`,void 0),B([x({attribute:!1})],Q.prototype,`selectedSession`,void 0),B([x({attribute:!1})],Q.prototype,`workspaceActivities`,void 0),B([x({attribute:!1})],Q.prototype,`sessionActivities`,void 0),B([x({attribute:!1})],Q.prototype,`sessionStatuses`,void 0),B([x({attribute:!1})],Q.prototype,`sendingPrompts`,void 0),B([x({attribute:!1})],Q.prototype,`unreadSessionIds`,void 0),B([x({attribute:!1})],Q.prototype,`workspacesByProjectId`,void 0),B([x({attribute:!1})],Q.prototype,`deletingWorkspaceIds`,void 0),B([x({attribute:!1})],Q.prototype,`workspaceLabelItems`,void 0),B([x({type:String})],Q.prototype,`version`,void 0),B([x({attribute:!1})],Q.prototype,`refreshControl`,void 0),B([x({type:Boolean,reflect:!0})],Q.prototype,`collapsible`,void 0),B([x({type:Boolean,reflect:!0})],Q.prototype,`compact`,void 0),B([x({type:Boolean})],Q.prototype,`machinesCollapsed`,void 0),B([x({type:Boolean})],Q.prototype,`projectsCollapsed`,void 0),B([x({type:Boolean})],Q.prototype,`workspacesCollapsed`,void 0),B([x({type:Boolean})],Q.prototype,`sessionsCollapsed`,void 0),B([x({type:Number})],Q.prototype,`startingSessionCount`,void 0),B([x({type:Boolean})],Q.prototype,`canStartSession`,void 0),B([x({type:Boolean})],Q.prototype,`canDeleteArchivedSessions`,void 0),B([x({type:Boolean})],Q.prototype,`canReloadSessions`,void 0),B([x({type:Boolean})],Q.prototype,`canReorderSessions`,void 0),B([x({type:Boolean})],Q.prototype,`canCleanupSessions`,void 0),B([x({type:Boolean})],Q.prototype,`authoritativeSessionPersistence`,void 0),B([x({type:String})],Q.prototype,`archivedDeleteUnavailableMessage`,void 0),B([x({type:String})],Q.prototype,`cleanupUnavailableMessage`,void 0),B([x({attribute:!1})],Q.prototype,`onShowActions`,void 0),B([x({type:Boolean})],Q.prototype,`skillsEnabled`,void 0),B([x({type:Boolean})],Q.prototype,`pluginsEnabled`,void 0),B([x({attribute:!1})],Q.prototype,`onOpenModels`,void 0),B([x({attribute:!1})],Q.prototype,`onOpenSkills`,void 0),B([x({attribute:!1})],Q.prototype,`onOpenPlugins`,void 0),B([x({attribute:!1})],Q.prototype,`onToggleMachines`,void 0),B([x({attribute:!1})],Q.prototype,`onToggleProjects`,void 0),B([x({attribute:!1})],Q.prototype,`onToggleWorkspaces`,void 0),B([x({attribute:!1})],Q.prototype,`onToggleSessions`,void 0),B([x({attribute:!1})],Q.prototype,`onAddProject`,void 0),B([x({attribute:!1})],Q.prototype,`onOpenProjectBrowser`,void 0),B([x({attribute:!1})],Q.prototype,`onOpenSessionBrowser`,void 0),B([x({attribute:!1})],Q.prototype,`onSelectProject`,void 0),B([x({attribute:!1})],Q.prototype,`onCloseProject`,void 0),B([x({attribute:!1})],Q.prototype,`onCloseProjectTree`,void 0),B([x({attribute:!1})],Q.prototype,`onPinProject`,void 0),B([x({attribute:!1})],Q.prototype,`onUnpinProject`,void 0),B([x({attribute:!1})],Q.prototype,`onShowProjectStatistics`,void 0),B([x({type:Boolean})],Q.prototype,`projectStatisticsAvailable`,void 0),B([x({attribute:!1})],Q.prototype,`onSelectWorkspace`,void 0),B([x({attribute:!1})],Q.prototype,`onDeleteWorkspace`,void 0),B([x({attribute:!1})],Q.prototype,`onStartSession`,void 0),B([x({attribute:!1})],Q.prototype,`onSelectSession`,void 0),B([x({attribute:!1})],Q.prototype,`onRenameSessionStart`,void 0),B([x({attribute:!1})],Q.prototype,`onRenameSession`,void 0),B([x({attribute:!1})],Q.prototype,`onArchiveSession`,void 0),B([x({attribute:!1})],Q.prototype,`onArchiveSessionWithDescendants`,void 0),B([x({attribute:!1})],Q.prototype,`onArchiveSessions`,void 0),B([x({attribute:!1})],Q.prototype,`onRestoreSession`,void 0),B([x({attribute:!1})],Q.prototype,`onDeleteCachedNewSession`,void 0),B([x({attribute:!1})],Q.prototype,`onDeleteArchivedSession`,void 0),B([x({attribute:!1})],Q.prototype,`onDeleteArchivedSessions`,void 0),B([x({attribute:!1})],Q.prototype,`onDetachParentSession`,void 0),B([x({attribute:!1})],Q.prototype,`onReloadSession`,void 0),B([x({attribute:!1})],Q.prototype,`onReorderSession`,void 0),B([x({attribute:!1})],Q.prototype,`onPinSession`,void 0),B([x({attribute:!1})],Q.prototype,`onUnpinSession`,void 0),B([x({attribute:!1})],Q.prototype,`onCleanupSessions`,void 0),B([x({attribute:!1})],Q.prototype,`onArchivedCollapsed`,void 0),B([x({attribute:!1})],Q.prototype,`onSelectMachine`,void 0),B([x({attribute:!1})],Q.prototype,`onRemoveMachine`,void 0),B([x({attribute:!1})],Q.prototype,`onFocusNavigationTarget`,void 0),B([x({attribute:!1})],Q.prototype,`onCancelKeyboardNavigation`,void 0),B([C(`machine-list`)],Q.prototype,`machineList`,void 0),B([C(`machine-switcher`)],Q.prototype,`machineSwitcher`,void 0),B([C(`project-list`)],Q.prototype,`projectList`,void 0),B([C(`workspace-list`)],Q.prototype,`workspaceList`,void 0),B([C(`session-list`)],Q.prototype,`sessionList`,void 0),Q=B([b(`app-navigation-panel`)],Q);function
|
|
6584
|
-
<button type="button" ?disabled=${!
|
|
6585
|
-
${
|
|
6613
|
+
`}};B([x({attribute:!1})],Q.prototype,`machines`,void 0),B([x({attribute:!1})],Q.prototype,`selectedMachine`,void 0),B([x({attribute:!1})],Q.prototype,`machineStatuses`,void 0),B([x({attribute:!1})],Q.prototype,`machineActivities`,void 0),B([x({attribute:!1})],Q.prototype,`projects`,void 0),B([x({attribute:!1})],Q.prototype,`selectedProject`,void 0),B([x({attribute:!1})],Q.prototype,`workspaces`,void 0),B([x({attribute:!1})],Q.prototype,`selectedWorkspace`,void 0),B([x({attribute:!1})],Q.prototype,`sessions`,void 0),B([x({attribute:!1})],Q.prototype,`projectSessions`,void 0),B([x({attribute:!1})],Q.prototype,`selectedSession`,void 0),B([x({attribute:!1})],Q.prototype,`workspaceActivities`,void 0),B([x({attribute:!1})],Q.prototype,`sessionActivities`,void 0),B([x({attribute:!1})],Q.prototype,`sessionStatuses`,void 0),B([x({attribute:!1})],Q.prototype,`sendingPrompts`,void 0),B([x({attribute:!1})],Q.prototype,`unreadSessionIds`,void 0),B([x({attribute:!1})],Q.prototype,`workspacesByProjectId`,void 0),B([x({attribute:!1})],Q.prototype,`deletingWorkspaceIds`,void 0),B([x({attribute:!1})],Q.prototype,`workspaceLabelItems`,void 0),B([x({type:String})],Q.prototype,`version`,void 0),B([x({attribute:!1})],Q.prototype,`refreshControl`,void 0),B([x({type:Boolean,reflect:!0})],Q.prototype,`collapsible`,void 0),B([x({type:Boolean,reflect:!0})],Q.prototype,`compact`,void 0),B([x({type:Boolean})],Q.prototype,`machinesCollapsed`,void 0),B([x({type:Boolean})],Q.prototype,`projectsCollapsed`,void 0),B([x({type:Boolean})],Q.prototype,`workspacesCollapsed`,void 0),B([x({type:Boolean})],Q.prototype,`sessionsCollapsed`,void 0),B([x({type:Number})],Q.prototype,`startingSessionCount`,void 0),B([x({type:Boolean})],Q.prototype,`canStartSession`,void 0),B([x({type:Boolean})],Q.prototype,`canDeleteArchivedSessions`,void 0),B([x({type:Boolean})],Q.prototype,`canReloadSessions`,void 0),B([x({type:Boolean})],Q.prototype,`canReorderSessions`,void 0),B([x({type:Boolean})],Q.prototype,`canCleanupSessions`,void 0),B([x({type:Boolean})],Q.prototype,`authoritativeSessionPersistence`,void 0),B([x({type:String})],Q.prototype,`archivedDeleteUnavailableMessage`,void 0),B([x({type:String})],Q.prototype,`cleanupUnavailableMessage`,void 0),B([x({attribute:!1})],Q.prototype,`onShowActions`,void 0),B([x({type:Boolean})],Q.prototype,`skillsEnabled`,void 0),B([x({type:Boolean})],Q.prototype,`pluginsEnabled`,void 0),B([x({attribute:!1})],Q.prototype,`onOpenModels`,void 0),B([x({attribute:!1})],Q.prototype,`onOpenSkills`,void 0),B([x({attribute:!1})],Q.prototype,`onOpenPlugins`,void 0),B([x({attribute:!1})],Q.prototype,`onToggleMachines`,void 0),B([x({attribute:!1})],Q.prototype,`onToggleProjects`,void 0),B([x({attribute:!1})],Q.prototype,`onToggleWorkspaces`,void 0),B([x({attribute:!1})],Q.prototype,`onToggleSessions`,void 0),B([x({attribute:!1})],Q.prototype,`onAddProject`,void 0),B([x({attribute:!1})],Q.prototype,`onOpenProjectBrowser`,void 0),B([x({attribute:!1})],Q.prototype,`onOpenSessionBrowser`,void 0),B([x({attribute:!1})],Q.prototype,`onSelectProject`,void 0),B([x({attribute:!1})],Q.prototype,`onCloseProject`,void 0),B([x({attribute:!1})],Q.prototype,`onCloseProjectTree`,void 0),B([x({attribute:!1})],Q.prototype,`onPinProject`,void 0),B([x({attribute:!1})],Q.prototype,`onUnpinProject`,void 0),B([x({attribute:!1})],Q.prototype,`onShowProjectStatistics`,void 0),B([x({type:Boolean})],Q.prototype,`projectStatisticsAvailable`,void 0),B([x({attribute:!1})],Q.prototype,`onSelectWorkspace`,void 0),B([x({attribute:!1})],Q.prototype,`onDeleteWorkspace`,void 0),B([x({attribute:!1})],Q.prototype,`onStartSession`,void 0),B([x({attribute:!1})],Q.prototype,`onSelectSession`,void 0),B([x({attribute:!1})],Q.prototype,`onRenameSessionStart`,void 0),B([x({attribute:!1})],Q.prototype,`onRenameSession`,void 0),B([x({attribute:!1})],Q.prototype,`onArchiveSession`,void 0),B([x({attribute:!1})],Q.prototype,`onArchiveSessionWithDescendants`,void 0),B([x({attribute:!1})],Q.prototype,`onArchiveSessions`,void 0),B([x({attribute:!1})],Q.prototype,`onRestoreSession`,void 0),B([x({attribute:!1})],Q.prototype,`onDeleteCachedNewSession`,void 0),B([x({attribute:!1})],Q.prototype,`onDeleteArchivedSession`,void 0),B([x({attribute:!1})],Q.prototype,`onDeleteArchivedSessions`,void 0),B([x({attribute:!1})],Q.prototype,`onDetachParentSession`,void 0),B([x({attribute:!1})],Q.prototype,`onReloadSession`,void 0),B([x({attribute:!1})],Q.prototype,`onReorderSession`,void 0),B([x({attribute:!1})],Q.prototype,`onPinSession`,void 0),B([x({attribute:!1})],Q.prototype,`onUnpinSession`,void 0),B([x({attribute:!1})],Q.prototype,`onCleanupSessions`,void 0),B([x({attribute:!1})],Q.prototype,`onArchivedCollapsed`,void 0),B([x({attribute:!1})],Q.prototype,`onSelectMachine`,void 0),B([x({attribute:!1})],Q.prototype,`onRemoveMachine`,void 0),B([x({attribute:!1})],Q.prototype,`onFocusNavigationTarget`,void 0),B([x({attribute:!1})],Q.prototype,`onCancelKeyboardNavigation`,void 0),B([C(`machine-list`)],Q.prototype,`machineList`,void 0),B([C(`machine-switcher`)],Q.prototype,`machineSwitcher`,void 0),B([C(`project-list`)],Q.prototype,`projectList`,void 0),B([C(`workspace-list`)],Q.prototype,`workspaceList`,void 0),B([C(`session-list`)],Q.prototype,`sessionList`,void 0),Q=B([b(`app-navigation-panel`)],Q);function CP(e,t,n,r){return g`
|
|
6614
|
+
<button type="button" ?disabled=${!wP(e.id,n,r)} title=${e.label} aria-label=${e.label} @click=${t}>
|
|
6615
|
+
${TP(e.id)}
|
|
6586
6616
|
<span>${e.label}</span>
|
|
6587
6617
|
</button>
|
|
6588
|
-
`}function
|
|
6618
|
+
`}function wP(e,t=!1,n=t){return e===`models`||e===`skills`&&t||e===`plugins`&&n}function TP(e){switch(e){case`models`:return _`
|
|
6589
6619
|
<svg class="resource-underbar-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
6590
6620
|
<rect x="4" y="4" width="16" height="16" rx="2"></rect>
|
|
6591
6621
|
<rect x="9" y="9" width="6" height="6"></rect>
|
|
@@ -6603,7 +6633,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
6603
6633
|
<path d="M6 13V8a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v5a6 6 0 0 1-12 0Z"></path>
|
|
6604
6634
|
<path d="M12 19v3"></path>
|
|
6605
6635
|
</svg>
|
|
6606
|
-
`}}function
|
|
6636
|
+
`}}function EP(e){return e.length>1}function DP(e,t){let n=kP(t);return n[n.indexOf(e)-1]}function OP(e,t){let n=kP(t);return n[n.indexOf(e)+1]??`chat`}function kP(e){return oy.filter(t=>t!==`machines`||EP(e))}var AP=new Set([`ArrowLeft`,`ArrowRight`,`Home`,`End`]),jP=420,MP=4,NP=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`
|
|
6607
6637
|
${this.renderResizeHandle()}
|
|
6608
6638
|
<button
|
|
6609
6639
|
type="button"
|
|
@@ -6633,7 +6663,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
6633
6663
|
@dblclick=${e=>{this.onResizeDoubleClick(e)}}
|
|
6634
6664
|
@keydown=${e=>{this.onResizeKeyDown(e)}}
|
|
6635
6665
|
></div>
|
|
6636
|
-
`}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)<=
|
|
6666
|
+
`}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)<=MP)&&(t.moved=!0,this.commitPanelWidth(wy(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||!AP.has(e.key))return;let t=this.resizeStartWidth();if(t===void 0)return;let n=Ty(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<=jP){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 Ey(this.side,e,this.resizeConstraints())}commitPanelWidth(e){this.onResize?.(Ey(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=Sy(this.side);return{...e,minWidth:this.minWidth??e.minWidth,maxWidth:this.maxWidth??e.maxWidth}}static{this.styles=h`
|
|
6637
6667
|
: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; }
|
|
6638
6668
|
:host([side="navigation"]) { grid-column: 2; }
|
|
6639
6669
|
:host([side="workspace"]) { grid-column: 4; }
|
|
@@ -6652,7 +6682,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
6652
6682
|
@media (max-width: 760px) {
|
|
6653
6683
|
:host([side="navigation"]) { display: none; }
|
|
6654
6684
|
}
|
|
6655
|
-
`}};B([x({reflect:!0})],
|
|
6685
|
+
`}};B([x({reflect:!0})],NP.prototype,`side`,void 0),B([x({type:Boolean,reflect:!0})],NP.prototype,`collapsed`,void 0),B([x({type:Boolean})],NP.prototype,`resizable`,void 0),B([x({type:Number})],NP.prototype,`panelWidth`,void 0),B([x({type:Number})],NP.prototype,`minWidth`,void 0),B([x({type:Number})],NP.prototype,`maxWidth`,void 0),B([x()],NP.prototype,`controls`,void 0),B([x()],NP.prototype,`resizeLabel`,void 0),B([x()],NP.prototype,`expandLabel`,void 0),B([x()],NP.prototype,`collapseLabel`,void 0),B([x({attribute:!1})],NP.prototype,`onToggle`,void 0),B([x({attribute:!1})],NP.prototype,`onResizeStart`,void 0),B([x({attribute:!1})],NP.prototype,`onResize`,void 0),B([x({attribute:!1})],NP.prototype,`onResizeEnd`,void 0),B([x({attribute:!1})],NP.prototype,`onReset`,void 0),NP=B([b(`app-panel-edge-control`)],NP);var PP=class extends y{constructor(...e){super(...e),this.onReloadClick=e=>{e.stopPropagation(),this.onReload?.()}}render(){let e=`Full page reload`;return g`
|
|
6656
6686
|
<button
|
|
6657
6687
|
class="app-refresh-button"
|
|
6658
6688
|
title=${e}
|
|
@@ -6671,7 +6701,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
6671
6701
|
:host, :host * { -webkit-user-select: none; user-select: none; }
|
|
6672
6702
|
.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; }
|
|
6673
6703
|
.app-refresh-icon { width: 18px; height: 18px; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; pointer-events: none; }
|
|
6674
|
-
`}};B([x({attribute:!1})],
|
|
6704
|
+
`}};B([x({attribute:!1})],PP.prototype,`onReload`,void 0),PP=B([b(`app-refresh-control`)],PP);var FP=[`terminal`,`git-update-manager`,`theme`,`system-prompt`,`history`,`info`],IP=`file-manager`,LP=`browser`,RP=[...FP],zP=new Set(FP),BP=`pi-webui:activity-rail-order`;function VP(){return typeof localStorage>`u`?void 0:localStorage}function HP(e){return zP.has(e)}function UP(e){if(!Array.isArray(e))return;let t=[],n=new Set;for(let r of e){if(typeof r!=`string`)return;let e=r===IP?`git-update-manager`:r;if(e!==LP){if(!HP(e)||n.has(e))return;n.add(e),t.push(e)}}if(t.length===FP.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===FP.length?r:void 0}function WP(){try{let e=VP();if(e===void 0)return;let t=e.getItem(BP);return t===null?void 0:UP(JSON.parse(t))}catch{return}}function GP(e){try{let t=VP();if(t===void 0)return;t.setItem(BP,JSON.stringify(e))}catch{}}var KP=[`terminal`,`git-update-manager`,`theme`,`system-prompt`,`history`,`info`];function qP(e){return KP.includes(e)}function JP(e){return typeof HTMLElement<`u`&&e instanceof HTMLElement}var YP=class extends y{constructor(){super(),this.terminalCount=0,this.gitUpdateManagerCount=0,this.systemPromptEnabled=!1,this.historyEnabled=!1,this.railOrder=[...RP],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(),JP(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||!qP(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(Zv))}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`
|
|
6675
6705
|
<button
|
|
6676
6706
|
type="button"
|
|
6677
6707
|
class="icon-button terminal-button"
|
|
@@ -6823,7 +6853,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
6823
6853
|
${e.badge===void 0?v:g`<span class="rail-badge" aria-hidden="true">${e.badge}</span>`}
|
|
6824
6854
|
</button>
|
|
6825
6855
|
`}renderRailContents(){return g`
|
|
6826
|
-
${(this.railOrder.length===0?[...
|
|
6856
|
+
${(this.railOrder.length===0?[...RP]:this.railOrder).map(e=>this.renderReorderableButton(e))}
|
|
6827
6857
|
${this.pluginItems.length===0?v:g`
|
|
6828
6858
|
<div class="rail-plugin-separator" role="separator"></div>
|
|
6829
6859
|
${this.pluginItems.map(e=>this.renderPluginButton(e))}
|
|
@@ -6938,7 +6968,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
6938
6968
|
.compact-rail-dialog { height: 100%; }
|
|
6939
6969
|
.compact-rail-dialog .rail { box-shadow: 8px 0 24px var(--pi-shadow); }
|
|
6940
6970
|
.compact-rail-close { margin-bottom: 2px; }
|
|
6941
|
-
`}};B([x({attribute:!1})],
|
|
6971
|
+
`}};B([x({attribute:!1})],YP.prototype,`onOpenTerminal`,void 0),B([x({attribute:!1})],YP.prototype,`onOpenGitUpdateManager`,void 0),B([x({attribute:!1})],YP.prototype,`onOpenTheme`,void 0),B([x({attribute:!1})],YP.prototype,`onOpenSystemPrompt`,void 0),B([x({attribute:!1})],YP.prototype,`onOpenHistory`,void 0),B([x({attribute:!1})],YP.prototype,`onOpenInfo`,void 0),B([x({attribute:!1})],YP.prototype,`onOpenSettings`,void 0),B([x({type:Number})],YP.prototype,`terminalCount`,void 0),B([x({type:Number})],YP.prototype,`gitUpdateManagerCount`,void 0),B([x({type:Boolean})],YP.prototype,`systemPromptEnabled`,void 0),B([x({type:Boolean})],YP.prototype,`historyEnabled`,void 0),B([x({attribute:!1})],YP.prototype,`railOrder`,void 0),B([x({attribute:!1})],YP.prototype,`onRailOrderChange`,void 0),B([x({attribute:!1})],YP.prototype,`pluginItems`,void 0),B([x({attribute:!1})],YP.prototype,`onOpenPluginActivity`,void 0),B([x({type:Boolean})],YP.prototype,`compactOpen`,void 0),B([x({attribute:!1})],YP.prototype,`onCloseCompact`,void 0),YP=B([b(`activity-rail`)],YP);var XP=(e,t,n)=>{console.warn(`Plugin activity rail contribution failed`,e,t,n)},ZP=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=Tg(this.activity,this.context,this.onReportError??XP);return g`
|
|
6942
6972
|
<dialog
|
|
6943
6973
|
class="plugin-activity-backdrop"
|
|
6944
6974
|
role="dialog"
|
|
@@ -7000,7 +7030,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
7000
7030
|
header { padding-top: max(12px, env(safe-area-inset-top)); }
|
|
7001
7031
|
.plugin-activity-body { padding-bottom: max(12px, env(safe-area-inset-bottom)); }
|
|
7002
7032
|
}
|
|
7003
|
-
`}};B([x({attribute:!1})],
|
|
7033
|
+
`}};B([x({attribute:!1})],ZP.prototype,`activity`,void 0),B([x({attribute:!1})],ZP.prototype,`context`,void 0),B([x({attribute:!1})],ZP.prototype,`onClose`,void 0),B([x({attribute:!1})],ZP.prototype,`onReportError`,void 0),B([C(`dialog.plugin-activity-backdrop`)],ZP.prototype,`nativeDialog`,void 0),B([C(`.plugin-activity-close`)],ZP.prototype,`closeButton`,void 0),ZP=B([b(`plugin-activity-dialog`)],ZP);var QP=class extends y{constructor(...e){super(...e),this.machineId=`local`,this.api=Ds,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:eF(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=rF(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=ab(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`?rb(t.bounds,n,this.viewport()):ib(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`
|
|
7004
7034
|
<div class="git-update-manager-backdrop" role="dialog" aria-modal="true" aria-label="Git Update Manager">
|
|
7005
7035
|
<section class=${this.bounds===void 0?`git-update-manager-frame`:`git-update-manager-frame git-update-manager-frame-positioned`} style=${this.frameStyle()}>
|
|
7006
7036
|
<header class="git-update-manager-header">
|
|
@@ -7034,15 +7064,15 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
7034
7064
|
></div>
|
|
7035
7065
|
</section>
|
|
7036
7066
|
</div>
|
|
7037
|
-
`}ensureWorkspaceScope(){let e=
|
|
7067
|
+
`}ensureWorkspaceScope(){let e=nF(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=Fl(e.files);return t.staged.length===0&&t.unstaged.length===0?g`<p class="git-update-manager-empty">No Git changes.</p>`:g`
|
|
7038
7068
|
${this.renderChangeGroup(`staged`,t.staged)}
|
|
7039
7069
|
${this.renderChangeGroup(`unstaged`,t.unstaged)}
|
|
7040
|
-
`}renderChangeGroup(e,t){if(t.length===0)return null;let n=
|
|
7070
|
+
`}renderChangeGroup(e,t){if(t.length===0)return null;let n=tF(e);return g`
|
|
7041
7071
|
<section class="git-update-manager-change-group" aria-label=${`${n} changes`}>
|
|
7042
7072
|
<h2>${n} (${String(t.length)})</h2>
|
|
7043
7073
|
${t.map(e=>this.renderChange(e))}
|
|
7044
7074
|
</section>
|
|
7045
|
-
`}renderChange(e){let t=this.selectedChange?.id===e.id,n=zl(e),r=Rl(e.state),i=
|
|
7075
|
+
`}renderChange(e){let t=this.selectedChange?.id===e.id,n=zl(e),r=Rl(e.state),i=tF(e.scope);return g`
|
|
7046
7076
|
<button
|
|
7047
7077
|
type="button"
|
|
7048
7078
|
class=${`git-update-manager-entry ${t?`selected`:``}`}
|
|
@@ -7054,13 +7084,13 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
7054
7084
|
<span class="git-update-manager-path">${n}</span>
|
|
7055
7085
|
<span class="git-update-manager-scope">${i}</span>
|
|
7056
7086
|
</button>
|
|
7057
|
-
`}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 ${zl(e)}.</p>`;if(this.loadingDiff||this.selectedDiff===void 0)return g`<p class="git-update-manager-empty">Loading ${zl(e)}…</p>`;let t=this.selectedDiff;return
|
|
7087
|
+
`}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 ${zl(e)}.</p>`;if(this.loadingDiff||this.selectedDiff===void 0)return g`<p class="git-update-manager-empty">Loading ${zl(e)}…</p>`;let t=this.selectedDiff;return $P(),g`
|
|
7058
7088
|
<header class="git-update-manager-diff-header">
|
|
7059
7089
|
<strong>${zl(e)}</strong>
|
|
7060
|
-
<small>${
|
|
7090
|
+
<small>${tF(e.scope)} · ${Rl(e.state)}${t.truncated?` · truncated`:``}</small>
|
|
7061
7091
|
</header>
|
|
7062
7092
|
<unified-diff-viewer .diff=${t.diff}></unified-diff-viewer>
|
|
7063
|
-
`}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=
|
|
7093
|
+
`}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=rF(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=ab(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`
|
|
7064
7094
|
:host { position: fixed; inset: 0; z-index: 80; color: var(--pi-text); font: 14px system-ui, sans-serif; }
|
|
7065
7095
|
.git-update-manager-backdrop { width: 100%; height: 100dvh; display: grid; place-items: center; padding: 16px; background: rgba(0, 0, 0, .48); }
|
|
7066
7096
|
.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); }
|
|
@@ -7099,7 +7129,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
7099
7129
|
.git-update-manager-workspace { grid-template-columns: 1fr; grid-template-rows: minmax(190px, 40%) minmax(0, 1fr); }
|
|
7100
7130
|
.git-update-manager-entries { border-right: 0; border-bottom: 1px solid var(--pi-border); }
|
|
7101
7131
|
}
|
|
7102
|
-
`}};B([x({attribute:!1})],ZP.prototype,`onClose`,void 0),B([x({attribute:!1})],ZP.prototype,`onStatusChange`,void 0),B([x({attribute:!1})],ZP.prototype,`workspace`,void 0),B([x()],ZP.prototype,`machineId`,void 0),B([x({attribute:!1})],ZP.prototype,`api`,void 0),B([S()],ZP.prototype,`status`,void 0),B([S()],ZP.prototype,`selectedChange`,void 0),B([S()],ZP.prototype,`selectedDiff`,void 0),B([S()],ZP.prototype,`loadingStatus`,void 0),B([S()],ZP.prototype,`loadingDiff`,void 0),B([S()],ZP.prototype,`error`,void 0),B([S()],ZP.prototype,`bounds`,void 0),ZP=B([b(`git-update-manager-panel`)],ZP);function QP(){S_(()=>import(`./UnifiedDiffViewer-BjLQphPw.js`),[],import.meta.url)}function $P(e,t){let n=Fl(e.files);return[...n.staged,...n.unstaged].find(e=>e.id===t)}function eF(e){return e===`staged`?`Staged`:`Unstaged`}function tF(e,t){return e===void 0?void 0:JSON.stringify([t,e.projectId,e.id])}function nF(e){return e instanceof Error?e.message:String(e)}var rF=900*1e3,iF=750,aF=[1e3,3e3,8e3,15e3,3e4],oF={capture:!0},sF=`auto:on`,cF=`auto:off`,lF=`theme:`,uF=sl(`core:workspace.files`),dF=sl(`core:workspace.git`),fF=sl(`core:workspace.terminal`),pF=`workspace-memory`,mF=`workspace.memory`,hF=`workspace-memory:workspace.memory`,gF=`workspace-learned-skills`,_F=`workspace.learned-skills`,vF=`workspace-learned-skills:workspace.learned-skills`,yF=320,bF=2,xF=`(min-width: 1181px)`,SF=75,CF=`Could not remember this model policy; this session still uses it.`,$=class extends y{constructor(...e){super(...e),this.state=Jc(),this.sessionUnread=new lg({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 Dm(()=>this.state,e=>{this.setState(e)},{onBackgroundError:(e,t)=>{console.warn(e,t)}}),this.sessions=new Op(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},new up,{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 Fm(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.sessions,new Nm,{onBackgroundError:(e,t)=>{console.warn(`Failed to ${e}`,t)}}),this.projectCatalog=new Zl(()=>this.state,{workspaces:ys.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 cu(()=>this.state,e=>{this.setState(e)},{api:ys,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 el(()=>this.state,e=>{this.setState(e)},{onActivityApplied:e=>{this.projectActivityOwnership.handleActivityApplied(e)}}),this.auth=new il(()=>this.state,e=>{this.setState(e)},e=>{this.sessions.applySessionStatus(e)}),this.projects=new ql(()=>this.state,e=>{this.setState(e)},this.workspaces,{onProjectsApplied:e=>{this.projectActivityOwnership.handleProjectsApplied(e),this.recentProjects.load()}}),this.machines=new Ul(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.projects),this.piWebUiStatusController=new uu(()=>this.state,e=>{this.setState(e)},{onRefreshError:(e,t)=>{console.warn(`Failed to refresh PI WEBUI status for ${e}`,t)}}),this.files=new bl(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.git=new El(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.memory=new Nl(()=>this.state,e=>{this.setState(e)}),this.learnedSkills=new kl(()=>this.state,e=>{this.setState(e)}),this.recentProjects=new $l({machineId:()=>R(this.state),onChange:()=>{this.requestUpdate()},onBackgroundError:(e,t)=>{console.warn(`Failed to ${e}`,t)},reconcileProjects:async e=>R(this.state)===e&&await this.projects.loadProjects()}),this.keyboard=new dh,this.realtime=new Of,this.machineRealtimeSockets=new Map,this.unreadRuntimeRefreshes=new Map,this.activeTerminalIds=new Set,this.machineNavigation=new qm,this.terminalSelection=new oh,this.appShell=new Qv(this),this.browserResume=new ty({onResumeSignal:()=>{this.handleBrowserResumeSignal()},refreshAfterResume:()=>this.refreshAfterBrowserResume(),onRefreshError:e=>{console.warn(`Failed to refresh after browser resume`,e)}}),this.panelCollapse=new _y(this),this.panelResize=new xy(this),this.navigationSections=new my(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=wF(),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=jg()??Dg,this.activeThemeId=Eg,this.isRefreshingApp=!1,this.closedRecentProjectDialogGeneration=0,this.starterSessionDefaultsSeq=0,this.starterModelPolicyPreferenceReadError=``,this.starterModelPolicyPreferenceWriter=new Lh({save:async(e,t)=>{let n=await bs.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 Hh({remember:(e,t)=>bs.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=fb(),this.terminalModalFontSize=this.initialTerminalModalPreferences.fontSize,this.terminalModalOpacity=this.initialTerminalModalPreferences.opacity,this.initialWorkspaceTabVisibility=bb(),this.terminalTabHidden=this.initialWorkspaceTabVisibility.terminalHidden,this.infoTabHidden=this.initialWorkspaceTabVisibility.infoHidden,this.railOrder=UP()??[...LP],this.compactRailOpen=!1,this.activeActivityRailGeneration=0,this.settingsSection=Hy(),this.shortcutConfig={},this.workspaceUploadDefaultFolder=Is(void 0),this.sessionWarningVisibility=_g(),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=ab(this.terminalModalBounds,this.terminalModalViewport()))},this.onKeyDown=e=>{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(Ic(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(Lc(`start-failed`,`Could not start the session. ${XF(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`?dc(t):t.tier===void 0?{...t,mode:`tiered`}:uc(t,t.tier);this.setStarterModelPolicyDraft(n),this.ensureModelTierCatalog(R(this.state));return}if(e===`exact`){let e=dc(t);this.setStarterModelPolicyDraft(e);let n=this.starterSessionDefaults,r=n===void 0?void 0:ac(n);r!==void 0&&lc(e.exact,r)&&this.persistStarterModelPolicyPreference(e);return}let n=t.tier===void 0?{...t,mode:`tiered`}:uc(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||mc(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=uc(t,e);if(this.starterModelPolicySelectionSupported()){this.setStarterModelPolicyDraft(r);return}mc(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(dc(t)),this.scheduleActiveExactModelPolicyApply();return}if(t.tier===void 0){this.setActiveModelPolicyDraft({...t,mode:`tiered`});return}this.setActiveModelPolicyDraft(uc(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=uc(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,WP(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`?rb(t.bounds,n,r):ib(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=ub(this.terminalModalFontSize+e);t!==this.terminalModalFontSize&&(this.terminalModalFontSize=t,this.persistTerminalModalPreferences())},this.adjustTerminalOpacity=e=>{let t=db(this.terminalModalOpacity+e);t!==this.terminalModalOpacity&&(this.terminalModalOpacity=t,this.persistTerminalModalPreferences())},this.handleStopActiveWork=()=>{this.sessions.stopActiveWork()},this.handleCompact=()=>{this.sessions.runCommand(`/compact`)},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=Sg(this.sessionWarningVisibility);e!==this.sessionWarningVisibility&&(this.sessionWarningVisibility=e,this.requestUpdate())},this.handleSelectModel=()=>{this.openModelDialog()},this.handleSelectThinking=()=>{this.openThinkingDialog()}}get routeRestoreInProgress(){return this.routeRestoreDepth>0}willUpdate(){this.toggleAttribute(`pwa-display-mode`,this.appShell.isPwaDisplayMode),this.syncSessionWarningVisibility(),this.syncStarterNotice()}updated(){this.committedChatIdentity=DF(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=yg(this.sessionWarningVisibility,e===void 0?void 0:Qc(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=EF(e,t);await this.updateComplete,!(!this.unreadConnected||DF(this.state)!==n)&&(this.readyChatIdentity=n,this.syncSelectedSessionReadState())}syncUnreadSessionIds(){let e=this.sessionUnread.unreadSessionIds(R(this.state),this.state.sessions);WF(e,this.unreadSessionIds)||(this.unreadSessionIds=e)}syncWindowTitle(){this.disconnectWindowTitle();let e=Eb(this.state.selectedProject?.name);this.windowTitleCleanup=Db(e)}disconnectWindowTitle(){this.windowTitleCleanup?.(),this.windowTitleCleanup=void 0}isSessionSeen(e,t){if(!this.unreadConnected)return!1;let n=EF(e,t);return DF(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.closedRecentProjectEntry!==void 0}connectedCallback(){super.connectedCallback(),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,oF),this.systemLightThemeMedia?.addEventListener(`change`,this.onSystemLightThemeChange),this.applyPreferredTheme(!1),this.connectRealtime(),this.renegotiateUnreadMachines(),this.piWebUiStatusTimer=window.setInterval(()=>{this.schedulePiWebUiStatusRefresh()},rF),this.refreshWorkspaceActivity(),this.recentProjects.load(),this.loadClientConfig(),this.ensureGatewayPluginsLoaded(),this.loadProjectsAndRestoreRoute().finally(()=>{this.schedulePiWebUiStatusRefresh()}),this.syncWindowTitle()}disconnectedCallback(){this.finishTerminalModalPointerInteraction(),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,oF),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(!UF(this.state,e))return;let t=this.state,n=OF(t),r=AF(t),i=kF(t);this.state={...this.state,...e},i!==kF(this.state)&&(this.starterModelPolicySelectionGeneration+=1),n!==OF(this.state)&&this.resetActiveModelPolicyDraft(),DF(t)!==DF(this.state)&&(this.committedChatIdentity=void 0,this.readyChatIdentity=void 0),zF(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),BF(t,this.state)&&this.syncMachineActivitySubscriptions(),this.notifications.syncEnvironment(t,this.state),t.selectedProject?.name!==this.state.selectedProject?.name&&this.syncWindowTitle(),this.synchronizeProjectCatalogPolling();let a=AF(this.state);a!==void 0&&a!==r&&this.preloadActiveModelPolicyInputs()}synchronizeProjectCatalogPolling(){this.projectCatalog.updatePolling(!!this.isConnected)}async loadProjectsAndRestoreRoute(){this.restoreSettingsRoute();let e=Ly();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()}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()])}schedulePiWebUiStatusRefresh(e=iF){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=>HF(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 $o.config()).effectiveConfig)}catch(e){console.warn(`Failed to load PI WEBUI config`,e)}}applyClientConfig(e){this.shortcutConfig=e.shortcuts??{},this.workspaceUploadDefaultFolder=Is(e)}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(Ly(),e),this.rememberCurrentMachineNavigation()}async restoreRouteFor(e,t,n=this.readWorkspaceRouteSurface(e),r){let i=R(this.state),a=e.projectId===void 0||e.projectId===``?qF():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===``?qF():{selectedFilePath:ll(uF,`file`),selectedDiffPath:ll(dF,`diff`),selectedTerminalId:ll(fF,`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){Ry(e,{replace:!0}),ul(uF,`file`,void 0,{replace:!0}),ul(dF,`diff`,void 0,{replace:!0}),ul(fF,`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=YF(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>=aF.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 $F(),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(),Ry({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(Ym(this.state))}syncWorkspaceRouteSurfaceToUrl(){this.writeWorkspaceRouteSurfaceToUrl(Ym(this.state).surface)}writeMachineNavigationSnapshotToUrl(e,t){Ry(Xm(e),t),this.writeWorkspaceRouteSurfaceToUrl(e.surface)}writeWorkspaceRouteSurfaceToUrl(e){ul(uF,`file`,e.selectedFilePath,{replace:!0}),ul(dF,`diff`,e.selectedDiffPath,{replace:!0}),ul(fF,`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)??Jm(e.id);if(await this.restoreRouteFor(Xm(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=JF(t,e),r=this.terminalCommandRunRuntimes.get(n);if(r!==void 0)return r;let i=Yy(e,{api:{runTerminalCommand:(e,n)=>xs.runTerminalCommand(e,n,t),listCommandRuns:e=>xs.listCommandRuns(e,t),getCommandRun:e=>xs.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){ul(fF,`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,Uy(e)}closeSettings(){this.settingsSection=void 0,Uy(void 0)}navigateSettings(e){this.settingsSection=e,Uy(e)}restoreSettingsRoute(){this.settingsSection=Hy()}handleWorkspaceChange(e,t){let n=RF(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 bs.sessionDefaultsV2(e.path,n):await bs.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&&!PF(o)?this.starterModelPolicy=oc(r):i?this.starterModelPolicy=s:this.starterModelPolicy=sc(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(Lc(`defaults-failed`,`Could not load this workspace's model defaults. ${XF(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 Of;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=>VF(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):KF(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 xs.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=GF(e),r=GF(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.closeClosedRecentProjectDialogForMachineChange(),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`
|
|
7132
|
+
`}};B([x({attribute:!1})],QP.prototype,`onClose`,void 0),B([x({attribute:!1})],QP.prototype,`onStatusChange`,void 0),B([x({attribute:!1})],QP.prototype,`workspace`,void 0),B([x()],QP.prototype,`machineId`,void 0),B([x({attribute:!1})],QP.prototype,`api`,void 0),B([S()],QP.prototype,`status`,void 0),B([S()],QP.prototype,`selectedChange`,void 0),B([S()],QP.prototype,`selectedDiff`,void 0),B([S()],QP.prototype,`loadingStatus`,void 0),B([S()],QP.prototype,`loadingDiff`,void 0),B([S()],QP.prototype,`error`,void 0),B([S()],QP.prototype,`bounds`,void 0),QP=B([b(`git-update-manager-panel`)],QP);function $P(){S_(()=>import(`./UnifiedDiffViewer-CFdMhoMV.js`),[],import.meta.url)}function eF(e,t){let n=Fl(e.files);return[...n.staged,...n.unstaged].find(e=>e.id===t)}function tF(e){return e===`staged`?`Staged`:`Unstaged`}function nF(e,t){return e===void 0?void 0:JSON.stringify([t,e.projectId,e.id])}function rF(e){return e instanceof Error?e.message:String(e)}var iF=900*1e3,aF=750,oF=[1e3,3e3,8e3,15e3,3e4],sF={capture:!0},cF=`auto:on`,lF=`auto:off`,uF=`theme:`,dF=sl(`core:workspace.files`),fF=sl(`core:workspace.git`),pF=sl(`core:workspace.terminal`),mF=`workspace-memory`,hF=`workspace.memory`,gF=`workspace-memory:workspace.memory`,_F=`workspace-learned-skills`,vF=`workspace.learned-skills`,yF=`workspace-learned-skills:workspace.learned-skills`,bF=320,xF=2,SF=`(min-width: 1181px)`,CF=75,wF=`Could not remember this model policy; this session still uses it.`,$=class extends y{constructor(...e){super(...e),this.state=Jc(),this.sessionUnread=new lg({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 Dm(()=>this.state,e=>{this.setState(e)},{onBackgroundError:(e,t)=>{console.warn(e,t)}}),this.sessions=new Op(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},new up,{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 Fm(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.sessions,new Nm,{onBackgroundError:(e,t)=>{console.warn(`Failed to ${e}`,t)}}),this.projectCatalog=new Zl(()=>this.state,{workspaces:ys.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 cu(()=>this.state,e=>{this.setState(e)},{api:ys,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 el(()=>this.state,e=>{this.setState(e)},{onActivityApplied:e=>{this.projectActivityOwnership.handleActivityApplied(e)}}),this.auth=new il(()=>this.state,e=>{this.setState(e)},e=>{this.sessions.applySessionStatus(e)}),this.projects=new ql(()=>this.state,e=>{this.setState(e)},this.workspaces,{onProjectsApplied:e=>{this.projectActivityOwnership.handleProjectsApplied(e),this.recentProjects.load()}}),this.machines=new Ul(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.projects),this.piWebUiStatusController=new uu(()=>this.state,e=>{this.setState(e)},{onRefreshError:(e,t)=>{console.warn(`Failed to refresh PI WEBUI status for ${e}`,t)}}),this.files=new bl(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.git=new El(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.memory=new Nl(()=>this.state,e=>{this.setState(e)}),this.learnedSkills=new kl(()=>this.state,e=>{this.setState(e)}),this.recentProjects=new $l({machineId:()=>R(this.state),onChange:()=>{this.requestUpdate()},onBackgroundError:(e,t)=>{console.warn(`Failed to ${e}`,t)},reconcileProjects:async e=>R(this.state)===e&&await this.projects.loadProjects()}),this.keyboard=new dh,this.realtime=new Of,this.machineRealtimeSockets=new Map,this.unreadRuntimeRefreshes=new Map,this.activeTerminalIds=new Set,this.machineNavigation=new qm,this.terminalSelection=new oh,this.appShell=new Qv(this),this.browserResume=new ty({onResumeSignal:()=>{this.handleBrowserResumeSignal()},refreshAfterResume:()=>this.refreshAfterBrowserResume(),onRefreshError:e=>{console.warn(`Failed to refresh after browser resume`,e)}}),this.panelCollapse=new _y(this),this.panelResize=new xy(this),this.navigationSections=new my(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=TF(),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=jg()??Dg,this.activeThemeId=Eg,this.isRefreshingApp=!1,this.closedRecentProjectDialogGeneration=0,this.starterSessionDefaultsSeq=0,this.starterModelPolicyPreferenceReadError=``,this.starterModelPolicyPreferenceWriter=new Lh({save:async(e,t)=>{let n=await bs.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 Hh({remember:(e,t)=>bs.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=fb(),this.terminalModalFontSize=this.initialTerminalModalPreferences.fontSize,this.terminalModalOpacity=this.initialTerminalModalPreferences.opacity,this.initialWorkspaceTabVisibility=bb(),this.terminalTabHidden=this.initialWorkspaceTabVisibility.terminalHidden,this.infoTabHidden=this.initialWorkspaceTabVisibility.infoHidden,this.railOrder=WP()??[...RP],this.compactRailOpen=!1,this.activeActivityRailGeneration=0,this.settingsSection=Hy(),this.shortcutConfig={},this.workspaceUploadDefaultFolder=Is(void 0),this.sessionWarningVisibility=_g(),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=ab(this.terminalModalBounds,this.terminalModalViewport()))},this.onKeyDown=e=>{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(Ic(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(Lc(`start-failed`,`Could not start the session. ${ZF(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`?dc(t):t.tier===void 0?{...t,mode:`tiered`}:uc(t,t.tier);this.setStarterModelPolicyDraft(n),this.ensureModelTierCatalog(R(this.state));return}if(e===`exact`){let e=dc(t);this.setStarterModelPolicyDraft(e);let n=this.starterSessionDefaults,r=n===void 0?void 0:ac(n);r!==void 0&&lc(e.exact,r)&&this.persistStarterModelPolicyPreference(e);return}let n=t.tier===void 0?{...t,mode:`tiered`}:uc(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||mc(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=uc(t,e);if(this.starterModelPolicySelectionSupported()){this.setStarterModelPolicyDraft(r);return}mc(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(dc(t)),this.scheduleActiveExactModelPolicyApply();return}if(t.tier===void 0){this.setActiveModelPolicyDraft({...t,mode:`tiered`});return}this.setActiveModelPolicyDraft(uc(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=uc(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,GP(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`?rb(t.bounds,n,r):ib(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=ub(this.terminalModalFontSize+e);t!==this.terminalModalFontSize&&(this.terminalModalFontSize=t,this.persistTerminalModalPreferences())},this.adjustTerminalOpacity=e=>{let t=db(this.terminalModalOpacity+e);t!==this.terminalModalOpacity&&(this.terminalModalOpacity=t,this.persistTerminalModalPreferences())},this.handleStopActiveWork=()=>{this.sessions.stopActiveWork()},this.handleCompact=()=>{this.sessions.runCommand(`/compact`)},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=Sg(this.sessionWarningVisibility);e!==this.sessionWarningVisibility&&(this.sessionWarningVisibility=e,this.requestUpdate())},this.handleSelectModel=()=>{this.openModelDialog()},this.handleSelectThinking=()=>{this.openThinkingDialog()}}get routeRestoreInProgress(){return this.routeRestoreDepth>0}willUpdate(){this.toggleAttribute(`pwa-display-mode`,this.appShell.isPwaDisplayMode),this.syncSessionWarningVisibility(),this.syncStarterNotice()}updated(){this.committedChatIdentity=OF(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=yg(this.sessionWarningVisibility,e===void 0?void 0:Qc(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=DF(e,t);await this.updateComplete,!(!this.unreadConnected||OF(this.state)!==n)&&(this.readyChatIdentity=n,this.syncSelectedSessionReadState())}syncUnreadSessionIds(){let e=this.sessionUnread.unreadSessionIds(R(this.state),this.state.sessions);GF(e,this.unreadSessionIds)||(this.unreadSessionIds=e)}syncWindowTitle(){this.disconnectWindowTitle();let e=Eb(this.state.selectedProject?.name);this.windowTitleCleanup=Db(e)}disconnectWindowTitle(){this.windowTitleCleanup?.(),this.windowTitleCleanup=void 0}isSessionSeen(e,t){if(!this.unreadConnected)return!1;let n=DF(e,t);return OF(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.closedRecentProjectEntry!==void 0}connectedCallback(){super.connectedCallback(),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,sF),this.systemLightThemeMedia?.addEventListener(`change`,this.onSystemLightThemeChange),this.applyPreferredTheme(!1),this.connectRealtime(),this.renegotiateUnreadMachines(),this.piWebUiStatusTimer=window.setInterval(()=>{this.schedulePiWebUiStatusRefresh()},iF),this.refreshWorkspaceActivity(),this.recentProjects.load(),this.loadClientConfig(),this.ensureGatewayPluginsLoaded(),this.loadProjectsAndRestoreRoute().finally(()=>{this.schedulePiWebUiStatusRefresh()}),this.syncWindowTitle()}disconnectedCallback(){this.finishTerminalModalPointerInteraction(),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,sF),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(!WF(this.state,e))return;let t=this.state,n=kF(t),r=jF(t),i=AF(t);this.state={...this.state,...e},i!==AF(this.state)&&(this.starterModelPolicySelectionGeneration+=1),n!==kF(this.state)&&this.resetActiveModelPolicyDraft(),OF(t)!==OF(this.state)&&(this.committedChatIdentity=void 0,this.readyChatIdentity=void 0),BF(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),VF(t,this.state)&&this.syncMachineActivitySubscriptions(),this.notifications.syncEnvironment(t,this.state),t.selectedProject?.name!==this.state.selectedProject?.name&&this.syncWindowTitle(),this.synchronizeProjectCatalogPolling();let a=jF(this.state);a!==void 0&&a!==r&&this.preloadActiveModelPolicyInputs()}synchronizeProjectCatalogPolling(){this.projectCatalog.updatePolling(!!this.isConnected)}async loadProjectsAndRestoreRoute(){this.restoreSettingsRoute();let e=Ly();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()}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()])}schedulePiWebUiStatusRefresh(e=aF){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=>UF(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 $o.config()).effectiveConfig)}catch(e){console.warn(`Failed to load PI WEBUI config`,e)}}applyClientConfig(e){this.shortcutConfig=e.shortcuts??{},this.workspaceUploadDefaultFolder=Is(e)}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(Ly(),e),this.rememberCurrentMachineNavigation()}async restoreRouteFor(e,t,n=this.readWorkspaceRouteSurface(e),r){let i=R(this.state),a=e.projectId===void 0||e.projectId===``?JF():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===``?JF():{selectedFilePath:ll(dF,`file`),selectedDiffPath:ll(fF,`diff`),selectedTerminalId:ll(pF,`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){Ry(e,{replace:!0}),ul(dF,`file`,void 0,{replace:!0}),ul(fF,`diff`,void 0,{replace:!0}),ul(pF,`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=XF(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>=oF.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 eI(),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(),Ry({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(Ym(this.state))}syncWorkspaceRouteSurfaceToUrl(){this.writeWorkspaceRouteSurfaceToUrl(Ym(this.state).surface)}writeMachineNavigationSnapshotToUrl(e,t){Ry(Xm(e),t),this.writeWorkspaceRouteSurfaceToUrl(e.surface)}writeWorkspaceRouteSurfaceToUrl(e){ul(dF,`file`,e.selectedFilePath,{replace:!0}),ul(fF,`diff`,e.selectedDiffPath,{replace:!0}),ul(pF,`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)??Jm(e.id);if(await this.restoreRouteFor(Xm(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=YF(t,e),r=this.terminalCommandRunRuntimes.get(n);if(r!==void 0)return r;let i=Yy(e,{api:{runTerminalCommand:(e,n)=>xs.runTerminalCommand(e,n,t),listCommandRuns:e=>xs.listCommandRuns(e,t),getCommandRun:e=>xs.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){ul(pF,`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,Uy(e)}closeSettings(){this.settingsSection=void 0,Uy(void 0)}navigateSettings(e){this.settingsSection=e,Uy(e)}restoreSettingsRoute(){this.settingsSection=Hy()}handleWorkspaceChange(e,t){let n=zF(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 bs.sessionDefaultsV2(e.path,n):await bs.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&&!FF(o)?this.starterModelPolicy=oc(r):i?this.starterModelPolicy=s:this.starterModelPolicy=sc(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(Lc(`defaults-failed`,`Could not load this workspace's model defaults. ${ZF(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 Of;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=>HF(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):qF(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 xs.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=KF(e),r=KF(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.closeClosedRecentProjectDialogForMachineChange(),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`
|
|
7103
7133
|
<workspace-panel
|
|
7104
7134
|
id="workspace-panel"
|
|
7105
7135
|
.emptyState=${this.state.selectedWorkspace===void 0?this.workspacePanelEmptyState():void 0}
|
|
@@ -7155,7 +7185,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
7155
7185
|
.onResizeEnd=${()=>{this.panelResize.persistPanelSizes()}}
|
|
7156
7186
|
.onReset=${()=>{this.resetResizablePanel(`workspace`)}}
|
|
7157
7187
|
></app-panel-edge-control>
|
|
7158
|
-
`}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-bF-yF);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(xF).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 Zf(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 MF(this.state,e)}starterModelPolicySelectionSupported(e=R(this.state)){return NF(this.state,e)}handleStarterModelPolicyCapabilityChange(e,t){let n=R(t);if(R(e)!==n||NF(e,n)||!NF(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=nc(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&&(zc(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=cc(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 is.settings(e);if(!r())return;this.modelTierCatalogMachineId=e,this.modelTierCatalog=t,this.completeStarterModelPolicyFromActiveTier()}catch(e){if(!r())return;this.modelTierCatalogError=XF(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(),AF(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=gc(t,e,n);FF(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=OF(this.state);if(e===void 0||jF(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),OF(this.state)!==e)return;let r=this.activeModelPolicyDraftForState(this.state);if(r!==void 0)return r;let i=this.selectedMachineModelTierCatalog(),a=jF(this.state);if(i===void 0||a===void 0)return;let o=this.state.modelPolicy?.policy,s;if(o!==void 0)s=rc({policy:o,catalog:i});else if(a.mode===`exact`)s=rc({liveResolved:a.resolved,catalog:i});else{let e=rc({catalog:i});s=a.tier===void 0?{...e,mode:`tiered`}:uc(e,a.tier)}return this.activeModelPolicyDraftScope=e,this.activeModelPolicyDraft=s,s}activeModelPolicyDraftForState(e){return this.activeModelPolicyDraftScope===OF(e)?this.activeModelPolicyDraft:void 0}setActiveModelPolicyDraft(e){let t=OF(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`||!hc(e,t))return;let n=this.activeModelPolicyApplyGeneration;this.activeModelPolicyApplyTimer=window.setTimeout(()=>{n===this.activeModelPolicyApplyGeneration&&(this.activeModelPolicyApplyTimer=void 0,this.applyActiveModelPolicyDraft())},SF)}async applyActiveModelPolicyDraft(){let e=this.activeModelPolicyDraftForState(this.state),t=this.selectedMachineModelTierCatalog();if(e===void 0||!hc(e,t)||t===void 0)return;let n=mc(e,t);if(n===void 0)return;let r=this.activeModelPolicyDraftScope,i=this.state.modelPolicy;if(await this.sessions.saveModelPolicy(n),r!==OF(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(rc({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 Kc({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 ng(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 bs.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: ${XF(e)}`})}}async runSessionCleanup(e){let t=this.sessionCleanupDialog;if(t?.preview===void 0||Yh(t.previewRequest)!==Yh(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 bs.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: ${XF(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 bs.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: ${XF(e)}`})}}renderNavigationPanel(){return g`
|
|
7188
|
+
`}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-xF-bF);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(SF).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 Zf(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 NF(this.state,e)}starterModelPolicySelectionSupported(e=R(this.state)){return PF(this.state,e)}handleStarterModelPolicyCapabilityChange(e,t){let n=R(t);if(R(e)!==n||PF(e,n)||!PF(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=nc(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&&(zc(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=cc(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 is.settings(e);if(!r())return;this.modelTierCatalogMachineId=e,this.modelTierCatalog=t,this.completeStarterModelPolicyFromActiveTier()}catch(e){if(!r())return;this.modelTierCatalogError=ZF(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(),jF(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=gc(t,e,n);IF(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=kF(this.state);if(e===void 0||MF(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),kF(this.state)!==e)return;let r=this.activeModelPolicyDraftForState(this.state);if(r!==void 0)return r;let i=this.selectedMachineModelTierCatalog(),a=MF(this.state);if(i===void 0||a===void 0)return;let o=this.state.modelPolicy?.policy,s;if(o!==void 0)s=rc({policy:o,catalog:i});else if(a.mode===`exact`)s=rc({liveResolved:a.resolved,catalog:i});else{let e=rc({catalog:i});s=a.tier===void 0?{...e,mode:`tiered`}:uc(e,a.tier)}return this.activeModelPolicyDraftScope=e,this.activeModelPolicyDraft=s,s}activeModelPolicyDraftForState(e){return this.activeModelPolicyDraftScope===kF(e)?this.activeModelPolicyDraft:void 0}setActiveModelPolicyDraft(e){let t=kF(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`||!hc(e,t))return;let n=this.activeModelPolicyApplyGeneration;this.activeModelPolicyApplyTimer=window.setTimeout(()=>{n===this.activeModelPolicyApplyGeneration&&(this.activeModelPolicyApplyTimer=void 0,this.applyActiveModelPolicyDraft())},CF)}async applyActiveModelPolicyDraft(){let e=this.activeModelPolicyDraftForState(this.state),t=this.selectedMachineModelTierCatalog();if(e===void 0||!hc(e,t)||t===void 0)return;let n=mc(e,t);if(n===void 0)return;let r=this.activeModelPolicyDraftScope,i=this.state.modelPolicy;if(await this.sessions.saveModelPolicy(n),r!==kF(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(rc({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 Kc({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 ng(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 bs.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: ${ZF(e)}`})}}async runSessionCleanup(e){let t=this.sessionCleanupDialog;if(t?.preview===void 0||Yh(t.previewRequest)!==Yh(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 bs.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: ${ZF(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 bs.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: ${ZF(e)}`})}}renderNavigationPanel(){return g`
|
|
7159
7189
|
<app-navigation-panel
|
|
7160
7190
|
.machines=${this.state.machines}
|
|
7161
7191
|
.selectedMachine=${this.state.selectedMachine}
|
|
@@ -7238,7 +7268,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
7238
7268
|
.onFocusNavigationTarget=${e=>{this.focusNavigationTarget(e)}}
|
|
7239
7269
|
.onCancelKeyboardNavigation=${()=>{this.focusChatComposer()}}
|
|
7240
7270
|
></app-navigation-panel>
|
|
7241
|
-
`}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(Ic(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(Lc(`start-failed`,`Could not start the session. ${
|
|
7271
|
+
`}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(Ic(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(Lc(`start-failed`,`Could not start the session. ${ZF(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`&&!EP(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 eI(),await this.navigationPanel?.focusSection(e)}async focusChatComposer(){this.state.mainView!==`chat`&&this.selectMainView(`chat`),await this.updateComplete,await eI(),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`
|
|
7242
7272
|
<session-tree-navigator
|
|
7243
7273
|
.tree=${e.treeDialog}
|
|
7244
7274
|
.onNavigate=${(e,t)=>this.navigateSessionTree(e,t)}
|
|
@@ -7252,7 +7282,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
7252
7282
|
.onRemove=${async()=>{if(R(this.state)!==t)return;let n=await this.recentProjects.removeEntry(e.id);R(this.state)===t&&n.kind===`registered-conflict`&&this.setState({error:n.error.message})}}
|
|
7253
7283
|
.onClose=${()=>{this.closeClosedRecentProjectDialog(t,e,n)}}
|
|
7254
7284
|
></closed-recent-project-dialog>
|
|
7255
|
-
`}openClosedRecentProject(e,t){this.closedRecentProjectDialogGeneration+=1,this.closedRecentProjectRestoreFocus=t,this.closedRecentProjectMachineId=R(this.state),this.closedRecentProjectEntry=e}closeClosedRecentProjectDialogForMachineChange(){let e=this.closedRecentProjectMachineId,t=this.closedRecentProjectEntry;e===void 0||t===void 0||this.closeClosedRecentProjectDialog(e,t,this.closedRecentProjectDialogGeneration,!1)}closeClosedRecentProjectDialog(e,t,n,r=!0){if(this.closedRecentProjectMachineId!==e||this.closedRecentProjectEntry!==t||this.closedRecentProjectDialogGeneration!==n||r&&R(this.state)!==e)return;let i=r?this.closedRecentProjectRestoreFocus:void 0;this.closedRecentProjectRestoreFocus=void 0,this.renderRoot.querySelector(`closed-recent-project-dialog`)?.close(),this.closedRecentProjectMachineId=void 0,this.closedRecentProjectEntry=void 0,r&&this.updateComplete.then(()=>{this.closedRecentProjectMachineId===void 0&&this.closedRecentProjectEntry===void 0&&this.closedRecentProjectDialogGeneration===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=>
|
|
7285
|
+
`}openClosedRecentProject(e,t){this.closedRecentProjectDialogGeneration+=1,this.closedRecentProjectRestoreFocus=t,this.closedRecentProjectMachineId=R(this.state),this.closedRecentProjectEntry=e}closeClosedRecentProjectDialogForMachineChange(){let e=this.closedRecentProjectMachineId,t=this.closedRecentProjectEntry;e===void 0||t===void 0||this.closeClosedRecentProjectDialog(e,t,this.closedRecentProjectDialogGeneration,!1)}closeClosedRecentProjectDialog(e,t,n,r=!0){if(this.closedRecentProjectMachineId!==e||this.closedRecentProjectEntry!==t||this.closedRecentProjectDialogGeneration!==n||r&&R(this.state)!==e)return;let i=r?this.closedRecentProjectRestoreFocus:void 0;this.closedRecentProjectRestoreFocus=void 0,this.renderRoot.querySelector(`closed-recent-project-dialog`)?.close(),this.closedRecentProjectMachineId=void 0,this.closedRecentProjectEntry=void 0,r&&this.updateComplete.then(()=>{this.closedRecentProjectMachineId===void 0&&this.closedRecentProjectEntry===void 0&&this.closedRecentProjectDialogGeneration===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=>LF(e)&&Cg(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=>RF(e)&&Cg(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=Rc(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`
|
|
7256
7286
|
<section class="session-start-screen" aria-labelledby="session-start-heading">
|
|
7257
7287
|
<div class="session-start-content">
|
|
7258
7288
|
<p class="session-start-eyebrow">PI WEBUI · ${t.label}</p>
|
|
@@ -7264,7 +7294,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
7264
7294
|
<p class="session-start-hint">Describe a goal, paste a task, or attach a file to begin.</p>
|
|
7265
7295
|
</div>
|
|
7266
7296
|
</section>
|
|
7267
|
-
`}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}:_c(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=ac(e),s=t.mode===`exact`&&o!==void 0&&!lc(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:`${CF} ${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:`${CF} ${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=ac(t);if(!(n===void 0||lc(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=_c(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=TF(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=>ys.workspaceFile(e.projectId,e.id,n,t),writeFile:async(n,r,i)=>{let a=await ys.writeWorkspaceFile(e.projectId,e.id,n,r,i,t);return this.files.refreshFiles(),a},deleteFile:async n=>{let r=await ys.deleteWorkspaceFile(e.projectId,e.id,n,t);return this.files.refreshFiles(),r},moveFile:async(n,r,i)=>{let a=await ys.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=TF(this.state),n=t.id,r=i=>{let a=this.terminalCommandRunsForOrigin(i,n);return Rv({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:Ls(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 Ky(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`,()=>yv())}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}`,()=>yv(`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=>Lv({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=TF(this.state),n=this.state.selectedWorkspace,r=this.activeActivityRailId===e?this.activeActivityRailGeneration:void 0,i=a=>zv({...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 wg(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(!Im(e)){this.setState({error:`Only secondary Git worktrees can be deleted`});return}if(qg(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 ys.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: ${XF(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=Jg(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(Wg(t.id));if(R(this.state)!==e)return;let r=Gg(n);this.setState({workspaceDeletionRuns:r});for(let t of Object.values(r))Yg(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(Yg);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=JF(t,e.id);if(this.handledWorkspaceDeletionRunIds.has(n))return;let r=Jg(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:QF(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 ys.workspaces(e.id,n);if(!r())return;let i={projectPath:e.path,liveCwds:t.map(e=>e.path)};_s.projectUsageCount(i,n).then(({sessionCount:e})=>{r()&&this.statisticsLoading&&(this.statisticsSessionCount=e)},()=>void 0);let a=await _s.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(fc(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(fc(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?cF:sF;this.setState({themeDialog:{title:`Select Theme`,selectedValue:n===void 0?r:`${lF}${n}`,options:[{value:r,label:`Auto ${this.themePreference.auto?`✓ on`:`off`}`,description:this.autoThemeDescription(t)},...e.map(e=>({value:`${lF}${e.id}`,label:this.themeOptionLabel(e,n),description:this.themeOptionDescription(e)}))]}})}pickTheme(e){if(this.setState({themeDialog:void 0}),e===sF||e===cF){let t=this.resolveCurrentThemePreference().selectedTheme?.id;if(t===void 0)return;this.themePreference={themeId:t,auto:e===sF},this.applyPreferredTheme(!0);return}if(!e.startsWith(lF))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,Ng(t),e&&Mg(this.themePreference))}resolveCurrentThemePreference(e=this.plugins.getThemes()){return Pg({themes:e,themePairs:this.plugins.getThemePairs(),preference:this.themePreference,prefersLight:this.systemPrefersLight()})}themePairForTheme(e){return Ig(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=eI(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=pc(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=eI(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(pc(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 bs.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?oc(r):sc(i,r);this.starterModelPolicy=a;let o=ac(r);a.mode===`exact`&&o!==void 0&&lc(a.exact,o)&&this.persistStarterModelPolicyPreference(a)}catch(e){R(this.state)===n&&this.state.selectedWorkspace?.id===t.id&&this.publishStarterNotice(Lc(`defaults-failed`,`Could not save this workspace's model defaults. ${XF(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=ab(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(){pb({fontSize:this.terminalModalFontSize,opacity:this.terminalModalOpacity})}toggleTerminalTab(){this.terminalTabHidden=!this.terminalTabHidden,this.persistWorkspaceTabVisibility()}toggleInfoTab(){this.infoTabHidden=!this.infoTabHidden,this.persistWorkspaceTabVisibility()}persistWorkspaceTabVisibility(){xb({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){return g`
|
|
7297
|
+
`}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}:_c(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=ac(e),s=t.mode===`exact`&&o!==void 0&&!lc(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:`${wF} ${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:`${wF} ${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=ac(t);if(!(n===void 0||lc(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=_c(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=EF(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=>ys.workspaceFile(e.projectId,e.id,n,t),writeFile:async(n,r,i)=>{let a=await ys.writeWorkspaceFile(e.projectId,e.id,n,r,i,t);return this.files.refreshFiles(),a},deleteFile:async n=>{let r=await ys.deleteWorkspaceFile(e.projectId,e.id,n,t);return this.files.refreshFiles(),r},moveFile:async(n,r,i)=>{let a=await ys.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=EF(this.state),n=t.id,r=i=>{let a=this.terminalCommandRunsForOrigin(i,n);return Rv({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:Ls(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 Ky(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`,()=>yv())}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}`,()=>yv(`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=>Lv({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=EF(this.state),n=this.state.selectedWorkspace,r=this.activeActivityRailId===e?this.activeActivityRailGeneration:void 0,i=a=>zv({...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 wg(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(!Im(e)){this.setState({error:`Only secondary Git worktrees can be deleted`});return}if(qg(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 ys.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: ${ZF(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=Jg(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(Wg(t.id));if(R(this.state)!==e)return;let r=Gg(n);this.setState({workspaceDeletionRuns:r});for(let t of Object.values(r))Yg(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(Yg);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=YF(t,e.id);if(this.handledWorkspaceDeletionRunIds.has(n))return;let r=Jg(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:$F(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 ys.workspaces(e.id,n);if(!r())return;let i={projectPath:e.path,liveCwds:t.map(e=>e.path)};_s.projectUsageCount(i,n).then(({sessionCount:e})=>{r()&&this.statisticsLoading&&(this.statisticsSessionCount=e)},()=>void 0);let a=await _s.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(fc(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(fc(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?lF:cF;this.setState({themeDialog:{title:`Select Theme`,selectedValue:n===void 0?r:`${uF}${n}`,options:[{value:r,label:`Auto ${this.themePreference.auto?`✓ on`:`off`}`,description:this.autoThemeDescription(t)},...e.map(e=>({value:`${uF}${e.id}`,label:this.themeOptionLabel(e,n),description:this.themeOptionDescription(e)}))]}})}pickTheme(e){if(this.setState({themeDialog:void 0}),e===cF||e===lF){let t=this.resolveCurrentThemePreference().selectedTheme?.id;if(t===void 0)return;this.themePreference={themeId:t,auto:e===cF},this.applyPreferredTheme(!0);return}if(!e.startsWith(uF))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,Ng(t),e&&Mg(this.themePreference))}resolveCurrentThemePreference(e=this.plugins.getThemes()){return Pg({themes:e,themePairs:this.plugins.getThemePairs(),preference:this.themePreference,prefersLight:this.systemPrefersLight()})}themePairForTheme(e){return Ig(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=tI(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=pc(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=tI(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(pc(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 bs.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?oc(r):sc(i,r);this.starterModelPolicy=a;let o=ac(r);a.mode===`exact`&&o!==void 0&&lc(a.exact,o)&&this.persistStarterModelPolicyPreference(a)}catch(e){R(this.state)===n&&this.state.selectedWorkspace?.id===t.id&&this.publishStarterNotice(Lc(`defaults-failed`,`Could not save this workspace's model defaults. ${ZF(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=ab(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(){pb({fontSize:this.terminalModalFontSize,opacity:this.terminalModalOpacity})}toggleTerminalTab(){this.terminalTabHidden=!this.terminalTabHidden,this.persistWorkspaceTabVisibility()}toggleInfoTab(){this.infoTabHidden=!this.infoTabHidden,this.persistWorkspaceTabVisibility()}persistWorkspaceTabVisibility(){xb({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){return g`
|
|
7268
7298
|
<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=${cm(e.selectedNotificationInbox)} .canClearServerQueue=${this.canClearServerQueue()} .onClearServerQueue=${this.handleClearServerQueue} .canMessageActions=${this.canMessageActions()&&t.archived!==!0} .onEditFromHere=${this.handleEditFromHere} .onForkFromHere=${this.handleForkFromHere} .onDismissWarning=${this.handleDismissWarning} .onDismissNotification=${this.handleDismissNotification} .onDismissAllNotifications=${this.handleDismissAllNotifications} .warningsVisible=${!this.sessionWarningVisibility.collapsed} .onLoadMore=${()=>this.withChatPrependTransition(()=>this.sessions.loadEarlierMessages())}></chat-view>
|
|
7269
7299
|
`}renderContextBar(){return this.appShell.isDesktopActivityRailLayout?null:g`
|
|
7270
7300
|
<app-context-bar
|
|
@@ -7396,7 +7426,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
7396
7426
|
<div class="mobile-navigation-panel">${this.appShell.isMobileNavigationLayout?this.renderNavigationPanel():null}</div>
|
|
7397
7427
|
${e.selectedSession?g`
|
|
7398
7428
|
${this.renderChatView(e,e.selectedSession)}
|
|
7399
|
-
<prompt-editor .sessionId=${e.selectedSession.id} .cwd=${e.selectedWorkspace?.path} .machineId=${R(e)} .projectId=${e.selectedWorkspace?.projectId} .workspaceId=${e.selectedWorkspace?.id} .workspaceScopedFileSuggestions=${this.supportsWorkspaceFileSuggestions()} .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?
|
|
7429
|
+
<prompt-editor .sessionId=${e.selectedSession.id} .cwd=${e.selectedWorkspace?.path} .machineId=${R(e)} .projectId=${e.selectedWorkspace?.projectId} .workspaceId=${e.selectedWorkspace?.id} .workspaceScopedFileSuggestions=${this.supportsWorkspaceFileSuggestions()} .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?QF(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>
|
|
7400
7430
|
${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>`}
|
|
7401
7431
|
`:this.shouldShowSessionStartScreen(e)?this.renderSessionStartScreen(e):g`<div class="empty">${this.sessionEmptyMessage()}</div>`}
|
|
7402
7432
|
${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>`}
|
|
@@ -7460,4 +7490,4 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
7460
7490
|
${this.renderClosedRecentProjectDialog()}
|
|
7461
7491
|
${this.settingsSection===void 0?null:g`<settings-dialog .section=${this.settingsSection} .machine=${e.selectedMachine} .machineRuntime=${this.selectedMachineRuntime()} .actions=${this.getDefaultActions()} .onNavigate=${e=>{this.navigateSettings(e)}} .onClose=${()=>{this.closeSettings()}} .onConfigSaved=${e=>{this.applyClientConfig(e)}} .onModelTiersSaved=${(e,t)=>{this.handleModelTiersSaved(e,t)}} .onRefreshMachineRuntime=${async e=>{await this.machines.refreshMachineRuntime(e)}}></settings-dialog>`}
|
|
7462
7492
|
</div>
|
|
7463
|
-
`}static{this.styles=u_}};B([S()],$.prototype,`state`,void 0),B([C(`chat-view`)],$.prototype,`chatView`,void 0),B([C(`prompt-editor`)],$.prototype,`promptEditor`,void 0),B([C(`app-navigation-panel`)],$.prototype,`navigationPanel`,void 0),B([C(`#navigation-panel`)],$.prototype,`navigationPanelFrame`,void 0),B([C(`#workspace-panel`)],$.prototype,`workspacePanelFrame`,void 0),B([S()],$.prototype,`unreadSessionIds`,void 0),B([S()],$.prototype,`activeThemeId`,void 0),B([S()],$.prototype,`isRefreshingApp`,void 0),B([S()],$.prototype,`sessionCleanupDialog`,void 0),B([S()],$.prototype,`historyWindow`,void 0),B([S()],$.prototype,`closedRecentProjectEntry`,void 0),B([S()],$.prototype,`starterSessionDefaults`,void 0),B([S()],$.prototype,`starterModelPolicyPreferenceReadError`,void 0),B([S()],$.prototype,`starterNotice`,void 0),B([S()],$.prototype,`modelTierCatalog`,void 0),B([S()],$.prototype,`modelTierCatalogLoading`,void 0),B([S()],$.prototype,`modelTierCatalogError`,void 0),B([S()],$.prototype,`starterModelPolicy`,void 0),B([S()],$.prototype,`activeModelPolicyDraft`,void 0),B([S()],$.prototype,`modelsConfigDialogOpen`,void 0),B([S()],$.prototype,`projectBrowserOpen`,void 0),B([S()],$.prototype,`statisticsProject`,void 0),B([S()],$.prototype,`statisticsReport`,void 0),B([S()],$.prototype,`statisticsSessionCount`,void 0),B([S()],$.prototype,`statisticsLoading`,void 0),B([S()],$.prototype,`statisticsError`,void 0),B([S()],$.prototype,`sessionBrowserOpen`,void 0),B([S()],$.prototype,`skillsConfigDialogOpen`,void 0),B([S()],$.prototype,`pluginsConfigDialogOpen`,void 0),B([S()],$.prototype,`systemPromptDialogOpen`,void 0),B([S()],$.prototype,`gitUpdateManagerPanelOpen`,void 0),B([S()],$.prototype,`terminalModalOpen`,void 0),B([S()],$.prototype,`terminalModalBounds`,void 0),B([S()],$.prototype,`terminalModalMaximized`,void 0),B([S()],$.prototype,`terminalModalFontSize`,void 0),B([S()],$.prototype,`terminalModalOpacity`,void 0),B([S()],$.prototype,`terminalTabHidden`,void 0),B([S()],$.prototype,`infoTabHidden`,void 0),B([S()],$.prototype,`railOrder`,void 0),B([S()],$.prototype,`compactRailOpen`,void 0),B([S()],$.prototype,`activeActivityRailId`,void 0),B([S()],$.prototype,`settingsSection`,void 0),B([S()],$.prototype,`shortcutConfig`,void 0),B([S()],$.prototype,`workspaceUploadDefaultFolder`,void 0),$=B([b(`pi-webui-app`)],$);function
|
|
7493
|
+
`}static{this.styles=u_}};B([S()],$.prototype,`state`,void 0),B([C(`chat-view`)],$.prototype,`chatView`,void 0),B([C(`prompt-editor`)],$.prototype,`promptEditor`,void 0),B([C(`app-navigation-panel`)],$.prototype,`navigationPanel`,void 0),B([C(`#navigation-panel`)],$.prototype,`navigationPanelFrame`,void 0),B([C(`#workspace-panel`)],$.prototype,`workspacePanelFrame`,void 0),B([S()],$.prototype,`unreadSessionIds`,void 0),B([S()],$.prototype,`activeThemeId`,void 0),B([S()],$.prototype,`isRefreshingApp`,void 0),B([S()],$.prototype,`sessionCleanupDialog`,void 0),B([S()],$.prototype,`historyWindow`,void 0),B([S()],$.prototype,`closedRecentProjectEntry`,void 0),B([S()],$.prototype,`starterSessionDefaults`,void 0),B([S()],$.prototype,`starterModelPolicyPreferenceReadError`,void 0),B([S()],$.prototype,`starterNotice`,void 0),B([S()],$.prototype,`modelTierCatalog`,void 0),B([S()],$.prototype,`modelTierCatalogLoading`,void 0),B([S()],$.prototype,`modelTierCatalogError`,void 0),B([S()],$.prototype,`starterModelPolicy`,void 0),B([S()],$.prototype,`activeModelPolicyDraft`,void 0),B([S()],$.prototype,`modelsConfigDialogOpen`,void 0),B([S()],$.prototype,`projectBrowserOpen`,void 0),B([S()],$.prototype,`statisticsProject`,void 0),B([S()],$.prototype,`statisticsReport`,void 0),B([S()],$.prototype,`statisticsSessionCount`,void 0),B([S()],$.prototype,`statisticsLoading`,void 0),B([S()],$.prototype,`statisticsError`,void 0),B([S()],$.prototype,`sessionBrowserOpen`,void 0),B([S()],$.prototype,`skillsConfigDialogOpen`,void 0),B([S()],$.prototype,`pluginsConfigDialogOpen`,void 0),B([S()],$.prototype,`systemPromptDialogOpen`,void 0),B([S()],$.prototype,`gitUpdateManagerPanelOpen`,void 0),B([S()],$.prototype,`terminalModalOpen`,void 0),B([S()],$.prototype,`terminalModalBounds`,void 0),B([S()],$.prototype,`terminalModalMaximized`,void 0),B([S()],$.prototype,`terminalModalFontSize`,void 0),B([S()],$.prototype,`terminalModalOpacity`,void 0),B([S()],$.prototype,`terminalTabHidden`,void 0),B([S()],$.prototype,`infoTabHidden`,void 0),B([S()],$.prototype,`railOrder`,void 0),B([S()],$.prototype,`compactRailOpen`,void 0),B([S()],$.prototype,`activeActivityRailId`,void 0),B([S()],$.prototype,`settingsSection`,void 0),B([S()],$.prototype,`shortcutConfig`,void 0),B([S()],$.prototype,`workspaceUploadDefaultFolder`,void 0),$=B([b(`pi-webui-app`)],$);function TF(){let e=new Nv;return e.register({id:`core`,plugin:cv}),e.register({id:`themes`,plugin:pv}),e}function EF(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 DF(e,t){return JSON.stringify([e,t.id,t.cwd])}function OF(e){let t=e.selectedSession;return t===void 0?void 0:DF(R(e),t)}function kF(e){let t=e.selectedSession;return t===void 0?void 0:JSON.stringify([R(e),t.id,t.cwd])}function AF(e){return JSON.stringify([R(e),e.selectedWorkspace?.id,e.selectedWorkspace?.path,e.selectedSession?.id,e.selectedSession?.cwd])}function jF(e){if(MF(e)!==void 0&&NF(e,R(e)))return kF(e)}function MF(e){return e.status?.modelPolicy}function NF(e,t){if(t===`local`)return!0;let n=e.machineRuntimes[t];return n?.ok===!0&&E(n,w.sessionsModelPolicy)}function PF(e,t){let n=e.machineRuntimes[t];return n?.ok===!0&&E(n,w.sessionsModelPolicyStarterSelection)}function FF(e){return e!==void 0&&`starterModelPolicyContractVersion`in e}function IF(e,t){return e.mode===t.mode&&e.tier===t.tier&&lc(e.exact,t.exact)}function LF(e){return e.id===gF||e.sourcePluginId===mF&&e.localId===hF}function RF(e){return e.id===yF||e.sourcePluginId===_F&&e.localId===vF}function zF(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 BF(e,t){return e.machines!==t.machines||e.machineRuntimes!==t.machineRuntimes}function VF(e,t){return e.machines!==t.machines||e.machineStatuses!==t.machineStatuses||(e.selectedMachine?.id??`local`)!==(t.selectedMachine?.id??`local`)}function HF(e,t){return UF(e,t)}function UF(e,t){if(e.kind===`local`)return!0;let n=t?.status??e.status;return n===void 0||n===`unknown`||n===`online`}function WF(e,t){return Object.entries(t).some(([t,n])=>Reflect.get(e,t)!==n)}function GF(e,t){return e.size===t.size&&[...e].every(e=>t.has(e))}function KF(e){return Yc(e.status,e.activity)}function qF(e){return e.type===`terminal.created`||e.type===`terminal.exited`||e.type===`terminal.closed`}function JF(){return{}}function YF(e,t){return JSON.stringify([e,t])}function XF(e){return oF[Math.min(e,oF.length-1)]??3e4}function ZF(e){return e instanceof Error?e.message:String(e)}function QF(e){if(e?.modelPolicy===void 0)return e;let t={...e};return delete t.modelPolicy,t}function $F(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>e!==t))}function eI(){return new Promise(e=>requestAnimationFrame(()=>{e()}))}function tI(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,B as t};
|